|
| 1 | +import React, { ReactNode, useMemo } from 'react' |
| 2 | +import { Code, CodeProps } from '@geist-ui/core' |
| 3 | + |
| 4 | +export type HybridCodeProps = CodeProps |
| 5 | +export const FILE_NAME_PREFIX = '// NAME:' |
| 6 | +type HybridCodeChildrenAndName = { |
| 7 | + children: ReactNode | undefined |
| 8 | + name?: string | undefined |
| 9 | +} |
| 10 | + |
| 11 | +const extractFileName = ( |
| 12 | + children: ReactNode | undefined, |
| 13 | + stopDeep: boolean = false, |
| 14 | +): HybridCodeChildrenAndName => { |
| 15 | + if (!children) return { children } |
| 16 | + let name: string | undefined = undefined |
| 17 | + const next = React.Children.map(children, child => { |
| 18 | + if (name) return child |
| 19 | + if (!React.isValidElement(child)) return null |
| 20 | + const grandson = child.props?.children |
| 21 | + if (typeof grandson === 'string' && grandson?.startsWith(FILE_NAME_PREFIX)) { |
| 22 | + name = grandson |
| 23 | + return null |
| 24 | + } |
| 25 | + if (!Array.isArray(grandson) || stopDeep) return child |
| 26 | + |
| 27 | + const { children: puredGrandson, name: puredName } = extractFileName( |
| 28 | + child.props?.children, |
| 29 | + true, |
| 30 | + ) |
| 31 | + if (!puredName) return child |
| 32 | + |
| 33 | + name = puredName |
| 34 | + const withoutSpaceAndNull = React.Children.toArray(puredGrandson).filter( |
| 35 | + (r, index) => { |
| 36 | + if (index === 0 && r === '\n') return false |
| 37 | + return !!r |
| 38 | + }, |
| 39 | + ) |
| 40 | + return React.cloneElement(child, { |
| 41 | + children: withoutSpaceAndNull, |
| 42 | + }) |
| 43 | + }) |
| 44 | + return { |
| 45 | + children: next, |
| 46 | + name, |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +const HybridCode: React.FC<HybridCodeProps> = ({ children }) => { |
| 51 | + const { children: withoutNameChildren, name } = useMemo<HybridCodeChildrenAndName>( |
| 52 | + () => extractFileName(children), |
| 53 | + [children], |
| 54 | + ) |
| 55 | + const withoutPrefixName = useMemo(() => { |
| 56 | + if (!name) return name |
| 57 | + return name.replace(FILE_NAME_PREFIX, '') |
| 58 | + }, [name]) |
| 59 | + |
| 60 | + return ( |
| 61 | + <Code block name={withoutPrefixName}> |
| 62 | + {withoutNameChildren} |
| 63 | + </Code> |
| 64 | + ) |
| 65 | +} |
| 66 | + |
| 67 | +export default HybridCode |
0 commit comments