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

+6 -4
View File
@@ -4,6 +4,7 @@ import { t } from '@/i18n'
import { computed } from 'vue'
import ActivityActor from '@/components/ActivityActor.vue'
import ActivityBadge from '@/components/ActivityBadge.vue'
import ActivityDetailLine from '@/components/ActivityDetailLine.vue'
import ActivitySentence from '@/components/ActivitySentence.vue'
import { ACTIVITY_SKELETON_CARDS } from '@/composables/useActivity'
import { categoryIcon, outcomeBadge, rowSurface, type ActivityItem } from '@/lib/activity'
@@ -96,10 +97,11 @@ function cardClass(item: ActivityItem) {
:name="categoryIcon(item.category)"
class="mt-0.5 size-4 shrink-0 text-muted"
/>
<span
class="line-clamp-3 min-w-0 flex-1 text-md wrap-anywhere text-default"
>
<ActivitySentence :item="item" />
<span class="flex min-w-0 flex-1 flex-col">
<span class="line-clamp-3 text-md wrap-anywhere text-default">
<ActivitySentence :item="item" />
</span>
<ActivityDetailLine :item="item" wrap />
</span>
</div>
<div class="flex flex-wrap items-center gap-1.5">
+19
View File
@@ -0,0 +1,19 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { ActivityItem } from '@/lib/activity'
import { detailLine } from '@/lib/activitySentence'
const props = defineProps<{ item: ActivityItem; wrap?: boolean }>()
const line = computed(() => detailLine(props.item))
</script>
<template>
<span
v-if="line"
data-testid="activity-detail-line"
class="block text-xs/5 text-muted"
:class="wrap ? 'wrap-anywhere' : 'truncate'"
>{{ line }}</span
>
</template>
@@ -5,6 +5,7 @@ import { computed, ref, watch } from 'vue'
import ActivityActor from '@/components/ActivityActor.vue'
import ActivityBadge from '@/components/ActivityBadge.vue'
import ActivityDiff from '@/components/ActivityDiff.vue'
import ActivityDetailLine from '@/components/ActivityDetailLine.vue'
import ActivitySentence from '@/components/ActivitySentence.vue'
import {
categoryIcon,
@@ -99,6 +100,7 @@ function onOpenChange(isOpen: boolean) {
>
<ActivitySentence :item="current" />
</p>
<ActivityDetailLine :item="current" wrap />
<div class="flex flex-wrap items-center gap-1.5">
<ActivityBadge v-bind="outcomeBadge(current.outcome)" />
<ActivityBadge
+6 -2
View File
@@ -4,6 +4,7 @@ import { t } from '@/i18n'
import { computed } from 'vue'
import ActivityActor from '@/components/ActivityActor.vue'
import ActivityBadge from '@/components/ActivityBadge.vue'
import ActivityDetailLine from '@/components/ActivityDetailLine.vue'
import ActivitySentence from '@/components/ActivitySentence.vue'
import ActivityTargetCell from '@/components/ActivityTargetCell.vue'
import { ACTIVITY_SKELETON_ROWS } from '@/composables/useActivity'
@@ -124,8 +125,11 @@ function rowClass(item: ActivityItem) {
:name="categoryIcon(item.category)"
class="size-4 shrink-0 text-muted"
/>
<span class="truncate text-default">
<ActivitySentence :item="item" />
<span class="flex min-w-0 flex-col">
<span class="truncate text-default">
<ActivitySentence :item="item" />
</span>
<ActivityDetailLine :item="item" />
</span>
<UIcon
v-if="item.security"
+142 -11
View File
@@ -1,13 +1,19 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed, ref, watch } from 'vue'
import { computed, nextTick, ref, watch } from 'vue'
import { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'
import VariantSelect from '@/components/variants/VariantSelect.vue'
import { articleImageId } from '@/lib/articleImage'
import { mediaRevision, withMediaRevision } from '@/lib/mediaRevision'
import { variantOfSrc, withVariant } from '@/lib/variants/blockVariant'
import { formatDimensions } from '@/lib/variants/variantFormat'
import { bareOriginalOption, variantOption } from '@/lib/variants/variantOptions'
import { useVariantCatalogStore } from '@/stores/variantCatalog'
const props = defineProps(nodeViewProps)
const catalog = useVariantCatalogStore()
const imageId = computed(() => articleImageId(props.node))
const showDeleteButton = computed(() => props.selected && imageId.value !== null)
interface ImageNodeAttrs {
@@ -31,11 +37,41 @@ const imageAttrs = computed(() => {
})
const failed = ref(false)
const picking = ref(false)
const pickButton = ref<{ $el: HTMLElement } | null>(null)
const displayAttrs = computed(() => ({
...imageAttrs.value,
src: withMediaRevision(imageAttrs.value.src, mediaRevision.value),
}))
const variantName = computed(() => variantOfSrc(imageAttrs.value.src))
const variant = computed(() =>
variantName.value === null ? undefined : catalog.find(variantName.value),
)
const verdict = computed<'deleted' | 'disabled' | null>(() => {
if (variantName.value === null || !catalog.loaded) {
return null
}
if (!variant.value) {
return 'deleted'
}
return variant.value.enabled ? null : 'disabled'
})
const chip = computed(() =>
variant.value
? `${variant.value.name} · ${formatDimensions(variant.value.width, variant.value.height)}`
: null,
)
const warningTitle = computed(() =>
verdict.value === 'deleted'
? t("Variant '{0}' no longer exists.", [variantName.value ?? ''])
: t("Variant '{0}' is disabled.", [variantName.value ?? '']),
)
const pickOptions = computed(() => [
bareOriginalOption(),
...catalog.enabled.map((entry) => variantOption(entry)),
])
watch(
() => displayAttrs.value.src,
() => {
@@ -49,18 +85,96 @@ function onDeleteClick() {
}
props.extension.options.onRequestRemove(imageId.value)
}
function rewrite(name: string) {
const src = imageAttrs.value.src
if (src) {
props.updateAttributes({ src: withVariant(src, name) })
}
picking.value = false
}
async function onPickOpenChange(open: boolean) {
if (open) {
return
}
picking.value = false
await nextTick()
pickButton.value?.$el?.focus()
}
</script>
<template>
<NodeViewWrapper
as="div"
class="relative block"
:class="[failed ? 'w-full' : 'w-fit', { 'outline-2 outline-primary rounded-md': selected }]"
:class="[
failed || verdict ? 'w-full' : 'w-fit',
{ 'outline-2 outline-primary rounded-md': selected },
]"
data-testid="article-editor-image"
@dragstart.prevent
>
<div
v-if="failed"
v-if="verdict"
data-testid="article-editor-variant-warning"
class="flex flex-col border border-warning font-sans text-sm"
>
<div class="relative aspect-video overflow-hidden border border-default">
<div
class="variant-placeholder absolute inset-0 flex items-center justify-center bg-secondary-200 text-muted opacity-50 dark:bg-secondary-300"
>
<UIcon name="i-lucide-image-off" class="size-10" />
</div>
<span
v-if="chip"
data-testid="variant-chip"
class="absolute top-2 left-2 inline-flex h-5 items-center border border-accented bg-default px-1.5 font-mono text-xs font-medium text-highlighted"
>{{ chip }}</span
>
</div>
<UAlert
role="alert"
color="warning"
variant="soft"
orientation="vertical"
:close="false"
icon="i-lucide-triangle-alert"
:title="warningTitle"
:description="t('This image returns an error on the public site.')"
:ui="{ actions: 'mt-2 w-full flex-col items-stretch gap-2' }"
>
<template #actions>
<div class="flex">
<UButton
ref="pickButton"
color="neutral"
variant="outline"
icon="i-lucide-layers"
data-testid="pick-another-variant"
class="h-11 gap-1.5 border border-accented bg-default px-2.5 text-xs font-medium text-highlighted ring-0 md:h-7"
:ui="{ leadingIcon: 'size-3.5' }"
@mousedown.prevent
@click="picking = true"
>
{{ t('Pick another variant') }}
</UButton>
</div>
<VariantSelect
v-if="picking"
:open="true"
:options="pickOptions"
:model-value="undefined"
:placeholder="t('Variant')"
class="max-w-80"
@update:open="onPickOpenChange"
@update:model-value="rewrite"
/>
</template>
</UAlert>
</div>
<div
v-else-if="failed"
data-testid="article-editor-image-missing"
class="flex min-h-40 flex-col items-center justify-center gap-2 border border-dashed border-accented bg-elevated p-6 text-center font-sans text-sm text-muted"
>
@@ -70,15 +184,22 @@ function onDeleteClick() {
}}</span>
<span>{{ t('It was deleted from the library. Remove it from the article.') }}</span>
</div>
<img
v-else
v-bind="displayAttrs"
draggable="false"
class="block max-w-full"
@error="failed = true"
/>
<div v-else class="relative">
<img
v-bind="displayAttrs"
draggable="false"
class="block max-w-full"
@error="failed = true"
/>
<span
v-if="chip"
data-testid="variant-chip"
class="absolute top-2 left-2 inline-flex h-5 items-center border border-accented bg-default px-1.5 font-mono text-xs font-medium text-highlighted"
>{{ chip }}</span
>
</div>
<UButton
v-if="showDeleteButton || (failed && imageId !== null)"
v-if="showDeleteButton || ((failed || verdict) && imageId !== null)"
data-testid="remove-image-button"
icon="i-lucide-trash-2"
color="neutral"
@@ -92,3 +213,13 @@ function onDeleteClick() {
</UButton>
</NodeViewWrapper>
</template>
<style scoped>
.variant-placeholder {
background-image: repeating-linear-gradient(
135deg,
color-mix(in srgb, var(--ui-text-muted) 12%, transparent) 0 1px,
transparent 1px 12px
);
}
</style>
@@ -4,6 +4,7 @@ import { t } from '@/i18n'
import { computed } from 'vue'
import ConfirmDialog from '@/components/ConfirmDialog.vue'
import MediaBadge from '@/components/MediaBadge.vue'
import VariantRemovalNote from '@/components/variants/VariantRemovalNote.vue'
import type { MediaItem } from '@/composables/useMedia'
import { pluralArticles } from '@/lib/mediaFormat'
@@ -20,6 +21,12 @@ const emit = defineEmits<{ close: [confirmed: boolean] }>()
const total = computed(() => props.items.length)
const imageLabel = computed(() => t(total.value === 1 ? '{0} image' : '{0} images', [total.value]))
const inUse = computed(() => props.items.filter((item) => item.used_in > 0))
const variantCount = computed(() =>
props.items.reduce((sum, item) => sum + (item.variant_count ?? 0), 0),
)
const variantBytes = computed(() =>
props.items.reduce((sum, item) => sum + (item.variant_size ?? 0), 0),
)
const articleCount = computed(() => inUse.value.reduce((sum, item) => sum + item.used_in, 0))
const description = computed(() => {
const usedCount = inUse.value.length
@@ -79,6 +86,7 @@ const description = computed(() => {
<MediaBadge v-else kind="unused" :label="t('Unused')" />
</li>
</ul>
<VariantRemovalNote :count="variantCount" :bytes="variantBytes" />
</template>
</ConfirmDialog>
</template>
+2
View File
@@ -4,6 +4,7 @@ import { t } from '@/i18n'
import { computed } from 'vue'
import ConfirmDialog from '@/components/ConfirmDialog.vue'
import MediaArticleStatusBadge from '@/components/MediaArticleStatusBadge.vue'
import VariantRemovalNote from '@/components/variants/VariantRemovalNote.vue'
import type { MediaItem, MediaUsageItem } from '@/composables/useMedia'
import { pluralArticles } from '@/lib/mediaFormat'
@@ -58,6 +59,7 @@ const description = computed(() =>
<MediaArticleStatusBadge :published="article.published" />
</li>
</ul>
<VariantRemovalNote :count="item.variant_count" :bytes="item.variant_size" />
</template>
</ConfirmDialog>
</template>
+25 -2
View File
@@ -8,6 +8,8 @@ import { ApiError, useApi } from '@/composables/useApi'
import { useLibraryList } from '@/composables/useLibraryList'
import { classifyMediaError, type MediaItem } from '@/composables/useMedia'
import { oldestOf } from '@/composables/useMediaUpload'
import { useCanManageVariants } from '@/composables/useCanManageVariants'
import { useVariantCatalogStore } from '@/stores/variantCatalog'
import { hashFile } from '@/lib/fileHash'
import {
IMAGE_TYPE_REJECTION_TEXT,
@@ -17,6 +19,7 @@ import {
validateImageFile,
} from '@/lib/imageUpload'
import { libraryMatchText } from '@/lib/mediaFormat'
import { insertedUrl } from '@/lib/variants/variantOptions'
import { UNDERLINE_TAB_TRIGGER } from '@/lib/tabStyles'
import {
ASPECT_RATIOS,
@@ -55,7 +58,7 @@ const props = withDefaults(
const emit = defineEmits<{
uploaded: [item: MediaItem]
inserted: [item: MediaItem, alt: string]
inserted: [item: MediaItem, alt: string, src: string]
close: []
}>()
@@ -102,7 +105,9 @@ const tab = ref<Tab>('library')
const existing = ref<MediaItem | null>(null)
const selected = ref<MediaItem | null>(null)
const alt = ref('')
const variant = ref('')
let tabTouched = false
let variantsRequested = false
const naturalWidth = ref(0)
const naturalHeight = ref(0)
@@ -117,6 +122,8 @@ const sourceBitmap = ref<ImageBitmap | null>(null)
const { progress, start, abort } = useImageUpload()
const { request } = useApi()
const library = useLibraryList()
const canManageVariants = useCanManageVariants()
const catalog = useVariantCatalogStore()
let closeTimer: ReturnType<typeof setTimeout> | null = null
const uploadPercent = computed(() => {
@@ -418,11 +425,22 @@ function selectItem(item: MediaItem) {
}
selected.value = item
alt.value = ''
variant.value = ''
requestVariants()
}
function requestVariants() {
if (variantsRequested || !canManageVariants.value) {
return
}
variantsRequested = true
catalog.load()
}
async function searchLibrary(query: string) {
selected.value = null
alt.value = ''
variant.value = ''
await library.search(query)
}
@@ -430,7 +448,7 @@ function insertSelected() {
if (!selected.value) {
return
}
emit('inserted', selected.value, alt.value)
emit('inserted', selected.value, alt.value, insertedUrl(selected.value, variant.value))
open.value = false
}
@@ -710,6 +728,8 @@ watch(open, (isOpen) => {
existing.value = null
selected.value = null
alt.value = ''
variant.value = ''
variantsRequested = false
tabTouched = false
library.reset()
if (props.initialFile) {
@@ -768,6 +788,9 @@ onUnmounted(() => {
<MediaPicker
v-if="onLibraryTab"
v-model:alt="alt"
v-model:variant="variant"
:variants="catalog.status === 'ready' ? catalog.enabled : []"
:variants-ready="catalog.status === 'ready'"
:items="library.items.value"
:status="library.status.value"
:show-skeleton="library.showSkeleton.value"
+5 -1
View File
@@ -3,7 +3,7 @@ import { computed } from 'vue'
const props = withDefaults(
defineProps<{
kind: 'unused' | 'duplicate' | 'used' | 'online' | 'draft'
kind: 'unused' | 'duplicate' | 'used' | 'online' | 'draft' | 'variants'
label: string
size?: 'sm' | 'md'
}>(),
@@ -21,6 +21,10 @@ const badges = {
icon: 'i-lucide-copy',
class: 'border border-(--rc-info-soft) bg-(--rc-info-soft) text-info',
},
variants: {
icon: 'i-lucide-layers',
class: 'border border-(--rc-info-soft) bg-(--rc-info-soft) text-info',
},
used: { icon: undefined, class: OUTLINE },
online: {
icon: 'i-lucide-globe',
+7 -1
View File
@@ -4,7 +4,8 @@ import { t } from '@/i18n'
import MediaBadge from '@/components/MediaBadge.vue'
defineProps<{
item: { duplicate: boolean; used_in: number }
item: { duplicate: boolean; used_in: number; variant_count?: number }
variants?: boolean
}>()
</script>
@@ -12,4 +13,9 @@ defineProps<{
<MediaBadge v-if="item.duplicate" kind="duplicate" :label="t('Duplicate')" />
<MediaBadge v-if="item.used_in > 0" kind="used" :label="t('Used in {0}', [item.used_in])" />
<MediaBadge v-else kind="unused" :label="t('Unused')" />
<MediaBadge
v-if="variants && (item.variant_count ?? 0) > 0"
kind="variants"
:label="item.variant_count === 1 ? t('1 variant') : t('{0} variants', [item.variant_count])"
/>
</template>
+179 -108
View File
@@ -1,10 +1,11 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed } from 'vue'
import { computed, ref, watch } from 'vue'
import { useMediaQuery } from '@vueuse/core'
import MediaArticleStatusBadge from '@/components/MediaArticleStatusBadge.vue'
import MediaThumb from '@/components/MediaThumb.vue'
import MediaVariantsTab from '@/components/variants/MediaVariantsTab.vue'
import type { MediaItem, MediaUsageItem } from '@/composables/useMedia'
import {
formatDimensions,
@@ -14,6 +15,8 @@ import {
joinNames,
pluralArticles,
} from '@/lib/mediaFormat'
import { PANEL_TAB_TRIGGER } from '@/lib/tabStyles'
import { useCanManageVariants } from '@/composables/useCanManageVariants'
const DESKTOP_QUERY = '(min-width: 48rem)'
const ACTION_BUTTON =
@@ -31,10 +34,46 @@ const emit = defineEmits<{
rename: []
delete: []
'review-duplicates': []
gone: []
}>()
const open = defineModel<boolean>('open', { default: false })
const isDesktop = useMediaQuery(DESKTOP_QUERY)
const canManageVariants = useCanManageVariants()
const panelTab = ref<'details' | 'variants'>('details')
const variantsVisited = ref(false)
const tabItems = computed(() => [
{
get label() {
return t('Details')
},
value: 'details',
},
{
get label() {
return t('Variants')
},
value: 'variants',
},
])
const tabModel = computed({
get: () => panelTab.value,
set: (value: string) => {
panelTab.value = value === 'variants' ? 'variants' : 'details'
if (panelTab.value === 'variants') {
variantsVisited.value = true
}
},
})
watch(
() => [open.value, props.item?.id],
() => {
panelTab.value = 'details'
variantsVisited.value = false
},
)
const closeButton = computed(() => ({
color: 'neutral' as const,
@@ -124,126 +163,158 @@ const duplicateAlert = computed(() => {
}"
>
<template #body>
<div v-if="item" class="flex flex-col gap-5">
<MediaThumb
:item="item"
size="xl"
class="aspect-4/3 w-full border border-default md:aspect-16/10"
/>
<div class="flex gap-2 max-md:flex-wrap">
<UButton
<div v-if="item" class="flex flex-col gap-4">
<div
v-if="canManageVariants"
data-testid="panel-tabs"
class="-mx-4 -mt-4 h-11 border-b border-default px-4 md:-mx-5 md:-mt-5 md:mb-1 md:h-10 md:px-5"
>
<UTabs
v-model="tabModel"
:items="tabItems"
variant="link"
color="neutral"
variant="outline"
icon="i-lucide-link"
:class="ACTION_BUTTON"
@click="emit('copy-url')"
>
{{ t('Copy URL') }}
</UButton>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-pencil"
:disabled="offline"
:class="ACTION_BUTTON"
@click="emit('rename')"
>
{{ t('Rename') }}
</UButton>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-trash-2"
:disabled="offline"
:class="ACTION_BUTTON"
class="text-error"
@click="emit('delete')"
>
{{ t('Delete') }}
</UButton>
:content="false"
class="-mb-px"
:ui="{
list: 'gap-5 border-b-0 p-0',
trigger: PANEL_TAB_TRIGGER,
}"
/>
</div>
<UAlert
v-if="duplicateAlert"
data-testid="duplicate-alert"
color="info"
variant="soft"
orientation="vertical"
:close="false"
icon="i-lucide-copy"
:title="duplicateAlert.title"
:description="duplicateAlert.description"
:ui="{ actions: 'mt-2 w-full', description: 'text-wrap' }"
>
<template #actions>
<MediaVariantsTab
v-if="canManageVariants && variantsVisited"
v-show="panelTab === 'variants'"
:key="item.id"
:item="item"
@gone="emit('gone')"
/>
<div v-show="panelTab === 'details'" class="flex flex-col gap-5">
<MediaThumb
:item="item"
size="xl"
class="aspect-4/3 w-full border border-default md:aspect-16/10"
/>
<div class="flex gap-2 max-md:flex-wrap">
<UButton
color="neutral"
variant="outline"
icon="i-lucide-arrow-right"
block
class="h-11 gap-1.5 border border-accented bg-default px-2.5 text-xs text-highlighted ring-0 md:h-7"
:ui="{ leadingIcon: 'size-3.5' }"
@click="emit('review-duplicates')"
icon="i-lucide-link"
:class="ACTION_BUTTON"
@click="emit('copy-url')"
>
{{ t('Review duplicates') }}
{{ t('Copy URL') }}
</UButton>
</template>
</UAlert>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-pencil"
:disabled="offline"
:class="ACTION_BUTTON"
@click="emit('rename')"
>
{{ t('Rename') }}
</UButton>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-trash-2"
:disabled="offline"
:class="ACTION_BUTTON"
class="text-error"
@click="emit('delete')"
>
{{ t('Delete') }}
</UButton>
</div>
<dl class="grid grid-cols-[110px_minmax(0,1fr)] gap-x-3 gap-y-2 text-toned">
<template v-for="row in metadata" :key="row.label">
<dt class="text-muted">{{ row.label }}</dt>
<dd class="m-0 text-highlighted">{{ row.value }}</dd>
</template>
<dt class="text-muted">URL</dt>
<dd class="m-0 truncate font-mono text-xs/5 text-highlighted">
{{ displayUrl }}
</dd>
</dl>
<section class="flex flex-col gap-2">
<h3 class="text-base font-semibold text-highlighted">
{{
item.used_in > 0
? t('Used in {0}', [pluralArticles(item.used_in)])
: t('Not used in any article')
}}
</h3>
<template v-if="item.used_in > 0">
<ul v-if="usage.length > 0" class="border border-default">
<li
v-for="(article, index) in usage"
:key="article.id"
data-testid="usage-row"
class="flex min-h-12 items-center gap-2 px-3 md:min-h-10"
:class="{ 'border-t border-muted': index > 0 }"
<UAlert
v-if="duplicateAlert"
data-testid="duplicate-alert"
color="info"
variant="soft"
orientation="vertical"
:close="false"
icon="i-lucide-copy"
:title="duplicateAlert.title"
:description="duplicateAlert.description"
:ui="{ actions: 'mt-2 w-full', description: 'text-wrap' }"
>
<template #actions>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-arrow-right"
block
class="h-11 gap-1.5 border border-accented bg-default px-2.5 text-xs text-highlighted ring-0 md:h-7"
:ui="{ leadingIcon: 'size-3.5' }"
@click="emit('review-duplicates')"
>
<RouterLink
:to="`/article/${article.id}/edit`"
class="min-w-0 flex-1 truncate font-medium text-highlighted underline underline-offset-3"
>
{{ article.title }}
</RouterLink>
<MediaArticleStatusBadge :published="article.published" size="md" />
<UIcon
name="i-lucide-arrow-up-right"
class="size-3.5 shrink-0 text-muted"
/>
</li>
</ul>
<p class="text-xs text-muted">
{{ t('Review duplicates') }}
</UButton>
</template>
</UAlert>
<dl class="grid grid-cols-[110px_minmax(0,1fr)] gap-x-3 gap-y-2 text-toned">
<template v-for="row in metadata" :key="row.label">
<dt class="text-muted">{{ row.label }}</dt>
<dd class="m-0 text-highlighted">{{ row.value }}</dd>
</template>
<dt class="text-muted">URL</dt>
<dd class="m-0 truncate font-mono text-xs/5 text-highlighted">
{{ displayUrl }}
</dd>
</dl>
<section class="flex flex-col gap-2">
<h3 class="text-base font-semibold text-highlighted">
{{
t(
'Counted from the text of your articles each time you open this page.',
)
item.used_in > 0
? t('Used in {0}', [pluralArticles(item.used_in)])
: t('Not used in any article')
}}
</h3>
<template v-if="item.used_in > 0">
<ul v-if="usage.length > 0" class="border border-default">
<li
v-for="(article, index) in usage"
:key="article.id"
data-testid="usage-row"
class="flex min-h-12 items-center gap-2 px-3 md:min-h-10"
:class="{ 'border-t border-muted': index > 0 }"
>
<RouterLink
:to="`/article/${article.id}/edit`"
class="min-w-0 flex-1 truncate font-medium text-highlighted underline underline-offset-3"
>
{{ article.title }}
</RouterLink>
<MediaArticleStatusBadge
:published="article.published"
size="md"
/>
<UIcon
name="i-lucide-arrow-up-right"
class="size-3.5 shrink-0 text-muted"
/>
</li>
</ul>
<p class="text-xs text-muted">
{{
t(
'Counted from the text of your articles each time you open this page.',
)
}}
</p>
</template>
<p v-else class="text-muted">
{{ t('This image is safe to delete. No article shows it.') }}
</p>
</template>
<p v-else class="text-muted">
{{ t('This image is safe to delete. No article shows it.') }}
</p>
</section>
</section>
</div>
</div>
</template>
</USlideover>
+15 -1
View File
@@ -6,7 +6,7 @@ import { computed } from 'vue'
const QUERY_MAX_LENGTH = 40
const props = defineProps<{
variant: 'first-run' | 'no-results' | 'no-duplicates'
variant: 'first-run' | 'no-results' | 'no-duplicates' | 'no-variants'
query?: string
filterLabel?: string
offline?: boolean
@@ -42,6 +42,20 @@ const current = computed(() => {
action: t('Back to all images'),
}
}
if (props.variant === 'no-variants') {
return {
icon: 'i-lucide-layers',
get title() {
return t('No images with variants')
},
get description() {
return t(
'Variants are generated when an image is requested with ?v=<name>, or from its Variants tab.',
)
},
action: t('Show all images'),
}
}
return {
icon: 'i-lucide-search',
get title() {
+8 -4
View File
@@ -6,7 +6,7 @@ import MediaCardBadges from '@/components/MediaCardBadges.vue'
import MediaCheckbox from '@/components/MediaCheckbox.vue'
import MediaThumb from '@/components/MediaThumb.vue'
import type { MediaItem } from '@/composables/useMedia'
import { accessibleName, formatDimensions, formatSize } from '@/lib/mediaFormat'
import { accessibleName, formatDimensions, formatSize, totalMeta } from '@/lib/mediaFormat'
const SELECTED_CARD =
'border-primary bg-secondary-200 text-primary-900 inset-ring-1 inset-ring-primary dark:bg-secondary-300'
@@ -16,6 +16,7 @@ const props = defineProps<{
items: MediaItem[]
columns: number
selected: number[]
totalSize?: boolean
}>()
const emit = defineEmits<{
@@ -108,12 +109,15 @@ function onKeyup(event: KeyboardEvent) {
<span
class="truncate text-xs/5"
:class="selected.includes(item.id) ? 'text-primary-600' : 'text-muted'"
>{{ formatSize(item.size) }} ·
{{ formatDimensions(item.width, item.height) }}</span
>{{
totalSize
? totalMeta(item)
: `${formatSize(item.size)} · ${formatDimensions(item.width, item.height)}`
}}</span
>
</span>
<span class="flex flex-wrap gap-1">
<MediaCardBadges :item="item" />
<MediaCardBadges :item="item" variants />
</span>
</span>
</button>
+11
View File
@@ -4,7 +4,9 @@ import { t } from '@/i18n'
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import { useMediaQuery } from '@vueuse/core'
import MediaThumb from '@/components/MediaThumb.vue'
import VariantPickerField from '@/components/variants/VariantPickerField.vue'
import type { LibraryStatus } from '@/composables/useLibraryList'
import type { ImageVariant } from '@/composables/useImageVariants'
import type { MediaItem } from '@/composables/useMedia'
import { accessibleName, formatDimensions, formatSize } from '@/lib/mediaFormat'
@@ -34,6 +36,8 @@ const props = defineProps<{
firstNewId: number | null
inArticleIds: number[]
selected: MediaItem | null
variants?: ImageVariant[]
variantsReady?: boolean
}>()
const emit = defineEmits<{
@@ -45,6 +49,7 @@ const emit = defineEmits<{
}>()
const alt = defineModel<string>('alt', { default: '' })
const variant = defineModel<string>('variant', { default: '' })
const isDesktop = useMediaQuery(DESKTOP_QUERY)
const grid = ref<HTMLElement | null>(null)
@@ -323,6 +328,12 @@ onBeforeUnmount(clearDebounce)
>
</div>
</div>
<VariantPickerField
v-model:variant="variant"
:image="selected"
:variants="variants ?? []"
:ready="variantsReady ?? false"
/>
<UFormField
:label="t('Alt text (optional)')"
help="Describes the image for people who use a screen reader, and shows if it doesn't load. Leave it empty if the image is only decoration."
+35 -6
View File
@@ -2,11 +2,20 @@
import { t, formatNumber } from '@/i18n'
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { useMediaQuery } from '@vueuse/core'
import MediaVariantsFilter from '@/components/MediaVariantsFilter.vue'
import type { MediaCounts } from '@/composables/useMedia'
import type { MediaControls, MediaFilter, MediaSort, MediaView } from '@/lib/mediaQuery'
import type {
MediaControls,
MediaFilter,
MediaSort,
MediaVariantsFilter as VariantsFilterValue,
MediaView,
} from '@/lib/mediaQuery'
import { UNDERLINE_TAB_TRIGGER } from '@/lib/tabStyles'
const SEARCH_DEBOUNCE_MS = 120
const DESKTOP_QUERY = '(min-width: 48rem)'
const SORT_LABELS: Record<MediaSort, string> = {
get newest() {
@@ -21,6 +30,9 @@ const SORT_LABELS: Record<MediaSort, string> = {
get largest() {
return t('Largest')
},
get total_size() {
return t('Largest total size (original + variants)')
},
}
const VIEW_OPTIONS: { value: MediaView; icon: string; label: string }[] = [
@@ -54,10 +66,12 @@ const emit = defineEmits<{
'update:q': [value: string]
'update:filter': [value: MediaFilter]
'update:sort': [value: MediaSort]
'update:variants': [value: VariantsFilterValue]
'update:view': [value: MediaView]
purge: []
}>()
const isDesktop = useMediaQuery(DESKTOP_QUERY)
const searchText = ref(props.controls.q)
let debounceTimer: ReturnType<typeof setTimeout> | null = null
@@ -128,9 +142,13 @@ const tab = computed({
},
})
function sortLabel(value: MediaSort) {
return value === 'total_size' && !isDesktop.value ? t('Largest total size') : SORT_LABELS[value]
}
const sortItems = computed(() =>
(Object.keys(SORT_LABELS) as MediaSort[]).map((value) => ({
label: SORT_LABELS[value],
label: sortLabel(value),
type: 'checkbox' as const,
checked: props.controls.sort === value,
onUpdateChecked: () => emit('update:sort', value),
@@ -197,19 +215,30 @@ const sortItems = computed(() =>
</template>
</UInput>
<MediaVariantsFilter
:model-value="controls.variants"
class="order-3 w-full md:order-none md:mb-1.5 md:w-auto"
@update:model-value="emit('update:variants', $event)"
/>
<div
class="order-3 flex flex-wrap gap-x-2 gap-y-3 md:order-none md:mb-1.5 md:flex-nowrap md:gap-2"
class="order-4 flex flex-wrap gap-x-2 gap-y-3 md:order-none md:mb-1.5 md:flex-nowrap md:gap-2"
>
<UDropdownMenu :items="sortItems" :content="{ align: 'start' }">
<UDropdownMenu
:items="sortItems"
:content="{ align: 'start' }"
:ui="{ content: 'md:w-85' }"
>
<UButton
color="neutral"
variant="outline"
trailing-icon="i-lucide-chevron-down"
:aria-label="t('Sort')"
class="h-11 flex-1 justify-between border border-accented bg-default px-2.5 text-sm font-normal text-highlighted ring-0 md:h-8 md:w-32 md:flex-none"
class="h-11 flex-1 justify-between border border-accented bg-default px-2.5 text-sm font-normal text-highlighted ring-0 md:h-8 md:flex-none"
:class="controls.sort === 'total_size' ? 'md:w-auto' : 'md:w-32'"
:ui="{ trailingIcon: 'size-3.5 text-muted' }"
>
{{ SORT_LABELS[controls.sort] }}
{{ sortLabel(controls.sort) }}
</UButton>
</UDropdownMenu>
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { t } from '@/i18n'
import type { MediaVariantsFilter } from '@/lib/mediaQuery'
const SEGMENT =
'h-10.5 flex-1 justify-center rounded-none px-2.5 text-xs font-medium whitespace-nowrap ring-0 md:h-7.5 md:flex-none md:px-3 md:text-sm'
defineProps<{ modelValue: MediaVariantsFilter }>()
const emit = defineEmits<{ 'update:modelValue': [value: MediaVariantsFilter] }>()
const OPTIONS: { value: MediaVariantsFilter; label: () => string }[] = [
{ value: 'all', label: () => t('All') },
{ value: 'with', label: () => t('With variants') },
{ value: 'without', label: () => t('Without') },
]
</script>
<template>
<div
role="group"
:aria-label="t('Variants')"
data-testid="variants-filter"
class="flex shrink-0 border border-accented bg-default"
>
<UButton
v-for="option in OPTIONS"
:key="option.value"
:color="option.value === modelValue ? 'primary' : 'neutral'"
:variant="option.value === modelValue ? 'solid' : 'ghost'"
:aria-pressed="option.value === modelValue"
:class="[SEGMENT, option.value === modelValue ? '' : 'text-toned']"
@click="emit('update:modelValue', option.value)"
>
{{ option.label() }}
</UButton>
</div>
</template>
+2 -1
View File
@@ -82,7 +82,8 @@ export const Host = defineComponent({
return {
open,
onUploaded: (item: MediaItem) => emit('uploaded', item),
onInserted: (item: MediaItem, alt: string) => emit('inserted', item, alt),
onInserted: (item: MediaItem, alt: string, src: string) =>
emit('inserted', item, alt, src),
onClose: () => emit('close'),
}
},
@@ -0,0 +1,224 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed, nextTick, onMounted, ref } from 'vue'
import { useMediaQuery } from '@vueuse/core'
import { useLocalizedToast } from '@/i18n/presentation'
import VariantImageRow from '@/components/variants/VariantImageRow.vue'
import VariantOriginalBlock from '@/components/variants/VariantOriginalBlock.vue'
import VariantPreviewDialog from '@/components/variants/VariantPreviewDialog.vue'
import { useImageVariantRows } from '@/composables/useImageVariantRows'
import type { MediaItem } from '@/composables/useMedia'
import type { MediaVariantItem } from '@/composables/useMediaVariants'
const ROOMY_QUERY = '(min-width: 40rem)'
const SKELETON_ROWS = 5
const TOAST_DURATION_MS = 5000
const SETTINGS_VARIANTS_PATH = '/settings/media/variants'
const RETRY_BUTTON =
'h-11 gap-1.5 border border-accented bg-default px-2.5 text-xs text-highlighted ring-0 md:h-7'
const props = defineProps<{ item: MediaItem }>()
const emit = defineEmits<{ gone: [] }>()
const toast = useLocalizedToast()
const roomy = useMediaQuery(ROOMY_QUERY)
const rows = useImageVariantRows(props.item.id, () => emit('gone'))
const previewOpen = ref(false)
const previewTarget = ref<MediaVariantItem | null>(null)
let previewOpener: HTMLElement | null = null
const total = computed(() => rows.items.value.length)
const showList = computed(
() => rows.status.value === 'ready' && rows.unsupported.value === null && total.value > 0,
)
const showEmpty = computed(
() => rows.status.value === 'ready' && rows.unsupported.value === null && total.value === 0,
)
const generateAllDisabled = computed(() => rows.allGenerated.value || rows.anyBusy.value)
onMounted(rows.load)
async function copyUrl(variant: MediaVariantItem) {
try {
await navigator.clipboard.writeText(`${window.location.origin}${variant.url}`)
} catch {
return
}
toast.add(() => ({
id: `media-variant-url-copied-${props.item.id}-${variant.name}`,
color: 'success' as const,
icon: 'i-lucide-circle-check',
get title() {
return t('URL copied')
},
get description() {
return t('Paste it wherever you need the image address.')
},
duration: TOAST_DURATION_MS,
}))
}
function openPreview(variant: MediaVariantItem, opener: HTMLElement) {
previewOpener = opener
previewTarget.value = variant
previewOpen.value = true
}
async function onPreviewOpenChange(open: boolean) {
previewOpen.value = open
if (open) {
return
}
await nextTick()
previewOpener?.focus()
}
</script>
<template>
<div data-testid="variants-tab" class="flex flex-col gap-4">
<section
v-if="rows.status.value === 'loading' && rows.showSkeleton.value"
:aria-label="t('Loading variants')"
aria-busy="true"
class="border border-default"
>
<div
v-for="row in SKELETON_ROWS"
:key="row"
data-testid="variant-skeleton-row"
class="flex flex-col gap-2 px-3 py-2.5"
:class="row > 1 ? 'border-t border-muted' : ''"
>
<USkeleton class="h-3.25 w-[30%] rounded-none bg-accented" />
<USkeleton class="h-2.75 w-[55%] rounded-none bg-accented" />
</div>
</section>
<UAlert
v-else-if="rows.status.value === 'error'"
role="alert"
color="error"
variant="soft"
orientation="vertical"
:close="false"
icon="i-lucide-circle-x"
:title="t('Couldn\'t load variants')"
:description="t('Check your connection and try again.')"
:ui="{ actions: 'mt-2' }"
>
<template #actions>
<UButton
color="neutral"
variant="outline"
icon="i-lucide-rotate-cw"
:class="RETRY_BUTTON"
:ui="{ leadingIcon: 'size-3.5' }"
@click="rows.load"
>
{{ t('Try again') }}
</UButton>
</template>
</UAlert>
<template v-else-if="rows.status.value === 'ready'">
<VariantOriginalBlock :item="item" />
<UAlert
v-if="rows.unsupported.value !== null"
color="info"
variant="soft"
:close="false"
icon="i-lucide-info"
:title="t('Variants aren\'t generated for this format.')"
:description="t('SVG images are served as they are.')"
/>
<UEmpty
v-else-if="showEmpty"
variant="naked"
icon="i-lucide-layers"
:title="t('No variants defined')"
:description="
t('Define a variant in Settings to get resized copies of this image.')
"
:ui="{
root: 'gap-3 border border-default bg-default px-6 py-7',
header: 'gap-3',
avatar: 'mb-0 size-11 rounded-none bg-elevated text-toned',
title: 'text-[0.9375rem] font-semibold',
description: 'max-w-95 text-muted text-pretty',
}"
>
<template #actions>
<RouterLink
:to="SETTINGS_VARIANTS_PATH"
class="inline-flex min-h-11 items-center gap-1 font-medium text-highlighted underline underline-offset-3 sm:min-h-5"
>
{{ t('Settings → Media → Variants') }}
<UIcon name="i-lucide-arrow-up-right" class="size-3.5" />
</RouterLink>
</template>
</UEmpty>
<template v-else-if="showList">
<div class="flex items-center gap-3">
<div class="flex flex-1 flex-col">
<span class="font-semibold text-highlighted">{{
t('{0} of {1} generated', [rows.generatedCount.value, total])
}}</span>
<span
v-if="rows.generatedCount.value === 0 && !rows.anyBusy.value"
class="text-xs/5 text-muted"
>{{ t('Nothing generated yet.') }}</span
>
<span v-if="rows.anyBusy.value" class="text-xs/5 text-info">{{
t('Generating variants…')
}}</span>
</div>
<UButton
color="neutral"
variant="outline"
:icon="rows.anyBusy.value ? 'i-lucide-loader-circle' : 'i-lucide-zap'"
:disabled="generateAllDisabled"
class="h-11 border border-accented bg-default px-3 text-sm font-medium text-highlighted ring-0 sm:h-8"
:ui="{
leadingIcon: rows.anyBusy.value ? 'size-4 animate-spin' : 'size-4',
}"
@click="rows.generateAll"
>
{{ rows.anyBusy.value ? t('Generating…') : t('Generate all') }}
</UButton>
</div>
<ul class="border border-default">
<VariantImageRow
v-for="(row, index) in rows.rows.value"
:key="row.item.name"
:row="row"
:original-size="item.size"
:roomy="roomy"
:first="index === 0"
@copy="copyUrl(row.item)"
@preview="openPreview(row.item, $event)"
@purge="rows.purge(row.item.name)"
@generate="rows.generateOne(row.item.name)"
/>
</ul>
</template>
</template>
<p role="status" aria-live="polite" data-testid="variants-announcer" class="sr-only">
{{ rows.announcement.value }}
</p>
<VariantPreviewDialog
v-if="previewTarget"
:open="previewOpen"
:variant="previewTarget"
:original="item"
@update:open="onPreviewOpenChange"
/>
</div>
</template>
@@ -0,0 +1,140 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed } from 'vue'
import VariantStatusBadge from '@/components/variants/VariantStatusBadge.vue'
import type { VariantRow } from '@/composables/useImageVariantRows'
import type { VariantFormat } from '@/composables/useImageVariants'
import { causeText } from '@/lib/variants/variantCauses'
import { formatLabel, formatVariantSize } from '@/lib/variants/variantFormat'
import { signedPercent } from '@/lib/variants/variantSaving'
type ActionKey = 'copy' | 'preview' | 'purge' | 'generate' | 'retry'
const props = defineProps<{
row: VariantRow
originalSize: number
roomy: boolean
first: boolean
}>()
const emit = defineEmits<{
copy: [element: HTMLElement]
preview: [element: HTMLElement]
purge: []
generate: []
}>()
const ACTIONS: Record<ActionKey, { icon: string; label: () => string }> = {
copy: { icon: 'i-lucide-link', label: () => t('Copy URL') },
preview: { icon: 'i-lucide-eye', label: () => t('Preview') },
purge: { icon: 'i-lucide-eraser', label: () => t('Purge') },
generate: { icon: 'i-lucide-zap', label: () => t('Generate now') },
retry: { icon: 'i-lucide-rotate-cw', label: () => t('Retry') },
}
const ACTIONS_BY_STATUS: Record<VariantRow['status'], ActionKey[]> = {
generated: ['copy', 'preview', 'purge'],
missing: ['copy', 'generate'],
busy: [],
failed: ['retry'],
}
const item = computed(() => props.row.item)
const generated = computed(() => props.row.status === 'generated')
const actions = computed(() =>
ACTIONS_BY_STATUS[props.row.status].map((key) => ({ key, ...ACTIONS[key] })),
)
const meta = computed(() => {
const base = `${item.value.output_width}×${item.value.output_height} · ${formatLabel(item.value.output_format as VariantFormat)}`
if (!generated.value || item.value.size === null) {
return base
}
return `${base} · ${formatVariantSize(item.value.size)} ·`
})
const saving = computed(() =>
t('{0} vs original', [signedPercent(props.originalSize, item.value.size ?? 0)]),
)
function run(key: ActionKey, event: Event) {
const element = event.currentTarget as HTMLElement
if (key === 'copy') {
emit('copy', element)
} else if (key === 'preview') {
emit('preview', element)
} else if (key === 'purge') {
emit('purge')
} else {
emit('generate')
}
}
</script>
<template>
<li
data-testid="variant-row"
:data-variant="item.name"
class="flex flex-col gap-2 px-3 py-2.5 sm:gap-1"
:class="[
row.status === 'busy' ? 'bg-elevated' : 'bg-default',
first ? '' : 'border-t border-muted',
]"
>
<div class="flex items-center gap-2">
<span class="font-mono text-sm font-medium text-highlighted">{{ item.name }}</span>
<VariantStatusBadge :status="row.status" />
<span class="flex-1" />
<div v-if="roomy && actions.length > 0" class="flex gap-1">
<template v-for="action in actions" :key="action.key">
<UButton
v-if="action.key === 'retry'"
color="neutral"
variant="outline"
:icon="action.icon"
class="h-7 gap-1.5 border border-accented bg-default px-2.5 text-xs font-medium text-highlighted ring-0"
:ui="{ leadingIcon: 'size-3.5' }"
@click="run(action.key, $event)"
>
{{ action.label() }}
</UButton>
<UTooltip v-else :text="action.label()">
<UButton
color="neutral"
variant="outline"
:icon="action.icon"
:aria-label="action.label()"
class="size-7 justify-center border border-accented bg-default p-0 text-highlighted ring-0"
:ui="{ leadingIcon: 'size-4' }"
@click="run(action.key, $event)"
/>
</UTooltip>
</template>
</div>
</div>
<div class="flex flex-wrap gap-1 text-xs/5 text-toned">
<span>{{ meta }}</span>
<span v-if="generated" class="font-medium text-success">{{ saving }}</span>
</div>
<div
v-if="row.status === 'failed' && row.cause"
class="flex items-center gap-1.5 text-xs/5 text-error"
>
<UIcon name="i-lucide-circle-alert" class="size-3.5 shrink-0" />
<span>{{ causeText(row.cause) }}</span>
</div>
<div v-if="!roomy && actions.length > 0" class="flex flex-wrap gap-2">
<UButton
v-for="action in actions"
:key="action.key"
color="neutral"
variant="outline"
:icon="action.icon"
class="h-11 gap-1.5 border border-accented bg-default px-3 text-sm font-medium text-highlighted ring-0"
:ui="{ leadingIcon: 'size-4' }"
@click="run(action.key, $event)"
>
{{ action.label() }}
</UButton>
</div>
</li>
</template>
@@ -0,0 +1,26 @@
<script setup lang="ts">
import { t } from '@/i18n'
import MediaThumb from '@/components/MediaThumb.vue'
import type { MediaItem } from '@/composables/useMedia'
import { formatDimensions, formatSize, formatType } from '@/lib/mediaFormat'
defineProps<{ item: MediaItem }>()
</script>
<template>
<div
data-testid="variants-original"
class="flex items-center gap-3 border border-default bg-muted p-3"
>
<MediaThumb :item="item" size="md" class="h-13.5 w-18 border border-default" />
<div class="flex min-w-0 flex-col">
<span class="text-xs/5 text-muted">{{ t('Original · kept untouched') }}</span>
<span class="truncate font-semibold text-highlighted">{{ item.filename }}</span>
<span class="text-xs/5 text-toned">
{{ formatType(item.content_type) }} ·
{{ formatDimensions(item.width, item.height) }} · {{ formatSize(item.size) }}
</span>
</div>
</div>
</template>
@@ -0,0 +1,34 @@
<script setup lang="ts">
import { ref } from 'vue'
import MediaThumb from '@/components/MediaThumb.vue'
defineProps<{
src: string
width: number
height: number
contentType: string
sha256: string
}>()
const failed = ref(false)
</script>
<template>
<MediaThumb
v-if="failed"
data-testid="pane-placeholder"
:item="{ url: '', content_type: contentType, sha256 }"
size="lg"
class="shrink-0"
:style="{ width: `${width}px`, height: `${height}px` }"
/>
<img
v-else
:src="src"
alt=""
:width="width"
:height="height"
class="block max-w-none shrink-0"
@error="failed = true"
/>
</template>
@@ -0,0 +1,61 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed } from 'vue'
import VariantSelect from '@/components/variants/VariantSelect.vue'
import type { ImageVariant } from '@/composables/useImageVariants'
import type { MediaItem } from '@/composables/useMedia'
import {
buildOptions,
insertedUrl,
isVector,
ORIGINAL_OPTION_VALUE,
} from '@/lib/variants/variantOptions'
const LINK_TOKEN = '\u0000'
const SETTINGS_VARIANTS_PATH = '/settings/media/variants'
const props = defineProps<{
image: MediaItem
variants: ImageVariant[]
ready: boolean
}>()
const variant = defineModel<string>('variant', { default: ORIGINAL_OPTION_VALUE })
const options = computed(() => buildOptions(props.image, props.variants))
const vector = computed(() => isVector(props.image))
const noVariants = computed(() => props.ready && !vector.value && props.variants.length === 0)
const url = computed(() => insertedUrl(props.image, variant.value))
const helpParts = computed(() =>
t('No variants defined. Add one in {0}.', [LINK_TOKEN]).split(LINK_TOKEN),
)
</script>
<template>
<UFormField
:label="t('Variant')"
name="variant"
:ui="{
label: 'font-medium text-highlighted',
help: 'text-xs/5 text-muted',
}"
data-testid="variant-field"
>
<VariantSelect v-model="variant" :options="options" />
<template #help>
<span v-if="noVariants" class="flex items-center gap-1.5">
<UIcon name="i-lucide-info" class="size-3.5 shrink-0" />
<span data-testid="variant-help"
>{{ helpParts[0]
}}<RouterLink
:to="SETTINGS_VARIANTS_PATH"
class="font-medium text-highlighted underline underline-offset-3"
>{{ t('Settings → Media → Variants') }}</RouterLink
>{{ helpParts[1] }}</span
>
</span>
<span v-else data-testid="variant-url" class="font-mono">{{ url }}</span>
</template>
</UFormField>
</template>
@@ -0,0 +1,109 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed } from 'vue'
import VariantPaneImage from '@/components/variants/VariantPaneImage.vue'
import type { MediaItem } from '@/composables/useMedia'
import type { MediaVariantItem } from '@/composables/useMediaVariants'
import type { VariantFormat } from '@/composables/useImageVariants'
import { formatSize, formatType } from '@/lib/mediaFormat'
import { formatLabel, formatVariantSize } from '@/lib/variants/variantFormat'
import { savesPercent } from '@/lib/variants/variantSaving'
const VARIANT_TONE_HASH = '1'
const PANE =
'flex overflow-auto border border-default bg-muted h-45 items-start justify-start sm:h-75 sm:items-center sm:justify-center'
const props = defineProps<{ variant: MediaVariantItem; original: MediaItem }>()
const open = defineModel<boolean>('open', { default: false })
const variantSize = computed(() => props.variant.size ?? 0)
const variantTitle = computed(
() =>
`${props.variant.name} · ${props.variant.output_width}×${props.variant.output_height} · ${formatLabel(props.variant.output_format as VariantFormat)}`,
)
const variantSub = computed(() =>
t('{0} · saves {1}%', [
formatVariantSize(variantSize.value),
savesPercent(props.original.size, variantSize.value),
]),
)
const originalTitle = computed(
() =>
`${t('Original')} · ${props.original.width ?? 0}×${props.original.height ?? 0} · ${formatType(props.original.content_type)}`,
)
</script>
<template>
<UModal
v-model:open="open"
:title="t('Preview: {0}', [variant.name])"
:description="t('Both images are shown at actual size. Scroll to pan.')"
:ui="{
content:
'sm:top-20 sm:translate-y-0 sm:max-w-220 max-sm:!inset-x-4 max-sm:!top-auto max-sm:!bottom-4 max-sm:!w-auto max-sm:!max-w-none max-sm:!translate-x-0 max-sm:!translate-y-0 divide-y-0 shadow-(--shadow-modal) ring-0',
header: 'min-h-0 px-6 pt-5 pb-0 sm:px-6',
close: 'top-5 end-6',
title: 'text-lg/6 font-semibold',
description: 'sr-only',
body: 'px-6 pt-5 pb-0 sm:px-6 sm:pt-5 sm:pb-0',
footer: 'px-6 py-5 sm:px-6',
}"
>
<template #body>
<div class="flex flex-col gap-3">
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div class="flex min-w-0 flex-col gap-2">
<div :class="PANE" data-testid="preview-variant-pane">
<VariantPaneImage
:src="variant.url"
:width="variant.output_width"
:height="variant.output_height"
:content-type="original.content_type"
:sha256="VARIANT_TONE_HASH"
/>
</div>
<div class="flex flex-col">
<span class="font-semibold text-highlighted">{{ variantTitle }}</span>
<span class="text-xs/5 text-toned">{{ variantSub }}</span>
</div>
</div>
<div class="flex min-w-0 flex-col gap-2">
<div :class="PANE" data-testid="preview-original-pane">
<VariantPaneImage
:src="original.url"
:width="original.width ?? 0"
:height="original.height ?? 0"
:content-type="original.content_type"
:sha256="original.sha256"
/>
</div>
<div class="flex flex-col">
<span class="font-semibold text-highlighted">{{ originalTitle }}</span>
<span class="text-xs/5 text-toned">{{
formatSize(original.size)
}}</span>
</div>
</div>
</div>
<p class="text-xs/5 text-muted">
{{ t('Both images are shown at actual size. Scroll to pan.') }}
</p>
</div>
</template>
<template #footer>
<div class="flex w-full flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<UButton
color="neutral"
variant="outline"
block
class="h-11 justify-center border border-accented bg-default text-sm text-highlighted ring-0 sm:h-8 sm:w-auto sm:px-3"
@click="open = false"
>
{{ t('Close') }}
</UButton>
</div>
</template>
</UModal>
</template>
@@ -0,0 +1,20 @@
<script setup lang="ts">
import { removalNote } from '@/lib/mediaFormat'
defineProps<{ count: number; bytes: number }>()
</script>
<template>
<UAlert
v-if="count > 0"
data-testid="variant-removal-note"
color="warning"
variant="soft"
icon="i-lucide-layers"
:title="removalNote(count, bytes)"
:ui="{
root: 'items-center px-3 py-2.5',
title: 'font-medium text-highlighted',
}"
/>
</template>
@@ -0,0 +1,72 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed } from 'vue'
import { ORIGINAL_OPTION_VALUE, type VariantOption } from '@/lib/variants/variantOptions'
const ORIGINAL_ITEM_VALUE = '@original'
const props = defineProps<{
options: VariantOption[]
modelValue?: string
id?: string
placeholder?: string
ariaLabel?: string
}>()
const emit = defineEmits<{ 'update:modelValue': [value: string] }>()
const open = defineModel<boolean>('open', { default: false })
function toItemValue(value: string) {
return value === ORIGINAL_OPTION_VALUE ? ORIGINAL_ITEM_VALUE : value
}
const items = computed(() =>
props.options.map((option) => ({ ...option, value: toItemValue(option.value) })),
)
const current = computed(() =>
props.modelValue === undefined ? undefined : toItemValue(props.modelValue),
)
function choose(value: string) {
emit('update:modelValue', value === ORIGINAL_ITEM_VALUE ? ORIGINAL_OPTION_VALUE : value)
}
</script>
<template>
<USelectMenu
v-model:open="open"
:model-value="current"
:items="items"
value-key="value"
label-key="label"
:id="id"
:placeholder="placeholder"
:search-input="false"
:aria-label="ariaLabel ?? t('Variant')"
color="neutral"
variant="outline"
data-testid="variant-select"
class="w-full"
:ui="{
base: 'h-11 rounded-none border border-accented bg-default px-3 text-lg ring-0 data-[state=open]:border-primary data-[state=open]:ring-1 data-[state=open]:ring-primary md:h-10 md:text-sm',
trailingIcon: 'size-4 text-muted',
content: 'min-w-(--reka-combobox-trigger-width)',
item: 'min-h-11 ps-2 text-lg md:min-h-9 md:text-sm',
itemLeadingIcon: 'hidden',
itemTrailingIcon: 'hidden',
}"
@update:model-value="choose($event as string)"
>
<template #item-leading="{ item }">
<span class="flex size-4 items-center justify-center">
<UIcon
v-if="(item as VariantOption).value === current"
name="i-lucide-check"
class="size-3.5"
/>
</span>
</template>
</USelectMenu>
</template>
@@ -0,0 +1,49 @@
<script setup lang="ts">
import { t } from '@/i18n'
import { computed } from 'vue'
import type { RowStatus } from '@/composables/useImageVariantRows'
const props = defineProps<{ status: RowStatus }>()
const BADGES = {
generated: {
icon: 'i-lucide-circle-check',
class: 'border border-(--rc-success-soft) bg-(--rc-success-soft) text-success',
label: () => t('Generated'),
},
missing: {
icon: 'i-lucide-circle-dashed',
class: 'border border-accented bg-transparent text-toned',
label: () => t('Not generated'),
},
busy: {
icon: 'i-lucide-loader-circle',
class: 'border border-(--rc-info-soft) bg-(--rc-info-soft) text-info',
label: () => t('Generating'),
},
failed: {
icon: 'i-lucide-circle-x',
class: 'border border-(--rc-error-soft) bg-(--rc-error-soft) text-error',
label: () => t('Failed'),
},
} as const
const badge = computed(() => BADGES[props.status])
</script>
<template>
<UBadge
color="neutral"
variant="soft"
:icon="badge.icon"
:class="badge.class"
:data-status="status"
:ui="{
base: 'h-5 gap-1 px-1.5 py-0 text-xs whitespace-nowrap',
leadingIcon: status === 'busy' ? 'size-3 animate-spin' : 'size-3',
}"
>
{{ badge.label() }}
</UBadge>
</template>
@@ -0,0 +1,7 @@
import { computed } from 'vue'
import { useSessionStore } from '@/stores/session'
export function useCanManageVariants() {
const session = useSessionStore()
return computed(() => session.session?.role === 'owner' || session.session?.role === 'admin')
}
+265
View File
@@ -0,0 +1,265 @@
import { computed, onBeforeUnmount, ref } from 'vue'
import { t } from '@/i18n'
import { useLocalizedToast } from '@/i18n/presentation'
import { ApiError } from '@/composables/useApi'
import { MEDIA_SKELETON_DELAY_MS, classifyMediaError } from '@/composables/useMedia'
import {
useMediaVariants,
type MediaVariantItem,
type VariantCause,
} from '@/composables/useMediaVariants'
import { formatSize } from '@/lib/mediaFormat'
import { causeOfStatus, causeText } from '@/lib/variants/variantCauses'
import { toastCopyFor } from '@/lib/variants/variantErrors'
export type RowStatus = 'generated' | 'missing' | 'busy' | 'failed'
export type TabStatus = 'loading' | 'ready' | 'error'
export interface VariantRow {
item: MediaVariantItem
status: RowStatus
cause: VariantCause | null
}
const TOAST_DURATION_MS = 5000
const NOT_FOUND = 404
export function useImageVariantRows(imageId: number, onGone: () => void) {
const api = useMediaVariants()
const toast = useLocalizedToast()
const items = ref<MediaVariantItem[]>([])
const unsupported = ref<string | null>(null)
const status = ref<TabStatus>('loading')
const showSkeleton = ref(false)
const busy = ref<string[]>([])
const failures = ref<Record<string, VariantCause>>({})
const announcement = ref('')
let skeletonTimer: ReturnType<typeof setTimeout> | null = null
let loadTicket = 0
const rows = computed<VariantRow[]>(() =>
items.value.map((item) => {
if (busy.value.includes(item.name)) {
return { item, status: 'busy', cause: null }
}
const cause = failures.value[item.name]
if (cause && !item.generated) {
return { item, status: 'failed', cause }
}
return { item, status: item.generated ? 'generated' : 'missing', cause: null }
}),
)
const generatedCount = computed(() => items.value.filter((item) => item.generated).length)
const anyBusy = computed(() => busy.value.length > 0)
const allGenerated = computed(
() => items.value.length > 0 && generatedCount.value === items.value.length,
)
function clearSkeletonTimer() {
if (skeletonTimer !== null) {
clearTimeout(skeletonTimer)
skeletonTimer = null
}
}
async function load() {
loadTicket += 1
const ticket = loadTicket
status.value = 'loading'
showSkeleton.value = false
clearSkeletonTimer()
skeletonTimer = setTimeout(() => {
showSkeleton.value = true
}, MEDIA_SKELETON_DELAY_MS)
try {
const response = await api.list(imageId)
if (ticket !== loadTicket) {
return
}
items.value = response.items
unsupported.value = response.unsupported
status.value = 'ready'
} catch (error) {
if (ticket !== loadTicket) {
return
}
if (classifyMediaError(error) === 'not-found') {
onGone()
return
}
status.value = 'error'
} finally {
if (ticket === loadTicket) {
clearSkeletonTimer()
showSkeleton.value = false
}
}
}
function replaceItem(updated: MediaVariantItem) {
items.value = items.value.map((item) => (item.name === updated.name ? updated : item))
}
function clearFailure(name: string) {
const next = { ...failures.value }
delete next[name]
failures.value = next
}
function markBusy(names: string[]) {
busy.value = [...busy.value, ...names]
names.forEach(clearFailure)
}
function releaseBusy(names: string[]) {
busy.value = busy.value.filter((name) => !names.includes(name))
}
function successToast(id: string, title: () => string) {
toast.add(() => ({
id,
color: 'success' as const,
icon: 'i-lucide-circle-check',
get title() {
return title()
},
duration: TOAST_DURATION_MS,
}))
}
function failureToast(error: unknown) {
toast.add(() => ({
color: 'error' as const,
icon: 'i-lucide-circle-x',
get title() {
return toastCopyFor(error).title
},
get description() {
return toastCopyFor(error).description
},
}))
}
function causeToast(title: () => string, cause: VariantCause) {
toast.add(() => ({
color: 'error' as const,
icon: 'i-lucide-circle-x',
get title() {
return title()
},
get description() {
return `${causeText(cause)}.`
},
}))
}
function announce(text: string) {
announcement.value = text
}
async function generateOne(name: string) {
markBusy([name])
announce(t('Generating variants'))
try {
replaceItem(await api.generate(imageId, name))
successToast(`media-variant-generated-${imageId}-${name}`, () =>
t('Generated {0}', [name]),
)
announce(t('Generated {0}', [name]))
} catch (error) {
announce(t("Couldn't generate {0}.", [name]))
const cause = error instanceof ApiError ? causeOfStatus(error.status) : null
if (cause) {
failures.value = { ...failures.value, [name]: cause }
causeToast(() => t("Couldn't generate {0}.", [name]), cause)
return
}
failureToast(error)
if (error instanceof ApiError && error.status === NOT_FOUND) {
releaseBusy([name])
await load()
}
} finally {
releaseBusy([name])
}
}
function generatedTitle(count: number) {
return count === 1 ? t('Generated 1 variant') : t('Generated {0} variants', [count])
}
async function generateAll() {
const names = items.value.filter((item) => !item.generated).map((item) => item.name)
if (names.length === 0) {
return
}
markBusy(names)
announce(t('Generating variants'))
try {
const result = await api.generateAll(imageId)
items.value = result.items
const next = { ...failures.value }
result.failures.forEach((failure) => {
next[failure.name] = failure.cause
})
failures.value = next
if (result.generated > 0) {
successToast(`media-variants-generated-${imageId}`, () =>
generatedTitle(result.generated),
)
announce(generatedTitle(result.generated))
} else if (result.failures.length > 0) {
causeToast(() => t("Couldn't generate the variants."), result.failures[0]!.cause)
announce(t("Couldn't generate the variants."))
}
} catch (error) {
failureToast(error)
announce(t("Couldn't generate the variants."))
if (error instanceof ApiError && error.status === NOT_FOUND) {
releaseBusy(names)
await load()
}
} finally {
releaseBusy(names)
}
}
function purgedTitle(files: number, bytes: number) {
return files === 1
? t('Purged 1 file ({0})', [formatSize(bytes)])
: t('Purged {0} files ({1})', [files, formatSize(bytes)])
}
async function purge(name: string) {
try {
const result = await api.purge(imageId, name)
items.value = items.value.map((item) =>
item.name === name ? { ...item, generated: false, size: null } : item,
)
successToast(`media-variants-purged-${imageId}-${name}`, () =>
purgedTitle(result.purged_files, result.purged_bytes),
)
} catch (error) {
failureToast(error)
}
}
onBeforeUnmount(clearSkeletonTimer)
return {
items,
unsupported,
status,
showSkeleton,
rows,
generatedCount,
anyBusy,
allGenerated,
announcement,
load,
generateOne,
generateAll,
purge,
}
}
+2
View File
@@ -17,6 +17,8 @@ export interface MediaItem {
created_at: string
used_in: number
duplicate: boolean
variant_count: number
variant_size: number
}
export interface MediaCounts {
+64
View File
@@ -0,0 +1,64 @@
import { useApi } from '@/composables/useApi'
export type VariantCause = 'too_large' | 'unsupported_format' | 'failed'
export interface MediaVariantItem {
name: string
width: number | null
height: number | null
fit: string
format: string
output_width: number
output_height: number
output_format: string
generated: boolean
size: number | null
url: string
}
export interface MediaVariantList {
unsupported: 'svg' | null
items: MediaVariantItem[]
}
export interface GenerateAllResult {
generated: number
failed: number
failures: { name: string; cause: VariantCause }[]
items: MediaVariantItem[]
}
export interface PurgedVariant {
purged_files: number
purged_bytes: number
}
function basePath(imageId: number) {
return `/v1/media/${imageId}/variants`
}
function namePath(imageId: number, name: string) {
return `${basePath(imageId)}/${encodeURIComponent(name)}`
}
export function useMediaVariants() {
const { request } = useApi()
function list(imageId: number) {
return request<MediaVariantList>(basePath(imageId))
}
function generate(imageId: number, name: string) {
return request<MediaVariantItem>(namePath(imageId, name), { method: 'POST' })
}
function generateAll(imageId: number) {
return request<GenerateAllResult>(basePath(imageId), { method: 'POST' })
}
function purge(imageId: number, name: string) {
return request<PurgedVariant>(namePath(imageId, name), { method: 'DELETE' })
}
return { list, generate, generateAll, purge }
}
+61
View File
@@ -1361,6 +1361,67 @@ export const messages = {
'Drag the divider, or focus it and use the arrow keys. The estimate comes from a sample; output is never larger than the source.':
'Faites glisser le séparateur, ou donnez-lui le focus et utilisez les flèches. L’estimation vient d’un échantillon ; le résultat n’est jamais plus lourd que la source.',
URL: 'URL',
'1 variant generated': '1 variante générée',
'{0} variants generated': '{0} variantes générées',
'Also removes 1 generated variant ({0})': 'Supprime aussi 1 variante générée ({0})',
'Also removes {0} generated variants ({1})': 'Supprime aussi {0} variantes générées ({1})',
'Both images are shown at actual size. Scroll to pan.':
'Les deux images sont affichées à leur taille réelle. Faites défiler pour les déplacer.',
'Define a variant in Settings to get resized copies of this image.':
'Définissez une variante dans les paramètres pour obtenir des copies redimensionnées de cette image.',
'Generate all': 'Tout générer',
'Generate now': 'Générer maintenant',
'Generated 1 variant': '1 variante générée',
'Generated {0} variants': '{0} variantes générées',
'Generated {0}': 'Variante {0} générée',
'Generating variants': 'Génération des variantes',
'Generating variants…': 'Génération des variantes…',
Generating: 'Génération',
'Generating…': 'Génération…',
'Generation failed': 'Échec de la génération',
'Image too large': 'Image trop grande',
'Largest total size (original + variants)': 'Plus grande taille totale (original + variantes)',
'Largest total size': 'Plus grande taille totale',
'No images with variants': 'Aucune image avec des variantes',
'No variants defined': 'Aucune variante définie',
'No variants defined. Add one in {0}.': 'Aucune variante définie. Ajoutez-en une dans {0}.',
'Not generated': 'Non générée',
'Nothing generated yet.': 'Rien n’a encore été généré.',
'Original · kept untouched': 'Original · conservé tel quel',
'Pick another variant': 'Choisir une autre variante',
'Preview: {0}': 'Aperçu : {0}',
Purge: 'Purger',
'Purged 1 file ({0})': '1 fichier purgé ({0})',
'Purged {0} files ({1})': '{0} fichiers purgés ({1})',
'Removed 1 file ({0})': '1 fichier supprimé ({0})',
'Removed {0} files ({1})': '{0} fichiers supprimés ({1})',
'SVG images are served as they are.': 'Les images SVG sont servies telles quelles.',
'Settings → Media → Variants': 'Paramètres → Médias → Variantes',
'Show all images': 'Afficher toutes les images',
'This image returns an error on the public site.':
'Cette image renvoie une erreur sur le site public.',
'Unsupported source format': 'Format source non pris en charge',
Variant: 'Variante',
'Variants are generated when an image is requested with ?v=<name>, or from its Variants tab.':
'Les variantes sont générées lorsqu’une image est demandée avec ?v=<nom>, ou depuis son onglet Variantes.',
'With variants': 'Avec variantes',
Without: 'Sans',
'{0} generated · {1} failed ({2})': '{0} générées · {1} en échec ({2})',
'{0} of {1} generated': '{0} sur {1} générées',
'{0} total · {1} + {2}': '{0} au total · {1} + {2}',
'{0} total': '{0} au total',
'{0} vs original': '{0} par rapport à l’original',
'{0} · saves {1}%': '{0} · économise {1} %',
'Generated all variants of {0}': 'A généré toutes les variantes de {0}',
'Failed to generate the variants of {0}': 'Échec de la génération des variantes de {0}',
'Purged the variants of {0}': 'A purgé les variantes de {0}',
'Failed to purge the variants of {0}': 'Échec de la purge des variantes de {0}',
"Couldn't generate {0}.": 'Impossible de générer {0}.',
"Couldn't generate the variants.": 'Impossible de générer les variantes.',
"Variants aren't generated for this format.":
'Les variantes ne sont pas générées pour ce format.',
"Variant '{0}' no longer exists.": 'La variante « {0} » n’existe plus.',
"Variant '{0}' is disabled.": 'La variante « {0} » est désactivée.',
} as const
export type MessageKey = keyof typeof messages
@@ -230,6 +230,8 @@ describe('The catalogue is complete in both languages', () => {
'media.delete',
'media.merge',
'media.purge',
'media.variant_generate_all',
'media.variant_purge_image',
'system.media_purge',
'user.register',
'user.verify',
@@ -1,12 +1,14 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { defineComponent } from 'vue'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { Editor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import { ArticleImage, findArticleImagePos } from '../articleImage'
import { bumpMediaRevision } from '../mediaRevision'
function mountHarness(onRequestRemove = vi.fn()) {
setActivePinia(createPinia())
let editor: Editor
const Harness = defineComponent({
components: { EditorContent },
+48
View File
@@ -2,6 +2,8 @@ import { formatNumber, t } from '@/i18n'
import type { MessageKey } from '@/i18n/messages'
import type { ActivityItem } from '@/lib/activity'
import { sizeLabel } from '@/lib/activityRetention'
import { formatSize } from '@/lib/mediaFormat'
import { causeText } from '@/lib/variants/variantCauses'
export interface SentenceSegment {
text: string
@@ -56,6 +58,14 @@ const CATALOGUE: Record<string, Template> = {
success: 'Ran the scheduled duplicate purge: {0}',
failed: 'Failed to run the scheduled duplicate purge',
},
'media.variant_generate_all': {
success: 'Generated all variants of {0}',
failed: 'Failed to generate the variants of {0}',
},
'media.variant_purge_image': {
success: 'Purged the variants of {0}',
failed: 'Failed to purge the variants of {0}',
},
'user.register': {
success: 'Registered the account {0}',
failed: 'Failed to register the account {0}',
@@ -224,6 +234,44 @@ export function composeSentence(item: ActivityItem): SentenceSegment[] {
return segments.filter((segment) => segment.text !== '')
}
function causeList(value: unknown) {
const causes = Array.isArray(value) ? value.filter((cause) => typeof cause === 'string') : []
return [...new Set(causes)].map(causeText).join(', ')
}
function generateAllDetail(params: Record<string, unknown>) {
const generated = count(params.generated)
const failed = count(params.failed)
if (failed === 0) {
return generated === 1
? t('1 variant generated')
: t('{0} variants generated', [formatNumber(generated)])
}
return t('{0} generated · {1} failed ({2})', [
formatNumber(generated),
formatNumber(failed),
causeList(params.causes),
])
}
function purgeImageDetail(params: Record<string, unknown>) {
const files = count(params.purged_files)
const size = formatSize(count(params.purged_bytes))
return files === 1
? t('Removed 1 file ({0})', [size])
: t('Removed {0} files ({1})', [formatNumber(files), size])
}
export function detailLine(item: ActivityItem): string | null {
if (item.action === 'media.variant_generate_all') {
return generateAllDetail(item.params)
}
if (item.action === 'media.variant_purge_image') {
return purgeImageDetail(item.params)
}
return null
}
export function sentenceText(item: ActivityItem) {
return composeSentence(item)
.map((segment) => segment.text)
+18
View File
@@ -36,6 +36,24 @@ export function formatSize(bytes: number) {
])
}
export function totalMeta(item: { size: number; variant_size: number; variant_count: number }) {
const total = formatSize(item.size + item.variant_size)
if (item.variant_count > 0) {
return t('{0} total · {1} + {2}', [
total,
formatSize(item.size),
formatSize(item.variant_size),
])
}
return t('{0} total', [total])
}
export function removalNote(count: number, bytes: number) {
return count === 1
? t('Also removes 1 generated variant ({0})', [formatSize(bytes)])
: t('Also removes {0} generated variants ({1})', [count, formatSize(bytes)])
}
export function formatDimensions(width: number | null, height: number | null) {
if (width === null || height === null) {
return t(VECTOR_DIMENSIONS)
+11 -2
View File
@@ -1,13 +1,15 @@
import type { LocationQuery } from 'vue-router'
export type MediaFilter = 'all' | 'unused' | 'duplicates'
export type MediaSort = 'newest' | 'oldest' | 'name' | 'largest'
export type MediaSort = 'newest' | 'oldest' | 'name' | 'largest' | 'total_size'
export type MediaVariantsFilter = 'all' | 'with' | 'without'
export type MediaView = 'grid' | 'list'
export interface MediaControls {
q: string
filter: MediaFilter
sort: MediaSort
variants: MediaVariantsFilter
view: MediaView
}
@@ -17,11 +19,13 @@ export const DEFAULT_CONTROLS: MediaControls = {
q: '',
filter: 'all',
sort: 'newest',
variants: 'all',
view: 'grid',
}
const FILTERS: MediaFilter[] = ['all', 'unused', 'duplicates']
const SORTS: MediaSort[] = ['newest', 'oldest', 'name', 'largest']
const SORTS: MediaSort[] = ['newest', 'oldest', 'name', 'largest', 'total_size']
const VARIANTS_FILTERS: MediaVariantsFilter[] = ['all', 'with', 'without']
const VIEWS: MediaView[] = ['grid', 'list']
function firstValue(value: LocationQuery[string] | undefined) {
@@ -37,6 +41,7 @@ export function parseMediaControls(query: LocationQuery): MediaControls {
q: firstValue(query.q).trim(),
filter: pick(FILTERS, firstValue(query.filter), DEFAULT_CONTROLS.filter),
sort: pick(SORTS, firstValue(query.sort), DEFAULT_CONTROLS.sort),
variants: pick(VARIANTS_FILTERS, firstValue(query.variants), DEFAULT_CONTROLS.variants),
view: pick(VIEWS, firstValue(query.view), DEFAULT_CONTROLS.view),
}
}
@@ -52,6 +57,9 @@ export function toRouteQuery(controls: MediaControls) {
if (controls.sort !== DEFAULT_CONTROLS.sort) {
query.sort = controls.sort
}
if (controls.variants !== DEFAULT_CONTROLS.variants) {
query.variants = controls.variants
}
if (controls.view !== DEFAULT_CONTROLS.view) {
query.view = controls.view
}
@@ -63,6 +71,7 @@ export function toRequestQuery(controls: MediaControls) {
...(controls.q ? [`q=${encodeURIComponent(controls.q)}`] : []),
`filter=${controls.filter}`,
`sort=${controls.sort}`,
...(controls.variants === 'all' ? [] : [`variants=${controls.variants}`]),
`limit=${MEDIA_PAGE_LIMIT}`,
]
return parts.join('&')
+2
View File
@@ -1,2 +1,4 @@
export const UNDERLINE_TAB_TRIGGER =
'h-9 px-0 py-0 data-[state=inactive]:text-toned in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:bottom-0 in-[[data-slot=list]:not(:has([data-slot=indicator]))]:data-[state=active]:after:h-0.5 max-md:h-11 max-md:text-[0.9375rem]'
export const PANEL_TAB_TRIGGER = UNDERLINE_TAB_TRIGGER.replace('h-9', 'h-10')
@@ -0,0 +1,54 @@
import { describe, expect, it } from 'vitest'
import { withMediaRevision } from '@/lib/mediaRevision'
import { bodyHasVariantImage, variantOfSrc, withVariant } from '../blockVariant'
describe('Reading the variant of an image src', () => {
it.each([
['/static/uploadedImages/1.jpg?v=hero', 'hero'],
['/static/uploadedImages/1.jpg?v=hero&rev=3', 'hero'],
['/static/uploadedImages/1.jpg?rev=3&v=thumb#top', 'thumb'],
['/static/uploadedImages/1.jpg', null],
['/static/uploadedImages/1.jpg?rev=3', null],
['/static/uploadedImages/1.jpg?v=', null],
[undefined, null],
])('%s reads %s', (src, expected) => {
expect(variantOfSrc(src)).toBe(expected)
})
})
describe('Rewriting the variant of an image src', () => {
it.each([
['/static/uploadedImages/1.jpg?v=hero', 'thumb', '/static/uploadedImages/1.jpg?v=thumb'],
['/static/uploadedImages/1.jpg?v=hero', '', '/static/uploadedImages/1.jpg'],
['/static/uploadedImages/1.jpg', 'hero', '/static/uploadedImages/1.jpg?v=hero'],
[
'/static/uploadedImages/1.jpg?rev=3&v=hero#a',
'og',
'/static/uploadedImages/1.jpg?rev=3&v=og#a',
],
])('%s with %s becomes %s', (src, name, expected) => {
expect(withVariant(src, name)).toBe(expected)
})
})
describe('Detecting variant images in a body', () => {
it('finds an img whose src carries ?v=', () => {
expect(bodyHasVariantImage('<p>x</p><img src="/static/uploadedImages/1.jpg?v=hero">')).toBe(
true,
)
})
it('ignores plain images and text', () => {
expect(bodyHasVariantImage('<p>?v=hero</p><img src="/static/uploadedImages/1.jpg">')).toBe(
false,
)
})
})
describe('The cache-busting parameter coexists with the variant', () => {
it('is appended after ?v=', () => {
expect(withMediaRevision('/static/uploadedImages/1.jpg?v=hero', 3)).toBe(
'/static/uploadedImages/1.jpg?v=hero&rev=3',
)
})
})
@@ -0,0 +1,86 @@
import { afterEach, describe, expect, it } from 'vitest'
import { initializeLocale, setLocale } from '@/i18n'
import type { ImageVariant } from '@/composables/useImageVariants'
import { buildOptions, insertedUrl, originalOption, variantOption } from '../variantOptions'
const NORTH_WALL = {
url: '/static/uploadedImages/1.jpg',
width: 4032,
height: 3024,
content_type: 'image/jpeg',
}
function variant(overrides: Partial<ImageVariant>): ImageVariant {
return {
name: 'hero',
width: 1200,
height: 630,
fit: 'cover',
format: 'webp',
quality: 82,
generate_on_upload: false,
enabled: true,
generated_files: 0,
cache_size: 0,
...overrides,
}
}
afterEach(() => {
localStorage.clear()
initializeLocale()
})
describe('Option labels', () => {
it('reads the original from the image', () => {
expect(originalOption(NORTH_WALL).label).toBe('Original · 4032×3024 · JPEG')
expect(originalOption({ ...NORTH_WALL, content_type: 'image/webp' }).label).toBe(
'Original · 4032×3024 · WEBP',
)
expect(
originalOption({
...NORTH_WALL,
width: null,
height: null,
content_type: 'image/svg+xml',
}).label,
).toBe('Original · Vector · SVG')
})
it.each([
[variant({}), 'Hero · 1200×630 · WebP'],
[
variant({ name: 'card', width: 800, height: null, format: 'webp' }),
'Card · 800 × auto · WebP',
],
[
variant({ name: 'tall', width: null, height: 2400, format: 'png' }),
'Tall · auto × 2400 · PNG',
],
[variant({ name: 'keep', format: 'original' }), 'Keep · 1200×630 · Original'],
])('reads a variant', (entry, label) => {
expect(variantOption(entry).label).toBe(label)
})
it('offers only Original for a vector image', () => {
const options = buildOptions(
{ ...NORTH_WALL, width: null, height: null, content_type: 'image/svg+xml' },
[variant({})],
)
expect(options.map((option) => option.label)).toEqual(['Original · Vector · SVG'])
})
it('translates the original label', () => {
setLocale('fr')
expect(originalOption(NORTH_WALL).label).toBe('Original · 4032×3024 · JPEG')
})
})
describe('The inserted url', () => {
it('is the image url for Original and carries ?v= for a variant', () => {
expect(insertedUrl(NORTH_WALL, '')).toBe('/static/uploadedImages/1.jpg')
expect(insertedUrl(NORTH_WALL, 'hero')).toBe('/static/uploadedImages/1.jpg?v=hero')
})
})
+39
View File
@@ -0,0 +1,39 @@
const VARIANT_PARAMETER = 'v'
const HASH = '#'
const QUERY = '?'
function splitSrc(src: string) {
const hashAt = src.indexOf(HASH)
const withoutHash = hashAt === -1 ? src : src.slice(0, hashAt)
const hash = hashAt === -1 ? '' : src.slice(hashAt)
const queryAt = withoutHash.indexOf(QUERY)
if (queryAt === -1) {
return { base: withoutHash, query: '', hash }
}
return { base: withoutHash.slice(0, queryAt), query: withoutHash.slice(queryAt + 1), hash }
}
export function variantOfSrc(src: string | undefined | null) {
if (!src) {
return null
}
const name = new URLSearchParams(splitSrc(src).query).get(VARIANT_PARAMETER)
return name === null || name === '' ? null : name
}
export function withVariant(src: string, name: string) {
const { base, query, hash } = splitSrc(src)
const params = new URLSearchParams(query)
params.delete(VARIANT_PARAMETER)
const kept = params.toString()
const parts = [kept, name === '' ? '' : `${VARIANT_PARAMETER}=${encodeURIComponent(name)}`]
const next = parts.filter((part) => part !== '').join('&')
return `${base}${next === '' ? '' : QUERY + next}${hash}`
}
export function bodyHasVariantImage(html: string) {
const document = new DOMParser().parseFromString(html, 'text/html')
return Array.from(document.querySelectorAll('img')).some(
(image) => variantOfSrc(image.getAttribute('src')) !== null,
)
}
+26
View File
@@ -0,0 +1,26 @@
import { t } from '@/i18n'
import type { VariantCause } from '@/composables/useMediaVariants'
const PAYLOAD_TOO_LARGE = 413
const UNSUPPORTED_MEDIA_TYPE = 415
const UNPROCESSABLE = 422
export function causeText(cause: string) {
if (cause === 'too_large') {
return t('Image too large')
}
if (cause === 'unsupported_format') {
return t('Unsupported source format')
}
return t('Generation failed')
}
export function causeOfStatus(status: number): VariantCause | null {
if (status === PAYLOAD_TOO_LARGE) {
return 'too_large'
}
if (status === UNSUPPORTED_MEDIA_TYPE || status === UNPROCESSABLE) {
return 'unsupported_format'
}
return null
}
+71
View File
@@ -0,0 +1,71 @@
import { t } from '@/i18n'
import type { ImageVariant, VariantFormat } from '@/composables/useImageVariants'
import { formatType } from '@/lib/mediaFormat'
import { formatDimensions, formatLabel } from '@/lib/variants/variantFormat'
const SEPARATOR = ' · '
const VECTOR = 'Vector'
const SVG_TYPE = 'image/svg+xml'
const ORIGINAL_VALUE = ''
export interface VariantOption {
value: string
label: string
}
export interface OptionSource {
url: string
width: number | null
height: number | null
content_type: string
}
export const ORIGINAL_OPTION_VALUE = ORIGINAL_VALUE
export function isVector(source: OptionSource) {
return source.content_type === SVG_TYPE
}
function sourceSize(source: OptionSource) {
if (source.width === null || source.height === null) {
return t(VECTOR)
}
return `${source.width}×${source.height}`
}
export function capitalised(name: string) {
return name.charAt(0).toUpperCase() + name.slice(1)
}
export function originalOption(source: OptionSource): VariantOption {
return {
value: ORIGINAL_VALUE,
label: [t('Original'), sourceSize(source), formatType(source.content_type)].join(SEPARATOR),
}
}
export function bareOriginalOption(): VariantOption {
return { value: ORIGINAL_VALUE, label: t('Original') }
}
export function variantOption(variant: ImageVariant): VariantOption {
return {
value: variant.name,
label: [
capitalised(variant.name),
formatDimensions(variant.width, variant.height),
formatLabel(variant.format as VariantFormat),
].join(SEPARATOR),
}
}
export function buildOptions(source: OptionSource, variants: ImageVariant[]): VariantOption[] {
const offered = isVector(source) ? [] : variants.map(variantOption)
return [originalOption(source), ...offered]
}
export function insertedUrl(source: OptionSource, variantName: string) {
return variantName === ORIGINAL_VALUE
? source.url
: `${source.url}?v=${encodeURIComponent(variantName)}`
}
+23
View File
@@ -0,0 +1,23 @@
const MAX_MAGNITUDE = 99
const PERCENT = 100
export function savedPercent(originalBytes: number, variantBytes: number) {
if (originalBytes <= 0) {
return 0
}
const change = ((variantBytes - originalBytes) / originalBytes) * PERCENT
const rounded = Math.sign(change) * Math.round(Math.abs(change))
if (variantBytes > 0 && rounded < -MAX_MAGNITUDE) {
return -MAX_MAGNITUDE
}
return rounded
}
export function signedPercent(originalBytes: number, variantBytes: number) {
const percent = savedPercent(originalBytes, variantBytes)
return `${percent > 0 ? '+' : ''}${percent}%`
}
export function savesPercent(originalBytes: number, variantBytes: number) {
return Math.max(0, -savedPercent(originalBytes, variantBytes))
}
+43
View File
@@ -0,0 +1,43 @@
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useImageVariants, type ImageVariant } from '@/composables/useImageVariants'
export type CatalogStatus = 'idle' | 'loading' | 'ready' | 'failed'
export const useVariantCatalogStore = defineStore('variantCatalog', () => {
const api = useImageVariants()
const items = ref<ImageVariant[]>([])
const status = ref<CatalogStatus>('idle')
const loaded = ref(false)
let pending: Promise<void> | null = null
const enabled = computed(() => items.value.filter((variant) => variant.enabled))
function find(name: string) {
return items.value.find((variant) => variant.name === name)
}
function load() {
if (pending) {
return pending
}
status.value = 'loading'
pending = api
.listVariants()
.then((listed) => {
items.value = listed
status.value = 'ready'
loaded.value = true
})
.catch(() => {
items.value = []
status.value = 'failed'
})
.finally(() => {
pending = null
})
return pending
}
return { items, status, loaded, enabled, find, load }
})
+10 -2
View File
@@ -20,7 +20,10 @@ import { useArticleDraft } from '@/composables/useArticleDraft'
import type { MediaItem } from '@/composables/useMedia'
import { bodyImageCount, bodyImageIds } from '@/lib/bodyImageIds'
import { formatSize } from '@/lib/mediaFormat'
import { useCanManageVariants } from '@/composables/useCanManageVariants'
import { bodyHasVariantImage } from '@/lib/variants/blockVariant'
import { useSeenImagesStore } from '@/stores/seenImages'
import { useVariantCatalogStore } from '@/stores/variantCatalog'
const SKELETON_DELAY_MS = 150
const BODY_MAX_LENGTH = 10000
@@ -36,6 +39,8 @@ const toast = useLocalizedToast()
const articleId = Number(route.params.id)
const draft = useArticleDraft(articleId)
const seenImages = useSeenImagesStore()
const variantCatalog = useVariantCatalogStore()
const canManageVariants = useCanManageVariants()
const loadState = ref<LoadState>('loading')
const showSkeleton = ref(false)
@@ -69,6 +74,9 @@ async function loadArticle() {
article.value = result
draft.load(result.body, new Date(result.updated_at))
loadState.value = 'loaded'
if (canManageVariants.value && bodyHasVariantImage(result.body)) {
variantCatalog.load()
}
} catch (err) {
if (err instanceof ApiError && err.status === 404) {
loadState.value = 'notFound'
@@ -284,9 +292,9 @@ function onImageUploaded(item: MediaItem) {
announceImageAdded()
}
function onImageInserted(item: MediaItem, alt: string) {
function onImageInserted(item: MediaItem, alt: string, src: string) {
seenImages.remember([item])
editorRef.value?.insertImage(item.url, alt, item.id)
editorRef.value?.insertImage(src, alt, item.id)
announceImageAdded()
}
+13 -4
View File
@@ -135,9 +135,15 @@ const nothingToShow = computed(
!emptyLibrary.value &&
(isDuplicates.value ? groups.value.length === 0 : media.items.value.length === 0),
)
const emptyVariant = computed(() =>
isDuplicates.value && controls.value.q === '' ? 'no-duplicates' : 'no-results',
)
const emptyVariant = computed(() => {
if (isDuplicates.value && controls.value.q === '') {
return 'no-duplicates'
}
if (controls.value.variants === 'with' && controls.value.q === '' && !isDuplicates.value) {
return controls.value.filter === 'all' ? 'no-variants' : 'no-results'
}
return 'no-results'
})
const filterLabel = computed(
() =>
({ all: t('All'), unused: t('Unused'), duplicates: t('Duplicates') })[
@@ -203,7 +209,7 @@ function updateControls(patch: Partial<MediaControls>) {
}
function clearFilters() {
updateControls({ q: '', filter: 'all' })
updateControls({ q: '', filter: 'all', variants: 'all' })
}
function announce(source: () => string) {
@@ -919,6 +925,7 @@ async function mergeAction() {
@update:q="updateControls({ q: $event })"
@update:filter="updateControls({ filter: $event })"
@update:sort="updateControls({ sort: $event })"
@update:variants="updateControls({ variants: $event })"
@update:view="updateControls({ view: $event })"
@purge="openPurge"
/>
@@ -985,6 +992,7 @@ async function mergeAction() {
:items="media.items.value"
:columns="isDesktop ? DESKTOP_COLUMNS : MOBILE_COLUMNS"
:selected="gridSelected"
:total-size="controls.sort === 'total_size'"
@open="openPanel"
@toggle="toggleSelected"
/>
@@ -1042,6 +1050,7 @@ async function mergeAction() {
@rename="renameOpen = true"
@delete="deleteOpen = true"
@review-duplicates="reviewDuplicates"
@gone="activeItem && handleGone(activeItem)"
/>
<RenameMediaDialog
@@ -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) }
}
+44 -4
View File
@@ -6,7 +6,7 @@ import { build, preview } from 'vite'
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright'
import { icons as lucide } from '@iconify-json/lucide'
import { getIconData, getIcons, iconToHTML, iconToSVG, replaceIDs } from '@iconify/utils'
import { visualStates, type ApiMock, type VisualState } from './states'
import { visualStates, type ApiMock, type DiffException, type VisualState } from './states'
type Viewport = 'desktop' | 'mobile'
type Theme = 'light' | 'dark'
@@ -151,6 +151,17 @@ const settleMs = 400
const diffThreshold = 24
const maxDiffPercent = 10
function budgetFor(cap: DiffException['maxPercent'] | undefined, viewport: Viewport) {
if (cap === undefined) {
return maxDiffPercent
}
return typeof cap === 'number' ? cap : cap[viewport]
}
function describeCap(cap: DiffException['maxPercent']) {
return typeof cap === 'number' ? `${cap}%` : `${cap.desktop}% desktop, ${cap.mobile}% mobile`
}
function slug(text: string) {
return text
.toLowerCase()
@@ -239,11 +250,40 @@ function variantsScreen(): Screen {
alias: numberedStates('2', formNames),
},
]
const libraryNames = [
'3a · Grid with badges',
'3b · Sort menu',
'3c · Filter: With variants, sorted by total size',
'3d · Filter: Without variants',
'3e · Filter: nothing to show',
'3f · Delete confirm',
]
const detailNames = [
'4a · Partly generated',
'4b · Nothing generated yet',
'4c · Generating',
'4d · Generation failed',
'4e · No variants defined',
'4f · Source is an SVG',
'4h · Preview dialog',
]
const editorNames = [
'6a · Variant select',
'6b · Select open',
'6c · No variants defined',
'6d · Variant deleted',
'6e · Variant disabled',
]
sources.push(
{ board: variantsBoard, group: 'Media library', states: libraryNames, alias: {} },
{ board: variantsBoard, group: 'Image detail', states: detailNames, alias: {} },
{ board: variantsBoard, group: 'Editor picker', states: editorNames, alias: {} },
)
return {
name: 'image-variants',
board: variantsBoard,
group: 'Variants list',
states: [...listNames, ...formNames],
states: [...listNames, ...formNames, ...libraryNames, ...detailNames, ...editorNames],
sources,
}
}
@@ -686,7 +726,7 @@ async function main() {
)
const result = await diff(browser, designPath, appPath, diffPath)
const percent = result.ratio * 100
const budget = setup.exception?.maxPercent ?? maxDiffPercent
const budget = budgetFor(setup.exception?.maxPercent, viewport)
const problems = [
...(percent > budget
? [`${percent.toFixed(2)}% exceeds ${budget}% budget`]
@@ -700,7 +740,7 @@ async function main() {
failures++
}
const exception = setup.exception
? ` [exception ${setup.exception.maxPercent}% approved by ${setup.exception.approvedBy}: ${setup.exception.reason}]`
? ` [exception ${describeCap(setup.exception.maxPercent)} approved by ${setup.exception.approvedBy}: ${setup.exception.reason}]`
: ''
lines.push(
`${problems.length ? 'FAIL' : 'PASS'} ${state} · ${viewport} · ${theme}: ${percent.toFixed(2)}% pixels differ → ${relative(repoRoot, directory)}${problems.length ? ` (${problems.join('; ')})` : ''}${exception}`,
+384 -19
View File
@@ -10,7 +10,7 @@ export interface ApiMock {
}
export interface DiffException {
maxPercent: number
maxPercent: number | { desktop: number; mobile: number }
reason: string
approvedBy: string
}
@@ -1837,6 +1837,7 @@ function pickerApi(
'GET /v1/auth/me': mediaSession,
'GET /v1/article/12': { status: 200, body: { ...editorArticle, body } },
'GET /v1/media/': { status: 200, bodyFor: pickerList },
'GET /v1/image-variants': { status: 403 },
...overrides,
}
}
@@ -3308,23 +3309,6 @@ const variantsStates: Record<string, VisualState> = {
await page.mouse.move(0, 0)
},
),
'Entry: sidebar': {
path: '/media',
origin: mediaOrigin,
api: mediaApi({ 'GET /v1/auth/me': variantsSession }),
steps: async (page) => {
if (isMobileViewport(page)) {
await page.locator('[data-slot="toggle"]').first().click()
}
await page
.locator(
'nav[aria-label="Main"]:visible a[href="/settings"] [data-slot="linkTrailing"]',
)
.click()
await page.mouse.move(0, 0)
await page.waitForTimeout(250)
},
},
'Request reference': {
...variantsListState({}, async (page) => {
if (isMobileViewport(page)) {
@@ -3428,6 +3412,383 @@ const variantsStates: Record<string, VisualState> = {
}),
}
const variantBoardSizes: Record<string, number> = {
thumb: 18432,
card: 65536,
hero: 98304,
square: 83968,
og: 145408,
}
const variantBoardOutputs: Record<string, [number, number, string]> = {
thumb: [400, 300, 'webp'],
card: [800, 600, 'webp'],
hero: [1200, 630, 'webp'],
square: [600, 600, 'jpeg'],
og: [1200, 630, 'jpeg'],
}
const variantBoardNames = ['thumb', 'card', 'hero', 'square', 'og']
const variantLibraryTotals: Record<number, [number, number]> = {
1: [4, 266240],
2: [5, 419840],
3: [5, 404480],
5: [3, 245760],
7: [2, 153600],
9: [1, 61440],
10: [3, 194560],
11: [4, 286720],
12: [5, 440320],
}
const variantsMediaPath = '/media'
const variantsPanelId = 1
const variantsSvgId = 4
function variantLibraryItems(ids?: number[]) {
const order = (id: number) => (ids ? ids.indexOf(id) : id)
return mediaSamples
.filter((sample) => !ids || ids.includes(sample.id))
.sort((left, right) => order(left.id) - order(right.id))
.map((sample) => {
const [count, size] = variantLibraryTotals[sample.id] ?? [0, 0]
return {
...mediaItem({ ...sample, duplicate: false }),
variant_count: count,
variant_size: size,
}
})
}
function boardVariantItems(generated: string[], storedName = '1.jpg') {
return variantBoardNames.map((name) => {
const [width, height, format] = variantBoardOutputs[name]!
const isGenerated = generated.includes(name)
return {
name,
width,
height,
fit: 'cover',
format,
output_width: width,
output_height: height,
output_format: format,
generated: isGenerated,
size: isGenerated ? variantBoardSizes[name]! : null,
url: `/static/uploadedImages/${storedName}?v=${name}`,
}
})
}
function variantsMediaApi(
ids?: number[],
overrides: Record<string, ApiMock> = {},
): Record<string, ApiMock> {
return {
'GET /v1/auth/me': variantsSession,
'GET /v1/media/': { status: 200, body: mediaList(variantLibraryItems(ids)) },
'GET /v1/media/1/usage': { status: 200, body: mediaNorthWallUsage },
...overrides,
}
}
function variantsMediaState(
overrides: Record<string, ApiMock> = {},
steps?: VisualState['steps'],
path = variantsMediaPath,
ids?: number[],
): VisualState {
return { path, api: variantsMediaApi(ids, overrides), steps }
}
async function openSortMenuOf(page: Page) {
await page.getByRole('button', { name: 'Sort', exact: true }).click()
await page.getByRole('menu').waitFor()
}
async function openImagePanel(page: Page, id = variantsPanelId) {
await page.locator(`[data-media-card][data-media-id="${id}"]`).click()
await page.getByRole('dialog').waitFor()
}
async function openVariantsTabOf(page: Page, id = variantsPanelId) {
await openImagePanel(page, id)
await page.getByRole('tab', { name: 'Variants', exact: true }).click()
await page.getByTestId('variants-tab').locator('[data-testid="variants-original"]').waitFor()
await page.mouse.move(0, 0)
}
function variantRow(page: Page, name: string) {
return page.locator(`[data-testid="variant-row"][data-variant="${name}"]`)
}
function variantsTabApi(
generated: string[],
overrides: Record<string, ApiMock> = {},
id = variantsPanelId,
) {
return variantsMediaApi(undefined, {
[`GET /v1/media/${id}/variants`]: {
status: 200,
body: { unsupported: null, items: boardVariantItems(generated) },
},
...overrides,
})
}
function variantsTabState(
generated: string[],
overrides: Record<string, ApiMock> = {},
steps?: VisualState['steps'],
): VisualState {
return {
path: variantsMediaPath,
api: variantsTabApi(generated, overrides),
steps: async (page) => {
await openVariantsTabOf(page)
await steps?.(page)
},
}
}
const variantsPartlyGenerated = ['thumb', 'card', 'hero', 'square']
const variantsFailedGeneration: ApiMock = {
status: 200,
body: {
generated: 2,
failed: 2,
failures: [
{ name: 'card', cause: 'unsupported_format' },
{ name: 'hero', cause: 'too_large' },
],
items: boardVariantItems(['thumb', 'square', 'og']),
},
}
const variantsPickerPath = '/article/12/edit'
function variantsBoardArticleBody(src: string | null) {
const image = src ? `<img src="${src}" alt="" data-image-id="1">` : ''
return `<p>${pickerIntro}</p>${image}<p>${pickerOutro}</p>`
}
function variantsPickerApi(catalog: unknown[]) {
return pickerApi(
{
'GET /v1/auth/me': variantsSession,
'GET /v1/media/': {
status: 200,
body: {
items: variantLibraryItems([1, 2, 3, 5]),
next_cursor: null,
counts: mediaFullCounts,
},
},
'GET /v1/image-variants': { status: 200, body: { items: catalog } },
},
variantsBoardArticleBody(null),
)
}
function variantsPickerState(
catalog: unknown[],
steps?: (page: Page) => Promise<void>,
): VisualState {
return {
path: variantsPickerPath,
api: variantsPickerApi(catalog),
steps: async (page) => {
await stubEditorImages(page)
await steps?.(page)
},
}
}
async function chooseBoardVariant(page: Page, label: string) {
await page.getByTestId('variant-select').click()
await page.getByRole('option', { name: label }).first().click()
await page.mouse.move(0, 0)
}
function variantsBlockState(catalog: unknown[]): VisualState {
return {
path: variantsPickerPath,
api: pickerApi(
{
'GET /v1/auth/me': variantsSession,
'GET /v1/image-variants': { status: 200, body: { items: catalog } },
},
variantsBoardArticleBody('/media/north-wall.jpg?v=hero'),
),
steps: async (page) => {
await page.getByTestId('article-editor-variant-warning').waitFor()
await page.mouse.move(0, 0)
},
}
}
const variantsWithoutHero = variantsBoardList.filter((entry) => entry.name !== 'hero')
const variantsHeroDisabled = variantsBoardList.map((entry) =>
entry.name === 'hero' ? { ...entry, enabled: false } : entry,
)
const variantsMediaStates: Record<string, VisualState> = {
'Entry: sidebar': {
path: '/media',
origin: mediaOrigin,
api: mediaApi({ 'GET /v1/auth/me': variantsSession }),
steps: async (page) => {
if (isMobileViewport(page)) {
await page.locator('[data-slot="toggle"]').first().click()
}
await page
.locator(
'nav[aria-label="Main"]:visible a[href="/settings"] [data-slot="linkTrailing"]',
)
.click()
await page.mouse.move(0, 0)
await page.waitForTimeout(250)
},
},
'3a · Grid with badges': variantsMediaState(),
'3b · Sort menu': variantsMediaState(
{},
async (page) => {
await openSortMenuOf(page)
await page.mouse.move(0, 0)
},
'/media?sort=total_size',
),
'3c · Filter: With variants, sorted by total size': variantsMediaState(
{},
undefined,
'/media?variants=with&sort=total_size',
[1, 7, 9, 12, 5, 11, 2, 3, 10],
),
'3d · Filter: Without variants': variantsMediaState(
{},
undefined,
'/media?variants=without',
[4, 6, 8],
),
'3e · Filter: nothing to show': variantsMediaState({}, undefined, '/media?variants=with', []),
'3f · Delete confirm': variantsMediaState({}, async (page) => {
await openImagePanel(page)
await page.getByRole('dialog').getByRole('button', { name: 'Delete', exact: true }).click()
await page.getByRole('alertdialog').waitFor()
await page.mouse.move(0, 0)
}),
'4a · Partly generated': variantsTabState(variantsPartlyGenerated),
'4b · Nothing generated yet': variantsTabState([]),
'4c · Generating': variantsTabState(
['thumb'],
{
'POST /v1/media/1/variants/card': { status: 200, hang: true },
'POST /v1/media/1/variants/hero': { status: 200, hang: true },
},
async (page) => {
await variantRow(page, 'card').getByRole('button', { name: 'Generate now' }).click()
await variantRow(page, 'hero').getByRole('button', { name: 'Generate now' }).click()
await page.mouse.move(0, 0)
},
),
'4d · Generation failed': variantsTabState(
['thumb'],
{ 'POST /v1/media/1/variants': variantsFailedGeneration },
async (page) => {
await page.getByRole('button', { name: 'Generate all', exact: true }).click()
await variantRow(page, 'card').getByText('Failed').waitFor()
await page.mouse.move(0, 0)
},
),
'4e · No variants defined': {
path: variantsMediaPath,
api: variantsMediaApi(undefined, {
'GET /v1/media/1/variants': { status: 200, body: { unsupported: null, items: [] } },
}),
steps: async (page) => {
await openVariantsTabOf(page)
},
},
'4f · Source is an SVG': {
path: variantsMediaPath,
api: variantsMediaApi(undefined, {
'GET /v1/media/4/variants': { status: 200, body: { unsupported: 'svg', items: [] } },
'GET /v1/media/4/usage': { status: 200, body: [] },
}),
steps: async (page) => {
await openVariantsTabOf(page, variantsSvgId)
},
},
'4h · Preview dialog': variantsTabState(variantsPartlyGenerated, {}, async (page) => {
await variantRow(page, 'thumb').getByRole('button', { name: 'Preview' }).click()
await page.getByRole('dialog').filter({ hasText: 'Preview: thumb' }).waitFor()
await page.mouse.move(0, 0)
}),
}
const variantsEditorStates: Record<string, VisualState> = {
'6a · Variant select': variantsPickerState(variantsBoardList, async (page) => {
await openImageUploader(page)
await selectPickerTile(page, 'north-wall.jpg')
await chooseBoardVariant(page, 'Hero')
}),
'6b · Select open': variantsPickerState(variantsBoardList, async (page) => {
await openImageUploader(page)
await selectPickerTile(page, 'north-wall.jpg')
await page.getByTestId('variant-select').click()
await page.getByRole('listbox').waitFor()
await page.mouse.move(0, 0)
}),
'6c · No variants defined': variantsPickerState([], async (page) => {
await openImageUploader(page)
await selectPickerTile(page, 'north-wall.jpg')
await page.getByTestId('variant-help').waitFor()
await page.mouse.move(0, 0)
}),
'6d · Variant deleted': variantsBlockState(variantsWithoutHero),
'6e · Variant disabled': variantsBlockState(variantsHeroDisabled),
}
const boardPredatesPages = 'board predates current Media page and editor'
const variantExceptionCaps: Record<string, { desktop: number; mobile: number }> = {
'3a': { desktop: 28, mobile: 42 },
'3b': { desktop: 28, mobile: 42 },
'3c': { desktop: 28, mobile: 42 },
'3d': { desktop: 10, mobile: 39 },
'3e': { desktop: 10, mobile: 39 },
'3f': { desktop: 78, mobile: 54 },
'4a': { desktop: 15, mobile: 10 },
'4b': { desktop: 15, mobile: 10 },
'4c': { desktop: 15, mobile: 10 },
'4d': { desktop: 15, mobile: 10 },
'4e': { desktop: 15, mobile: 10 },
'4f': { desktop: 15, mobile: 10 },
'6a': { desktop: 29, mobile: 52 },
'6b': { desktop: 29, mobile: 52 },
'6c': { desktop: 29, mobile: 52 },
'6d': { desktop: 29, mobile: 52 },
'6e': { desktop: 29, mobile: 52 },
}
function withVariantExceptions(states: Record<string, VisualState>) {
return Object.fromEntries(
Object.entries(states).map(([name, state]) => {
const cap = variantExceptionCaps[name.slice(0, 2)]
return [
name,
cap
? {
...state,
exception: {
maxPercent: cap,
reason: boardPredatesPages,
approvedBy: 'user',
},
}
: state,
]
}),
)
}
export const visualStates: Record<string, Record<string, VisualState>> = {
activity: activityStates,
profile: {
@@ -4566,7 +4927,11 @@ export const visualStates: Record<string, Record<string, VisualState>> = {
steps: submitAcceptInvite('lea', 'limewash2026'),
},
},
'image-variants': variantsStates,
'image-variants': {
...variantsStates,
...withVariantExceptions(variantsMediaStates),
...withVariantExceptions(variantsEditorStates),
},
media: { ...mediaStates, ...mediaPurgeStates },
'media-picker': pickerStates,
}