From 402a227c30447e2ee0f13f01d72baa3e247e950f Mon Sep 17 00:00:00 2001 From: Luis Ball Date: Fri, 25 Feb 2022 10:55:54 -0800 Subject: [PATCH] feat: add _buildSrcSet static method --- src/index.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/index.js b/src/index.js index f6a91783..33f51527 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,8 @@ import md5 from 'md5'; import { Base64 } from 'js-base64'; +import { extractUrl } from './helpers'; +import { getQuery } from 'ufo'; + import { VERSION, @@ -132,6 +135,48 @@ export default class ImgixClient { } } + /** + * _buildSrcSet static method allows full URLs to be used when generating + * imgix formatted `srcset` string values. + * + * - If the source URL has included parameters, they are merged with + * the `params` passed in as an argument. + * - URL must match `{host}/{pathname}?{query}` otherwise an error is thrown. + * + * @param {String} url - full source URL path string, required + * @param {Object} params - imgix params object, optional + * @param {Object} srcsetModifiers - srcset modifiers, optional + * @param {Object} clientOptions - imgix client options, optional + * @returns imgix `srcset` for full URLs. + */ + static _buildSrcSet( + url, + params = {}, + srcsetModifiers = {}, + clientOptions = {}, + ) { + if (url == null) { + return ''; + } + + const { host, pathname, search } = extractUrl({ + url, + useHTTPS: clientOptions.useHTTPS, + }); + // merge source URL parameters with options parameters + const combinedParams = { ...getQuery(search), ...params }; + + // throw error if no host or no pathname present + if (!host.length || !pathname.length) { + throw new Error( + '_buildOneStepURL: URL must match {host}/{pathname}?{query}', + ); + } + + const client = new ImgixClient({ domain: host, ...clientOptions }); + return client.buildSrcSet(pathname, combinedParams, srcsetModifiers); + } + // returns an array of width values used during srcset generation static targetWidths( minWidth = 100,