Skip to content

Commit 1004f75

Browse files
committed
Create link annotations
1 parent 4c8f649 commit 1004f75

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

packages/mdx/dev/content/autolink.mdx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{/* prettier-ignore */}
2+
```py
3+
import requests
4+
5+
# URL: https://api.example.com/data
6+
# Invalid URL: http://invalid_domain.123
7+
urls = ["https://typicode.com/todos/1", "https://typicode.com/todos/2"]
8+
responses = [requests.get(url) for url in urls]
9+
```
10+
11+
```ruby mark=3:5
12+
require 'net/http'
13+
14+
url = URI.parse('https://www.ruby-lang.org/en/')
15+
url = URI.parse 'https://www.ruby-lang.org/en/'
16+
url = URI.parse 'https://www.ruby-lang.org/en/'asdasd;
17+
response = Net::HTTP.get_response(url)
18+
puts response.body
19+
```

packages/mdx/src/remark/annotations.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,46 @@ export function extractAnnotationsFromCode(code: Code) {
5050
lineNumber++
5151
}
5252
}
53+
54+
// extract links
55+
lineNumber = 1
56+
while (lineNumber <= lines.length) {
57+
const line = lines[lineNumber - 1]
58+
const lineContent = line.tokens
59+
.map(t => t.content)
60+
.join("")
61+
62+
const urls = extractURLsFromLine(lineContent)
63+
urls.forEach(({ url, start, end }) => {
64+
const Component = annotationsMap["link"]
65+
const focus = `${lineNumber}[${start + 1}:${end}]`
66+
annotations.push({
67+
Component,
68+
focus,
69+
data: url,
70+
})
71+
})
72+
lineNumber++
73+
}
5374
return [annotations, focusList.join(",")] as const
5475
}
5576

77+
const urlRegex = /https?:\/\/[\w\-_.~:/?#[\]@!$&*+,;=%]+/g
78+
function extractURLsFromLine(line: string) {
79+
const urls = []
80+
let match: RegExpExecArray | null
81+
82+
while ((match = urlRegex.exec(line)) !== null) {
83+
const url = match[0]
84+
const start = match.index
85+
const end = start + url.length
86+
87+
urls.push({ url, start, end })
88+
}
89+
90+
return urls
91+
}
92+
5693
export function extractJSXAnnotations(
5794
node: SuperNode,
5895
index: number,

0 commit comments

Comments
 (0)