perf(image): 图片列表默认加载缩略图

This commit is contained in:
yml
2026-11-24 22:30:37 +08:00
parent 3cc61615f9
commit 43df96a973
22 changed files with 227 additions and 85 deletions
+18 -1
View File
@@ -247,7 +247,14 @@ func (h *Handler) writeObject(c *gin.Context, publicOnly bool) {
} }
storageStart := time.Now() storageStart := time.Now()
object, err := h.storage.Get(c.Request.Context(), key) var object *Object
var err error
for _, readKey := range objectReadKeys(key) {
object, err = h.storage.Get(c.Request.Context(), readKey)
if err == nil {
break
}
}
storageMS := float64(time.Since(storageStart).Microseconds()) / 1000 storageMS := float64(time.Since(storageStart).Microseconds()) / 1000
if err != nil { if err != nil {
fields := []zap.Field{ fields := []zap.Field{
@@ -308,6 +315,16 @@ func (h *Handler) writeObject(c *gin.Context, publicOnly bool) {
} }
} }
// objectReadKeys 为图片变体提供原图回退,兼容启用缩略图之前上传的历史文件。
func objectReadKeys(key string) []string {
keys := []string{key}
canonical := filekey.Canonical(key)
if canonical != "" && canonical != key {
keys = append(keys, canonical)
}
return keys
}
func isPublicObjectKey(key string) bool { func isPublicObjectKey(key string) bool {
for _, prefix := range []string{ for _, prefix := range []string{
"home-banner/", "home-banner/",
@@ -0,0 +1,37 @@
package file
import (
"reflect"
"testing"
)
func TestObjectReadKeysFallsBackToOriginalImage(t *testing.T) {
tests := []struct {
name string
key string
want []string
}{
{
name: "original key",
key: "listing/account.webp",
want: []string{"listing/account.webp"},
},
{
name: "thumbnail fallback",
key: "listing/account.webp.thumb.jpg",
want: []string{"listing/account.webp.thumb.jpg", "listing/account.webp"},
},
{
name: "medium fallback",
key: "listing/account.webp.medium.jpg",
want: []string{"listing/account.webp.medium.jpg", "listing/account.webp"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := objectReadKeys(tt.key); !reflect.DeepEqual(got, tt.want) {
t.Fatalf("objectReadKeys(%q) = %#v, want %#v", tt.key, got, tt.want)
}
})
}
}
@@ -2,6 +2,7 @@
import { computed, onBeforeUnmount, ref, watch } from 'vue' import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { fetchAdminFileBlob, fetchFileBlobByURL } from '@/shared/api/files' import { fetchAdminFileBlob, fetchFileBlobByURL } from '@/shared/api/files'
import { isAdminPath } from '@/shared/utils/adminPath' import { isAdminPath } from '@/shared/utils/adminPath'
import { getFileVariantURL } from '@/shared/utils/fileURLs'
const props = defineProps<{ const props = defineProps<{
source: string source: string
@@ -11,6 +12,8 @@ const props = defineProps<{
const objectURL = ref('') const objectURL = ref('')
const failed = ref(false) const failed = ref(false)
const effectiveAdmin = computed(() => props.admin || isAdminPath(window.location.pathname)) const effectiveAdmin = computed(() => props.admin || isAdminPath(window.location.pathname))
const thumbnailURL = computed(() => getFileVariantURL(props.source, 'thumb'))
const previewURL = computed(() => getFileVariantURL(props.source, 'medium'))
function extractObjectKey(value: string) { function extractObjectKey(value: string) {
try { try {
@@ -35,20 +38,32 @@ async function loadImage() {
return return
} }
try { try {
const key = extractObjectKey(props.source) const key = extractObjectKey(thumbnailURL.value)
const blob = const blob =
effectiveAdmin.value && key effectiveAdmin.value && key
? await fetchAdminFileBlob(key) ? await fetchAdminFileBlob(key)
: await fetchFileBlobByURL(props.source) : await fetchFileBlobByURL(thumbnailURL.value)
objectURL.value = URL.createObjectURL(blob) objectURL.value = URL.createObjectURL(blob)
} catch { } catch {
failed.value = true failed.value = true
} }
} }
function openImage() { async function openImage() {
if (!objectURL.value) return try {
window.open(objectURL.value, '_blank') const key = extractObjectKey(previewURL.value)
const blob =
effectiveAdmin.value && key
? await fetchAdminFileBlob(key)
: await fetchFileBlobByURL(previewURL.value)
const previewObjectURL = URL.createObjectURL(blob)
window.open(previewObjectURL, '_blank')
window.setTimeout(() => URL.revokeObjectURL(previewObjectURL), 60_000)
} catch {
if (objectURL.value) {
window.open(objectURL.value, '_blank')
}
}
} }
watch(() => [props.source, effectiveAdmin.value] as const, loadImage, { immediate: true }) watch(() => [props.source, effectiveAdmin.value] as const, loadImage, { immediate: true })
@@ -2,7 +2,7 @@
import { computed, ref, watch } from 'vue' import { computed, ref, watch } from 'vue'
import { EditPen, FullScreen, Pointer } from '@element-plus/icons-vue' import { EditPen, FullScreen, Pointer } from '@element-plus/icons-vue'
import type { Listing } from '@/features/listings' import type { Listing } from '@/features/listings'
import { formatListingCode } from '@/shared/utils/listingDisplay' import { formatListingCode, getScreenshotThumbURL } from '@/shared/utils/listingDisplay'
interface ReviewScreenshotItem { interface ReviewScreenshotItem {
url: string url: string
@@ -13,7 +13,6 @@ interface ReviewScreenshotItem {
const props = defineProps<{ const props = defineProps<{
visible: boolean visible: boolean
listing: Listing | null listing: Listing | null
previewUrls: Record<string, string>
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
@@ -140,7 +139,12 @@ function handleEdit(shot: ReviewScreenshotItem) {
@click="handleView(index)" @click="handleView(index)"
> >
<div class="image-wrapper"> <div class="image-wrapper">
<img :src="previewUrls[shot.url] || shot.url" :alt="shot.label" loading="lazy" /> <img
:src="getScreenshotThumbURL(shot.url)"
:alt="shot.label"
loading="lazy"
decoding="async"
/>
<span v-if="isDefaultScreenshot(shot.url)" class="default-badge">默认占位图</span> <span v-if="isDefaultScreenshot(shot.url)" class="default-badge">默认占位图</span>
<span class="category-tag">{{ shot.label }}</span> <span class="category-tag">{{ shot.label }}</span>
<div class="image-overlay" @click.stop> <div class="image-overlay" @click.stop>
@@ -545,6 +545,7 @@ function hasMore(item: ProcessTimelineEvent) {
preview-teleported preview-teleported
fit="cover" fit="cover"
admin admin
variant="thumb"
image-class="attachment-img" image-class="attachment-img"
fallback-class="attachment-fallback" fallback-class="attachment-fallback"
/> />
@@ -307,6 +307,7 @@ function incomeText(income?: number) {
:key="idx" :key="idx"
:source="url" :source="url"
:admin="true" :admin="true"
variant="thumb"
:preview-src-list="withdrawal.certificate_urls" :preview-src-list="withdrawal.certificate_urls"
fit="cover" fit="cover"
:image-style="{ :image-style="{
@@ -351,6 +352,7 @@ function incomeText(income?: number) {
<AuthImage <AuthImage
:source="withdrawal.payment_proof_url" :source="withdrawal.payment_proof_url"
admin admin
variant="thumb"
alt="打款凭证" alt="打款凭证"
class="certificate-image" class="certificate-image"
:preview-src-list="[withdrawal.payment_proof_url]" :preview-src-list="[withdrawal.payment_proof_url]"
@@ -645,6 +645,7 @@ async function handleArbitrate() {
v-if="evidenceKind(item) === 'image'" v-if="evidenceKind(item) === 'image'"
:source="evidenceSource(item)" :source="evidenceSource(item)"
admin admin
variant="thumb"
:alt="evidenceName(item, index)" :alt="evidenceName(item, index)"
image-class="evidence-image" image-class="evidence-image"
fallback-class="evidence-image-fallback" fallback-class="evidence-image-fallback"
@@ -458,6 +458,7 @@ onBeforeUnmount(() => {
<AuthImage <AuthImage
:source="row.image_url" :source="row.image_url"
fit="contain" fit="contain"
variant="thumb"
:image-style="{ width: '64px', height: '64px', background: '#f7f9fc' }" :image-style="{ width: '64px', height: '64px', background: '#f7f9fc' }"
:preview-src-list="[row.image_url]" :preview-src-list="[row.image_url]"
/> />
@@ -883,6 +883,8 @@ function accountTypeLabel(type: string) {
:source="createForm.voucher_url" :source="createForm.voucher_url"
alt="凭证预览" alt="凭证预览"
class="voucher-img-preview" class="voucher-img-preview"
variant="thumb"
:preview-src-list="[createForm.voucher_url]"
/> />
</div> </div>
</div> </div>
@@ -948,7 +950,13 @@ function accountTypeLabel(type: string) {
<div v-if="selectedManual.voucher_url" class="detail-row column-row"> <div v-if="selectedManual.voucher_url" class="detail-row column-row">
<span class="detail-label">打款凭证</span> <span class="detail-label">打款凭证</span>
<div class="detail-img-container"> <div class="detail-img-container">
<AuthImage :source="selectedManual.voucher_url" alt="凭证" class="detail-voucher-img" /> <AuthImage
:source="selectedManual.voucher_url"
alt="凭证"
class="detail-voucher-img"
variant="thumb"
:preview-src-list="[selectedManual.voucher_url]"
/>
</div> </div>
</div> </div>
<div v-if="selectedManual.status === 'voided'" class="void-info-box"> <div v-if="selectedManual.status === 'voided'" class="void-info-box">
@@ -1028,6 +1028,7 @@ async function openScreenshot(url: string) {
<AuthImage <AuthImage
:source="url" :source="url"
admin admin
variant="thumb"
:alt="`资产截图 ${index + 1}`" :alt="`资产截图 ${index + 1}`"
image-class="screenshot-image" image-class="screenshot-image"
fallback-class="screenshot-image" fallback-class="screenshot-image"
@@ -54,6 +54,8 @@ import {
getFaceOwnerText, getFaceOwnerText,
getListingConsumablePrice, getListingConsumablePrice,
getListingResources, getListingResources,
getScreenshotMediumURL,
getScreenshotThumbURL,
getOnlineTimeText, getOnlineTimeText,
getResourceQuantity, getResourceQuantity,
getSkinNames, getSkinNames,
@@ -144,7 +146,6 @@ const filters = reactive({
sortBy: 'default', sortBy: 'default',
}) })
const previewURLs = reactive<Record<string, string>>({}) const previewURLs = reactive<Record<string, string>>({})
const createdObjectURLs = new Set<string>()
const lastRefreshedAt = ref<string>('') const lastRefreshedAt = ref<string>('')
const shortcutsDialogVisible = ref(false) const shortcutsDialogVisible = ref(false)
@@ -249,7 +250,7 @@ watch(
if (!listing) return if (!listing) return
selectedID.value = listing.id selectedID.value = listing.id
await nextTick() await nextTick()
loadScreenshotPreviews(listing) prepareScreenshotPreviews(listing)
}, },
{ immediate: true } { immediate: true }
) )
@@ -260,7 +261,6 @@ onMounted(() => {
}) })
onBeforeUnmount(() => { onBeforeUnmount(() => {
createdObjectURLs.forEach(url => URL.revokeObjectURL(url))
window.removeEventListener('keydown', handleGlobalKeydown) window.removeEventListener('keydown', handleGlobalKeydown)
}) })
@@ -455,7 +455,7 @@ async function onPriceAdjustSave(payload: {
function openEvidence(row: Listing) { function openEvidence(row: Listing) {
evidenceListing.value = row evidenceListing.value = row
evidenceDialogVisible.value = true evidenceDialogVisible.value = true
loadScreenshotPreviews(row) prepareScreenshotPreviews(row)
} }
function money(value: number) { function money(value: number) {
@@ -780,21 +780,9 @@ function extractObjectKey(url: string) {
} }
} }
async function loadScreenshotPreviews(row: Listing) { function prepareScreenshotPreviews(row: Listing) {
for (const url of row.screenshot_urls || []) { for (const url of row.screenshot_urls || []) {
if (previewURLs[url]) continue previewURLs[url] = isDefaultScreenshot(url) ? url : getScreenshotMediumURL(url)
if (isDefaultScreenshot(url) || !extractObjectKey(url)) {
previewURLs[url] = url
continue
}
try {
const blob = await fetchAdminFileBlob(extractObjectKey(url))
const objectURL = URL.createObjectURL(blob)
createdObjectURLs.add(objectURL)
previewURLs[url] = objectURL
} catch {
previewURLs[url] = url
}
} }
} }
@@ -890,11 +878,6 @@ function openRawScreenshot(url: string) {
window.open(url, '_blank') window.open(url, '_blank')
return return
} }
const preview = previewURLs[url]
if (preview) {
window.open(preview, '_blank')
return
}
try { try {
const key = extractObjectKey(url) const key = extractObjectKey(url)
if (!key) { if (!key) {
@@ -952,7 +935,7 @@ async function handleScreenshotSaved(payload: { oldUrl: string; newUrl: string }
evidenceListing.value.screenshot_urls = nextUrls evidenceListing.value.screenshot_urls = nextUrls
} }
await loadScreenshotPreviews(targetListing) prepareScreenshotPreviews(targetListing)
editorVisible.value = false editorVisible.value = false
editingScreenshot.value = null editingScreenshot.value = null
} }
@@ -1121,13 +1104,10 @@ async function handleScreenshotSaved(payload: { oldUrl: string; newUrl: string }
<div class="queue-main-row"> <div class="queue-main-row">
<div class="queue-thumb"> <div class="queue-thumb">
<img <img
:src=" :src="getScreenshotThumbURL(item.screenshot_urls?.[0]) || _defaultScreenshotURL"
previewURLs[item.screenshot_urls?.[0] || ''] ||
item.screenshot_urls?.[0] ||
_defaultScreenshotURL
"
alt="缩略图" alt="缩略图"
loading="lazy" loading="lazy"
decoding="async"
@error="onThumbError" @error="onThumbError"
/> />
<span v-if="hasDefaultScreenshot(item)" class="thumb-warning-badge">默认图</span> <span v-if="hasDefaultScreenshot(item)" class="thumb-warning-badge">默认图</span>
@@ -1611,7 +1591,12 @@ async function handleScreenshotSaved(payload: { oldUrl: string; newUrl: string }
@click="handleCardClick(selectedReviewScreenshots, index)" @click="handleCardClick(selectedReviewScreenshots, index)"
> >
<div class="image-wrapper"> <div class="image-wrapper">
<img :src="previewURLs[shot.url] || shot.url" :alt="shot.label" loading="lazy" /> <img
:src="getScreenshotThumbURL(shot.url)"
:alt="shot.label"
loading="lazy"
decoding="async"
/>
<span v-if="isDefaultScreenshot(shot.url)" class="default-badge"> <span v-if="isDefaultScreenshot(shot.url)" class="default-badge">
<el-icon><Warning /></el-icon> 默认占位图 <el-icon><Warning /></el-icon> 默认占位图
</span> </span>
@@ -1742,7 +1727,6 @@ async function handleScreenshotSaved(payload: { oldUrl: string; newUrl: string }
<AdminListingReviewEvidenceDialog <AdminListingReviewEvidenceDialog
v-model:visible="evidenceDialogVisible" v-model:visible="evidenceDialogVisible"
:listing="evidenceListing" :listing="evidenceListing"
:preview-urls="previewURLs"
@view-image="openPreviewDialog($event.images, $event.index)" @view-image="openPreviewDialog($event.images, $event.index)"
@peek-image="startPeekPreview($event.images, $event.index)" @peek-image="startPeekPreview($event.images, $event.index)"
@edit-screenshot="openEditor($event.shot, $event.listing)" @edit-screenshot="openEditor($event.shot, $event.listing)"
@@ -478,6 +478,8 @@ function statusType(status: string): 'success' | 'danger' {
:source="createForm.voucher_url" :source="createForm.voucher_url"
alt="凭证预览" alt="凭证预览"
class="voucher-img-preview" class="voucher-img-preview"
variant="thumb"
:preview-src-list="[createForm.voucher_url]"
/> />
</div> </div>
</div> </div>
@@ -545,6 +547,8 @@ function statusType(status: string): 'success' | 'danger' {
:source="selectedExpense.voucher_url" :source="selectedExpense.voucher_url"
alt="凭证" alt="凭证"
class="detail-voucher-img" class="detail-voucher-img"
variant="thumb"
:preview-src-list="[selectedExpense.voucher_url]"
/> />
</div> </div>
</div> </div>
@@ -696,6 +696,7 @@ onMounted(reloadAll)
<AuthImage <AuthImage
:source="row.image_url" :source="row.image_url"
fit="cover" fit="cover"
variant="thumb"
:image-style="{ width: '56px', height: '56px', borderRadius: '6px' }" :image-style="{ width: '56px', height: '56px', borderRadius: '6px' }"
:preview-src-list="[row.image_url]" :preview-src-list="[row.image_url]"
/> />
@@ -837,6 +838,7 @@ onMounted(reloadAll)
v-if="img.url" v-if="img.url"
:source="img.url" :source="img.url"
fit="cover" fit="cover"
variant="thumb"
:image-style="{ width: '52px', height: '52px', borderRadius: '6px' }" :image-style="{ width: '52px', height: '52px', borderRadius: '6px' }"
:preview-src-list="[img.url]" :preview-src-list="[img.url]"
/> />
@@ -910,6 +912,7 @@ onMounted(reloadAll)
v-if="editForm.image_url" v-if="editForm.image_url"
:source="editForm.image_url" :source="editForm.image_url"
fit="cover" fit="cover"
variant="thumb"
:preview-src-list="[editForm.image_url]" :preview-src-list="[editForm.image_url]"
:image-style="{ width: '100%', height: '100%', borderRadius: '6px' }" :image-style="{ width: '100%', height: '100%', borderRadius: '6px' }"
/> />
@@ -255,6 +255,7 @@ const hasContent = computed(() => Boolean(snapshot.value))
<AuthImage <AuthImage
:source="shot.url" :source="shot.url"
:alt="shot.label" :alt="shot.label"
variant="thumb"
image-class="shot-img" image-class="shot-img"
fit="cover" fit="cover"
:preview-src-list="screenshotUrls" :preview-src-list="screenshotUrls"
@@ -314,6 +315,7 @@ const hasContent = computed(() => Boolean(snapshot.value))
<AuthImage <AuthImage
:source="shot.url" :source="shot.url"
:alt="shot.label" :alt="shot.label"
variant="thumb"
image-class="shot-img" image-class="shot-img"
fit="cover" fit="cover"
:preview-src-list="screenshotUrls" :preview-src-list="screenshotUrls"
@@ -253,6 +253,7 @@ async function handleOffline() {
<AuthImage <AuthImage
:source="detailScreenshots[0].url" :source="detailScreenshots[0].url"
:alt="getListingTitle(listing)" :alt="getListingTitle(listing)"
variant="thumb"
image-class="cover-img" image-class="cover-img"
fit="cover" fit="cover"
:preview-src-list="detailScreenshotUrls" :preview-src-list="detailScreenshotUrls"
@@ -333,6 +334,7 @@ async function handleOffline() {
<AuthImage <AuthImage
:source="shot.url" :source="shot.url"
:alt="shot.label" :alt="shot.label"
variant="thumb"
image-class="shot-img" image-class="shot-img"
fit="cover" fit="cover"
:preview-src-list="detailScreenshotUrls" :preview-src-list="detailScreenshotUrls"
@@ -335,6 +335,7 @@ async function handleOffline() {
<AuthImage <AuthImage
:source="shot.url" :source="shot.url"
:alt="shot.label" :alt="shot.label"
variant="thumb"
image-class="shot-img" image-class="shot-img"
fit="cover" fit="cover"
:preview-src-list="detailScreenshotUrls" :preview-src-list="detailScreenshotUrls"
@@ -260,6 +260,7 @@ function removeImage(index: number) {
:source="url" :source="url"
alt="凭证" alt="凭证"
fit="cover" fit="cover"
variant="thumb"
:preview-src-list="form.certificate_urls" :preview-src-list="form.certificate_urls"
:preview-initial-index="index" :preview-initial-index="index"
/> />
@@ -633,6 +633,7 @@ function statusType(status: string): 'primary' | 'success' | 'danger' | 'warning
:source="url" :source="url"
alt="收款凭证" alt="收款凭证"
fit="cover" fit="cover"
variant="thumb"
:preview-src-list="accountForm.certificate_urls" :preview-src-list="accountForm.certificate_urls"
:preview-initial-index="index" :preview-initial-index="index"
/> />
@@ -2,6 +2,7 @@
import { computed, onBeforeUnmount, ref, watch } from 'vue' import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { fetchAdminFileBlob, fetchFileAccessTicket, fetchFileBlobByURL } from '@/shared/api/files' import { fetchAdminFileBlob, fetchFileAccessTicket, fetchFileBlobByURL } from '@/shared/api/files'
import { isAdminPath } from '@/shared/utils/adminPath' import { isAdminPath } from '@/shared/utils/adminPath'
import { getFileVariantURL, type FileImageVariant } from '@/shared/utils/fileURLs'
const props = withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
@@ -15,6 +16,8 @@ const props = withDefaults(
previewSrcList?: string[] previewSrcList?: string[]
previewTeleported?: boolean previewTeleported?: boolean
previewInitialIndex?: number previewInitialIndex?: number
variant?: FileImageVariant
previewVariant?: FileImageVariant
fit?: 'fill' | 'contain' | 'cover' | 'none' | 'scale-down' fit?: 'fill' | 'contain' | 'cover' | 'none' | 'scale-down'
imageStyle?: any imageStyle?: any
}>(), }>(),
@@ -25,6 +28,8 @@ const props = withDefaults(
fallbackClass: '', fallbackClass: '',
loading: 'lazy', loading: 'lazy',
decoding: 'async', decoding: 'async',
variant: 'raw',
previewVariant: 'medium',
previewTeleported: true, previewTeleported: true,
previewInitialIndex: 0, previewInitialIndex: 0,
} }
@@ -46,6 +51,7 @@ const imageStyleValue = computed(() => {
if (!props.fit) return props.imageStyle if (!props.fit) return props.imageStyle
return [props.imageStyle, { objectFit: props.fit }] return [props.imageStyle, { objectFit: props.fit }]
}) })
const sourceVariantURL = computed(() => getFileVariantURL(props.source, props.variant))
const previewSignature = computed(() => props.previewSrcList?.join('\u0000') || '') const previewSignature = computed(() => props.previewSrcList?.join('\u0000') || '')
function withAuthImageLoadSlot<T>(task: () => Promise<T>): Promise<T> { function withAuthImageLoadSlot<T>(task: () => Promise<T>): Promise<T> {
@@ -130,39 +136,30 @@ async function loadImage() {
} }
try { try {
const sourceURL = await resolveURL(props.source) const sourceURL = await resolveURL(sourceVariantURL.value)
imageURL.value = sourceURL imageURL.value = sourceURL
if (props.previewSrcList?.length) { if (props.previewSrcList?.length) {
// 先填充公开或当前已解析的主图 URL,让预览组件立即可用 previewURLs.value = props.previewSrcList.map(url =>
const initialPreviews = props.previewSrcList.map(url => url === props.source ? sourceURL : getFileVariantURL(url, props.previewVariant)
url === props.source ? sourceURL : url
) )
previewURLs.value = initialPreviews
// 若包含需要鉴权转 Blob 的私有 URL,在后台异步静默解析,不阻塞主图呈现
const hasAuthPreviews = props.previewSrcList.some(
url => url !== props.source && shouldFetchWithAuth(url)
)
if (hasAuthPreviews) {
Promise.all(
props.previewSrcList.map(url => (url === props.source ? sourceURL : resolveURL(url)))
)
.then(urls => {
previewURLs.value = urls
})
.catch(() => {
// 预览图静默降级,不破坏主图正常显示
})
}
} }
} catch { } catch {
failed.value = true failed.value = true
} }
} }
watch(() => [props.source, effectiveAdmin.value, previewSignature.value] as const, loadImage, { watch(
immediate: true, () =>
}) [
props.source,
props.variant,
props.previewVariant,
effectiveAdmin.value,
previewSignature.value,
] as const,
loadImage,
{ immediate: true }
)
onBeforeUnmount(cleanup) onBeforeUnmount(cleanup)
</script> </script>
@@ -6,6 +6,9 @@ import {
getListingResources, getListingResources,
getListingSellerCoinPrice, getListingSellerCoinPrice,
getListingSellerPrice, getListingSellerPrice,
getScreenshotMediumURL,
getScreenshotRawURL,
getScreenshotThumbURL,
isNonOwnFace, isNonOwnFace,
} from '../listingDisplay' } from '../listingDisplay'
import type { PublicListingItem } from '@/features/listings/api/listings' import type { PublicListingItem } from '@/features/listings/api/listings'
@@ -99,6 +102,39 @@ describe('本人人脸展示', () => {
}) })
}) })
describe('截图变体 URL', () => {
const objectURL = '/api/files/object?key=listing%2F2026%2F11%2Faccount.webp'
it('私有对象 URL 使用已生成的缩略图和中等图', () => {
expect(getScreenshotThumbURL(objectURL)).toBe(
'/api/files/object?key=listing%2F2026%2F11%2Faccount.thumb.jpg'
)
expect(getScreenshotMediumURL(objectURL)).toBe(
'/api/files/object?key=listing%2F2026%2F11%2Faccount.medium.jpg'
)
})
it('原图 URL 不做变体转换', () => {
expect(getScreenshotRawURL(objectURL)).toBe(objectURL)
})
it('已带图片变体的 URL 不会重复叠加后缀', () => {
const mediumURL = '/api/files/object?key=listing%2Faccount.webp.medium.jpg'
expect(getScreenshotMediumURL(mediumURL)).toBe(
'/api/files/object?key=listing%2Faccount.medium.jpg'
)
expect(getScreenshotThumbURL(mediumURL)).toBe(
'/api/files/object?key=listing%2Faccount.thumb.jpg'
)
})
it('兼容公开截图站点的 variant 参数', () => {
expect(getScreenshotThumbURL('/api/listings/1/screenshots/0')).toBe(
'/api/listings/1/screenshots/0?variant=thumb'
)
})
})
describe('首页规格芯片 · 德穆兰优先级高于全英雄', () => { describe('首页规格芯片 · 德穆兰优先级高于全英雄', () => {
it('解锁德穆兰时用「解锁德穆兰」替换「全英雄」', () => { it('解锁德穆兰时用「解锁德穆兰」替换「全英雄」', () => {
const chips = getListingChips(buildListing({ all_hero: '是', unlock_demulan: '是' })) const chips = getListingChips(buildListing({ all_hero: '是', unlock_demulan: '是' }))
+38
View File
@@ -0,0 +1,38 @@
export type FileImageVariant = 'thumb' | 'medium' | 'raw'
function withObjectVariant(url: string, variant: Exclude<FileImageVariant, 'raw'>): string {
const separatorIndex = url.indexOf('?')
const pathname = separatorIndex >= 0 ? url.slice(0, separatorIndex) : url
if (!pathname.endsWith('/files/object')) return ''
const params = new URLSearchParams(separatorIndex >= 0 ? url.slice(separatorIndex + 1) : '')
const key = params.get('key') || ''
if (!key) return ''
const withoutVariant = key.replace(/\.(?:thumb|medium)\.jpg$/i, '')
const slashIndex = withoutVariant.lastIndexOf('/')
const dotIndex = withoutVariant.lastIndexOf('.')
const base = dotIndex > slashIndex ? withoutVariant.slice(0, dotIndex) : withoutVariant
params.set('key', `${base}.${variant}.jpg`)
return `${pathname}?${params.toString()}`
}
/**
* 将私有对象或公开截图地址转换为上传时生成的图片变体。
* 非图片对象、外链和无法识别的地址保持原样。
*/
export function getFileVariantURL(
url: string | undefined | null,
variant: FileImageVariant
): string {
if (!url) return ''
if (variant === 'raw') return url
const objectVariantURL = withObjectVariant(url, variant)
if (objectVariantURL) return objectVariantURL
if (url.includes('/screenshots/')) {
const separator = url.includes('?') ? '&' : '?'
return `${url}${separator}variant=${variant}`
}
return url
}
+6 -20
View File
@@ -1,4 +1,5 @@
import type { Listing, PublicListingItem } from '@/features/listings/api/listings' import type { Listing, PublicListingItem } from '@/features/listings/api/listings'
import { getFileVariantURL } from '@/shared/utils/fileURLs'
import { centToYuan } from '@/shared/utils/money' import { centToYuan } from '@/shared/utils/money'
export interface ListingDisplayChip { export interface ListingDisplayChip {
@@ -436,37 +437,22 @@ export function getCoinScreenshotURL(item: Listing): string {
} }
/** /**
* 转换截图为缩略图 URL(优先使用 16KB 极速缩略图,秒级加载) * 转换截图为缩略图 URL(优先使用上传时生成的缩略图,秒级加载)
*/ */
export function getScreenshotThumbURL(url: string | undefined | null): string { export function getScreenshotThumbURL(url: string | undefined | null): string {
if (!url) return '' return getFileVariantURL(url, 'thumb')
if (url.includes('/screenshots/')) {
const separator = url.includes('?') ? '&' : '?'
return `${url}${separator}variant=thumb`
}
return url
} }
/** /**
* 转换截图为中等图 URL(1280px,100KB左右,清晰秒开) * 转换截图为中等图 URL(1280px,100KB左右,适合弹窗预览)
*/ */
export function getScreenshotMediumURL(url: string | undefined | null): string { export function getScreenshotMediumURL(url: string | undefined | null): string {
if (!url) return '' return getFileVariantURL(url, 'medium')
if (url.includes('/screenshots/')) {
const separator = url.includes('?') ? '&' : '?'
return `${url}${separator}variant=medium`
}
return url
} }
/** /**
* 转换截图为原始高清原图 URL(用于全屏放大查看细节) * 转换截图为原始高清原图 URL(用于全屏放大查看细节)
*/ */
export function getScreenshotRawURL(url: string | undefined | null): string { export function getScreenshotRawURL(url: string | undefined | null): string {
if (!url) return '' return getFileVariantURL(url, 'raw')
if (url.includes('/screenshots/')) {
const separator = url.includes('?') ? '&' : '?'
return `${url}${separator}variant=raw`
}
return url
} }