fix(editor): Task 1 review round 1, section back pops, scroll proof

This commit is contained in:
bchanot committed 2026-11-13 18:12:19 +01:00
1 parent 792394d3b2
commit 8e4f02620a
7 files changed
+251 -64

No files matched your search

+19 -4
View File
@@ -68,6 +68,8 @@ export function ownedEntry(
owner: HistoryOwner,
): HistoryEntry | null {
const entry = readEntry(state)
// An empty id is no owner: nobody signed in, no sheet known.
if (!owner.sheetId || !owner.userId) return null
const mine = entry?.sheetId === owner.sheetId && entry.userId === owner.userId
return mine ? entry : null
}
@@ -79,13 +81,26 @@ export function layerCount(view: EditorView): number {
return (view.finding ? 1 : 0) + (view.reference ? 1 : 0)
}
/** An Annotations section other than the drawing is a step over it, like a layer. */
function isStepOver(view: EditorView): boolean {
return view.tab === 'annotations' && view.section !== 'drawing'
}
/** True when the move took a layer away, or left a section for its drawing. */
function isRemoval(top: EditorView, view: EditorView): boolean {
if (layerCount(view) < layerCount(top)) return true
const backToDrawing = view.tab === top.tab && isStepOver(top)
return backToDrawing && !isStepOver(view) && layerCount(view) === 0
}
/** What a changed view asks of the history. */
export type HistoryWrite = 'none' | 'push' | 'replace' | 'back'
/**
* A user move to `view`. A layer taken away goes back when the entry holds the view the
* move lands on (the entry that opened the layer), else it replaces; a layer, tab or
* section added pushes, unless the move asked for a replace.
* A user move to `view`. A layer taken away, or a section left for its drawing ("Retour
* au dessin"), goes back when the entry holds the view the move lands on (the entry that
* opened it), else it replaces; a layer, tab or section added pushes, unless the move
* asked for a replace.
*/
export function planWrite(
top: HistoryEntry,
@@ -93,7 +108,7 @@ export function planWrite(
replace: boolean,
): HistoryWrite {
if (sameView(top.view, view)) return 'none'
if (layerCount(view) < layerCount(top.view)) {
if (isRemoval(top.view, view)) {
return top.below && sameView(top.below, view) ? 'back' : 'replace'
}
return replace ? 'replace' : 'push'
+80 -45
View File
@@ -34,7 +34,6 @@ interface Book {
backTimer: ReturnType<typeof setTimeout> | undefined
/** Scroll position of the entries left, by entry id. */
scrolls: Map<string, number>
lastScroll: number
counter: number
takeWrite: (now: number) => boolean
}
@@ -46,7 +45,6 @@ function newBook(): Book {
pendingBack: false,
backTimer: undefined,
scrolls: new Map(),
lastScroll: 0,
counter: 0,
takeWrite: createWriteBudget(WRITE_LIMIT, WRITE_WINDOW_MS),
}
@@ -84,6 +82,9 @@ function useWriter(book: Book, owner: HistoryOwner) {
}
const write = (entry: HistoryEntry, replace: boolean) => {
book.entry = entry
// shortcut: past the write budget a push is kept in memory only, so a later Back
// lands on the real previous entry. Fine at one push per user move; upgrade path:
// coalesce the skipped views into one replace once the window slides.
if (replace || book.takeWrite(Date.now())) send(entry, replace)
}
return {
@@ -155,22 +156,29 @@ function landOnForeign(ctx: PopContext): Landing | null {
return book.entry && { entry: book.entry, tabChanged: true }
}
/**
* Something the history does not carry is on screen: the view stays, the pre-POP view is
* pushed again above the entry landed on. A dirty form shows its own confirmation.
*/
function refusePop(ctx: PopContext, landed: HistoryEntry | null): null {
const { nav, book, writer, view } = ctx
nav.guards.askAll(false)
if (landed) book.entry = landed
writer.push(view)
return null
}
/** What the page does with the entry a Back or Forward landed on. */
function landOn(ctx: PopContext, state: unknown): Landing | null {
const { nav, book, writer, owner, view } = ctx
if (book.entry) book.scrolls.set(book.entry.id, book.lastScroll)
const { nav, book, owner, view } = ctx
// Scrolling is manual while the editor is mounted: the leaving page's offset is intact.
if (book.entry) book.scrolls.set(book.entry.id, window.scrollY)
const expected = book.pendingBack
book.pendingBack = false
clearTimeout(book.backTimer)
const entry = ownedEntry(state, owner)
if (!expected && popRefused(nav)) return refusePop(ctx, entry)
if (!entry) return landOnForeign(ctx)
if (!expected && popRefused(nav)) {
// The dirty form, if any, says so itself; the page keeps everything mounted.
nav.guards.askAll(false)
book.entry = entry
writer.push(view)
return null
}
book.entry = entry
if (sameView(entry.view, view)) return null
nav.restoreView(entry.view)
@@ -184,6 +192,13 @@ function mount(ctx: PopContext, state: unknown): void {
else ctx.writer.first(ctx.view)
}
/** Focus after a Back or Forward: the tab button, or the heading of a section reached. */
function landFocus({ entry, tabChanged }: Landing): void {
const heading = tabChanged ? null : headingOf(shownPlace(entry.view))
if (heading) heading.focus({ preventScroll: true })
else focusActiveTab({ preventScroll: true })
}
/** Scroll, focus and announcement once a Back or Forward has restored a view. */
function useLanding(
nav: EditorNavigation,
@@ -191,23 +206,64 @@ function useLanding(
landing: Landing | null,
) {
const moveText = useMoveText()
const { announce } = nav
const landed = useRef<Landing | null>(null)
useEffect(() => {
// A new wording (locale switch) re-creates `moveText`: the landing stays one.
if (!landing || landed.current === landing) return
landed.current = landing
const { entry, tabChanged } = landing
const { tab, section } = entry.view
const { id, view } = landing.entry
return afterModalsClosed(() => {
window.scrollTo(0, book.scrolls.get(entry.id) ?? 0)
const heading = tabChanged ? null : headingOf(shownPlace(entry.view))
if (heading) heading.focus({ preventScroll: true })
else focusActiveTab({ preventScroll: true })
const shown = tab === 'annotations' ? section : null
announce(moveText({ place: 'tab', tab, section: shown, key: null }))
window.scrollTo(0, book.scrolls.get(id) ?? 0)
landFocus(landing)
const section = view.tab === 'annotations' ? view.section : null
nav.announce(
moveText({ place: 'tab', tab: view.tab, section, key: null }),
)
})
}, [landing, book, announce, moveText])
}, [landing, book, nav, moveText])
}
/** The view the reducer holds, as one object that changes only when the view does. */
function useViewOf(state: EditorNavigation['state']): EditorView {
const { tab, section, finding, reference, referenceFilter } = state
return useMemo(
() => ({ tab, section, finding, reference, referenceFilter }),
[tab, section, finding, reference, referenceFilter],
)
}
/**
* The router's own restoration would scroll before the adapter has read the leaving
* page's offset: it is manual while the editor is mounted, the adapter restores itself.
*/
function useManualScroll(): void {
useEffect(() => {
const previous = window.history.scrollRestoration
window.history.scrollRestoration = 'manual'
return () => {
window.history.scrollRestoration = previous
}
}, [])
}
/** Each new location is read once: the first is the mount, a POP after it is a landing. */
function usePop(ctx: PopContext): Landing | null {
const location = useLocation()
const navType = useNavigationType()
const [landing, setLanding] = useState<Landing | null>(null)
const { book } = ctx
useEffect(() => {
// The type is part of the stamp: a POP back onto a key this adapter pushed, with the
// transition of a later push never rendered, is still a landing to read.
const stamp = `${location.key}|${navType}`
if (book.handled === stamp) return
book.handled = stamp
if (book.entry === null) mount(ctx, location.state)
else if (navType === 'POP') setLanding(landOn(ctx, location.state))
// Read once per location: the context is the one this render holds.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [location.key, navType])
return landing
}
/**
@@ -224,33 +280,12 @@ export default function useEditorHistory(
owner: HistoryOwner,
defaultView: EditorView,
): void {
const location = useLocation()
const navType = useNavigationType()
const bookRef = useRef<Book | null>(null)
const book = (bookRef.current ??= newBook())
const writer = useWriter(book, owner)
const [landing, setLanding] = useState<Landing | null>(null)
const { tab, section, finding, reference, referenceFilter } = nav.state
const view = useMemo(
() => ({ tab, section, finding, reference, referenceFilter }),
[tab, section, finding, reference, referenceFilter],
)
const ctx = { nav, book, writer, owner, defaultView, view }
useEffect(() => {
if (book.handled === location.key) return
book.handled = location.key
if (book.entry === null) mount(ctx, location.state)
else if (navType === 'POP') setLanding(landOn(ctx, location.state))
// Read once per location: the context is the one this render holds.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [location.key])
const view = useViewOf(nav.state)
const landing = usePop({ nav, book, writer, owner, defaultView, view })
useReconcile(nav, view, book, writer)
useLanding(nav, book, landing)
useEffect(() => {
const onScroll = () => {
book.lastScroll = window.scrollY
}
window.addEventListener('scroll', onScroll, { passive: true })
return () => window.removeEventListener('scroll', onScroll)
}, [book])
useManualScroll()
}
+4 -2
View File
@@ -163,10 +163,12 @@ export function useMoveText(): (target: EditorTarget) => string {
function useLiveRegion() {
const [live, setLive] = useState('')
const queued = useRef<string[]>([])
const waiting = useRef<() => void>(() => undefined)
const announce = useCallback((text: string) => {
queued.current.push(text)
if (queued.current.length > 1) return
afterModalsClosed(() => {
// Each message re-arms the wait, so a wait that never fires cannot hold later ones.
waiting.current()
waiting.current = afterModalsClosed(() => {
const joined = queued.current.splice(0).join('. ')
setLive((previous) => (previous === joined ? `${joined} ` : joined))
})