Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownTaskEdits.ts

27 lines1019 Bytes

1// Callers pass the start of an item remark-gfm parsed as a task, so this only locates the marker:
2// after the bullet, or on the next line (past any blockquote prefix) when the bullet stands alone.
3const taskMarker =
4 /[ \t]*(?:[-+*]|\d+[.)])(?:[ \t]+|[ \t]*(?:\r\n?|\n)(?:[ \t]*>)*[ \t]*)\[[ xX]\]/y;
5​
6/** Offset of the `[ ]` marker of the task list item starting at `listItemStart`. */
7export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null {
8 taskMarker.lastIndex = listItemStart;
9 return taskMarker.exec(markdown) ? taskMarker.lastIndex - 3 : null;
11​
12export function setMarkdownTaskChecked(
13 markdown: string,
14 markerOffset: number,
15 checked: boolean,
16): string {
17 if (
18 markerOffset < 0 ||
19 markdown[markerOffset] !== "[" ||
20 !/[ xX]/.test(markdown[markerOffset + 1] ?? "") ||
21 markdown[markerOffset + 2] !== "]"
22 ) {
23 return markdown;
24 }
25​
26 return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`;