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// Native renderers give other top-level blocks (code, tables, quotes, media) their own views, and
31// each view numbers its tasks from 0. Lists, headings and rules share the text view around them.
32const sharedViewBlocks = new Set(["list", "heading", "thematicBreak"]);
33
34/**
35 * Marker offset of the task a native checkbox tap names. Null unless exactly one task has that
36 * text and state and could have that index under some split of the document into native views.
37 */
38export function markdownTaskMarkerOffset(
39 markdown: string,
40 index: number,
41 renderedText: string,
42 checked: boolean,
43): number | null {
44 // Native attachments replace their labels, so the remaining text could name another task.
45 if (renderedText.includes("\uFFFC")) return null;
46 const tasks: ListItem[] = [];
47 const collect = (node: Nodes) => {
48 if (node.type === "listItem" && typeof node.checked === "boolean") tasks.push(node);
49 if ("children" in node) node.children.forEach(collect);
50 };
51 const viewStarts = new Set([0]);
52 for (const block of parser.parse(markdown).children) {
53 const before = tasks.length;
54 collect(block);
55 if (sharedViewBlocks.has(block.type)) continue;
56 for (let count = before; count <= tasks.length; count++) viewStarts.add(count);
57 }
58 const rendered = lettersAndDigits(renderedText);
59 const matches = tasks.filter(
60 (task, position) =>
61 task.checked === !checked &&
62 viewStarts.has(position - index) &&
63 renderedTexts(task).includes(rendered),
64 );
65 const start = matches.length === 1 ? matches[0]?.position?.start.offset : undefined;
66 return start === undefined ? null : taskListMarkerOffset(markdown, start);
67}