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

markdownTaskList.ts

71 lines2.6 KB

1import type { ListItem, Nodes } from "mdast";
2import remarkGfm from "remark-gfm";
3import remarkParse from "remark-parse";
4import { unified } from "unified";
5​
6import { taskListMarkerOffset } from "./markdownTaskEdits.ts";
7​
8const parser = unified().use(remarkParse).use(remarkGfm);
9​
10/** Hard breaks as U+2028, as iOS draws them; soft breaks stay "\n". */
11function plainText(node: Nodes): string {
12 if (node.type === "text" || node.type === "inlineCode") return node.value;
13 if (node.type === "break" || (node.type === "html" && /^<br\b/i.test(node.value))) {
14 return "\u2028";
15 }
16 return "children" in node ? node.children.map(plainText).join("") : "";
18​
19const lettersAndDigits = (text: string) => text.replace(/[^\p{L}\p{N}]/gu, "");
20​
21/** iOS sends the first paragraph whole. Android cuts it at a hard break, or any break with hard breaks on. */
22function renderedTexts(item: ListItem): string[] {
23 const first = item.children[0];
24 const text = first?.type === "paragraph" ? plainText(first) : "";
25 return [text, text.replace(/\u2028[^]*$/, ""), text.replace(/[\u2028\n][^]*$/, "")].map(
26 lettersAndDigits,
27 );
29​
30/**
31 * Marker offset of the task at the native renderer's document-wide task index, or null unless its
32 * text and pre-tap state match the tap.
33 */
34export function markdownTaskMarkerOffset(
35 markdown: string,
36 index: number,
37 renderedText: string,
38 checked: boolean,
39): number | null {
40 // Native attachments replace their labels, so the remaining text could name another task.
41 if (renderedText.includes("\uFFFC")) return null;
42 const tasks: Array<{ readonly item: ListItem; readonly offset: number }> = [];
43 const collect = (node: Nodes) => {
44 if (node.type === "listItem") {
45 const first = node.children[0];
46 const emptyTask =
47 first?.type === "paragraph" &&
48 /^\[[ xX]\][ \t]*$/.test(
49 markdown.slice(first.position?.start.offset, first.position?.end.offset),
50 );
51 // Native enrmrkd only recognizes task markers on the same line as their list bullet.
52 const start = node.position?.start.offset;
53 const offset = start === undefined ? null : taskListMarkerOffset(markdown, start);
54 if (
55 (typeof node.checked === "boolean" || emptyTask) &&
56 start !== undefined &&
57 offset !== null &&
58 !/[\r\n]/.test(markdown.slice(start, offset))
59 ) {
60 tasks.push({ item: node, offset });
61 }
62 }
63 if ("children" in node) node.children.forEach(collect);
64 };
65 collect(parser.parse(markdown));
66 const task = tasks[index];
67 return task?.item.checked === !checked &&
68 renderedTexts(task.item).includes(lettersAndDigits(renderedText))
69 ? task.offset
70 : null;