mirror of
https://github.com/bretzel-app/crumbs.git
synced 2026-10-12 12:06:57 +02:00
feat: add note version history and restore (#note-history)
Co-authored-by: fredicious <1580688+fredicious@users.noreply.github.com>
This commit is contained in:
committed by
Fred Cabassut
co-authored by
fredicious
parent
8ed915bc69
commit
0b34654736
@@ -5,6 +5,7 @@
|
||||
import TiptapEditor from './TiptapEditor.svelte';
|
||||
import ImageUpload from './ImageUpload.svelte';
|
||||
import ShareDialog from './ShareDialog.svelte';
|
||||
import NoteHistory from './NoteHistory.svelte';
|
||||
import { updateNote, createNote } from '$lib/stores/notes.js';
|
||||
import { notes } from '$lib/stores/notes.js';
|
||||
import { NOTE_COLORS } from '$lib/utils/colors.js';
|
||||
@@ -19,6 +20,7 @@
|
||||
import FileText from 'lucide-svelte/icons/file-text';
|
||||
import UserPlus from 'lucide-svelte/icons/user-plus';
|
||||
import Users from 'lucide-svelte/icons/users';
|
||||
import History from 'lucide-svelte/icons/history';
|
||||
|
||||
interface Props {
|
||||
note: Note | null;
|
||||
@@ -55,6 +57,7 @@
|
||||
let attachmentsList = $state<Attachment[]>(note?.attachments ?? []);
|
||||
|
||||
let showShareDialog = $state(false);
|
||||
let showHistory = $state(false);
|
||||
// svelte-ignore state_referenced_locally
|
||||
let collaboratorsList = $state<Collaborator[]>(note?.collaborators ?? []);
|
||||
const isOwner = $derived(note?.isOwner !== false);
|
||||
@@ -84,6 +87,37 @@
|
||||
showShareDialog = !showShareDialog;
|
||||
}
|
||||
|
||||
async function toggleHistory() {
|
||||
if (currentlyNew) {
|
||||
const id = await autoSave();
|
||||
if (!id) return;
|
||||
}
|
||||
showHistory = !showHistory;
|
||||
}
|
||||
|
||||
async function handleHistoryRestored() {
|
||||
if (!noteId) return;
|
||||
// Reload the note content from the server after a restore
|
||||
try {
|
||||
const res = await fetch(`/api/notes/${noteId}`);
|
||||
if (res.ok) {
|
||||
const updated = await res.json();
|
||||
title = updated.title ?? '';
|
||||
content = updated.content ?? '';
|
||||
color = updated.color ?? 'default';
|
||||
checklistMode = updated.checklistMode ?? false;
|
||||
// Bump editor tick to force TiptapEditor to re-render
|
||||
editorTick++;
|
||||
// Update the store too
|
||||
notes.update((list) =>
|
||||
list.map((n) => (n.id === noteId ? { ...n, ...updated } : n))
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// failed silently
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch attachments for existing notes if not pre-populated (e.g. loaded from IDB)
|
||||
$effect(() => {
|
||||
if (noteId && !currentlyNew && (!note?.attachments || note.attachments.length === 0)) {
|
||||
@@ -381,6 +415,18 @@
|
||||
<Users class="h-5 w-5" />
|
||||
</span>
|
||||
{/if}
|
||||
|
||||
<!-- History button (only for saved notes) -->
|
||||
{#if !currentlyNew}
|
||||
<button
|
||||
onclick={toggleHistory}
|
||||
class="rounded-sm p-2 hover:bg-[var(--border)]/10"
|
||||
title="Version history"
|
||||
data-testid="history-toggle"
|
||||
>
|
||||
<History class="h-5 w-5 {showHistory ? 'text-[var(--primary)]' : ''}" />
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<button
|
||||
@@ -403,3 +449,11 @@
|
||||
onUpdate={handleCollaboratorsUpdate}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if showHistory && noteId}
|
||||
<NoteHistory
|
||||
noteId={noteId}
|
||||
onClose={() => (showHistory = false)}
|
||||
onRestored={handleHistoryRestored}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
<script lang="ts">
|
||||
import type { NoteVersionSummary, NoteVersion } from '$lib/types/index.js';
|
||||
import X from 'lucide-svelte/icons/x';
|
||||
import RotateCcw from 'lucide-svelte/icons/rotate-ccw';
|
||||
import Clock from 'lucide-svelte/icons/clock';
|
||||
import { showToast } from '$lib/stores/toast.js';
|
||||
|
||||
interface Props {
|
||||
noteId: string;
|
||||
onClose: () => void;
|
||||
onRestored: () => void;
|
||||
}
|
||||
|
||||
const { noteId, onClose, onRestored }: Props = $props();
|
||||
|
||||
let versions = $state<NoteVersionSummary[]>([]);
|
||||
let selectedVersion = $state<NoteVersion | null>(null);
|
||||
let isLoading = $state(true);
|
||||
let isLoadingVersion = $state(false);
|
||||
let isRestoring = $state(false);
|
||||
let showConfirm = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
void loadVersions();
|
||||
});
|
||||
|
||||
async function loadVersions() {
|
||||
isLoading = true;
|
||||
try {
|
||||
const res = await fetch(`/api/notes/${noteId}/versions`);
|
||||
if (res.ok) {
|
||||
versions = await res.json();
|
||||
}
|
||||
} catch {
|
||||
// failed silently
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function selectVersion(versionId: string) {
|
||||
isLoadingVersion = true;
|
||||
selectedVersion = null;
|
||||
try {
|
||||
const res = await fetch(`/api/notes/${noteId}/versions/${versionId}`);
|
||||
if (res.ok) {
|
||||
selectedVersion = await res.json();
|
||||
}
|
||||
} catch {
|
||||
// failed silently
|
||||
} finally {
|
||||
isLoadingVersion = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreVersion() {
|
||||
if (!selectedVersion) return;
|
||||
isRestoring = true;
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/notes/${noteId}/versions/${selectedVersion.id}/restore`,
|
||||
{ method: 'POST' }
|
||||
);
|
||||
if (res.ok) {
|
||||
showToast('Version restored successfully', 'success');
|
||||
onRestored();
|
||||
onClose();
|
||||
} else {
|
||||
showToast('Failed to restore version', 'error');
|
||||
}
|
||||
} catch {
|
||||
showToast('Failed to restore version', 'error');
|
||||
} finally {
|
||||
isRestoring = false;
|
||||
showConfirm = false;
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(date: Date | string): string {
|
||||
const d = new Date(date);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - d.getTime();
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
const diffHours = Math.floor(diffMins / 60);
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
|
||||
if (diffMins < 1) return 'Just now';
|
||||
if (diffMins < 60) return `${diffMins} minute${diffMins === 1 ? '' : 's'} ago`;
|
||||
if (diffHours < 24) return `${diffHours} hour${diffHours === 1 ? '' : 's'} ago`;
|
||||
if (diffDays < 7) return `${diffDays} day${diffDays === 1 ? '' : 's'} ago`;
|
||||
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/50 pt-20 pb-10"
|
||||
onkeydown={(e) => { if (e.key === 'Escape') onClose(); }}
|
||||
onclick={(e) => { if (e.target === e.currentTarget) onClose(); }}
|
||||
data-testid="history-overlay"
|
||||
>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="mx-4 flex w-full max-w-2xl flex-col overflow-hidden rounded-sm border border-[var(--border)] bg-[var(--bg-surface)] shadow-[var(--card-shadow)]"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
onkeydown={(e) => e.stopPropagation()}
|
||||
data-testid="history-panel"
|
||||
>
|
||||
<!-- Header -->
|
||||
<div class="flex items-center justify-between border-b border-[var(--border-subtle)] px-4 py-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<Clock class="h-4 w-4 text-[var(--text-muted)]" />
|
||||
<h2 class="text-sm font-semibold text-[var(--text)]">Version History</h2>
|
||||
</div>
|
||||
<button
|
||||
onclick={onClose}
|
||||
class="rounded-sm p-1 hover:bg-[var(--border)]/10"
|
||||
title="Close history"
|
||||
data-testid="close-history-btn"
|
||||
>
|
||||
<X class="h-4 w-4 text-[var(--text-muted)]" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex min-h-0 flex-1">
|
||||
<!-- Version list -->
|
||||
<div class="w-56 flex-none border-r border-[var(--border-subtle)] overflow-y-auto max-h-[60vh]">
|
||||
{#if isLoading}
|
||||
<div class="flex items-center justify-center py-8 text-sm text-[var(--text-muted)]">
|
||||
Loading…
|
||||
</div>
|
||||
{:else if versions.length === 0}
|
||||
<div class="flex items-center justify-center py-8 text-sm text-[var(--text-muted)]">
|
||||
No history yet
|
||||
</div>
|
||||
{:else}
|
||||
<ul class="divide-y divide-[var(--border-subtle)]">
|
||||
{#each versions as v (v.id)}
|
||||
<li>
|
||||
<button
|
||||
class="w-full px-3 py-3 text-left hover:bg-[var(--border)]/10 transition-colors {selectedVersion?.id === v.id ? 'bg-[var(--primary)]/10 border-l-2 border-[var(--primary)]' : ''}"
|
||||
onclick={() => selectVersion(v.id)}
|
||||
data-testid="version-item"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-1">
|
||||
<span class="text-xs font-semibold text-[var(--primary)]">v{v.version}</span>
|
||||
</div>
|
||||
<div class="mt-0.5 text-xs text-[var(--text-muted)]">{formatDate(v.createdAt)}</div>
|
||||
{#if v.title}
|
||||
<div class="mt-1 truncate text-xs font-medium text-[var(--text)]">{v.title}</div>
|
||||
{/if}
|
||||
{#if v.contentPreview}
|
||||
<div class="mt-0.5 line-clamp-2 text-xs text-[var(--text-muted)]">{v.contentPreview}</div>
|
||||
{/if}
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Version preview -->
|
||||
<div class="flex min-w-0 flex-1 flex-col">
|
||||
{#if isLoadingVersion}
|
||||
<div class="flex items-center justify-center py-8 text-sm text-[var(--text-muted)]">
|
||||
Loading…
|
||||
</div>
|
||||
{:else if selectedVersion}
|
||||
<div class="flex flex-1 flex-col overflow-y-auto max-h-[60vh]">
|
||||
<div class="flex-1 overflow-y-auto px-4 py-3">
|
||||
{#if selectedVersion.title}
|
||||
<h3 class="mb-2 text-base font-semibold text-[var(--text)]">{selectedVersion.title}</h3>
|
||||
{/if}
|
||||
<pre class="whitespace-pre-wrap text-sm text-[var(--text)] font-[inherit]">{selectedVersion.content || '(empty)'}</pre>
|
||||
</div>
|
||||
|
||||
<!-- Restore footer -->
|
||||
<div class="border-t border-[var(--border-subtle)] px-4 py-3">
|
||||
{#if showConfirm}
|
||||
<div class="flex flex-col gap-2">
|
||||
<p class="text-xs text-[var(--text-muted)]">
|
||||
This will replace the current note. The current version will be saved as a snapshot.
|
||||
</p>
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
onclick={restoreVersion}
|
||||
disabled={isRestoring}
|
||||
class="flex items-center gap-1.5 rounded-sm border border-[var(--destructive)] bg-[var(--destructive)] px-3 py-1.5 text-xs font-medium text-white hover:opacity-90 disabled:opacity-50"
|
||||
data-testid="confirm-restore-btn"
|
||||
>
|
||||
<RotateCcw class="h-3.5 w-3.5" />
|
||||
{isRestoring ? 'Restoring…' : 'Confirm Restore'}
|
||||
</button>
|
||||
<button
|
||||
onclick={() => (showConfirm = false)}
|
||||
class="rounded-sm border border-[var(--border-subtle)] px-3 py-1.5 text-xs font-medium text-[var(--text)] hover:bg-[var(--border)]/10"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<button
|
||||
onclick={() => (showConfirm = true)}
|
||||
class="flex items-center gap-1.5 rounded-sm border border-[var(--border-subtle)] px-3 py-1.5 text-xs font-medium text-[var(--text)] hover:border-[var(--primary)] hover:text-[var(--primary)] transition-colors"
|
||||
data-testid="restore-btn"
|
||||
>
|
||||
<RotateCcw class="h-3.5 w-3.5" />
|
||||
Restore this version
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex items-center justify-center py-8 text-sm text-[var(--text-muted)]">
|
||||
Select a version to preview
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -123,6 +123,18 @@ sqlite.exec(`
|
||||
value TEXT NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS note_versions (
|
||||
id TEXT PRIMARY KEY,
|
||||
note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
|
||||
version INTEGER NOT NULL,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
checklist_mode INTEGER NOT NULL DEFAULT 0,
|
||||
color TEXT NOT NULL DEFAULT 'default',
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE(note_id, version)
|
||||
);
|
||||
`);
|
||||
|
||||
// Migration: detect old schema (no email column on users) and add columns
|
||||
@@ -196,6 +208,8 @@ sqlite.exec(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS note_user_state_unique ON note_user_state(note_id, user_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS user_preferences_user_key_unique ON user_preferences(user_id, key);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS note_versions_note_id_idx ON note_versions(note_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||
|
||||
@@ -189,3 +189,23 @@ export const userPreferences = sqliteTable(
|
||||
},
|
||||
(table) => [uniqueIndex('user_preferences_user_key_unique').on(table.userId, table.key)]
|
||||
);
|
||||
|
||||
export const noteVersions = sqliteTable(
|
||||
'note_versions',
|
||||
{
|
||||
id: text('id').primaryKey(),
|
||||
noteId: text('note_id')
|
||||
.references(() => notes.id, { onDelete: 'cascade' })
|
||||
.notNull(),
|
||||
version: integer('version').notNull(),
|
||||
title: text('title').notNull().default(''),
|
||||
content: text('content').notNull().default(''),
|
||||
checklistMode: integer('checklist_mode', { mode: 'boolean' }).notNull().default(false),
|
||||
color: text('color').notNull().default('default'),
|
||||
createdAt: integer('created_at', { mode: 'timestamp' }).notNull()
|
||||
},
|
||||
(table) => [
|
||||
index('note_versions_note_id_idx').on(table.noteId),
|
||||
uniqueIndex('note_versions_note_id_version_unique').on(table.noteId, table.version)
|
||||
]
|
||||
);
|
||||
|
||||
@@ -136,6 +136,19 @@ export function createTestDb(options?: { seedUser?: boolean }) {
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX user_preferences_user_key_unique ON user_preferences(user_id, key);
|
||||
|
||||
CREATE TABLE note_versions (
|
||||
id TEXT PRIMARY KEY,
|
||||
note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE,
|
||||
version INTEGER NOT NULL,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
checklist_mode INTEGER NOT NULL DEFAULT 0,
|
||||
color TEXT NOT NULL DEFAULT 'default',
|
||||
created_at INTEGER NOT NULL,
|
||||
UNIQUE(note_id, version)
|
||||
);
|
||||
CREATE INDEX note_versions_note_id_idx ON note_versions(note_id);
|
||||
`);
|
||||
|
||||
const db = drizzle(sqlite, { schema });
|
||||
|
||||
@@ -7,6 +7,7 @@ import { fetchTagsForNotes, syncNoteTags } from './tags.js';
|
||||
import { fetchAttachmentsForNotes } from './attachments.js';
|
||||
import { fetchCollaboratorsForNotes } from './collaborators.js';
|
||||
import { canAccessNote } from './api-utils.js';
|
||||
import { createSnapshot } from './versions-service.js';
|
||||
import type { NoteFilter } from '$lib/types/index.js';
|
||||
|
||||
interface NoteRow {
|
||||
@@ -293,6 +294,26 @@ export function updateNote(db: Db, userId: number, id: string, input: UpdateNote
|
||||
}
|
||||
}
|
||||
|
||||
// Create a version snapshot whenever content-related fields are saved
|
||||
const hasContentUpdate =
|
||||
input.title !== undefined ||
|
||||
input.content !== undefined ||
|
||||
input.color !== undefined ||
|
||||
input.checklistMode !== undefined;
|
||||
|
||||
if (hasContentUpdate) {
|
||||
const saved = db.select().from(notes).where(eq(notes.id, id)).get();
|
||||
if (saved) {
|
||||
createSnapshot(db, id, {
|
||||
version: saved.version,
|
||||
title: saved.title,
|
||||
content: saved.content,
|
||||
checklistMode: saved.checklistMode,
|
||||
color: saved.color
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return getNote(db, userId, id);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { createTestDb } from './db/test-helpers.js';
|
||||
import { users, notes, noteVersions } from './db/schema.js';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import type { Db } from './db/index.js';
|
||||
import { createSnapshot, listVersions, getVersion, snapshotCurrentNote } from './versions-service.js';
|
||||
|
||||
let db: Db;
|
||||
|
||||
const OWNER_ID = 1;
|
||||
const NOTE_ID = 'note-history-test';
|
||||
|
||||
function seedUser() {
|
||||
db.insert(users)
|
||||
.values({
|
||||
id: OWNER_ID,
|
||||
email: 'owner@test.com',
|
||||
displayName: 'Owner',
|
||||
role: 'admin',
|
||||
authProvider: 'password',
|
||||
createdAt: new Date()
|
||||
})
|
||||
.run();
|
||||
}
|
||||
|
||||
function seedNote(overrides: Partial<typeof notes.$inferInsert> = {}) {
|
||||
const now = new Date();
|
||||
db.insert(notes)
|
||||
.values({
|
||||
id: NOTE_ID,
|
||||
userId: OWNER_ID,
|
||||
title: 'Test Note',
|
||||
content: 'Test content',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
version: 1,
|
||||
...overrides
|
||||
})
|
||||
.run();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
({ db } = createTestDb());
|
||||
seedUser();
|
||||
});
|
||||
|
||||
describe('createSnapshot', () => {
|
||||
it('should store a snapshot for a note', () => {
|
||||
seedNote();
|
||||
createSnapshot(db, NOTE_ID, {
|
||||
version: 1,
|
||||
title: 'Test Note',
|
||||
content: 'Test content',
|
||||
checklistMode: false,
|
||||
color: 'default'
|
||||
});
|
||||
|
||||
const rows = db.select().from(noteVersions).where(eq(noteVersions.noteId, NOTE_ID)).all();
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].version).toBe(1);
|
||||
expect(rows[0].title).toBe('Test Note');
|
||||
expect(rows[0].content).toBe('Test content');
|
||||
expect(rows[0].checklistMode).toBe(false);
|
||||
expect(rows[0].color).toBe('default');
|
||||
});
|
||||
|
||||
it('should not duplicate snapshots for the same version (onConflictDoNothing)', () => {
|
||||
seedNote();
|
||||
createSnapshot(db, NOTE_ID, { version: 1, title: 'A', content: '', checklistMode: false, color: 'default' });
|
||||
createSnapshot(db, NOTE_ID, { version: 1, title: 'B', content: '', checklistMode: false, color: 'default' });
|
||||
|
||||
const rows = db.select().from(noteVersions).where(eq(noteVersions.noteId, NOTE_ID)).all();
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].title).toBe('A'); // first one wins
|
||||
});
|
||||
|
||||
it('should prune to at most 50 snapshots', () => {
|
||||
seedNote();
|
||||
for (let i = 1; i <= 55; i++) {
|
||||
createSnapshot(db, NOTE_ID, {
|
||||
version: i,
|
||||
title: `Version ${i}`,
|
||||
content: '',
|
||||
checklistMode: false,
|
||||
color: 'default'
|
||||
});
|
||||
}
|
||||
|
||||
const rows = db.select().from(noteVersions).where(eq(noteVersions.noteId, NOTE_ID)).all();
|
||||
expect(rows).toHaveLength(50);
|
||||
// Oldest (v1–v5) should be pruned; newest (v6–v55) should remain
|
||||
const versions = rows.map((r) => r.version);
|
||||
expect(Math.min(...versions)).toBe(6);
|
||||
expect(Math.max(...versions)).toBe(55);
|
||||
});
|
||||
});
|
||||
|
||||
describe('listVersions', () => {
|
||||
it('should return an empty array when there are no versions', () => {
|
||||
seedNote();
|
||||
expect(listVersions(db, NOTE_ID)).toEqual([]);
|
||||
});
|
||||
|
||||
it('should return summaries sorted newest first', () => {
|
||||
seedNote();
|
||||
createSnapshot(db, NOTE_ID, { version: 1, title: 'First', content: 'Hello world', checklistMode: false, color: 'default' });
|
||||
createSnapshot(db, NOTE_ID, { version: 2, title: 'Second', content: 'Updated content here', checklistMode: false, color: 'mint' });
|
||||
|
||||
const summaries = listVersions(db, NOTE_ID);
|
||||
expect(summaries).toHaveLength(2);
|
||||
expect(summaries[0].version).toBe(2); // newest first
|
||||
expect(summaries[1].version).toBe(1);
|
||||
});
|
||||
|
||||
it('should truncate contentPreview to 80 characters', () => {
|
||||
seedNote();
|
||||
const longContent = 'a'.repeat(200);
|
||||
createSnapshot(db, NOTE_ID, { version: 1, title: 'T', content: longContent, checklistMode: false, color: 'default' });
|
||||
|
||||
const summaries = listVersions(db, NOTE_ID);
|
||||
expect(summaries[0].contentPreview).toHaveLength(80);
|
||||
});
|
||||
|
||||
it('should include correct summary fields', () => {
|
||||
seedNote();
|
||||
createSnapshot(db, NOTE_ID, { version: 3, title: 'My Title', content: 'My content', checklistMode: false, color: 'coral' });
|
||||
|
||||
const summaries = listVersions(db, NOTE_ID);
|
||||
expect(summaries[0]).toMatchObject({
|
||||
noteId: NOTE_ID,
|
||||
version: 3,
|
||||
title: 'My Title',
|
||||
contentPreview: 'My content'
|
||||
});
|
||||
expect(summaries[0].id).toBeTruthy();
|
||||
expect(summaries[0].createdAt).toBeInstanceOf(Date);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getVersion', () => {
|
||||
it('should return null for a non-existent version', () => {
|
||||
seedNote();
|
||||
expect(getVersion(db, NOTE_ID, 'non-existent-id')).toBeNull();
|
||||
});
|
||||
|
||||
it('should return the full version content', () => {
|
||||
seedNote();
|
||||
createSnapshot(db, NOTE_ID, {
|
||||
version: 2,
|
||||
title: 'Full Title',
|
||||
content: '# Heading\n\nSome content',
|
||||
checklistMode: true,
|
||||
color: 'mint'
|
||||
});
|
||||
|
||||
const summaries = listVersions(db, NOTE_ID);
|
||||
const versionId = summaries[0].id;
|
||||
|
||||
const version = getVersion(db, NOTE_ID, versionId);
|
||||
expect(version).not.toBeNull();
|
||||
expect(version!.version).toBe(2);
|
||||
expect(version!.title).toBe('Full Title');
|
||||
expect(version!.content).toBe('# Heading\n\nSome content');
|
||||
expect(version!.checklistMode).toBe(true);
|
||||
expect(version!.color).toBe('mint');
|
||||
});
|
||||
|
||||
it('should not return a version from a different note', () => {
|
||||
const OTHER_NOTE_ID = 'other-note';
|
||||
seedNote();
|
||||
db.insert(notes).values({
|
||||
id: OTHER_NOTE_ID,
|
||||
userId: OWNER_ID,
|
||||
title: 'Other',
|
||||
content: '',
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
version: 1
|
||||
}).run();
|
||||
|
||||
createSnapshot(db, OTHER_NOTE_ID, { version: 1, title: 'Other', content: 'Other content', checklistMode: false, color: 'default' });
|
||||
const summaries = listVersions(db, OTHER_NOTE_ID);
|
||||
const versionId = summaries[0].id;
|
||||
|
||||
// Requesting version from wrong noteId returns null
|
||||
expect(getVersion(db, NOTE_ID, versionId)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('snapshotCurrentNote', () => {
|
||||
it('should return false for a non-existent note', () => {
|
||||
expect(snapshotCurrentNote(db, 'non-existent')).toBe(false);
|
||||
});
|
||||
|
||||
it('should snapshot the current note state', () => {
|
||||
seedNote({ title: 'Current Title', content: 'Current content', version: 5 });
|
||||
|
||||
const result = snapshotCurrentNote(db, NOTE_ID);
|
||||
expect(result).toBe(true);
|
||||
|
||||
const rows = db.select().from(noteVersions).where(eq(noteVersions.noteId, NOTE_ID)).all();
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].version).toBe(5);
|
||||
expect(rows[0].title).toBe('Current Title');
|
||||
expect(rows[0].content).toBe('Current content');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { Db } from './db/index.js';
|
||||
import { noteVersions, notes } from './db/schema.js';
|
||||
import { eq, and, desc } from 'drizzle-orm';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import type { NoteVersion, NoteVersionSummary, NoteColor } from '$lib/types/index.js';
|
||||
|
||||
const MAX_VERSIONS_PER_NOTE = 50;
|
||||
const CONTENT_PREVIEW_LENGTH = 80;
|
||||
|
||||
/**
|
||||
* Create a snapshot of a note's current state.
|
||||
* Called on every save. Prunes snapshots beyond MAX_VERSIONS_PER_NOTE.
|
||||
*/
|
||||
export function createSnapshot(
|
||||
db: Db,
|
||||
noteId: string,
|
||||
snapshot: {
|
||||
version: number;
|
||||
title: string;
|
||||
content: string;
|
||||
checklistMode: boolean;
|
||||
color: string;
|
||||
}
|
||||
): void {
|
||||
const now = new Date();
|
||||
|
||||
db.insert(noteVersions)
|
||||
.values({
|
||||
id: uuidv4(),
|
||||
noteId,
|
||||
version: snapshot.version,
|
||||
title: snapshot.title,
|
||||
content: snapshot.content,
|
||||
checklistMode: snapshot.checklistMode,
|
||||
color: snapshot.color,
|
||||
createdAt: now
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.run();
|
||||
|
||||
// Prune: keep only the most recent MAX_VERSIONS_PER_NOTE snapshots
|
||||
const allVersions = db
|
||||
.select({ id: noteVersions.id })
|
||||
.from(noteVersions)
|
||||
.where(eq(noteVersions.noteId, noteId))
|
||||
.orderBy(desc(noteVersions.version))
|
||||
.all();
|
||||
|
||||
if (allVersions.length > MAX_VERSIONS_PER_NOTE) {
|
||||
const toDelete = allVersions.slice(MAX_VERSIONS_PER_NOTE).map((v) => v.id);
|
||||
for (const id of toDelete) {
|
||||
db.delete(noteVersions).where(eq(noteVersions.id, id)).run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List version summaries for a note, newest first.
|
||||
*/
|
||||
export function listVersions(db: Db, noteId: string): NoteVersionSummary[] {
|
||||
const rows = db
|
||||
.select()
|
||||
.from(noteVersions)
|
||||
.where(eq(noteVersions.noteId, noteId))
|
||||
.orderBy(desc(noteVersions.version))
|
||||
.all();
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
noteId: row.noteId,
|
||||
version: row.version,
|
||||
title: row.title,
|
||||
contentPreview: row.content.slice(0, CONTENT_PREVIEW_LENGTH),
|
||||
createdAt: row.createdAt
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full content of a specific version.
|
||||
*/
|
||||
export function getVersion(db: Db, noteId: string, versionId: string): NoteVersion | null {
|
||||
const row = db
|
||||
.select()
|
||||
.from(noteVersions)
|
||||
.where(and(eq(noteVersions.id, versionId), eq(noteVersions.noteId, noteId)))
|
||||
.get();
|
||||
|
||||
if (!row) return null;
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
noteId: row.noteId,
|
||||
version: row.version,
|
||||
title: row.title,
|
||||
content: row.content,
|
||||
checklistMode: row.checklistMode,
|
||||
color: row.color as NoteColor,
|
||||
createdAt: row.createdAt
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot the current state of a note (used before a restore).
|
||||
*/
|
||||
export function snapshotCurrentNote(db: Db, noteId: string): boolean {
|
||||
const currentNote = db.select().from(notes).where(eq(notes.id, noteId)).get();
|
||||
if (!currentNote) return false;
|
||||
|
||||
createSnapshot(db, noteId, {
|
||||
version: currentNote.version,
|
||||
title: currentNote.title,
|
||||
content: currentNote.content,
|
||||
checklistMode: currentNote.checklistMode,
|
||||
color: currentNote.color
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -98,5 +98,25 @@ export type NoteFilter = 'all' | 'archived' | 'trashed';
|
||||
|
||||
export type SyncStatus = 'synced' | 'syncing' | 'offline' | 'error';
|
||||
|
||||
export interface NoteVersionSummary {
|
||||
id: string;
|
||||
noteId: string;
|
||||
version: number;
|
||||
title: string;
|
||||
contentPreview: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface NoteVersion {
|
||||
id: string;
|
||||
noteId: string;
|
||||
version: number;
|
||||
title: string;
|
||||
content: string;
|
||||
checklistMode: boolean;
|
||||
color: NoteColor;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export type { UserPreferences } from './preferences.js';
|
||||
export { DEFAULT_PREFERENCES, BOOLEAN_PREF_KEYS } from './preferences.js';
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types.js';
|
||||
import { db } from '$lib/server/db/index.js';
|
||||
import { getUserId, requireNoteAccess } from '$lib/server/api-utils.js';
|
||||
import { listVersions } from '$lib/server/versions-service.js';
|
||||
|
||||
export const GET: RequestHandler = async ({ params, ...event }) => {
|
||||
const userId = getUserId(event);
|
||||
requireNoteAccess(db, params.id, userId);
|
||||
|
||||
const versions = listVersions(db, params.id);
|
||||
return json(versions);
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types.js';
|
||||
import { db } from '$lib/server/db/index.js';
|
||||
import { getUserId, requireNoteAccess } from '$lib/server/api-utils.js';
|
||||
import { getVersion } from '$lib/server/versions-service.js';
|
||||
|
||||
export const GET: RequestHandler = async ({ params, ...event }) => {
|
||||
const userId = getUserId(event);
|
||||
requireNoteAccess(db, params.id, userId);
|
||||
|
||||
const version = getVersion(db, params.id, params.versionId);
|
||||
if (!version) throw error(404, 'Version not found');
|
||||
|
||||
return json(version);
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types.js';
|
||||
import { db } from '$lib/server/db/index.js';
|
||||
import { getUserId, requireNoteAccess } from '$lib/server/api-utils.js';
|
||||
import { getVersion, snapshotCurrentNote } from '$lib/server/versions-service.js';
|
||||
import { updateNote } from '$lib/server/notes-service.js';
|
||||
|
||||
export const POST: RequestHandler = async ({ params, ...event }) => {
|
||||
const userId = getUserId(event);
|
||||
requireNoteAccess(db, params.id, userId);
|
||||
|
||||
const version = getVersion(db, params.id, params.versionId);
|
||||
if (!version) throw error(404, 'Version not found');
|
||||
|
||||
// Snapshot current state before overwriting so the user can undo the restore
|
||||
snapshotCurrentNote(db, params.id);
|
||||
|
||||
// Apply the restored content (updateNote will increment version + create a new snapshot)
|
||||
const restored = updateNote(db, userId, params.id, {
|
||||
title: version.title,
|
||||
content: version.content,
|
||||
checklistMode: version.checklistMode,
|
||||
color: version.color
|
||||
});
|
||||
|
||||
if (!restored) throw error(404, 'Note not found');
|
||||
|
||||
return json(restored);
|
||||
};
|
||||
Reference in New Issue
Block a user