@korajs/react 0.4.0 → 0.5.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/index.cjs +243 -54
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +61 -13
- package/dist/index.d.ts +61 -13
- package/dist/index.js +247 -58
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -49,7 +49,9 @@ function KoraProvider({
|
|
|
49
49
|
const value = {
|
|
50
50
|
store: resolvedStore,
|
|
51
51
|
syncEngine: resolvedSync,
|
|
52
|
-
app: app ?? null
|
|
52
|
+
app: app ?? null,
|
|
53
|
+
events: app?.events ?? null,
|
|
54
|
+
subscribeSyncStatus: app?.sync?.subscribeStatus ?? null
|
|
53
55
|
};
|
|
54
56
|
return createElement(KoraContext.Provider, { value }, children);
|
|
55
57
|
}
|
|
@@ -149,6 +151,18 @@ var QueryStore = class {
|
|
|
149
151
|
};
|
|
150
152
|
|
|
151
153
|
// src/hooks/use-query.ts
|
|
154
|
+
var APP_NOT_READY_CODE = "APP_NOT_READY";
|
|
155
|
+
function assertQueryReady(query) {
|
|
156
|
+
const descriptor = query.getDescriptor();
|
|
157
|
+
if (descriptor.collection === "__pending__") {
|
|
158
|
+
const err = new Error(
|
|
159
|
+
"Cannot use useQuery() before app.ready. Await app.ready or wrap your UI in <KoraProvider app={app}>."
|
|
160
|
+
);
|
|
161
|
+
err.name = "AppNotReadyError";
|
|
162
|
+
Object.assign(err, { code: APP_NOT_READY_CODE });
|
|
163
|
+
throw err;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
152
166
|
var EMPTY_ARRAY2 = Object.freeze([]);
|
|
153
167
|
var noopSubscribe = (_onStoreChange) => {
|
|
154
168
|
return () => {
|
|
@@ -156,6 +170,9 @@ var noopSubscribe = (_onStoreChange) => {
|
|
|
156
170
|
};
|
|
157
171
|
function useQuery(query, options) {
|
|
158
172
|
const enabled = options?.enabled !== false;
|
|
173
|
+
if (enabled) {
|
|
174
|
+
assertQueryReady(query);
|
|
175
|
+
}
|
|
159
176
|
const descriptorKey = JSON.stringify(query.getDescriptor());
|
|
160
177
|
const queryStoreRef = useRef(null);
|
|
161
178
|
const prevKeyRef = useRef(null);
|
|
@@ -188,7 +205,7 @@ function useQuery(query, options) {
|
|
|
188
205
|
|
|
189
206
|
// src/hooks/use-mutation.ts
|
|
190
207
|
import { useCallback, useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
|
|
191
|
-
function useMutation(mutationFn) {
|
|
208
|
+
function useMutation(mutationFn, options) {
|
|
192
209
|
const [state, setState] = useState2({
|
|
193
210
|
isLoading: false,
|
|
194
211
|
error: null
|
|
@@ -202,21 +219,35 @@ function useMutation(mutationFn) {
|
|
|
202
219
|
}, []);
|
|
203
220
|
const fnRef = useRef2(mutationFn);
|
|
204
221
|
fnRef.current = mutationFn;
|
|
222
|
+
const optionsRef = useRef2(options);
|
|
223
|
+
optionsRef.current = options;
|
|
205
224
|
const mutateAsync = useCallback(async (...args) => {
|
|
225
|
+
const opts = optionsRef.current;
|
|
226
|
+
let context;
|
|
206
227
|
if (mountedRef.current) {
|
|
207
228
|
setState({ isLoading: true, error: null });
|
|
208
229
|
}
|
|
209
230
|
try {
|
|
231
|
+
if (opts?.onMutate) {
|
|
232
|
+
context = await opts.onMutate(...args);
|
|
233
|
+
}
|
|
210
234
|
const result = await fnRef.current(...args);
|
|
211
235
|
if (mountedRef.current) {
|
|
212
236
|
setState({ isLoading: false, error: null });
|
|
213
237
|
}
|
|
238
|
+
opts?.onSuccess?.(result, ...args);
|
|
239
|
+
opts?.onSettled?.(result, null, ...args);
|
|
214
240
|
return result;
|
|
215
241
|
} catch (err) {
|
|
216
242
|
const error = err instanceof Error ? err : new Error(String(err));
|
|
243
|
+
if (context !== void 0 && opts?.onRollback) {
|
|
244
|
+
await opts.onRollback(context, ...args);
|
|
245
|
+
}
|
|
217
246
|
if (mountedRef.current) {
|
|
218
247
|
setState({ isLoading: false, error });
|
|
219
248
|
}
|
|
249
|
+
opts?.onError?.(error, ...args);
|
|
250
|
+
opts?.onSettled?.(void 0, error, ...args);
|
|
220
251
|
throw error;
|
|
221
252
|
}
|
|
222
253
|
}, []);
|
|
@@ -242,8 +273,7 @@ function useMutation(mutationFn) {
|
|
|
242
273
|
}
|
|
243
274
|
|
|
244
275
|
// src/hooks/use-sync-status.ts
|
|
245
|
-
import { useCallback as useCallback2,
|
|
246
|
-
var POLL_INTERVAL_MS = 500;
|
|
276
|
+
import { useCallback as useCallback2, useRef as useRef3, useSyncExternalStore as useSyncExternalStore2 } from "react";
|
|
247
277
|
var OFFLINE_STATUS = Object.freeze({
|
|
248
278
|
status: "offline",
|
|
249
279
|
pendingOperations: 0,
|
|
@@ -252,15 +282,36 @@ var OFFLINE_STATUS = Object.freeze({
|
|
|
252
282
|
lastSuccessfulPull: null,
|
|
253
283
|
conflicts: 0
|
|
254
284
|
});
|
|
285
|
+
var SYNC_STATUS_EVENT_TYPES = [
|
|
286
|
+
"sync:connected",
|
|
287
|
+
"sync:disconnected",
|
|
288
|
+
"sync:schema-mismatch",
|
|
289
|
+
"sync:auth-failed",
|
|
290
|
+
"sync:sent",
|
|
291
|
+
"sync:received",
|
|
292
|
+
"sync:acknowledged",
|
|
293
|
+
"sync:apply-failed",
|
|
294
|
+
"sync:diagnostics",
|
|
295
|
+
"sync:initial-sync-progress"
|
|
296
|
+
];
|
|
255
297
|
function useSyncStatus() {
|
|
256
|
-
const { syncEngine } = useKoraContext();
|
|
298
|
+
const { syncEngine, subscribeSyncStatus, events } = useKoraContext();
|
|
257
299
|
const snapshotRef = useRef3(OFFLINE_STATUS);
|
|
258
300
|
const serializedRef = useRef3(JSON.stringify(OFFLINE_STATUS));
|
|
259
301
|
const subscribe = useCallback2(
|
|
260
302
|
(onStoreChange) => {
|
|
261
|
-
if (
|
|
262
|
-
|
|
263
|
-
|
|
303
|
+
if (subscribeSyncStatus) {
|
|
304
|
+
return subscribeSyncStatus((status) => {
|
|
305
|
+
snapshotRef.current = status;
|
|
306
|
+
serializedRef.current = JSON.stringify(status);
|
|
307
|
+
onStoreChange();
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
if (!syncEngine) {
|
|
311
|
+
return () => {
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
const refresh = () => {
|
|
264
315
|
const newStatus = syncEngine.getStatus();
|
|
265
316
|
const newSerialized = JSON.stringify(newStatus);
|
|
266
317
|
if (newSerialized !== serializedRef.current) {
|
|
@@ -268,29 +319,28 @@ function useSyncStatus() {
|
|
|
268
319
|
serializedRef.current = newSerialized;
|
|
269
320
|
onStoreChange();
|
|
270
321
|
}
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
322
|
+
};
|
|
323
|
+
if (events) {
|
|
324
|
+
const unsubs = SYNC_STATUS_EVENT_TYPES.map((type) => events.on(type, refresh));
|
|
325
|
+
refresh();
|
|
326
|
+
return () => {
|
|
327
|
+
for (const unsub of unsubs) {
|
|
328
|
+
unsub();
|
|
329
|
+
}
|
|
330
|
+
};
|
|
278
331
|
}
|
|
332
|
+
refresh();
|
|
279
333
|
return () => {
|
|
280
|
-
clearInterval(intervalId);
|
|
281
334
|
};
|
|
282
335
|
},
|
|
283
|
-
[syncEngine]
|
|
336
|
+
[syncEngine, subscribeSyncStatus, events]
|
|
284
337
|
);
|
|
285
338
|
const getSnapshot = useCallback2(() => {
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
useEffect3(() => {
|
|
289
|
-
if (!syncEngine) {
|
|
290
|
-
snapshotRef.current = OFFLINE_STATUS;
|
|
291
|
-
serializedRef.current = JSON.stringify(OFFLINE_STATUS);
|
|
339
|
+
if (subscribeSyncStatus) {
|
|
340
|
+
return snapshotRef.current;
|
|
292
341
|
}
|
|
293
|
-
|
|
342
|
+
return syncEngine ? syncEngine.getStatus() : OFFLINE_STATUS;
|
|
343
|
+
}, [syncEngine, subscribeSyncStatus]);
|
|
294
344
|
return useSyncExternalStore2(subscribe, getSnapshot);
|
|
295
345
|
}
|
|
296
346
|
|
|
@@ -304,12 +354,16 @@ function useCollection(name) {
|
|
|
304
354
|
}
|
|
305
355
|
|
|
306
356
|
// src/hooks/use-rich-text.ts
|
|
307
|
-
import {
|
|
357
|
+
import { encodeRichtext } from "@korajs/store";
|
|
358
|
+
import { useCallback as useCallback3, useEffect as useEffect3, useMemo as useMemo3, useRef as useRef4, useState as useState3 } from "react";
|
|
308
359
|
import * as Y from "yjs";
|
|
309
360
|
var LOAD_ORIGIN = "kora-load";
|
|
361
|
+
var REMOTE_ORIGIN = "kora-remote";
|
|
362
|
+
var DOC_CHANNEL_ORIGIN = "kora-doc-channel";
|
|
310
363
|
var TEXT_KEY = "content";
|
|
311
364
|
var COMPACT_AFTER_DELTAS = 20;
|
|
312
|
-
|
|
365
|
+
var PERSIST_DEBOUNCE_MS = 400;
|
|
366
|
+
function useRichText(collectionName, recordId, fieldName, options) {
|
|
313
367
|
const { store, syncEngine } = useKoraContext();
|
|
314
368
|
const collection = useMemo3(
|
|
315
369
|
() => store.collection(collectionName),
|
|
@@ -323,6 +377,12 @@ function useRichText(collectionName, recordId, fieldName) {
|
|
|
323
377
|
const [cursors, setCursors] = useState3([]);
|
|
324
378
|
const baseUpdateRef = useRef4(null);
|
|
325
379
|
const pendingDeltasRef = useRef4([]);
|
|
380
|
+
const docChannelActiveRef = useRef4(false);
|
|
381
|
+
const persistTimerRef = useRef4(null);
|
|
382
|
+
const userRef = useRef4(options?.user);
|
|
383
|
+
useEffect3(() => {
|
|
384
|
+
userRef.current = options?.user;
|
|
385
|
+
}, [options?.user]);
|
|
326
386
|
const text = useMemo3(() => doc.getText(TEXT_KEY), [doc]);
|
|
327
387
|
const undoManager = useMemo3(() => new Y.UndoManager(text), [text]);
|
|
328
388
|
const syncHistoryState = useCallback3(() => {
|
|
@@ -337,7 +397,73 @@ function useRichText(collectionName, recordId, fieldName) {
|
|
|
337
397
|
undoManager.redo();
|
|
338
398
|
syncHistoryState();
|
|
339
399
|
}, [syncHistoryState, undoManager]);
|
|
340
|
-
|
|
400
|
+
const resolveAwarenessUser = useCallback3(() => {
|
|
401
|
+
if (userRef.current) {
|
|
402
|
+
return userRef.current;
|
|
403
|
+
}
|
|
404
|
+
if (syncEngine) {
|
|
405
|
+
const existing = syncEngine.getAwarenessManager().getLocalState()?.user;
|
|
406
|
+
if (existing) {
|
|
407
|
+
return existing;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return {
|
|
411
|
+
name: "Anonymous",
|
|
412
|
+
color: "#6366f1"
|
|
413
|
+
};
|
|
414
|
+
}, [syncEngine]);
|
|
415
|
+
const setCursor = useCallback3(
|
|
416
|
+
(anchor, head) => {
|
|
417
|
+
if (!syncEngine) {
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
const awareness = syncEngine.getAwarenessManager();
|
|
421
|
+
const state = {
|
|
422
|
+
user: resolveAwarenessUser(),
|
|
423
|
+
cursor: {
|
|
424
|
+
collection: collectionName,
|
|
425
|
+
recordId,
|
|
426
|
+
field: fieldName,
|
|
427
|
+
anchor,
|
|
428
|
+
head
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
awareness.setLocalState(state);
|
|
432
|
+
},
|
|
433
|
+
[collectionName, fieldName, recordId, resolveAwarenessUser, syncEngine]
|
|
434
|
+
);
|
|
435
|
+
const clearCursor = useCallback3(() => {
|
|
436
|
+
if (!syncEngine) {
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
const awareness = syncEngine.getAwarenessManager();
|
|
440
|
+
const current = awareness.getLocalState();
|
|
441
|
+
if (!current?.cursor) {
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
if (current.cursor.collection !== collectionName || current.cursor.recordId !== recordId || current.cursor.field !== fieldName) {
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
awareness.setLocalState({ user: current.user });
|
|
448
|
+
}, [collectionName, fieldName, recordId, syncEngine]);
|
|
449
|
+
const applyRemoteSnapshot = useCallback3(
|
|
450
|
+
(value) => {
|
|
451
|
+
const encoded = encodeRichtextInput(value);
|
|
452
|
+
if (!encoded) {
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
const currentSnapshot = Y.encodeStateAsUpdate(doc);
|
|
456
|
+
if (updatesEqual(currentSnapshot, encoded)) {
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
Y.applyUpdate(doc, encoded, REMOTE_ORIGIN);
|
|
460
|
+
baseUpdateRef.current = encoded;
|
|
461
|
+
pendingDeltasRef.current = [];
|
|
462
|
+
syncHistoryState();
|
|
463
|
+
},
|
|
464
|
+
[doc, syncHistoryState]
|
|
465
|
+
);
|
|
466
|
+
useEffect3(() => {
|
|
341
467
|
let disposed = false;
|
|
342
468
|
const initialize = async () => {
|
|
343
469
|
setReady(false);
|
|
@@ -355,18 +481,15 @@ function useRichText(collectionName, recordId, fieldName) {
|
|
|
355
481
|
if (encoded) {
|
|
356
482
|
Y.applyUpdate(doc, encoded, LOAD_ORIGIN);
|
|
357
483
|
}
|
|
484
|
+
const channel = syncEngine?.getRichtextDocChannel?.();
|
|
485
|
+
docChannelActiveRef.current = channel?.shouldUseChannel(encoded?.length ?? 0, options?.useDocChannel) ?? false;
|
|
358
486
|
setReady(true);
|
|
359
487
|
} catch (cause) {
|
|
360
488
|
if (disposed) return;
|
|
361
489
|
setError(cause instanceof Error ? cause : new Error(String(cause)));
|
|
362
490
|
}
|
|
363
491
|
};
|
|
364
|
-
const
|
|
365
|
-
syncHistoryState();
|
|
366
|
-
if (origin === LOAD_ORIGIN) {
|
|
367
|
-
return;
|
|
368
|
-
}
|
|
369
|
-
pendingDeltasRef.current.push(_update);
|
|
492
|
+
const flushPersist = async () => {
|
|
370
493
|
const snapshot = composeRichtextSnapshot(baseUpdateRef.current, pendingDeltasRef.current);
|
|
371
494
|
if (pendingDeltasRef.current.length >= COMPACT_AFTER_DELTAS) {
|
|
372
495
|
baseUpdateRef.current = snapshot;
|
|
@@ -382,18 +505,78 @@ function useRichText(collectionName, recordId, fieldName) {
|
|
|
382
505
|
}
|
|
383
506
|
}
|
|
384
507
|
};
|
|
508
|
+
const schedulePersist = () => {
|
|
509
|
+
if (persistTimerRef.current) {
|
|
510
|
+
clearTimeout(persistTimerRef.current);
|
|
511
|
+
}
|
|
512
|
+
persistTimerRef.current = setTimeout(() => {
|
|
513
|
+
persistTimerRef.current = null;
|
|
514
|
+
void flushPersist();
|
|
515
|
+
}, PERSIST_DEBOUNCE_MS);
|
|
516
|
+
};
|
|
517
|
+
const persist = (_update, origin) => {
|
|
518
|
+
syncHistoryState();
|
|
519
|
+
if (origin === LOAD_ORIGIN || origin === REMOTE_ORIGIN || origin === DOC_CHANNEL_ORIGIN) {
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
pendingDeltasRef.current.push(_update);
|
|
523
|
+
if (docChannelActiveRef.current && syncEngine) {
|
|
524
|
+
syncEngine.getRichtextDocChannel().send(collectionName, recordId, fieldName, _update);
|
|
525
|
+
schedulePersist();
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
void flushPersist();
|
|
529
|
+
};
|
|
385
530
|
doc.on("update", persist);
|
|
386
531
|
void initialize();
|
|
387
532
|
syncHistoryState();
|
|
388
533
|
return () => {
|
|
389
534
|
disposed = true;
|
|
535
|
+
if (persistTimerRef.current) {
|
|
536
|
+
clearTimeout(persistTimerRef.current);
|
|
537
|
+
persistTimerRef.current = null;
|
|
538
|
+
}
|
|
390
539
|
doc.off("update", persist);
|
|
391
540
|
undoManager.destroy();
|
|
392
541
|
baseUpdateRef.current = null;
|
|
393
542
|
pendingDeltasRef.current = [];
|
|
543
|
+
docChannelActiveRef.current = false;
|
|
394
544
|
};
|
|
395
|
-
}, [
|
|
396
|
-
|
|
545
|
+
}, [
|
|
546
|
+
collection,
|
|
547
|
+
collectionName,
|
|
548
|
+
doc,
|
|
549
|
+
fieldName,
|
|
550
|
+
options?.useDocChannel,
|
|
551
|
+
recordId,
|
|
552
|
+
syncEngine,
|
|
553
|
+
syncHistoryState,
|
|
554
|
+
undoManager
|
|
555
|
+
]);
|
|
556
|
+
useEffect3(() => {
|
|
557
|
+
if (!ready || !syncEngine || !docChannelActiveRef.current) {
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
const channel = syncEngine.getRichtextDocChannel();
|
|
561
|
+
return channel.subscribe(collectionName, recordId, fieldName, (update) => {
|
|
562
|
+
Y.applyUpdate(doc, update, DOC_CHANNEL_ORIGIN);
|
|
563
|
+
syncHistoryState();
|
|
564
|
+
});
|
|
565
|
+
}, [collectionName, doc, fieldName, ready, recordId, syncEngine, syncHistoryState]);
|
|
566
|
+
useEffect3(() => {
|
|
567
|
+
if (!ready) {
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
const unsubscribe = store.collection(collectionName).where({ id: recordId }).subscribe((results) => {
|
|
571
|
+
const record = results[0];
|
|
572
|
+
if (!record) {
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
applyRemoteSnapshot(record[fieldName]);
|
|
576
|
+
});
|
|
577
|
+
return unsubscribe;
|
|
578
|
+
}, [applyRemoteSnapshot, collectionName, fieldName, ready, recordId, store]);
|
|
579
|
+
useEffect3(() => {
|
|
397
580
|
if (!syncEngine) return;
|
|
398
581
|
const awareness = syncEngine.getAwarenessManager();
|
|
399
582
|
const localClientId = awareness.clientId;
|
|
@@ -420,42 +603,48 @@ function useRichText(collectionName, recordId, fieldName) {
|
|
|
420
603
|
updateCursors();
|
|
421
604
|
});
|
|
422
605
|
updateCursors();
|
|
423
|
-
return
|
|
424
|
-
|
|
425
|
-
|
|
606
|
+
return () => {
|
|
607
|
+
unsubscribe();
|
|
608
|
+
clearCursor();
|
|
609
|
+
};
|
|
610
|
+
}, [clearCursor, collectionName, fieldName, recordId, syncEngine]);
|
|
611
|
+
return { doc, text, undo, redo, canUndo, canRedo, ready, error, cursors, setCursor, clearCursor };
|
|
426
612
|
}
|
|
427
613
|
function encodeRichtextInput(value) {
|
|
428
614
|
if (value === null || value === void 0) {
|
|
429
615
|
return null;
|
|
430
616
|
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
}
|
|
439
|
-
if (value instanceof ArrayBuffer) {
|
|
440
|
-
return new Uint8Array(value);
|
|
441
|
-
}
|
|
442
|
-
if (typeof globalThis !== "undefined" && "Buffer" in globalThis) {
|
|
443
|
-
const BufferCtor = globalThis.Buffer;
|
|
444
|
-
if (BufferCtor.isBuffer(value)) {
|
|
445
|
-
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
617
|
+
try {
|
|
618
|
+
return encodeRichtext(value);
|
|
619
|
+
} catch {
|
|
620
|
+
if (typeof value === "string") {
|
|
621
|
+
const fallbackDoc = new Y.Doc();
|
|
622
|
+
fallbackDoc.getText(TEXT_KEY).insert(0, value);
|
|
623
|
+
return Y.encodeStateAsUpdate(fallbackDoc);
|
|
446
624
|
}
|
|
625
|
+
throw new Error("Richtext record value must be a string, Uint8Array, ArrayBuffer, or null.");
|
|
447
626
|
}
|
|
448
|
-
throw new Error("Richtext record value must be a string, Uint8Array, ArrayBuffer, or null.");
|
|
449
627
|
}
|
|
450
628
|
function composeRichtextSnapshot(base, deltas) {
|
|
451
|
-
const
|
|
629
|
+
const mergedDoc = new Y.Doc();
|
|
452
630
|
if (base) {
|
|
453
|
-
Y.applyUpdate(
|
|
631
|
+
Y.applyUpdate(mergedDoc, base);
|
|
454
632
|
}
|
|
455
633
|
for (const delta of deltas) {
|
|
456
|
-
Y.applyUpdate(
|
|
634
|
+
Y.applyUpdate(mergedDoc, delta);
|
|
635
|
+
}
|
|
636
|
+
return Y.encodeStateAsUpdate(mergedDoc);
|
|
637
|
+
}
|
|
638
|
+
function updatesEqual(left, right) {
|
|
639
|
+
if (left.length !== right.length) {
|
|
640
|
+
return false;
|
|
641
|
+
}
|
|
642
|
+
for (let index = 0; index < left.length; index++) {
|
|
643
|
+
if (left[index] !== right[index]) {
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
457
646
|
}
|
|
458
|
-
return
|
|
647
|
+
return true;
|
|
459
648
|
}
|
|
460
649
|
export {
|
|
461
650
|
KoraProvider,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context/kora-context.ts","../src/hooks/use-app.ts","../src/hooks/use-query.ts","../src/query-store/query-store.ts","../src/hooks/use-mutation.ts","../src/hooks/use-sync-status.ts","../src/hooks/use-collection.ts","../src/hooks/use-rich-text.ts"],"sourcesContent":["import type { Store } from '@korajs/store'\nimport type { SyncEngine } from '@korajs/sync'\nimport { createContext, createElement, useContext, useEffect, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { KoraContextValue, KoraProviderProps } from '../types'\n\nconst KoraContext = createContext<KoraContextValue | null>(null)\n\n/**\n * Provides Kora store and optional sync engine to all child components.\n * Must wrap any component that uses Kora hooks (useQuery, useMutation, etc.).\n *\n * Accepts either an `app` prop (recommended) or explicit `store` + `syncEngine` props.\n *\n * When using the `app` prop, KoraProvider waits for `app.ready` before rendering\n * children. A `fallback` prop can be provided to show content while initializing.\n *\n * @example\n * ```typescript\n * // Recommended: pass the app object directly\n * const app = createApp({ schema })\n * <KoraProvider app={app}><App /></KoraProvider>\n *\n * // Advanced: pass store and syncEngine explicitly\n * <KoraProvider store={store} syncEngine={syncEngine}><App /></KoraProvider>\n * ```\n */\nfunction KoraProvider({\n\tapp,\n\tstore,\n\tsyncEngine,\n\tfallback,\n\tchildren,\n}: KoraProviderProps): ReactNode {\n\tconst [resolvedStore, setResolvedStore] = useState<Store | null>(store ?? null)\n\tconst [resolvedSync, setResolvedSync] = useState<SyncEngine | null>(syncEngine ?? null)\n\t// If no app prop, we're using the store prop and are ready immediately\n\tconst [ready, setReady] = useState(!app)\n\tconst [initError, setInitError] = useState<Error | null>(null)\n\n\tuseEffect(() => {\n\t\tif (!app) return\n\t\tlet cancelled = false\n\t\tapp.ready\n\t\t\t.then(() => {\n\t\t\t\tif (cancelled) return\n\t\t\t\tsetResolvedStore(app.getStore())\n\t\t\t\tsetResolvedSync(app.getSyncEngine())\n\t\t\t\tsetReady(true)\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tif (cancelled) return\n\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error))\n\t\t\t\tconsole.error('[Kora] Initialization failed:', err)\n\t\t\t\tsetInitError(err)\n\t\t\t})\n\t\treturn () => {\n\t\t\tcancelled = true\n\t\t}\n\t}, [app])\n\n\tif (initError) {\n\t\treturn createElement(\n\t\t\t'div',\n\t\t\t{ style: { color: 'red', padding: '1rem', fontFamily: 'monospace' } },\n\t\t\tcreateElement('strong', null, 'Kora initialization error: '),\n\t\t\tinitError.message,\n\t\t)\n\t}\n\n\tif (!ready) {\n\t\treturn (fallback ?? null) as ReactNode\n\t}\n\n\tif (!resolvedStore) {\n\t\tthrow new Error(\n\t\t\t'KoraProvider requires either an \"app\" or \"store\" prop. ' +\n\t\t\t\t'Pass a KoraApp from createApp() or a Store instance.',\n\t\t)\n\t}\n\n\tconst value: KoraContextValue = {\n\t\tstore: resolvedStore,\n\t\tsyncEngine: resolvedSync,\n\t\tapp: app ?? null,\n\t}\n\treturn createElement(KoraContext.Provider, { value }, children)\n}\n\n/**\n * Internal hook to access the Kora context.\n * Throws if used outside of a KoraProvider.\n */\nfunction useKoraContext(): KoraContextValue {\n\tconst context = useContext(KoraContext)\n\tif (context === null) {\n\t\tthrow new Error(\n\t\t\t'useKoraContext must be used within a <KoraProvider>. ' +\n\t\t\t\t'Wrap your component tree with <KoraProvider store={store}>.',\n\t\t)\n\t}\n\treturn context\n}\n\nexport { KoraProvider, useKoraContext }\n","import { useKoraContext } from '../context/kora-context'\nimport type { KoraAppLike } from '../types'\n\n/**\n * React hook that returns the Kora app instance from context.\n *\n * Use the generic parameter to cast to your typed app for full type inference:\n *\n * ```typescript\n * // In your app setup:\n * export const app = createApp({ schema: mySchema })\n * export type App = typeof app\n *\n * // In components:\n * const app = useApp<App>()\n * app.todos.insert({ title: 'Hello' }) // fully typed\n * const todos = useQuery(app.todos.where({ completed: false }))\n * ```\n *\n * Requires `KoraProvider` to be initialized with the `app` prop.\n * Throws if used outside of `KoraProvider` or without an `app` prop.\n *\n * @returns The KoraApp instance, typed as `T`\n */\nexport function useApp<T extends KoraAppLike = KoraAppLike>(): T {\n\tconst { app } = useKoraContext()\n\tif (!app) {\n\t\tthrow new Error(\n\t\t\t'useApp() requires KoraProvider to be initialized with an \"app\" prop. ' +\n\t\t\t\t'Pass your createApp() result to <KoraProvider app={app}>.',\n\t\t)\n\t}\n\treturn app as T\n}\n","import type { CollectionRecord, QueryBuilder } from '@korajs/store'\nimport { useMemo, useRef, useSyncExternalStore } from 'react'\nimport { QueryStore } from '../query-store/query-store'\nimport type { UseQueryOptions } from '../types'\n\n/**\n * Frozen empty array returned when the query is disabled or before data loads.\n * Same reference prevents unnecessary re-renders.\n */\nconst EMPTY_ARRAY: readonly unknown[] = Object.freeze([])\n\nconst noopSubscribe = (_onStoreChange: () => void): (() => void) => {\n\treturn () => {}\n}\n\n/**\n * React hook for reactive queries against the local Kora store.\n *\n * Returns data synchronously from the local store — no loading spinners needed.\n * Re-renders automatically when the query results change due to mutations.\n * Uses `useSyncExternalStore` for React 18+ concurrent mode safety.\n *\n * The generic parameter `T` is inferred from the QueryBuilder, providing\n * full type safety when used with typed collection accessors.\n *\n * @param query - A QueryBuilder instance (e.g., `app.todos.where({ done: false })`)\n * @param options - Optional configuration (e.g., `{ enabled: false }` to skip the query)\n * @returns Readonly array of matching records\n *\n * @example\n * ```typescript\n * const todos = useQuery(app.todos.where({ completed: false }).orderBy('createdAt'))\n * // todos is typed as readonly InferRecord<typeof todoFields>[]\n * ```\n */\nexport function useQuery<T = CollectionRecord>(\n\tquery: QueryBuilder<T>,\n\toptions?: UseQueryOptions,\n): readonly T[] {\n\tconst enabled = options?.enabled !== false\n\n\t// Compute a stable key from the query descriptor\n\tconst descriptorKey = JSON.stringify(query.getDescriptor())\n\n\t// Track the current QueryStore instance\n\tconst queryStoreRef = useRef<QueryStore<T> | null>(null)\n\tconst prevKeyRef = useRef<string | null>(null)\n\n\t// Create or reuse a QueryStore when the descriptor changes\n\tconst queryStore = useMemo(() => {\n\t\tif (!enabled) {\n\t\t\t// Destroy previous if it exists\n\t\t\tif (queryStoreRef.current) {\n\t\t\t\tqueryStoreRef.current.destroy()\n\t\t\t\tqueryStoreRef.current = null\n\t\t\t}\n\t\t\tprevKeyRef.current = null\n\t\t\treturn null\n\t\t}\n\n\t\t// If descriptor changed, destroy previous and create new\n\t\tif (prevKeyRef.current !== descriptorKey) {\n\t\t\tif (queryStoreRef.current) {\n\t\t\t\tqueryStoreRef.current.destroy()\n\t\t\t}\n\t\t\tconst newStore = new QueryStore<T>(query)\n\t\t\tqueryStoreRef.current = newStore\n\t\t\tprevKeyRef.current = descriptorKey\n\t\t\treturn newStore\n\t\t}\n\n\t\treturn queryStoreRef.current\n\t}, [descriptorKey, enabled, query])\n\n\t// No useEffect cleanup needed: QueryStore's subscribe/unsubscribe cycle\n\t// manages the underlying subscription lifetime. When the last listener\n\t// detaches (on unmount), the subscription auto-stops. This also makes\n\t// the hook resilient to React StrictMode's double-mount cycle.\n\n\tconst disabledGetSnapshot = (): readonly T[] => EMPTY_ARRAY as readonly T[]\n\n\treturn useSyncExternalStore(\n\t\tqueryStore ? queryStore.subscribe : noopSubscribe,\n\t\tqueryStore ? queryStore.getSnapshot : disabledGetSnapshot,\n\t)\n}\n","import type { CollectionRecord, QueryBuilder } from '@korajs/store'\n\n/**\n * Frozen empty array returned as the initial snapshot before any data loads.\n * Same reference every time prevents infinite re-render loops with useSyncExternalStore.\n */\nconst EMPTY_ARRAY: readonly unknown[] = Object.freeze([])\n\n/**\n * Bridges the async QueryBuilder.subscribe() API with the synchronous\n * getSnapshot() required by React's useSyncExternalStore.\n *\n * Uses a lazy subscription model: the underlying query subscription starts\n * when the first listener attaches (via useSyncExternalStore's subscribe)\n * and stops when the last listener detaches. This makes QueryStore resilient\n * to React StrictMode's double-mount cycle, where useEffect cleanup fires\n * between mount and remount.\n *\n * Generic parameter `T` defaults to `CollectionRecord` for backward compatibility.\n */\nexport class QueryStore<T = CollectionRecord> {\n\tprivate snapshot: readonly T[] = EMPTY_ARRAY as readonly T[]\n\tprivate listeners = new Set<() => void>()\n\tprivate unsubscribeQuery: (() => void) | null = null\n\tprivate active = false\n\tprivate readonly queryBuilder: QueryBuilder<T>\n\n\tconstructor(queryBuilder: QueryBuilder<T>) {\n\t\tthis.queryBuilder = queryBuilder\n\t}\n\n\t/**\n\t * Subscribe to snapshot changes. Compatible with useSyncExternalStore.\n\t *\n\t * Lazily starts the underlying query subscription when the first listener\n\t * attaches, and stops it when the last listener detaches. This allows\n\t * React StrictMode to unmount/remount without permanently killing the subscription.\n\t *\n\t * @returns Unsubscribe function\n\t */\n\tsubscribe = (onStoreChange: () => void): (() => void) => {\n\t\tthis.listeners.add(onStoreChange)\n\n\t\t// Start the underlying query subscription when the first listener attaches\n\t\tif (!this.active) {\n\t\t\tthis.startSubscription()\n\t\t}\n\n\t\treturn () => {\n\t\t\tthis.listeners.delete(onStoreChange)\n\t\t\t// Stop the underlying subscription when the last listener detaches.\n\t\t\t// This ensures cleanup on unmount without needing a useEffect.\n\t\t\tif (this.listeners.size === 0) {\n\t\t\t\tthis.stopSubscription()\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get the current snapshot synchronously. Compatible with useSyncExternalStore.\n\t * Returns EMPTY_ARRAY before the first async fetch completes.\n\t */\n\tgetSnapshot = (): readonly T[] => {\n\t\treturn this.snapshot\n\t}\n\n\t/**\n\t * Clean up the underlying subscription and release resources.\n\t * Called by useMemo when the query descriptor changes.\n\t */\n\tdestroy(): void {\n\t\tthis.stopSubscription()\n\t\tthis.listeners.clear()\n\t\tthis.snapshot = EMPTY_ARRAY as readonly T[]\n\t}\n\n\tprivate startSubscription(): void {\n\t\tthis.active = true\n\t\tthis.unsubscribeQuery = this.queryBuilder.subscribe((results) => {\n\t\t\tif (!this.active) return\n\t\t\tconst newSnapshot = Object.freeze([...results])\n\t\t\tthis.snapshot = newSnapshot\n\t\t\tthis.notifyListeners()\n\t\t})\n\t}\n\n\tprivate stopSubscription(): void {\n\t\tthis.active = false\n\t\tif (this.unsubscribeQuery) {\n\t\t\tthis.unsubscribeQuery()\n\t\t\tthis.unsubscribeQuery = null\n\t\t}\n\t}\n\n\tprivate notifyListeners(): void {\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener()\n\t\t}\n\t}\n}\n","import { useCallback, useEffect, useRef, useState } from 'react'\nimport type { UseMutationResult } from '../types'\n\n/**\n * React hook for performing mutations against the local Kora store.\n *\n * Returns `mutate` for fire-and-forget usage (optimistic) and `mutateAsync`\n * for when you need to await the result. Tracks loading and error state.\n *\n * @param mutationFn - An async function to execute (e.g., `app.todos.insert`)\n * @returns Object with mutate, mutateAsync, isLoading, error, and reset\n *\n * @example\n * ```typescript\n * const { mutate } = useMutation(app.todos.insert)\n * mutate({ title: 'New todo' }) // fire-and-forget\n * ```\n */\nexport function useMutation<TData, TArgs extends unknown[]>(\n\tmutationFn: (...args: TArgs) => Promise<TData>,\n): UseMutationResult<TData, TArgs> {\n\tconst [state, setState] = useState<{ isLoading: boolean; error: Error | null }>({\n\t\tisLoading: false,\n\t\terror: null,\n\t})\n\n\t// Track mounted state to avoid state updates after unmount\n\tconst mountedRef = useRef(true)\n\tuseEffect(() => {\n\t\tmountedRef.current = true\n\t\treturn () => {\n\t\t\tmountedRef.current = false\n\t\t}\n\t}, [])\n\n\t// Keep latest mutation function in a ref to avoid stale closures\n\tconst fnRef = useRef(mutationFn)\n\tfnRef.current = mutationFn\n\n\tconst mutateAsync = useCallback(async (...args: TArgs): Promise<TData> => {\n\t\tif (mountedRef.current) {\n\t\t\tsetState({ isLoading: true, error: null })\n\t\t}\n\t\ttry {\n\t\t\tconst result = await fnRef.current(...args)\n\t\t\tif (mountedRef.current) {\n\t\t\t\tsetState({ isLoading: false, error: null })\n\t\t\t}\n\t\t\treturn result\n\t\t} catch (err) {\n\t\t\tconst error = err instanceof Error ? err : new Error(String(err))\n\t\t\tif (mountedRef.current) {\n\t\t\t\tsetState({ isLoading: false, error })\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t}, [])\n\n\tconst mutate = useCallback(\n\t\t(...args: TArgs): void => {\n\t\t\tmutateAsync(...args).catch(() => {\n\t\t\t\t// Fire-and-forget: error is captured in state, no unhandled rejection\n\t\t\t})\n\t\t},\n\t\t[mutateAsync],\n\t)\n\n\tconst reset = useCallback((): void => {\n\t\tif (mountedRef.current) {\n\t\t\tsetState({ isLoading: false, error: null })\n\t\t}\n\t}, [])\n\n\treturn {\n\t\tmutate,\n\t\tmutateAsync,\n\t\tisLoading: state.isLoading,\n\t\terror: state.error,\n\t\treset,\n\t}\n}\n","import type { SyncStatusInfo } from '@korajs/sync'\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'\nimport { useKoraContext } from '../context/kora-context'\n\nconst POLL_INTERVAL_MS = 500\n\n/** Default status returned when no sync engine is configured */\nconst OFFLINE_STATUS: SyncStatusInfo = Object.freeze({\n\tstatus: 'offline',\n\tpendingOperations: 0,\n\tlastSyncedAt: null,\n\tlastSuccessfulPush: null,\n\tlastSuccessfulPull: null,\n\tconflicts: 0,\n})\n\n/**\n * React hook for monitoring the sync engine's connection status.\n *\n * Polls the SyncEngine at ~500ms intervals and re-renders only when\n * the status actually changes. Returns a default offline status when\n * no sync engine is configured.\n *\n * @returns Current sync status information\n *\n * @example\n * ```typescript\n * const status = useSyncStatus()\n * // status.status: 'connected' | 'syncing' | 'synced' | 'offline' | 'error'\n * // status.pendingOperations: number\n * // status.lastSyncedAt: number | null\n * ```\n */\nexport function useSyncStatus(): SyncStatusInfo {\n\tconst { syncEngine } = useKoraContext()\n\n\t// Cache the latest status snapshot for stable references\n\tconst snapshotRef = useRef<SyncStatusInfo>(OFFLINE_STATUS)\n\tconst serializedRef = useRef<string>(JSON.stringify(OFFLINE_STATUS))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\tif (!syncEngine) return () => {}\n\n\t\t\t// Poll the sync engine status at regular intervals\n\t\t\tconst intervalId = setInterval(() => {\n\t\t\t\tconst newStatus = syncEngine.getStatus()\n\t\t\t\tconst newSerialized = JSON.stringify(newStatus)\n\n\t\t\t\t// Only notify React if status actually changed\n\t\t\t\tif (newSerialized !== serializedRef.current) {\n\t\t\t\t\tsnapshotRef.current = newStatus\n\t\t\t\t\tserializedRef.current = newSerialized\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t}, POLL_INTERVAL_MS)\n\n\t\t\t// Do an immediate check\n\t\t\tconst initialStatus = syncEngine.getStatus()\n\t\t\tconst initialSerialized = JSON.stringify(initialStatus)\n\t\t\tif (initialSerialized !== serializedRef.current) {\n\t\t\t\tsnapshotRef.current = initialStatus\n\t\t\t\tserializedRef.current = initialSerialized\n\t\t\t\tonStoreChange()\n\t\t\t}\n\n\t\t\treturn () => {\n\t\t\t\tclearInterval(intervalId)\n\t\t\t}\n\t\t},\n\t\t[syncEngine],\n\t)\n\n\tconst getSnapshot = useCallback((): SyncStatusInfo => {\n\t\treturn snapshotRef.current\n\t}, [])\n\n\t// Reset snapshot when syncEngine changes\n\tuseEffect(() => {\n\t\tif (!syncEngine) {\n\t\t\tsnapshotRef.current = OFFLINE_STATUS\n\t\t\tserializedRef.current = JSON.stringify(OFFLINE_STATUS)\n\t\t}\n\t}, [syncEngine])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n","import type { CollectionAccessor } from '@korajs/store'\nimport { useMemo } from 'react'\nimport { useKoraContext } from '../context/kora-context'\n\n/**\n * React hook that returns a CollectionAccessor for the given collection name.\n * Convenience hook for accessing a collection without going through the store directly.\n *\n * @param name - The collection name (must match a collection in the schema)\n * @returns CollectionAccessor with insert, findById, update, delete, and where methods\n *\n * @example\n * ```typescript\n * const todos = useCollection('todos')\n * await todos.insert({ title: 'New todo' })\n * ```\n */\nexport function useCollection(name: string): CollectionAccessor {\n\tconst { store } = useKoraContext()\n\n\treturn useMemo(() => {\n\t\treturn store.collection(name)\n\t}, [store, name])\n}\n","import type { CollectionAccessor } from '@korajs/store'\nimport type { AwarenessState, CursorInfo } from '@korajs/sync'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport * as Y from 'yjs'\nimport { useKoraContext } from '../context/kora-context'\nimport type { UseRichTextResult } from '../types'\n\nconst LOAD_ORIGIN = 'kora-load'\nconst TEXT_KEY = 'content'\nconst COMPACT_AFTER_DELTAS = 20\n\n/**\n * Binds a richtext field to a shared Yjs document for editor integration.\n */\nexport function useRichText(\n\tcollectionName: string,\n\trecordId: string,\n\tfieldName: string,\n): UseRichTextResult {\n\tconst { store, syncEngine } = useKoraContext()\n\tconst collection = useMemo<CollectionAccessor>(\n\t\t() => store.collection(collectionName),\n\t\t[store, collectionName],\n\t)\n\tconst [doc] = useState(() => new Y.Doc())\n\tconst [ready, setReady] = useState(false)\n\tconst [error, setError] = useState<Error | null>(null)\n\tconst [canUndo, setCanUndo] = useState(false)\n\tconst [canRedo, setCanRedo] = useState(false)\n\tconst [cursors, setCursors] = useState<CursorInfo[]>([])\n\tconst baseUpdateRef = useRef<Uint8Array | null>(null)\n\tconst pendingDeltasRef = useRef<Uint8Array[]>([])\n\n\tconst text = useMemo(() => doc.getText(TEXT_KEY), [doc])\n\tconst undoManager = useMemo(() => new Y.UndoManager(text), [text])\n\n\tconst syncHistoryState = useCallback(() => {\n\t\tsetCanUndo(undoManager.undoStack.length > 0)\n\t\tsetCanRedo(undoManager.redoStack.length > 0)\n\t}, [undoManager])\n\n\tconst undo = useCallback(() => {\n\t\tundoManager.undo()\n\t\tsyncHistoryState()\n\t}, [syncHistoryState, undoManager])\n\n\tconst redo = useCallback(() => {\n\t\tundoManager.redo()\n\t\tsyncHistoryState()\n\t}, [syncHistoryState, undoManager])\n\n\tuseEffect(() => {\n\t\tlet disposed = false\n\n\t\tconst initialize = async (): Promise<void> => {\n\t\t\tsetReady(false)\n\t\t\tsetError(null)\n\n\t\t\ttry {\n\t\t\t\tconst record = await collection.findById(recordId)\n\t\t\t\tif (disposed) return\n\n\t\t\t\tdoc.transact(() => {\n\t\t\t\t\tconst target = doc.getText(TEXT_KEY)\n\t\t\t\t\ttarget.delete(0, target.length)\n\t\t\t\t}, LOAD_ORIGIN)\n\n\t\t\t\tconst encoded = encodeRichtextInput(record?.[fieldName])\n\t\t\t\tbaseUpdateRef.current = encoded\n\t\t\t\tpendingDeltasRef.current = []\n\t\t\t\tif (encoded) {\n\t\t\t\t\tY.applyUpdate(doc, encoded, LOAD_ORIGIN)\n\t\t\t\t}\n\n\t\t\t\tsetReady(true)\n\t\t\t} catch (cause) {\n\t\t\t\tif (disposed) return\n\t\t\t\tsetError(cause instanceof Error ? cause : new Error(String(cause)))\n\t\t\t}\n\t\t}\n\n\t\tconst persist = async (_update: Uint8Array, origin: unknown): Promise<void> => {\n\t\t\tsyncHistoryState()\n\t\t\tif (origin === LOAD_ORIGIN) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tpendingDeltasRef.current.push(_update)\n\t\t\tconst snapshot = composeRichtextSnapshot(baseUpdateRef.current, pendingDeltasRef.current)\n\n\t\t\tif (pendingDeltasRef.current.length >= COMPACT_AFTER_DELTAS) {\n\t\t\t\tbaseUpdateRef.current = snapshot\n\t\t\t\tpendingDeltasRef.current = []\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait collection.update(recordId, {\n\t\t\t\t\t[fieldName]: snapshot,\n\t\t\t\t})\n\t\t\t} catch (cause) {\n\t\t\t\tif (!disposed) {\n\t\t\t\t\tsetError(cause instanceof Error ? cause : new Error(String(cause)))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdoc.on('update', persist)\n\t\tvoid initialize()\n\n\t\tsyncHistoryState()\n\n\t\treturn () => {\n\t\t\tdisposed = true\n\t\t\tdoc.off('update', persist)\n\t\t\tundoManager.destroy()\n\t\t\tbaseUpdateRef.current = null\n\t\t\tpendingDeltasRef.current = []\n\t\t}\n\t}, [collection, doc, fieldName, recordId, syncHistoryState, undoManager])\n\n\t// Track remote collaborators' cursors for this specific field\n\tuseEffect(() => {\n\t\tif (!syncEngine) return\n\n\t\tconst awareness = syncEngine.getAwarenessManager()\n\t\tconst localClientId = awareness.clientId\n\n\t\tconst updateCursors = (): void => {\n\t\t\tconst states = awareness.getStates()\n\t\t\tconst fieldCursors: CursorInfo[] = []\n\n\t\t\tfor (const [clientId, state] of states) {\n\t\t\t\tif (clientId === localClientId) continue\n\t\t\t\tif (!state.cursor) continue\n\t\t\t\t// Only include cursors for this specific field\n\t\t\t\tif (\n\t\t\t\t\tstate.cursor.collection !== collectionName ||\n\t\t\t\t\tstate.cursor.recordId !== recordId ||\n\t\t\t\t\tstate.cursor.field !== fieldName\n\t\t\t\t) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfieldCursors.push({\n\t\t\t\t\tclientId,\n\t\t\t\t\tuserName: state.user.name,\n\t\t\t\t\tcolor: state.user.color,\n\t\t\t\t\tanchor: state.cursor.anchor,\n\t\t\t\t\thead: state.cursor.head,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tsetCursors(fieldCursors)\n\t\t}\n\n\t\tconst unsubscribe = awareness.on('change', () => {\n\t\t\tupdateCursors()\n\t\t})\n\n\t\t// Initial check\n\t\tupdateCursors()\n\n\t\treturn unsubscribe\n\t}, [syncEngine, collectionName, recordId, fieldName])\n\n\treturn { doc, text, undo, redo, canUndo, canRedo, ready, error, cursors }\n}\n\nfunction encodeRichtextInput(value: unknown): Uint8Array | null {\n\tif (value === null || value === undefined) {\n\t\treturn null\n\t}\n\n\tif (typeof value === 'string') {\n\t\tconst doc = new Y.Doc()\n\t\tdoc.getText(TEXT_KEY).insert(0, value)\n\t\treturn Y.encodeStateAsUpdate(doc)\n\t}\n\n\tif (value instanceof Uint8Array) {\n\t\treturn value\n\t}\n\n\tif (value instanceof ArrayBuffer) {\n\t\treturn new Uint8Array(value)\n\t}\n\n\t// Handle Node.js Buffer without requiring @types/node\n\tif (typeof globalThis !== 'undefined' && 'Buffer' in globalThis) {\n\t\tconst BufferCtor = (globalThis as Record<string, unknown>).Buffer as {\n\t\t\tisBuffer(v: unknown): v is { buffer: ArrayBuffer; byteOffset: number; byteLength: number }\n\t\t}\n\t\tif (BufferCtor.isBuffer(value)) {\n\t\t\treturn new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n\t\t}\n\t}\n\n\tthrow new Error('Richtext record value must be a string, Uint8Array, ArrayBuffer, or null.')\n}\n\nfunction composeRichtextSnapshot(base: Uint8Array | null, deltas: Uint8Array[]): Uint8Array {\n\tconst doc = new Y.Doc()\n\tif (base) {\n\t\tY.applyUpdate(doc, base)\n\t}\n\n\tfor (const delta of deltas) {\n\t\tY.applyUpdate(doc, delta)\n\t}\n\n\treturn Y.encodeStateAsUpdate(doc)\n}\n"],"mappings":";AAEA,SAAS,eAAe,eAAe,YAAY,WAAW,gBAAgB;AAI9E,IAAM,cAAc,cAAuC,IAAI;AAqB/D,SAAS,aAAa;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,GAAiC;AAChC,QAAM,CAAC,eAAe,gBAAgB,IAAI,SAAuB,SAAS,IAAI;AAC9E,QAAM,CAAC,cAAc,eAAe,IAAI,SAA4B,cAAc,IAAI;AAEtF,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAS,CAAC,GAAG;AACvC,QAAM,CAAC,WAAW,YAAY,IAAI,SAAuB,IAAI;AAE7D,YAAU,MAAM;AACf,QAAI,CAAC,IAAK;AACV,QAAI,YAAY;AAChB,QAAI,MACF,KAAK,MAAM;A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A,MAAI,OAAO,eAAe,eAAe,YAAY,YAAY;AAChE,UAAM,aAAc,WAAuC;AAG3D,QAAI,WAAW,SAAS,KAAK,GAAG;AAC/B,aAAO,IAAI,WAAW,MAAM,QAAQ,MAAM,YAAY,MAAM,UAAU;AAAA,IACvE;AAAA,EACD;AAEA,QAAM,IAAI,MAAM,2EAA2E;AAC5F;AAEA,SAAS,wBAAwB,MAAyB,QAAkC;AAC3F,QAAM,MAAM,IAAM,MAAI;AACtB,MAAI,MAAM;AACT,IAAE,cAAY,KAAK,IAAI;AAAA,EACxB;AAEA,aAAW,SAAS,QAAQ;AAC3B,IAAE,cAAY,KAAK,KAAK;AAAA,EACzB;AAEA,SAAS,sBAAoB,GAAG;AACjC;","names":["EMPTY_ARRAY","useEffect","useRef","useState","useCallback","useEffect","useRef","useSyncExternalStore","useRef","useCallback","useEffect","useSyncExternalStore","useMemo","useMemo","useCallback","useEffect","useMemo","useRef","useState","useMemo","useState","useRef","useCallback","useEffect"]}
|
|
1
|
+
{"version":3,"sources":["../src/context/kora-context.ts","../src/hooks/use-app.ts","../src/hooks/use-query.ts","../src/query-store/query-store.ts","../src/hooks/use-mutation.ts","../src/hooks/use-sync-status.ts","../src/hooks/use-collection.ts","../src/hooks/use-rich-text.ts"],"sourcesContent":["import type { Store } from '@korajs/store'\nimport type { SyncEngine } from '@korajs/sync'\nimport { createContext, createElement, useContext, useEffect, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { KoraContextValue, KoraProviderProps } from '../types'\n\nconst KoraContext = createContext<KoraContextValue | null>(null)\n\n/**\n * Provides Kora store and optional sync engine to all child components.\n * Must wrap any component that uses Kora hooks (useQuery, useMutation, etc.).\n *\n * Accepts either an `app` prop (recommended) or explicit `store` + `syncEngine` props.\n *\n * When using the `app` prop, KoraProvider waits for `app.ready` before rendering\n * children. A `fallback` prop can be provided to show content while initializing.\n *\n * @example\n * ```typescript\n * // Recommended: pass the app object directly\n * const app = createApp({ schema })\n * <KoraProvider app={app}><App /></KoraProvider>\n *\n * // Advanced: pass store and syncEngine explicitly\n * <KoraProvider store={store} syncEngine={syncEngine}><App /></KoraProvider>\n * ```\n */\nfunction KoraProvider({\n\tapp,\n\tstore,\n\tsyncEngine,\n\tfallback,\n\tchildren,\n}: KoraProviderProps): ReactNode {\n\tconst [resolvedStore, setResolvedStore] = useState<Store | null>(store ?? null)\n\tconst [resolvedSync, setResolvedSync] = useState<SyncEngine | null>(syncEngine ?? null)\n\t// If no app prop, we're using the store prop and are ready immediately\n\tconst [ready, setReady] = useState(!app)\n\tconst [initError, setInitError] = useState<Error | null>(null)\n\n\tuseEffect(() => {\n\t\tif (!app) return\n\t\tlet cancelled = false\n\t\tapp.ready\n\t\t\t.then(() => {\n\t\t\t\tif (cancelled) return\n\t\t\t\tsetResolvedStore(app.getStore())\n\t\t\t\tsetResolvedSync(app.getSyncEngine())\n\t\t\t\tsetReady(true)\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tif (cancelled) return\n\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error))\n\t\t\t\tconsole.error('[Kora] Initialization failed:', err)\n\t\t\t\tsetInitError(err)\n\t\t\t})\n\t\treturn () => {\n\t\t\tcancelled = true\n\t\t}\n\t}, [app])\n\n\tif (initError) {\n\t\treturn createElement(\n\t\t\t'div',\n\t\t\t{ style: { color: 'red', padding: '1rem', fontFamily: 'monospace' } },\n\t\t\tcreateElement('strong', null, 'Kora initialization error: '),\n\t\t\tinitError.message,\n\t\t)\n\t}\n\n\tif (!ready) {\n\t\treturn (fallback ?? null) as ReactNode\n\t}\n\n\tif (!resolvedStore) {\n\t\tthrow new Error(\n\t\t\t'KoraProvider requires either an \"app\" or \"store\" prop. ' +\n\t\t\t\t'Pass a KoraApp from createApp() or a Store instance.',\n\t\t)\n\t}\n\n\tconst value: KoraContextValue = {\n\t\tstore: resolvedStore,\n\t\tsyncEngine: resolvedSync,\n\t\tapp: app ?? null,\n\t\tevents: app?.events ?? null,\n\t\tsubscribeSyncStatus: app?.sync?.subscribeStatus ?? null,\n\t}\n\treturn createElement(KoraContext.Provider, { value }, children)\n}\n\n/**\n * Internal hook to access the Kora context.\n * Throws if used outside of a KoraProvider.\n */\nfunction useKoraContext(): KoraContextValue {\n\tconst context = useContext(KoraContext)\n\tif (context === null) {\n\t\tthrow new Error(\n\t\t\t'useKoraContext must be used within a <KoraProvider>. ' +\n\t\t\t\t'Wrap your component tree with <KoraProvider store={store}>.',\n\t\t)\n\t}\n\treturn context\n}\n\nexport { KoraProvider, useKoraContext }\n","import { useKoraContext } from '../context/kora-context'\nimport type { KoraAppLike } from '../types'\n\n/**\n * React hook that returns the Kora app instance from context.\n *\n * Use the generic parameter to cast to your typed app for full type inference:\n *\n * ```typescript\n * // In your app setup:\n * export const app = createApp({ schema: mySchema })\n * export type App = typeof app\n *\n * // In components:\n * const app = useApp<App>()\n * app.todos.insert({ title: 'Hello' }) // fully typed\n * const todos = useQuery(app.todos.where({ completed: false }))\n * ```\n *\n * Requires `KoraProvider` to be initialized with the `app` prop.\n * Throws if used outside of `KoraProvider` or without an `app` prop.\n *\n * @returns The KoraApp instance, typed as `T`\n */\nexport function useApp<T extends KoraAppLike = KoraAppLike>(): T {\n\tconst { app } = useKoraContext()\n\tif (!app) {\n\t\tthrow new Error(\n\t\t\t'useApp() requires KoraProvider to be initialized with an \"app\" prop. ' +\n\t\t\t\t'Pass your createApp() result to <KoraProvider app={app}>.',\n\t\t)\n\t}\n\treturn app as T\n}\n","import type { CollectionRecord, QueryBuilder } from '@korajs/store'\nimport { useMemo, useRef, useSyncExternalStore } from 'react'\nimport { QueryStore } from '../query-store/query-store'\nimport type { UseQueryOptions } from '../types'\n\nconst APP_NOT_READY_CODE = 'APP_NOT_READY'\n\nfunction assertQueryReady(query: QueryBuilder<unknown>): void {\n\tconst descriptor = query.getDescriptor()\n\tif (descriptor.collection === '__pending__') {\n\t\tconst err = new Error(\n\t\t\t'Cannot use useQuery() before app.ready. Await app.ready or wrap your UI in <KoraProvider app={app}>.',\n\t\t)\n\t\terr.name = 'AppNotReadyError'\n\t\tObject.assign(err, { code: APP_NOT_READY_CODE })\n\t\tthrow err\n\t}\n}\n\n/**\n * Frozen empty array returned when the query is disabled or before data loads.\n * Same reference prevents unnecessary re-renders.\n */\nconst EMPTY_ARRAY: readonly unknown[] = Object.freeze([])\n\nconst noopSubscribe = (_onStoreChange: () => void): (() => void) => {\n\treturn () => {}\n}\n\n/**\n * React hook for reactive queries against the local Kora store.\n *\n * Returns data synchronously from the local store — no loading spinners needed.\n * Re-renders automatically when the query results change due to mutations.\n * Uses `useSyncExternalStore` for React 18+ concurrent mode safety.\n *\n * The generic parameter `T` is inferred from the QueryBuilder, providing\n * full type safety when used with typed collection accessors.\n *\n * @param query - A QueryBuilder instance (e.g., `app.todos.where({ done: false })`)\n * @param options - Optional configuration (e.g., `{ enabled: false }` to skip the query)\n * @returns Readonly array of matching records\n *\n * @example\n * ```typescript\n * const todos = useQuery(app.todos.where({ completed: false }).orderBy('createdAt'))\n * // todos is typed as readonly InferRecord<typeof todoFields>[]\n * ```\n */\nexport function useQuery<T = CollectionRecord>(\n\tquery: QueryBuilder<T>,\n\toptions?: UseQueryOptions,\n): readonly T[] {\n\tconst enabled = options?.enabled !== false\n\n\tif (enabled) {\n\t\tassertQueryReady(query)\n\t}\n\n\t// Compute a stable key from the query descriptor\n\tconst descriptorKey = JSON.stringify(query.getDescriptor())\n\n\t// Track the current QueryStore instance\n\tconst queryStoreRef = useRef<QueryStore<T> | null>(null)\n\tconst prevKeyRef = useRef<string | null>(null)\n\n\t// Create or reuse a QueryStore when the descriptor changes\n\tconst queryStore = useMemo(() => {\n\t\tif (!enabled) {\n\t\t\t// Destroy previous if it exists\n\t\t\tif (queryStoreRef.current) {\n\t\t\t\tqueryStoreRef.current.destroy()\n\t\t\t\tqueryStoreRef.current = null\n\t\t\t}\n\t\t\tprevKeyRef.current = null\n\t\t\treturn null\n\t\t}\n\n\t\t// If descriptor changed, destroy previous and create new\n\t\tif (prevKeyRef.current !== descriptorKey) {\n\t\t\tif (queryStoreRef.current) {\n\t\t\t\tqueryStoreRef.current.destroy()\n\t\t\t}\n\t\t\tconst newStore = new QueryStore<T>(query)\n\t\t\tqueryStoreRef.current = newStore\n\t\t\tprevKeyRef.current = descriptorKey\n\t\t\treturn newStore\n\t\t}\n\n\t\treturn queryStoreRef.current\n\t}, [descriptorKey, enabled, query])\n\n\t// No useEffect cleanup needed: QueryStore's subscribe/unsubscribe cycle\n\t// manages the underlying subscription lifetime. When the last listener\n\t// detaches (on unmount), the subscription auto-stops. This also makes\n\t// the hook resilient to React StrictMode's double-mount cycle.\n\n\tconst disabledGetSnapshot = (): readonly T[] => EMPTY_ARRAY as readonly T[]\n\n\t// The query object is deliberately excluded from the dependency array.\n\t// QueryBuilder instances are ephemeral (created on every render when\n\t// developers use inline `app.todos.where({...})`). Using it as a dep\n\t// would destroy and recreate the QueryStore on every render, causing\n\t// subscription storms. Instead, we only react to the stable descriptor\n\t// JSON key, which captures the actual query parameters.\n\treturn useSyncExternalStore(\n\t\tqueryStore ? queryStore.subscribe : noopSubscribe,\n\t\tqueryStore ? queryStore.getSnapshot : disabledGetSnapshot,\n\t)\n}\n","import type { CollectionRecord, QueryBuilder } from '@korajs/store'\n\n/**\n * Frozen empty array returned as the initial snapshot before any data loads.\n * Same reference every time prevents infinite re-render loops with useSyncExternalStore.\n */\nconst EMPTY_ARRAY: readonly unknown[] = Object.freeze([])\n\n/**\n * Bridges the async QueryBuilder.subscribe() API with the synchronous\n * getSnapshot() required by React's useSyncExternalStore.\n *\n * Uses a lazy subscription model: the underlying query subscription starts\n * when the first listener attaches (via useSyncExternalStore's subscribe)\n * and stops when the last listener detaches. This makes QueryStore resilient\n * to React StrictMode's double-mount cycle, where useEffect cleanup fires\n * between mount and remount.\n *\n * Generic parameter `T` defaults to `CollectionRecord` for backward compatibility.\n */\nexport class QueryStore<T = CollectionRecord> {\n\tprivate snapshot: readonly T[] = EMPTY_ARRAY as readonly T[]\n\tprivate listeners = new Set<() => void>()\n\tprivate unsubscribeQuery: (() => void) | null = null\n\tprivate active = false\n\tprivate readonly queryBuilder: QueryBuilder<T>\n\n\tconstructor(queryBuilder: QueryBuilder<T>) {\n\t\tthis.queryBuilder = queryBuilder\n\t}\n\n\t/**\n\t * Subscribe to snapshot changes. Compatible with useSyncExternalStore.\n\t *\n\t * Lazily starts the underlying query subscription when the first listener\n\t * attaches, and stops it when the last listener detaches. This allows\n\t * React StrictMode to unmount/remount without permanently killing the subscription.\n\t *\n\t * @returns Unsubscribe function\n\t */\n\tsubscribe = (onStoreChange: () => void): (() => void) => {\n\t\tthis.listeners.add(onStoreChange)\n\n\t\t// Start the underlying query subscription when the first listener attaches\n\t\tif (!this.active) {\n\t\t\tthis.startSubscription()\n\t\t}\n\n\t\treturn () => {\n\t\t\tthis.listeners.delete(onStoreChange)\n\t\t\t// Stop the underlying subscription when the last listener detaches.\n\t\t\t// This ensures cleanup on unmount without needing a useEffect.\n\t\t\tif (this.listeners.size === 0) {\n\t\t\t\tthis.stopSubscription()\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get the current snapshot synchronously. Compatible with useSyncExternalStore.\n\t * Returns EMPTY_ARRAY before the first async fetch completes.\n\t */\n\tgetSnapshot = (): readonly T[] => {\n\t\treturn this.snapshot\n\t}\n\n\t/**\n\t * Clean up the underlying subscription and release resources.\n\t * Called by useMemo when the query descriptor changes.\n\t */\n\tdestroy(): void {\n\t\tthis.stopSubscription()\n\t\tthis.listeners.clear()\n\t\tthis.snapshot = EMPTY_ARRAY as readonly T[]\n\t}\n\n\tprivate startSubscription(): void {\n\t\tthis.active = true\n\t\tthis.unsubscribeQuery = this.queryBuilder.subscribe((results) => {\n\t\t\tif (!this.active) return\n\t\t\tconst newSnapshot = Object.freeze([...results])\n\t\t\tthis.snapshot = newSnapshot\n\t\t\tthis.notifyListeners()\n\t\t})\n\t}\n\n\tprivate stopSubscription(): void {\n\t\tthis.active = false\n\t\tif (this.unsubscribeQuery) {\n\t\t\tthis.unsubscribeQuery()\n\t\t\tthis.unsubscribeQuery = null\n\t\t}\n\t}\n\n\tprivate notifyListeners(): void {\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener()\n\t\t}\n\t}\n}\n","import { useCallback, useEffect, useRef, useState } from 'react'\nimport type { UseMutationOptions, UseMutationResult } from '../types'\n\n/**\n * React hook for performing mutations against the local Kora store.\n *\n * Returns `mutate` for fire-and-forget usage and `mutateAsync` when you need\n * to await the result. Optional `onMutate` / `onRollback` support optimistic\n * UI updates that revert if the mutation throws.\n *\n * @param mutationFn - An async function to execute (e.g., `app.todos.insert`)\n * @param options - Optional optimistic/rollback and lifecycle callbacks\n * @returns Object with mutate, mutateAsync, isLoading, error, and reset\n *\n * @example\n * ```typescript\n * const { mutate } = useMutation(app.todos.insert, {\n * onMutate: (data) => {\n * const previous = todos\n * setTodos((list) => [...list, { id: 'temp', ...data }])\n * return previous\n * },\n * onRollback: (previous) => setTodos(previous),\n * })\n * ```\n */\nexport function useMutation<TData, TArgs extends unknown[], TContext = void>(\n\tmutationFn: (...args: TArgs) => Promise<TData>,\n\toptions?: UseMutationOptions<TData, TArgs, TContext>,\n): UseMutationResult<TData, TArgs> {\n\tconst [state, setState] = useState<{ isLoading: boolean; error: Error | null }>({\n\t\tisLoading: false,\n\t\terror: null,\n\t})\n\n\tconst mountedRef = useRef(true)\n\tuseEffect(() => {\n\t\tmountedRef.current = true\n\t\treturn () => {\n\t\t\tmountedRef.current = false\n\t\t}\n\t}, [])\n\n\tconst fnRef = useRef(mutationFn)\n\tfnRef.current = mutationFn\n\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\n\tconst mutateAsync = useCallback(async (...args: TArgs): Promise<TData> => {\n\t\tconst opts = optionsRef.current\n\t\tlet context: TContext | undefined\n\n\t\tif (mountedRef.current) {\n\t\t\tsetState({ isLoading: true, error: null })\n\t\t}\n\n\t\ttry {\n\t\t\tif (opts?.onMutate) {\n\t\t\t\tcontext = await opts.onMutate(...args)\n\t\t\t}\n\n\t\t\tconst result = await fnRef.current(...args)\n\n\t\t\tif (mountedRef.current) {\n\t\t\t\tsetState({ isLoading: false, error: null })\n\t\t\t}\n\t\t\topts?.onSuccess?.(result, ...args)\n\t\t\topts?.onSettled?.(result, null, ...args)\n\t\t\treturn result\n\t\t} catch (err) {\n\t\t\tconst error = err instanceof Error ? err : new Error(String(err))\n\n\t\t\tif (context !== undefined && opts?.onRollback) {\n\t\t\t\tawait opts.onRollback(context, ...args)\n\t\t\t}\n\n\t\t\tif (mountedRef.current) {\n\t\t\t\tsetState({ isLoading: false, error })\n\t\t\t}\n\t\t\topts?.onError?.(error, ...args)\n\t\t\topts?.onSettled?.(undefined, error, ...args)\n\t\t\tthrow error\n\t\t}\n\t}, [])\n\n\tconst mutate = useCallback(\n\t\t(...args: TArgs): void => {\n\t\t\tmutateAsync(...args).catch(() => {\n\t\t\t\t// Fire-and-forget: error is captured in state, no unhandled rejection\n\t\t\t})\n\t\t},\n\t\t[mutateAsync],\n\t)\n\n\tconst reset = useCallback((): void => {\n\t\tif (mountedRef.current) {\n\t\t\tsetState({ isLoading: false, error: null })\n\t\t}\n\t}, [])\n\n\treturn {\n\t\tmutate,\n\t\tmutateAsync,\n\t\tisLoading: state.isLoading,\n\t\terror: state.error,\n\t\treset,\n\t}\n}\n","import type { KoraEventType } from '@korajs/core'\nimport type { SyncStatusInfo } from '@korajs/sync'\nimport { useCallback, useRef, useSyncExternalStore } from 'react'\nimport { useKoraContext } from '../context/kora-context'\n\nconst OFFLINE_STATUS: SyncStatusInfo = Object.freeze({\n\tstatus: 'offline',\n\tpendingOperations: 0,\n\tlastSyncedAt: null,\n\tlastSuccessfulPush: null,\n\tlastSuccessfulPull: null,\n\tconflicts: 0,\n})\n\nconst SYNC_STATUS_EVENT_TYPES = [\n\t'sync:connected',\n\t'sync:disconnected',\n\t'sync:schema-mismatch',\n\t'sync:auth-failed',\n\t'sync:sent',\n\t'sync:received',\n\t'sync:acknowledged',\n\t'sync:apply-failed',\n\t'sync:diagnostics',\n\t'sync:initial-sync-progress',\n] as const satisfies readonly KoraEventType[]\n\n/**\n * React hook for monitoring the sync engine's connection status.\n *\n * Subscribes to sync events via `app.sync.subscribeStatus` (or the sync engine\n * emitter when using store-only mode) and re-renders only when status changes.\n *\n * @returns Current sync status information\n *\n * @example\n * ```typescript\n * const status = useSyncStatus()\n * // status.status: 'connected' | 'syncing' | 'synced' | 'offline' | 'error'\n * ```\n */\nexport function useSyncStatus(): SyncStatusInfo {\n\tconst { syncEngine, subscribeSyncStatus, events } = useKoraContext()\n\tconst snapshotRef = useRef<SyncStatusInfo>(OFFLINE_STATUS)\n\tconst serializedRef = useRef<string>(JSON.stringify(OFFLINE_STATUS))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\tif (subscribeSyncStatus) {\n\t\t\t\treturn subscribeSyncStatus((status) => {\n\t\t\t\t\tsnapshotRef.current = status\n\t\t\t\t\tserializedRef.current = JSON.stringify(status)\n\t\t\t\t\tonStoreChange()\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (!syncEngine) {\n\t\t\t\treturn () => {}\n\t\t\t}\n\n\t\t\tconst refresh = (): void => {\n\t\t\t\tconst newStatus = syncEngine.getStatus()\n\t\t\t\tconst newSerialized = JSON.stringify(newStatus)\n\t\t\t\tif (newSerialized !== serializedRef.current) {\n\t\t\t\t\tsnapshotRef.current = newStatus\n\t\t\t\t\tserializedRef.current = newSerialized\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (events) {\n\t\t\t\tconst unsubs = SYNC_STATUS_EVENT_TYPES.map((type) => events.on(type, refresh))\n\t\t\t\trefresh()\n\t\t\t\treturn () => {\n\t\t\t\t\tfor (const unsub of unsubs) {\n\t\t\t\t\t\tunsub()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\trefresh()\n\t\t\treturn () => {}\n\t\t},\n\t\t[syncEngine, subscribeSyncStatus, events],\n\t)\n\n\tconst getSnapshot = useCallback((): SyncStatusInfo => {\n\t\tif (subscribeSyncStatus) {\n\t\t\treturn snapshotRef.current\n\t\t}\n\t\treturn syncEngine ? syncEngine.getStatus() : OFFLINE_STATUS\n\t}, [syncEngine, subscribeSyncStatus])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n","import type { CollectionAccessor } from '@korajs/store'\nimport { useMemo } from 'react'\nimport { useKoraContext } from '../context/kora-context'\n\n/**\n * React hook that returns a CollectionAccessor for the given collection name.\n * Convenience hook for accessing a collection without going through the store directly.\n *\n * @param name - The collection name (must match a collection in the schema)\n * @returns CollectionAccessor with insert, findById, update, delete, and where methods\n *\n * @example\n * ```typescript\n * const todos = useCollection('todos')\n * await todos.insert({ title: 'New todo' })\n * ```\n */\nexport function useCollection(name: string): CollectionAccessor {\n\tconst { store } = useKoraContext()\n\n\treturn useMemo(() => {\n\t\treturn store.collection(name)\n\t}, [store, name])\n}\n","import type { CollectionAccessor } from '@korajs/store'\nimport { encodeRichtext } from '@korajs/store'\nimport type { AwarenessState, AwarenessUser, CursorInfo } from '@korajs/sync'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport * as Y from 'yjs'\nimport { useKoraContext } from '../context/kora-context'\nimport type { UseRichTextResult } from '../types'\n\nconst LOAD_ORIGIN = 'kora-load'\nconst REMOTE_ORIGIN = 'kora-remote'\nconst DOC_CHANNEL_ORIGIN = 'kora-doc-channel'\nconst TEXT_KEY = 'content'\nconst COMPACT_AFTER_DELTAS = 20\nconst PERSIST_DEBOUNCE_MS = 400\n\nexport interface UseRichTextOptions {\n\t/** Presence identity broadcast with cursor updates. */\n\tuser?: AwarenessUser\n\t/**\n\t * Use the incremental Yjs doc channel for live edits (recommended for large documents).\n\t * When omitted, the channel activates automatically once the snapshot exceeds the sync threshold.\n\t */\n\tuseDocChannel?: boolean\n}\n\n/**\n * Binds a richtext field to a shared Yjs document for editor integration.\n */\nexport function useRichText(\n\tcollectionName: string,\n\trecordId: string,\n\tfieldName: string,\n\toptions?: UseRichTextOptions,\n): UseRichTextResult {\n\tconst { store, syncEngine } = useKoraContext()\n\tconst collection = useMemo<CollectionAccessor>(\n\t\t() => store.collection(collectionName),\n\t\t[store, collectionName],\n\t)\n\tconst [doc] = useState(() => new Y.Doc())\n\tconst [ready, setReady] = useState(false)\n\tconst [error, setError] = useState<Error | null>(null)\n\tconst [canUndo, setCanUndo] = useState(false)\n\tconst [canRedo, setCanRedo] = useState(false)\n\tconst [cursors, setCursors] = useState<CursorInfo[]>([])\n\tconst baseUpdateRef = useRef<Uint8Array | null>(null)\n\tconst pendingDeltasRef = useRef<Uint8Array[]>([])\n\tconst docChannelActiveRef = useRef(false)\n\tconst persistTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)\n\tconst userRef = useRef<AwarenessUser | undefined>(options?.user)\n\n\tuseEffect(() => {\n\t\tuserRef.current = options?.user\n\t}, [options?.user])\n\n\tconst text = useMemo(() => doc.getText(TEXT_KEY), [doc])\n\tconst undoManager = useMemo(() => new Y.UndoManager(text), [text])\n\n\tconst syncHistoryState = useCallback(() => {\n\t\tsetCanUndo(undoManager.undoStack.length > 0)\n\t\tsetCanRedo(undoManager.redoStack.length > 0)\n\t}, [undoManager])\n\n\tconst undo = useCallback(() => {\n\t\tundoManager.undo()\n\t\tsyncHistoryState()\n\t}, [syncHistoryState, undoManager])\n\n\tconst redo = useCallback(() => {\n\t\tundoManager.redo()\n\t\tsyncHistoryState()\n\t}, [syncHistoryState, undoManager])\n\n\tconst resolveAwarenessUser = useCallback((): AwarenessUser => {\n\t\tif (userRef.current) {\n\t\t\treturn userRef.current\n\t\t}\n\t\tif (syncEngine) {\n\t\t\tconst existing = syncEngine.getAwarenessManager().getLocalState()?.user\n\t\t\tif (existing) {\n\t\t\t\treturn existing\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tname: 'Anonymous',\n\t\t\tcolor: '#6366f1',\n\t\t}\n\t}, [syncEngine])\n\n\tconst setCursor = useCallback(\n\t\t(anchor: number, head: number) => {\n\t\t\tif (!syncEngine) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst awareness = syncEngine.getAwarenessManager()\n\t\t\tconst state: AwarenessState = {\n\t\t\t\tuser: resolveAwarenessUser(),\n\t\t\t\tcursor: {\n\t\t\t\t\tcollection: collectionName,\n\t\t\t\t\trecordId,\n\t\t\t\t\tfield: fieldName,\n\t\t\t\t\tanchor,\n\t\t\t\t\thead,\n\t\t\t\t},\n\t\t\t}\n\t\t\tawareness.setLocalState(state)\n\t\t},\n\t\t[collectionName, fieldName, recordId, resolveAwarenessUser, syncEngine],\n\t)\n\n\tconst clearCursor = useCallback(() => {\n\t\tif (!syncEngine) {\n\t\t\treturn\n\t\t}\n\n\t\tconst awareness = syncEngine.getAwarenessManager()\n\t\tconst current = awareness.getLocalState()\n\t\tif (!current?.cursor) {\n\t\t\treturn\n\t\t}\n\t\tif (\n\t\t\tcurrent.cursor.collection !== collectionName ||\n\t\t\tcurrent.cursor.recordId !== recordId ||\n\t\t\tcurrent.cursor.field !== fieldName\n\t\t) {\n\t\t\treturn\n\t\t}\n\n\t\tawareness.setLocalState({ user: current.user })\n\t}, [collectionName, fieldName, recordId, syncEngine])\n\n\tconst applyRemoteSnapshot = useCallback(\n\t\t(value: unknown) => {\n\t\t\tconst encoded = encodeRichtextInput(value)\n\t\t\tif (!encoded) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst currentSnapshot = Y.encodeStateAsUpdate(doc)\n\t\t\tif (updatesEqual(currentSnapshot, encoded)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tY.applyUpdate(doc, encoded, REMOTE_ORIGIN)\n\t\t\tbaseUpdateRef.current = encoded\n\t\t\tpendingDeltasRef.current = []\n\t\t\tsyncHistoryState()\n\t\t},\n\t\t[doc, syncHistoryState],\n\t)\n\n\tuseEffect(() => {\n\t\tlet disposed = false\n\n\t\tconst initialize = async (): Promise<void> => {\n\t\t\tsetReady(false)\n\t\t\tsetError(null)\n\n\t\t\ttry {\n\t\t\t\tconst record = await collection.findById(recordId)\n\t\t\t\tif (disposed) return\n\n\t\t\t\tdoc.transact(() => {\n\t\t\t\t\tconst target = doc.getText(TEXT_KEY)\n\t\t\t\t\ttarget.delete(0, target.length)\n\t\t\t\t}, LOAD_ORIGIN)\n\n\t\t\t\tconst encoded = encodeRichtextInput(record?.[fieldName])\n\t\t\t\tbaseUpdateRef.current = encoded\n\t\t\t\tpendingDeltasRef.current = []\n\t\t\t\tif (encoded) {\n\t\t\t\t\tY.applyUpdate(doc, encoded, LOAD_ORIGIN)\n\t\t\t\t}\n\n\t\t\t\tconst channel = syncEngine?.getRichtextDocChannel?.()\n\t\t\t\tdocChannelActiveRef.current =\n\t\t\t\t\tchannel?.shouldUseChannel(encoded?.length ?? 0, options?.useDocChannel) ?? false\n\n\t\t\t\tsetReady(true)\n\t\t\t} catch (cause) {\n\t\t\t\tif (disposed) return\n\t\t\t\tsetError(cause instanceof Error ? cause : new Error(String(cause)))\n\t\t\t}\n\t\t}\n\n\t\tconst flushPersist = async (): Promise<void> => {\n\t\t\tconst snapshot = composeRichtextSnapshot(baseUpdateRef.current, pendingDeltasRef.current)\n\t\t\tif (pendingDeltasRef.current.length >= COMPACT_AFTER_DELTAS) {\n\t\t\t\tbaseUpdateRef.current = snapshot\n\t\t\t\tpendingDeltasRef.current = []\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait collection.update(recordId, {\n\t\t\t\t\t[fieldName]: snapshot,\n\t\t\t\t})\n\t\t\t} catch (cause) {\n\t\t\t\tif (!disposed) {\n\t\t\t\t\tsetError(cause instanceof Error ? cause : new Error(String(cause)))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst schedulePersist = (): void => {\n\t\t\tif (persistTimerRef.current) {\n\t\t\t\tclearTimeout(persistTimerRef.current)\n\t\t\t}\n\t\t\tpersistTimerRef.current = setTimeout(() => {\n\t\t\t\tpersistTimerRef.current = null\n\t\t\t\tvoid flushPersist()\n\t\t\t}, PERSIST_DEBOUNCE_MS)\n\t\t}\n\n\t\tconst persist = (_update: Uint8Array, origin: unknown): void => {\n\t\t\tsyncHistoryState()\n\t\t\tif (origin === LOAD_ORIGIN || origin === REMOTE_ORIGIN || origin === DOC_CHANNEL_ORIGIN) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tpendingDeltasRef.current.push(_update)\n\n\t\t\tif (docChannelActiveRef.current && syncEngine) {\n\t\t\t\tsyncEngine.getRichtextDocChannel().send(collectionName, recordId, fieldName, _update)\n\t\t\t\tschedulePersist()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvoid flushPersist()\n\t\t}\n\n\t\tdoc.on('update', persist)\n\t\tvoid initialize()\n\n\t\tsyncHistoryState()\n\n\t\treturn () => {\n\t\t\tdisposed = true\n\t\t\tif (persistTimerRef.current) {\n\t\t\t\tclearTimeout(persistTimerRef.current)\n\t\t\t\tpersistTimerRef.current = null\n\t\t\t}\n\t\t\tdoc.off('update', persist)\n\t\t\tundoManager.destroy()\n\t\t\tbaseUpdateRef.current = null\n\t\t\tpendingDeltasRef.current = []\n\t\t\tdocChannelActiveRef.current = false\n\t\t}\n\t}, [\n\t\tcollection,\n\t\tcollectionName,\n\t\tdoc,\n\t\tfieldName,\n\t\toptions?.useDocChannel,\n\t\trecordId,\n\t\tsyncEngine,\n\t\tsyncHistoryState,\n\t\tundoManager,\n\t])\n\n\t// Incremental Yjs updates from the doc channel (large-document side path).\n\tuseEffect(() => {\n\t\tif (!ready || !syncEngine || !docChannelActiveRef.current) {\n\t\t\treturn\n\t\t}\n\n\t\tconst channel = syncEngine.getRichtextDocChannel()\n\t\treturn channel.subscribe(collectionName, recordId, fieldName, (update) => {\n\t\t\tY.applyUpdate(doc, update, DOC_CHANNEL_ORIGIN)\n\t\t\tsyncHistoryState()\n\t\t})\n\t}, [collectionName, doc, fieldName, ready, recordId, syncEngine, syncHistoryState])\n\n\t// Merge remote richtext writes from sync into the live Y.Doc.\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\n\t\tconst unsubscribe = store\n\t\t\t.collection(collectionName)\n\t\t\t.where({ id: recordId })\n\t\t\t.subscribe((results) => {\n\t\t\t\tconst record = results[0]\n\t\t\t\tif (!record) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tapplyRemoteSnapshot(record[fieldName])\n\t\t\t})\n\n\t\treturn unsubscribe\n\t}, [applyRemoteSnapshot, collectionName, fieldName, ready, recordId, store])\n\n\t// Track remote collaborators' cursors for this specific field.\n\tuseEffect(() => {\n\t\tif (!syncEngine) return\n\n\t\tconst awareness = syncEngine.getAwarenessManager()\n\t\tconst localClientId = awareness.clientId\n\n\t\tconst updateCursors = (): void => {\n\t\t\tconst states = awareness.getStates()\n\t\t\tconst fieldCursors: CursorInfo[] = []\n\n\t\t\tfor (const [clientId, state] of states) {\n\t\t\t\tif (clientId === localClientId) continue\n\t\t\t\tif (!state.cursor) continue\n\t\t\t\tif (\n\t\t\t\t\tstate.cursor.collection !== collectionName ||\n\t\t\t\t\tstate.cursor.recordId !== recordId ||\n\t\t\t\t\tstate.cursor.field !== fieldName\n\t\t\t\t) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfieldCursors.push({\n\t\t\t\t\tclientId,\n\t\t\t\t\tuserName: state.user.name,\n\t\t\t\t\tcolor: state.user.color,\n\t\t\t\t\tanchor: state.cursor.anchor,\n\t\t\t\t\thead: state.cursor.head,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tsetCursors(fieldCursors)\n\t\t}\n\n\t\tconst unsubscribe = awareness.on('change', () => {\n\t\t\tupdateCursors()\n\t\t})\n\n\t\tupdateCursors()\n\n\t\treturn () => {\n\t\t\tunsubscribe()\n\t\t\tclearCursor()\n\t\t}\n\t}, [clearCursor, collectionName, fieldName, recordId, syncEngine])\n\n\treturn { doc, text, undo, redo, canUndo, canRedo, ready, error, cursors, setCursor, clearCursor }\n}\n\nfunction encodeRichtextInput(value: unknown): Uint8Array | null {\n\tif (value === null || value === undefined) {\n\t\treturn null\n\t}\n\n\ttry {\n\t\treturn encodeRichtext(value as Parameters<typeof encodeRichtext>[0])\n\t} catch {\n\t\tif (typeof value === 'string') {\n\t\t\tconst fallbackDoc = new Y.Doc()\n\t\t\tfallbackDoc.getText(TEXT_KEY).insert(0, value)\n\t\t\treturn Y.encodeStateAsUpdate(fallbackDoc)\n\t\t}\n\t\tthrow new Error('Richtext record value must be a string, Uint8Array, ArrayBuffer, or null.')\n\t}\n}\n\nfunction composeRichtextSnapshot(base: Uint8Array | null, deltas: Uint8Array[]): Uint8Array {\n\tconst mergedDoc = new Y.Doc()\n\tif (base) {\n\t\tY.applyUpdate(mergedDoc, base)\n\t}\n\n\tfor (const delta of deltas) {\n\t\tY.applyUpdate(mergedDoc, delta)\n\t}\n\n\treturn Y.encodeStateAsUpdate(mergedDoc)\n}\n\nfunction updatesEqual(left: Uint8Array, right: Uint8Array): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false\n\t}\n\tfor (let index = 0; index < left.length; index++) {\n\t\tif (left[index] !== right[index]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"],"mappings":";AAEA,SAAS,eAAe,eAAe,YAAY,WAAW,gBAAgB;AAI9E,IAAM,cAAc,cAAuC,IAAI;AAqB/D,SAAS,aAAa;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,GAAiC;AAChC,QAAM,CAAC,eAAe,gBAAgB,IAAI,SAAuB,SAAS,IAAI;AAC9E,QAAM,CAAC,cAAc,eAAe,IAAI,SAA4B,cAAc,IAAI;AAEtF,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAS,CAAC,GAAG;AACvC,QAAM,CAAC,WAAW,YAAY,IAAI,SAAuB,IAAI;AAE7D,YAAU,MAAM;AACf,QAAI,CAAC,IAAK;AACV,QAAI,YAAY;AAChB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Z,kBAAY;AACZ,kBAAY;AAAA,IACb;AAAA,EACD,GAAG,CAAC,aAAa,gBAAgB,WAAW,UAAU,UAAU,CAAC;AAEjE,SAAO,EAAE,KAAK,MAAM,MAAM,MAAM,SAAS,SAAS,OAAO,OAAO,SAAS,WAAW,YAAY;AACjG;AAEA,SAAS,oBAAoB,OAAmC;AAC/D,MAAI,UAAU,QAAQ,UAAU,QAAW;AAC1C,WAAO;AAAA,EACR;AAEA,MAAI;AACH,WAAO,eAAe,KAA6C;AAAA,EACpE,QAAQ;AACP,QAAI,OAAO,UAAU,UAAU;AAC9B,YAAM,cAAc,IAAM,MAAI;AAC9B,kBAAY,QAAQ,QAAQ,EAAE,OAAO,GAAG,KAAK;AAC7C,aAAS,sBAAoB,WAAW;AAAA,IACzC;AACA,UAAM,IAAI,MAAM,2EAA2E;AAAA,EAC5F;AACD;AAEA,SAAS,wBAAwB,MAAyB,QAAkC;AAC3F,QAAM,YAAY,IAAM,MAAI;AAC5B,MAAI,MAAM;AACT,IAAE,cAAY,WAAW,IAAI;AAAA,EAC9B;AAEA,aAAW,SAAS,QAAQ;AAC3B,IAAE,cAAY,WAAW,KAAK;AAAA,EAC/B;AAEA,SAAS,sBAAoB,SAAS;AACvC;AAEA,SAAS,aAAa,MAAkB,OAA4B;AACnE,MAAI,KAAK,WAAW,MAAM,QAAQ;AACjC,WAAO;AAAA,EACR;AACA,WAAS,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS;AACjD,QAAI,KAAK,KAAK,MAAM,MAAM,KAAK,GAAG;AACjC,aAAO;AAAA,IACR;AAAA,EACD;AACA,SAAO;AACR;","names":["EMPTY_ARRAY","useEffect","useRef","useState","useCallback","useRef","useSyncExternalStore","useRef","useCallback","useSyncExternalStore","useMemo","useMemo","useCallback","useEffect","useMemo","useRef","useState","useMemo","useState","useRef","useEffect","useCallback"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@korajs/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Kora.js React hooks and bindings for offline-first applications",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -31,9 +31,9 @@
|
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"yjs": "^13.6.30",
|
|
34
|
-
"@korajs/core": "0.
|
|
35
|
-
"@korajs/
|
|
36
|
-
"@korajs/
|
|
34
|
+
"@korajs/core": "0.5.0",
|
|
35
|
+
"@korajs/sync": "0.5.0",
|
|
36
|
+
"@korajs/store": "0.5.0"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@testing-library/jest-dom": "^6.0.0",
|