Skip to content

Commit

Permalink
Uses execCommand if navigator.clipboard is not available
Browse files Browse the repository at this point in the history
  • Loading branch information
j3rem1e committed Jan 30, 2021
1 parent 14a7f4b commit 9b03384
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions lib/components/src/syntaxhighlighter/syntaxhighlighter.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { ComponentProps, FunctionComponent, MouseEvent, useState } from 'react';
import { logger } from '@storybook/client-logger';
import { styled } from '@storybook/theming';
import { navigator, window } from 'global';
import { navigator, document, window } from 'global';
import memoize from 'memoizerific';

// @ts-ignore
Expand Down Expand Up @@ -52,6 +52,24 @@ const themedSyntax = memoize(2)((theme) =>
Object.entries(theme.code || {}).reduce((acc, [key, val]) => ({ ...acc, [`* .${key}`]: val }), {})
);

let copyToClipboard: (text: string) => Promise<void>;

if (navigator.clipboard) {
copyToClipboard = (text: string) => navigator.clipboard.writeText(text);
} else {
copyToClipboard = async (text: string) => {
const tmp = document.createElement('TEXTAREA');
const focus = document.activeElement;

tmp.value = text;

document.body.appendChild(tmp);
tmp.select();
document.execCommand('copy');
document.body.removeChild(tmp);
focus.focus();
};
}
export interface WrapperProps {
bordered?: boolean;
padded?: boolean;
Expand Down Expand Up @@ -135,8 +153,7 @@ export const SyntaxHighlighter: FunctionComponent<Props> = ({
const onClick = (e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault();

navigator.clipboard
.writeText(highlightableCode)
copyToClipboard(highlightableCode)
.then(() => {
setCopied(true);
window.setTimeout(() => setCopied(false), 1500);
Expand Down

0 comments on commit 9b03384

Please sign in to comment.