Files
faunosteo/apps/app/src/editor/history/useLeaveConfirm.ts
T

152 lines
5.2 KiB
TypeScript

import { useCallback, useEffect, useRef } from 'react'
import { useLocation } from 'react-router-dom'
import { topDirtyLayer } from '../leftDraft'
import type {
EditorNavigation,
Guards,
LayerExit,
LayerName,
} from '../useEditorNavigation'
/** The part of a Navigation API `navigate` event this guard reads (not in the DOM types). */
interface NavigateEventLike extends Event {
readonly navigationType: string
readonly destination: {
readonly url: string
readonly key: string
readonly sameDocument: boolean
}
}
interface NavigationLike extends EventTarget {
traverseTo: (key: string) => {
committed: Promise<unknown>
finished: Promise<unknown>
}
}
/** The Navigation API where the browser offers it (Chromium), else null. */
function navigationApi(): NavigationLike | null {
const api = (window as { navigation?: NavigationLike }).navigation
return api && typeof api.traverseTo === 'function' ? api : null
}
/** A jump through this document's history to a page other than the editor. */
function leavesEditor(event: NavigateEventLike, path: string): boolean {
const { navigationType, destination } = event
if (navigationType !== 'traverse' || !destination?.sameDocument) return false
return new URL(destination.url).pathname !== path
}
interface Watch {
guards: Guards
/**
* Closes the citations sheet and a reference dialog over it: they lie over the finding
* dialog, so its question would be hidden under them.
*/
clearAbove: () => void
path: string
/** The key of the jump the user confirmed: it passes, and leaves no flag. */
passing: { current: string | null }
}
interface Jump {
api: NavigationLike
key: string
watch: Watch
}
/**
* The last « Abandonner »: the same jump, let through this time. A jump that fails closes
* the question and keeps the draft (`keep`).
*/
function jumpTo({ api, key, watch }: Jump, keep: () => void): void {
watch.passing.current = key
const failed = () => {
watch.passing.current = null
keep()
}
const { committed, finished } = api.traverseTo(key)
committed.catch(() => undefined)
finished.catch(failed)
}
/**
* `layer` asks « Abandonner les modifications ? » and holds the jump. Its « Abandonner »
* closes it, with the citations sheet it may have been opened from (so the next question
* is not hidden under the sheet), and the next dirty layer under it asks in turn; the
* last one lets the jump go. Any « Continuer la saisie » drops the jump. The finding
* dialog asks once the layers over it are closed (they are clean: it is the top dirty one).
*/
function askLeave(jump: Jump, layer: LayerName): void {
const { guards, clearAbove } = jump.watch
if (layer === 'finding') clearAbove()
guards.ask(layer, false)
guards.holdLeave({
layer,
go: (exit: LayerExit) => {
const next = topDirtyLayer(guards, layer)
if (!next) return jumpTo(jump, exit.keep)
// One commit closes both: the history writes one replace, never a Back racing it.
exit.close()
askLeave(jump, next)
},
})
}
/**
* A jump out of the editor while a dialog holds changes is cancelled when the browser
* lets the page cancel it; the dirty dialogs ask, top down, before it goes.
*/
function onNavigate(api: NavigationLike, event: NavigateEventLike, w: Watch) {
if (!leavesEditor(event, w.path)) return
const { key } = event.destination
if (w.passing.current === key || !event.cancelable) return
const layer = topDirtyLayer(w.guards)
if (!layer) return
event.preventDefault()
askLeave({ api, key, watch: w }, layer)
}
type LeaveNav = Pick<
EditorNavigation,
'guards' | 'state' | 'closeCitations' | 'references'
>
/** Closes the sheet and the reference dialog of the navigation `latest` holds, if open. */
function clearerOf(latest: { current: LeaveNav }): () => void {
return () => {
const { state, closeCitations, references } = latest.current
const { finding } = state
if (finding && 'key' in finding && finding.citations) closeCitations()
if (state.reference) references.close(true)
}
}
/**
* Confirmation before a history jump of several entries leaves the editor with a dirty
* dialog (criterion 23): where the Navigation API can cancel it, the jump waits for each
* dirty dialog's own question; elsewhere (no API, a jump the browser will not let the page
* cancel) the left-draft notice says it afterwards. Traversals inside the editor keep the
* history adapter's refusal path. Returns whether the user confirmed a leave.
*/
export default function useLeaveConfirm(nav: LeaveNav): () => boolean {
const { pathname } = useLocation()
const passing = useRef<string | null>(null)
const path = useRef(pathname).current
const latest = useRef(nav)
latest.current = nav
const { guards } = nav
useEffect(() => {
const api = navigationApi()
if (!api) return
const clearAbove = clearerOf(latest)
const watch: Watch = { guards, clearAbove, path, passing }
const listener = (event: Event) =>
onNavigate(api, event as NavigateEventLike, watch)
api.addEventListener('navigate', listener)
return () => api.removeEventListener('navigate', listener)
}, [guards, path])
return useCallback(() => passing.current !== null, [])
}