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:
1 parent
9ba4655662
commit
eba5621082
21 files changed
+1079
-32
No files matched your search
@@ -6,10 +6,12 @@ import AppHeader from '@/components/AppHeader.vue'
|
||||
import ToastHost from '@/components/ToastHost.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useClipsStore } from '@/stores/clips'
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
import { useSyncStore } from '@/stores/sync'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const clips = useClipsStore()
|
||||
const projects = useProjectsStore()
|
||||
const sync = useSyncStore()
|
||||
|
||||
// Live sync runs while someone is logged in; local data is dropped on logout or user switch
|
||||
@@ -19,8 +21,12 @@ watch(
|
||||
if (previousId !== undefined && userId !== previousId) {
|
||||
sync.stop()
|
||||
clips.reset()
|
||||
projects.reset()
|
||||
}
|
||||
if (userId !== null) {
|
||||
sync.start()
|
||||
void projects.load().catch(() => {})
|
||||
}
|
||||
if (userId !== null) sync.start()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
@@ -27,6 +27,7 @@ export interface Clip {
|
||||
content: string
|
||||
language: string | null
|
||||
pinned: boolean
|
||||
project_id: number | null
|
||||
version: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
@@ -37,4 +38,20 @@ export interface ClipList {
|
||||
total: number
|
||||
}
|
||||
|
||||
export type ClipInput = Partial<Pick<Clip, 'kind' | 'title' | 'content' | 'language' | 'pinned'>>
|
||||
export type ClipInput = Partial<
|
||||
Pick<Clip, 'kind' | 'title' | 'content' | 'language' | 'pinned' | 'project_id'>
|
||||
>
|
||||
|
||||
export type ProjectColor =
|
||||
'blue' | 'teal' | 'green' | 'amber' | 'orange' | 'red' | 'pink' | 'violet'
|
||||
|
||||
export interface Project {
|
||||
id: number
|
||||
name: string
|
||||
color: ProjectColor
|
||||
clip_count: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export type ProjectInput = Partial<Pick<Project, 'name' | 'color'>>
|
||||
@@ -74,6 +74,7 @@ textarea {
|
||||
|
||||
.form {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,12 +4,21 @@ import { RouterLink } from 'vue-router'
|
||||
|
||||
import type { Clip } from '@/api/types'
|
||||
import CopyButton from '@/components/CopyButton.vue'
|
||||
import ProjectDot from '@/components/ProjectDot.vue'
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
import { formatDateTime, formatRelative } from '@/utils/format'
|
||||
import { highlight, languageLabel } from '@/utils/highlight'
|
||||
import { now } from '@/utils/now'
|
||||
|
||||
const props = defineProps<{ clip: Clip }>()
|
||||
const emit = defineEmits<{ togglePin: []; remove: [] }>()
|
||||
const props = withDefaults(defineProps<{ clip: Clip; showProject?: boolean }>(), {
|
||||
showProject: true,
|
||||
})
|
||||
const emit = defineEmits<{ togglePin: []; remove: []; selectProject: [id: number] }>()
|
||||
|
||||
const projects = useProjectsStore()
|
||||
const project = computed(() =>
|
||||
props.clip.project_id === null ? undefined : projects.byId.get(props.clip.project_id),
|
||||
)
|
||||
|
||||
const PREVIEW_LINES = 10
|
||||
const PREVIEW_CHARS = 2000
|
||||
@@ -37,6 +46,16 @@ const html = computed(() =>
|
||||
<div class="clip-meta">
|
||||
<strong v-if="clip.title" class="clip-title">{{ clip.title }}</strong>
|
||||
<span v-if="clip.pinned" class="badge accent">angeheftet</span>
|
||||
<button
|
||||
v-if="showProject && project"
|
||||
type="button"
|
||||
class="badge project"
|
||||
:title="`Nur ${project.name} zeigen`"
|
||||
@click="emit('selectProject', project.id)"
|
||||
>
|
||||
<ProjectDot :color="project.color" />
|
||||
{{ project.name }}
|
||||
</button>
|
||||
<span v-if="clip.kind === 'code'" class="badge">{{ languageLabel(clip.language) }}</span>
|
||||
</div>
|
||||
<time
|
||||
@@ -93,6 +112,20 @@ const html = computed(() =>
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.badge.project {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
min-height: 0;
|
||||
max-width: 14rem;
|
||||
overflow: hidden;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-size: 0.8rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.clip-title {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
import type { ProjectColor } from '@/api/types'
|
||||
import { PROJECT_COLORS } from '@/utils/projects'
|
||||
|
||||
const model = defineModel<ProjectColor>({ required: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="colors" role="radiogroup" aria-label="Farbe">
|
||||
<button
|
||||
v-for="color in PROJECT_COLORS"
|
||||
:key="color.id"
|
||||
type="button"
|
||||
role="radio"
|
||||
class="swatch"
|
||||
:class="{ active: model === color.id }"
|
||||
:aria-checked="model === color.id"
|
||||
:aria-label="color.label"
|
||||
:title="color.label"
|
||||
:style="{ '--swatch': color.value }"
|
||||
@click="model = color.id"
|
||||
></button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.colors {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
/* 44px touch target around a smaller visible circle */
|
||||
.swatch {
|
||||
position: relative;
|
||||
width: 44px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.swatch::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 10px;
|
||||
border-radius: 50%;
|
||||
background: var(--swatch);
|
||||
}
|
||||
|
||||
.swatch.active::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 5px;
|
||||
border: 2px solid var(--text);
|
||||
border-radius: 50%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,106 @@
|
||||
<script setup lang="ts">
|
||||
import { RouterLink } from 'vue-router'
|
||||
|
||||
import ProjectDot from '@/components/ProjectDot.vue'
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
import type { ProjectFilter } from '@/utils/projects'
|
||||
|
||||
defineProps<{ active: ProjectFilter }>()
|
||||
const emit = defineEmits<{ select: [filter: ProjectFilter] }>()
|
||||
|
||||
const projects = useProjectsStore()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav class="project-bar" aria-label="Projekte">
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: active === null }"
|
||||
:aria-pressed="active === null"
|
||||
@click="emit('select', null)"
|
||||
>
|
||||
Alle
|
||||
</button>
|
||||
<button
|
||||
v-for="project in projects.items"
|
||||
:key="project.id"
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: active === project.id }"
|
||||
:aria-pressed="active === project.id"
|
||||
@click="emit('select', project.id)"
|
||||
>
|
||||
<ProjectDot :color="project.color" />
|
||||
<span class="name">{{ project.name }}</span>
|
||||
<span class="count">{{ project.clip_count }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="projects.items.length > 0"
|
||||
type="button"
|
||||
class="chip"
|
||||
:class="{ active: active === 'none' }"
|
||||
:aria-pressed="active === 'none'"
|
||||
@click="emit('select', 'none')"
|
||||
>
|
||||
Ohne Projekt
|
||||
</button>
|
||||
<RouterLink to="/projects" class="chip manage">
|
||||
{{ projects.items.length > 0 ? 'Verwalten' : '+ Projekt' }}
|
||||
</RouterLink>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* One scrollable row; swipe sideways on narrow screens */
|
||||
.project-bar {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
overflow-x: auto;
|
||||
margin: 0 -1rem 1rem;
|
||||
padding: 0.125rem 1rem;
|
||||
scrollbar-width: none;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.project-bar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
min-height: 44px;
|
||||
padding: 0 0.9rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
font-size: 0.9rem;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chip.active {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.chip.manage {
|
||||
border-style: dashed;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.name {
|
||||
max-width: 12rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.count {
|
||||
color: var(--muted);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { colorValue } from '@/utils/projects'
|
||||
|
||||
const props = defineProps<{ color: string }>()
|
||||
const style = computed(() => ({ background: colorValue(props.color) }))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="dot" :style="style" aria-hidden="true"></span>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.dot {
|
||||
display: inline-block;
|
||||
flex: none;
|
||||
width: 0.6rem;
|
||||
height: 0.6rem;
|
||||
border-radius: 50%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,24 @@
|
||||
<script setup lang="ts">
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
|
||||
const model = defineModel<number | null>({ required: true })
|
||||
const projects = useProjectsStore()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<select v-model="model" aria-label="Projekt" class="project-select">
|
||||
<option :value="null">Ohne Projekt</option>
|
||||
<option v-for="project in projects.items" :key="project.id" :value="project.id">
|
||||
{{ project.name }}
|
||||
</option>
|
||||
</select>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.project-select {
|
||||
width: auto;
|
||||
min-width: 9rem;
|
||||
max-width: 100%;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
</style>
|
||||
@@ -2,18 +2,22 @@
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
import type { ClipKind } from '@/api/types'
|
||||
import ProjectSelect from '@/components/ProjectSelect.vue'
|
||||
import { useClipsStore } from '@/stores/clips'
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
import { useToastStore } from '@/stores/toast'
|
||||
import { readClipboardText } from '@/utils/clipboard'
|
||||
import { detectLanguage, LANGUAGES } from '@/utils/highlight'
|
||||
|
||||
const store = useClipsStore()
|
||||
const projects = useProjectsStore()
|
||||
const toast = useToastStore()
|
||||
|
||||
const content = ref('')
|
||||
const kind = ref<ClipKind>('text')
|
||||
const language = ref<string>('plaintext')
|
||||
const languageTouched = ref(false)
|
||||
const projectId = ref<number | null>(null)
|
||||
const busy = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
@@ -25,6 +29,15 @@ watch([content, kind], () => {
|
||||
language.value = detectLanguage(content.value) ?? 'plaintext'
|
||||
})
|
||||
|
||||
// New clips go to the project currently shown
|
||||
watch(
|
||||
() => store.filter.project,
|
||||
(filter) => {
|
||||
projectId.value = typeof filter === 'number' ? filter : null
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// Content shared from another app (share target) arrives as a draft
|
||||
watch(
|
||||
() => store.draft,
|
||||
@@ -56,6 +69,7 @@ async function save(): Promise<void> {
|
||||
content: content.value,
|
||||
kind: kind.value,
|
||||
language: kind.value === 'code' ? language.value : null,
|
||||
project_id: projectId.value,
|
||||
})
|
||||
content.value = ''
|
||||
kind.value = 'text'
|
||||
@@ -111,6 +125,7 @@ async function save(): Promise<void> {
|
||||
>
|
||||
<option v-for="l in LANGUAGES" :key="l.id" :value="l.id">{{ l.label }}</option>
|
||||
</select>
|
||||
<ProjectSelect v-if="projects.items.length > 0" v-model="projectId" />
|
||||
<div class="spacer"></div>
|
||||
<button type="button" @click="paste">Einfügen</button>
|
||||
<button type="submit" class="primary" :disabled="!canSave">Speichern</button>
|
||||
@@ -122,6 +137,8 @@ async function save(): Promise<void> {
|
||||
<style scoped>
|
||||
.quick-add {
|
||||
display: grid;
|
||||
/* Never wider than the card, even with a long project name in the select */
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,11 @@ const router = createRouter({
|
||||
component: () => import('@/views/ClipEditView.vue'),
|
||||
props: true,
|
||||
},
|
||||
{
|
||||
path: '/projects',
|
||||
name: 'projects',
|
||||
component: () => import('@/views/ProjectsView.vue'),
|
||||
},
|
||||
{ path: '/account', name: 'account', component: () => import('@/views/AccountView.vue') },
|
||||
{
|
||||
path: '/admin/users',
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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,
|
||||
}
|
||||
})
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { colorValue, foldCase, parseProjectFilter } from './projects'
|
||||
|
||||
describe('parseProjectFilter', () => {
|
||||
it('accepts project ids and "none"', () => {
|
||||
expect(parseProjectFilter('3')).toBe(3)
|
||||
expect(parseProjectFilter('none')).toBe('none')
|
||||
})
|
||||
|
||||
it.each([undefined, null, '', '0', '-1', 'abc', '1.5', ['3']])('treats %j as all', (value) => {
|
||||
expect(parseProjectFilter(value)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('foldCase', () => {
|
||||
it('folds like the backend search', () => {
|
||||
expect(foldCase('Straße')).toBe(foldCase('STRASSE'))
|
||||
expect(foldCase('ÜBERSICHT')).toBe('übersicht')
|
||||
})
|
||||
})
|
||||
|
||||
describe('colorValue', () => {
|
||||
it('falls back to the first color for unknown keys', () => {
|
||||
expect(colorValue('red')).toBe('#f87171')
|
||||
expect(colorValue('nope')).toBe(colorValue('blue'))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { ProjectColor } from '@/api/types'
|
||||
|
||||
/** Same keys as PROJECT_COLORS in backend/app/models/project.py. */
|
||||
export const PROJECT_COLORS: { id: ProjectColor; label: string; value: string }[] = [
|
||||
{ id: 'blue', label: 'Blau', value: '#6ea8fe' },
|
||||
{ id: 'teal', label: 'Türkis', value: '#2dd4bf' },
|
||||
{ id: 'green', label: 'Grün', value: '#4ade80' },
|
||||
{ id: 'amber', label: 'Gelb', value: '#fbbf24' },
|
||||
{ id: 'orange', label: 'Orange', value: '#fb923c' },
|
||||
{ id: 'red', label: 'Rot', value: '#f87171' },
|
||||
{ id: 'pink', label: 'Pink', value: '#f472b6' },
|
||||
{ id: 'violet', label: 'Violett', value: '#a78bfa' },
|
||||
]
|
||||
|
||||
export function colorValue(color: string): string {
|
||||
return (PROJECT_COLORS.find((c) => c.id === color) ?? PROJECT_COLORS[0]!).value
|
||||
}
|
||||
|
||||
/** "Alle", "Ohne Projekt" or one project. */
|
||||
export type ProjectFilter = number | 'none' | null
|
||||
|
||||
/** Parse the `p` query parameter; anything unexpected means "all". */
|
||||
export function parseProjectFilter(value: unknown): ProjectFilter {
|
||||
if (value === 'none') return 'none'
|
||||
if (typeof value === 'string' && /^[1-9]\d{0,15}$/.test(value)) return Number(value)
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Case-insensitive comparison key, close to Python's str.casefold() used by the backend
|
||||
* search: upper-casing first turns "ß" into "SS", so "Straße" matches "strasse".
|
||||
*/
|
||||
export function foldCase(text: string): string {
|
||||
return text.toUpperCase().toLowerCase()
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { onBeforeRouteLeave, useRouter } from 'vue-router'
|
||||
|
||||
import { ApiError } from '@/api/client'
|
||||
import type { Clip, ClipKind } from '@/api/types'
|
||||
import CopyButton from '@/components/CopyButton.vue'
|
||||
import ProjectSelect from '@/components/ProjectSelect.vue'
|
||||
import { ClipConflictError, useClipsStore } from '@/stores/clips'
|
||||
import { useToastStore } from '@/stores/toast'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
@@ -31,6 +32,7 @@ const title = ref('')
|
||||
const content = ref('')
|
||||
const kind = ref<ClipKind>('text')
|
||||
const language = ref('plaintext')
|
||||
const projectId = ref<number | null>(null)
|
||||
const baseVersion = ref(0)
|
||||
|
||||
function fillForm(source: Clip): void {
|
||||
@@ -39,6 +41,7 @@ function fillForm(source: Clip): void {
|
||||
content.value = source.content
|
||||
kind.value = source.kind
|
||||
language.value = source.language ?? detectLanguage(source.content) ?? 'plaintext'
|
||||
projectId.value = source.project_id
|
||||
baseVersion.value = source.version
|
||||
remoteChange.value = null
|
||||
}
|
||||
@@ -50,6 +53,7 @@ const dirty = computed(() => {
|
||||
title.value !== (c.title ?? '') ||
|
||||
content.value !== c.content ||
|
||||
kind.value !== c.kind ||
|
||||
projectId.value !== c.project_id ||
|
||||
(kind.value === 'code' && language.value !== c.language)
|
||||
)
|
||||
})
|
||||
@@ -58,20 +62,19 @@ const previewHtml = computed(() =>
|
||||
kind.value === 'code' ? highlight(content.value, language.value) : null,
|
||||
)
|
||||
|
||||
// React to live-sync updates of the clip being edited
|
||||
watch(
|
||||
() => store.items.find((c) => c.id === clip.value?.id),
|
||||
(remote) => {
|
||||
// React to live-sync updates of the clip being edited (it may be filtered out of the list)
|
||||
const unsubscribe = store.subscribe((change) => {
|
||||
if (!clip.value || leaving) return
|
||||
if (!remote) {
|
||||
remoteDeleted.value = true
|
||||
if ('deleted' in change) {
|
||||
if (change.deleted === clip.value.id) remoteDeleted.value = true
|
||||
return
|
||||
}
|
||||
if (remote.version <= baseVersion.value) return
|
||||
const remote = change.clip
|
||||
if (remote.id !== clip.value.id || remote.version <= baseVersion.value) return
|
||||
if (dirty.value) remoteChange.value = remote
|
||||
else fillForm(remote)
|
||||
},
|
||||
)
|
||||
})
|
||||
onBeforeUnmount(unsubscribe)
|
||||
|
||||
async function save(version = baseVersion.value): Promise<void> {
|
||||
if (!clip.value) return
|
||||
@@ -85,6 +88,8 @@ async function save(version = baseVersion.value): Promise<void> {
|
||||
content: content.value,
|
||||
kind: kind.value,
|
||||
language: kind.value === 'code' ? language.value : null,
|
||||
// Only when changed, so a project deleted meanwhile does not block other edits
|
||||
...(projectId.value !== clip.value.project_id && { project_id: projectId.value }),
|
||||
},
|
||||
version,
|
||||
)
|
||||
@@ -206,6 +211,7 @@ onMounted(async () => {
|
||||
<select v-if="kind === 'code'" v-model="language" aria-label="Sprache" class="language">
|
||||
<option v-for="l in LANGUAGES" :key="l.id" :value="l.id">{{ l.label }}</option>
|
||||
</select>
|
||||
<ProjectSelect v-model="projectId" />
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
|
||||
@@ -1,14 +1,86 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
import type { Clip } from '@/api/types'
|
||||
import ClipCard from '@/components/ClipCard.vue'
|
||||
import ProjectBar from '@/components/ProjectBar.vue'
|
||||
import QuickAdd from '@/components/QuickAdd.vue'
|
||||
import { useClipsStore } from '@/stores/clips'
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
import { useToastStore } from '@/stores/toast'
|
||||
import { parseProjectFilter, type ProjectFilter } from '@/utils/projects'
|
||||
|
||||
const SEARCH_DELAY_MS = 250
|
||||
|
||||
const store = useClipsStore()
|
||||
const projects = useProjectsStore()
|
||||
const toast = useToastStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
// Filter lives in the URL (?p=3&q=…), so back button and bookmarks work
|
||||
const projectFilter = computed(() => parseProjectFilter(route.query.p))
|
||||
const queryFromUrl = computed(() => (typeof route.query.q === 'string' ? route.query.q : ''))
|
||||
const search = ref(queryFromUrl.value)
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
// Query we last wrote to the URL ourselves; must not overwrite what the user typed since
|
||||
let ownQuery: string | null = null
|
||||
|
||||
/** Choosing a project adds a history entry (back button); typing a search does not. */
|
||||
function setQuery(changes: { p?: ProjectFilter; q?: string }, push = false): void {
|
||||
const p = 'p' in changes ? changes.p : projectFilter.value
|
||||
const q = ('q' in changes ? changes.q : queryFromUrl.value)?.trim()
|
||||
ownQuery = q ?? ''
|
||||
const query = { ...(p !== null && p !== undefined && { p: String(p) }), ...(q && { q }) }
|
||||
void (push ? router.push({ query }) : router.replace({ query }))
|
||||
}
|
||||
|
||||
function selectProject(filter: ProjectFilter): void {
|
||||
if (filter !== projectFilter.value) setQuery({ p: filter }, true)
|
||||
}
|
||||
|
||||
function clearSearch(): void {
|
||||
search.value = ''
|
||||
clearTimeout(searchTimer)
|
||||
setQuery({ q: '' })
|
||||
}
|
||||
|
||||
watch(search, (value) => {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => setQuery({ q: value }), SEARCH_DELAY_MS)
|
||||
})
|
||||
|
||||
watch(
|
||||
[projectFilter, queryFromUrl],
|
||||
([project, query]) => {
|
||||
// Back button or link: take the query from the URL
|
||||
if (query !== ownQuery && query.trim() !== search.value.trim()) search.value = query
|
||||
ownQuery = null
|
||||
void store.setFilter({ project, query })
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// A project from the URL that does not exist (any more): show everything instead
|
||||
watch(
|
||||
() => [projects.loaded, projectFilter.value, projects.byId] as const,
|
||||
([loaded, filter, byId]) => {
|
||||
if (loaded && typeof filter === 'number' && !byId.has(filter)) setQuery({ p: null })
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => clearTimeout(searchTimer))
|
||||
|
||||
const filtering = computed(() => projectFilter.value !== null || queryFromUrl.value.trim() !== '')
|
||||
const emptyText = computed(() => {
|
||||
const query = queryFromUrl.value.trim()
|
||||
if (query) return `Keine Treffer für „${query}“.`
|
||||
if (projectFilter.value === 'none') return 'Alle Clips sind einem Projekt zugeordnet.'
|
||||
if (projectFilter.value !== null) return 'In diesem Projekt sind noch keine Clips.'
|
||||
return 'Noch keine Clips. Füge oben Text oder Code ein.'
|
||||
})
|
||||
|
||||
async function togglePin(clip: Clip): Promise<void> {
|
||||
try {
|
||||
@@ -28,18 +100,45 @@ async function remove(clip: Clip): Promise<void> {
|
||||
toast.error(e)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(store.load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="page wide">
|
||||
<QuickAdd />
|
||||
|
||||
<div class="search">
|
||||
<input
|
||||
v-model="search"
|
||||
type="search"
|
||||
placeholder="Suchen …"
|
||||
aria-label="Clips durchsuchen"
|
||||
enterkeyhint="search"
|
||||
autocapitalize="off"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
maxlength="200"
|
||||
@keydown.esc="clearSearch"
|
||||
/>
|
||||
<button
|
||||
v-if="search"
|
||||
type="button"
|
||||
class="clear"
|
||||
aria-label="Suche leeren"
|
||||
@click="clearSearch"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<ProjectBar :active="projectFilter" @select="selectProject" />
|
||||
|
||||
<p v-if="store.error" class="error" role="alert">{{ store.error }}</p>
|
||||
<p v-if="store.loading && store.items.length === 0" class="muted">Lade …</p>
|
||||
<p v-else-if="!store.loading && store.items.length === 0" class="muted empty">
|
||||
Noch keine Clips. Füge oben Text oder Code ein.
|
||||
{{ emptyText }}
|
||||
</p>
|
||||
<p v-else-if="filtering" class="muted small result-count">
|
||||
{{ store.total }} {{ store.total === 1 ? 'Clip' : 'Clips' }}
|
||||
</p>
|
||||
|
||||
<div class="clip-grid">
|
||||
@@ -47,6 +146,8 @@ onMounted(store.load)
|
||||
v-for="clip in store.items"
|
||||
:key="clip.id"
|
||||
:clip="clip"
|
||||
:show-project="projectFilter !== clip.project_id"
|
||||
@select-project="selectProject"
|
||||
@toggle-pin="togglePin(clip)"
|
||||
@remove="remove(clip)"
|
||||
/>
|
||||
@@ -64,6 +165,38 @@ onMounted(store.load)
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.search {
|
||||
position: relative;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.search input {
|
||||
padding-right: 3rem;
|
||||
}
|
||||
|
||||
/* Own clear button; WebKit's built-in one is tiny on touch screens */
|
||||
.search input::-webkit-search-cancel-button {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.clear {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
width: 44px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.result-count {
|
||||
margin: 0 0 0.75rem;
|
||||
}
|
||||
|
||||
.small {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.empty {
|
||||
text-align: center;
|
||||
padding: 2rem 0;
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
|
||||
import type { Project, ProjectColor } from '@/api/types'
|
||||
import ColorPicker from '@/components/ColorPicker.vue'
|
||||
import ProjectDot from '@/components/ProjectDot.vue'
|
||||
import { useProjectsStore } from '@/stores/projects'
|
||||
import { useToastStore } from '@/stores/toast'
|
||||
|
||||
const projects = useProjectsStore()
|
||||
const toast = useToastStore()
|
||||
|
||||
const newName = ref('')
|
||||
const newColor = ref<ProjectColor>('blue')
|
||||
const createError = ref<string | null>(null)
|
||||
const busy = ref(false)
|
||||
|
||||
const editingId = ref<number | null>(null)
|
||||
const editName = ref('')
|
||||
const editColor = ref<ProjectColor>('blue')
|
||||
const editError = ref<string | null>(null)
|
||||
|
||||
function message(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e)
|
||||
}
|
||||
|
||||
async function create(): Promise<void> {
|
||||
if (!newName.value.trim() || busy.value) return
|
||||
busy.value = true
|
||||
createError.value = null
|
||||
try {
|
||||
await projects.create({ name: newName.value, color: newColor.value })
|
||||
newName.value = ''
|
||||
toast.show('Projekt angelegt')
|
||||
} catch (e) {
|
||||
createError.value = message(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function startEdit(project: Project): void {
|
||||
editingId.value = project.id
|
||||
editName.value = project.name
|
||||
editColor.value = project.color
|
||||
editError.value = null
|
||||
}
|
||||
|
||||
async function saveEdit(project: Project): Promise<void> {
|
||||
if (!editName.value.trim() || busy.value) return
|
||||
busy.value = true
|
||||
editError.value = null
|
||||
try {
|
||||
await projects.update(project.id, { name: editName.value, color: editColor.value })
|
||||
editingId.value = null
|
||||
toast.show('Gespeichert')
|
||||
} catch (e) {
|
||||
editError.value = message(e)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(project: Project): Promise<void> {
|
||||
const n = project.clip_count
|
||||
const clips =
|
||||
n === 0
|
||||
? ''
|
||||
: n === 1
|
||||
? ' Der Clip bleibt erhalten und landet bei „Ohne Projekt“.'
|
||||
: ` Die ${n} Clips bleiben erhalten und landen bei „Ohne Projekt“.`
|
||||
if (!confirm(`Projekt „${project.name}“ löschen?${clips}`)) return
|
||||
try {
|
||||
await projects.remove(project.id)
|
||||
toast.show('Projekt gelöscht')
|
||||
} catch (e) {
|
||||
toast.error(e)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="page">
|
||||
<h1>Projekte</h1>
|
||||
|
||||
<form class="card form" @submit.prevent="create">
|
||||
<h2>Neues Projekt</h2>
|
||||
<label>
|
||||
Name
|
||||
<input v-model="newName" maxlength="100" autocomplete="off" required />
|
||||
</label>
|
||||
<ColorPicker v-model="newColor" />
|
||||
<p v-if="createError" class="error" role="alert">{{ createError }}</p>
|
||||
<div>
|
||||
<button type="submit" class="primary" :disabled="busy || !newName.trim()">Anlegen</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<p v-if="projects.loaded && projects.items.length === 0" class="muted">
|
||||
Noch keine Projekte. Mit Projekten gruppierst du Clips, z. B. nach Kunde oder Thema.
|
||||
</p>
|
||||
|
||||
<ul class="list">
|
||||
<li v-for="project in projects.items" :key="project.id" class="card">
|
||||
<form v-if="editingId === project.id" class="form" @submit.prevent="saveEdit(project)">
|
||||
<label>
|
||||
Name
|
||||
<input v-model="editName" maxlength="100" autocomplete="off" required />
|
||||
</label>
|
||||
<ColorPicker v-model="editColor" />
|
||||
<p v-if="editError" class="error" role="alert">{{ editError }}</p>
|
||||
<div class="actions">
|
||||
<button type="submit" class="primary" :disabled="busy || !editName.trim()">
|
||||
Speichern
|
||||
</button>
|
||||
<button type="button" @click="editingId = null">Abbrechen</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div v-else class="row">
|
||||
<RouterLink :to="{ path: '/', query: { p: project.id } }" class="name">
|
||||
<ProjectDot :color="project.color" />
|
||||
<span>{{ project.name }}</span>
|
||||
</RouterLink>
|
||||
<span class="muted small">
|
||||
{{ project.clip_count }} {{ project.clip_count === 1 ? 'Clip' : 'Clips' }}
|
||||
</span>
|
||||
<div class="spacer"></div>
|
||||
<div class="buttons">
|
||||
<button type="button" class="small" @click="startEdit(project)">Bearbeiten</button>
|
||||
<button type="button" class="small danger" @click="remove(project)">Löschen</button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.row,
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.name {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
min-height: 44px;
|
||||
min-width: 0;
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Buttons wrap as a group, never one by one */
|
||||
.buttons {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.small {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user