From 168e9b8beaefde81fdd83e071534802ffa13df42 Mon Sep 17 00:00:00 2001 From: devleejb Date: Sun, 3 Nov 2024 15:40:50 +0900 Subject: [PATCH] Synchronize cursor when the snapshot event is published --- frontend/src/utils/yorkie/yorkieSync.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/frontend/src/utils/yorkie/yorkieSync.ts b/frontend/src/utils/yorkie/yorkieSync.ts index eec7e022..f3ca8a14 100644 --- a/frontend/src/utils/yorkie/yorkieSync.ts +++ b/frontend/src/utils/yorkie/yorkieSync.ts @@ -53,10 +53,22 @@ class YorkieSyncPluginValue implements cmView.PluginValue { // The text is replaced to snapshot and must be re-synced. const text = this._doc.getRoot().content; - view.dispatch({ + const selection = this._doc.getMyPresence().selection; + const transactionSpec: cmState.TransactionSpec = { changes: { from: 0, to: view.state.doc.length, insert: text.toString() }, annotations: [cmState.Transaction.remote.of(true)], - }); + }; + + if (selection) { + // Restore the cursor position when the text is replaced. + const cursor = text.posRangeToIndexRange(selection); + transactionSpec["selection"] = { + anchor: cursor[0], + head: cursor[1], + }; + } + + view.dispatch(transactionSpec); }); this._doc.update((root) => {