@verdant-web/react 23.0.1 → 23.0.3-next.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/esm/hooks.js CHANGED
@@ -1,387 +1,387 @@
1
- var __rest = (this && this.__rest) || function (s, e) {
2
- var t = {};
3
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
- t[p] = s[p];
5
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
- t[p[i]] = s[p[i]];
9
- }
10
- return t;
11
- };
12
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
13
- import { EntityFile, } from '@verdant-web/store';
14
- import { createContext, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore, } from 'react';
15
- import { suspend } from 'suspend-react';
16
- import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector.js';
17
- function isQueryCurrentValid(query) {
18
- return !(query.status === 'initial' || query.status === 'initializing');
19
- }
20
- function useLiveQuery(liveQuery, disableSuspense = false) {
21
- // suspend if the query doesn't have a valid result set yet.
22
- if (!disableSuspense && liveQuery && !isQueryCurrentValid(liveQuery)) {
23
- suspend(() => liveQuery.resolved, [liveQuery]);
24
- }
25
- return useSyncExternalStore((callback) => {
26
- if (liveQuery) {
27
- return liveQuery.subscribe('change', callback);
28
- }
29
- else {
30
- return () => { };
31
- }
32
- }, () => {
33
- return liveQuery ? liveQuery.current : null;
34
- });
35
- }
36
- function useLiveQueryStatus(liveQuery) {
37
- return useSyncExternalStore((callback) => {
38
- if (liveQuery) {
39
- return liveQuery.subscribe('statusChange', callback);
40
- }
41
- else {
42
- return () => { };
43
- }
44
- }, () => {
45
- var _a;
46
- return (_a = liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.status) !== null && _a !== void 0 ? _a : 'initial';
47
- });
48
- }
49
- function capitalize(str) {
50
- return (str.charAt(0).toUpperCase() + str.slice(1));
51
- }
52
- export function createHooks(schema) {
53
- const Context = createContext(null);
54
- function useStorage() {
55
- const ctx = useContext(Context);
56
- if (!ctx) {
57
- throw new Error('No verdant provider was found');
58
- }
59
- return suspend(() => ctx.readyPromise, ['lofi_' + ctx.namespace]);
60
- }
61
- function useWatch(liveObject, prop) {
62
- return useSyncExternalStore((handler) => {
63
- if (liveObject) {
64
- return liveObject.subscribe('change', handler);
65
- }
66
- return () => { };
67
- }, () => {
68
- if (liveObject) {
69
- if (liveObject instanceof EntityFile) {
70
- return liveObject.url;
71
- }
72
- else {
73
- if (prop) {
74
- return liveObject.get(prop);
75
- }
76
- return liveObject.getAll();
77
- }
78
- }
79
- return undefined;
80
- });
81
- }
82
- function useSelf() {
83
- const storage = useStorage();
84
- return useSyncExternalStore((callback) => storage.sync.presence.subscribe('selfChanged', callback), () => storage.sync.presence.self);
85
- }
86
- function usePeerIds() {
87
- const storage = useStorage();
88
- return useSyncExternalStore((callback) => storage.sync.presence.subscribe('peersChanged', callback), () => storage.sync.presence.peerIds);
89
- }
90
- function usePeer(peerId) {
91
- const storage = useStorage();
92
- return useSyncExternalStore((callback) => {
93
- const unsubs = [];
94
- unsubs.push(storage.sync.presence.subscribe('peerChanged', (id, user) => {
95
- if (id === peerId) {
96
- callback();
97
- }
98
- }));
99
- unsubs.push(storage.sync.presence.subscribe('peerLeft', (id) => {
100
- if (id === peerId) {
101
- callback();
102
- }
103
- }));
104
- return () => {
105
- unsubs.forEach((unsub) => unsub());
106
- };
107
- }, () => { var _a; return (peerId ? (_a = storage.sync.presence.peers[peerId]) !== null && _a !== void 0 ? _a : null : null); });
108
- }
109
- function useFindPeer(query, options) {
110
- const storage = useStorage();
111
- return useSyncExternalStore((callback) => {
112
- const unsubs = [];
113
- unsubs.push(storage.sync.presence.subscribe('peerChanged', (id, user) => {
114
- if (query(user)) {
115
- callback();
116
- }
117
- }));
118
- unsubs.push(storage.sync.presence.subscribe('peerLeft', (id) => {
119
- if (query(storage.sync.presence.peers[id])) {
120
- callback();
121
- }
122
- }));
123
- if (options === null || options === void 0 ? void 0 : options.includeSelf) {
124
- unsubs.push(storage.sync.presence.subscribe('selfChanged', (user) => {
125
- if (query(user)) {
126
- callback();
127
- }
128
- }));
129
- }
130
- return () => {
131
- unsubs.forEach((unsub) => unsub());
132
- };
133
- }, () => {
134
- const peers = Object.values(storage.sync.presence.peers);
135
- if (options === null || options === void 0 ? void 0 : options.includeSelf) {
136
- peers.push(storage.sync.presence.self);
137
- }
138
- return peers.find(query) || null;
139
- });
140
- }
141
- function useFindPeers(query, options) {
142
- const storage = useStorage();
143
- return useSyncExternalStoreWithSelector((callback) => {
144
- const unsubs = [];
145
- unsubs.push(storage.sync.presence.subscribe('peerChanged', (id, user) => {
146
- if (user && query(user)) {
147
- callback();
148
- }
149
- }));
150
- unsubs.push(storage.sync.presence.subscribe('peerLeft', (id) => {
151
- callback();
152
- }));
153
- if (options === null || options === void 0 ? void 0 : options.includeSelf) {
154
- unsubs.push(storage.sync.presence.subscribe('selfChanged', (user) => {
155
- if (query(user)) {
156
- callback();
157
- }
158
- }));
159
- }
160
- return () => {
161
- unsubs.forEach((unsub) => unsub());
162
- };
163
- }, () => {
164
- const peers = Object.values(storage.sync.presence.peers).filter(Boolean);
165
- if (options === null || options === void 0 ? void 0 : options.includeSelf) {
166
- peers.push(storage.sync.presence.self);
167
- }
168
- return peers.filter((p) => !!p).filter(query);
169
- }, () => [], (peers) => peers, (a, b) => a.length === b.length && a.every((peer, i) => peer === b[i]));
170
- }
171
- function useSyncStatus() {
172
- const storage = useStorage();
173
- return useSyncExternalStore((callback) => storage.sync.subscribe('onlineChange', callback), () => storage.sync.isConnected);
174
- }
175
- function useUndo() {
176
- const storage = useStorage();
177
- return useCallback(() => storage.undoHistory.undo(), [storage]);
178
- }
179
- function useRedo() {
180
- const storage = useStorage();
181
- return useCallback(() => storage.undoHistory.redo(), [storage]);
182
- }
183
- function useCanUndo() {
184
- const storage = useStorage();
185
- return useSyncExternalStore((callback) => storage.undoHistory.subscribe('change', callback), () => storage.undoHistory.canUndo);
186
- }
187
- function useCanRedo() {
188
- const storage = useStorage();
189
- return useSyncExternalStore((callback) => storage.undoHistory.subscribe('change', callback), () => storage.undoHistory.canRedo);
190
- }
191
- function useUnsuspendedClient() {
192
- const desc = useContext(Context);
193
- const client = desc === null || desc === void 0 ? void 0 : desc.current;
194
- const [_, forceUpdate] = useState(0);
195
- useEffect(() => {
196
- if (desc && !client) {
197
- desc.readyPromise.then(() => forceUpdate((n) => n + 1));
198
- }
199
- }, [desc, client]);
200
- return client || null;
201
- }
202
- /**
203
- * Non-suspending hook which allows declarative sync start/stop
204
- * control.
205
- *
206
- * You can optionally configure parameters as part of this as well.
207
- */
208
- function useSync(isOn, config = {}) {
209
- const client = useUnsuspendedClient();
210
- useEffect(() => {
211
- if (client) {
212
- if (isOn) {
213
- client.sync.start();
214
- }
215
- else {
216
- client.sync.stop();
217
- }
218
- }
219
- }, [client, isOn]);
220
- useEffect(() => {
221
- if (client) {
222
- if (config.mode !== undefined) {
223
- client.sync.setMode(config.mode);
224
- }
225
- }
226
- }, [client, config.mode]);
227
- useEffect(() => {
228
- if (client) {
229
- if (config.pullInterval !== undefined) {
230
- client.sync.setPullInterval(config.pullInterval);
231
- }
232
- }
233
- }, [client, config.pullInterval]);
234
- }
235
- function SyncController({ isOn }) {
236
- useSync(isOn);
237
- return null;
238
- }
239
- const hooks = {
240
- useStorage,
241
- useClient: useStorage,
242
- useUnsuspendedClient,
243
- useWatch,
244
- useSelf,
245
- usePeerIds,
246
- usePeer,
247
- useFindPeer,
248
- useFindPeers,
249
- useSyncStatus,
250
- useUndo,
251
- useRedo,
252
- useCanUndo,
253
- useCanRedo,
254
- useSync,
255
- Context,
256
- Provider: (_a) => {
257
- var { value, children, sync } = _a, rest = __rest(_a, ["value", "children", "sync"]);
258
- // auto-open storage when used in provider
259
- useMemo(() => {
260
- value.open();
261
- }, [value]);
262
- return (_jsxs(Context.Provider, Object.assign({ value: value }, rest, { children: [children, sync !== undefined && _jsx(SyncController, { isOn: sync })] })));
263
- },
264
- };
265
- const collectionNames = Object.keys(schema.collections);
266
- for (const pluralName of collectionNames) {
267
- const collection = schema.collections[pluralName];
268
- const getOneHookName = `use${capitalize(collection.name)}`;
269
- hooks[getOneHookName] = function useIndividual(id, { skip } = {}) {
270
- const storage = useStorage();
271
- const liveQuery = useMemo(() => {
272
- return skip ? null : storage[pluralName].get(id);
273
- }, [id, skip]);
274
- const data = useLiveQuery(liveQuery);
275
- return data;
276
- };
277
- hooks[getOneHookName + 'Unsuspended'] = function useIndividualUnsuspended(id, { skip } = {}) {
278
- const storage = useStorage();
279
- const liveQuery = useMemo(() => {
280
- return skip ? null : storage[pluralName].get(id);
281
- }, [id, skip]);
282
- const data = useLiveQuery(liveQuery, true);
283
- const status = useLiveQueryStatus(liveQuery);
284
- return { data, status };
285
- };
286
- const findOneHookName = `useOne${capitalize(collection.name)}`;
287
- hooks[findOneHookName] = function useOne({ skip, index, key, } = {}) {
288
- const storage = useStorage();
289
- const liveQuery = useMemo(() => {
290
- return skip ? null : storage[pluralName].findOne({ index, key });
291
- }, [index, skip]);
292
- const data = useLiveQuery(liveQuery);
293
- return data;
294
- };
295
- hooks[findOneHookName + 'Unsuspended'] = function useOneUnsuspended({ skip, index, key, } = {}) {
296
- const storage = useStorage();
297
- const liveQuery = useMemo(() => {
298
- return skip ? null : storage[pluralName].findOne({ index, key });
299
- }, [index, skip]);
300
- const data = useLiveQuery(liveQuery, true);
301
- const status = useLiveQueryStatus(liveQuery);
302
- return { data, status };
303
- };
304
- const getAllHookName = `useAll${capitalize(pluralName)}`;
305
- hooks[getAllHookName] = function useAll({ index, skip, key, } = {}) {
306
- const storage = useStorage();
307
- // assumptions: this query getter is fast and returns the same
308
- // query identity for subsequent calls.
309
- const liveQuery = useMemo(() => (skip ? null : storage[pluralName].findAll({ index, key })), [index, skip]);
310
- const data = useLiveQuery(liveQuery);
311
- return data || [];
312
- };
313
- hooks[getAllHookName + 'Unsuspended'] = function useAllUnsuspended({ index, skip, key, } = {}) {
314
- const storage = useStorage();
315
- // assumptions: this query getter is fast and returns the same
316
- // query identity for subsequent calls.
317
- const liveQuery = useMemo(() => (skip ? null : storage[pluralName].findAll({ index, key })), [index, skip]);
318
- const data = useLiveQuery(liveQuery, true) || [];
319
- const status = useLiveQueryStatus(liveQuery);
320
- return { data, status };
321
- };
322
- const getAllPaginatedHookName = `useAll${capitalize(pluralName)}Paginated`;
323
- hooks[getAllPaginatedHookName] = function useAllPaginated({ index, skip, pageSize = 10, key, suspend, } = {}) {
324
- const storage = useStorage();
325
- // assumptions: this query getter is fast and returns the same
326
- // query identity for subsequent calls.
327
- const liveQuery = useMemo(() => skip
328
- ? null
329
- : storage[pluralName].findPage({
330
- index,
331
- pageSize,
332
- page: 0,
333
- key: key || getAllPaginatedHookName,
334
- }), [index, skip, pageSize]);
335
- const data = useLiveQuery(liveQuery, suspend === false);
336
- const status = useLiveQueryStatus(liveQuery);
337
- const tools = useMemo(() => ({
338
- next: () => liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.nextPage(),
339
- previous: () => liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.previousPage(),
340
- setPage: (page) => liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.setPage(page),
341
- get hasPrevious() {
342
- return liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.hasPreviousPage;
343
- },
344
- get hasNext() {
345
- return liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.hasNextPage;
346
- },
347
- status,
348
- }), [liveQuery, status]);
349
- return [data, tools];
350
- };
351
- const getAllInfiniteHookName = `useAll${capitalize(pluralName)}Infinite`;
352
- hooks[getAllInfiniteHookName] = function useAllInfinite({ index, skip, pageSize = 10, key, suspend, } = {}) {
353
- const storage = useStorage();
354
- // assumptions: this query getter is fast and returns the same
355
- // query identity for subsequent calls.
356
- const liveQuery = useMemo(() => skip
357
- ? null
358
- : storage[pluralName].findAllInfinite({
359
- index,
360
- pageSize,
361
- key: key || getAllInfiniteHookName,
362
- }), [index, skip, pageSize]);
363
- const data = useLiveQuery(liveQuery, suspend === false);
364
- const status = useLiveQueryStatus(liveQuery);
365
- const tools = useMemo(() => ({
366
- loadMore: () => liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.loadMore(),
367
- get hasMore() {
368
- return liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.hasMore;
369
- },
370
- status,
371
- }), [liveQuery, status]);
372
- return [data, tools];
373
- };
374
- }
375
- hooks.withMutations = (mutations) => {
376
- const augmentedHooks = Object.assign({}, hooks);
377
- for (const [name, subHook] of Object.entries(mutations)) {
378
- augmentedHooks[name] = (...args) => {
379
- const client = hooks.useClient();
380
- return subHook(client, ...args);
381
- };
382
- }
383
- return augmentedHooks;
384
- };
385
- return hooks;
386
- }
1
+ var __rest = (this && this.__rest) || function (s, e) {
2
+ var t = {};
3
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
+ t[p] = s[p];
5
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
+ t[p[i]] = s[p[i]];
9
+ }
10
+ return t;
11
+ };
12
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
13
+ import { EntityFile, } from '@verdant-web/store';
14
+ import { createContext, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore, } from 'react';
15
+ import { suspend } from 'suspend-react';
16
+ import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector.js';
17
+ function isQueryCurrentValid(query) {
18
+ return !(query.status === 'initial' || query.status === 'initializing');
19
+ }
20
+ function useLiveQuery(liveQuery, disableSuspense = false) {
21
+ // suspend if the query doesn't have a valid result set yet.
22
+ if (!disableSuspense && liveQuery && !isQueryCurrentValid(liveQuery)) {
23
+ suspend(() => liveQuery.resolved, [liveQuery]);
24
+ }
25
+ return useSyncExternalStore((callback) => {
26
+ if (liveQuery) {
27
+ return liveQuery.subscribe('change', callback);
28
+ }
29
+ else {
30
+ return () => { };
31
+ }
32
+ }, () => {
33
+ return liveQuery ? liveQuery.current : null;
34
+ });
35
+ }
36
+ function useLiveQueryStatus(liveQuery) {
37
+ return useSyncExternalStore((callback) => {
38
+ if (liveQuery) {
39
+ return liveQuery.subscribe('statusChange', callback);
40
+ }
41
+ else {
42
+ return () => { };
43
+ }
44
+ }, () => {
45
+ var _a;
46
+ return (_a = liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.status) !== null && _a !== void 0 ? _a : 'initial';
47
+ });
48
+ }
49
+ function capitalize(str) {
50
+ return (str.charAt(0).toUpperCase() + str.slice(1));
51
+ }
52
+ export function createHooks(schema) {
53
+ const Context = createContext(null);
54
+ function useStorage() {
55
+ const ctx = useContext(Context);
56
+ if (!ctx) {
57
+ throw new Error('No verdant provider was found');
58
+ }
59
+ return suspend(() => ctx.readyPromise, ['lofi_' + ctx.namespace]);
60
+ }
61
+ function useWatch(liveObject, prop) {
62
+ return useSyncExternalStore((handler) => {
63
+ if (liveObject) {
64
+ return liveObject.subscribe('change', handler);
65
+ }
66
+ return () => { };
67
+ }, () => {
68
+ if (liveObject) {
69
+ if (liveObject instanceof EntityFile) {
70
+ return liveObject.url;
71
+ }
72
+ else {
73
+ if (prop) {
74
+ return liveObject.get(prop);
75
+ }
76
+ return liveObject.getAll();
77
+ }
78
+ }
79
+ return undefined;
80
+ });
81
+ }
82
+ function useSelf() {
83
+ const storage = useStorage();
84
+ return useSyncExternalStore((callback) => storage.sync.presence.subscribe('selfChanged', callback), () => storage.sync.presence.self);
85
+ }
86
+ function usePeerIds() {
87
+ const storage = useStorage();
88
+ return useSyncExternalStore((callback) => storage.sync.presence.subscribe('peersChanged', callback), () => storage.sync.presence.peerIds);
89
+ }
90
+ function usePeer(peerId) {
91
+ const storage = useStorage();
92
+ return useSyncExternalStore((callback) => {
93
+ const unsubs = [];
94
+ unsubs.push(storage.sync.presence.subscribe('peerChanged', (id, user) => {
95
+ if (id === peerId) {
96
+ callback();
97
+ }
98
+ }));
99
+ unsubs.push(storage.sync.presence.subscribe('peerLeft', (id) => {
100
+ if (id === peerId) {
101
+ callback();
102
+ }
103
+ }));
104
+ return () => {
105
+ unsubs.forEach((unsub) => unsub());
106
+ };
107
+ }, () => { var _a; return (peerId ? (_a = storage.sync.presence.peers[peerId]) !== null && _a !== void 0 ? _a : null : null); });
108
+ }
109
+ function useFindPeer(query, options) {
110
+ const storage = useStorage();
111
+ return useSyncExternalStore((callback) => {
112
+ const unsubs = [];
113
+ unsubs.push(storage.sync.presence.subscribe('peerChanged', (id, user) => {
114
+ if (query(user)) {
115
+ callback();
116
+ }
117
+ }));
118
+ unsubs.push(storage.sync.presence.subscribe('peerLeft', (id) => {
119
+ if (query(storage.sync.presence.peers[id])) {
120
+ callback();
121
+ }
122
+ }));
123
+ if (options === null || options === void 0 ? void 0 : options.includeSelf) {
124
+ unsubs.push(storage.sync.presence.subscribe('selfChanged', (user) => {
125
+ if (query(user)) {
126
+ callback();
127
+ }
128
+ }));
129
+ }
130
+ return () => {
131
+ unsubs.forEach((unsub) => unsub());
132
+ };
133
+ }, () => {
134
+ const peers = Object.values(storage.sync.presence.peers);
135
+ if (options === null || options === void 0 ? void 0 : options.includeSelf) {
136
+ peers.push(storage.sync.presence.self);
137
+ }
138
+ return peers.find(query) || null;
139
+ });
140
+ }
141
+ function useFindPeers(query, options) {
142
+ const storage = useStorage();
143
+ return useSyncExternalStoreWithSelector((callback) => {
144
+ const unsubs = [];
145
+ unsubs.push(storage.sync.presence.subscribe('peerChanged', (id, user) => {
146
+ if (user && query(user)) {
147
+ callback();
148
+ }
149
+ }));
150
+ unsubs.push(storage.sync.presence.subscribe('peerLeft', (id) => {
151
+ callback();
152
+ }));
153
+ if (options === null || options === void 0 ? void 0 : options.includeSelf) {
154
+ unsubs.push(storage.sync.presence.subscribe('selfChanged', (user) => {
155
+ if (query(user)) {
156
+ callback();
157
+ }
158
+ }));
159
+ }
160
+ return () => {
161
+ unsubs.forEach((unsub) => unsub());
162
+ };
163
+ }, () => {
164
+ const peers = Object.values(storage.sync.presence.peers).filter(Boolean);
165
+ if (options === null || options === void 0 ? void 0 : options.includeSelf) {
166
+ peers.push(storage.sync.presence.self);
167
+ }
168
+ return peers.filter((p) => !!p).filter(query);
169
+ }, () => [], (peers) => peers, (a, b) => a.length === b.length && a.every((peer, i) => peer === b[i]));
170
+ }
171
+ function useSyncStatus() {
172
+ const storage = useStorage();
173
+ return useSyncExternalStore((callback) => storage.sync.subscribe('onlineChange', callback), () => storage.sync.isConnected);
174
+ }
175
+ function useUndo() {
176
+ const storage = useStorage();
177
+ return useCallback(() => storage.undoHistory.undo(), [storage]);
178
+ }
179
+ function useRedo() {
180
+ const storage = useStorage();
181
+ return useCallback(() => storage.undoHistory.redo(), [storage]);
182
+ }
183
+ function useCanUndo() {
184
+ const storage = useStorage();
185
+ return useSyncExternalStore((callback) => storage.undoHistory.subscribe('change', callback), () => storage.undoHistory.canUndo);
186
+ }
187
+ function useCanRedo() {
188
+ const storage = useStorage();
189
+ return useSyncExternalStore((callback) => storage.undoHistory.subscribe('change', callback), () => storage.undoHistory.canRedo);
190
+ }
191
+ function useUnsuspendedClient() {
192
+ const desc = useContext(Context);
193
+ const client = desc === null || desc === void 0 ? void 0 : desc.current;
194
+ const [_, forceUpdate] = useState(0);
195
+ useEffect(() => {
196
+ if (desc && !client) {
197
+ desc.readyPromise.then(() => forceUpdate((n) => n + 1));
198
+ }
199
+ }, [desc, client]);
200
+ return client || null;
201
+ }
202
+ /**
203
+ * Non-suspending hook which allows declarative sync start/stop
204
+ * control.
205
+ *
206
+ * You can optionally configure parameters as part of this as well.
207
+ */
208
+ function useSync(isOn, config = {}) {
209
+ const client = useUnsuspendedClient();
210
+ useEffect(() => {
211
+ if (client) {
212
+ if (isOn) {
213
+ client.sync.start();
214
+ }
215
+ else {
216
+ client.sync.stop();
217
+ }
218
+ }
219
+ }, [client, isOn]);
220
+ useEffect(() => {
221
+ if (client) {
222
+ if (config.mode !== undefined) {
223
+ client.sync.setMode(config.mode);
224
+ }
225
+ }
226
+ }, [client, config.mode]);
227
+ useEffect(() => {
228
+ if (client) {
229
+ if (config.pullInterval !== undefined) {
230
+ client.sync.setPullInterval(config.pullInterval);
231
+ }
232
+ }
233
+ }, [client, config.pullInterval]);
234
+ }
235
+ function SyncController({ isOn }) {
236
+ useSync(isOn);
237
+ return null;
238
+ }
239
+ const hooks = {
240
+ useStorage,
241
+ useClient: useStorage,
242
+ useUnsuspendedClient,
243
+ useWatch,
244
+ useSelf,
245
+ usePeerIds,
246
+ usePeer,
247
+ useFindPeer,
248
+ useFindPeers,
249
+ useSyncStatus,
250
+ useUndo,
251
+ useRedo,
252
+ useCanUndo,
253
+ useCanRedo,
254
+ useSync,
255
+ Context,
256
+ Provider: (_a) => {
257
+ var { value, children, sync } = _a, rest = __rest(_a, ["value", "children", "sync"]);
258
+ // auto-open storage when used in provider
259
+ useMemo(() => {
260
+ value.open();
261
+ }, [value]);
262
+ return (_jsxs(Context.Provider, Object.assign({ value: value }, rest, { children: [children, sync !== undefined && _jsx(SyncController, { isOn: sync })] })));
263
+ },
264
+ };
265
+ const collectionNames = Object.keys(schema.collections);
266
+ for (const pluralName of collectionNames) {
267
+ const collection = schema.collections[pluralName];
268
+ const getOneHookName = `use${capitalize(collection.name)}`;
269
+ hooks[getOneHookName] = function useIndividual(id, { skip } = {}) {
270
+ const storage = useStorage();
271
+ const liveQuery = useMemo(() => {
272
+ return skip ? null : storage[pluralName].get(id);
273
+ }, [id, skip]);
274
+ const data = useLiveQuery(liveQuery);
275
+ return data;
276
+ };
277
+ hooks[getOneHookName + 'Unsuspended'] = function useIndividualUnsuspended(id, { skip } = {}) {
278
+ const storage = useStorage();
279
+ const liveQuery = useMemo(() => {
280
+ return skip ? null : storage[pluralName].get(id);
281
+ }, [id, skip]);
282
+ const data = useLiveQuery(liveQuery, true);
283
+ const status = useLiveQueryStatus(liveQuery);
284
+ return { data, status };
285
+ };
286
+ const findOneHookName = `useOne${capitalize(collection.name)}`;
287
+ hooks[findOneHookName] = function useOne({ skip, index, key, } = {}) {
288
+ const storage = useStorage();
289
+ const liveQuery = useMemo(() => {
290
+ return skip ? null : storage[pluralName].findOne({ index, key });
291
+ }, [index, skip]);
292
+ const data = useLiveQuery(liveQuery);
293
+ return data;
294
+ };
295
+ hooks[findOneHookName + 'Unsuspended'] = function useOneUnsuspended({ skip, index, key, } = {}) {
296
+ const storage = useStorage();
297
+ const liveQuery = useMemo(() => {
298
+ return skip ? null : storage[pluralName].findOne({ index, key });
299
+ }, [index, skip]);
300
+ const data = useLiveQuery(liveQuery, true);
301
+ const status = useLiveQueryStatus(liveQuery);
302
+ return { data, status };
303
+ };
304
+ const getAllHookName = `useAll${capitalize(pluralName)}`;
305
+ hooks[getAllHookName] = function useAll({ index, skip, key, } = {}) {
306
+ const storage = useStorage();
307
+ // assumptions: this query getter is fast and returns the same
308
+ // query identity for subsequent calls.
309
+ const liveQuery = useMemo(() => (skip ? null : storage[pluralName].findAll({ index, key })), [index, skip]);
310
+ const data = useLiveQuery(liveQuery);
311
+ return data || [];
312
+ };
313
+ hooks[getAllHookName + 'Unsuspended'] = function useAllUnsuspended({ index, skip, key, } = {}) {
314
+ const storage = useStorage();
315
+ // assumptions: this query getter is fast and returns the same
316
+ // query identity for subsequent calls.
317
+ const liveQuery = useMemo(() => (skip ? null : storage[pluralName].findAll({ index, key })), [index, skip]);
318
+ const data = useLiveQuery(liveQuery, true) || [];
319
+ const status = useLiveQueryStatus(liveQuery);
320
+ return { data, status };
321
+ };
322
+ const getAllPaginatedHookName = `useAll${capitalize(pluralName)}Paginated`;
323
+ hooks[getAllPaginatedHookName] = function useAllPaginated({ index, skip, pageSize = 10, key, suspend, } = {}) {
324
+ const storage = useStorage();
325
+ // assumptions: this query getter is fast and returns the same
326
+ // query identity for subsequent calls.
327
+ const liveQuery = useMemo(() => skip
328
+ ? null
329
+ : storage[pluralName].findPage({
330
+ index,
331
+ pageSize,
332
+ page: 0,
333
+ key: key || getAllPaginatedHookName,
334
+ }), [index, skip, pageSize]);
335
+ const data = useLiveQuery(liveQuery, suspend === false);
336
+ const status = useLiveQueryStatus(liveQuery);
337
+ const tools = useMemo(() => ({
338
+ next: () => liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.nextPage(),
339
+ previous: () => liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.previousPage(),
340
+ setPage: (page) => liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.setPage(page),
341
+ get hasPrevious() {
342
+ return liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.hasPreviousPage;
343
+ },
344
+ get hasNext() {
345
+ return liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.hasNextPage;
346
+ },
347
+ status,
348
+ }), [liveQuery, status]);
349
+ return [data, tools];
350
+ };
351
+ const getAllInfiniteHookName = `useAll${capitalize(pluralName)}Infinite`;
352
+ hooks[getAllInfiniteHookName] = function useAllInfinite({ index, skip, pageSize = 10, key, suspend, } = {}) {
353
+ const storage = useStorage();
354
+ // assumptions: this query getter is fast and returns the same
355
+ // query identity for subsequent calls.
356
+ const liveQuery = useMemo(() => skip
357
+ ? null
358
+ : storage[pluralName].findAllInfinite({
359
+ index,
360
+ pageSize,
361
+ key: key || getAllInfiniteHookName,
362
+ }), [index, skip, pageSize]);
363
+ const data = useLiveQuery(liveQuery, suspend === false);
364
+ const status = useLiveQueryStatus(liveQuery);
365
+ const tools = useMemo(() => ({
366
+ loadMore: () => liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.loadMore(),
367
+ get hasMore() {
368
+ return liveQuery === null || liveQuery === void 0 ? void 0 : liveQuery.hasMore;
369
+ },
370
+ status,
371
+ }), [liveQuery, status]);
372
+ return [data, tools];
373
+ };
374
+ }
375
+ hooks.withMutations = (mutations) => {
376
+ const augmentedHooks = Object.assign({}, hooks);
377
+ for (const [name, subHook] of Object.entries(mutations)) {
378
+ augmentedHooks[name] = (...args) => {
379
+ const client = hooks.useClient();
380
+ return subHook(client, ...args);
381
+ };
382
+ }
383
+ return augmentedHooks;
384
+ };
385
+ return hooks;
386
+ }
387
387
  //# sourceMappingURL=hooks.js.map