-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdraft-stats.ts
More file actions
62 lines (54 loc) · 1.28 KB
/
draft-stats.ts
File metadata and controls
62 lines (54 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
export interface MdImage {
url: string
alt?: string
}
export interface MdLink {
text: string
url: string
}
export interface MdCodeBlock {
language?: string
code: string
}
export interface DraftStats {
charCount: number
images: MdImage[]
links: MdLink[]
codeBlocks: MdCodeBlock[]
}
export function statsFor(md: string): DraftStats {
const charCount = md.length
const images: MdImage[] = []
const links: MdLink[] = []
const codeBlocks: MdCodeBlock[] = []
const imageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g
let imageMatch: RegExpExecArray | null
while ((imageMatch = imageRegex.exec(md)) !== null) {
images.push({
...(imageMatch[1] && { alt: imageMatch[1] }),
url: imageMatch[2]!,
})
}
const linkRegex = /(?<!!)\[([^\]]+)\]\(([^)]+)\)/g
let linkMatch: RegExpExecArray | null
while ((linkMatch = linkRegex.exec(md)) !== null) {
links.push({
text: linkMatch[1]!,
url: linkMatch[2]!,
})
}
const codeBlockRegex = /```(\w*)\n?([\s\S]*?)```/g
let codeMatch: RegExpExecArray | null
while ((codeMatch = codeBlockRegex.exec(md)) !== null) {
codeBlocks.push({
...(codeMatch[1] && { language: codeMatch[1] }),
code: codeMatch[2]!,
})
}
return {
charCount,
codeBlocks,
images,
links,
}
}