From c7eb52013479e88fe939a4069881c16829dcb5e3 Mon Sep 17 00:00:00 2001 From: Filionus Date: Mon, 30 Nov 2026 10:40:02 +0100 Subject: [PATCH 01/11] Claim the photo gallery and ask for cancelling uploads Co-Authored-By: Claude Sonnet 5.5 --- docs/BACKLOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index 9ef973c..df863f0 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -8,8 +8,12 @@ - **F4/F5 Dates table:** Lastenheft F4 asks for an interactive table. A desktop table view with sorting (`sort` and `order` exist in the API) comes later. - **F7/F8 Dashboard** (countdown, dates created per month, category totals): done (PR #19). - **F6 Location** (save and delete the own location, distance and midpoint, link to OpenStreetMap; no map): done (PR #20). -- **Landing page** (start page `/`, `/en`, `/nl` with register and sign-in; "frontend prompt F10", not requirement F10): - claimed by `Filionus`, branch `feat/landing`, in progress. +- **Landing page** (start page `/`, `/en`, `/nl` with register and sign-in; "frontend prompt F10", not requirement F10): done (PR #21). +- **F3 Photos** (add from file or camera, shared gallery, delete; no captions, albums or zoom): + claimed by `Filionus`, branch `feat/photos`, in progress. +- **F3 Photos, wish for the backend:** an endpoint that cancels an open upload, for example + `DELETE /api/photos/uploads/:uploadId`. An unfinished upload blocks 5 MiB for more than two hours, and a file that + was stored but never confirmed counts against the quota until somebody removes it by hand. - **Landing page, still open:** logo and illustrations from the designer (the page uses a text wordmark so far). SEO beyond title and description: `hreflang` and canonical links, sitemap, `robots.txt`, Open Graph with a preview image and structured data. Most of these need a fixed base URL. From a3b45322f0ff78763cf22001c04e9e3b259a052a Mon Sep 17 00:00:00 2001 From: Filionus Date: Mon, 30 Nov 2026 10:40:09 +0100 Subject: [PATCH 02/11] Add tests for preparing, uploading and listing photos Co-Authored-By: Claude Sonnet 5.5 --- composables/__tests__/fake-image.ts | 26 ++ composables/__tests__/fake-photos-api.ts | 187 +++++++++ composables/__tests__/galleryUpload.spec.ts | 64 +++ composables/__tests__/photoRules.spec.ts | 65 +++ composables/__tests__/preparePhoto.spec.ts | 97 +++++ composables/__tests__/reset-upload.ts | 13 + .../__tests__/usePhotoUpload.nuxt.spec.ts | 386 ++++++++++++++++++ composables/__tests__/usePhotos.nuxt.spec.ts | 301 ++++++++++++++ 8 files changed, 1139 insertions(+) create mode 100644 composables/__tests__/fake-image.ts create mode 100644 composables/__tests__/fake-photos-api.ts create mode 100644 composables/__tests__/galleryUpload.spec.ts create mode 100644 composables/__tests__/photoRules.spec.ts create mode 100644 composables/__tests__/preparePhoto.spec.ts create mode 100644 composables/__tests__/reset-upload.ts create mode 100644 composables/__tests__/usePhotoUpload.nuxt.spec.ts create mode 100644 composables/__tests__/usePhotos.nuxt.spec.ts diff --git a/composables/__tests__/fake-image.ts b/composables/__tests__/fake-image.ts new file mode 100644 index 0000000..e29cc6c --- /dev/null +++ b/composables/__tests__/fake-image.ts @@ -0,0 +1,26 @@ +import { vi } from 'vitest' +import type { DecodedImage } from '../preparePhoto' + +// Stand-ins for files and for the browser's image decoder. +// It lives in a __tests__ folder, so Nuxt does not auto-import it. + +export function aFile(type = 'image/jpeg', bytes = 2000, name = 'photo.jpg') { + return new File([new Uint8Array(bytes)], name, { type }) +} + +// A decoder for an image of the given size. Each JPEG it makes is as large as +// "sizes" says, one entry per attempt; the last entry repeats. +export function fakeDecoder({ width = 4000, height = 3000, sizes = [500_000] } = {}) { + const attempts = [...sizes] + const image = { + width, + height, + toJpeg: vi.fn(async (_width: number, _height: number, _quality: number): Promise => { + const size = attempts.length > 1 ? attempts.shift()! : attempts[0]! + return new Blob([new Uint8Array(size)], { type: 'image/jpeg' }) + }), + release: vi.fn(), + } satisfies DecodedImage + const decode = vi.fn(async (_file: Blob): Promise => image) + return { decode, image } +} diff --git a/composables/__tests__/fake-photos-api.ts b/composables/__tests__/fake-photos-api.ts new file mode 100644 index 0000000..0823779 --- /dev/null +++ b/composables/__tests__/fake-photos-api.ts @@ -0,0 +1,187 @@ +import { registerEndpoint } from '@nuxt/test-utils/runtime' +import { createError, getQuery, readBody, setResponseStatus } from 'h3' +import { vi } from 'vitest' +import type { PhotosResponse } from '../../shared/api-contract' +import { ANN, SPACE_ID } from './fake-space-api' + +// An in-memory stand-in for the photo routes and the private storage bucket. +// It lives in a __tests__ folder, so Nuxt does not auto-import it. + +type Action = 'list' | 'reserve' | 'confirm' | 'delete' +type Photo = PhotosResponse[number] + +export function photoId(number: number) { + return `10000000-0000-4000-8000-${String(number).padStart(12, '0')}` +} + +// A photo as the list route returns it. The higher the number, the newer the photo. +export function aPhoto(number: number, changes: Partial = {}): Photo { + return { + name: photoId(number), + createdAt: new Date(Date.UTC(2026, 10, 1, 12, number)).toISOString(), + url: `https://storage.test/${photoId(number)}?token=1`, + mime: 'image/jpeg', + size: 1000, + uploadedBy: ANN, + ...changes, + } +} + +// Registers the routes. Call remove() after the test. +export function fakePhotosApi() { + const failures = new Map() + const holds = new Map[]>() + const removals: (() => void)[] = [] + const routed = new Set() + let photos: Photo[] = [] + let reserved = 500 + // Every answer of the list route carries new signed addresses. + let signed = 1 + + // Open uploads by id, and the files in the bucket by path. + const reservations = new Map() + const files = new Map() + + const backend = { + requests: { list: vi.fn(), reserve: vi.fn(), confirm: vi.fn(), delete: vi.fn() }, + reservations, + files, + // False: the list keeps handing out the same address. + renewUrls: true, + seed(...stored: Photo[]) { + photos = [...stored].sort((a, b) => b.createdAt.localeCompare(a.createdAt)) + photos.forEach(photo => route(photo.name)) + }, + seedMany(count: number) { + backend.seed(...Array.from({ length: count }, (_unused, index) => aPhoto(index + 1))) + }, + drop(name: string) { + photos = photos.filter(photo => photo.name !== name) + }, + stored() { + return photos + }, + // What the storage service does with a signed upload: a path can be written once. + receive(path: string, file: Blob) { + if (files.has(path)) { + throw new Error('The resource already exists') + } + files.set(path, file) + }, + // The next request of this kind fails the way the API reports errors. + failOnce(action: Action, status: number, code: string) { + failures.set(action, [...(failures.get(action) ?? []), { status, code }]) + }, + // $fetch repeats a failed GET once, so listing only fails if both attempts do. + failListing(status = 500, code = 'internal') { + backend.failOnce('list', status, code) + backend.failOnce('list', status, code) + }, + holdNext(action: Action) { + let release = () => {} + const gate = new Promise((resolve) => { + release = resolve + }) + holds.set(action, [...(holds.get(action) ?? []), gate]) + return release + }, + remove() { + removals.forEach(remove => remove()) + }, + } + + async function answer(action: Action, respond: () => unknown) { + const failure = failures.get(action)?.shift() + if (failure) { + throw createError({ statusCode: failure.status, data: { code: failure.code } }) + } + const gate = holds.get(action)?.shift() + const response = structuredClone(respond()) + await gate + return response + } + + const notFound = () => createError({ statusCode: 404, data: { code: 'not_found' } }) + + // The test server only matches exact paths, so every photo gets its own route. + function route(name: string) { + if (routed.has(name)) { + return + } + routed.add(name) + removals.push(registerEndpoint(`/api/photos/${name}`, { + method: 'DELETE', + handler: async (event) => { + backend.requests.delete(name) + return answer('delete', () => { + if (!photos.some(photo => photo.name === name)) { + throw notFound() + } + backend.drop(name) + setResponseStatus(event, 204) + return null + }) + }, + })) + } + + removals.push(registerEndpoint('/api/photos', { + method: 'GET', + handler: async (event) => { + const query = getQuery(event) + backend.requests.list(query) + return answer('list', () => { + const offset = Number(query.offset ?? 0) + if (backend.renewUrls) { + signed += 1 + photos = photos.map(photo => ({ + ...photo, + url: photo.url && photo.url.replace(/token=\d+/, `token=${signed}`), + })) + } + return photos.slice(offset, offset + 30) + }) + }, + })) + + removals.push(registerEndpoint('/api/photos/upload-url', { + method: 'POST', + handler: async (event) => { + const body = await readBody(event) + backend.requests.reserve(body) + return answer('reserve', () => { + reserved += 1 + const uploadId = photoId(reserved) + const path = `${SPACE_ID}/${uploadId}` + reservations.set(uploadId, { path, ...body }) + return { uploadId, path, signedUrl: `https://storage.test/upload/${uploadId}`, token: `token-${reserved}` } + }) + }, + })) + + removals.push(registerEndpoint('/api/photos/confirm', { + method: 'POST', + handler: async (event) => { + const body = await readBody(event) + backend.requests.confirm(body) + return answer('confirm', () => { + const reservation = reservations.get(body.uploadId) + const file = reservation && files.get(reservation.path) + if (!reservation || !file) { + throw notFound() + } + if (file.size !== reservation.size || file.type !== reservation.mime) { + throw createError({ statusCode: 400, data: { code: 'validation_failed' } }) + } + // Confirming twice returns the same photo. + if (!photos.some(photo => photo.name === body.uploadId)) { + const number = Number(body.uploadId.slice(-12)) + backend.seed(aPhoto(number, { size: file.size }), ...photos) + } + return { id: body.uploadId, path: reservation.path } + }) + }, + })) + + return backend +} diff --git a/composables/__tests__/galleryUpload.spec.ts b/composables/__tests__/galleryUpload.spec.ts new file mode 100644 index 0000000..384a50a --- /dev/null +++ b/composables/__tests__/galleryUpload.spec.ts @@ -0,0 +1,64 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { UPLOAD_GIVE_UP_MS, uploadToGallery } from '../galleryUpload' +import { aFile } from './fake-image' + +const reservation = { path: 'space/photo', token: 'signed-token' } + +// The parts of the Supabase storage client that the upload uses. +function fakeStorage(result: () => Promise<{ error: Error | null }> = async () => ({ error: null })) { + const uploadToSignedUrl = vi.fn(result) + const from = vi.fn(() => ({ uploadToSignedUrl })) + return { client: { from } as unknown as Parameters[0], from, uploadToSignedUrl } +} + +afterEach(() => vi.useRealTimers()) + +describe('sending a file to storage', () => { + test('uses the signed address of the private gallery', async () => { + const storage = fakeStorage() + const file = aFile() + + await uploadToGallery(storage.client, reservation, file) + + expect(storage.from).toHaveBeenCalledWith('gallery') + expect(storage.uploadToSignedUrl).toHaveBeenCalledWith('space/photo', 'signed-token', file, { contentType: 'image/jpeg' }) + }) + + test('fails when storage reports an error', async () => { + const storage = fakeStorage(async () => ({ error: new Error('text from storage') })) + + await expect(uploadToGallery(storage.client, reservation, aFile())).rejects.toThrow() + }) + + test('fails when the request itself fails', async () => { + const storage = fakeStorage(async () => { + throw new TypeError('Failed to fetch') + }) + + await expect(uploadToGallery(storage.client, reservation, aFile())).rejects.toThrow() + }) + + test('fails when there is no storage client', async () => { + await expect(uploadToGallery(undefined, reservation, aFile())).rejects.toThrow() + }) + + // A hanging upload would leave the person with no way out. + test('gives up after two minutes', async () => { + vi.useFakeTimers() + const storage = fakeStorage(() => new Promise(() => {})) + const failed = expect(uploadToGallery(storage.client, reservation, aFile())).rejects.toThrow() + + await vi.advanceTimersByTimeAsync(UPLOAD_GIVE_UP_MS) + + await failed + expect(UPLOAD_GIVE_UP_MS).toBe(120_000) + }) + + test('leaves no timer behind', async () => { + vi.useFakeTimers() + + await uploadToGallery(fakeStorage().client, reservation, aFile()) + + expect(vi.getTimerCount()).toBe(0) + }) +}) diff --git a/composables/__tests__/photoRules.spec.ts b/composables/__tests__/photoRules.spec.ts new file mode 100644 index 0000000..470740b --- /dev/null +++ b/composables/__tests__/photoRules.spec.ts @@ -0,0 +1,65 @@ +import { describe, expect, test } from 'vitest' +import { photoContentTypeSchema, photoUploadMaxBytes } from '../../shared/api-contract' +import { PHOTO_INPUT_MAX_BYTES, PHOTO_MAX_BYTES, PHOTO_TYPES, fitWithin, formatUploadTime, photoFileError } from '../photoRules' +import { aFile } from './fake-image' + +const MB = 1024 * 1024 + +describe('choosing a file', () => { + test.each(['image/jpeg', 'image/png', 'image/webp'])('accepts %s', (type) => { + expect(photoFileError(aFile(type))).toBeUndefined() + }) + + test.each([ + ['an iPhone photo', 'image/heic', 'IMG_1.heic'], + ['an animation', 'image/gif', 'a.gif'], + ['a vector image', 'image/svg+xml', 'a.svg'], + ['a video', 'video/mp4', 'a.mp4'], + ['a document', 'application/pdf', 'a.pdf'], + ['a file without a known type', '', 'IMG_2.heic'], + ])('rejects %s', (_name, type, fileName) => { + expect(photoFileError(aFile(type, 100, fileName))).toBe('errors.photo.type') + }) + + test('rejects an empty file', () => { + expect(photoFileError(aFile('image/jpeg', 0))).toBe('errors.photo.unreadable') + }) + + // Larger than the upload limit is fine, because the photo is made smaller first. + test('accepts up to 25 MB', () => { + expect(PHOTO_INPUT_MAX_BYTES).toBe(25 * MB) + expect(photoFileError(aFile('image/jpeg', 25 * MB))).toBeUndefined() + expect(photoFileError(aFile('image/jpeg', 25 * MB + 1))).toBe('errors.photo.tooLarge') + }) + + test('agrees with the contract on types and the upload limit', () => { + expect([...PHOTO_TYPES]).toEqual(photoContentTypeSchema.options) + expect(PHOTO_MAX_BYTES).toBe(photoUploadMaxBytes) + }) +}) + +describe('the size of the stored photo', () => { + test.each([ + [4000, 3000, 2048, 1536], + [3000, 4000, 1536, 2048], + [8000, 2000, 2048, 512], + [800, 600, 800, 600], + [2048, 2048, 2048, 2048], + [10000, 1, 2048, 1], + ])('turns %i x %i into %i x %i', (width, height, newWidth, newHeight) => { + expect(fitWithin(width, height, 2048)).toEqual({ width: newWidth, height: newHeight }) + }) +}) + +describe('the upload time', () => { + test.each([ + ['de-DE', '30. November 2026', '13:05'], + ['en-GB', '30 November 2026', '13:05'], + ['nl-NL', '30 november 2026', '13:05'], + ])('is written in the form of %s', (locale, date, time) => { + const text = formatUploadTime('2026-11-30T12:05:00+00:00', locale, 'Europe/Berlin') + + expect(text).toContain(date) + expect(text).toContain(time) + }) +}) diff --git a/composables/__tests__/preparePhoto.spec.ts b/composables/__tests__/preparePhoto.spec.ts new file mode 100644 index 0000000..e426c27 --- /dev/null +++ b/composables/__tests__/preparePhoto.spec.ts @@ -0,0 +1,97 @@ +import { describe, expect, test, vi } from 'vitest' +import { preparePhoto } from '../preparePhoto' +import { aFile, fakeDecoder } from './fake-image' + +const MB = 1024 * 1024 + +describe('preparing a photo', () => { + // Re-encoding also removes the metadata, for example where a photo was taken. + test.each(['image/jpeg', 'image/png', 'image/webp'])('stores %s as a new JPEG', async (type) => { + const { decode, image } = fakeDecoder({ width: 800, height: 600 }) + + const result = await preparePhoto(aFile(type), decode) + + expect(result.type).toBe('image/jpeg') + expect(image.toJpeg).toHaveBeenCalledWith(800, 600, 0.85) + }) + + test('makes a large photo smaller', async () => { + const { decode, image } = fakeDecoder({ width: 4032, height: 3024 }) + + await preparePhoto(aFile('image/jpeg', 12 * MB), decode) + + expect(image.toJpeg).toHaveBeenCalledWith(2048, 1536, 0.85) + }) + + test('tries harder until the photo fits into the upload limit', async () => { + const { decode, image } = fakeDecoder({ width: 4000, height: 3000, sizes: [6 * MB, 6 * MB, 4 * MB] }) + + const result = await preparePhoto(aFile(), decode) + + expect(result.size).toBe(4 * MB) + expect(image.toJpeg.mock.calls).toEqual([[2048, 1536, 0.85], [2048, 1536, 0.7], [1600, 1200, 0.7]]) + }) + + test('gives up when it stays too large', async () => { + const { decode } = fakeDecoder({ sizes: [6 * MB] }) + + await expect(preparePhoto(aFile(), decode)).rejects.toMatchObject({ messageKey: 'errors.photo.stillTooLarge' }) + }) + + test('does not even open a file of the wrong type', async () => { + const { decode } = fakeDecoder() + + await expect(preparePhoto(aFile('image/heic'), decode)).rejects.toMatchObject({ messageKey: 'errors.photo.type' }) + expect(decode).not.toHaveBeenCalled() + }) + + // For example a HEIC photo that only carries the name of a JPEG. + test('rejects a file that cannot be decoded', async () => { + const decode = vi.fn(async () => { + throw new Error('text from the browser') + }) + + await expect(preparePhoto(aFile(), decode)).rejects.toMatchObject({ messageKey: 'errors.photo.unreadable' }) + }) + + test.each([ + [0, 0], + [0, 600], + [800, 0], + ])('rejects an image of %i x %i pixels', async (width, height) => { + const { decode, image } = fakeDecoder({ width, height }) + + await expect(preparePhoto(aFile(), decode)).rejects.toMatchObject({ messageKey: 'errors.photo.unreadable' }) + expect(image.toJpeg).not.toHaveBeenCalled() + }) + + test.each([ + ['nothing', null], + ['an empty file', new Blob([], { type: 'image/jpeg' })], + // A browser that cannot write JPEG answers with another type. + ['another format', new Blob(['png'], { type: 'image/png' })], + ])('never returns %s', async (_name, output) => { + const { decode, image } = fakeDecoder() + image.toJpeg.mockResolvedValue(output) + + await expect(preparePhoto(aFile(), decode)).rejects.toMatchObject({ messageKey: 'errors.photo.unreadable' }) + }) + + test('reports a failure while drawing', async () => { + const { decode, image } = fakeDecoder() + image.toJpeg.mockRejectedValue(new Error('out of memory')) + + await expect(preparePhoto(aFile(), decode)).rejects.toMatchObject({ messageKey: 'errors.photo.unreadable' }) + }) + + test.each([ + ['success', 500_000], + ['failure', 6 * MB], + ])('releases the image after %s', async (_name, size) => { + const { decode, image } = fakeDecoder({ sizes: [size] }) + + await preparePhoto(aFile(), decode).catch(() => {}) + + expect(image.release).toHaveBeenCalledTimes(1) + }) +}) diff --git a/composables/__tests__/reset-upload.ts b/composables/__tests__/reset-upload.ts new file mode 100644 index 0000000..3f187d9 --- /dev/null +++ b/composables/__tests__/reset-upload.ts @@ -0,0 +1,13 @@ +import { useNuxtApp } from '#app' +import { usePhotoUploadStore } from '../../stores/photoUpload' +import { resetSpace } from './reset-space' + +// The Nuxt test app lives for a whole test file, so each test needs fresh stores. +// The upload store goes first, because it watches the session store. +export function resetUpload() { + const store = usePhotoUploadStore() + store.clear() + store.$dispose() + delete (useNuxtApp().$pinia as { state: { value: Record } }).state.value.photoUpload + resetSpace() +} diff --git a/composables/__tests__/usePhotoUpload.nuxt.spec.ts b/composables/__tests__/usePhotoUpload.nuxt.spec.ts new file mode 100644 index 0000000..3bbd6d3 --- /dev/null +++ b/composables/__tests__/usePhotoUpload.nuxt.spec.ts @@ -0,0 +1,386 @@ +import { mockNuxtImport } from '@nuxt/test-utils/runtime' +import { flushPromises } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { useSessionStore } from '../../stores/session' +import { usePhotoUpload } from '../usePhotoUpload' +import { createFakeAuth } from './fake-auth' +import { aFile, fakeDecoder } from './fake-image' +import { fakePhotosApi } from './fake-photos-api' +import { ANN, BEN, CODE, fakeSpaceApi, member, spaceOf } from './fake-space-api' +import { resetUpload } from './reset-upload' + +const fakes = vi.hoisted(() => ({ + auth: undefined as unknown, + send: undefined as unknown as (reservation: { path: string }, file: Blob) => Promise, + decode: undefined as unknown as (file: Blob) => Promise, +})) +mockNuxtImport('useSupabaseAuth', () => () => fakes.auth) +mockNuxtImport('useGalleryStorage', () => () => (reservation: { path: string }, file: Blob) => fakes.send(reservation, file)) +mockNuxtImport('decodeInBrowser', () => (file: Blob) => fakes.decode(file)) + +let fake: ReturnType +let photos: ReturnType +let space: ReturnType +// The upload to storage. By default it arrives. +let send: ReturnType Promise>> +let decoder: ReturnType + +beforeEach(async () => { + await useNuxtApp().$i18n.setLocale('de') + fake = createFakeAuth({ signedInAs: 'ann@example.org' }) + fakes.auth = fake.auth + resetUpload() + space = fakeSpaceApi() + space.space = spaceOf([member(ANN, 'Ann'), member(BEN, 'Ben', 2)], CODE) + photos = fakePhotosApi() + send = vi.fn(async (reservation, file) => photos.receive(reservation.path, file)) + fakes.send = send + decoder = fakeDecoder() + fakes.decode = decoder.decode + await useRouter().push('/map') +}) + +afterEach(() => { + resetUpload() + photos.remove() + space.remove() + vi.useRealTimers() + vi.restoreAllMocks() +}) + +const loseConnection = () => send.mockRejectedValueOnce(new Error('offline')) +const requestCount = () => + photos.requests.reserve.mock.calls.length + photos.requests.confirm.mock.calls.length + send.mock.calls.length + +describe('adding a photo', () => { + test('reserves, uploads and confirms', async () => { + const upload = usePhotoUpload() + + await upload.select(aFile()) + + expect(photos.requests.reserve).toHaveBeenCalledWith({ mime: 'image/jpeg', size: 500_000 }) + expect(send).toHaveBeenCalledTimes(1) + const [reservation, file] = send.mock.calls[0]! + expect(file.size).toBe(500_000) + expect(photos.requests.confirm).toHaveBeenCalledWith({ uploadId: reservation.path.split('/')[1] }) + expect(photos.stored()).toHaveLength(1) + expect(upload.pending.value).toBe(false) + expect(upload.failure.value).toBeUndefined() + expect(upload.completed.value).toBe(1) + }) + + test('names each step while it runs', async () => { + const upload = usePhotoUpload() + let finishDecoding = () => {} + decoder.decode.mockImplementationOnce(() => new Promise((resolve) => { + finishDecoding = () => resolve(decoder.image) + })) + const releaseReserve = photos.holdNext('reserve') + let finishSending = () => {} + send.mockImplementationOnce((reservation, file) => new Promise((resolve) => { + finishSending = () => resolve(photos.receive(reservation.path, file)) + })) + const releaseConfirm = photos.holdNext('confirm') + + const done = upload.select(aFile()) + expect(upload.step.value).toBe('preparing') + finishDecoding() + await vi.waitFor(() => expect(upload.step.value).toBe('reserving')) + releaseReserve() + await vi.waitFor(() => expect(upload.step.value).toBe('uploading')) + finishSending() + await vi.waitFor(() => expect(upload.step.value).toBe('confirming')) + releaseConfirm() + await done + + expect(upload.step.value).toBeUndefined() + }) + + test.each([ + ['of the wrong type', aFile('image/heic', 100, 'a.heic'), 'errors.photo.type'], + ['that is too large', aFile('image/jpeg', 25 * 1024 * 1024 + 1), 'errors.photo.tooLarge'], + ['that is empty', aFile('image/jpeg', 0), 'errors.photo.unreadable'], + ])('rejects a file %s before any request', async (_name, file, messageKey) => { + const upload = usePhotoUpload() + + await upload.select(file) + + expect(upload.selectionError.value).toBe(messageKey) + expect(requestCount()).toBe(0) + expect(upload.pending.value).toBe(false) + }) + + test('rejects a file that cannot be decoded before any request', async () => { + decoder.decode.mockRejectedValueOnce(new Error('text from the browser')) + const upload = usePhotoUpload() + + await upload.select(aFile()) + + expect(upload.selectionError.value).toBe('errors.photo.unreadable') + expect(requestCount()).toBe(0) + }) + + test('forgets the old message with the next file', async () => { + const upload = usePhotoUpload() + await upload.select(aFile('image/gif')) + + await upload.select(aFile()) + + expect(upload.selectionError.value).toBeUndefined() + }) + + test('takes one photo at a time', async () => { + const upload = usePhotoUpload() + + await Promise.all([upload.select(aFile()), upload.select(aFile())]) + + expect(photos.requests.reserve).toHaveBeenCalledTimes(1) + }) + + test('takes no new photo while one is unfinished', async () => { + const upload = usePhotoUpload() + loseConnection() + await upload.select(aFile()) + + await upload.select(aFile()) + + expect(photos.requests.reserve).toHaveBeenCalledTimes(1) + }) +}) + +// Every reservation blocks 5 MiB for two hours, so a retry has to use the same one. +describe('when a step fails', () => { + test.each([ + [409, 'quota_exceeded', 'errors.api.quotaExceeded'], + [500, 'internal', 'errors.api.internal'], + ])('reports a refused reservation (%i %s) and can try again', async (status, code, messageKey) => { + const upload = usePhotoUpload() + photos.failOnce('reserve', status, code) + + await upload.select(aFile()) + + expect(upload.failure.value).toEqual({ step: 'reserving', messageKey }) + expect(upload.leftover.value).toBe('nothing') + expect(send).not.toHaveBeenCalled() + + await upload.retry() + + expect(photos.stored()).toHaveLength(1) + }) + + test('reports a failed upload and keeps the reservation', async () => { + const upload = usePhotoUpload() + loseConnection() + + await upload.select(aFile()) + + expect(upload.failure.value).toEqual({ step: 'uploading', messageKey: 'errors.photo.upload' }) + expect(upload.pending.value).toBe(true) + // The request was on its way, so the file may be stored. + expect(upload.leftover.value).toBe('file') + expect(photos.requests.confirm).not.toHaveBeenCalled() + }) + + test('uploads again with the same reservation, without preparing again', async () => { + const upload = usePhotoUpload() + loseConnection() + await upload.select(aFile()) + + await upload.retry() + + expect(photos.requests.reserve).toHaveBeenCalledTimes(1) + expect(decoder.decode).toHaveBeenCalledTimes(1) + expect(send).toHaveBeenCalledTimes(2) + expect(send.mock.calls[1]![0]).toEqual(send.mock.calls[0]![0]) + expect(photos.stored()).toHaveLength(1) + expect(upload.pending.value).toBe(false) + }) + + // The file arrived, only the answer got lost. Uploading again would be refused. + test('only confirms when the file has arrived after all', async () => { + const upload = usePhotoUpload() + send.mockImplementationOnce(async (reservation, file) => { + photos.receive(reservation.path, file) + throw new Error('answer lost') + }) + await upload.select(aFile()) + + await upload.retry() + + expect(send).toHaveBeenCalledTimes(1) + expect(photos.stored()).toHaveLength(1) + expect(upload.pending.value).toBe(false) + }) + + test('only confirms again when confirming failed', async () => { + const upload = usePhotoUpload() + photos.failOnce('confirm', 500, 'internal') + await upload.select(aFile()) + expect(upload.failure.value).toEqual({ step: 'confirming', messageKey: 'errors.api.internal' }) + expect(upload.leftover.value).toBe('file') + + await upload.retry() + + expect(photos.requests.reserve).toHaveBeenCalledTimes(1) + expect(send).toHaveBeenCalledTimes(1) + expect(photos.requests.confirm).toHaveBeenCalledTimes(2) + expect(photos.stored()).toHaveLength(1) + }) + + test('keeps everything when the check before a new upload fails', async () => { + const upload = usePhotoUpload() + loseConnection() + await upload.select(aFile()) + photos.failOnce('confirm', 500, 'internal') + + await upload.retry() + + expect(upload.failure.value).toEqual({ step: 'confirming', messageKey: 'errors.api.internal' }) + expect(send).toHaveBeenCalledTimes(1) + }) + + test('starts over when the stored file does not match', async () => { + const upload = usePhotoUpload() + photos.failOnce('confirm', 400, 'validation_failed') + await upload.select(aFile()) + expect(upload.failure.value).toEqual({ step: 'confirming', messageKey: 'errors.photo.mismatch' }) + + await upload.retry() + + expect(photos.requests.reserve).toHaveBeenCalledTimes(2) + expect(photos.stored()).toHaveLength(1) + }) + + test('starts over when the upload cannot be found right after sending it', async () => { + const upload = usePhotoUpload() + photos.failOnce('confirm', 404, 'not_found') + await upload.select(aFile()) + expect(upload.failure.value).toEqual({ step: 'confirming', messageKey: 'errors.photo.lost' }) + + await upload.retry() + + expect(photos.requests.reserve).toHaveBeenCalledTimes(2) + expect(photos.stored()).toHaveLength(1) + }) + + // The signed address works for two hours. + test('reserves again when the old address has expired', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(new Date('2026-12-01T10:00:00Z')) + const upload = usePhotoUpload() + loseConnection() + await upload.select(aFile()) + vi.setSystemTime(new Date('2026-12-01T12:00:01Z')) + + await upload.retry() + + expect(photos.requests.reserve).toHaveBeenCalledTimes(2) + expect(photos.stored()).toHaveLength(1) + }) + + test('says that a reservation stays blocked when nothing was sent', async () => { + const upload = usePhotoUpload() + // The person has no connection when the upload is about to start. + send.mockImplementation(async () => { + throw new Error('offline') + }) + await upload.select(aFile()) + + expect(upload.leftover.value).not.toBe('nothing') + }) + + test('can be discarded', async () => { + const upload = usePhotoUpload() + loseConnection() + await upload.select(aFile()) + + upload.discard() + + expect(upload.pending.value).toBe(false) + expect(upload.failure.value).toBeUndefined() + await upload.select(aFile()) + expect(photos.requests.reserve).toHaveBeenCalledTimes(2) + }) + + test('explains a missing space and drops the upload', async () => { + const upload = usePhotoUpload() + photos.failOnce('reserve', 403, 'no_space') + + await upload.select(aFile()) + + expect(upload.selectionError.value).toBe('errors.api.noSpace') + expect(upload.pending.value).toBe(false) + }) +}) + +describe('an unfinished upload', () => { + test('is still there after leaving the page', async () => { + loseConnection() + await usePhotoUpload().select(aFile()) + + const later = usePhotoUpload() + expect(later.pending.value).toBe(true) + await later.retry() + + expect(photos.stored()).toHaveLength(1) + }) + + function closingTheTab() { + const event = new Event('beforeunload', { cancelable: true }) + window.dispatchEvent(event) + return event.defaultPrevented + } + + test('makes the browser warn before the tab is closed', async () => { + const upload = usePhotoUpload() + expect(closingTheTab()).toBe(false) + loseConnection() + + await upload.select(aFile()) + await flushPromises() + expect(closingTheTab()).toBe(true) + + await upload.retry() + await flushPromises() + expect(closingTheTab()).toBe(false) + }) + + test('also warns while the upload is running', async () => { + const upload = usePhotoUpload() + const release = photos.holdNext('reserve') + + const done = upload.select(aFile()) + await flushPromises() + expect(closingTheTab()).toBe(true) + release() + await done + }) + + test('is forgotten when somebody else signs in', async () => { + const upload = usePhotoUpload() + loseConnection() + await upload.select(aFile()) + + fake.endSession() + await useSessionStore().signIn('ben@example.org', 'secret-12') + + expect(usePhotoUpload().pending.value).toBe(false) + }) + + // The photo was chosen under one account and must not end up under another. + test('stops when somebody else signs in on the way', async () => { + const upload = usePhotoUpload() + const release = photos.holdNext('reserve') + const done = upload.select(aFile()) + await vi.waitFor(() => expect(photos.requests.reserve).toHaveBeenCalled()) + + fake.endSession() + await useSessionStore().signIn('ben@example.org', 'secret-12') + release() + await done + + expect(send).not.toHaveBeenCalled() + expect(photos.requests.confirm).not.toHaveBeenCalled() + expect(upload.pending.value).toBe(false) + }) +}) diff --git a/composables/__tests__/usePhotos.nuxt.spec.ts b/composables/__tests__/usePhotos.nuxt.spec.ts new file mode 100644 index 0000000..a8bf413 --- /dev/null +++ b/composables/__tests__/usePhotos.nuxt.spec.ts @@ -0,0 +1,301 @@ +import { mockNuxtImport } from '@nuxt/test-utils/runtime' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { usePhotos } from '../usePhotos' +import { createFakeAuth } from './fake-auth' +import { aPhoto, fakePhotosApi, photoId } from './fake-photos-api' +import { ANN, CODE, fakeSpaceApi, member, spaceOf } from './fake-space-api' +import { resetSpace } from './reset-space' + +const supabase = vi.hoisted(() => ({ auth: undefined as unknown })) +mockNuxtImport('useSupabaseAuth', () => () => supabase.auth) + +let photos: ReturnType +let space: ReturnType + +beforeEach(async () => { + await useNuxtApp().$i18n.setLocale('de') + supabase.auth = createFakeAuth({ signedInAs: 'ann@example.org' }).auth + resetSpace() + space = fakeSpaceApi() + space.space = spaceOf([member(ANN, 'Ann')], CODE) + photos = fakePhotosApi() + await useRouter().push('/map') +}) + +afterEach(() => { + photos.remove() + space.remove() +}) + +async function loaded() { + const gallery = usePhotos() + await gallery.load() + return gallery +} + +const names = (gallery: ReturnType) => gallery.photos.value.map(photo => photo.name) + +describe('loading the gallery', () => { + test('is loading before the first answer', () => { + expect(usePhotos().status.value).toBe('loading') + }) + + test('shows the photos newest first', async () => { + photos.seed(aPhoto(1), aPhoto(2)) + + const gallery = await loaded() + + expect(gallery.status.value).toBe('ready') + expect(names(gallery)).toEqual([photoId(2), photoId(1)]) + expect(gallery.hasMore.value).toBe(false) + }) + + test('reports a failure and can be tried again', async () => { + photos.failListing() + const gallery = await loaded() + expect(gallery.status.value).toBe('failed') + expect(gallery.loadError.value).toBe('errors.api.internal') + + await gallery.load() + + expect(gallery.status.value).toBe('ready') + }) + + test('recognizes somebody without a space from the error code', async () => { + photos.failListing(403, 'no_space') + + const gallery = await loaded() + + expect(gallery.status.value).toBe('noSpace') + }) + + test('recognizes somebody without a space from the space', async () => { + space.space = null + + const gallery = await loaded() + + expect(gallery.status.value).toBe('noSpace') + }) +}) + +describe('loading more', () => { + test('appends the next 30 photos', async () => { + photos.seedMany(65) + const gallery = await loaded() + expect(gallery.photos.value).toHaveLength(30) + expect(gallery.hasMore.value).toBe(true) + + await gallery.loadMore() + + expect(photos.requests.list).toHaveBeenLastCalledWith({ offset: '30' }) + expect(gallery.photos.value).toHaveLength(60) + await gallery.loadMore() + expect(gallery.photos.value).toHaveLength(65) + expect(gallery.hasMore.value).toBe(false) + }) + + test('shows no photo twice when one was added meanwhile', async () => { + photos.seedMany(35) + const gallery = await loaded() + photos.seed(aPhoto(36), ...photos.stored()) + + await gallery.loadMore() + + expect(new Set(names(gallery)).size).toBe(names(gallery).length) + }) + + test('keeps the photos and reports a failure', async () => { + photos.seedMany(35) + const gallery = await loaded() + photos.failListing() + + await gallery.loadMore() + + expect(gallery.photos.value).toHaveLength(30) + expect(gallery.moreError.value).toBe('errors.api.internal') + }) +}) + +// The signed addresses expire after five minutes. +describe('refreshing', () => { + test('fetches new addresses without leaving the screen', async () => { + photos.seed(aPhoto(1)) + const gallery = await loaded() + const before = gallery.photos.value[0]!.url + + await expect(gallery.refresh()).resolves.toBe(true) + + expect(gallery.photos.value[0]!.url).not.toBe(before) + expect(gallery.status.value).toBe('ready') + }) + + test('keeps as many pages as are on screen', async () => { + photos.seedMany(65) + const gallery = await loaded() + await gallery.loadMore() + photos.requests.list.mockClear() + + await gallery.refresh() + + expect(photos.requests.list.mock.calls).toEqual([[{ offset: '0' }], [{ offset: '30' }]]) + expect(gallery.photos.value).toHaveLength(60) + }) + + test('shows a photo of the partner', async () => { + const gallery = await loaded() + photos.seed(aPhoto(1)) + + await gallery.refresh() + + expect(names(gallery)).toEqual([photoId(1)]) + }) + + test('keeps what is there when it fails', async () => { + photos.seed(aPhoto(1)) + const gallery = await loaded() + photos.failListing() + + await expect(gallery.refresh()).resolves.toBe(false) + + expect(names(gallery)).toEqual([photoId(1)]) + expect(gallery.status.value).toBe('ready') + }) + + test('sends one request for several calls at once', async () => { + photos.seed(aPhoto(1)) + const gallery = await loaded() + photos.requests.list.mockClear() + + await Promise.all([gallery.refresh(), gallery.refresh()]) + + expect(photos.requests.list).toHaveBeenCalledTimes(1) + }) + + test('does not bring back a photo deleted while it was running', async () => { + photos.seed(aPhoto(1), aPhoto(2)) + const gallery = await loaded() + const release = photos.holdNext('list') + const refreshing = gallery.refresh() + await vi.waitFor(() => expect(photos.requests.list).toHaveBeenCalledTimes(2)) + await gallery.remove(gallery.photos.value[0]!) + + release() + await refreshing + + expect(names(gallery)).toEqual([photoId(1)]) + }) +}) + +describe('an image that does not load', () => { + async function onePhoto() { + photos.seed(aPhoto(1)) + const gallery = await loaded() + photos.requests.list.mockClear() + return gallery + } + + test('gets one new address by itself', async () => { + const gallery = await onePhoto() + + await gallery.imageFailed(photoId(1)) + + expect(photos.requests.list).toHaveBeenCalledTimes(1) + expect(gallery.isBroken(photoId(1))).toBe(false) + }) + + test('is given up after the second failure', async () => { + const gallery = await onePhoto() + await gallery.imageFailed(photoId(1)) + + await gallery.imageFailed(photoId(1)) + + expect(gallery.isBroken(photoId(1))).toBe(true) + expect(photos.requests.list).toHaveBeenCalledTimes(1) + }) + + test('is given up at once when the address stays the same', async () => { + photos.renewUrls = false + const gallery = await onePhoto() + + await gallery.imageFailed(photoId(1)) + + expect(gallery.isBroken(photoId(1))).toBe(true) + }) + + test('is given up when no new address can be fetched', async () => { + const gallery = await onePhoto() + photos.failListing() + + await gallery.imageFailed(photoId(1)) + + expect(gallery.isBroken(photoId(1))).toBe(true) + }) + + // Five minutes later the new address expires as well. + test('may get a new address again after it has loaded once', async () => { + const gallery = await onePhoto() + await gallery.imageFailed(photoId(1)) + gallery.imageLoaded(photoId(1)) + + await gallery.imageFailed(photoId(1)) + + expect(photos.requests.list).toHaveBeenCalledTimes(2) + expect(gallery.isBroken(photoId(1))).toBe(false) + }) + + test('can be loaded again by hand', async () => { + const gallery = await onePhoto() + await gallery.imageFailed(photoId(1)) + await gallery.imageFailed(photoId(1)) + + await gallery.reload(photoId(1)) + + expect(gallery.isBroken(photoId(1))).toBe(false) + expect(photos.requests.list).toHaveBeenCalledTimes(2) + }) +}) + +describe('deleting', () => { + test('removes the photo', async () => { + photos.seed(aPhoto(1), aPhoto(2)) + const gallery = await loaded() + + await expect(gallery.remove(gallery.photos.value[0]!)).resolves.toEqual({ ok: true }) + + expect(photos.requests.delete).toHaveBeenCalledWith(photoId(2)) + expect(names(gallery)).toEqual([photoId(1)]) + }) + + test('keeps it and reports a failure', async () => { + photos.seed(aPhoto(1)) + const gallery = await loaded() + photos.failOnce('delete', 500, 'internal') + + await expect(gallery.remove(gallery.photos.value[0]!)) + .resolves.toEqual({ ok: false, messageKey: 'errors.api.internal' }) + + expect(names(gallery)).toEqual([photoId(1)]) + }) + + test('counts as done if the partner was faster', async () => { + photos.seed(aPhoto(1)) + const gallery = await loaded() + const photo = gallery.photos.value[0]! + photos.drop(photo.name) + + await expect(gallery.remove(photo)).resolves.toEqual({ ok: true }) + + expect(names(gallery)).toEqual([]) + expect(gallery.notice.value).toBe('photos.alreadyDeleted') + }) + + test('sends one request per photo at a time', async () => { + photos.seed(aPhoto(1)) + const gallery = await loaded() + const photo = gallery.photos.value[0]! + + await Promise.all([gallery.remove(photo), gallery.remove(photo)]) + + expect(photos.requests.delete).toHaveBeenCalledTimes(1) + }) +}) From fb0fbdf2a8a4a96ec713b239812356e88f2bafbb Mon Sep 17 00:00:00 2001 From: Filionus Date: Mon, 30 Nov 2026 10:41:57 +0100 Subject: [PATCH 03/11] Correct the test for the upload steps It finished the simulated decoding before the decoding had started. Co-Authored-By: Claude Sonnet 5.5 --- composables/__tests__/usePhotoUpload.nuxt.spec.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/composables/__tests__/usePhotoUpload.nuxt.spec.ts b/composables/__tests__/usePhotoUpload.nuxt.spec.ts index 3bbd6d3..4f0b823 100644 --- a/composables/__tests__/usePhotoUpload.nuxt.spec.ts +++ b/composables/__tests__/usePhotoUpload.nuxt.spec.ts @@ -84,6 +84,7 @@ describe('adding a photo', () => { const done = upload.select(aFile()) expect(upload.step.value).toBe('preparing') + await vi.waitFor(() => expect(decoder.decode).toHaveBeenCalled()) finishDecoding() await vi.waitFor(() => expect(upload.step.value).toBe('reserving')) releaseReserve() From 6e98d16c72ce9ca729f13b2f23eb27f0cfab9514 Mon Sep 17 00:00:00 2001 From: Filionus Date: Mon, 30 Nov 2026 10:42:54 +0100 Subject: [PATCH 04/11] Add preparing, uploading and listing of photos Co-Authored-By: Claude Sonnet 5.5 --- composables/browserImage.ts | 39 +++++ composables/galleryUpload.ts | 33 ++++ composables/photoRules.ts | 34 ++++ composables/preparePhoto.ts | 75 +++++++++ composables/useGalleryStorage.ts | 11 ++ composables/usePhotoUpload.ts | 193 ++++++++++++++++++++++ composables/usePhotos.ts | 274 +++++++++++++++++++++++++++++++ stores/photoUpload.ts | 61 +++++++ 8 files changed, 720 insertions(+) create mode 100644 composables/browserImage.ts create mode 100644 composables/galleryUpload.ts create mode 100644 composables/photoRules.ts create mode 100644 composables/preparePhoto.ts create mode 100644 composables/useGalleryStorage.ts create mode 100644 composables/usePhotoUpload.ts create mode 100644 composables/usePhotos.ts create mode 100644 stores/photoUpload.ts diff --git a/composables/browserImage.ts b/composables/browserImage.ts new file mode 100644 index 0000000..8b950ab --- /dev/null +++ b/composables/browserImage.ts @@ -0,0 +1,39 @@ +import type { DecodedImage } from './preparePhoto' + +// Opens an image with the browser and draws it on a canvas. Unit tests replace this, +// because their simulated browser cannot draw; it is checked in a real browser. +export async function decodeInBrowser(file: Blob): Promise { + const address = URL.createObjectURL(file) + const image = new Image() + image.src = address + try { + // Rejects if the browser cannot read the file. + await image.decode() + } + catch (error) { + URL.revokeObjectURL(address) + throw error + } + + return { + // Browsers already turn phone photos upright here. + width: image.naturalWidth, + height: image.naturalHeight, + toJpeg(width, height, quality) { + const canvas = document.createElement('canvas') + canvas.width = width + canvas.height = height + const drawing = canvas.getContext('2d') + if (!drawing) { + return Promise.resolve(null) + } + // JPEG has no transparency, so see-through areas become white. + drawing.fillStyle = 'white' + drawing.fillRect(0, 0, width, height) + drawing.imageSmoothingQuality = 'high' + drawing.drawImage(image, 0, 0, width, height) + return new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', quality)) + }, + release: () => URL.revokeObjectURL(address), + } +} diff --git a/composables/galleryUpload.ts b/composables/galleryUpload.ts new file mode 100644 index 0000000..805b142 --- /dev/null +++ b/composables/galleryUpload.ts @@ -0,0 +1,33 @@ +import type { SupabaseClient } from '@supabase/supabase-js' + +// A hanging upload would leave the person with no way out, so it is given up. +export const UPLOAD_GIVE_UP_MS = 120_000 + +// Sends one file to the private "gallery" bucket. The API issued the path and the +// token, which only work for this one file. +export async function uploadToGallery( + storage: SupabaseClient['storage'] | undefined, + reservation: { path: string, token: string }, + file: Blob, +) { + if (!storage) { + throw new Error('Storage is not available') + } + let timer: ReturnType | undefined + const tooLong = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error('The upload took too long')), UPLOAD_GIVE_UP_MS) + }) + try { + const { error } = await Promise.race([ + storage.from('gallery').uploadToSignedUrl(reservation.path, reservation.token, file, { contentType: file.type }), + tooLong, + ]) + // The storage client reports most failures this way instead of throwing. + if (error) { + throw error + } + } + finally { + clearTimeout(timer) + } +} diff --git a/composables/photoRules.ts b/composables/photoRules.ts new file mode 100644 index 0000000..20a4250 --- /dev/null +++ b/composables/photoRules.ts @@ -0,0 +1,34 @@ +// Limits and calculations for photos (F3). The API and the storage bucket check again. +// A test compares types and upload limit with shared/api-contract.ts. + +export const PHOTO_TYPES = ['image/jpeg', 'image/png', 'image/webp'] as const +// The largest file that may be uploaded. +export const PHOTO_MAX_BYTES = 5 * 1024 * 1024 +// The largest file that may be chosen. It is made smaller before the upload. +export const PHOTO_INPUT_MAX_BYTES = 25 * 1024 * 1024 + +// Checks a chosen file by what the browser says about it, before opening it. +export function photoFileError(file: File) { + if (!(PHOTO_TYPES as readonly string[]).includes(file.type)) { + return 'errors.photo.type' + } + if (file.size === 0) { + return 'errors.photo.unreadable' + } + return file.size > PHOTO_INPUT_MAX_BYTES ? 'errors.photo.tooLarge' : undefined +} + +// The size of an image whose longer side is at most "edge" pixels. Never enlarges. +export function fitWithin(width: number, height: number, edge: number) { + const scale = Math.min(1, edge / Math.max(width, height)) + return { + width: Math.max(1, Math.round(width * scale)), + height: Math.max(1, Math.round(height * scale)), + } +} + +// When a photo was added, in the time zone of the viewer. Tests pass a fixed zone. +export function formatUploadTime(moment: string, locale: string, timeZone?: string) { + const format = new Intl.DateTimeFormat(locale, { dateStyle: 'long', timeStyle: 'short', timeZone }) + return format.format(new Date(moment)) +} diff --git a/composables/preparePhoto.ts b/composables/preparePhoto.ts new file mode 100644 index 0000000..00848df --- /dev/null +++ b/composables/preparePhoto.ts @@ -0,0 +1,75 @@ +// Turns a chosen file into the JPEG that gets uploaded. +// +// Every photo is drawn anew, also a small one. The new file contains the picture only, +// so metadata such as the place where a phone photo was taken is not shared. +import { PHOTO_MAX_BYTES, fitWithin, photoFileError } from './photoRules' + +// An opened image. decodeInBrowser (browserImage.ts) provides it in the app. +export interface DecodedImage { + width: number + height: number + // Draws the image in the given size and returns it as a JPEG. + toJpeg: (width: number, height: number, quality: number) => Promise + // Frees the memory of the image. + release: () => void +} + +export type ImageDecoder = (file: Blob) => Promise + +// Show it with t(failure.messageKey). +export class PhotoFailure extends Error { + constructor(readonly messageKey: string) { + super(messageKey) + this.name = 'PhotoFailure' + } +} + +// Longer side in pixels and JPEG quality, from the best result to the smallest file. +const attempts = [ + { edge: 2048, quality: 0.85 }, + { edge: 2048, quality: 0.7 }, + { edge: 1600, quality: 0.7 }, + { edge: 1200, quality: 0.6 }, +] + +const unreadable = () => new PhotoFailure('errors.photo.unreadable') + +export async function preparePhoto(file: File, decode: ImageDecoder) { + const fileError = photoFileError(file) + if (fileError) { + throw new PhotoFailure(fileError) + } + + // The type only says what the file claims to be. Opening it shows what it is. + let image: DecodedImage + try { + image = await decode(file) + } + catch { + throw unreadable() + } + + try { + if (!image.width || !image.height) { + throw unreadable() + } + for (const { edge, quality } of attempts) { + const { width, height } = fitWithin(image.width, image.height, edge) + const jpeg = await image.toJpeg(width, height, quality) + // Never upload an empty or unexpected result. + if (!jpeg?.size || jpeg.type !== 'image/jpeg') { + throw unreadable() + } + if (jpeg.size <= PHOTO_MAX_BYTES) { + return jpeg + } + } + throw new PhotoFailure('errors.photo.stillTooLarge') + } + catch (error) { + throw error instanceof PhotoFailure ? error : unreadable() + } + finally { + image.release() + } +} diff --git a/composables/useGalleryStorage.ts b/composables/useGalleryStorage.ts new file mode 100644 index 0000000..6d6ebdb --- /dev/null +++ b/composables/useGalleryStorage.ts @@ -0,0 +1,11 @@ +import type { SupabaseClient } from '@supabase/supabase-js' + +// The one place that reaches Supabase Storage, and only for uploads with a token +// from the API. Everything else about photos goes through /api/photos. +export function useGalleryStorage() { + const supabase = useNuxtApp().$supabase as SupabaseClient | undefined + + return function upload(reservation: { path: string, token: string }, file: Blob) { + return uploadToGallery(supabase?.storage, reservation, file) + } +} diff --git a/composables/usePhotoUpload.ts b/composables/usePhotoUpload.ts new file mode 100644 index 0000000..c6d568b --- /dev/null +++ b/composables/usePhotoUpload.ts @@ -0,0 +1,193 @@ +import type { PhotoUploadUrlResponse } from '../shared/api-contract' +import type { UploadJob } from '../stores/photoUpload' + +// The signed upload address works for two hours. +const TOKEN_LIFETIME_MS = 2 * 60 * 60 * 1000 + +// What an unfinished upload leaves behind if it is thrown away: +// nothing no place was reserved +// reservation a place stays blocked for about two hours +// file the file may be stored, and would then count for good +export type UploadLeftover = 'nothing' | 'reservation' | 'file' + +// Adds a photo: prepare, reserve a place, upload to storage, confirm. +// +// Every reservation blocks 5 MiB of the couple's storage for two hours. So another +// attempt keeps using the same one and only asks for a new one if the old is useless. +// const { step, failure, select, retry } = usePhotoUpload() +export function usePhotoUpload() { + const api = useApi() + const session = useSessionStore() + const space = useSpace() + const send = useGalleryStorage() + const store = usePhotoUploadStore() + + const step = computed(() => store.step) + const pending = computed(() => Boolean(store.job)) + const failure = computed(() => store.failure) + const selectionError = computed(() => store.selectionError) + const completed = computed(() => store.completed) + const leftover = computed(() => { + if (!store.job?.reservation) { + return 'nothing' + } + return store.job.sent ? 'file' : 'reservation' + }) + + // False if the upload was thrown away, or somebody else has signed in meanwhile. + function wanted(job: UploadJob) { + return store.job === job && session.user?.id === job.owner + } + + function codeOf(error: unknown) { + return error instanceof ApiError ? error.code : undefined + } + + function confirm(job: UploadJob) { + return api('/api/photos/confirm', { method: 'POST', body: { uploadId: job.reservation!.uploadId } }) + } + + // Before sending again: perhaps the file has arrived and only the answer got lost. + async function arrived(job: UploadJob) { + try { + await confirm(job) + return true + } + catch (error) { + if (codeOf(error) === 'not_found') { + return false + } + throw error + } + } + + function startOver(job: UploadJob) { + job.reservation = undefined + job.sent = false + } + + function finish(job: UploadJob) { + if (wanted(job)) { + store.job = undefined + store.completed += 1 + } + } + + function fail(job: UploadJob, error: unknown) { + if (!wanted(job)) { + return + } + const failedStep = store.step! + const code = codeOf(error) + if (code === 'no_space') { + store.job = undefined + store.selectionError = 'errors.api.noSpace' + space.refresh() + return + } + + let messageKey = failedStep === 'uploading' ? 'errors.photo.upload' : 'errors.unexpected' + if (error instanceof ApiError) { + messageKey = error.messageKey + } + // The API cannot complete this reservation, so the next attempt needs a new one. + if (failedStep === 'confirming' && (code === 'validation_failed' || code === 'not_found')) { + messageKey = code === 'validation_failed' ? 'errors.photo.mismatch' : 'errors.photo.lost' + startOver(job) + } + store.failure = { step: failedStep, messageKey } + } + + // Runs the steps that are still open. Also used for another attempt. + async function run() { + const job = store.job! + store.failure = undefined + try { + if (job.reservation && job.sent) { + store.step = 'confirming' + if (await arrived(job)) { + finish(job) + return + } + if (Date.now() - job.reservation.reservedAt > TOKEN_LIFETIME_MS) { + startOver(job) + } + } + if (!wanted(job)) { + return + } + if (!job.reservation) { + store.step = 'reserving' + const place = await api('/api/photos/upload-url', { + method: 'POST', + body: { mime: job.file.type, size: job.file.size }, + }) + if (!wanted(job)) { + return + } + job.reservation = { uploadId: place.uploadId, path: place.path, token: place.token, reservedAt: Date.now() } + } + store.step = 'uploading' + job.sent = true + await send(job.reservation, job.file) + if (!wanted(job)) { + return + } + store.step = 'confirming' + await confirm(job) + finish(job) + } + catch (error) { + fail(job, error) + } + finally { + // Not if another upload has started meanwhile. + if (!store.job || store.job === job) { + store.step = undefined + } + } + } + + // A newly chosen file. Ignored while another upload is unfinished. + async function select(file: File) { + if (store.step || store.job) { + return + } + store.selectionError = undefined + store.step = 'preparing' + await session.init() + const owner = session.user?.id + + // Everything that can be wrong with the file shows here, before any request. + let prepared: Blob + try { + prepared = await preparePhoto(file, decodeInBrowser) + } + catch (error) { + store.step = undefined + store.selectionError = error instanceof PhotoFailure ? error.messageKey : 'errors.photo.unreadable' + return + } + if (!owner || session.user?.id !== owner) { + store.step = undefined + return + } + store.job = { owner, file: prepared, sent: false } + await run() + } + + async function retry() { + if (!store.step && store.job) { + await run() + } + } + + function discard() { + if (!store.step) { + store.job = undefined + store.failure = undefined + } + } + + return { step, pending, failure, selectionError, completed, leftover, select, retry, discard } +} diff --git a/composables/usePhotos.ts b/composables/usePhotos.ts new file mode 100644 index 0000000..128e9b3 --- /dev/null +++ b/composables/usePhotos.ts @@ -0,0 +1,274 @@ +import type { PhotosResponse } from '../shared/api-contract' + +// How many photos the API returns at most in one answer. +export const PHOTOS_PAGE_SIZE = 30 + +export type Photo = PhotosResponse[number] +export type GalleryStatus = 'loading' | 'failed' | 'noSpace' | 'ready' + +// The result of deleting a photo. +export interface PhotoOutcome { + ok: boolean + messageKey?: string +} + +// The shared photos (F3). Their addresses expire after five minutes. +// const { status, photos, load, remove } = usePhotos() +export function usePhotos() { + const api = useApi() + const space = useSpace() + + const status = ref('loading') + const photos = ref([]) + const hasMore = ref(false) + const loadingMore = ref(false) + // Message keys. + const loadError = ref() + const moreError = ref() + // About a photo that has disappeared from the gallery. + const notice = ref() + + // Names of images that are given up until somebody asks again. + const broken = ref(new Set()) + // Names that already got a new address because they did not load. + const retried = new Set() + // Names of photos being deleted. + const deleting = ref(new Set()) + // Deleted names. An answer that was already on the way must not bring them back. + const removed = new Set() + // Only the answer to the newest load counts. + let newest = 0 + // Counts changes to the list. A refresh that started before a change is outdated. + let changes = 0 + let refreshing: Promise | undefined + + function fetchPage(offset: number) { + return api('/api/photos', { query: { offset } }) + } + + // The first pages, as many as asked for. The last short page ends the list. + async function fetchPages(count: number) { + const found = new Map() + let hasNext = true + for (let page = 0; page < count && hasNext; page += 1) { + const rows = await fetchPage(page * PHOTOS_PAGE_SIZE) + rows.forEach(photo => found.set(photo.name, photo)) + hasNext = rows.length === PHOTOS_PAGE_SIZE + } + return { rows: [...found.values()], hasNext } + } + + function codeOf(error: unknown) { + return error instanceof ApiError ? error.code : undefined + } + + function showNoSpace() { + status.value = 'noSpace' + photos.value = [] + hasMore.value = false + } + + // Turns a failed request into a message key. "no_space" changes the whole page instead. + function messageFor(error: unknown) { + if (codeOf(error) === 'no_space') { + showNoSpace() + return undefined + } + return error instanceof ApiError ? error.messageKey : 'errors.unexpected' + } + + function show(rows: Photo[], hasNext: boolean) { + photos.value = rows + hasMore.value = hasNext + broken.value.clear() + loadError.value = undefined + moreError.value = undefined + status.value = 'ready' + } + + // Loads the first page. + async function load() { + newest += 1 + const mine = newest + status.value = 'loading' + loadError.value = undefined + + // The space is asked as well, for the hint to somebody without one. + const [, answer] = await Promise.all([ + space.refresh(), + fetchPage(0).then( + rows => ({ rows, error: undefined }), + (error: unknown) => ({ rows: undefined, error }), + ), + ]) + if (mine !== newest) { + return + } + if (space.state.value.status === 'none') { + showNoSpace() + return + } + if (!answer.rows) { + const messageKey = messageFor(answer.error) + if (messageKey) { + loadError.value = messageKey + status.value = 'failed' + } + return + } + removed.clear() + show(answer.rows, answer.rows.length === PHOTOS_PAGE_SIZE) + } + + async function loadMore() { + if (loadingMore.value) { + return + } + loadingMore.value = true + moreError.value = undefined + const mine = newest + try { + const rows = await fetchPage(photos.value.length) + if (mine !== newest) { + return + } + // Somebody may have added photos meanwhile, which shifts the pages. + const known = new Set(photos.value.map(photo => photo.name)) + const fresh = rows.filter(photo => !known.has(photo.name) && !removed.has(photo.name)) + changes += 1 + photos.value = [...photos.value, ...fresh] + hasMore.value = rows.length === PHOTOS_PAGE_SIZE + } + catch (error) { + moreError.value = messageFor(error) + } + finally { + loadingMore.value = false + } + } + + async function readAgain() { + const mine = newest + const before = changes + const pageCount = Math.max(1, Math.ceil(photos.value.length / PHOTOS_PAGE_SIZE)) + const [, answer] = await Promise.all([ + space.refresh(), + fetchPages(pageCount).then( + pages => ({ pages, error: undefined }), + (error: unknown) => ({ pages: undefined, error }), + ), + ]) + if (mine !== newest || before !== changes) { + return false + } + if (space.state.value.status === 'none' || codeOf(answer.error) === 'no_space') { + showNoSpace() + return false + } + if (!answer.pages) { + return false + } + show(answer.pages.rows, answer.pages.hasNext) + return true + } + + // Reads the list again, with new addresses, without leaving the screen. Returns true + // if the new list is shown. Calls that arrive while one is running share it. + function refresh() { + if (status.value === 'loading') { + return Promise.resolve(false) + } + refreshing ??= readAgain().finally(() => { + refreshing = undefined + }) + return refreshing + } + + const urlOf = (name: string) => photos.value.find(photo => photo.name === name)?.url + + // The address has probably expired. One new one is fetched; if that does not help + // either, the image is given up. + async function imageFailed(name: string) { + if (retried.has(name)) { + broken.value.add(name) + return + } + retried.add(name) + const before = urlOf(name) + const renewed = await refresh() + if (!renewed || urlOf(name) === before) { + broken.value.add(name) + } + } + + // It worked, so the next expiry may be answered with a new address again. + function imageLoaded(name: string) { + retried.delete(name) + } + + function isBroken(name: string) { + return broken.value.has(name) + } + + // "Load again", pressed by a person. + async function reload(name: string) { + broken.value.delete(name) + retried.delete(name) + await refresh() + } + + function forget(name: string) { + changes += 1 + removed.add(name) + photos.value = photos.value.filter(photo => photo.name !== name) + } + + function isDeleting(name: string) { + return deleting.value.has(name) + } + + async function remove(photo: Photo): Promise { + if (isDeleting(photo.name)) { + return { ok: false } + } + deleting.value.add(photo.name) + notice.value = undefined + try { + await api(`/api/photos/${photo.name}`, { method: 'DELETE' }) + forget(photo.name) + return { ok: true } + } + catch (error) { + // Gone is gone: this is what the person wanted. + if (codeOf(error) === 'not_found') { + forget(photo.name) + notice.value = 'photos.alreadyDeleted' + return { ok: true } + } + const messageKey = messageFor(error) + return messageKey ? { ok: false, messageKey } : { ok: false } + } + finally { + deleting.value.delete(photo.name) + } + } + + return { + status, + photos, + hasMore, + loadingMore, + loadError, + moreError, + notice, + load, + loadMore, + refresh, + imageFailed, + imageLoaded, + isBroken, + reload, + remove, + isDeleting, + } +} diff --git a/stores/photoUpload.ts b/stores/photoUpload.ts new file mode 100644 index 0000000..3834ff4 --- /dev/null +++ b/stores/photoUpload.ts @@ -0,0 +1,61 @@ +export type UploadStep = 'preparing' | 'reserving' | 'uploading' | 'confirming' + +export interface UploadJob { + // The person who chose the photo. + owner: string + // The prepared JPEG. + file: Blob + // The place reserved in storage, once there is one. + reservation?: { uploadId: string, path: string, token: string, reservedAt: number } + // True once the file was sent: it may be in storage. + sent: boolean +} + +// The upload in progress. It lives here, so that leaving the page neither stops it nor +// loses the chance to try again. The steps are in composables/usePhotoUpload.ts. +export const usePhotoUploadStore = defineStore('photoUpload', () => { + const session = useSessionStore() + + const job = ref() + // Set while a step is running. + const step = ref() + // The step that failed, with a message key. + const failure = ref<{ step: UploadStep, messageKey: string }>() + // Why a chosen file was not accepted. + const selectionError = ref() + // Counts finished uploads, so that the gallery can load again. + const completed = ref(0) + + function clear() { + job.value = undefined + step.value = undefined + failure.value = undefined + selectionError.value = undefined + } + + // The next person on this device must never continue somebody else's upload. + watch(() => session.user?.id, (_id, previous) => { + // Nothing to forget when the session is read for the first time. + if (previous !== undefined) { + clear() + } + }, { flush: 'sync' }) + + // Closing or reloading the tab would lose an unfinished upload, so the browser asks first. + function askBeforeClosing(event: BeforeUnloadEvent) { + event.preventDefault() + } + + watch(() => Boolean(step.value || job.value), (unfinished) => { + if (unfinished) { + window.addEventListener('beforeunload', askBeforeClosing) + } + else { + window.removeEventListener('beforeunload', askBeforeClosing) + } + }, { flush: 'sync' }) + + onScopeDispose(() => window.removeEventListener('beforeunload', askBeforeClosing)) + + return { job, step, failure, selectionError, completed, clear } +}) From 14662c5184a94bb3cf3459f9748bcd08beda709a Mon Sep 17 00:00:00 2001 From: Filionus Date: Mon, 30 Nov 2026 10:43:05 +0100 Subject: [PATCH 05/11] Add tests for the photos page Co-Authored-By: Claude Sonnet 5.5 --- pages/__tests__/photos.nuxt.spec.ts | 456 ++++++++++++++++++++++++++++ 1 file changed, 456 insertions(+) create mode 100644 pages/__tests__/photos.nuxt.spec.ts diff --git a/pages/__tests__/photos.nuxt.spec.ts b/pages/__tests__/photos.nuxt.spec.ts new file mode 100644 index 0000000..abf610b --- /dev/null +++ b/pages/__tests__/photos.nuxt.spec.ts @@ -0,0 +1,456 @@ +import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime' +import { enableAutoUnmount, flushPromises, type DOMWrapper } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { RouterLink } from 'vue-router' +import { formatUploadTime } from '../../composables/photoRules' +import { createFakeAuth } from '../../composables/__tests__/fake-auth' +import { aFile, fakeDecoder } from '../../composables/__tests__/fake-image' +import { aPhoto, fakePhotosApi, photoId } from '../../composables/__tests__/fake-photos-api' +import { ANN, BEN, CODE, fakeSpaceApi, member, spaceOf } from '../../composables/__tests__/fake-space-api' +import { button } from '../../composables/__tests__/form-helpers' +import { resetUpload } from '../../composables/__tests__/reset-upload' +import PhotosPage from '../photos.vue' + +const fakes = vi.hoisted(() => ({ + auth: undefined as unknown, + send: undefined as unknown as (reservation: { path: string }, file: Blob) => Promise, + decode: undefined as unknown as (file: Blob) => Promise, +})) +mockNuxtImport('useSupabaseAuth', () => () => fakes.auth) +mockNuxtImport('useGalleryStorage', () => () => (reservation: { path: string }, file: Blob) => fakes.send(reservation, file)) +mockNuxtImport('decodeInBrowser', () => (file: Blob) => fakes.decode(file)) + +// The pages are attached to the document so that focus works. +enableAutoUnmount(afterEach) + +let space: ReturnType +let photos: ReturnType +let send: ReturnType Promise>> +let decoder: ReturnType + +beforeEach(async () => { + fakes.auth = createFakeAuth({ signedInAs: 'ann@example.org' }).auth + resetUpload() + space = fakeSpaceApi() + space.space = spaceOf([member(ANN, 'Ann'), member(BEN, 'Ben', 2)]) + photos = fakePhotosApi() + send = vi.fn(async (reservation, file) => photos.receive(reservation.path, file)) + fakes.send = send + decoder = fakeDecoder() + fakes.decode = decoder.decode + await useNuxtApp().$i18n.setLocale('de') + await useRouter().push('/') +}) + +afterEach(() => { + resetUpload() + photos.remove() + space.remove() + vi.restoreAllMocks() +}) + +type Page = Awaited> + +async function open() { + const page = await mountSuspended(PhotosPage, { + route: '/photos', + attachTo: document.body, + // The real link component builds the address. + global: { stubs: { RouterLink } }, + }) + await vi.waitFor(() => expect(page.text()).not.toContain('Eure Fotos werden geladen')) + await flushPromises() + return page +} + +function shows(page: Page, text: string) { + return vi.waitFor(() => expect(page.text()).toContain(text)) +} + +const EMPTY = 'Noch keine Fotos.' +const CHOOSE = 'Foto auswählen' + +const alerts = (page: Page) => page.findAll('[role="alert"]').map(alert => alert.text()) +const images = (page: Page) => page.findAll('img') +const hasButton = (page: Page, text: string) => page.findAll('button').some(candidate => candidate.text() === text) +const tiles = (page: Page) => page.findAll('li') +const galleryHeading = (page: Page) => page.findAll('h2').find(heading => heading.text() === 'Eure Fotos')! +const uploadTime = (number: number) => formatUploadTime(aPhoto(number).createdAt, 'de-DE') + +const inputs = (page: Page) => page.findAll('input[type="file"]') + +// What happens when somebody picks a file in the dialog of the browser. +async function choose(page: Page, file = aFile(), input = 0) { + const element = inputs(page)[input]! + Object.defineProperty(element.element, 'files', { configurable: true, value: [file] }) + await element.trigger('change') +} + +describe('loading', () => { + test('says that it is loading', async () => { + const release = photos.holdNext('list') + const page = await mountSuspended(PhotosPage, { route: '/photos', attachTo: document.body }) + + expect(page.get('h1').text()).toBe('Fotos') + expect(page.get('[role="status"]').text()).toBe('Eure Fotos werden geladen …') + release() + await shows(page, EMPTY) + }) + + test('shows the failure and offers to try again', async () => { + photos.failListing() + const page = await open() + + expect(alerts(page)).toEqual(['Der Server hat gerade ein Problem. Bitte versuche es später erneut.']) + expect(page.text()).not.toContain(EMPTY) + const retry = button(page, 'Erneut versuchen') + ;(retry.element as HTMLElement).focus() + await retry.trigger('click') + + await shows(page, EMPTY) + await vi.waitFor(() => expect(document.activeElement).toBe(page.get('h1').element)) + }) + + test('points somebody without a space to the space page and offers nothing else', async () => { + space.space = null + photos.failListing(403, 'no_space') + const page = await open() + + await shows(page, 'Erstelle einen gemeinsamen Bereich') + expect(page.findAll('a').map(link => link.attributes('href'))).toEqual(['/space']) + expect(inputs(page)).toEqual([]) + expect(alerts(page)).toEqual([]) + }) + + test('lets somebody add photos while waiting for the partner', async () => { + space.space = spaceOf([member(ANN, 'Ann')], CODE) + const page = await open() + + await shows(page, 'wartet noch auf die zweite Person') + expect(hasButton(page, CHOOSE)).toBe(true) + }) +}) + +describe('the gallery', () => { + test('says that there is nothing yet', async () => { + const page = await open() + + expect(page.text()).toContain(EMPTY) + expect(images(page)).toEqual([]) + expect(hasButton(page, 'Mehr laden')).toBe(false) + }) + + test('shows the photos newest first, described by their upload time', async () => { + photos.seed(aPhoto(1), aPhoto(2)) + photos.renewUrls = false + const page = await open() + + expect(images(page).map(image => image.attributes())).toMatchObject([ + { src: aPhoto(2).url, alt: `Foto, hochgeladen am ${uploadTime(2)}`, loading: 'lazy' }, + { src: aPhoto(1).url, alt: `Foto, hochgeladen am ${uploadTime(1)}`, loading: 'lazy' }, + ]) + expect(page.text()).not.toContain(EMPTY) + }) + + test('names the photo in each delete button', async () => { + photos.seed(aPhoto(1)) + const page = await open() + + const remove = button(page, 'Löschen') + + // The visible word comes first, so that voice control finds the button. + expect(remove.attributes('aria-label')).toBe(`Löschen: Foto vom ${uploadTime(1)}`) + }) + + test('follows the chosen language', async () => { + photos.seed(aPhoto(1)) + const page = await open() + + await useNuxtApp().$i18n.setLocale('en') + await flushPromises() + + expect(page.get('h1').text()).toBe('Photos') + expect(images(page)[0]!.attributes('alt')) + .toBe(`Photo uploaded on ${formatUploadTime(aPhoto(1).createdAt, 'en-GB')}`) + }) + + test('loads more', async () => { + photos.seedMany(31) + const page = await open() + expect(images(page)).toHaveLength(30) + + await button(page, 'Mehr laden').trigger('click') + + await vi.waitFor(() => expect(images(page)).toHaveLength(31)) + expect(hasButton(page, 'Mehr laden')).toBe(false) + }) + + test('says so when loading more fails', async () => { + photos.seedMany(31) + const page = await open() + photos.failListing() + + await button(page, 'Mehr laden').trigger('click') + + await shows(page, 'Der Server hat gerade ein Problem') + expect(images(page)).toHaveLength(30) + }) + + test('fetches new addresses when somebody comes back', async () => { + photos.seed(aPhoto(1)) + const page = await open() + const before = images(page)[0]!.attributes('src') + + window.dispatchEvent(new Event('focus')) + + await vi.waitFor(() => expect(images(page)[0]!.attributes('src')).not.toBe(before)) + }) +}) + +describe('an image that cannot be shown', () => { + const PLACEHOLDER = 'Das Bild lässt sich gerade nicht laden.' + + test('gets a new address by itself first', async () => { + photos.seed(aPhoto(1)) + const page = await open() + const before = images(page)[0]!.attributes('src') + + await images(page)[0]!.trigger('error') + + await vi.waitFor(() => expect(images(page)[0]!.attributes('src')).not.toBe(before)) + expect(page.text()).not.toContain(PLACEHOLDER) + }) + + test('is replaced by a message when that does not help, and can be loaded again', async () => { + photos.seed(aPhoto(1)) + const page = await open() + const before = images(page)[0]!.attributes('src') + await images(page)[0]!.trigger('error') + await vi.waitFor(() => expect(images(page)[0]!.attributes('src')).not.toBe(before)) + + await images(page)[0]!.trigger('error') + + await shows(page, PLACEHOLDER) + expect(images(page)).toEqual([]) + // It can still be deleted. + expect(hasButton(page, 'Löschen')).toBe(true) + await button(page, 'Erneut laden').trigger('click') + await vi.waitFor(() => expect(images(page)).toHaveLength(1)) + }) + + test('shows the message when the API has no address for it', async () => { + photos.seed(aPhoto(1, { url: null })) + + const page = await open() + + expect(page.text()).toContain(PLACEHOLDER) + expect(images(page)).toEqual([]) + }) +}) + +describe('adding a photo', () => { + test('accepts only the supported formats and offers the camera separately', async () => { + const page = await open() + + expect(inputs(page).map(input => input.attributes('accept'))) + .toEqual(['image/jpeg,image/png,image/webp', 'image/jpeg,image/png,image/webp']) + expect(inputs(page)[0]!.attributes('capture')).toBeUndefined() + expect(inputs(page)[1]!.attributes('capture')).toBe('environment') + expect(hasButton(page, CHOOSE)).toBe(true) + expect(hasButton(page, 'Foto aufnehmen')).toBe(true) + expect(page.text()).toContain('bis 25 MB') + }) + + test.each([ + [CHOOSE, 0], + ['Foto aufnehmen', 1], + ])('"%s" opens its file dialog', async (label, index) => { + const page = await open() + const click = vi.spyOn(inputs(page)[index]!.element as HTMLInputElement, 'click') + + await button(page, label).trigger('click') + + expect(click).toHaveBeenCalled() + }) + + test.each([0, 1])('uploads the chosen file and shows it (input %i)', async (input) => { + const page = await open() + + await choose(page, aFile(), input) + + await shows(page, 'Foto hinzugefügt.') + expect(send).toHaveBeenCalledTimes(1) + await vi.waitFor(() => expect(images(page)).toHaveLength(1)) + expect(page.text()).not.toContain(EMPTY) + }) + + test('shows which step it is on and takes no second photo', async () => { + const page = await open() + const release = photos.holdNext('reserve') + + await choose(page) + + await shows(page, 'Schritt 2 von 4: Platz wird reserviert …') + expect(page.text()).toContain('Bitte lass diesen Tab offen.') + expect(page.find('progress').exists()).toBe(true) + expect(button(page, CHOOSE).attributes('aria-disabled')).toBe('true') + release() + await shows(page, 'Foto hinzugefügt.') + expect(page.find('progress').exists()).toBe(false) + }) + + test.each([ + ['the wrong type', aFile('image/heic', 100, 'a.heic'), 'Dieses Format wird nicht unterstützt.'], + ['a file that is too large', aFile('image/jpeg', 25 * 1024 * 1024 + 1), 'Die Datei ist größer als 25 MB.'], + ])('rejects %s before any request', async (_name, file, message) => { + const page = await open() + + await choose(page, file) + + await vi.waitFor(() => expect(alerts(page)).toHaveLength(1)) + expect(alerts(page)[0]).toContain(message) + expect(photos.requests.reserve).not.toHaveBeenCalled() + expect(send).not.toHaveBeenCalled() + }) + + test('rejects a file that cannot be read as an image', async () => { + decoder.decode.mockRejectedValueOnce(new Error('text from the browser')) + const page = await open() + + await choose(page) + + await vi.waitFor(() => expect(alerts(page)).toHaveLength(1)) + expect(alerts(page)[0]).toContain('Diese Datei lässt sich nicht als Bild lesen.') + expect(alerts(page)[0]).not.toContain('text from the browser') + expect(photos.requests.reserve).not.toHaveBeenCalled() + }) +}) + +describe('an upload that fails', () => { + const NOT_THERE = 'Das Foto ist noch nicht in der Galerie.' + + async function failing() { + send.mockRejectedValueOnce(new Error('offline')) + const page = await open() + await choose(page) + await shows(page, NOT_THERE) + return page + } + + test('says what happened and what a discarded upload leaves behind', async () => { + const page = await failing() + + expect(alerts(page)[0]).toContain('Das Hochladen in den Speicher hat nicht geklappt.') + expect(page.text()).toContain('kann dieser Speicherplatz dauerhaft belegt bleiben') + expect(hasButton(page, 'Upload erneut versuchen')).toBe(true) + expect(hasButton(page, 'Upload verwerfen')).toBe(true) + expect(button(page, CHOOSE).attributes('aria-disabled')).toBe('true') + }) + + test('can be tried again', async () => { + const page = await failing() + + await button(page, 'Upload erneut versuchen').trigger('click') + + await shows(page, 'Foto hinzugefügt.') + expect(photos.requests.reserve).toHaveBeenCalledTimes(1) + expect(page.text()).not.toContain(NOT_THERE) + }) + + test('can be discarded', async () => { + const page = await failing() + + await button(page, 'Upload verwerfen').trigger('click') + + expect(page.text()).not.toContain(NOT_THERE) + expect(button(page, CHOOSE).attributes('aria-disabled')).toBe('false') + expect(document.activeElement).toBe(button(page, CHOOSE).element) + }) + + test('is still there after leaving the page', async () => { + const first = await failing() + first.unmount() + + const page = await open() + + expect(page.text()).toContain(NOT_THERE) + expect(hasButton(page, 'Upload erneut versuchen')).toBe(true) + }) + + test('explains a full storage without claiming that something stays blocked', async () => { + const page = await open() + photos.failOnce('reserve', 409, 'quota_exceeded') + + await choose(page) + + await shows(page, 'Der Speicher für eure gemeinsamen Fotos ist voll') + expect(page.text()).not.toContain('belegt bleiben') + expect(page.text()).not.toContain('bleibt der Platz') + }) +}) + +describe('deleting a photo', () => { + const dialog = (page: Page) => page.get('dialog') + + const pressInDialog = (page: Page, text: string) => + dialog(page).findAll('button').find(candidate => candidate.text() === text)!.trigger('click') + + async function askToDelete() { + photos.seed(aPhoto(1)) + const page = await open() + await button(page, 'Löschen').trigger('click') + await vi.waitFor(() => expect((dialog(page).element as HTMLDialogElement).open).toBe(true)) + return page + } + + test('asks first', async () => { + const page = await askToDelete() + + expect(dialog(page).text()).toContain(`Das Foto vom ${uploadTime(1)} wird für euch beide gelöscht.`) + // The harmless choice gets the focus. + expect(dialog(page).get('button').text()).toBe('Abbrechen') + expect(dialog(page).get('button').attributes('autofocus')).toBeDefined() + expect(photos.requests.delete).not.toHaveBeenCalled() + }) + + test('keeps it after "cancel" and returns the focus', async () => { + const page = await askToDelete() + + await pressInDialog(page, 'Abbrechen') + + await vi.waitFor(() => expect(page.find('dialog').exists()).toBe(false)) + expect(images(page)).toHaveLength(1) + expect(document.activeElement).toBe(button(page, 'Löschen').element) + }) + + test('removes it and moves the focus to the gallery', async () => { + const page = await askToDelete() + + await pressInDialog(page, 'Ja, löschen') + + await shows(page, EMPTY) + expect(photos.requests.delete).toHaveBeenCalledWith(photoId(1)) + expect(page.find('dialog').exists()).toBe(false) + await vi.waitFor(() => expect(document.activeElement).toBe(galleryHeading(page).element)) + }) + + test('stays open and says so when it fails', async () => { + const page = await askToDelete() + photos.failOnce('delete', 500, 'internal') + + await pressInDialog(page, 'Ja, löschen') + + await vi.waitFor(() => expect(dialog(page).find('[role="alert"]').exists()).toBe(true)) + expect(images(page)).toHaveLength(1) + }) + + test('says when the partner was faster', async () => { + const page = await askToDelete() + photos.drop(photoId(1)) + + await pressInDialog(page, 'Ja, löschen') + + await shows(page, 'Dieses Foto wurde schon gelöscht.') + expect(tiles(page)).toEqual([] as DOMWrapper[]) + }) +}) From c8a3e776a2605af030775e14bd14c9a4b8ba8e3f Mon Sep 17 00:00:00 2001 From: Filionus Date: Mon, 30 Nov 2026 10:44:14 +0100 Subject: [PATCH 06/11] Add tests for showing a freshly uploaded photo Co-Authored-By: Claude Sonnet 5.5 --- composables/__tests__/usePhotos.nuxt.spec.ts | 31 ++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/composables/__tests__/usePhotos.nuxt.spec.ts b/composables/__tests__/usePhotos.nuxt.spec.ts index a8bf413..84239e2 100644 --- a/composables/__tests__/usePhotos.nuxt.spec.ts +++ b/composables/__tests__/usePhotos.nuxt.spec.ts @@ -186,6 +186,37 @@ describe('refreshing', () => { }) }) +describe('after an upload', () => { + test('shows the new photo even if an older refresh is still running', async () => { + const gallery = await loaded() + // This answer is from before the new photo. + const release = photos.holdNext('list') + const older = gallery.refresh() + await vi.waitFor(() => expect(photos.requests.list).toHaveBeenCalledTimes(2)) + photos.seed(aPhoto(1)) + + const shown = gallery.showNewPhoto() + release() + await Promise.all([older, shown]) + + expect(names(gallery)).toEqual([photoId(1)]) + }) + + test('shows the new photo if the first load is still running', async () => { + const release = photos.holdNext('list') + const gallery = usePhotos() + const first = gallery.load() + await vi.waitFor(() => expect(photos.requests.list).toHaveBeenCalledTimes(1)) + photos.seed(aPhoto(1)) + + const shown = gallery.showNewPhoto() + release() + await Promise.all([first, shown]) + + expect(names(gallery)).toEqual([photoId(1)]) + }) +}) + describe('an image that does not load', () => { async function onePhoto() { photos.seed(aPhoto(1)) From cc64497ff6fb88e27b92c1c7ccd7da5ae0f8dd2c Mon Sep 17 00:00:00 2001 From: Filionus Date: Mon, 30 Nov 2026 10:45:23 +0100 Subject: [PATCH 07/11] Add the photo gallery page Co-Authored-By: Claude Sonnet 5.5 --- components/PhotoDeleteDialog.vue | 93 +++++++++++++++ components/PhotoTile.vue | 91 +++++++++++++++ components/PhotoUploader.vue | 168 +++++++++++++++++++++++++++ components/SpaceHint.vue | 6 +- composables/usePhotos.ts | 12 ++ i18n/locales/de.json | 50 ++++++++ i18n/locales/en.json | 50 ++++++++ i18n/locales/nl.json | 50 ++++++++ pages/photos.vue | 192 ++++++++++++++++++++++++++++++- 9 files changed, 706 insertions(+), 6 deletions(-) create mode 100644 components/PhotoDeleteDialog.vue create mode 100644 components/PhotoTile.vue create mode 100644 components/PhotoUploader.vue diff --git a/components/PhotoDeleteDialog.vue b/components/PhotoDeleteDialog.vue new file mode 100644 index 0000000..d1f7d04 --- /dev/null +++ b/components/PhotoDeleteDialog.vue @@ -0,0 +1,93 @@ + + + diff --git a/components/PhotoTile.vue b/components/PhotoTile.vue new file mode 100644 index 0000000..bc60346 --- /dev/null +++ b/components/PhotoTile.vue @@ -0,0 +1,91 @@ + + + diff --git a/components/PhotoUploader.vue b/components/PhotoUploader.vue new file mode 100644 index 0000000..86f88e4 --- /dev/null +++ b/components/PhotoUploader.vue @@ -0,0 +1,168 @@ + + + diff --git a/components/SpaceHint.vue b/components/SpaceHint.vue index c3f7ee2..9197ccb 100644 --- a/components/SpaceHint.vue +++ b/components/SpaceHint.vue @@ -1,7 +1,7 @@ From 0e57f43f72e45fd1da790b2f6ad82b7516a1f72b Mon Sep 17 00:00:00 2001 From: Filionus Date: Mon, 30 Nov 2026 10:53:21 +0100 Subject: [PATCH 08/11] Add tests for opening a photo in a new tab Co-Authored-By: Claude Sonnet 5.5 --- pages/__tests__/photos.nuxt.spec.ts | 49 +++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/pages/__tests__/photos.nuxt.spec.ts b/pages/__tests__/photos.nuxt.spec.ts index abf610b..5871a31 100644 --- a/pages/__tests__/photos.nuxt.spec.ts +++ b/pages/__tests__/photos.nuxt.spec.ts @@ -174,6 +174,55 @@ describe('the gallery', () => { .toBe(`Photo uploaded on ${formatUploadTime(aPhoto(1).createdAt, 'en-GB')}`) }) + // A real link: it works with the keyboard and can be opened like any other. + test('opens the full photo in a new tab', async () => { + photos.seed(aPhoto(1)) + photos.renewUrls = false + const page = await open() + + const link = page.get('li a') + + expect(link.attributes()).toMatchObject({ + 'href': aPhoto(1).url, + 'target': '_blank', + 'rel': 'noopener noreferrer', + 'aria-label': `Foto vom ${uploadTime(1)} in voller Größe öffnen (neuer Tab)`, + }) + expect(link.attributes('tabindex')).toBeUndefined() + expect(link.find('img').exists()).toBe(true) + }) + + test('names that link in the chosen language', async () => { + photos.seed(aPhoto(1)) + const page = await open() + + await useNuxtApp().$i18n.setLocale('en') + await flushPromises() + + expect(page.get('li a').attributes('aria-label')) + .toBe(`Open the full photo from ${formatUploadTime(aPhoto(1).createdAt, 'en-GB')} (new tab)`) + }) + + // The old address would show an error in the new tab. + test('keeps the link on the renewed address', async () => { + photos.seed(aPhoto(1)) + const page = await open() + const before = page.get('li a').attributes('href') + + window.dispatchEvent(new Event('focus')) + + await vi.waitFor(() => expect(page.get('li a').attributes('href')).not.toBe(before)) + expect(page.get('li a').attributes('href')).toBe(images(page)[0]!.attributes('src')) + }) + + test('offers no link when there is no address', async () => { + photos.seed(aPhoto(1, { url: null })) + + const page = await open() + + expect(page.find('li a').exists()).toBe(false) + }) + test('loads more', async () => { photos.seedMany(31) const page = await open() From 43f6beee47a19201c6474fc72ef08e65a10ae376 Mon Sep 17 00:00:00 2001 From: Filionus Date: Mon, 30 Nov 2026 10:54:08 +0100 Subject: [PATCH 09/11] Open the full photo in a new tab from its thumbnail Co-Authored-By: Claude Sonnet 5.5 --- components/PhotoTile.vue | 28 ++++++++++++++++++++-------- i18n/locales/de.json | 1 + i18n/locales/en.json | 1 + i18n/locales/nl.json | 1 + 4 files changed, 23 insertions(+), 8 deletions(-) diff --git a/components/PhotoTile.vue b/components/PhotoTile.vue index bc60346..c50fd9d 100644 --- a/components/PhotoTile.vue +++ b/components/PhotoTile.vue @@ -42,16 +42,28 @@ async function closeQuestion() {