Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement responsive height to sizes prop #1324

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 71 additions & 13 deletions src/runtime/image.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import { defu } from 'defu'
import { hasProtocol, parseURL, joinURL, withLeadingSlash } from 'ufo'
import type { ImageOptions, ImageSizesOptions, CreateImageOptions, ResolvedImage, ImageCTX, $Img, ImageSizes, ImageSizesVariant } from '../types/image'
import type {
ImageOptions,
ImageSizesOptions,
CreateImageOptions,
ResolvedImage,
ImageCTX,
$Img,
ImageSizes,
ImageSizesVariant,
WidthAndHeightFromSize,
HandleVariantHeightOptions
} from '../types/image'
import { imageMeta } from './utils/meta'
import { checkDensities, parseDensities, parseSize, parseSizes } from './utils'
import { prerenderStaticImages } from './utils/prerender'
Expand Down Expand Up @@ -201,39 +212,86 @@ function getSizes (ctx: ImageCTX, input: string, opts: ImageSizesOptions): Image
}
}

function getSizesVariant (key: string, size: string, height: number | undefined, hwRatio: number, ctx: ImageCTX): ImageSizesVariant | undefined {
const screenMaxWidth = (ctx.options.screens && ctx.options.screens[key]) || parseInt(key)
const isFluid = size.endsWith('vw')
if (!isFluid && /^\d+$/.test(size)) {
size = size + 'px'
function getWidthAndHeightFromSize (size: string): WidthAndHeightFromSize {
if (size.includes('/')) {
const [widthFromSize, heightFromSize] = size.split('/')
return { widthFromSize, heightFromSize }
}
if (!isFluid && !size.endsWith('px')) {
return { widthFromSize: size, heightFromSize: null }
}

function handleVariantHeight ({
heightFromSize,
hwRatio,
_cWidth,
height
}: HandleVariantHeightOptions): number | undefined {
if (heightFromSize) {
return parseInt(heightFromSize)
}
if (hwRatio) {
return Math.round(_cWidth * hwRatio)
}
return height
}

function getSizesVariant (
key: string,
size: string,
height: number | undefined,
hwRatio: number,
ctx: ImageCTX
): ImageSizesVariant | undefined {
const screenMaxWidth =
(ctx.options.screens && ctx.options.screens[key]) || parseInt(key)

// eslint-disable-next-line prefer-const
let { widthFromSize, heightFromSize } = getWidthAndHeightFromSize(size)
const isFluid = widthFromSize.endsWith('vw')
if (!isFluid && /^\d+$/.test(widthFromSize)) {
widthFromSize = widthFromSize + 'px'
}
if (!isFluid && !widthFromSize.endsWith('px')) {
return undefined
}
let _cWidth = parseInt(size)
let _cWidth = parseInt(widthFromSize)
if (!screenMaxWidth || !_cWidth) {
return undefined
}
if (isFluid) {
_cWidth = Math.round((_cWidth / 100) * screenMaxWidth)
}
const _cHeight = hwRatio ? Math.round(_cWidth * hwRatio) : height

const _cHeight = handleVariantHeight({
heightFromSize,
hwRatio,
_cWidth,
height
})
return {
size,
size: widthFromSize,
screenMaxWidth,
_cWidth,
_cHeight
}
}

function getVariantSrc (ctx: ImageCTX, input: string, opts: ImageSizesOptions, variant: ImageSizesVariant, density: number) {
return ctx.$img!(input,
function getVariantSrc (
ctx: ImageCTX,
input: string,
opts: ImageSizesOptions,
variant: ImageSizesVariant,
density: number
) {
return ctx.$img!(
input,
{
...opts.modifiers,
width: variant._cWidth ? variant._cWidth * density : undefined,
height: variant._cHeight ? variant._cHeight * density : undefined
},
opts)
opts
)
}

function finaliseSizeVariants (sizeVariants: any[]) {
Expand Down
23 changes: 16 additions & 7 deletions src/runtime/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,24 +108,33 @@ export function parseDensities (input: string | undefined = ''): number[] {

export function checkDensities (densities: number[]) {
if (densities.length === 0) {
throw new Error('`densities` must not be empty, configure to `1` to render regular size only (DPR 1.0)')
throw new Error(
'`densities` must not be empty, configure to `1` to render regular size only (DPR 1.0)'
)
}
if (process.dev && Array.from(densities).some(d => d > 2)) {
// eslint-disable-next-line no-console
console.warn('[nuxt] [image] Density values above `2` are not recommended. See https://observablehq.com/@eeeps/visual-acuity-and-device-pixel-ratio.')
console.warn(
'[nuxt] [image] Density values above `2` are not recommended. See https://observablehq.com/@eeeps/visual-acuity-and-device-pixel-ratio.'
)
}
}

export function parseSizes (input: Record<string, string | number> | string): Record<string, string> {
export function parseSizes (
input: Record<string, string | number> | string
): Record<string, string> {
const sizes: Record<string, string> = {}
// string => object
if (typeof input === 'string') {
for (const entry of input.split(/[\s,]+/).filter(e => e)) {
const s = entry.split(':')
if (s.length !== 2) {
sizes['1px'] = s[0].trim()
const sizeParts = entry.split(':')
if (sizeParts.length !== 2) {
const [size] = sizeParts
const DEFAULT_BREAKPOINT = '1px'
sizes[DEFAULT_BREAKPOINT] = size.trim()
} else {
sizes[s[0].trim()] = s[1].trim()
const [breakpoint, size] = sizeParts
sizes[breakpoint.trim()] = size.trim()
}
}
} else {
Expand Down
12 changes: 12 additions & 0 deletions src/types/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,15 @@ export interface ImageSizesVariant {
_cWidth: number
_cHeight?: number | undefined
}

export type WidthAndHeightFromSize = {
widthFromSize: string;
heightFromSize: string | null;
};

export type HandleVariantHeightOptions = {
heightFromSize:WidthAndHeightFromSize['heightFromSize'];
hwRatio:number;
_cWidth:number;
height?:number;
}
9 changes: 9 additions & 0 deletions test/unit/image.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,15 @@ describe('Renders simple image', () => {
const domNonce = img.element.getAttribute('nonce')
expect(domNonce).toBe('stub-nonce')
})

it('works with responsive height', () => {
const img = mountImage({
src: '/image.png',
sizes: '100px/20px sm:100px/10px md:10px lg:200px/50px',
densities: 'x1 x2'
})
expect(img.html()).toMatchInlineSnapshot('"<img src="/_ipx/s_400x100/image.png" data-nuxt-img="" sizes="(max-width: 640px) 100px, (max-width: 768px) 100px, (max-width: 1024px) 10px, 200px" srcset="/_ipx/w_10/image.png 10w, /_ipx/w_20/image.png 20w, /_ipx/s_100x10/image.png 100w, /_ipx/s_200x50/image.png 200w, /_ipx/s_400x100/image.png 400w">"')
})
})

const getImageLoad = (cb = () => {}) => {
Expand Down