Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Link checker parses headings inside component #2230

Merged
merged 1 commit into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions scripts/js/lib/links/extractLinks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,43 @@ test("parseAnchors()", () => {

## \`code-header\`

## Header.with periods-and wild! punctuation?? and numbers 1234 8 (parentheses)

## header_using\_underscores

## UpperCase Should Be lowercase

## repeated
## repeated
## repeated

<Function id="mdx.component.testId" name="testId" signature="testId">
Convert to dictionary.

**Return type**

\`Dict\`
</Function>

<Class>
### Header inside a component
</Class>
`);
expect(result).toEqual(
new Set([
"#my-top-level-heading",
"#header-2",
"#code-header",
"#headerwith-periods-and-wild-punctuation-and-numbers-1234-8-parentheses",
"#header_using_underscores",
"#uppercase-should-be-lowercase",
"#this-is-a-hardcoded-anchor",
"#another_span",
"#mdx.component.testId",
"#header-inside-a-component",
"#repeated",
"#repeated-1",
"#repeated-2",
]),
);
});
Expand Down
27 changes: 22 additions & 5 deletions scripts/js/lib/links/extractLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,28 @@ export type ParsedFile = {
};

export function parseAnchors(markdown: string): Set<string> {
// Anchors generated from markdown titles.
const mdAnchors = markdownLinkExtractor(markdown).anchors;
// Anchors from HTML id tags.
const idAnchors = markdown.match(/(?<=id=")(.+?)(?=")/gm) || [];
return new Set([...mdAnchors, ...idAnchors.map((id) => `#${id}`)]);
const lines = markdown.split("\n");
const anchors = new Set<string>();
for (const line of lines) {
const heading = line.match(/^\s*#{1,6}\s+(.+?)\s*$/);
if (heading) {
const normalized = heading[1]
.toLowerCase()
.trim()
.replaceAll(" ", "-")
.replaceAll(/[\.,;!?`\\\(\)]/g, "");
let deduplicated = normalized;
let i = 1;
while (anchors.has(`#${deduplicated}`)) {
deduplicated = `${normalized}-${i}`;
i += 1;
}
anchors.add(`#${deduplicated}`);
}
const id = line.match(/(?<=id=")(.+?)(?=")/);
if (id) anchors.add(`#${id[1]}`);
}
return anchors;
}

export async function parseLinks(
Expand Down