Skip to content

Commit

Permalink
fix(slate): fix insert/remove element edgecase bug in slate (#5926)
Browse files Browse the repository at this point in the history
  • Loading branch information
razvanMiu authored Mar 31, 2024
1 parent ce930b6 commit 77a7a28
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
1 change: 1 addition & 0 deletions packages/volto-slate/news/5928.bugfix
Original file line number Diff line number Diff line change
@@ -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
29 changes: 24 additions & 5 deletions packages/volto-slate/src/elementEditor/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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 };
Expand Down

0 comments on commit 77a7a28

Please sign in to comment.