diff options
author | Samy Pesse <samypesse@gmail.com> | 2016-10-10 12:45:18 +0200 |
---|---|---|
committer | Samy Pesse <samypesse@gmail.com> | 2016-10-10 12:45:18 +0200 |
commit | 66231f8b7f5b74efb15e2c6aa34af796e68b58c8 (patch) | |
tree | 206ed8cfeb55a270cade81647e19e2092f3d1a0c /packages/gitbook-plugin-copy-code/src | |
parent | 7037ac55bd444441fcacefa1224a6c36e3ecd7a6 (diff) | |
download | gitbook-66231f8b7f5b74efb15e2c6aa34af796e68b58c8.zip gitbook-66231f8b7f5b74efb15e2c6aa34af796e68b58c8.tar.gz gitbook-66231f8b7f5b74efb15e2c6aa34af796e68b58c8.tar.bz2 |
Add plugin "copy-code" to default
Diffstat (limited to 'packages/gitbook-plugin-copy-code/src')
-rw-r--r-- | packages/gitbook-plugin-copy-code/src/index.js | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/packages/gitbook-plugin-copy-code/src/index.js b/packages/gitbook-plugin-copy-code/src/index.js new file mode 100644 index 0000000..cfbe1b1 --- /dev/null +++ b/packages/gitbook-plugin-copy-code/src/index.js @@ -0,0 +1,54 @@ +const copy = require('copy-to-clipboard'); +const GitBook = require('gitbook-core'); +const { React } = GitBook; + +/** + * Get children as text + * @param {React.Children} children + * @return {String} + */ +function getChildrenToText(children) { + return React.Children.map(children, child => { + if (typeof child === 'string') { + return child; + } else { + return child.props.children ? + getChildrenToText(child.props.children) : ''; + } + }).join(''); +} + +const CodeBlockWithCopy = React.createClass({ + propTypes: { + children: React.PropTypes.node + }, + + onClick(event) { + const { children } = this.props; + + event.preventDefault(); + event.stopPropagation(); + + const text = getChildrenToText(children); + copy(text); + }, + + render() { + const { children } = this.props; + + return ( + <div className="CodeBlockWithCopy-Container"> + <GitBook.ImportCSS href="gitbook/copy-code/button.css" /> + + {children} + <span className="CodeBlockWithCopy-Button" onClick={this.onClick}>Copy</span> + </div> + ); + } +}); + +module.exports = GitBook.createPlugin({ + activate: (dispatch, getState, { Components }) => { + dispatch(Components.registerComponent(CodeBlockWithCopy, { role: 'html:pre' })); + } +}); |