From 77a7a280f75d7cfcb4b8efb3b4aca9629732d730 Mon Sep 17 00:00:00 2001 From: Miu Razvan Date: Sun, 31 Mar 2024 14:43:42 +0300 Subject: [PATCH] fix(slate): fix insert/remove element edgecase bug in slate (#5926) --- packages/volto-slate/news/5928.bugfix | 1 + .../volto-slate/src/elementEditor/utils.js | 29 +++++++++++++++---- 2 files changed, 25 insertions(+), 5 deletions(-) create mode 100644 packages/volto-slate/news/5928.bugfix diff --git a/packages/volto-slate/news/5928.bugfix b/packages/volto-slate/news/5928.bugfix new file mode 100644 index 0000000000..14399fbc91 --- /dev/null +++ b/packages/volto-slate/news/5928.bugfix @@ -0,0 +1 @@ +Fix removing an element in slate when cursor is at the end of the element to be removed; Fix losing selection when adding an element. @razvanMiu \ No newline at end of file diff --git a/packages/volto-slate/src/elementEditor/utils.js b/packages/volto-slate/src/elementEditor/utils.js index 9f0a76c06e..8f0badaeb6 100644 --- a/packages/volto-slate/src/elementEditor/utils.js +++ b/packages/volto-slate/src/elementEditor/utils.js @@ -45,13 +45,16 @@ export const _insertElement = (elementType) => (editor, data) => { match: (node) => { return Node.string(node).length !== 0; }, - }, //, + }, ); } const sel = JSON.parse(JSON.stringify(rangeRef.current)); - Transforms.select(editor, sel); - editor.setSavedSelection(sel); + + setTimeout(() => { + Transforms.select(editor, sel); + editor.setSavedSelection(sel); + }); return true; } @@ -69,10 +72,26 @@ export const _insertElement = (elementType) => (editor, data) => { * @returns {Object|null} - current node */ export const _unwrapElement = (elementType) => (editor) => { - const [link] = Editor.nodes(editor, { - at: editor.selection, + const selection = editor.selection || editor.getSavedSelection(); + let [link] = Editor.nodes(editor, { + at: selection, match: (node) => node?.type === elementType, }); + const isAtStart = + selection.anchor.offset === 0 && selection.focus.offset === 0; + + if (!link && !isAtStart) return false; + + if (!link) { + try { + link = Editor.previous(editor, { + at: selection.anchor.path, + }); + } catch (ex) { + link = []; + } + } + const [, path] = link; const [start, end] = Editor.edges(editor, path); const range = { anchor: start, focus: end };