@botiverse/porthole 0.2.4 → 0.3.1

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.
Files changed (85) hide show
  1. package/README.md +17 -11
  2. package/dist/check/check.d.ts +100 -0
  3. package/dist/check/check.js +247 -0
  4. package/dist/check/drivers.d.ts +43 -0
  5. package/dist/check/drivers.js +181 -0
  6. package/dist/check/index.d.ts +8 -0
  7. package/dist/check/index.js +8 -0
  8. package/dist/check/instrument.d.ts +71 -0
  9. package/dist/check/instrument.js +84 -0
  10. package/dist/check/lint.d.ts +21 -0
  11. package/dist/check/lint.js +131 -0
  12. package/dist/check/page-source.d.ts +2 -0
  13. package/dist/check/page-source.js +2 -0
  14. package/dist/check/page.d.ts +13 -0
  15. package/dist/check/page.js +170 -0
  16. package/dist/check/tools.d.ts +61 -0
  17. package/dist/check/tools.js +140 -0
  18. package/dist/conformance/host-kit.d.ts +26 -5
  19. package/dist/conformance/host-kit.js +46 -22
  20. package/dist/conformance/index.d.ts +1 -1
  21. package/dist/conformance/reporter.d.ts +14 -0
  22. package/dist/conformance/reporter.js +28 -0
  23. package/dist/displays/displays.d.ts +61 -0
  24. package/dist/displays/displays.js +113 -0
  25. package/dist/host/client.d.ts +110 -0
  26. package/dist/host/client.js +274 -0
  27. package/dist/index.d.ts +4 -0
  28. package/dist/index.js +6 -0
  29. package/dist/node/index.d.ts +26 -1
  30. package/dist/node/index.js +91 -1
  31. package/dist/react/frame.d.ts +79 -3
  32. package/dist/react/frame.js +183 -42
  33. package/dist/react/index.d.ts +2 -1
  34. package/dist/react/index.js +1 -0
  35. package/dist/react/view.d.ts +54 -0
  36. package/dist/react/view.js +151 -0
  37. package/dist/server/bootstrap.d.ts +27 -0
  38. package/dist/server/bootstrap.js +63 -0
  39. package/dist/server/host.d.ts +77 -8
  40. package/dist/server/host.js +268 -11
  41. package/dist/server/index.d.ts +4 -2
  42. package/dist/server/index.js +3 -1
  43. package/dist/server/pages.d.ts +19 -0
  44. package/dist/server/pages.js +8 -0
  45. package/dist/server/proxy.d.ts +24 -0
  46. package/dist/server/proxy.js +67 -0
  47. package/dist/server/server.js +14 -1
  48. package/dist/server/types.d.ts +8 -0
  49. package/docs/ADOPTING.md +278 -108
  50. package/docs/DECISIONS.md +280 -0
  51. package/docs/DESIGN.md +84 -2
  52. package/examples/app.mjs +82 -78
  53. package/examples/conformance/page.spec.mjs +23 -0
  54. package/examples/conformance/playwright.config.mjs +3 -2
  55. package/examples/conformance/porthole.spec.mjs +6 -3
  56. package/examples/displays.mjs +21 -0
  57. package/examples/mcp/server.mjs +121 -0
  58. package/examples/node/server.mjs +16 -34
  59. package/examples/workers/worker.mjs +19 -7
  60. package/package.json +13 -1
  61. package/src/check/check.ts +386 -0
  62. package/src/check/drivers.ts +242 -0
  63. package/src/check/index.ts +22 -0
  64. package/src/check/instrument.ts +138 -0
  65. package/src/check/lint.ts +238 -0
  66. package/src/check/page-source.ts +19 -0
  67. package/src/check/page.ts +230 -0
  68. package/src/check/tools.ts +206 -0
  69. package/src/conformance/host-kit.ts +82 -27
  70. package/src/conformance/index.ts +1 -0
  71. package/src/conformance/reporter.ts +38 -0
  72. package/src/displays/displays.ts +191 -0
  73. package/src/host/client.ts +395 -0
  74. package/src/index.ts +25 -0
  75. package/src/node/index.ts +112 -2
  76. package/src/react/frame.tsx +271 -57
  77. package/src/react/index.ts +9 -0
  78. package/src/react/view.tsx +237 -0
  79. package/src/server/bootstrap.ts +97 -0
  80. package/src/server/host.ts +372 -18
  81. package/src/server/index.ts +11 -1
  82. package/src/server/pages.ts +28 -0
  83. package/src/server/proxy.ts +86 -0
  84. package/src/server/server.ts +26 -2
  85. package/src/server/types.ts +5 -0
@@ -34,6 +34,7 @@ import type { InstanceLocator, InstanceRef } from "../isolation/types.ts";
34
34
  import { ConfirmDialog } from "./dialog.tsx";
35
35
  import { createLiveFrames, type FrameState, type LiveFrames } from "./live.ts";
36
36
  import { CopyToast, type CopyNotice } from "./toast.tsx";
37
+ import type { PortholeClient } from "../host/client.ts";
37
38
 
38
39
  /**
39
40
  * The React binding: a `<PortholeProvider>` near the root owns what is per page (which frames
@@ -49,6 +50,14 @@ export const PLACEHOLDER_HEIGHT_PX = 96;
49
50
 
50
51
  interface PageState {
51
52
  readonly live: LiveFrames;
53
+ /** The host kit's client (P072): the locator, configs by kind, links. */
54
+ readonly client?: PortholeClient;
55
+ /** Defaults every frame below takes unless it says its own (P072). */
56
+ readonly scheme?: ColorScheme;
57
+ readonly theme?: (scheme: ColorScheme) => Readonly<Record<string, string | null | undefined>>;
58
+ readonly themeKey?: string | number;
59
+ /** The provider's handlers as of now (its own over the default `openLink`). */
60
+ readonly handlers?: () => CapabilityHandlers;
52
61
  /** Heights displays reported, by display id: a frame mounting again starts at its last. */
53
62
  readonly heights: Map<string, number>;
54
63
  readonly confirm?: Confirm;
@@ -65,7 +74,47 @@ const PAGE: PageState = { live: createLiveFrames(), heights: new Map() };
65
74
 
66
75
  const Page = createContext<PageState>(PAGE);
67
76
 
77
+ /** The provider's page state, for the binding's other components (`PortholeView`). */
78
+ export const PortholeContext = Page;
79
+
68
80
  export interface PortholeProviderProps {
81
+ /**
82
+ * The host kit's client (`portholeClient`, P072): it locates served frames (unless `locator` is
83
+ * given), and `PortholeView` takes each kind's config and link from it.
84
+ */
85
+ readonly client?: PortholeClient;
86
+ /** The color scheme every frame below shows in, unless it says its own. */
87
+ readonly scheme?: ColorScheme;
88
+ /**
89
+ * The host's live values for the theme variables, for every frame below (`cssVariableTheme`
90
+ * reads them from the page's own CSS variables). Change `themeKey` when they change.
91
+ */
92
+ readonly theme?: (scheme: ColorScheme) => Readonly<Record<string, string | null | undefined>>;
93
+ readonly themeKey?: string | number;
94
+ /** Handlers every frame below has, under its own (a frame's own win). */
95
+ readonly handlers?: CapabilityHandlers;
96
+ /**
97
+ * How `openLink` opens a link where a frame has no handler of its own: a desktop app's
98
+ * external browser. Default: a new tab, `noopener`.
99
+ */
100
+ readonly openLink?: (url: string) => void;
101
+ /**
102
+ * Shows what a copy button put on the clipboard, in the app's own toast (the words stay
103
+ * Porthole's: `notice`); `copy` copies it again in a click where the first write failed.
104
+ * Omitted: Porthole's `CopyToast`.
105
+ */
106
+ readonly notify?: (
107
+ notice: CopyNotice,
108
+ actions: { readonly copy: () => Promise<boolean> },
109
+ ) => void;
110
+ /**
111
+ * Draws the confirmation in the app's own dialog, for the request at the head of the queue:
112
+ * Porthole keeps the queue (one question at a time), runs `accept` inside the click, and counts
113
+ * declines. `redirect`: the person took it elsewhere (edited a prompt first, P074): the call
114
+ * doesn't go, and it neither counts toward muting the display nor resets the count. Omitted:
115
+ * Porthole's `ConfirmDialog`. (`confirm` replaces the whole mechanism.)
116
+ */
117
+ readonly renderConfirm?: (request: ConfirmRequest, answer: ConfirmActions) => ReactNode;
69
118
  /**
70
119
  * Who confirms gated calls for every frame below. Omitted: the default dialog (`ConfirmDialog`).
71
120
  * Pass your own function to replace it.
@@ -81,12 +130,37 @@ export interface PortholeProviderProps {
81
130
  readonly toastClassName?: string;
82
131
  /**
83
132
  * The page's CSP nonce, where its `script-src` is nonce-based: opaque frames inherit the page's
84
- * policy, so their shell carries it (P054).
133
+ * policy, so their shell carries it (P054). `"auto"`: read from the page (a `<meta
134
+ * name="csp-nonce">`, else its first script's nonce).
85
135
  */
86
136
  readonly nonce?: string;
87
137
  readonly children?: ReactNode;
88
138
  }
89
139
 
140
+ /** What an app's own confirmation dialog answers with (`renderConfirm`). */
141
+ export interface ConfirmActions {
142
+ /** Yes: the call goes, run inside this click. */
143
+ readonly accept: () => void;
144
+ /** No: the call doesn't go, and it counts toward muting the display. */
145
+ readonly decline: () => void;
146
+ /** Elsewhere (the person edits the prompt first): the call doesn't go, and doesn't count. */
147
+ readonly redirect: () => void;
148
+ }
149
+
150
+ /** The page's own nonce: `<meta name="csp-nonce" content>`, else the first `script[nonce]`'s. */
151
+ function pageNonce(): string | undefined {
152
+ if (typeof document === "undefined") {
153
+ return undefined;
154
+ }
155
+ const meta = document.querySelector<HTMLMetaElement>('meta[name="csp-nonce"]')?.content;
156
+ const script = document.querySelector<HTMLScriptElement>("script[nonce]")?.nonce;
157
+ return meta !== undefined && meta !== ""
158
+ ? meta
159
+ : script !== undefined && script !== ""
160
+ ? script
161
+ : undefined;
162
+ }
163
+
90
164
  interface Pending {
91
165
  readonly request: ConfirmRequest;
92
166
  readonly resolve: (answer: ConfirmAnswer) => void;
@@ -114,9 +188,18 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
114
188
  // The default copyText: the host's page writes the clipboard (in the frame's click, which
115
189
  // activated this page too) and shows the person what went on it, or offers to copy it.
116
190
  const [notice, setNotice] = useState<CopyNotice | null>(null);
191
+ const ownNotify = useRef(props.notify);
192
+ useLayoutEffect(() => {
193
+ ownNotify.current = props.notify;
194
+ });
117
195
  const copyText = useCallback<CapabilityHandler<"copyText">>(async ({ text }, context) => {
118
196
  const copied = await writeClipboard(text, globalThis.document);
119
- setNotice({ text, copied, title: context.title });
197
+ const said = { text, copied, title: context.title };
198
+ if (ownNotify.current === undefined) {
199
+ setNotice(said);
200
+ } else {
201
+ ownNotify.current(said, { copy: () => writeClipboard(text, globalThis.document) });
202
+ }
120
203
  return copied;
121
204
  }, []);
122
205
  const closeNotice = useCallback(() => setNotice(null), []);
@@ -127,15 +210,50 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
127
210
  useLayoutEffect(() => {
128
211
  ownLocator.current = props.locator;
129
212
  });
213
+ const ownClient = useRef(props.client);
214
+ useLayoutEffect(() => {
215
+ ownClient.current = props.client;
216
+ });
130
217
  const locate = useCallback<InstanceLocator["locate"]>(
131
218
  (instance, signal) =>
132
- ownLocator.current === undefined
133
- ? Promise.reject(new Error("No locator (PortholeProvider.locator)"))
134
- : ownLocator.current.locate(instance, signal),
219
+ ownLocator.current !== undefined
220
+ ? ownLocator.current.locate(instance, signal)
221
+ : ownClient.current !== undefined
222
+ ? ownClient.current.locate(instance, signal)
223
+ : Promise.reject(new Error("No locator (PortholeProvider.locator or client)")),
135
224
  [],
136
225
  );
137
- const locates = props.locator !== undefined;
138
- const { nonce } = props;
226
+ const locates = props.locator !== undefined || props.client !== undefined;
227
+ // `"auto"`: the page's own nonce, read once.
228
+ const [autoNonce] = useState(() => (props.nonce === "auto" ? pageNonce() : undefined));
229
+ const nonce = props.nonce === "auto" ? autoNonce : props.nonce;
230
+ const { client, scheme, theme, themeKey } = props;
231
+ // openLink without a frame handler: the provider's, or a new tab.
232
+ const ownOpen = useRef(props.openLink);
233
+ useLayoutEffect(() => {
234
+ ownOpen.current = props.openLink;
235
+ });
236
+ const handlers = useMemo<CapabilityHandlers>(
237
+ () => ({
238
+ openLink: ({ url }) => {
239
+ if (ownOpen.current === undefined) {
240
+ globalThis.open?.(url, "_blank", "noopener");
241
+ } else {
242
+ ownOpen.current(url);
243
+ }
244
+ return true;
245
+ },
246
+ }),
247
+ [],
248
+ );
249
+ const ownHandlers = useRef(props.handlers);
250
+ useLayoutEffect(() => {
251
+ ownHandlers.current = props.handlers;
252
+ });
253
+ const merged = useCallback<() => CapabilityHandlers>(
254
+ () => ({ ...handlers, ...ownHandlers.current }),
255
+ [handlers],
256
+ );
139
257
  const value = useMemo<PageState>(
140
258
  () => ({
141
259
  live,
@@ -145,14 +263,51 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
145
263
  ...(hostInfo === undefined ? {} : { hostInfo }),
146
264
  ...(locates ? { locate } : {}),
147
265
  ...(nonce === undefined ? {} : { nonce }),
266
+ ...(client === undefined ? {} : { client }),
267
+ ...(scheme === undefined ? {} : { scheme }),
268
+ ...(theme === undefined ? {} : { theme }),
269
+ ...(themeKey === undefined ? {} : { themeKey }),
270
+ handlers: merged,
148
271
  }),
149
- [live, heights, confirm, copyText, hostInfo, locates, locate, nonce],
272
+ [
273
+ live,
274
+ heights,
275
+ confirm,
276
+ copyText,
277
+ hostInfo,
278
+ locates,
279
+ locate,
280
+ nonce,
281
+ client,
282
+ scheme,
283
+ theme,
284
+ themeKey,
285
+ merged,
286
+ ],
150
287
  );
151
288
  const current = queue[0] ?? null;
152
289
  return (
153
290
  <Page.Provider value={value}>
154
291
  {props.children}
155
- {props.confirm === undefined ? (
292
+ {props.confirm === undefined && props.renderConfirm !== undefined && current !== null
293
+ ? props.renderConfirm(current.request, {
294
+ accept: () => {
295
+ // Inside the app's own click: the effect is the person's (a window it opens).
296
+ current.proceed();
297
+ current.resolve("accepted");
298
+ setQueue((waiting) => waiting.slice(1));
299
+ },
300
+ decline: () => {
301
+ current.resolve("declined");
302
+ setQueue((waiting) => waiting.slice(1));
303
+ },
304
+ redirect: () => {
305
+ current.resolve("redirected");
306
+ setQueue((waiting) => waiting.slice(1));
307
+ },
308
+ })
309
+ : null}
310
+ {props.confirm === undefined && props.renderConfirm === undefined ? (
156
311
  <ConfirmDialog
157
312
  request={current?.request ?? null}
158
313
  {...(props.dialogClassName === undefined ? {} : { className: props.dialogClassName })}
@@ -166,17 +321,19 @@ export function PortholeProvider(props: PortholeProviderProps): ReactElement {
166
321
  }}
167
322
  />
168
323
  ) : null}
169
- <CopyToast
170
- notice={notice}
171
- {...(props.toastClassName === undefined ? {} : { className: props.toastClassName })}
172
- onClose={closeNotice}
173
- onCopy={(failed) => {
174
- // A click on the host's own page: the write has the gesture it needs now.
175
- void writeClipboard(failed.text, globalThis.document).then((copied) =>
176
- setNotice({ ...failed, copied }),
177
- );
178
- }}
179
- />
324
+ {props.notify !== undefined ? null : (
325
+ <CopyToast
326
+ notice={notice}
327
+ {...(props.toastClassName === undefined ? {} : { className: props.toastClassName })}
328
+ onClose={closeNotice}
329
+ onCopy={(failed) => {
330
+ // A click on the host's own page: the write has the gesture it needs now.
331
+ void writeClipboard(failed.text, globalThis.document).then((copied) =>
332
+ setNotice({ ...failed, copied }),
333
+ );
334
+ }}
335
+ />
336
+ )}
180
337
  </Page.Provider>
181
338
  );
182
339
  }
@@ -204,7 +361,8 @@ export interface PortholeFrameProps {
204
361
  readonly document?: string;
205
362
  /** Domain and external isolation: the instance to show. */
206
363
  readonly instance?: InstanceRef;
207
- readonly scheme: ColorScheme;
364
+ /** The color scheme it shows in. Default: the provider's `scheme`, else light. */
365
+ readonly scheme?: ColorScheme;
208
366
  /** The host's live values for the config's theme variables (from its design tokens). */
209
367
  readonly theme?: (scheme: ColorScheme) => Readonly<Record<string, string | null | undefined>>;
210
368
  /** Handlers for the declared capabilities (the latest ones are called). */
@@ -332,12 +490,15 @@ function rememberedHeight(
332
490
 
333
491
  export function PortholeFrame(props: PortholeFrameProps): ReactElement {
334
492
  const page = useContext(Page);
493
+ // The provider's registry and heights: stable, unlike the context value, which a scheme flip
494
+ // or a new themeKey renews (an effect keyed on it would let the frame go and make it again, #9).
495
+ const { live, heights } = page;
335
496
  const key = useId();
336
497
  const box = useRef<HTMLDivElement>(null);
337
498
  const max = props.config.limits.maxLiveFrames;
338
499
  const state = useSyncExternalStore(
339
- (listener) => page.live.subscribe(listener),
340
- () => page.live.state(key),
500
+ (listener) => live.subscribe(listener),
501
+ () => live.state(key),
341
502
  (): FrameState => "waiting",
342
503
  );
343
504
  const { eager } = props;
@@ -348,9 +509,9 @@ export function PortholeFrame(props: PortholeFrameProps): ReactElement {
348
509
  return;
349
510
  }
350
511
  if (eager === true || typeof IntersectionObserver !== "function") {
351
- page.live.near(key, true);
352
- page.live.admit(key, max);
353
- return () => page.live.release(key);
512
+ live.near(key, true);
513
+ live.admit(key, max);
514
+ return () => live.release(key);
354
515
  }
355
516
  const observer = new IntersectionObserver(
356
517
  (entries) => {
@@ -358,9 +519,9 @@ export function PortholeFrame(props: PortholeFrameProps): ReactElement {
358
519
  if (entry === undefined) {
359
520
  return;
360
521
  }
361
- page.live.near(key, entry.isIntersecting);
522
+ live.near(key, entry.isIntersecting);
362
523
  if (entry.isIntersecting) {
363
- page.live.admit(key, max);
524
+ live.admit(key, max);
364
525
  }
365
526
  },
366
527
  { rootMargin: NEAR_SCREEN },
@@ -368,22 +529,22 @@ export function PortholeFrame(props: PortholeFrameProps): ReactElement {
368
529
  observer.observe(element);
369
530
  return () => {
370
531
  observer.disconnect();
371
- page.live.release(key);
532
+ live.release(key);
372
533
  };
373
- }, [page, key, max, eager]);
534
+ }, [live, key, max, eager]);
374
535
 
375
- const height = rememberedHeight(page.heights, props.displayId, props.aliases);
536
+ const height = rememberedHeight(heights, props.displayId, props.aliases);
376
537
  // A display renamed while it runs (its id settled) keeps its height under its new id.
377
538
  const previousId = useRef(props.displayId);
378
539
  useLayoutEffect(() => {
379
540
  const before = previousId.current;
380
541
  previousId.current = props.displayId;
381
- const kept = page.heights.get(before);
382
- if (before !== props.displayId && kept !== undefined && !page.heights.has(props.displayId)) {
383
- page.heights.set(props.displayId, kept);
542
+ const kept = heights.get(before);
543
+ if (before !== props.displayId && kept !== undefined && !heights.has(props.displayId)) {
544
+ heights.set(props.displayId, kept);
384
545
  }
385
- }, [page, props.displayId]);
386
- const run = () => page.live.admit(key, max);
546
+ }, [heights, props.displayId]);
547
+ const run = () => live.admit(key, max);
387
548
  const placeholder = props.renderPlaceholder ?? DefaultPlaceholder;
388
549
  return (
389
550
  <div
@@ -437,7 +598,10 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
437
598
  const [ready, setReady] = useState(false);
438
599
  // The height this display started at: later reports don't make it start again.
439
600
  const [startHeight] = useState(initialHeightPx);
440
- const { document: view, content, partial, scheme } = frame;
601
+ const { document: view, content, partial } = frame;
602
+ const scheme = frame.scheme ?? page.scheme ?? "light";
603
+ // A run's content errors, told once each (a loop throwing the same error says it once).
604
+ const told = useRef(new Set<string>());
441
605
  // By value: a config or instance made inline (each render) is the same display.
442
606
  const config = useByValue(frame.config);
443
607
  const instance = useByValue(frame.instance);
@@ -445,6 +609,18 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
445
609
 
446
610
  // The latest props, read when the display calls back (never during render).
447
611
  const latest = useEffectEvent(() => frame);
612
+ // The provider's scheme and theme, read when used: a flip or a new themeKey (a new context
613
+ // value) re-themes the running display, never makes it again (#9, P074). What a display is
614
+ // made with comes from the provider's stable parts below.
615
+ const latestPage = useEffectEvent(() => page);
616
+ const {
617
+ handlers: pageHandlers,
618
+ copyText: pageCopyText,
619
+ confirm: pageConfirm,
620
+ hostInfo,
621
+ locate,
622
+ nonce,
623
+ } = page;
448
624
  const notify = useEffectEvent(
449
625
  <E extends keyof DisplayEvents>(event: E, detail: DisplayEvents[E]): void => {
450
626
  switch (event) {
@@ -458,9 +634,14 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
458
634
  frame.onResize?.(size);
459
635
  return;
460
636
  }
461
- case "contentError":
462
- frame.onContentError?.((detail as DisplayEvents["contentError"]).message);
637
+ case "contentError": {
638
+ const { message } = detail as DisplayEvents["contentError"];
639
+ if (!told.current.has(message)) {
640
+ told.current.add(message);
641
+ frame.onContentError?.(message);
642
+ }
463
643
  return;
644
+ }
464
645
  case "hostError":
465
646
  frame.onHostError?.(detail as DisplayEvents["hostError"]);
466
647
  return;
@@ -503,24 +684,29 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
503
684
  displayId: latest().displayId,
504
685
  title: latest().title,
505
686
  });
506
- // The handlers present now (a declared one must be), each calling the latest prop's.
687
+ // The handlers present now (a declared one must be), each calling the latest prop's, else
688
+ // the provider's (P072).
507
689
  const handlers: Record<string, AnyHandler> = {};
508
- for (const name of Object.keys(first.handlers ?? {})) {
690
+ const declared = new Set(Object.keys(config.capabilities));
691
+ for (const name of new Set([
692
+ ...Object.keys(first.handlers ?? {}),
693
+ ...Object.keys(pageHandlers?.() ?? {}).filter((each) => declared.has(each)),
694
+ ])) {
509
695
  handlers[name] = (args, context) =>
510
- (latest().handlers as Record<string, AnyHandler | undefined> | undefined)?.[name]?.(
511
- args,
512
- named(context),
513
- );
696
+ (
697
+ (latest().handlers as Record<string, AnyHandler | undefined> | undefined)?.[name] ??
698
+ (pageHandlers?.() as Record<string, AnyHandler | undefined> | undefined)?.[name]
699
+ )?.(args, named(context));
514
700
  }
515
701
  // Copy buttons without a handler of the host's: the provider's, which shows a toast.
516
702
  if (config.capabilities.copyText !== undefined && handlers.copyText === undefined) {
517
- const fallback = page.copyText;
703
+ const fallback = pageCopyText;
518
704
  if (fallback !== undefined) {
519
705
  handlers.copyText = (args, context) =>
520
706
  fallback(args as { readonly text: string }, named(context));
521
707
  }
522
708
  }
523
- const asks = first.confirm !== undefined || page.confirm !== undefined;
709
+ const asks = first.confirm !== undefined || pageConfirm !== undefined;
524
710
  let display: DisplayHandle;
525
711
  try {
526
712
  display = createHost(config, {
@@ -528,20 +714,20 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
528
714
  ...(asks
529
715
  ? {
530
716
  confirm: (request: ConfirmRequest, proceed: Proceed) =>
531
- (latest().confirm ?? page.confirm ?? (() => Promise.resolve(false)))(
717
+ (latest().confirm ?? pageConfirm ?? (() => Promise.resolve(false)))(
532
718
  { ...request, display: { id: latest().displayId, title: latest().title } },
533
719
  proceed,
534
720
  ),
535
721
  }
536
722
  : {}),
537
- theme: (each) => latest().theme?.(each) ?? {},
538
- ...(page.hostInfo === undefined ? {} : { hostInfo: page.hostInfo }),
539
- ...(page.locate === undefined ? {} : { locator: { locate: page.locate } }),
540
- ...(page.nonce === undefined ? {} : { nonce: page.nonce }),
723
+ theme: (each) => (latest().theme ?? latestPage().theme)?.(each) ?? {},
724
+ ...(hostInfo === undefined ? {} : { hostInfo }),
725
+ ...(locate === undefined ? {} : { locator: { locate } }),
726
+ ...(nonce === undefined ? {} : { nonce }),
541
727
  }).mount(container, {
542
728
  displayId: first.displayId,
543
729
  title: first.title,
544
- scheme: first.scheme,
730
+ scheme: first.scheme ?? latestPage().scheme ?? "light",
545
731
  initialHeightPx: startHeight,
546
732
  ...(view === undefined ? {} : { document: view }),
547
733
  ...(instance === undefined ? {} : { instance }),
@@ -577,9 +763,22 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
577
763
  display.destroy();
578
764
  handle.current = null;
579
765
  };
580
- // A new display only for a new config, document, instance or page (or generation, by key);
581
- // content, theme, handlers, id and title are fed to the running one.
582
- }, [config, view, instance, page, startHeight, fills]);
766
+ // A new display only for a new config, document or instance, or what the provider makes
767
+ // displays with (its nonce, hostInfo by value, whether it locates or confirms; generation, by
768
+ // key). Content, scheme, theme, handlers, id and title are fed to the running one.
769
+ }, [
770
+ config,
771
+ view,
772
+ instance,
773
+ startHeight,
774
+ fills,
775
+ pageHandlers,
776
+ pageCopyText,
777
+ pageConfirm,
778
+ hostInfo,
779
+ locate,
780
+ nonce,
781
+ ]);
583
782
 
584
783
  useEffect(() => {
585
784
  if (content !== undefined) {
@@ -638,13 +837,28 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
638
837
  handle.current?.setTheme(scheme);
639
838
  }
640
839
  }, [scheme, mountScheme]);
641
- const { themeKey } = frame;
840
+ const themeKey = frame.themeKey ?? page.themeKey;
642
841
  const [mountThemeKey] = useState(themeKey);
643
842
  useEffect(() => {
644
843
  if (themeKey !== undefined && themeKey !== mountThemeKey) {
645
844
  handle.current?.refreshTheme();
646
845
  }
647
846
  }, [themeKey, mountThemeKey]);
847
+ // A new theme function (tokens a host passes inline): its values reach the running display
848
+ // where they changed for the scheme it shows (a flip re-reads them itself), P074.
849
+ const themeOf = frame.theme ?? page.theme;
850
+ const themed = useRef<string | null>(null);
851
+ useEffect(() => {
852
+ if (themeOf === undefined) {
853
+ return;
854
+ }
855
+ const now = `${scheme}\n${JSON.stringify(themeOf(scheme))}`;
856
+ const before = themed.current;
857
+ themed.current = now;
858
+ if (before !== null && before !== now && before.startsWith(`${scheme}\n`)) {
859
+ handle.current?.refreshTheme();
860
+ }
861
+ }, [themeOf, scheme]);
648
862
 
649
863
  return (
650
864
  <div
@@ -14,9 +14,18 @@ export {
14
14
  PortholeProvider,
15
15
  type PlaceholderProps,
16
16
  type PortholeFrameProps,
17
+ type ConfirmActions,
17
18
  type PortholeProviderProps,
18
19
  } from "./frame.tsx";
19
20
  export { ARM_DELAY_MS, ConfirmDialog, type ConfirmDialogProps } from "./dialog.tsx";
21
+ export {
22
+ cssVariableTheme,
23
+ PortholeView,
24
+ usePortholeLink,
25
+ useRunAgain,
26
+ type PortholeFallbackProps,
27
+ type PortholeViewProps,
28
+ } from "./view.tsx";
20
29
  export {
21
30
  CopyToast,
22
31
  TOAST_CHARS,