@runic-artifex/react 0.17.1 → 0.18.0

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
@@ -199,10 +199,10 @@ same on every render. `aria-invalid` is true while the field has `errors` or an
199
199
  `errors` holds the member's validation messages from the descriptor (`[]` when valid), `error` why the latest write
200
200
  or text failed (a `BridgeError` or a `FieldError`, whose `kind` is `rejected`, `conflict`, `committed-with-error` or
201
201
  `invalid-text`). `FieldError`, `FieldOptions`, `FieldState` and `BridgeField` are exported from this package. See the
202
- [field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#fields) for the receipts
202
+ [field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#fields) for the receipts
203
203
  and text forms. An `invalid-text` error has a `reason` and `arguments`: render `useText(name.error)` after
204
204
  `configureFieldErrorText` to show your own text for it in the window's language
205
- ([Translating field errors](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#translating-field-errors)).
205
+ ([Translating field errors](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#translating-field-errors)).
206
206
 
207
207
  #### Row cells and nested members
208
208
 
@@ -219,7 +219,7 @@ function LineRow({ invoice, line }: { invoice: InvoiceView; line: InvoiceLine })
219
219
  ```
220
220
 
221
221
  Such a field always writes checked, conflicts only when another writer changed the same cell, and shows the messages
222
- .NET reports at the cell's validation path. See [Fields below a member and row cells](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.1/packages/web/react/../views/README.md#fields-below-a-member-and-row-cells).
222
+ .NET reports at the cell's validation path. See [Fields below a member and row cells](https://github.com/Runic-Artifex/runic-sdk/blob/v0.18.0/packages/web/react/../views/README.md#fields-below-a-member-and-row-cells).
223
223
 
224
224
  ### Forms: `useForm(fields, options?)`
225
225
 
@@ -235,7 +235,7 @@ const form = useForm({ title, step }, { dirty: editor.state?.isDirty });
235
235
  ### Text inputs: `useTextField(view, read, write, options?)`
236
236
 
237
237
  Binds a controlled text input to a member through the framework-neutral
238
- [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#text-inputs)
238
+ [text field controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#text-inputs)
239
239
  while the component is mounted. `read` and `write` may close over render values:
240
240
 
241
241
  ```tsx
@@ -316,7 +316,7 @@ component registered for `reference.kind` with the reference as its `page`
316
316
  prop. Declare the registry with `satisfies ViewRegistry<State["main"]>` so each
317
317
  kind has a component whose `page` prop matches. A component whose `page` is a
318
318
  shared page reference, such as `ResultPagePageReference` of a .NET
319
- [`[RunicSharedClient]`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.1/packages/web/react/../../dotnet/Runic.Application.Views/README.md#shared-clients)
319
+ [`[RunicSharedClient]`](https://github.com/Runic-Artifex/runic-sdk/blob/v0.18.0/packages/web/react/../../dotnet/Runic.Application.Views/README.md#shared-clients)
320
320
  interface, registers for each of its kinds:
321
321
  `{ ...registryEntries(resultPageKinds, ResultPage), settings: Settings }`. A different reference
322
322
  remounts the component, and `fallback` renders while `content` is empty. A kind
@@ -425,7 +425,7 @@ neither.
425
425
  ## `useOperation(start, options?)`
426
426
 
427
427
  Observes a generated `start<Command>()` operation through the framework-neutral
428
- [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#operation-feedback-and-latest-selection).
428
+ [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#operation-feedback-and-latest-selection).
429
429
  `run(...args)` calls the latest `start`, so it may close over the current client:
430
430
 
431
431
  ```tsx
@@ -457,7 +457,7 @@ controller's options.
457
457
 
458
458
  Admits only the newest of several reads, for example loading the item the user
459
459
  selected last, through the framework-neutral
460
- [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#operation-feedback-and-latest-selection).
460
+ [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#operation-feedback-and-latest-selection).
461
461
  Each `run(intent)` replaces the queued intent and cancels the active read; the next
462
462
  read starts only after the previous one reaches its terminal status and the intent's
463
463
  optional `waitForCompletion` barrier:
@@ -488,7 +488,7 @@ It wraps `onBridgeConnection` from `@runic-artifex/views` (re-exported here sinc
488
488
  `{ state }`, where `state` is a `BridgeConnectionState`: `connecting`,
489
489
  `connected`, `reconnecting`, `lost` or `closed` (the application closed the
490
490
  window, since 0.15; a closed set, see
491
- [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#connection-state)):
491
+ [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#connection-state)):
492
492
 
493
493
  ```tsx
494
494
  import { useBridgeConnection } from "@runic-artifex/react";
@@ -509,7 +509,7 @@ subscribes again; an invalid one throws a `RangeError`. A server render reads
509
509
  Follows the declared menu bar of a Runic Desktop window that leaves it to the
510
510
  page (`DesktopMenuBarPresentation.Page`) while the component is mounted. It
511
511
  wraps `createMenuBarController` from `@runic-artifex/views` (see
512
- [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#in-page-menu-bar)) and returns `{ state, invoke, handleKeyDown }`: `state` is a
512
+ [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#in-page-menu-bar)) and returns `{ state, invoke, handleKeyDown }`: `state` is a
513
513
  `MenuBarState`, and the bar is rendered by the menubar component of the
514
514
  application's own UI library. Runic ships no menubar component.
515
515
 
@@ -539,7 +539,7 @@ The controller starts in an effect, so a server render reads `connecting`, and
539
539
 
540
540
  Base UI's `Menubar` (`@base-ui/react`, the base of shadcn/ui's Base UI
541
541
  Menubar) with a controlled open menu; the
542
- [Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
542
+ [Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
543
543
  items and is tested with real keys:
544
544
 
545
545
  ```tsx
@@ -596,7 +596,7 @@ Shows a text reference that a ViewModel produced, such as a status line or a
596
596
  validation error's `text`, in the window's language, and renders again when the
597
597
  language changes. A string shows as it is; `null` and `undefined` show
598
598
  `fallback`. Connect the page's Translations runtime once with
599
- `configureTranslatedText` ([Translated text](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.1/packages/dotnet/Runic.Application.Views/README.md#translated-text)).
599
+ `configureTranslatedText` ([Translated text](https://github.com/Runic-Artifex/runic-sdk/blob/v0.18.0/packages/dotnet/Runic.Application.Views/README.md#translated-text)).
600
600
  `useWindowLocale()` reads the window's locale.
601
601
 
602
602
  `useTextLocale()` renders the locale that text is shown in, and renders again
@@ -625,7 +625,7 @@ function ErrorLine({ error }: { error: BridgeValidationMessage }) {
625
625
  Renders the page's appearance and renders again when it changes: the colour
626
626
  scheme, contrast and reduced motion of the page's engine, combined with the
627
627
  desktop's text scale, accent colour, forced-colours palette, contrast and motion
628
- that a Runic host pushes ([Appearance](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.1/packages/web/views/README.md#appearance)). The server snapshot
628
+ that a Runic host pushes ([Appearance](https://github.com/Runic-Artifex/runic-sdk/blob/v0.18.0/packages/web/views/README.md#appearance)). The server snapshot
629
629
  has every member `null`.
630
630
 
631
631
  ```tsx
@@ -639,7 +639,7 @@ function Shell({ children }: { readonly children: ReactNode }) {
639
639
 
640
640
  The `error` of `useView` and of a command or operation handle is typed
641
641
  `unknown`: it holds whatever the connection or the call rejected with. Show it
642
- with `describeBridgeError(error)`, one English sentence, instead of
642
+ with `describeBridgeError(error)`, one sentence (in the window's language with `configureRunicViewsText()`), instead of
643
643
  `String(error)`. A Bridge failure is a `BridgeError` from
644
644
  `@runic-artifex/views`; narrow it with `isBridgeError` (or `instanceof`) before
645
645
  reading `kind`, `route` or `detail`:
@@ -652,7 +652,7 @@ const offline = isBridgeError(error, "disconnected");
652
652
  ```
653
653
 
654
654
  `instanceof` holds for errors from every copy of the package on the page.
655
- [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#errors-and-diagnostics)
655
+ [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#errors-and-diagnostics)
656
656
  lists the kinds. Any other value, such as an exception that your own connect
657
657
  function or command callback throws, arrives unchanged.
658
658
 
@@ -694,11 +694,11 @@ the application's own dialog.
694
694
  such as a close during the page's first render, is answered by the
695
695
  ViewModel's .NET fallback handler, or fails closed without one.
696
696
 
697
- The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.1/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
697
+ The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.18.0/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
698
698
  has the .NET side and which View answers which departure. In a frontend test,
699
699
  the generated mock's `interactions.<name>.request(input)` resolves with the
700
700
  registered handler's answer; see the
701
- [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#testing).
701
+ [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#testing).
702
702
 
703
703
  ## View requests
704
704
 
@@ -725,14 +725,14 @@ the page painted the state the request was raised with, so the field of that
725
725
  state is rendered; `signal` aborts when the handler is replaced or removed, the
726
726
  client is disposed or the connection is lost. A request is never replayed: one
727
727
  raised before the effect ran, or while the page is disconnected, is not
728
- delivered later. See [View requests](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#view-requests) for the rules, and in a frontend
728
+ delivered later. See [View requests](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#view-requests) for the rules, and in a frontend
729
729
  test raise one with the generated mock's `requests.<name>.raise(input)` (the
730
- [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#testing)).
730
+ [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#testing)).
731
731
 
732
732
  ## `useCollectionViewport(options)`
733
733
 
734
734
  Follows a fixed-row-height scroll container and returns `{ viewport, ref }`.
735
- `viewport` is the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#collectionviewportoptions)
735
+ `viewport` is the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#collectionviewportoptions)
736
736
  range for the container; it changes only when the range or sizes change. Send
737
737
  the range to the ViewModel from an effect:
738
738
 
@@ -751,7 +751,7 @@ return <div ref={ref} style={{ height: 480, overflow: "auto" }}>
751
751
 
752
752
  ## `useQueryCollection(collection, options)`
753
753
 
754
- Follows a scroll container for a [query collection](https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/views#query-collections) (`client.queries.{name}`), whose rows stay in .NET: it
754
+ Follows a scroll container for a [query collection](https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/views#query-collections) (`client.queries.{name}`), whose rows stay in .NET: it
755
755
  loads the rows the container shows, with placeholders until they arrive, and lays them out with variable heights
756
756
  (`estimateSize` for rows not measured yet). It returns the `QueryViewport` (`items` with `top` and `size`, `totalSize`,
757
757
  `total`, `query`, `loading`, `error`), `ref` for the container, `measure(index)` for each row, and `scrollToKey`,
@@ -775,4 +775,19 @@ The package re-exports `installBackNavigation`, `installNavigationPath`,
775
775
  `@runic-artifex/views` (since 0.16). Call the installs once where the page
776
776
  starts, before or after mounting: the mouse's Back button and Alt+Left then go
777
777
  back in the .NET window, and `#/customers/42` follows its path region. See
778
- [Back and the URL](https://github.com/Runic-Artifex/runic-sdk/blob/v0.17.1/packages/web/views/README.md#back-and-the-url).
778
+ [Back and the URL](https://github.com/Runic-Artifex/runic-sdk/blob/v0.18.0/packages/web/views/README.md#back-and-the-url).
779
+
780
+ ## Hosted regions (experimental)
781
+
782
+ `RunicHostedRegion` from `@runic-artifex/react/experimental` renders
783
+ `<runic-hosted-region>`, a region where the host application shows a hosted guest's
784
+ Window ([hosted regions](https://github.com/Runic-Artifex/runic-sdk/blob/v0.18.0/packages/web/react/../views/README.md#hosted-regions-experimental)). `fallback` is content, or a function of the region's
785
+ state, shown while no guest page shows in it:
786
+
787
+ ```tsx
788
+ import { RunicHostedRegion } from "@runic-artifex/react/experimental";
789
+
790
+ <RunicHostedRegion name="check" style={{ height: 420 }}
791
+ fallback={state => state === "ended" ? <RunAgain /> : <p>Starting the check…</p>}
792
+ onStateChange={state => setStep(state)} />
793
+ ```
@@ -0,0 +1,27 @@
1
+ import { type HTMLAttributes, type ReactNode } from "react";
2
+ import { type HostedRegionSizing, type HostedRegionState } from "@runic-artifex/views/experimental";
3
+ export type { HostedRegionSizing, HostedRegionState, RunicHostedRegionElement } from "@runic-artifex/views/experimental";
4
+ /** Props of {@link RunicHostedRegion}. Other HTML attributes, such as `className`, `style` and `id`, go to the element. */
5
+ export interface RunicHostedRegionProps extends Omit<HTMLAttributes<HTMLElement>, "children" | "title"> {
6
+ /** The region's name, which the host application's policy embeds a guest's Window in. */
7
+ readonly name: string;
8
+ /** `fill` (the default): the page's layout sets the height. `content-height`: the guest's page does. */
9
+ readonly sizing?: HostedRegionSizing;
10
+ /** The region's accessible name; without it, the guest page's title. */
11
+ readonly label?: string;
12
+ /** What the region shows while no guest page shows in it: content, or a function of the region's state. */
13
+ readonly fallback?: ReactNode | ((state: HostedRegionState) => ReactNode);
14
+ readonly onStateChange?: (state: HostedRegionState, previous: HostedRegionState) => void;
15
+ /** The guest page's title as the host passed it on, or `null`. */
16
+ readonly onTitleChange?: (title: string | null) => void;
17
+ }
18
+ /**
19
+ * A region where the host application shows a hosted guest's Window (`<runic-hosted-region>`), in a frame the page never
20
+ * gets a reference to:
21
+ *
22
+ * ```tsx
23
+ * <RunicHostedRegion name="check" style={{ height: 420 }}
24
+ * fallback={state => state === "ended" ? <RunAgain /> : <p>Starting the check…</p>} />
25
+ * ```
26
+ */
27
+ export declare function RunicHostedRegion({ name, sizing, label, fallback, onStateChange, onTitleChange, className, ...attributes }: RunicHostedRegionProps): ReactNode;
@@ -0,0 +1,42 @@
1
+ // The experimental entry (docs/experimental.md, "npm packages"): importing it is the opt-in. Hosted regions (0.18): the
2
+ // .NET side is the experimental family RUNICDESK103.
3
+ import { createElement, useEffect, useRef, useState } from "react";
4
+ import { defineHostedRegion, hostedRegionTag, } from "@runic-artifex/views/experimental";
5
+ /**
6
+ * A region where the host application shows a hosted guest's Window (`<runic-hosted-region>`), in a frame the page never
7
+ * gets a reference to:
8
+ *
9
+ * ```tsx
10
+ * <RunicHostedRegion name="check" style={{ height: 420 }}
11
+ * fallback={state => state === "ended" ? <RunAgain /> : <p>Starting the check…</p>} />
12
+ * ```
13
+ */
14
+ export function RunicHostedRegion({ name, sizing, label, fallback, onStateChange, onTitleChange, className, ...attributes }) {
15
+ defineHostedRegion();
16
+ const element = useRef(null);
17
+ const [state, setState] = useState("waiting");
18
+ const handlers = useRef({ onStateChange, onTitleChange });
19
+ handlers.current = { onStateChange, onTitleChange };
20
+ useEffect(() => {
21
+ const region = element.current;
22
+ if (!region)
23
+ return undefined;
24
+ setState(region.state);
25
+ const stateChanged = (event) => {
26
+ setState(event.detail.state);
27
+ handlers.current.onStateChange?.(event.detail.state, event.detail.previous);
28
+ };
29
+ const titleChanged = (event) => handlers.current.onTitleChange?.(event.detail.title);
30
+ region.addEventListener("runicregionstatechange", stateChanged);
31
+ region.addEventListener("runicregiontitlechange", titleChanged);
32
+ return () => {
33
+ region.removeEventListener("runicregionstatechange", stateChanged);
34
+ region.removeEventListener("runicregiontitlechange", titleChanged);
35
+ };
36
+ }, []);
37
+ const content = typeof fallback === "function" ? fallback(state) : fallback;
38
+ return createElement(hostedRegionTag, {
39
+ // React 18 sets a custom element's className as an attribute of that name; `class` is the attribute in 18 and 19.
40
+ ...attributes, ...(className === undefined ? {} : { class: className }), ref: element, name, ...(sizing === undefined ? {} : { sizing }), ...(label === undefined ? {} : { label }),
41
+ }, content === undefined || content === null ? null : createElement("div", { slot: "fallback", style: { display: "contents" } }, content));
42
+ }
package/dist/index.d.ts CHANGED
@@ -396,6 +396,8 @@ export declare function useAppearance(): Appearance;
396
396
  * ```
397
397
  */
398
398
  export declare function useTextLocale(): string | undefined;
399
+ export { RunicInstanceProvider, useRunicInstance, type RunicInstanceProviderProps } from "./instance.js";
400
+ export { createRunicInstance, pageInstance, type RunicInstance, type RunicInstanceOptions } from "@runic-artifex/views";
399
401
  export { retrySuspenseView, useSuspenseView, type SuspenseViewHandle, type SuspenseViewOptions } from "./suspense.js";
400
402
  export { useCollectionViewport, type CollectionViewportHandle } from "./viewport.js";
401
403
  export { useForm, type FormFieldHandle, type FormHandle, type UseFormOptions } from "./form.js";
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createElement, useCallback, useEffect, useInsertionEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, } from "react";
2
2
  import { createCommandController, createLatestOperationController, createOperationController, createFieldController, createTextFieldController, createViewController, onBridgeConnection, onWindowLocale, appearance, onAppearance, unknownAppearance, resolveText, subscribeText, textLocale, textVersion, windowLocale, regionEntries, } from "@runic-artifex/views";
3
3
  import { isViewClient, missingViewMessage, reportMissingView, viewSourceIdentity, viewSourcePreview } from "@runic-artifex/views/bindings";
4
+ import { useRunicInstance } from "./instance.js";
4
5
  // An inline `{ connect: () => connectX() }` creates a new function on every
5
6
  // render, so every render reconnects and each connection renders again.
6
7
  function warnInlineConnect(tracker, connect) {
@@ -69,15 +70,17 @@ function createViewStore(controller) {
69
70
  * `connect` function recreated on every render logs a warning.
70
71
  */
71
72
  export function useView(source, options = {}) {
73
+ const instance = useRunicInstance();
72
74
  const release = useRef(options.release);
73
75
  useInsertionEffect(() => { release.current = options.release; });
74
- const [controller] = useState(() => createViewController({
76
+ // The controller connects in the component's Runic instance, also when it retries.
77
+ const [controller] = useState(() => instance.run(() => createViewController({
75
78
  release: client => { if (release.current)
76
79
  release.current(client);
77
80
  else
78
81
  client.dispose(); },
79
82
  ...(options.keepAlive === undefined ? {} : { keepAlive: options.keepAlive }),
80
- }));
83
+ })));
81
84
  const [store] = useState(() => createViewStore(controller));
82
85
  const tracker = useRef({ connect: undefined, text: "", times: [], warned: false });
83
86
  const identity = viewSourceIdentity(source);
@@ -99,7 +102,7 @@ export function useView(source, options = {}) {
99
102
  return { state: observed.snapshot, client: observed, error: undefined, pending: false, retry };
100
103
  // Until the effect follows a changed reference, do not show the previous one; show a client kept for it instead.
101
104
  if (viewSourceIdentity(current.source) !== identity) {
102
- const preview = viewSourcePreview(source);
105
+ const preview = instance.run(() => viewSourcePreview(source));
103
106
  if (preview)
104
107
  return { state: preview.state, client: preview.client, error: undefined, pending: false, retry };
105
108
  return { state: undefined, client: undefined, error: undefined, pending: source !== null && source !== undefined, retry };
@@ -165,6 +168,7 @@ function referenceKey(reference) {
165
168
  * nothing in production, where the kind is reported (`installErrorReporting`, `onBridgeDiagnostic`).
166
169
  */
167
170
  export function ViewOutlet({ content, registry, fallback = null, missing }) {
171
+ const instance = useRunicInstance();
168
172
  if (!content)
169
173
  return fallback;
170
174
  const component = registry[content.kind];
@@ -173,7 +177,7 @@ export function ViewOutlet({ content, registry, fallback = null, missing }) {
173
177
  return missing(content);
174
178
  if (process.env.NODE_ENV !== "production")
175
179
  return createElement("p", { role: "alert" }, missingViewMessage(content.kind));
176
- reportMissingView(content.kind);
180
+ instance.run(() => reportMissingView(content.kind));
177
181
  return null;
178
182
  }
179
183
  return createElement(component, { key: referenceKey(content), page: content });
@@ -199,7 +203,10 @@ export function RegionOutlets({ collection, registry, fallback = null, missing,
199
203
  // observing accepted work (it never cancels the work). StrictMode's simulated unmount, and a component that React shows again (`<Activity>`),
200
204
  // mount once more with a fresh controller, so feedback of runs started before the unmount ends.
201
205
  const disposedControllers = new WeakSet();
202
- function useMountedController(create) {
206
+ // It is created in the component's Runic instance.
207
+ function useMountedController(createIn) {
208
+ const instance = useRunicInstance();
209
+ const create = () => instance.run(createIn);
203
210
  const controller = useRef(null);
204
211
  if (controller.current === null)
205
212
  controller.current = create();
@@ -408,9 +415,9 @@ export function useField(view, field, options = {}) {
408
415
  };
409
416
  }
410
417
  // The state before the component subscribes: a subscription reports it at once.
411
- function currentBridgeConnection(options) {
418
+ function currentBridgeConnection(instance, options) {
412
419
  let current = "connecting";
413
- onBridgeConnection(state => { current = state; }, options)();
420
+ instance.run(() => onBridgeConnection(state => { current = state; }, options))();
414
421
  return current;
415
422
  }
416
423
  /**
@@ -425,12 +432,13 @@ function currentBridgeConnection(options) {
425
432
  */
426
433
  export function useBridgeConnection(options = {}) {
427
434
  const { lostAfter } = options;
435
+ const instance = useRunicInstance();
428
436
  const [store] = useState(() => ({ state: undefined }));
429
- const subscribe = useCallback((onChange) => onBridgeConnection(state => {
437
+ const subscribe = useCallback((onChange) => instance.run(() => onBridgeConnection(state => {
430
438
  store.state = state;
431
439
  onChange();
432
- }, lostAfter === undefined ? {} : { lostAfter }), [store, lostAfter]);
433
- const read = useCallback(() => store.state ??= currentBridgeConnection(lostAfter === undefined ? {} : { lostAfter }), [store, lostAfter]);
440
+ }, lostAfter === undefined ? {} : { lostAfter })), [instance, store, lostAfter]);
441
+ const read = useCallback(() => store.state ??= currentBridgeConnection(instance, lostAfter === undefined ? {} : { lostAfter }), [instance, store, lostAfter]);
434
442
  const state = useSyncExternalStore(subscribe, read, serverConnectionState);
435
443
  return { state };
436
444
  }
@@ -450,18 +458,37 @@ const serverConnectionState = () => "connecting";
450
458
  * ```
451
459
  */
452
460
  export function useText(value, fallback) {
453
- const version = useSyncExternalStore(subscribeText, textVersion, textVersion);
461
+ const instance = useRunicInstance();
462
+ const text = instanceText(instance);
463
+ const version = useSyncExternalStore(text.subscribe, text.version, text.version);
454
464
  // version is the language the text resolves in.
455
- return useMemo(() => resolveText(value, fallback), [value, fallback, version]);
465
+ return useMemo(() => instance.run(() => resolveText(value, fallback)), [instance, value, fallback, version]);
466
+ }
467
+ const instanceTexts = new WeakMap();
468
+ function instanceText(instance) {
469
+ let text = instanceTexts.get(instance);
470
+ if (!text) {
471
+ const run = instance.run;
472
+ instanceTexts.set(instance, text = {
473
+ subscribe: onChange => run(() => subscribeText(onChange)),
474
+ version: () => run(textVersion),
475
+ locale: () => run(textLocale),
476
+ subscribeWindowLocale: onChange => run(() => onWindowLocale(() => onChange())),
477
+ windowLocale: () => run(windowLocale),
478
+ subscribeAppearance: onChange => run(() => onAppearance(() => onChange())),
479
+ appearance: () => run(appearance),
480
+ });
481
+ }
482
+ return text;
456
483
  }
457
484
  /**
458
485
  * Renders the window's locale that the application set (`IRunicWindowLocale` in .NET), or `null` while it sets none,
459
486
  * for example to set `lang` on an element. The server snapshot is `null`.
460
487
  */
461
488
  export function useWindowLocale() {
462
- return useSyncExternalStore(subscribeWindowLocale, windowLocale, serverWindowLocale);
489
+ const text = instanceText(useRunicInstance());
490
+ return useSyncExternalStore(text.subscribeWindowLocale, text.windowLocale, serverWindowLocale);
463
491
  }
464
- const subscribeWindowLocale = (onChange) => onWindowLocale(() => onChange());
465
492
  const serverWindowLocale = () => null;
466
493
  /**
467
494
  * Renders the page's appearance (`appearance` from `@runic-artifex/views`): the colour scheme, contrast and reduced
@@ -474,9 +501,9 @@ const serverWindowLocale = () => null;
474
501
  * ```
475
502
  */
476
503
  export function useAppearance() {
477
- return useSyncExternalStore(subscribeAppearance, appearance, serverAppearance);
504
+ const text = instanceText(useRunicInstance());
505
+ return useSyncExternalStore(text.subscribeAppearance, text.appearance, serverAppearance);
478
506
  }
479
- const subscribeAppearance = (onChange) => onAppearance(() => onChange());
480
507
  const serverAppearance = () => unknownAppearance;
481
508
  /**
482
509
  * Renders the locale that text is shown in (`textLocale`: the page's Translations locale, which follows the window's
@@ -492,8 +519,11 @@ const serverAppearance = () => unknownAppearance;
492
519
  * ```
493
520
  */
494
521
  export function useTextLocale() {
495
- return useSyncExternalStore(subscribeText, textLocale, textLocale);
522
+ const text = instanceText(useRunicInstance());
523
+ return useSyncExternalStore(text.subscribe, text.locale, text.locale);
496
524
  }
525
+ export { RunicInstanceProvider, useRunicInstance } from "./instance.js";
526
+ export { createRunicInstance, pageInstance } from "@runic-artifex/views";
497
527
  export { retrySuspenseView, useSuspenseView } from "./suspense.js";
498
528
  export { useCollectionViewport } from "./viewport.js";
499
529
  export { useForm } from "./form.js";
@@ -0,0 +1,20 @@
1
+ import { type ReactNode } from "react";
2
+ import { type RunicInstance } from "@runic-artifex/views";
3
+ export interface RunicInstanceProviderProps {
4
+ /** The instance whose Views, connection state, text and appearance the subtree's hooks use. */
5
+ readonly instance: RunicInstance;
6
+ readonly children?: ReactNode;
7
+ }
8
+ /**
9
+ * Makes `instance` the Runic instance of its subtree: `useView`, `useField`, `useText`, `useBridgeConnection`,
10
+ * `useAppearance` and the other hooks below it connect and read through it instead of the page instance. A guest that
11
+ * renders inside another page, such as an embedded component, wraps its root in it.
12
+ *
13
+ * ```tsx
14
+ * const instance = createRunicInstance({ bridge });
15
+ * root.render(<RunicInstanceProvider instance={instance}><App /></RunicInstanceProvider>);
16
+ * ```
17
+ */
18
+ export declare function RunicInstanceProvider({ instance, children }: RunicInstanceProviderProps): ReactNode;
19
+ /** The Runic instance of the calling component: that of the nearest `RunicInstanceProvider`, or the default instance (`defaultInstance()`): the page instance, or in a component bundle its element's. */
20
+ export declare function useRunicInstance(): RunicInstance;
@@ -0,0 +1,22 @@
1
+ import { createContext, createElement, useContext } from "react";
2
+ import { defaultInstance } from "@runic-artifex/views";
3
+ // The Runic instance of a subtree (`createRunicInstance` in @runic-artifex/views). Without a provider it is the page
4
+ // instance, on `globalThis.__runicBridge`, as before instances existed.
5
+ const RunicInstanceContext = createContext(undefined);
6
+ /**
7
+ * Makes `instance` the Runic instance of its subtree: `useView`, `useField`, `useText`, `useBridgeConnection`,
8
+ * `useAppearance` and the other hooks below it connect and read through it instead of the page instance. A guest that
9
+ * renders inside another page, such as an embedded component, wraps its root in it.
10
+ *
11
+ * ```tsx
12
+ * const instance = createRunicInstance({ bridge });
13
+ * root.render(<RunicInstanceProvider instance={instance}><App /></RunicInstanceProvider>);
14
+ * ```
15
+ */
16
+ export function RunicInstanceProvider({ instance, children }) {
17
+ return createElement(RunicInstanceContext.Provider, { value: instance }, children);
18
+ }
19
+ /** The Runic instance of the calling component: that of the nearest `RunicInstanceProvider`, or the default instance (`defaultInstance()`): the page instance, or in a component bundle its element's. */
20
+ export function useRunicInstance() {
21
+ return useContext(RunicInstanceContext) ?? defaultInstance();
22
+ }
package/dist/menu-bar.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { useEffect, useInsertionEffect, useRef, useState, useSyncExternalStore } from "react";
2
+ import { useRunicInstance } from "./instance.js";
2
3
  import { BridgeError, createMenuBarController, } from "@runic-artifex/views";
3
4
  // The state before a controller follows the host, as a new controller starts.
4
5
  const connectingState = (shortcuts) => Object.freeze({
@@ -58,19 +59,21 @@ export function useMenuBar(options = {}) {
58
59
  const { shortcuts, keyboard } = options;
59
60
  const onRequest = useRef(options.onRequest);
60
61
  useInsertionEffect(() => { onRequest.current = options.onRequest; });
62
+ const instance = useRunicInstance();
61
63
  const [store] = useState(() => createMenuBarStore(shortcuts));
62
64
  useEffect(() => {
63
- const controller = createMenuBarController({
65
+ // The menu bar of the component's Runic instance.
66
+ const controller = instance.run(() => createMenuBarController({
64
67
  ...(shortcuts === undefined ? {} : { shortcuts }),
65
68
  ...(keyboard === undefined ? {} : { keyboard }),
66
- });
69
+ }));
67
70
  controller.onRequest(request => onRequest.current?.(request));
68
71
  const detach = store.attach(controller);
69
72
  return () => {
70
73
  detach();
71
74
  controller.dispose();
72
75
  };
73
- }, [store, shortcuts, keyboard]);
76
+ }, [instance, store, shortcuts, keyboard]);
74
77
  const state = useSyncExternalStore(store.subscribe, store.read, () => store.initial);
75
78
  return { state, invoke: store.invoke, handleKeyDown: store.handleKeyDown };
76
79
  }
@@ -1,10 +1,11 @@
1
- import type { ViewClient, ViewConnector } from "@runic-artifex/views";
1
+ import { type RunicInstance, type ViewClient, type ViewConnector } from "@runic-artifex/views";
2
2
  /**
3
3
  * Forgets a failed `useSuspenseView` connection, so the next render connects
4
4
  * again. Call it from an error boundary's reset before rendering the
5
5
  * component again. A connection that is pending or connected is unaffected.
6
+ * Pass the Runic instance of the component (`useRunicInstance()`) when it is not the default instance.
6
7
  */
7
- export declare function retrySuspenseView(source: ViewConnector<ViewClient>): void;
8
+ export declare function retrySuspenseView(source: ViewConnector<ViewClient>, instance?: RunicInstance): void;
8
9
  export interface SuspenseViewOptions {
9
10
  /**
10
11
  * Milliseconds that a connection no mounted component has claimed, or a failure no
package/dist/suspense.js CHANGED
@@ -1,8 +1,14 @@
1
1
  import { useCallback, useEffect, useReducer, useSyncExternalStore } from "react";
2
+ import { defaultInstance } from "@runic-artifex/views";
2
3
  import { checkKeepAlive, isViewClient } from "@runic-artifex/views/bindings";
3
- // Suspense discards the state of a component that never mounted, so pending
4
- // connections live here, keyed by connect function, until a component claims them.
5
- const suspended = new WeakMap();
4
+ import { useRunicInstance } from "./instance.js";
5
+ const suspendedByInstance = new WeakMap();
6
+ function suspendedOf(instance) {
7
+ let suspended = suspendedByInstance.get(instance);
8
+ if (!suspended)
9
+ suspendedByInstance.set(instance, suspended = new WeakMap());
10
+ return suspended;
11
+ }
6
12
  const defaultReleaseTimeout = 10_000;
7
13
  // setTimeout runs a larger delay, like Infinity, at once.
8
14
  const maxReleaseTimeout = 2_147_483_647;
@@ -16,7 +22,7 @@ function checkReleaseTimeout(value) {
16
22
  }
17
23
  // Releases an entry no mounted component uses after `delay`: disposes its client, or
18
24
  // forgets its failure so that a later render connects again. Infinity keeps it.
19
- function releaseLater(key, entry, delay) {
25
+ function releaseLater(suspended, key, entry, delay) {
20
26
  clearTimeout(entry.timer);
21
27
  entry.timer = delay === Infinity ? undefined : setTimeout(() => {
22
28
  if (entry.users !== 0 || suspended.get(key) !== entry)
@@ -25,7 +31,8 @@ function releaseLater(key, entry, delay) {
25
31
  entry.client?.dispose();
26
32
  }, delay);
27
33
  }
28
- function suspendedConnection(connector, releaseTimeout) {
34
+ function suspendedConnection(instance, connector, releaseTimeout) {
35
+ const suspended = suspendedOf(instance);
29
36
  const key = connector.connect;
30
37
  const existing = suspended.get(key);
31
38
  if (existing) {
@@ -33,21 +40,21 @@ function suspendedConnection(connector, releaseTimeout) {
33
40
  existing.releaseTimeout = releaseTimeout;
34
41
  // A settled entry that nobody uses waits for the longer timeout from now.
35
42
  if (existing.status !== "pending" && existing.users === 0)
36
- releaseLater(key, existing, releaseTimeout);
43
+ releaseLater(suspended, key, existing, releaseTimeout);
37
44
  }
38
45
  return existing;
39
46
  }
40
47
  const entry = { status: "pending", promise: Promise.resolve(), users: 0, releaseTimeout, keepAlive: 0 };
41
- entry.promise = Promise.resolve().then(() => connector.connect()).then(client => {
48
+ entry.promise = Promise.resolve().then(() => instance.run(() => connector.connect())).then(client => {
42
49
  entry.status = "ready";
43
50
  entry.client = client;
44
51
  // Release a connection whose render was abandoned before it mounted.
45
- releaseLater(key, entry, entry.releaseTimeout);
52
+ releaseLater(suspended, key, entry, entry.releaseTimeout);
46
53
  }, (error) => {
47
54
  entry.status = "failed";
48
55
  entry.error = error;
49
56
  // Keep the failure for the error boundary; forget it later so a later render reconnects.
50
- releaseLater(key, entry, entry.releaseTimeout);
57
+ releaseLater(suspended, key, entry, entry.releaseTimeout);
51
58
  });
52
59
  suspended.set(key, entry);
53
60
  return entry;
@@ -56,8 +63,10 @@ function suspendedConnection(connector, releaseTimeout) {
56
63
  * Forgets a failed `useSuspenseView` connection, so the next render connects
57
64
  * again. Call it from an error boundary's reset before rendering the
58
65
  * component again. A connection that is pending or connected is unaffected.
66
+ * Pass the Runic instance of the component (`useRunicInstance()`) when it is not the default instance.
59
67
  */
60
- export function retrySuspenseView(source) {
68
+ export function retrySuspenseView(source, instance = defaultInstance()) {
69
+ const suspended = suspendedOf(instance);
61
70
  const entry = suspended.get(source.connect);
62
71
  if (entry?.status !== "failed")
63
72
  return;
@@ -81,8 +90,10 @@ export function retrySuspenseView(source) {
81
90
  export function useSuspenseView(source, options = {}) {
82
91
  const releaseTimeout = checkReleaseTimeout(options.releaseTimeout);
83
92
  const keepAlive = checkKeepAlive(options.keepAlive, "useSuspenseView's keepAlive");
93
+ const instance = useRunicInstance();
94
+ const suspended = suspendedOf(instance);
84
95
  const connector = isViewClient(source) ? undefined : source;
85
- const entry = connector ? suspendedConnection(connector, releaseTimeout) : undefined;
96
+ const entry = connector ? suspendedConnection(instance, connector, releaseTimeout) : undefined;
86
97
  const [, refresh] = useReducer((count) => count + 1, 0);
87
98
  useEffect(() => {
88
99
  if (!connector || !entry)
@@ -99,9 +110,9 @@ export function useSuspenseView(source, options = {}) {
99
110
  return () => {
100
111
  entry.users--;
101
112
  if (entry.users === 0)
102
- releaseLater(key, entry, entry.keepAlive);
113
+ releaseLater(suspended, key, entry, entry.keepAlive);
103
114
  };
104
- }, [entry, keepAlive]);
115
+ }, [suspended, entry, keepAlive]);
105
116
  if (entry?.status === "pending")
106
117
  throw entry.promise;
107
118
  if (entry?.status === "failed")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runic-artifex/react",
3
- "version": "0.17.1",
3
+ "version": "0.18.0",
4
4
  "description": "React hooks for generated Runic Views clients",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -19,6 +19,11 @@
19
19
  "import": "./dist/index.js",
20
20
  "default": "./dist/index.js"
21
21
  },
22
+ "./experimental": {
23
+ "types": "./dist/experimental.d.ts",
24
+ "import": "./dist/experimental.js",
25
+ "default": "./dist/experimental.js"
26
+ },
22
27
  "./package.json": "./package.json"
23
28
  },
24
29
  "scripts": {
@@ -30,10 +35,10 @@
30
35
  },
31
36
  "peerDependencies": {
32
37
  "react": ">=18.3.0 <20",
33
- "@runic-artifex/views": "0.17.1"
38
+ "@runic-artifex/views": "0.18.0"
34
39
  },
35
40
  "devDependencies": {
36
- "@runic-artifex/views": "0.17.1",
41
+ "@runic-artifex/views": "0.18.0",
37
42
  "@types/react": "19.3.0",
38
43
  "@types/react-dom": "19.3.0",
39
44
  "esbuild": "0.28.2",
@@ -53,7 +58,7 @@
53
58
  "url": "git+https://github.com/Runic-Artifex/runic-sdk.git",
54
59
  "directory": "packages/web/react"
55
60
  },
56
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.17.1/packages/web/react#readme",
61
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.18.0/packages/web/react#readme",
57
62
  "bugs": {
58
63
  "url": "https://github.com/Runic-Artifex/runic-sdk/issues"
59
64
  },
@@ -63,5 +68,5 @@
63
68
  "views",
64
69
  "react"
65
70
  ],
66
- "gitHead": "4f200eadd987eab9a2e38db6e8841849b743b615"
71
+ "gitHead": "e025c0ab74aa76547e2d0307de223c43d5271228"
67
72
  }