|
| 1 | +import React from 'react'; |
| 2 | +import Editor from 'react-simple-code-editor'; |
| 3 | +import CopyToClipboard from 'react-copy-to-clipboard'; |
| 4 | +import useToggle from 'react-use/esm/useToggle'; |
| 5 | +import { Divider, Typography, Icon, Tooltip, message } from 'antd'; |
| 6 | +import { highlight, languages } from 'prismjs/components/prism-core'; |
| 7 | + |
| 8 | +import 'prismjs/components/prism-clike'; |
| 9 | +import 'prismjs/components/prism-javascript'; |
| 10 | +import 'prismjs/components/prism-markup'; |
| 11 | +import './index.less'; |
| 12 | + |
| 13 | +require('prismjs/components/prism-jsx'); |
| 14 | + |
| 15 | +const { Text } = Typography; |
| 16 | +interface Props { |
| 17 | + code: string; |
| 18 | + title?: React.ReactNode; |
| 19 | + desc?: React.ReactNode; |
| 20 | +} |
| 21 | + |
| 22 | +export const HappyBox: React.FC<Props> = ({ code, title, desc, children }) => { |
| 23 | + const [isEditVisible, toggleEditVisible] = useToggle(false); |
| 24 | + |
| 25 | + return ( |
| 26 | + <div className="code-box"> |
| 27 | + <section className="code-box-demo"> {children}</section> |
| 28 | + <section className="code-box-meta"> |
| 29 | + <Divider orientation="left">{title || '示例'}</Divider> |
| 30 | + <div className="code-box-description"> |
| 31 | + <Text>{desc || '暂无描述'}</Text> |
| 32 | + </div> |
| 33 | + <Divider dashed></Divider> |
| 34 | + <div className="code-box-action"> |
| 35 | + <Tooltip placement="top" title="复制代码"> |
| 36 | + <CopyToClipboard text={code} onCopy={() => message.success('复制成功')}> |
| 37 | + <Icon type="copy" /> |
| 38 | + </CopyToClipboard> |
| 39 | + </Tooltip> |
| 40 | + <Tooltip placement="top" title={isEditVisible ? '收起代码' : '显示代码'}> |
| 41 | + <Icon type="code" onClick={toggleEditVisible} /> |
| 42 | + </Tooltip> |
| 43 | + </div> |
| 44 | + </section> |
| 45 | + {renderEditor()} |
| 46 | + </div> |
| 47 | + ); |
| 48 | + |
| 49 | + function renderEditor() { |
| 50 | + if (!isEditVisible) return null; |
| 51 | + return ( |
| 52 | + <div className="container_editor_area"> |
| 53 | + <Editor |
| 54 | + readOnly |
| 55 | + value={code} |
| 56 | + onValueChange={() => {}} |
| 57 | + highlight={code => highlight(code, languages.jsx)} |
| 58 | + padding={10} |
| 59 | + className="container__editor" |
| 60 | + style={{ |
| 61 | + fontFamily: '"Fira code", "Fira Mono", monospace', |
| 62 | + fontSize: 14, |
| 63 | + }} |
| 64 | + /> |
| 65 | + </div> |
| 66 | + ); |
| 67 | + } |
| 68 | +}; |
| 69 | + |
| 70 | +export default HappyBox; |
0 commit comments