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:
bchanot committed 2026-11-06 21:22:10 +01:00
1 parent 9d89daed19
commit c57af6441f
23 files changed
+883 -108

No files matched your search

@@ -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
+66
View File
@@ -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),
}
}
+10
View File
@@ -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()
}
+16 -2
View File
@@ -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)