diff --git a/CHANGELOG.md b/CHANGELOG.md index 220aee1..b184c0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## Version 5.1.0 + +1. **New helper** `getResponsiveImageAttributes()` + Generates ready‑to‑use `src`, `srcSet`, and `sizes` for responsive `` tags (breakpoint pruning, DPR 1×/2×, custom breakpoints, no up‑scaling). +2. Added exports: + `getResponsiveImageAttributes`, `GetImageAttributesOptions`, `ResponsiveImageAttributes`. + +_No breaking changes from 5.0.x._ + ## Version 5.0.0 This version introduces major breaking changes, for usage examples, refer to the [official documentation](https://imagekit.io/docs/integration/javascript). diff --git a/package-lock.json b/package-lock.json index aa14b58..cc7eafd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@imagekit/javascript", - "version": "5.0.0", + "version": "5.1.0-beta.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@imagekit/javascript", - "version": "5.0.0", + "version": "5.1.0-beta.1", "license": "MIT", "devDependencies": { "@babel/cli": "^7.10.5", diff --git a/package.json b/package.json index 8d007cb..f1d3e66 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@imagekit/javascript", - "version": "5.0.0", + "version": "5.1.0-beta.1", "description": "ImageKit Javascript SDK", "main": "dist/imagekit.cjs.js", "module": "dist/imagekit.esm.js", diff --git a/src/getResponsiveImageAttributes.ts b/src/getResponsiveImageAttributes.ts new file mode 100644 index 0000000..3b3c120 --- /dev/null +++ b/src/getResponsiveImageAttributes.ts @@ -0,0 +1,164 @@ +import type { SrcOptions } from './interfaces' +import { buildSrc } from './url' + +/* Default break‑point pools */ +const DEFAULT_DEVICE_BREAKPOINTS = [640, 750, 828, 1080, 1200, 1920, 2048, 3840] as const +const DEFAULT_IMAGE_BREAKPOINTS = [16, 32, 48, 64, 96, 128, 256, 384] as const + +export interface GetImageAttributesOptions extends SrcOptions { + /** + * The intended display width of the image in pixels, + * used **only when the `sizes` attribute is not provided**. + * + * Triggers a DPR-based strategy (1x and 2x variants) and generates `x` descriptors in `srcSet`. + * + * Ignored if `sizes` is present. + */ + width?: number + + /** + * The value for the HTML `sizes` attribute + * (e.g., `"100vw"` or `"(min-width:768px) 50vw, 100vw"`). + * + * - If it includes one or more `vw` units, breakpoints smaller than the corresponding percentage of the smallest device width are excluded. + * - If it contains no `vw` units, the full breakpoint list is used. + * + * Enables a width-based strategy and generates `w` descriptors in `srcSet`. + */ + sizes?: string + + /** + * Custom list of **device-width breakpoints** in pixels. + * These define common screen widths for responsive image generation. + * + * Defaults to `[640, 750, 828, 1080, 1200, 1920, 2048, 3840]`. + * Sorted automatically. + */ + deviceBreakpoints?: number[] + + /** + * Custom list of **image-specific breakpoints** in pixels. + * Useful for generating small variants (e.g., placeholders or thumbnails). + * + * Merged with `deviceBreakpoints` before calculating `srcSet`. + * Defaults to `[16, 32, 48, 64, 96, 128, 256, 384]`. + * Sorted automatically. + */ + imageBreakpoints?: number[] +} + +/** + * Resulting set of attributes suitable for an HTML `` element. + * Useful for enabling responsive image loading. + */ +export interface ResponsiveImageAttributes { + /** URL for the *largest* candidate (assigned to plain `src`). */ + src: string + /** Candidate set with `w` or `x` descriptors. */ + srcSet?: string + /** `sizes` returned (or synthesised as `100vw`). */ + sizes?: string + /** Width as a number (if `width` was provided). */ + width?: number +} + +/** + * Generates a responsive image URL, `srcSet`, and `sizes` attributes + * based on the input options such as `width`, `sizes`, and breakpoints. + */ +export function getResponsiveImageAttributes( + opts: GetImageAttributesOptions +): ResponsiveImageAttributes { + const { + src, + urlEndpoint, + transformation = [], + queryParameters, + transformationPosition, + sizes, + width, + deviceBreakpoints = DEFAULT_DEVICE_BREAKPOINTS as unknown as number[], + imageBreakpoints = DEFAULT_IMAGE_BREAKPOINTS as unknown as number[], + } = opts + + const sortedDeviceBreakpoints = [...deviceBreakpoints].sort((a, b) => a - b); + const sortedImageBreakpoints = [...imageBreakpoints].sort((a, b) => a - b); + const allBreakpoints = [...sortedImageBreakpoints, ...sortedDeviceBreakpoints].sort((a, b) => a - b); + + const { candidates, descriptorKind } = computeCandidateWidths({ + allBreakpoints, + deviceBreakpoints: sortedDeviceBreakpoints, + explicitWidth: width, + sizesAttr: sizes, + }) + + /* helper to build a single ImageKit URL */ + const buildURL = (w: number) => + buildSrc({ + src, + urlEndpoint, + queryParameters, + transformationPosition, + transformation: [ + ...transformation, + { width: w, crop: 'at_max' }, // never upscale beyond original + ], + }) + + /* build srcSet */ + const srcSet = + candidates + .map((w, i) => `${buildURL(w)} ${descriptorKind === 'w' ? w : i + 1}${descriptorKind}`) + .join(', ') || undefined + + const finalSizes = sizes ?? (descriptorKind === 'w' ? '100vw' : undefined) + + return { + src: buildURL(candidates[candidates.length - 1]), // largest candidate + srcSet, + ...(finalSizes ? { sizes: finalSizes } : {}), // include only when defined + ...(width !== undefined ? { width } : {}), // include only when defined + } +} + +function computeCandidateWidths(params: { + allBreakpoints: number[] + deviceBreakpoints: number[] + explicitWidth?: number + sizesAttr?: string +}): { candidates: number[]; descriptorKind: 'w' | 'x' } { + const { allBreakpoints, deviceBreakpoints, explicitWidth, sizesAttr } = params + + // Strategy 1: Width-based srcSet (`w`) using viewport `vw` hints + if (sizesAttr) { + const vwTokens = sizesAttr.match(/(^|\s)(1?\d{1,2})vw/g) || [] + const vwPercents = vwTokens.map((t) => parseInt(t, 10)) + + if (vwPercents.length) { + const smallestRatio = Math.min(...vwPercents) / 100 + const minRequiredPx = deviceBreakpoints[0] * smallestRatio + return { + candidates: allBreakpoints.filter((w) => w >= minRequiredPx), + descriptorKind: 'w', + } + } + + // No usable `vw` found: fallback to all breakpoints + return { candidates: allBreakpoints, descriptorKind: 'w' } + } + + // Strategy 2: Fallback using explicit image width using device breakpoints + if (typeof explicitWidth !== 'number') { + return { candidates: deviceBreakpoints, descriptorKind: 'w' } + } + + // Strategy 3: Use 1x and 2x nearest breakpoints for `x` descriptor + const nearest = (t: number) => + allBreakpoints.find((n) => n >= t) || allBreakpoints[allBreakpoints.length - 1] + + const unique = Array.from( + new Set([nearest(explicitWidth), nearest(explicitWidth * 2)]), + ) + + return { candidates: unique, descriptorKind: 'x' } +} diff --git a/src/index.ts b/src/index.ts index 4b047e1..51ec6b0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,13 +1,14 @@ import type { SrcOptions, Transformation, UploadOptions, UploadResponse } from "./interfaces"; import { ImageKitAbortError, ImageKitInvalidRequestError, ImageKitServerError, ImageKitUploadNetworkError, upload } from "./upload"; import { buildSrc, buildTransformationString } from "./url"; +import { getResponsiveImageAttributes } from "./getResponsiveImageAttributes"; +import type { GetImageAttributesOptions, ResponsiveImageAttributes } from "./getResponsiveImageAttributes"; -export { buildSrc, buildTransformationString, upload, ImageKitInvalidRequestError, ImageKitAbortError, ImageKitServerError, ImageKitUploadNetworkError }; +export { buildSrc, buildTransformationString, upload, getResponsiveImageAttributes, ImageKitInvalidRequestError, ImageKitAbortError, ImageKitServerError, ImageKitUploadNetworkError }; export type { Transformation, SrcOptions, UploadOptions, - UploadResponse + UploadResponse, + GetImageAttributesOptions, ResponsiveImageAttributes }; - - diff --git a/src/interfaces/Transformation.ts b/src/interfaces/Transformation.ts index b45be9f..6396b37 100644 --- a/src/interfaces/Transformation.ts +++ b/src/interfaces/Transformation.ts @@ -720,4 +720,19 @@ export type SolidColorOverlayTransformation = Pick { + it('bare minimum input', () => { + const out = getResponsiveImageAttributes({ + src: 'sample.jpg', + urlEndpoint: 'https://ik.imagekit.io/demo', + }); + // Expected object based on default deviceBreakpoints and imageBreakpoints: + expect(out).to.deep.equal({ + src: "https://ik.imagekit.io/demo/sample.jpg?tr=w-3840,c-at_max", + srcSet: "https://ik.imagekit.io/demo/sample.jpg?tr=w-640,c-at_max 640w, https://ik.imagekit.io/demo/sample.jpg?tr=w-750,c-at_max 750w, https://ik.imagekit.io/demo/sample.jpg?tr=w-828,c-at_max 828w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1080,c-at_max 1080w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1200,c-at_max 1200w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1920,c-at_max 1920w, https://ik.imagekit.io/demo/sample.jpg?tr=w-2048,c-at_max 2048w, https://ik.imagekit.io/demo/sample.jpg?tr=w-3840,c-at_max 3840w", + sizes: "100vw" + }); + }); + + it('sizes provided (100vw)', () => { + const out = getResponsiveImageAttributes({ + src: 'sample.jpg', + urlEndpoint: 'https://ik.imagekit.io/demo', + sizes: '100vw', + }); + // With a sizes value of "100vw", the function should use the same breakpoints as in the bare minimum case. + expect(out).to.deep.equal({ + src: "https://ik.imagekit.io/demo/sample.jpg?tr=w-3840,c-at_max", + srcSet: "https://ik.imagekit.io/demo/sample.jpg?tr=w-640,c-at_max 640w, https://ik.imagekit.io/demo/sample.jpg?tr=w-750,c-at_max 750w, https://ik.imagekit.io/demo/sample.jpg?tr=w-828,c-at_max 828w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1080,c-at_max 1080w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1200,c-at_max 1200w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1920,c-at_max 1920w, https://ik.imagekit.io/demo/sample.jpg?tr=w-2048,c-at_max 2048w, https://ik.imagekit.io/demo/sample.jpg?tr=w-3840,c-at_max 3840w", + sizes: "100vw" + }); + }); + + it('width only – DPR strategy', () => { + const out = getResponsiveImageAttributes({ + src: 'sample.jpg', + urlEndpoint: 'https://ik.imagekit.io/demo', + width: 400, + }); + // When width is provided without sizes attribute, the DPR strategy should be used. + expect(out).to.deep.equal({ + src: "https://ik.imagekit.io/demo/sample.jpg?tr=w-828,c-at_max", + srcSet: "https://ik.imagekit.io/demo/sample.jpg?tr=w-640,c-at_max 1x, https://ik.imagekit.io/demo/sample.jpg?tr=w-828,c-at_max 2x", + width: 400 + }); + }); + + it('custom breakpoints', () => { + const out = getResponsiveImageAttributes({ + src: 'sample.jpg', + urlEndpoint: 'https://ik.imagekit.io/demo', + deviceBreakpoints: [200, 400, 800], + imageBreakpoints: [100], + }); + // For custom breakpoints, the breakpoints will be derived from the provided arrays. + expect(out).to.deep.equal({ + src: "https://ik.imagekit.io/demo/sample.jpg?tr=w-800,c-at_max", + srcSet: "https://ik.imagekit.io/demo/sample.jpg?tr=w-200,c-at_max 200w, https://ik.imagekit.io/demo/sample.jpg?tr=w-400,c-at_max 400w, https://ik.imagekit.io/demo/sample.jpg?tr=w-800,c-at_max 800w", + sizes: "100vw" + }); + }); + + it('preserves caller transformations', () => { + const out = getResponsiveImageAttributes({ + src: 'sample.jpg', + urlEndpoint: 'https://ik.imagekit.io/demo', + width: 500, + transformation: [{ height: 300 }], + }); + // The provided transformation should be preserved in the output. + expect(out).to.deep.equal({ + src: "https://ik.imagekit.io/demo/sample.jpg?tr=h-300:w-1080,c-at_max", + srcSet: "https://ik.imagekit.io/demo/sample.jpg?tr=h-300:w-640,c-at_max 1x, https://ik.imagekit.io/demo/sample.jpg?tr=h-300:w-1080,c-at_max 2x", + width: 500 + }); + }); + + it('both sizes and width passed', () => { + const out = getResponsiveImageAttributes({ + src: 'sample.jpg', + urlEndpoint: 'https://ik.imagekit.io/demo', + sizes: '50vw', + width: 600, + }); + // Both sizes and width are provided, so the function should apply the sizes attribute while using width for DPR strategy. + expect(out).to.deep.equal({ + src: "https://ik.imagekit.io/demo/sample.jpg?tr=w-3840,c-at_max", + srcSet: "https://ik.imagekit.io/demo/sample.jpg?tr=w-384,c-at_max 384w, https://ik.imagekit.io/demo/sample.jpg?tr=w-640,c-at_max 640w, https://ik.imagekit.io/demo/sample.jpg?tr=w-750,c-at_max 750w, https://ik.imagekit.io/demo/sample.jpg?tr=w-828,c-at_max 828w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1080,c-at_max 1080w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1200,c-at_max 1200w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1920,c-at_max 1920w, https://ik.imagekit.io/demo/sample.jpg?tr=w-2048,c-at_max 2048w, https://ik.imagekit.io/demo/sample.jpg?tr=w-3840,c-at_max 3840w", + sizes: "50vw", + width: 600 + }); + }); + + it('multiple transformations', () => { + const out = getResponsiveImageAttributes({ + src: 'sample.jpg', + urlEndpoint: 'https://ik.imagekit.io/demo', + width: 450, + transformation: [ + { height: 300 }, + { aiRemoveBackground: true } + ] + }); + // Multiple caller transformations should be combined appropriately. + expect(out).to.deep.equal({ + src: "https://ik.imagekit.io/demo/sample.jpg?tr=h-300:e-bgremove:w-1080,c-at_max", + srcSet: "https://ik.imagekit.io/demo/sample.jpg?tr=h-300:e-bgremove:w-640,c-at_max 1x, https://ik.imagekit.io/demo/sample.jpg?tr=h-300:e-bgremove:w-1080,c-at_max 2x", + width: 450 + }); + }); + + it('sizes causes breakpoint pruning (33vw path)', () => { + const out = getResponsiveImageAttributes({ + src: 'sample.jpg', + urlEndpoint: 'https://ik.imagekit.io/demo', + sizes: '(min-width: 800px) 33vw, 100vw', + }); + // When specified with a sizes attribute that prunes breakpoints, the output should reflect the pruned values. + expect(out).to.deep.equal({ + src: "https://ik.imagekit.io/demo/sample.jpg?tr=w-3840,c-at_max", + srcSet: "https://ik.imagekit.io/demo/sample.jpg?tr=w-256,c-at_max 256w, https://ik.imagekit.io/demo/sample.jpg?tr=w-384,c-at_max 384w, https://ik.imagekit.io/demo/sample.jpg?tr=w-640,c-at_max 640w, https://ik.imagekit.io/demo/sample.jpg?tr=w-750,c-at_max 750w, https://ik.imagekit.io/demo/sample.jpg?tr=w-828,c-at_max 828w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1080,c-at_max 1080w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1200,c-at_max 1200w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1920,c-at_max 1920w, https://ik.imagekit.io/demo/sample.jpg?tr=w-2048,c-at_max 2048w, https://ik.imagekit.io/demo/sample.jpg?tr=w-3840,c-at_max 3840w", + sizes: "(min-width: 800px) 33vw, 100vw" + }); + }); + + it("Using queryParameters and transformationPosition", () => { + const out = getResponsiveImageAttributes({ + src: 'sample.jpg', + urlEndpoint: 'https://ik.imagekit.io/demo', + width: 450, + transformation: [ + { height: 300 }, + { aiRemoveBackground: true } + ], + queryParameters: { + key: "value" + }, + transformationPosition: "path" + }); + // The function should respect the transformation position and query parameters. + expect(out).to.deep.equal({ + src: "https://ik.imagekit.io/demo/tr:h-300:e-bgremove:w-1080,c-at_max/sample.jpg?key=value", + srcSet: "https://ik.imagekit.io/demo/tr:h-300:e-bgremove:w-640,c-at_max/sample.jpg?key=value 1x, https://ik.imagekit.io/demo/tr:h-300:e-bgremove:w-1080,c-at_max/sample.jpg?key=value 2x", + width: 450 + }); + }) + + it("fallback when no usable vw tokens", () => { + const out = getResponsiveImageAttributes({ + src: 'sample.jpg', + urlEndpoint: 'https://ik.imagekit.io/demo', + sizes: "100%" + }); + expect(out).to.deep.equal({ + src: "https://ik.imagekit.io/demo/sample.jpg?tr=w-3840,c-at_max", + srcSet: "https://ik.imagekit.io/demo/sample.jpg?tr=w-16,c-at_max 16w, https://ik.imagekit.io/demo/sample.jpg?tr=w-32,c-at_max 32w, https://ik.imagekit.io/demo/sample.jpg?tr=w-48,c-at_max 48w, https://ik.imagekit.io/demo/sample.jpg?tr=w-64,c-at_max 64w, https://ik.imagekit.io/demo/sample.jpg?tr=w-96,c-at_max 96w, https://ik.imagekit.io/demo/sample.jpg?tr=w-128,c-at_max 128w, https://ik.imagekit.io/demo/sample.jpg?tr=w-256,c-at_max 256w, https://ik.imagekit.io/demo/sample.jpg?tr=w-384,c-at_max 384w, https://ik.imagekit.io/demo/sample.jpg?tr=w-640,c-at_max 640w, https://ik.imagekit.io/demo/sample.jpg?tr=w-750,c-at_max 750w, https://ik.imagekit.io/demo/sample.jpg?tr=w-828,c-at_max 828w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1080,c-at_max 1080w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1200,c-at_max 1200w, https://ik.imagekit.io/demo/sample.jpg?tr=w-1920,c-at_max 1920w, https://ik.imagekit.io/demo/sample.jpg?tr=w-2048,c-at_max 2048w, https://ik.imagekit.io/demo/sample.jpg?tr=w-3840,c-at_max 3840w", + sizes: "100%" + }); + }) + +});