import { createContext, useContext, useEffect, useRef } from 'react' import type { ElementKey } from '@faunosteo/core-wasm/types' import type { AnnotationSection, EditorTarget, FocusRequest, } from './navigation' import { MORE_BUTTON_ID, type EditorTabId } from './tabs' export type { FocusRequest } /** * What a place did with a request: `found` the element and focused it, `kept` a creation * or tracing in progress instead of jumping, `none` when it holds no such element. */ export type FocusOutcome = 'found' | 'kept' | 'none' /** * The `data-place` name of a place. `citations` (the panel) is no navigation target: it * is a name only for its heading and its focus scope. */ export type PlaceName = | EditorTabId | `annotations.${AnnotationSection}` | 'citations' export function placeOf(target: EditorTarget): PlaceName { if (target.tab !== 'annotations') return target.tab return `annotations.${target.section ?? 'drawing'}` } /** The request, only when `place` is the one its target names (a hidden place never answers). */ export function ownedBy( focus: FocusRequest | undefined, place: PlaceName, ): FocusRequest | undefined { return focus && placeOf(focus.target) === place ? focus : undefined } /** The attributes that make a row of a list reachable by a focus request. */ export function focusAttrs(key: ElementKey) { return { 'data-focus-key': JSON.stringify(key), tabIndex: -1, } as const } /** The ring a programmatically focused row shows. */ export const FOCUS_CLASS = 'focus:outline focus:outline-2 focus:outline-[var(--color-accent)]' /** The workspace's answer to a handled request: it clears it, so a remount never replays. */ export const FocusConsumedContext = createContext< (serial: number, outcome: FocusOutcome) => void >(() => undefined) /** Says something to the polite live region of the workspace. */ export const AnnounceContext = createContext<(text: string) => void>( () => undefined, ) /** * Runs `apply` once per request, after the place has rendered, then reports the outcome. * The workspace passes a request only to the place its target names. */ export function useFocusRequest( focus: FocusRequest | undefined, apply: (target: EditorTarget) => FocusOutcome, ): void { const handled = useRef(null) const consumed = useContext(FocusConsumedContext) useEffect(() => { if (!focus || handled.current === focus.serial) return handled.current = focus.serial consumed(focus.serial, apply(focus.target)) }, [focus, apply, consumed]) } /** The first element matching `selector` (and `accept`) that no hidden place contains. */ export function visibleElement( selector: string, accept: (element: HTMLElement) => boolean = () => true, ): HTMLElement | null { const found = [...document.querySelectorAll(selector)] return ( found.find((element) => !element.closest('[hidden]') && accept(element)) ?? null ) } /** Scrolls to and focuses the visible row tagged with `key`; false when there is none. */ export function focusRow(key: ElementKey): boolean { const wanted = JSON.stringify(key) const row = [ ...document.querySelectorAll('[data-focus-key]'), ].find( (candidate) => candidate.dataset.focusKey === wanted && !candidate.closest('[hidden]'), ) if (!row) return false row.scrollIntoView?.({ block: 'center' }) row.focus() return true } /** Row-based places (Général, Vues, Catégories, Régions, Références): focus the named row. */ export function useRowFocus(focus: FocusRequest | undefined): void { useFocusRequest(focus, (target) => target.key && focusRow(target.key) ? 'found' : 'none', ) } /** Input types that take no typed text: Escape there is not the field's. */ const NON_TEXT_INPUTS = new Set([ 'checkbox', 'radio', 'range', 'button', 'submit', 'reset', 'color', 'file', 'image', ]) /** A field that takes typed text (or a choice): Escape there belongs to the field. */ export function isTextField(target: EventTarget | null): boolean { if (target instanceof HTMLInputElement) return !NON_TEXT_INPUTS.has(target.type) return ( target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement || (target instanceof HTMLElement && target.closest('[contenteditable="true"]') !== null) ) } /** * Commits the text being typed before a place is left: blurs the focused field, so its * `TextField` commits on blur. Safari and iPadOS do not move the focus to a tapped button, * so the blur is forced rather than assumed. Answers whether a field was blurred. */ export function commitFocusedField(): boolean { const active = document.activeElement const isField = isTextField(active) if (isField) (active as HTMLElement).blur() return isField } /** The tab shown, or « Plus » while the shown tab sits in the closed list. */ function activeTabButton(): HTMLElement | null { return ( document.querySelector('[role="tab"][aria-selected="true"]') ?? document.getElementById(MORE_BUTTON_ID) ) } /** Gives the focus to the shown tab's button: a lost focus must not leave on `body`. */ export function focusActiveTab(): void { activeTabButton()?.focus() } /** The element holding the focus, when it is something other than `body`. */ export function heldElement(): HTMLElement | null { const active = document.activeElement return active instanceof HTMLElement && active !== document.body ? active : null } /** * After the render that hides parts: `held` (taken before) that left the page or sits in a * hidden part hands its focus to the shown tab; one still shown gets its focus back when * the commit blurred it (never `body`), and the tab takes it if the element refuses. */ export function refocusIfHidden(held: HTMLElement | null): void { if (!held) return const gone = !held.isConnected || held.closest('[hidden]') if (!gone && document.activeElement !== held) held.focus() if (gone || document.activeElement !== held) focusActiveTab() } /** * The editor turned read-only: commits the text being typed, then whatever held the focus * in a now hidden part gives it to the shown tab, never to `body`. */ export function releaseEditFocus(): void { const held = heldElement() commitFocusedField() refocusIfHidden(held) }