Skip to content
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

Make copy command work inside Modal HTML Dialogs #137

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
29 changes: 26 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,26 @@ function format(message) {
return message.replace(/#{\s*key\s*}/g, copyKey);
}

function findOpenedModalDialog() {
/**
* "Modal" dialog is an html <dialog> with "open" property set to `true`
* and an unset "open" attribute:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog#open
*/
let element = document.activeElement;
while (element) {
if (
element.tagName === 'DIALOG' &&
element.open &&
!element.getAttribute('open')
) {
return element;
}
element = element.parentElement;
}
return null;
}

function copy(text, options) {
var debug,
message,
Expand All @@ -27,6 +47,7 @@ function copy(text, options) {
options = {};
}
debug = options.debug || false;
let root = null;
try {
reselectPrevious = deselectCurrent();

Expand Down Expand Up @@ -71,9 +92,11 @@ function copy(text, options) {
}
});

document.body.appendChild(mark);
root = findOpenedModalDialog() || document.body;
root.appendChild(mark);

range.selectNodeContents(mark);
selection.removeAllRanges();
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps this line is not needed since toggle-selection package is used.

selection.addRange(range);

var successful = document.execCommand("copy");
Expand Down Expand Up @@ -103,8 +126,8 @@ function copy(text, options) {
}
}

if (mark) {
document.body.removeChild(mark);
if (mark && root) {
root.removeChild(mark);
}
reselectPrevious();
}
Expand Down