Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c389bab46e | |||
| bd2b8e6241 | |||
| 4328bbaeda | |||
| bf8e98dd49 | |||
| 2ebfa4caaf |
10
.dockerignore
Normal file
10
.dockerignore
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
.git
|
||||||
|
.gitea
|
||||||
|
build
|
||||||
|
desktop
|
||||||
|
frontend/node_modules
|
||||||
|
frontend/dist
|
||||||
|
server/webdist/dist
|
||||||
|
notes.zip
|
||||||
|
*.md
|
||||||
|
.env.docker
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -9,4 +9,5 @@ desktop/build/bin/
|
|||||||
*.db-wal
|
*.db-wal
|
||||||
*.db-shm
|
*.db-shm
|
||||||
notes.zip
|
notes.zip
|
||||||
|
.env.docker
|
||||||
!server/webdist/dist/.gitkeep
|
!server/webdist/dist/.gitkeep
|
||||||
|
|||||||
40
Dockerfile
Normal file
40
Dockerfile
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
# Build the frontend bundle (vite), then the static tefterd binary that
|
||||||
|
# embeds it, then ship binary-only. VERSION flows in from compose
|
||||||
|
# (${TEFTER_VERSION}) so `tefterd version` matches the git describe.
|
||||||
|
|
||||||
|
# Fully-qualified images (podman enforces short-name resolution non-interactively).
|
||||||
|
FROM docker.io/library/node:22-alpine AS frontend
|
||||||
|
WORKDIR /src/frontend
|
||||||
|
COPY frontend/package.json frontend/package-lock.json ./
|
||||||
|
RUN npm ci --no-audit --no-fund
|
||||||
|
COPY frontend/ ./
|
||||||
|
ARG VERSION=dev
|
||||||
|
RUN TEFTER_VERSION=$VERSION npx vite build
|
||||||
|
|
||||||
|
FROM docker.io/library/golang:1.25-alpine AS build
|
||||||
|
# git enables the GOPROXY "direct" fallback (fetch modules from their VCS).
|
||||||
|
RUN apk add --no-cache git
|
||||||
|
# Overridable for hosts where proxy.golang.org (Google) is unreachable —
|
||||||
|
# set e.g. GOPROXY=https://goproxy.io,direct in .env.docker. Module
|
||||||
|
# integrity is still verified against the committed go.sum either way.
|
||||||
|
ARG GOPROXY=https://proxy.golang.org,direct
|
||||||
|
ENV GOPROXY=$GOPROXY
|
||||||
|
WORKDIR /src/server
|
||||||
|
COPY server/go.mod server/go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY server/ ./
|
||||||
|
# go:embed cannot reach outside the module dir, so the bundle is copied in
|
||||||
|
# (same as the Makefile does).
|
||||||
|
COPY --from=frontend /src/frontend/dist ./webdist/dist
|
||||||
|
ARG VERSION=dev
|
||||||
|
RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X main.Version=$VERSION" -o /tefterd .
|
||||||
|
|
||||||
|
FROM docker.io/library/alpine:3.22
|
||||||
|
RUN adduser -D -H tefter && mkdir -p /data && chown tefter /data
|
||||||
|
COPY --from=build /tefterd /usr/local/bin/tefterd
|
||||||
|
USER tefter
|
||||||
|
ENV TEFTER_DB=/data/tefter.db
|
||||||
|
# The auth token is generated and printed to the logs on first start.
|
||||||
|
EXPOSE 8420
|
||||||
|
VOLUME /data
|
||||||
|
CMD ["tefterd"]
|
||||||
@@ -31,6 +31,7 @@ Open `http://localhost:8420`, click `⋯` → set server URL + token → Save.
|
|||||||
| `Ctrl/Cmd+Shift+P` | toggle markdown preview (`[[wiki-links]]` open/create notes) |
|
| `Ctrl/Cmd+Shift+P` | toggle markdown preview (`[[wiki-links]]` open/create notes) |
|
||||||
| `Ctrl/Cmd+K` | cycle tag filter |
|
| `Ctrl/Cmd+K` | cycle tag filter |
|
||||||
| `Ctrl/Cmd+J` / `+Shift` | next / previous note while editing |
|
| `Ctrl/Cmd+J` / `+Shift` | next / previous note while editing |
|
||||||
|
| `Ctrl/Cmd+I` | note info (created / last synced) & version history |
|
||||||
|
|
||||||
## CLI
|
## CLI
|
||||||
|
|
||||||
@@ -96,6 +97,12 @@ edits of the same note never silently overwrite: the loser comes back as a new n
|
|||||||
tagged `conflict` with “(conflicted copy …)” in its title. Delete-vs-edit: the edit wins.
|
tagged `conflict` with “(conflicted copy …)” in its title. Delete-vs-edit: the edit wins.
|
||||||
Every client keeps a full offline copy in IndexedDB; a crash mid-sync loses nothing.
|
Every client keeps a full offline copy in IndexedDB; a crash mid-sync loses nothing.
|
||||||
|
|
||||||
|
**Version history:** every time an accepted sync overwrites a note, the server keeps the
|
||||||
|
previous state (last 50 revisions per note). `Ctrl/Cmd+I` (or the “History” button under
|
||||||
|
the editor) shows a note’s revisions; restoring one applies the old text as a new edit,
|
||||||
|
so the replaced text itself stays in history — rollback is never destructive.
|
||||||
|
`tefterd compact` drops history along with the purged notes.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
14
SPEC.md
14
SPEC.md
@@ -92,17 +92,29 @@ CREATE TABLE notes (
|
|||||||
CREATE INDEX idx_notes_version ON notes(version);
|
CREATE INDEX idx_notes_version ON notes(version);
|
||||||
|
|
||||||
CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT); -- schema_version, next_version counter
|
CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT); -- schema_version, next_version counter
|
||||||
|
|
||||||
|
CREATE TABLE note_history ( -- schema v2: version history
|
||||||
|
note_id TEXT NOT NULL,
|
||||||
|
version INTEGER NOT NULL, -- version of the superseded revision
|
||||||
|
content TEXT NOT NULL DEFAULT '',
|
||||||
|
tags TEXT NOT NULL DEFAULT '[]',
|
||||||
|
modified_at INTEGER NOT NULL,
|
||||||
|
replaced_at INTEGER NOT NULL, -- unix ms when it was overwritten
|
||||||
|
PRIMARY KEY (note_id, version)
|
||||||
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Title is derived**, never stored: first non-empty line of `content`, markdown heading markers stripped for display.
|
- **Title is derived**, never stored: first non-empty line of `content`, markdown heading markers stripped for display.
|
||||||
- `version` is a single global monotonically increasing counter (like a Lamport clock per server). Every accepted write bumps the global counter and stamps the note. This makes "give me everything changed since cursor X" trivial.
|
- `version` is a single global monotonically increasing counter (like a Lamport clock per server). Every accepted write bumps the global counter and stamps the note. This makes "give me everything changed since cursor X" trivial.
|
||||||
- Tombstones are kept forever (personal scale; millions of notes are not expected). A `tefterd compact` subcommand may purge tombstones older than N days.
|
- Tombstones are kept forever (personal scale; millions of notes are not expected). A `tefterd compact` subcommand may purge tombstones older than N days.
|
||||||
|
- **Version history:** whenever an accepted push overwrites an existing note (fast-forward or edit-over-tombstone), the superseded state is copied into `note_history`, capped at the newest 50 revisions per note. Conflict pushes touch nothing, so they record nothing. `compact` purges history rows of notes that no longer exist. Rollback is client-side: fetch a revision, apply its content as a normal edit.
|
||||||
|
|
||||||
### Client store (IndexedDB)
|
### Client store (IndexedDB)
|
||||||
|
|
||||||
Object store `notes`: same fields as server, plus:
|
Object store `notes`: same fields as server, plus:
|
||||||
- `dirty: boolean` — locally modified, not yet pushed.
|
- `dirty: boolean` — locally modified, not yet pushed.
|
||||||
- `baseVersion: number` — server version this local copy was derived from (0 for never-synced).
|
- `baseVersion: number` — server version this local copy was derived from (0 for never-synced).
|
||||||
|
- `synced_at?: number` — unix ms of the last confirmed exchange with the server for this note (accepted push or applied pull); absent = never synced.
|
||||||
|
|
||||||
Object store `meta`: `cursor` (last server version pulled), `serverUrl`, `token`.
|
Object store `meta`: `cursor` (last server version pulled), `serverUrl`, `token`.
|
||||||
|
|
||||||
@@ -116,6 +128,7 @@ Design: **pull-then-push, last-write-wins with conflict copies** (Simplenote-sty
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| GET | `/changes?since=<cursor>&limit=500` | Pull notes with `version > cursor`, ordered by version. Returns `{notes: [...], cursor: <max version returned>, more: bool}` |
|
| GET | `/changes?since=<cursor>&limit=500` | Pull notes with `version > cursor`, ordered by version. Returns `{notes: [...], cursor: <max version returned>, more: bool}` |
|
||||||
| POST | `/notes/batch` | Push local changes. Body: `{notes: [{id, content, tags, created_at, modified_at, deleted, baseVersion}]}` |
|
| POST | `/notes/batch` | Push local changes. Body: `{notes: [{id, content, tags, created_at, modified_at, deleted, baseVersion}]}` |
|
||||||
|
| GET | `/notes/{id}/history` | Superseded revisions of a note, newest first: `{revisions: [{note_id, version, content, tags, modified_at, replaced_at}]}` (empty list for unknown ids) |
|
||||||
| GET | `/health` | Liveness + schema version |
|
| GET | `/health` | Liveness + schema version |
|
||||||
| POST | `/import/simplenote` | Multipart upload of Simplenote export zip (also available as CLI) |
|
| POST | `/import/simplenote` | Multipart upload of Simplenote export zip (also available as CLI) |
|
||||||
|
|
||||||
@@ -187,6 +200,7 @@ This section is the heart of the product. The NV model must be reproduced exactl
|
|||||||
| Cmd/Ctrl+Shift+P | Toggle markdown preview for current note |
|
| Cmd/Ctrl+Shift+P | Toggle markdown preview for current note |
|
||||||
| Cmd/Ctrl+K | Cycle tag filter (simple tag dropdown) |
|
| Cmd/Ctrl+K | Cycle tag filter (simple tag dropdown) |
|
||||||
| Cmd/Ctrl+J / Cmd/Ctrl+Shift+J | Next / previous note in list while in editor |
|
| Cmd/Ctrl+J / Cmd/Ctrl+Shift+J | Next / previous note in list while in editor |
|
||||||
|
| Cmd/Ctrl+I | Note info (created / modified / last synced) + version history panel; a revision can be previewed and restored (restore = normal edit, non-destructive) |
|
||||||
|
|
||||||
### Editor
|
### Editor
|
||||||
- CodeMirror 6, markdown mode, light syntax styling only (bold headings, dim syntax marks). Monospace or user-set font. No WYSIWYG.
|
- CodeMirror 6, markdown mode, light syntax styling only (bold headings, dim syntax marks). Monospace or user-set font. No WYSIWYG.
|
||||||
|
|||||||
32
deploy/redeploy-tefter.sh
Executable file
32
deploy/redeploy-tefter.sh
Executable file
@@ -0,0 +1,32 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
APP_DIR=$HOME/tefter
|
||||||
|
SERVICE=tefter.service
|
||||||
|
|
||||||
|
cd "$APP_DIR"
|
||||||
|
|
||||||
|
# Host-specific settings (WEB_PORT, GOPROXY, ...) live in .env.docker next to
|
||||||
|
# the compose file; export them so compose interpolation sees them.
|
||||||
|
set -a; [ -f .env.docker ] && . ./.env.docker; set +a
|
||||||
|
WEB_PORT=${WEB_PORT:-8420}
|
||||||
|
|
||||||
|
echo "==> Pulling latest code..."
|
||||||
|
git pull
|
||||||
|
|
||||||
|
echo "==> Rebuilding container..."
|
||||||
|
TEFTER_VERSION=$(git describe --tags --always --dirty) podman-compose build
|
||||||
|
|
||||||
|
echo "==> Restarting service..."
|
||||||
|
systemctl --user restart $SERVICE
|
||||||
|
|
||||||
|
echo "==> Waiting for boot..."
|
||||||
|
sleep 5
|
||||||
|
|
||||||
|
if curl -s -o /dev/null -w "" http://localhost:$WEB_PORT/; then
|
||||||
|
echo "==> Deploy successful! App is running on port $WEB_PORT."
|
||||||
|
podman-compose logs --tail 5 tefter 2>&1
|
||||||
|
else
|
||||||
|
echo "==> WARNING: App may not be ready yet. Check logs:"
|
||||||
|
podman-compose logs --tail 20 tefter 2>&1
|
||||||
|
fi
|
||||||
20
deploy/tefter.service
Normal file
20
deploy/tefter.service
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
# User unit — install to ~/.config/systemd/user/tefter.service, then:
|
||||||
|
# systemctl --user daemon-reload && systemctl --user enable --now tefter.service
|
||||||
|
# Requires lingering (loginctl enable-linger) so it survives logout.
|
||||||
|
|
||||||
|
[Unit]
|
||||||
|
Description=Tefter notes server (podman-compose)
|
||||||
|
Wants=network-online.target
|
||||||
|
After=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory=%h/tefter
|
||||||
|
EnvironmentFile=%h/tefter/.env.docker
|
||||||
|
ExecStart=/home/hamo/.local/bin/podman-compose up
|
||||||
|
ExecStop=/home/hamo/.local/bin/podman-compose down
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
21
docker-compose.yml
Normal file
21
docker-compose.yml
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
services:
|
||||||
|
tefter:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
args:
|
||||||
|
VERSION: ${TEFTER_VERSION:-dev}
|
||||||
|
GOPROXY: ${GOPROXY:-https://proxy.golang.org,direct}
|
||||||
|
environment:
|
||||||
|
TEFTER_DB: /data/tefter.db
|
||||||
|
volumes:
|
||||||
|
# ":Z" relabels for SELinux (required on the podman/SELinux server; a
|
||||||
|
# harmless no-op on non-SELinux Docker hosts).
|
||||||
|
- data:/data:Z
|
||||||
|
security_opt:
|
||||||
|
- label:disable
|
||||||
|
ports:
|
||||||
|
- "${WEB_PORT:-8420}:8420"
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
data:
|
||||||
@@ -102,10 +102,11 @@ export async function applyServerNote(sn: ServerNote): Promise<void> {
|
|||||||
export async function applyServerNotes(sns: ServerNote[]): Promise<void> {
|
export async function applyServerNotes(sns: ServerNote[]): Promise<void> {
|
||||||
const m = get(notes);
|
const m = get(notes);
|
||||||
const updates: Note[] = [];
|
const updates: Note[] = [];
|
||||||
|
const now = Date.now();
|
||||||
for (const sn of sns) {
|
for (const sn of sns) {
|
||||||
const local = m.get(sn.id);
|
const local = m.get(sn.id);
|
||||||
if (local && local.dirty) continue; // push will resolve
|
if (local && local.dirty) continue; // push will resolve
|
||||||
updates.push({ ...sn, baseVersion: sn.version, dirty: false });
|
updates.push({ ...sn, baseVersion: sn.version, dirty: false, synced_at: now });
|
||||||
}
|
}
|
||||||
if (!updates.length) return;
|
if (!updates.length) return;
|
||||||
notes.update((map) => {
|
notes.update((map) => {
|
||||||
@@ -120,14 +121,14 @@ export async function markPushed(id: string, sentModifiedAt: number, version: nu
|
|||||||
const n = get(notes).get(id);
|
const n = get(notes).get(id);
|
||||||
if (!n) return;
|
if (!n) return;
|
||||||
const stillSame = n.modified_at === sentModifiedAt;
|
const stillSame = n.modified_at === sentModifiedAt;
|
||||||
const upd: Note = { ...n, version, baseVersion: version, dirty: stillSame ? false : n.dirty };
|
const upd: Note = { ...n, version, baseVersion: version, dirty: stillSame ? false : n.dirty, synced_at: Date.now() };
|
||||||
mutate(upd);
|
mutate(upd);
|
||||||
await idbPutNote(upd);
|
await idbPutNote(upd);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** After a conflict: server truth replaces local; conflict copy arrives via next pull. */
|
/** After a conflict: server truth replaces local; conflict copy arrives via next pull. */
|
||||||
export async function replaceWithServer(sn: ServerNote): Promise<void> {
|
export async function replaceWithServer(sn: ServerNote): Promise<void> {
|
||||||
const upd: Note = { ...sn, baseVersion: sn.version, dirty: false };
|
const upd: Note = { ...sn, baseVersion: sn.version, dirty: false, synced_at: Date.now() };
|
||||||
mutate(upd);
|
mutate(upd);
|
||||||
await idbPutNote(upd);
|
await idbPutNote(upd);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { writable, get } from 'svelte/store';
|
import { writable, get } from 'svelte/store';
|
||||||
import type { PushResult, ServerNote, SyncState } from '../types';
|
import type { PushResult, Revision, ServerNote, SyncState } from '../types';
|
||||||
import { notes, settings, cursor, setCursor, applyServerNotes, markPushed, replaceWithServer } from '../db/store';
|
import { notes, settings, cursor, setCursor, applyServerNotes, markPushed, replaceWithServer } from '../db/store';
|
||||||
|
|
||||||
export const syncState = writable<SyncState>('local');
|
export const syncState = writable<SyncState>('local');
|
||||||
@@ -66,6 +66,15 @@ async function push(): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Fetch a note's server-side revision history (newest first). */
|
||||||
|
export async function fetchHistory(id: string): Promise<Revision[]> {
|
||||||
|
if (!configured()) throw new Error('no server configured');
|
||||||
|
const res = await api(`/api/v1/notes/${encodeURIComponent(id)}/history`);
|
||||||
|
if (!res.ok) throw new Error(`history: HTTP ${res.status}`);
|
||||||
|
const body: { revisions: Revision[] } = await res.json();
|
||||||
|
return body.revisions;
|
||||||
|
}
|
||||||
|
|
||||||
/** Pull-then-push; safe to interrupt at any point (SPEC §4). */
|
/** Pull-then-push; safe to interrupt at any point (SPEC §4). */
|
||||||
export async function syncNow(): Promise<void> {
|
export async function syncNow(): Promise<void> {
|
||||||
if (!configured()) {
|
if (!configured()) {
|
||||||
|
|||||||
13
frontend/src/time.ts
Normal file
13
frontend/src/time.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
/** Absolute timestamp for metadata display, e.g. "Jul 25, 2026, 14:03". */
|
||||||
|
export function fmtDateTime(ms: number): string {
|
||||||
|
return new Date(ms).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Coarse relative timestamp: "just now", "5 min ago", "3 h ago", else absolute. */
|
||||||
|
export function fmtAgo(ms: number, now: number = Date.now()): string {
|
||||||
|
const d = now - ms;
|
||||||
|
if (d < 60_000) return 'just now';
|
||||||
|
if (d < 3_600_000) return `${Math.floor(d / 60_000)} min ago`;
|
||||||
|
if (d < 86_400_000) return `${Math.floor(d / 3_600_000)} h ago`;
|
||||||
|
return fmtDateTime(ms);
|
||||||
|
}
|
||||||
@@ -8,6 +8,17 @@ export interface Note {
|
|||||||
version: number; // server-assigned version of the copy we derived from (0 = never synced)
|
version: number; // server-assigned version of the copy we derived from (0 = never synced)
|
||||||
baseVersion: number; // server version this local copy was derived from
|
baseVersion: number; // server version this local copy was derived from
|
||||||
dirty: boolean; // locally modified, not yet pushed
|
dirty: boolean; // locally modified, not yet pushed
|
||||||
|
synced_at?: number; // unix ms of last confirmed server exchange (absent = never synced)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A superseded note state kept server-side (GET /notes/{id}/history). */
|
||||||
|
export interface Revision {
|
||||||
|
note_id: string;
|
||||||
|
version: number;
|
||||||
|
content: string;
|
||||||
|
tags: string[];
|
||||||
|
modified_at: number;
|
||||||
|
replaced_at: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ServerNote {
|
export interface ServerNote {
|
||||||
|
|||||||
@@ -10,13 +10,17 @@
|
|||||||
import Preview from './Preview.svelte';
|
import Preview from './Preview.svelte';
|
||||||
import StatusDot from './StatusDot.svelte';
|
import StatusDot from './StatusDot.svelte';
|
||||||
import SettingsMenu from './SettingsMenu.svelte';
|
import SettingsMenu from './SettingsMenu.svelte';
|
||||||
|
import NoteInfo from './NoteInfo.svelte';
|
||||||
import Toast from './Toast.svelte';
|
import Toast from './Toast.svelte';
|
||||||
|
import { fmtDateTime, fmtAgo } from '../time';
|
||||||
|
|
||||||
let query = '';
|
let query = '';
|
||||||
let selectedId: string | null = null;
|
let selectedId: string | null = null;
|
||||||
let tagFilter: string | null = null;
|
let tagFilter: string | null = null;
|
||||||
let preview = false;
|
let preview = false;
|
||||||
let menuOpen = false;
|
let menuOpen = false;
|
||||||
|
let infoOpen = false;
|
||||||
|
let now = Date.now(); // periodic tick so "synced X ago" stays fresh
|
||||||
let narrow = false;
|
let narrow = false;
|
||||||
let mobileView: 'list' | 'editor' = 'list';
|
let mobileView: 'list' | 'editor' = 'list';
|
||||||
let toast: { message: string; onAction: () => void } | null = null;
|
let toast: { message: string; onAction: () => void } | null = null;
|
||||||
@@ -142,6 +146,9 @@
|
|||||||
} else if (mod && e.shiftKey && e.key.toLowerCase() === 'p') {
|
} else if (mod && e.shiftKey && e.key.toLowerCase() === 'p') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (selected) preview = !preview;
|
if (selected) preview = !preview;
|
||||||
|
} else if (mod && !e.shiftKey && e.key.toLowerCase() === 'i') {
|
||||||
|
e.preventDefault();
|
||||||
|
if (selected) infoOpen = !infoOpen;
|
||||||
} else if (mod && !e.shiftKey && e.key.toLowerCase() === 'k') {
|
} else if (mod && !e.shiftKey && e.key.toLowerCase() === 'k') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
cycleTag();
|
cycleTag();
|
||||||
@@ -161,13 +168,17 @@
|
|||||||
narrow = mq.matches;
|
narrow = mq.matches;
|
||||||
const onMq = () => (narrow = mq.matches);
|
const onMq = () => (narrow = mq.matches);
|
||||||
mq.addEventListener('change', onMq);
|
mq.addEventListener('change', onMq);
|
||||||
|
const tick = setInterval(() => (now = Date.now()), 30_000);
|
||||||
omnibar?.focus();
|
omnibar?.focus();
|
||||||
// First run: offer server config; Cancel = work locally only (SPEC §7).
|
// First run: offer server config; Cancel = work locally only (SPEC §7).
|
||||||
if (!localStorage.getItem('tefter-first-run-done')) {
|
if (!localStorage.getItem('tefter-first-run-done')) {
|
||||||
localStorage.setItem('tefter-first-run-done', '1');
|
localStorage.setItem('tefter-first-run-done', '1');
|
||||||
if (!notesArr.length && !$settings.serverUrl) menuOpen = true;
|
if (!notesArr.length && !$settings.serverUrl) menuOpen = true;
|
||||||
}
|
}
|
||||||
return () => mq.removeEventListener('change', onMq);
|
return () => {
|
||||||
|
mq.removeEventListener('change', onMq);
|
||||||
|
clearInterval(tick);
|
||||||
|
};
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -219,6 +230,24 @@
|
|||||||
<p>Type to search — <kbd>Enter</kbd> creates a note when nothing matches.</p>
|
<p>Type to search — <kbd>Enter</kbd> creates a note when nothing matches.</p>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
{#if selected}
|
||||||
|
<div class="note-meta">
|
||||||
|
<span>Created {fmtDateTime(selected.created_at)}</span>
|
||||||
|
<span class="meta-sep">·</span>
|
||||||
|
<span>
|
||||||
|
{#if selected.dirty}
|
||||||
|
Sync pending
|
||||||
|
{:else if selected.synced_at}
|
||||||
|
Synced {fmtAgo(selected.synced_at, now)}
|
||||||
|
{:else}
|
||||||
|
Not synced
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
<button class="meta-btn" title="Note info & version history (Ctrl+I)" on:click={() => (infoOpen = true)}>
|
||||||
|
History
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
@@ -227,6 +256,10 @@
|
|||||||
<SettingsMenu on:close={() => (menuOpen = false)} />
|
<SettingsMenu on:close={() => (menuOpen = false)} />
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
{#if infoOpen && selected}
|
||||||
|
<NoteInfo note={selected} on:close={() => (infoOpen = false)} />
|
||||||
|
{/if}
|
||||||
|
|
||||||
{#if toast}
|
{#if toast}
|
||||||
<Toast message={toast.message} actionLabel="Undo" onAction={toast.onAction} on:done={() => (toast = null)} />
|
<Toast message={toast.message} actionLabel="Undo" onAction={toast.onAction} on:done={() => (toast = null)} />
|
||||||
{/if}
|
{/if}
|
||||||
@@ -319,6 +352,30 @@
|
|||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
.note-meta {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 3px 10px;
|
||||||
|
border-top: 1px solid var(--sep);
|
||||||
|
font-size: 11.5px;
|
||||||
|
color: var(--fg-dim);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.meta-sep {
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
.meta-btn {
|
||||||
|
margin-left: auto;
|
||||||
|
color: var(--accent);
|
||||||
|
font-size: 11.5px;
|
||||||
|
padding: 2px 6px;
|
||||||
|
border-radius: 5px;
|
||||||
|
}
|
||||||
|
.meta-btn:hover {
|
||||||
|
background: var(--sel-bg);
|
||||||
|
}
|
||||||
.empty {
|
.empty {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
@@ -106,39 +106,52 @@
|
|||||||
|
|
||||||
// Swap document when a different note is opened; apply external (sync) changes
|
// Swap document when a different note is opened; apply external (sync) changes
|
||||||
// without clobbering in-flight typing.
|
// without clobbering in-flight typing.
|
||||||
$: if (view && note) {
|
function applyNote(n: Note) {
|
||||||
if (note.id !== currentId) {
|
if (!view || !n) return;
|
||||||
|
if (n.id !== currentId) {
|
||||||
if (saveTimer) {
|
if (saveTimer) {
|
||||||
clearTimeout(saveTimer);
|
clearTimeout(saveTimer);
|
||||||
saveTimer = null;
|
saveTimer = null;
|
||||||
flushSave(currentId, view.state.doc.toString());
|
flushSave(currentId, view.state.doc.toString());
|
||||||
}
|
}
|
||||||
currentId = note.id;
|
currentId = n.id;
|
||||||
lastKnown = note.content;
|
lastKnown = n.content;
|
||||||
view.setState(makeState(note.content));
|
view.setState(makeState(n.content));
|
||||||
} else if (note.content !== lastKnown) {
|
} else if (n.content !== lastKnown) {
|
||||||
// Store changed underneath us (sync pull / conflict replacement) — not an
|
// Store changed underneath us (sync pull / conflict replacement) — not an
|
||||||
// echo of our own autosave. Replace the doc.
|
// echo of our own autosave. Replace the doc.
|
||||||
lastKnown = note.content;
|
lastKnown = n.content;
|
||||||
if (saveTimer) {
|
if (saveTimer) {
|
||||||
clearTimeout(saveTimer);
|
clearTimeout(saveTimer);
|
||||||
saveTimer = null;
|
saveTimer = null;
|
||||||
}
|
}
|
||||||
if (note.content !== view.state.doc.toString()) {
|
if (n.content !== view.state.doc.toString()) {
|
||||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: note.content } });
|
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: n.content } });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let lastQuery = '';
|
let lastQuery = '';
|
||||||
$: if (view && query !== lastQuery) {
|
function applyQuery(q: string) {
|
||||||
lastQuery = query;
|
if (!view || q === lastQuery) return;
|
||||||
view.dispatch({ effects: searchMark.reconfigure(searchExtension(query)) });
|
lastQuery = q;
|
||||||
|
view.dispatch({ effects: searchMark.reconfigure(searchExtension(q)) });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Deliberately `$: fn(prop)` instead of inlining the logic in a reactive
|
||||||
|
// block: these must re-run ONLY when the prop itself changes. Svelte tracks
|
||||||
|
// every variable a `$:` statement mentions (including writes like
|
||||||
|
// `saveTimer = null` deep in the autosave path), and a re-run triggered by
|
||||||
|
// our own bookkeeping sees a stale `note`, misreads the autosave echo as an
|
||||||
|
// external sync change, and replaces the doc mid-typing — which on Android
|
||||||
|
// aborts IME composition and throws the cursor to the top of the note.
|
||||||
|
$: applyNote(note);
|
||||||
|
$: applyQuery(query);
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
currentId = note.id;
|
currentId = note.id;
|
||||||
lastKnown = note.content;
|
lastKnown = note.content;
|
||||||
|
lastQuery = query; // makeState below bakes in the current query
|
||||||
view = new EditorView({ state: makeState(note.content), parent: host });
|
view = new EditorView({ state: makeState(note.content), parent: host });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
220
frontend/src/ui/NoteInfo.svelte
Normal file
220
frontend/src/ui/NoteInfo.svelte
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount, createEventDispatcher } from 'svelte';
|
||||||
|
import { get } from 'svelte/store';
|
||||||
|
import { settings, updateContent } from '../db/store';
|
||||||
|
import { fetchHistory, notifyEdit } from '../sync/engine';
|
||||||
|
import { noteTitle } from '../search';
|
||||||
|
import { fmtDateTime, fmtAgo } from '../time';
|
||||||
|
import type { Note, Revision } from '../types';
|
||||||
|
|
||||||
|
export let note: Note;
|
||||||
|
|
||||||
|
const dispatch = createEventDispatcher<{ close: void }>();
|
||||||
|
|
||||||
|
let revisions: Revision[] = [];
|
||||||
|
let loading = true;
|
||||||
|
let error = '';
|
||||||
|
let selected: Revision | null = null;
|
||||||
|
|
||||||
|
const hasServer = !!get(settings).serverUrl;
|
||||||
|
|
||||||
|
$: syncLabel = note.dirty
|
||||||
|
? 'changes pending' + (note.synced_at ? ` · last synced ${fmtAgo(note.synced_at)}` : '')
|
||||||
|
: note.synced_at
|
||||||
|
? fmtAgo(note.synced_at)
|
||||||
|
: 'never';
|
||||||
|
|
||||||
|
function fmtSize(chars: number): string {
|
||||||
|
return chars < 1024 ? `${chars} chars` : `${(chars / 1024).toFixed(1)}k chars`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function restore(rev: Revision) {
|
||||||
|
await updateContent(note.id, rev.content);
|
||||||
|
notifyEdit();
|
||||||
|
dispatch('close');
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(async () => {
|
||||||
|
if (!hasServer) {
|
||||||
|
loading = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
revisions = await fetchHistory(note.id);
|
||||||
|
} catch (e) {
|
||||||
|
error = e instanceof Error ? e.message : String(e);
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<!-- svelte-ignore a11y-click-events-have-key-events a11y-no-static-element-interactions -->
|
||||||
|
<div class="backdrop" on:click|self={() => dispatch('close')}>
|
||||||
|
<div class="panel">
|
||||||
|
<h2>{noteTitle(note.content)}</h2>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h3>Info</h3>
|
||||||
|
<dl>
|
||||||
|
<dt>Created</dt>
|
||||||
|
<dd>{fmtDateTime(note.created_at)}</dd>
|
||||||
|
<dt>Modified</dt>
|
||||||
|
<dd>{fmtDateTime(note.modified_at)}</dd>
|
||||||
|
<dt>Last synced</dt>
|
||||||
|
<dd>{syncLabel}</dd>
|
||||||
|
{#if note.version > 0}
|
||||||
|
<dt>Server version</dt>
|
||||||
|
<dd>{note.version}</dd>
|
||||||
|
{/if}
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h3>History</h3>
|
||||||
|
{#if !hasServer}
|
||||||
|
<div class="hint">Versions are recorded on the server — configure sync in Settings to get history.</div>
|
||||||
|
{:else if loading}
|
||||||
|
<div class="hint">Loading…</div>
|
||||||
|
{:else if error}
|
||||||
|
<div class="hint">Couldn’t load history: {error}</div>
|
||||||
|
{:else if !revisions.length}
|
||||||
|
<div class="hint">No older versions yet. A version is saved every time a synced note is overwritten.</div>
|
||||||
|
{:else}
|
||||||
|
<ul class="revs">
|
||||||
|
{#each revisions as rev (rev.version)}
|
||||||
|
<li>
|
||||||
|
<button
|
||||||
|
class="rev"
|
||||||
|
class:active={selected?.version === rev.version}
|
||||||
|
on:click={() => (selected = selected?.version === rev.version ? null : rev)}
|
||||||
|
>
|
||||||
|
<span class="rev-when">{fmtDateTime(rev.modified_at)}</span>
|
||||||
|
<span class="rev-size">{fmtSize(rev.content.length)}</span>
|
||||||
|
</button>
|
||||||
|
{#if selected?.version === rev.version}
|
||||||
|
<pre class="rev-preview">{rev.content}</pre>
|
||||||
|
<button class="btn primary" on:click={() => restore(rev)}>Restore this version</button>
|
||||||
|
{/if}
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
<div class="hint">Restoring applies the old text as a new edit — nothing is lost, the current text stays in history.</div>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="actions">
|
||||||
|
<button class="btn" on:click={() => dispatch('close')}>Close</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.backdrop {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 40;
|
||||||
|
background: rgba(0, 0, 0, 0.3);
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: center;
|
||||||
|
padding-top: 8vh;
|
||||||
|
}
|
||||||
|
.panel {
|
||||||
|
background: var(--bg-panel);
|
||||||
|
border: 1px solid var(--sep);
|
||||||
|
border-radius: 10px;
|
||||||
|
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
|
||||||
|
width: min(520px, 92vw);
|
||||||
|
max-height: 84vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 18px 22px;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
margin: 0 0 6px;
|
||||||
|
font-size: 17px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
h3 {
|
||||||
|
margin: 14px 0 6px;
|
||||||
|
font-size: 13px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
|
color: var(--fg-dim);
|
||||||
|
}
|
||||||
|
dl {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: auto 1fr;
|
||||||
|
gap: 3px 14px;
|
||||||
|
margin: 0;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
dt {
|
||||||
|
color: var(--fg-dim);
|
||||||
|
}
|
||||||
|
dd {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.hint {
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--fg-dim);
|
||||||
|
margin-top: 6px;
|
||||||
|
}
|
||||||
|
.revs {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.rev {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
padding: 5px 8px;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.rev:hover,
|
||||||
|
.rev.active {
|
||||||
|
background: var(--sel-bg);
|
||||||
|
}
|
||||||
|
.rev-size {
|
||||||
|
color: var(--fg-dim);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.rev-preview {
|
||||||
|
margin: 4px 0 2px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
max-height: 180px;
|
||||||
|
overflow: auto;
|
||||||
|
border: 1px solid var(--sep);
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--bg);
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 12px;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
.btn {
|
||||||
|
border: 1px solid var(--sep);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 5px 14px;
|
||||||
|
margin-top: 4px;
|
||||||
|
background: var(--bg);
|
||||||
|
}
|
||||||
|
.btn.primary {
|
||||||
|
background: var(--accent);
|
||||||
|
border-color: var(--accent);
|
||||||
|
color: #fff;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
.actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -28,6 +28,7 @@ func (s *Server) Handler() http.Handler {
|
|||||||
mux.HandleFunc("GET /api/v1/health", s.handleHealth)
|
mux.HandleFunc("GET /api/v1/health", s.handleHealth)
|
||||||
mux.Handle("GET /api/v1/changes", s.auth(s.handleChanges))
|
mux.Handle("GET /api/v1/changes", s.auth(s.handleChanges))
|
||||||
mux.Handle("POST /api/v1/notes/batch", s.auth(s.handleBatch))
|
mux.Handle("POST /api/v1/notes/batch", s.auth(s.handleBatch))
|
||||||
|
mux.Handle("GET /api/v1/notes/{id}/history", s.auth(s.handleHistory))
|
||||||
mux.Handle("POST /api/v1/import/simplenote", s.auth(s.handleImport))
|
mux.Handle("POST /api/v1/import/simplenote", s.auth(s.handleImport))
|
||||||
mux.HandleFunc("OPTIONS /api/v1/", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("OPTIONS /api/v1/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
@@ -108,6 +109,16 @@ func (s *Server) handleBatch(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, map[string]any{"results": results})
|
writeJSON(w, map[string]any{"results": results})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleHistory(w http.ResponseWriter, r *http.Request) {
|
||||||
|
revs, err := s.Store.History(r.PathValue("id"))
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("history: %v", err)
|
||||||
|
jsonError(w, http.StatusInternalServerError, "internal error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, map[string]any{"revisions": revs})
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) handleImport(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleImport(w http.ResponseWriter, r *http.Request) {
|
||||||
if err := r.ParseMultipartForm(64 << 20); err != nil {
|
if err := r.ParseMultipartForm(64 << 20); err != nil {
|
||||||
jsonError(w, http.StatusBadRequest, "bad multipart form: "+err.Error())
|
jsonError(w, http.StatusBadRequest, "bad multipart form: "+err.Error())
|
||||||
|
|||||||
@@ -229,6 +229,45 @@ func TestTwoClientsConverge(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestHistoryEndpoint(t *testing.T) {
|
||||||
|
srv, tok := newTestServer(t)
|
||||||
|
a := newClient(t, srv.URL, tok)
|
||||||
|
|
||||||
|
a.edit("n1", "v1")
|
||||||
|
a.sync()
|
||||||
|
a.edit("n1", "v2")
|
||||||
|
a.notes["n1"].ModifiedAt = 2
|
||||||
|
a.sync()
|
||||||
|
|
||||||
|
var body struct {
|
||||||
|
Revisions []store.Revision `json:"revisions"`
|
||||||
|
}
|
||||||
|
if code := a.req("GET", "/api/v1/notes/n1/history", nil, &body); code != 200 {
|
||||||
|
t.Fatalf("history HTTP %d", code)
|
||||||
|
}
|
||||||
|
if len(body.Revisions) != 1 || body.Revisions[0].Content != "v1" {
|
||||||
|
t.Fatalf("history: %+v", body.Revisions)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unknown note → empty list, not an error.
|
||||||
|
if code := a.req("GET", "/api/v1/notes/nope/history", nil, &body); code != 200 {
|
||||||
|
t.Fatalf("unknown note HTTP %d", code)
|
||||||
|
}
|
||||||
|
if len(body.Revisions) != 0 {
|
||||||
|
t.Fatalf("want empty history, got %+v", body.Revisions)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auth required.
|
||||||
|
res, err := http.Get(srv.URL + "/api/v1/notes/n1/history")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
res.Body.Close()
|
||||||
|
if res.StatusCode != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("want 401, got %d", res.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestDeleteEditConflictAcrossClients(t *testing.T) {
|
func TestDeleteEditConflictAcrossClients(t *testing.T) {
|
||||||
srv, tok := newTestServer(t)
|
srv, tok := newTestServer(t)
|
||||||
a := newClient(t, srv.URL, tok)
|
a := newClient(t, srv.URL, tok)
|
||||||
|
|||||||
@@ -17,7 +17,10 @@ import (
|
|||||||
_ "modernc.org/sqlite"
|
_ "modernc.org/sqlite"
|
||||||
)
|
)
|
||||||
|
|
||||||
const SchemaVersion = 1
|
const SchemaVersion = 2
|
||||||
|
|
||||||
|
// historyKeep caps stored revisions per note; older ones are pruned on write.
|
||||||
|
const historyKeep = 50
|
||||||
|
|
||||||
type Note struct {
|
type Note struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
@@ -29,6 +32,16 @@ type Note struct {
|
|||||||
Version int64 `json:"version"`
|
Version int64 `json:"version"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Revision is a superseded note state, recorded when an accepted push overwrites it.
|
||||||
|
type Revision struct {
|
||||||
|
NoteID string `json:"note_id"`
|
||||||
|
Version int64 `json:"version"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
Tags []string `json:"tags"`
|
||||||
|
ModifiedAt int64 `json:"modified_at"`
|
||||||
|
ReplacedAt int64 `json:"replaced_at"`
|
||||||
|
}
|
||||||
|
|
||||||
type IncomingNote struct {
|
type IncomingNote struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
@@ -83,11 +96,22 @@ CREATE TABLE IF NOT EXISTS notes (
|
|||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS idx_notes_version ON notes(version);
|
CREATE INDEX IF NOT EXISTS idx_notes_version ON notes(version);
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_notes_source ON notes(source_id) WHERE source_id IS NOT NULL;
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_notes_source ON notes(source_id) WHERE source_id IS NOT NULL;
|
||||||
|
CREATE TABLE IF NOT EXISTS note_history (
|
||||||
|
note_id TEXT NOT NULL,
|
||||||
|
version INTEGER NOT NULL,
|
||||||
|
content TEXT NOT NULL DEFAULT '',
|
||||||
|
tags TEXT NOT NULL DEFAULT '[]',
|
||||||
|
modified_at INTEGER NOT NULL,
|
||||||
|
replaced_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (note_id, version)
|
||||||
|
);
|
||||||
CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT);
|
CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT);
|
||||||
INSERT OR IGNORE INTO meta (k, v) VALUES ('schema_version', '1');
|
|
||||||
INSERT OR IGNORE INTO meta (k, v) VALUES ('next_version', '1');
|
INSERT OR IGNORE INTO meta (k, v) VALUES ('next_version', '1');
|
||||||
`)
|
`)
|
||||||
return err
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return s.setMeta("schema_version", strconv.Itoa(SchemaVersion))
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- meta helpers ---
|
// --- meta helpers ---
|
||||||
@@ -228,6 +252,45 @@ func getNoteTx(tx *sql.Tx, id string) (*Note, error) {
|
|||||||
return &n, nil
|
return &n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// recordHistoryTx snapshots the note state that is about to be overwritten,
|
||||||
|
// then prunes revisions beyond historyKeep.
|
||||||
|
func recordHistoryTx(tx *sql.Tx, n *Note, now time.Time) error {
|
||||||
|
if _, err := tx.Exec(
|
||||||
|
`INSERT OR REPLACE INTO note_history (note_id, version, content, tags, modified_at, replaced_at) VALUES (?,?,?,?,?,?)`,
|
||||||
|
n.ID, n.Version, n.Content, tagsJSON(n.Tags), n.ModifiedAt, now.UnixMilli()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := tx.Exec(
|
||||||
|
`DELETE FROM note_history WHERE note_id = ? AND version NOT IN (
|
||||||
|
SELECT version FROM note_history WHERE note_id = ? ORDER BY version DESC LIMIT ?)`,
|
||||||
|
n.ID, n.ID, historyKeep)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// History returns a note's superseded revisions, newest first.
|
||||||
|
func (s *Store) History(noteID string) ([]Revision, error) {
|
||||||
|
rows, err := s.db.Query(
|
||||||
|
`SELECT note_id, version, content, tags, modified_at, replaced_at
|
||||||
|
FROM note_history WHERE note_id = ? ORDER BY version DESC`, noteID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
revs := []Revision{}
|
||||||
|
for rows.Next() {
|
||||||
|
var r Revision
|
||||||
|
var tags string
|
||||||
|
if err := rows.Scan(&r.NoteID, &r.Version, &r.Content, &tags, &r.ModifiedAt, &r.ReplacedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal([]byte(tags), &r.Tags); err != nil || r.Tags == nil {
|
||||||
|
r.Tags = []string{}
|
||||||
|
}
|
||||||
|
revs = append(revs, r)
|
||||||
|
}
|
||||||
|
return revs, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
// conflictTitle appends the marker to the first non-empty line of content.
|
// conflictTitle appends the marker to the first non-empty line of content.
|
||||||
func conflictTitle(content string, at time.Time) string {
|
func conflictTitle(content string, at time.Time) string {
|
||||||
marker := at.Format(" (conflicted copy 2006-01-02 15:04)")
|
marker := at.Format(" (conflicted copy 2006-01-02 15:04)")
|
||||||
@@ -281,6 +344,9 @@ func (s *Store) ApplyBatch(in []IncomingNote, now time.Time) ([]PushResult, erro
|
|||||||
|
|
||||||
case inc.BaseVersion == cur.Version:
|
case inc.BaseVersion == cur.Version:
|
||||||
// Rule 2: clean fast-forward.
|
// Rule 2: clean fast-forward.
|
||||||
|
if err := recordHistoryTx(tx, cur, now); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
v, err := nextVersionTx(tx)
|
v, err := nextVersionTx(tx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -299,6 +365,9 @@ func (s *Store) ApplyBatch(in []IncomingNote, now time.Time) ([]PushResult, erro
|
|||||||
|
|
||||||
case cur.Deleted:
|
case cur.Deleted:
|
||||||
// Rule 4b: stale edit vs server tombstone → edit wins, overwrites the tombstone.
|
// Rule 4b: stale edit vs server tombstone → edit wins, overwrites the tombstone.
|
||||||
|
if err := recordHistoryTx(tx, cur, now); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
v, err := nextVersionTx(tx)
|
v, err := nextVersionTx(tx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -370,13 +439,17 @@ func (s *Store) UpsertImported(sourceID string, n Note) (bool, error) {
|
|||||||
return true, tx.Commit()
|
return true, tx.Commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compact purges tombstones older than the given number of days.
|
// Compact purges tombstones older than the given number of days, plus the
|
||||||
|
// history of any note that no longer exists.
|
||||||
func (s *Store) Compact(olderThanDays int) (int64, error) {
|
func (s *Store) Compact(olderThanDays int) (int64, error) {
|
||||||
cutoff := time.Now().AddDate(0, 0, -olderThanDays).UnixMilli()
|
cutoff := time.Now().AddDate(0, 0, -olderThanDays).UnixMilli()
|
||||||
res, err := s.db.Exec(`DELETE FROM notes WHERE deleted = 1 AND modified_at < ?`, cutoff)
|
res, err := s.db.Exec(`DELETE FROM notes WHERE deleted = 1 AND modified_at < ?`, cutoff)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
if _, err := s.db.Exec(`DELETE FROM note_history WHERE note_id NOT IN (SELECT id FROM notes)`); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
return res.RowsAffected()
|
return res.RowsAffected()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package store
|
package store
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -159,6 +160,104 @@ func TestChangesPaging(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestHistoryRecordsSupersededRevisions(t *testing.T) {
|
||||||
|
s := newTestStore(t)
|
||||||
|
|
||||||
|
r1 := push(t, s, IncomingNote{ID: "a", Content: "v1", Tags: []string{"t"}, ModifiedAt: 1})
|
||||||
|
if revs, _ := s.History("a"); len(revs) != 0 {
|
||||||
|
t.Fatalf("insert must not create history, got %d", len(revs))
|
||||||
|
}
|
||||||
|
|
||||||
|
r2 := push(t, s, IncomingNote{ID: "a", Content: "v2", ModifiedAt: 2, BaseVersion: r1.Version})
|
||||||
|
r3 := push(t, s, IncomingNote{ID: "a", Content: "v3", ModifiedAt: 3, BaseVersion: r2.Version})
|
||||||
|
|
||||||
|
revs, err := s.History("a")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(revs) != 2 {
|
||||||
|
t.Fatalf("want 2 revisions, got %d", len(revs))
|
||||||
|
}
|
||||||
|
// Newest first: the v2 state (superseded by the v3 push), then v1.
|
||||||
|
if revs[0].Content != "v2" || revs[0].Version != r2.Version {
|
||||||
|
t.Fatalf("revs[0] = %+v", revs[0])
|
||||||
|
}
|
||||||
|
if revs[1].Content != "v1" || revs[1].Version != r1.Version || !containsStr(revs[1].Tags, "t") {
|
||||||
|
t.Fatalf("revs[1] = %+v", revs[1])
|
||||||
|
}
|
||||||
|
if revs[0].ReplacedAt == 0 {
|
||||||
|
t.Fatal("replaced_at not stamped")
|
||||||
|
}
|
||||||
|
_ = r3
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHistoryRecordedOnDeleteAndResurrect(t *testing.T) {
|
||||||
|
s := newTestStore(t)
|
||||||
|
|
||||||
|
r1 := push(t, s, IncomingNote{ID: "a", Content: "precious", ModifiedAt: 1})
|
||||||
|
r2 := push(t, s, IncomingNote{ID: "a", Content: "precious", Deleted: true, ModifiedAt: 2, BaseVersion: r1.Version})
|
||||||
|
// Stale edit overwrites the tombstone (rule 4b) — tombstone state goes to history.
|
||||||
|
push(t, s, IncomingNote{ID: "a", Content: "resurrected", ModifiedAt: 3, BaseVersion: r1.Version})
|
||||||
|
|
||||||
|
revs, err := s.History("a")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(revs) != 2 || revs[0].Version != r2.Version || revs[1].Content != "precious" {
|
||||||
|
t.Fatalf("history after delete+resurrect: %+v", revs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHistoryNotRecordedOnConflict(t *testing.T) {
|
||||||
|
s := newTestStore(t)
|
||||||
|
|
||||||
|
r1 := push(t, s, IncomingNote{ID: "a", Content: "base", ModifiedAt: 1})
|
||||||
|
push(t, s, IncomingNote{ID: "a", Content: "B's edit", ModifiedAt: 2, BaseVersion: r1.Version})
|
||||||
|
// Stale edit → conflict copy; server note untouched, so no new history entry.
|
||||||
|
push(t, s, IncomingNote{ID: "a", Content: "A's edit", ModifiedAt: 3, BaseVersion: r1.Version})
|
||||||
|
|
||||||
|
revs, _ := s.History("a")
|
||||||
|
if len(revs) != 1 || revs[0].Content != "base" {
|
||||||
|
t.Fatalf("conflict must not record history: %+v", revs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHistoryPrunedToCap(t *testing.T) {
|
||||||
|
s := newTestStore(t)
|
||||||
|
r := push(t, s, IncomingNote{ID: "a", Content: "v0", ModifiedAt: 0})
|
||||||
|
for i := 1; i <= historyKeep+10; i++ {
|
||||||
|
r = push(t, s, IncomingNote{ID: "a", Content: fmt.Sprintf("v%d", i), ModifiedAt: int64(i), BaseVersion: r.Version})
|
||||||
|
}
|
||||||
|
revs, err := s.History("a")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(revs) != historyKeep {
|
||||||
|
t.Fatalf("want %d revisions after prune, got %d", historyKeep, len(revs))
|
||||||
|
}
|
||||||
|
if revs[0].Content != fmt.Sprintf("v%d", historyKeep+9) {
|
||||||
|
t.Fatalf("newest revision wrong: %q", revs[0].Content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompactPurgesOrphanHistory(t *testing.T) {
|
||||||
|
s := newTestStore(t)
|
||||||
|
old := time.Now().AddDate(0, 0, -200).UnixMilli()
|
||||||
|
r1 := push(t, s, IncomingNote{ID: "a", Content: "x", ModifiedAt: old})
|
||||||
|
push(t, s, IncomingNote{ID: "a", Deleted: true, ModifiedAt: old, BaseVersion: r1.Version})
|
||||||
|
|
||||||
|
if _, err := s.Compact(90); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
revs, err := s.History("a")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(revs) != 0 {
|
||||||
|
t.Fatalf("history must be purged with the note, got %d", len(revs))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestTokenRoundtrip(t *testing.T) {
|
func TestTokenRoundtrip(t *testing.T) {
|
||||||
s := newTestStore(t)
|
s := newTestStore(t)
|
||||||
tok, err := s.EnsureToken()
|
tok, err := s.EnsureToken()
|
||||||
|
|||||||
Reference in New Issue
Block a user