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
12 changes: 9 additions & 3 deletions docs/contracts/renderer-frames.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ handshake by sending `ready`.
- `init` starts the frame with either `mode: "extraction"` and `extraction`, or
`mode: "comparison"` with `before`, `after`, and `comparison`. It also
includes `projection {id, title, renderer}`, `theme {colorMode, tokens}`,
`reducedMotion`, `locale`, and optional `pane` (`before` or `after`) and
`sizing` (`content` or `fill`).
`reducedMotion`, `locale`, and optional `pane` (`before` or `after`), `sizing`
(`content` or `fill`) and `generation`, a number the host gives each `init` it
sends.
- `progress` drives animated playback with `progress` (0–1), `highlighting`
(0–1), and `direction` (±1).
- `select` sets the active selection to `id` or `null`, with an optional `path`
Expand Down Expand Up @@ -68,7 +69,12 @@ handshake by sending `ready`.
- `controls` replaces the declared `controls` list.
- `control` reports that someone changed a declared control from inside the
renderer (`id`, `value`), which the host applies as a settings change.
- `rendered` confirms the frame painted a given `progress`.
- `rendered` confirms the frame painted a given `progress`. When the host
numbered its `init` messages (`generation`), `rendered` carries the generation
of the document it painted, and the host drops an acknowledgement of an
earlier one. The SDK's client adds it: `rendered(progress, init)` echoes the
generation of the `init` payload it painted (the SDK's React hooks pass it),
or without one the latest it received.
- `select` reports a selection change (`id` or `null`, plus optional `path` for
renderers declaring `properties`).
- `annotation` * fires when someone activates an item's annotation marker (`id`)
Expand Down
12 changes: 6 additions & 6 deletions docs/reference/renderer-messages.md

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions docs/reference/renderer-sdk.md

Large diffs are not rendered by default.

10 changes: 7 additions & 3 deletions packages/host/core/src/frame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,10 @@ export class RendererFrame {
this.progress = progress
this.flow.reset()
this.renderedProgress = undefined
// Numbered, so the gate drops a renderer's acknowledgement of an earlier one.
this.gate.generation++
if (this.status !== 'ready') return
this.send(initMessage(init, this.capabilities))
this.send(initMessage(init, this.capabilities, this.gate.generation))
if (progress) this.setProgress(progress)
}

Expand Down Expand Up @@ -246,7 +248,7 @@ export class RendererFrame {
case 'rendered':
this.renderedProgress = message.progress
this.flow.acknowledged(message.progress)
this.onEvent(message)
this.onEvent({type: 'rendered', progress: message.progress})
this.lifecycle.reveal()
return
case 'height': {
Expand Down Expand Up @@ -302,7 +304,9 @@ export class RendererFrame {
this.declared = capabilities.controls ?? []
this.onEvent({type: 'ready', capabilities})
const {init, options, selection, selectionPath, marks, hovered, filtering} = this
for (const message of replay({init, options, selection, selectionPath, marks, hovered, filtering}, capabilities)) this.send(message)
const {generation} = this.gate
for (const message of replay({init, generation, options, selection, selectionPath, marks, hovered, filtering}, capabilities))
this.send(message)
this.send({type: 'viewport', ...viewportOf(this.iframe, this.view)})
if (this.progress) this.flow.send(this.progress)
}
Expand Down
9 changes: 8 additions & 1 deletion packages/host/core/src/frame/admission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export type Admission =
| {type: 'rejected'; reason: 'invalid' | 'oversized' | 'rate-limited'}
/** Dropped silently: over the rate limit again. */
| {type: 'dropped'}
/** Dropped silently: a paint of an earlier document, sent before the renderer received the frame's latest `init`. */
| {type: 'stale'}
/** The frame must be stopped. */
| {type: 'failed'; message: string}

Expand All @@ -49,6 +51,8 @@ export type Admission =
export class MessageGate {
private readonly rate: MessageRate
private dropped = 0
/** The generation of the frame's latest `init`, which the renderer's `rendered` echoes (see `HostMessage`). */
generation = 0

constructor(
view: Window,
Expand All @@ -71,7 +75,10 @@ export class MessageGate {
}
if (size(event.data) > rendererLimits.messageBytes) return {type: 'rejected', reason: 'oversized'}
const message = parseRendererMessage(event.data, this.channel)
return message ? {type: 'message', message} : {type: 'rejected', reason: 'invalid'}
if (!message) return {type: 'rejected', reason: 'invalid'}
// A renderer that echoes no generation is taken at its word.
const stale = message.type === 'rendered' && message.generation !== undefined && message.generation !== this.generation
return stale ? {type: 'stale'} : {type: 'message', message}
}
}

Expand Down
10 changes: 6 additions & 4 deletions packages/host/core/src/frame/replay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export const selectMessage = (id: string | null, path: string | undefined): Host
/** What the host set for a renderer, kept so a renderer that becomes ready later gets it too. */
export interface FrameState {
init: InitPayload
/** The init's generation, which the renderer's `rendered` echoes. */
generation: number
options: RendererOptions
selection: string | null
selectionPath: string | undefined
Expand All @@ -29,19 +31,19 @@ export interface FrameState {
* The `init` a renderer is sent: the comparison's change `context` only to a renderer that declares the `context`
* capability, as a renderer that checks comparisons against an older schema rejects it.
*/
export function initMessage(init: InitPayload, capabilities: RendererCapabilities | undefined): HostMessage {
export function initMessage(init: InitPayload, capabilities: RendererCapabilities | undefined, generation: number): HostMessage {
if (init.mode !== 'comparison' || capabilities?.context || !init.comparison.changes.some(change => change.context))
return {type: 'init', ...init}
return {type: 'init', generation, ...init}
const changes = init.comparison.changes.map(({context: _context, ...change}) => change)
return {type: 'init', ...init, comparison: {...init.comparison, changes}}
return {type: 'init', generation, ...init, comparison: {...init.comparison, changes}}
}

/**
* The messages that bring a renderer that just became ready up to date: the presented documents, then the state set
* while it loaded that its capabilities accept.
*/
export function replay(state: FrameState, capabilities: RendererCapabilities): HostMessage[] {
const messages: HostMessage[] = [initMessage(state.init, capabilities)]
const messages: HostMessage[] = [initMessage(state.init, capabilities, state.generation)]
if (Object.keys(state.options).length) messages.push({type: 'options', options: state.options})
if (state.selection !== null) messages.push(selectMessage(state.selection, state.selectionPath))
if (state.marks.length && capabilities.annotations) messages.push({type: 'annotations', items: state.marks})
Expand Down
3 changes: 2 additions & 1 deletion packages/host/core/src/pane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,8 @@ export function RendererPane(props: RendererPaneProps) {
onState(state)
}, [state, onState])

// The init the frame was last given, so an acknowledgement records the one it answers.
// The init the frame was last given, so an acknowledgement records the one it answers: the frame drops a renderer's
// acknowledgement of an earlier init (renderers that echo its generation), and the ref changes with `setInit`.
const initialized = useRef(init)
const url = renderer.url
const title = props.label ? `${renderer.title} renderer, ${props.label}` : `${renderer.title} renderer`
Expand Down
97 changes: 97 additions & 0 deletions packages/host/core/test/frame-generation.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// A renderer's paint acknowledgements belong to the document it was sent: the frame numbers each `init`, the renderer
// echoes the latest it received, and an acknowledgement of an earlier one is dropped.
import {test} from 'node:test'
import assert from 'node:assert/strict'
import {RendererFrame} from '../dist/frame.js'

/** A window, its frame's contentWindow, the messages the frame sent its renderer, and a way to answer as the renderer. */
function setup() {
const listeners = new Set()
const sent = []
const contentWindow = {postMessage: data => sent.push(data)}
const view = {
location: {href: 'http://host.test/', origin: 'http://host.test'},
crypto: globalThis.crypto,
performance: globalThis.performance,
btoa: globalThis.btoa,
setTimeout: () => 0,
clearTimeout: () => {},
requestAnimationFrame: () => 0,
cancelAnimationFrame: () => {},
addEventListener: (type, listener) => type === 'message' && listeners.add(listener),
removeEventListener: (type, listener) => listeners.delete(listener),
getComputedStyle: () => ({}),
}
const iframe = {
contentWindow,
style: {},
dataset: {},
attributes: {},
clientWidth: 800,
clientHeight: 600,
isConnected: true,
setAttribute(name, value) {
this.attributes[name] = value
},
getAttribute(name) {
return this.attributes[name] ?? null
},
removeAttribute() {},
addEventListener() {},
removeEventListener() {},
getBoundingClientRect: () => ({width: 800, height: 600, left: 0, top: 0}),
remove() {},
}
const container = {ownerDocument: {createElement: () => iframe, defaultView: view}, append() {}}
const events = []
const document = {protocolVersion: 0, schema: 'graph/v0', entities: [], relationships: []}
const init = generation => ({
projection: {id: 'p', title: 'P', renderer: 'graph'},
mode: 'extraction',
extraction: {...document, generation},
theme: {colorMode: 'light', tokens: {}},
reducedMotion: false,
locale: 'en',
})
const frame = new RendererFrame({
container,
url: '/graph/index.html',
title: 'Graph',
init: init(1),
onEvent: event => events.push(event),
window: view,
})
const channel = new URLSearchParams(new URL(iframe.src ?? frame.iframe.src ?? iframe.attributes.src).hash.slice(1)).get('channel')
const answer = message => {
for (const listener of [...listeners]) listener({data: {projections: 0, channel, ...message}, source: contentWindow, origin: 'null'})
}
return {frame, events, sent, answer, init}
}

const inits = sent => sent.filter(message => message.type === 'init')

test("a frame numbers each init, and drops a renderer's acknowledgement of an earlier one", () => {
const {frame, events, sent, answer, init} = setup()
answer({type: 'ready', capabilities: {changeHighlighting: 'supported'}})
assert.equal(inits(sent).at(-1).generation, 0)
frame.setInit(init(2))
assert.equal(inits(sent).at(-1).generation, 1)
// Sent before the renderer received the new init.
answer({type: 'rendered', progress: 1, generation: 0})
assert.equal(frame.renderedProgress, undefined)
assert.equal(events.filter(event => event.type === 'rendered').length, 0)
answer({type: 'rendered', progress: 1, generation: 1})
assert.equal(frame.renderedProgress, 1)
assert.deepEqual(
events.filter(event => event.type === 'rendered'),
[{type: 'rendered', progress: 1}],
)
})

test('a renderer that echoes no generation is taken at its word, as before', () => {
const {frame, answer, init} = setup()
answer({type: 'ready', capabilities: {changeHighlighting: 'supported'}})
frame.setInit(init(2))
answer({type: 'rendered', progress: 0.5})
assert.equal(frame.renderedProgress, 0.5)
})
2 changes: 1 addition & 1 deletion packages/renderers/kit/src/react/shell/reports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export function usePaintAcknowledgement(
useEffect(() => {
if (!client || !init || holds.current) return
return afterPaint(() => {
if (!holds.current) client.rendered(hostProgress.progress)
if (!holds.current) client.rendered(hostProgress.progress, init)
})
}, [client, init, hostProgress, released])
return hold
Expand Down
18 changes: 13 additions & 5 deletions packages/renderers/sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ import {
} from './protocol.js'
import {documentRings} from './rings.js'
import {optionalThemeTokenNames, resolveThemeTokens} from './tokens.js'
import {dispatch, replayed, resumeSession, type RendererHandlers} from './client/host-messages.js'
import {dispatch, echoedGeneration, replayed, resumeSession, type RendererHandlers} from './client/host-messages.js'
import {documentRequests} from './client/documents.js'
import type {
AnchorRect,
ControlValue,
HostMessage,
InitPayload,
RendererControl,
RendererEnvironment,
RendererCapabilities,
Expand Down Expand Up @@ -54,8 +55,12 @@ export interface ConnectOptions {
export interface RendererClient {
/** The frame's channel nonce, from the URL fragment. */
readonly channel: string
/** Acknowledges that the frame for `progress` has been painted. */
rendered(progress: number): void
/**
* Acknowledges that the frame for `progress` has been painted. Pass the `init` payload it painted when the
* acknowledgement is deferred (after a paint, say), so that a paint of a document the host has since replaced isn't
* taken for the new one; without it, the latest `init` is assumed.
*/
rendered(progress: number, init?: InitPayload): void
/**
* Reports the renderer's selection, or `null` when it clears it. `path`, an
* RFC 6901 pointer such as `/data/owner`, selects a property of the item
Expand Down Expand Up @@ -150,11 +155,13 @@ export class RendererConnectionError extends Error {
* const client = connectRenderer(
* {
* init(payload) {
* document = payload
* draw(payload)
* },
* progress({progress, highlighting}) {
* update(progress, highlighting)
* afterPaint(() => client.rendered(progress))
* const painted = document
* afterPaint(() => client.rendered(progress, painted))
* },
* environment: applyEnvironment,
* },
Expand Down Expand Up @@ -206,7 +213,8 @@ export function connectRenderer(handlers: RendererHandlers, options: ConnectOpti
const clamp = (value: number) => Math.min(rendererLimits.maxHeight, Math.max(0, Math.ceil(value)))
const client: RendererClient = {
channel,
rendered: progress => post({type: 'rendered', progress: Math.min(1, Math.max(0, progress))}),
rendered: (progress, init) =>
post({type: 'rendered', progress: Math.min(1, Math.max(0, progress)), ...echoedGeneration(messages.get('init'), init)}),
select(id, path) {
if (path !== undefined && !isPropertyPath(path))
throw new RendererConnectionError('A selection path must be an RFC 6901 JSON pointer')
Expand Down
15 changes: 14 additions & 1 deletion packages/renderers/sdk/src/client/host-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,24 @@ export function resumeSession(view: Window, channel: string) {
return {messages: session.messages, replay}
}

/** The generation of each `init` payload handed to a renderer, so a paint of it echoes its own. */
const generations = new WeakMap<InitPayload, number>()

/**
* What a renderer's `rendered` echoes (see `HostMessage`): the generation of the `init` it painted when it says which,
* else the latest `init`'s; nothing when that had none.
*/
export function echoedGeneration(latest: HostMessage | undefined, painted?: InitPayload): {generation?: number} {
const generation = painted ? generations.get(painted) : latest?.type === 'init' ? latest.generation : undefined
return generation === undefined ? {} : {generation}
}

/** Hands a host message to its handler, as the handler's own payload. */
export function dispatch(handlers: RendererHandlers, message: HostMessage) {
switch (message.type) {
case 'init': {
const {type: _type, ...payload} = message
const {type: _type, generation, ...payload} = message
if (generation !== undefined) generations.set(payload as InitPayload, generation)
handlers.init?.(payload as InitPayload)
break
}
Expand Down
3 changes: 2 additions & 1 deletion packages/renderers/sdk/src/protocol/host-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {focus, parseKinds} from './init-fields.js'
import {environment} from './environment.js'
import type {HostMessage, RendererOptions} from './messages.js'
import {scrollPosition} from './positions.js'
import {controlIdPattern, envelopeKeys, finite, isEnvelope, isPropertyPath, record} from './validation.js'
import {controlIdPattern, envelopeKeys, finite, isEnvelope, isPropertyPath, record, isGeneration} from './validation.js'
import {document} from './document-message.js'
import {filter} from './filter-message.js'

Expand Down Expand Up @@ -36,6 +36,7 @@ function init(message: Fields): HostMessage | undefined {
const {kinds: rawKinds, ...rest} = raw as Fields
const kinds = parseKinds(rawKinds)
const projection = {...rest, ...(kinds ? {kinds} : {})}
if (message.generation !== undefined && !isGeneration(message.generation)) return undefined
const {projections: _projections, channel: _channel, ...fields} = message
const payload = {...fields, projection}
if (message.mode === 'extraction' && record(message.extraction))
Expand Down
14 changes: 11 additions & 3 deletions packages/renderers/sdk/src/protocol/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,12 @@ export interface RendererLegend {
* whenever the document changes, and every other message may arrive at any time after it.
*/
export type HostMessage =
| ({type: 'init'} & InitPayload)
/**
* The documents to present. `generation` numbers each `init` a host sends, and the renderer's `rendered` echoes the
* latest it received, so a host tells an acknowledgement of an earlier document from one of this. Optional: hosts
* that send none get none back.
*/
| ({type: 'init'; generation?: number} & InitPayload)
| ({type: 'progress'} & ProgressPayload)
/** The selected item, and optionally a property of it (`path`, an RFC 6901 pointer into the item). */
| {type: 'select'; id: string | null; path?: string}
Expand Down Expand Up @@ -314,8 +319,11 @@ export interface ScrollPosition {
export type RendererMessage =
/** The renderer is listening and supports `capabilities`; the host replies with `init`. */
| {type: 'ready'; capabilities: RendererCapabilities}
/** The frame for `progress` (0 to 1) has been painted. */
| {type: 'rendered'; progress: number}
/**
* The frame for `progress` (0 to 1) has been painted, with the `generation` of the latest `init` the renderer had
* received when it said so (none when that `init` had none).
*/
| {type: 'rendered'; progress: number; generation?: number}
/** The person selected an item, or a property of it (`path`), or cleared the selection (`null`). */
| {type: 'select'; id: string | null; path?: string}
/** The frame height the renderer wants, in CSS px; the host clamps it to `rendererLimits.minHeight`–`maxHeight`. */
Expand Down
12 changes: 9 additions & 3 deletions packages/renderers/sdk/src/protocol/renderer-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type {RendererMessage} from './messages.js'
import {anchorRect, scrollPosition} from './positions.js'
import {steps} from './steps-message.js'
import {parseSummaryItems} from './summary/items.js'
import {envelopeKeys, finite, isEnvelope, isPropertyPath, keys, rendererNamePattern, text} from './validation.js'
import {envelopeKeys, finite, isEnvelope, isPropertyPath, keys, rendererNamePattern, text, isGeneration} from './validation.js'

type Fields = Record<string, unknown>

Expand Down Expand Up @@ -42,9 +42,15 @@ const parsers: {[type: string]: (message: Fields) => RendererMessage | undefined
return capabilities ? {type: 'ready', capabilities} : undefined
},
rendered(message) {
if (!keys(message, [...envelopeKeys, 'progress']) || !finite(message.progress) || message.progress < 0 || message.progress > 1)
if (
!keys(message, [...envelopeKeys, 'progress', 'generation']) ||
!finite(message.progress) ||
message.progress < 0 ||
message.progress > 1
)
return undefined
return {type: 'rendered', progress: message.progress}
if (message.generation === undefined) return {type: 'rendered', progress: message.progress}
return isGeneration(message.generation) ? {type: 'rendered', progress: message.progress, generation: message.generation} : undefined
},
select,
annotation(message) {
Expand Down
5 changes: 5 additions & 0 deletions packages/renderers/sdk/src/protocol/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,8 @@ export const coordinate = (value: unknown): value is number => finite(value) &&
export function isEnvelope(value: unknown, channel: string): value is Envelope & {type: string} {
return record(value) && value.projections === rendererProtocolVersion && value.channel === channel && typeof value.type === 'string'
}

/** An `init`'s generation (`HostMessage`): a non-negative safe integer. */
export function isGeneration(value: unknown): value is number {
return Number.isSafeInteger(value) && (value as number) >= 0
}
Loading
Loading