fix(theme): Fix code block magic comments with CRLF line breaks bug (#11046)

* fix: with CRLF line breaks, an extra empty line was rendered with // highlight-end at end of code blocks

See: #11036

* Add unit tests

---------

Co-authored-by: sebastien <lorber.sebastien@gmail.com>
This commit is contained in:
程序员小墨 2025-04-01 21:14:02 +08:00 committed by GitHub
parent c0f3755d51
commit 3176a2ccba
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 49 additions and 2 deletions

View file

@ -70,6 +70,30 @@ bbbbb",
}
`;
exports[`parseLines handles CRLF line breaks with highlight comments correctly 1`] = `
{
"code": "aaaaa
bbbbb",
"lineClassNames": {
"1": [
"theme-code-block-highlighted-line",
],
},
}
`;
exports[`parseLines handles CRLF line breaks with highlight metastring 1`] = `
{
"code": "aaaaa
bbbbb",
"lineClassNames": {
"1": [
"theme-code-block-highlighted-line",
],
},
}
`;
exports[`parseLines handles one line with multiple class names 1`] = `
{
"code": "

View file

@ -360,6 +360,29 @@ line
),
).toMatchSnapshot();
});
it('handles CRLF line breaks with highlight comments correctly', () => {
expect(
parseLines(
`aaaaa\r\n// highlight-start\r\nbbbbb\r\n// highlight-end\r\n`,
{
metastring: '',
language: 'js',
magicComments: defaultMagicComments,
},
),
).toMatchSnapshot();
});
it('handles CRLF line breaks with highlight metastring', () => {
expect(
parseLines(`aaaaa\r\nbbbbb\r\n`, {
metastring: '{2}',
language: 'js',
magicComments: defaultMagicComments,
}),
).toMatchSnapshot();
});
});
describe('getLineNumbersStart', () => {

View file

@ -241,7 +241,7 @@ export function parseLines(
*/
code: string;
} {
let code = content.replace(/\n$/, '');
let code = content.replace(/\r?\n$/, '');
const {language, magicComments, metastring} = options;
// Highlighted lines specified in props: don't parse the content
if (metastring && metastringLinesRangeRegex.test(metastring)) {
@ -266,7 +266,7 @@ export function parseLines(
magicComments,
);
// Go through line by line
const lines = code.split('\n');
const lines = code.split(/\r?\n/);
const blocks = Object.fromEntries(
magicComments.map((d) => [d.className, {start: 0, range: ''}]),
);