feat: image variants per image

This commit is contained in:
fsylvain committed 2026-10-08 19:57:51 +02:00
1 parent f567866161
commit 951fef18ba
92 files changed
+8695 -413

No files matched your search

@@ -0,0 +1,175 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import router from '@/router'
import { useApi } from '@/composables/useApi'
import { initializeLocale, setLocale } from '@/i18n'
import { messages } from '@/i18n/messages'
import type { ActivityItem } from '@/lib/activity'
import { detailLine, sentenceText } from '@/lib/activitySentence'
import { mountActivity, rows, textOf, unmountActivity } from './activityHarness'
import { makeItem, pageOf, target } from './activityFixtures'
vi.mock('@/composables/useApi', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/composables/useApi')>()
return { ...actual, useApi: vi.fn() }
})
vi.mock('@nuxt/ui/composables', async (importOriginal) => {
const actual = await importOriginal<typeof import('@nuxt/ui/composables')>()
return { ...actual, useToast: () => ({ add: vi.fn() }) }
})
const IMAGE = target('image', '1', 'north-wall.jpg')
function variantEvent(overrides: Partial<ActivityItem>) {
return makeItem({
id: 1,
category: 'media',
target: IMAGE,
action: 'media.variant_generate_all',
...overrides,
})
}
beforeEach(() => {
localStorage.clear()
initializeLocale()
})
afterEach(async () => {
unmountActivity()
vi.mocked(useApi).mockReset()
localStorage.clear()
initializeLocale()
await router.push('/login')
})
describe('The two new sentences', () => {
it.each([
['media.variant_generate_all', 'Generated all variants of north-wall.jpg'],
['media.variant_purge_image', 'Purged the variants of north-wall.jpg'],
])('reads %s as a sentence ending with the target', (action, sentence) => {
expect(sentenceText(variantEvent({ action }))).toBe(sentence)
})
it.each([
['media.variant_generate_all', 'Failed to generate the variants of north-wall.jpg'],
['media.variant_purge_image', 'Failed to purge the variants of north-wall.jpg'],
])('reads %s failed', (action, sentence) => {
expect(sentenceText(variantEvent({ action, outcome: 'failed' }))).toBe(sentence)
})
})
describe('The detail line under the sentence', () => {
it.each([
[
'media.variant_generate_all',
{ generated: 5, failed: 0, causes: [] },
'5 variants generated',
],
[
'media.variant_generate_all',
{ generated: 1, failed: 0, causes: [] },
'1 variant generated',
],
[
'media.variant_generate_all',
{ generated: 4, failed: 1, causes: ['too_large'] },
'4 generated · 1 failed (Image too large)',
],
[
'media.variant_generate_all',
{ generated: 3, failed: 2, causes: ['too_large', 'unsupported_format'] },
'3 generated · 2 failed (Image too large, Unsupported source format)',
],
[
'media.variant_purge_image',
{ purged_files: 4, purged_bytes: 266240 },
'Removed 4 files (260 KB)',
],
[
'media.variant_purge_image',
{ purged_files: 1, purged_bytes: 18432 },
'Removed 1 file (18 KB)',
],
])('%s %j reads "%s"', (action, params, detail) => {
expect(detailLine(variantEvent({ action, params }))).toBe(detail)
})
it('has no detail line for other actions', () => {
expect(detailLine(makeItem({ id: 2, action: 'media.rename' }))).toBeNull()
})
it('shows the line in the row, under the sentence', async () => {
const events = [
variantEvent({ params: { generated: 4, failed: 1, causes: ['too_large'] } }),
makeItem({ id: 2, action: 'media.rename', category: 'media', target: IMAGE }),
]
await mountActivity({ list: () => pageOf(events) })
const [first, second] = rows()
const line = first!.querySelector<HTMLElement>('[data-testid="activity-detail-line"]')!
expect(textOf(line)).toBe('4 generated · 1 failed (Image too large)')
expect(line.className).toContain('text-xs')
expect(line.className).toContain('text-muted')
expect(second!.querySelector('[data-testid="activity-detail-line"]')).toBeNull()
})
it('shows the line in the details panel', async () => {
const events = [
variantEvent({
action: 'media.variant_purge_image',
params: { purged_files: 4, purged_bytes: 266240 },
}),
]
await mountActivity({ list: () => pageOf(events) })
rows()[0]!.click()
await flushPromises()
await vi.waitFor(() =>
expect(document.body.querySelector('[data-testid="activity-details"]')).toBeTruthy(),
)
const details = document.body.querySelector<HTMLElement>(
'[data-testid="activity-details"]',
)!
expect(textOf(details.querySelector('[data-testid="activity-detail-line"]'))).toBe(
'Removed 4 files (260 KB)',
)
})
})
describe('The French interface', () => {
it('translates the sentences and the detail lines', () => {
setLocale('fr')
expect(sentenceText(variantEvent({}))).toBe(
'A généré toutes les variantes de north-wall.jpg',
)
expect(
sentenceText(variantEvent({ action: 'media.variant_purge_image', outcome: 'failed' })),
).toBe('Échec de la purge des variantes de north-wall.jpg')
expect(
detailLine(
variantEvent({ params: { generated: 4, failed: 1, causes: ['too_large'] } }),
),
).toBe('4 générées · 1 en échec (Image trop grande)')
})
it.each([
'Generated all variants of {0}',
'Failed to generate the variants of {0}',
'Purged the variants of {0}',
'Failed to purge the variants of {0}',
'1 variant generated',
'{0} variants generated',
'{0} generated · {1} failed ({2})',
'Removed 1 file ({0})',
'Removed {0} files ({1})',
'Image too large',
'Unsupported source format',
])('has a French entry for %s', (key) => {
expect(messages).toHaveProperty([key])
expect(messages[key as keyof typeof messages]).not.toBe(key)
})
})
@@ -0,0 +1,666 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import uiPlugin from '@nuxt/ui/vue-plugin'
import router from '@/router'
import { useSessionStore } from '@/stores/session'
import type { Article } from '@/composables/useArticles'
import ArticleEditor from '@/components/ArticleEditor.vue'
import RootComponent from '@/App.vue'
import { messages } from '@/i18n/messages'
import { fixture, textOf } from './mediaTestKit'
const FIXED_NOW = '2026-09-26T11:02:00Z'
const HERO_BODY =
'<p>Intro</p><img src="/static/uploadedImages/1.jpg?v=hero" alt="A wall" data-image-id="1">'
const TWO_HERO_BODY = `${HERO_BODY}<img src="/static/uploadedImages/1.jpg?v=hero" alt="Again" data-image-id="1">`
interface Reply {
status: number
body?: unknown
}
function variant(
name: string,
width: number | null,
height: number | null,
fit: string,
format: string,
enabled = true,
) {
return {
name,
width,
height,
fit,
format,
quality: 80,
generate_on_upload: false,
enabled,
generated_files: 0,
cache_size: 0,
}
}
const CATALOG = [
variant('card', 800, null, 'inside', 'webp'),
variant('hero', 1200, 630, 'cover', 'webp'),
variant('og', 1200, 630, 'cover', 'jpeg'),
variant('print', null, 2400, 'inside', 'png', false),
variant('square', 600, 600, 'cover', 'jpeg'),
variant('thumb', 400, 300, 'cover', 'webp'),
]
function reply(status: number, body: unknown = null) {
return {
ok: status >= 200 && status < 300,
status,
headers: { get: () => null },
json: async () => body,
text: async () => '',
} as unknown as Response
}
function article(body: string): Article {
return {
id: 12,
title: 'How we price a bathroom renovation',
body,
is_online: false,
created_at: '2026-03-12T09:14:00Z',
updated_at: FIXED_NOW,
}
}
function libraryPage() {
const urls: Record<number, string> = {
1: '/static/uploadedImages/1.jpg',
2: '/static/uploadedImages/2.webp',
4: '/static/uploadedImages/4.svg',
}
const items = fixture().map((item) => ({ ...item, url: urls[item.id] ?? item.url }))
return { items, next_cursor: null, counts: { all: 12, unused: 2, duplicates: 2 } }
}
let toastAdd: ReturnType<typeof vi.fn>
vi.mock('@nuxt/ui/composables', () => ({
useOverlay: () => ({ create: vi.fn() }),
useToast: () => ({ add: toastAdd }),
}))
let currentWrapper: Awaited<ReturnType<typeof mount>> | null = null
let fetchMock: ReturnType<typeof vi.fn>
interface EditorOptions {
body?: string
role?: string
variants?: () => Reply | Promise<Reply>
}
async function mountEditor(options: EditorOptions = {}) {
setActivePinia(createPinia())
toastAdd = vi.fn()
const session = useSessionStore()
session.session = {
verified: true,
username: 'marta',
role: (options.role ?? 'owner') as never,
}
session.status = 'ready'
const variants = options.variants ?? (() => ({ status: 200, body: { items: CATALOG } }))
fetchMock = vi.fn(async (url: string) => {
if (url === '/v1/article/12?format=html') {
return reply(200, article(options.body ?? '<p>Intro</p>'))
}
if (url === '/v1/media/?limit=24') {
return reply(200, libraryPage())
}
if (url === '/v1/image-variants') {
const result = await variants()
return reply(result.status, result.body)
}
throw new Error(`Unexpected fetch call: ${url}`)
})
global.fetch = fetchMock as unknown as typeof fetch
await router.push('/article/12/edit')
const wrapper = mount(RootComponent, {
attachTo: document.body,
global: { plugins: [router, uiPlugin] },
})
currentWrapper = wrapper
await flushPromises()
await settle()
return wrapper
}
async function settle() {
await new Promise((resolve) => setTimeout(resolve, 20))
await flushPromises()
}
function variantRequests() {
return fetchMock.mock.calls.filter(([url]) => url === '/v1/image-variants')
}
function writeRequests() {
return fetchMock.mock.calls.filter(([, init]) => (init as RequestInit | undefined)?.method)
}
function findButton(text: string, root: ParentNode = document.body) {
return Array.from(root.querySelectorAll<HTMLButtonElement>('button')).find(
(button) => textOf(button) === text,
)
}
async function openPicker(wrapper: Awaited<ReturnType<typeof mount>>) {
await wrapper
.findAll('button')
.find((button) => button.text() === 'Image')
?.trigger('click')
await flushPromises()
}
function tile(filename: string) {
return Array.from(document.body.querySelectorAll<HTMLButtonElement>('[data-picker-tile]')).find(
(element) => element.getAttribute('aria-label')?.startsWith(`${filename},`),
)!
}
async function selectTile(filename: string) {
tile(filename).click()
await flushPromises()
await settle()
}
function select() {
return document.body.querySelector<HTMLElement>('[data-testid="variant-select"]')
}
function selectText() {
return textOf(select())
}
interface SelectInstance {
type: { __name?: string }
parent: SelectInstance | null
props: { options: { value: string; label: string }[]; modelValue?: string }
emit: (event: string, ...args: unknown[]) => void
}
function variantSelect() {
let instance = (select() as unknown as { __vueParentComponent: SelectInstance | null })
.__vueParentComponent
while (instance && instance.type.__name !== 'VariantSelect') {
instance = instance.parent
}
return instance!
}
function optionLabels() {
return select() ? variantSelect().props.options.map((option) => option.label) : []
}
async function chooseOption(prefix: string) {
const instance = variantSelect()
const option = instance.props.options.find((entry) => entry.label.startsWith(prefix))!
instance.emit('update:modelValue', option.value)
await flushPromises()
await settle()
}
function urlLine() {
return document.body.querySelector<HTMLElement>('[data-testid="variant-url"]')
}
function editorBody(wrapper: Awaited<ReturnType<typeof mount>>) {
return wrapper.findComponent(ArticleEditor).props('modelValue')
}
beforeEach(() => {
localStorage.clear()
})
afterEach(async () => {
currentWrapper?.unmount()
currentWrapper = null
document.body.innerHTML = ''
await router.push('/login')
})
describe('The Variant select', () => {
it('Selecting an image shows the select with Original chosen', async () => {
const wrapper = await mountEditor()
await openPicker(wrapper)
expect(variantRequests()).toHaveLength(0)
await selectTile('north-wall.jpg')
expect(variantRequests()).toHaveLength(1)
const panel = document.body.querySelector<HTMLElement>('[data-testid="picker-panel"]')!
const order = [
panel.querySelector('[class*="size-14"]'),
panel.querySelector('label'),
select(),
urlLine(),
panel.querySelector('input[placeholder^="e.g. North wall"]'),
]
expect(order.every(Boolean)).toBe(true)
order.slice(0, -1).forEach((element, index) => {
expect(
element!.compareDocumentPosition(order[index + 1]!) &
Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy()
})
expect(textOf(panel.querySelector('label'))).toBe('Variant')
expect(selectText()).toBe('Original · 4032×3024 · JPEG')
expect(textOf(urlLine())).toBe('/static/uploadedImages/1.jpg')
expect(findButton('Insert image')!.disabled).toBe(false)
})
it('The open list offers Original and the enabled variants', async () => {
const wrapper = await mountEditor()
await openPicker(wrapper)
await selectTile('north-wall.jpg')
expect(optionLabels()).toEqual([
'Original · 4032×3024 · JPEG',
'Card · 800 × auto · WebP',
'Hero · 1200×630 · WebP',
'Og · 1200×630 · JPEG',
'Square · 600×600 · JPEG',
'Thumb · 400×300 · WebP',
])
expect(optionLabels().some((label) => label.startsWith('Print'))).toBe(false)
expect(select()!.className).toContain('data-[state=open]:border-primary')
expect(select()!.className).toContain('data-[state=open]:ring-primary')
expect(variantSelect().props.modelValue).toBe('')
})
it('Choosing a variant changes the url line', async () => {
const wrapper = await mountEditor()
await openPicker(wrapper)
await selectTile('north-wall.jpg')
await chooseOption('Hero')
expect(selectText()).toBe('Hero · 1200×630 · WebP')
expect(textOf(urlLine())).toBe('/static/uploadedImages/1.jpg?v=hero')
})
it('The choice is reset when another image is selected', async () => {
const wrapper = await mountEditor()
await openPicker(wrapper)
await selectTile('north-wall.jpg')
await chooseOption('Hero')
await selectTile('kitchen-after.webp')
expect(selectText()).toBe('Original · 2400×1600 · WEBP')
expect(textOf(urlLine())).toBe('/static/uploadedImages/2.webp')
})
it('The variants list is not requested again within one opening', async () => {
const wrapper = await mountEditor()
await openPicker(wrapper)
await selectTile('north-wall.jpg')
await selectTile('kitchen-after.webp')
expect(variantRequests()).toHaveLength(1)
})
it.each([
['No variants defined', { status: 200, body: { items: [] } }],
[
'Only disabled variants count as none',
{
status: 200,
body: { items: CATALOG.map((entry) => ({ ...entry, enabled: false })) },
},
],
])('%s', async (_label, result) => {
const wrapper = await mountEditor({ variants: () => result })
await openPicker(wrapper)
await selectTile('north-wall.jpg')
expect(optionLabels()).toEqual(['Original · 4032×3024 · JPEG'])
const help = document.body.querySelector<HTMLElement>('[data-testid="variant-help"]')!
expect(help.textContent).toBe(
'No variants defined. Add one in Settings → Media → Variants.',
)
expect(help.querySelector('a')!.getAttribute('href')).toBe('/settings/media/variants')
expect(urlLine()).toBeNull()
})
it('An SVG offers only Original', async () => {
const wrapper = await mountEditor()
await openPicker(wrapper)
await selectTile('logo-renew.svg')
expect(optionLabels()).toEqual(['Original · Vector · SVG'])
expect(document.body.querySelector('[data-testid="variant-help"]')).toBeNull()
})
it.each([
['resolves with a 500 response', () => ({ status: 500 })],
['resolves with a 403 response', () => ({ status: 403 })],
['never reaches the server', () => Promise.reject(new TypeError('Failed to fetch'))],
])('The variants list fails: %s', async (_label, failure) => {
const wrapper = await mountEditor({ variants: failure as () => Reply })
await openPicker(wrapper)
await selectTile('north-wall.jpg')
expect(optionLabels()).toEqual(['Original · 4032×3024 · JPEG'])
expect(document.body.querySelector('[role="alert"]')).toBeNull()
expect(findButton('Insert image')!.disabled).toBe(false)
})
it('sends no variants request for a session that is not owner or admin', async () => {
const wrapper = await mountEditor({ role: 'user' })
await openPicker(wrapper)
await selectTile('north-wall.jpg')
expect(variantRequests()).toHaveLength(0)
expect(selectText()).toBe('Original · 4032×3024 · JPEG')
})
it('exposes the select as a listbox trigger that the keyboard can reach', async () => {
const wrapper = await mountEditor()
await openPicker(wrapper)
await selectTile('north-wall.jpg')
const trigger = select()!
expect(trigger.tagName).toBe('BUTTON')
expect(trigger.getAttribute('aria-haspopup')).toBe('listbox')
expect(trigger.getAttribute('aria-label')).toBe('Variant')
expect(trigger.getAttribute('tabindex')).not.toBe('-1')
})
})
describe('Inserting a variant', () => {
it.each([
['Original', '/static/uploadedImages/1.jpg'],
['Hero', '/static/uploadedImages/1.jpg?v=hero'],
['Thumb', '/static/uploadedImages/1.jpg?v=thumb'],
])('The inserted url carries the variant: %s', async (option, src) => {
const wrapper = await mountEditor({ body: '<p>Intro</p>' })
await openPicker(wrapper)
await selectTile('north-wall.jpg')
await chooseOption(option)
const alt = document.body.querySelector<HTMLInputElement>(
'input[placeholder^="e.g. North wall"]',
)!
alt.value = 'A wall'
alt.dispatchEvent(new Event('input', { bubbles: true }))
await flushPromises()
findButton('Insert image')!.click()
await flushPromises()
await settle()
expect(editorBody(wrapper)).toContain(`<img src="${src}" alt="A wall" data-image-id="1">`)
expect(wrapper.text()).toContain('Unsaved changes')
expect(toastAdd).toHaveBeenCalledWith(
expect.objectContaining({ title: 'Image added', icon: 'i-lucide-circle-check' }),
)
expect(document.body.querySelector('[role="dialog"]')).toBeNull()
expect(writeRequests()).toHaveLength(0)
})
it('can insert an image already in the article again with another variant', async () => {
const wrapper = await mountEditor({
body: '<p>Intro</p><img src="/static/uploadedImages/1.jpg" alt="" data-image-id="1">',
})
await openPicker(wrapper)
await selectTile('north-wall.jpg')
expect(textOf(tile('north-wall.jpg'))).toContain('In this article')
await chooseOption('Thumb')
findButton('Insert image')!.click()
await flushPromises()
await settle()
expect(editorBody(wrapper)).toContain('src="/static/uploadedImages/1.jpg?v=thumb"')
expect(editorBody(wrapper).match(/<img/g)).toHaveLength(2)
})
it('leaves the editor untouched when the dialog is cancelled after choosing a variant', async () => {
const wrapper = await mountEditor({ body: '<p>Intro</p>' })
await openPicker(wrapper)
await selectTile('north-wall.jpg')
await chooseOption('Hero')
findButton('Cancel')!.click()
await flushPromises()
expect(editorBody(wrapper)).not.toContain('<img')
expect(wrapper.text()).not.toContain('Unsaved changes')
expect(toastAdd).not.toHaveBeenCalled()
})
})
describe('A block whose variant was deleted or disabled', () => {
function block() {
return document.body.querySelector<HTMLElement>(
'[data-testid="article-editor-variant-warning"]',
)
}
function chips() {
return Array.from(
document.body.querySelectorAll<HTMLElement>('[data-testid="variant-chip"]'),
)
}
it('A deleted variant keeps the src and shows the warning', async () => {
const items = CATALOG.filter((entry) => entry.name !== 'hero')
const wrapper = await mountEditor({
body: HERO_BODY,
variants: () => ({ status: 200, body: { items } }),
})
const warning = block()!
expect(warning.className).toContain('border-warning')
expect(textOf(warning)).toContain("Variant 'hero' no longer exists.")
expect(textOf(warning)).toContain('This image returns an error on the public site.')
expect(findButton('Pick another variant', warning)).toBeDefined()
expect(warning.querySelector('[role="alert"]')).not.toBeNull()
expect(textOf(document.body)).not.toContain('This image is no longer available')
expect(editorBody(wrapper)).toContain('src="/static/uploadedImages/1.jpg?v=hero"')
expect(editorBody(wrapper)).toContain('data-image-id="1"')
expect(chips()).toHaveLength(0)
})
it('A disabled variant shows its own title and still its chip', async () => {
const items = CATALOG.map((entry) =>
entry.name === 'hero' ? { ...entry, enabled: false } : entry,
)
await mountEditor({ body: HERO_BODY, variants: () => ({ status: 200, body: { items } }) })
expect(textOf(block())).toContain("Variant 'hero' is disabled.")
expect(textOf(block())).toContain('This image returns an error on the public site.')
expect(chips().map(textOf)).toEqual(['hero · 1200×630'])
})
it('An enabled variant has no warning but a chip', async () => {
await mountEditor({ body: HERO_BODY })
expect(block()).toBeNull()
const [chip] = chips()
expect(textOf(chip)).toBe('hero · 1200×630')
for (const name of [
'top-2',
'left-2',
'h-5',
'font-mono',
'text-xs',
'font-medium',
'bg-default',
'border-accented',
]) {
expect(chip!.className).toContain(name)
}
})
it('A block without a variant is unchanged', async () => {
await mountEditor({
body: '<p>Intro</p><img src="/static/uploadedImages/1.jpg" alt="" data-image-id="1">',
})
expect(block()).toBeNull()
expect(chips()).toHaveLength(0)
expect(variantRequests()).toHaveLength(0)
})
it('The list is requested once for all blocks', async () => {
await mountEditor({
body: `${HERO_BODY}<img src="/static/uploadedImages/2.webp?v=thumb" alt="" data-image-id="2">`,
})
expect(variantRequests()).toHaveLength(1)
expect(chips().map(textOf)).toEqual(['hero · 1200×630', 'thumb · 400×300'])
})
it.each([
['resolves with a 500 response', () => ({ status: 500 })],
['resolves with a 403 response', () => ({ status: 403 })],
['never reaches the server', () => Promise.reject(new TypeError('Failed to fetch'))],
])('The variants list fails: %s', async (_label, failure) => {
await mountEditor({ body: HERO_BODY, variants: failure as () => Reply })
expect(block()).toBeNull()
expect(chips()).toHaveLength(0)
expect(document.body.querySelector('[data-testid="article-editor-image"]')).not.toBeNull()
})
it('keeps the Pick another variant button 44 px high on touch screens', async () => {
const items = CATALOG.filter((entry) => entry.name !== 'hero')
await mountEditor({ body: HERO_BODY, variants: () => ({ status: 200, body: { items } }) })
const button = findButton('Pick another variant', block()!)!
expect(button.className).toContain('h-11')
expect(button.className).toContain('md:h-7')
})
describe('Pick another variant', () => {
const GONE = CATALOG.filter((entry) => entry.name !== 'hero')
async function openPick() {
findButton('Pick another variant', block()!)!.click()
await flushPromises()
await settle()
}
it('opens the select on the block with Original and the enabled variants', async () => {
await mountEditor({
body: HERO_BODY,
variants: () => ({ status: 200, body: { items: GONE } }),
})
await openPick()
expect(optionLabels()).toEqual([
'Original',
'Card · 800 × auto · WebP',
'Og · 1200×630 · JPEG',
'Square · 600×600 · JPEG',
'Thumb · 400×300 · WebP',
])
expect(block()!.contains(select())).toBe(true)
expect(select()!.getAttribute('aria-expanded')).toBe('true')
})
it('Escape closes the select and returns focus to the button', async () => {
await mountEditor({
body: HERO_BODY,
variants: () => ({ status: 200, body: { items: GONE } }),
})
await openPick()
variantSelect().emit('update:open', false)
await settle()
expect(select()).toBeNull()
expect(document.activeElement).toBe(findButton('Pick another variant', block()!))
})
it.each([
['Thumb', 'src="/static/uploadedImages/1.jpg?v=thumb"', ['thumb · 400×300']],
['Original', 'src="/static/uploadedImages/1.jpg"', []],
])('Choosing %s rewrites the block', async (option, src, expectedChips) => {
const wrapper = await mountEditor({
body: HERO_BODY,
variants: () => ({ status: 200, body: { items: GONE } }),
})
const before = fetchMock.mock.calls.length
await openPick()
await chooseOption(option)
const body = editorBody(wrapper)
expect(body).toContain(src)
expect(body).toContain('data-image-id="1"')
expect(body).toContain('alt="A wall"')
expect(block()).toBeNull()
expect(chips().map(textOf)).toEqual(expectedChips)
expect(wrapper.text()).toContain('Unsaved changes')
expect(fetchMock.mock.calls.length).toBe(before)
})
it('rewrites only the clicked block', async () => {
const wrapper = await mountEditor({
body: TWO_HERO_BODY,
variants: () => ({ status: 200, body: { items: GONE } }),
})
const warnings = document.body.querySelectorAll(
'[data-testid="article-editor-variant-warning"]',
)
expect(warnings).toHaveLength(2)
findButton('Pick another variant', warnings[0] as HTMLElement)!.click()
await flushPromises()
await settle()
await chooseOption('Thumb')
const body = editorBody(wrapper)
expect(body).toContain('?v=thumb')
expect(body).toContain('?v=hero')
expect(
document.body.querySelectorAll('[data-testid="article-editor-variant-warning"]'),
).toHaveLength(1)
})
it('does not save the warning in the article', async () => {
const wrapper = await mountEditor({
body: HERO_BODY,
variants: () => ({ status: 200, body: { items: GONE } }),
})
const body = editorBody(wrapper)
expect(body).toContain('<img')
expect(body).not.toContain('This image returns an error')
expect(body).not.toContain('Pick another variant')
})
})
})
describe('French strings', () => {
it.each([
'Variant',
'Pick another variant',
"Variant '{0}' no longer exists.",
"Variant '{0}' is disabled.",
'This image returns an error on the public site.',
'No variants defined. Add one in {0}.',
'Settings → Media → Variants',
])('has a French entry for %s', (key) => {
expect(messages).toHaveProperty([key])
expect(messages[key as keyof typeof messages]).not.toBe(key)
})
})
@@ -0,0 +1,437 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import UBadge from '@nuxt/ui/components/Badge.vue'
import router from '@/router'
import { MOBILE_WIDTH } from '@/components/__tests__/viewport'
import {
callsTo,
cardFor,
cards,
checkboxFor,
dialog,
findButton,
fixture,
kit,
lastListPath,
listBody,
listCalls,
mountPage,
panel,
settle,
textOf,
unmountPage,
} from './mediaTestKit'
vi.mock('@/composables/useApi', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/composables/useApi')>()
return { ...actual, useApi: vi.fn() }
})
const toasts = vi.hoisted(() => ({ add: vi.fn(), remove: vi.fn(), update: vi.fn() }))
vi.mock('@nuxt/ui/composables', async (importOriginal) => {
const actual = await importOriginal<typeof import('@nuxt/ui/composables')>()
return { ...actual, useToast: () => toasts }
})
function activate(element: Element) {
element.dispatchEvent(new MouseEvent('pointerup', { bubbles: true }))
element.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
function badgesOf(filename: string) {
return Array.from(cardFor(filename).querySelectorAll('[data-kind]')).map(textOf)
}
function metaOf(filename: string) {
return textOf(cardFor(filename).querySelector('.text-xs\\/5'))
}
function segment(label: string) {
return Array.from(
document.body.querySelectorAll<HTMLElement>('[data-testid="variants-filter"] button'),
).find((button) => textOf(button) === label)!
}
async function openSortMenu() {
const sort = document.body.querySelector<HTMLElement>('[aria-label="Sort"]')!
sort.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }))
sort.click()
await flushPromises()
return Array.from(document.body.querySelectorAll<HTMLElement>('[role="menuitemcheckbox"]'))
}
async function openPanelFor(filename: string) {
cardFor(filename).click()
await flushPromises()
}
beforeEach(() => {
toasts.add.mockClear()
vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(true)
})
afterEach(unmountPage)
describe('The library badge', () => {
it('A card with generated variants carries the badge', async () => {
await mountPage()
expect(badgesOf('north-wall.jpg')).toEqual(['Used in 2', '4 variants'])
expect(badgesOf('kitchen-after.webp')).toEqual(['Used in 3', '5 variants'])
})
it.each([
['north-wall.jpg', ['Used in 2', '4 variants']],
['stone-wall-detail.jpg', ['Duplicate', 'Used in 1', '1 variant']],
['window-frame.jpg', ['Unused']],
['logo-renew.svg', ['Used in 5']],
['IMG_2208.jpg', ['Duplicate', 'Used in 2']],
])('The badge text and its absence: %s', async (filename, expected) => {
await mountPage()
expect(badgesOf(filename)).toEqual(expected)
})
it('draws the badge with the info fill and the layers icon', async () => {
await mountPage()
const badge = cardFor('north-wall.jpg').querySelector('[data-kind="variants"]')!
expect(badge.className).toContain('bg-(--rc-info-soft)')
expect(badge.className).toContain('text-info')
expect(badge.className).toContain('h-5')
const component = kit
.wrapper!.findAllComponents(UBadge)
.find((entry) => entry.element === badge)
expect(component?.props('icon')).toBe('i-lucide-layers')
})
it('The accessible name of a card is unchanged', async () => {
await mountPage()
expect(cardFor('north-wall.jpg').getAttribute('aria-label')).toBe(
'north-wall.jpg, 3.9 MB, used in 2 articles',
)
})
it('List view shows no variants badge', async () => {
await mountPage({}, '/media?view=list')
const rows = Array.from(document.body.querySelectorAll('[data-testid="media-row"]'))
expect(rows).toHaveLength(12)
expect(rows.map(textOf).join(' ')).not.toMatch(/\d variants?/)
expect(document.body.querySelector('[data-kind="variants"]')).toBeNull()
})
it('List view on mobile shows no variants badge', async () => {
await mountPage({}, '/media?view=list', MOBILE_WIDTH)
expect(document.body.querySelector('[data-kind="variants"]')).toBeNull()
})
})
describe('The variants filter', () => {
it('sits between the search field and the sort menu with All selected', async () => {
await mountPage()
const control = document.body.querySelector<HTMLElement>('[data-testid="variants-filter"]')!
const toolbarOrder = Array.from(control.parentElement!.children).map(
(element) => element.getAttribute('data-testid') ?? element.tagName,
)
expect(toolbarOrder.indexOf('variants-filter')).toBeGreaterThan(
toolbarOrder.findIndex((id) => id === 'DIV' || id.includes('tabs')),
)
expect(Array.from(control.querySelectorAll('button')).map(textOf)).toEqual([
'All',
'With variants',
'Without',
])
expect(segment('All').getAttribute('aria-pressed')).toBe('true')
expect(segment('All').className).toContain('bg-primary')
expect(segment('With variants').getAttribute('aria-pressed')).toBe('false')
expect(control.className).toContain('border-accented')
})
it('On mobile the control is its own full-width row with 44 px segments', async () => {
await mountPage({}, '/media', MOBILE_WIDTH)
const control = document.body.querySelector<HTMLElement>('[data-testid="variants-filter"]')!
expect(control.className).toContain('w-full')
for (const button of control.querySelectorAll('button')) {
expect(button.className).toContain('h-10.5')
expect(button.className).toContain('flex-1')
expect(button.className).toContain('text-xs')
}
})
it.each([
['With variants', '?variants=with', 'filter=all&sort=newest&variants=with&limit=100'],
['Without', '?variants=without', 'filter=all&sort=newest&variants=without&limit=100'],
])('Choosing %s writes the URL and requests the list', async (label, search, request) => {
await mountPage()
segment(label).click()
await flushPromises()
expect(router.currentRoute.value.fullPath).toBe(`/media${search}`)
expect(lastListPath()).toBe(`/v1/media/?${request}`)
})
it('shows the skeleton 150 ms after the request starts', async () => {
await mountPage()
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
const never = new Promise(() => undefined)
const { kit } = await import('./mediaTestKit')
const original = kit.requestMock.getMockImplementation()!
kit.requestMock.mockImplementation((path: string, options?: RequestInit) =>
path.includes('variants=with') ? never : original(path, options),
)
segment('With variants').click()
await flushPromises()
expect(document.body.querySelector('[data-testid="media-skeleton"]')).toBeNull()
vi.advanceTimersByTime(150)
await flushPromises()
expect(document.body.querySelector('[aria-busy="true"]')).not.toBeNull()
})
it('All removes the parameter', async () => {
await mountPage({}, '/media?variants=with')
segment('All').click()
await flushPromises()
expect(router.currentRoute.value.fullPath).toBe('/media')
expect(lastListPath()).toBe('/v1/media/?filter=all&sort=newest&limit=100')
})
it.each([
[
'?variants=with',
'filter=all&sort=newest&variants=with',
'With variants',
'/media?variants=with',
],
[
'?variants=without&filter=unused',
'filter=unused&sort=newest&variants=without',
'Without',
'/media?filter=unused&variants=without',
],
['?variants=all', 'filter=all&sort=newest', 'All', '/media'],
['?variants=zzz', 'filter=all&sort=newest', 'All', '/media'],
])('The query string is the source of truth: %s', async (search, request, selected, url) => {
await mountPage({}, `/media${search}`)
expect(lastListPath()).toBe(`/v1/media/?${request}&limit=100`)
expect(segment(selected).getAttribute('aria-pressed')).toBe('true')
expect(router.currentRoute.value.fullPath).toBe(url)
})
it('With variants returns only the images that have cached files', async () => {
const ids = [1, 7, 9, 12, 5, 11, 2, 3, 10]
await mountPage(
{
list: () => listBody(ids.map((id) => fixture([id])[0]!)),
},
'/media?variants=with&sort=total_size',
)
expect(cards().map((card) => card.getAttribute('aria-label')!.split(',')[0])).toEqual([
'north-wall.jpg',
'IMG_4471.jpg',
'stone-wall-detail.jpg',
'floorboards.jpg',
'floorboards-copy.jpg',
'lime-plaster.jpg',
'kitchen-after.webp',
'kitchen-before.webp',
'bathroom-tiles.png',
])
expect(cards().every((card) => card.querySelector('[data-kind="variants"]'))).toBe(true)
})
it('Without variants returns the images with no cached file', async () => {
await mountPage(
{ list: () => listBody([4, 6, 8].map((id) => fixture([id])[0]!)) },
'/media?variants=without',
)
expect(cards()).toHaveLength(3)
expect(document.body.querySelector('[data-kind="variants"]')).toBeNull()
})
})
describe('Sorting by total size', () => {
it('The new option is last in the sort menu and the selected one carries a check', async () => {
await mountPage()
const items = await openSortMenu()
expect(items.map(textOf)).toEqual([
'Newest',
'Oldest',
'Name',
'Largest',
'Largest total size (original + variants)',
])
expect(items[0]!.getAttribute('aria-checked')).toBe('true')
})
it('labels the option "Largest total size" on mobile', async () => {
await mountPage({}, '/media', MOBILE_WIDTH)
const items = await openSortMenu()
expect(textOf(items.at(-1))).toBe('Largest total size')
})
it('Choosing it sends sort=total_size and the button reads the long label', async () => {
await mountPage()
const items = await openSortMenu()
activate(items.at(-1)!)
await flushPromises()
expect(router.currentRoute.value.query).toEqual({ sort: 'total_size' })
expect(lastListPath()).toBe('/v1/media/?filter=all&sort=total_size&limit=100')
expect(textOf(document.body.querySelector('[aria-label="Sort"]'))).toBe(
'Largest total size (original + variants)',
)
})
it.each([
['north-wall.jpg', '4.2 MB total · 3.9 MB + 260 KB'],
['kitchen-after.webp', '1.6 MB total · 1.2 MB + 410 KB'],
['window-frame.jpg', '1.8 MB total'],
['logo-renew.svg', '8 KB total'],
])('The meta line shows the total while sorted by total size: %s', async (filename, meta) => {
await mountPage({}, '/media?sort=total_size')
expect(metaOf(filename)).toBe(meta)
})
it('Other sorts keep the usual meta line', async () => {
await mountPage()
expect(metaOf('north-wall.jpg')).toBe('3.9 MB · 4032 × 3024')
})
it('A stale sort value is dropped', async () => {
await mountPage({}, '/media?sort=total')
expect(router.currentRoute.value.fullPath).toBe('/media')
expect(lastListPath()).toBe('/v1/media/?filter=all&sort=newest&limit=100')
})
})
describe('Nothing to show with the variants filter', () => {
it('With variants and an empty cache', async () => {
await mountPage({ list: () => listBody([]) }, '/media?variants=with')
const content = textOf(document.body)
expect(content).toContain('No images with variants')
expect(content).toContain(
'Variants are generated when an image is requested with ?v=<name>, or from its Variants tab.',
)
expect(findButton('Show all images')).toBeDefined()
expect(document.body.querySelector('[data-testid="variants-filter"]')).not.toBeNull()
})
it('Show all images resets the variants filter', async () => {
const handlers = {
list: (path: string) =>
path.includes('variants=with') ? listBody([]) : listBody(fixture()),
}
await mountPage(handlers, '/media?variants=with')
findButton('Show all images')!.click()
await flushPromises()
expect(router.currentRoute.value.fullPath).toBe('/media')
expect(segment('All').getAttribute('aria-pressed')).toBe('true')
expect(cards()).toHaveLength(12)
})
})
describe('Delete dialogs name the generated variants they also remove', () => {
it('A single delete of an image with variants', async () => {
await mountPage({
usage: () => [{ id: 10, title: 'How we price a bathroom', published: true }],
})
await openPanelFor('north-wall.jpg')
const before = callsTo('GET', /\/v1\/media\//).length
findButton('Delete', panel()!)!.click()
await flushPromises()
const content = textOf(dialog())
expect(content).toContain("Delete an image that's in use?")
expect(content).toContain('Also removes 4 generated variants (260 KB)')
expect(callsTo('GET', /\/v1\/media\//).length).toBe(before)
})
it.each([
['stone-wall-detail.jpg', 'Also removes 1 generated variant (60 KB)'],
['window-frame.jpg', null],
])('The note is singular for one variant and absent for none: %s', async (filename, note) => {
await mountPage()
await openPanelFor(filename)
findButton('Delete', panel()!)!.click()
await flushPromises()
if (note) {
expect(textOf(dialog())).toContain(note)
} else {
expect(textOf(dialog())).not.toContain('Also removes')
}
})
it('Bulk delete sums the selection', async () => {
await mountPage()
for (const name of ['north-wall.jpg', 'kitchen-after.webp', 'window-frame.jpg']) {
checkboxFor(name).click()
}
await flushPromises()
findButton(
'Delete',
document.body.querySelector<HTMLElement>('[data-testid="media-bulk-bar"]')!,
)!.click()
await flushPromises()
expect(textOf(dialog())).toContain('Also removes 9 generated variants (670 KB)')
expect(dialog()!.querySelectorAll('[data-testid="bulk-delete-row"]')).toHaveLength(3)
})
it('A bulk delete with no variant in the selection shows no note', async () => {
await mountPage()
for (const name of ['window-frame.jpg', 'IMG_2208.jpg']) {
checkboxFor(name).click()
}
await flushPromises()
findButton(
'Delete',
document.body.querySelector<HTMLElement>('[data-testid="media-bulk-bar"]')!,
)!.click()
await flushPromises()
expect(textOf(dialog())).not.toContain('Also removes')
})
it('The delete flow itself is unchanged and the list is requested again', async () => {
await mountPage({ remove: () => undefined })
await openPanelFor('window-frame.jpg')
const before = listCalls().length
findButton('Delete', panel()!)!.click()
await flushPromises()
findButton('Delete image', dialog()!)!.click()
await settle()
expect(callsTo('DELETE', /\/v1\/media\/8$/)).toHaveLength(1)
expect(listCalls().length).toBeGreaterThan(before)
})
})
@@ -0,0 +1,783 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import UButton from '@nuxt/ui/components/Button.vue'
import router from '@/router'
import { ApiError, NetworkError } from '@/composables/useApi'
import { MOBILE_WIDTH } from '@/components/__tests__/viewport'
import {
NORTH_WALL_BYTES,
callsTo,
cardFor,
cards,
deferred,
findButton,
kit,
listBody,
fixture,
mountPage,
panel,
press,
tab,
tabs,
textOf,
unmountPage,
variantItems,
variantList,
} from './mediaTestKit'
import { savedPercent, signedPercent } from '@/lib/variants/variantSaving'
vi.mock('@/composables/useApi', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/composables/useApi')>()
return { ...actual, useApi: vi.fn() }
})
const toasts = vi.hoisted(() => ({ add: vi.fn(), remove: vi.fn(), update: vi.fn() }))
vi.mock('@nuxt/ui/composables', async (importOriginal) => {
const actual = await importOriginal<typeof import('@nuxt/ui/composables')>()
return { ...actual, useToast: () => toasts }
})
const PARTLY = ['card', 'hero', 'square', 'thumb']
const SVG_LIST = { unsupported: 'svg', items: [] }
const writeText = vi.fn()
function mountTab(...[handlers, url, width, options]: Parameters<typeof mountPage>) {
return mountPage(handlers, url, width, { ...options, app: true })
}
function toastWith(id: string) {
return toasts.add.mock.calls.map(([content]) => content).find((content) => content.id === id)
}
function lastToast() {
return toasts.add.mock.calls.at(-1)![0]
}
async function openVariants(filename = 'north-wall.jpg') {
cardFor(filename).click()
await flushPromises()
activateTab('Variants')
await flushPromises()
}
function activateTab(label: string) {
const target = tab(label)
target.focus()
press(target, 'Enter')
}
function body() {
return panel()!.querySelector<HTMLElement>('[data-testid="variants-tab"]')!
}
function rows() {
return Array.from(body().querySelectorAll<HTMLElement>('[data-testid="variant-row"]'))
}
function rowOf(name: string) {
return rows().find((row) => row.getAttribute('data-variant') === name)!
}
function rowAction(name: string, label: string) {
return Array.from(rowOf(name).querySelectorAll<HTMLButtonElement>('button')).find(
(button) => (button.getAttribute('aria-label') ?? textOf(button)) === label,
)
}
function summary() {
return textOf(
Array.from(body().querySelectorAll('span')).find((span) =>
/of \d+ generated/.test(span.textContent ?? ''),
),
)
}
function generateAllButton() {
return findButton('Generate all', body()) ?? findButton('Generating…', body())
}
function variantRequests(method = 'GET') {
return callsTo(method, /\/v1\/media\/1\/variants$/)
}
beforeEach(() => {
toasts.add.mockClear()
writeText.mockReset().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(true)
})
afterEach(unmountPage)
describe('Saving percent', () => {
it.each([
[18432, '-99%'],
[65536, '-98%'],
[98304, '-98%'],
[145408, '-96%'],
[3250586, '-21%'],
[4089446, '0%'],
[4500000, '+10%'],
])('Saving against the original for %i bytes reads %s', (size, text) => {
expect(signedPercent(NORTH_WALL_BYTES, size)).toBe(text)
})
it('never shows -100% for a non-empty file', () => {
expect(savedPercent(NORTH_WALL_BYTES, 1)).toBe(-99)
expect(savedPercent(NORTH_WALL_BYTES, 0)).toBe(-100)
})
it('rounds half away from zero', () => {
expect(savedPercent(200, 101)).toBe(-50)
expect(savedPercent(200, 301)).toBe(51)
expect(savedPercent(0, 10)).toBe(0)
})
})
describe('The panel tabs', () => {
it('gives an owner two tabs under the header with the first selected', async () => {
await mountTab({ variants: () => variantList() })
cardFor('north-wall.jpg').click()
await flushPromises()
const labels = tabs()
.map(textOf)
.filter((label) => label === 'Details' || label === 'Variants')
expect(labels).toEqual(['Details', 'Variants'])
expect(tab('Details').getAttribute('aria-selected')).toBe('true')
expect(tab('Variants').className).toContain('h-10')
expect(tab('Variants').className).toContain('max-md:h-11')
})
it('gives an admin the tabs too', async () => {
await mountTab({ variants: () => variantList() }, '/media', undefined, { role: 'admin' })
cardFor('north-wall.jpg').click()
await flushPromises()
expect(tab('Variants')).toBeDefined()
})
it('A session that is not owner or admin sees no tab and sends no request', async () => {
await mountTab({}, '/media', undefined, { role: 'user' })
cardFor('north-wall.jpg').click()
await flushPromises()
expect(tabs().filter((entry) => textOf(entry) === 'Variants')).toHaveLength(0)
expect(textOf(panel())).toContain('Copy URL')
expect(variantRequests()).toHaveLength(0)
})
it('Selecting the tab requests the variants once per open panel', async () => {
await mountTab({ variants: () => variantList(PARTLY) })
cardFor('north-wall.jpg').click()
await flushPromises()
expect(variantRequests()).toHaveLength(0)
activateTab('Variants')
await flushPromises()
activateTab('Details')
await flushPromises()
activateTab('Variants')
await flushPromises()
expect(variantRequests()).toHaveLength(1)
expect(textOf(panel())).toContain('Original · kept untouched')
})
it('keeps the Details body unchanged', async () => {
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
activateTab('Details')
await flushPromises()
const details = panel()!.querySelector<HTMLElement>('dl')!
expect(textOf(details)).toContain('JPEG')
expect(details.closest<HTMLElement>('[style*="display: none"]')).toBeNull()
})
})
describe('Loading and failing', () => {
it('draws nothing at 149 ms and five skeleton rows with aria-busy at 150 ms', async () => {
const pending = deferred<unknown>()
await mountTab({ variants: () => pending.promise })
cardFor('north-wall.jpg').click()
await flushPromises()
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
activateTab('Variants')
await flushPromises()
vi.advanceTimersByTime(149)
await flushPromises()
expect(body().children).toHaveLength(1)
expect(body().querySelector('[aria-busy="true"]')).toBeNull()
vi.advanceTimersByTime(1)
await flushPromises()
const region = body().querySelector<HTMLElement>('[aria-busy="true"]')!
expect(region.getAttribute('aria-label')).toBe('Loading variants')
expect(region.querySelectorAll('[data-testid="variant-skeleton-row"]')).toHaveLength(5)
vi.useRealTimers()
})
it.each([
['status 500', () => Promise.reject(new ApiError(500))],
['a network failure', () => Promise.reject(new NetworkError())],
])('The variants request fails with %s and Try again sends it again', async (_label, fail) => {
await mountTab({ variants: fail })
await openVariants()
const alert = body().querySelector<HTMLElement>('[role="alert"]')!
expect(textOf(alert)).toContain("Couldn't load variants")
expect(textOf(alert)).toContain('Check your connection and try again.')
const retry = findButton('Try again', alert)!
expect(retry).toBeDefined()
retry.click()
await flushPromises()
expect(variantRequests()).toHaveLength(2)
})
})
describe('The list', () => {
it('shows the Original block, the summary and the list when partly generated', async () => {
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
const children = Array.from(body().children)
expect(children[0]!.getAttribute('data-testid')).toBe('variants-original')
expect(textOf(children[0])).toBe(
'Original · kept untouched north-wall.jpg JPEG · 4032 × 3024 · 3.9 MB',
)
expect(summary()).toBe('4 of 5 generated')
expect(findButton('Generate all', body())).toBeDefined()
expect(rows().map((row) => row.getAttribute('data-variant'))).toEqual([
'card',
'hero',
'og',
'square',
'thumb',
])
})
it.each([
['thumb', '400×300 · WebP · 18 KB · -99% vs original'],
['card', '800×600 · WebP · 64 KB · -98% vs original'],
['hero', '1200×630 · WebP · 96 KB · -98% vs original'],
['square', '600×600 · JPEG · 82 KB · -98% vs original'],
])('A generated row: %s', async (name, meta) => {
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
const row = rowOf(name)
expect(textOf(row)).toContain('Generated')
expect(textOf(row)).toContain(meta)
const saving = Array.from(row.querySelectorAll('span')).find((span) =>
span.textContent?.endsWith('vs original'),
)!
expect(saving.className).toContain('text-success')
expect(row.querySelector('.font-mono')!.className).toContain('font-medium')
})
it('A not generated row', async () => {
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
const row = rowOf('og')
expect(textOf(row)).toContain('Not generated')
expect(textOf(row)).toContain('1200×630 · JPEG')
expect(textOf(row)).not.toContain('vs original')
expect(textOf(row)).not.toContain('KB')
})
it('Nothing generated yet', async () => {
await mountTab({ variants: () => variantList([]) })
await openVariants()
expect(textOf(body())).toContain('0 of 5 generated')
expect(textOf(body())).toContain('Nothing generated yet.')
expect(rows().every((row) => textOf(row).includes('Not generated'))).toBe(true)
})
it('No variants defined', async () => {
await mountTab({ variants: () => ({ unsupported: null, items: [] }) })
await openVariants()
expect(textOf(body())).toContain('No variants defined')
expect(textOf(body())).toContain(
'Define a variant in Settings to get resized copies of this image.',
)
const link = body().querySelector<HTMLAnchorElement>('a')!
expect(textOf(link)).toBe('Settings → Media → Variants')
expect(link.getAttribute('href')).toBe('/settings/media/variants')
expect(rows()).toHaveLength(0)
expect(generateAllButton()).toBeUndefined()
expect(body().querySelector('[data-testid="variants-original"]')).not.toBeNull()
})
it('An SVG source', async () => {
await mountTab({ variants: () => SVG_LIST })
cardFor('logo-renew.svg').click()
await flushPromises()
activateTab('Variants')
await flushPromises()
expect(textOf(body().firstElementChild)).toContain('SVG · Vector · 8 KB')
const alert = body().querySelector('[class*="bg-(--rc-info-soft)"], [data-slot="root"]')
expect(textOf(body())).toContain("Variants aren't generated for this format.")
expect(textOf(body())).toContain('SVG images are served as they are.')
expect(alert).not.toBeNull()
expect(rows()).toHaveLength(0)
expect(generateAllButton()).toBeUndefined()
})
})
describe('Row actions', () => {
it('shows icon buttons with accessible names on desktop', async () => {
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
const generated = Array.from(rowOf('thumb').querySelectorAll('button')).map((button) =>
button.getAttribute('aria-label'),
)
expect(generated).toEqual(['Copy URL', 'Preview', 'Purge'])
const missing = Array.from(rowOf('og').querySelectorAll('button')).map((button) =>
button.getAttribute('aria-label'),
)
expect(missing).toEqual(['Copy URL', 'Generate now'])
expect(rowAction('thumb', 'Copy URL')!.className).toContain('size-7')
})
it('shows labelled 44 px buttons on their own line below 640 px', async () => {
await mountTab({ variants: () => variantList(PARTLY) }, '/media', MOBILE_WIDTH)
await openVariants()
const buttons = Array.from(rowOf('thumb').querySelectorAll('button'))
expect(buttons.map(textOf)).toEqual(['Copy URL', 'Preview', 'Purge'])
expect(buttons.every((button) => button.className.includes('h-11'))).toBe(true)
expect(textOf(rowAction('og', 'Generate now'))).toBe('Generate now')
})
it('disables Generate all when everything is generated', async () => {
await mountTab({ variants: () => variantList() })
await openVariants()
expect(generateAllButton()!.disabled).toBe(true)
})
it('shows an icon and a word for every status', async () => {
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
const icons = kit
.wrapper!.findAllComponents({ name: 'Badge' })
.filter((badge) => badge.element.hasAttribute('data-status'))
.map((badge) => [badge.attributes('data-status'), badge.props('icon')])
expect(icons).toContainEqual(['generated', 'i-lucide-circle-check'])
expect(icons).toContainEqual(['missing', 'i-lucide-circle-dashed'])
})
})
describe('Generating', () => {
it('Generate now shows the row in flight and then generated with a toast', async () => {
const pending = deferred<unknown>()
await mountTab({
variants: () => variantList(PARTLY),
generate: () => pending.promise,
})
await openVariants()
rowAction('og', 'Generate now')!.click()
await flushPromises()
expect(callsTo('POST', /\/v1\/media\/1\/variants\/og$/)).toHaveLength(1)
expect(textOf(rowOf('og'))).toContain('Generating')
expect(rowOf('og').querySelectorAll('button')).toHaveLength(0)
expect(rowOf('og').className).toContain('bg-elevated')
expect(rowOf('hero').className).not.toContain('bg-elevated')
expect(textOf(body())).toContain('Generating variants…')
const all = generateAllButton()!
expect(textOf(all)).toBe('Generating…')
expect(all.disabled).toBe(true)
pending.resolve(variantItems().find((item) => item.name === 'og'))
await flushPromises()
expect(textOf(rowOf('og'))).toContain('Generated')
expect(summary()).toBe('5 of 5 generated')
expect(toastWith('media-variant-generated-1-og')).toMatchObject({
icon: 'i-lucide-circle-check',
title: 'Generated og',
})
})
it('Generate all shows the rows in flight and toasts the count', async () => {
const pending = deferred<unknown>()
await mountTab({
variants: () => variantList(['thumb']),
generateAll: () => pending.promise,
})
await openVariants()
generateAllButton()!.click()
await flushPromises()
expect(variantRequests('POST')).toHaveLength(1)
expect(
rows()
.filter((row) => textOf(row).includes('Generating'))
.map((row) => row.getAttribute('data-variant')),
).toEqual(['card', 'hero', 'og', 'square'])
expect(textOf(rowOf('thumb'))).toContain('Generated')
pending.resolve({ generated: 4, failed: 0, failures: [], items: variantItems() })
await flushPromises()
expect(rows().every((row) => textOf(row).includes('Generated'))).toBe(true)
expect(toastWith('media-variants-generated-1')).toMatchObject({
title: 'Generated 4 variants',
})
})
it('A single generated variant reads in the singular', async () => {
await mountTab({
variants: () => variantList(PARTLY),
generateAll: () => ({ generated: 1, failed: 0, failures: [], items: variantItems() }),
})
await openVariants()
generateAllButton()!.click()
await flushPromises()
expect(toastWith('media-variants-generated-1')).toMatchObject({
title: 'Generated 1 variant',
})
})
it('Generate all with a failure marks the row with its cause and Retry', async () => {
const items = variantItems().map((item) =>
item.name === 'hero' ? { ...item, generated: false, size: null } : item,
)
await mountTab({
variants: () => variantList(['thumb']),
generateAll: () => ({
generated: 4,
failed: 1,
failures: [{ name: 'hero', cause: 'too_large' }],
items,
}),
})
await openVariants()
generateAllButton()!.click()
await flushPromises()
const row = rowOf('hero')
expect(textOf(row)).toContain('Failed')
expect(textOf(row)).toContain('Image too large')
const retry = findButton('Retry', row)!
expect(retry.className).toContain('h-7')
expect(retry.className).toContain('text-xs')
expect(summary()).toBe('4 of 5 generated')
expect(toastWith('media-variants-generated-1')).toMatchObject({
title: 'Generated 4 variants',
})
})
it.each([
[413, 'Image too large'],
[415, 'Unsupported source format'],
])('A single generation fails with %i', async (status, cause) => {
await mountTab({
variants: () => variantList(PARTLY),
generate: () => Promise.reject(new ApiError(status, undefined, 'plain text body')),
})
await openVariants()
rowAction('og', 'Generate now')!.click()
await flushPromises()
expect(textOf(rowOf('og'))).toContain('Failed')
expect(textOf(rowOf('og'))).toContain(cause)
expect(findButton('Retry', rowOf('og'))).toBeDefined()
expect(lastToast()).toMatchObject({
color: 'error',
title: "Couldn't generate og.",
description: `${cause}.`,
})
expect(textOf(document.body)).not.toContain('plain text body')
})
it('does not remember a failed state when the panel is closed and opened again', async () => {
await mountTab({
variants: () => variantList(PARTLY),
generate: () => Promise.reject(new ApiError(413)),
})
await openVariants()
rowAction('og', 'Generate now')!.click()
await flushPromises()
expect(textOf(rowOf('og'))).toContain('Failed')
press(panel()!, 'Escape')
document.body
.querySelector<HTMLElement>('[role="dialog"] button[aria-label="Close"]')
?.click()
await flushPromises()
await new Promise((resolve) => setTimeout(resolve, 20))
await flushPromises()
await openVariants()
expect(textOf(rowOf('og'))).toContain('Not generated')
})
it('Retry sends the same request and shows Generating', async () => {
const pending = deferred<unknown>()
let calls = 0
await mountTab({
variants: () => variantList(PARTLY),
generate: () => (++calls === 1 ? Promise.reject(new ApiError(413)) : pending.promise),
})
await openVariants()
rowAction('og', 'Generate now')!.click()
await flushPromises()
findButton('Retry', rowOf('og'))!.click()
await flushPromises()
expect(callsTo('POST', /\/v1\/media\/1\/variants\/og$/)).toHaveLength(2)
expect(textOf(rowOf('og'))).toContain('Generating')
})
it.each([
['500', new ApiError(500), 'Something went wrong'],
['403', new ApiError(403), "You don't have access"],
['network failure', new NetworkError(), 'Something went wrong'],
])(
'Other failures of a generation: %s returns the row to Not generated',
async (_l, error, title) => {
await mountTab({
variants: () => variantList(PARTLY),
generate: () => Promise.reject(error),
})
await openVariants()
rowAction('og', 'Generate now')!.click()
await flushPromises()
expect(textOf(rowOf('og'))).toContain('Not generated')
expect(lastToast()).toMatchObject({ color: 'error', title })
},
)
it('a 404 returns the row, toasts and requests the tab again', async () => {
await mountTab({
variants: () => variantList(PARTLY),
generate: () => Promise.reject(new ApiError(404)),
})
await openVariants()
rowAction('og', 'Generate now')!.click()
await flushPromises()
expect(textOf(rowOf('og'))).toContain('Not generated')
expect(lastToast()).toMatchObject({
title: 'Not found',
description: 'This variant or image no longer exists. Refresh the page.',
})
expect(variantRequests()).toHaveLength(2)
})
it('closes the panel and drops the image when the second request is a 404', async () => {
let variantCalls = 0
let imageGone = false
await mountTab({
variants: () => {
if (++variantCalls === 1) {
return variantList(PARTLY)
}
imageGone = true
return Promise.reject(new ApiError(404))
},
generate: () => Promise.reject(new ApiError(404)),
list: () => listBody(fixture().filter((item) => !imageGone || item.id !== 1)),
})
await openVariants()
rowAction('og', 'Generate now')!.click()
await flushPromises()
await new Promise((resolve) => setTimeout(resolve, 20))
await flushPromises()
expect(cards().some((card) => textOf(card).includes('north-wall.jpg'))).toBe(false)
expect(toastWith('media-not-found-1')).toMatchObject({
title: 'That image no longer exists',
})
})
it('announces the progress in a polite live region', async () => {
const pending = deferred<unknown>()
await mountTab({ variants: () => variantList(PARTLY), generate: () => pending.promise })
await openVariants()
rowAction('og', 'Generate now')!.click()
await flushPromises()
const region = body().querySelector<HTMLElement>('[aria-live="polite"]')!
expect(textOf(region)).toBe('Generating variants')
pending.resolve(variantItems().find((item) => item.name === 'og'))
await flushPromises()
expect(textOf(region)).toBe('Generated og')
})
})
describe('Copy URL, Purge and Preview', () => {
it('copies the absolute variant url, also for a row that is not generated', async () => {
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
rowAction('thumb', 'Copy URL')!.click()
await flushPromises()
rowAction('og', 'Copy URL')!.click()
await flushPromises()
expect(writeText).toHaveBeenNthCalledWith(
1,
`${window.location.origin}/static/uploadedImages/1.jpg?v=thumb`,
)
expect(writeText).toHaveBeenNthCalledWith(
2,
`${window.location.origin}/static/uploadedImages/1.jpg?v=og`,
)
expect(toastWith('media-variant-url-copied-1-thumb')).toMatchObject({
title: 'URL copied',
description: 'Paste it wherever you need the image address.',
})
})
it('shows no success toast when the clipboard rejects', async () => {
writeText.mockRejectedValue(new Error('denied'))
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
rowAction('thumb', 'Copy URL')!.click()
await flushPromises()
expect(toastWith('media-variant-url-copied-1-thumb')).toBeUndefined()
})
it('Purge removes the file, updates the row and the summary, and toasts', async () => {
await mountTab({
variants: () => variantList(PARTLY),
purgeVariant: () => ({ purged_files: 1, purged_bytes: 18432 }),
})
await openVariants()
rowAction('thumb', 'Purge')!.click()
await flushPromises()
expect(callsTo('DELETE', /\/v1\/media\/1\/variants\/thumb$/)).toHaveLength(1)
expect(textOf(rowOf('thumb'))).toContain('Not generated')
expect(textOf(rowOf('thumb'))).not.toContain('KB')
expect(summary()).toBe('3 of 5 generated')
expect(toastWith('media-variants-purged-1-thumb')).toMatchObject({
title: 'Purged 1 file (18 KB)',
})
})
it.each([
[403, "You don't have access"],
[404, 'Not found'],
[500, 'Something went wrong'],
])('Purge fails with %i and the row stays Generated', async (status, title) => {
await mountTab({
variants: () => variantList(PARTLY),
purgeVariant: () => Promise.reject(new ApiError(status)),
})
await openVariants()
rowAction('thumb', 'Purge')!.click()
await flushPromises()
expect(textOf(rowOf('thumb'))).toContain('Generated')
expect(lastToast()).toMatchObject({ color: 'error', title })
})
it('Preview opens a dialog with both panes at actual size', async () => {
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
rowAction('thumb', 'Preview')!.click()
await flushPromises()
const dialogs = Array.from(document.body.querySelectorAll<HTMLElement>('[role="dialog"]'))
const preview = dialogs.find((entry) => textOf(entry).includes('Preview: thumb'))!
const content = textOf(preview)
expect(content).toContain('thumb · 400×300 · WebP')
expect(content).toContain('18 KB · saves 99%')
expect(content).toContain('Original · 4032×3024 · JPEG')
expect(content).toContain('3.9 MB')
expect(content).toContain('Both images are shown at actual size. Scroll to pan.')
expect(findButton('Close', preview)).toBeDefined()
expect(preview.querySelector('[data-testid="preview-variant-pane"]')!.className).toContain(
'sm:h-75',
)
expect(preview.querySelector('[data-testid="preview-variant-pane"]')!.className).toContain(
'h-45',
)
const sources = Array.from(preview.querySelectorAll('img')).map((image) =>
image.getAttribute('src'),
)
expect(sources).toEqual(['/static/uploadedImages/1.jpg?v=thumb', '/media/north-wall.jpg'])
})
it('returns focus to the Preview button when the dialog closes', async () => {
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
const opener = rowAction('thumb', 'Preview')!
opener.focus()
opener.click()
await flushPromises()
const preview = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="dialog"]'),
).find((entry) => textOf(entry).includes('Preview: thumb'))!
findButton('Close', preview)!.click()
await flushPromises()
await new Promise((resolve) => setTimeout(resolve, 20))
await flushPromises()
expect(document.activeElement).toBe(opener)
})
it('uses the sheet layout from the same markup below 640 px', async () => {
await mountTab({ variants: () => variantList(PARTLY) }, '/media', MOBILE_WIDTH)
await openVariants()
rowAction('thumb', 'Preview')!.click()
await flushPromises()
const preview = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="dialog"]'),
).find((entry) => textOf(entry).includes('Preview: thumb'))!
expect(preview.className).toContain('max-sm:!bottom-4')
expect(findButton('Close', preview)!.className).toContain('h-11')
})
})
describe('Vocabulary', () => {
it('never says thumbnail preset, version or rendition', async () => {
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
expect(textOf(body())).not.toMatch(/thumbnail preset|version|rendition/i)
})
it('keeps the buttons buttons', async () => {
await mountTab({ variants: () => variantList(PARTLY) })
await openVariants()
expect(kit.wrapper!.findAllComponents(UButton).length).toBeGreaterThan(0)
expect(router.currentRoute.value.path).toBe('/media')
})
})
+105 -2
View File
@@ -1,7 +1,9 @@
import { vi } from 'vitest'
import { defineComponent, h } from 'vue'
import { mount, flushPromises, type VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import uiPlugin from '@nuxt/ui/vue-plugin'
import UApp from '@nuxt/ui/components/App.vue'
import router from '@/router'
import { ApiError, useApi } from '@/composables/useApi'
import type { MediaItem } from '@/composables/useMedia'
@@ -21,6 +23,8 @@ type Row = [
string,
boolean,
string,
number,
number,
]
const ROWS: Row[] = [
@@ -36,6 +40,8 @@ const ROWS: Row[] = [
'2026-09-12T12:00:00Z',
false,
'0a',
4,
266240,
],
[
2,
@@ -49,6 +55,8 @@ const ROWS: Row[] = [
'2026-09-08T12:00:00Z',
false,
'1b',
5,
419840,
],
[
3,
@@ -62,6 +70,8 @@ const ROWS: Row[] = [
'2026-09-08T11:00:00Z',
false,
'2c',
5,
404480,
],
[
4,
@@ -75,6 +85,8 @@ const ROWS: Row[] = [
'2026-09-05T12:00:00Z',
false,
'3d',
0,
0,
],
[
5,
@@ -88,6 +100,8 @@ const ROWS: Row[] = [
'2026-09-02T12:00:00Z',
true,
'0e',
3,
245760,
],
[
6,
@@ -101,6 +115,8 @@ const ROWS: Row[] = [
'2026-08-30T12:00:00Z',
true,
'0e',
0,
0,
],
[
7,
@@ -114,6 +130,8 @@ const ROWS: Row[] = [
'2026-08-29T12:00:00Z',
true,
'2f',
2,
153600,
],
[
8,
@@ -127,6 +145,8 @@ const ROWS: Row[] = [
'2026-08-28T12:00:00Z',
false,
'3a',
0,
0,
],
[
9,
@@ -140,6 +160,8 @@ const ROWS: Row[] = [
'2026-08-21T12:00:00Z',
true,
'2f',
1,
61440,
],
[
10,
@@ -153,6 +175,8 @@ const ROWS: Row[] = [
'2026-08-04T12:00:00Z',
false,
'1b',
3,
194560,
],
[
11,
@@ -166,6 +190,8 @@ const ROWS: Row[] = [
'2026-07-19T12:00:00Z',
false,
'1c',
4,
286720,
],
[
12,
@@ -179,6 +205,8 @@ const ROWS: Row[] = [
'2026-06-14T12:00:00Z',
true,
'0e',
5,
440320,
],
]
@@ -199,6 +227,8 @@ export function fixture(ids?: number[]): MediaItem[] {
created_at,
duplicate,
sha256,
variant_count,
variant_size,
]) => ({
id,
filename,
@@ -212,6 +242,8 @@ export function fixture(ids?: number[]): MediaItem[] {
created_at,
used_in,
duplicate,
variant_count,
variant_size,
}),
)
}
@@ -238,6 +270,10 @@ export interface Handlers {
merge?: (body: { keep_id: number; merge_ids: number[] }) => unknown
preview?: () => unknown
purge?: (body: { fingerprint: string }) => unknown
variants?: (id: number) => unknown
generateAll?: (id: number) => unknown
generate?: (id: number, name: string) => unknown
purgeVariant?: (id: number, name: string) => unknown
}
export function libraryHandlers(
@@ -282,6 +318,28 @@ function dispatcher(handlers: Handlers) {
if (method === 'POST' && path === '/v1/media/purge') {
return (handlers.purge ?? (() => undefined))(JSON.parse(String(options?.body)))
}
const variantsList = /^\/v1\/media\/(\d+)\/variants$/.exec(path)
if (variantsList && method === 'GET') {
return (handlers.variants ?? (() => ({ unsupported: null, items: [] })))(
Number(variantsList[1]),
)
}
if (variantsList && method === 'POST') {
return (handlers.generateAll ?? (() => undefined))(Number(variantsList[1]))
}
const variantNamed = /^\/v1\/media\/(\d+)\/variants\/([\w-]+)$/.exec(path)
if (variantNamed && method === 'POST') {
return (handlers.generate ?? (() => undefined))(
Number(variantNamed[1]),
variantNamed[2]!,
)
}
if (variantNamed && method === 'DELETE') {
return (handlers.purgeVariant ?? (() => undefined))(
Number(variantNamed[1]),
variantNamed[2]!,
)
}
const usage = /^\/v1\/media\/(\d+)\/usage$/.exec(path)
if (method === 'GET' && usage) {
return (handlers.usage ?? (() => []))(Number(usage[1]))
@@ -324,7 +382,7 @@ export async function mountPage(
handlers: Handlers = {},
url = '/media',
width = DESKTOP_WIDTH,
options: { realApi?: boolean; role?: string } = {},
options: { realApi?: boolean; role?: string; app?: boolean } = {},
) {
setViewportWidth(width)
setActivePinia(createPinia())
@@ -349,7 +407,10 @@ export async function mountPage(
})
}
await router.push(url)
kit.wrapper = mount(MediaView, {
const root = options.app
? defineComponent({ render: () => h(UApp, null, { default: () => h(MediaView) }) })
: MediaView
kit.wrapper = mount(root, {
attachTo: document.body,
global: { plugins: [router, uiPlugin] },
})
@@ -599,3 +660,45 @@ export function uploadRows() {
export function rowTexts() {
return uploadRows().map(textOf)
}
export const STORED_NAME = '1.jpg'
export const NORTH_WALL_BYTES = 4089446
const VARIANT_SPECS: [
string,
number | null,
number | null,
string,
string,
number,
number,
number,
][] = [
['card', 800, null, 'inside', 'webp', 800, 600, 65536],
['hero', 1200, 630, 'cover', 'webp', 1200, 630, 98304],
['og', 1200, 630, 'cover', 'jpeg', 1200, 630, 145408],
['square', 600, 600, 'cover', 'jpeg', 600, 600, 83968],
['thumb', 400, 300, 'cover', 'webp', 400, 300, 18432],
]
export function variantItems(generated: string[] = VARIANT_SPECS.map(([name]) => name)) {
return VARIANT_SPECS.map(
([name, width, height, fit, format, outputWidth, outputHeight, size]) => ({
name,
width,
height,
fit,
format,
output_width: outputWidth,
output_height: outputHeight,
output_format: format,
generated: generated.includes(name),
size: generated.includes(name) ? size : null,
url: `/static/uploadedImages/${STORED_NAME}?v=${name}`,
}),
)
}
export function variantList(generated?: string[]) {
return { unsupported: null, items: variantItems(generated) }
}