Skip to content

Commit

Permalink
Merge pull request #13777 from j3rem1e/copy-source
Browse files Browse the repository at this point in the history
UI: Fix copy to clipboard for insecure deployments
  • Loading branch information
shilman committed Feb 2, 2021
1 parent 94753dc commit 62f39ed
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 @@ -54,6 +54,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 @@ -151,8 +169,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 62f39ed

Please sign in to comment.