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

Add support for densities #634

Open
wants to merge 1 commit into
base: v0
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions playground/pages/responsive.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@
<nuxt-img
src="/logos/nuxt.png"
sizes="sm:100vw md:50vw lg:400px"
densities="1x"
loading="lazy"
/>
<br>
<nuxt-picture
src="/logos/nuxt.png"
sizes="sm:100vw md:50vw lg:400px"
densities="1x"
loading="lazy"
/>
</div>
Expand Down
1 change: 1 addition & 0 deletions src/runtime/components/image.mixin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const imageMixin = defineMixin({
provider: { type: String, default: undefined },

sizes: { type: [Object, String] as unknown as () => string | Record<string, any>, default: undefined },
densities: { type: String, default: undefined },
preload: { type: Boolean, default: undefined },

// <img> attributes
Expand Down
2 changes: 2 additions & 0 deletions src/runtime/components/nuxt-img.vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const defineComponent: DefineComponentWithMixin = (opts: any) => opts
type NAttrs = typeof imageMixin['nImgAttrs'] & {
sizes?: string
srcset?: string
densities?: string
}

export default defineComponent({
Expand Down Expand Up @@ -54,6 +55,7 @@ export default defineComponent({
return this.$img.getSizes(this.src, {
...this.nOptions,
sizes: this.sizes,
densities: this.densities,
modifiers: {
...this.nModifiers,
width: parseSize(this.width),
Expand Down
1 change: 1 addition & 0 deletions src/runtime/components/nuxt-picture.vue
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export default defineComponent({
const { srcset, sizes, src } = this.$img.getSizes(this.src, {
...this.nOptions,
sizes: this.sizes || this.$img.options.screens,
densities: this.densities,
modifiers: {
...this.nModifiers,
format
Expand Down
40 changes: 31 additions & 9 deletions src/runtime/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import defu from 'defu'
import { hasProtocol, parseURL, joinURL, withLeadingSlash } from 'ufo'
import type { ImageOptions, ImageSizesOptions, CreateImageOptions, ResolvedImage, MapToStatic, ImageCTX, $Img } from '../types/image'
import { imageMeta } from './utils/meta'
import { parseSize } from './utils'
import { parseDensities, parseSize } from './utils'
import { useStaticImageMap } from './utils/static-map'

export function createImage (globalOptions: CreateImageOptions, nuxtContext: any) {
Expand Down Expand Up @@ -161,8 +161,10 @@ function getPreset (ctx: ImageCTX, name?: string): ImageOptions {
function getSizes (ctx: ImageCTX, input: string, opts: ImageSizesOptions) {
const width = parseSize(opts.modifiers?.width)
const height = parseSize(opts.modifiers?.height)
const densities = opts.densities ? parseDensities(opts.densities) : [1, 2]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this would mean a default of 1x 2x ?

Not sure if 2x should be added by default. This could lead to confusion for many users. 🤔
Further, it would change the behaviour on upgrade.

Suggested improvement: allow to configure the default globally via nuxt.config.

const hwRatio = (width && height) ? height / width : 0
const variants = []
const sizeVariants = []
const srcVariants = []

const sizes: Record<string, string> = {}

Expand Down Expand Up @@ -195,25 +197,45 @@ function getSizes (ctx: ImageCTX, input: string, opts: ImageSizesOptions) {
_cWidth = Math.round((_cWidth / 100) * screenMaxWidth)
}
const _cHeight = hwRatio ? Math.round(_cWidth * hwRatio) : height
variants.push({
sizeVariants.push({
width: _cWidth,
size,
screenMaxWidth,
media: `(max-width: ${screenMaxWidth}px)`,
src: ctx.$img!(input, { ...opts.modifiers, width: _cWidth, height: _cHeight }, opts)
})

if (densities) {
for (const density of densities) {
srcVariants.push({
width: _cWidth * density,
src: ctx.$img!(input, { ...opts.modifiers, width: _cWidth * density, height: _cHeight ? _cHeight * density : undefined }, opts)
})
}
}
}

variants.sort((v1, v2) => v1.screenMaxWidth - v2.screenMaxWidth)
sizeVariants.sort((v1, v2) => v1.screenMaxWidth - v2.screenMaxWidth)

// Remove duplicate size variants,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about using Set ?

const sizeVariantsUnique = [...new Set(sizeVariants)]

let previousSize = ''

const defaultVar = variants[variants.length - 1]
if (defaultVar) {
defaultVar.media = ''
// Loop in reverse order to allow safe deletion
for (let i = sizeVariants.length - 1; i >= 0; i--) {
const sizeVariant = sizeVariants[i]
if (sizeVariant.media === previousSize) {
sizeVariants.splice(i, 1)
}
previousSize = sizeVariant.size
}

srcVariants.sort((v1, v2) => v1.width - v2.width)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: shouldn't srcVariants also be de-duplicated?


const defaultVar = srcVariants[srcVariants.length - 1]

return {
sizes: variants.map(v => `${v.media ? v.media + ' ' : ''}${v.size}`).join(', '),
srcset: variants.map(v => `${v.src} ${v.width}w`).join(', '),
sizes: sizeVariants.map(v => `${v.media ? v.media + ' ' : ''}${v.size}`).join(', '),
srcset: srcVariants.map(v => `${v.src} ${v.width}w`).join(', '),
src: defaultVar?.src
}
}
7 changes: 7 additions & 0 deletions src/runtime/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,10 @@ export function parseSize (input: string | number | undefined = '') {
}
}
}

export function parseDensities (input: string | undefined = '') {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should be more strictly typed to return number[]

How to deal with invalid input format, maybe it should throw/print some WARN messages and return [] if unable to parse...

if (!input.length) {
return undefined
}
return input.split(' ').map(size => parseInt(size.replace('x', ''), 10))
}
1 change: 1 addition & 0 deletions src/types/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export interface ImageModifiers {
export interface ImageOptions {
provider?: string,
preset?: string,
densities?: string,
modifiers?: Partial<ImageModifiers>
[key: string]: any
}
Expand Down