export interface Note { id: string; title: string; content: string; createdAt: Date; updatedAt: Date; linksTo?: Note[]; linkedBy?: Note[]; } import { writable } from 'svelte/store'; function createNotesStore() { const { subscribe, set, update: innerUpdate } = writable([]); let currentNotes: Note[] = []; subscribe((value) => { currentNotes = value; }); const get = () => currentNotes; return { subscribe, add: async (note: Omit) => { // Skip if no note or empty required fields if (!note || !note.title?.trim() || !note.content?.trim()) { return; } const newNote = { ...note, createdAt: new Date(), updatedAt: new Date() }; const response = await fetch('/api/notes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newNote) }); if (!response.ok) { throw new Error('Failed to create note'); } // Get the created note with server-generated ID const createdNote = await response.json(); // Convert date strings to Date objects createdNote.createdAt = new Date(createdNote.createdAt); createdNote.updatedAt = new Date(createdNote.updatedAt); // Reload all notes to get updated link information await notes.load(); return createdNote; }, update: async (id: string, content: Partial) => { const response = await fetch(`/api/notes/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...content, updatedAt: new Date() }) }); if (!response.ok) { throw new Error('Failed to update note'); } const existingNote = get().find((note) => note.id === id); if (!existingNote) { throw new Error('Note not found'); } innerUpdate((notes) => notes.map((note) => note.id === id ? { ...note, ...content, updatedAt: new Date() } : note ) ); }, delete: async (id: string) => { const response = await fetch(`/api/notes/${id}`, { method: 'DELETE' }); if (!response.ok) { throw new Error('Failed to delete note'); } innerUpdate((notes) => notes.filter((note) => note.id !== id)); }, load: async () => { try { const response = await fetch('/api/notes'); if (!response.ok) { throw new Error('Failed to load notes'); } const notes: Note[] = await response.json(); if (!Array.isArray(notes)) { set([]); return; } set( notes.map((note) => ({ ...note, createdAt: new Date(note.createdAt), updatedAt: new Date(note.updatedAt) })) ); } catch (error) { console.error('Failed to load notes:', error); set([]); } }, importObsidianVault: async (file: File): Promise<{ imported: number }> => { try { const formData = new FormData(); formData.append('file', file); const response = await fetch('/api/notes/import', { method: 'POST', body: formData }); if (!response.ok) { throw new Error(`Failed to import Obsidian vault: ${response.statusText}`); } const result = await response.json(); // Reload notes to get the newly imported ones await notes.load(); return result; } catch (error) { console.error('Error importing Obsidian vault:', error); throw error; } } }; } export const notes = createNotesStore();