Skip to content
Merged
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
17 changes: 17 additions & 0 deletions .changeset/ripe-nights-feel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'astro': minor
---

Responsive images are now supported when `security.csp` is enabled, out of the box.

Before, the styles for responsive images were injected using the `style="""` attribute, and the image would look like this:

```html
<img style="--fit: <value>; --pos: <value>" >
```

After this change, styles now use a combination of `class=""` and data attributes. The image would look like this:

```html
<img class="__a_HaSh350" data-atro-fit="value" data-astro-pos="value" >
```
5 changes: 5 additions & 0 deletions .changeset/static-output-cloudflare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@astrojs/cloudflare": patch
---

Fixes fully static sites to not output server-side worker code. When all routes are prerendered, the `_worker.js` directory is now removed from the build output.
5 changes: 5 additions & 0 deletions .changeset/upset-dodos-rhyme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': major
---

Changes how styles of responsive images are emitted - ([v6 upgrade guidance](https://v6.docs.astro.build/en/guides/upgrade-to/v6/#changed-how-responsive-image-styles-are-emitted))
28 changes: 27 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,29 @@ env:
NODE_OPTIONS: --max-old-space-size=6144

jobs:
changes:
runs-on: ubuntu-latest
permissions:
pull-requests: read
outputs:
language-tools: ${{ steps.filter.outputs.language-tools }}
astro-types: ${{ steps.filter.outputs.astro-types }}
ci: ${{ steps.filter.outputs.ci }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
id: filter
with:
# When updating filters here, make sure to also add or remove them from the outputs block above.
filters: |
language-tools:
- 'packages/language-tools/**'
astro-types:
- 'packages/astro/types/**'
- 'packages/astro/astro-jsx.d.ts'
ci:
- '.github/workflows/ci.yml'

# Build primes out Turbo build cache and pnpm cache
build:
name: "Build: ${{ matrix.os }}"
Expand Down Expand Up @@ -165,7 +188,10 @@ jobs:
test-language-tools:
runs-on: ${{ matrix.os }}
timeout-minutes: 30
needs: build
needs:
- changes
- build
if: needs.changes.outputs.language-tools == 'true' || needs.changes.outputs.astro-types == 'true' || needs.changes.outputs.ci == 'true'
strategy:
matrix:
os: [ubuntu-latest]
Expand Down
5 changes: 5 additions & 0 deletions packages/astro/client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ declare module 'astro:assets' {
}: AstroAssets;
}

declare module 'virtual:astro:image-styles.css' {
const styles: string;
export default styles;
}

type ImageMetadata = import('./dist/assets/types.js').ImageMetadata;

declare module '*.gif' {
Expand Down
2 changes: 0 additions & 2 deletions packages/astro/components/ResponsiveImage.astro
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import Image from './Image.astro';
type Props = LocalImageProps | RemoteImageProps;

const { class: className, ...props } = Astro.props;

import './image.css';
---

{/* Applying class outside of the spread prevents it from applying unnecessary astro-* classes */}
Expand Down
1 change: 0 additions & 1 deletion packages/astro/components/ResponsivePicture.astro
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { default as Picture, type Props as PictureProps } from './Picture.astro'
type Props = PictureProps;
const { class: className, ...props } = Astro.props;
import './image.css';
---

{/* Applying class outside of the spread prevents it from applying unnecessary astro-* classes */}
Expand Down
11 changes: 0 additions & 11 deletions packages/astro/components/image.css

This file was deleted.

42 changes: 42 additions & 0 deletions packages/astro/e2e/core-image-styles.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { expect } from '@playwright/test';
import { testFactory } from './test-utils.js';

const test = testFactory(import.meta.url, {
root: '../test/fixtures/core-image-layout/',
devToolbar: {
enabled: false,
},
});

let devServer;

test.beforeAll(async ({ astro }) => {
devServer = await astro.startDevServer();
});

test.afterAll(async () => {
await devServer.stop();
});

test.describe('Image styles injection', () => {
test('injects a style tag with [data-astro-image] CSS', async ({ page, astro }) => {
await page.goto(astro.resolveUrl('/'));

// Wait for client-side CSS injection
await page.waitForLoadState('networkidle');

// Check all style tags for image styles
const styleTags = await page.locator('style').all();
let foundImageStyles = false;

for (const styleTag of styleTags) {
const content = await styleTag.textContent();
if (content && content.includes('[data-astro-image]')) {
foundImageStyles = true;
break;
}
}

expect(foundImageStyles).toBe(true);
});
});
3 changes: 3 additions & 0 deletions packages/astro/src/assets/consts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
export const VIRTUAL_MODULE_ID = 'astro:assets';
export const RESOLVED_VIRTUAL_MODULE_ID = '\0' + VIRTUAL_MODULE_ID;
export const VIRTUAL_SERVICE_ID = 'virtual:image-service';
// Must keep the extension so we trigger the pipeline of CSS files
export const VIRTUAL_IMAGE_STYLES_ID = 'virtual:astro:image-styles.css';
export const RESOLVED_VIRTUAL_IMAGE_STYLES_ID = '\0' + VIRTUAL_IMAGE_STYLES_ID;
export const VALID_INPUT_FORMATS = [
'jpeg',
'jpg',
Expand Down
22 changes: 14 additions & 8 deletions packages/astro/src/assets/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@ import {
type SrcSetValue,
type UnresolvedImageTransform,
} from './types.js';
import { addCSSVarsToStyle, cssFitValues } from './utils/imageAttributes.js';
import { isESMImportedImage, isRemoteImage, resolveSrc } from './utils/imageKind.js';
import { inferRemoteSize } from './utils/remoteProbe.js';
import { createPlaceholderURL, stringifyPlaceholderURL } from './utils/url.js';

export const cssFitValues = ['fill', 'contain', 'cover', 'scale-down'];

export async function getConfiguredImageService(): Promise<ImageService> {
if (!globalThis?.astroAsset?.imageService) {
const { default: service }: { default: ImageService } = await import(
Expand Down Expand Up @@ -149,14 +150,19 @@ export async function getImage(
resolvedOptions.sizes ||= getSizesAttribute({ width: resolvedOptions.width, layout });
// The densities option is incompatible with the `layout` option
delete resolvedOptions.densities;
resolvedOptions.style = addCSSVarsToStyle(
{
fit: cssFitValues.includes(resolvedOptions.fit ?? '') && resolvedOptions.fit,
pos: resolvedOptions.position,
},
resolvedOptions.style,
);

// Set data attribute for layout
resolvedOptions['data-astro-image'] = layout;

// Set data attributes for fit and position for CSP-compliant styling
if (resolvedOptions.fit && cssFitValues.includes(resolvedOptions.fit)) {
resolvedOptions['data-astro-image-fit'] = resolvedOptions.fit;
}

if (resolvedOptions.position) {
// Normalize position value for data attribute (spaces to dashes)
resolvedOptions['data-astro-image-pos'] = resolvedOptions.position.replace(/\s+/g, '-');
}
}

const validatedOptions = service.validateOptions
Expand Down
48 changes: 48 additions & 0 deletions packages/astro/src/assets/utils/generateImageStylesCSS.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { cssFitValues } from '../internal.js';

export function generateImageStylesCSS(
defaultObjectFit?: string,
defaultObjectPosition?: string,
): string {
const fitStyles = cssFitValues
.map(
(fit) => `
[data-astro-image-fit="${fit}"] {
object-fit: ${fit};
}`,
)
.join('\n');

const defaultFitStyle =
defaultObjectFit && cssFitValues.includes(defaultObjectFit)
? `
:where([data-astro-image]:not([data-astro-image-fit])) {
object-fit: ${defaultObjectFit};
}`
: '';

const positionStyle = defaultObjectPosition
? `
[data-astro-image-pos="${defaultObjectPosition.replace(/\s+/g, '-')}"] {
object-position: ${defaultObjectPosition};
}

:where([data-astro-image]:not([data-astro-image-pos])) {
object-position: ${defaultObjectPosition};
}`
: '';
return `
:where([data-astro-image]) {
height: auto;
}
:where([data-astro-image="full-width"]) {
width: 100%;
}
:where([data-astro-image="constrained"]) {
max-width: 100%;
}
${fitStyles}
${defaultFitStyle}
${positionStyle}
`.trim();
}
20 changes: 0 additions & 20 deletions packages/astro/src/assets/utils/imageAttributes.ts

This file was deleted.

Loading
Loading