Files
faunosteo/apps/app/src/editor/focusRequest.ts
T

239 lines
8.3 KiB
TypeScript

import { createContext, useContext, useEffect, useRef } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed'
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 a request can name (the citations panel is none). */
export type PlaceName = EditorTabId | `annotations.${AnnotationSection}`
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<number | null>(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<HTMLElement>(selector)]
return (
found.find((element) => !element.closest('[hidden]') && accept(element)) ??
null
)
}
/** The visible row tagged with `key`. */
function rowOf(key: ElementKey): HTMLElement | null {
const wanted = JSON.stringify(key)
return visibleElement(
'[data-focus-key]',
(candidate) => candidate.dataset.focusKey === wanted,
)
}
/** Scrolls to and focuses the visible row tagged with `key`; false unless the row now holds the focus. */
export function focusRow(key: ElementKey): boolean {
const row = rowOf(key)
if (!row) return false
row.scrollIntoView?.({ block: 'center' })
row.focus()
return document.activeElement === row
}
/**
* The row is there: its focus waits for the dialogs a move closed (the page behind them
* is inert until then). False when no visible row carries `key`.
*/
export function focusRowLater(key: ElementKey): boolean {
if (!rowOf(key)) return false
landAfterModalsClosed(() => void focusRow(key))
return true
}
/** Row-based places (Général, Vues, Catégories, Régions): 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. A field of a transactional form
* (`data-draft-form`) is a local draft nothing commits: it keeps its focus. Answers
* whether a field was blurred.
*/
export function commitFocusedField(): boolean {
const active = document.activeElement
if (!isTextField(active)) return false
const field = active as HTMLElement
if (field.closest('[data-draft-form]')) return false
field.blur()
return true
}
/** The tab shown, or « Plus » while the shown tab sits in the closed list. */
function activeTabButton(): HTMLElement | null {
return (
document.querySelector<HTMLElement>('[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(options?: FocusOptions): void {
activeTabButton()?.focus(options)
}
/**
* The element sits in a transactional form of an open dialog: the form keeps its draft
* and its focus when the editor turns read-only, nothing moves it. (The citations
* sheet's tiles still edit inline until the reference dialog: they are not drafts.)
*/
function inOpenDialog(element: HTMLElement): boolean {
return element.closest('dialog[open] [data-draft-form]') !== null
}
/** 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
}
/** The disclosure button of the reference tile that holds `element`, if any. */
export function tileHeaderOf(element: HTMLElement | null): HTMLElement | null {
const tile = element?.closest('[data-reference-tile]')
return tile?.querySelector<HTMLElement>('[data-tile-header]') ?? null
}
/**
* After the render that hides parts: `held` (taken before) that left the page or sits in a
* hidden part hands its focus to `home` (the header of the tile it was in) when that is
* still shown, else 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,
home: HTMLElement | null = null,
): void {
if (!held || inOpenDialog(held)) return
const gone = !held.isConnected || held.closest('[hidden]')
if (!gone && document.activeElement !== held) held.focus()
if (!gone && document.activeElement === held) return
const homeShown = home?.isConnected && !home.closest('[hidden]')
if (homeShown) home.focus()
if (homeShown && document.activeElement === home) return
// Under a modal dialog the tab row is inert: the focus stays in the top dialog.
if (!focusTopDialog()) focusActiveTab()
}
/** The first control of the top open dialog takes the focus; false when none is open. */
function focusTopDialog(): boolean {
const top = [...document.querySelectorAll<HTMLElement>('dialog[open]')].at(-1)
const control = top?.querySelector<HTMLElement>(
'button:not([disabled]), input:not([disabled]), select, textarea, a[href]',
)
control?.focus()
return control !== undefined && document.activeElement === control
}
/**
* 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()
if (held && inOpenDialog(held)) return
commitFocusedField()
refocusIfHidden(held)
}