feat(editor): keep edit-only forms across a width change
Edit-only parts (creation forms, submission note, crop group, annotation edit body) mount at the first editable render and stay mounted, hidden and detached from canvases, while read-only. Guards: the viewport hook commits the focused field before the tier crosses 1 024 px, the route releases focus left in a hidden part and treats a store out of step as read-only, delete and discard confirmations close when the editor turns read-only, a drag is dropped while the edit body is hidden. Read-only twins take an id prefix. R-24: no existing assertion rewritten; editor-no-loss.test.tsx and two editor-shell Chromium cases added.
This commit is contained in:
1 parent
9d89daed19
commit
c57af6441f
23 files changed
+883
-108
No files matched your search
@@ -4,6 +4,8 @@ import { expect, test } from '../support/browser'
|
||||
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
|
||||
import {
|
||||
backToDrawing,
|
||||
copyKeyOf,
|
||||
storedCopy,
|
||||
closeReferences,
|
||||
editorActor,
|
||||
openEditor,
|
||||
@@ -34,7 +36,7 @@ async function open(page: Page) {
|
||||
}
|
||||
const seed = await seedDraft(actor, { shape: shapeWith(free) })
|
||||
await openEditor(page, dict, actor, seed.sheetId)
|
||||
return seed
|
||||
return { ...seed, actor }
|
||||
}
|
||||
|
||||
const active = (page: Page) => page.locator(':focus')
|
||||
@@ -141,3 +143,47 @@ test.describe('editor shell, kept places (B2a)', () => {
|
||||
await expect(active(page)).toHaveAttribute('id', 'editor-tab-annotations')
|
||||
})
|
||||
})
|
||||
|
||||
// V1-2.6 U1 B2b: a 1 024 px crossing never loses typed input.
|
||||
test.describe('editor shell, width crossing (B2b)', () => {
|
||||
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
|
||||
test.beforeEach(async ({ context }, info) => {
|
||||
test.skip(isPhone(info), 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; phone read-only covered in editor-access
|
||||
await routeToSandbox(context)
|
||||
})
|
||||
test.afterEach(async ({ context }) => {
|
||||
await dropLateReplays(context)
|
||||
})
|
||||
|
||||
test('a field typed without a blur is committed before the crossing and the copy is written', async ({
|
||||
page,
|
||||
}) => {
|
||||
const { actor, draftId } = await open(page)
|
||||
await selectTab(page, dict, 'general')
|
||||
const field = page.locator('#general-name-fr')
|
||||
await field.click()
|
||||
await field.fill('Nom saisi sans quitter le champ')
|
||||
const key = copyKeyOf(actor.account.id, draftId)
|
||||
expect(await storedCopy(page, key)).toBeNull()
|
||||
await page.setViewportSize({ width: 800, height: 900 })
|
||||
await expect(page.locator('#general-name-fr')).toHaveText(
|
||||
'Nom saisi sans quitter le champ',
|
||||
)
|
||||
await expect.poll(() => storedCopy(page, key)).not.toBeNull()
|
||||
})
|
||||
|
||||
test('the category form text is hidden below 1 024 px and comes back on widening', async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page)
|
||||
await openSection(page, dict, 'categories')
|
||||
const field = page.locator('#category-new-fr')
|
||||
await field.fill('Brouillon')
|
||||
await page.setViewportSize({ width: 800, height: 900 })
|
||||
await expect(field).toBeHidden()
|
||||
await expect(page.locator(':focus')).toHaveCount(0)
|
||||
await page.setViewportSize({ width: 1280, height: 900 })
|
||||
await expect(field).toBeVisible()
|
||||
await expect(field).toHaveValue('Brouillon')
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useEffect, useLayoutEffect, useRef } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import {
|
||||
getOfficialSheetAdmin,
|
||||
@@ -18,10 +18,12 @@ import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery'
|
||||
import { useLeaveGuard } from '@/app/useLeaveGuard'
|
||||
import {
|
||||
editorMode,
|
||||
type EditorMode,
|
||||
hasEditRight,
|
||||
modeAfterSave,
|
||||
storeCanEdit,
|
||||
} from '@/editor/mode'
|
||||
import { releaseEditFocus } from '@/editor/focusRequest'
|
||||
import { leaveGuardArmed, useEditorStore } from '@/editor/state/editorStore'
|
||||
import { useUndoShortcuts } from '@/editor/useUndoShortcuts'
|
||||
import { useTabTier } from '@/editor/useViewport'
|
||||
@@ -37,6 +39,17 @@ interface DraftEditorProps {
|
||||
reloadSheet: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Not editable now: a mode that cannot save, a recovery offer not answered yet, or a
|
||||
* store not yet in step with the mode. The last keeps every render before the recovery
|
||||
* detection of `setCanEdit` read-only.
|
||||
*/
|
||||
function useReadOnly(mode: EditorMode, canEdit: boolean): boolean {
|
||||
const recovery = useEditorStore((s) => s.recovery)
|
||||
const storeEditable = useEditorStore((s) => s.canEdit)
|
||||
return mode !== 'edit' || recovery !== 'none' || storeEditable !== canEdit
|
||||
}
|
||||
|
||||
/**
|
||||
* The draft page once the sheet is read: opens the store session for this version, derives
|
||||
* the mode, and renders what the store holds. Components only render and call actions.
|
||||
@@ -54,13 +67,12 @@ function DraftEditor({
|
||||
const status = useEditorStore((s) => s.status)
|
||||
const sessionVersion = useEditorStore((s) => s.versionId)
|
||||
const failure = useEditorStore((s) => s.failure)
|
||||
const recovery = useEditorStore((s) => s.recovery)
|
||||
const mode = modeAfterSave(
|
||||
editorMode({ hasRight, sheet, wide: tier === 'wide' }),
|
||||
saveFailure,
|
||||
)
|
||||
const canEdit = storeCanEdit(mode)
|
||||
const readOnly = mode !== 'edit' || recovery !== 'none'
|
||||
const readOnly = useReadOnly(mode, canEdit)
|
||||
const firstCanEdit = useRef(canEdit)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -69,7 +81,15 @@ function DraftEditor({
|
||||
.open(versionId, userId, { canEdit: firstCanEdit.current })
|
||||
return () => useEditorStore.getState().close()
|
||||
}, [versionId, userId])
|
||||
useEffect(() => useEditorStore.getState().setCanEdit(canEdit), [canEdit])
|
||||
// `sheet` too: after a submission whose refresh keeps the draft editable, the store
|
||||
// (set to false by `submit()`) is brought back in step.
|
||||
useEffect(
|
||||
() => useEditorStore.getState().setCanEdit(canEdit),
|
||||
[canEdit, sheet],
|
||||
)
|
||||
useLayoutEffect(() => {
|
||||
if (readOnly) releaseEditFocus()
|
||||
}, [readOnly])
|
||||
useLeaveGuard(useEditorStore(leaveGuardArmed))
|
||||
useUndoShortcuts(!readOnly)
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import type {
|
||||
AnatomicalSheetDocument,
|
||||
Dependent,
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import { useEditorReadOnly } from '@/editor/editingContext'
|
||||
import { dependentsOf } from '@/editor/core/editOps'
|
||||
import { refusalMessage } from '@/editor/refusal'
|
||||
import { elementLabel, useSheetDocument } from '@/editor/sheetDocument'
|
||||
@@ -34,6 +35,11 @@ export interface DeleteDialogProps {
|
||||
export default function DeleteDialog({ target, onClose }: DeleteDialogProps) {
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const readOnly = useEditorReadOnly()
|
||||
// A dialog that confirms an edit never stays open once the editor is read-only.
|
||||
useEffect(() => {
|
||||
if (readOnly && target !== null) onClose()
|
||||
}, [readOnly, target, onClose])
|
||||
const heading = t('editor.delete.title').replace(
|
||||
'{name}',
|
||||
target?.label ?? '',
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { useEverEditable } from '@/editor/editingContext'
|
||||
import KeptPlace from './KeptPlace'
|
||||
|
||||
/**
|
||||
* An edit-only part (a creation form, the annotation edit body): mounted at the first
|
||||
* editable render, then kept and hidden while the editor is read-only, so a width change
|
||||
* never drops what was typed in it. Its canvases detach while it is hidden.
|
||||
*/
|
||||
export default function EditOnly({
|
||||
readOnly,
|
||||
children,
|
||||
}: {
|
||||
readOnly: boolean
|
||||
children: ReactNode
|
||||
}) {
|
||||
const mounted = useEverEditable(readOnly)
|
||||
if (!mounted) return null
|
||||
return <KeptPlace visible={!readOnly}>{children}</KeptPlace>
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type { OfficialSheetAdmin } from '@faunosteo/supabase'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { ReadOnlyContext, ReferencesOpenContext } from '@/editor/editingContext'
|
||||
import {
|
||||
AnnounceContext,
|
||||
FocusConsumedContext,
|
||||
@@ -47,6 +49,25 @@ function SaveFailureNotice() {
|
||||
)
|
||||
}
|
||||
|
||||
/** What dialogs and edit-only parts below need of the editor's state. */
|
||||
function EditingState({
|
||||
readOnly,
|
||||
referencesOpen,
|
||||
children,
|
||||
}: {
|
||||
readOnly: boolean
|
||||
referencesOpen: boolean
|
||||
children: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<ReadOnlyContext value={readOnly}>
|
||||
<ReferencesOpenContext value={referencesOpen}>
|
||||
{children}
|
||||
</ReferencesOpenContext>
|
||||
</ReadOnlyContext>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The draft page once the version is ready: header, notices, tab row, the references
|
||||
* panel and the shown place. Owns the navigation state, so the first tab is known at
|
||||
@@ -64,49 +85,51 @@ export default function EditorWorkspace(props: Props) {
|
||||
? nav.closeReferences()
|
||||
: nav.openReferences(null, opener)
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<DraftHeader
|
||||
sheet={sheet}
|
||||
mode={mode}
|
||||
referencesOpen={state.references.open}
|
||||
onToggleReferences={toggleReferences}
|
||||
/>
|
||||
<ModeNotice mode={mode} sheet={sheet} />
|
||||
<SaveFailureNotice />
|
||||
<RecoveryNotice />
|
||||
<CopyIssueNotice />
|
||||
<EditorTabs active={state.tab} tier={tier} onSelect={nav.selectTab} />
|
||||
<FocusConsumedContext value={nav.consumed}>
|
||||
<AnnounceContext value={nav.announce}>
|
||||
{state.referencesMounted && (
|
||||
<KeptPlace name="references" visible={state.references.open}>
|
||||
<ReferencesPanel
|
||||
readOnly={readOnly}
|
||||
focus={ownedBy(state.focus, 'references')}
|
||||
onClose={nav.closeReferences}
|
||||
/>
|
||||
</KeptPlace>
|
||||
)}
|
||||
<EditorTabBody
|
||||
tab={state.tab}
|
||||
visited={state.visitedTabs}
|
||||
readOnly={readOnly}
|
||||
navigate={nav.navigate}
|
||||
focus={state.focus}
|
||||
reloadSheet={reloadSheet}
|
||||
annotations={{
|
||||
section: state.section,
|
||||
visited: state.visitedSections,
|
||||
onOpenSection: nav.openSection,
|
||||
onBack: nav.backToDrawing,
|
||||
}}
|
||||
/>
|
||||
</AnnounceContext>
|
||||
</FocusConsumedContext>
|
||||
<p aria-live="polite" className="sr-only">
|
||||
{nav.live}
|
||||
</p>
|
||||
<ConflictDialog />
|
||||
</div>
|
||||
<EditingState readOnly={readOnly} referencesOpen={state.references.open}>
|
||||
<div className="space-y-4">
|
||||
<DraftHeader
|
||||
sheet={sheet}
|
||||
mode={mode}
|
||||
referencesOpen={state.references.open}
|
||||
onToggleReferences={toggleReferences}
|
||||
/>
|
||||
<ModeNotice mode={mode} sheet={sheet} />
|
||||
<SaveFailureNotice />
|
||||
<RecoveryNotice />
|
||||
<CopyIssueNotice />
|
||||
<EditorTabs active={state.tab} tier={tier} onSelect={nav.selectTab} />
|
||||
<FocusConsumedContext value={nav.consumed}>
|
||||
<AnnounceContext value={nav.announce}>
|
||||
{state.referencesMounted && (
|
||||
<KeptPlace name="references" visible={state.references.open}>
|
||||
<ReferencesPanel
|
||||
readOnly={readOnly}
|
||||
focus={ownedBy(state.focus, 'references')}
|
||||
onClose={nav.closeReferences}
|
||||
/>
|
||||
</KeptPlace>
|
||||
)}
|
||||
<EditorTabBody
|
||||
tab={state.tab}
|
||||
visited={state.visitedTabs}
|
||||
readOnly={readOnly}
|
||||
navigate={nav.navigate}
|
||||
focus={state.focus}
|
||||
reloadSheet={reloadSheet}
|
||||
annotations={{
|
||||
section: state.section,
|
||||
visited: state.visitedSections,
|
||||
onOpenSection: nav.openSection,
|
||||
onBack: nav.backToDrawing,
|
||||
}}
|
||||
/>
|
||||
</AnnounceContext>
|
||||
</FocusConsumedContext>
|
||||
<p aria-live="polite" className="sr-only">
|
||||
{nav.live}
|
||||
</p>
|
||||
<ConflictDialog />
|
||||
</div>
|
||||
</EditingState>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import { useEditorReadOnly } from '@/editor/editingContext'
|
||||
import { loadFailureMessage } from '@/editor/messages'
|
||||
import { useEditorStore } from '@/editor/state/editorStore'
|
||||
import { REFERENCES_BUTTON_ID } from '@/editor/tabs'
|
||||
@@ -22,8 +23,11 @@ function DiscardButton({ onFailure }: Pick<Props, 'onFailure'>) {
|
||||
const t = useT()
|
||||
const unsaved = useEditorStore((s) => s.unsaved)
|
||||
const saving = useEditorStore((s) => s.saving)
|
||||
const blocked = useEditorStore((s) => s.recovery !== 'none')
|
||||
const readOnly = useEditorReadOnly()
|
||||
const [asking, setAsking] = useState(false)
|
||||
useEffect(() => {
|
||||
if (readOnly) setAsking(false)
|
||||
}, [readOnly])
|
||||
const discard = async () => {
|
||||
setAsking(false)
|
||||
const result = await useEditorStore
|
||||
@@ -40,7 +44,7 @@ function DiscardButton({ onFailure }: Pick<Props, 'onFailure'>) {
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
disabled={!unsaved || saving || blocked}
|
||||
disabled={!unsaved || saving || readOnly}
|
||||
onClick={() => setAsking(true)}
|
||||
>
|
||||
{t('editor.draft.discard')}
|
||||
|
||||
@@ -16,6 +16,8 @@ interface Props {
|
||||
doc: AnatomicalSheetDocument
|
||||
readOnly: boolean
|
||||
edit: EditCommandApi
|
||||
/** Put before every field id (the read-only twin of the panel). */
|
||||
idPrefix?: string
|
||||
}
|
||||
|
||||
/** One `update` carrying the whole annotation with `patch` applied. */
|
||||
@@ -37,7 +39,7 @@ const noneOption = (label: string) => ({ value: '', label })
|
||||
function NameFields(props: Props) {
|
||||
const t = useT()
|
||||
const send = useSend(props)
|
||||
const { annotation, edit, readOnly } = props
|
||||
const { annotation, edit, readOnly, idPrefix = '' } = props
|
||||
const isLink = annotation.kind === 'detail_trigger'
|
||||
const rename = (locale: 'fr' | 'en') => (value: string) => {
|
||||
const name = {
|
||||
@@ -55,7 +57,7 @@ function NameFields(props: Props) {
|
||||
{(['fr', 'en'] as const).map((locale) => (
|
||||
<TextField
|
||||
key={locale}
|
||||
id={`annotation-name-${locale}`}
|
||||
id={`${idPrefix}annotation-name-${locale}`}
|
||||
label={t(`editor.annotations.name_${locale}`)}
|
||||
value={annotation.name?.[locale] ?? ''}
|
||||
onCommit={rename(locale)}
|
||||
@@ -72,7 +74,7 @@ export default function AnnotationFields(props: Props) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const send = useSend(props)
|
||||
const { annotation, doc, readOnly, edit } = props
|
||||
const { annotation, doc, readOnly, edit, idPrefix = '' } = props
|
||||
const categories = doc.categories.map((c) => ({
|
||||
value: c.id,
|
||||
label: c.name[locale],
|
||||
@@ -85,7 +87,7 @@ export default function AnnotationFields(props: Props) {
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<NameFields {...props} />
|
||||
<SelectField
|
||||
id="annotation-category"
|
||||
id={`${idPrefix}annotation-category`}
|
||||
label={t('editor.annotations.category')}
|
||||
value={annotation.category_id}
|
||||
options={categories}
|
||||
@@ -94,7 +96,7 @@ export default function AnnotationFields(props: Props) {
|
||||
error={edit.fieldError('category')}
|
||||
/>
|
||||
<TextField
|
||||
id="annotation-color"
|
||||
id={`${idPrefix}annotation-color`}
|
||||
label={t('editor.annotations.color')}
|
||||
value={annotation.color ?? ''}
|
||||
onCommit={(value) => send('color', { color: nullable(value) })}
|
||||
@@ -103,7 +105,7 @@ export default function AnnotationFields(props: Props) {
|
||||
error={edit.fieldError('color')}
|
||||
/>
|
||||
<SelectField
|
||||
id="annotation-laterality"
|
||||
id={`${idPrefix}annotation-laterality`}
|
||||
label={t('editor.annotations.laterality')}
|
||||
value={annotation.laterality}
|
||||
options={sides}
|
||||
@@ -120,7 +122,7 @@ export default function AnnotationFields(props: Props) {
|
||||
)
|
||||
}
|
||||
|
||||
function OpensField({ annotation, doc, readOnly, edit }: Props) {
|
||||
function OpensField({ annotation, doc, readOnly, edit, idPrefix = '' }: Props) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const send = useSend({ annotation, doc, readOnly, edit })
|
||||
@@ -135,7 +137,7 @@ function OpensField({ annotation, doc, readOnly, edit }: Props) {
|
||||
}
|
||||
return (
|
||||
<SelectField
|
||||
id="annotation-opens"
|
||||
id={`${idPrefix}annotation-opens`}
|
||||
label={t('editor.annotations.opens')}
|
||||
value={annotation.opens_view_id}
|
||||
options={options}
|
||||
@@ -150,7 +152,7 @@ function LinkFields(props: Props) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const send = useSend(props)
|
||||
const { annotation, doc, readOnly, edit } = props
|
||||
const { annotation, doc, readOnly, edit, idPrefix = '' } = props
|
||||
if (annotation.kind === 'detail_trigger') return null
|
||||
const regions = [
|
||||
noneOption(t('editor.annotations.none')),
|
||||
@@ -166,7 +168,7 @@ function LinkFields(props: Props) {
|
||||
return (
|
||||
<>
|
||||
<SelectField
|
||||
id="annotation-region"
|
||||
id={`${idPrefix}annotation-region`}
|
||||
label={t('editor.annotations.region')}
|
||||
value={annotation.vertebral_region_code ?? ''}
|
||||
options={regions}
|
||||
@@ -177,7 +179,7 @@ function LinkFields(props: Props) {
|
||||
error={edit.fieldError('region')}
|
||||
/>
|
||||
<SelectField
|
||||
id="annotation-zone"
|
||||
id={`${idPrefix}annotation-zone`}
|
||||
label={t('editor.annotations.zone')}
|
||||
value={annotation.finding_zone_id ?? ''}
|
||||
options={zones}
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
type ViewModel,
|
||||
} from '@/editor/annotations/useViewModel'
|
||||
import type { AnnotationSection } from '@/editor/navigation'
|
||||
import { usePlaceVisible } from '@/lib/placeVisibility'
|
||||
import type { EditorPlaceProps } from '@/editor/tabs'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
@@ -213,6 +214,8 @@ function CanvasStage({
|
||||
placement: Placement
|
||||
}) {
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
// Hidden (the editor is read-only): no drag in flight survives, none is committed.
|
||||
const shown = usePlaceVisible()
|
||||
const { doc, ui, dispatch, model, frame, selected } = scene
|
||||
const view = doc.views.find((v) => v.id === scene.viewId)
|
||||
const blocked = !model.measured || doc.categories.length === 0
|
||||
@@ -223,7 +226,7 @@ function CanvasStage({
|
||||
viewName={view.name[locale]}
|
||||
tool={ui.tool}
|
||||
selectedId={ui.selectedId}
|
||||
moveTarget={moveTargetOf(selected, model, ui.tool)}
|
||||
moveTarget={shown ? moveTargetOf(selected, model, ui.tool) : null}
|
||||
overlay={overlayOf(ui, selected, frame)}
|
||||
tools={{
|
||||
tool: ui.tool,
|
||||
|
||||
@@ -21,6 +21,8 @@ export interface OverviewPanelProps {
|
||||
viewId: string
|
||||
/** Read-only modes only consult: the entries read « Voir … ». */
|
||||
readOnly: boolean
|
||||
/** Put before every id (the read-only twin beside the kept edit panel). */
|
||||
idPrefix?: string
|
||||
onSelectView: (viewId: string) => void
|
||||
onOpenSection: (section: AnnotationSection, opener: HTMLElement) => void
|
||||
}
|
||||
@@ -91,10 +93,11 @@ function ViewRow({
|
||||
function ViewsCard(props: OverviewPanelProps) {
|
||||
const t = useT()
|
||||
const { doc, viewId, readOnly, onSelectView, onOpenSection } = props
|
||||
const id = `${props.idPrefix ?? ''}overview-views`
|
||||
const counts = useOverviewCounts(doc)
|
||||
return (
|
||||
<section aria-labelledby="overview-views" className={CARD}>
|
||||
<h3 id="overview-views" className={TITLE}>
|
||||
<section aria-labelledby={id} className={CARD}>
|
||||
<h3 id={id} className={TITLE}>
|
||||
{t('editor.overview.views')}
|
||||
</h3>
|
||||
<ul>
|
||||
@@ -126,13 +129,11 @@ function CategoriesCard(props: OverviewPanelProps) {
|
||||
const plural = usePlural()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { doc, readOnly, onOpenSection } = props
|
||||
const id = `${props.idPrefix ?? ''}overview-categories`
|
||||
const counts = useOverviewCounts(doc)
|
||||
return (
|
||||
<section aria-labelledby="overview-categories" className={CARD}>
|
||||
<h3
|
||||
id="overview-categories"
|
||||
className={`${TITLE} flex items-center justify-between`}
|
||||
>
|
||||
<section aria-labelledby={id} className={CARD}>
|
||||
<h3 id={id} className={`${TITLE} flex items-center justify-between`}>
|
||||
{t('editor.overview.categories')}
|
||||
<span
|
||||
data-testid="overview-categories-count"
|
||||
|
||||
@@ -37,6 +37,8 @@ export interface PropertiesPanelProps {
|
||||
dispatch: Dispatch<UiAction>
|
||||
context: CommitContext
|
||||
navigate: EditorPlaceProps['navigate']
|
||||
/** Put before every id, for a twin of the panel that lives beside another one. */
|
||||
idPrefix?: string
|
||||
}
|
||||
|
||||
/** What still names this annotation as invalid: never hidden, never shown as valid. */
|
||||
@@ -73,6 +75,7 @@ export default function PropertiesPanel(props: PropertiesPanelProps) {
|
||||
doc={doc}
|
||||
readOnly={readOnly}
|
||||
edit={edit}
|
||||
idPrefix={props.idPrefix}
|
||||
/>
|
||||
<GeometrySection {...props} />
|
||||
<StatusActions annotation={annotation} readOnly={readOnly} edit={edit} />
|
||||
@@ -94,7 +97,7 @@ function GeometrySection(props: PropertiesPanelProps) {
|
||||
{isEditable(geometry) ? (
|
||||
<GeometryGroup
|
||||
key={annotation.id}
|
||||
idPrefix="annotation"
|
||||
idPrefix={`${props.idPrefix ?? ''}annotation`}
|
||||
geometry={geometry}
|
||||
locked={locked}
|
||||
onApply={(next) => applyGeometry(annotation, next, props.context)}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useState } from 'react'
|
||||
import DeleteDialog, {
|
||||
type DeleteTarget,
|
||||
} from '@/components/editor/DeleteDialog'
|
||||
import EditOnly from '@/components/editor/EditOnly'
|
||||
import RegionForm from '@/components/editor/vertebrae/RegionForm'
|
||||
import RegionRow from '@/components/editor/vertebrae/RegionRow'
|
||||
import { useRowFocus } from '@/editor/focusRequest'
|
||||
@@ -48,7 +49,11 @@ export default function RegionsSection({
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
{doc && !readOnly && <RegionForm />}
|
||||
{doc && (
|
||||
<EditOnly readOnly={readOnly}>
|
||||
<RegionForm />
|
||||
</EditOnly>
|
||||
)}
|
||||
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useState } from 'react'
|
||||
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'
|
||||
@@ -61,7 +62,11 @@ export default function ViewsSection({
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
{doc && !readOnly && <DetailViewForm views={views} />}
|
||||
{doc && (
|
||||
<EditOnly readOnly={readOnly}>
|
||||
<DetailViewForm views={views} />
|
||||
</EditOnly>
|
||||
)}
|
||||
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
AnatomicalSheetDocument,
|
||||
AnnotationCategory,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import EditOnly from '@/components/editor/EditOnly'
|
||||
import ActionButton from '@/components/editor/fields/ActionButton'
|
||||
import DraftField from '@/components/editor/fields/DraftField'
|
||||
import TextField from '@/components/editor/fields/TextField'
|
||||
@@ -53,7 +54,9 @@ export default function CategoriesSection({
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
{!readOnly && <CategoryForm />}
|
||||
<EditOnly readOnly={readOnly}>
|
||||
<CategoryForm />
|
||||
</EditOnly>
|
||||
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useState, type KeyboardEvent } from 'react'
|
||||
import DeleteDialog, {
|
||||
type DeleteTarget,
|
||||
} from '@/components/editor/DeleteDialog'
|
||||
import EditOnly from '@/components/editor/EditOnly'
|
||||
import ReferenceForm from '@/components/editor/references/ReferenceForm'
|
||||
import ReferenceRow from '@/components/editor/references/ReferenceRow'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
@@ -19,11 +20,7 @@ interface Props extends Pick<EditorPlaceProps, 'readOnly' | 'focus'> {
|
||||
* from the findings, opened by the header button. Not a dialog: it keeps the page usable.
|
||||
* The workspace mounts it at the first opening and keeps it (hidden) afterwards.
|
||||
*/
|
||||
export default function ReferencesPanel({
|
||||
readOnly,
|
||||
focus,
|
||||
onClose,
|
||||
}: Props) {
|
||||
export default function ReferencesPanel({ readOnly, focus, onClose }: Props) {
|
||||
const t = useT()
|
||||
useRowFocus(focus)
|
||||
const doc = useSheetDocument()
|
||||
@@ -82,7 +79,11 @@ export default function ReferencesPanel({
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
{doc && !readOnly && <ReferenceForm />}
|
||||
{doc && (
|
||||
<EditOnly readOnly={readOnly}>
|
||||
<ReferenceForm />
|
||||
</EditOnly>
|
||||
)}
|
||||
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -10,6 +10,7 @@ import PropertiesPanel from '@/components/editor/annotations/PropertiesPanel'
|
||||
import AnnotationSection from '@/components/editor/annotations/sections/AnnotationSection'
|
||||
import ViewSwitcher from '@/components/editor/annotations/ViewSwitcher'
|
||||
import SelectionTag from '@/components/editor/annotations/SelectionTag'
|
||||
import EditOnly from '@/components/editor/EditOnly'
|
||||
import KeptPlace from '@/components/editor/KeptPlace'
|
||||
import { ownedBy } from '@/editor/focusRequest'
|
||||
import { useAnnotationRequest } from '@/editor/annotations/focusTarget'
|
||||
@@ -58,7 +59,7 @@ function DrawingPlace(props: AnnotationsTabProps) {
|
||||
const doc = useSheetDocument()
|
||||
const preview = useEditorStore((s) => s.preview)
|
||||
const { readOnly, navigate, onOpenSection, focus } = props
|
||||
const body = { navigate, onOpenSection, focus }
|
||||
const body = { navigate, onOpenSection }
|
||||
const ready = doc && preview
|
||||
return (
|
||||
<section
|
||||
@@ -66,8 +67,18 @@ function DrawingPlace(props: AnnotationsTabProps) {
|
||||
aria-label={t('editor.tab.annotations')}
|
||||
className="min-h-24 space-y-3"
|
||||
>
|
||||
{ready && readOnly && <ReadOnlyAnnotations {...body} doc={doc} />}
|
||||
{ready && !readOnly && <EditableAnnotations {...body} doc={doc} />}
|
||||
{ready && readOnly && (
|
||||
<ReadOnlyAnnotations {...body} focus={focus} doc={doc} />
|
||||
)}
|
||||
{ready && (
|
||||
<EditOnly readOnly={readOnly}>
|
||||
<EditableAnnotations
|
||||
{...body}
|
||||
focus={readOnly ? undefined : focus}
|
||||
doc={doc}
|
||||
/>
|
||||
</EditOnly>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -118,6 +129,12 @@ function useViewFallback(
|
||||
}, [doc, shown, setViewId, setSelectedId])
|
||||
}
|
||||
|
||||
/**
|
||||
* The read-only body shares the tab with the kept (hidden) edit body: whatever both
|
||||
* render takes this prefix here, so no id repeats in the page.
|
||||
*/
|
||||
const READ_ONLY_IDS = 'ro-'
|
||||
|
||||
function ReadOnlyAnnotations({
|
||||
doc,
|
||||
navigate,
|
||||
@@ -185,6 +202,7 @@ function ReadOnlyAnnotations({
|
||||
key={selected.id}
|
||||
annotation={selected}
|
||||
doc={doc}
|
||||
idPrefix={READ_ONLY_IDS}
|
||||
readOnly
|
||||
geometryLocked={!model.measured}
|
||||
dispatch={() => undefined}
|
||||
@@ -195,6 +213,7 @@ function ReadOnlyAnnotations({
|
||||
<OverviewPanel
|
||||
doc={doc}
|
||||
viewId={viewId}
|
||||
idPrefix={READ_ONLY_IDS}
|
||||
readOnly
|
||||
onSelectView={(id) => {
|
||||
setViewId(id)
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useCallback, useMemo, useState } from 'react'
|
||||
import DeleteDialog, {
|
||||
type DeleteTarget,
|
||||
} from '@/components/editor/DeleteDialog'
|
||||
import EditOnly from '@/components/editor/EditOnly'
|
||||
import AddBar from '@/components/editor/findings/AddBar'
|
||||
import FindingCreateForm, {
|
||||
type PendingFinding,
|
||||
@@ -120,13 +121,15 @@ export default function FindingsTab({ readOnly, focus }: EditorPlaceProps) {
|
||||
readOnly={readOnly}
|
||||
onStart={setPending}
|
||||
/>
|
||||
{pending && !readOnly && (
|
||||
<FindingCreateForm
|
||||
key={`${pending.kind}-${pending.parent?.id ?? ''}`}
|
||||
pending={pending}
|
||||
onCreated={created}
|
||||
onCancel={() => setPending(null)}
|
||||
/>
|
||||
{pending && (
|
||||
<EditOnly readOnly={readOnly}>
|
||||
<FindingCreateForm
|
||||
key={`${pending.kind}-${pending.parent?.id ?? ''}`}
|
||||
pending={pending}
|
||||
onCreated={created}
|
||||
onCancel={() => setPending(null)}
|
||||
/>
|
||||
</EditOnly>
|
||||
)}
|
||||
{doc && items.length === 0 && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
|
||||
@@ -2,6 +2,7 @@ import type {
|
||||
AnatomicalSheetDocument,
|
||||
SheetReport,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import EditOnly from '@/components/editor/EditOnly'
|
||||
import IssueList from '@/components/editor/verification/IssueList'
|
||||
import {
|
||||
Completeness,
|
||||
@@ -49,9 +50,9 @@ function Panel({ report, doc, readOnly, navigate, reloadSheet }: PanelProps) {
|
||||
<Completeness report={report} />
|
||||
<GroupStatuses report={report} doc={doc} />
|
||||
<SizeAndCaps report={report} />
|
||||
{!readOnly && (
|
||||
<EditOnly readOnly={readOnly}>
|
||||
<SubmitPanel errorCount={errors.length} reloadSheet={reloadSheet} />
|
||||
)}
|
||||
</EditOnly>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ViewBox } from '@faunosteo/core-wasm/types'
|
||||
import EditOnly from '@/components/editor/EditOnly'
|
||||
import ActionButton from '@/components/editor/fields/ActionButton'
|
||||
import DraftField from '@/components/editor/fields/DraftField'
|
||||
import ReadOnlyValue from '@/components/editor/fields/ReadOnlyValue'
|
||||
@@ -13,16 +14,31 @@ interface CropProps {
|
||||
box: ViewBox | null
|
||||
}
|
||||
|
||||
/** The read-only twin of the fields shares no id with the kept edit group. */
|
||||
const READ_ONLY_PREFIX = 'ro-'
|
||||
|
||||
/**
|
||||
* The four `view_box` fields as ONE group: leaving the group or Enter proposes all four
|
||||
* together (a frame change under the geometry check). A refused group stays shown,
|
||||
* marked « non appliqué », with the refusal naming what it would break.
|
||||
* marked « non appliqué », with the refusal naming what it would break. While the
|
||||
* editor is read-only the group stays mounted, hidden (a width change keeps what was
|
||||
* typed), beside the values as text.
|
||||
*/
|
||||
export default function CropEditor({
|
||||
readOnly,
|
||||
open,
|
||||
...props
|
||||
}: CropProps & { readOnly: boolean }) {
|
||||
return readOnly ? <CropValues {...props} /> : <EditableCrop {...props} />
|
||||
}: CropProps & { readOnly: boolean; open: boolean }) {
|
||||
return (
|
||||
<>
|
||||
{open && (
|
||||
<EditOnly readOnly={readOnly}>
|
||||
<EditableCrop {...props} />
|
||||
</EditOnly>
|
||||
)}
|
||||
{readOnly && <CropValues {...props} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function CropValues({ viewId, box }: CropProps) {
|
||||
@@ -33,7 +49,7 @@ function CropValues({ viewId, box }: CropProps) {
|
||||
{BOX_KEYS.map((key) => (
|
||||
<ReadOnlyValue
|
||||
key={key}
|
||||
id={`view-${viewId}-crop-${key}`}
|
||||
id={`${READ_ONLY_PREFIX}view-${viewId}-crop-${key}`}
|
||||
label={t(`editor.views.crop.${key}`)}
|
||||
value={fields[key]}
|
||||
/>
|
||||
|
||||
@@ -70,14 +70,13 @@ export default function DetailViewRow({
|
||||
{t('editor.views.crop.toggle')}
|
||||
</ActionButton>
|
||||
</div>
|
||||
{(readOnly || cropOpen) && (
|
||||
<CropEditor
|
||||
viewId={view.id}
|
||||
parentId={view.parent_view_id}
|
||||
box={view.view_box}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
)}
|
||||
<CropEditor
|
||||
viewId={view.id}
|
||||
parentId={view.parent_view_id}
|
||||
box={view.view_box}
|
||||
readOnly={readOnly}
|
||||
open={cropOpen}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<ActionButton
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { createContext, useContext, useState } from 'react'
|
||||
import { usePlaceVisible } from '@/lib/placeVisibility'
|
||||
|
||||
/** The editor cannot be edited now (route rule: mode, recovery, store not in step). */
|
||||
export const ReadOnlyContext = createContext(false)
|
||||
|
||||
/** The references panel is open: a place beside it is not where a modal may open. */
|
||||
export const ReferencesOpenContext = createContext(false)
|
||||
|
||||
export function useEditorReadOnly(): boolean {
|
||||
return useContext(ReadOnlyContext)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a decision dialog of a kept part may open: only while editing, in a shown
|
||||
* place, with the references panel closed, so no native modal ever sits inside a hidden
|
||||
* subtree and focus is never lost to `body`.
|
||||
*/
|
||||
export function useDecisionsOpen(): boolean {
|
||||
const readOnly = useContext(ReadOnlyContext)
|
||||
const referencesOpen = useContext(ReferencesOpenContext)
|
||||
const visible = usePlaceVisible()
|
||||
return !readOnly && visible && !referencesOpen
|
||||
}
|
||||
|
||||
/**
|
||||
* True from the first render that is editable, and for good: an edit-only part mounts
|
||||
* then and is kept (hidden) afterwards; a page opened read-only never mounts it.
|
||||
*/
|
||||
export function useEverEditable(readOnly: boolean): boolean {
|
||||
const [ever, setEver] = useState(!readOnly)
|
||||
if (!readOnly && !ever) setEver(true)
|
||||
return ever || !readOnly
|
||||
}
|
||||
|
||||
/** What a decision dialog needs: the decision to show now, and whether one is held back. */
|
||||
export interface DecisionGate<T> {
|
||||
shown: T | null
|
||||
withheld: boolean
|
||||
resume: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Gates a decision object (a cleaning candidate, a repair offer, a parent choice). A
|
||||
* decision that exists in any render where `open` is false is withheld for good: it never
|
||||
* reopens by itself, only through `resume` (the « Reprendre » button). A new decision
|
||||
* that arrives while `open` is true opens normally.
|
||||
*/
|
||||
export function useDecisionGate<T extends object>(
|
||||
decision: T | null,
|
||||
open: boolean,
|
||||
): DecisionGate<T> {
|
||||
const [held, setHeld] = useState<T | null>(null)
|
||||
const [resumed, setResumed] = useState<T | null>(null)
|
||||
if (decision !== null && !open) {
|
||||
if (held !== decision) setHeld(decision)
|
||||
if (resumed === decision) setResumed(null)
|
||||
}
|
||||
const withheld =
|
||||
decision !== null && held === decision && resumed !== decision
|
||||
return {
|
||||
shown: decision !== null && open && !withheld ? decision : null,
|
||||
withheld,
|
||||
resume: () => setResumed(decision),
|
||||
}
|
||||
}
|
||||
@@ -117,3 +117,13 @@ export function commitFocusedField(): void {
|
||||
active.blur()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The editor turned read-only: commits the text being typed, then releases any focus left
|
||||
* inside a hidden part, so no field is focused in a place that left the page.
|
||||
*/
|
||||
export function releaseEditFocus(): void {
|
||||
commitFocusedField()
|
||||
const active = document.activeElement
|
||||
if (active instanceof HTMLElement && active.closest('[hidden]')) active.blur()
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { commitFocusedField } from './focusRequest'
|
||||
import { MIN_EDIT_WIDTH } from './mode'
|
||||
|
||||
/** The tab lists of board 05: all, the four of 640 px and over, the two below. */
|
||||
@@ -11,11 +12,24 @@ function tierOf(width: number): TabTier {
|
||||
return width >= MEDIUM_WIDTH ? 'medium' : 'small'
|
||||
}
|
||||
|
||||
/** Whether the width moved across the 1 024 px edit threshold. */
|
||||
function crossesEditWidth(from: TabTier, to: TabTier): boolean {
|
||||
return (from === 'wide') !== (to === 'wide')
|
||||
}
|
||||
|
||||
/** The viewport's tier, kept in step with the window (resize and rotation). */
|
||||
export function useTabTier(): TabTier {
|
||||
const [tier, setTier] = useState<TabTier>(() => tierOf(window.innerWidth))
|
||||
const previous = useRef(tier)
|
||||
useEffect(() => {
|
||||
const update = () => setTier(tierOf(window.innerWidth))
|
||||
const update = () => {
|
||||
const next = tierOf(window.innerWidth)
|
||||
// The typed text is committed before the editor turns read-only (or back): a blur
|
||||
// after the hide would be too late, a hidden field keeps no focus event.
|
||||
if (crossesEditWidth(previous.current, next)) commitFocusedField()
|
||||
previous.current = next
|
||||
setTier(next)
|
||||
}
|
||||
update()
|
||||
window.addEventListener('resize', update)
|
||||
return () => window.removeEventListener('resize', update)
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
/** U1 Lot B2b: a 1 024 px crossing or a recovery decision never loses typed input. */
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
act,
|
||||
cleanup,
|
||||
fireEvent,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useAuthStore } from '@/state/authStore'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { drawnText, emptyText, insert, point } from '../helpers/editorFixtures'
|
||||
import {
|
||||
SHEET,
|
||||
USER,
|
||||
VERSION,
|
||||
baseText,
|
||||
copyKeyOf,
|
||||
resetStore,
|
||||
serverHas,
|
||||
storedCopy,
|
||||
store,
|
||||
sb,
|
||||
} from '../helpers/editorHarness'
|
||||
import {
|
||||
adminAnswer,
|
||||
grant,
|
||||
mountDraft,
|
||||
round,
|
||||
setWidth,
|
||||
} from '../helpers/editorRoute'
|
||||
|
||||
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
|
||||
vi.mock('@faunosteo/supabase', async (orig) => ({
|
||||
...(await orig<typeof import('@faunosteo/supabase')>()),
|
||||
getSheetVersion: vi.fn(),
|
||||
downloadSheetDrawing: vi.fn(),
|
||||
saveSheetDraft: vi.fn(),
|
||||
getOfficialSheetAdmin: vi.fn(),
|
||||
submitSheetReview: vi.fn(),
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
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 }),
|
||||
})
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
resetStore()
|
||||
setWidth(1024)
|
||||
})
|
||||
|
||||
const ready = () =>
|
||||
screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
|
||||
const tab = (name: string | RegExp) => screen.getByRole('tab', { name })
|
||||
const button = (name: string | RegExp) => screen.getByRole('button', { name })
|
||||
const place = (name: string) =>
|
||||
document.querySelector<HTMLElement>(`[data-place="${name}"]`)!
|
||||
const byId = (id: string) => document.getElementById(id) as HTMLInputElement
|
||||
|
||||
/** A real window resize across the 1 024 px edit threshold. */
|
||||
function cross(width: number) {
|
||||
act(() => {
|
||||
setWidth(width)
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
})
|
||||
}
|
||||
|
||||
async function mount(text = baseText()) {
|
||||
serverHas(text, 3)
|
||||
const user = userEvent.setup()
|
||||
mountDraft()
|
||||
await ready()
|
||||
return user
|
||||
}
|
||||
|
||||
function duplicateIds(): string[] {
|
||||
const seen = new Map<string, number>()
|
||||
for (const element of document.querySelectorAll('[id]')) {
|
||||
seen.set(element.id, (seen.get(element.id) ?? 0) + 1)
|
||||
}
|
||||
return [...seen].filter(([, count]) => count > 1).map(([id]) => id)
|
||||
}
|
||||
|
||||
const detail = (extra: object = {}) =>
|
||||
({
|
||||
kind: 'view',
|
||||
value: {
|
||||
kind: 'detail',
|
||||
id: 'view-d',
|
||||
name: { fr: 'Détail', en: 'Detail' },
|
||||
svg_asset_id: null,
|
||||
view_box: { min_x: 0, min_y: 0, width: 50, height: 50 },
|
||||
parent_view_id: 'view-main',
|
||||
...extra,
|
||||
},
|
||||
}) as Parameters<typeof insert>[1]
|
||||
|
||||
const spareCategory = (text: string) =>
|
||||
insert(text, {
|
||||
kind: 'category',
|
||||
value: { id: 'cat-spare', name: { fr: 'Libre', en: 'Free' }, color: null },
|
||||
})
|
||||
|
||||
type User = ReturnType<typeof userEvent.setup>
|
||||
|
||||
/** Types in `#id`, crosses below 1 024 px, checks the part left the page, widens, checks it is back. */
|
||||
async function keepsTypedValue(
|
||||
user: User,
|
||||
id: string,
|
||||
controlName: string,
|
||||
addName: string,
|
||||
) {
|
||||
const field = byId(id)
|
||||
await user.type(field, 'Saisie')
|
||||
cross(800)
|
||||
expect(field.closest('[hidden]')).not.toBeNull()
|
||||
expect(screen.queryByRole('textbox', { name: controlName })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: addName })).toBeNull()
|
||||
cross(1280)
|
||||
expect(byId(id)).toBe(field)
|
||||
expect(field).toBeVisible()
|
||||
expect(field).toHaveValue('Saisie')
|
||||
expect(store.getState().unsaved).toBe(false)
|
||||
}
|
||||
|
||||
describe('typed values come back after a 1 024 px crossing', () => {
|
||||
it('the category creation form', async () => {
|
||||
const user = await mount()
|
||||
await user.click(tab('Annotations'))
|
||||
await user.click(button('Modifier les catégories'))
|
||||
await keepsTypedValue(
|
||||
user,
|
||||
'category-new-fr',
|
||||
'Nom de la catégorie (FR)',
|
||||
'Ajouter la catégorie',
|
||||
)
|
||||
})
|
||||
|
||||
it('the reference creation form, in the references panel', async () => {
|
||||
const user = await mount()
|
||||
await user.click(button('Références'))
|
||||
await keepsTypedValue(
|
||||
user,
|
||||
'reference-new-citation',
|
||||
'Citation',
|
||||
'Ajouter la référence',
|
||||
)
|
||||
})
|
||||
|
||||
it('the region creation form', async () => {
|
||||
const user = await mount()
|
||||
await user.click(tab('Annotations'))
|
||||
await user.click(
|
||||
document.querySelector<HTMLElement>('[data-section-entry="regions"]')!,
|
||||
)
|
||||
await keepsTypedValue(user, 'region-new-code', 'Code', 'Ajouter la région')
|
||||
})
|
||||
|
||||
it('the detail view creation form', async () => {
|
||||
const user = await mount()
|
||||
await user.click(tab('Annotations'))
|
||||
await user.click(button('Gérer les vues'))
|
||||
await keepsTypedValue(user, 'view-new-fr', 'Nom (FR)', 'Ajouter la vue')
|
||||
})
|
||||
|
||||
it('the findings creation form', async () => {
|
||||
const user = await mount()
|
||||
await user.click(tab('Constats'))
|
||||
await user.click(button('Ajouter une zone'))
|
||||
await keepsTypedValue(
|
||||
user,
|
||||
'finding-new-name-fr',
|
||||
'Nom (FR)',
|
||||
'Ajouter une zone',
|
||||
)
|
||||
})
|
||||
|
||||
it('the submission note', async () => {
|
||||
const user = await mount()
|
||||
await user.click(tab(/Vérification/))
|
||||
await keepsTypedValue(
|
||||
user,
|
||||
'verification-note',
|
||||
'Note de soumission (obligatoire)',
|
||||
'Soumettre à la revue',
|
||||
)
|
||||
})
|
||||
|
||||
it('the crop group editor, open, with the typed numbers', async () => {
|
||||
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'))
|
||||
const field = byId('view-view-d-crop-min_x')
|
||||
await user.clear(field)
|
||||
await user.type(field, '7x')
|
||||
cross(800)
|
||||
expect(field.closest('[hidden]')).not.toBeNull()
|
||||
expect(screen.queryByRole('group', { name: 'Recadrage' })).toBeNull()
|
||||
expect(byId('ro-view-view-d-crop-min_x')).toBeTruthy()
|
||||
cross(1280)
|
||||
expect(byId('view-view-d-crop-min_x')).toBe(field)
|
||||
expect(field).toHaveValue('7x')
|
||||
expect(store.getState().unsaved).toBe(false)
|
||||
})
|
||||
|
||||
it('the annotation edit body: tool, pending creation with its name', async () => {
|
||||
const user = await mount(baseText())
|
||||
const drawing = within(place('annotations.drawing'))
|
||||
await waitFor(() =>
|
||||
expect(drawing.getByRole('button', { name: 'Zone' })).toBeEnabled(),
|
||||
)
|
||||
await user.click(drawing.getByRole('button', { name: 'Zone' }))
|
||||
await user.click(drawing.getByRole('button', { name: 'Ajouter un point' }))
|
||||
const name = await screen.findByLabelText('Nom (FR)')
|
||||
await user.type(name, 'Futur point')
|
||||
cross(800)
|
||||
expect(name.closest('[hidden]')).not.toBeNull()
|
||||
expect(screen.queryByRole('region', { name: 'Nouveau point' })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Zone' })).toBeNull()
|
||||
cross(1280)
|
||||
expect(screen.getByLabelText('Nom (FR)')).toBe(name)
|
||||
expect(name).toHaveValue('Futur point')
|
||||
expect(drawing.getByRole('button', { name: 'Zone' })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'true',
|
||||
)
|
||||
expect(store.getState().unsaved).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the guards of a width change', () => {
|
||||
it('commits a typed, unblurred field before the editor turns read-only', async () => {
|
||||
const user = await mount()
|
||||
await user.click(tab('Général'))
|
||||
const field = byId('general-name-fr')
|
||||
await user.click(field)
|
||||
fireEvent.change(field, { target: { value: 'Nom saisi' } })
|
||||
expect(store.getState().unsaved).toBe(false)
|
||||
cross(800)
|
||||
expect(JSON.parse(store.getState().documentText).name.fr).toBe('Nom saisi')
|
||||
expect(store.getState().unsaved).toBe(true)
|
||||
await waitFor(() => expect(storedCopy()).not.toBeNull())
|
||||
})
|
||||
|
||||
it('a field that switches in place loses a refused value, a field of a kept part keeps it', async () => {
|
||||
const user = await mount()
|
||||
await user.click(tab('Général'))
|
||||
const general = byId('general-name-fr')
|
||||
await user.clear(general)
|
||||
cross(800)
|
||||
cross(1280)
|
||||
expect(byId('general-name-fr')).toHaveValue('Fiche')
|
||||
await user.click(tab('Annotations'))
|
||||
await user.click(button('Modifier les catégories'))
|
||||
await user.type(byId('category-new-en'), 'Gardé')
|
||||
cross(800)
|
||||
cross(1280)
|
||||
expect(byId('category-new-en')).toHaveValue('Gardé')
|
||||
})
|
||||
|
||||
it('drops a drag in flight without a commit', async () => {
|
||||
const user = await mount()
|
||||
const drawing = place('annotations.drawing')
|
||||
await user.click(
|
||||
within(drawing).getAllByRole('button', { name: /Point|anno-a/ })[0],
|
||||
)
|
||||
const marker = () =>
|
||||
drawing.querySelector<Element>('[data-anno-id="anno-a"]')!
|
||||
await waitFor(() => expect(marker()).not.toBeNull())
|
||||
fireEvent.pointerDown(marker(), {
|
||||
clientX: 50,
|
||||
clientY: 50,
|
||||
button: 0,
|
||||
pointerId: 1,
|
||||
})
|
||||
fireEvent.pointerMove(marker(), { clientX: 70, clientY: 50, pointerId: 1 })
|
||||
const version = store.getState().handleVersion
|
||||
cross(800)
|
||||
cross(1280)
|
||||
await waitFor(() => expect(marker()).not.toBeNull())
|
||||
fireEvent.pointerUp(marker(), { clientX: 70, clientY: 50, pointerId: 1 })
|
||||
expect(store.getState().handleVersion).toBe(version)
|
||||
expect(store.getState().unsaved).toBe(false)
|
||||
})
|
||||
|
||||
it('closes a delete confirmation and the discard confirmation when the editor turns read-only', async () => {
|
||||
const user = await mount(spareCategory(baseText()))
|
||||
await user.click(tab('Annotations'))
|
||||
await user.click(button('Modifier les catégories'))
|
||||
await user.click(screen.getAllByRole('button', { name: 'Supprimer' })[1])
|
||||
expect(document.querySelectorAll('dialog[open]')).toHaveLength(1)
|
||||
cross(800)
|
||||
await waitFor(() =>
|
||||
expect(document.querySelectorAll('dialog[open]')).toHaveLength(0),
|
||||
)
|
||||
cross(1280)
|
||||
expect(document.querySelectorAll('dialog[open]')).toHaveLength(0)
|
||||
expect(JSON.parse(store.getState().documentText).categories).toHaveLength(2)
|
||||
// the discard confirmation: opened on unsaved work, closed by a recovery block
|
||||
fireEvent.change(byId('category-new-fr'), { target: { value: 'x' } })
|
||||
act(
|
||||
() =>
|
||||
void store.getState().commit({
|
||||
op: 'update',
|
||||
key: { kind: 'annotation', id: 'anno-a' },
|
||||
element: point('anno-a', 60, 50, 5),
|
||||
}),
|
||||
)
|
||||
await user.click(button('Annuler les modifications'))
|
||||
expect(document.querySelectorAll('dialog[open]')).toHaveLength(1)
|
||||
act(() => store.setState({ recovery: 'pending' }))
|
||||
await waitFor(() =>
|
||||
expect(document.querySelectorAll('dialog[open]')).toHaveLength(0),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ids stay unique', () => {
|
||||
async function everyPlace(user: User) {
|
||||
for (const name of ['Général', 'Constats', /Vérification/, 'Annotations']) {
|
||||
await user.click(tab(name))
|
||||
}
|
||||
await user.click(button('Gérer les vues'))
|
||||
await user.click(button('Modifier le recadrage'))
|
||||
await user.click(button('Retour au dessin'))
|
||||
await user.click(button('Références'))
|
||||
}
|
||||
const text = () => insert(baseText(), detail())
|
||||
|
||||
it('in edit mode and after a crossing, nothing selected', async () => {
|
||||
const user = await mount(text())
|
||||
await everyPlace(user)
|
||||
expect(duplicateIds()).toEqual([])
|
||||
cross(800)
|
||||
expect(duplicateIds()).toEqual([])
|
||||
cross(1280)
|
||||
expect(duplicateIds()).toEqual([])
|
||||
})
|
||||
|
||||
it('with a selection, the read-only twin takes its own ids', async () => {
|
||||
const user = await mount(text())
|
||||
await everyPlace(user)
|
||||
const list = within(place('annotations.drawing')).getByRole('list', {
|
||||
name: 'Annotations de la vue',
|
||||
})
|
||||
await user.click(within(list).getAllByRole('button')[0])
|
||||
expect(duplicateIds()).toEqual([])
|
||||
cross(800)
|
||||
expect(duplicateIds()).toEqual([])
|
||||
const twin = screen
|
||||
.getAllByRole('list', { name: 'Annotations de la vue' })
|
||||
.find((candidate) => !candidate.closest('[hidden]'))!
|
||||
await user.click(within(twin).getAllByRole('button')[0])
|
||||
expect(duplicateIds()).toEqual([])
|
||||
expect(document.getElementById('ro-annotation-name-fr')).not.toBeNull()
|
||||
expect(document.getElementById('annotation-name-fr')).not.toBeNull()
|
||||
cross(1280)
|
||||
expect(duplicateIds()).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('focus requests', () => {
|
||||
it('go to the visible annotation body only', async () => {
|
||||
const bare = point('anno-bare', 10, 10, 2)
|
||||
const value = {
|
||||
...bare.value,
|
||||
geometry: null,
|
||||
name: { fr: 'Sans tracé', en: 'Bare' },
|
||||
}
|
||||
const user = await mount(
|
||||
insert(baseText(), { kind: 'annotation', value } as typeof bare),
|
||||
)
|
||||
cross(800)
|
||||
await user.click(tab(/Vérification/))
|
||||
fireEvent.click(
|
||||
screen.getAllByRole('button', { name: 'Aller à Sans tracé' })[0],
|
||||
)
|
||||
const visible = (id: string) =>
|
||||
[...document.querySelectorAll(`[data-testid="${id}"]`)].filter(
|
||||
(element) => !element.closest('[hidden]'),
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(visible('annotation-properties')).toHaveLength(1),
|
||||
)
|
||||
cross(1280)
|
||||
expect(visible('annotation-properties')).toHaveLength(0)
|
||||
expect(visible('annotation-overview')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('edit-only parts of a page opened read-only', () => {
|
||||
it('a page opened narrow has no edit body and no creation form', async () => {
|
||||
serverHas(baseText(), 3)
|
||||
mountDraft({ width: 800 })
|
||||
await ready()
|
||||
expect(document.querySelector('[data-place] [data-place]')).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Zone' })).toBeNull()
|
||||
expect(screen.queryByTestId('annotation-canvas')).toBeNull()
|
||||
cross(1280)
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('annotation-canvas')).toBeVisible(),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('recovery decisions', () => {
|
||||
function seedCopy() {
|
||||
sessionStorage.setItem(
|
||||
copyKeyOf(),
|
||||
JSON.stringify({
|
||||
v: 1,
|
||||
user_id: USER,
|
||||
version_id: VERSION,
|
||||
sheet_id: SHEET,
|
||||
sheet_name: 'Fiche',
|
||||
revision: 3,
|
||||
written_at: '2026-11-03T10:00:00Z',
|
||||
document: JSON.parse(emptyText()),
|
||||
drawings: [],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
it('a pending offer at opening: no edit part, empty forms after the answer', async () => {
|
||||
seedCopy()
|
||||
const user = await mount()
|
||||
expect(byId('category-new-fr')).toBeNull()
|
||||
expect(screen.getByTestId('catalogue-canvas')).toBeVisible()
|
||||
await user.click(button('Ignorer la copie'))
|
||||
await user.click(
|
||||
within(await screen.findByRole('dialog')).getByRole('button', {
|
||||
name: 'Abandonner la copie',
|
||||
}),
|
||||
)
|
||||
await waitFor(() => expect(store.getState().recovery).toBe('none'))
|
||||
await user.click(tab('Annotations'))
|
||||
await user.click(button('Modifier les catégories'))
|
||||
expect(byId('category-new-fr')).toHaveValue('')
|
||||
})
|
||||
|
||||
it('rights to edit inside one mount with a copy: no edit part before the offer', async () => {
|
||||
seedCopy()
|
||||
serverHas(baseText(), 3)
|
||||
mountDraft({ grants: [grant('sheet_reviewer')] })
|
||||
await ready()
|
||||
act(() => useAuthStore.setState({ catalogGrants: [grant('sheet_editor')] }))
|
||||
await waitFor(() => expect(store.getState().recovery).toBe('pending'))
|
||||
expect(byId('category-new-fr')).toBeNull()
|
||||
expect(screen.getByTestId('catalogue-canvas')).toBeVisible()
|
||||
})
|
||||
|
||||
it('an offer pending mid-session keeps the hidden drafts across the answer', async () => {
|
||||
const user = await mount()
|
||||
await user.click(tab('Annotations'))
|
||||
await user.click(button('Modifier les catégories'))
|
||||
await user.type(byId('category-new-fr'), 'Brouillon')
|
||||
act(() =>
|
||||
useAuthStore.setState({ catalogGrants: [grant('sheet_reviewer')] }),
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(byId('category-new-fr').closest('[hidden]')).not.toBeNull(),
|
||||
)
|
||||
seedCopy()
|
||||
act(() => useAuthStore.setState({ catalogGrants: [grant('sheet_editor')] }))
|
||||
await waitFor(() => expect(store.getState().recovery).toBe('pending'))
|
||||
expect(byId('category-new-fr').closest('[hidden]')).not.toBeNull()
|
||||
await user.click(button('Ignorer la copie'))
|
||||
await user.click(
|
||||
within(await screen.findByRole('dialog')).getByRole('button', {
|
||||
name: 'Abandonner la copie',
|
||||
}),
|
||||
)
|
||||
await waitFor(() => expect(store.getState().recovery).toBe('none'))
|
||||
expect(byId('category-new-fr')).toHaveValue('Brouillon')
|
||||
expect(byId('category-new-fr')).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the route after a submission', () => {
|
||||
it.each(['verification_failed', 'changes_requested', 'withdrawn'])(
|
||||
'a refresh that keeps the draft editable (%s) re-enables editing',
|
||||
async (status) => {
|
||||
const user = await mount()
|
||||
sb.submitSheetReview.mockResolvedValue('review-1' as never)
|
||||
await user.click(tab(/Vérification/))
|
||||
await user.type(byId('verification-note'), 'Prête')
|
||||
sb.getOfficialSheetAdmin.mockResolvedValue(
|
||||
adminAnswer({ rounds: [round(status)] }) as never,
|
||||
)
|
||||
await user.click(button('Soumettre à la revue'))
|
||||
await waitFor(() => expect(sb.submitSheetReview).toHaveBeenCalled())
|
||||
await waitFor(() => expect(store.getState().canEdit).toBe(true))
|
||||
await waitFor(() => expect(byId('verification-note')).toBeVisible())
|
||||
expect(button('Soumettre à la revue')).toBeTruthy()
|
||||
},
|
||||
)
|
||||
})
|
||||
Reference in new issue
Block a user