import type { Point } from '@faunosteo/core-wasm/types' import type { NewKind, PendingElement } from './creation' export type ToolId = 'select' | 'point' | 'zone' | 'link' /** A tracing in progress: a new zone or link, or a polygon replacing a geometry. */ export interface Tracing { target: NewKind | 'replace' /** The annotation whose geometry the tracing replaces (target `replace`). */ annotationId: string | null points: Point[] } export interface UiState { viewId: string | null tool: ToolId selectedId: string | null pending: PendingElement | null /** Bumped by every new pending element: keys the creation form's own state. */ serial: number tracing: Tracing | null hint: string | null /** The overview's « Filtrer par nom » term: it outlives a selection, not a view. */ filter: string } export type UiAction = | { type: 'view'; viewId: string } | { type: 'tool'; tool: ToolId } | { type: 'select'; id: string | null } | { type: 'pending_new'; pending: PendingElement } | { type: 'pending_update'; pending: PendingElement } | { type: 'pending_drop' } | { type: 'trace_start'; target: Tracing['target']; annotationId?: string } | { type: 'trace_add'; point: Point } | { type: 'trace_pop' } | { type: 'trace_cancel' } | { type: 'hint'; hint: string | null } | { type: 'filter'; term: string } export const initialUi: UiState = { viewId: null, tool: 'select', selectedId: null, pending: null, serial: 0, tracing: null, hint: null, filter: '', } const TOOL_OF: Record = { point: 'point', zone: 'zone', detail_trigger: 'link', replace: 'zone', } export function uiReducer(state: UiState, action: UiAction): UiState { switch (action.type) { case 'view': return { ...initialUi, viewId: action.viewId } case 'tool': return { ...state, tool: action.tool, tracing: null, hint: null } case 'select': return { ...state, selectedId: action.id, pending: null, tracing: null, hint: null, } case 'pending_new': return { ...state, pending: action.pending, // A second click with the same kind keeps the typed fields (same panel). serial: state.pending?.kind === action.pending.kind ? state.serial : state.serial + 1, selectedId: null, tracing: null, hint: null, } case 'pending_update': return state.pending ? { ...state, pending: action.pending } : state case 'pending_drop': return { ...state, pending: null, hint: null } case 'trace_start': return { ...state, tool: TOOL_OF[action.target], pending: null, hint: null, tracing: { target: action.target, annotationId: action.annotationId ?? null, points: [], }, } case 'trace_add': return state.tracing ? { ...state, tracing: { ...state.tracing, points: [...state.tracing.points, action.point], }, } : state case 'trace_pop': return state.tracing ? { ...state, tracing: { ...state.tracing, points: state.tracing.points.slice(0, -1), }, } : state case 'trace_cancel': return { ...state, tracing: null, hint: null } case 'hint': return { ...state, hint: action.hint } case 'filter': return { ...state, filter: action.term } } }