feat(editor): views section draws, recrops and adds accesses on the drawing

This commit is contained in:
bchanot committed 2026-11-23 17:02:47 +01:00
1 parent d05c3fe34e
commit 9aa791db24
20 files changed
+500 -49

No files matched your search

+1 -1
View File
@@ -298,7 +298,7 @@ test.describe('editor geometry (adversarial)', () => {
await openSection(page, dict, 'views')
const detail = page.getByRole('listitem', { name: 'Détail A' })
await detail
.getByRole('button', { name: dict['editor.views.crop.toggle'] })
.getByRole('button', { name: dict['editor.views.precise'] })
.click()
const width = detail.getByLabel(dict['editor.views.crop.width'], {
exact: true,
@@ -110,6 +110,7 @@ async function importDrawing(page: Page) {
await expect(
page.getByRole('dialog', { name: dict['editor.cleaning.title'] }),
).toHaveCount(0)
await clickButton(page, dict['editor.views.own_drawing'])
await page.locator('#view-new-fr').fill('Détail essai')
await page.locator('#view-new-en').fill('Trial detail')
const crop = { min_x: '20', min_y: '20', width: '60', height: '45' }
@@ -140,6 +140,9 @@ test.describe('editor shell, width crossing (H)', () => {
'annotations',
)
await openSection(page, dict, 'views')
await page
.getByRole('button', { name: dict['editor.views.own_drawing'] })
.click()
await keepsTypedValue(
page,
page.locator('#view-new-fr'),
@@ -154,7 +157,7 @@ test.describe('editor shell, width crossing (H)', () => {
await open(page)
await openSection(page, dict, 'views')
await place(page, 'annotations.views')
.getByRole('button', { name: dict['editor.views.crop.toggle'] })
.getByRole('button', { name: dict['editor.views.precise'] })
.first()
.click()
const field = page.locator('#view-detail-a-crop-min_x')
@@ -69,6 +69,8 @@ import type { EditorPlaceProps } from '@/editor/tabs'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import { useViewsRequestRun } from '@/editor/annotations/useViewsRequestRun'
import { startDetailView } from '@/editor/annotations/viewsRequest'
import AnnotationCanvas from './AnnotationCanvas'
import { annotationName } from './AnnotationList'
import GestureMessage from './GestureMessage'
@@ -260,6 +262,7 @@ export default function EditableAnnotations(props: Props) {
const work = useWork(scene)
const { ui, selected } = scene
const visible = usePlaceVisible()
useViewsRequestRun(scene, visible)
const framing = useAnnotationWork((s) => s.frame !== null)
const { asideRef, byDrawing } = useSelectionEscape(
selected?.id ?? null,
@@ -548,6 +551,11 @@ function SidePanel({ scene }: { scene: Scene }) {
}
onOpenAnnotation={(id) => scene.onOpen(id, 'drawing')}
onOpenSection={scene.onOpenSection}
onNewDetailView={(button) =>
guardedPress(button, () =>
startDetailView(scene.viewId, scene.viewId, dispatch),
)
}
/>
)
}
@@ -41,6 +41,8 @@ export interface OverviewPanelProps {
/** Enter on the selected row: its properties dialog (A1). */
onOpenAnnotation: (annotationId: string) => void
onOpenSection: (section: AnnotationSection, opener: HTMLElement) => void
/** « Nouvelle vue de détail » on the view shown (D3); absent: the entry is not offered. */
onNewDetailView?: (button: HTMLElement) => void
}
function SectionEntry({
@@ -109,6 +111,7 @@ function ViewRow({
function ViewsCard(props: OverviewPanelProps) {
const t = useT()
const { doc, viewId, readOnly, onSelectView, onOpenSection } = props
const { onNewDetailView } = props
const id = `${props.idPrefix ?? ''}overview-views`
const counts = useOverviewCounts(doc)
return (
@@ -127,6 +130,16 @@ function ViewsCard(props: OverviewPanelProps) {
/>
))}
</ul>
{onNewDetailView && !readOnly && (
<button
type="button"
data-new-detail-view=""
onClick={(event) => onNewDetailView(event.currentTarget)}
className={ENTRY}
>
{t('editor.annotations.view.new')}
</button>
)}
<SectionEntry
section="views"
label={t(
@@ -5,7 +5,7 @@ import { useDeselect } from '@/editor/annotations/deselect'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { dropCreation } from '@/editor/annotations/creationWork'
import { canvasSurface, placeAtCentre } from '@/editor/annotations/frameDraw'
import { startFrame } from '@/editor/annotations/frameWork'
import { startDetailView } from '@/editor/annotations/viewsRequest'
import { guardedPress } from '@/editor/annotations/guardedPress'
import { beginRedraw } from '@/editor/annotations/redraw'
import { stripLeadOf } from '@/editor/annotations/stripLead'
@@ -255,15 +255,7 @@ function newView(
keyboard: boolean,
) {
const { viewId } = scene
guardedPress(button, () =>
startFrame({
purpose: 'create',
viewId,
drawnOn: viewId,
box: null,
returnTo: viewId,
}),
)
guardedPress(button, () => startDetailView(viewId, viewId, scene.dispatch))
const surface = keyboard ? canvasSurface() : null
if (!surface || useAnnotationWork.getState().frame === null) return
if (!placeAtCentre(surface)) return
@@ -29,10 +29,7 @@ export default function AnnotationSection({
const { titleKey, Body } = ANNOTATION_SECTION_BODIES[section]
const headingId = `annotation-section-${section}-title`
return (
<section
aria-labelledby={headingId}
className="space-y-4"
>
<section aria-labelledby={headingId} className="space-y-4">
<Button type="button" variant="secondary" size="sm" onClick={onBack}>
{t('editor.section.back')}
</Button>
@@ -44,7 +41,7 @@ export default function AnnotationSection({
>
{t(titleKey)}
</h2>
<Body doc={doc} readOnly={readOnly} focus={focus} />
<Body doc={doc} readOnly={readOnly} focus={focus} onBack={onBack} />
</section>
)
}
@@ -3,9 +3,14 @@ import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import EditOnly from '@/components/editor/EditOnly'
import DetailViewForm from '@/components/editor/views/DetailViewForm'
import DetailViewRow from '@/components/editor/views/DetailViewRow'
import MainViewCard from '@/components/editor/views/MainViewCard'
import NewDetailViewCard from '@/components/editor/views/NewDetailViewCard'
import {
requestViews,
type ViewsRequest,
} from '@/editor/annotations/viewsRequest'
import { hasAccess } from '@/editor/annotations/viewAccess'
import { useRowFocus } from '@/editor/focusRequest'
import type { SectionBodyProps } from './registry'
import { useSheetDocument } from '@/editor/sheetDocument'
@@ -19,7 +24,12 @@ import { useLocaleStore } from '@/state/localeStore'
export default function ViewsSection({
readOnly,
focus,
}: Pick<SectionBodyProps, 'readOnly' | 'focus'>) {
onBack,
onRecrop,
}: Pick<SectionBodyProps, 'readOnly' | 'focus' | 'onBack'> & {
/** « Recadrer sur le dessin » (crop views): offered only when given. */
onRecrop?: (viewId: string) => void
}) {
const t = useT()
useRowFocus(focus)
const locale = useLocaleStore((s) => s.locale)
@@ -27,16 +37,33 @@ export default function ViewsSection({
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const [cropOpen, setCropOpen] = useState<string | null>(null)
const views = doc?.views ?? []
// The drawing alone holds the view, the tool and the frame: it answers once shown.
const hand = (request: ViewsRequest) => {
requestViews(request)
onBack?.()
}
const main = views.find((view) => view.kind === 'main')
const details = views.filter((view) => view.kind === 'detail')
return (
<div data-testid="editor-section-views" className="min-h-24 space-y-4">
{main?.kind === 'main' && (
<MainViewCard view={main} readOnly={readOnly} />
<MainViewCard
view={main}
readOnly={readOnly}
onCreate={() => hand({ kind: 'create', parentId: main.id })}
/>
)}
<h3 className="text-base font-semibold">
{t('editor.views.details_title')}
</h3>
{doc && (
<EditOnly readOnly={readOnly}>
<NewDetailViewCard
views={views}
onDraw={() => hand({ kind: 'create', parentId: null })}
/>
</EditOnly>
)}
{doc && details.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.views.empty')}
@@ -53,6 +80,15 @@ export default function ViewsSection({
onToggleCrop={() =>
setCropOpen(cropOpen === view.id ? null : view.id)
}
missingAccess={doc !== null && !hasAccess(doc, view)}
onAddAccess={() =>
hand({
kind: 'access',
parentId: view.parent_view_id,
viewId: view.id,
})
}
onRecrop={onRecrop}
onDelete={() =>
setDeleting({
key: { kind: 'view', id: view.id },
@@ -62,11 +98,6 @@ export default function ViewsSection({
/>
))}
</ul>
{doc && (
<EditOnly readOnly={readOnly}>
<DetailViewForm views={views} />
</EditOnly>
)}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
</div>
)
@@ -11,6 +11,8 @@ export interface SectionBodyProps {
doc: AnatomicalSheetDocument
readOnly: boolean
focus?: FocusRequest
/** The section's own close (« Retour au dessin »), for a section that hands work to the drawing. */
onBack?: () => void
}
type SectionName = Exclude<AnnotationSection, 'drawing'>
@@ -19,6 +19,9 @@ export default function DetailViewRow({
cropOpen,
onToggleCrop,
onDelete,
missingAccess,
onAddAccess,
onRecrop,
}: {
view: DetailView
views: readonly SheetView[]
@@ -26,6 +29,11 @@ export default function DetailViewRow({
cropOpen: boolean
onToggleCrop: () => void
onDelete: () => void
/** No access on the parent opens this view: the notice and « Ajouter l'accès ». */
missingAccess: boolean
onAddAccess: () => void
/** « Recadrer sur le dessin » on a crop view; absent: not offered. */
onRecrop?: (viewId: string) => void
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
@@ -57,28 +65,46 @@ export default function DetailViewRow({
/>
</div>
<ViewDrawing view={view} readOnly={readOnly} />
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<p className="text-sm font-medium">{t('editor.views.crop.title')}</p>
{missingAccess && (
<div className="flex flex-wrap items-center gap-3 rounded-lg bg-[var(--color-surface-strong)] p-3 text-sm">
<p>
{t('editor.views.no_access').replace(
'{name}',
() =>
parents.find((p) => p.value === view.parent_view_id)?.label ??
'',
)}
</p>
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
aria-expanded={cropOpen}
onClick={onToggleCrop}
onClick={onAddAccess}
>
{t('editor.views.crop.toggle')}
{t('editor.views.add_access')}
</ActionButton>
</div>
<CropEditor
viewId={view.id}
parentId={view.parent_view_id}
box={view.view_box}
)}
<div className="flex flex-wrap items-center gap-2">
{onRecrop && view.svg_asset_id === null && (
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={() => onRecrop(view.id)}
>
{t('editor.views.recrop_on_drawing')}
</ActionButton>
)}
<ActionButton
readOnly={readOnly}
open={cropOpen}
/>
</div>
<div className="flex justify-end">
variant="ghost"
size="sm"
aria-expanded={cropOpen}
onClick={onToggleCrop}
>
{t('editor.views.precise')}
</ActionButton>
<ActionButton
readOnly={readOnly}
variant="danger"
@@ -88,6 +114,13 @@ export default function DetailViewRow({
{t('editor.action.delete')}
</ActionButton>
</div>
<CropEditor
viewId={view.id}
parentId={view.parent_view_id}
box={view.view_box}
readOnly={readOnly}
open={cropOpen}
/>
</li>
)
}
@@ -1,4 +1,5 @@
import type { MainView } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import { FOCUS_CLASS, focusAttrs } from '@/editor/focusRequest'
import { useViewUpdate } from '@/editor/useViewUpdate'
import { useT } from '@/i18n/useT'
@@ -11,9 +12,12 @@ const CARD = 'space-y-3 rounded-lg border border-[var(--color-border)] p-3'
export default function MainViewCard({
view,
readOnly,
onCreate,
}: {
view: MainView
readOnly: boolean
/** « Créer une vue de détail »: this view is the parent (D2). */
onCreate: () => void
}) {
const t = useT()
const views = useViewUpdate()
@@ -30,6 +34,14 @@ export default function MainViewCard({
<ViewNames view={view} readOnly={readOnly} views={views} />
</div>
<ViewDrawing view={view} readOnly={readOnly} />
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={onCreate}
>
{t('editor.views.create_here')}
</ActionButton>
</section>
)
}
@@ -0,0 +1,39 @@
import { useState } from 'react'
import type { SheetView } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import { useT } from '@/i18n/useT'
import DetailViewForm from './DetailViewForm'
/**
* « Nouvelle vue de détail » (board 14): the normal way is to draw the crop on the
* drawing; the link opens the form of a view with its own drawing.
*/
export default function NewDetailViewCard({
views,
onDraw,
}: {
views: readonly SheetView[]
onDraw: () => void
}) {
const t = useT()
const [formOpen, setFormOpen] = useState(false)
return (
<div className="space-y-3 rounded-lg border border-[var(--color-border)] p-3">
<h4 className="text-sm font-medium">{t('editor.views.new')}</h4>
<div className="flex flex-wrap items-center gap-3">
<ActionButton readOnly={false} variant="primary" onClick={onDraw}>
{t('editor.views.draw_new')}
</ActionButton>
<button
type="button"
aria-expanded={formOpen}
onClick={() => setFormOpen(!formOpen)}
className="min-h-11 text-sm underline xl:min-h-9"
>
{t('editor.views.own_drawing')}
</button>
</div>
{formOpen && <DetailViewForm views={views} />}
</div>
)
}
@@ -0,0 +1,54 @@
import { useEffect } from 'react'
import { placeAtCentre } from './usePlacement'
import type { Scene } from '@/components/editor/annotations/EditableAnnotations'
import {
clearViewsRequest,
startDetailView,
useViewsRequest,
type ViewsRequest,
} from './viewsRequest'
/** The access tool armed for `viewId`: rectangle, preset « Vue ouverte » (board 14). */
function armed(scene: Scene, viewId: string): boolean {
const { tool, accessTarget, accessShape } = scene.ui
return (
tool === 'link' && accessTarget === viewId && accessShape === 'rectangle'
)
}
/**
* One step of « Ajouter l'accès »: switch to the parent, arm the access tool, then place
* the default rectangle once the drawing is measured. Each step ends the effect; the
* next render runs the next one.
*/
function accessStep(scene: Scene, request: ViewsRequest & { kind: 'access' }) {
const { dispatch, viewId, frame, model } = scene
if (viewId !== request.parentId) {
return dispatch({ type: 'view', viewId: request.parentId })
}
if (!armed(scene, request.viewId)) {
dispatch({ type: 'access_shape', shape: 'rectangle' })
dispatch({ type: 'tool', tool: 'link', from: 'add' })
return dispatch({ type: 'access_target', viewId: request.viewId })
}
if (!frame || !model.measured) return
clearViewsRequest()
placeAtCentre(scene, 'detail_trigger', 'add')
}
/**
* Runs the views section's request once the drawing is shown: the frame creation, or the
* access placement. A request whose view is gone is dropped.
*/
export function useViewsRequestRun(scene: Scene, visible: boolean): void {
const request = useViewsRequest((s) => s.request)
useEffect(() => {
if (!request || !visible) return
const { parentId: parent } = request
const known = (id: string) => scene.doc.views.some((view) => view.id === id)
if (parent !== null && !known(parent)) return clearViewsRequest()
if (request.kind === 'access') return accessStep(scene, request)
clearViewsRequest()
startDetailView(parent ?? scene.viewId, scene.viewId, scene.dispatch)
})
}
@@ -0,0 +1,17 @@
import type {
AnatomicalSheetDocument,
DetailView,
} from '@faunosteo/core-wasm/types'
/** Whether an access on the parent view opens this detail view. */
export function hasAccess(
doc: AnatomicalSheetDocument,
view: DetailView,
): boolean {
return doc.annotations.some(
(annotation) =>
annotation.kind === 'detail_trigger' &&
annotation.view_id === view.parent_view_id &&
annotation.opens_view_id === view.id,
)
}
@@ -0,0 +1,45 @@
import { create } from 'zustand'
import type { Dispatch } from 'react'
import { startFrame } from './frameWork'
import type { UiAction } from './uiState'
/**
* What the views section asks of the drawing once the drawing is shown again: the
* section is a layer over a kept drawing, which alone holds the view, the tool and the
* frame (board 14). `parentId` null: the view the drawing shows.
*/
export type ViewsRequest =
| { kind: 'create'; parentId: string | null }
| { kind: 'access'; parentId: string; viewId: string }
export const useViewsRequest = create<{ request: ViewsRequest | null }>(() => ({
request: null,
}))
export const requestViews = (request: ViewsRequest): void =>
useViewsRequest.setState({ request })
export const clearViewsRequest = (): void =>
useViewsRequest.setState({ request: null })
/**
* « Nouvelle vue de détail »: the frame work begins with `parentId` as the parent, drawn
* on it; the drawing switches to it first when another view is shown (D2).
*/
export function startDetailView(
parentId: string,
shownId: string,
dispatch: Dispatch<UiAction>,
): boolean {
const started = startFrame({
purpose: 'create',
viewId: parentId,
drawnOn: parentId,
box: null,
returnTo: shownId,
})
if (started && parentId !== shownId) {
dispatch({ type: 'view', viewId: parentId })
}
return started
}
+7 -1
View File
@@ -1633,7 +1633,13 @@ export const en: Dict = {
"Going back to the parent view's drawing is waiting for your confirmation.",
'editor.views.pending.resume': 'Resume',
'editor.views.crop.title': 'Crop',
'editor.views.crop.toggle': 'Edit the crop',
'editor.views.draw_new': 'Draw on the drawing',
'editor.views.own_drawing': 'View with its own drawing…',
'editor.views.create_here': 'Create a detail view',
'editor.views.recrop_on_drawing': 'Recrop on the drawing',
'editor.views.precise': 'Precise values',
'editor.views.no_access': 'No access on “{name}”',
'editor.views.add_access': 'Add the access',
'editor.views.crop.min_x': 'Crop: minimum x',
'editor.views.crop.min_y': 'Crop: minimum y',
'editor.views.crop.width': 'Crop: width',
+7 -1
View File
@@ -1696,7 +1696,13 @@ export const fr: Dict = {
"Le retour à l'illustration de la vue parente attend votre confirmation.",
'editor.views.pending.resume': 'Reprendre',
'editor.views.crop.title': 'Recadrage',
'editor.views.crop.toggle': 'Modifier le recadrage',
'editor.views.draw_new': 'Tracer sur le dessin',
'editor.views.own_drawing': 'Vue avec sa propre illustration…',
'editor.views.create_here': 'Créer une vue de détail',
'editor.views.recrop_on_drawing': 'Recadrer sur le dessin',
'editor.views.precise': 'Valeurs précises',
'editor.views.no_access': 'Aucun accès sur « {name} »',
'editor.views.add_access': "Ajouter l'accès",
'editor.views.crop.min_x': 'Recadrage : x minimum',
'editor.views.crop.min_y': 'Recadrage : y minimum',
'editor.views.crop.width': 'Recadrage : largeur',
@@ -353,7 +353,7 @@ describe('ids and parses', () => {
await user.click(entry('Gérer les vues'))
await user.click(
inPlace('annotations.views').getByRole('button', {
name: 'Modifier le recadrage',
name: 'Valeurs précises',
}),
)
await waitFor(() => expect(composedHosts()).toHaveLength(1))
+3 -2
View File
@@ -157,6 +157,7 @@ describe('typed values come back after a 1 024 px crossing', () => {
const user = await mount()
await user.click(tab('Annotations'))
await user.click(button('Gérer les vues'))
await user.click(button('Vue avec sa propre illustration…'))
await keepsTypedValue(user, 'view-new-fr', 'Nom (FR)', 'Ajouter la vue')
})
@@ -202,7 +203,7 @@ describe('typed values come back after a 1 024 px crossing', () => {
const user = await mount(insert(drawnText(), detail()))
await user.click(tab('Annotations'))
await user.click(button('Gérer les vues'))
await user.click(button('Modifier le recadrage'))
await user.click(button('Valeurs précises'))
const field = byId('view-view-d-crop-min_x')
await user.clear(field)
await user.type(field, '7x')
@@ -414,7 +415,7 @@ describe('ids stay unique', () => {
await user.click(tab(name))
}
await user.click(button('Gérer les vues'))
await user.click(button('Modifier le recadrage'))
await user.click(button('Valeurs précises'))
await user.click(button('Retour au dessin'))
}
const text = () => insert(baseText(), detail())
+196 -5
View File
@@ -1,15 +1,39 @@
/** Lot G: Vues et illustrations (states, detail views, crop group under the frame check). */
import { createHash } from 'node:crypto'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, within } from '@testing-library/react'
import {
cleanup,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type {
AnatomicalSheetDocument,
DetailView,
NewElement,
} from '@faunosteo/core-wasm/types'
import ViewsSection from '@/components/editor/annotations/sections/ViewsSection'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDialog'
import DetailViewRow from '@/components/editor/views/DetailViewRow'
import { annotationLayerOf } from '@/editor/findingLayer'
import { AnnounceContext } from '@/editor/focusRequest'
import { useEditorNavigation } from '@/editor/useEditorNavigation'
import {
clearViewsRequest,
useViewsRequest,
} from '@/editor/annotations/viewsRequest'
import { resetWork, useAnnotationWork } from '@/editor/annotations/workStore'
import { useLocaleStore } from '@/state/localeStore'
import { ASSET, emptyText, insert, point } from '../helpers/editorFixtures'
import {
ASSET,
drawnText,
emptyText,
insert,
point,
} from '../helpers/editorFixtures'
import {
baseText,
openReady,
@@ -51,15 +75,15 @@ beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
resetWork()
clearViewsRequest()
})
async function openCrop(text: string) {
await openReady({ text })
const user = userEvent.setup()
render(<ViewsSection {...props} />)
await user.click(
screen.getByRole('button', { name: 'Modifier le recadrage' }),
)
await user.click(screen.getByRole('button', { name: 'Valeurs précises' }))
return user
}
@@ -194,6 +218,9 @@ describe('Vues et illustrations: detail views', () => {
await openReady()
const user = userEvent.setup()
render(<ViewsSection {...props} />)
await user.click(
screen.getByRole('button', { name: 'Vue avec sa propre illustration…' }),
)
await user.click(screen.getByRole('button', { name: 'Ajouter la vue' }))
expect(screen.getByRole('alert')).toHaveTextContent('Renseignez les noms')
await user.type(document.getElementById('view-new-fr')!, 'Tête')
@@ -381,3 +408,167 @@ function detail2(): NewElement {
},
}
}
/** The tab with its real navigation: a section opens over the kept drawing (board 14). */
function NavigatedTab() {
const nav = useEditorNavigation('annotations')
const { state } = nav
return (
<AnnounceContext value={nav.announce}>
<AnnotationsTab
{...props}
section={state.section}
visited={state.visitedSections}
onOpenSection={nav.openSection}
onBack={nav.backToDrawing}
annotationLayer={annotationLayerOf(nav)}
/>
<DrawingGuardDialog />
</AnnounceContext>
)
}
/** main > Tête (crop, no access on main) . */
const withHead = () => insert(drawnText(), detail())
async function openViews(text = withHead()) {
await openReady({ text })
const user = userEvent.setup()
render(<NavigatedTab />)
await user.click(
await screen.findByRole('button', { name: 'Gérer les vues' }),
)
return user
}
const frame = () => useAnnotationWork.getState().frame
const hidden = (element: HTMLElement) => element.closest('[hidden]') !== null
describe('« Gérer les vues » follows the new journey', () => {
it('« Tracer sur le dessin » closes the section and starts the frame on the shown view', async () => {
const user = await openViews()
await user.click(
screen.getByRole('button', { name: 'Tracer sur le dessin' }),
)
await waitFor(() => expect(frame()).toMatchObject({ purpose: 'create' }))
expect(frame()).toMatchObject({ viewId: 'view-main', box: null })
expect(hidden(screen.getByTestId('editor-section-views'))).toBe(true)
expect(useViewsRequest.getState().request).toBeNull()
})
it('the link « Vue avec sa propre illustration… » opens the form, folded before', async () => {
const user = await openViews()
expect(document.getElementById('view-new-fr')).toBeNull()
await user.click(
screen.getByRole('button', { name: 'Vue avec sa propre illustration…' }),
)
expect(document.getElementById('view-new-fr')).not.toBeNull()
})
it('« Créer une vue de détail » on the main row makes it the parent, switching to it', async () => {
const user = await openViews()
await user.click(
screen.getByRole('button', { name: 'Créer une vue de détail' }),
)
await waitFor(() => expect(frame()).toMatchObject({ viewId: 'view-main' }))
expect(hidden(screen.getByTestId('editor-section-views'))).toBe(true)
})
it("« Ajouter l'accès » places the access dialog on the parent with the view preset", async () => {
const user = await openViews()
expect(screen.getByText('Aucun accès sur « Vue principale »')).toBeTruthy()
await user.click(screen.getByRole('button', { name: "Ajouter l'accès" }))
await waitFor(() =>
expect(useAnnotationWork.getState().creation).not.toBeNull(),
)
const { creation } = useAnnotationWork.getState()
expect(creation).toMatchObject({ viewId: 'view-main' })
expect(creation!.pending.kind).toBe('detail_trigger')
expect(JSON.stringify(creation!.form)).toContain('view-d')
})
it('a view with an access on its parent shows no notice', async () => {
const text = insert(withHead(), {
kind: 'annotation',
value: {
id: 'acc',
view_id: 'view-main',
category_id: 'cat-access',
laterality: 'unpaired',
geometry: { type: 'circle', cx: 50, cy: 50, r: 5 },
review_status: 'to_confirm',
color: null,
kind: 'detail_trigger',
name: null,
opens_view_id: 'view-d',
},
} as NewElement)
await openReady({ text })
render(<ViewsSection {...props} />)
expect(screen.queryByText(/Aucun accès sur/)).toBeNull()
})
})
describe('« Valeurs précises » and « Recadrer sur le dessin »', () => {
it('the four fields stay folded until the disclosure opens', async () => {
await openReady({ text: insert(emptyText(), detail()) })
const user = userEvent.setup()
render(<ViewsSection {...props} />)
const toggle = screen.getByRole('button', { name: 'Valeurs précises' })
expect(toggle).toHaveAttribute('aria-expanded', 'false')
expect(cropField('largeur')).toBeNull()
await user.click(toggle)
expect(cropField('largeur')).not.toBeNull()
})
it('the recrop button is absent without a handler', async () => {
await openReady({ text: insert(emptyText(), detail()) })
render(<ViewsSection {...props} />)
expect(
screen.queryByRole('button', { name: 'Recadrer sur le dessin' }),
).toBeNull()
})
it('with a handler it is offered on a crop view, not on one with its own drawing', async () => {
await openReady({ text: insert(emptyText(), detail()) })
const onRecrop = vi.fn()
const user = userEvent.setup()
const row = (view: DetailView) => (
<DetailViewRow
view={view}
views={doc().views}
readOnly={false}
cropOpen={false}
onToggleCrop={vi.fn()}
onDelete={vi.fn()}
missingAccess={false}
onAddAccess={vi.fn()}
onRecrop={onRecrop}
/>
)
const crop = doc().views.find((v) => v.kind === 'detail') as DetailView
const { rerender } = render(<ul>{row(crop)}</ul>)
await user.click(
screen.getByRole('button', { name: 'Recadrer sur le dessin' }),
)
expect(onRecrop).toHaveBeenCalledWith('view-d')
rerender(<ul>{row({ ...crop, svg_asset_id: ASSET })}</ul>)
expect(
screen.queryByRole('button', { name: 'Recadrer sur le dessin' }),
).toBeNull()
})
})
describe('the « Vues » card of the overview', () => {
it('« Nouvelle vue de détail » starts the frame on the view shown', async () => {
await openReady({ text: withHead() })
render(<NavigatedTab />)
const aside = await screen.findByRole('complementary')
await userEvent
.setup()
.click(
within(aside).getByRole('button', { name: 'Nouvelle vue de détail' }),
)
await waitFor(() => expect(frame()).toMatchObject({ viewId: 'view-main' }))
})
})