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
11 changes: 8 additions & 3 deletions docs/design/proposals/headless-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,14 @@ them:
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.
2. **Panes as a machine.** `paneLifecycle` (`pane-lifecycle.ts`): loading until
the frame is revealed, then ready; failed for good until a new bundle loads;
each state keeps what the renderer reported. `RendererPane` runs it with
`useMachine`, and `PaneState` is unchanged. `paint` stays a selector over the
shown panes, and the Inspector's snapshot page uses it (`paintState`) for its
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.
4. **Selectors and selection.** Rows, scope, summary, payloads and selection
Expand Down
165 changes: 165 additions & 0 deletions packages/host/core/src/pane-lifecycle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
// A renderer pane's lifecycle as an explicit machine: loading until its frame is revealed, then ready; failed for good
// when the host stops its renderer, until a new bundle loads. Each state keeps what the renderer has reported so far.
import {defineMachine, ignore} from '@githubnext/projections-machine'
import type {
InitPayload,
RendererCapabilities,
RendererControl,
RendererLegend,
SummaryItem,
} from '@githubnext/projections-renderer-sdk/protocol'
import type {PaneState} from './pane.js'

/** What a pane knows of its renderer, in every state. */
export type PaneReports = Omit<PaneState, 'status' | 'message'>

/** The pane's state: its frame's stage, and what its renderer reported. */
export type PaneLifecycleState =
| {readonly kind: 'loading'; readonly reports: PaneReports}
| {readonly kind: 'ready'; readonly reports: PaneReports}
/** The host stopped the renderer (it timed out, navigated or flooded the host): final until a new bundle loads. */
| {readonly kind: 'failed'; readonly reports: PaneReports; readonly message: string}

/** What a pane hears: its frame's reports, and the host giving it a new document or a new bundle. */
export type PaneLifecycleEvent =
| {readonly type: 'ready'; readonly capabilities: RendererCapabilities}
| {readonly type: 'revealed'}
| {readonly type: 'failed'; readonly message: string}
/** The renderer acknowledged painting `progress` of the document `init`. */
| {readonly type: 'rendered'; readonly progress: number; readonly init: InitPayload}
| {readonly type: 'controls'; readonly controls: RendererControl[]}
| {readonly type: 'steps'; readonly ends: number[]; readonly slots?: number | undefined}
| {readonly type: 'aspect'; readonly ratio: number}
| {readonly type: 'height'; readonly px: number}
| ({readonly type: 'legend'} & RendererLegend)
| {readonly type: 'summary'; readonly items: SummaryItem[]}
| {readonly type: 'error'; readonly message: string}
| {readonly type: 'rejected'}
/** The host sent the frame a new document: what was painted and stepped belongs to the old one. */
| {readonly type: 'reinit'}
/** The pane loads another bundle, starting over. */
| {readonly type: 'reloaded'}

export const noReports: PaneReports = {steps: [], rendererErrors: [], rejected: 0, controls: []}

/** The state a pane starts in, and returns to when it loads another bundle. */
export const loadingLifecycle: PaneLifecycleState = {kind: 'loading', reports: noReports}

type Reporting = Exclude<PaneLifecycleState, {kind: 'failed'}>

/** Whether two reported values are equal: the renderer's reports arrive as new copies of plain data. */
function same(a: unknown, b: unknown): boolean {
if (Object.is(a, b)) return true
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null || Array.isArray(a) !== Array.isArray(b)) return false
const keys = Object.keys(a)
if (keys.length !== Object.keys(b).length) return false
return keys.every(key => Object.hasOwn(b, key) && same((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]))
}

/**
* The same state with its reports changed, or the state itself when they don't. The painted init is compared by
* identity: which document a pane painted, not what it contains.
*/
function reporting<S extends PaneLifecycleState>(state: S, reports: PaneReports): S {
const before = state.reports
const keys = Object.keys(reports) as (keyof PaneReports)[]
const unchanged =
keys.length === Object.keys(before).length &&
keys.every(
key => Object.hasOwn(before, key) && (key === 'renderedInit' ? before[key] === reports[key] : same(before[key], reports[key])),
)
return unchanged ? state : {...state, reports}
}

/** How a running renderer's reports change what the pane knows, in loading and ready alike. */
const reports = {
ready: (state: Reporting, event: {capabilities: RendererCapabilities}) =>
reporting(state, {...state.reports, capabilities: event.capabilities, controls: event.capabilities.controls ?? []}),
rendered: (state: Reporting, event: {progress: number; init: InitPayload}) =>
reporting(state, {...state.reports, rendered: event.progress, renderedInit: event.init}),
controls: (state: Reporting, event: {controls: RendererControl[]}) => reporting(state, {...state.reports, controls: event.controls}),
steps: (state: Reporting, event: {ends: number[]; slots?: number | undefined}) => {
const {stepSlots: _slots, ...rest} = state.reports
return reporting(state, {...rest, steps: event.ends, ...(event.slots === undefined ? {} : {stepSlots: event.slots})})
},
aspect: (state: Reporting, event: {ratio: number}) =>
state.reports.aspect === event.ratio ? state : reporting(state, {...state.reports, aspect: event.ratio}),
height: (state: Reporting, event: {px: number}) =>
state.reports.height === event.px ? state : reporting(state, {...state.reports, height: event.px}),
legend: (state: Reporting, event: {type: 'legend'} & RendererLegend) => {
const {type: _type, ...legend} = event
if (legend.items.length) return reporting(state, {...state.reports, legend})
const {legend: _legend, ...rest} = state.reports
return reporting(state, rest)
},
summary: (state: Reporting, event: {items: SummaryItem[]}) => {
if (!event.items.length) {
const {summary: _summary, ...rest} = state.reports
return reporting(state, rest)
}
return JSON.stringify(state.reports.summary) === JSON.stringify(event.items)
? state
: reporting(state, {...state.reports, summary: event.items})
},
error: (state: Reporting, event: {message: string}) =>
reporting(state, {...state.reports, rendererErrors: [...state.reports.rendererErrors, event.message].slice(-5)}),
rejected: (state: Reporting) => reporting(state, {...state.reports, rejected: state.reports.rejected + 1}),
}

/** A new document: the painted progress and the steps belong to the old one. */
const reinit = <S extends PaneLifecycleState>(state: S): S => {
const {rendered: _rendered, renderedInit: _init, stepSlots: _slots, ...rest} = state.reports
return {...state, reports: {...rest, steps: []}}
}

const failed = (state: Reporting, event: {message: string}): PaneLifecycleState => ({
kind: 'failed',
reports: state.reports,
message: event.message,
})

export const paneLifecycle = defineMachine<PaneLifecycleState, PaneLifecycleEvent>()({
states: {
loading: {
on: {
...reports,
revealed: state => ({kind: 'ready', reports: state.reports}),
failed,
reinit,
reloaded: () => loadingLifecycle,
},
},
ready: {
on: {
...reports,
revealed: ignore,
failed,
reinit,
reloaded: () => loadingLifecycle,
},
},
// A stopped frame reports nothing more; only a new bundle starts the pane over.
failed: {
on: {
ready: ignore,
revealed: ignore,
failed: ignore,
rendered: ignore,
controls: ignore,
steps: ignore,
aspect: ignore,
height: ignore,
legend: ignore,
summary: ignore,
error: ignore,
rejected: ignore,
reinit,
reloaded: () => loadingLifecycle,
},
},
},
})

/** The pane's state as `RendererPane` reports it (`PaneState`): its status, its failure's message and its reports. */
export const paneStateOf = (state: PaneLifecycleState): PaneState =>
state.kind === 'failed' ? {status: 'failed', message: state.message, ...state.reports} : {status: state.kind, ...state.reports}
68 changes: 18 additions & 50 deletions packages/host/core/src/pane.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {useEffect, useRef, useState} from 'react'
import {useEffect, useMemo, useRef, useState} from 'react'
import {useMachine} from '@githubnext/projections-machine/react'
import type {ReactNode} from 'react'
import type {
AnchorRect,
Expand All @@ -18,6 +19,7 @@ import type {
import {RendererFrame} from './frame.js'
import type {RendererFrameEvent} from './frame/types.js'
import type {RendererDocuments, RendererEntry} from './registry.js'
import {loadingLifecycle, paneLifecycle, paneStateOf} from './pane-lifecycle.js'

/**
* What a `RendererPane` reports through `onState`: its frame's status (with the failure `message`), the renderer's
Expand Down Expand Up @@ -109,7 +111,8 @@ export function RendererPane(props: RendererPaneProps) {
const {renderer, init, progress, environment, selectedId, hoveredId} = props
const container = useRef<HTMLDivElement>(null)
const frame = useRef<RendererFrame | null>(null)
const [state, setState] = useState<PaneState>(loadingPane)
const [lifecycle, send] = useMachine(paneLifecycle, {state: loadingLifecycle})
const state = useMemo(() => paneStateOf(lifecycle), [lifecycle])
// Counts the renderer's `control` messages, each answered with the options once the host has applied it.
const [controlAnswer, setControlAnswer] = useState(0)
const callbacks = useRef(props)
Expand All @@ -135,40 +138,27 @@ export function RendererPane(props: RendererPaneProps) {
useEffect(() => {
const host = container.current
if (!host) return
setState(loadingPane)
send({type: 'reloaded'})
const onEvent = (event: RendererFrameEvent) => {
const current = callbacks.current
switch (event.type) {
case 'ready':
setState(previous => ({...previous, capabilities: event.capabilities, controls: event.capabilities.controls ?? []}))
case 'rendered':
send({...event, init: initialized.current})
Comment thread
agorischek marked this conversation as resolved.
Resolved
break
case 'ready':
case 'revealed':
setState(previous => ({...previous, status: 'ready'}))
break
case 'controls':
setState(previous => ({...previous, controls: event.controls}))
break
case 'failed':
setState(previous => ({...previous, status: 'failed', message: event.message}))
break
case 'rendered':
setState(previous => ({...previous, rendered: event.progress, renderedInit: initialized.current}))
break
case 'steps':
setState(({stepSlots: _slots, ...previous}) => ({
...previous,
steps: event.ends,
...(event.slots === undefined ? {} : {stepSlots: event.slots}),
}))
break
case 'aspect':
setState(previous => (previous.aspect === event.ratio ? previous : {...previous, aspect: event.ratio}))
break
case 'height':
case 'legend':
case 'summary':
case 'error':
setState(previous => ({...previous, rendererErrors: [...previous.rendererErrors, event.message].slice(-5)}))
send(event)
break
case 'rejected':
setState(previous => ({...previous, rejected: previous.rejected + 1}))
send({type: 'rejected'})
break
case 'select':
current.onSelect(event.id, event.path)
Expand All @@ -181,26 +171,6 @@ export function RendererPane(props: RendererPaneProps) {
// Answer with the options as they stand once applied, so a value the host or its embedder declined is undone.
setControlAnswer(previous => previous + 1)
break
case 'legend': {
const {type: _type, ...legend} = event
setState(previous => {
if (!legend.items.length) {
const {legend: _legend, ...rest} = previous
return rest
}
return {...previous, legend}
})
break
}
case 'summary':
setState(previous => {
if (!event.items.length) {
const {summary: _summary, ...rest} = previous
return rest
}
return JSON.stringify(previous.summary) === JSON.stringify(event.items) ? previous : {...previous, summary: event.items}
})
break
case 'hover':
current.onHover(event.id)
break
Expand All @@ -213,9 +183,6 @@ export function RendererPane(props: RendererPaneProps) {
case 'open':
current.onOpen(event.path, event.line)
break
case 'height':
setState(previous => (previous.height === event.px ? previous : {...previous, height: event.px}))
break
}
}
const created = new RendererFrame({
Expand All @@ -241,7 +208,8 @@ export function RendererPane(props: RendererPaneProps) {
if (frame.current === created) frame.current = null
callbacks.current.frameRef?.(null)
}
}, [url])
// `send` is the pane's actor's, the same for its life.
}, [url, send])
useEffect(() => {
frame.current?.setTitle(title)
}, [title])
Expand All @@ -251,9 +219,9 @@ export function RendererPane(props: RendererPaneProps) {
useEffect(() => {
if (initialized.current === init) return
initialized.current = init
setState(({rendered: _rendered, renderedInit: _init, stepSlots: _slots, ...previous}) => ({...previous, steps: []}))
send({type: 'reinit'})
frame.current?.setInit(init, latest.current.progress)
}, [init])
}, [init, send])
useEffect(() => {
if (progress) frame.current?.setProgress(progress)
}, [progress])
Expand Down
Loading
Loading