forked from hackorum-dev/hackorum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff_highlight_controller.js
More file actions
41 lines (34 loc) · 1.21 KB
/
diff_highlight_controller.js
File metadata and controls
41 lines (34 loc) · 1.21 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
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
connect() {
if (this.element.dataset.diffHighlighted === "true") return
const text = this.element.textContent
if (!text) return
const fragment = document.createDocumentFragment()
const lines = text.split("\n")
lines.forEach((line) => {
const span = document.createElement("span")
span.classList.add("diff-line")
if (line.startsWith("+") && !line.startsWith("+++")) {
span.classList.add("diff-line-add")
} else if (line.startsWith("-") && !line.startsWith("---")) {
span.classList.add("diff-line-del")
} else if (line.startsWith("@@")) {
span.classList.add("diff-line-hunk")
} else if (
line.startsWith("diff ") ||
line.startsWith("index ") ||
line.startsWith("---") ||
line.startsWith("+++")
) {
span.classList.add("diff-line-header")
}
span.textContent = line.length ? line : " "
fragment.appendChild(span)
})
this.element.textContent = ""
this.element.appendChild(fragment)
this.element.dataset.diffHighlighted = "true"
this.element.classList.add("diff-highlighted")
}
}