-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-block-parser.ts
More file actions
53 lines (45 loc) · 1.31 KB
/
code-block-parser.ts
File metadata and controls
53 lines (45 loc) · 1.31 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
import { cleanDiffLine, getDiffStyles, getDiffType } from "./code-block-diff"
import { tokenize } from "./code-block-syntax-highlighter"
interface CodeBlockChild {
props?: {
children?: string
}
}
export const extractCodeContent = (children: string | CodeBlockChild) => {
const code = typeof children === "string" ? children : (children?.props?.children ?? "")
return { code }
}
export const processLines = (content: string) => {
const lines = content.split("\n")
return filterEmptyLines(lines)
}
const filterEmptyLines = (lines: string[]) => {
return lines.filter((line, index, array) => {
const isLastLine = index === array.length - 1
const isEmpty = line.trim() === ""
return !(isEmpty && isLastLine)
})
}
export const createLineData = (line: string) => {
const diffType = getDiffType(line)
const cleanLine = cleanDiffLine(line)
const tokens = tokenize(cleanLine)
const styles = getDiffStyles(diffType)
const isNormalDiff = diffType === "normal"
return {
diffType,
cleanLine,
tokens,
styles,
isNormalDiff,
}
}
export const processCopyContent = (content: string): { code: string } => {
// removes diff markers from content
const code = content
.split("\n")
.filter((line) => !line.trimStart().startsWith("- "))
.map((line) => line.replace(/^(\s*)\+ /, "$1"))
.join("\n")
return { code }
}