@lincyaw/host 1.0.0-rc.13 → 1.0.0-rc.131

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.13",
3
+ "version": "1.0.0-rc.131",
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": {
@@ -16,6 +16,9 @@
16
16
  "design-system"
17
17
  ],
18
18
  "type": "module",
19
+ "sideEffects": [
20
+ "*.css"
21
+ ],
19
22
  "engines": {
20
23
  "node": ">=22.19"
21
24
  },
@@ -30,6 +33,7 @@
30
33
  "src"
31
34
  ],
32
35
  "dependencies": {
36
+ "@fontsource-variable/hanken-grotesk": "5.3.0",
33
37
  "@fontsource/ibm-plex-mono": "5.3.0",
34
38
  "@fontsource/ibm-plex-sans": "5.3.0",
35
39
  "@fontsource/source-serif-4": "5.3.1",
@@ -41,8 +45,8 @@
41
45
  "@radix-ui/react-tooltip": "^1.2.8",
42
46
  "react": "18.3.1",
43
47
  "react-dom": "18.3.1",
44
- "@lincyaw/design": "1.0.0-rc.13",
45
- "@lincyaw/kernel": "1.0.0-rc.13"
48
+ "@lincyaw/design": "1.0.0-rc.131",
49
+ "@lincyaw/kernel": "1.0.0-rc.131"
46
50
  },
47
51
  "devDependencies": {
48
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,22 +138,48 @@ 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
 
153
+ /**
154
+ * A component that draws asynchronously (a scene loading its code) holds the page as not yet drawn until it has: the
155
+ * viewer tells an embedding page when the current slide is drawn (`notifyEmbedder`).
156
+ */
157
+ export interface PageReadiness {
158
+ readonly pending: Store<number>
159
+ hold(): Unsubscribe
160
+ }
161
+ export const PAGE_READINESS = defineService<PageReadiness>('presmium.pageReadiness')
162
+
146
163
  export interface StepClockDriver {
147
164
  readonly elapsed: Store<number | undefined>
148
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
149
173
  }
150
174
 
151
175
  export interface StepClock {
152
176
  drive(driver: StepClockDriver): Unsubscribe
153
- wait(work: Promise<unknown>): void
154
- 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
155
183
  }
156
184
 
157
185
  export const STEP_CLOCK = defineService<StepClock>('presmium.stepClock')
@@ -1,40 +1,55 @@
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'
5
- import * as Dropdown from '@radix-ui/react-dropdown-menu'
6
5
  import * as Tabs from '@radix-ui/react-tabs'
7
6
  import * as Tooltip from '@radix-ui/react-tooltip'
8
- import * as RadioGroup from '@radix-ui/react-radio-group'
9
7
  import { useLocale } from '../locale.ts'
10
8
  import { HOST_MESSAGES } from '../messages.ts'
11
9
  import { ICONS } from '@lincyaw/design'
12
10
  import type { IconName } from '@lincyaw/design'
13
11
  import type { ToolbarPlacement } from '../contracts.ts'
14
- export type ButtonVariant = 'default' | 'primary' | 'accent' | 'ghost' | 'danger'
12
+ export type ButtonVariant = 'default' | 'primary' | 'ghost' | 'text' | 'danger'
15
13
  export type ControlDensity = 'compact' | 'regular' | 'touch'
14
+ /** `overlay`: one large round control laid over media, such as the Play that starts a lecture the browser would not autoplay. */
15
+ export type IconButtonVariant = 'default' | 'overlay'
16
16
  export type Tone = 'neutral' | 'accent' | 'ok' | 'warn' | 'danger' | 'outline'
17
17
  export type PopoverPlacement = 'below-end' | 'below-start' | 'above-end' | 'above-start' | 'above' | 'below'
18
18
  export interface Choice { value: string, label: string, icon?: IconName, disabled?: boolean }
19
19
  export interface MenuItem { id: string, label: string, icon?: IconName, danger?: boolean, disabled?: boolean, shortcut?: string, checked?: boolean, separator?: boolean }
20
- const cls = (...values: (string | false | undefined)[]) => values.filter(Boolean).join(' ')
20
+ export const cls = (...values: (string | false | undefined)[]) => values.filter(Boolean).join(' ')
21
21
  export function PmIcon({ name, size: _size, strokeWidth = 1.7, ...attrs }: { name: IconName, size?: number | string, strokeWidth?: number } & HTMLAttributes<SVGElement>) {
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, ButtonProps & { icon: IconName, label: string, hint?: string, shortcut?: string }>(function PmIconButton({ icon, label, hint, shortcut, small, density = small ? 'compact' : 'regular', loading, className, disabled, ...rest }, ref) {
37
- 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', className) }, h(PmIcon, { name: loading ? 'loading' : icon, className: loading ? 'pm-ui-loading' : undefined }))
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) {
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
  })
40
55
  export function PmBadge({ tone = 'neutral', pill, children, className, ...rest }: HTMLAttributes<HTMLSpanElement> & { tone?: Tone, pill?: boolean }) { return h('span', { ...rest, className: cls('pm-ui-badge', tone !== 'neutral' && `pm-ui-badge--${tone}`, pill && 'pm-ui-badge--pill', className) }, children) }
@@ -102,18 +117,8 @@ function DialogSurface({ open, label, closeLabel, name, children, actions, trigg
102
117
  }
103
118
  export function PmDialog(props: OverlayProps) { return h(DialogSurface, props) }
104
119
  export function PmDrawer(props: OverlayProps) { return h(DialogSurface, { ...props, drawer: true }) }
105
- const placement = (value: PopoverPlacement) => ({ side: value.startsWith('above') ? 'top' as const : 'bottom' as const, align: value.endsWith('start') ? 'start' as const : 'end' as const })
120
+ export const placement = (value: PopoverPlacement) => ({ side: value.startsWith('above') ? 'top' as const : 'bottom' as const, align: value.endsWith('start') ? 'start' as const : 'end' as const })
106
121
  export function PmPopover({ open, label, name, children, trigger, placement: place = 'below-end', onOpenChange }: OverlayProps & { placement?: PopoverPlacement }) { return h(Popover.Root, { open, onOpenChange }, trigger ? h(Popover.Trigger, { asChild: true }, trigger) : null, h(Popover.Portal, {}, h(Popover.Content, { ...placement(place), className: cls('pm-ui-popover pm-ui-floating pm-ui', name), 'aria-label': label, onEscapeKeyDown: event => event.stopPropagation() }, children))) }
107
- export function PmMenu({ label, items, icon = 'more', placement: place = 'below-end', onSelect }: { label: string, items: MenuItem[], icon?: IconName, placement?: PopoverPlacement, onSelect?(id: string): void }) {
108
- return h(Dropdown.Root, {},
109
- h(Dropdown.Trigger, { asChild: true }, h(PmIconButton, { icon, label, small: true })),
110
- h(Dropdown.Portal, {}, h(Dropdown.Content, { ...placement(place), className: 'pm-ui-menu pm-ui-floating pm-ui', ...{ 'data-density': 'compact' }, 'aria-label': label, onEscapeKeyDown: event => event.stopPropagation() },
111
- items.map(item => h(Dropdown.Group, { key: item.id }, item.separator ? h(Dropdown.Separator, { className: 'pm-ui-menu__separator' }) : null,
112
- item.checked === undefined ? h(Dropdown.Item, { disabled: item.disabled, textValue: item.label, className: cls('pm-ui-menu__item', item.danger && 'pm-ui-menu__item--danger'), onSelect: () => onSelect?.(item.id) },
113
- item.icon ? h(PmIcon, { name: item.icon }) : null, item.label, item.shortcut ? h('kbd', { className: 'pm-ui-shortcut' }, item.shortcut) : null)
114
- : h(Dropdown.CheckboxItem, { checked: item.checked, disabled: item.disabled, textValue: item.label, className: cls('pm-ui-menu__item', item.danger && 'pm-ui-menu__item--danger'), onSelect: () => onSelect?.(item.id) },
115
- h(Dropdown.ItemIndicator, {}, h(PmIcon, { name: 'check' })), item.label))))))
116
- }
117
122
  export function PmTabs({ value, modelValue, tabs, label, children, onValueChange, iconOnly, density = 'compact' }: { value?: string, modelValue?: string, tabs: Choice[], label: string, children?: ReactNode, iconOnly?: boolean, density?: ControlDensity, onValueChange?(value: string): void }) {
118
123
  return h(Tabs.Root, { value: value ?? modelValue, onValueChange, activationMode: 'manual', className: 'pm-ui-tabs-root', ...{ 'data-density': density } },
119
124
  h(Tabs.List, { className: 'pm-ui-tabs', 'aria-label': label }, tabs.map(tab => {
@@ -122,11 +127,14 @@ export function PmTabs({ value, modelValue, tabs, label, children, onValueChange
122
127
  })), children)
123
128
  }
124
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) }
125
- export function PmSegmented({ value, modelValue, choices, items, label, onValueChange, density = 'compact', disabled }: { value?: string, modelValue?: string, choices?: Choice[], items?: Choice[], label: string, density?: ControlDensity, disabled?: boolean, onValueChange?(value: string): void }) {
126
- return h(RadioGroup.Root, { className: 'pm-ui-segmented', 'aria-label': label, value: value ?? modelValue, onValueChange, orientation: 'horizontal', ...{ 'data-density': density }, disabled },
127
- (choices ?? items ?? []).map(item => h(RadioGroup.Item, { key: item.value, value: item.value, className: 'pm-ui-segmented__option', disabled: item.disabled }, item.icon ? h(PmIcon, { name: item.icon }) : null, item.label)))
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)
128
137
  }
129
- 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
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) }
131
139
  /** Loading in the shape of the content: `document` headings and paragraphs, `list` rows, `preview` a slide-shaped area. */
132
140
  export function PmSkeleton({ label, shape = 'document' }: { label: string, shape?: 'document' | 'list' | 'preview' }) {
@@ -0,0 +1,18 @@
1
+ import { createElement as h } from 'react'
2
+ import * as Dropdown from '@radix-ui/react-dropdown-menu'
3
+ import type { IconName } from '@lincyaw/design'
4
+ import { cls, placement, PmIcon, PmIconButton } from './components.ts'
5
+ import type { MenuItem, PopoverPlacement } from './components.ts'
6
+
7
+ // A module of its own, as `segmented.ts` is: a page whose code shows no menu loads none of Radix's menus.
8
+
9
+ export function PmMenu({ label, items, icon = 'more', placement: place = 'below-end', onSelect }: { label: string, items: MenuItem[], icon?: IconName, placement?: PopoverPlacement, onSelect?(id: string): void }) {
10
+ return h(Dropdown.Root, {},
11
+ h(Dropdown.Trigger, { asChild: true }, h(PmIconButton, { icon, label, small: true })),
12
+ h(Dropdown.Portal, {}, h(Dropdown.Content, { ...placement(place), className: 'pm-ui-menu pm-ui-floating pm-ui', ...{ 'data-density': 'compact' }, 'aria-label': label, onEscapeKeyDown: event => event.stopPropagation() },
13
+ items.map(item => h(Dropdown.Group, { key: item.id }, item.separator ? h(Dropdown.Separator, { className: 'pm-ui-menu__separator' }) : null,
14
+ item.checked === undefined ? h(Dropdown.Item, { disabled: item.disabled, textValue: item.label, className: cls('pm-ui-menu__item', item.danger && 'pm-ui-menu__item--danger'), onSelect: () => onSelect?.(item.id) },
15
+ item.icon ? h(PmIcon, { name: item.icon }) : null, item.label, item.shortcut ? h('kbd', { className: 'pm-ui-shortcut' }, item.shortcut) : null)
16
+ : h(Dropdown.CheckboxItem, { checked: item.checked, disabled: item.disabled, textValue: item.label, className: cls('pm-ui-menu__item', item.danger && 'pm-ui-menu__item--danger'), onSelect: () => onSelect?.(item.id) },
17
+ h(Dropdown.ItemIndicator, {}, h(PmIcon, { name: 'check' })), item.label))))))
18
+ }
@@ -0,0 +1,11 @@
1
+ import { createElement as h } from 'react'
2
+ import * as RadioGroup from '@radix-ui/react-radio-group'
3
+ import { PmIcon } from './components.ts'
4
+ import type { Choice, ControlDensity } from './components.ts'
5
+
6
+ // A module of its own, as `menu.ts` is: a page whose code shows no segmented control loads none of Radix's radio group.
7
+
8
+ export function PmSegmented({ value, modelValue, choices, items, label, onValueChange, density = 'compact', disabled }: { value?: string, modelValue?: string, choices?: Choice[], items?: Choice[], label: string, density?: ControlDensity, disabled?: boolean, onValueChange?(value: string): void }) {
9
+ return h(RadioGroup.Root, { className: 'pm-ui-segmented', 'aria-label': label, value: value ?? modelValue, onValueChange, orientation: 'horizontal', ...{ 'data-density': density }, disabled },
10
+ (choices ?? items ?? []).map(item => h(RadioGroup.Item, { key: item.value, value: item.value, className: 'pm-ui-segmented__option', disabled: item.disabled }, item.icon ? h(PmIcon, { name: item.icon }) : null, item.label)))
11
+ }
package/src/index.ts CHANGED
@@ -18,10 +18,8 @@ export {
18
18
  PmField,
19
19
  PmIcon,
20
20
  PmIconButton,
21
- PmMenu,
22
21
  PmNotice,
23
22
  PmPopover,
24
- PmSegmented,
25
23
  PmTabs,
26
24
  PmTabPanel,
27
25
  PmTooltip,
@@ -29,7 +27,9 @@ export {
29
27
  provideToolbarPlacement,
30
28
  useToolbarPlacement,
31
29
  } from './design/components.ts'
32
- export type { ButtonVariant, Choice, ControlDensity, MenuItem, PopoverPlacement, Tone } from './design/components.ts'
30
+ export type { ButtonVariant, Choice, ControlDensity, IconButtonVariant, MenuItem, PopoverPlacement, Tone } from './design/components.ts'
31
+ export { PmMenu } from './design/menu.ts'
32
+ export { PmSegmented } from './design/segmented.ts'
33
33
  export { PmColumns, PmStack, PmTabGroup } from './design/layout.ts'
34
34
  export { PmCaption, PmCaptionProvider } from './design/caption.ts'
35
35
  export type { CaptionProps } from './design/caption.ts'
@@ -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'
@@ -73,9 +73,10 @@ export type { StepScope as StepScopeValue } from './step-scope.ts'
73
73
  export { createSharedStates } from './shared-state.ts'
74
74
  export type { SharedStates } from './shared-state.ts'
75
75
  export { PmToolbar } from './panels.ts'
76
- export { NAVIGATION, OPERATIONS, PLAYBACK_CONTROL, PRODUCTION_PLAYBACK, STATUS, STEP_CLOCK, SYNC_TRANSPORTS, TIMED_CAPTIONS, TOOLBAR } from './contracts.ts'
77
- export type { TimedCaptions } from './contracts.ts'
76
+ export { NAVIGATION, OPERATIONS, PAGE_READINESS, PLAYBACK_CONTROL, PRODUCTION_PLAYBACK, STATUS, STEP_CLOCK, SYNC_TRANSPORTS, TIMED_CAPTIONS, TOOLBAR } from './contracts.ts'
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
@@ -2,15 +2,24 @@ import type { PresenterPanel, PresenterPanels, Unsubscribe } from '@lincyaw/kern
2
2
  import { currentLocale } from './locale.ts'
3
3
  import { HOST_MESSAGES } from './messages.ts'
4
4
  import StartReportPanel from './start-report-panel.ts'
5
- import type { StatusProvider, StatusRegistry, TimedCaptions, Toolbar, ToolbarItem } from './contracts.ts'
5
+ import type { PageReadiness, StatusProvider, StatusRegistry, TimedCaptions, Toolbar, ToolbarItem } from './contracts.ts'
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
+ }, show(on) { shown.set(on) } }
15
+ }
16
+
17
+ export function createPageReadiness(): PageReadiness {
18
+ const holders = new Set<symbol>(), pending = createStore(0)
19
+ return { pending, hold() {
20
+ const holder = Symbol()
21
+ holders.add(holder); pending.set(holders.size)
22
+ return () => { if (holders.delete(holder)) pending.set(holders.size) }
14
23
  } }
15
24
  }
16
25
 
package/src/runtime.ts CHANGED
@@ -3,7 +3,7 @@ import type { EnvironmentSpec, Logger, PluginDefinition, PluginReport, Presentat
3
3
  import { createStore } from './store.ts'
4
4
  import { connectActions } from './actions.ts'
5
5
  import { PmApprovals } from './approvals.ts'
6
- import { NAVIGATION, OPERATIONS, PLAYBACK_CONTROL, STATUS, STEP_CLOCK, SYNC_TRANSPORTS, TIMED_CAPTIONS, TOOLBAR } from './contracts.ts'
6
+ import { NAVIGATION, OPERATIONS, PAGE_READINESS, PLAYBACK_CONTROL, STATUS, STEP_CLOCK, SYNC_TRANSPORTS, TIMED_CAPTIONS, TOOLBAR } from './contracts.ts'
7
7
  import type { Navigation, ServerClient, SyncTransports } from './contracts.ts'
8
8
  import { connectControl } from './control.ts'
9
9
  import { componentErrors } from './error-boundary.ts'
@@ -11,7 +11,7 @@ import { currentLocale } from './locale.ts'
11
11
  import { HOST_MESSAGES } from './messages.ts'
12
12
  import { createOperations } from './operations.ts'
13
13
  import { createPlaybackControl } from './playback-control.ts'
14
- import { createPresenterPanels, createStatusRegistry, createTimedCaptions, createToolbar } from './registries.ts'
14
+ import { createPageReadiness, createPresenterPanels, createStatusRegistry, createTimedCaptions, createToolbar } from './registries.ts'
15
15
  import { provideServer } from './server.ts'
16
16
  import { createStepClock } from './step-clock.ts'
17
17
 
@@ -156,6 +156,7 @@ export function startHost(options: HostStart): Promise<StartReport> {
156
156
  kernel.provide(OPERATIONS, operations)
157
157
  kernel.provide(PLAYBACK_CONTROL, createPlaybackControl())
158
158
  kernel.provide(TIMED_CAPTIONS, createTimedCaptions())
159
+ kernel.provide(PAGE_READINESS, createPageReadiness())
159
160
  const stepClock = createStepClock(options.navigation)
160
161
  release(stepClock.stop)
161
162
  kernel.provide(STEP_CLOCK, stepClock.clock)
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
+ }