forked from web-infra-dev/rspress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpre.tsx
58 lines (52 loc) · 1.41 KB
/
pre.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import type { CodeProps } from './code';
import clsx from '../../../utils/tailwind';
const DEFAULT_LANGUAGE_CLASS = 'language-bash';
export interface PreProps {
children: React.ReactElement[] | React.ReactElement;
className?: string;
}
export function parseTitleFromMeta(meta: string): string {
if (!meta) {
return '';
}
let result = meta;
const highlightReg = /{[\d,-]*}/i;
const highlightMeta = highlightReg.exec(meta)?.[0];
if (highlightMeta) {
result = meta.replace(highlightReg, '').trim();
}
result = result.split('=')[1] ?? '';
return result?.replace(/["'`]/g, '');
}
const renderChildren = (children: React.ReactElement) => {
const { className, meta, ...restProps } = children.props as CodeProps;
const codeTitle = parseTitleFromMeta(meta);
return (
<>
{codeTitle && <div className="rspress-code-title">{codeTitle}</div>}
<div
{...restProps}
className={clsx('rspress-code-content rspress-scrollbar', className)}
>
{children}
</div>
</>
);
};
export function Pre({
children,
className = DEFAULT_LANGUAGE_CLASS,
}: PreProps) {
if (Array.isArray(children)) {
return (
<div>
{children.map((child, index) => (
<div key={index} className={className}>
{renderChildren(child)}
</div>
))}
</div>
);
}
return <div className={className}>{renderChildren(children)}</div>;
}