Skip to content

Commit

Permalink
Clipboard bugfix (#70)
Browse files Browse the repository at this point in the history
Brings over bug fix for table clipboard issue that was fixed
on the internal repo.
  • Loading branch information
themadcreator authored Nov 10, 2016
1 parent 18a5e73 commit 352e5ea
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions packages/table/src/common/clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const Clipboard = {
* See `Clipboard.copy`
*/
copyCells(cells: string[][]) {
const table = document.createElement("tbody");
const table = document.createElement("table");
Clipboard.applySelectableStyles(table);
for (const row of cells) {
const tr = table.appendChild(document.createElement("tr"));
Expand All @@ -40,7 +40,8 @@ export const Clipboard = {
}
}

return Clipboard.copyElement(table);
const tsv = cells.map((row) => row.join("\t")).join("\n");
return Clipboard.copyElement(table, tsv);
},

/**
Expand All @@ -54,13 +55,19 @@ export const Clipboard = {
Clipboard.applySelectableStyles(text);
text.value = value;

return Clipboard.copyElement(text);
return Clipboard.copyElement(text, value);
},

/**
* Copies the element and its children to the clipboard. Returns a boolean
* indicating whether the copy succeeded.
*
* If a plaintext argument is supplied, we add both the text/html and
* text/plain mime types to the clipboard. This preserves the built in
* semantics of copying elements to the clipboard while allowing custom
* plaintext output for programs that can't cope with HTML data in the
* clipboard.
*
* Verified on Firefox 47, Chrome 51.
*
* Note: Sometimes the copy does not succeed. Presumably, in order to
Expand All @@ -69,7 +76,7 @@ export const Clipboard = {
* inconsistent limit at about 300KB or 40,000 cells. Depending on the on
* the content of cells, your limits may vary.
*/
copyElement(elem: HTMLElement) {
copyElement(elem: HTMLElement, plaintext?: string) {
if (!Clipboard.isCopySupported()) {
return false;
}
Expand All @@ -78,6 +85,20 @@ export const Clipboard = {
document.body.appendChild(elem);
try {
window.getSelection().selectAllChildren(elem);

if (plaintext != null) {
// add plaintext fallback
// http://stackoverflow.com/questions/23211018/copy-to-clipboard-with-jquery-js-in-chrome
elem.addEventListener("copy", (e: UIEvent) => {
e.preventDefault();
const clipboardData = (e as any).clipboardData || (window as any).clipboardData;
if (clipboardData != null) {
clipboardData.setData("text/html", elem.outerHTML);
clipboardData.setData("text/plain", plaintext);
}
});
}

return document.execCommand("copy");
} catch (err) {
return false;
Expand Down

1 comment on commit 352e5ea

@blueprint-bot
Copy link

Choose a reason for hiding this comment

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

Clipboard bugfix (#70)

Preview: docs Coverage: core | datetime

Please sign in to comment.