Skip to content
This repository has been archived by the owner on Nov 28, 2022. It is now read-only.

fix: bug where it takes two clicks to get a code snippet to copy #1096

Merged
merged 1 commit into from
Dec 9, 2020
Merged
Show file tree
Hide file tree
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
37 changes: 37 additions & 0 deletions packages/api-explorer/__tests__/CopyCode.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const React = require('react');
const { mount } = require('enzyme');

const CopyCode = require('../src/CopyCode');

const curl = `curl --request POST \
--url http://petstore.swagger.io/v2/pet \
--header 'Authorization: Bearer 123' \
--header 'Content-Type: application/json'`;

// `react-copy-to-clipboard` uses this when copying text to the clipboard so we need to mock it out or else we'll get
// errors in the test.
window.prompt = () => {};

test('should copy a snippet to the clipboard', () => {
const onCopy = jest.fn();

const node = mount(<CopyCode code={curl} onCopy={onCopy} />);

node.find('button').simulate('click');

expect(onCopy).toHaveBeenCalledWith(curl);
});

test('should update the code to copy when supplied with a new snippet', () => {
const onCopy = jest.fn();

const node = mount(<CopyCode code={curl} onCopy={onCopy} />);

node.find('button').simulate('click');
expect(onCopy).toHaveBeenCalledWith(curl);

node.setProps({ code: 'console.log()' });

node.find('button').simulate('click');
expect(onCopy).toHaveBeenCalledWith('console.log()');
});
20 changes: 14 additions & 6 deletions packages/api-explorer/src/CopyCode.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,18 @@ class CopyCode extends React.Component {
this.onCopy = this.onCopy.bind(this);
}

componentDidUpdate(prevProps) {
const code = typeof prevProps.code === 'function' ? prevProps.code() : prevProps.code;

if (code !== this.state.code) {
this.setState({ code });
static getDerivedStateFromProps(props, state) {
const code = typeof props.code === 'function' ? props.code() : props.code;
if (!('code' in state) || code !== state.code) {
return { code };
}

return null;
}

onCopy() {
onCopy(text) {
this.props.onCopy(text);

this.setState({ copied: true });
setTimeout(() => {
this.setState({ copied: false });
Expand All @@ -41,6 +44,11 @@ class CopyCode extends React.Component {

CopyCode.propTypes = {
code: PropTypes.oneOfType([PropTypes.string, PropTypes.func]).isRequired,
onCopy: PropTypes.func,
};

CopyCode.defaultProps = {
onCopy: () => {},
};

module.exports = CopyCode;