@runic-artifex/react 0.9.1 → 0.10.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,6 +111,20 @@ 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
@@ -148,7 +157,7 @@ neither.
148
157
  ## `useOperation(start, options?)`
149
158
 
150
159
  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).
160
+ [operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.10.0/packages/web/views#operation-feedback-and-latest-selection).
152
161
  `run(...args)` calls the latest `start`, so it may close over the current client:
153
162
 
154
163
  ```tsx
@@ -173,6 +182,33 @@ before the unmount ends there. The optional
173
182
  `cancel(operation)` and `waitForCompletion(operation, status)` callbacks are the
174
183
  controller's options.
175
184
 
185
+ ## `useLatestOperation()`
186
+
187
+ Admits only the newest of several reads, for example loading the item the user
188
+ selected last, through the framework-neutral
189
+ [latest-operation controller](https://github.com/Runic-Artifex/runic-sdk/tree/v0.10.0/packages/web/views#operation-feedback-and-latest-selection).
190
+ Each `run(intent)` replaces the queued intent and cancels the active read; the next
191
+ read starts only after the previous one reaches its terminal status and the intent's
192
+ optional `waitForCompletion` barrier:
193
+
194
+ ```tsx
195
+ const load = useLatestOperation<Item>();
196
+ // `client` comes from useView; the intent captures the one it starts on.
197
+ const select = (id: string) => { if (client) void load.run({ start: () => client.startLoad(id) }); };
198
+ {load.outcome?.ok && <ItemView item={load.outcome.value} />}
199
+ {load.blocked && <p role="alert">Reconnect before selecting again.</p>}
200
+ ```
201
+
202
+ The result has the `useOperation` fields plus `blocked`, with `run(intent)` and
203
+ `clear(mode?)`, which never reject. The intent carries `start` and the optional
204
+ `cancel`, `waitForCompletion` and `isCurrent` callbacks, so it captures the client or
205
+ session it belongs to. `blocked` means admission is uncertain, for example after a
206
+ lost Start reply; only `clear("replace")`, called after the application has
207
+ established a fresh session, clears it. `clear()` drops the queued intent and cancels
208
+ the active read. Unmounting disposes the controller like `useOperation`: pending runs
209
+ resolve to `undefined` and accepted work is never cancelled. StrictMode's simulated
210
+ unmount starts a fresh controller.
211
+
176
212
  ## Errors
177
213
 
178
214
  The `error` of `useView` and of a command or operation handle is typed
@@ -187,7 +223,7 @@ const offline = error instanceof BridgeError && error.kind === "disconnected";
187
223
  ```
188
224
 
189
225
  `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)
226
+ [Errors and diagnostics](https://github.com/Runic-Artifex/runic-sdk/tree/v0.10.0/packages/web/views#errors-and-diagnostics)
191
227
  lists the kinds. Any other value, such as an exception that your own connect
192
228
  function or command callback throws, arrives unchanged.
193
229
 
@@ -229,19 +265,16 @@ the application's own dialog.
229
265
  such as a close during the page's first render, is answered by the
230
266
  ViewModel's .NET fallback handler, or fails closed without one.
231
267
 
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)
268
+ The [ReactiveUI leave confirmation](https://github.com/Runic-Artifex/runic-sdk/blob/v0.10.0/packages/dotnet/Runic.Application.Views.ReactiveUI/README.md#leave-confirmation-in-a-web-view)
233
269
  has the .NET side and which View answers which departure. In a frontend test,
234
270
  the generated mock's `interactions.<name>.request(input)` resolves with the
235
271
  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)
272
+ [Testing guide](https://github.com/Runic-Artifex/runic-sdk/tree/v0.10.0/packages/web/views#testing).
239
273
 
240
- Exported from `@runic-artifex/react/experimental`, like the
241
- `@runic-artifex/views/experimental` controller it wraps.
274
+ ## `useCollectionViewport(options)`
242
275
 
243
276
  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)
277
+ `viewport` is the [`collectionViewport`](https://github.com/Runic-Artifex/runic-sdk/tree/v0.10.0/packages/web/views#collectionviewportoptions)
245
278
  range for the container; it changes only when the range or sizes change. Send
246
279
  the range to the ViewModel from an effect:
247
280
 
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 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;
@@ -100,3 +100,23 @@ export interface OperationHandle<TArgs extends readonly unknown[], TResult, TFai
100
100
  * ```
101
101
  */
102
102
  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>;
103
+ export interface LatestOperationHandle<TResult, TFailure = never> extends LatestOperationState<TResult, TFailure>, Pick<LatestOperationController<TResult, TFailure>, "run" | "clear"> {
104
+ }
105
+ /**
106
+ * Admits only the newest selection, for reads such as "load the selected item": each
107
+ * `run(intent)` replaces the queued intent and cancels the active read, and the next read
108
+ * starts only after the previous one has finished (including `waitForCompletion`). The
109
+ * intent carries `start`, `cancel`, `waitForCompletion` and `isCurrent`, so it may close over
110
+ * the current client. `blocked` means admission is uncertain; only `clear("replace")`, after
111
+ * the application has established a fresh session, clears it. Unmounting disposes the
112
+ * controller: pending runs resolve to undefined, but accepted work is never cancelled.
113
+ *
114
+ * ```tsx
115
+ * const load = useLatestOperation<Item>();
116
+ * <li onClick={() => load.run({ start: () => client?.startLoad(id) })}>…</li>
117
+ * {load.outcome?.ok && <ItemView item={load.outcome.value} />}
118
+ * ```
119
+ */
120
+ export declare function useLatestOperation<TResult = void, TFailure = never>(): LatestOperationHandle<TResult, TFailure>;
121
+ export { retrySuspenseView, useSuspenseView, type SuspenseViewHandle, type SuspenseViewOptions } from "./suspense.js";
122
+ export { useCollectionViewport, type CollectionViewportHandle } from "./viewport.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, } 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.
@@ -185,3 +185,26 @@ export function useOperation(start, options = {}) {
185
185
  const current = useSyncExternalStore(controller.subscribe, read, read);
186
186
  return { ...current, run: controller.run, cancel: controller.cancel, reset: controller.reset };
187
187
  }
188
+ /**
189
+ * Admits only the newest selection, for reads such as "load the selected item": each
190
+ * `run(intent)` replaces the queued intent and cancels the active read, and the next read
191
+ * starts only after the previous one has finished (including `waitForCompletion`). The
192
+ * intent carries `start`, `cancel`, `waitForCompletion` and `isCurrent`, so it may close over
193
+ * the current client. `blocked` means admission is uncertain; only `clear("replace")`, after
194
+ * the application has established a fresh session, clears it. Unmounting disposes the
195
+ * controller: pending runs resolve to undefined, but accepted work is never cancelled.
196
+ *
197
+ * ```tsx
198
+ * const load = useLatestOperation<Item>();
199
+ * <li onClick={() => load.run({ start: () => client?.startLoad(id) })}>…</li>
200
+ * {load.outcome?.ok && <ItemView item={load.outcome.value} />}
201
+ * ```
202
+ */
203
+ export function useLatestOperation() {
204
+ const controller = useMountedController(() => createLatestOperationController());
205
+ const read = useCallback(() => controller.current, [controller]);
206
+ const current = useSyncExternalStore(controller.subscribe, read, read);
207
+ return { ...current, run: controller.run, clear: controller.clear };
208
+ }
209
+ export { retrySuspenseView, useSuspenseView } from "./suspense.js";
210
+ export { useCollectionViewport } from "./viewport.js";
@@ -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.10.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.10.0"
39
34
  },
40
35
  "devDependencies": {
41
- "@runic-artifex/views": "0.9.1",
36
+ "@runic-artifex/views": "0.10.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.10.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": "fcc71ba13aa56c8f1a720909c1074825a1f5dd6f"
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";