Share picture fallback image with source (#5324)
This commit is contained in:
parent
bcd0f8f8c4
commit
dc00ca4648
3 changed files with 43 additions and 14 deletions
5
.changeset/fifty-olives-end.md
Normal file
5
.changeset/fifty-olives-end.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
'@astrojs/image': patch
|
||||
---
|
||||
|
||||
Share fallback img src with source of Picture component
|
|
@ -59,6 +59,13 @@ export async function getPicture(params: GetPictureParams): Promise<GetPictureRe
|
|||
throw new Error('`aspectRatio` must be provided for remote images');
|
||||
}
|
||||
|
||||
// always include the original image format
|
||||
const allFormats = await resolveFormats(params);
|
||||
const lastFormat = allFormats[allFormats.length - 1];
|
||||
const maxWidth = Math.max(...widths);
|
||||
|
||||
let image: astroHTML.JSX.ImgHTMLAttributes;
|
||||
|
||||
async function getSource(format: OutputFormat) {
|
||||
const imgs = await Promise.all(
|
||||
widths.map(async (width) => {
|
||||
|
@ -69,8 +76,13 @@ export async function getPicture(params: GetPictureParams): Promise<GetPictureRe
|
|||
fit,
|
||||
position,
|
||||
background,
|
||||
height: Math.round(width / aspectRatio!),
|
||||
aspectRatio,
|
||||
});
|
||||
|
||||
if (format === lastFormat && width === maxWidth) {
|
||||
image = img;
|
||||
}
|
||||
|
||||
return `${img.src} ${width}w`;
|
||||
})
|
||||
);
|
||||
|
@ -81,23 +93,11 @@ export async function getPicture(params: GetPictureParams): Promise<GetPictureRe
|
|||
};
|
||||
}
|
||||
|
||||
// always include the original image format
|
||||
const allFormats = await resolveFormats(params);
|
||||
|
||||
const image = await getImage({
|
||||
src,
|
||||
width: Math.max(...widths),
|
||||
aspectRatio,
|
||||
fit,
|
||||
position,
|
||||
background,
|
||||
format: allFormats[allFormats.length - 1],
|
||||
});
|
||||
|
||||
const sources = await Promise.all(allFormats.map((format) => getSource(format)));
|
||||
|
||||
return {
|
||||
sources,
|
||||
// @ts-expect-error image will always be defined
|
||||
image,
|
||||
};
|
||||
}
|
||||
|
|
|
@ -381,3 +381,27 @@ describe('SSG pictures with subpath - build', function () {
|
|||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('SSG pictures others - build', function () {
|
||||
let fixture;
|
||||
let $;
|
||||
let html;
|
||||
|
||||
before(async () => {
|
||||
fixture = await loadFixture({ root: './fixtures/basic-picture/' });
|
||||
await fixture.build();
|
||||
|
||||
html = await fixture.readFile('/index.html');
|
||||
$ = cheerio.load(html);
|
||||
});
|
||||
|
||||
it('fallback image should share last source', async () => {
|
||||
const hero = $('#hero');
|
||||
const picture = hero.closest('picture');
|
||||
|
||||
const source = picture.children('source').last();
|
||||
const image = picture.children('img').last();
|
||||
|
||||
expect(source.attr('srcset')).to.include(image.attr('src'));
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue