Skip to content

Commit

Permalink
Merge pull request #198 from storybookjs/fix-clipboard-snippets
Browse files Browse the repository at this point in the history
Add callback option for Clipboard component
  • Loading branch information
kylesuss authored Aug 10, 2020
2 parents 2052946 + b246055 commit 0815ebc
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 10 deletions.
8 changes: 6 additions & 2 deletions src/components/Clipboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const Tooltip = styled(WithTooltip)`
export const Clipboard = ({
children,
toCopy,
getCopyContent,
copyOptions,
resetTimeout,
renderCopiedTooltip,
Expand All @@ -35,7 +36,7 @@ export const Clipboard = ({
}, [copied]);

const copy = () => {
if (copyToClipboard(toCopy, copyOptions)) {
if (copyToClipboard(toCopy || getCopyContent(), copyOptions)) {
setCopied(true);
}
};
Expand All @@ -54,7 +55,8 @@ export const Clipboard = ({

Clipboard.propTypes = {
children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]).isRequired,
toCopy: PropTypes.string.isRequired,
toCopy: PropTypes.string,
getCopyContent: PropTypes.func,
copyOptions: PropTypes.object, // eslint-disable-line
renderCopiedTooltip: PropTypes.func,
renderUncopiedTooltip: PropTypes.func,
Expand All @@ -66,4 +68,6 @@ Clipboard.defaultProps = {
renderCopiedTooltip: () => null,
renderUncopiedTooltip: () => null,
resetTimeout: 3000,
toCopy: undefined,
getCopyContent: () => undefined,
};
4 changes: 4 additions & 0 deletions src/components/Clipboard.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ export default {

export const Default = () => <Clipboard toCopy="linky">Click to copy</Clipboard>;

export const Callback = () => (
<Clipboard getCopyContent={() => 'linky from callback'}>Click to copy</Clipboard>
);

export const Tooltips = () => (
<Clipboard
toCopy="linky"
Expand Down
12 changes: 4 additions & 8 deletions src/components/CodeSnippets.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,17 @@ const StyledClipboard = styled(Clipboard)`

function Snippet({ snippet }) {
const { Snippet: SnippetComponent } = snippet;
const [toCopy, setToCopy] = useState('');
const snippetRef = useRef();

useEffect(() => {
if (snippetRef.current) {
setToCopy(snippetRef.current.textContent);
}
}, [snippetRef.current]);
const getCopyContent = () => snippetRef.current && snippetRef.current.textContent;

return (
<StyledHighlight withHTMLChildren={false}>
<div ref={snippetRef}>
<SnippetComponent />
</div>
<StyledClipboard toCopy={toCopy}>{(copied) => (copied ? 'Copied' : 'Copy')}</StyledClipboard>
<StyledClipboard getCopyContent={getCopyContent}>
{(copied) => (copied ? 'Copied' : 'Copy')}
</StyledClipboard>
</StyledHighlight>
);
}
Expand Down

0 comments on commit 0815ebc

Please sign in to comment.