@peers-app/peers-ui 0.26.5 → 0.27.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/dist/hooks/index.d.ts +7 -0
- package/dist/hooks/index.js +24 -0
- package/dist/hooks/use-observable-state.d.ts +12 -0
- package/dist/hooks/use-observable-state.js +15 -0
- package/dist/hooks/use-observable-state.test.js +64 -0
- package/dist/hooks/use-observable.d.ts +8 -0
- package/dist/hooks/use-observable.js +35 -0
- package/dist/hooks/use-observable.test.d.ts +1 -0
- package/dist/{hooks.test.js → hooks/use-observable.test.js} +22 -62
- package/dist/hooks/use-on-screen.d.ts +3 -0
- package/dist/hooks/use-on-screen.js +23 -0
- package/dist/hooks/use-promise.d.ts +9 -0
- package/dist/hooks/use-promise.js +31 -0
- package/dist/hooks/use-rows.d.ts +42 -0
- package/dist/hooks/use-rows.js +83 -0
- package/dist/hooks/use-rows.test.d.ts +1 -0
- package/dist/hooks/use-rows.test.js +175 -0
- package/dist/hooks/use-subscription.d.ts +10 -0
- package/dist/hooks/use-subscription.js +21 -0
- package/dist/hooks/use-tool.d.ts +43 -0
- package/dist/hooks/use-tool.js +82 -0
- package/dist/hooks/use-tool.test.d.ts +1 -0
- package/dist/hooks/use-tool.test.js +190 -0
- package/dist/screens/tools/tool-catalog-ipc.d.ts +6 -54
- package/dist/utils.d.ts +9 -4
- package/dist/utils.js +9 -174
- package/package.json +3 -3
- package/src/hooks/index.ts +8 -0
- package/src/hooks/use-observable-state.test.tsx +101 -0
- package/src/hooks/use-observable-state.ts +29 -0
- package/src/{hooks.test.tsx → hooks/use-observable.test.tsx} +27 -100
- package/src/hooks/use-observable.ts +67 -0
- package/src/hooks/use-on-screen.ts +24 -0
- package/src/hooks/use-promise.ts +34 -0
- package/src/hooks/use-rows.test.tsx +196 -0
- package/src/hooks/use-rows.ts +120 -0
- package/src/hooks/use-subscription.ts +24 -0
- package/src/hooks/use-tool.test.tsx +225 -0
- package/src/hooks/use-tool.ts +116 -0
- package/src/utils.ts +9 -167
- package/dist/hooks.d.ts +0 -36
- package/dist/hooks.js +0 -108
- package/src/hooks.ts +0 -150
- /package/dist/{hooks.test.d.ts → hooks/use-observable-state.test.d.ts} +0 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import type { IHostSubscribeOptions } from "@peers-app/peers-sdk";
|
|
2
|
+
import { act, render, renderHook, screen, waitFor } from "@testing-library/react";
|
|
3
|
+
import { type IRowsSource, useRows } from "./use-rows";
|
|
4
|
+
|
|
5
|
+
interface IRow {
|
|
6
|
+
id: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** A table whose reads are answered by the test, one at a time. */
|
|
10
|
+
function fakeTable(answer: (filter: unknown) => IRow[] | Promise<IRow[]>) {
|
|
11
|
+
const listeners = new Set<{ handler: () => void; options?: IHostSubscribeOptions }>();
|
|
12
|
+
const reads: unknown[] = [];
|
|
13
|
+
const table: IRowsSource<IRow> = {
|
|
14
|
+
list: jest.fn(async (filter) => {
|
|
15
|
+
reads.push(filter);
|
|
16
|
+
return answer(filter);
|
|
17
|
+
}),
|
|
18
|
+
dataChanged: {
|
|
19
|
+
subscribe: (handler, options) => {
|
|
20
|
+
const listener = { handler: () => handler({}), options };
|
|
21
|
+
listeners.add(listener);
|
|
22
|
+
return { unsubscribe: () => listeners.delete(listener) };
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
table,
|
|
28
|
+
reads,
|
|
29
|
+
listeners,
|
|
30
|
+
change: () => {
|
|
31
|
+
for (const listener of listeners) listener.handler();
|
|
32
|
+
},
|
|
33
|
+
reconnect: () => {
|
|
34
|
+
for (const listener of listeners) listener.options?.onReconnect?.();
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function Rows({ table, filter }: { table: IRowsSource<IRow>; filter?: Partial<IRow> }) {
|
|
40
|
+
const { rows, loading, error } = useRows(table, filter);
|
|
41
|
+
return (
|
|
42
|
+
<div>
|
|
43
|
+
<span data-testid="rows">{rows.map((row) => row.id).join(",")}</span>
|
|
44
|
+
<span data-testid="loading">{String(loading)}</span>
|
|
45
|
+
<span data-testid="error">{error?.message ?? ""}</span>
|
|
46
|
+
</div>
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const text = (id: string) => screen.getByTestId(id).textContent;
|
|
51
|
+
|
|
52
|
+
describe("useRows", () => {
|
|
53
|
+
test("reads on mount and again when the table changes", async () => {
|
|
54
|
+
let rows = [{ id: "a" }];
|
|
55
|
+
const fake = fakeTable(() => rows);
|
|
56
|
+
render(<Rows table={fake.table} />);
|
|
57
|
+
expect(text("loading")).toBe("true");
|
|
58
|
+
await waitFor(() => expect(text("rows")).toBe("a"));
|
|
59
|
+
expect(text("loading")).toBe("false");
|
|
60
|
+
|
|
61
|
+
rows = [{ id: "a" }, { id: "b" }];
|
|
62
|
+
act(() => fake.change());
|
|
63
|
+
await waitFor(() => expect(text("rows")).toBe("a,b"));
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("changes during a read cause one more read, not one per change", async () => {
|
|
67
|
+
let release: (() => void) | undefined;
|
|
68
|
+
let n = 0;
|
|
69
|
+
const fake = fakeTable(
|
|
70
|
+
() =>
|
|
71
|
+
new Promise<IRow[]>((resolve) => {
|
|
72
|
+
const id = String(++n);
|
|
73
|
+
release = () => resolve([{ id }]);
|
|
74
|
+
}),
|
|
75
|
+
);
|
|
76
|
+
render(<Rows table={fake.table} />);
|
|
77
|
+
await waitFor(() => expect(fake.reads).toHaveLength(1));
|
|
78
|
+
act(() => {
|
|
79
|
+
fake.change();
|
|
80
|
+
fake.change();
|
|
81
|
+
fake.change();
|
|
82
|
+
});
|
|
83
|
+
await act(async () => release?.());
|
|
84
|
+
await waitFor(() => expect(fake.reads).toHaveLength(2));
|
|
85
|
+
await act(async () => release?.());
|
|
86
|
+
await waitFor(() => expect(text("rows")).toBe("2"));
|
|
87
|
+
expect(fake.reads).toHaveLength(2);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test("reads again after a reconnect", async () => {
|
|
91
|
+
let rows = [{ id: "a" }];
|
|
92
|
+
const fake = fakeTable(() => rows);
|
|
93
|
+
render(<Rows table={fake.table} />);
|
|
94
|
+
await waitFor(() => expect(text("rows")).toBe("a"));
|
|
95
|
+
rows = [{ id: "missed" }];
|
|
96
|
+
act(() => fake.reconnect());
|
|
97
|
+
await waitFor(() => expect(text("rows")).toBe("missed"));
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("reports a failed read and keeps the last rows", async () => {
|
|
101
|
+
let fail = false;
|
|
102
|
+
const fake = fakeTable(() => {
|
|
103
|
+
if (fail) throw new Error("host is down");
|
|
104
|
+
return [{ id: "a" }];
|
|
105
|
+
});
|
|
106
|
+
render(<Rows table={fake.table} />);
|
|
107
|
+
await waitFor(() => expect(text("rows")).toBe("a"));
|
|
108
|
+
fail = true;
|
|
109
|
+
act(() => fake.change());
|
|
110
|
+
await waitFor(() => expect(text("error")).toBe("host is down"));
|
|
111
|
+
expect(text("rows")).toBe("a");
|
|
112
|
+
fail = false;
|
|
113
|
+
act(() => fake.change());
|
|
114
|
+
await waitFor(() => expect(text("error")).toBe(""));
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test("reads again when the filter changes, and unsubscribes on unmount", async () => {
|
|
118
|
+
const fake = fakeTable((filter) => [{ id: JSON.stringify(filter) }]);
|
|
119
|
+
const { rerender, unmount } = render(<Rows table={fake.table} filter={{ id: "x" }} />);
|
|
120
|
+
await waitFor(() => expect(text("rows")).toBe('{"id":"x"}'));
|
|
121
|
+
// An equal filter in a new object doesn't read again.
|
|
122
|
+
rerender(<Rows table={fake.table} filter={{ id: "x" }} />);
|
|
123
|
+
rerender(<Rows table={fake.table} filter={{ id: "y" }} />);
|
|
124
|
+
await waitFor(() => expect(text("rows")).toBe('{"id":"y"}'));
|
|
125
|
+
expect(fake.reads).toEqual([{ id: "x" }, { id: "y" }]);
|
|
126
|
+
expect(fake.listeners.size).toBe(1);
|
|
127
|
+
unmount();
|
|
128
|
+
expect(fake.listeners.size).toBe(0);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test("reads again once an asynchronous subscription is live", async () => {
|
|
132
|
+
let rows = [{ id: "before" }];
|
|
133
|
+
const fake = fakeTable(() => rows);
|
|
134
|
+
let release!: (live: boolean) => void;
|
|
135
|
+
const ready = new Promise<boolean>((resolve) => {
|
|
136
|
+
release = resolve;
|
|
137
|
+
});
|
|
138
|
+
const subscribe = fake.table.dataChanged.subscribe;
|
|
139
|
+
fake.table.dataChanged.subscribe = (handler, options) => ({
|
|
140
|
+
...subscribe(handler, options),
|
|
141
|
+
ready,
|
|
142
|
+
});
|
|
143
|
+
render(<Rows table={fake.table} />);
|
|
144
|
+
await waitFor(() => expect(text("rows")).toBe("before"));
|
|
145
|
+
// No notification can be delivered while the remote subscription is still attaching.
|
|
146
|
+
rows = [{ id: "during setup" }];
|
|
147
|
+
await act(async () => release(true));
|
|
148
|
+
await waitFor(() => expect(text("rows")).toBe("during setup"));
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test("a synchronous list failure can be retried", async () => {
|
|
152
|
+
const fake = fakeTable(() => [{ id: "recovered" }]);
|
|
153
|
+
const list = fake.table.list;
|
|
154
|
+
fake.table.list = jest.fn(() => {
|
|
155
|
+
throw new Error("offline");
|
|
156
|
+
});
|
|
157
|
+
render(<Rows table={fake.table} />);
|
|
158
|
+
await waitFor(() => expect(text("error")).toBe("offline"));
|
|
159
|
+
fake.table.list = list;
|
|
160
|
+
act(() => fake.change());
|
|
161
|
+
await waitFor(() => expect(text("rows")).toBe("recovered"));
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test("reload retries a failed subscription", async () => {
|
|
165
|
+
const fake = fakeTable(() => [{ id: "recovered" }]);
|
|
166
|
+
const subscribe = fake.table.dataChanged.subscribe;
|
|
167
|
+
fake.table.dataChanged.subscribe = () => {
|
|
168
|
+
throw new Error("subscription unavailable");
|
|
169
|
+
};
|
|
170
|
+
const { result } = renderHook(() => useRows(fake.table));
|
|
171
|
+
await waitFor(() => expect(result.current.error?.message).toBe("subscription unavailable"));
|
|
172
|
+
fake.table.dataChanged.subscribe = subscribe;
|
|
173
|
+
await act(async () => result.current.reload());
|
|
174
|
+
expect(result.current.rows).toEqual([{ id: "recovered" }]);
|
|
175
|
+
expect(result.current.error).toBeUndefined();
|
|
176
|
+
expect(fake.listeners.size).toBe(1);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
test("reload resolves once the rows are current", async () => {
|
|
180
|
+
let rows = [{ id: "a" }];
|
|
181
|
+
const fake = fakeTable(() => rows);
|
|
182
|
+
let reload: (() => Promise<void>) | undefined;
|
|
183
|
+
function Reloading() {
|
|
184
|
+
const result = useRows(fake.table);
|
|
185
|
+
reload = result.reload;
|
|
186
|
+
return <span data-testid="rows">{result.rows.map((row) => row.id).join(",")}</span>;
|
|
187
|
+
}
|
|
188
|
+
render(<Reloading />);
|
|
189
|
+
await waitFor(() => expect(text("rows")).toBe("a"));
|
|
190
|
+
rows = [{ id: "b" }];
|
|
191
|
+
await act(async () => {
|
|
192
|
+
await reload?.();
|
|
193
|
+
});
|
|
194
|
+
expect(text("rows")).toBe("b");
|
|
195
|
+
});
|
|
196
|
+
});
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DataFilter,
|
|
3
|
+
IDataQueryParams,
|
|
4
|
+
IHostSubscribeOptions,
|
|
5
|
+
ISubscriptionResult,
|
|
6
|
+
} from "@peers-app/peers-sdk";
|
|
7
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
8
|
+
|
|
9
|
+
/** A table `useRows` can read: a `hostContract` table, or anything with the same two members. */
|
|
10
|
+
export interface IRowsSource<T extends Record<string, any>> {
|
|
11
|
+
/** Rows matching `filter`, with paging and sorting options. */
|
|
12
|
+
list(filter?: DataFilter<T>, options?: IDataQueryParams<T>): Promise<T[]>;
|
|
13
|
+
/**
|
|
14
|
+
* Changes to the rows. Optional `ready` acknowledges remote attachment; `onReconnect` runs
|
|
15
|
+
* once a replacement subscription is live, when changes may have been missed.
|
|
16
|
+
*/
|
|
17
|
+
readonly dataChanged: {
|
|
18
|
+
subscribe(
|
|
19
|
+
handler: (event: unknown) => void,
|
|
20
|
+
options?: IHostSubscribeOptions,
|
|
21
|
+
): ISubscriptionResult & { readonly ready?: Promise<boolean> };
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What {@link useRows} returns. */
|
|
26
|
+
export interface IUseRowsResult<T> {
|
|
27
|
+
/** The latest rows; empty until the first read. */
|
|
28
|
+
rows: T[];
|
|
29
|
+
/** True until a read settles after mounting or after the query changed. */
|
|
30
|
+
loading: boolean;
|
|
31
|
+
/** Why the latest read failed; cleared by the next one that succeeds. */
|
|
32
|
+
error: Error | undefined;
|
|
33
|
+
/** Read again now. Resolves when the rows are current. */
|
|
34
|
+
reload(): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Rows from a contract table, kept current: read on mount, and read again whenever the table
|
|
39
|
+
* changes, once an asynchronous subscription is live, after a reconnect, or when `filter` or
|
|
40
|
+
* `options` change (compared as JSON). Changes
|
|
41
|
+
* that arrive during a read cause one more read, not one per change.
|
|
42
|
+
*
|
|
43
|
+
* ```tsx
|
|
44
|
+
* const { rows: headlines, error } = useRows(news.tables.Headlines, {}, { pageSize: 100 });
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* @param table - A table from a `hostContract` client. Keep it stable (make the client once, at
|
|
48
|
+
* module scope, as `hostContract` does): a new table reads and subscribes again.
|
|
49
|
+
* @param filter - Which rows (all when omitted).
|
|
50
|
+
* @param options - Paging and sorting.
|
|
51
|
+
*/
|
|
52
|
+
export function useRows<T extends Record<string, any>>(
|
|
53
|
+
table: IRowsSource<T>,
|
|
54
|
+
filter?: DataFilter<T>,
|
|
55
|
+
options?: IDataQueryParams<T>,
|
|
56
|
+
): IUseRowsResult<T> {
|
|
57
|
+
const key = JSON.stringify([filter ?? {}, options ?? {}]);
|
|
58
|
+
const query = useRef({ filter, options });
|
|
59
|
+
query.current = { filter, options };
|
|
60
|
+
const [state, setState] = useState<{ rows: T[]; loading: boolean; error?: Error }>({
|
|
61
|
+
rows: [],
|
|
62
|
+
loading: true,
|
|
63
|
+
});
|
|
64
|
+
const reloadRef = useRef<() => Promise<void>>(async () => undefined);
|
|
65
|
+
|
|
66
|
+
// `key` stands for filter and options, which the reads take from `query`.
|
|
67
|
+
useEffect(() => {
|
|
68
|
+
let cancelled = false;
|
|
69
|
+
let again = false;
|
|
70
|
+
let reading: Promise<void> | undefined;
|
|
71
|
+
let subscription: ReturnType<IRowsSource<T>["dataChanged"]["subscribe"]> | undefined;
|
|
72
|
+
setState((previous) => (previous.loading ? previous : { ...previous, loading: true }));
|
|
73
|
+
|
|
74
|
+
const read = (): Promise<void> => {
|
|
75
|
+
again = true;
|
|
76
|
+
reading ??= Promise.resolve().then(async () => {
|
|
77
|
+
try {
|
|
78
|
+
while (again && !cancelled) {
|
|
79
|
+
again = false;
|
|
80
|
+
try {
|
|
81
|
+
if (!subscription) {
|
|
82
|
+
subscription = table.dataChanged.subscribe(readAgain, { onReconnect: readAgain });
|
|
83
|
+
// Read again after remote attachment, covering changes missed during setup
|
|
84
|
+
// without delaying the initial read's connection timeout.
|
|
85
|
+
void subscription.ready?.then((live) => {
|
|
86
|
+
if (live && !cancelled) readAgain();
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
const rows = await table.list(query.current.filter, query.current.options);
|
|
90
|
+
if (!cancelled) {
|
|
91
|
+
setState({ rows: Array.isArray(rows) ? rows : [], loading: false });
|
|
92
|
+
}
|
|
93
|
+
} catch (cause) {
|
|
94
|
+
if (!cancelled) {
|
|
95
|
+
const error = cause instanceof Error ? cause : new Error(String(cause));
|
|
96
|
+
setState((previous) => ({ rows: previous.rows, loading: false, error }));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
} finally {
|
|
101
|
+
reading = undefined;
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
return reading;
|
|
105
|
+
};
|
|
106
|
+
const readAgain = () => {
|
|
107
|
+
void read();
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
reloadRef.current = read;
|
|
111
|
+
readAgain();
|
|
112
|
+
return () => {
|
|
113
|
+
cancelled = true;
|
|
114
|
+
subscription?.unsubscribe();
|
|
115
|
+
};
|
|
116
|
+
}, [table, key]);
|
|
117
|
+
|
|
118
|
+
const reload = useCallback(() => reloadRef.current(), []);
|
|
119
|
+
return { rows: state.rows, loading: state.loading, error: state.error, reload };
|
|
120
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ReadonlyObservable } from "@peers-app/peers-sdk";
|
|
2
|
+
import { useEffect } from "react";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Use this to register a handler for an observable in a functional component.
|
|
6
|
+
* The handler is called immediately (unless `doNotCallOnChangeDuringSetup`) and whenever the
|
|
7
|
+
* observable changes.
|
|
8
|
+
* @param subscribable The observable to subscribe to
|
|
9
|
+
* @param onChange The function to call with the new value when the observable changes
|
|
10
|
+
* @param doNotCallOnChangeDuringSetup Skip the immediate call.
|
|
11
|
+
*/
|
|
12
|
+
export function useSubscription<T>(
|
|
13
|
+
subscribable: ReadonlyObservable<T>,
|
|
14
|
+
onChange: (value: T) => void,
|
|
15
|
+
doNotCallOnChangeDuringSetup?: boolean,
|
|
16
|
+
): void {
|
|
17
|
+
useEffect(() => {
|
|
18
|
+
if (!doNotCallOnChangeDuringSetup) {
|
|
19
|
+
onChange(subscribable());
|
|
20
|
+
}
|
|
21
|
+
const subscription = subscribable.subscribe(() => onChange(subscribable()));
|
|
22
|
+
return () => subscription.dispose();
|
|
23
|
+
}, [subscribable, onChange, doNotCallOnChangeDuringSetup]);
|
|
24
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { act, renderHook } from "@testing-library/react";
|
|
2
|
+
import { useTool } from "./use-tool";
|
|
3
|
+
|
|
4
|
+
function deferred<T>() {
|
|
5
|
+
let resolve!: (value: T) => void;
|
|
6
|
+
let reject!: (error: unknown) => void;
|
|
7
|
+
const promise = new Promise<T>((yes, no) => {
|
|
8
|
+
resolve = yes;
|
|
9
|
+
reject = no;
|
|
10
|
+
});
|
|
11
|
+
return { promise, resolve, reject };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
describe("useTool", () => {
|
|
15
|
+
test("tracks a run from pending to its result", async () => {
|
|
16
|
+
const answer = deferred<{ count: number }>();
|
|
17
|
+
const tool = jest.fn((_input?: { feed?: string }) => answer.promise);
|
|
18
|
+
const { result } = renderHook(() => useTool(tool));
|
|
19
|
+
expect(result.current.pending).toBe(false);
|
|
20
|
+
|
|
21
|
+
let running!: Promise<{ count: number } | undefined>;
|
|
22
|
+
act(() => {
|
|
23
|
+
running = result.current.run({ feed: "bbc" });
|
|
24
|
+
});
|
|
25
|
+
expect(result.current.pending).toBe(true);
|
|
26
|
+
expect(tool).toHaveBeenCalledWith({ feed: "bbc" });
|
|
27
|
+
|
|
28
|
+
await act(async () => answer.resolve({ count: 3 }));
|
|
29
|
+
await expect(running).resolves.toEqual({ count: 3 });
|
|
30
|
+
expect(result.current).toMatchObject({ pending: false, result: { count: 3 } });
|
|
31
|
+
expect(result.current.error).toBeUndefined();
|
|
32
|
+
|
|
33
|
+
const typeChecks = () => {
|
|
34
|
+
// @ts-expect-error the input is the tool's
|
|
35
|
+
void result.current.run({ feed: 1 });
|
|
36
|
+
const count: number | undefined = result.current.result?.count;
|
|
37
|
+
void count;
|
|
38
|
+
};
|
|
39
|
+
void typeChecks;
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("a failed run sets error and resolves undefined instead of throwing", async () => {
|
|
43
|
+
const onError = jest.fn();
|
|
44
|
+
const { result } = renderHook(() =>
|
|
45
|
+
useTool(
|
|
46
|
+
async () => {
|
|
47
|
+
throw "offline";
|
|
48
|
+
},
|
|
49
|
+
{ onError },
|
|
50
|
+
),
|
|
51
|
+
);
|
|
52
|
+
let outcome: unknown = "unset";
|
|
53
|
+
await act(async () => {
|
|
54
|
+
outcome = await result.current.run();
|
|
55
|
+
});
|
|
56
|
+
expect(outcome).toBeUndefined();
|
|
57
|
+
expect(result.current.error?.message).toBe("offline");
|
|
58
|
+
expect(result.current.pending).toBe(false);
|
|
59
|
+
expect(onError).toHaveBeenCalledWith(expect.any(Error));
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("a new run clears the last error and result", async () => {
|
|
63
|
+
let fail = true;
|
|
64
|
+
const { result } = renderHook(() =>
|
|
65
|
+
useTool(async () => {
|
|
66
|
+
if (fail) throw new Error("nope");
|
|
67
|
+
return "ok";
|
|
68
|
+
}),
|
|
69
|
+
);
|
|
70
|
+
await act(async () => {
|
|
71
|
+
await result.current.run();
|
|
72
|
+
});
|
|
73
|
+
expect(result.current.error).toBeDefined();
|
|
74
|
+
fail = false;
|
|
75
|
+
const next = deferred<void>();
|
|
76
|
+
act(() => {
|
|
77
|
+
void result.current.run().then(() => next.resolve());
|
|
78
|
+
});
|
|
79
|
+
expect(result.current.error).toBeUndefined();
|
|
80
|
+
expect(result.current.pending).toBe(true);
|
|
81
|
+
await act(async () => next.promise);
|
|
82
|
+
expect(result.current.result).toBe("ok");
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("overlapping runs: the state follows the latest, each run resolves its own result", async () => {
|
|
86
|
+
const slow = deferred<string>();
|
|
87
|
+
const fast = deferred<string>();
|
|
88
|
+
const answers = [slow, fast];
|
|
89
|
+
const onSuccess = jest.fn();
|
|
90
|
+
const { result } = renderHook(() =>
|
|
91
|
+
useTool(() => (answers.shift() as ReturnType<typeof deferred<string>>).promise, {
|
|
92
|
+
onSuccess,
|
|
93
|
+
}),
|
|
94
|
+
);
|
|
95
|
+
let first!: Promise<string | undefined>;
|
|
96
|
+
let second!: Promise<string | undefined>;
|
|
97
|
+
act(() => {
|
|
98
|
+
first = result.current.run();
|
|
99
|
+
second = result.current.run();
|
|
100
|
+
});
|
|
101
|
+
await act(async () => fast.resolve("fast"));
|
|
102
|
+
await expect(second).resolves.toBe("fast");
|
|
103
|
+
expect(result.current).toMatchObject({ pending: false, result: "fast" });
|
|
104
|
+
await act(async () => slow.resolve("slow"));
|
|
105
|
+
await expect(first).resolves.toBe("slow");
|
|
106
|
+
expect(result.current.result).toBe("fast");
|
|
107
|
+
expect(onSuccess.mock.calls.map(([value]) => value)).toEqual(["fast", "slow"]);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test("reset clears state but lets the pending call and callback finish", async () => {
|
|
111
|
+
const answer = deferred<string>();
|
|
112
|
+
const onSuccess = jest.fn();
|
|
113
|
+
const { result } = renderHook(() => useTool(() => answer.promise, { onSuccess }));
|
|
114
|
+
act(() => {
|
|
115
|
+
void result.current.run();
|
|
116
|
+
});
|
|
117
|
+
act(() => result.current.reset());
|
|
118
|
+
expect(result.current.pending).toBe(false);
|
|
119
|
+
await act(async () => answer.resolve("late"));
|
|
120
|
+
expect(result.current.result).toBeUndefined();
|
|
121
|
+
expect(onSuccess).toHaveBeenCalledWith("late");
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test("run is stable and calls the latest function and callbacks", async () => {
|
|
125
|
+
const onSuccess = jest.fn();
|
|
126
|
+
const { result, rerender } = renderHook(
|
|
127
|
+
({ label }: { label: string }) =>
|
|
128
|
+
useTool(async () => label, { onSuccess: (value) => onSuccess(label, value) }),
|
|
129
|
+
{ initialProps: { label: "first" } },
|
|
130
|
+
);
|
|
131
|
+
const run = result.current.run;
|
|
132
|
+
rerender({ label: "second" });
|
|
133
|
+
expect(result.current.run).toBe(run);
|
|
134
|
+
await act(async () => {
|
|
135
|
+
await run();
|
|
136
|
+
});
|
|
137
|
+
expect(result.current.result).toBe("second");
|
|
138
|
+
expect(onSuccess).toHaveBeenCalledWith("second", "second");
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test("nothing updates after unmount", async () => {
|
|
142
|
+
const answer = deferred<string>();
|
|
143
|
+
const onSuccess = jest.fn();
|
|
144
|
+
const errors = jest.spyOn(console, "error").mockImplementation(() => {});
|
|
145
|
+
const { result, unmount } = renderHook(() => useTool(() => answer.promise, { onSuccess }));
|
|
146
|
+
let running!: Promise<string | undefined>;
|
|
147
|
+
act(() => {
|
|
148
|
+
running = result.current.run();
|
|
149
|
+
});
|
|
150
|
+
unmount();
|
|
151
|
+
answer.resolve("done");
|
|
152
|
+
await expect(running).resolves.toBe("done");
|
|
153
|
+
expect(onSuccess).not.toHaveBeenCalled();
|
|
154
|
+
expect(errors).not.toHaveBeenCalled();
|
|
155
|
+
errors.mockRestore();
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test("callback failures do not change the call's outcome or reject run", async () => {
|
|
159
|
+
const errors = jest.spyOn(console, "error").mockImplementation(() => {});
|
|
160
|
+
const onError = jest.fn(() => {
|
|
161
|
+
throw new Error("error callback failed");
|
|
162
|
+
});
|
|
163
|
+
const { result, rerender } = renderHook(
|
|
164
|
+
({ fail }: { fail: boolean }) =>
|
|
165
|
+
useTool(
|
|
166
|
+
async () => {
|
|
167
|
+
if (fail) throw new Error("tool failed");
|
|
168
|
+
return "saved";
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
onSuccess: () => {
|
|
172
|
+
throw new Error("success callback failed");
|
|
173
|
+
},
|
|
174
|
+
onError,
|
|
175
|
+
},
|
|
176
|
+
),
|
|
177
|
+
{ initialProps: { fail: false } },
|
|
178
|
+
);
|
|
179
|
+
await act(async () => {
|
|
180
|
+
await expect(result.current.run()).resolves.toBe("saved");
|
|
181
|
+
});
|
|
182
|
+
expect(result.current.result).toBe("saved");
|
|
183
|
+
expect(result.current.error).toBeUndefined();
|
|
184
|
+
expect(onError).not.toHaveBeenCalled();
|
|
185
|
+
rerender({ fail: true });
|
|
186
|
+
await act(async () => {
|
|
187
|
+
await expect(result.current.run()).resolves.toBeUndefined();
|
|
188
|
+
});
|
|
189
|
+
expect(result.current.error?.message).toBe("tool failed");
|
|
190
|
+
expect(errors).toHaveBeenCalledTimes(2);
|
|
191
|
+
errors.mockRestore();
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("observes rejected async callbacks and unprintable rejection values", async () => {
|
|
195
|
+
const errors = jest.spyOn(console, "error").mockImplementation(() => {});
|
|
196
|
+
const { result, rerender } = renderHook(
|
|
197
|
+
({ fail }: { fail: boolean }) =>
|
|
198
|
+
useTool(
|
|
199
|
+
async () => {
|
|
200
|
+
if (fail) throw Object.create(null);
|
|
201
|
+
return "ok";
|
|
202
|
+
},
|
|
203
|
+
{
|
|
204
|
+
onSuccess: async () => {
|
|
205
|
+
throw new Error("async success callback");
|
|
206
|
+
},
|
|
207
|
+
onError: async () => {
|
|
208
|
+
throw new Error("async error callback");
|
|
209
|
+
},
|
|
210
|
+
},
|
|
211
|
+
),
|
|
212
|
+
{ initialProps: { fail: false } },
|
|
213
|
+
);
|
|
214
|
+
await act(async () => {
|
|
215
|
+
await expect(result.current.run()).resolves.toBe("ok");
|
|
216
|
+
});
|
|
217
|
+
rerender({ fail: true });
|
|
218
|
+
await act(async () => {
|
|
219
|
+
await expect(result.current.run()).resolves.toBeUndefined();
|
|
220
|
+
});
|
|
221
|
+
expect(result.current.error).toBeInstanceOf(Error);
|
|
222
|
+
expect(errors).toHaveBeenCalledTimes(2);
|
|
223
|
+
errors.mockRestore();
|
|
224
|
+
});
|
|
225
|
+
});
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
2
|
+
|
|
3
|
+
/** A call {@link useTool} can run: a contract tool, a table write, or any async function. */
|
|
4
|
+
export type UseToolCall = (...args: any[]) => Promise<unknown>;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Callbacks for {@link useTool}. The latest ones passed are used. Callback failures are
|
|
8
|
+
* logged; they do not change the call's result or error. Async callbacks are not awaited.
|
|
9
|
+
*/
|
|
10
|
+
export interface IUseToolOptions<T extends UseToolCall> {
|
|
11
|
+
/** After a run succeeds, with its result and arguments. Not called after unmount. */
|
|
12
|
+
onSuccess?: (result: Awaited<ReturnType<T>>, ...args: Parameters<T>) => void;
|
|
13
|
+
/** After a run fails, with its error and arguments. Not called after unmount. */
|
|
14
|
+
onError?: (error: Error, ...args: Parameters<T>) => void;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** What {@link useTool} returns. */
|
|
18
|
+
export interface IUseToolResult<T extends UseToolCall> {
|
|
19
|
+
/** Run the call. Resolves to its result, or `undefined` when it fails; it never rejects. */
|
|
20
|
+
run: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>> | undefined>;
|
|
21
|
+
/** True while the latest run is in flight. */
|
|
22
|
+
pending: boolean;
|
|
23
|
+
/** Why the latest run failed. Cleared when a run starts. */
|
|
24
|
+
error: Error | undefined;
|
|
25
|
+
/** The latest run's result. Cleared when a run starts. */
|
|
26
|
+
result: Awaited<ReturnType<T>> | undefined;
|
|
27
|
+
/** Clear state and ignore pending state updates, without cancelling calls or their callbacks. */
|
|
28
|
+
reset: () => void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface IToolState<R> {
|
|
32
|
+
pending: boolean;
|
|
33
|
+
error?: Error;
|
|
34
|
+
result?: R;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Run a tool from a component and track it: `pending` while it runs, then `result` or `error`.
|
|
39
|
+
*
|
|
40
|
+
* ```tsx
|
|
41
|
+
* const refresh = useTool(news.tools.refresh);
|
|
42
|
+
* <button disabled={refresh.pending} onClick={() => refresh.run()}>Refresh</button>
|
|
43
|
+
* {refresh.error && <div>Couldn't refresh.</div>}
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
46
|
+
* Typed from the call, so `run` takes the tool's input and `result` is its output. It also
|
|
47
|
+
* takes table writes (`useTool(news.tables.Feeds.save)`) or any async function. `run` keeps
|
|
48
|
+
* the same identity across renders and calls the latest function passed. When runs overlap,
|
|
49
|
+
* the state follows the latest one. Nothing updates after unmount.
|
|
50
|
+
*
|
|
51
|
+
* @param call - The tool or async function to run.
|
|
52
|
+
* @param options - `onSuccess` and `onError` callbacks.
|
|
53
|
+
*/
|
|
54
|
+
export function useTool<T extends UseToolCall>(
|
|
55
|
+
call: T,
|
|
56
|
+
options: IUseToolOptions<T> = {},
|
|
57
|
+
): IUseToolResult<T> {
|
|
58
|
+
type Result = Awaited<ReturnType<T>>;
|
|
59
|
+
const latest = useRef({ call, options });
|
|
60
|
+
latest.current = { call, options };
|
|
61
|
+
const runs = useRef(0);
|
|
62
|
+
const mounted = useRef(true);
|
|
63
|
+
const [state, setState] = useState<IToolState<Result>>({ pending: false });
|
|
64
|
+
|
|
65
|
+
useEffect(() => {
|
|
66
|
+
mounted.current = true;
|
|
67
|
+
return () => {
|
|
68
|
+
mounted.current = false;
|
|
69
|
+
};
|
|
70
|
+
}, []);
|
|
71
|
+
|
|
72
|
+
const run = useCallback(async (...args: Parameters<T>): Promise<Result | undefined> => {
|
|
73
|
+
const id = ++runs.current;
|
|
74
|
+
if (mounted.current) setState({ pending: true });
|
|
75
|
+
try {
|
|
76
|
+
const result = (await latest.current.call(...args)) as Result;
|
|
77
|
+
if (mounted.current) {
|
|
78
|
+
if (id === runs.current) setState({ pending: false, result });
|
|
79
|
+
notify(() => latest.current.options.onSuccess?.(result, ...args));
|
|
80
|
+
}
|
|
81
|
+
return result;
|
|
82
|
+
} catch (cause) {
|
|
83
|
+
const error = toolError(cause);
|
|
84
|
+
if (mounted.current) {
|
|
85
|
+
if (id === runs.current) setState({ pending: false, error });
|
|
86
|
+
notify(() => latest.current.options.onError?.(error, ...args));
|
|
87
|
+
}
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
}, []);
|
|
91
|
+
|
|
92
|
+
const reset = useCallback(() => {
|
|
93
|
+
runs.current++;
|
|
94
|
+
if (mounted.current) setState({ pending: false });
|
|
95
|
+
}, []);
|
|
96
|
+
|
|
97
|
+
return { run, reset, pending: state.pending, error: state.error, result: state.result };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function notify(callback: () => void): void {
|
|
101
|
+
const failed = (cause: unknown) => console.error("useTool callback failed", cause);
|
|
102
|
+
try {
|
|
103
|
+
void Promise.resolve(callback()).catch(failed);
|
|
104
|
+
} catch (cause) {
|
|
105
|
+
failed(cause);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function toolError(cause: unknown): Error {
|
|
110
|
+
try {
|
|
111
|
+
if (cause instanceof Error) return cause;
|
|
112
|
+
return new Error(String(cause));
|
|
113
|
+
} catch {
|
|
114
|
+
return new Error("Tool call failed");
|
|
115
|
+
}
|
|
116
|
+
}
|