@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
package/src/utils.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import DOMPurify from "dompurify";
|
|
2
2
|
import _ from "lodash";
|
|
3
3
|
|
|
4
|
+
/** Plain text content of an HTML string (parsed with `DOMParser`, so browser-only). */
|
|
4
5
|
export function htmlToText(html: string): string {
|
|
5
6
|
const doc = new DOMParser().parseFromString(html, "text/html");
|
|
6
7
|
return doc.body.textContent || "";
|
|
7
8
|
}
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
/** Replaces `<@type:name:id>` / `<$type:name:id>` mentions with the readable name, underscores as spaces. */
|
|
10
11
|
export function stripMentions(text: string): string {
|
|
11
12
|
// Replace <type:name:id> with just the readable name part
|
|
12
13
|
// Convert underscores to spaces for better readability
|
|
@@ -15,6 +16,7 @@ export function stripMentions(text: string): string {
|
|
|
15
16
|
});
|
|
16
17
|
}
|
|
17
18
|
|
|
19
|
+
/** Sanitizes HTML with DOMPurify, collapses repeated blank paragraphs, and drops a trailing one. */
|
|
18
20
|
export function trimAndSanitizeHtml(value: string) {
|
|
19
21
|
let sanitizedValue: string = DOMPurify.sanitize(value);
|
|
20
22
|
// removes empty paragraphs
|
|
@@ -35,34 +37,16 @@ export function trimAndSanitizeHtml(value: string) {
|
|
|
35
37
|
return sanitizedValue;
|
|
36
38
|
}
|
|
37
39
|
|
|
38
|
-
export function isObject(x: any): x is Record<string, any> {
|
|
39
|
-
return _.isObject(x) && !_.isArray(x) && !_.isDate(x) && x !== null;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export function js(jsCode: string, externalReferences?: any) {
|
|
43
|
-
const hideGlobals = [
|
|
44
|
-
"process",
|
|
45
|
-
"global", //,'setTimeout','setInterval','setImmediate','clearImmediate','clearInterval','clearTimeout'
|
|
46
|
-
];
|
|
47
|
-
const common = module.exports;
|
|
48
|
-
const refNames = ["console", "common"];
|
|
49
|
-
const refValues = [console, common];
|
|
50
|
-
_.keys(externalReferences).forEach((key) => {
|
|
51
|
-
refNames.push(key);
|
|
52
|
-
refValues.push(externalReferences[key]);
|
|
53
|
-
});
|
|
54
|
-
const compiledJs = Function.apply(null, [
|
|
55
|
-
...refNames,
|
|
56
|
-
...hideGlobals,
|
|
57
|
-
`"use strict"; ${jsCode.trim()}`,
|
|
58
|
-
]);
|
|
59
|
-
return compiledJs.apply(null, refValues);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
40
|
// must be done this way so TypeScript doesn't rewrite async keyword
|
|
63
41
|
// export const AsyncFunction = eval('Object.getPrototypeOf(async function () { }).constructor');
|
|
42
|
+
/** The `AsyncFunction` constructor, for compiling async code from a string. */
|
|
64
43
|
export const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
|
|
65
44
|
|
|
45
|
+
/**
|
|
46
|
+
* Compiles and runs `jsCode` as the body of a strict async function. `utils`, `Promise`,
|
|
47
|
+
* `console` and each key of `externalReferences` are in scope; `process` and `global` are hidden.
|
|
48
|
+
* Runs arbitrary code: never pass it untrusted input.
|
|
49
|
+
*/
|
|
66
50
|
export function jsAsync(jsCode: string, externalReferences: any = {}) {
|
|
67
51
|
jsCode = String(jsCode).trim();
|
|
68
52
|
const hideGlobals = [
|
|
@@ -84,148 +68,6 @@ export function jsAsync(jsCode: string, externalReferences: any = {}) {
|
|
|
84
68
|
return compiledJs.apply(null, refValues);
|
|
85
69
|
}
|
|
86
70
|
|
|
87
|
-
export function toJSON(obj: any) {
|
|
88
|
-
//console.log('toJSON');
|
|
89
|
-
const knownObjs: any[] = [];
|
|
90
|
-
const objRefs: any[] = [];
|
|
91
|
-
const newObjs: any[] = [];
|
|
92
|
-
let refCount = 0;
|
|
93
|
-
|
|
94
|
-
function recurse(obj: any) {
|
|
95
|
-
// stringify values
|
|
96
|
-
if (Number.isNaN(obj)) return "NaN";
|
|
97
|
-
if (obj === undefined) return "undefined";
|
|
98
|
-
if (obj === Infinity) return "Infinity";
|
|
99
|
-
if (obj instanceof RegExp) return `__REGEXP ${obj.toString()}`;
|
|
100
|
-
// if(isDate(obj))
|
|
101
|
-
// return "__DATE " + obj.toISOString();
|
|
102
|
-
if (_.isDate(obj)) return obj.toISOString();
|
|
103
|
-
if (_.isFunction(obj)) return `__FUNCTION ${obj.toString()}`;
|
|
104
|
-
if (_.isElement(obj)) {
|
|
105
|
-
return `__HTML ${obj.outerHTML}`;
|
|
106
|
-
}
|
|
107
|
-
if (typeof window !== "undefined" && window && obj === window) {
|
|
108
|
-
return "__WINDOW";
|
|
109
|
-
}
|
|
110
|
-
if (_.isError(obj)) {
|
|
111
|
-
return `__ERROR ${obj.stack}`;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// non-objects can just be returned at this point
|
|
115
|
-
if (!(isObject(obj) || _.isArray(obj))) {
|
|
116
|
-
return obj;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// if we've found a duplicate reference, deal with it
|
|
120
|
-
var iObj = knownObjs.indexOf(obj);
|
|
121
|
-
if (iObj >= 0) {
|
|
122
|
-
var ref = objRefs[iObj];
|
|
123
|
-
|
|
124
|
-
var nObj = newObjs[iObj];
|
|
125
|
-
if (_.isArray(nObj) && (!_.isString(nObj[0]) || !nObj[0].match(/^__this_ref:/)))
|
|
126
|
-
nObj.unshift(`__this_ref:${ref}`);
|
|
127
|
-
else if (isObject(nObj) && !nObj.__this_ref) nObj.__this_ref = ref;
|
|
128
|
-
return ref;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// capture references in case we need them later
|
|
132
|
-
refCount++;
|
|
133
|
-
var newRef = `__duplicate_ref_${_.isArray(obj) ? "ary_" : "obj_"}${refCount}`;
|
|
134
|
-
var outObj: any[] | any = _.isArray(obj) ? [] : {};
|
|
135
|
-
knownObjs.push(obj);
|
|
136
|
-
objRefs.push(newRef);
|
|
137
|
-
newObjs.push(outObj);
|
|
138
|
-
|
|
139
|
-
// recurse on properties
|
|
140
|
-
if (_.isArray(obj))
|
|
141
|
-
for (var i = 0; i < obj.length; i++) outObj.push(recurse(obj[i])); // use push so offset from reference capture doesn't mess things up
|
|
142
|
-
else
|
|
143
|
-
for (var key in obj) {
|
|
144
|
-
if (!Object.hasOwn(obj as object, key)) continue;
|
|
145
|
-
var value = recurse(obj[key]);
|
|
146
|
-
if (key[0] === "$")
|
|
147
|
-
// escape leading dollar signs
|
|
148
|
-
key = `__DOLLAR_${key.substr(1)}`;
|
|
149
|
-
outObj[key] = value;
|
|
150
|
-
}
|
|
151
|
-
return outObj;
|
|
152
|
-
}
|
|
153
|
-
obj = recurse(obj);
|
|
154
|
-
return obj;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
export function fromJSON(obj: any, externalReferences?: any) {
|
|
158
|
-
//console.log('fromJSON');
|
|
159
|
-
var dup_refs: any = {};
|
|
160
|
-
|
|
161
|
-
function recurse(obj: any) {
|
|
162
|
-
if (_.isString(obj)) {
|
|
163
|
-
// restore values
|
|
164
|
-
if (obj === "undefined") return undefined;
|
|
165
|
-
if (obj === "NaN") return NaN;
|
|
166
|
-
if (obj === "Infinity") return Infinity;
|
|
167
|
-
if (obj.match(/^__REGEXP /)) {
|
|
168
|
-
var m: any = obj.split("__REGEXP ")[1].match(/\/(.*)\/(.*)?/);
|
|
169
|
-
return new RegExp(m[1], m[2] || "");
|
|
170
|
-
}
|
|
171
|
-
if (obj.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)) {
|
|
172
|
-
return new Date(obj);
|
|
173
|
-
}
|
|
174
|
-
if (obj.match(/^__FUNCTION /)) {
|
|
175
|
-
return js(obj.substring(11), externalReferences);
|
|
176
|
-
}
|
|
177
|
-
if (obj.match(/^__HTML /)) {
|
|
178
|
-
//@ts-expect-error
|
|
179
|
-
if (typeof $ !== "undefined") return $(obj.substring(7))[0];
|
|
180
|
-
else return obj;
|
|
181
|
-
}
|
|
182
|
-
if (obj.startsWith("__ERROR ")) {
|
|
183
|
-
const error = new Error();
|
|
184
|
-
error.stack = obj.substring(8);
|
|
185
|
-
return error;
|
|
186
|
-
}
|
|
187
|
-
if (obj === "__WINDOW") {
|
|
188
|
-
return window;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
// deal with duplicate refs
|
|
192
|
-
if (obj.match(/^__duplicate_ref_/)) {
|
|
193
|
-
if (!dup_refs[obj]) dup_refs[obj] = obj.match(/_obj_/) ? {} : [];
|
|
194
|
-
return dup_refs[obj];
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
if (!(isObject(obj) || _.isArray(obj))) return obj;
|
|
199
|
-
|
|
200
|
-
// deal with objects that have duplicate refs
|
|
201
|
-
var dup_ref = null;
|
|
202
|
-
obj = _.clone(obj); // don't mess up the original JSON object
|
|
203
|
-
if (_.isArray(obj) && _.isString(obj[0]) && obj[0].match(/^__this_ref:/))
|
|
204
|
-
dup_ref = obj.shift().split(":")[1];
|
|
205
|
-
else if (obj.__this_ref) {
|
|
206
|
-
dup_ref = obj.__this_ref;
|
|
207
|
-
delete obj.__this_ref;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
var mObj: any = _.isArray(obj) ? [] : {};
|
|
211
|
-
if (dup_ref)
|
|
212
|
-
if (!dup_refs[dup_ref]) dup_refs[dup_ref] = mObj;
|
|
213
|
-
else mObj = dup_refs[dup_ref];
|
|
214
|
-
|
|
215
|
-
// restore keys and recurse on objects
|
|
216
|
-
for (var key in obj) {
|
|
217
|
-
if (!Object.hasOwn(obj, key)) continue;
|
|
218
|
-
|
|
219
|
-
var value = recurse(obj[key]);
|
|
220
|
-
if (key.match(/^__DOLLAR_/)) key = `$${key.substr(9)}`;
|
|
221
|
-
mObj[key] = value;
|
|
222
|
-
}
|
|
223
|
-
return mObj;
|
|
224
|
-
}
|
|
225
|
-
obj = recurse(obj);
|
|
226
|
-
return obj;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
71
|
// export type IObjectMatch<T> = {
|
|
230
72
|
// [key in keyof T]?: RegExp | string | number | boolean
|
|
231
73
|
// }
|
package/dist/hooks.d.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { type Observable } from "@peers-app/peers-sdk";
|
|
2
|
-
import type React from "react";
|
|
3
|
-
/**
|
|
4
|
-
* Use this to subscribe to an observable or computed in a functional component.
|
|
5
|
-
* Uses useSyncExternalStore for proper React 18 concurrent rendering support.
|
|
6
|
-
* @param sub the observable or computed to subscribe to
|
|
7
|
-
* @param deps an array of dependencies that will cause re-subscription when changed
|
|
8
|
-
* @returns the current value of the observable or computed and a function to set the value
|
|
9
|
-
*/
|
|
10
|
-
export declare function useObservable<T>(sub: Observable<T> | T, deps?: React.DependencyList): [T, (value: T) => void];
|
|
11
|
-
/**
|
|
12
|
-
* Use this to easily wait for a promise in a functional component.
|
|
13
|
-
* @param p The promise to wait for
|
|
14
|
-
* @param initialValue the initial value to return before the promise resolves
|
|
15
|
-
* @param deps the dependencies to pass to useEffect which will trigger a re-render when any of the dependencies change
|
|
16
|
-
* @returns the initial value and the resolved value of the promise
|
|
17
|
-
*/
|
|
18
|
-
export declare function usePromise<T>(p: Promise<T> | (() => Promise<T>), initialValue?: T, deps?: React.DependencyList): T | undefined;
|
|
19
|
-
/**
|
|
20
|
-
* Use this to create an observable in a functional component.
|
|
21
|
-
* This automatically subscribes to the observable and triggers a re-render when the value changes.
|
|
22
|
-
* @param initialValue This will be the initial value of the observable
|
|
23
|
-
* @param doNotSubscribe If true, the observable will not be subscribed to automatically.
|
|
24
|
-
* This is useful if you want to create an observable that persists between rerenders but doesn't cause rerenders itself.
|
|
25
|
-
* @returns
|
|
26
|
-
*/
|
|
27
|
-
export declare function useObservableState<T>(initialValue: T, doNotSubscribe?: boolean): Observable<T>;
|
|
28
|
-
export declare function useObservableState<T = undefined>(initialValue?: T, doNotSubscribe?: boolean): Observable<T | undefined>;
|
|
29
|
-
/**
|
|
30
|
-
* Use this to register a handler for a knockout subscribable in a functional component.
|
|
31
|
-
* The handler will be called immediately and whenever the subscribable changes.
|
|
32
|
-
* @param subscribable The observable to subscribe to
|
|
33
|
-
* @param onChange The function to call with the new value when the observable changes
|
|
34
|
-
*/
|
|
35
|
-
export declare function useSubscription<T>(subscribable: Observable<T>, onChange: (value: T) => void, doNotCallOnChangeDuringSetup?: boolean): void;
|
|
36
|
-
export declare function useOnScreen(ref: React.RefObject<Element | null>): boolean;
|
package/dist/hooks.js
DELETED
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.useObservable = useObservable;
|
|
4
|
-
exports.usePromise = usePromise;
|
|
5
|
-
exports.useObservableState = useObservableState;
|
|
6
|
-
exports.useSubscription = useSubscription;
|
|
7
|
-
exports.useOnScreen = useOnScreen;
|
|
8
|
-
const peers_sdk_1 = require("@peers-app/peers-sdk");
|
|
9
|
-
const react_1 = require("react");
|
|
10
|
-
/**
|
|
11
|
-
* Use this to subscribe to an observable or computed in a functional component.
|
|
12
|
-
* Uses useSyncExternalStore for proper React 18 concurrent rendering support.
|
|
13
|
-
* @param sub the observable or computed to subscribe to
|
|
14
|
-
* @param deps an array of dependencies that will cause re-subscription when changed
|
|
15
|
-
* @returns the current value of the observable or computed and a function to set the value
|
|
16
|
-
*/
|
|
17
|
-
function useObservable(sub, deps = []) {
|
|
18
|
-
// Create memoized subscribe function that adapts Observable's subscribe API to useSyncExternalStore's expected signature
|
|
19
|
-
const subscribe = (0, react_1.useCallback)((onStoreChange) => {
|
|
20
|
-
if (!(0, peers_sdk_1.isSubscribable)(sub)) {
|
|
21
|
-
// If not subscribable, return a no-op unsubscribe
|
|
22
|
-
return () => { };
|
|
23
|
-
}
|
|
24
|
-
const subscription = sub.subscribe(onStoreChange);
|
|
25
|
-
return () => subscription.dispose();
|
|
26
|
-
}, [sub, ...deps]);
|
|
27
|
-
// getSnapshot returns the current value from the observable
|
|
28
|
-
const getSnapshot = (0, react_1.useCallback)(() => {
|
|
29
|
-
return (0, peers_sdk_1.unwrapObservable)(sub);
|
|
30
|
-
}, [sub, ...deps]);
|
|
31
|
-
// Use useSyncExternalStore for concurrent-safe subscription
|
|
32
|
-
const data = (0, react_1.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
|
|
33
|
-
// Create setter that updates both local understanding and the observable
|
|
34
|
-
const setter = (0, react_1.useCallback)((newData) => {
|
|
35
|
-
if ((0, peers_sdk_1.isSubscribable)(sub)) {
|
|
36
|
-
sub(newData);
|
|
37
|
-
}
|
|
38
|
-
}, [sub]);
|
|
39
|
-
return [data, setter];
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Use this to easily wait for a promise in a functional component.
|
|
43
|
-
* @param p The promise to wait for
|
|
44
|
-
* @param initialValue the initial value to return before the promise resolves
|
|
45
|
-
* @param deps the dependencies to pass to useEffect which will trigger a re-render when any of the dependencies change
|
|
46
|
-
* @returns the initial value and the resolved value of the promise
|
|
47
|
-
*/
|
|
48
|
-
function usePromise(p, initialValue, deps = []) {
|
|
49
|
-
const [data, setData] = (0, react_1.useState)(initialValue);
|
|
50
|
-
// `deps` drives when the effect re-runs; callers include `p` when it changes. Omitting `p` avoids duplicate tracking with `[...deps]`.
|
|
51
|
-
(0, react_1.useEffect)(() => {
|
|
52
|
-
let disposed = false;
|
|
53
|
-
if (typeof p === "function") {
|
|
54
|
-
p = p();
|
|
55
|
-
}
|
|
56
|
-
p.then((newData) => {
|
|
57
|
-
// if (!_.isEqual(newData, data) && !disposed) {
|
|
58
|
-
if (!disposed) {
|
|
59
|
-
setData(newData);
|
|
60
|
-
}
|
|
61
|
-
});
|
|
62
|
-
return () => {
|
|
63
|
-
disposed = true;
|
|
64
|
-
};
|
|
65
|
-
}, [...deps]);
|
|
66
|
-
return data;
|
|
67
|
-
}
|
|
68
|
-
function useObservableState(initialValue, doNotSubscribe) {
|
|
69
|
-
const [obs] = (0, react_1.useState)(() => initialValue !== undefined ? (0, peers_sdk_1.observable)(initialValue) : (0, peers_sdk_1.observable)());
|
|
70
|
-
if (!doNotSubscribe) {
|
|
71
|
-
// biome-ignore lint/correctness/useHookAtTopLevel: when doNotSubscribe, caller keeps a stable observable without React-driven subscription (see docstring).
|
|
72
|
-
useObservable(obs);
|
|
73
|
-
}
|
|
74
|
-
return obs;
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* Use this to register a handler for a knockout subscribable in a functional component.
|
|
78
|
-
* The handler will be called immediately and whenever the subscribable changes.
|
|
79
|
-
* @param subscribable The observable to subscribe to
|
|
80
|
-
* @param onChange The function to call with the new value when the observable changes
|
|
81
|
-
*/
|
|
82
|
-
function useSubscription(subscribable, onChange, doNotCallOnChangeDuringSetup) {
|
|
83
|
-
(0, react_1.useEffect)(() => {
|
|
84
|
-
if (!doNotCallOnChangeDuringSetup) {
|
|
85
|
-
onChange(subscribable());
|
|
86
|
-
}
|
|
87
|
-
const subscription = subscribable.subscribe(() => onChange(subscribable()));
|
|
88
|
-
return () => subscription.dispose();
|
|
89
|
-
}, [subscribable, onChange, doNotCallOnChangeDuringSetup]);
|
|
90
|
-
}
|
|
91
|
-
function useOnScreen(ref) {
|
|
92
|
-
const [isIntersecting, setIntersecting] = (0, react_1.useState)(false);
|
|
93
|
-
// Read ref.current once on mount (ref object identity is stable).
|
|
94
|
-
(0, react_1.useEffect)(() => {
|
|
95
|
-
const element = ref.current;
|
|
96
|
-
if (!element) {
|
|
97
|
-
return;
|
|
98
|
-
}
|
|
99
|
-
const observer = new IntersectionObserver(([entry]) => {
|
|
100
|
-
setIntersecting(entry.isIntersecting);
|
|
101
|
-
});
|
|
102
|
-
observer.observe(element);
|
|
103
|
-
return () => {
|
|
104
|
-
observer.disconnect();
|
|
105
|
-
};
|
|
106
|
-
}, []);
|
|
107
|
-
return isIntersecting;
|
|
108
|
-
}
|
package/src/hooks.ts
DELETED
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
isSubscribable,
|
|
3
|
-
type Observable,
|
|
4
|
-
observable,
|
|
5
|
-
unwrapObservable,
|
|
6
|
-
} from "@peers-app/peers-sdk";
|
|
7
|
-
import type React from "react";
|
|
8
|
-
import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Use this to subscribe to an observable or computed in a functional component.
|
|
12
|
-
* Uses useSyncExternalStore for proper React 18 concurrent rendering support.
|
|
13
|
-
* @param sub the observable or computed to subscribe to
|
|
14
|
-
* @param deps an array of dependencies that will cause re-subscription when changed
|
|
15
|
-
* @returns the current value of the observable or computed and a function to set the value
|
|
16
|
-
*/
|
|
17
|
-
export function useObservable<T>(
|
|
18
|
-
sub: Observable<T> | T,
|
|
19
|
-
deps: React.DependencyList = [],
|
|
20
|
-
): [T, (value: T) => void] {
|
|
21
|
-
// Create memoized subscribe function that adapts Observable's subscribe API to useSyncExternalStore's expected signature
|
|
22
|
-
const subscribe = useCallback(
|
|
23
|
-
(onStoreChange: () => void) => {
|
|
24
|
-
if (!isSubscribable(sub)) {
|
|
25
|
-
// If not subscribable, return a no-op unsubscribe
|
|
26
|
-
return () => {};
|
|
27
|
-
}
|
|
28
|
-
const subscription = sub.subscribe(onStoreChange);
|
|
29
|
-
return () => subscription.dispose();
|
|
30
|
-
},
|
|
31
|
-
[sub, ...deps],
|
|
32
|
-
);
|
|
33
|
-
|
|
34
|
-
// getSnapshot returns the current value from the observable
|
|
35
|
-
const getSnapshot = useCallback(() => {
|
|
36
|
-
return unwrapObservable(sub);
|
|
37
|
-
}, [sub, ...deps]);
|
|
38
|
-
|
|
39
|
-
// Use useSyncExternalStore for concurrent-safe subscription
|
|
40
|
-
const data = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
41
|
-
|
|
42
|
-
// Create setter that updates both local understanding and the observable
|
|
43
|
-
const setter = useCallback(
|
|
44
|
-
(newData: T) => {
|
|
45
|
-
if (isSubscribable(sub)) {
|
|
46
|
-
sub(newData);
|
|
47
|
-
}
|
|
48
|
-
},
|
|
49
|
-
[sub],
|
|
50
|
-
);
|
|
51
|
-
|
|
52
|
-
return [data, setter];
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* Use this to easily wait for a promise in a functional component.
|
|
57
|
-
* @param p The promise to wait for
|
|
58
|
-
* @param initialValue the initial value to return before the promise resolves
|
|
59
|
-
* @param deps the dependencies to pass to useEffect which will trigger a re-render when any of the dependencies change
|
|
60
|
-
* @returns the initial value and the resolved value of the promise
|
|
61
|
-
*/
|
|
62
|
-
export function usePromise<T>(
|
|
63
|
-
p: Promise<T> | (() => Promise<T>),
|
|
64
|
-
initialValue?: T,
|
|
65
|
-
deps: React.DependencyList = [],
|
|
66
|
-
): T | undefined {
|
|
67
|
-
const [data, setData] = useState(initialValue);
|
|
68
|
-
// `deps` drives when the effect re-runs; callers include `p` when it changes. Omitting `p` avoids duplicate tracking with `[...deps]`.
|
|
69
|
-
useEffect(() => {
|
|
70
|
-
let disposed = false;
|
|
71
|
-
if (typeof p === "function") {
|
|
72
|
-
p = p();
|
|
73
|
-
}
|
|
74
|
-
p.then((newData) => {
|
|
75
|
-
// if (!_.isEqual(newData, data) && !disposed) {
|
|
76
|
-
if (!disposed) {
|
|
77
|
-
setData(newData);
|
|
78
|
-
}
|
|
79
|
-
});
|
|
80
|
-
return () => {
|
|
81
|
-
disposed = true;
|
|
82
|
-
};
|
|
83
|
-
}, [...deps]);
|
|
84
|
-
return data;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* Use this to create an observable in a functional component.
|
|
89
|
-
* This automatically subscribes to the observable and triggers a re-render when the value changes.
|
|
90
|
-
* @param initialValue This will be the initial value of the observable
|
|
91
|
-
* @param doNotSubscribe If true, the observable will not be subscribed to automatically.
|
|
92
|
-
* This is useful if you want to create an observable that persists between rerenders but doesn't cause rerenders itself.
|
|
93
|
-
* @returns
|
|
94
|
-
*/
|
|
95
|
-
export function useObservableState<T>(initialValue: T, doNotSubscribe?: boolean): Observable<T>;
|
|
96
|
-
export function useObservableState<T = undefined>(
|
|
97
|
-
initialValue?: T,
|
|
98
|
-
doNotSubscribe?: boolean,
|
|
99
|
-
): Observable<T | undefined>;
|
|
100
|
-
export function useObservableState<T>(initialValue?: T, doNotSubscribe?: boolean) {
|
|
101
|
-
const [obs] = useState(() =>
|
|
102
|
-
initialValue !== undefined ? observable<T>(initialValue) : observable<T | undefined>(),
|
|
103
|
-
);
|
|
104
|
-
if (!doNotSubscribe) {
|
|
105
|
-
// biome-ignore lint/correctness/useHookAtTopLevel: when doNotSubscribe, caller keeps a stable observable without React-driven subscription (see docstring).
|
|
106
|
-
useObservable(obs);
|
|
107
|
-
}
|
|
108
|
-
return obs;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Use this to register a handler for a knockout subscribable in a functional component.
|
|
113
|
-
* The handler will be called immediately and whenever the subscribable changes.
|
|
114
|
-
* @param subscribable The observable to subscribe to
|
|
115
|
-
* @param onChange The function to call with the new value when the observable changes
|
|
116
|
-
*/
|
|
117
|
-
export function useSubscription<T>(
|
|
118
|
-
subscribable: Observable<T>,
|
|
119
|
-
onChange: (value: T) => void,
|
|
120
|
-
doNotCallOnChangeDuringSetup?: boolean,
|
|
121
|
-
): void {
|
|
122
|
-
useEffect(() => {
|
|
123
|
-
if (!doNotCallOnChangeDuringSetup) {
|
|
124
|
-
onChange(subscribable());
|
|
125
|
-
}
|
|
126
|
-
const subscription = subscribable.subscribe(() => onChange(subscribable()));
|
|
127
|
-
return () => subscription.dispose();
|
|
128
|
-
}, [subscribable, onChange, doNotCallOnChangeDuringSetup]);
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export function useOnScreen(ref: React.RefObject<Element | null>) {
|
|
132
|
-
const [isIntersecting, setIntersecting] = useState(false);
|
|
133
|
-
|
|
134
|
-
// Read ref.current once on mount (ref object identity is stable).
|
|
135
|
-
useEffect(() => {
|
|
136
|
-
const element = ref.current;
|
|
137
|
-
if (!element) {
|
|
138
|
-
return;
|
|
139
|
-
}
|
|
140
|
-
const observer = new IntersectionObserver(([entry]) => {
|
|
141
|
-
setIntersecting(entry.isIntersecting);
|
|
142
|
-
});
|
|
143
|
-
observer.observe(element);
|
|
144
|
-
return () => {
|
|
145
|
-
observer.disconnect();
|
|
146
|
-
};
|
|
147
|
-
}, []);
|
|
148
|
-
|
|
149
|
-
return isIntersecting;
|
|
150
|
-
}
|
|
File without changes
|