UNPKG

1.5 kBJSXView Raw
1const React = require('react');
2const PropTypes = require('prop-types');
3
4const upper = require('@readme/syntax-highlighter/uppercase');
5
6const CodeTabs = props => {
7 const { attributes, children } = props;
8
9 function handleClick({ target }, index) {
10 const $wrap = target.parentElement.parentElement;
11 const $open = [].slice.call($wrap.querySelectorAll('.CodeTabs_active'));
12 $open.forEach(el => el.classList.remove('CodeTabs_active'));
13 $wrap.classList.remove('CodeTabs_initial');
14
15 const codeblocks = $wrap.querySelectorAll('pre');
16 codeblocks[index].classList.add('CodeTabs_active');
17
18 target.classList.add('CodeTabs_active');
19 }
20
21 return (
22 // eslint-disable-next-line react/jsx-props-no-spreading
23 <div {...attributes} className="CodeTabs CodeTabs_initial">
24 <div className="CodeTabs-toolbar">
25 {children.map(({ props: pre }, i) => {
26 const { meta, lang } = pre.children[0].props;
27 /* istanbul ignore next */
28 return (
29 <button key={i} onClick={e => handleClick(e, i)} type="button">
30 {meta || `${!lang ? 'Text' : upper(lang)}`}
31 </button>
32 );
33 })}
34 </div>
35 <div className="CodeTabs-inner">{children}</div>
36 </div>
37 );
38};
39
40CodeTabs.propTypes = {
41 attributes: PropTypes.shape({}),
42 children: PropTypes.arrayOf(PropTypes.any).isRequired,
43};
44
45CodeTabs.defaultProps = {
46 attributes: null,
47};
48
49module.exports = (/* sanitizeSchema */) => {
50 return CodeTabs;
51};