Skip to content

Commit 8cbc2f7

Browse files
author
Jacob Logan
committed
parse out markdown links in comments
1 parent 4ec76ba commit 8cbc2f7

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/components/ApiDocs/ApiComment.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Fragment } from 'react';
22
import { View } from '@aws-amplify/ui-react';
3+
import { parseMarkdownLinks } from '@/utils/parseMdxLinks';
34

45
interface ApiCommentProps {
56
apiComment?: any[];
@@ -26,7 +27,7 @@ export const ApiComment = ({ apiComment, codeBlock }: ApiCommentProps) => {
2627
</Fragment>
2728
);
2829
} else {
29-
return text;
30+
return parseMarkdownLinks(text);
3031
}
3132
}
3233
});

src/utils/parseMdxLinks.tsx

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { MDXLink } from '@/components/MDXComponents';
2+
3+
type stringOrJSXArray = (string | JSX.Element)[];
4+
5+
export const parseMarkdownLinks = (inputString: string): stringOrJSXArray => {
6+
const result: stringOrJSXArray = [];
7+
if (!inputString) return result;
8+
const regex = /\[([^\]]+)\]\(([^)]+)\)/g;
9+
let lastIndex = 0;
10+
let match;
11+
12+
while ((match = regex.exec(inputString)) !== null) {
13+
const [fullMatch, linkText, url] = match;
14+
15+
if (!fullMatch) continue;
16+
17+
// add text before the link
18+
if (match.index > lastIndex) {
19+
result.push(inputString.slice(lastIndex, match.index));
20+
}
21+
22+
// add link
23+
result.push(
24+
<MDXLink href={url} hash="">
25+
{linkText}
26+
</MDXLink>
27+
);
28+
29+
lastIndex = regex.lastIndex;
30+
}
31+
32+
// Add any text found after the last link
33+
if (lastIndex < inputString.length) {
34+
result.push(inputString.slice(lastIndex));
35+
}
36+
37+
return result;
38+
};

0 commit comments

Comments
 (0)