Skip to content

Commit b47beb3

Browse files
agorischekCopilot
andcommitted
Run the fit plan's lifecycle as a state machine
`fitPlanLifecycle` names what `useFitPlan` kept in refs, effect timers and deferred setState: planning, settled (locked while a lock holds the plan), held (focus moved during a press, so the replan waits for the release) and releasing (the replan after focus has finished moving, an `after` timer). The frame after a resize is an activity, and the settled marker follows the state. The measured needs stay with the hook. Its explore test checks that no replan comes while a pointer is pressed, and the lifecycle baseline drops `ui/fit-plan.ts` to none. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 8e13601 commit b47beb3

5 files changed

Lines changed: 239 additions & 66 deletions

File tree

‎docs/guides/host-core.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -370,8 +370,9 @@ transition and the bar, default `toolbarHysteresis`, 24px), a plan's identity
370370
which plans keep a control in use mounted (`lock`) and the widest bar a plan
371371
suits (`ceiling`).
372372

373-
The core owns the lifecycle: needs measured as rendered, before paint, cached
374-
until `key` changes; a ResizeObserver on the bar and on its
373+
The core owns the lifecycle, an explicit machine (`fitPlanLifecycle`, see
374+
[State machines](state-machines.md)): needs measured as rendered, before paint,
375+
cached until `key` changes; a ResizeObserver on the bar and on its
375376
`data-toolbar-region` elements, so a growing block replans; `data-fit-settled`
376377
on the bar once a plan settles, at that width in whole pixels; no replanning
377378
between a pointer's press and its click, so the pressed control isn't remounted;

‎packages/host/core/src/fit-plan.ts‎

Lines changed: 39 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
// A bar's planned layout, headless: the bar's UI owns its plans, how they are measured and its policy; this owns the
22
// measurement cache, the observation, the settled marker, the interaction lock and focus retention.
33

4-
import {useEffect, useLayoutEffect, useRef, useState} from 'react'
4+
import {useEffect, useLayoutEffect, useRef} from 'react'
5+
import {useMachine} from '@githubnext/projections-machine/react'
56
import type {RefObject} from 'react'
67
import {flushSync} from 'react-dom'
78
import {chooseFitPlan, toolbarHysteresis} from './fit-plan/choose.js'
89
import {fitWidth} from './fit-plan/fit-width.js'
910
import {useFocusRetention} from './fit-plan/focus.js'
11+
import {fitPlanLifecycle} from './fit-plan/lifecycle.js'
1012

1113
export {chooseFitPlan, toolbarHysteresis} from './fit-plan/choose.js'
1214
export type {FitChoice, FitHysteresis} from './fit-plan/choose.js'
@@ -65,17 +67,22 @@ export function useFitPlan<T>(
6567
const index = list.findIndex(item => sign(item) === sign(plan))
6668
return index < 0 ? 0 : index
6769
})
68-
const [state, setState] = useState<{plan: T; width: number; tick: number}>(() => ({plan: plans[0]!, width: 0, tick: 0}))
69-
const memo = useRef({
70-
key,
71-
needs: new Map<string, number>(),
72-
ceilings: new Map<string, number>(),
73-
settled: plans[0]!,
74-
locked: false,
75-
steps: 0,
76-
burst: '',
70+
const memo = useRef({key, needs: new Map<string, number>(), ceilings: new Map<string, number>(), steps: 0, burst: ''})
71+
const [state, send, actor] = useMachine(fitPlanLifecycle, {
72+
state: {kind: 'planning', plan: plans[0]!, settled: plans[0]!, width: 0, run: 0, hand: 'free', frame: false},
73+
activities: {
74+
// Replanning inside the observer's callback would resize observed elements mid-delivery (a ResizeObserver loop),
75+
// so it waits for the next frame, and renders synchronously there, before that frame's layout and paint.
76+
frame: (_activity, {send}) => {
77+
const handle = requestAnimationFrame(() => {
78+
const element = bar.current
79+
if (element) flushSync(() => send({type: 'frame', width: Math.round(element.getBoundingClientRect().width)}))
80+
})
81+
return () => cancelAnimationFrame(handle)
82+
},
83+
},
7784
})
78-
const index = find(plans, state.plan)
85+
const index = find(plans, state.plan as T)
7986
const plan = plans[index]!
8087
const {lock, ceiling, measure = fitWidth, hysteresis = toolbarHysteresis} = options
8188
const latest = useRef({sign, find, lock, ceiling, measure, hysteresis})
@@ -94,18 +101,16 @@ export function useFitPlan<T>(
94101
const width = element.getBoundingClientRect().width
95102
if (Math.round(width) !== state.width) {
96103
// What a plan needs may depend on the width (say, a slider's minimum): render with it before measuring.
97-
delete element.dataset.fitSettled
98-
setState(previous => ({...previous, width: Math.round(width)}))
104+
send({type: 'resized', width: Math.round(width)})
99105
return
100106
}
101107
m.needs.set(sign(plan), Math.ceil(measure(element, plan)))
102108
if (ceiling) m.ceilings.set(sign(plan), ceiling(element, plan))
103109
const lock = lockOf?.(element, plan)
104-
m.locked = Boolean(lock)
105110
const target = chooseFitPlan({
106111
plans,
107112
width,
108-
settled: find(plans, m.settled),
113+
settled: find(plans, actor.getState().settled as T),
109114
need: candidate => m.needs.get(sign(candidate)),
110115
ceiling: candidate => m.ceilings.get(sign(candidate)),
111116
hysteresis: typeof hysteresis === 'number' ? hysteresis : (from, to) => hysteresis(from, to, element),
@@ -122,41 +127,33 @@ export function useFitPlan<T>(
122127
}
123128
const known = m.needs.has(sign(plans[target]!))
124129
const switches = known ? ++m.steps : m.steps
125-
if (target !== index && (!known || switches <= 4 || (!fits(plan) && switches <= 4 + plans.length))) {
126-
delete element.dataset.fitSettled
127-
setState(previous => ({...previous, plan: plans[target]!}))
128-
} else {
129-
m.settled = plan
130-
element.dataset.fitSettled = String(Math.round(width))
131-
}
132-
}, [bar, plans, plan, index, key, state.width, state.tick])
130+
if (target !== index && (!known || switches <= 4 || (!fits(plan) && switches <= 4 + plans.length)))
131+
send({type: 'tried', plan: plans[target]!})
132+
else send({type: 'fitted', plan, locked: Boolean(lock)})
133+
}, [bar, send, actor, plans, plan, index, key, state.width, state.run])
134+
135+
// Once a plan settles, the bar says at what width, so a test can wait for it.
136+
useLayoutEffect(() => {
137+
const element = bar.current
138+
if (!element) return
139+
if (state.kind === 'planning') delete element.dataset.fitSettled
140+
else element.dataset.fitSettled = String(state.width)
141+
}, [bar, state.kind, state.width])
133142

134143
// Replan when the bar or one of its regions changes size.
135144
const observer = useRef<ResizeObserver | undefined>(undefined)
136145
useLayoutEffect(() => {
137146
const element = bar.current
138147
if (!element) return
139-
// Replanning inside the observer's callback would resize observed elements mid-delivery (a ResizeObserver loop),
140-
// so it waits for the next frame, and renders synchronously there, before that frame's layout and paint.
141-
let frame = 0
142-
const resize = new ResizeObserver(() => {
143-
if (frame) return
144-
frame = requestAnimationFrame(() => {
145-
frame = 0
146-
flushSync(() =>
147-
setState(previous => ({...previous, width: Math.round(element.getBoundingClientRect().width), tick: previous.tick + 1})),
148-
)
149-
})
150-
})
148+
const resize = new ResizeObserver(() => send({type: 'observed'}))
151149
observer.current = resize
152150
resize.observe(element)
153151
return () => {
154-
cancelAnimationFrame(frame)
155152
resize.disconnect()
156153
observer.current = undefined
157154
observed.current = new Set()
158155
}
159-
}, [bar])
156+
}, [bar, send])
160157
const observed = useRef(new Set<Element>())
161158
useLayoutEffect(() => {
162159
const resize = observer.current
@@ -168,47 +165,26 @@ export function useFitPlan<T>(
168165
observed.current = regions
169166
})
170167

171-
// Once focus leaves a control kept in use, plan again, but not between a pointer's press and its click: trying
172-
// other plans then would remount the control being clicked (WebKit moves focus away on press).
168+
// Focus moving and a pointer's press and release, for the lock (`fitPlanLifecycle`).
173169
useEffect(() => {
174170
const document = bar.current?.ownerDocument
175171
if (!document) return
176-
let timer: ReturnType<typeof setTimeout> | undefined
177-
let pressed = false
178-
let pending = false
179-
const replan = () => {
180-
clearTimeout(timer)
181-
timer = setTimeout(() => setState(previous => ({...previous, tick: previous.tick + 1})), 0)
182-
}
183-
const moved = () => {
184-
if (!memo.current.locked) return
185-
if (pressed) pending = true
186-
else replan()
187-
}
188-
const press = () => {
189-
pressed = true
190-
}
191-
const release = () => {
192-
pressed = false
193-
if (pending) {
194-
pending = false
195-
replan()
196-
}
197-
}
172+
const moved = () => send({type: 'moved'})
173+
const press = () => send({type: 'pressed'})
174+
const release = () => send({type: 'released'})
198175
document.addEventListener('focusin', moved)
199176
document.addEventListener('focusout', moved)
200177
document.addEventListener('pointerdown', press, true)
201178
document.addEventListener('pointerup', release, true)
202179
document.addEventListener('pointercancel', release, true)
203180
return () => {
204-
clearTimeout(timer)
205181
document.removeEventListener('focusin', moved)
206182
document.removeEventListener('focusout', moved)
207183
document.removeEventListener('pointerdown', press, true)
208184
document.removeEventListener('pointerup', release, true)
209185
document.removeEventListener('pointercancel', release, true)
210186
}
211-
}, [bar])
187+
}, [bar, send])
212188

213189
useFocusRetention(bar, options.focusFallbacks)
214190

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
// A planned bar's lifecycle: the plan it renders, planning it again when it resizes (on the next frame) or when focus
2+
// leaves a control a lock kept mounted (once the event's other handlers have run), and never between a pointer's press
3+
// and its click. The plans are the UI's, so a plan is opaque here; `useFitPlan` measures them in a layout effect and
4+
// sends what it finds (`resized`, `tried`, `fitted`).
5+
import {after, defineMachine, ignore} from '@githubnext/projections-machine'
6+
7+
/** Whether a pointer is pressed: the plan isn't replanned away between a press and its click. */
8+
export type FitPlanHand = 'free' | 'pressing'
9+
10+
type Planned = {
11+
/** The plan the bar renders. */
12+
readonly plan: unknown
13+
/** The plan the bar last settled on: a move to a more spacious plan is measured from it (the hysteresis). */
14+
readonly settled: unknown
15+
/** The bar's width the plan is measured at, in whole pixels. */
16+
readonly width: number
17+
/** Counts the replans asked for from outside (a frame after a resize, focus leaving a locked bar): each measures again. */
18+
readonly run: number
19+
readonly hand: FitPlanHand
20+
/** Whether a resize was observed: the bar is planned again on the next frame. */
21+
readonly frame: boolean
22+
}
23+
24+
/**
25+
* `planning` while the bar is measured as rendered and other plans are tried, `settled` once it keeps one (`locked`
26+
* while a person's use of the bar holds it), `held` when focus moved during a press while a lock held it (the replan
27+
* waits for the release) and `releasing` until focus that moved has finished moving.
28+
*/
29+
export type FitPlanState =
30+
| (Planned & {readonly kind: 'planning'})
31+
| (Planned & {readonly kind: 'settled'; readonly locked: boolean})
32+
| (Planned & {readonly kind: 'held'})
33+
| (Planned & {readonly kind: 'releasing'})
34+
35+
/** What happens to a planned bar. */
36+
export type FitPlanEvent =
37+
/** The bar isn't as wide as the plan was measured at: it renders at the new width before measuring. */
38+
| {readonly type: 'resized'; readonly width: number}
39+
/** Another plan is tried. */
40+
| {readonly type: 'tried'; readonly plan: unknown}
41+
/** The plan shown is kept; `locked` while a person's use of the bar holds it. */
42+
| {readonly type: 'fitted'; readonly plan: unknown; readonly locked: boolean}
43+
/** The bar or one of its regions resized. */
44+
| {readonly type: 'observed'}
45+
/** The frame after a resize: the bar is `width` wide. */
46+
| {readonly type: 'frame'; readonly width: number}
47+
/** Focus moved in the document. */
48+
| {readonly type: 'moved'}
49+
| {readonly type: 'pressed'}
50+
| {readonly type: 'released'}
51+
/** Focus that left a locked bar has finished moving: plan again. */
52+
| {readonly type: 'replan'}
53+
54+
/** The frame after a resize, while one waits for it. */
55+
export type FitPlanActivity = {readonly type: 'frame'; readonly key: 'frame'}
56+
57+
const planned = ({plan, settled, width, run, hand, frame}: FitPlanState): Planned => ({plan, settled, width, run, hand, frame})
58+
59+
/** What every state does alike: a new width, a plan tried, a resize and its frame, and the pointer. */
60+
const always = {
61+
resized: (state: FitPlanState, {width}: {width: number}): FitPlanState => ({...planned(state), kind: 'planning', width}),
62+
tried: (state: FitPlanState, {plan}: {plan: unknown}): FitPlanState => ({...planned(state), kind: 'planning', plan}),
63+
observed: (state: FitPlanState): FitPlanState => (state.frame ? state : {...state, frame: true}),
64+
frame: (state: FitPlanState, {width}: {width: number}): FitPlanState => ({
65+
...planned(state),
66+
kind: 'planning',
67+
width,
68+
run: state.run + 1,
69+
frame: false,
70+
}),
71+
pressed: (state: FitPlanState): FitPlanState => (state.hand === 'pressing' ? state : {...state, hand: 'pressing'}),
72+
released: (state: FitPlanState): FitPlanState => (state.hand === 'free' ? state : {...state, hand: 'free'}),
73+
} as const
74+
75+
/** While a replan waits (`held`, `releasing`), the plan shown is kept as it is measured again. */
76+
const keeping = (state: FitPlanState, {plan}: {plan: unknown}): FitPlanState =>
77+
state.plan === plan && state.settled === plan ? state : {...state, plan, settled: plan}
78+
79+
const frames = (state: FitPlanState): FitPlanActivity[] => (state.frame ? [{type: 'frame', key: 'frame'}] : [])
80+
81+
export const fitPlanLifecycle = defineMachine<FitPlanState, FitPlanEvent, never, FitPlanActivity>()({
82+
states: {
83+
planning: {
84+
on: {
85+
...always,
86+
fitted: (state, {plan, locked}) => ({...planned(state), kind: 'settled', plan, settled: plan, locked}),
87+
// The planning under way reads the lock afresh.
88+
moved: ignore,
89+
replan: ignore,
90+
},
91+
activities: frames,
92+
},
93+
settled: {
94+
on: {
95+
...always,
96+
fitted: (state, {plan, locked}) =>
97+
state.plan === plan && state.settled === plan && state.locked === locked ? state : {...state, plan, settled: plan, locked},
98+
// Focus that moves while a lock holds the plan may have left the control in use: plan again, but not between a
99+
// press and its click, since another plan would remount the control being clicked (WebKit moves focus on press).
100+
moved: state =>
101+
!state.locked ? state : state.hand === 'pressing' ? {...planned(state), kind: 'held'} : {...planned(state), kind: 'releasing'},
102+
replan: ignore,
103+
},
104+
activities: frames,
105+
},
106+
held: {
107+
on: {
108+
...always,
109+
fitted: keeping,
110+
moved: ignore,
111+
pressed: ignore,
112+
released: state => ({...planned(state), kind: 'releasing', hand: 'free'}),
113+
replan: ignore,
114+
},
115+
activities: frames,
116+
},
117+
releasing: {
118+
on: {
119+
...always,
120+
fitted: keeping,
121+
moved: ignore,
122+
released: ignore,
123+
pressed: state => ({...planned(state), kind: 'held', hand: 'pressing'}),
124+
replan: state => ({...planned(state), kind: 'planning', run: state.run + 1}),
125+
},
126+
activities: state => [...frames(state), after('replan', 0, {type: 'replan'})],
127+
},
128+
},
129+
})

‎packages/host/core/test/fit-plan.test.mjs‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import {test} from 'node:test'
22
import assert from 'node:assert/strict'
3+
import {explore} from '@githubnext/projections-machine/testing'
34
import {chooseFitPlan, toolbarHysteresis} from '../dist/index.js'
5+
import {fitPlanLifecycle} from '../dist/fit-plan/lifecycle.js'
46

57
const plans = ['full', 'compact', 'minimal']
68
const needs = {full: 600, compact: 450, minimal: 300}
@@ -80,3 +82,69 @@ test('a growing label replans: its plan stops fitting and a narrower one is trie
8082
bar.width = 524
8183
assert.equal(settle(), 'full')
8284
})
85+
86+
/** Sends events in order to the bar's lifecycle. */
87+
function run(state, ...events) {
88+
for (const event of events) state = fitPlanLifecycle.transition(state, event).state
89+
return state
90+
}
91+
const fresh = {kind: 'planning', plan: 'wide', settled: 'wide', width: 0, run: 0, hand: 'free', frame: false}
92+
93+
test('a press is not replanned away before its click: focus that moves during it replans once it is released', () => {
94+
const locked = run(fresh, {type: 'resized', width: 800}, {type: 'fitted', plan: 'narrow', locked: true})
95+
assert.equal(locked.kind, 'settled')
96+
// As WebKit does, the press moves focus out of the bar: the replan waits for the release.
97+
const held = run(locked, {type: 'pressed'}, {type: 'moved'})
98+
assert.equal(held.kind, 'held')
99+
assert.equal(fitPlanLifecycle.activities(held).length, 0)
100+
const released = run(held, {type: 'released'})
101+
assert.equal(released.kind, 'releasing')
102+
assert.deepEqual(fitPlanLifecycle.activities(released), [{type: 'machine.after', key: 'replan', ms: 0, event: {type: 'replan'}}])
103+
// Released, it measures again (a new run) with the plan it kept.
104+
assert.deepEqual(run(released, {type: 'replan'}), {...released, kind: 'planning', run: locked.run + 1})
105+
// Without a lock, focus moving plans nothing.
106+
const free = run(fresh, {type: 'fitted', plan: 'wide', locked: false})
107+
assert.equal(run(free, {type: 'moved'}), free)
108+
})
109+
110+
test('a resize waits for the next frame, and the bar is measured again at its width there', () => {
111+
const settled = run(fresh, {type: 'resized', width: 800}, {type: 'fitted', plan: 'wide', locked: false})
112+
const observed = run(settled, {type: 'observed'})
113+
assert.deepEqual(fitPlanLifecycle.activities(observed), [{type: 'frame', key: 'frame'}])
114+
assert.equal(run(observed, {type: 'observed'}), observed)
115+
const {locked: _, ...planned} = settled
116+
assert.deepEqual(run(observed, {type: 'frame', width: 400}), {...planned, kind: 'planning', width: 400, run: 1, frame: false})
117+
})
118+
119+
test("every state of the bar's lifecycle", () => {
120+
explore(fitPlanLifecycle, {
121+
from: fresh,
122+
events: [
123+
{type: 'resized', width: 400},
124+
{type: 'tried', plan: 'narrow'},
125+
{type: 'fitted', plan: 'wide', locked: true},
126+
{type: 'fitted', plan: 'narrow', locked: false},
127+
{type: 'observed'},
128+
{type: 'frame', width: 800},
129+
{type: 'moved'},
130+
{type: 'pressed'},
131+
{type: 'released'},
132+
],
133+
// The runs count up without bound: a state is the same with any count.
134+
key: state => JSON.stringify({...state, run: undefined}),
135+
depth: 8,
136+
invariants: {
137+
'a replan waits while a pointer is pressed': state => state.kind !== 'releasing' || state.hand === 'free',
138+
'a held replan waits for a press': state => state.kind !== 'held' || state.hand === 'pressing',
139+
'a frame is asked for only after a resize': state =>
140+
fitPlanLifecycle.activities(state).some(activity => activity.type === 'frame') === state.frame,
141+
},
142+
transitions: {
143+
'a plan changes only by planning': ({from, to}) => from.plan === to.plan || to.kind === 'planning' || to.plan === to.settled,
144+
'a press never starts a replan': ({event, to, from}) =>
145+
event.type !== 'pressed' || to.kind !== 'planning' || from.kind === 'planning',
146+
'measuring again counts a run': ({event, from, to}) => !['frame', 'replan'].includes(event.type) || to.run === from.run + 1,
147+
},
148+
complete: true,
149+
})
150+
})

0 commit comments

Comments
 (0)