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

note-editor.tsx

299 lines9.9 KB

1import { Check } from "lucide-react";
2import { useImperativeHandle, useLayoutEffect, useRef } from "react";
3import type { ComponentProps, KeyboardEvent, Ref } from "react";
4​
5import { editNote } from "@/db/mutations";
6import type { Note } from "@/db/schema";
7import { parseEditableBody, serializeBody } from "@/lib/notes/note-body";
8import type { NoteBlock } from "@/lib/notes/note-body";
9import {
10 joinWithPrevious,
11 setBlockText,
12 setTitle,
13 splitBlock,
14 splitTitle,
15 toggleChecked,
16 toggleChecklist,
17} from "@/lib/notes/note-editing";
18import type { Caret, NoteTextEdit } from "@/lib/notes/note-editing";
19import { cn } from "@/lib/utils";
20​
21/** What toolbars outside the editor can do to it. */
22export interface NoteEditorHandle {
23 /** Turns the line with the caret into a checklist item, or back. */
24 toggleChecklist: () => void;
26​
27interface NoteEditorProps {
28 note: Note;
29 variant: "mac" | "ios";
30 handleRef?: Ref<NoteEditorHandle>;
32​
33const TITLE = -1;
34​
35/** A new note's title gets focus when the note opens. */
36let noteToFocus: string | null = null;
37​
38export function focusNoteWhenOpened(noteId: string) {
39 noteToFocus = noteId;
41​
42/**
43 * The note editor: a title field, then one field per line of the body
44 * (paragraphs, headings, bullets, checklist items). Every keystroke is an
45 * optimistic update of the note in `notesCollection`, so the list, the
46 * folder counts and the tab title follow along as you type. The fields
47 * render straight from the collection; the update is synchronous, so the
48 * caret stays put.
49 */
50export function NoteEditor({ note, variant, handleRef }: NoteEditorProps) {
51 const blocks = parseEditableBody(note.body);
52 const fields = useRef(new Map<number, HTMLTextAreaElement>());
53 const pendingCaret = useRef<Caret | null>(null);
54 const lastFocusedField = useRef(TITLE);
55 const ios = variant === "ios";
56​
57 function placeCaret({ field, offset }: Caret) {
58 const element = fields.current.get(field);
59 if (!element) return;
60 element.focus();
61 element.setSelectionRange(offset, offset);
62 }
63​
64 // After an edit that moves the caret to another line (Enter, Backspace…).
65 useLayoutEffect(() => {
66 if (!pendingCaret.current) return;
67 placeCaret(pendingCaret.current);
68 pendingCaret.current = null;
69 });
70​
71 useLayoutEffect(() => {
72 if (noteToFocus !== note.id) return;
73 noteToFocus = null;
74 placeCaret({ field: TITLE, offset: note.title.length });
75 }, [note.id, note.title.length]);
76​
77 /** Saves an edit; `moveCaret` when the caret has to land somewhere new. */
78 function apply(edit: NoteTextEdit, moveCaret: boolean) {
79 const body = serializeBody(edit.blocks);
80 const changes = {
81 ...(edit.title !== note.title && { title: edit.title }),
82 ...(body !== note.body && { body }),
83 };
84 if (Object.keys(changes).length === 0) {
85 // Nothing to save (e.g. Enter at the end of a new note's title): just move.
86 if (moveCaret) placeCaret(edit.caret);
87 return;
88 }
89 // Placed after the re-render that shows the edit.
90 if (moveCaret) pendingCaret.current = edit.caret;
91 editNote(note.id, changes);
92 }
93​
94 const text = { title: note.title, blocks };
95​
96 useImperativeHandle(handleRef, () => ({
97 toggleChecklist: () => {
98 const field = Math.max(lastFocusedField.current, 0);
99 if (field >= blocks.length) return;
100 apply(toggleChecklist(text, field), true);
101 },
102 }));
103​
104 function onTitleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
105 if (event.nativeEvent.isComposing) return;
106 const { selectionStart, selectionEnd, value } = event.currentTarget;
107 if (event.key === "Enter") {
108 event.preventDefault();
109 apply(splitTitle(text, selectionStart, selectionEnd), true);
110 } else if (event.key === "ArrowDown" && selectionStart === value.length) {
111 event.preventDefault();
112 placeCaret({ field: 0, offset: 0 });
113 }
114 }
115​
116 function onBlockKeyDown(event: KeyboardEvent<HTMLTextAreaElement>, index: number) {
117 if (event.nativeEvent.isComposing) return;
118 const { selectionStart, selectionEnd, value } = event.currentTarget;
119 const collapsed = selectionStart === selectionEnd;
120 if (event.key === "Enter") {
121 event.preventDefault();
122 apply(splitBlock(text, index, selectionStart, selectionEnd), true);
123 } else if (event.key === "Backspace" && collapsed && selectionStart === 0) {
124 event.preventDefault();
125 apply(joinWithPrevious(text, index), true);
126 } else if (event.key === "ArrowUp" && collapsed && selectionStart === 0) {
127 event.preventDefault();
128 const previous = index === 0 ? note.title : blocks[index - 1]!.text;
129 placeCaret({ field: index - 1, offset: previous.length });
130 } else if (event.key === "ArrowDown" && collapsed && selectionEnd === value.length) {
131 if (index + 1 >= blocks.length) return;
132 event.preventDefault();
133 placeCaret({ field: index + 1, offset: 0 });
134 }
135 }
136​
137 const register = (field: number) => (element: HTMLTextAreaElement | null) => {
138 if (element) fields.current.set(field, element);
139 else fields.current.delete(field);
140 };
141​
142 return (
143 <div
144 className={cn(ios ? "text-[17px] leading-[1.45]" : "text-[13.5px] leading-[1.5]")}
145 onFocus={(event) => {
146 const field = [...fields.current].find(
147 ([, element]) => element === (event.target as Element),
148 )?.[0];
149 if (field !== undefined) lastFocusedField.current = field;
150 }}
151 >
152 <EditorField
153 ref={register(TITLE)}
154 aria-label="Title"
155 placeholder="Title"
156 value={note.title}
157 onChange={(event) => {
158 const { value, selectionStart } = event.currentTarget;
159 const edit = setTitle(text, value, selectionStart);
160 apply(edit, edit.blocks.length !== blocks.length);
161 }}
162 onKeyDown={onTitleKeyDown}
163 className={cn(
164 "font-bold tracking-[-0.01em]",
165 ios ? "mb-1.5 text-[28px] leading-tight" : "mb-1 text-[22px] leading-tight",
166 )}
167 />
168 <div role="group" aria-label="Note body">
169 {blocks.map((block, index) => (
170 <BlockRow
171 key={index}
172 block={block}
173 ios={ios}
174 onToggleChecked={() =>
175 editNote(note.id, { body: serializeBody(toggleChecked(blocks, index)) })
176 }
177 >
178 <EditorField
179 ref={register(index)}
180 aria-label={blockLabel(block, index)}
181 value={block.text}
182 onChange={(event) => {
183 const { value, selectionStart } = event.currentTarget;
184 const edit = setBlockText(text, index, value, selectionStart);
185 const structural =
186 edit.blocks.length !== blocks.length || edit.blocks[index]!.type !== block.type;
187 apply(edit, structural);
188 }}
189 onKeyDown={(event) => onBlockKeyDown(event, index)}
190 className={cn(
191 block.type === "heading" && cn("font-bold", ios ? "text-[20px]" : "text-[17px]"),
192 block.type === "checklist" &&
193 block.checked &&
194 "text-mac-text-secondary line-through",
195 )}
196 />
197 </BlockRow>
198 ))}
199 </div>
200 </div>
201 );
203​
204function blockLabel(block: NoteBlock, index: number): string {
205 const kind = { heading: "Heading", paragraph: "Line", bullet: "Bullet", checklist: "To-do" };
206 return `${kind[block.type]} ${index + 1}`;
208​
209function BlockRow({
210 block,
211 ios,
212 onToggleChecked,
213 children,
214}: {
215 block: NoteBlock;
216 ios: boolean;
217 onToggleChecked: () => void;
218 children: React.ReactNode;
219}) {
220 switch (block.type) {
221 case "heading":
222 return <div className={ios ? "mt-3" : "mt-2.5"}>{children}</div>;
223 case "bullet":
224 return (
225 <div className="flex gap-2 pl-1">
226 <span aria-hidden>•</span>
227 {children}
228 </div>
229 );
230 case "checklist":
231 return (
232 <div className={cn("flex items-start", ios ? "gap-3 py-1" : "gap-2 py-px")}>
233 <button
234 type="button"
235 role="checkbox"
236 aria-checked={block.checked}
237 aria-label={block.text || "To-do"}
238 onClick={onToggleChecked}
239 className={cn(
240 "grid shrink-0 place-items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-notes-accent/60",
241 ios ? "mt-[1px] size-[24px]" : "mt-[2px] size-[16px]",
242 block.checked
243 ? "bg-notes-accent text-white"
244 : "border-[1.5px] border-[#b5b5b8] dark:border-[#5c5c60]",
245 )}
246 >
247 {block.checked && <Check className="size-[65%]" strokeWidth={3} />}
248 </button>
249 {children}
250 </div>
251 );
252 case "paragraph":
253 return children;
254 }
256​
257/**
258 * A borderless textarea that grows with its text, so a long line wraps
259 * like the rest of the note instead of scrolling.
260 */
261function EditorField({ className, value, ref, ...props }: ComponentProps<"textarea">) {
262 const innerRef = useRef<HTMLTextAreaElement>(null);
263​
264 useLayoutEffect(() => {
265 const element = innerRef.current;
266 if (!element) return;
267 const fit = () => {
268 element.style.height = "0px";
269 element.style.height = `${element.scrollHeight}px`;
270 };
271 fit();
272 let width = element.offsetWidth;
273 const observer = new ResizeObserver(() => {
274 if (element.offsetWidth === width) return;
275 width = element.offsetWidth;
276 fit();
277 });
278 observer.observe(element);
279 return () => observer.disconnect();
280 }, [value]);
281​
282 return (
283 <textarea
284 ref={(element) => {
285 innerRef.current = element;
286 if (typeof ref === "function") return ref(element);
287 if (ref) ref.current = element;
288 }}
289 rows={1}
290 spellCheck
291 value={value}
292 className={cn(
293 "block w-full min-w-0 resize-none overflow-hidden border-0 bg-transparent p-0 text-inherit outline-none placeholder:text-mac-text-secondary/70",
294 className,
295 )}
296 {...props}
297 />
298 );