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

note-body.ts

78 lines2.5 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​
52function wordsIn(text: string): number {
53 return text.split(/\s+/).filter(Boolean).length;
55​
56/**
57 * Words in a note as the editor shows it: the title, then each block's text.
58 * Block markers (`# `, `- `, `[ ] `, `[x] `) aren't words.
59 */
60export function countWords(note: { title: string; body: string }): number {
61 return parseNoteBody(note.body).reduce(
62 (total, block) => total + wordsIn(block.text),
63 wordsIn(note.title),
64 );
66​
67/** The grey preview text shown under a note's title in the list. */
68export function noteSnippet(body: string): string {
69 const [first] = parseNoteBody(body);
70 return first?.text ?? "No additional text";
72​
73/** What the list and the tab show for a note without a title. */
74export const UNTITLED_NOTE = "New Note";
75​
76export function noteDisplayTitle(title: string): string {
77 return title.trim() === "" ? UNTITLED_NOTE : title;