@prismicio/client
Version:
The official JavaScript + TypeScript client library for Prismic
71 lines (70 loc) • 2.76 kB
JavaScript
import { imageThumbnail } from "./isFilled.js";
import { buildURL, buildWidthSrcSet } from "imgix-url-builder";
//#region src/helpers/asImageWidthSrcSet.ts
/** The default widths used to generate a `srcset` value. */
const DEFAULT_WIDTHS = [
640,
828,
1200,
2048,
3840
];
/**
* Creates a width-based `srcset` from an image field with optional image transformations via imgix
* URL parameters.
*
* If a `widths` parameter is not given, the following widths (in pixels) will be used by default:
* 640, 750, 828, 1080, 1200, 1920, 2048, 3840.
*
* If the image field contains responsive views, each responsive view can be used as a width in the
* resulting `srcset` by passing `"thumbnails"` as the `widths` parameter.
*
* @example
* ;```ts
* const srcset = asImageWidthSrcSet(document.data.photo, {
* widths: [400, 800, 1600],
* sat: -100,
* })
* // => {
* // src: "https://images.prismic.io/repo/image.png?sat=-100",
* // srcset: "https://images.prismic.io/repo/image.png?sat=-100&width=400 400w, " +
* // "https://images.prismic.io/repo/image.png?sat=-100&width=800 800w, " +
* // "https://images.prismic.io/repo/image.png?sat=-100&width=1600 1600w"
* // }
* ```
*
* @param field - An image field (or one of its responsive views) from which to get an image URL.
* @param config - An object of imgix URL API parameters. The `widths` parameter defines the
* resulting `srcset` widths. Pass `"thumbnails"` to automatically use the field's responsive
* views.
* @returns A `srcset` attribute value for the image field with imgix URL parameters, or `null` if
* the field is empty.
* @see Learn how to optimize images with imgix: {@link https://prismic.io/docs/fields/image}
* @see imgix URL parameters reference: {@link https://docs.imgix.com/apis/rendering}
*/
const asImageWidthSrcSet = (field, config = {}) => {
if (field && imageThumbnail(field)) {
let { widths = DEFAULT_WIDTHS, ...imgixParams } = config;
const { url, dimensions, id: _id, alt: _alt, copyright: _copyright, edit: _edit, ...responsiveViews } = field;
const responsiveViewObjects = Object.values(responsiveViews);
if (widths === "thumbnails" && responsiveViewObjects.length < 1) widths = DEFAULT_WIDTHS;
return {
src: buildURL(url, imgixParams),
srcset: widths === "thumbnails" ? [buildWidthSrcSet(url, {
...imgixParams,
widths: [dimensions.width]
}), ...responsiveViewObjects.map((thumbnail) => {
return buildWidthSrcSet(thumbnail.url, {
...imgixParams,
widths: [thumbnail.dimensions.width]
});
})].join(", ") : buildWidthSrcSet(field.url, {
...imgixParams,
widths
})
};
} else return null;
};
//#endregion
export { asImageWidthSrcSet };
//# sourceMappingURL=asImageWidthSrcSet.js.map