feat: image variants per image

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

No files matched your search

@@ -0,0 +1,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>