@runic-artifex/react 0.9.1 → 0.11.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
@@ -88,18 +88,13 @@ export function CounterPage({ page }: { page: CounterPageReference }) {
88
88
  The control shows the ViewModel's value, so it reverts when the setter throws
89
89
  or keeps a different value.
90
90
 
91
- ## `useSuspenseView(source)` (experimental)
92
-
93
- `useSuspenseView` and `retrySuspenseView` are exported from
94
- `@runic-artifex/react/experimental`: the module-wide connection cache and its
95
- ten-second timeout may change in a minor release (see
96
- [experimental APIs](https://github.com/Runic-Artifex/runic-sdk/blob/v0.9.1/docs/experimental.md#npm-packages)).
91
+ ## `useSuspenseView(source, options?)`
97
92
 
98
93
  Suspends the component until a reference connects, then returns
99
94
  `{ state, client }` without `undefined`. A failed connection is thrown to the
100
95
  nearest error boundary. Call `retrySuspenseView(reference)` when the boundary
101
96
  resets, so the next render connects again; an unretried failure is forgotten
102
- after ten seconds:
97
+ after `releaseTimeout`:
103
98
 
104
99
  ```tsx
105
100
  <ErrorBoundary fallback={<p role="alert">Offline</p>} onReset={() => retrySuspenseView(page)}>
@@ -116,14 +111,36 @@ Components that pass a reference with the same `connect` function share one
116
111
  client, which is disposed after the last of them unmounts. The reference must
117
112
  be stable: a `connect` function created during render never resolves.
118
113
 
114
+ The connections live in a module-wide cache until a component claims them,
115
+ because Suspense discards the state of a component that never mounted.
116
+ `options.releaseTimeout` is how many milliseconds a connection that no mounted
117
+ component has claimed, or a failure that no `retrySuspenseView` has cleared,
118
+ stays cached. It defaults to 10000 (ten seconds); `Infinity` keeps the entry
119
+ until it is claimed or retried. Other values must be whole numbers from 1 to
120
+ 2147483647, or the hook throws a `RangeError`. It is not a connection timeout.
121
+ Components that share a `connect` function share one entry, which keeps the
122
+ largest `releaseTimeout` any of them passed:
123
+
124
+ ```tsx
125
+ const { state } = useSuspenseView(page, { releaseTimeout: 30_000 });
126
+ ```
127
+
119
128
  ## `ViewOutlet`
120
129
 
121
130
  `<ViewOutlet content={reference} registry={pages} fallback={…} />` renders the
122
131
  component registered for `reference.kind` with the reference as its `page`
123
132
  prop. Declare the registry with `satisfies ViewRegistry<State["main"]>` so each
124
133
  kind has a component whose `page` prop matches. A different reference
125
- remounts the component; a kind without a component renders an alert, and
126
- `fallback` renders while `content` is empty.
134
+ remounts the component; a kind without a component renders an English
135
+ `<p role="alert">`, and `fallback` renders while `content` is empty.
136
+
137
+ `missing` replaces that alert, for example with localized text. It receives the
138
+ reference whose kind has no component, and its markup (including any `role`) is yours:
139
+
140
+ ```tsx
141
+ <ViewOutlet content={state?.main} registry={pages}
142
+ missing={page => <p role="alert">{t("missingView", { kind: page.kind })}</p>} />
143
+ ```
127
144
 
128
145
  ## `useCommand(command)`
129
146
 
@@ -148,7 +165,7 @@ neither.
148
165
  ## `useOperation(start, options?)`
149
166
 
150
167
  Observes a generated `start<Command>()` operation through the framework-neutral
151
- [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.9.1/packages/web/views#operation-feedback-and-latest-selection).
168
+ [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.11.0/packages/web/views#operation-feedback-and-latest-selection).
152
169
  `run(...args)` calls the latest `start`, so it may close over the current client:
153
170
 
154
171
  ```tsx
@@ -173,6 +190,142 @@ before the unmount ends there. The optional
173
190
  `cancel(operation)` and `waitForCompletion(operation, status)` callbacks are the
174
191
  controller's options.
175
192
 
193
+ ## `useLatestOperation()`
194
+
195
+ Admits only the newest of several reads, for example loading the item the user
196
+ selected last, through the framework-neutral
197
+ [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.11.0/packages/web/views#operation-feedback-and-latest-selection).
198
+ Each `run(intent)` replaces the queued intent and cancels the active read; the next
199
+ read starts only after the previous one reaches its terminal status and the intent's
200
+ optional `waitForCompletion` barrier:
201
+
202
+ ```tsx
203
+ const load = useLatestOperation<Item>();
204
+ // `client` comes from useView; the intent captures the one it starts on.
205
+ const select = (id: string) => { if (client) void load.run({ start: () => client.startLoad(id) }); };
206
+ {load.outcome?.ok && <ItemView item={load.outcome.value} />}
207
+ {load.blocked && <p role="alert">Reconnect before selecting again.</p>}
208
+ ```
209
+
210
+ The result has the `useOperation` fields plus `blocked`, with `run(intent)` and
211
+ `clear(mode?)`, which never reject. The intent carries `start` and the optional
212
+ `cancel`, `waitForCompletion` and `isCurrent` callbacks, so it captures the client or
213
+ session it belongs to. `blocked` means admission is uncertain, for example after a
214
+ lost Start reply; only `clear("replace")`, called after the application has
215
+ established a fresh session, clears it. `clear()` drops the queued intent and cancels
216
+ the active read. Unmounting disposes the controller like `useOperation`: pending runs
217
+ resolve to `undefined` and accepted work is never cancelled. StrictMode's simulated
218
+ unmount starts a fresh controller.
219
+
220
+ ## `useBridgeConnection(options?)`
221
+
222
+ Renders the page's connection to its .NET host while the component is mounted.
223
+ It wraps `onBridgeConnection` from `@runic-artifex/views` (re-exported here since 0.11, with the
224
+ `BridgeConnectionState` and `BridgeConnectionOptions` types) and returns
225
+ `{ state }`, where `state` is a `BridgeConnectionState`: `connecting`,
226
+ `connected`, `reconnecting` or `lost` (a closed set, see
227
+ [Connection state](https://github.com/Runic-Artifex/runic-sdk/tree/v0.11.0/packages/web/views#connection-state)):
228
+
229
+ ```tsx
230
+ import { useBridgeConnection } from "@runic-artifex/react";
231
+
232
+ function ConnectionBanner() {
233
+ const connection = useBridgeConnection({ lostAfter: 5_000 });
234
+ return connection.state === "lost" ? <p role="alert">The application stopped responding.</p> : null;
235
+ }
236
+ ```
237
+
238
+ The first render already has the current state. Unmounting unsubscribes, and
239
+ StrictMode's simulated unmount keeps one subscription. A changed `lostAfter`
240
+ subscribes again; an invalid one throws a `RangeError`. A server render reads
241
+ `connecting` and does not observe.
242
+
243
+ ## `useMenuBar(options?)`
244
+
245
+ Follows the declared menu bar of a Runic Desktop window that leaves it to the
246
+ page (`DesktopMenuBarPresentation.Page`) while the component is mounted. It
247
+ wraps `createMenuBarController` from `@runic-artifex/views` (see
248
+ [In-page menu bar](https://github.com/Runic-Artifex/runic-sdk/tree/v0.11.0/packages/web/views#in-page-menu-bar)) and returns `{ state, invoke, handleKeyDown }`: `state` is a
249
+ `MenuBarState`, and the bar is rendered by the menubar component of the
250
+ application's own UI library. Runic ships no menubar component.
251
+
252
+ ```tsx
253
+ import { useMenuBar } from "@runic-artifex/react";
254
+
255
+ function AppMenuBar() {
256
+ const [open, setOpen] = useState("");
257
+ const menuBar = useMenuBar({
258
+ onRequest: request => request.kind === "open" ? setOpen(request.menu.key) : focusFirstTrigger(),
259
+ });
260
+ // On macOS the application menu bar keeps the menus ("global"): render nothing.
261
+ if (menuBar.state.placement !== "page") return null;
262
+ // Map menuBar.state.menus to the component; an item's select handler calls menuBar.invoke(item).
263
+ }
264
+ ```
265
+
266
+ Options are those of `createMenuBarController` (`shortcuts`, `keyboard`)
267
+ without `signal`, plus `onRequest`, which receives the `focus` and `open`
268
+ requests; the latest function is called. A changed `shortcuts` or `keyboard`
269
+ creates a new controller, and unmounting disposes it, which also returns the
270
+ `shortcuts: "app"` lease. StrictMode's simulated unmount keeps one controller.
271
+ The controller starts in an effect, so a server render reads `connecting`, and
272
+ `invoke` rejects with a `BridgeError` (`disconnected`) until then.
273
+
274
+ ### With Base UI or Radix
275
+
276
+ Base UI's `Menubar` (`@base-ui/react`, the base of shadcn/ui's Base UI
277
+ Menubar) with a controlled open menu; the
278
+ [Notes example](https://github.com/Runic-Artifex/runic-sdk/tree/v0.11.0/examples/notes-view-first#in-page-menu-bar) adds submenus, check and radio
279
+ items and is tested with real keys:
280
+
281
+ ```tsx
282
+ import { Menu } from "@base-ui/react/menu";
283
+ import { Menubar } from "@base-ui/react/menubar";
284
+ import { splitAccessKey, type MenuBarItem, type MenuBarMenu } from "@runic-artifex/views";
285
+ import { useMenuBar } from "@runic-artifex/react";
286
+
287
+ function AppMenuBar() {
288
+ const bar = useRef<HTMLDivElement>(null);
289
+ const [open, setOpen] = useState<string | null>(null);
290
+ const menuBar = useMenuBar({
291
+ onRequest: request => request.kind === "open"
292
+ ? setOpen(request.menu.key)
293
+ : bar.current?.querySelector<HTMLElement>("[role=menuitem]")?.focus(),
294
+ });
295
+ const { placement, menus, accessKeyHints } = menuBar.state;
296
+ if (placement !== "page") return null;
297
+ const label = (entry: MenuBarMenu | MenuBarItem) => {
298
+ const [before, key, after] = splitAccessKey(entry);
299
+ return <>{before}{accessKeyHints ? <u>{key}</u> : key}{after}</>;
300
+ };
301
+ return (
302
+ <Menubar ref={bar} aria-label="Application">
303
+ {menus.map(menu => (
304
+ <Menu.Root key={menu.key} disabled={!menu.enabled} open={open === menu.key}
305
+ onOpenChange={next => setOpen(current => next ? menu.key : current === menu.key ? null : current)}>
306
+ <Menu.Trigger>{label(menu)}</Menu.Trigger>
307
+ <Menu.Portal><Menu.Positioner align="start"><Menu.Popup>
308
+ {menu.entries.map(entry => entry.kind === "separator" ? <Menu.Separator key={entry.key} />
309
+ : entry.kind === "item" ? (
310
+ <Menu.Item key={entry.key} disabled={!entry.enabled} aria-keyshortcuts={entry.ariaKeyShortcuts}
311
+ onClick={() => void menuBar.invoke(entry)}>
312
+ {label(entry)} <kbd aria-hidden>{entry.shortcutText}</kbd>
313
+ </Menu.Item>)
314
+ : null /* a submenu: Menu.SubmenuRoot */)}
315
+ </Menu.Popup></Menu.Positioner></Menu.Portal>
316
+ </Menu.Root>
317
+ ))}
318
+ </Menubar>
319
+ );
320
+ }
321
+ ```
322
+
323
+ With Radix (`@radix-ui/react-menubar`) the open menu is the root's controlled
324
+ `value`: `<Menubar.Root value={open} onValueChange={setOpen}>`, each
325
+ `<Menubar.Menu value={menu.key}>`, and `<Menubar.Item onSelect={() => menuBar.invoke(item)}>`.
326
+ Check items are `Menubar.CheckboxItem checked`, radio groups
327
+ `Menubar.RadioGroup value` with `Menubar.RadioItem`.
328
+
176
329
  ## Errors
177
330
 
178
331
  The `error` of `useView` and of a command or operation handle is typed
@@ -187,7 +340,7 @@ const offline = error instanceof BridgeError && error.kind === "disconnected";
187
340
  ```
188
341
 
189
342
  `instanceof` holds for errors from every copy of the package on the page.
190
- [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.9.1/packages/web/views#errors-and-diagnostics)
343
+ [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.11.0/packages/web/views#errors-and-diagnostics)
191
344
  lists the kinds. Any other value, such as an exception that your own connect
192
345
  function or command callback throws, arrives unchanged.
193
346
 
@@ -229,19 +382,16 @@ the application's own dialog.
229
382
  such as a close during the page's first render, is answered by the
230
383
  ViewModel's .NET fallback handler, or fails closed without one.
231
384
 
232
- The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.9.1/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
385
+ The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.11.0/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
233
386
  has the .NET side and which View answers which departure. In a frontend test,
234
387
  the generated mock's `interactions.<name>.request(input)` resolves with the
235
388
  registered handler's answer; see the
236
- [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.9.1/packages/web/views#testing).
237
-
238
- ## `useCollectionViewport(options)` (experimental)
389
+ [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.11.0/packages/web/views#testing).
239
390
 
240
- Exported from `@runic-artifex/react/experimental`, like the
241
- `@runic-artifex/views/experimental` controller it wraps.
391
+ ## `useCollectionViewport(options)`
242
392
 
243
393
  Follows a fixed-row-height scroll container and returns `{ viewport, ref }`.
244
- `viewport` is the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.9.1/packages/web/views#collectionviewportoptions-experimental)
394
+ `viewport` is the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.11.0/packages/web/views#collectionviewportoptions)
245
395
  range for the container; it changes only when the range or sizes change. Send
246
396
  the range to the ViewModel from an effect:
247
397
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type ComponentType, type ReactNode } from "react";
2
- import { type BridgeOperation, type BridgeOutcomeFailure, type OperationController, type OperationControllerOptions, type OperationState, type PageReference, type ViewClient, type ViewSource } from "@runic-artifex/views";
2
+ import { type BridgeConnectionOptions, type BridgeConnectionState, type BridgeOperation, type BridgeOutcomeFailure, type LatestOperationController, type LatestOperationState, type OperationController, type OperationControllerOptions, type OperationState, type PageReference, type ViewClient, type ViewSource } from "@runic-artifex/views";
3
3
  export interface ViewHandle<TClient extends ViewClient> {
4
4
  /** The latest state, or undefined until the client connects. */
5
5
  readonly state: TClient["snapshot"] | undefined;
@@ -44,13 +44,18 @@ export interface ViewOutletProps<R extends PageReference> {
44
44
  readonly registry: ViewRegistry<R>;
45
45
  /** Rendered while there is no content. Defaults to nothing. */
46
46
  readonly fallback?: ReactNode;
47
+ /**
48
+ * Renders a reference whose kind has no registered component, for example localized text.
49
+ * Defaults to an English `<p role="alert">`.
50
+ */
51
+ readonly missing?: (content: R) => ReactNode;
47
52
  }
48
53
  /**
49
54
  * Renders the registered component for a generated View reference and passes
50
55
  * the reference as its `page` prop. A different reference remounts the
51
- * component. A kind without a component renders an alert.
56
+ * component. A kind without a component renders `missing`, or an English alert without it.
52
57
  */
53
- export declare function ViewOutlet<R extends PageReference>({ content, registry, fallback }: ViewOutletProps<R>): ReactNode;
58
+ export declare function ViewOutlet<R extends PageReference>({ content, registry, fallback, missing }: ViewOutletProps<R>): ReactNode;
54
59
  export interface CommandHandle<TArgs extends readonly unknown[], TResult, TFailure = BridgeOutcomeFailure<TResult>> {
55
60
  /**
56
61
  * Runs the command. Resolves to its result, including a `BridgeOutcome` with a
@@ -100,3 +105,40 @@ export interface OperationHandle<TArgs extends readonly unknown[], TResult, TFai
100
105
  * ```
101
106
  */
102
107
  export declare function useOperation<TArgs extends readonly unknown[], TResult, TFailure = never>(start: (...args: TArgs) => BridgeOperation<TResult, TFailure> | undefined | PromiseLike<BridgeOperation<TResult, TFailure> | undefined>, options?: OperationControllerOptions<TResult, TFailure>): OperationHandle<TArgs, TResult, TFailure>;
108
+ export interface LatestOperationHandle<TResult, TFailure = never> extends LatestOperationState<TResult, TFailure>, Pick<LatestOperationController<TResult, TFailure>, "run" | "clear"> {
109
+ }
110
+ /**
111
+ * Admits only the newest selection, for reads such as "load the selected item": each
112
+ * `run(intent)` replaces the queued intent and cancels the active read, and the next read
113
+ * starts only after the previous one has finished (including `waitForCompletion`). The
114
+ * intent carries `start`, `cancel`, `waitForCompletion` and `isCurrent`, so it may close over
115
+ * the current client. `blocked` means admission is uncertain; only `clear("replace")`, after
116
+ * the application has established a fresh session, clears it. Unmounting disposes the
117
+ * controller: pending runs resolve to undefined, but accepted work is never cancelled.
118
+ *
119
+ * ```tsx
120
+ * const load = useLatestOperation<Item>();
121
+ * <li onClick={() => load.run({ start: () => client?.startLoad(id) })}>…</li>
122
+ * {load.outcome?.ok && <ItemView item={load.outcome.value} />}
123
+ * ```
124
+ */
125
+ export declare function useLatestOperation<TResult = void, TFailure = never>(): LatestOperationHandle<TResult, TFailure>;
126
+ export interface BridgeConnectionHandle {
127
+ /** The connection to the .NET host, as `onBridgeConnection` reports it. */
128
+ readonly state: BridgeConnectionState;
129
+ }
130
+ /**
131
+ * Renders the page's connection to its .NET host (`connecting`, `connected`, `reconnecting`
132
+ * or `lost`) while the component is mounted, through `onBridgeConnection`. A changed
133
+ * `lostAfter` subscribes again. The server snapshot is `connecting`.
134
+ *
135
+ * ```tsx
136
+ * const connection = useBridgeConnection();
137
+ * {connection.state === "lost" && <p role="alert">The application stopped responding.</p>}
138
+ * ```
139
+ */
140
+ export declare function useBridgeConnection(options?: BridgeConnectionOptions): BridgeConnectionHandle;
141
+ export { retrySuspenseView, useSuspenseView, type SuspenseViewHandle, type SuspenseViewOptions } from "./suspense.js";
142
+ export { useCollectionViewport, type CollectionViewportHandle } from "./viewport.js";
143
+ export { onBridgeConnection, type BridgeConnectionOptions, type BridgeConnectionState } from "@runic-artifex/views";
144
+ export { useMenuBar, type MenuBarEntry, type MenuBarHandle, type MenuBarInvokeResult, type MenuBarItem, type MenuBarMenu, type MenuBarRequest, type MenuBarSeparator, type MenuBarState, type UseMenuBarOptions, } from "./menu-bar.js";
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createElement, useCallback, useEffect, useInsertionEffect, useReducer, useRef, useState, useSyncExternalStore, } from "react";
2
- import { createCommandController, createOperationController, createViewController, } from "@runic-artifex/views";
2
+ import { createCommandController, createLatestOperationController, createOperationController, createViewController, onBridgeConnection, } from "@runic-artifex/views";
3
3
  import { isViewClient, viewSourceIdentity } from "@runic-artifex/views/bindings";
4
4
  // An inline `{ connect: () => connectX() }` creates a new function on every
5
5
  // render, so every render reconnects and each connection renders again.
@@ -106,14 +106,17 @@ function referenceKey(reference) {
106
106
  /**
107
107
  * Renders the registered component for a generated View reference and passes
108
108
  * the reference as its `page` prop. A different reference remounts the
109
- * component. A kind without a component renders an alert.
109
+ * component. A kind without a component renders `missing`, or an English alert without it.
110
110
  */
111
- export function ViewOutlet({ content, registry, fallback = null }) {
111
+ export function ViewOutlet({ content, registry, fallback = null, missing }) {
112
112
  if (!content)
113
113
  return fallback;
114
114
  const component = registry[content.kind];
115
- if (!component)
115
+ if (!component) {
116
+ if (missing)
117
+ return missing(content);
116
118
  return createElement("p", { role: "alert" }, `No web component is registered for ${content.kind}.`);
119
+ }
117
120
  return createElement(component, { key: referenceKey(content), page: content });
118
121
  }
119
122
  // A command or operation controller lives while its component is mounted: unmounting disposes it,
@@ -185,3 +188,56 @@ export function useOperation(start, options = {}) {
185
188
  const current = useSyncExternalStore(controller.subscribe, read, read);
186
189
  return { ...current, run: controller.run, cancel: controller.cancel, reset: controller.reset };
187
190
  }
191
+ /**
192
+ * Admits only the newest selection, for reads such as "load the selected item": each
193
+ * `run(intent)` replaces the queued intent and cancels the active read, and the next read
194
+ * starts only after the previous one has finished (including `waitForCompletion`). The
195
+ * intent carries `start`, `cancel`, `waitForCompletion` and `isCurrent`, so it may close over
196
+ * the current client. `blocked` means admission is uncertain; only `clear("replace")`, after
197
+ * the application has established a fresh session, clears it. Unmounting disposes the
198
+ * controller: pending runs resolve to undefined, but accepted work is never cancelled.
199
+ *
200
+ * ```tsx
201
+ * const load = useLatestOperation<Item>();
202
+ * <li onClick={() => load.run({ start: () => client?.startLoad(id) })}>…</li>
203
+ * {load.outcome?.ok && <ItemView item={load.outcome.value} />}
204
+ * ```
205
+ */
206
+ export function useLatestOperation() {
207
+ const controller = useMountedController(() => createLatestOperationController());
208
+ const read = useCallback(() => controller.current, [controller]);
209
+ const current = useSyncExternalStore(controller.subscribe, read, read);
210
+ return { ...current, run: controller.run, clear: controller.clear };
211
+ }
212
+ // The state before the component subscribes: a subscription reports it at once.
213
+ function currentBridgeConnection(options) {
214
+ let current = "connecting";
215
+ onBridgeConnection(state => { current = state; }, options)();
216
+ return current;
217
+ }
218
+ /**
219
+ * Renders the page's connection to its .NET host (`connecting`, `connected`, `reconnecting`
220
+ * or `lost`) while the component is mounted, through `onBridgeConnection`. A changed
221
+ * `lostAfter` subscribes again. The server snapshot is `connecting`.
222
+ *
223
+ * ```tsx
224
+ * const connection = useBridgeConnection();
225
+ * {connection.state === "lost" && <p role="alert">The application stopped responding.</p>}
226
+ * ```
227
+ */
228
+ export function useBridgeConnection(options = {}) {
229
+ const { lostAfter } = options;
230
+ const [store] = useState(() => ({ state: undefined }));
231
+ const subscribe = useCallback((onChange) => onBridgeConnection(state => {
232
+ store.state = state;
233
+ onChange();
234
+ }, lostAfter === undefined ? {} : { lostAfter }), [store, lostAfter]);
235
+ const read = useCallback(() => store.state ??= currentBridgeConnection(lostAfter === undefined ? {} : { lostAfter }), [store, lostAfter]);
236
+ const state = useSyncExternalStore(subscribe, read, serverConnectionState);
237
+ return { state };
238
+ }
239
+ const serverConnectionState = () => "connecting";
240
+ export { retrySuspenseView, useSuspenseView } from "./suspense.js";
241
+ export { useCollectionViewport } from "./viewport.js";
242
+ export { onBridgeConnection } from "@runic-artifex/views";
243
+ export { useMenuBar, } from "./menu-bar.js";
@@ -0,0 +1,30 @@
1
+ import { type MenuBarController, type MenuBarControllerOptions, type MenuBarRequest, type MenuBarState } from "@runic-artifex/views";
2
+ export type { MenuBarEntry, MenuBarInvokeResult, MenuBarItem, MenuBarMenu, MenuBarRequest, MenuBarSeparator, MenuBarState, } from "@runic-artifex/views";
3
+ export interface UseMenuBarOptions extends Omit<MenuBarControllerOptions, "signal"> {
4
+ /**
5
+ * Receives the `focus` (Alt tap, F10) and `open` (Alt plus a menu's access key) requests: focus the first trigger
6
+ * or open the menu in the menubar component. The latest function is called.
7
+ */
8
+ readonly onRequest?: (request: MenuBarRequest) => void;
9
+ }
10
+ export interface MenuBarHandle {
11
+ /** The menu bar as the page renders it; render a bar only when `placement` is `"page"`. */
12
+ readonly state: MenuBarState;
13
+ /** Runs an item through the native bar's command path. Rejects with a BridgeError before the hook connected. */
14
+ readonly invoke: MenuBarController["invoke"];
15
+ /** Matches a `keydown` event against the items' shortcuts, for the `shortcuts: "app"` option. */
16
+ readonly handleKeyDown: MenuBarController["handleKeyDown"];
17
+ }
18
+ /**
19
+ * Follows the window's declared menu bar (Runic Desktop's `DesktopMenuBarPresentation.Page`) while the component is
20
+ * mounted, as headless state for the application's own menubar component, through `createMenuBarController`. Pass
21
+ * `invoke` to the component's item `onSelect`/`onClick` and map `onRequest` to it. A changed `shortcuts` or
22
+ * `keyboard` creates a new controller; unmounting disposes it. The server snapshot is `connecting`.
23
+ *
24
+ * ```tsx
25
+ * const menuBar = useMenuBar({ onRequest: request => request.kind === "open" ? setOpen(request.menu.key) : focusBar() });
26
+ * if (menuBar.state.placement !== "page") return null;
27
+ * menuBar.state.menus.map(menu => <Menubar.Menu key={menu.key}>…</Menubar.Menu>)
28
+ * ```
29
+ */
30
+ export declare function useMenuBar(options?: UseMenuBarOptions): MenuBarHandle;
@@ -0,0 +1,76 @@
1
+ import { useEffect, useInsertionEffect, useRef, useState, useSyncExternalStore } from "react";
2
+ import { BridgeError, createMenuBarController, } from "@runic-artifex/views";
3
+ // The state before a controller follows the host, as a new controller starts.
4
+ const connectingState = (shortcuts) => Object.freeze({
5
+ status: "connecting", placement: "none", shortcuts: shortcuts === "app" ? "app" : "host", accessKeyHints: false,
6
+ revision: 0, menus: Object.freeze([]),
7
+ });
8
+ // The controller listens to the window and polls the host from creation, so the effect owns it; render reads a
9
+ // store that mirrors the mounted controller.
10
+ function createMenuBarStore(shortcuts) {
11
+ const initial = connectingState(shortcuts);
12
+ const listeners = new Set();
13
+ let snapshot = initial;
14
+ let controller;
15
+ const publish = (next) => {
16
+ if (next === snapshot)
17
+ return;
18
+ snapshot = next;
19
+ for (const listener of [...listeners])
20
+ listener();
21
+ };
22
+ return {
23
+ initial,
24
+ subscribe(onChange) {
25
+ listeners.add(onChange);
26
+ return () => { listeners.delete(onChange); };
27
+ },
28
+ read: () => snapshot,
29
+ attach(mounted) {
30
+ controller = mounted;
31
+ const stop = mounted.subscribe(() => publish(mounted.current));
32
+ publish(mounted.current);
33
+ return () => {
34
+ stop();
35
+ if (controller === mounted)
36
+ controller = undefined;
37
+ };
38
+ },
39
+ invoke: item => controller
40
+ ? controller.invoke(item)
41
+ : Promise.reject(new BridgeError("disconnected", "The menu bar is not connected yet.", { route: "__runicMenuBarInvoke" })),
42
+ handleKeyDown: event => controller?.handleKeyDown(event) ?? false,
43
+ };
44
+ }
45
+ /**
46
+ * Follows the window's declared menu bar (Runic Desktop's `DesktopMenuBarPresentation.Page`) while the component is
47
+ * mounted, as headless state for the application's own menubar component, through `createMenuBarController`. Pass
48
+ * `invoke` to the component's item `onSelect`/`onClick` and map `onRequest` to it. A changed `shortcuts` or
49
+ * `keyboard` creates a new controller; unmounting disposes it. The server snapshot is `connecting`.
50
+ *
51
+ * ```tsx
52
+ * const menuBar = useMenuBar({ onRequest: request => request.kind === "open" ? setOpen(request.menu.key) : focusBar() });
53
+ * if (menuBar.state.placement !== "page") return null;
54
+ * menuBar.state.menus.map(menu => <Menubar.Menu key={menu.key}>…</Menubar.Menu>)
55
+ * ```
56
+ */
57
+ export function useMenuBar(options = {}) {
58
+ const { shortcuts, keyboard } = options;
59
+ const onRequest = useRef(options.onRequest);
60
+ useInsertionEffect(() => { onRequest.current = options.onRequest; });
61
+ const [store] = useState(() => createMenuBarStore(shortcuts));
62
+ useEffect(() => {
63
+ const controller = createMenuBarController({
64
+ ...(shortcuts === undefined ? {} : { shortcuts }),
65
+ ...(keyboard === undefined ? {} : { keyboard }),
66
+ });
67
+ controller.onRequest(request => onRequest.current?.(request));
68
+ const detach = store.attach(controller);
69
+ return () => {
70
+ detach();
71
+ controller.dispose();
72
+ };
73
+ }, [store, shortcuts, keyboard]);
74
+ const state = useSyncExternalStore(store.subscribe, store.read, () => store.initial);
75
+ return { state, invoke: store.invoke, handleKeyDown: store.handleKeyDown };
76
+ }
@@ -5,6 +5,17 @@ import type { ViewClient, ViewConnector } from "@runic-artifex/views";
5
5
  * component again. A connection that is pending or connected is unaffected.
6
6
  */
7
7
  export declare function retrySuspenseView(source: ViewConnector<ViewClient>): void;
8
+ export interface SuspenseViewOptions {
9
+ /**
10
+ * Milliseconds that a connection no mounted component has claimed, or a failure no
11
+ * `retrySuspenseView` has cleared, stays cached: a whole number from 1 to 2147483647,
12
+ * or `Infinity` to keep it until it is claimed or retried. Defaults to 10000. This is
13
+ * not a connection timeout. Components that share a `connect` function share one
14
+ * entry, which keeps the largest value any of them passed. Other values throw a
15
+ * `RangeError`.
16
+ */
17
+ readonly releaseTimeout?: number;
18
+ }
8
19
  export interface SuspenseViewHandle<TClient extends ViewClient> {
9
20
  /** The latest state. */
10
21
  readonly state: TClient["snapshot"];
@@ -15,7 +26,8 @@ export interface SuspenseViewHandle<TClient extends ViewClient> {
15
26
  * Suspends the component until a generated View reference connects, then
16
27
  * renders its state. A failed connection is thrown to the nearest error
17
28
  * boundary; call `retrySuspenseView(reference)` when resetting the boundary to
18
- * connect again. An unretried failure is forgotten after ten seconds.
29
+ * connect again. An unretried failure, and a connection whose component never
30
+ * mounted, is released after `options.releaseTimeout` (ten seconds by default).
19
31
  *
20
32
  * Components that pass a reference with the same `connect` function share one
21
33
  * client, which is disposed after the last of them unmounts. Pass a stable
@@ -23,4 +35,4 @@ export interface SuspenseViewHandle<TClient extends ViewClient> {
23
35
  * a function recreated on every render never resolves. An already connected
24
36
  * client is observed and left to its owner.
25
37
  */
26
- export declare function useSuspenseView<TClient extends ViewClient>(source: ViewConnector<TClient> | TClient): SuspenseViewHandle<TClient>;
38
+ export declare function useSuspenseView<TClient extends ViewClient>(source: ViewConnector<TClient> | TClient, options?: SuspenseViewOptions): SuspenseViewHandle<TClient>;
package/dist/suspense.js CHANGED
@@ -3,33 +3,51 @@ import { isViewClient } from "@runic-artifex/views/bindings";
3
3
  // Suspense discards the state of a component that never mounted, so pending
4
4
  // connections live here, keyed by connect function, until a component claims them.
5
5
  const suspended = new WeakMap();
6
- const unclaimedConnectionTimeout = 10_000;
6
+ const defaultReleaseTimeout = 10_000;
7
+ // setTimeout runs a larger delay, like Infinity, at once.
8
+ const maxReleaseTimeout = 2_147_483_647;
9
+ function checkReleaseTimeout(value) {
10
+ if (value === undefined)
11
+ return defaultReleaseTimeout;
12
+ if (value === Infinity || (Number.isInteger(value) && value >= 1 && value <= maxReleaseTimeout))
13
+ return value;
14
+ throw new RangeError(`useSuspenseView's releaseTimeout must be a whole number of milliseconds from 1 to ${maxReleaseTimeout}, ` +
15
+ `or Infinity, not ${String(value)}.`);
16
+ }
17
+ // Releases an entry no mounted component uses after `delay`: disposes its client, or
18
+ // forgets its failure so that a later render connects again. Infinity keeps it.
7
19
  function releaseLater(key, entry, delay) {
8
20
  clearTimeout(entry.timer);
9
- entry.timer = setTimeout(() => {
21
+ entry.timer = delay === Infinity ? undefined : setTimeout(() => {
10
22
  if (entry.users !== 0 || suspended.get(key) !== entry)
11
23
  return;
12
24
  suspended.delete(key);
13
25
  entry.client?.dispose();
14
26
  }, delay);
15
27
  }
16
- function suspendedConnection(connector) {
28
+ function suspendedConnection(connector, releaseTimeout) {
17
29
  const key = connector.connect;
18
30
  const existing = suspended.get(key);
19
- if (existing)
31
+ if (existing) {
32
+ if (releaseTimeout > existing.releaseTimeout) {
33
+ existing.releaseTimeout = releaseTimeout;
34
+ // A settled entry that nobody uses waits for the longer timeout from now.
35
+ if (existing.status !== "pending" && existing.users === 0)
36
+ releaseLater(key, existing, releaseTimeout);
37
+ }
20
38
  return existing;
21
- const entry = { status: "pending", promise: Promise.resolve(), users: 0 };
39
+ }
40
+ const entry = { status: "pending", promise: Promise.resolve(), users: 0, releaseTimeout };
22
41
  entry.promise = Promise.resolve().then(() => connector.connect()).then(client => {
23
42
  entry.status = "ready";
24
43
  entry.client = client;
25
44
  // Release a connection whose render was abandoned before it mounted.
26
- releaseLater(key, entry, unclaimedConnectionTimeout);
45
+ releaseLater(key, entry, entry.releaseTimeout);
27
46
  }, (error) => {
28
47
  entry.status = "failed";
29
48
  entry.error = error;
30
49
  // Keep the failure for the error boundary; forget it later so a later render reconnects.
31
- entry.timer = setTimeout(() => { if (suspended.get(key) === entry)
32
- suspended.delete(key); }, unclaimedConnectionTimeout);
50
+ releaseLater(key, entry, entry.releaseTimeout);
33
51
  });
34
52
  suspended.set(key, entry);
35
53
  return entry;
@@ -50,7 +68,8 @@ export function retrySuspenseView(source) {
50
68
  * Suspends the component until a generated View reference connects, then
51
69
  * renders its state. A failed connection is thrown to the nearest error
52
70
  * boundary; call `retrySuspenseView(reference)` when resetting the boundary to
53
- * connect again. An unretried failure is forgotten after ten seconds.
71
+ * connect again. An unretried failure, and a connection whose component never
72
+ * mounted, is released after `options.releaseTimeout` (ten seconds by default).
54
73
  *
55
74
  * Components that pass a reference with the same `connect` function share one
56
75
  * client, which is disposed after the last of them unmounts. Pass a stable
@@ -58,9 +77,10 @@ export function retrySuspenseView(source) {
58
77
  * a function recreated on every render never resolves. An already connected
59
78
  * client is observed and left to its owner.
60
79
  */
61
- export function useSuspenseView(source) {
80
+ export function useSuspenseView(source, options = {}) {
81
+ const releaseTimeout = checkReleaseTimeout(options.releaseTimeout);
62
82
  const connector = isViewClient(source) ? undefined : source;
63
- const entry = connector ? suspendedConnection(connector) : undefined;
83
+ const entry = connector ? suspendedConnection(connector, releaseTimeout) : undefined;
64
84
  const [, refresh] = useReducer((count) => count + 1, 0);
65
85
  useEffect(() => {
66
86
  if (!connector || !entry)
@@ -1,4 +1,4 @@
1
- import { type CollectionViewport, type CollectionViewportOptions } from "@runic-artifex/views/experimental";
1
+ import { type CollectionViewport, type CollectionViewportOptions } from "@runic-artifex/views";
2
2
  export interface CollectionViewportHandle {
3
3
  /** The rows to request and the sizes to render. */
4
4
  readonly viewport: CollectionViewport;
package/dist/viewport.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
2
- import { createCollectionViewportController, } from "@runic-artifex/views/experimental";
2
+ import { createCollectionViewportController, } from "@runic-artifex/views";
3
3
  /**
4
4
  * Follows a fixed-row-height scroll container and returns the rows to request
5
5
  * from .NET. Send `viewport.start` and `viewport.size` to the ViewModel from an
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runic-artifex/react",
3
- "version": "0.9.1",
3
+ "version": "0.11.0",
4
4
  "description": "React hooks for generated Runic Views clients",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -19,11 +19,6 @@
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
- },
27
22
  "./package.json": "./package.json"
28
23
  },
29
24
  "scripts": {
@@ -35,10 +30,10 @@
35
30
  },
36
31
  "peerDependencies": {
37
32
  "react": ">=18.3.0 <20",
38
- "@runic-artifex/views": "0.9.1"
33
+ "@runic-artifex/views": "0.11.0"
39
34
  },
40
35
  "devDependencies": {
41
- "@runic-artifex/views": "0.9.1",
36
+ "@runic-artifex/views": "0.11.0",
42
37
  "@types/react": "19.3.0",
43
38
  "@types/react-dom": "19.3.0",
44
39
  "happy-dom": "20.14.5",
@@ -56,7 +51,7 @@
56
51
  "url": "git+https://github.com/Runic-Artifex/runic-sdk.git",
57
52
  "directory": "packages/web/react"
58
53
  },
59
- "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.9.1/packages/web/react#readme",
54
+ "homepage": "https://github.com/Runic-Artifex/runic-sdk/tree/v0.11.0/packages/web/react#readme",
60
55
  "bugs": {
61
56
  "url": "https://github.com/Runic-Artifex/runic-sdk/issues"
62
57
  },
@@ -66,5 +61,5 @@
66
61
  "views",
67
62
  "react"
68
63
  ],
69
- "gitHead": "7df2f00a9800c180e266ca545d4d6a03bf78dc89"
64
+ "gitHead": "318762a9d5dcdd74303ca30b095fed355a1ab21f"
70
65
  }
@@ -1,2 +0,0 @@
1
- export { retrySuspenseView, useSuspenseView, type SuspenseViewHandle } from "./suspense.js";
2
- export { useCollectionViewport, type CollectionViewportHandle } from "./viewport.js";
@@ -1,4 +0,0 @@
1
- // `@runic-artifex/react/experimental`: hooks whose shape may still change in a minor release
2
- // (docs/experimental.md). Graduation moves an export to `@runic-artifex/react`.
3
- export { retrySuspenseView, useSuspenseView } from "./suspense.js";
4
- export { useCollectionViewport } from "./viewport.js";