fix(editor): repair dialog limits, pending drafts block apply, dialog wording

This commit is contained in:
bchanot committed 2026-11-04 20:17:51 +01:00
1 parent 3776a33b79
commit 9c21fd3f86
8 files changed
+197 -52

No files matched your search

@@ -522,3 +522,9 @@ Shown when a drawing attached to a view that was unmeasured would put the geomet
| `editor.views.repair.path_blocked` | Ce tracé n'a pas de coordonnées à corriger ici. Remplacez-le par un polygone pour pouvoir attacher l'illustration. | This path has no coordinates to correct here. Replace it with a polygon to be able to attach the drawing. | New: a path cannot be edited numerically; the existing « Remplacer par un polygone » converts it inside the form |
| `editor.views.repair.refused` | Rien n'a été appliqué : le contrôle du document refuse ces valeurs. | Nothing was applied: the document check refuses these values. | New: the core refused the end state; the core's messages follow per annotation |
| `editor.views.repair.apply` / `cancel` | Attacher et appliquer / Annuler | Attach and apply / Cancel | New: dialog buttons (« Attacher et appliquer » is the owner's wording) |
### Lot N3 fix round 1
| Key | FR | EN | Why |
|---|---|---|---|
| `editor.views.repair.more_outside` | D'autres éléments sortiraient aussi du nouveau cadre : {names}. Rien n'a été appliqué. Annulez, corrigez-les, puis choisissez de nouveau l'illustration. | Other elements would also fall outside the new frame: {names}. Nothing was applied. Cancel, fix them, then choose the drawing again. | New: `newly_invalid` inside the dialog (the old wording sent to a locked tab) |
| `editor.views.repair.not_measurable` | Avec cette illustration, une vue qui porte des annotations ne serait pas mesurable. Rien n'a été appliqué. | With this drawing, a view holding annotations would not be measurable. Nothing was applied. | New: `view_unmeasured` / `changed_unmeasured` inside the dialog |
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Button from '@/components/ui/Button'
import Input from '@/components/ui/Input'
@@ -26,6 +26,8 @@ export interface GeometryGroupProps {
onApply: (geometry: EditableGeometry) => ApplyResult
/** Fields shown as text: read-only mode or an unmeasured view. */
locked: boolean
/** Told whenever typed values differ from `geometry` (shown « non appliqué »). */
onPending?: (pending: boolean) => void
}
type Fields = GroupFields
@@ -62,6 +64,13 @@ function useGroupState(geometry: EditableGeometry) {
*/
export default function GeometryGroup(props: GeometryGroupProps) {
const { state, set } = useGroupState(props.geometry)
const pending = changedFieldNames(state.draft, props.geometry).size > 0
const report = useRef(props.onPending)
report.current = props.onPending
useEffect(() => {
report.current?.(pending)
return () => report.current?.(false)
}, [pending])
const propose = (next: Fields) => {
if (sameAsStored(next, props.geometry))
return set({ draft: next, messages: [] })
@@ -85,7 +94,7 @@ export default function GeometryGroup(props: GeometryGroupProps) {
)
}
interface BodyProps extends Omit<GeometryGroupProps, 'onApply'> {
interface BodyProps extends Omit<GeometryGroupProps, 'onApply' | 'onPending'> {
draft: Fields
pending: Set<string>
messages: string[]
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useCallback, useState } from 'react'
import type { Annotation, Geometry } from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
@@ -48,10 +48,8 @@ export default function RepairDialog({ offer, ...actions }: RepairDialogProps) {
)
}
/** The temporary state of the form: proposals, typed edits and the last refusal. */
function useRepairState(offer: RepairOffer, onApplied: () => void) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
/** The listed annotations and their temporary geometries (proposals, then typed edits). */
function useRepairGeometries(offer: RepairOffer) {
const doc = useSheetDocument()
const [annotations] = useState(() =>
doc ? listedAnnotations(offer, doc) : [],
@@ -59,15 +57,50 @@ function useRepairState(offer: RepairOffer, onApplied: () => void) {
const [geometries, setGeometries] = useState(() =>
initialGeometries(offer, annotations),
)
const change = (id: string, geometry: Geometry) =>
setGeometries((current) => ({ ...current, [id]: geometry }))
return { annotations, geometries, change }
}
/** « Attacher et appliquer »: one batch, the refusal kept for the rows. */
function useRepairApply(
offer: RepairOffer,
geometries: Record<string, Geometry>,
onApplied: () => void,
) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [result, setResult] = useState<RepairResult | null>(null)
const apply = () => {
const applied = applyRepair(offer, geometries, { t, locale })
if (applied.ok) onApplied()
else setResult(applied)
}
const change = (id: string, geometry: Geometry) =>
setGeometries((current) => ({ ...current, [id]: geometry }))
return { annotations, geometries, result, apply, change }
return { result, apply }
}
/** The annotations whose geometry group holds typed values not yet in the form. */
function usePendingIds() {
const [ids, setIds] = useState<ReadonlySet<string>>(new Set())
const report = useCallback((id: string, pending: boolean) => {
setIds((current) => {
if (current.has(id) === pending) return current
const next = new Set(current)
if (pending) next.add(id)
else next.delete(id)
return next
})
}, [])
return { pending: ids, report }
}
function useRepairState(offer: RepairOffer, onApplied: () => void) {
const geometry = useRepairGeometries(offer)
const applied = useRepairApply(offer, geometry.geometries, onApplied)
const pending = usePendingIds()
const blocked =
blockedIds(geometry.geometries).length > 0 || pending.pending.size > 0
return { ...geometry, ...applied, report: pending.report, blocked }
}
function RepairForm({
@@ -89,6 +122,7 @@ function RepairForm({
offer={offer}
messages={refused?.byAnnotation[annotation.id]}
onChange={(geometry) => state.change(annotation.id, geometry)}
onPending={state.report}
/>
))}
</ul>
@@ -97,11 +131,7 @@ function RepairForm({
<Button type="button" variant="ghost" onClick={onCancel}>
{t('editor.views.repair.cancel')}
</Button>
<Button
type="button"
disabled={blockedIds(state.geometries).length > 0}
onClick={state.apply}
>
<Button type="button" disabled={state.blocked} onClick={state.apply}>
{t('editor.views.repair.apply')}
</Button>
</div>
@@ -128,6 +158,7 @@ interface RowProps {
offer: RepairOffer
messages: string[] | undefined
onChange: (geometry: Geometry) => void
onPending: (id: string, pending: boolean) => void
}
function RepairRow({
@@ -136,6 +167,7 @@ function RepairRow({
offer,
messages,
onChange,
onPending,
}: RowProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
@@ -149,12 +181,13 @@ function RepairRow({
data-testid={`repair-${annotation.id}`}
className="space-y-2 rounded-lg border border-[var(--color-border)] p-3"
>
<h4 className="text-sm font-semibold">{title}</h4>
<h3 className="text-sm font-semibold">{title}</h3>
{geometry && isEditable(geometry) ? (
<GeometryGroup
idPrefix={`repair-${annotation.id}`}
geometry={geometry}
locked={false}
onPending={(pending) => onPending(annotation.id, pending)}
onApply={(next) => {
onChange(next)
return { ok: true }
@@ -26,7 +26,7 @@ export default function SignOutLossDialog({
<Button type="button" variant="ghost" onClick={onCancel}>
{t('shell.sign_out_loss_cancel')}
</Button>
<Button type="button" onClick={onConfirm}>
<Button type="button" variant="danger" onClick={onConfirm}>
{t('shell.sign_out_loss_confirm')}
</Button>
</div>
+77 -35
View File
@@ -6,7 +6,7 @@ import type {
PreviewState,
SheetView,
} from '@faunosteo/core-wasm/types'
import type { Acceptance } from '@/catalogue/preview'
import type { Acceptance, CataloguePreview } from '@/catalogue/preview'
import { buildView } from '@/components/catalogue/CatalogueCanvas'
import {
describeOutcome,
@@ -25,6 +25,7 @@ import {
unmeasuredViews,
type GeometryRefusal,
} from './issues'
import { elementLabel } from './sheetDocument'
import { useEditorStore } from './state/editorStore'
import type { CommitOutcome } from './state/editorTypes'
@@ -108,9 +109,11 @@ export function blockedIds(geometries: Record<string, Geometry>): string[] {
.map(([id]) => id)
}
/** The frame of `viewId` as the CANDIDATE document composes it (read inside `accept`). */
function candidateFrame(viewId: string): Frame | null {
const preview = useEditorStore.getState().preview
/** The frame of `viewId` as the CANDIDATE document composes it: `preview` must hold it. */
function candidateFrame(
preview: CataloguePreview | null,
viewId: string,
): Frame | null {
const built = preview ? buildView(preview, viewId) : null
return built?.ok ? parseFrame(built.svg.getAttribute('viewBox')) : null
}
@@ -119,6 +122,7 @@ function framesOfListed(
before: PreviewState,
after: PreviewState,
ids: readonly string[],
preview: CataloguePreview | null,
): Record<string, Frame> | null {
const viewIds = after.document.annotations
.filter((annotation) => ids.includes(annotation.id))
@@ -126,7 +130,9 @@ function framesOfListed(
const unmeasured = unmeasuredViews(before)
const frames: Record<string, Frame> = {}
for (const viewId of new Set(viewIds)) {
const frame = unmeasured.has(viewId) ? candidateFrame(viewId) : null
const frame = unmeasured.has(viewId)
? candidateFrame(preview, viewId)
: null
if (!frame) return null
frames[viewId] = frame
}
@@ -147,7 +153,9 @@ export function markRepairable(
return verdict
}
const { refusal } = verdict
const frames = framesOfListed(before, after, refusal.annotationIds)
// Inside `accept` the store's preview handle holds the candidate document (not yet kept).
const { preview } = useEditorStore.getState()
const frames = framesOfListed(before, after, refusal.annotationIds, preview)
return frames
? { accepted: false, refusal: { ...refusal, repairFrames: frames } }
: verdict
@@ -176,9 +184,9 @@ function updateAnnotation(
}
/**
* The geometries first, the view last: the core then turns the redrawn view's annotations
* `to_confirm` itself, after the page's copies of them were written. Only the end text is
* judged, so the order of the intermediate texts is free.
* The geometries first, the view last. The order is free: the core's `update_annotation`
* keeps the current status and sets `to_confirm` on any change, so both orders end in the
* same text, and only that end text is judged.
*/
export function repairCommands(
view: SheetView,
@@ -220,22 +228,45 @@ function blockedResult(context: CommitContext): RepairResult {
return { ok: false, general, byAnnotation: {} }
}
function refusedResult(
const UNMEASURED: ReadonlySet<string> = new Set([
'view_unmeasured',
'changed_unmeasured',
])
function namesOf(ids: readonly string[], { locale }: CommitContext): string {
const doc = useEditorStore.getState().previewState?.document
const label = (id: string) =>
doc ? elementLabel(doc, { kind: 'annotation', id }, locale) : id
return [...new Set(ids)].map(label).join(', ')
}
/** Words that fit the dialog: none of them sends the user to a tab behind it. */
function dialogMessage(
outcome: Exclude<CommitOutcome<GeometryRefusal>, { ok: true }>,
context: CommitContext,
): string | null {
const refusal = outcome.reason === 'refused' ? outcome.refusal : null
if (refusal?.reason === 'newly_invalid') {
return context
.t('editor.views.repair.more_outside')
.replace('{names}', namesOf(refusal.annotationIds, context))
}
if (refusal && UNMEASURED.has(refusal.reason)) {
return context.t('editor.views.repair.not_measurable')
}
return describeOutcome(outcome, context).messages[0] ?? null
}
export function refusedResult(
outcome: Exclude<CommitOutcome<GeometryRefusal>, { ok: true }>,
context: CommitContext,
): RepairResult {
if (
outcome.reason === 'refused' &&
outcome.refusal.reason === 'changed_invalid'
) {
return {
ok: false,
general: null,
byAnnotation: issueMessages(outcome.refusal),
}
const refusal = outcome.reason === 'refused' ? outcome.refusal : null
if (refusal?.reason === 'changed_invalid') {
return { ok: false, general: null, byAnnotation: issueMessages(refusal) }
}
const [general] = describeOutcome(outcome, context).messages
return { ok: false, general: general ?? null, byAnnotation: {} }
const general = dialogMessage(outcome, context)
return { ok: false, general, byAnnotation: {} }
}
/** The end-state verdict: a refused drawing first, then the geometry of the repaired ids. */
@@ -245,6 +276,26 @@ function repairAccept(before: PreviewState, assetId: string, ids: string[]) {
rejectedDrawingFault(after, assetId) ?? geometry(after)
}
/** The commands and the repaired ids, or null when the view is gone. */
function repairBatch(
offer: RepairOffer,
before: PreviewState,
geometries: Record<string, Geometry>,
) {
const view = before.document.views.find((v) => v.id === offer.viewId)
if (!view) return null
const repairs = listedAnnotations(offer, before.document).map(
(annotation) => ({
annotation,
geometry: geometries[annotation.id] ?? (annotation.geometry as Geometry),
}),
)
return {
commands: repairCommands(view, offer.assetId, repairs),
ids: repairs.map((r) => r.annotation.id),
}
}
/**
* ONE batch: the listed annotations take the typed geometries and the view takes the
* drawing, judged by the core on the end state (`geometryAccept` on the repaired ids).
@@ -257,19 +308,10 @@ export function applyRepair(
): RepairResult {
const store = useEditorStore.getState()
const before = store.previewState
const view = before?.document.views.find((v) => v.id === offer.viewId)
if (!before || !view || store.session !== offer.session) {
return blockedResult(context)
}
const repairs = listedAnnotations(offer, before.document).map(
(annotation) => ({
annotation,
geometry: geometries[annotation.id] ?? (annotation.geometry as Geometry),
}),
)
const ids = repairs.map((r) => r.annotation.id)
const accept = repairAccept(before, offer.assetId, ids)
const commands = repairCommands(view, offer.assetId, repairs)
const outcome = store.commitBatch(commands, { accept })
const live = before !== null && store.session === offer.session
const batch = live ? repairBatch(offer, before, geometries) : null
if (!before || !batch) return blockedResult(context)
const accept = repairAccept(before, offer.assetId, batch.ids)
const outcome = store.commitBatch(batch.commands, { accept })
return outcome.ok ? { ok: true } : refusedResult(outcome, context)
}
+2
View File
@@ -1396,6 +1396,8 @@ export const en: Dict = {
'editor.views.repair.row': '{kind} "{name}"',
'editor.views.repair.path_blocked': 'This path has no coordinates to correct here. Replace it with a polygon to be able to attach the drawing.',
'editor.views.repair.refused': 'Nothing was applied: the document check refuses these values.',
'editor.views.repair.more_outside': 'Other elements would also fall outside the new frame: {names}. Nothing was applied. Cancel, fix them, then choose the drawing again.',
'editor.views.repair.not_measurable': 'With this drawing, a view holding annotations would not be measurable. Nothing was applied.',
'editor.views.repair.apply': 'Attach and apply',
'editor.views.repair.cancel': 'Cancel',
'editor.upload.working': 'Checking and sending the drawing…',
+2
View File
@@ -1427,6 +1427,8 @@ export const fr: Dict = {
'editor.views.repair.row': '{kind} « {name} »',
'editor.views.repair.path_blocked': "Ce tracé n'a pas de coordonnées à corriger ici. Remplacez-le par un polygone pour pouvoir attacher l'illustration.",
'editor.views.repair.refused': "Rien n'a été appliqué : le contrôle du document refuse ces valeurs.",
'editor.views.repair.more_outside': "D'autres éléments sortiraient aussi du nouveau cadre : {names}. Rien n'a été appliqué. Annulez, corrigez-les, puis choisissez de nouveau l'illustration.",
'editor.views.repair.not_measurable': "Avec cette illustration, une vue qui porte des annotations ne serait pas mesurable. Rien n'a été appliqué.",
'editor.views.repair.apply': 'Attacher et appliquer',
'editor.views.repair.cancel': 'Annuler',
'editor.upload.working': "Vérification et envoi de l'illustration…",
@@ -391,3 +391,54 @@ describe('the repair dialog', () => {
expect(annotation('anno-p').geometry).toMatchObject({ type: 'polygon' })
})
})
describe('the repair dialog (fix round 1)', () => {
it('disables « Attacher et appliquer » while a group holds an unapplied draft', async () => {
const { user, dialog } = await pickAndOpenDialog()
const apply = within(dialog).getByRole('button', {
name: t('editor.views.repair.apply'),
})
expect(apply).toBeEnabled()
const cx = within(
within(dialog).getByTestId('repair-anno-a'),
).getByLabelText('Centre x')
await user.clear(cx)
await user.keyboard('{Enter}')
expect(apply).toBeDisabled()
await user.type(cx, '60{Enter}')
expect(apply).toBeEnabled()
})
it('headings sit under the dialog title as h3', async () => {
const { dialog } = await pickAndOpenDialog()
expect(within(dialog).getAllByRole('heading', { level: 3 }).length).toBe(2)
})
it('words a refusal for the dialog, never the locked Annotations tab', async () => {
await openReady({ text: unmeasuredText() })
await holdNewDrawing()
const step = attachToView('view-main', NEW_ASSET)
if (step.ok || step.error.code !== 'repair') throw new Error('no offer')
const { offer } = step.error
const context = { t, locale: 'fr' as const }
const refused = (reason: string) => ({
ok: false as const,
reason: 'refused' as const,
refusal: { ...offer.refusal, reason: reason as never },
})
const { refusedResult } = await import('@/editor/repair')
const words = [
'newly_invalid',
'view_unmeasured',
'changed_unmeasured',
].map((reason) => {
const result = refusedResult(refused(reason), context)
return result.ok ? '' : (result.general ?? '')
})
for (const word of words) {
expect(word).not.toBe('')
expect(word).not.toMatch(/onglet|Annotations|Vues/)
}
expect(words[0]).toMatch(/anno-a|N/)
})
})