Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions docs/design/proposals/headless-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,17 @@ them:
readiness. #122's events depend on every shown pane, so they stay derived
from `rendererStatus` and `paint` until the store composes the panes (step
4), where they become its effects, with the same names.
3. **Playback in the store.** `playbackLifecycle` is driven by `createActor`
inside the store, and `usePlaybackControl` goes.
3. **Playback without React.** `createPlaybackController`
(`projection/playback-controller.ts`) drives `playbackLifecycle` with
`createActor`: the frame loop runs on an injectable scheduler
(`requestAnimationFrame` by default), the position and playing requests go to
a host, and `show` sends the `*Shown` events from what the view shows. Like
the actor, it does nothing until `start()`. `usePlaybackControl` keeps only
React's part: it creates the controller once, starts it in a layout effect
and calls `show` after every render. The store composes the controller in
step 5, with the settings store as its host. Node tests cover playing,
pausing, seeking, a new subject and a declined play with a hand-stepped
scheduler.
4. **Selectors and selection.** Rows, scope, summary, payloads and selection
move into the store; the remaining per-concern hooks go.
5. **The adapter.** `createProjection` is exported, `useProjection` becomes
Expand Down
114 changes: 52 additions & 62 deletions packages/host/core/src/projection/playback-control.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
import {useCallback, useEffect, useLayoutEffect, useMemo, useRef} from 'react'
import {useMachine} from '@githubnext/projections-machine/react'
import {useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react'
import {endpointHoldMs, holdDuration, stepHoldMs} from '../playback.js'
import type {ComparisonMode} from '../modes.js'
import {unit} from './controllable.js'
import type {Controllable} from './controllable.js'
import {nextDirection, playbackLifecycle} from './playback-lifecycle.js'
import {createPlaybackController} from './playback-controller.js'
import {nextDirection} from './playback-lifecycle.js'
import type {PlaybackRun} from './playback-lifecycle.js'
import type {PlaybackPosition} from './playback-position.js'

/** The plan and reduced motion of the latest render, for an action called after it. */
const now = (current: {current: {plan: PlaybackRun; reducedMotion: boolean}}) => ({
plan: current.current.plan,
reducedMotion: current.current.reducedMotion,
})

export type PlaybackControlInput = Pick<Controllable, 'latest' | 'setInternal' | 'request'> &
Pick<PlaybackPosition, 'position' | 'progress' | 'stepEnds' | 'durationMs' | 'timeline' | 'toProgress' | 'toPosition'> & {
playing: boolean
Expand All @@ -28,7 +22,7 @@ export type PlaybackControlInput = Pick<Controllable, 'latest' | 'setInternal' |
}

/**
* Seeking, playing and pausing, and the frame loop, run by `playbackLifecycle`. The view's values (playing, the
* Seeking, playing and pausing, and the frame loop, run by `playbackLifecycle` through `createPlaybackController`. The view's values (playing, the
* position, the mode, reduced motion, the subject) reach the lifecycle as events when they change; its requests for
* playing and the position go to the core or the embedder, whichever controls them.
*/
Expand All @@ -43,50 +37,51 @@ export function usePlaybackControl(input: PlaybackControlInput) {
timeline,
speed: input.speed,
}
const current = useRef({plan, reducedMotion, toProgress})
current.current = {plan, reducedMotion, toProgress}
const [state, send, actor] = useMachine(playbackLifecycle, {
state: {kind: 'paused', position, direction: input.direction ?? 1, travelled: false, armed: null, stopping: false},
effects: {
requestPlaying: ({playing: next}) => request('playing', next),
// A slider position: `onPositionChange`, and `onProgressChange` when the embedder controls progress.
requestPosition: ({position: next}) => {
const clamped = unit(next)
const options = latest.current
if (options.position === undefined)
setInternal(previous => (previous.position === clamped ? previous : {...previous, position: clamped}))
options.onPositionChange?.(clamped)
if (options.progress !== undefined) options.onProgressChange?.(current.current.toProgress(clamped))
},
},
activities: {
frames: (_activity, {send: tick, signal}) => {
let last: number | undefined
let handle = requestAnimationFrame(function frame(time) {
if (last !== undefined) tick({type: 'tick', elapsedMs: time - last, plan: current.current.plan})
if (signal.aborted) return
last = time
handle = requestAnimationFrame(frame)
})
return () => cancelAnimationFrame(handle)
const current = useRef({plan, reducedMotion, toProgress, request})
current.current = {plan, reducedMotion, toProgress, request}
const [controller] = useState(() =>
createPlaybackController(
{position, direction: input.direction},
{
plan: () => current.current.plan,
reducedMotion: () => current.current.reducedMotion,
requestPlaying: next => current.current.request('playing', next),
// A slider position: `onPositionChange`, and `onProgressChange` when the embedder controls progress.
requestPosition: next => {
const clamped = unit(next)
const options = latest.current
if (options.position === undefined)
setInternal(previous => (previous.position === clamped ? previous : {...previous, position: clamped}))
options.onPositionChange?.(clamped)
if (options.progress !== undefined) options.onProgressChange?.(current.current.toProgress(clamped))
},
},
},
})
),
)
const {actor} = controller
const [state, setState] = useState(actor.getState)
// Started before paint, so the frame loop and a state an event changes there render before paint too.
useLayoutEffect(() => {
const unsubscribe = actor.subscribe(setState)
actor.start()
setState(actor.getState())
return () => {
unsubscribe()
actor.stop()
}
}, [actor])

// After every render, the lifecycle is reconciled with what the view shows: the subject, the mode and reduced motion
// when they change; the position, a controlled direction and whether it plays when they differ from the lifecycle's,
// so a request an embedder declined (or hasn't applied yet) never leaves the two apart.
const shown = useRef({reducedMotion, mode, subject})
// After every render, the lifecycle is reconciled with what the view shows.
useLayoutEffect(() => {
const last = shown.current
shown.current = {reducedMotion, mode, subject}
if (last.subject !== subject) send({type: 'subjectChanged', position, stops: latest.current.playing === undefined})
if (actor.getState().position !== position) send({type: 'positionShown', position})
if (input.direction !== undefined && actor.getState().direction !== input.direction)
send({type: 'directionShown', direction: input.direction})
if (last.mode !== mode) send({type: 'modeChanged'})
if (last.reducedMotion !== reducedMotion) send({type: 'motionShown', reduced: reducedMotion})
send({type: 'playingShown', playing, plan: current.current.plan, reducedMotion})
controller.show({
subject,
mode,
reducedMotion,
position,
playing,
direction: input.direction,
playingControlled: latest.current.playing !== undefined,
})
})

// Uncontrolled progress reports every change, including resets.
Expand All @@ -105,22 +100,17 @@ export function usePlaybackControl(input: PlaybackControlInput) {
setInternal(previous => ({...previous, position: toPosition(before.progress)}))
}, [timeline, progress, toPosition, toProgress, latest, setInternal, still, position])

const seek = useCallback((to: number) => send({type: 'seek', to}), [send])
const play = useCallback((direction: 1 | -1 = 1) => send({type: 'play', direction, ...now(current)}), [send])
const pause = useCallback(() => send({type: 'pause'}), [send])
const toggle = useCallback((direction: 1 | -1 = 1) => send({type: 'toggle', direction, ...now(current)}), [send])
const togglePlayback = useCallback(() => send({type: 'togglePlayback', ...now(current)}), [send])
const direction = input.direction ?? state.direction
return useMemo(
() => ({
direction,
nextDirection: nextDirection({...state, direction}, reducedMotion),
seek,
play,
pause,
toggle,
togglePlayback,
seek: controller.seek,
play: controller.play,
pause: controller.pause,
toggle: controller.toggle,
togglePlayback: controller.togglePlayback,
}),
[state, direction, reducedMotion, seek, play, pause, toggle, togglePlayback],
[state, direction, reducedMotion, controller],
)
}
114 changes: 114 additions & 0 deletions packages/host/core/src/projection/playback-controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Playback without a framework: `playbackLifecycle` run by an actor, with the runners it needs (the position and playing
// requests, and a frame loop) and the reconciliation that turns what the view shows into events. `usePlaybackControl`
// runs it in a component; the projection store will run it directly.
import {createActor} from '@githubnext/projections-machine'
import type {Actor} from '@githubnext/projections-machine'
import type {ComparisonMode} from '../modes.js'
import {playbackLifecycle} from './playback-lifecycle.js'
import type {PlaybackEvent, PlaybackLifecycle, PlaybackRun} from './playback-lifecycle.js'

/** What playback reads of the host each time it acts, and the requests it makes of it. */
export interface PlaybackHost {
/** The plan playback runs now: stops, speed, holds, loop. */
plan(): PlaybackRun
reducedMotion(): boolean
/** Playback asks to play or pause: the core's setting, or the embedder's. */
requestPlaying(playing: boolean): void
/** Playback asks to move the slider. */
requestPosition(position: number): void
}

/** Schedules animation frames: `requestAnimationFrame` by default, a fake one in a test. */
export interface FrameScheduler {
request(callback: (time: number) => void): unknown
cancel(handle: unknown): void
}

const animationFrames: FrameScheduler = {
request: callback => requestAnimationFrame(callback),
cancel: handle => cancelAnimationFrame(handle as number),
}

/** What the view shows of playback after a render, which the lifecycle is reconciled with. */
export interface PlaybackView {
/** The subject shown: a new one starts over. */
subject: unknown
mode: ComparisonMode
reducedMotion: boolean
position: number
playing: boolean
/** The direction, when the embedder controls it. */
direction: 1 | -1 | undefined
/** Whether the embedder controls playing: then a new subject doesn't stop playback. */
playingControlled: boolean
}

/** Playback's actions and its reconciliation, around one actor. */
export interface PlaybackController {
readonly actor: Actor<PlaybackLifecycle, PlaybackEvent>
/**
* Reconciles the lifecycle with what the view shows now; call it after each render, before paint. The subject, the
* mode and reduced motion are sent when they change; the position, a controlled direction and whether it plays when
* they differ from the lifecycle's, so a request an embedder declined (or hasn't applied yet) never leaves the two apart.
*/
show(view: PlaybackView): void
seek(to: number): void
play(direction?: 1 | -1): void
pause(): void
toggle(direction?: 1 | -1): void
togglePlayback(): void
}

/**
* A playback controller over `playbackLifecycle`, starting paused at `position`. Nothing runs until its actor starts:
* construction has no side effects, and `actor.start()` and `actor.stop()` may alternate (as in React's development
* remount).
*/
export function createPlaybackController(
start: {position: number; direction?: 1 | -1 | undefined},
host: PlaybackHost,
frames: FrameScheduler = animationFrames,
): PlaybackController {
const actor = createActor(playbackLifecycle, {
state: {kind: 'paused', position: start.position, direction: start.direction ?? 1, travelled: false, armed: null, stopping: false},
effects: {
requestPlaying: ({playing}) => host.requestPlaying(playing),
requestPosition: ({position}) => host.requestPosition(position),
},
activities: {
frames: (_activity, {send, signal}) => {
let last: number | undefined
let handle = frames.request(function frame(time) {
if (last !== undefined) send({type: 'tick', elapsedMs: time - last, plan: host.plan()})
if (signal.aborted) return
last = time
handle = frames.request(frame)
})
return () => frames.cancel(handle)
},
},
})
const now = () => ({plan: host.plan(), reducedMotion: host.reducedMotion()})
let shown: PlaybackView | undefined
return {
actor,
show(view) {
const last = shown
// A copy, so a host that updates one view object and shows it again still has its changes noticed.
shown = {...view}
if (last && last.subject !== view.subject)
actor.send({type: 'subjectChanged', position: view.position, stops: !view.playingControlled})
if (actor.getState().position !== view.position) actor.send({type: 'positionShown', position: view.position})
if (view.direction !== undefined && actor.getState().direction !== view.direction)
actor.send({type: 'directionShown', direction: view.direction})
if (last && last.mode !== view.mode) actor.send({type: 'modeChanged'})
if (last && last.reducedMotion !== view.reducedMotion) actor.send({type: 'motionShown', reduced: view.reducedMotion})
actor.send({type: 'playingShown', playing: view.playing, plan: host.plan(), reducedMotion: view.reducedMotion})
},
seek: to => actor.send({type: 'seek', to}),
play: (direction = 1) => actor.send({type: 'play', direction, ...now()}),
pause: () => actor.send({type: 'pause'}),
toggle: (direction = 1) => actor.send({type: 'toggle', direction, ...now()}),
togglePlayback: () => actor.send({type: 'togglePlayback', ...now()}),
}
}
Loading
Loading