prettier/website/playground/buttons.js

58 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-04-12 19:27:34 +03:00
import React from "react";
2018-04-12 21:09:04 +03:00
import ClipboardJS from "clipboard";
2018-04-12 19:27:34 +03:00
2018-04-12 21:09:04 +03:00
export const Button = React.forwardRef((props, ref) => (
<button type="button" className="btn" ref={ref} {...props} />
));
2018-04-12 19:27:34 +03:00
export function LinkButton(props) {
2018-04-12 21:09:04 +03:00
return <a className="btn" {...props} />;
}
export class ClipboardButton extends React.Component {
constructor() {
super();
this.state = { showTooltip: false, tooltipText: "" };
this.timer = null;
this.ref = React.createRef();
}
componentDidMount() {
this.clipboard = new ClipboardJS(this.ref.current, {
2018-04-17 19:40:55 +03:00
text: () => {
const { copy } = this.props;
return typeof copy === "function" ? copy() : copy;
}
2018-04-12 21:09:04 +03:00
});
this.clipboard.on("success", () => this.showTooltip("Copied!"));
this.clipboard.on("error", () => this.showTooltip("Press ctrl+c to copy"));
}
showTooltip(text) {
this.setState({ showTooltip: true, tooltipText: text }, () => {
2018-04-17 23:29:44 +03:00
if (this.timer) {
clearTimeout(this.timer);
}
2018-04-12 21:09:04 +03:00
this.timer = setTimeout(() => {
this.timer = null;
this.setState({ showTooltip: false });
}, 2000);
});
}
render() {
const rest = Object.assign({}, this.props);
delete rest.children;
2018-04-19 20:46:29 +03:00
delete rest.copy;
2018-04-12 21:09:04 +03:00
return (
<Button ref={this.ref} {...rest}>
{this.state.showTooltip ? (
<span className="tooltip">{this.state.tooltipText}</span>
) : null}
{this.props.children}
</Button>
);
}
2018-04-12 19:27:34 +03:00
}