Skip to content

fix: Cut/copy handling in non-editable blocks and empty selections #1427

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 12, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions packages/core/src/api/clipboard/toClipboard/copyExtension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,34 @@ export function selectedFragmentToHTML<
return { clipboardHTML, externalHTML, markdown };
}

const checkIfSelectionInNonEditableBlock = () => {
// Let browser handle event if selection is empty (nothing
// happens).
const selection = window.getSelection();
if (!selection || selection.isCollapsed) {
return true;
}

// Let browser handle event if it's within a non-editable
// "island". This means it's in selectable content within a
// non-editable block. We only need to check one node as it's
// not possible for the browser selection to start in an
// editable block and end in a non-editable one.
let node = selection.focusNode;
while (node) {
if (
node instanceof HTMLElement &&
node.getAttribute("contenteditable") === "false"
) {
return true;
}

node = node.parentElement;
}

return false;
};

const copyToClipboard = <
BSchema extends BlockSchema,
I extends InlineContentSchema,
Expand Down Expand Up @@ -187,11 +215,19 @@ export const createCopyToClipboardExtension = <
props: {
handleDOMEvents: {
copy(view, event) {
if (checkIfSelectionInNonEditableBlock()) {
return true;
}

copyToClipboard(editor, view, event);
// Prevent default PM handler to be called
return true;
},
cut(view, event) {
if (checkIfSelectionInNonEditableBlock()) {
return true;
}

copyToClipboard(editor, view, event);
if (view.editable) {
view.dispatch(view.state.tr.deleteSelection());
Expand Down
Loading