import { FC, MouseEventHandler, ReactNode } from 'react' import ReactMarkdown, { Components } from 'react-markdown' import remarkGfm from 'remark-gfm' import type { Markdown, Code, AnyEvent } from '../models' import { useClassName } from '../hooks/className' import { useFireEvent } from '../events' import { useCustomRender } from '../hooks/config' import { CodeComp } from './Code' const MarkdownComp: FC = (props) => { const { text, codeStyle } = props const components: Components = { a({ children, href }) { return {children} }, code({ children, className }) { return ( {children} ) }, } return ( {text} ) } export default MarkdownComp const MarkdownA: FC<{ children: ReactNode; href?: string }> = ({ children, href }) => { const { fireEvent } = useFireEvent() let onClick: AnyEvent | undefined let preventDefault = true if (!href) { href = '#' } else if (href === '!back') { href = '#' onClick = { type: 'back' } } else if (href.startsWith('!')) { onClick = { type: 'page', name: href.slice(1) } href = '#' } else if (href.startsWith('#')) { preventDefault = href.length === 1 } else { onClick = { type: 'go-to', url: href } } const clickHandler: MouseEventHandler = (e) => { if (preventDefault) { e.preventDefault() fireEvent(onClick) } } return ( {children} ) } interface MarkdownCodeProps { children: ReactNode className?: string codeStyle?: string } const MarkdownCode: FC = ({ children, className, codeStyle }) => { const match = /language-(\w+)/.exec(className || '') if (match) { return ( {children} ) } else { return {children} } } interface MarkdownCodeHighlightProps { children: ReactNode language?: string codeStyle?: string } const MarkdownCodeHighlight: FC = ({ children, codeStyle, language }) => { const codeProps: Code = { type: 'Code', text: String(children).replace(/\n$/, ''), language, codeStyle, } const CustomRenderComp = useCustomRender(codeProps) if (CustomRenderComp) { return } else { return } }