|
| 1 | +import React from 'react'; |
| 2 | +import Tabs from 'react-responsive-tabs'; |
| 3 | + |
| 4 | +export default class CodeTabsWithCopy extends React.Component { |
| 5 | + constructor(props) { |
| 6 | + super(props); |
| 7 | + this.state = { |
| 8 | + items: this._getTabs(), |
| 9 | + selectedTabKey: 0, |
| 10 | + copied: false |
| 11 | + }; |
| 12 | + |
| 13 | + // bind event handlers here |
| 14 | + this.onTabChange = this.onTabChange.bind(this); |
| 15 | + this.copyCode = this.copyCode.bind(this); |
| 16 | + } |
| 17 | + |
| 18 | + _getTabs() { |
| 19 | + return this.props.schema.map((s, i) => ({ |
| 20 | + key: i, |
| 21 | + tabClassName: 'tab', |
| 22 | + panelClassName: 'panel', |
| 23 | + title: s.name, |
| 24 | + getContent: () => s.content |
| 25 | + })); |
| 26 | + } |
| 27 | + |
| 28 | + onTabChange(index) { |
| 29 | + this.setState({ selectedTabKey: index, copied: false }); |
| 30 | + } |
| 31 | + |
| 32 | + copyCode() { |
| 33 | + const { selectedTabKey, items } = this.state; |
| 34 | + const codeNode = items[selectedTabKey].getContent(); |
| 35 | + |
| 36 | + let textToCopy = ''; |
| 37 | + |
| 38 | + try { |
| 39 | + if ( |
| 40 | + codeNode && |
| 41 | + codeNode.props && |
| 42 | + codeNode.props.children && |
| 43 | + codeNode.props.children.props && |
| 44 | + typeof codeNode.props.children.props.children === 'string' |
| 45 | + ) { |
| 46 | + textToCopy = codeNode.props.children.props.children; |
| 47 | + } else if ( |
| 48 | + codeNode && |
| 49 | + codeNode.props && |
| 50 | + typeof codeNode.props.children === 'string' |
| 51 | + ) { |
| 52 | + textToCopy = codeNode.props.children; |
| 53 | + } |
| 54 | + } catch (e) { |
| 55 | + textToCopy = ''; |
| 56 | + } |
| 57 | + |
| 58 | + if (textToCopy) { |
| 59 | + navigator.clipboard.writeText(textToCopy); |
| 60 | + this.setState({ copied: true }); |
| 61 | + setTimeout(() => this.setState({ copied: false }), 2000); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + render() { |
| 66 | + const { items, selectedTabKey, copied } = this.state; |
| 67 | + |
| 68 | + return ( |
| 69 | + <div style={{ position: 'relative' }}> |
| 70 | + <Tabs |
| 71 | + transform={false} |
| 72 | + items={items} |
| 73 | + showInkBar={true} |
| 74 | + selectedTabKey={selectedTabKey} |
| 75 | + onChange={this.onTabChange} |
| 76 | + /> |
| 77 | + <button |
| 78 | + onClick={this.copyCode} |
| 79 | + className="copy-btn" |
| 80 | + style={{ top: '62px' }} |
| 81 | + aria-label="Copy code" |
| 82 | + > |
| 83 | + {copied ? 'Copied!' : 'Copy'} |
| 84 | + </button> |
| 85 | + </div> |
| 86 | + ); |
| 87 | + } |
| 88 | +} |
0 commit comments