From ab8c1a4810987748ce2c828cdbd1cac5179a463d Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Mon, 26 Sep 2022 17:34:37 +0100 Subject: [PATCH] Fix HTML and CSS highlighting --- .../components/MDX/CodeBlock/CodeBlock.tsx | 32 ++++++++++++++++--- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/beta/src/components/MDX/CodeBlock/CodeBlock.tsx b/beta/src/components/MDX/CodeBlock/CodeBlock.tsx index ec2058b4..83e2cf2c 100644 --- a/beta/src/components/MDX/CodeBlock/CodeBlock.tsx +++ b/beta/src/components/MDX/CodeBlock/CodeBlock.tsx @@ -5,6 +5,8 @@ import cn from 'classnames'; import {highlightTree} from '@codemirror/highlight'; import {javascript} from '@codemirror/lang-javascript'; +import {html} from '@codemirror/lang-html'; +import {css} from '@codemirror/lang-css'; import {HighlightStyle, tags} from '@codemirror/highlight'; import rangeParser from 'parse-numeric-range'; import {CustomTheme} from '../Sandpack/Themes'; @@ -16,6 +18,10 @@ interface InlineHiglight { endColumn: number; } +const jsxLang = javascript({jsx: true, typescript: false}); +const cssLang = css(); +const htmlLang = html(); + const CodeBlock = function CodeBlock({ children: { props: {className = 'language-js', children: code = '', meta}, @@ -33,7 +39,13 @@ const CodeBlock = function CodeBlock({ noMargin?: boolean; }) { code = code.trimEnd(); - const tree = language.language.parser.parse(code); + let lang = jsxLang; + if (className === 'language-css') { + lang = cssLang; + } else if (className === 'language-html') { + lang = htmlLang; + } + const tree = lang.language.parser.parse(code); let tokenStarts = new Map(); let tokenEnds = new Map(); const highlightTheme = getSyntaxHighlight(CustomTheme); @@ -157,7 +169,21 @@ const CodeBlock = function CodeBlock({ buffer += code[i]; } } - lineOutput.push(buffer); + if (currentDecorator) { + lineOutput.push( + + {buffer} + + ); + } else if (currentToken) { + lineOutput.push( + + {buffer} + + ); + } else { + lineOutput.push(buffer); + } finalOutput.push(