UNPKG

imgix-url-builder

Version:

JavaScript/TypeScript Imgix URL builders for browsers and Node.js

1 lines 2.61 kB
{"version":3,"file":"buildWidthSrcSet.cjs","sources":["../../src/buildWidthSrcSet.ts"],"sourcesContent":["import type { ImgixURLParams } from \"./types.generated\";\nimport { buildURL } from \"./buildURL\";\n\n/**\n * Parameters for `buildWidthSrcSet`.\n */\nexport type BuildWidthSrcSetParams = Omit<\n\tImgixURLParams,\n\t\"width\" | \"w\" | \"height\" | \"h\"\n> & {\n\t/**\n\t * The pixel widths to include in the resulting `srcset` value.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * [400, 800, 1600];\n\t * ```\n\t */\n\twidths: number[];\n};\n\n/**\n * Builds an `<img>` `srcset` attribute value for a given set of widths. It can\n * also optinally apply Imgix URL API parameters to the URLs.\n *\n * The `width` URL parameter will be applied for each `srcset` entry. If a\n * `width` or `w` parameter is provided to the `params` parameter, it will be\n * ignored. Similarly, if a `height` or `h` parameter is provided to the\n * `params` parameter, it will be ignored to prevent unexpected aspect ratio.\n *\n * @example\n *\n * ```ts\n * const srcset = buildWidthSrcSet(\"https://example.imgix.net/image.png\", {\n * \twidths: [400, 800, 1600],\n * });\n * // => https://example.imgix.net/image.png?width=400 400w,\n * // https://example.imgix.net/image.png?width=800 800w,\n * // https://example.imgix.net/image.png?width=1600 1600w\n * ```\n *\n * @example\n *\n * ```ts\n * const srcset = buildWidthSrcSet(\"https://example.imgix.net/image.png\", {\n * \twidths: [400, 800, 1600],\n * \tsat: -100,\n * });\n * // => https://example.imgix.net/image.png?width=400&sat=-100 400w,\n * // https://example.imgix.net/image.png?width=800&sat=-100 800w,\n * // https://example.imgix.net/image.png?width=1600&sat=-100 1600w\n * ```\n *\n * @param url - Full absolute URL to the Imgix image.\n * @param params - An object of Imgix URL API parameters. The `widths` parameter\n * defines the resulting `srcset` widths.\n *\n * @returns A `srcset` attribute value for `url` with the given Imgix URL API\n * parameters applied.\n */\nexport const buildWidthSrcSet = (\n\turl: string,\n\t{ widths, ...params }: BuildWidthSrcSetParams,\n): string => {\n\treturn widths\n\t\t.map((width) => {\n\t\t\treturn `${buildURL(url, { ...params, w: undefined, h: undefined, height: undefined, width })} ${width}w`;\n\t\t})\n\t\t.join(\", \");\n};\n"],"names":["buildURL"],"mappings":";;;AA6DO,MAAM,mBAAmB,CAC/B,KACA,EAAE,QAAQ,GAAG,aACF;AACJ,SAAA,OACL,IAAI,CAAC,UAAS;AACd,WAAO,GAAGA,SAAS,SAAA,KAAK,EAAE,GAAG,QAAQ,GAAG,QAAW,GAAG,QAAW,QAAQ,QAAW,MAAA,CAAO,CAAC,IAAI,KAAK;AAAA,EAAA,CACrG,EACA,KAAK,IAAI;AACZ;;"}