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
17 changes: 11 additions & 6 deletions docs/design/proposals/headless-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,19 +94,24 @@ them:

## Steps, as pull requests

1. **The store skeleton.** `createProjection` runs the settings reducer and
`subscribe`, and `useProjection` keeps its implementation and reads the
store's settings. Node tests cover controlled and uncontrolled settings
without React.
1. **The settings reducer.** The controllable settings' rules (initial values,
reading, requesting, restarting on a new subject) become framework-free
functions in `projection/settings-store.ts`, with `createSettingsStore` to
run them with `subscribe`. `useControllable` runs the same functions in
component state, so React's timing is unchanged (a new subject still resets
settings during render). Node tests cover controlled and uncontrolled
settings without React. Nothing new is exported yet: the public
`createProjection` arrives in step 5, once its snapshot is the whole
controller, so its API doesn't churn.
2. **Panes as a machine.** The pane-status machine, with #122's events as its
effects and `paint` as a selector. The Inspector's snapshot page uses it for
its readiness.
3. **Playback in the store.** `playbackLifecycle` is driven by `createActor`
inside the store, and `usePlaybackControl` goes.
4. **Selectors and selection.** Rows, scope, summary, payloads and selection
move into the store; the remaining per-concern hooks go.
5. **The adapter.** `useProjection` becomes `useSyncExternalStore` over the
store, and `controllerRef` hosts can `subscribe`.
5. **The adapter.** `createProjection` is exported, `useProjection` becomes
`useSyncExternalStore` over it, and `controllerRef` hosts can `subscribe`.
6. **`mountStage` and a vanilla host.** The stage without React, a Storybook
story of a plain-DOM host as its conformance check, and `ProjectionStage` on
top of it.
Expand Down
76 changes: 13 additions & 63 deletions packages/host/core/src/projection/controllable.ts
Original file line number Diff line number Diff line change
@@ -1,82 +1,32 @@
import {useCallback, useRef, useState} from 'react'
import type {ControlValue} from '@githubnext/projections-renderer-sdk/protocol'
import type {ComparisonMode} from '../modes.js'
import {endpointHoldMs, stepHoldMs, timelinePosition} from '../playback.js'
import type {Holds, PlaybackTimeline} from '../playback.js'
import type {SummaryFilter} from '../summary.js'
import type {Highlighting, ProjectionOptions} from './types.js'
import {defaultDuration} from './timing.js'
import {initialSettings, notifySetting, requestedSettings, settingValue} from './settings-store.js'
import type {SettingKey, Settings} from './settings-store.js'
import type {ProjectionOptions} from './types.js'

export const speedRange = (speed: number) => (Number.isFinite(speed) ? Math.min(10, Math.max(0.1, speed)) : 1)
export {positionOn, speedRange, unit} from './settings-store.js'

export const unit = (value: number) => Math.max(0, Math.min(1, value))

export const positionOn = (progress: number, timeline: PlaybackTimeline | undefined) =>
timeline ? timelinePosition(progress, timeline) : unit(progress)

/** The timeline before the renderer reports its steps: endpoint holds only. */
function initialTimeline(options: ProjectionOptions): PlaybackTimeline | undefined {
if (options.holds === 'pause' || (options.holds === undefined && options.initialHolds === 'pause')) return undefined
const steps = options.subject.mode === 'comparison' ? options.subject.comparison.steps.length : 0
return {
stops: [],
travelMs: Math.max(100, options.durationMs ?? options.presentation?.durationMs ?? defaultDuration(steps)),
stepHoldMs,
endpointHoldMs,
}
}

/** The core's own values, seeded from the `initial…` options, for everything the embedder doesn't control. */
function initialInternal(options: ProjectionOptions) {
const {presentation} = options
return {
// Before the renderer reports its steps, the timeline has only the endpoint holds.
position:
options.subject.mode === 'comparison'
? unit(options.initialPosition ?? positionOn(options.initialProgress ?? 1, initialTimeline(options)))
: 1,
playing: options.initialPlaying ?? false,
loop: options.initialLoop ?? true,
holds: options.initialHolds ?? ('timeline' as Holds),
speed: speedRange(options.initialSpeed ?? 1),
mode: options.initialMode ?? (presentation?.mode as ComparisonMode | undefined),
swipePosition: unit(options.initialSwipePosition ?? 0.5),
highlighting: options.initialHighlighting ?? presentation?.highlighting ?? ('animated' as Highlighting),
// A comparison opens on its changes and their context unless the definition opts out.
changesOnly: options.initialChangesOnly ?? presentation?.changesOnly ?? true,
variedOnly: options.initialVariedOnly ?? false,
regeneratedOnly: options.initialRegeneratedOnly ?? false,
summaryFilter: options.initialSummaryFilter ?? (null as SummaryFilter | null),
connector: options.initialConnector ?? false,
search: options.initialSearch ?? '',
selectedId: options.initialSelectedId ?? (null as string | null),
rendererName: options.initialRendererName ?? options.renderers?.[0]?.name ?? '',
controlValues: {} as {[id: string]: ControlValue},
}
}

export type Internal = ReturnType<typeof initialInternal>
export type Internal = Settings

/** Reads a value: the embedder's when it controls it, else the core's own. */
export type ValueOf = <K extends keyof Internal & keyof ProjectionOptions>(key: K) => Internal[K]
export type ValueOf = <K extends SettingKey>(key: K) => Internal[K]

/** Requests a change: updates internal state when uncontrolled, and always notifies. */
export type RequestChange = <K extends keyof Internal>(key: K, next: Internal[K]) => void

/**
* Every value the embedder may control (pass it with its `on…Change` handler) or leave to the core (optionally seeded
* with `initial…`), and `latest`, the options of the latest render for callbacks that outlive it.
* with `initial…`), and `latest`, the options of the latest render for callbacks that outlive it. The rules are the
* framework-free settings reducer's (`settings-store.ts`); this runs them in a component's state.
*/
export function useControllable(options: ProjectionOptions) {
const latest = useRef(options)
latest.current = options
const [internal, setInternal] = useState(() => initialInternal(options))
const value: ValueOf = key => (options[key] !== undefined ? options[key] : internal[key]) as Internal[typeof key]
const [internal, setInternal] = useState(() => initialSettings(options))
const value: ValueOf = key => settingValue(internal, options, key)
const request = useCallback<RequestChange>((key, next) => {
const current = latest.current as Record<string, unknown>
if (current[key] === undefined) setInternal(previous => (previous[key] === next ? previous : {...previous, [key]: next}))
const handler = current[`on${key[0]!.toUpperCase()}${key.slice(1)}Change`]
if (typeof handler === 'function') (handler as (value: unknown) => void)(next)
const current = latest.current
setInternal(previous => requestedSettings(previous, current, key, next))
notifySetting(current, key, next)
}, [])
return {latest, internal, setInternal, value, request}
}
Expand Down
146 changes: 146 additions & 0 deletions packages/host/core/src/projection/settings-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// The settings an embedder may control, outside React: their initial values, how a value is read and how a change is
// requested. `useControllable` runs it in a component; `createSettingsStore` runs it anywhere.
import type {ControlValue} from '@githubnext/projections-renderer-sdk/protocol'
import type {ComparisonMode} from '../modes.js'
import {endpointHoldMs, stepHoldMs, timelinePosition} from '../playback.js'
import type {Holds, PlaybackTimeline} from '../playback.js'
import type {SummaryFilter} from '../summary.js'
import type {Highlighting, ProjectionOptions} from './types.js'
import {defaultDuration} from './timing.js'

export const speedRange = (speed: number) => (Number.isFinite(speed) ? Math.min(10, Math.max(0.1, speed)) : 1)

export const unit = (value: number) => Math.max(0, Math.min(1, value))

export const positionOn = (progress: number, timeline: PlaybackTimeline | undefined) =>
timeline ? timelinePosition(progress, timeline) : unit(progress)

/** The timeline before the renderer reports its steps: endpoint holds only. */
function initialTimeline(options: ProjectionOptions): PlaybackTimeline | undefined {
if (options.holds === 'pause' || (options.holds === undefined && options.initialHolds === 'pause')) return undefined
const steps = options.subject.mode === 'comparison' ? options.subject.comparison.steps.length : 0
return {
stops: [],
travelMs: Math.max(100, options.durationMs ?? options.presentation?.durationMs ?? defaultDuration(steps)),
stepHoldMs,
endpointHoldMs,
}
}

/** The core's own values, seeded from the `initial…` options, for everything the embedder doesn't control. */
export function initialSettings(options: ProjectionOptions) {
const {presentation} = options
return {
// Before the renderer reports its steps, the timeline has only the endpoint holds.
position:
options.subject.mode === 'comparison'
? unit(options.initialPosition ?? positionOn(options.initialProgress ?? 1, initialTimeline(options)))
: 1,
playing: options.initialPlaying ?? false,
loop: options.initialLoop ?? true,
holds: options.initialHolds ?? ('timeline' as Holds),
speed: speedRange(options.initialSpeed ?? 1),
mode: options.initialMode ?? (presentation?.mode as ComparisonMode | undefined),
swipePosition: unit(options.initialSwipePosition ?? 0.5),
highlighting: options.initialHighlighting ?? presentation?.highlighting ?? ('animated' as Highlighting),
// A comparison opens on its changes and their context unless the definition opts out.
changesOnly: options.initialChangesOnly ?? presentation?.changesOnly ?? true,
variedOnly: options.initialVariedOnly ?? false,
regeneratedOnly: options.initialRegeneratedOnly ?? false,
summaryFilter: options.initialSummaryFilter ?? (null as SummaryFilter | null),
connector: options.initialConnector ?? false,
search: options.initialSearch ?? '',
selectedId: options.initialSelectedId ?? (null as string | null),
rendererName: options.initialRendererName ?? options.renderers?.[0]?.name ?? '',
controlValues: {} as {[id: string]: ControlValue},
}
}

/** The core's own values of the settings (`initialSettings`), for those the embedder doesn't control. */
export type Settings = ReturnType<typeof initialSettings>

/** A setting the embedder may control: a value of the options and of the core's own settings. */
export type SettingKey = keyof Settings & keyof ProjectionOptions

/** A setting's value: the embedder's when it controls it, else the core's own. */
export const settingValue = <K extends SettingKey>(settings: Settings, options: ProjectionOptions, key: K): Settings[K] =>
(options[key] !== undefined ? options[key] : settings[key]) as Settings[K]

/**
* The core's settings after a requested change: changed only while the embedder doesn't control the setting (and the
* same object when nothing changes), so a refused change to a controlled one isn't kept for later.
*/
export function requestedSettings<K extends keyof Settings>(
settings: Settings,
options: ProjectionOptions,
key: K,
next: Settings[K],
): Settings {
if ((options as Record<string, unknown>)[key] !== undefined || settings[key] === next) return settings
return {...settings, [key]: next}
}

/** Tells the embedder about a requested change, through the setting's `on…Change`, whether or not it controls it. */
export function notifySetting<K extends keyof Settings>(options: ProjectionOptions, key: K, next: Settings[K]) {
const handler = (options as Record<string, unknown>)[`on${key[0]!.toUpperCase()}${key.slice(1)}Change`]
if (typeof handler === 'function') (handler as (value: unknown) => void)(next)
}

/**
* The core's settings when a new subject replaces the shown one: the slider back where the options start it
* (`toPosition` maps an initial progress through the current timeline), playback stopped and nothing selected.
*/
export function restartedSettings(settings: Settings, options: ProjectionOptions, toPosition: (progress: number) => number): Settings {
return {
...settings,
position: options.subject.mode === 'comparison' ? unit(options.initialPosition ?? toPosition(options.initialProgress ?? 1)) : 1,
playing: false,
selectedId: options.initialSelectedId ?? null,
}
}

/** The settings of one projection, run without a framework: read them, request changes and hear about them. */
export interface SettingsStore {
/** The core's own values; a new object whenever one changes. */
getSnapshot(): Settings
/** Calls `listener` after each change; returns the function that stops it. */
subscribe(listener: () => void): () => void
/** The embedder's latest options: controlled values, their handlers and the subject. */
update(options: ProjectionOptions): void
/** A setting's value: the embedder's when it controls it, else the core's own. */
value<K extends SettingKey>(key: K): Settings[K]
/** Requests a change: kept while the setting is uncontrolled, and always reported to its `on…Change`. */
request<K extends keyof Settings>(key: K, next: Settings[K]): void
/** Changes the core's own values directly, as the core does when it restarts or records what a renderer declares. */
set(change: (settings: Settings) => Settings): void
}

/** A `SettingsStore` for a projection's options, seeded from their `initial…` values. */
export function createSettingsStore(initial: ProjectionOptions): SettingsStore {
let options = initial
let settings = initialSettings(initial)
const listeners = new Set<() => void>()
const set = (change: (settings: Settings) => Settings) => {
const next = change(settings)
if (next === settings) return
settings = next
for (const listener of [...listeners]) listener()
}
return {
getSnapshot: () => settings,
subscribe(listener) {
listeners.add(listener)
return () => listeners.delete(listener)
},
update(next) {
options = next
},
value: key => settingValue(settings, options, key),
request(key, next) {
const current = options
set(previous => requestedSettings(previous, current, key, next))
notifySetting(current, key, next)
},
set,
}
}
8 changes: 2 additions & 6 deletions packages/host/core/src/projection/use-projection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {placeAnnotations} from '../targets/annotations.js'
import {summaryFigures} from '../summary.js'
import type {PaneKey, ProjectionController, ProjectionOptions} from './types.js'
import {speedRange, unit, useControllable} from './controllable.js'
import {restartedSettings} from './settings-store.js'
import {useHostEnvironment} from './environment.js'
import {filterActions, filterState, useRowFilter} from './filtering.js'
import {usePlaybackControl} from './playback-control.js'
Expand Down Expand Up @@ -105,12 +106,7 @@ export function useProjection(options: ProjectionOptions): ProjectionController
const [shownSubject, setShownSubject] = useState(subject)
if (shownSubject !== subject) {
setShownSubject(subject)
setInternal(previous => ({
...previous,
position: subject.mode === 'comparison' ? unit(options.initialPosition ?? toPosition(options.initialProgress ?? 1)) : 1,
playing: false,
selectedId: options.initialSelectedId ?? null,
}))
setInternal(previous => restartedSettings(previous, options, toPosition))
setHoveredId(null)
setAnchors({before: {}, after: {}})
selection.setPinned(null)
Expand Down
66 changes: 66 additions & 0 deletions packages/host/core/test/settings-store.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import {test} from 'node:test'
import assert from 'node:assert/strict'
import {createSettingsStore, initialSettings, restartedSettings} from '../dist/projection/settings-store.js'

const extraction = {mode: 'extraction', extraction: {entities: [], relationships: []}}
const comparison = steps => ({mode: 'comparison', comparison: {steps: Array.from({length: steps}, () => ({}))}})
const options = overrides => ({subject: extraction, projection: {id: 'p', title: 'P'}, ...overrides})

test('settings start from the initial options, then the definition, then the shared defaults', () => {
const plain = initialSettings(options())
assert.equal(plain.changesOnly, true)
assert.equal(plain.highlighting, 'animated')
assert.equal(plain.loop, true)
assert.equal(plain.position, 1)
const seeded = initialSettings(options({presentation: {changesOnly: false, highlighting: 'on', mode: 'diff'}, initialLoop: false}))
assert.equal(seeded.changesOnly, false)
assert.equal(seeded.highlighting, 'on')
assert.equal(seeded.mode, 'diff')
assert.equal(seeded.loop, false)
assert.equal(initialSettings(options({initialSpeed: 40})).speed, 10)
assert.equal(initialSettings(options({subject: comparison(2), initialProgress: 0})).position, 0)
})

test('an uncontrolled setting keeps a requested change, notifies, and tells subscribers once', () => {
const heard = []
const store = createSettingsStore(options({onSearchChange: value => heard.push(value)}))
let changes = 0
const stop = store.subscribe(() => changes++)
store.request('search', 'pay')
assert.equal(store.value('search'), 'pay')
assert.deepEqual(heard, ['pay'])
assert.equal(changes, 1)
store.request('search', 'pay')
assert.equal(changes, 1, 'the same value is no change')
assert.deepEqual(heard, ['pay', 'pay'], 'the embedder still hears every request')
stop()
store.request('search', '')
assert.equal(changes, 1)
})

test('a controlled setting reads the embedder’s value and only requests a change, which a refusal discards', () => {
const heard = []
const store = createSettingsStore(options({loop: true, onLoopChange: value => heard.push(value)}))
const before = store.getSnapshot()
store.request('loop', false)
assert.equal(store.value('loop'), true)
assert.deepEqual(heard, [false])
assert.equal(store.getSnapshot(), before, 'nothing changes while controlled')
// The embedder stops controlling it without accepting the change: the refused value doesn't surface.
store.update(options({onLoopChange: value => heard.push(value)}))
assert.equal(store.value('loop'), true)
})

test('a new subject restarts playback, the slider and the selection, and keeps the rest', () => {
const store = createSettingsStore(options({subject: comparison(2)}))
store.request('playing', true)
store.request('selectedId', 'a')
store.request('search', 'pay')
const next = options({subject: comparison(3), initialProgress: 0})
store.update(next)
store.set(settings => restartedSettings(settings, next, progress => progress))
assert.equal(store.value('playing'), false)
assert.equal(store.value('selectedId'), null)
assert.equal(store.value('position'), 0)
assert.equal(store.value('search'), 'pay')
})
Loading