Skip to content

Commit

Permalink
Refactor copy to clipboard
Browse files Browse the repository at this point in the history
And ensure we `remove` the temporary note for copying is used
  • Loading branch information
kizza committed Feb 24, 2024
1 parent 380325d commit dcd8118
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 21 deletions.
30 changes: 30 additions & 0 deletions src/clipboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export const copyToClipboard = (text: string) => {
if (!copyViaWriteText(text) && !copyViaExecCommand(text)) {
console.error('Could not copy to clipboard')
}
}

const copyViaWriteText = (text: string) :boolean => {
try {
navigator.clipboard.writeText(text);
return true;
} catch(err) {
console.info('Failed to copy via writeText: ', err);
return false
}
}

const copyViaExecCommand = (text: string) :boolean =>
withSelectedText(text, () => document.execCommand('copy'))

const withSelectedText = (text: string, fn: () => boolean) => {
const input = document.createElement('textarea');
document.body.appendChild(input);
input.value = text;
input.focus();
input.select();

const result = fn();
input.remove();
return result;
}
23 changes: 2 additions & 21 deletions src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import './elements/chip';
import './elements/entities-picker';
import './elements/palette';
import { ChipEvent, Colour, MagicHomePartyConfig } from './types';
import { copyToClipboard } from './clipboard';

const { values } = Object;

Expand Down Expand Up @@ -80,27 +81,7 @@ export class MagicHomePartyEditor extends LitElement {

private _copyToClipboard() {
const colours = this.selectedColours.map(colour => ` - [${colour.join(', ')}]`);

try {
navigator.clipboard.writeText(colours.join('\n'));
} catch(err) {
console.info('Failed to copy: ', err);
this._copyToClipboardAlt()
}
}

private _copyToClipboardAlt() {
const colours = this.selectedColours.map(colour => ` - [${colour.join(', ')}]`);
const input = document.createElement('textarea');
document.body.appendChild(input);
input.value = colours.join('\n');
input.focus();
input.select();

const isSuccessful = document.execCommand('copy');
if (!isSuccessful) {
console.error('Failed to copy text again');
}
copyToClipboard(colours.join('\n'))
}

private _setLight = (colour: Colour) =>
Expand Down

0 comments on commit dcd8118

Please sign in to comment.