Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

note-body.ts

63 lines2.1 KB

1/**
2 * A note body is plain text, one block per line:
3 * `# Heading`, `- bullet`, `[ ] todo`, `[x] done`, anything else is a paragraph.
4 */
5export type NoteBlock =
6 | { type: "heading"; text: string }
7 | { type: "paragraph"; text: string }
8 | { type: "bullet"; text: string }
9 | { type: "checklist"; text: string; checked: boolean };
10​
11export function parseLine(line: string): NoteBlock {
12 if (line.startsWith("# ")) return { type: "heading", text: line.slice(2) };
13 if (line.startsWith("- ")) return { type: "bullet", text: line.slice(2) };
14 if (line.startsWith("[ ] ")) return { type: "checklist", text: line.slice(4), checked: false };
15 if (line.startsWith("[x] ")) return { type: "checklist", text: line.slice(4), checked: true };
16 return { type: "paragraph", text: line };
18​
19export function serializeBlock(block: NoteBlock): string {
20 switch (block.type) {
21 case "heading":
22 return `# ${block.text}`;
23 case "bullet":
24 return `- ${block.text}`;
25 case "checklist":
26 return `${block.checked ? "[x]" : "[ ]"} ${block.text}`;
27 case "paragraph":
28 return block.text;
29 }
31​
32/** Blocks to render (blank lines skipped). */
33export function parseNoteBody(body: string): NoteBlock[] {
34 return body
35 .split("\n")
36 .filter((line) => line.trim() !== "")
37 .map(parseLine);
39​
40/**
41 * Blocks to edit: every line, blank ones included, so the editor round-trips
42 * the text exactly. An empty body is one empty paragraph to type into.
43 */
44export function parseEditableBody(body: string): NoteBlock[] {
45 return body.split("\n").map(parseLine);
47​
48export function serializeBody(blocks: NoteBlock[]): string {
49 return blocks.map(serializeBlock).join("\n");
51​
52/** The grey preview text shown under a note's title in the list. */
53export function noteSnippet(body: string): string {
54 const [first] = parseNoteBody(body);
55 return first?.text ?? "No additional text";
57​
58/** What the list and the tab show for a note without a title. */
59export const UNTITLED_NOTE = "New Note";
60​
61export function noteDisplayTitle(title: string): string {
62 return title.trim() === "" ? UNTITLED_NOTE : title;