feat: projekte und suche im frontend

Projektleiste mit Filter, Suchfeld, Projektauswahl beim Anlegen und
Bearbeiten, Etikett auf der Clip-Karte und eigene Seite zum Verwalten.
Filter und Suche stehen in der URL; Live-Ereignisse respektieren den
aktiven Filter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 13:33:03 +01:00
1 parent 9ba4655662
commit eba5621082
21 files changed
+1084 -37

No files matched your search

+98 -1
View File
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { Clip } from '@/api/types'
import { ClipConflictError, useClipsStore } from './clips'
import { ClipConflictError, matchesFilter, useClipsStore } from './clips'
function clip(overrides: Partial<Clip> = {}): Clip {
return {
@@ -13,6 +13,7 @@ function clip(overrides: Partial<Clip> = {}): Clip {
content: 'hello',
language: null,
pinned: false,
project_id: null,
version: 1,
created_at: '2026-10-25T10:00:00Z',
updated_at: '2026-10-25T10:00:00Z',
@@ -107,4 +108,100 @@ describe('clips store', () => {
expect(init.method).toBe('PATCH')
expect(JSON.parse(init.body as string)).toEqual({ pinned: true, version: 1 })
})
it('requests the filtered list', async () => {
const store = useClipsStore()
const fetchMock = vi.fn<typeof fetch>(async () => jsonResponse(200, { items: [], total: 0 }))
vi.stubGlobal('fetch', fetchMock)
await store.setFilter({ project: 3, query: ' a&b ' })
const url = new URL(String(fetchMock.mock.calls[0]![0]), 'https://x')
expect(url.searchParams.get('project')).toBe('3')
expect(url.searchParams.get('q')).toBe('a&b')
await store.setFilter({ project: 3, query: 'a&b' })
expect(fetchMock).toHaveBeenCalledOnce()
})
it('drops responses to superseded requests', async () => {
const store = useClipsStore()
const resolvers: ((r: Response) => void)[] = []
vi.stubGlobal(
'fetch',
vi.fn(() => new Promise<Response>((resolve) => resolvers.push(resolve))),
)
const first = store.setFilter({ project: null, query: 'a' })
const second = store.setFilter({ project: null, query: 'ab' })
resolvers[1]!(jsonResponse(200, { items: [clip({ id: 2, content: 'ab' })], total: 1 }))
await second
resolvers[0]!(jsonResponse(200, { items: [clip({ id: 1, content: 'a' })], total: 1 }))
await first
expect(store.items.map((c) => c.id)).toEqual([2])
expect(store.loading).toBe(false)
})
it('keeps live updates that do not match the filter out of the list', () => {
const store = useClipsStore()
store.filter = { project: 5, query: '' }
store.upsert(clip({ id: 1, project_id: 5 }))
store.upsert(clip({ id: 2, project_id: 6 }))
expect(store.items.map((c) => c.id)).toEqual([1])
// Moved to another project on a different device
store.upsert(clip({ id: 1, project_id: 6, version: 2 }))
expect(store.items).toEqual([])
expect(store.total).toBe(0)
})
it('tells subscribers about changes to filtered-out clips', () => {
const store = useClipsStore()
store.filter = { project: 'none', query: '' }
const listener = vi.fn()
const unsubscribe = store.subscribe(listener)
store.upsert(clip({ id: 1, project_id: 9 }))
store.removeLocal(1)
unsubscribe()
store.upsert(clip({ id: 2 }))
expect(listener.mock.calls).toEqual([
[{ clip: clip({ id: 1, project_id: 9 }) }],
[{ deleted: 1 }],
])
})
it('detaches clips from a deleted project like the backend', () => {
const store = useClipsStore()
store.upsert(clip({ id: 1, project_id: 4, version: 2 }))
store.upsert(clip({ id: 2, project_id: 5 }))
store.detachProject(4)
const byId = Object.fromEntries(store.items.map((c) => [c.id, c]))
expect(byId[1]).toMatchObject({ project_id: null, version: 3 })
expect(byId[2]).toMatchObject({ project_id: 5, version: 1 })
})
})
describe('matchesFilter', () => {
const all = { project: null, query: '' }
it('filters by project', () => {
expect(matchesFilter(clip({ project_id: 1 }), all)).toBe(true)
expect(matchesFilter(clip({ project_id: 1 }), { ...all, project: 1 })).toBe(true)
expect(matchesFilter(clip({ project_id: 2 }), { ...all, project: 1 })).toBe(false)
expect(matchesFilter(clip(), { ...all, project: 'none' })).toBe(true)
expect(matchesFilter(clip({ project_id: 1 }), { ...all, project: 'none' })).toBe(false)
})
it('searches title and content case-insensitively', () => {
const c = clip({ title: 'Server', content: 'cfg = getConfig()' })
expect(matchesFilter(c, { ...all, query: 'CONFIG' })).toBe(true)
expect(matchesFilter(c, { ...all, query: ' serv ' })).toBe(true)
expect(matchesFilter(c, { ...all, query: 'missing' })).toBe(false)
expect(matchesFilter(clip({ content: 'Straße' }), { ...all, query: 'STRASSE' })).toBe(true)
})
})
+84 -8
View File
@@ -3,9 +3,18 @@ import { ref } from 'vue'
import { ApiError, api } from '@/api/client'
import type { Clip, ClipInput, ClipList } from '@/api/types'
import { foldCase, type ProjectFilter } from '@/utils/projects'
const PAGE_SIZE = 50
export interface ClipFilter {
project: ProjectFilter
query: string
}
/** A clip changed or was deleted, whether or not it is in the current (filtered) list. */
export type ClipChange = { clip: Clip } | { deleted: number }
export class ClipConflictError extends Error {
constructor(public readonly current: Clip) {
super('Der Clip wurde inzwischen auf einem anderen Gerät geändert.')
@@ -19,6 +28,22 @@ function compareClips(a: Clip, b: Clip): number {
return b.id - a.id
}
/** Client-side mirror of the backend filter, applied to live-sync events. */
export function matchesFilter(clip: Clip, filter: ClipFilter): boolean {
if (filter.project === 'none' && clip.project_id !== null) return false
if (typeof filter.project === 'number' && clip.project_id !== filter.project) return false
const needle = foldCase(filter.query.trim())
if (!needle) return true
return foldCase(clip.content).includes(needle) || foldCase(clip.title ?? '').includes(needle)
}
function listUrl(filter: ClipFilter, offset: number): string {
const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: String(offset) })
if (filter.project !== null) params.set('project', String(filter.project))
if (filter.query.trim()) params.set('q', filter.query.trim())
return `/clips?${params}`
}
export const useClipsStore = defineStore('clips', () => {
const items = ref<Clip[]>([])
const total = ref(0)
@@ -27,20 +52,39 @@ export const useClipsStore = defineStore('clips', () => {
const loaded = ref(false)
/** Content handed over from the share target, picked up by the quick-add form. */
const draft = ref<string | null>(null)
const filter = ref<ClipFilter>({ project: null, query: '' })
// Responses to superseded requests (e.g. while typing a search) are dropped
let loadToken = 0
const listeners = new Set<(change: ClipChange) => void>()
/** Get told about every clip change; returns the unsubscribe function. */
function subscribe(listener: (change: ClipChange) => void): () => void {
listeners.add(listener)
return () => listeners.delete(listener)
}
function emit(change: ClipChange): void {
for (const listener of listeners) listener(change)
}
/**
* Insert or replace a clip locally. Used for API responses and live-sync events;
* an older version never overwrites a newer one, whatever arrives first.
* Clips that do not match the current filter leave the list.
*/
function upsert(clip: Clip): void {
emit({ clip })
const index = items.value.findIndex((c) => c.id === clip.id)
if (index !== -1 && items.value[index]!.version > clip.version) return
if (!matchesFilter(clip, filter.value)) {
if (index !== -1) dropLocal(clip.id)
return
}
if (index === -1) {
items.value.push(clip)
total.value += 1
} else if (items.value[index]!.version <= clip.version) {
items.value[index] = clip
} else {
return
items.value[index] = clip
}
items.value.sort(compareClips)
}
@@ -52,31 +96,59 @@ export const useClipsStore = defineStore('clips', () => {
error.value = null
loaded.value = false
draft.value = null
filter.value = { project: null, query: '' }
loadToken += 1
}
function removeLocal(id: number): void {
/** Remove from the visible list only (filtered out); the clip still exists. */
function dropLocal(id: number): void {
const before = items.value.length
items.value = items.value.filter((c) => c.id !== id)
total.value -= before - items.value.length
}
/** The clip was deleted. */
function removeLocal(id: number): void {
dropLocal(id)
emit({ deleted: id })
}
/** Mirror the backend after a project was deleted: its clips lose the project. */
function detachProject(projectId: number): void {
for (const clip of items.value.filter((c) => c.project_id === projectId)) {
upsert({ ...clip, project_id: null, version: clip.version + 1 })
}
}
async function load(): Promise<void> {
const token = ++loadToken
loading.value = true
error.value = null
try {
const page = await api.get<ClipList>(`/clips?limit=${PAGE_SIZE}&offset=0`)
const page = await api.get<ClipList>(listUrl(filter.value, 0))
if (token !== loadToken) return
items.value = page.items
total.value = page.total
loaded.value = true
} catch (e) {
error.value = e instanceof Error ? e.message : String(e)
if (token === loadToken) error.value = e instanceof Error ? e.message : String(e)
} finally {
loading.value = false
if (token === loadToken) loading.value = false
}
}
/** Change the filter and reload; no request if nothing changed and data is there. */
async function setFilter(next: ClipFilter): Promise<void> {
const same =
next.project === filter.value.project && next.query.trim() === filter.value.query.trim()
filter.value = next
if (!same || !loaded.value) await load()
}
async function loadMore(): Promise<void> {
const page = await api.get<ClipList>(`/clips?limit=${PAGE_SIZE}&offset=${items.value.length}`)
const token = loadToken
const page = await api.get<ClipList>(listUrl(filter.value, items.value.length))
if (token !== loadToken) return
for (const clip of page.items) upsert(clip)
total.value = page.total
}
@@ -121,10 +193,14 @@ export const useClipsStore = defineStore('clips', () => {
error,
loaded,
draft,
filter,
subscribe,
upsert,
removeLocal,
detachProject,
reset,
load,
setFilter,
loadMore,
fetchOne,
create,
+72
View File
@@ -0,0 +1,72 @@
import { createPinia, setActivePinia } from 'pinia'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { Project } from '@/api/types'
import { useProjectsStore } from './projects'
function project(overrides: Partial<Project> = {}): Project {
return {
id: 1,
name: 'Work',
color: 'blue',
clip_count: 0,
created_at: '2026-10-25T10:00:00Z',
updated_at: '2026-10-25T10:00:00Z',
...overrides,
}
}
function jsonResponse(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
})
}
describe('projects store', () => {
beforeEach(() => setActivePinia(createPinia()))
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
it('keeps projects sorted by name, ignoring case', () => {
const store = useProjectsStore()
store.upsert(project({ id: 1, name: 'zeta' }))
store.upsert(project({ id: 2, name: 'Äpfel' }))
store.upsert(project({ id: 3, name: 'Mitte' }))
store.upsert(project({ id: 1, name: 'Alpha' }))
expect(store.items.map((p) => p.name)).toEqual(['Alpha', 'Äpfel', 'Mitte'])
expect(store.byId.get(3)?.name).toBe('Mitte')
})
it('bundles count refreshes after clip changes', async () => {
vi.useFakeTimers()
const fetchMock = vi.fn<typeof fetch>(async () => jsonResponse(200, [project()]))
vi.stubGlobal('fetch', fetchMock)
const store = useProjectsStore()
store.scheduleRefresh()
expect(fetchMock).not.toHaveBeenCalled() // never loaded: nothing to refresh
await store.load()
store.scheduleRefresh()
store.scheduleRefresh()
store.scheduleRefresh()
await vi.advanceTimersByTimeAsync(600)
expect(fetchMock).toHaveBeenCalledTimes(2)
})
it('reset forgets everything', () => {
const store = useProjectsStore()
store.upsert(project())
store.loaded = true
store.reset()
expect(store.items).toEqual([])
expect(store.loaded).toBe(false)
})
})
+82
View File
@@ -0,0 +1,82 @@
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { api } from '@/api/client'
import type { Project, ProjectInput } from '@/api/types'
import { foldCase } from '@/utils/projects'
// Clip counts are refreshed after clip changes, bundled so bursts cause one request
const COUNT_REFRESH_DELAY_MS = 500
function compareProjects(a: Project, b: Project): number {
const byName = foldCase(a.name).localeCompare(foldCase(b.name), 'de')
return byName !== 0 ? byName : a.id - b.id
}
export const useProjectsStore = defineStore('projects', () => {
const items = ref<Project[]>([])
const loaded = ref(false)
let refreshTimer: ReturnType<typeof setTimeout> | undefined
const byId = computed(() => new Map(items.value.map((p) => [p.id, p])))
function upsert(project: Project): void {
const index = items.value.findIndex((p) => p.id === project.id)
if (index === -1) items.value.push(project)
else items.value[index] = project
items.value.sort(compareProjects)
}
function removeLocal(id: number): void {
items.value = items.value.filter((p) => p.id !== id)
}
function reset(): void {
clearTimeout(refreshTimer)
items.value = []
loaded.value = false
}
async function load(): Promise<void> {
items.value = (await api.get<Project[]>('/projects')).sort(compareProjects)
loaded.value = true
}
/** Reload soon to update clip counts; failures are ignored, counts are informational. */
function scheduleRefresh(): void {
if (!loaded.value) return
clearTimeout(refreshTimer)
refreshTimer = setTimeout(() => void load().catch(() => {}), COUNT_REFRESH_DELAY_MS)
}
async function create(input: ProjectInput): Promise<Project> {
const project = await api.post<Project>('/projects', input)
upsert(project)
return project
}
async function update(id: number, changes: ProjectInput): Promise<Project> {
const project = await api.patch<Project>(`/projects/${id}`, changes)
upsert(project)
return project
}
async function remove(id: number): Promise<void> {
await api.delete(`/projects/${id}`)
removeLocal(id)
}
return {
items,
loaded,
byId,
upsert,
removeLocal,
reset,
load,
scheduleRefresh,
create,
update,
remove,
}
})
+27
View File
@@ -5,6 +5,7 @@ import { setUnauthorizedHandler } from '@/api/client'
import type { Clip } from '@/api/types'
import { useClipsStore } from './clips'
import { useProjectsStore } from './projects'
import { useSyncStore } from './sync'
/** Minimal stand-in for the browser WebSocket, driven by the test. */
@@ -46,6 +47,7 @@ const clip: Clip = {
content: 'live',
language: null,
pinned: false,
project_id: null,
version: 1,
created_at: '2026-10-25T10:00:00Z',
updated_at: '2026-10-25T10:00:00Z',
@@ -92,6 +94,31 @@ describe('sync store', () => {
expect(clips.items).toEqual([])
})
it('applies project events', () => {
const sync = useSyncStore()
const clips = useClipsStore()
const projects = useProjectsStore()
sync.start()
latest().receive({ type: 'hello' })
const project = {
id: 3,
name: 'Work',
color: 'blue',
clip_count: 1,
created_at: '2026-10-25T10:00:00Z',
updated_at: '2026-10-25T10:00:00Z',
}
latest().receive({ type: 'project.created', data: project })
latest().receive({ type: 'project.updated', data: { ...project, name: 'Job' } })
expect(projects.items.map((p) => p.name)).toEqual(['Job'])
latest().receive({ type: 'clip.created', data: { ...clip, project_id: 3 } })
latest().receive({ type: 'project.deleted', data: { id: 3 } })
expect(projects.items).toEqual([])
expect(clips.items[0]).toMatchObject({ project_id: null, version: 2 })
})
it('reloads the list after reconnecting if it was loaded before', () => {
const sync = useSyncStore()
const clips = useClipsStore()
+26 -5
View File
@@ -2,8 +2,9 @@ import { defineStore } from 'pinia'
import { ref } from 'vue'
import { notifyUnauthorized } from '@/api/client'
import type { Clip } from '@/api/types'
import type { Clip, Project } from '@/api/types'
import { useClipsStore } from '@/stores/clips'
import { useProjectsStore } from '@/stores/projects'
export type SyncStatus = 'offline' | 'connecting' | 'live'
@@ -12,6 +13,8 @@ type ServerMessage =
| { type: 'ping' }
| { type: 'clip.created' | 'clip.updated'; data: Clip }
| { type: 'clip.deleted'; data: { id: number } }
| { type: 'project.created' | 'project.updated'; data: Project }
| { type: 'project.deleted'; data: { id: number } }
const MIN_RETRY_MS = 1_000
const MAX_RETRY_MS = 30_000
@@ -22,7 +25,7 @@ const CLOSE_UNAUTHORIZED = 4401
const STALE_AFTER_HIDDEN_MS = 60_000
/**
* Live sync: receives change events over a WebSocket and applies them to the clip store.
* Live sync: receives change events over a WebSocket and applies them to the stores.
* Writes always go through the REST API; the socket is read-only.
*/
export const useSyncStore = defineStore('sync', () => {
@@ -38,25 +41,44 @@ export const useSyncStore = defineStore('sync', () => {
function handle(message: ServerMessage): void {
const clips = useClipsStore()
const projects = useProjectsStore()
switch (message.type) {
case 'hello':
status.value = 'live'
retryDelay = MIN_RETRY_MS
// Events may have been missed while disconnected
if (clips.loaded) void clips.load()
refresh()
break
case 'clip.created':
case 'clip.updated':
clips.upsert(message.data)
projects.scheduleRefresh()
break
case 'clip.deleted':
clips.removeLocal(message.data.id)
projects.scheduleRefresh()
break
case 'project.created':
case 'project.updated':
projects.upsert(message.data)
break
case 'project.deleted':
projects.removeLocal(message.data.id)
clips.detachProject(message.data.id)
break
case 'ping':
break
}
}
/** Reload whatever has been loaded before. */
function refresh(): void {
const clips = useClipsStore()
const projects = useProjectsStore()
if (clips.loaded) void clips.load()
if (projects.loaded) void projects.load().catch(() => {})
}
function resetWatchdog(ws: WebSocket): void {
clearTimeout(watchdogTimer)
watchdogTimer = setTimeout(() => drop(ws), WATCHDOG_MS)
@@ -118,8 +140,7 @@ export const useSyncStore = defineStore('sync', () => {
}
const away = hiddenSince === null ? 0 : Date.now() - hiddenSince
hiddenSince = null
const clips = useClipsStore()
if (wanted && away >= STALE_AFTER_HIDDEN_MS && clips.loaded) void clips.load()
if (wanted && away >= STALE_AFTER_HIDDEN_MS) refresh()
reconnectNow()
}