Files
tehran_taj/apps/user-app-v2/src/utils/image.ts
T

45 lines
1.9 KiB
TypeScript
Raw Normal View History

import { shallowRef } from 'vue'
// Uploaded images through the API's resize endpoint (GET /api/img/:file?w=).
// Anything that is not a plain upload path (blob:, data:, bundled assets,
// absolute URLs) is returned untouched.
const UPLOAD_PREFIXES = ['/uploads/', '/api/uploads/']
/** Must match IMAGE_WIDTHS in apps/api image-variants.service.ts. */
export type ImageWidth = 200 | 400 | 600 | 800 | 1200 | 1600
export function imageUrl(url: string | null | undefined, width: ImageWidth): string | undefined {
if (!url) return undefined
const prefix = UPLOAD_PREFIXES.find((p) => url.startsWith(p))
if (!prefix) return url
const name = url.slice(prefix.length)
// Preserve encoded names, query strings and fragments as actual original URLs.
if (!name || /[/\\%?#]/.test(name)) return url
return `/api/img/${encodeURIComponent(name)}?w=${width}`
}
/** Only invert our generated resize URLs, never external/blob/data images. */
export function originalImageUrl(url: string): string | undefined {
const prefix = '/api/img/'
if (!url.startsWith(prefix)) return undefined
try {
const name = decodeURIComponent(url.slice(prefix.length).split(/[?#]/, 1)[0] ?? '')
if (!name || name === '.' || name === '..' || /[/\\\u0000]/.test(name)) return undefined
return `/uploads/${encodeURIComponent(name)}`
} catch {
return undefined
}
}
/** Reactive state prevents a later render from restoring a failed thumbnail. */
export function useImageFallback() {
const failed = shallowRef<ReadonlySet<string>>(new Set())
const imageSource = (url: string | undefined): string | undefined =>
url && failed.value.has(url) ? originalImageUrl(url) ?? url : url
function imageFailed(url: string | undefined) {
if (!url || failed.value.has(url) || !originalImageUrl(url)) return
failed.value = new Set([...failed.value, url])
}
return { imageSource, imageFailed }
}