From a501e0bcd65703d37d3a675ce93e4f2e3ebbf19f Mon Sep 17 00:00:00 2001 From: gvergnaud Date: Thu, 21 Nov 2024 15:00:09 -0500 Subject: [PATCH] fix: avoid throwing an exception if the current selection no longer makes sense when initializing ySyncPlugin --- src/plugins/sync-plugin.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/plugins/sync-plugin.js b/src/plugins/sync-plugin.js index 772631c..b548aef 100644 --- a/src/plugins/sync-plugin.js +++ b/src/plugins/sync-plugin.js @@ -409,7 +409,15 @@ export class ProsemirrorBinding { new PModel.Slice(PModel.Fragment.from(fragmentContent), 0, 0) ) if (sel) { - tr.setSelection(TextSelection.create(tr.doc, sel.anchor, sel.head)) + /** + * If the Prosemirror document we just created from this.type is + * smaller than the previous document, the selection might be + * out of bound, which would make Prosemirror throw an error. + */ + const clampedAnchor = math.min(math.max(sel.anchor, 0), tr.doc.content.size) + const clampedHead = math.min(math.max(sel.head, 0), tr.doc.content.size) + + tr.setSelection(TextSelection.create(tr.doc, clampedAnchor, clampedHead)) } this.prosemirrorView.dispatch( tr.setMeta(ySyncPluginKey, { isChangeOrigin: true, binding: this })