feat: dateiaustausch im frontend

Hochladen per Dateiauswahl, Drag & Drop und Einfügen mit Fortschritt
und Abbrechen, Aufbewahrung wählbar. Datei-Karten mit Bildvorschau,
Größe, Ablauf und Download; Speicheranzeige im Konto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 14:10:07 +01:00
1 parent 52a8fd019f
commit 4b79f08bdd
18 files changed
+872 -28

No files matched your search

+6
View File
@@ -32,6 +32,12 @@ LOGIN_IP_LOCKOUT=false
CLIP_MAX_CHARS=200000
MAX_REQUEST_BYTES=1048576
# File uploads (bytes): maximum per file, storage per user, and the free disk space
# that must remain on the server (uploads are refused below it)
FILE_MAX_BYTES=104857600
FILE_QUOTA_BYTES=1073741824
FILE_MIN_FREE_BYTES=2147483648
# Swagger UI under /api/docs; keep disabled on a publicly reachable instance
ENABLE_API_DOCS=false
+3
View File
@@ -7,11 +7,13 @@ import ToastHost from '@/components/ToastHost.vue'
import { useAuthStore } from '@/stores/auth'
import { useClipsStore } from '@/stores/clips'
import { useProjectsStore } from '@/stores/projects'
import { useUploadsStore } from '@/stores/uploads'
import { useSyncStore } from '@/stores/sync'
const auth = useAuthStore()
const clips = useClipsStore()
const projects = useProjectsStore()
const uploads = useUploadsStore()
const sync = useSyncStore()
// Live sync runs while someone is logged in; local data is dropped on logout or user switch
@@ -22,6 +24,7 @@ watch(
sync.stop()
clips.reset()
projects.reset()
uploads.reset()
}
if (userId !== null) {
sync.start()
+8 -4
View File
@@ -23,18 +23,18 @@ export function notifyUnauthorized(): void {
onUnauthorized?.()
}
function readCookie(name: string): string | null {
export function readCookie(name: string): string | null {
const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`))
return match ? decodeURIComponent(match.slice(name.length + 1)) : null
}
function errorMessage(response: Response, data: unknown): string {
export function errorMessage(status: number, statusText: string, data: unknown): string {
if (data && typeof data === 'object' && 'detail' in data) {
const detail = (data as { detail: unknown }).detail
if (typeof detail === 'string') return detail
if (Array.isArray(detail)) return 'Ungültige Eingabe.'
}
return `${response.status} ${response.statusText}`
return `${status} ${statusText}`
}
export async function apiRequest<T>(method: string, path: string, body?: unknown): Promise<T> {
@@ -55,7 +55,11 @@ export async function apiRequest<T>(method: string, path: string, body?: unknown
if (!response.ok) {
if (response.status === 401 && path !== '/auth/login') onUnauthorized?.()
const data: unknown = await response.json().catch(() => null)
throw new ApiError(response.status, errorMessage(response, data), data)
throw new ApiError(
response.status,
errorMessage(response.status, response.statusText, data),
data,
)
}
if (response.status === 204) return undefined as T
return (await response.json()) as T
+21 -1
View File
@@ -18,7 +18,25 @@ export interface SessionInfo {
current: boolean
}
export type ClipKind = 'text' | 'code'
export type ClipKind = 'text' | 'code' | 'file'
export interface FileInfo {
name: string
content_type: string
size: number
/** Verified JPEG/PNG/GIF/WebP; only these may be shown inline */
previewable: boolean
expires_at: string | null
}
export interface FileUsage {
used_bytes: number
quota_bytes: number
max_file_bytes: number
}
/** Allowed lifetimes of an upload in days; 0 keeps the file until it is deleted. */
export type ExpiryDays = 0 | 1 | 7 | 30
export interface Clip {
id: number
@@ -28,6 +46,8 @@ export interface Clip {
language: string | null
pinned: boolean
project_id: number | null
/** Set for clips of kind "file" */
file: FileInfo | null
version: number
created_at: string
updated_at: string
+87
View File
@@ -0,0 +1,87 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ApiError } from './client'
import { uploadFile } from './upload'
class FakeXhr {
static last: FakeXhr
method = ''
url = ''
headers: Record<string, string> = {}
body: unknown = null
status = 0
statusText = ''
response: unknown = null
responseType = ''
upload: { onprogress: ((e: ProgressEvent) => void) | null } = { onprogress: null }
onload: (() => void) | null = null
onerror: (() => void) | null = null
onabort: (() => void) | null = null
constructor() {
FakeXhr.last = this
}
open(method: string, url: string) {
this.method = method
this.url = url
}
setRequestHeader(name: string, value: string) {
this.headers[name] = value
}
send(body: unknown) {
this.body = body
}
abort() {
this.onabort?.()
}
respond(status: number, response: unknown) {
this.status = status
this.response = response
this.onload?.()
}
}
describe('uploadFile', () => {
afterEach(() => vi.unstubAllGlobals())
it('sends the raw file with metadata in the query string', async () => {
vi.stubGlobal('XMLHttpRequest', FakeXhr)
document.cookie = 'lc_csrf=token123'
const file = new File(['abc'], 'Bericht März.pdf', { type: 'application/pdf' })
const progress = vi.fn()
const handle = uploadFile(file, { expiresDays: 30, projectId: 4, onProgress: progress })
const xhr = FakeXhr.last
xhr.upload.onprogress?.({ lengthComputable: true, loaded: 2, total: 3 } as ProgressEvent)
xhr.respond(201, { id: 9 })
expect(await handle.promise).toEqual({ id: 9 })
const url = new URL(xhr.url, 'https://x')
expect(xhr.method).toBe('POST')
expect(url.pathname).toBe('/api/files')
expect(Object.fromEntries(url.searchParams)).toEqual({
name: 'Bericht März.pdf',
expires_days: '30',
project_id: '4',
})
expect(xhr.headers['Content-Type']).toBe('application/pdf')
expect(xhr.headers['X-CSRF-Token']).toBe('token123')
expect(xhr.body).toBe(file)
expect(progress).toHaveBeenCalledWith(2, 3)
})
it('reports the backend message, or a proxy 413 without JSON', async () => {
vi.stubGlobal('XMLHttpRequest', FakeXhr)
const file = new File(['abc'], 'a.txt')
const quota = uploadFile(file, { expiresDays: 7, projectId: null })
FakeXhr.last.respond(413, { detail: 'Nicht genug Speicherplatz' })
await expect(quota.promise).rejects.toThrow('Nicht genug Speicherplatz')
const proxy = uploadFile(file, { expiresDays: 7, projectId: null })
FakeXhr.last.respond(413, null)
const error = await proxy.promise.catch((e: unknown) => e)
expect(error).toBeInstanceOf(ApiError)
expect((error as ApiError).message).toBe('Die Datei ist zu groß für den Server.')
})
})
+64
View File
@@ -0,0 +1,64 @@
import { ApiError, errorMessage, notifyUnauthorized, readCookie } from '@/api/client'
import type { Clip, ExpiryDays } from '@/api/types'
export interface UploadOptions {
expiresDays: ExpiryDays
projectId: number | null
onProgress?: (loaded: number, total: number) => void
}
export interface UploadHandle {
promise: Promise<Clip>
abort: () => void
}
export class UploadAborted extends Error {
constructor() {
super('Hochladen abgebrochen.')
}
}
/**
* Upload one file as raw request body. Uses XMLHttpRequest because fetch reports no
* upload progress; the backend streams the body straight to disk.
*/
export function uploadFile(file: File, options: UploadOptions): UploadHandle {
const xhr = new XMLHttpRequest()
const params = new URLSearchParams({
name: file.name || 'datei',
expires_days: String(options.expiresDays),
})
if (options.projectId !== null) params.set('project_id', String(options.projectId))
const promise = new Promise<Clip>((resolve, reject) => {
xhr.open('POST', `/api/files?${params}`)
xhr.setRequestHeader('Accept', 'application/json')
xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream')
const csrf = readCookie('lc_csrf')
if (csrf) xhr.setRequestHeader('X-CSRF-Token', csrf)
xhr.responseType = 'json'
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) options.onProgress?.(event.loaded, event.total)
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response as Clip)
return
}
if (xhr.status === 401) notifyUnauthorized()
// A proxy in front (e.g. nginx) answers 413 with HTML, not JSON
const data: unknown = xhr.response
const message =
xhr.status === 413 && data === null
? 'Die Datei ist zu groß für den Server.'
: errorMessage(xhr.status, xhr.statusText, data)
reject(new ApiError(xhr.status, message, data))
}
xhr.onerror = () => reject(new Error('Netzwerkfehler beim Hochladen.'))
xhr.onabort = () => reject(new UploadAborted())
xhr.send(file)
})
return { promise, abort: () => xhr.abort() }
}
+78 -8
View File
@@ -6,7 +6,7 @@ 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 { formatBytes, formatDateTime, formatExpiry, formatRelative } from '@/utils/format'
import { highlight, languageLabel } from '@/utils/highlight'
import { now } from '@/utils/now'
@@ -34,6 +34,12 @@ const visibleText = computed(() =>
? props.clip.content
: lines.value.slice(0, PREVIEW_LINES).join('\n').slice(0, PREVIEW_CHARS),
)
const fileUrl = computed(() => `/api/files/${props.clip.id}`)
const expired = computed(() => {
const expires = props.clip.file?.expires_at
return expires != null && new Date(expires).getTime() <= now.value
})
// Highlight only what is visible; large clips stay cheap until expanded
const html = computed(() =>
props.clip.kind === 'code' ? highlight(visibleText.value, props.clip.language) : null,
@@ -67,16 +73,41 @@ const html = computed(() =>
</time>
</header>
<!-- eslint-disable-next-line vue/no-v-html -- highlight.js output is escaped -->
<pre v-if="html !== null" class="content code"><code class="hljs" v-html="html"></code></pre>
<pre v-else class="content text">{{ visibleText }}</pre>
<div v-if="clip.file" class="file">
<a
v-if="clip.file.previewable && !expired"
:href="`${fileUrl}?inline=1`"
target="_blank"
rel="noopener"
class="preview"
>
<img :src="`${fileUrl}?inline=1`" :alt="clip.file.name" loading="lazy" />
</a>
<div class="file-info">
<span class="file-name">{{ clip.file.name }}</span>
<span class="muted small" :class="{ error: expired }">
{{ formatBytes(clip.file.size) }} · {{ formatExpiry(clip.file.expires_at, now) }}
</span>
</div>
</div>
<button v-if="isLong" type="button" class="link" @click="expanded = !expanded">
{{ expanded ? 'weniger' : `mehr (${lines.length} Zeilen)` }}
</button>
<template v-else>
<!-- eslint-disable-next-line vue/no-v-html -- highlight.js output is escaped -->
<pre v-if="html !== null" class="content code"><code class="hljs" v-html="html"></code></pre>
<pre v-else class="content text">{{ visibleText }}</pre>
<button v-if="isLong" type="button" class="link" @click="expanded = !expanded">
{{ expanded ? 'weniger' : `mehr (${lines.length} Zeilen)` }}
</button>
</template>
<footer class="actions">
<CopyButton :text="clip.content" />
<template v-if="clip.file">
<a v-if="!expired" :href="fileUrl" download class="button-link small download">
Herunterladen
</a>
</template>
<CopyButton v-else :text="clip.content" />
<RouterLink :to="`/clips/${clip.id}`" class="button-link small">Bearbeiten</RouterLink>
<button type="button" class="small" @click="emit('togglePin')">
{{ clip.pinned ? 'Lösen' : 'Anheften' }}
@@ -155,6 +186,45 @@ const html = computed(() =>
background: transparent;
}
.file {
display: grid;
gap: 0.5rem;
}
.preview {
display: block;
justify-self: start;
max-width: 100%;
}
.preview img {
display: block;
max-width: 100%;
max-height: 16rem;
border-radius: calc(var(--radius) - 4px);
background: var(--bg);
object-fit: contain;
}
.file-info {
display: grid;
min-width: 0;
padding: 0.75rem;
border-radius: calc(var(--radius) - 4px);
background: var(--bg);
}
.file-name {
font-weight: 600;
overflow-wrap: anywhere;
}
.download {
background: var(--accent);
color: var(--bg);
font-weight: 600;
}
.link {
min-height: 32px;
padding: 0;
+88 -4
View File
@@ -1,16 +1,20 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { ClipKind } from '@/api/types'
import type { ClipKind, ExpiryDays } from '@/api/types'
import ProjectSelect from '@/components/ProjectSelect.vue'
import UploadList from '@/components/UploadList.vue'
import { useClipsStore } from '@/stores/clips'
import { useProjectsStore } from '@/stores/projects'
import { DEFAULT_EXPIRY, useUploadsStore } from '@/stores/uploads'
import { useToastStore } from '@/stores/toast'
import { readClipboardText } from '@/utils/clipboard'
import { EXPIRY_OPTIONS } from '@/utils/expiry'
import { detectLanguage, LANGUAGES } from '@/utils/highlight'
const store = useClipsStore()
const projects = useProjectsStore()
const uploads = useUploadsStore()
const toast = useToastStore()
const content = ref('')
@@ -18,6 +22,9 @@ const kind = ref<ClipKind>('text')
const language = ref<string>('plaintext')
const languageTouched = ref(false)
const projectId = ref<number | null>(null)
const expiresDays = ref<ExpiryDays>(DEFAULT_EXPIRY)
const fileInput = ref<HTMLInputElement | null>(null)
const dragging = ref(false)
const busy = ref(false)
const error = ref<string | null>(null)
@@ -49,6 +56,35 @@ watch(
{ immediate: true },
)
function uploadFiles(files: FileList | File[] | null | undefined): void {
if (!files || files.length === 0) return
void uploads.add([...files], { expiresDays: expiresDays.value, projectId: projectId.value })
}
function onFilesChosen(): void {
uploadFiles(fileInput.value?.files)
// Allow choosing the same file again
if (fileInput.value) fileInput.value.value = ''
}
function onDrop(event: DragEvent): void {
dragging.value = false
uploadFiles(event.dataTransfer?.files)
}
function onDragOver(event: DragEvent): void {
if (event.dataTransfer?.types.includes('Files')) dragging.value = true
}
/** Pasting a screenshot or copied file uploads it; plain text pastes as usual. */
function onPaste(event: ClipboardEvent): void {
const files = event.clipboardData?.files
if (files && files.length > 0) {
event.preventDefault()
uploadFiles(files)
}
}
async function paste(): Promise<void> {
error.value = null
try {
@@ -84,7 +120,14 @@ async function save(): Promise<void> {
</script>
<template>
<form class="card quick-add" @submit.prevent="save">
<form
class="card quick-add"
:class="{ dragging }"
@submit.prevent="save"
@dragover.prevent="onDragOver"
@dragleave.self="dragging = false"
@drop.prevent="onDrop"
>
<textarea
v-model="content"
:class="{ mono: kind === 'code' }"
@@ -94,6 +137,7 @@ async function save(): Promise<void> {
spellcheck="false"
@keydown.enter.ctrl.prevent="save"
@keydown.enter.meta.prevent="save"
@paste="onPaste"
></textarea>
<div class="row">
<div class="segmented" role="radiogroup" aria-label="Art">
@@ -127,9 +171,22 @@ async function save(): Promise<void> {
</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>
<div class="buttons">
<button type="button" @click="paste">Einfügen</button>
<button type="submit" class="primary" :disabled="!canSave">Speichern</button>
</div>
</div>
<div class="row files">
<button type="button" @click="fileInput?.click()">Datei …</button>
<select v-model="expiresDays" aria-label="Datei aufbewahren" class="expiry">
<option v-for="o in EXPIRY_OPTIONS" :key="o.days" :value="o.days">
{{ o.days === 0 ? 'Unbegrenzt behalten' : `${o.label} behalten` }}
</option>
</select>
<span class="muted small hint">oder hierher ziehen</span>
<input ref="fileInput" type="file" multiple hidden @change="onFilesChosen" />
</div>
<UploadList />
<p v-if="error" class="error" role="alert">{{ error }}</p>
</form>
</template>
@@ -153,6 +210,33 @@ async function save(): Promise<void> {
flex: 1;
}
/* Wrap together, never one by one */
.buttons {
display: flex;
gap: 0.5rem;
margin-left: auto;
}
.quick-add.dragging {
border-color: var(--accent);
border-style: dashed;
}
.expiry {
width: auto;
}
.small {
font-size: 0.85rem;
}
/* Drag and drop needs a mouse; no hint on touch screens */
@media (pointer: coarse) {
.hint {
display: none;
}
}
.language {
width: auto;
min-width: 9rem;
+79
View File
@@ -0,0 +1,79 @@
<script setup lang="ts">
import { useUploadsStore } from '@/stores/uploads'
import { formatBytes } from '@/utils/format'
const uploads = useUploadsStore()
function percent(loaded: number, size: number): number {
return size > 0 ? Math.min(100, Math.round((loaded / size) * 100)) : 0
}
</script>
<template>
<ul v-if="uploads.items.length > 0" class="uploads" aria-label="Uploads">
<li v-for="upload in uploads.items" :key="upload.id" class="upload" :class="upload.status">
<div class="line">
<span class="name">{{ upload.name }}</span>
<span class="muted small">
<template v-if="upload.status === 'uploading'">
{{ percent(upload.loaded, upload.size) }} % von {{ formatBytes(upload.size) }}
</template>
<template v-else-if="upload.status === 'waiting'">wartet</template>
</span>
<button
type="button"
class="small"
:class="{ danger: upload.status !== 'failed' }"
@click="uploads.dismiss(upload.id)"
>
{{ upload.status === 'failed' ? 'OK' : 'Abbrechen' }}
</button>
</div>
<progress
v-if="upload.status !== 'failed'"
:value="upload.loaded"
:max="upload.size"
:aria-label="`Fortschritt ${upload.name}`"
></progress>
<p v-else class="error small" role="alert">{{ upload.error }}</p>
</li>
</ul>
</template>
<style scoped>
.uploads {
display: grid;
gap: 0.5rem;
margin: 0;
padding: 0;
list-style: none;
}
.line {
display: flex;
align-items: center;
gap: 0.5rem;
}
.name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.small {
font-size: 0.85rem;
}
progress {
width: 100%;
height: 0.4rem;
accent-color: var(--accent);
}
.error {
margin: 0.25rem 0 0;
}
</style>
+1
View File
@@ -14,6 +14,7 @@ function clip(overrides: Partial<Clip> = {}): Clip {
language: null,
pinned: false,
project_id: null,
file: null,
version: 1,
created_at: '2026-10-25T10:00:00Z',
updated_at: '2026-10-25T10:00:00Z',
+1
View File
@@ -48,6 +48,7 @@ const clip: Clip = {
language: null,
pinned: false,
project_id: null,
file: null,
version: 1,
created_at: '2026-10-25T10:00:00Z',
updated_at: '2026-10-25T10:00:00Z',
+117
View File
@@ -0,0 +1,117 @@
import { createPinia, setActivePinia } from 'pinia'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { Clip } from '@/api/types'
import { UploadAborted, uploadFile, type UploadHandle } from '@/api/upload'
import { useClipsStore } from './clips'
import { useUploadsStore } from './uploads'
vi.mock('@/api/upload', async (importOriginal) => ({
...(await importOriginal<typeof import('@/api/upload')>()),
uploadFile: vi.fn(),
}))
const upload = vi.mocked(uploadFile)
function fileClip(id: number, name: string): Clip {
return {
id,
kind: 'file',
title: null,
content: name,
language: null,
pinned: false,
project_id: null,
file: { name, content_type: 'text/plain', size: 3, previewable: false, expires_at: null },
version: 1,
created_at: '2026-10-25T10:00:00Z',
updated_at: '2026-10-25T10:00:00Z',
}
}
/** A pending upload that the test settles by hand. */
function deferred(): UploadHandle & { resolve: (c: Clip) => void; reject: (e: Error) => void } {
let resolve!: (c: Clip) => void
let reject!: (e: Error) => void
const promise = new Promise<Clip>((res, rej) => {
resolve = res
reject = rej
})
return { promise, abort: vi.fn(() => reject(new UploadAborted())), resolve, reject }
}
const flush = () => new Promise((r) => setTimeout(r, 0))
const options = { expiresDays: 7 as const, projectId: null }
describe('uploads store', () => {
beforeEach(() => {
setActivePinia(createPinia())
upload.mockReset()
const store = useUploadsStore()
store.usage = { used_bytes: 0, quota_bytes: 1000, max_file_bytes: 10 }
})
it('rejects empty and oversized files without sending them', async () => {
const store = useUploadsStore()
await store.add([new File([], 'empty.txt'), new File(['x'.repeat(11)], 'big.bin')], options)
expect(upload).not.toHaveBeenCalled()
expect(store.items.map((u) => [u.name, u.status, u.error])).toEqual([
['empty.txt', 'failed', 'Die Datei ist leer.'],
['big.bin', 'failed', 'Die Datei ist zu groß (höchstens 10 B).'],
])
})
it('uploads one file after another and adds the clips', async () => {
const first = deferred()
const second = deferred()
upload.mockReturnValueOnce(first).mockReturnValueOnce(second)
const store = useUploadsStore()
await store.add([new File(['abc'], 'a.txt'), new File(['def'], 'b.txt')], options)
expect(upload).toHaveBeenCalledOnce()
expect(store.items.map((u) => u.status)).toEqual(['uploading', 'waiting'])
first.resolve(fileClip(1, 'a.txt'))
await flush()
expect(upload).toHaveBeenCalledTimes(2)
second.resolve(fileClip(2, 'b.txt'))
await flush()
expect(store.items).toEqual([])
expect(
useClipsStore()
.items.map((c) => c.id)
.sort(),
).toEqual([1, 2])
expect(store.usage?.used_bytes).toBe(6)
})
it('keeps failed uploads until dismissed', async () => {
const job = deferred()
upload.mockReturnValueOnce(job)
const store = useUploadsStore()
await store.add([new File(['abc'], 'a.txt')], options)
job.reject(new Error('Nicht genug Speicherplatz'))
await flush()
expect(store.items[0]).toMatchObject({ status: 'failed', error: 'Nicht genug Speicherplatz' })
store.dismiss(store.items[0]!.id)
expect(store.items).toEqual([])
})
it('cancels a running upload', async () => {
const job = deferred()
upload.mockReturnValueOnce(job)
const store = useUploadsStore()
await store.add([new File(['abc'], 'a.txt')], options)
store.dismiss(store.items[0]!.id)
await flush()
expect(job.abort).toHaveBeenCalledOnce()
expect(store.items).toEqual([])
})
})
+134
View File
@@ -0,0 +1,134 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { api } from '@/api/client'
import type { ExpiryDays, FileUsage } from '@/api/types'
import { UploadAborted, uploadFile } from '@/api/upload'
import { useClipsStore } from '@/stores/clips'
import { useProjectsStore } from '@/stores/projects'
import { formatBytes } from '@/utils/format'
export interface Upload {
id: number
name: string
size: number
loaded: number
status: 'waiting' | 'uploading' | 'failed'
error: string | null
}
export const DEFAULT_EXPIRY: ExpiryDays = 7
/**
* Upload queue: files go up one after another, so a phone on a slow line
* does not split its bandwidth. Finished uploads leave the list; failed ones stay
* until dismissed.
*/
export const useUploadsStore = defineStore('uploads', () => {
const items = ref<Upload[]>([])
const usage = ref<FileUsage | null>(null)
let nextId = 1
let running = false
const pending = new Map<
number,
{ file: File; expiresDays: ExpiryDays; projectId: number | null }
>()
const aborts = new Map<number, () => void>()
async function loadUsage(): Promise<FileUsage> {
usage.value = await api.get<FileUsage>('/files/usage')
return usage.value
}
function patch(id: number, changes: Partial<Upload>): void {
const index = items.value.findIndex((u) => u.id === id)
if (index !== -1) items.value[index] = { ...items.value[index]!, ...changes }
}
function dismiss(id: number): void {
aborts.get(id)?.()
pending.delete(id)
items.value = items.value.filter((u) => u.id !== id)
}
/** Queue files; obviously too large ones fail right away without being sent. */
async function add(
files: Iterable<File>,
options: { expiresDays: ExpiryDays; projectId: number | null },
): Promise<void> {
const limits = usage.value ?? (await loadUsage().catch(() => null))
for (const file of files) {
const id = nextId++
const upload: Upload = {
id,
name: file.name || 'datei',
size: file.size,
loaded: 0,
status: 'waiting',
error: null,
}
if (file.size === 0) {
upload.status = 'failed'
upload.error = 'Die Datei ist leer.'
} else if (limits && file.size > limits.max_file_bytes) {
upload.status = 'failed'
upload.error = `Die Datei ist zu groß (höchstens ${formatBytes(limits.max_file_bytes)}).`
} else {
pending.set(id, { file, ...options })
}
items.value.push(upload)
}
void run()
}
async function run(): Promise<void> {
if (running) return
running = true
try {
for (let next = pending.entries().next(); !next.done; next = pending.entries().next()) {
const [id, job] = next.value
pending.delete(id)
await send(id, job.file, job.expiresDays, job.projectId)
}
} finally {
running = false
}
}
async function send(
id: number,
file: File,
expiresDays: ExpiryDays,
projectId: number | null,
): Promise<void> {
patch(id, { status: 'uploading' })
const handle = uploadFile(file, {
expiresDays,
projectId,
onProgress: (loaded) => patch(id, { loaded }),
})
aborts.set(id, handle.abort)
try {
const clip = await handle.promise
useClipsStore().upsert(clip)
useProjectsStore().scheduleRefresh()
items.value = items.value.filter((u) => u.id !== id)
if (usage.value)
usage.value = { ...usage.value, used_bytes: usage.value.used_bytes + file.size }
} catch (e) {
if (e instanceof UploadAborted) return
patch(id, { status: 'failed', error: e instanceof Error ? e.message : String(e) })
} finally {
aborts.delete(id)
}
}
function reset(): void {
for (const abort of aborts.values()) abort()
pending.clear()
items.value = []
usage.value = null
}
return { items, usage, loadUsage, add, dismiss, reset }
})
+8
View File
@@ -0,0 +1,8 @@
import type { ExpiryDays } from '@/api/types'
export const EXPIRY_OPTIONS: { days: ExpiryDays; label: string }[] = [
{ days: 1, label: '1 Tag' },
{ days: 7, label: '7 Tage' },
{ days: 30, label: '30 Tage' },
{ days: 0, label: 'Unbegrenzt' },
]
+37 -1
View File
@@ -1,6 +1,12 @@
import { describe, expect, it } from 'vitest'
import { describeUserAgent, formatDateTime, formatRelative } from './format'
import {
describeUserAgent,
formatBytes,
formatDateTime,
formatExpiry,
formatRelative,
} from './format'
describe('describeUserAgent', () => {
it.each([
@@ -55,3 +61,33 @@ describe('formatRelative', () => {
expect(formatRelative(ago(8 * 86_400_000), now)).toBe(formatDateTime(ago(8 * 86_400_000)))
})
})
describe('formatBytes', () => {
it.each([
[0, '0 B'],
[1023, '1023 B'],
[1024, '1 KB'],
[1536, '1,5 KB'],
[100 * 1024 * 1024, '100 MB'],
[1024 ** 3, '1 GB'],
])('%d → %s', (size, expected) => {
expect(formatBytes(size)).toBe(expected)
})
})
describe('formatExpiry', () => {
const now = Date.parse('2026-10-25T12:00:00Z')
const at = (ms: number) => new Date(now + ms).toISOString()
const HOUR = 3_600_000
it.each([
[null, 'unbegrenzt'],
[at(-1), 'abgelaufen'],
[at(10 * 60_000), 'läuft in wenigen Minuten ab'],
[at(5 * HOUR), 'läuft in 5 Std. ab'],
[at(30 * HOUR), 'läuft in 1 Tag ab'],
[at(7 * 24 * HOUR - 60_000), 'läuft in 7 Tagen ab'],
])('%s → %s', (iso, expected) => {
expect(formatExpiry(iso, now)).toBe(expected)
})
})
+27
View File
@@ -52,3 +52,30 @@ export function describeUserAgent(ua: string | null): string {
if (device && browser) return `${browser} auf ${device}`
return device ?? browser ?? ua.slice(0, 40)
}
/** "512 B", "1,5 MB" – same units as the backend messages (1 KB = 1024 B). */
export function formatBytes(size: number): string {
const units: [string, number][] = [
['GB', 1024 ** 3],
['MB', 1024 ** 2],
['KB', 1024],
]
for (const [unit, factor] of units) {
if (size >= factor) {
const value = (size / factor).toLocaleString('de-DE', { maximumFractionDigits: 1 })
return `${value} ${unit}`
}
}
return `${size} B`
}
/** "läuft ab in 6 Tagen", "läuft heute ab", "abgelaufen", "unbegrenzt". */
export function formatExpiry(iso: string | null, now: number = Date.now()): string {
if (iso === null) return 'unbegrenzt'
const left = new Date(iso).getTime() - now
if (left <= 0) return 'abgelaufen'
if (left < HOUR) return 'läuft in wenigen Minuten ab'
if (left < DAY) return `läuft in ${Math.floor(left / HOUR)} Std. ab`
const days = Math.round(left / DAY)
return days === 1 ? 'läuft in 1 Tag ab' : `läuft in ${days} Tagen ab`
}
+37 -2
View File
@@ -5,7 +5,8 @@ import { useRouter } from 'vue-router'
import { api } from '@/api/client'
import type { SessionInfo } from '@/api/types'
import { useAuthStore } from '@/stores/auth'
import { describeUserAgent, formatDateTime } from '@/utils/format'
import { useUploadsStore } from '@/stores/uploads'
import { describeUserAgent, formatBytes, formatDateTime } from '@/utils/format'
const auth = useAuthStore()
const router = useRouter()
@@ -73,7 +74,14 @@ async function revokeOthers(): Promise<void> {
await loadSessions()
}
onMounted(loadSessions)
// --- File storage -------------------------------------------------------------
const uploads = useUploadsStore()
onMounted(() => {
void loadSessions()
void uploads.loadUsage().catch(() => {})
})
</script>
<template>
@@ -88,6 +96,23 @@ onMounted(loadSessions)
</p>
</section>
<section v-if="uploads.usage" class="card">
<h2>Speicher für Dateien</h2>
<p class="usage-text">
{{ formatBytes(uploads.usage.used_bytes) }} von
{{ formatBytes(uploads.usage.quota_bytes) }} belegt
</p>
<progress
:value="uploads.usage.used_bytes"
:max="uploads.usage.quota_bytes"
aria-label="Belegter Speicher"
></progress>
<p class="muted small">
Höchstens {{ formatBytes(uploads.usage.max_file_bytes) }} pro Datei. Abgelaufene Dateien
werden automatisch gelöscht.
</p>
</section>
<section class="card">
<h2>Passwort ändern</h2>
<form class="form" @submit.prevent="changePassword">
@@ -161,6 +186,16 @@ onMounted(loadSessions)
</template>
<style scoped>
.usage-text {
margin: 0 0 0.5rem;
}
progress {
width: 100%;
height: 0.5rem;
accent-color: var(--accent);
}
.sessions {
list-style: none;
margin: 0 0 1rem;
+76 -8
View File
@@ -3,12 +3,14 @@ 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 { api } from '@/api/client'
import type { Clip, ClipKind, ExpiryDays } 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'
import { EXPIRY_OPTIONS } from '@/utils/expiry'
import { formatBytes, formatDateTime, formatExpiry } from '@/utils/format'
import { detectLanguage, highlight, LANGUAGES } from '@/utils/highlight'
const props = defineProps<{ id: string }>()
@@ -62,6 +64,32 @@ const previewHtml = computed(() =>
kind.value === 'code' ? highlight(content.value, language.value) : null,
)
const isFile = computed(() => clip.value?.kind === 'file')
/** Applied right away, like pinning; does not touch the form. */
async function changeExpiry(event: Event): Promise<void> {
if (!clip.value) return
const select = event.target as HTMLSelectElement
const days = Number(select.value) as ExpiryDays
select.value = ''
try {
const updated = await api.patch<Clip>(`/files/${clip.value.id}`, { expires_days: days })
if (dirty.value) {
// Keep unsaved edits; our own change must not show up as a change from elsewhere
clip.value = { ...clip.value, file: updated.file, version: updated.version }
baseVersion.value = updated.version
}
store.upsert(updated) // not dirty: the change listener refills the form
toast.show(
days === 0
? 'Wird unbegrenzt behalten'
: `Wird ${days === 1 ? '1 Tag' : `${days} Tage`} ab jetzt behalten`,
)
} catch (e) {
toast.error(e)
}
}
// 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
@@ -85,9 +113,12 @@ async function save(version = baseVersion.value): Promise<void> {
clip.value.id,
{
title: title.value.trim() || null,
content: content.value,
kind: kind.value,
language: kind.value === 'code' ? language.value : null,
// A file's content (its name) is fixed
...(!isFile.value && {
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 }),
},
@@ -143,7 +174,7 @@ onMounted(async () => {
<template>
<main class="page">
<h1>Clip bearbeiten</h1>
<h1>{{ isFile ? 'Datei bearbeiten' : 'Clip bearbeiten' }}</h1>
<p v-if="notFound" class="muted">
Diesen Clip gibt es nicht (mehr). <RouterLink to="/">Zur Übersicht</RouterLink>
@@ -187,7 +218,25 @@ onMounted(async () => {
<input v-model="title" maxlength="200" />
</label>
<div class="row">
<template v-if="clip.file">
<div class="file-info">
<strong class="file-name">{{ clip.file.name }}</strong>
<span class="muted small">
{{ formatBytes(clip.file.size) }} · {{ formatExpiry(clip.file.expires_at) }}
</span>
</div>
<div class="row">
<ProjectSelect v-model="projectId" />
<select aria-label="Aufbewahren" class="expiry" value="" @change="changeExpiry">
<option value="" disabled>Aufbewahrung ändern …</option>
<option v-for="o in EXPIRY_OPTIONS" :key="o.days" :value="o.days">
{{ o.days === 0 ? 'Unbegrenzt' : `${o.label} ab jetzt` }}
</option>
</select>
</div>
</template>
<div v-else class="row">
<div class="segmented" role="radiogroup" aria-label="Art">
<button
type="button"
@@ -215,6 +264,7 @@ onMounted(async () => {
</div>
<textarea
v-if="!isFile"
v-model="content"
:class="{ mono: kind === 'code' }"
rows="14"
@@ -234,7 +284,10 @@ onMounted(async () => {
<button type="submit" class="primary" :disabled="busy || remoteDeleted || !content.trim()">
Speichern
</button>
<CopyButton :text="content" />
<a v-if="clip.file" :href="`/api/files/${clip.id}`" download class="button-link"
>Herunterladen</a
>
<CopyButton v-else :text="content" />
<RouterLink to="/" class="button-link">Abbrechen</RouterLink>
<div class="spacer"></div>
<button type="button" class="danger" @click="remove">Löschen</button>
@@ -269,6 +322,21 @@ onMounted(async () => {
font-size: 0.85rem;
}
.file-info {
display: grid;
padding: 0.75rem;
border-radius: calc(var(--radius) - 4px);
background: var(--bg);
}
.file-name {
overflow-wrap: anywhere;
}
.expiry {
width: auto;
}
.conflict {
border-color: var(--error);
}