feat(theme-classic): usable CodeBlock outside markdown (#6216)

This commit is contained in:
Joshua Chen 2021-12-30 00:17:09 +08:00 committed by GitHub
parent 96dbb8e7ef
commit c45281a581
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 53 additions and 18 deletions

View file

@ -114,6 +114,7 @@ declare module '@theme/CodeBlock' {
readonly className?: string;
readonly metastring?: string;
readonly title?: string;
readonly language?: string;
}
const CodeBlock: (props: Props) => JSX.Element;

View file

@ -24,9 +24,10 @@ import styles from './styles.module.css';
export default function CodeBlock({
children,
className: blockClassName,
className: blockClassName = '',
metastring,
title,
language: languageProp,
}: Props): JSX.Element {
const {prism} = useThemeConfig();
@ -85,8 +86,7 @@ export default function CodeBlock({
: (children as string);
const language =
parseLanguage(blockClassName) ??
(prism.defaultLanguage as Language | undefined);
languageProp ?? parseLanguage(blockClassName) ?? prism.defaultLanguage;
const {highlightLines, code} = parseLines(content, metastring, language);
const handleCopyCode = () => {
@ -102,12 +102,16 @@ export default function CodeBlock({
key={String(mounted)}
theme={prismTheme}
code={code}
language={language ?? ('text' as Language)}>
language={(language ?? 'text') as Language}>
{({className, style, tokens, getLineProps, getTokenProps}) => (
<div
className={clsx(
styles.codeBlockContainer,
blockClassName,
{
[`language-${language}`]:
language && !blockClassName.includes(`language-${language}`),
},
ThemeClassNames.common.codeBlock,
)}>
{codeBlockTitle && (

View file

@ -6,7 +6,6 @@
*/
import rangeParser from 'parse-numeric-range';
import type {Language} from 'prism-react-renderer';
const codeBlockTitleRegex = /title=(["'])(.*?)\1/;
const highlightLinesRangeRegex = /{([\d,-]+)}/;
@ -93,11 +92,11 @@ export function parseCodeBlockTitle(metastring?: string): string {
return metastring?.match(codeBlockTitleRegex)?.[2] ?? '';
}
export function parseLanguage(className?: string): Language | undefined {
export function parseLanguage(className: string): string | undefined {
const languageClassName = className
?.split(' ')
.split(' ')
.find((str) => str.startsWith('language-'));
return languageClassName?.replace(/language-/, '') as Language | undefined;
return languageClassName?.replace(/language-/, '');
}
/**
@ -107,7 +106,7 @@ export function parseLanguage(className?: string): Language | undefined {
export function parseLines(
content: string,
metastring?: string,
language?: Language,
language?: string,
): {
highlightLines: number[];
code: string;