Open History to see the last commit
1/**
2 * Thin data-access layer for the Notes app.
3 *
4 * Phase 1 reads the static fixtures directly. Phase 2 swaps the internals for
5 * TanStack DB collections and live queries; the hook signatures stay the same,
6 * so the components don't need to change.
7 */
8import { useMemo } from "react";
9
10import { createSeedData } from "@/fixtures";
11import type { Account, Folder, Note } from "@/fixtures";
12import {
13 byUpdatedAtDesc,
14 noteMatchesView,
15 resolveFolderView,
16 SMART_FOLDERS,
17} from "@/lib/notes/folder-views";
18import type { FolderView } from "@/lib/notes/folder-views";
19
20const seed = createSeedData();
21
22const folders = [...seed.folders].sort((a, b) => a.position - b.position);
23
24export function useFolders(): Folder[] {
25 return folders;
26}
27
28export function useFolderView(folderId: string): FolderView | undefined {
29 return useMemo(() => resolveFolderView(folderId, folders), [folderId]);
30}
31
32/** Notes shown in a folder or smart folder, newest first. */
33export function useNotesInFolder(folderId: string): Note[] {
34 return useMemo(
35 () => seed.notes.filter((note) => noteMatchesView(note, folderId)).sort(byUpdatedAtDesc),
36 [folderId],
37 );
38}
39
40export function useNote(noteId: string): Note | undefined {
41 return useMemo(() => seed.notes.find((note) => note.id === noteId), [noteId]);
42}
43
44/**
45 * A note, but only if it belongs to the folder (or smart folder) in the URL.
46 * `/folders/work/notes/<a grocery list>` finds nothing, and so will a note
47 * that was just moved or deleted.
48 */
49export function useNoteInFolder(folderId: string, noteId: string): Note | undefined {
50 const note = useNote(noteId);
51 return note && noteMatchesView(note, folderId) ? note : undefined;
52}
53
54/** Note count per folder id, including the smart folders. */
55export function useNoteCounts(): Record<string, number> {
56 return useMemo(() => {
57 const ids = [...folders.map((f) => f.id), ...Object.keys(SMART_FOLDERS)];
58 return Object.fromEntries(
59 ids.map((id) => [id, seed.notes.filter((note) => noteMatchesView(note, id)).length]),
60 );
61 }, []);
62}
63
64export function useAccount(): Account {
65 return seed.account;
66}
67
68export type AccountSettings = Pick<
69 Account,
70 "name" | "email" | "defaultFolderId" | "sortNotesBy" | "newNotesStartWith" | "groupNotesByDate"
71>;
72
73/**
74 * Saves account settings. Phase 1 has no backend, so this only resolves;
75 * phase 2 turns it into an optimistic update on `accountCollection`.
76 */
77export async function updateAccountSettings(_settings: AccountSettings): Promise<void> {}