44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
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,
|
|
)
|
|
}
|