Skip to content

Commit a882461

Browse files
committed
Create checkbox.ts
1 parent 2298554 commit a882461

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

lib/checkbox.ts

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import MarkdownIt from 'markdown-it/lib'
2+
import Token from 'markdown-it/lib/token'
3+
4+
// modified from https://github.com/mcecot/markdown-it-checkbox
5+
export function MarkdownItCheckbox(md: MarkdownIt) {
6+
let lastId: number = 0
7+
function createTokens(checked: boolean, label: string): Token[] {
8+
const nodes: Token[] = []
9+
10+
const id = lastId
11+
lastId++
12+
13+
let token = new Token('checkbox_input', 'input', 0)
14+
token.attrs = [['type', 'checkbox'], ['id', id.toString()], ['class', 'task-list-item-checkbox']]
15+
if (checked) {
16+
token.attrPush(['checked', 'true'])
17+
}
18+
nodes.push(token)
19+
20+
token = new Token('label_open', 'label', 1)
21+
token.attrs = [['for', id.toString()]]
22+
nodes.push(token)
23+
24+
token = new Token('text', '', 0)
25+
token.content = label
26+
nodes.push(token)
27+
28+
nodes.push(new Token('label_close', 'label', -1))
29+
30+
return nodes
31+
}
32+
33+
function splitTextToken(token: Token): Token[] | null {
34+
let matches = token.content.match(/\[(X|\s|\_|\-)\]\s(.*)/i)
35+
if (matches === null) {
36+
return null
37+
}
38+
39+
let checked = false
40+
const value: string = matches[1] || ''
41+
const label: string = matches[2] || ''
42+
if (value == 'X' || value == 'x') {
43+
checked = true
44+
}
45+
return createTokens(checked, label)
46+
}
47+
48+
49+
function checkbox(state: any): void {
50+
let blockTokens = state.tokens
51+
const l = blockTokens.length
52+
let k = -1
53+
for (let j = 0; j < l; j++) {
54+
//
55+
if (blockTokens[j].type === 'list_item_open') {
56+
k = j
57+
}
58+
if (blockTokens[j].type !== 'inline') {
59+
continue
60+
}
61+
let tokens = blockTokens[j].children
62+
for (let i = tokens.length - 1; i >= 0; i--) {
63+
const newTokens = splitTextToken(tokens[i])
64+
if (newTokens !== null) {
65+
tokens = md.utils.arrayReplaceAt(tokens, i, newTokens)
66+
blockTokens[j].children = tokens
67+
if (k !== -1) {
68+
blockTokens[k].attrs = [['class', 'task-list-item']]
69+
}
70+
}
71+
}
72+
}
73+
}
74+
75+
md.core.ruler.push('checkbox', checkbox)
76+
}

0 commit comments

Comments
 (0)