Skip to content

Commit 71b743a

Browse files
Strekgaearon
Strek
andauthored
Generate Ids when there are none in local development (#4304)
* Generate Ids when there are no headings * Tweak code Co-authored-by: Dan Abramov <dan.abramov@gmail.com>
1 parent e2b2ebf commit 71b743a

File tree

1 file changed

+18
-24
lines changed

1 file changed

+18
-24
lines changed

beta/plugins/remark-header-custom-ids.js

+18-24
Original file line numberDiff line numberDiff line change
@@ -32,32 +32,26 @@ module.exports = ({
3232
visit(tree, 'heading', (node) => {
3333
const children = node.children;
3434
let tail = children[children.length - 1];
35-
36-
// A bit weird: this is to support MDX 2 comments in expressions,
37-
// while we’re still on MDX 1, which doesn’t support them.
38-
if (!tail || tail.type !== 'text' || tail.value !== '/}') {
39-
return;
35+
// Generate slugs on the fly (even if not specified in markdown)
36+
// so that it's possible to copy anchor links in newly written content.
37+
let id = slugs.slug(toString(node), maintainCase);
38+
// However, for committed docs, we'll extract slug from the headers.
39+
if (tail && tail.type === 'text' && tail.value === '/}') {
40+
tail = children[children.length - 2];
41+
if (tail && tail.type === 'emphasis') {
42+
// Use custom ID instead.
43+
id = toString(tail);
44+
// Until we're on MDX 2, we need to "cut off" the comment syntax.
45+
tail = children[children.length - 3];
46+
if (tail && tail.type === 'text' && tail.value.endsWith('{/')) {
47+
// Remove the emphasis and trailing `/}`
48+
children.splice(children.length - 2, 2);
49+
// Remove the `{/`
50+
tail.value = tail.value.replace(/[ \t]*\{\/$/, '');
51+
}
52+
}
4053
}
4154

42-
tail = children[children.length - 2];
43-
44-
if (!tail && tail.type !== 'emphasis') {
45-
return;
46-
}
47-
48-
const id = toString(tail);
49-
50-
tail = children[children.length - 3];
51-
52-
if (!tail || tail.type !== 'text' || !tail.value.endsWith('{/')) {
53-
return;
54-
}
55-
56-
// Remove the emphasis and trailing `/}`
57-
children.splice(children.length - 2, 2);
58-
// Remove the `{/`
59-
tail.value = tail.value.replace(/[ \t]*\{\/$/, '');
60-
6155
const data = patch(node, 'data', {});
6256

6357
patch(data, 'id', id);

0 commit comments

Comments
 (0)