@yorkie-js/react 0.6.23 → 0.6.24

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.
@@ -6,12 +6,6 @@ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { en
6
6
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
7
 
8
8
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
9
- const name$1 = "@yorkie-js/react";
10
- const version$1 = "0.6.23";
11
- const pkg$1 = {
12
- name: name$1,
13
- version: version$1
14
- };
15
9
  var Code$1;
16
10
  (function(Code2) {
17
11
  Code2[Code2["Canceled"] = 1] = "Canceled";
@@ -2325,7 +2319,17 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
2325
2319
  }
2326
2320
  switch (m.kind) {
2327
2321
  case "message":
2328
- return m.T.equals(va, vb);
2322
+ let a2 = va;
2323
+ let b2 = vb;
2324
+ if (m.T.fieldWrapper) {
2325
+ if (a2 !== void 0 && !isMessage(a2)) {
2326
+ a2 = m.T.fieldWrapper.wrapField(a2);
2327
+ }
2328
+ if (b2 !== void 0 && !isMessage(b2)) {
2329
+ b2 = m.T.fieldWrapper.wrapField(b2);
2330
+ }
2331
+ }
2332
+ return m.T.equals(a2, b2);
2329
2333
  case "enum":
2330
2334
  return scalarEquals(ScalarType.INT32, va, vb);
2331
2335
  case "scalar":
@@ -7827,7 +7831,41 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
7827
7831
  kind: "scalar",
7828
7832
  T: 9
7829
7833
  /* ScalarType.STRING */
7830
- }
7834
+ },
7835
+ {
7836
+ no: 3,
7837
+ name: "api_service",
7838
+ kind: "scalar",
7839
+ T: 9
7840
+ /* ScalarType.STRING */
7841
+ },
7842
+ {
7843
+ no: 4,
7844
+ name: "quota_metric",
7845
+ kind: "scalar",
7846
+ T: 9
7847
+ /* ScalarType.STRING */
7848
+ },
7849
+ {
7850
+ no: 5,
7851
+ name: "quota_id",
7852
+ kind: "scalar",
7853
+ T: 9
7854
+ /* ScalarType.STRING */
7855
+ },
7856
+ { no: 6, name: "quota_dimensions", kind: "map", K: 9, V: {
7857
+ kind: "scalar",
7858
+ T: 9
7859
+ /* ScalarType.STRING */
7860
+ } },
7861
+ {
7862
+ no: 7,
7863
+ name: "quota_value",
7864
+ kind: "scalar",
7865
+ T: 3
7866
+ /* ScalarType.INT64 */
7867
+ },
7868
+ { no: 8, name: "future_quota_value", kind: "scalar", T: 3, opt: true }
7831
7869
  ],
7832
7870
  { localName: "QuotaFailure_Violation" }
7833
7871
  );
@@ -9474,7 +9512,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
9474
9512
  if (value < 0) return UZERO;
9475
9513
  if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;
9476
9514
  } else {
9477
- if (value <= -9223372036854776e3) return MIN_VALUE;
9515
+ if (value <= -TWO_PWR_63_DBL) return MIN_VALUE;
9478
9516
  if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE;
9479
9517
  }
9480
9518
  if (value < 0) return fromNumber(-value, unsigned).neg();
@@ -10006,13 +10044,13 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
10006
10044
  );
10007
10045
  };
10008
10046
  if (typeof BigInt === "function") {
10009
- Long.fromBigInt = function fromBigInt2(value, unsigned) {
10047
+ Long.fromBigInt = function fromBigInt(value, unsigned) {
10010
10048
  var lowBits = Number(BigInt.asIntN(32, value));
10011
10049
  var highBits = Number(BigInt.asIntN(32, value >> BigInt(32)));
10012
10050
  return fromBits(lowBits, highBits, unsigned);
10013
10051
  };
10014
10052
  Long.fromValue = function fromValueWithBigInt(value, unsigned) {
10015
- if (typeof value === "bigint") return fromBigInt(value, unsigned);
10053
+ if (typeof value === "bigint") return Long.fromBigInt(value, unsigned);
10016
10054
  return fromValue(value, unsigned);
10017
10055
  };
10018
10056
  LongPrototype.toBigInt = function toBigInt() {
@@ -13197,7 +13235,9 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
13197
13235
  __publicField(this, "_value", "");
13198
13236
  this.id = id;
13199
13237
  this.removedAt = removedAt;
13200
- attributes && (this.attrs = attributes);
13238
+ if (attributes) {
13239
+ this.attrs = attributes;
13240
+ }
13201
13241
  if (typeof opts === "string") {
13202
13242
  this.value = opts;
13203
13243
  } else if (Array.isArray(opts)) {
@@ -17520,7 +17560,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
17520
17560
  this.reconnectStreamDelay
17521
17561
  );
17522
17562
  });
17523
- } catch (err) {
17563
+ } catch {
17524
17564
  }
17525
17565
  };
17526
17566
  await doLoop();
@@ -18467,9 +18507,9 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
18467
18507
  );
18468
18508
  return toWrappedElement(context, inserted);
18469
18509
  };
18470
- } else if (method === "setInteger") {
18510
+ } else if (method === "setValue") {
18471
18511
  return (index, value) => {
18472
- const array2 = ArrayProxy.setIntegerInternal(
18512
+ const array2 = ArrayProxy.setValueInternal(
18473
18513
  context,
18474
18514
  target,
18475
18515
  index,
@@ -18565,6 +18605,14 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
18565
18605
  }
18566
18606
  return Reflect.get(target, method, receiver);
18567
18607
  },
18608
+ set: (target, key, value) => {
18609
+ if (isNumericString(key)) {
18610
+ const index = Number(key);
18611
+ ArrayProxy.setValueInternal(context, target, index, value);
18612
+ return true;
18613
+ }
18614
+ return Reflect.set(target, key, value);
18615
+ },
18568
18616
  deleteProperty: (target, key) => {
18569
18617
  if (logger.isEnabled(LogLevel.Trivial)) {
18570
18618
  logger.trivial(`array[${key}]`);
@@ -18741,9 +18789,9 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
18741
18789
  );
18742
18790
  }
18743
18791
  /**
18744
- * `setIntegerInternal` sets the given integer at the given index.
18792
+ * `setValueInternal` sets the given value at the given index.
18745
18793
  */
18746
- static setIntegerInternal(context, target, index, value) {
18794
+ static setValueInternal(context, target, index, value) {
18747
18795
  const prev = target.get(index);
18748
18796
  if (!prev) {
18749
18797
  throw new YorkieError(
@@ -20584,10 +20632,12 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
20584
20632
  targetOps.push(op);
20585
20633
  }
20586
20634
  }
20587
- targetOps.length && callback({
20588
- ...docEvent,
20589
- value: { ...docEvent.value, operations: targetOps }
20590
- });
20635
+ if (targetOps.length) {
20636
+ callback({
20637
+ ...docEvent,
20638
+ value: { ...docEvent.value, operations: targetOps }
20639
+ });
20640
+ }
20591
20641
  }
20592
20642
  },
20593
20643
  arg3,
@@ -21523,18 +21573,18 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
21523
21573
  setToken
21524
21574
  };
21525
21575
  }
21526
- const name = "@yorkie-js/sdk";
21527
- const version = "0.6.23";
21528
- const pkg = {
21529
- name,
21530
- version
21576
+ const name$1 = "@yorkie-js/sdk";
21577
+ const version$1 = "0.6.24";
21578
+ const pkg$1 = {
21579
+ name: name$1,
21580
+ version: version$1
21531
21581
  };
21532
21582
  function createMetricInterceptor(userAgent) {
21533
21583
  return (next) => async (req) => {
21534
21584
  if (userAgent) {
21535
21585
  req.header.set("x-yorkie-user-agent", userAgent);
21536
21586
  } else {
21537
- req.header.set("x-yorkie-user-agent", pkg.name + "/" + pkg.version);
21587
+ req.header.set("x-yorkie-user-agent", pkg$1.name + "/" + pkg$1.version);
21538
21588
  }
21539
21589
  return await next(req);
21540
21590
  };
@@ -21545,7 +21595,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
21545
21595
  if (serialized === void 0) {
21546
21596
  return false;
21547
21597
  }
21548
- } catch (error) {
21598
+ } catch {
21549
21599
  return false;
21550
21600
  }
21551
21601
  return true;
@@ -22096,7 +22146,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
22096
22146
  * the server and pulls remote changes from the server.
22097
22147
  */
22098
22148
  runSyncLoop() {
22099
- const doLoop = () => {
22149
+ const doLoop = async () => {
22100
22150
  if (!this.isActive()) {
22101
22151
  logger.debug(`[SL] c:"${this.getKey()}" exit sync loop`);
22102
22152
  this.conditions[
@@ -22105,31 +22155,37 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
22105
22155
  ] = false;
22106
22156
  return;
22107
22157
  }
22108
- const syncJobs = [];
22109
- for (const [, attachment] of this.attachmentMap) {
22110
- if (attachment.needRealtimeSync()) {
22111
- attachment.remoteChangeEventReceived = false;
22112
- syncJobs.push(
22113
- this.syncInternal(attachment, attachment.syncMode).catch(
22114
- async (err) => {
22115
- if (err instanceof ConnectError && errorCodeOf(err) === Code.ErrUnauthenticated) {
22116
- attachment.doc.publish([
22117
- {
22118
- type: DocEventType.AuthError,
22119
- value: {
22120
- reason: errorMetadataOf(err).reason,
22121
- method: "PushPull"
22158
+ try {
22159
+ await this.enqueueTask(async () => {
22160
+ const syncs = [];
22161
+ for (const [, attachment] of this.attachmentMap) {
22162
+ if (!attachment.needRealtimeSync()) {
22163
+ continue;
22164
+ }
22165
+ attachment.remoteChangeEventReceived = false;
22166
+ syncs.push(
22167
+ this.syncInternal(attachment, attachment.syncMode).catch(
22168
+ async (err) => {
22169
+ if (err instanceof ConnectError && errorCodeOf(err) === Code.ErrUnauthenticated) {
22170
+ attachment.doc.publish([
22171
+ {
22172
+ type: DocEventType.AuthError,
22173
+ value: {
22174
+ reason: errorMetadataOf(err).reason,
22175
+ method: "PushPull"
22176
+ }
22122
22177
  }
22123
- }
22124
- ]);
22178
+ ]);
22179
+ }
22180
+ throw err;
22125
22181
  }
22126
- throw err;
22127
- }
22128
- )
22129
- );
22130
- }
22131
- }
22132
- Promise.all(syncJobs).then(() => setTimeout(doLoop, this.syncLoopDuration)).catch(async (err) => {
22182
+ )
22183
+ );
22184
+ }
22185
+ await Promise.all(syncs);
22186
+ setTimeout(doLoop, this.syncLoopDuration);
22187
+ });
22188
+ } catch (err) {
22133
22189
  logger.error(`[SL] c:"${this.getKey()}" sync failed:`, err);
22134
22190
  if (await this.handleConnectError(err)) {
22135
22191
  setTimeout(doLoop, this.retrySyncLoopDelay);
@@ -22139,7 +22195,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
22139
22195
  /* SyncLoop */
22140
22196
  ] = false;
22141
22197
  }
22142
- });
22198
+ }
22143
22199
  };
22144
22200
  logger.debug(`[SL] c:"${this.getKey()}" run sync loop`);
22145
22201
  this.conditions[
@@ -22178,6 +22234,18 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
22178
22234
  )
22179
22235
  );
22180
22236
  }
22237
+ if (!this.attachmentMap.has(docKey)) {
22238
+ this.conditions[
22239
+ "WatchLoop"
22240
+ /* WatchLoop */
22241
+ ] = false;
22242
+ return Promise.reject(
22243
+ new YorkieError(
22244
+ Code.ErrDocumentNotAttached,
22245
+ `${docKey} is not attached`
22246
+ )
22247
+ );
22248
+ }
22181
22249
  const ac = new AbortController();
22182
22250
  const stream = this.rpcClient.watchDocument(
22183
22251
  {
@@ -22196,6 +22264,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
22196
22264
  }
22197
22265
  ]);
22198
22266
  logger.info(`[WD] c:"${this.getKey()}" watches d:"${docKey}"`);
22267
+ attachment.remoteChangeEventReceived = true;
22199
22268
  return new Promise((resolve, reject) => {
22200
22269
  const handleStream = async () => {
22201
22270
  try {
@@ -22370,7 +22439,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
22370
22439
  this.processing = true;
22371
22440
  const task = this.taskQueue.shift();
22372
22441
  await task();
22373
- } catch (error) {
22442
+ } catch {
22374
22443
  logger.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`);
22375
22444
  }
22376
22445
  this.processNext();
@@ -22394,6 +22463,12 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
22394
22463
  LongType: CounterType.Long
22395
22464
  };
22396
22465
  }
22466
+ const name = "@yorkie-js/react";
22467
+ const version = "0.6.24";
22468
+ const pkg = {
22469
+ name,
22470
+ version
22471
+ };
22397
22472
  const YorkieContext = react.createContext({
22398
22473
  client: void 0,
22399
22474
  loading: true,
@@ -22441,7 +22516,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
22441
22516
  }) => {
22442
22517
  const clientOpts = react.useMemo(() => {
22443
22518
  return {
22444
- userAgent: pkg$1.name + "/" + pkg$1.version,
22519
+ userAgent: pkg.name + "/" + pkg.version,
22445
22520
  ...opts
22446
22521
  };
22447
22522
  }, [opts.apiKey, opts.rpcAddr]);
@@ -22459,59 +22534,213 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
22459
22534
  error: context.error
22460
22535
  };
22461
22536
  };
22462
- function useYorkieDocument(client, clientLoading, clientError, docKey, initialRoot, initialPresence) {
22463
- const [doc, setDoc] = react.useState();
22464
- const [loading, setLoading] = react.useState(true);
22465
- const [error, setError] = react.useState();
22466
- const [root, setRoot] = react.useState(initialRoot);
22467
- const [presences, setPresences] = react.useState([]);
22468
- const [connection, setConnection] = react.useState(
22469
- StreamConnectionStatus.Disconnected
22537
+ function createStore(initialState) {
22538
+ const subscribers = /* @__PURE__ */ new Set();
22539
+ let currentState = initialState;
22540
+ const notify = () => {
22541
+ subscribers.forEach((callback) => callback(currentState));
22542
+ };
22543
+ const setState = (newState) => {
22544
+ const prevState = currentState;
22545
+ currentState = typeof newState === "function" ? newState(prevState) : newState;
22546
+ if (prevState !== currentState) {
22547
+ notify();
22548
+ }
22549
+ };
22550
+ const subscribe = (callback) => {
22551
+ subscribers.add(callback);
22552
+ return () => subscribers.delete(callback);
22553
+ };
22554
+ const getSnapshot = () => currentState;
22555
+ const destroy = () => {
22556
+ subscribers.clear();
22557
+ };
22558
+ return {
22559
+ subscribe,
22560
+ getSnapshot,
22561
+ setState,
22562
+ destroy
22563
+ };
22564
+ }
22565
+ const createDocumentStore = (initialState) => {
22566
+ return createStore(initialState);
22567
+ };
22568
+ function useSelector(store, selector, equalityFn = Object.is) {
22569
+ const selectorRef = react.useRef(selector);
22570
+ const equalityFnRef = react.useRef(equalityFn);
22571
+ const currentSliceRef = react.useRef(void 0);
22572
+ selectorRef.current = selector;
22573
+ equalityFnRef.current = equalityFn;
22574
+ const getSelection = () => {
22575
+ const state = store.getSnapshot();
22576
+ const nextSlice = selectorRef.current ? selectorRef.current(state) : state;
22577
+ if (currentSliceRef.current !== void 0 && equalityFnRef.current(currentSliceRef.current, nextSlice)) {
22578
+ return currentSliceRef.current;
22579
+ }
22580
+ currentSliceRef.current = nextSlice;
22581
+ return nextSlice;
22582
+ };
22583
+ return react.useSyncExternalStore(store.subscribe, getSelection, getSelection);
22584
+ }
22585
+ function isIterable(obj) {
22586
+ return obj != null && typeof obj[Symbol.iterator] === "function";
22587
+ }
22588
+ function hasIterableEntries(value) {
22589
+ return "entries" in value && typeof value.entries === "function";
22590
+ }
22591
+ function compareEntries(valueA, valueB) {
22592
+ const mapA = valueA instanceof Map ? valueA : new Map(valueA.entries());
22593
+ const mapB = valueB instanceof Map ? valueB : new Map(valueB.entries());
22594
+ if (mapA.size !== mapB.size) {
22595
+ return false;
22596
+ }
22597
+ for (const [key, value] of mapA) {
22598
+ if (!mapB.has(key) || !Object.is(value, mapB.get(key))) {
22599
+ return false;
22600
+ }
22601
+ }
22602
+ return true;
22603
+ }
22604
+ function compareIterables(valueA, valueB) {
22605
+ const iteratorA = valueA[Symbol.iterator]();
22606
+ const iteratorB = valueB[Symbol.iterator]();
22607
+ let nextA = iteratorA.next();
22608
+ let nextB = iteratorB.next();
22609
+ while (!nextA.done && !nextB.done) {
22610
+ if (!Object.is(nextA.value, nextB.value)) {
22611
+ return false;
22612
+ }
22613
+ nextA = iteratorA.next();
22614
+ nextB = iteratorB.next();
22615
+ }
22616
+ return nextA.done === nextB.done;
22617
+ }
22618
+ function comparePlainObjects(valueA, valueB) {
22619
+ const keysA = Object.keys(valueA);
22620
+ const keysB = Object.keys(valueB);
22621
+ if (keysA.length !== keysB.length) {
22622
+ return false;
22623
+ }
22624
+ for (const key of keysA) {
22625
+ if (!Object.prototype.hasOwnProperty.call(valueB, key) || !Object.is(valueA[key], valueB[key])) {
22626
+ return false;
22627
+ }
22628
+ }
22629
+ return true;
22630
+ }
22631
+ function shallowEqual(valueA, valueB) {
22632
+ if (Object.is(valueA, valueB)) {
22633
+ return true;
22634
+ }
22635
+ if (typeof valueA !== "object" || valueA === null || typeof valueB !== "object" || valueB === null) {
22636
+ return false;
22637
+ }
22638
+ if (Object.getPrototypeOf(valueA) !== Object.getPrototypeOf(valueB)) {
22639
+ return false;
22640
+ }
22641
+ const isIterableA = isIterable(valueA);
22642
+ const isIterableB = isIterable(valueB);
22643
+ if (isIterableA !== isIterableB) {
22644
+ return false;
22645
+ }
22646
+ if (isIterableA && isIterableB) {
22647
+ if (hasIterableEntries(valueA) && hasIterableEntries(valueB)) {
22648
+ return compareEntries(valueA, valueB);
22649
+ }
22650
+ return compareIterables(valueA, valueB);
22651
+ }
22652
+ return comparePlainObjects(
22653
+ valueA,
22654
+ valueB
22470
22655
  );
22656
+ }
22657
+ function useYorkieDocument(client, clientLoading, clientError, docKey, initialRoot, initialPresence, documentStore) {
22658
+ const initialRootRef = react.useRef(initialRoot);
22659
+ const initialPresenceRef = react.useRef(initialPresence);
22660
+ const [didMount, setDidMount] = react.useState(false);
22661
+ react.useEffect(() => {
22662
+ setDidMount(true);
22663
+ }, []);
22471
22664
  react.useEffect(() => {
22472
22665
  if (clientError) {
22473
- setLoading(false);
22474
- setError(clientError);
22666
+ documentStore.setState((state) => ({
22667
+ ...state,
22668
+ loading: false,
22669
+ error: clientError
22670
+ }));
22475
22671
  return;
22476
22672
  }
22477
- if (!client || clientLoading) {
22478
- setLoading(true);
22673
+ if (!client || clientLoading || !didMount) {
22674
+ documentStore.setState((state) => ({
22675
+ ...state,
22676
+ loading: true
22677
+ }));
22479
22678
  return;
22480
22679
  }
22481
- setLoading(true);
22482
- setError(void 0);
22680
+ documentStore.setState((state) => ({
22681
+ ...state,
22682
+ loading: true,
22683
+ error: void 0
22684
+ }));
22483
22685
  const newDoc = new Document(docKey);
22484
22686
  const unsubs = [];
22485
22687
  unsubs.push(
22486
22688
  newDoc.subscribe(() => {
22487
- setRoot(newDoc.getRoot());
22689
+ documentStore.setState((state) => ({
22690
+ ...state,
22691
+ root: newDoc.getRoot()
22692
+ }));
22488
22693
  })
22489
22694
  );
22490
22695
  unsubs.push(
22491
22696
  newDoc.subscribe("presence", () => {
22492
- setPresences(newDoc.getPresences());
22697
+ documentStore.setState((state) => ({
22698
+ ...state,
22699
+ presences: newDoc.getPresences()
22700
+ }));
22493
22701
  })
22494
22702
  );
22495
22703
  unsubs.push(
22496
22704
  newDoc.subscribe("connection", (event) => {
22497
- setConnection(event.value);
22705
+ documentStore.setState((state) => ({
22706
+ ...state,
22707
+ connection: event.value
22708
+ }));
22498
22709
  })
22499
22710
  );
22500
22711
  async function attachDocument() {
22501
22712
  try {
22502
22713
  await (client == null ? void 0 : client.attach(newDoc, {
22503
- initialRoot,
22504
- initialPresence
22714
+ initialRoot: initialRootRef.current,
22715
+ initialPresence: initialPresenceRef.current
22716
+ }));
22717
+ const update = (callback) => {
22718
+ try {
22719
+ newDoc.update(callback);
22720
+ } catch (err) {
22721
+ documentStore.setState((state) => ({
22722
+ ...state,
22723
+ error: err instanceof Error ? err : new Error("Failed to update document")
22724
+ }));
22725
+ }
22726
+ };
22727
+ documentStore.setState((state) => ({
22728
+ ...state,
22729
+ doc: newDoc,
22730
+ root: newDoc.getRoot(),
22731
+ presences: newDoc.getPresences(),
22732
+ update
22505
22733
  }));
22506
- setDoc(newDoc);
22507
- setRoot(newDoc.getRoot());
22508
- setPresences(newDoc.getPresences());
22509
22734
  } catch (err) {
22510
- setError(
22511
- err instanceof Error ? err : new Error("Failed to attach document")
22512
- );
22735
+ documentStore.setState((state) => ({
22736
+ ...state,
22737
+ error: err instanceof Error ? err : new Error("Failed to attach document")
22738
+ }));
22513
22739
  } finally {
22514
- setLoading(false);
22740
+ documentStore.setState((state) => ({
22741
+ ...state,
22742
+ loading: false
22743
+ }));
22515
22744
  }
22516
22745
  }
22517
22746
  attachDocument();
@@ -22523,35 +22752,9 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
22523
22752
  unsub();
22524
22753
  }
22525
22754
  };
22526
- }, [client, clientLoading, clientError, docKey]);
22527
- const update = react.useCallback(
22528
- (callback) => {
22529
- if (!doc) {
22530
- return;
22531
- }
22532
- try {
22533
- doc.update(callback);
22534
- } catch (err) {
22535
- setError(
22536
- err instanceof Error ? err : new Error("Failed to update document")
22537
- );
22538
- }
22539
- },
22540
- [doc]
22541
- );
22542
- return {
22543
- doc,
22544
- root,
22545
- presences,
22546
- connection,
22547
- update,
22548
- loading,
22549
- error
22550
- };
22755
+ }, [client, clientLoading, clientError, docKey, documentStore, didMount]);
22551
22756
  }
22552
- const DocumentContext = react.createContext(
22553
- null
22554
- );
22757
+ const DocumentContext = react.createContext(void 0);
22555
22758
  const DocumentProvider = ({
22556
22759
  docKey,
22557
22760
  initialRoot = {},
@@ -22559,98 +22762,117 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
22559
22762
  children
22560
22763
  }) => {
22561
22764
  const { client, loading: clientLoading, error: clientError } = useYorkie();
22562
- const { doc, root, presences, connection, update, loading, error } = useYorkieDocument(
22765
+ const documentStoreRef = react.useRef(void 0);
22766
+ if (!documentStoreRef.current) {
22767
+ documentStoreRef.current = createDocumentStore({
22768
+ doc: void 0,
22769
+ root: initialRoot,
22770
+ presences: [],
22771
+ connection: StreamConnectionStatus.Disconnected,
22772
+ update: () => {
22773
+ },
22774
+ loading: true,
22775
+ error: void 0
22776
+ });
22777
+ }
22778
+ const documentStore = documentStoreRef.current;
22779
+ useYorkieDocument(
22563
22780
  client,
22564
22781
  clientLoading,
22565
22782
  clientError,
22566
22783
  docKey,
22567
22784
  initialRoot,
22568
- initialPresence
22569
- );
22570
- return /* @__PURE__ */ jsxRuntime.jsx(
22571
- DocumentContext.Provider,
22572
- {
22573
- value: {
22574
- doc,
22575
- root,
22576
- presences,
22577
- connection,
22578
- update,
22579
- loading,
22580
- error
22581
- },
22582
- children
22583
- }
22785
+ initialPresence,
22786
+ documentStore
22584
22787
  );
22788
+ return /* @__PURE__ */ jsxRuntime.jsx(DocumentContext.Provider, { value: documentStore, children });
22585
22789
  };
22586
- const useDocument = () => {
22587
- const context = react.useContext(DocumentContext);
22588
- if (!context) {
22790
+ function useDocument() {
22791
+ const documentStore = react.useContext(DocumentContext);
22792
+ if (!documentStore) {
22589
22793
  throw new Error("useDocument must be used within a DocumentProvider");
22590
22794
  }
22591
- return {
22592
- doc: context.doc,
22593
- root: context.root,
22594
- presences: context.presences,
22595
- connection: context.connection,
22596
- update: context.update,
22597
- loading: context.loading,
22598
- error: context.error
22795
+ return useSelector(documentStore);
22796
+ }
22797
+ const createDocumentSelector = () => {
22798
+ return (selector, equalityFn = shallowEqual) => {
22799
+ const documentStore = react.useContext(DocumentContext);
22800
+ if (!documentStore) {
22801
+ throw new Error("useDocument must be used within a DocumentProvider");
22802
+ }
22803
+ return useSelector(documentStore, selector, equalityFn);
22599
22804
  };
22600
22805
  };
22601
22806
  const useRoot = () => {
22602
- const context = react.useContext(DocumentContext);
22603
- if (!context) {
22604
- throw new Error("useRoot must be used within a DocumentProvider");
22605
- }
22606
- return { root: context.root };
22807
+ const documentStore = useDocumentStore("useRoot");
22808
+ const root = useSelector(documentStore, (store) => store.root);
22809
+ return { root };
22607
22810
  };
22608
22811
  const usePresences = () => {
22609
- const context = react.useContext(DocumentContext);
22610
- if (!context) {
22611
- throw new Error("usePresences must be used within a DocumentProvider");
22612
- }
22613
- return context.presences;
22812
+ const documentStore = useDocumentStore("usePresences");
22813
+ return useSelector(documentStore, (store) => store.presences);
22614
22814
  };
22615
22815
  const useConnection = () => {
22616
- const context = react.useContext(DocumentContext);
22617
- if (!context) {
22618
- throw new Error("useConnection must be used within a DocumentProvider");
22816
+ const documentStore = useDocumentStore("useConnection");
22817
+ return useSelector(documentStore, (store) => store.connection);
22818
+ };
22819
+ const useDocumentStore = (hookName) => {
22820
+ const documentStore = react.useContext(DocumentContext);
22821
+ if (!documentStore) {
22822
+ throw new Error(`${hookName} must be used within a DocumentProvider`);
22619
22823
  }
22620
- return context.connection;
22824
+ return documentStore;
22621
22825
  };
22622
22826
  function useYorkieDoc(apiKey, docKey, opts) {
22827
+ const documentStoreRef = react.useRef(void 0);
22828
+ if (!documentStoreRef.current) {
22829
+ documentStoreRef.current = createDocumentStore({
22830
+ doc: void 0,
22831
+ root: (opts == null ? void 0 : opts.initialRoot) ?? {},
22832
+ presences: [],
22833
+ connection: StreamConnectionStatus.Disconnected,
22834
+ update: () => {
22835
+ },
22836
+ loading: true,
22837
+ error: void 0
22838
+ });
22839
+ }
22840
+ const documentStore = documentStoreRef.current;
22623
22841
  const clientOpts = react.useMemo(() => {
22624
22842
  return {
22625
22843
  apiKey,
22626
- userAgent: pkg$1.name + "/" + pkg$1.version,
22844
+ userAgent: pkg.name + "/" + pkg.version,
22627
22845
  ...opts
22628
22846
  };
22629
- }, [apiKey]);
22847
+ }, [apiKey, opts]);
22630
22848
  const {
22631
22849
  client,
22632
22850
  loading: clientLoading,
22633
22851
  error: clientError
22634
22852
  } = useYorkieClient(clientOpts);
22635
- const { root, presences, connection, update, loading, error } = useYorkieDocument(
22853
+ useYorkieDocument(
22636
22854
  client,
22637
22855
  clientLoading,
22638
22856
  clientError,
22639
22857
  docKey,
22640
- opts == null ? void 0 : opts.initialRoot,
22641
- opts == null ? void 0 : opts.initialPresence
22858
+ (opts == null ? void 0 : opts.initialRoot) ?? {},
22859
+ (opts == null ? void 0 : opts.initialPresence) ?? {},
22860
+ documentStore
22642
22861
  );
22862
+ const documentState = useSelector(documentStore);
22643
22863
  return {
22644
- root,
22645
- presences,
22646
- connection,
22647
- update,
22648
- loading,
22649
- error
22864
+ root: documentState.root,
22865
+ presences: documentState.presences,
22866
+ connection: documentState.connection,
22867
+ update: documentState.update,
22868
+ loading: documentState.loading,
22869
+ error: documentState.error
22650
22870
  };
22651
22871
  }
22652
22872
  exports2.DocumentProvider = DocumentProvider;
22653
22873
  exports2.YorkieProvider = YorkieProvider;
22874
+ exports2.createDocumentSelector = createDocumentSelector;
22875
+ exports2.shallowEqual = shallowEqual;
22654
22876
  exports2.useConnection = useConnection;
22655
22877
  exports2.useDocument = useDocument;
22656
22878
  exports2.usePresences = usePresences;