Skip to content

Commit

Permalink
Support scope styles for picture element in Picture component (#10975)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored May 9, 2024
1 parent 25caca0 commit 6b640b3
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/ten-needles-rescue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro": patch
---

Passes the scoped style attribute or class to the `<picture>` element in the `<Picture />` component so scoped styling can be applied to the `<picture>` element
15 changes: 15 additions & 0 deletions packages/astro/components/Picture.astro
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ if (props.alt === undefined || props.alt === null) {
throw new AstroError(AstroErrorData.ImageMissingAlt);
}
// Picture attribute inherit scoped styles from class and attributes
const scopedStyleClass = props.class?.match(/\bastro-\w{8}\b/)?.[0]
if (scopedStyleClass) {
if (pictureAttributes.class) {
pictureAttributes.class = `${pictureAttributes.class} ${scopedStyleClass}`;
} else {
pictureAttributes.class = scopedStyleClass;
}
}
for (const key in props) {
if (key.startsWith('data-astro-cid')) {
pictureAttributes[key] = props[key];
}
}
const originalSrc = await resolveSrc(props.src);
const optimizedImages: GetImageResult[] = await Promise.all(
formats.map(
Expand Down
13 changes: 13 additions & 0 deletions packages/astro/test/core-image.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,19 @@ describe('astro:image', () => {
);
});

it('Picture component scope styles work', async () => {
let res = await fixture.fetch('/picturecomponent');
let html = await res.text();
$ = cheerio.load(html);

// Should have scoped attribute
let $picture = $('#picture-attributes picture');
assert.ok(Object.keys($picture.attr()).find((a) => a.startsWith('data-astro-cid-')));

let $img = $('#picture-attributes img');
assert.ok(Object.keys($img.attr()).find((a) => a.startsWith('data-astro-cid-')));
});

it('properly deduplicate srcset images', async () => {
let res = await fixture.fetch('/srcset');
let html = await res.text();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,18 @@ import myImage from "../assets/penguin1.jpg";
<div id="picture-fallback">
<Picture src={myImage} fallbackFormat="jpeg" alt="A penguin" />
</div>

<div id="picture-attributes">
<Picture src={myImage} fallbackFormat="jpeg" alt="A penguin" class="img-comp" pictureAttributes={{ class: 'picture-comp' }} />
</div>

<style>
.img-comp {
border: 5px solid blue;
}

.picture-comp {
border: 5px solid red;
display: inline-block;
}
</style>

0 comments on commit 6b640b3

Please sign in to comment.