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

wip: responsive image component #12381

Draft
wants to merge 18 commits into
base: responsive-images
Choose a base branch
from
Draft
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
53 changes: 51 additions & 2 deletions packages/astro/components/Image.astro
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
import { type LocalImageProps, type RemoteImageProps, getImage } from 'astro:assets';
import { type LocalImageProps, type RemoteImageProps, getImage, imageConfig } from 'astro:assets';
import { AstroError, AstroErrorData } from '../dist/core/errors/index.js';
import type { HTMLAttributes } from '../types';

Expand Down Expand Up @@ -33,6 +33,55 @@ if (image.srcSet.values.length > 0) {
if (import.meta.env.DEV) {
additionalAttributes['data-image-component'] = 'true';
}

const { experimentalResponsiveImages } = imageConfig;

const layoutClassMap = {
fixed: 'aim-fi',
responsive: 'aim-re',
};

const cssFitValues = ['fill', 'contain', 'cover', 'scale-down'];
const objectFit = props.fit ?? imageConfig.experimentalObjectFit ?? 'cover';
const objectPosition = props.position ?? imageConfig.experimentalObjectPosition ?? 'center';

// The style prop can't be spread when using define:vars, so we need to extract it here
// @see https://github.com/withastro/compiler/issues/1050
const { style, class: className, ...attrs } = { ...additionalAttributes, ...image.attributes };
---

<img src={image.src} {...additionalAttributes} {...image.attributes} />
<img
src={image.src}
{...attrs}
{style}
class:list={[
experimentalResponsiveImages && layoutClassMap[props.layout ?? imageConfig.experimentalLayout],
experimentalResponsiveImages && 'aim',
className,
]}
/>

<style
define:vars={experimentalResponsiveImages && {
w: image.attributes.width ?? props.width ?? image.options.width,
h: image.attributes.height ?? props.height ?? image.options.height,
fit: cssFitValues.includes(objectFit) && objectFit,
pos: objectPosition,
}}
>
.aim {
width: 100%;
height: auto;
object-fit: var(--fit);
object-position: var(--pos);
aspect-ratio: var(--w) / var(--h);
}
.aim-re {
max-width: calc(var(--w) * 1px);
max-height: calc(var(--h) * 1px);
}
.aim-fi {
width: calc(var(--w) * 1px);
height: calc(var(--h) * 1px);
}
</style>
34 changes: 33 additions & 1 deletion packages/astro/src/assets/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from './types.js';
import { isESMImportedImage, isRemoteImage, resolveSrc } from './utils/imageKind.js';
import { inferRemoteSize } from './utils/remoteProbe.js';
import { getSizes, getWidths } from './layout.js';

export async function getConfiguredImageService(): Promise<ImageService> {
if (!globalThis?.astroAsset?.imageService) {
Expand All @@ -32,9 +33,13 @@ export async function getConfiguredImageService(): Promise<ImageService> {
return globalThis.astroAsset.imageService;
}

type ImageConfig = AstroConfig['image'] & {
experimentalResponsiveImages: boolean;
};

export async function getImage(
options: UnresolvedImageTransform,
imageConfig: AstroConfig['image'],
imageConfig: ImageConfig,
): Promise<GetImageResult> {
if (!options || typeof options !== 'object') {
throw new AstroError({
Expand Down Expand Up @@ -65,6 +70,8 @@ export async function getImage(
src: await resolveSrc(options.src),
};

let originalWidth: number | undefined;

// Infer size for remote images if inferSize is true
if (
options.inferSize &&
Expand All @@ -74,6 +81,7 @@ export async function getImage(
const result = await inferRemoteSize(resolvedOptions.src); // Directly probe the image URL
resolvedOptions.width ??= result.width;
resolvedOptions.height ??= result.height;
originalWidth = result.width;
delete resolvedOptions.inferSize; // Delete so it doesn't end up in the attributes
}

Expand All @@ -88,8 +96,32 @@ export async function getImage(
(resolvedOptions.src.clone ?? resolvedOptions.src)
: resolvedOptions.src;

originalWidth ||= isESMImportedImage(clonedSrc) ? clonedSrc.width : undefined;

resolvedOptions.src = clonedSrc;

const layout = options.layout ?? imageConfig.experimentalLayout;

if (imageConfig.experimentalResponsiveImages && layout) {
resolvedOptions.widths ||= getWidths({
width: resolvedOptions.width,
layout,
originalWidth,
});
resolvedOptions.sizes ||= getSizes({ width: resolvedOptions.width, layout });

if (resolvedOptions.priority) {
resolvedOptions.loading ??= 'eager';
resolvedOptions.decoding ??= 'sync';
resolvedOptions.fetchpriority ??= 'high';
} else {
resolvedOptions.loading ??= 'lazy';
resolvedOptions.decoding ??= 'async';
resolvedOptions.fetchpriority ??= 'auto';
}
delete resolvedOptions.priority;
}

const validatedOptions = service.validateOptions
? await service.validateOptions(resolvedOptions, imageConfig)
: resolvedOptions;
Expand Down
96 changes: 96 additions & 0 deletions packages/astro/src/assets/layout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import type { ImageLayout } from '../types/public/index.js';

// Common screen widths. These will be filtered according to the image size and layout
export const DEFAULT_RESOLUTIONS = [
6016, // 6K
5120, // 5K
4480, // 4.5K
3840, // 4K
3200, // QHD+
2560, // WQXGA
2048, // QXGA
1920, // 1080p
1668, // Various iPads
1280, // 720p
1080, // iPhone 6-8 Plus
960, // older horizontal phones
828, // iPhone XR/11
750, // iPhone 6-8
640, // older and lower-end phones
];

/**
* Gets the breakpoints for an image, based on the layout and width
*/
export const getWidths = ({
width,
layout,
breakpoints = DEFAULT_RESOLUTIONS,
originalWidth,
}: {
width?: number;
layout: ImageLayout;
breakpoints?: Array<number>;
originalWidth?: number;
}): Array<number> => {
const smallerThanOriginal = (w: number) => !originalWidth || w <= originalWidth;

if (layout === 'full-width') {
return breakpoints.filter(smallerThanOriginal);
}
if (!width) {
return [];
}
const doubleWidth = width * 2;
const maxSize = originalWidth ? Math.min(doubleWidth, originalWidth) : doubleWidth;
if (layout === 'fixed') {
// If the image is larger than the original, only include the original width
// Otherwise, include the image width and the double-resolution width, unless the double-resolution width is larger than the original
return originalWidth && width > originalWidth ? [originalWidth] : [width, maxSize];
}
if (layout === 'responsive') {
return (
[
// Always include the image at 1x and 2x the specified width
width,
doubleWidth,
...breakpoints,
]
// Sort the resolutions in ascending order
.sort((a, b) => a - b)
// Filter out any resolutions that are larger than the double-resolution image or source image
.filter((w) => w <= maxSize)
);
}

return [];
};

/**
* Gets the `sizes` attribute for an image, based on the layout and width
*/
export const getSizes = ({
width,
layout,
}: { width?: number; layout?: ImageLayout }): string | undefined => {
if (!width || !layout) {
return undefined;
}
switch (layout) {
// If screen is wider than the max size then image width is the max size,
// otherwise it's the width of the screen
case `responsive`:
return `(min-width: ${width}px) ${width}px, 100vw`;

// Image is always the same width, whatever the size of the screen
case `fixed`:
return `${width}px`;

// Image is always the width of the screen
case `full-width`:
return `100vw`;

default:
return undefined;
}
};
16 changes: 13 additions & 3 deletions packages/astro/src/assets/services/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,9 +224,19 @@ export const baseService: Omit<LocalImageService, 'transform'> = {
},
getHTMLAttributes(options) {
const { targetWidth, targetHeight } = getTargetDimensions(options);
const { src, width, height, format, quality, densities, widths, formats, ...attributes } =
options;

const {
src,
width,
height,
format,
quality,
densities,
widths,
formats,
layout,
priority,
...attributes
} = options;
return {
...attributes,
width: targetWidth,
Expand Down
15 changes: 15 additions & 0 deletions packages/astro/src/assets/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,18 @@ type ImageSharedProps<T> = T & {
position?: string;
} & (
| {
/**
* The layout type for responsive images. Overrides any default set in the Astro config.
* Requires the `experimental.responsiveImages` flag to be enabled.
*
* - `responsive` - The image will scale to fit the container, maintaining its aspect ratio, but will not exceed the specified dimensions.
* - `fixed` - The image will maintain its original dimensions.
* - `full-width` - The image will scale to fit the container, maintaining its aspect ratio.
*/
layout?: ImageLayout;
fit?: 'fill' | 'contain' | 'cover' | 'none' | 'scale-down' | (string & {});
position?: string;
priority?: boolean;
/**
* A list of widths to generate images for. The value of this property will be used to assign the `srcset` property on the final `img` element.
*
Expand All @@ -176,6 +188,9 @@ type ImageSharedProps<T> = T & {
*/
densities?: (number | `${number}x`)[];
widths?: never;
layout?: never;
fit?: never;
position?: never;
}
);

Expand Down
10 changes: 5 additions & 5 deletions packages/astro/test/content-collections-render.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ describe('Content Collections - render()', () => {
assert.equal($('ul li').length, 3);

// Includes styles
assert.equal($('link[rel=stylesheet]').length, 1);
assert.equal($('link[rel=stylesheet]').length, 2);
});

it('Excludes CSS for non-rendered entries', async () => {
const html = await fixture.readFile('/index.html');
const $ = cheerio.load(html);

// Excludes styles
assert.equal($('link[rel=stylesheet]').length, 0);
assert.equal($('link[rel=stylesheet]').length, 1);
});

it('De-duplicates CSS used both in layout and directly in target page', async () => {
Expand Down Expand Up @@ -110,7 +110,7 @@ describe('Content Collections - render()', () => {
assert.equal($('ul li').length, 3);

// Includes styles
assert.equal($('link[rel=stylesheet]').length, 1);
assert.equal($('link[rel=stylesheet]').length, 2);
});

it('Exclude CSS for non-rendered entries', async () => {
Expand All @@ -121,7 +121,7 @@ describe('Content Collections - render()', () => {
const $ = cheerio.load(html);

// Includes styles
assert.equal($('link[rel=stylesheet]').length, 0);
assert.equal($('link[rel=stylesheet]').length, 1);
});

it('De-duplicates CSS used both in layout and directly in target page', async () => {
Expand Down Expand Up @@ -202,7 +202,7 @@ describe('Content Collections - render()', () => {
assert.equal($('ul li').length, 3);

// Includes styles
assert.equal($('head > style').length, 1);
assert.equal($('head > style').length, 2);
assert.ok($('head > style').text().includes("font-family: 'Comic Sans MS'"));
});

Expand Down
10 changes: 10 additions & 0 deletions packages/astro/test/fixtures/core-image-layout/astro.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// @ts-check
import { defineConfig } from 'astro/config';

export default defineConfig({
image: {
experimentalLayout: 'responsive'
},
experimental: {
responsiveImages: true
}});
8 changes: 8 additions & 0 deletions packages/astro/test/fixtures/core-image-layout/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "@test/core-image-layout",
"version": "0.0.0",
"private": true,
"dependencies": {
"astro": "workspace:*"
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
import { Image } from "astro:assets";
import hero from "../assets/hero.jpg";
---

<div>
<Image src={hero} alt="A penguin" layout="fixed" width={800} height={300} class="green" priority/>
</div>
<div>
<Image src={hero} alt="A penguin" layout="responsive" width={800} height={300} style="border: 2px red solid"/>
</div>
<div>
<Image src={hero} alt="A heroic penguin" layout="full-width"/>
</div>
<style>
.green {
border: 2px green solid;
}
</style>
11 changes: 11 additions & 0 deletions packages/astro/test/fixtures/core-image-layout/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "astro/tsconfigs/base",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/assets/*": ["src/assets/*"]
},
},
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}
Loading
Loading