Open History to see the last commit
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("") : "";
17}
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 );
28}
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" && typeof node.checked === "boolean") {
45 // Native enrmrkd only recognizes task markers on the same line as their list bullet.
46 const start = node.position?.start.offset;
47 const offset = start === undefined ? null : taskListMarkerOffset(markdown, start);
48 if (start !== undefined && offset !== null && !/[\r\n]/.test(markdown.slice(start, offset))) {
49 tasks.push({ item: node, offset });
50 }
51 }
52 if ("children" in node) node.children.forEach(collect);
53 };
54 collect(parser.parse(markdown));
55 const task = tasks[index];
56 return task?.item.checked === !checked &&
57 renderedTexts(task.item).includes(lettersAndDigits(renderedText))
58 ? task.offset
59 : null;
60}