@peers-app/peers-ui 0.26.6 → 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
package/dist/utils.js
CHANGED
|
@@ -7,18 +7,15 @@ exports.AsyncFunction = void 0;
|
|
|
7
7
|
exports.htmlToText = htmlToText;
|
|
8
8
|
exports.stripMentions = stripMentions;
|
|
9
9
|
exports.trimAndSanitizeHtml = trimAndSanitizeHtml;
|
|
10
|
-
exports.isObject = isObject;
|
|
11
|
-
exports.js = js;
|
|
12
10
|
exports.jsAsync = jsAsync;
|
|
13
|
-
exports.toJSON = toJSON;
|
|
14
|
-
exports.fromJSON = fromJSON;
|
|
15
11
|
const dompurify_1 = __importDefault(require("dompurify"));
|
|
16
12
|
const lodash_1 = __importDefault(require("lodash"));
|
|
13
|
+
/** Plain text content of an HTML string (parsed with `DOMParser`, so browser-only). */
|
|
17
14
|
function htmlToText(html) {
|
|
18
15
|
const doc = new DOMParser().parseFromString(html, "text/html");
|
|
19
16
|
return doc.body.textContent || "";
|
|
20
17
|
}
|
|
21
|
-
|
|
18
|
+
/** Replaces `<@type:name:id>` / `<$type:name:id>` mentions with the readable name, underscores as spaces. */
|
|
22
19
|
function stripMentions(text) {
|
|
23
20
|
// Replace <type:name:id> with just the readable name part
|
|
24
21
|
// Convert underscores to spaces for better readability
|
|
@@ -26,6 +23,7 @@ function stripMentions(text) {
|
|
|
26
23
|
return name.replace(/_/g, " ");
|
|
27
24
|
});
|
|
28
25
|
}
|
|
26
|
+
/** Sanitizes HTML with DOMPurify, collapses repeated blank paragraphs, and drops a trailing one. */
|
|
29
27
|
function trimAndSanitizeHtml(value) {
|
|
30
28
|
let sanitizedValue = dompurify_1.default.sanitize(value);
|
|
31
29
|
// removes empty paragraphs
|
|
@@ -42,31 +40,15 @@ function trimAndSanitizeHtml(value) {
|
|
|
42
40
|
}
|
|
43
41
|
return sanitizedValue;
|
|
44
42
|
}
|
|
45
|
-
function isObject(x) {
|
|
46
|
-
return lodash_1.default.isObject(x) && !lodash_1.default.isArray(x) && !lodash_1.default.isDate(x) && x !== null;
|
|
47
|
-
}
|
|
48
|
-
function js(jsCode, externalReferences) {
|
|
49
|
-
const hideGlobals = [
|
|
50
|
-
"process",
|
|
51
|
-
"global", //,'setTimeout','setInterval','setImmediate','clearImmediate','clearInterval','clearTimeout'
|
|
52
|
-
];
|
|
53
|
-
const common = module.exports;
|
|
54
|
-
const refNames = ["console", "common"];
|
|
55
|
-
const refValues = [console, common];
|
|
56
|
-
lodash_1.default.keys(externalReferences).forEach((key) => {
|
|
57
|
-
refNames.push(key);
|
|
58
|
-
refValues.push(externalReferences[key]);
|
|
59
|
-
});
|
|
60
|
-
const compiledJs = Function.apply(null, [
|
|
61
|
-
...refNames,
|
|
62
|
-
...hideGlobals,
|
|
63
|
-
`"use strict"; ${jsCode.trim()}`,
|
|
64
|
-
]);
|
|
65
|
-
return compiledJs.apply(null, refValues);
|
|
66
|
-
}
|
|
67
43
|
// must be done this way so TypeScript doesn't rewrite async keyword
|
|
68
44
|
// export const AsyncFunction = eval('Object.getPrototypeOf(async function () { }).constructor');
|
|
45
|
+
/** The `AsyncFunction` constructor, for compiling async code from a string. */
|
|
69
46
|
exports.AsyncFunction = Object.getPrototypeOf(async () => { }).constructor;
|
|
47
|
+
/**
|
|
48
|
+
* Compiles and runs `jsCode` as the body of a strict async function. `utils`, `Promise`,
|
|
49
|
+
* `console` and each key of `externalReferences` are in scope; `process` and `global` are hidden.
|
|
50
|
+
* Runs arbitrary code: never pass it untrusted input.
|
|
51
|
+
*/
|
|
70
52
|
function jsAsync(jsCode, externalReferences = {}) {
|
|
71
53
|
jsCode = String(jsCode).trim();
|
|
72
54
|
const hideGlobals = [
|
|
@@ -87,153 +69,6 @@ function jsAsync(jsCode, externalReferences = {}) {
|
|
|
87
69
|
]);
|
|
88
70
|
return compiledJs.apply(null, refValues);
|
|
89
71
|
}
|
|
90
|
-
function toJSON(obj) {
|
|
91
|
-
//console.log('toJSON');
|
|
92
|
-
const knownObjs = [];
|
|
93
|
-
const objRefs = [];
|
|
94
|
-
const newObjs = [];
|
|
95
|
-
let refCount = 0;
|
|
96
|
-
function recurse(obj) {
|
|
97
|
-
// stringify values
|
|
98
|
-
if (Number.isNaN(obj))
|
|
99
|
-
return "NaN";
|
|
100
|
-
if (obj === undefined)
|
|
101
|
-
return "undefined";
|
|
102
|
-
if (obj === Infinity)
|
|
103
|
-
return "Infinity";
|
|
104
|
-
if (obj instanceof RegExp)
|
|
105
|
-
return `__REGEXP ${obj.toString()}`;
|
|
106
|
-
// if(isDate(obj))
|
|
107
|
-
// return "__DATE " + obj.toISOString();
|
|
108
|
-
if (lodash_1.default.isDate(obj))
|
|
109
|
-
return obj.toISOString();
|
|
110
|
-
if (lodash_1.default.isFunction(obj))
|
|
111
|
-
return `__FUNCTION ${obj.toString()}`;
|
|
112
|
-
if (lodash_1.default.isElement(obj)) {
|
|
113
|
-
return `__HTML ${obj.outerHTML}`;
|
|
114
|
-
}
|
|
115
|
-
if (typeof window !== "undefined" && window && obj === window) {
|
|
116
|
-
return "__WINDOW";
|
|
117
|
-
}
|
|
118
|
-
if (lodash_1.default.isError(obj)) {
|
|
119
|
-
return `__ERROR ${obj.stack}`;
|
|
120
|
-
}
|
|
121
|
-
// non-objects can just be returned at this point
|
|
122
|
-
if (!(isObject(obj) || lodash_1.default.isArray(obj))) {
|
|
123
|
-
return obj;
|
|
124
|
-
}
|
|
125
|
-
// if we've found a duplicate reference, deal with it
|
|
126
|
-
var iObj = knownObjs.indexOf(obj);
|
|
127
|
-
if (iObj >= 0) {
|
|
128
|
-
var ref = objRefs[iObj];
|
|
129
|
-
var nObj = newObjs[iObj];
|
|
130
|
-
if (lodash_1.default.isArray(nObj) && (!lodash_1.default.isString(nObj[0]) || !nObj[0].match(/^__this_ref:/)))
|
|
131
|
-
nObj.unshift(`__this_ref:${ref}`);
|
|
132
|
-
else if (isObject(nObj) && !nObj.__this_ref)
|
|
133
|
-
nObj.__this_ref = ref;
|
|
134
|
-
return ref;
|
|
135
|
-
}
|
|
136
|
-
// capture references in case we need them later
|
|
137
|
-
refCount++;
|
|
138
|
-
var newRef = `__duplicate_ref_${lodash_1.default.isArray(obj) ? "ary_" : "obj_"}${refCount}`;
|
|
139
|
-
var outObj = lodash_1.default.isArray(obj) ? [] : {};
|
|
140
|
-
knownObjs.push(obj);
|
|
141
|
-
objRefs.push(newRef);
|
|
142
|
-
newObjs.push(outObj);
|
|
143
|
-
// recurse on properties
|
|
144
|
-
if (lodash_1.default.isArray(obj))
|
|
145
|
-
for (var i = 0; i < obj.length; i++)
|
|
146
|
-
outObj.push(recurse(obj[i])); // use push so offset from reference capture doesn't mess things up
|
|
147
|
-
else
|
|
148
|
-
for (var key in obj) {
|
|
149
|
-
if (!Object.hasOwn(obj, key))
|
|
150
|
-
continue;
|
|
151
|
-
var value = recurse(obj[key]);
|
|
152
|
-
if (key[0] === "$")
|
|
153
|
-
// escape leading dollar signs
|
|
154
|
-
key = `__DOLLAR_${key.substr(1)}`;
|
|
155
|
-
outObj[key] = value;
|
|
156
|
-
}
|
|
157
|
-
return outObj;
|
|
158
|
-
}
|
|
159
|
-
obj = recurse(obj);
|
|
160
|
-
return obj;
|
|
161
|
-
}
|
|
162
|
-
function fromJSON(obj, externalReferences) {
|
|
163
|
-
//console.log('fromJSON');
|
|
164
|
-
var dup_refs = {};
|
|
165
|
-
function recurse(obj) {
|
|
166
|
-
if (lodash_1.default.isString(obj)) {
|
|
167
|
-
// restore values
|
|
168
|
-
if (obj === "undefined")
|
|
169
|
-
return undefined;
|
|
170
|
-
if (obj === "NaN")
|
|
171
|
-
return NaN;
|
|
172
|
-
if (obj === "Infinity")
|
|
173
|
-
return Infinity;
|
|
174
|
-
if (obj.match(/^__REGEXP /)) {
|
|
175
|
-
var m = obj.split("__REGEXP ")[1].match(/\/(.*)\/(.*)?/);
|
|
176
|
-
return new RegExp(m[1], m[2] || "");
|
|
177
|
-
}
|
|
178
|
-
if (obj.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)) {
|
|
179
|
-
return new Date(obj);
|
|
180
|
-
}
|
|
181
|
-
if (obj.match(/^__FUNCTION /)) {
|
|
182
|
-
return js(obj.substring(11), externalReferences);
|
|
183
|
-
}
|
|
184
|
-
if (obj.match(/^__HTML /)) {
|
|
185
|
-
//@ts-expect-error
|
|
186
|
-
if (typeof $ !== "undefined")
|
|
187
|
-
return $(obj.substring(7))[0];
|
|
188
|
-
else
|
|
189
|
-
return obj;
|
|
190
|
-
}
|
|
191
|
-
if (obj.startsWith("__ERROR ")) {
|
|
192
|
-
const error = new Error();
|
|
193
|
-
error.stack = obj.substring(8);
|
|
194
|
-
return error;
|
|
195
|
-
}
|
|
196
|
-
if (obj === "__WINDOW") {
|
|
197
|
-
return window;
|
|
198
|
-
}
|
|
199
|
-
// deal with duplicate refs
|
|
200
|
-
if (obj.match(/^__duplicate_ref_/)) {
|
|
201
|
-
if (!dup_refs[obj])
|
|
202
|
-
dup_refs[obj] = obj.match(/_obj_/) ? {} : [];
|
|
203
|
-
return dup_refs[obj];
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
if (!(isObject(obj) || lodash_1.default.isArray(obj)))
|
|
207
|
-
return obj;
|
|
208
|
-
// deal with objects that have duplicate refs
|
|
209
|
-
var dup_ref = null;
|
|
210
|
-
obj = lodash_1.default.clone(obj); // don't mess up the original JSON object
|
|
211
|
-
if (lodash_1.default.isArray(obj) && lodash_1.default.isString(obj[0]) && obj[0].match(/^__this_ref:/))
|
|
212
|
-
dup_ref = obj.shift().split(":")[1];
|
|
213
|
-
else if (obj.__this_ref) {
|
|
214
|
-
dup_ref = obj.__this_ref;
|
|
215
|
-
delete obj.__this_ref;
|
|
216
|
-
}
|
|
217
|
-
var mObj = lodash_1.default.isArray(obj) ? [] : {};
|
|
218
|
-
if (dup_ref)
|
|
219
|
-
if (!dup_refs[dup_ref])
|
|
220
|
-
dup_refs[dup_ref] = mObj;
|
|
221
|
-
else
|
|
222
|
-
mObj = dup_refs[dup_ref];
|
|
223
|
-
// restore keys and recurse on objects
|
|
224
|
-
for (var key in obj) {
|
|
225
|
-
if (!Object.hasOwn(obj, key))
|
|
226
|
-
continue;
|
|
227
|
-
var value = recurse(obj[key]);
|
|
228
|
-
if (key.match(/^__DOLLAR_/))
|
|
229
|
-
key = `$${key.substr(9)}`;
|
|
230
|
-
mObj[key] = value;
|
|
231
|
-
}
|
|
232
|
-
return mObj;
|
|
233
|
-
}
|
|
234
|
-
obj = recurse(obj);
|
|
235
|
-
return obj;
|
|
236
|
-
}
|
|
237
72
|
// export type IObjectMatch<T> = {
|
|
238
73
|
// [key in keyof T]?: RegExp | string | number | boolean
|
|
239
74
|
// }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@peers-app/peers-ui",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.27.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/peers-app/peers-ui.git"
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"lint:fix": "biome check --write ."
|
|
31
31
|
},
|
|
32
32
|
"peerDependencies": {
|
|
33
|
-
"@peers-app/peers-sdk": "^0.
|
|
33
|
+
"@peers-app/peers-sdk": "^0.27.0",
|
|
34
34
|
"bootstrap": "^5.3.3",
|
|
35
35
|
"react": "^18.0.0",
|
|
36
36
|
"react-dom": "^18.0.0"
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"@babel/preset-react": "^7.24.1",
|
|
42
42
|
"@babel/preset-typescript": "^7.27.1",
|
|
43
43
|
"@biomejs/biome": "2.3.11",
|
|
44
|
-
"@peers-app/peers-sdk": "0.
|
|
44
|
+
"@peers-app/peers-sdk": "0.27.0",
|
|
45
45
|
"@testing-library/dom": "^10.4.0",
|
|
46
46
|
"@testing-library/jest-dom": "^6.6.3",
|
|
47
47
|
"@testing-library/react": "^16.3.0",
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// `use-host-contract` stays internal: its screens import it by path.
|
|
2
|
+
export * from "./use-observable";
|
|
3
|
+
export * from "./use-observable-state";
|
|
4
|
+
export * from "./use-on-screen";
|
|
5
|
+
export * from "./use-promise";
|
|
6
|
+
export * from "./use-rows";
|
|
7
|
+
export * from "./use-subscription";
|
|
8
|
+
export * from "./use-tool";
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { Observable } from "@peers-app/peers-sdk";
|
|
2
|
+
import { act, render, screen, waitFor } from "@testing-library/react";
|
|
3
|
+
import { useObservable } from "./use-observable";
|
|
4
|
+
import { useObservableState } from "./use-observable-state";
|
|
5
|
+
|
|
6
|
+
// Helper component to test useObservableState
|
|
7
|
+
function ObservableStateTestComponent({ initialValue }: { initialValue: number }) {
|
|
8
|
+
const obs = useObservableState(initialValue);
|
|
9
|
+
const [value] = useObservable(obs);
|
|
10
|
+
return (
|
|
11
|
+
<div>
|
|
12
|
+
<span data-testid="state-value">{value}</span>
|
|
13
|
+
<button type="button" data-testid="increment" onClick={() => obs(obs() + 1)}>
|
|
14
|
+
Increment
|
|
15
|
+
</button>
|
|
16
|
+
</div>
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
describe("useObservableState", () => {
|
|
21
|
+
it("should create an observable with the initial value", () => {
|
|
22
|
+
render(<ObservableStateTestComponent initialValue={42} />);
|
|
23
|
+
expect(screen.getByTestId("state-value")).toHaveTextContent("42");
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("should re-render when the observable is updated", async () => {
|
|
27
|
+
render(<ObservableStateTestComponent initialValue={0} />);
|
|
28
|
+
|
|
29
|
+
expect(screen.getByTestId("state-value")).toHaveTextContent("0");
|
|
30
|
+
|
|
31
|
+
act(() => {
|
|
32
|
+
screen.getByTestId("increment").click();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
await waitFor(() => {
|
|
36
|
+
expect(screen.getByTestId("state-value")).toHaveTextContent("1");
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("should maintain the same observable instance across re-renders", async () => {
|
|
41
|
+
let capturedObs: Observable<number> | null = null;
|
|
42
|
+
|
|
43
|
+
function CaptureObsComponent() {
|
|
44
|
+
const obs = useObservableState(0);
|
|
45
|
+
if (!capturedObs) {
|
|
46
|
+
capturedObs = obs;
|
|
47
|
+
}
|
|
48
|
+
const [value] = useObservable(obs);
|
|
49
|
+
return (
|
|
50
|
+
<div>
|
|
51
|
+
<span data-testid="value">{value}</span>
|
|
52
|
+
<span data-testid="same-obs">{obs === capturedObs ? "same" : "different"}</span>
|
|
53
|
+
<button type="button" data-testid="update" onClick={() => obs(obs() + 1)}>
|
|
54
|
+
Update
|
|
55
|
+
</button>
|
|
56
|
+
</div>
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
render(<CaptureObsComponent />);
|
|
61
|
+
|
|
62
|
+
expect(screen.getByTestId("same-obs")).toHaveTextContent("same");
|
|
63
|
+
|
|
64
|
+
// Trigger a re-render by updating the observable
|
|
65
|
+
act(() => {
|
|
66
|
+
screen.getByTestId("update").click();
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
await waitFor(() => {
|
|
70
|
+
expect(screen.getByTestId("value")).toHaveTextContent("1");
|
|
71
|
+
expect(screen.getByTestId("same-obs")).toHaveTextContent("same");
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("should not subscribe when doNotSubscribe is true", () => {
|
|
76
|
+
function NoSubscribeComponent() {
|
|
77
|
+
const obs = useObservableState(0, true); // doNotSubscribe = true
|
|
78
|
+
return (
|
|
79
|
+
<div>
|
|
80
|
+
<span data-testid="value">{obs()}</span>
|
|
81
|
+
<button type="button" data-testid="update" onClick={() => obs(obs() + 1)}>
|
|
82
|
+
Update
|
|
83
|
+
</button>
|
|
84
|
+
</div>
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
render(<NoSubscribeComponent />);
|
|
89
|
+
|
|
90
|
+
expect(screen.getByTestId("value")).toHaveTextContent("0");
|
|
91
|
+
|
|
92
|
+
// Update won't cause re-render since we're not subscribed
|
|
93
|
+
act(() => {
|
|
94
|
+
screen.getByTestId("update").click();
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
// Value in DOM should still show 0 since component didn't re-render
|
|
98
|
+
// But the observable itself has been updated
|
|
99
|
+
expect(screen.getByTestId("value")).toHaveTextContent("0");
|
|
100
|
+
});
|
|
101
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type Observable, observable } from "@peers-app/peers-sdk";
|
|
2
|
+
import { useState } from "react";
|
|
3
|
+
import { useObservable } from "./use-observable";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Use this to create an observable in a functional component.
|
|
7
|
+
* This automatically subscribes to the observable and triggers a re-render when the value changes.
|
|
8
|
+
* @param initialValue This will be the initial value of the observable
|
|
9
|
+
* @param doNotSubscribe If true, the observable will not be subscribed to automatically.
|
|
10
|
+
* This is useful if you want to create an observable that persists between rerenders but doesn't cause rerenders itself.
|
|
11
|
+
* @returns The same observable on every render.
|
|
12
|
+
*/
|
|
13
|
+
export function useObservableState<T>(initialValue: T, doNotSubscribe?: boolean): Observable<T>;
|
|
14
|
+
/** Create an observable that may start undefined and subscribe unless `doNotSubscribe` is true. */
|
|
15
|
+
export function useObservableState<T = undefined>(
|
|
16
|
+
initialValue?: T,
|
|
17
|
+
doNotSubscribe?: boolean,
|
|
18
|
+
): Observable<T | undefined>;
|
|
19
|
+
/** Create and optionally subscribe to a component-owned observable. */
|
|
20
|
+
export function useObservableState<T>(initialValue?: T, doNotSubscribe?: boolean) {
|
|
21
|
+
const [obs] = useState(() =>
|
|
22
|
+
initialValue !== undefined ? observable<T>(initialValue) : observable<T | undefined>(),
|
|
23
|
+
);
|
|
24
|
+
if (!doNotSubscribe) {
|
|
25
|
+
// biome-ignore lint/correctness/useHookAtTopLevel: when doNotSubscribe, caller keeps a stable observable without React-driven subscription (see docstring).
|
|
26
|
+
useObservable(obs);
|
|
27
|
+
}
|
|
28
|
+
return obs;
|
|
29
|
+
}
|
|
@@ -1,6 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import {
|
|
2
|
+
isSubscribable,
|
|
3
|
+
type Observable,
|
|
4
|
+
observable,
|
|
5
|
+
type ReadonlyObservable,
|
|
6
|
+
} from "@peers-app/peers-sdk";
|
|
7
|
+
import { act, render, renderHook, screen, waitFor } from "@testing-library/react";
|
|
8
|
+
import { useObservable } from "./use-observable";
|
|
4
9
|
|
|
5
10
|
// Helper component to test useObservable
|
|
6
11
|
function TestComponent<T>({ obs, testId = "value" }: { obs: Observable<T> | T; testId?: string }) {
|
|
@@ -26,21 +31,26 @@ function ArrayTestComponent({ obs }: { obs: Observable<string[]> }) {
|
|
|
26
31
|
);
|
|
27
32
|
}
|
|
28
33
|
|
|
29
|
-
// Helper component to test useObservableState
|
|
30
|
-
function ObservableStateTestComponent({ initialValue }: { initialValue: number }) {
|
|
31
|
-
const obs = useObservableState(initialValue);
|
|
32
|
-
const [value] = useObservable(obs);
|
|
33
|
-
return (
|
|
34
|
-
<div>
|
|
35
|
-
<span data-testid="state-value">{value}</span>
|
|
36
|
-
<button type="button" data-testid="increment" onClick={() => obs(obs() + 1)}>
|
|
37
|
-
Increment
|
|
38
|
-
</button>
|
|
39
|
-
</div>
|
|
40
|
-
);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
34
|
describe("useObservable", () => {
|
|
35
|
+
it("reads and follows a read-only observable without allowing typed writes", () => {
|
|
36
|
+
const source = observable(1);
|
|
37
|
+
const view: ReadonlyObservable<number> = source;
|
|
38
|
+
const { result } = renderHook(() => useObservable(view));
|
|
39
|
+
const checkReadonly = () => {
|
|
40
|
+
// @ts-expect-error the read-only hook's setter accepts no values
|
|
41
|
+
result.current[1](2);
|
|
42
|
+
if (isSubscribable(view)) {
|
|
43
|
+
// @ts-expect-error testing subscribability must not make a read-only view writable
|
|
44
|
+
view(2);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
void checkReadonly;
|
|
48
|
+
const initial: number = result.current[0];
|
|
49
|
+
expect(initial).toBe(1);
|
|
50
|
+
act(() => source(3));
|
|
51
|
+
expect(result.current[0]).toBe(3);
|
|
52
|
+
});
|
|
53
|
+
|
|
44
54
|
describe("basic functionality", () => {
|
|
45
55
|
it("should return the current value of an observable", () => {
|
|
46
56
|
const obs = observable("hello");
|
|
@@ -246,86 +256,3 @@ describe("useObservable", () => {
|
|
|
246
256
|
});
|
|
247
257
|
});
|
|
248
258
|
});
|
|
249
|
-
|
|
250
|
-
describe("useObservableState", () => {
|
|
251
|
-
it("should create an observable with the initial value", () => {
|
|
252
|
-
render(<ObservableStateTestComponent initialValue={42} />);
|
|
253
|
-
expect(screen.getByTestId("state-value")).toHaveTextContent("42");
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
it("should re-render when the observable is updated", async () => {
|
|
257
|
-
render(<ObservableStateTestComponent initialValue={0} />);
|
|
258
|
-
|
|
259
|
-
expect(screen.getByTestId("state-value")).toHaveTextContent("0");
|
|
260
|
-
|
|
261
|
-
act(() => {
|
|
262
|
-
screen.getByTestId("increment").click();
|
|
263
|
-
});
|
|
264
|
-
|
|
265
|
-
await waitFor(() => {
|
|
266
|
-
expect(screen.getByTestId("state-value")).toHaveTextContent("1");
|
|
267
|
-
});
|
|
268
|
-
});
|
|
269
|
-
|
|
270
|
-
it("should maintain the same observable instance across re-renders", async () => {
|
|
271
|
-
let capturedObs: Observable<number> | null = null;
|
|
272
|
-
|
|
273
|
-
function CaptureObsComponent() {
|
|
274
|
-
const obs = useObservableState(0);
|
|
275
|
-
if (!capturedObs) {
|
|
276
|
-
capturedObs = obs;
|
|
277
|
-
}
|
|
278
|
-
const [value] = useObservable(obs);
|
|
279
|
-
return (
|
|
280
|
-
<div>
|
|
281
|
-
<span data-testid="value">{value}</span>
|
|
282
|
-
<span data-testid="same-obs">{obs === capturedObs ? "same" : "different"}</span>
|
|
283
|
-
<button type="button" data-testid="update" onClick={() => obs(obs() + 1)}>
|
|
284
|
-
Update
|
|
285
|
-
</button>
|
|
286
|
-
</div>
|
|
287
|
-
);
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
render(<CaptureObsComponent />);
|
|
291
|
-
|
|
292
|
-
expect(screen.getByTestId("same-obs")).toHaveTextContent("same");
|
|
293
|
-
|
|
294
|
-
// Trigger a re-render by updating the observable
|
|
295
|
-
act(() => {
|
|
296
|
-
screen.getByTestId("update").click();
|
|
297
|
-
});
|
|
298
|
-
|
|
299
|
-
await waitFor(() => {
|
|
300
|
-
expect(screen.getByTestId("value")).toHaveTextContent("1");
|
|
301
|
-
expect(screen.getByTestId("same-obs")).toHaveTextContent("same");
|
|
302
|
-
});
|
|
303
|
-
});
|
|
304
|
-
|
|
305
|
-
it("should not subscribe when doNotSubscribe is true", () => {
|
|
306
|
-
function NoSubscribeComponent() {
|
|
307
|
-
const obs = useObservableState(0, true); // doNotSubscribe = true
|
|
308
|
-
return (
|
|
309
|
-
<div>
|
|
310
|
-
<span data-testid="value">{obs()}</span>
|
|
311
|
-
<button type="button" data-testid="update" onClick={() => obs(obs() + 1)}>
|
|
312
|
-
Update
|
|
313
|
-
</button>
|
|
314
|
-
</div>
|
|
315
|
-
);
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
render(<NoSubscribeComponent />);
|
|
319
|
-
|
|
320
|
-
expect(screen.getByTestId("value")).toHaveTextContent("0");
|
|
321
|
-
|
|
322
|
-
// Update won't cause re-render since we're not subscribed
|
|
323
|
-
act(() => {
|
|
324
|
-
screen.getByTestId("update").click();
|
|
325
|
-
});
|
|
326
|
-
|
|
327
|
-
// Value in DOM should still show 0 since component didn't re-render
|
|
328
|
-
// But the observable itself has been updated
|
|
329
|
-
expect(screen.getByTestId("value")).toHaveTextContent("0");
|
|
330
|
-
});
|
|
331
|
-
});
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isSubscribable,
|
|
3
|
+
type Observable,
|
|
4
|
+
type ReadonlyObservable,
|
|
5
|
+
unwrapObservable,
|
|
6
|
+
} from "@peers-app/peers-sdk";
|
|
7
|
+
import type React from "react";
|
|
8
|
+
import { useCallback, useSyncExternalStore } from "react";
|
|
9
|
+
|
|
10
|
+
/** Read and subscribe to a writable observable, with a setter for its value. */
|
|
11
|
+
export function useObservable<T>(
|
|
12
|
+
sub: Observable<T>,
|
|
13
|
+
deps?: React.DependencyList,
|
|
14
|
+
): [T, (value: T) => void];
|
|
15
|
+
/** Read and subscribe to a read-only observable; its setter accepts no values. */
|
|
16
|
+
export function useObservable<T>(
|
|
17
|
+
sub: ReadonlyObservable<T>,
|
|
18
|
+
deps?: React.DependencyList,
|
|
19
|
+
): [T, (value: never) => void];
|
|
20
|
+
/** Read a plain value or a writable observable, retaining the existing optional-observable API. */
|
|
21
|
+
export function useObservable<T>(
|
|
22
|
+
sub: Observable<T> | T,
|
|
23
|
+
deps?: React.DependencyList,
|
|
24
|
+
): [T, (value: T) => void];
|
|
25
|
+
/**
|
|
26
|
+
* Subscribe to an observable or computed in a functional component, using useSyncExternalStore
|
|
27
|
+
* for React 18 concurrent rendering. Only writable observables have a callable typed setter.
|
|
28
|
+
* @param sub the observable, computed, or plain value to read
|
|
29
|
+
* @param deps dependencies that cause re-subscription when changed
|
|
30
|
+
*/
|
|
31
|
+
export function useObservable<T>(
|
|
32
|
+
sub: ReadonlyObservable<T> | T,
|
|
33
|
+
deps: React.DependencyList = [],
|
|
34
|
+
): [T, (value: T) => void] {
|
|
35
|
+
// Create memoized subscribe function that adapts Observable's subscribe API to useSyncExternalStore's expected signature
|
|
36
|
+
const subscribe = useCallback(
|
|
37
|
+
(onStoreChange: () => void) => {
|
|
38
|
+
if (!isSubscribable(sub)) {
|
|
39
|
+
// If not subscribable, return a no-op unsubscribe
|
|
40
|
+
return () => {};
|
|
41
|
+
}
|
|
42
|
+
const subscription = sub.subscribe(onStoreChange);
|
|
43
|
+
return () => subscription.dispose();
|
|
44
|
+
},
|
|
45
|
+
[sub, ...deps],
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
// getSnapshot returns the current value from the observable
|
|
49
|
+
const getSnapshot = useCallback(() => {
|
|
50
|
+
return unwrapObservable(sub);
|
|
51
|
+
}, [sub, ...deps]);
|
|
52
|
+
|
|
53
|
+
// Use useSyncExternalStore for concurrent-safe subscription
|
|
54
|
+
const data = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
55
|
+
|
|
56
|
+
// Create setter that updates both local understanding and the observable
|
|
57
|
+
const setter = useCallback(
|
|
58
|
+
(newData: T) => {
|
|
59
|
+
if (isSubscribable(sub)) {
|
|
60
|
+
sub(newData);
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
[sub],
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
return [data, setter];
|
|
67
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type React from "react";
|
|
2
|
+
import { useEffect, useState } from "react";
|
|
3
|
+
|
|
4
|
+
/** Track whether the referenced element intersects the viewport. */
|
|
5
|
+
export function useOnScreen(ref: React.RefObject<Element | null>) {
|
|
6
|
+
const [isIntersecting, setIntersecting] = useState(false);
|
|
7
|
+
|
|
8
|
+
// Read ref.current once on mount (ref object identity is stable).
|
|
9
|
+
useEffect(() => {
|
|
10
|
+
const element = ref.current;
|
|
11
|
+
if (!element) {
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
const observer = new IntersectionObserver(([entry]) => {
|
|
15
|
+
setIntersecting(entry.isIntersecting);
|
|
16
|
+
});
|
|
17
|
+
observer.observe(element);
|
|
18
|
+
return () => {
|
|
19
|
+
observer.disconnect();
|
|
20
|
+
};
|
|
21
|
+
}, []);
|
|
22
|
+
|
|
23
|
+
return isIntersecting;
|
|
24
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type React from "react";
|
|
2
|
+
import { useEffect, useState } from "react";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Use this to easily wait for a promise in a functional component.
|
|
6
|
+
* @param p The promise to wait for
|
|
7
|
+
* @param initialValue the initial value to return before the promise resolves
|
|
8
|
+
* @param deps the dependencies to pass to useEffect which will trigger a re-render when any of the dependencies change
|
|
9
|
+
* @returns the initial value and the resolved value of the promise
|
|
10
|
+
*/
|
|
11
|
+
export function usePromise<T>(
|
|
12
|
+
p: Promise<T> | (() => Promise<T>),
|
|
13
|
+
initialValue?: T,
|
|
14
|
+
deps: React.DependencyList = [],
|
|
15
|
+
): T | undefined {
|
|
16
|
+
const [data, setData] = useState(initialValue);
|
|
17
|
+
// `deps` drives when the effect re-runs; callers include `p` when it changes. Omitting `p` avoids duplicate tracking with `[...deps]`.
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
let disposed = false;
|
|
20
|
+
if (typeof p === "function") {
|
|
21
|
+
p = p();
|
|
22
|
+
}
|
|
23
|
+
p.then((newData) => {
|
|
24
|
+
// if (!_.isEqual(newData, data) && !disposed) {
|
|
25
|
+
if (!disposed) {
|
|
26
|
+
setData(newData);
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
return () => {
|
|
30
|
+
disposed = true;
|
|
31
|
+
};
|
|
32
|
+
}, [...deps]);
|
|
33
|
+
return data;
|
|
34
|
+
}
|