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

UI: Fix copy to clipboard for insecure deployments #13777

Merged
merged 1 commit into from
Feb 1, 2021
Merged
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
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