Skip to content

Commit 5727cc8

Browse files
Validate line highlight ranges in markdown code blocks
Code fence metadata like `{3,7}` can reference lines past the end of the code block. The site silently ignores those lines, so the line the author meant to highlight is never highlighted. Extend lint-markdown-code-blocks to report highlighted lines outside the code block, using the same pattern as getHighlightLines() in CodeBlock.tsx, and fix the three existing cases in the cacheSignal reference and the "Components and Hooks must be pure" page. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 15653c0 commit 5727cc8

7 files changed

Lines changed: 81 additions & 27 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
```js {1,3}
2+
function submitAction() {}
3+
submitAction();
4+
```
5+
6+
```js {1-3}
7+
function submitAction() {}
8+
submitAction();
9+
```

‎eslint-local-rules/__tests__/fixtures/src/content/valid-highlight.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,13 @@ function submitAction() {}
55
```js [[1, 1, "\\"hidden\\""]]
66
const mode = "hidden";
77
```
8+
9+
```js {2}
10+
function submitAction() {}
11+
submitAction();
12+
```
13+
14+
```js {1-2} [[1, 2, "submitAction"]]
15+
function submitAction() {}
16+
submitAction();
17+
```

‎eslint-local-rules/__tests__/lint-markdown-code-blocks.test.js‎

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,7 @@ const path = require('path');
1111
const {ESLint} = require('eslint');
1212
const plugin = require('..');
1313

14-
const FIXTURES_DIR = path.join(
15-
__dirname,
16-
'fixtures',
17-
'src',
18-
'content'
19-
);
14+
const FIXTURES_DIR = path.join(__dirname, 'fixtures', 'src', 'content');
2015
const PARSER_PATH = path.join(__dirname, '..', 'parser.js');
2116

2217
function createESLint({fix = false} = {}) {
@@ -53,11 +48,7 @@ async function lintFixture(name, {fix = false} = {}) {
5348

5449
async function run() {
5550
const basicResult = await lintFixture('basic-error.md');
56-
assert.strictEqual(
57-
basicResult.messages.length,
58-
1,
59-
'expected one diagnostic'
60-
);
51+
assert.strictEqual(basicResult.messages.length, 1, 'expected one diagnostic');
6152
assert(
6253
basicResult.messages[0].message.includes('Calling setState during render'),
6354
'expected message to mention setState during render'
@@ -91,9 +82,7 @@ async function run() {
9182
fix: true,
9283
});
9384
assert(
94-
duplicateFixed.output.includes(
95-
"{expectedErrors: {'react-compiler': [4]}}"
96-
),
85+
duplicateFixed.output.includes("{expectedErrors: {'react-compiler': [4]}}"),
9786
'expected duplicates to be rewritten to a single canonical block'
9887
);
9988
assert(
@@ -118,9 +107,7 @@ async function run() {
118107
fix: true,
119108
});
120109
assert(
121-
malformedFixed.output.includes(
122-
"{expectedErrors: {'react-compiler': [4]}}"
123-
),
110+
malformedFixed.output.includes("{expectedErrors: {'react-compiler': [4]}}"),
124111
'expected malformed metadata to be replaced with canonical form'
125112
);
126113

@@ -154,9 +141,24 @@ async function run() {
154141
outOfBoundsHighlightResult.messages[0].message,
155142
'Code highlight line 3 is outside this code block'
156143
);
144+
145+
const outOfBoundsLineHighlightResult = await lintFixture(
146+
'out-of-bounds-line-highlight.md'
147+
);
148+
assert.strictEqual(
149+
outOfBoundsLineHighlightResult.messages.length,
150+
2,
151+
'expected a highlighted line and range end past the code block to fail'
152+
);
153+
for (const message of outOfBoundsLineHighlightResult.messages) {
154+
assert.strictEqual(
155+
message.message,
156+
'Highlighted line 3 is outside this code block, which has 2 lines'
157+
);
158+
}
157159
}
158160

159-
run().catch(error => {
161+
run().catch((error) => {
160162
console.error(error);
161163
process.exitCode = 1;
162164
});

‎eslint-local-rules/rules/inline-highlights.js‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,34 @@ function validateInlineHighlights(meta, code) {
6363
return errors;
6464
}
6565

66-
module.exports = {validateInlineHighlights};
66+
// Matches the line ranges read by getHighlightLines() in
67+
// src/components/MDX/CodeBlock/CodeBlock.tsx, e.g. `{1-3,7}`.
68+
const LINE_HIGHLIGHT_REGEX = /{([\d,-]+)}/;
69+
70+
function validateLineHighlights(meta, code) {
71+
const match = LINE_HIGHLIGHT_REGEX.exec(meta);
72+
if (!match) {
73+
return [];
74+
}
75+
76+
const lineCount = code.split('\n').length;
77+
const errors = [];
78+
79+
for (const range of match[1].split(',')) {
80+
for (const bound of range.split('-')) {
81+
if (bound === '') {
82+
continue;
83+
}
84+
const lineNo = Number(bound);
85+
if (lineNo < 1 || lineNo > lineCount) {
86+
errors.push(
87+
`Highlighted line ${lineNo} is outside this code block, which has ${lineCount} lines`
88+
);
89+
}
90+
}
91+
}
92+
93+
return errors;
94+
}
95+
96+
module.exports = {validateInlineHighlights, validateLineHighlights};

‎eslint-local-rules/rules/lint-markdown-code-blocks.js‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ const {
1616
setCompilerExpectedLines,
1717
} = require('./metadata');
1818
const {normalizeDiagnostics} = require('./diagnostics');
19-
const {validateInlineHighlights} = require('./inline-highlights');
19+
const {
20+
validateInlineHighlights,
21+
validateLineHighlights,
22+
} = require('./inline-highlights');
2023
const {parseMarkdownFile} = require('./markdown');
2124
const {runReactCompiler} = require('./react-compiler');
2225

@@ -44,10 +47,10 @@ module.exports = {
4447
const {blocks} = parseMarkdownFile(sourceCode.text, filename);
4548
// For each supported code block, run the compiler and reconcile metadata.
4649
for (const block of blocks) {
47-
for (const message of validateInlineHighlights(
48-
block.meta,
49-
block.code
50-
)) {
50+
for (const message of [
51+
...validateLineHighlights(block.meta, block.code),
52+
...validateInlineHighlights(block.meta, block.code),
53+
]) {
5154
context.report({
5255
node,
5356
loc: block.position,

‎src/content/reference/react/cacheSignal.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const signal = cacheSignal();
2828

2929
Call `cacheSignal` to get an `AbortSignal`.
3030

31-
```js {3,7}
31+
```js {3}
3232
import {cacheSignal} from 'react';
3333
async function Component() {
3434
await fetch(url, { signal: cacheSignal() });

‎src/content/reference/rules/components-and-hooks-must-be-pure.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -309,13 +309,13 @@ function useIconStyle(icon) {
309309

310310
If you were to mutate the Hook's arguments, the custom hook's memoization will become incorrect, so it's important to avoid doing that.
311311

312-
```js {4}
312+
```js {2}
313313
style = useIconStyle(icon); // `style` is memoized based on `icon`
314314
icon.enabled = false; // Bad: 🔴 never mutate hook arguments directly
315315
style = useIconStyle(icon); // previously memoized result is returned
316316
```
317317

318-
```js {4}
318+
```js {2}
319319
style = useIconStyle(icon); // `style` is memoized based on `icon`
320320
icon = { ...icon, enabled: false }; // Good: ✅ make a copy instead
321321
style = useIconStyle(icon); // new value of `style` is calculated

0 commit comments

Comments
 (0)