@lincyaw/host 1.0.0-rc.14 → 1.0.0-rc.140

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Presmium's host interface for plugin components: step state, services, shared state, interface text, the site path and the design system, the same in the web form and in the slides (both are the viewer).
4
4
 
5
- Part of [Presmium](https://github.com/Lincyaw/presmium), which compiles canonical lecture.json teaching documents into web pages, slides, Jupyter notebooks and narrated playback.
5
+ Part of [Presmium](https://github.com/Lincyaw/presmium), which compiles canonical index.pmd teaching documents into web pages, slides, Jupyter notebooks and narrated playback.
6
6
 
7
7
  ## Install
8
8
 
@@ -32,7 +32,7 @@ Hooks return ordinary React values. `useSharedState` returns `[value, setValue]`
32
32
 
33
33
  ## Documentation
34
34
 
35
- - [Plugin guide](https://github.com/Lincyaw/presmium/blob/main/site/plugins/locales/en/lecture.json)
35
+ - [Plugin guide](https://github.com/Lincyaw/presmium/blob/main/site/plugins/locales/en/index.pmd)
36
36
 
37
37
  ## License
38
38
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/host",
3
- "version": "1.0.0-rc.14",
3
+ "version": "1.0.0-rc.140",
4
4
  "description": "Presmium's host interface for plugin components in every form: step state, services, interface text, and the design system (tokens, components, fonts)",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -20,7 +20,7 @@
20
20
  "*.css"
21
21
  ],
22
22
  "engines": {
23
- "node": ">=22.19"
23
+ "node": "^24.22.3 || >=26.13.1"
24
24
  },
25
25
  "publishConfig": {
26
26
  "access": "public"
@@ -33,6 +33,7 @@
33
33
  "src"
34
34
  ],
35
35
  "dependencies": {
36
+ "@fontsource-variable/hanken-grotesk": "5.3.0",
36
37
  "@fontsource/ibm-plex-mono": "5.3.0",
37
38
  "@fontsource/ibm-plex-sans": "5.3.0",
38
39
  "@fontsource/source-serif-4": "5.3.1",
@@ -44,8 +45,8 @@
44
45
  "@radix-ui/react-tooltip": "^1.2.8",
45
46
  "react": "18.3.1",
46
47
  "react-dom": "18.3.1",
47
- "@lincyaw/design": "1.0.0-rc.14",
48
- "@lincyaw/kernel": "1.0.0-rc.14"
48
+ "@lincyaw/design": "1.0.0-rc.140",
49
+ "@lincyaw/kernel": "1.0.0-rc.140"
49
50
  },
50
51
  "devDependencies": {
51
52
  "@types/react": "18.3.28",
package/src/approvals.ts CHANGED
@@ -8,5 +8,5 @@ export function PmApprovals({ placement = 'below' }: { placement?: 'below' | 'ab
8
8
  const t = useMessages(HOST_MESSAGES); const [open, setOpen] = useState(false); const [failed, setFailed] = useState<string>(); const pending = useStore(approvals.pending)
9
9
  if (!pending.length) return null
10
10
  const answer = (id: string, allow: boolean) => { setFailed(undefined); void approvals.answer(id, allow).catch(() => setFailed(t.answerFailed)) }
11
- return h(PmPopover, { open, label: t.approvalsTitle, name: 'pm-approvals', placement: placement === 'above' ? 'above-end' : 'below-end', onOpenChange: setOpen, trigger: h(PmButton, { variant: 'accent', small: true }, t.approvals(pending.length)) }, pending.map(({ id, request }) => h('div', { key: id, 'data-approval': id }, h('p', {}, request.title), h('p', {}, t.from(t.origins[request.from] ?? t.otherOrigin)), ...(request.detail ?? '').split('\n').filter(Boolean).map((line, key) => h('p', { key }, line)), h(PmButton, { small: true, variant: 'primary', onClick: () => answer(id, true) }, t.allow), h(PmButton, { small: true, onClick: () => answer(id, false) }, t.deny))), failed ? h(PmNotice, { tone: 'danger' }, failed) : null)
11
+ return h(PmPopover, { open, label: t.approvalsTitle, name: 'pm-approvals', placement: placement === 'above' ? 'above-end' : 'below-end', onOpenChange: setOpen, trigger: h(PmButton, { variant: 'primary', small: true }, t.approvals(pending.length)) }, pending.map(({ id, request }) => h('div', { key: id, 'data-approval': id }, h('p', {}, request.title), h('p', {}, t.from(t.origins[request.from] ?? t.otherOrigin)), ...(request.detail ?? '').split('\n').filter(Boolean).map((line, key) => h('p', { key }, line)), h(PmButton, { small: true, variant: 'primary', onClick: () => answer(id, true) }, t.allow), h(PmButton, { small: true, onClick: () => answer(id, false) }, t.deny))), failed ? h(PmNotice, { tone: 'danger' }, failed) : null)
12
12
  }
package/src/contracts.ts CHANGED
@@ -81,6 +81,8 @@ export interface ServerClient {
81
81
  readonly available: boolean
82
82
  readonly member: Store<Member | undefined>
83
83
  fetch(plugin: string, path: string, init?: RequestInit): Promise<Response>
84
+ /** A document-scoped GET resource for native media requests, using the page's existing authentication. */
85
+ resourceURL?(plugin: string, path: string): string
84
86
  events(plugin: string, path: string): EventSource
85
87
  }
86
88
 
@@ -136,10 +138,15 @@ export interface ProductionPlayback {
136
138
  }
137
139
  export const PRODUCTION_PLAYBACK = defineService<ProductionPlayback>('presmium.productionPlayback')
138
140
 
139
- /** A loaded timed-caption player owns presentation captions until its lease is released. */
141
+ /**
142
+ * A loaded timed-caption player owns presentation captions until its lease is released. `shown` tells whether it shows
143
+ * them (turned on, in a production preview, burned into an export): the slides keep room for them while it does.
144
+ */
140
145
  export interface TimedCaptions {
141
146
  readonly active: Store<boolean>
147
+ readonly shown: Store<boolean>
142
148
  claim(): Unsubscribe
149
+ show(on: boolean): void
143
150
  }
144
151
  export const TIMED_CAPTIONS = defineService<TimedCaptions>('presmium.timedCaptions')
145
152
 
@@ -156,12 +163,23 @@ export const PAGE_READINESS = defineService<PageReadiness>('presmium.pageReadine
156
163
  export interface StepClockDriver {
157
164
  readonly elapsed: Store<number | undefined>
158
165
  readonly recording?: boolean
166
+ /** Holds the clock until it is released (a capture of the page): other drivers wait until then. */
167
+ readonly exclusive?: boolean
168
+ /**
169
+ * How long (ms) the animation of step `step` of slide `slide` may take while this driver plays it: a narrated lecture
170
+ * gives the time from the step's start until its voice ends. Undefined for a step it does not pace.
171
+ */
172
+ readonly stepLength?: (slide: number, step: number) => number | undefined
159
173
  }
160
174
 
161
175
  export interface StepClock {
162
176
  drive(driver: StepClockDriver): Unsubscribe
163
- wait(work: Promise<unknown>): void
164
- settled(): Promise<void>
177
+ wait(work: Promise<unknown>, slide?: number): void
178
+ /** Wait for the named slides, or every pending picture when omitted (capture/export). */
179
+ settled(slides?: readonly number[]): Promise<void>
180
+ /** Warm pictures for the given slide indices before playback reaches them. */
181
+ prepare?(slides: readonly number[], options?: { wait?: boolean }): Promise<void>
182
+ registerPreparation?(slide: number, prepare: () => void | Promise<void>): Unsubscribe
165
183
  }
166
184
 
167
185
  export const STEP_CLOCK = defineService<StepClock>('presmium.stepClock')
@@ -1,4 +1,4 @@
1
- import { createContext, createElement as h, forwardRef, useContext, useEffect, useId, useRef } from 'react'
1
+ import { createContext, createElement as h, forwardRef, useContext, useEffect, useId, useRef, useState } from 'react'
2
2
  import type { ButtonHTMLAttributes, HTMLAttributes, ReactNode } from 'react'
3
3
  import * as Dialog from '@radix-ui/react-dialog'
4
4
  import * as Popover from '@radix-ui/react-popover'
@@ -9,7 +9,7 @@ import { HOST_MESSAGES } from '../messages.ts'
9
9
  import { ICONS } from '@lincyaw/design'
10
10
  import type { IconName } from '@lincyaw/design'
11
11
  import type { ToolbarPlacement } from '../contracts.ts'
12
- export type ButtonVariant = 'default' | 'primary' | 'accent' | 'ghost' | 'danger'
12
+ export type ButtonVariant = 'default' | 'primary' | 'ghost' | 'text' | 'danger'
13
13
  export type ControlDensity = 'compact' | 'regular' | 'touch'
14
14
  /** `overlay`: one large round control laid over media, such as the Play that starts a lecture the browser would not autoplay. */
15
15
  export type IconButtonVariant = 'default' | 'overlay'
@@ -22,18 +22,33 @@ export function PmIcon({ name, size: _size, strokeWidth = 1.7, ...attrs }: { nam
22
22
  return h('svg', { ...attrs, className: cls('pm-ui-icon', attrs.className), viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, focusable: false }, ICONS[name]?.map(([tag, attributes], key) => h(tag, { ...attributes, key })))
23
23
  }
24
24
  type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & { variant?: ButtonVariant, small?: boolean, icon?: IconName, density?: ControlDensity, loading?: boolean }
25
- export const PmButton = forwardRef<HTMLButtonElement, ButtonProps>(function PmButton({ variant = 'default', small, density = small ? 'compact' : 'regular', loading, icon, className, children, disabled, ...rest }, ref) {
25
+ export const PmButton = forwardRef<HTMLButtonElement, ButtonProps>(function PmButton({ variant = 'default', small, density = 'compact', loading, icon, className, children, disabled, ...rest }, ref) {
26
26
  return h('button', { ...rest, ref, type: rest.type ?? 'button', 'data-density': density, 'aria-busy': loading || undefined, disabled: disabled || loading || rest['aria-disabled'] === true || rest['aria-disabled'] === 'true', className: cls('pm-ui-button', variant !== 'default' && `pm-ui-button--${variant}`, className) },
27
27
  h('span', { className: cls('pm-ui-button__content', !icon && loading !== undefined && 'pm-ui-button__content--loading-text') },
28
28
  icon || loading !== undefined ? h('span', { className: 'pm-ui-button__icon', 'aria-hidden': true }, loading ? h(PmIcon, { name: 'loading', className: 'pm-ui-loading' }) : icon ? h(PmIcon, { name: icon }) : null) : null,
29
29
  children))
30
30
  })
31
+ const TOOLTIP_DELAY = 500
32
+ const TOOLTIP_SKIP = 300
33
+ let tooltipClosedAt = 0
34
+ /** A pointer shows the tooltip after 500 ms, keyboard focus at once; within 300 ms of one closing the next opens at once. */
31
35
  export function PmTooltip({ label, shortcut, children }: { label: string, shortcut?: string, children: ReactNode }) {
32
- return h(Tooltip.Provider, { delayDuration: 300, skipDelayDuration: 0, children:
33
- h(Tooltip.Root, {}, h(Tooltip.Trigger, { asChild: true }, children), h(Tooltip.Portal, {},
36
+ const [open, setOpen] = useState(false)
37
+ const shown = useRef(false)
38
+ const pointer = useRef(false)
39
+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
40
+ useEffect(() => () => clearTimeout(timer.current), [])
41
+ const change = (next: boolean) => {
42
+ clearTimeout(timer.current)
43
+ if (!next) { if (shown.current) tooltipClosedAt = Date.now(); shown.current = false; setOpen(false); return }
44
+ const wait = pointer.current && Date.now() - tooltipClosedAt > TOOLTIP_SKIP ? TOOLTIP_DELAY : 0
45
+ timer.current = setTimeout(() => { shown.current = true; setOpen(true) }, wait)
46
+ }
47
+ return h(Tooltip.Provider, { delayDuration: 0, skipDelayDuration: 0, children:
48
+ h(Tooltip.Root, { open, onOpenChange: change }, h(Tooltip.Trigger, { asChild: true, onPointerEnter: () => { pointer.current = true }, onPointerLeave: () => { pointer.current = false } }, children), h(Tooltip.Portal, {},
34
49
  h(Tooltip.Content, { className: 'pm-ui-tooltip pm-ui', side: 'top', sideOffset: 6, collisionPadding: 8 }, label, shortcut ? h('kbd', { className: 'pm-ui-shortcut' }, shortcut) : null))) })
35
50
  }
36
- export const PmIconButton = forwardRef<HTMLButtonElement, Omit<ButtonProps, 'variant'> & { variant?: IconButtonVariant, icon: IconName, label: string, hint?: string, shortcut?: string }>(function PmIconButton({ variant = 'default', icon, label, hint, shortcut, small, density = small ? 'compact' : 'regular', loading, className, disabled, ...rest }, ref) {
51
+ export const PmIconButton = forwardRef<HTMLButtonElement, Omit<ButtonProps, 'variant'> & { variant?: IconButtonVariant, icon: IconName, label: string, hint?: string, shortcut?: string }>(function PmIconButton({ variant = 'default', icon, label, hint, shortcut, small, density = 'compact', loading, className, disabled, ...rest }, ref) {
37
52
  const button = h('button', { ...rest, ref, type: 'button', 'data-density': density, 'aria-label': label, 'aria-busy': loading || undefined, disabled: disabled || loading || rest['aria-disabled'] === true || rest['aria-disabled'] === 'true', className: cls('pm-ui-icon-button', variant !== 'default' && `pm-ui-icon-button--${variant}`, className) }, h(PmIcon, { name: loading ? 'loading' : icon, className: loading ? 'pm-ui-loading' : undefined }))
38
53
  return h(PmTooltip, { label: hint ?? label, shortcut, children: button })
39
54
  })
@@ -112,7 +127,14 @@ export function PmTabs({ value, modelValue, tabs, label, children, onValueChange
112
127
  })), children)
113
128
  }
114
129
  export function PmTabPanel({ value, children, forceMount, hidden }: { value: string, children?: ReactNode, forceMount?: true, hidden?: boolean }) { return h(Tabs.Content, { value, forceMount, hidden, className: 'pm-ui-tab-panel' }, children) }
115
- export function PmNotice({ tone = 'neutral', children, className, ...rest }: HTMLAttributes<HTMLDivElement> & { tone?: Tone }) { return h('div', { ...rest, className: cls('pm-ui-notice', tone !== 'neutral' && `pm-ui-notice--${tone}`, className), role: tone === 'danger' ? 'alert' : 'status' }, children) }
130
+ const NOTICE_ICONS: Record<Tone, IconName> = { neutral: 'info', outline: 'info', accent: 'info', ok: 'check', warn: 'warning', danger: 'warning' }
131
+ /** A tone icon, the message, and an optional action at the end. */
132
+ export function PmNotice({ tone = 'neutral', action, children, className, ...rest }: HTMLAttributes<HTMLDivElement> & { tone?: Tone, action?: ReactNode }) {
133
+ return h('div', { ...rest, className: cls('pm-ui-notice', tone !== 'neutral' && `pm-ui-notice--${tone}`, className), role: tone === 'danger' ? 'alert' : 'status' },
134
+ h('span', { className: 'pm-ui-notice__icon' }, h(PmIcon, { name: NOTICE_ICONS[tone] })),
135
+ h('div', { className: 'pm-ui-notice__message' }, children),
136
+ action ? h('div', { className: 'pm-ui-notice__action' }, action) : null)
137
+ }
116
138
  export function PmEmpty({ title, icon, action, children }: { title?: string, icon?: IconName, action?: ReactNode, children?: ReactNode }) { return h('div', { className: 'pm-ui-empty' }, icon ? h(PmIcon, { name: icon }) : null, title ? h('p', { className: 'pm-ui-empty__title' }, title) : null, children, action) }
117
139
  /** Loading in the shape of the content: `document` headings and paragraphs, `list` rows, `preview` a slide-shaped area. */
118
140
  export function PmSkeleton({ label, shape = 'document' }: { label: string, shape?: 'document' | 'list' | 'preview' }) {
package/src/index.ts CHANGED
@@ -65,7 +65,7 @@ export { PmApprovals } from './approvals.ts'
65
65
  export { claimFirst } from './claim-first.ts'
66
66
  export { createServerClient, pluginRoutePath, provideServer, useServer, serverClient } from './server.ts'
67
67
  export { PmPresenterPanels } from './panels.ts'
68
- export { useStepTime } from './step-clock.ts'
68
+ export { useDrivenStepLength, useStepTime } from './step-clock.ts'
69
69
  export type { StepTimeOptions } from './step-clock.ts'
70
70
  export { StepScope, useBlockStepRange, useStepScope } from './step-scope.ts'
71
71
  export { useSessionSnapshot } from './session.ts'
@@ -76,6 +76,7 @@ export { PmToolbar } from './panels.ts'
76
76
  export { NAVIGATION, OPERATIONS, PAGE_READINESS, PLAYBACK_CONTROL, PRODUCTION_PLAYBACK, STATUS, STEP_CLOCK, SYNC_TRANSPORTS, TIMED_CAPTIONS, TOOLBAR } from './contracts.ts'
77
77
  export type { PageReadiness, TimedCaptions } from './contracts.ts'
78
78
  export { joinWindows } from './windows.ts'
79
+ export { useAudienceControl, useAudienceRemote } from './window-control.ts'
79
80
  export { setSiteBase, siteBase } from './site.ts'
80
81
  export type { WindowChannel } from './windows.ts'
81
82
  export type {
package/src/messages.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { zhSpaced } from '@lincyaw/kernel'
1
2
  import type { PluginStatus } from '@lincyaw/kernel/contracts'
2
3
  import type { Catalog } from './locale.ts'
3
4
 
@@ -31,7 +32,7 @@ export const HOST_MESSAGES: Catalog<HostMessages> = {
31
32
  status: { started: '已启动', degraded: '部分可用', disabled: '已禁用', failed: '启动失败' },
32
33
  because: ':',
33
34
  unnamedPlugin: '其他插件',
34
- componentError: (component, message) => `${component} 出错:${message}`,
35
+ componentError: (component, message) => zhSpaced`${component}出错:${message}`,
35
36
  problems: count => `${count} 个问题`,
36
37
  approvals: count => `待确认 ${count}`,
37
38
  approvalsTitle: '待确认的操作',
package/src/registries.ts CHANGED
@@ -6,12 +6,12 @@ import type { PageReadiness, StatusProvider, StatusRegistry, TimedCaptions, Tool
6
6
  import { createStore } from './store.ts'
7
7
 
8
8
  export function createTimedCaptions(): TimedCaptions {
9
- const owners = new Set<symbol>(), active = createStore(false)
10
- return { active, claim() {
9
+ const owners = new Set<symbol>(), active = createStore(false), shown = createStore(false)
10
+ return { active, shown, claim() {
11
11
  const owner = Symbol()
12
12
  owners.add(owner); active.set(true)
13
13
  return () => { if (owners.delete(owner)) active.set(owners.size > 0) }
14
- } }
14
+ }, show(on) { shown.set(on) } }
15
15
  }
16
16
 
17
17
  export function createPageReadiness(): PageReadiness {
package/src/server.ts CHANGED
@@ -23,10 +23,16 @@ export function createServerClient(options: { document?: string, root?: string,
23
23
  const root = (options.root ?? '/').replace(/\/?$/, '/')
24
24
  const member = createStore<Member | undefined>(undefined)
25
25
  const url = (plugin: string, path: string) => `${root}__presmium/${plugin}/${path.replace(/^\//, '')}`
26
+ const resourceURL = (plugin: string, path: string) => {
27
+ const target = url(plugin, path)
28
+ // After query parsing, the server decodes this selector just like the document header.
29
+ return `${target}${target.includes('?') ? '&' : '?'}document=${encodeURIComponent(documentHeader(document))}`
30
+ }
26
31
  const client: ServerClient = {
27
32
  available: true, member,
33
+ resourceURL,
28
34
  fetch(plugin, path, init = {}) { const headers = new Headers(init.headers); headers.set('Presmium-Document', documentHeader(document)); if (!headers.has('Accept-Language')) headers.set('Accept-Language', currentLocale()); return fetch(url(plugin, path), { ...init, headers }) },
29
- events(plugin, path) { const target = url(plugin, path); return new EventSource(`${target}${target.includes('?') ? '&' : '?'}document=${documentHeader(document)}`) },
35
+ events(plugin, path) { return new EventSource(resourceURL(plugin, path)) },
30
36
  }
31
37
  void fetch(`${root}${SERVER_PATH.slice(1)}/hello`, { headers: { 'Presmium-Document': documentHeader(document) } }).then(response => response.ok ? response.json() : undefined).then((hello: { member?: Member } | undefined) => member.set(hello?.member)).catch(() => undefined)
32
38
  documents.set(client, document)
package/src/step-clock.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { useEffect, useRef } from 'react'
1
+ import { useEffect, useRef, useSyncExternalStore } from 'react'
2
2
  import type { Unsubscribe } from '@lincyaw/kernel/contracts'
3
3
  import type { Navigation, NavigationPosition, StepClock, StepClockDriver } from './contracts.ts'
4
4
  import { useHost, usePrefersReducedMotion } from './host.ts'
@@ -16,22 +16,51 @@ function isForward(to: NavigationPosition, from: StepChange | undefined) { retur
16
16
  const nextFrame = () => new Promise<void>(done => typeof requestAnimationFrame === 'undefined' ? setTimeout(done, 0) : requestAnimationFrame(() => done()))
17
17
  function handOff(elapsed: number) { const at = change.getSnapshot(); if (at) change.set({ ...at, at: clockNow() - elapsed, forward: true }); ensureTicking() }
18
18
  export function createStepClock(navigation: Navigation): { clock: StepClock, stop: Unsubscribe } {
19
- const pending = new Set<Promise<unknown>>()
20
- let failure: { error: unknown } | undefined
19
+ const pending = new Map<Promise<unknown>, number | undefined>()
20
+ const preparations = new Map<number, Set<() => void | Promise<void>>>()
21
+ const failures = new Map<number | undefined, unknown>()
21
22
  let stopped = false
22
- const rethrow = () => { const failed = failure; failure = undefined; if (failed) throw failed.error }
23
+ const matches = (slide: number | undefined, slides?: readonly number[]) => slide === undefined || slides === undefined || slides.includes(slide)
24
+ const rethrow = (slides?: readonly number[]) => { for (const [slide, error] of failures) if (matches(slide, slides)) { failures.delete(slide); throw error } }
23
25
  const stop = observe(navigation.position, position => { const before = change.getSnapshot(); if (before && before.slide === position.slide && before.step === position.step) return; change.set({ slide: position.slide, step: position.step, at: clockNow(), forward: isForward(position, before) }); ensureTicking() }, true)
24
26
  let unfollow: Unsubscribe | undefined
27
+ // A driver that comes while an exclusive one holds the clock waits for it, the latest one only.
28
+ let waiting: StepClockDriver | undefined
29
+ const activate = (next: StepClockDriver) => { unfollow?.(); driver.set(next); unfollow = observe(next.elapsed, (now, before) => { if (now === undefined && before !== undefined) handOff(before) }) }
25
30
  const clock: StepClock = {
26
31
  drive(next) {
27
- unfollow?.(); driver.set(next)
28
- unfollow = observe(next.elapsed, (now, before) => { if (now === undefined && before !== undefined) handOff(before) })
29
- return () => { if (driver.getSnapshot() !== next) return; const last = next.elapsed.getSnapshot(); unfollow?.(); unfollow = undefined; driver.set(undefined); if (last !== undefined) handOff(last) }
32
+ if (driver.getSnapshot()?.exclusive && !next.exclusive) waiting = next
33
+ else activate(next)
34
+ return () => {
35
+ if (waiting === next) { waiting = undefined; return }
36
+ if (driver.getSnapshot() !== next) return
37
+ const last = next.elapsed.getSnapshot(); unfollow?.(); unfollow = undefined; driver.set(undefined)
38
+ if (waiting) { const held = waiting; waiting = undefined; activate(held) } else if (last !== undefined) handOff(last)
39
+ }
40
+ },
41
+ wait(work, slide) { if (!stopped) pending.set(work, slide); void work.catch(error => { if (!stopped && !failures.has(slide)) failures.set(slide, error) }).finally(() => pending.delete(work)) },
42
+ registerPreparation(slide, prepare) {
43
+ const callbacks = preparations.get(slide) ?? new Set()
44
+ preparations.set(slide, callbacks); callbacks.add(prepare)
45
+ return () => { callbacks.delete(prepare); if (!callbacks.size) preparations.delete(slide) }
46
+ },
47
+ async prepare(slides, options) {
48
+ for (const slide of new Set(slides)) for (const prepare of preparations.get(slide) ?? []) clock.wait(Promise.resolve().then(prepare), slide)
49
+ await nextFrame()
50
+ if (options?.wait !== false) await clock.settled(slides)
51
+ },
52
+ async settled(slides) {
53
+ const own = () => [...pending].filter(([, slide]) => matches(slide, slides)).map(([work]) => work)
54
+ let waited = false
55
+ for (let round = 0; round < 100; round++) {
56
+ if (stopped) return
57
+ if (!own().length) { if (waited) { waited = false; await nextFrame() } if (!own().length) return rethrow(slides) }
58
+ await Promise.allSettled(own()); waited = true
59
+ }
60
+ throw new Error('the page kept preparing its picture: settled() stopped waiting after 100 rounds')
30
61
  },
31
- wait(work) { if (!stopped) pending.add(work); void work.catch(error => { if (!stopped) failure ??= { error } }).finally(() => pending.delete(work)) },
32
- async settled() { let waited = false; for (let round = 0; round < 100; round++) { if (stopped) return; if (!pending.size) { if (waited) { waited = false; await nextFrame() } if (!pending.size) return rethrow() } await Promise.allSettled([...pending]); waited = true } throw new Error('the page kept preparing its picture: settled() stopped waiting after 100 rounds') },
33
62
  }
34
- return { clock, stop() { if (stopped) return; stopped = true; stop(); unfollow?.(); driver.set(undefined); change.set(undefined); pending.clear(); failure = undefined } }
63
+ return { clock, stop() { if (stopped) return; stopped = true; stop(); unfollow?.(); waiting = undefined; driver.set(undefined); change.set(undefined); pending.clear(); preparations.clear(); failures.clear() } }
35
64
  }
36
65
  export interface StepTimeOptions { until?: number }
37
66
  const settle = (time: number, until: number | undefined) => until !== undefined && time >= until ? Infinity : Math.max(0, time)
@@ -47,3 +76,10 @@ export function useStepTime(options: StepTimeOptions = {}): number {
47
76
  useEffect(() => { const running = () => Number.isFinite(renderedTime.current) && driver.getSnapshot()?.elapsed.getSnapshot() === undefined; live.add(running); ensureTicking(); return () => { live.delete(running) } }, [step, cursor.slide, player, options.until, reduced])
48
77
  return time
49
78
  }
79
+ const unobserved = () => () => {}
80
+ /** While the driver of the clock paces the steps it plays (a narrated lecture), the length it gives a step: `StepClockDriver.stepLength`. */
81
+ export function useDrivenStepLength(): StepClockDriver['stepLength'] {
82
+ const player = useStore(driver)
83
+ const playing = () => player?.elapsed.getSnapshot() !== undefined
84
+ return useSyncExternalStore(player?.elapsed.subscribe ?? unobserved, playing, playing) ? player?.stepLength : undefined
85
+ }
@@ -0,0 +1,50 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react'
2
+ import { joinWindows } from './windows.ts'
3
+ import type { WindowChannel } from './windows.ts'
4
+
5
+ type Message = { state: unknown } | { command: string }
6
+
7
+ const isMessage = (value: unknown): value is Message => typeof value === 'object' && value !== null && ('state' in value || typeof (value as { command?: unknown }).command === 'string')
8
+
9
+ /**
10
+ * A control of the audience's window that another window of the same presentation drives (the presenter view): the
11
+ * audience tells the control's state (`undefined` while it offers none) through the windows' channel and runs the
12
+ * commands it receives. A window that joins later is told the current state.
13
+ */
14
+ export function useAudienceControl<S>(name: string, state: S | undefined, run: (command: string) => void): void {
15
+ const latest = useRef({ state, run })
16
+ latest.current = { state, run }
17
+ const channel = useRef<WindowChannel | undefined>(undefined)
18
+ useEffect(() => {
19
+ const windows = joinWindows(name, value => {
20
+ if (isMessage(value) && 'command' in value && latest.current.state !== undefined) latest.current.run(value.command)
21
+ }, () => ({ state: latest.current.state ?? null }))
22
+ channel.current = windows
23
+ return () => {
24
+ windows?.send({ state: null })
25
+ windows?.close()
26
+ channel.current = undefined
27
+ }
28
+ }, [name])
29
+ const shown = JSON.stringify(state ?? null)
30
+ useEffect(() => { channel.current?.send({ state: state ?? null }) }, [name, shown])
31
+ }
32
+
33
+ /** The other side of `useAudienceControl`: the state the audience tells, and the way to send it a command. */
34
+ export function useAudienceRemote<S>(name: string): [S | undefined, (command: string) => void] {
35
+ const [state, setState] = useState<S | undefined>(undefined)
36
+ const channel = useRef<WindowChannel | undefined>(undefined)
37
+ useEffect(() => {
38
+ const windows = joinWindows(name, value => {
39
+ if (isMessage(value) && 'state' in value) setState((value.state ?? undefined) as S | undefined)
40
+ }, () => undefined)
41
+ channel.current = windows
42
+ return () => {
43
+ windows?.close()
44
+ channel.current = undefined
45
+ setState(undefined)
46
+ }
47
+ }, [name])
48
+ const send = useCallback((command: string) => { channel.current?.send({ command }) }, [])
49
+ return [state, send]
50
+ }