-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarkdown-it-task-lists.ts
291 lines (250 loc) · 9.43 KB
/
markdown-it-task-lists.ts
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/**
* @fileoverview A markdown-it plugin that converts GitHub-style task lists to HTML checkboxes.
* Supports custom styling, nested lists, and configurable checkbox behavior.
*
* @example
* ```typescript
* import MarkdownIt from 'markdown-it';
* import taskLists, { type TaskListOptions } from 'markdown-it-task-lists-ts';
*
* const md = new MarkdownIt();
* md.use(taskLists, {
* enabled: true,
* label: true,
* labelClass: 'custom-label'
* });
* ```
*
* @license MIT
* @author TypeDown Team
*/
import MarkdownIt from 'markdown-it';
import type { Token } from 'markdown-it';
/**
* Configuration options for the task lists plugin
*
* @interface TaskListOptions
*/
export interface TaskListOptions {
/**
* Whether checkboxes are enabled and interactive
* When false, checkboxes will be rendered with the disabled attribute
* @default false
*/
enabled?: boolean;
/**
* Whether to wrap checkboxes in a label element
* Improves accessibility and click target size
* @default true
*/
label?: boolean;
/**
* Whether to place the label after the checkbox
* @default false
*/
labelAfter?: boolean;
/**
* Custom class name for the task list container (ul element)
* @default 'contains-task-list'
*/
listClass?: string;
/**
* Custom class name for task list items (li element)
* @default 'task-list-item'
*/
itemClass?: string;
/**
* Custom class name for the checkbox input element
* @default 'task-list-item-checkbox'
*/
checkboxClass?: string;
/**
* Custom class name for the label element (when label option is true)
* @default 'task-list-item-label'
*/
labelClass?: string;
/**
* Whether to use Tiptap-compatible HTML attributes
* When true, adds data-type="taskList" to ul and data-type="taskItem" data-checked to li
* @default false
*/
tiptapCompatible?: boolean;
}
/**
* Extended token type for task list items
*
* @interface TaskListToken
*/
export interface TaskListToken extends Token {
/**
* The content of the token
*/
content: string;
/**
* Child tokens of the current token
*/
children: (TaskListToken | Token)[] | null;
/**
* Get the index of an attribute by name
* @param name The attribute name
* @returns The index of the attribute, or -1 if not found
*/
attrIndex(name: string): number;
/**
* Add an attribute to the token
* @param attr The attribute to add
*/
attrPush(attr: [string, string]): void;
/**
* Get the attributes of the token
*/
attrs: [string, string][];
}
// Disable checkboxes by default
let disableCheckboxes = true;
// Use label wrapper by default
let useLabelWrapper = true;
// Place label after checkbox by default
let useLabelAfter = false;
// Default class names
const defaultClasses = {
list: 'contains-task-list',
item: 'task-list-item',
checkbox: 'task-list-item-checkbox',
label: 'task-list-item-label'
};
/**
* Check if a string starts with a todo markdown pattern
* @param str The string to check
* @returns Whether the string starts with a todo markdown pattern
*/
const startsWithTodoMarkdown = (str: string): boolean => {
// Leading whitespace in a list item is already trimmed off by markdown-it
return str.indexOf('[ ] ') === 0 || str.indexOf('[x] ') === 0 || str.indexOf('[X] ') === 0;
};
/**
* Check if a token is a list item
* @param token The token to check
* @returns Whether the token is a list item
*/
const isListItem = (token: Token): boolean => {
return token.type === 'list_item_open';
};
/**
* Check if a token is a paragraph
* @param token The token to check
* @returns Whether the token is a paragraph
*/
const isParagraph = (token: Token): boolean => {
return token.type === 'paragraph_open';
};
/**
* Check if a token is an inline token
* @param token The token to check
* @returns Whether the token is an inline token
*/
const isInline = (token: Token): boolean => {
return token.type === 'inline';
};
/**
* Check if a token has an open or close tag
* @param token The token to check
* @param tag The tag to check for
* @returns Whether the token has an open or close tag
*/
const hasOpenOrCloseTag = (token: Token, tag: string): boolean => {
return token.tag === tag && (token.type === 'paragraph_open' || token.type === 'paragraph_close');
};
/**
* Markdown-it plugin for task lists
* @param md The markdown-it instance
* @param options The plugin options
*/
export function taskLists(md: MarkdownIt, options?: TaskListOptions): void {
if (options) {
disableCheckboxes = !options.enabled;
useLabelWrapper = !!options.label;
useLabelAfter = !!options.labelAfter;
}
const classes = {
list: options?.listClass ?? defaultClasses.list,
item: options?.itemClass ?? defaultClasses.item,
checkbox: options?.checkboxClass ?? defaultClasses.checkbox,
label: options?.labelClass ?? defaultClasses.label
};
// Add the checkbox replacing function to the renderer
md.core.ruler.after('inline', 'github-task-lists', (state) => {
const tokens = state.tokens;
let insideList = false;
for (let i = 0; i < tokens.length; i++) {
if (tokens[i].type === 'bullet_list_open') {
insideList = true;
continue;
}
if (tokens[i].type === 'bullet_list_close') {
insideList = false;
continue;
}
if (!insideList) continue;
if (!isListItem(tokens[i])) continue;
// Find the content token within this list item
for (let j = i + 1; j < tokens.length; j++) {
if (tokens[j].type === 'list_item_close') break;
if (!isParagraph(tokens[j])) continue;
// Find the content within the paragraph
for (let k = j + 1; k < tokens.length; k++) {
if (hasOpenOrCloseTag(tokens[k], 'p')) break;
if (!isInline(tokens[k])) continue;
if (!startsWithTodoMarkdown(tokens[k].content)) continue;
// Transform the token
const token = tokens[k] as TaskListToken;
const checked = token.content.indexOf('[x]') === 0 || token.content.indexOf('[X]') === 0;
if (token.children && token.children.length > 0) {
token.children[0].content = token.children[0].content.slice(3);
const checkbox = new state.Token('html_inline', '', 0);
const disabledAttr = disableCheckboxes ? ' disabled ' : '';
if (useLabelWrapper) {
const id = `task-item-${Math.ceil(Math.random() * (10000 * 1000) - 1000)}`;
const label = `<label class="${classes.label}" for="${id}">`;
const closeLabel = '</label>';
checkbox.content = useLabelAfter
? `<input class="${classes.checkbox}" ${disabledAttr} type="checkbox" ${checked ? 'checked="" ' : ''} id="${id}">${label}${closeLabel}`
: `${label}<input class="${classes.checkbox}" ${disabledAttr} type="checkbox" ${checked ? 'checked="" ' : ''} id="${id}">${closeLabel}`;
} else {
checkbox.content = `<input class="${classes.checkbox}" ${disabledAttr} type="checkbox" ${checked ? 'checked="" ' : ''}>`;
}
token.children.unshift(checkbox);
token.content = token.content.slice(3);
// Add CSS classes to the list item
let itemClass = classes.item;
let parentClass = classes.list;
// Find the nearest list item token
let current = k;
while (current >= 0 && tokens[current].type !== 'list_item_open') {
current--;
}
if (current >= 0) {
tokens[current].attrJoin('class', itemClass);
if (options?.tiptapCompatible) {
tokens[current].attrSet('data-type', 'taskItem');
tokens[current].attrSet('data-checked', checked.toString());
}
}
// Find the nearest list token
while (current >= 0 && tokens[current].type !== 'bullet_list_open') {
current--;
}
if (current >= 0) {
tokens[current].attrJoin('class', parentClass);
if (options?.tiptapCompatible) {
tokens[current].attrSet('data-type', 'taskList');
}
}
}
}
}
}
return true;
});
}
export default taskLists;