0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-16 21:46:22 -05:00

Support scope styles for picture element in Picture component (#10975)

This commit is contained in:
Bjorn Lu 2024-05-09 21:04:19 +08:00 committed by GitHub
parent 25caca015e
commit 6b640b3bcb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 48 additions and 0 deletions

View file

@ -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

View file

@ -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(

View file

@ -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();

View file

@ -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>