From 4fde292bb58f5d5bc3cf6e634f7cff9eb0d13d84 Mon Sep 17 00:00:00 2001 From: Alex Castle Date: Thu, 6 Oct 2022 16:40:00 -0700 Subject: [PATCH] feat(common): Add automatic srcset generation to ngOptimizedImage (#47547) Add a feature to automatically generate the srcset attribute for images using the NgOptimizedImage directive. Uses the 'sizes' attribute to determine the appropriate srcset to generate. PR Close #47547 --- aio/content/guide/image-directive.md | 63 +++++- goldens/public-api/common/index.md | 6 +- .../ng_optimized_image/ng_optimized_image.ts | 126 ++++++++++- .../directives/ng_optimized_image_spec.ts | 206 ++++++++++++++++-- .../e2e/image-distortion/image-distortion.ts | 12 +- .../e2e/oversized-image/oversized-image.ts | 2 +- 6 files changed, 381 insertions(+), 34 deletions(-) diff --git a/aio/content/guide/image-directive.md b/aio/content/guide/image-directive.md index 06ce9d3dc3f38..c074279e1fe8d 100644 --- a/aio/content/guide/image-directive.md +++ b/aio/content/guide/image-directive.md @@ -89,7 +89,40 @@ You can typically fix this by adding `height: auto` or `width: auto` to your ima ### Handling `srcset` attributes -If your `` tag defines a `srcset` attribute, replace it with `ngSrcset`. +Defining a [`srcset` attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/srcset) ensures that the browser requests an image at the right size for your user's viewport, so it doesn't waste time downloading an image that's too large. 'NgOptimizedImage' generates an appropriate `srcset` for the image, based on the presence and value of the [`sizes` attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes) on the image tag. + +#### Fixed-size images + +If your image should be "fixed" in size (i.e. the same size across devices, except for [pixel density](https://web.dev/codelab-density-descriptors/)), there is no need to set a `sizes` attribute. A `srcset` can be generated automatically from the image's width and height attributes with no further input required. + +Example srcset generated: `` + +#### Responsive images + +If your image should be responsive (i.e. grow and shrink according to viewport size), then you will need to define a [`sizes` attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes) to generate the `srcset`. + +If you haven't used `sizes` before, a good place to start is to set it based on viewport width. For example, if your CSS causes the image to fill 100% of viewport width, set `sizes` to `100vw` and the browser will select the image in the `srcset` that is closest to the viewport width (after accounting for pixel density). If your image is only likely to take up half the screen (ex: in a sidebar), set `sizes` to `50vw` to ensure the browser selects a smaller image. And so on. + +If you find that the above does not cover your desired image behavior, see the documentation on [advanced sizes values](#advanced-sizes-values). + +By default, the responsive breakpoints are: + +`[16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840]` + +If you would like to customize these breakpoints, you can do so using the `IMAGE_CONFIG` provider: + + +providers: [ + { + provide: IMAGE_CONFIG, + useValue: { + breakpoints: [16, 48, 96, 128, 384, 640, 750, 828, 1080, 1200, 1920] + } + }, +], + + +If you would like to manually define a `srcset` attribute, you can provide your own directly, or use the `ngSrcset` attribute: @@ -97,9 +130,7 @@ If your `` tag defines a `srcset` attribute, replace it with `ngSrcset`. -If the `ngSrcset` attribute is present, `NgOptimizedImage` generates and sets the [`srcset` attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/srcset) using the configured image loader. Do not include image file names in `ngSrcset` - the directive infers this information from `ngSrc`. The directive supports both width descriptors (e.g. `100w`) and density descriptors (e.g. `1x`) are supported. - -You can also use `ngSrcset` with the standard image [`sizes` attribute](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes). +If the `ngSrcset` attribute is present, `NgOptimizedImage` generates and sets the `srcset` using the configured image loader. Do not include image file names in `ngSrcset` - the directive infers this information from `ngSrc`. The directive supports both width descriptors (e.g. `100w`) and density descriptors (e.g. `1x`) are supported. @@ -107,6 +138,16 @@ You can also use `ngSrcset` with the standard image [`sizes` attribute](https:// +### Disabling automatic srcset generation + +To disable srcset generation for a single image, you can add the `disableOptimizedSrcset` attribute on the image: + + + +<img ngSrc="about.jpg" disableOptimizedSrcset> + + + ### Disabling image lazy loading By default, `NgOptimizedImage` sets `loading=lazy` for all images that are not marked `priority`. You can disable this behavior for non-priority images by setting the `loading` attribute. This attribute accepts values: `eager`, `auto`, and `lazy`. [See the documentation for the standard image `loading` attribute for details](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/loading#value). @@ -117,6 +158,20 @@ By default, `NgOptimizedImage` sets `loading=lazy` for all images that are not m +### Advanced 'sizes' values + +You may want to have images displayed at varying widths on differently-sized screens. A common example of this pattern is a grid- or column-based layout that renders a single column on mobile devices, and two columns on larger devices. You can capture this behavior in the `sizes` attribute, using a "media query" syntax, such as the following: + + + +<img ngSrc="cat.jpg" width="400" height="200" sizes="(max-width: 768px) 100vw, 50vw"> + + + +The `sizes` attribute in the above example says "I expect this image to be 100 percent of the screen width on devices under 768px wide. Otherwise, I expect it to be 50 percent of the screen width. + +For additional information about the `sizes` attribute, see [web.dev](https://web.dev/learn/design/responsive-images/#sizes) or [mdn](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes). + diff --git a/goldens/public-api/common/index.md b/goldens/public-api/common/index.md index 368263a16a394..ab18be6cb5f87 100644 --- a/goldens/public-api/common/index.md +++ b/goldens/public-api/common/index.md @@ -546,6 +546,9 @@ export abstract class NgLocalization { // @public export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy { + set disableOptimizedSrcset(value: string | boolean | undefined); + // (undocumented) + get disableOptimizedSrcset(): boolean; set height(value: string | number | undefined); // (undocumented) get height(): number | undefined; @@ -563,11 +566,12 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy { get priority(): boolean; // @deprecated set rawSrc(value: string); + sizes?: string; set width(value: string | number | undefined); // (undocumented) get width(): number | undefined; // (undocumented) - static ɵdir: i0.ɵɵDirectiveDeclaration; + static ɵdir: i0.ɵɵDirectiveDeclaration; // (undocumented) static ɵfac: i0.ɵɵFactoryDeclaration; } diff --git a/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts b/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts index fca335c95e4fa..fc1ac8469a9c0 100644 --- a/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts +++ b/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {Directive, ElementRef, inject, Injector, Input, NgZone, OnChanges, OnDestroy, OnInit, Renderer2, SimpleChanges, ɵformatRuntimeError as formatRuntimeError, ɵRuntimeError as RuntimeError} from '@angular/core'; +import {Directive, ElementRef, inject, InjectionToken, Injector, Input, NgZone, OnChanges, OnDestroy, OnInit, Renderer2, SimpleChanges, ɵformatRuntimeError as formatRuntimeError, ɵRuntimeError as RuntimeError} from '@angular/core'; import {RuntimeErrorCode} from '../../errors'; @@ -49,6 +49,15 @@ export const ABSOLUTE_SRCSET_DENSITY_CAP = 3; */ export const RECOMMENDED_SRCSET_DENSITY_CAP = 2; +/** + * Used in generating automatic density-based srcsets + */ +const DENSITY_SRCSET_MULTIPLIERS = [1, 2]; + +/** + * Used to determine which breakpoints to use on full-width images + */ +const VIEWPORT_BREAKPOINT_CUTOFF = 640; /** * Used to determine whether two aspect ratios are similar in value. */ @@ -61,6 +70,34 @@ const ASPECT_RATIO_TOLERANCE = .1; */ const OVERSIZED_IMAGE_TOLERANCE = 1000; +/** + * A configuration object for the NgOptimizedImage directive. Contains: + * - breakpoints: An array of integer breakpoints used to generate + * srcsets for responsive images. + * + * Learn more about the responsive image configuration in [the NgOptimizedImage + * guide](guide/image-directive). + * @publicApi + * @developerPreview + */ +export type ImageConfig = { + breakpoints?: number[] +}; + +const defaultConfig: ImageConfig = { + breakpoints: [16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840], +}; + +/** + * Injection token that configures the image optimized image functionality. + * + * @see `NgOptimizedImage` + * @publicApi + * @developerPreview + */ +export const IMAGE_CONFIG = new InjectionToken( + 'ImageConfig', {providedIn: 'root', factory: () => defaultConfig}); + /** * Directive that improves image loading performance by enforcing best practices. * @@ -72,6 +109,7 @@ const OVERSIZED_IMAGE_TOLERANCE = 1000; * * In addition, the directive: * - Generates appropriate asset URLs if a corresponding `ImageLoader` function is provided + * - Automatically generates a srcset * - Requires that `width` and `height` are set * - Warns if `width` or `height` have been set incorrectly * - Warns if the image will be visually distorted when rendered @@ -165,6 +203,7 @@ const OVERSIZED_IMAGE_TOLERANCE = 1000; }) export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy { private imageLoader = inject(IMAGE_LOADER); + private config: ImageConfig = processConfig(inject(IMAGE_CONFIG)); private renderer = inject(Renderer2); private imgElement: HTMLImageElement = inject(ElementRef).nativeElement; private injector = inject(Injector); @@ -223,6 +262,12 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy { */ @Input() ngSrcset!: string; + /** + * The base `sizes` attribute passed through to the `` element. + * Providing sizes causes the image to create an automatic responsive srcset. + */ + @Input() sizes?: string; + /** * The intrinsic width of the image in pixels. */ @@ -269,6 +314,18 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy { } private _priority = false; + /** + * Disables automatic srcset generation for this image. + */ + @Input() + set disableOptimizedSrcset(value: string|boolean|undefined) { + this._disableOptimizedSrcset = inputToBoolean(value); + } + get disableOptimizedSrcset(): boolean { + return this._disableOptimizedSrcset; + } + private _disableOptimizedSrcset = false; + /** * Value of the `src` attribute if set on the host `` element. * This input is exclusively read to assert that `src` is not set in conflict @@ -290,12 +347,17 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy { assertNonEmptyInput(this, 'ngSrc', this.ngSrc); assertValidNgSrcset(this, this.ngSrcset); assertNoConflictingSrc(this); - assertNoConflictingSrcset(this); + if (this.ngSrcset) { + assertNoConflictingSrcset(this); + } assertNotBase64Image(this); assertNotBlobUrl(this); assertNonEmptyWidthAndHeight(this); assertValidLoadingInput(this); assertNoImageDistortion(this, this.imgElement, this.renderer); + if (!this.ngSrcset) { + assertNoComplexSizes(this); + } if (this.priority) { const checker = this.injector.get(PreconnectLinkChecker); checker.assertPreconnect(this.getRewrittenSrc(), this.ngSrc); @@ -325,8 +387,13 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy { // The `src` and `srcset` attributes should be set last since other attributes // could affect the image's loading behavior. this.setHostAttribute('src', this.getRewrittenSrc()); + if (this.sizes) { + this.setHostAttribute('sizes', this.sizes); + } if (this.ngSrcset) { this.setHostAttribute('srcset', this.getRewrittenSrcset()); + } else if (!this._disableOptimizedSrcset && !this.srcset) { + this.setHostAttribute('srcset', this.getAutomaticSrcset()); } } @@ -370,6 +437,36 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy { return finalSrcs.join(', '); } + private getAutomaticSrcset(): string { + if (this.sizes) { + return this.getResponsiveSrcset(); + } else { + return this.getFixedSrcset(); + } + } + + private getResponsiveSrcset(): string { + const {breakpoints} = this.config; + + let filteredBreakpoints = breakpoints!; + if (this.sizes?.trim() === '100vw') { + // Since this is a full-screen-width image, our srcset only needs to include + // breakpoints with full viewport widths. + filteredBreakpoints = breakpoints!.filter(bp => bp >= VIEWPORT_BREAKPOINT_CUTOFF); + } + + const finalSrcs = + filteredBreakpoints.map(bp => `${this.imageLoader({src: this.ngSrc, width: bp})} ${bp}w`); + return finalSrcs.join(', '); + } + + private getFixedSrcset(): string { + const finalSrcs = DENSITY_SRCSET_MULTIPLIERS.map( + multiplier => `${this.imageLoader({src: this.ngSrc, width: this.width! * multiplier})} ${ + multiplier}x`); + return finalSrcs.join(', '); + } + ngOnDestroy() { if (ngDevMode) { if (!this.priority && this._renderedSrc !== null && this.lcpObserver !== null) { @@ -399,6 +496,16 @@ function inputToBoolean(value: unknown): boolean { return value != null && `${value}` !== 'false'; } +/** + * Sorts provided config breakpoints and uses defaults. + */ +function processConfig(config: ImageConfig): ImageConfig { + let sortedBreakpoints: {breakpoints?: number[]} = {}; + if (config.breakpoints) { + sortedBreakpoints.breakpoints = config.breakpoints.sort((a, b) => a - b); + } + return Object.assign({}, defaultConfig, config, sortedBreakpoints); +} /***** Assert functions *****/ @@ -448,6 +555,21 @@ function assertNotBase64Image(dir: NgOptimizedImage) { } } +/** + * Verifies that the 'sizes' only includes responsive values. + */ +function assertNoComplexSizes(dir: NgOptimizedImage) { + let sizes = dir.sizes; + if (sizes?.match(/((\)|,)\s|^)\d+px/)) { + throw new RuntimeError( + RuntimeErrorCode.INVALID_INPUT, + `${imgDirectiveDetails(dir.ngSrc, false)} \`sizes\` was set to a string including ` + + `pixel values. For automatic \`srcset\` generation, \`sizes\` must only include responsive ` + + `values, such as \`sizes="50vw"\` or \`sizes="(min-width: 768px) 50vw, 100vw"\`. ` + + `To fix this, modify the \`sizes\` attribute, or provide your own \`ngSrcset\` value directly.`); + } +} + /** * Verifies that the `ngSrc` is not a Blob URL. */ diff --git a/packages/common/test/directives/ng_optimized_image_spec.ts b/packages/common/test/directives/ng_optimized_image_spec.ts index 0cfb640220eaf..49284f4e3ec7c 100644 --- a/packages/common/test/directives/ng_optimized_image_spec.ts +++ b/packages/common/test/directives/ng_optimized_image_spec.ts @@ -14,7 +14,7 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; import {withHead} from '@angular/private/testing'; import {createImageLoader, IMAGE_LOADER, ImageLoader, ImageLoaderConfig} from '../../src/directives/ng_optimized_image/image_loaders/image_loader'; -import {ABSOLUTE_SRCSET_DENSITY_CAP, assertValidNgSrcset, NgOptimizedImage, RECOMMENDED_SRCSET_DENSITY_CAP} from '../../src/directives/ng_optimized_image/ng_optimized_image'; +import {ABSOLUTE_SRCSET_DENSITY_CAP, assertValidNgSrcset, IMAGE_CONFIG, ImageConfig, NgOptimizedImage, RECOMMENDED_SRCSET_DENSITY_CAP} from '../../src/directives/ng_optimized_image/ng_optimized_image'; import {PRECONNECT_CHECK_BLOCKLIST} from '../../src/directives/ng_optimized_image/preconnect_link_checker'; describe('Image directive', () => { @@ -99,11 +99,11 @@ describe('Image directive', () => { 'the `src` attribute.'); }); - it('should throw if both `ngSrc` and `srcset` is present', () => { + it('should throw if both `ngSrcet` and `srcset` is present', () => { setupTestingModule(); const template = - ''; + ''; expect(() => { const fixture = createTestComponent(template); fixture.detectChanges(); @@ -901,21 +901,6 @@ describe('Image directive', () => { }; }); - it('should NOT set `srcset` if no `ngSrcset` value', () => { - setupTestingModule({imageLoader}); - - const template = ` - - `; - const fixture = createTestComponent(template); - fixture.detectChanges(); - - const nativeElement = fixture.nativeElement as HTMLElement; - const img = nativeElement.querySelector('img')!; - expect(img.src).toBe(`${IMG_BASE_URL}/img-100.png`); - expect(img.srcset).toBe(''); - }); - it('should set the `srcset` using the `ngSrcset` value with width descriptors', () => { setupTestingModule({imageLoader}); @@ -1033,6 +1018,180 @@ describe('Image directive', () => { `${IMG_BASE_URL}/img.png?w=300 3x`); }); }); + + describe('sizes attribute', () => { + it('should pass through the sizes attribute', () => { + setupTestingModule(); + + const template = ''; + const fixture = createTestComponent(template); + fixture.detectChanges(); + + const nativeElement = fixture.nativeElement as HTMLElement; + const img = nativeElement.querySelector('img')!; + + expect(img.getAttribute('sizes')) + .toBe('(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw'); + }); + + it('should throw if a complex `sizes` is used', () => { + setupTestingModule(); + + const template = + ''; + expect(() => { + const fixture = createTestComponent(template); + fixture.detectChanges(); + }) + .toThrowError( + 'NG02952: The NgOptimizedImage directive has detected that `sizes` was set to a string including pixel values. ' + + 'For automatic `srcset` generation, `sizes` must only include responsive values, such as `sizes="50vw"` or ' + + '`sizes="(min-width: 768px) 50vw, 100vw"`. To fix this, modify the `sizes` attribute, or provide your own \`ngSrcset\` value directly.'); + }); + it('should throw if a complex `sizes` is used with srcset', () => { + setupTestingModule(); + + const template = + ''; + expect(() => { + const fixture = createTestComponent(template); + fixture.detectChanges(); + }) + .toThrowError( + 'NG02952: The NgOptimizedImage directive has detected that `sizes` was set to a string including pixel values. ' + + 'For automatic `srcset` generation, `sizes` must only include responsive values, such as `sizes="50vw"` or ' + + '`sizes="(min-width: 768px) 50vw, 100vw"`. To fix this, modify the `sizes` attribute, or provide your own \`ngSrcset\` value directly.'); + }); + it('should not throw if a complex `sizes` is used with ngSrcset', () => { + setupTestingModule(); + + const template = + ''; + expect(() => { + const fixture = createTestComponent(template); + fixture.detectChanges(); + }).not.toThrow(); + }); + }); + + describe('automatic srcset generation', () => { + const imageLoader = (config: ImageLoaderConfig) => { + const width = config.width ? `?w=${config.width}` : ``; + return `${IMG_BASE_URL}/${config.src}${width}`; + }; + + it('should add a responsive srcset to the img element if sizes attribute exists', () => { + setupTestingModule({imageLoader}); + + const template = ` + + `; + const fixture = createTestComponent(template); + fixture.detectChanges(); + + const nativeElement = fixture.nativeElement as HTMLElement; + const img = nativeElement.querySelector('img')!; + expect(img.getAttribute('srcset')) + .toBe(`${IMG_BASE_URL}/img?w=640 640w, ${IMG_BASE_URL}/img?w=750 750w, ${ + IMG_BASE_URL}/img?w=828 828w, ${IMG_BASE_URL}/img?w=1080 1080w, ${ + IMG_BASE_URL}/img?w=1200 1200w, ${IMG_BASE_URL}/img?w=1920 1920w, ${ + IMG_BASE_URL}/img?w=2048 2048w, ${IMG_BASE_URL}/img?w=3840 3840w`); + }); + + it('should use the long responsive srcset if sizes attribute exists and is less than 100vw', + () => { + setupTestingModule({imageLoader}); + + const template = ` + + `; + const fixture = createTestComponent(template); + fixture.detectChanges(); + + const nativeElement = fixture.nativeElement as HTMLElement; + const img = nativeElement.querySelector('img')!; + expect(img.getAttribute('srcset')) + .toBe(`${IMG_BASE_URL}/img?w=16 16w, ${IMG_BASE_URL}/img?w=32 32w, ${ + IMG_BASE_URL}/img?w=48 48w, ${IMG_BASE_URL}/img?w=64 64w, ${ + IMG_BASE_URL}/img?w=96 96w, ${IMG_BASE_URL}/img?w=128 128w, ${ + IMG_BASE_URL}/img?w=256 256w, ${IMG_BASE_URL}/img?w=384 384w, ${ + IMG_BASE_URL}/img?w=640 640w, ${IMG_BASE_URL}/img?w=750 750w, ${ + IMG_BASE_URL}/img?w=828 828w, ${IMG_BASE_URL}/img?w=1080 1080w, ${ + IMG_BASE_URL}/img?w=1200 1200w, ${IMG_BASE_URL}/img?w=1920 1920w, ${ + IMG_BASE_URL}/img?w=2048 2048w, ${IMG_BASE_URL}/img?w=3840 3840w`); + }); + + it('should add a fixed srcset to the img element if sizes attribute does not exist', () => { + setupTestingModule({imageLoader}); + + const template = ` + + `; + const fixture = createTestComponent(template); + fixture.detectChanges(); + + const nativeElement = fixture.nativeElement as HTMLElement; + const img = nativeElement.querySelector('img')!; + expect(img.getAttribute('srcset')) + .toBe(`${IMG_BASE_URL}/img?w=100 1x, ${IMG_BASE_URL}/img?w=200 2x`); + }); + + it('should use a custom breakpoint set if one is provided', () => { + const imageConfig = { + breakpoints: [16, 32, 48, 64, 96, 128, 256, 384, 640, 1280, 3840], + }; + setupTestingModule({imageLoader, imageConfig}); + + const template = ` + + `; + const fixture = createTestComponent(template); + fixture.detectChanges(); + const nativeElement = fixture.nativeElement as HTMLElement; + const img = nativeElement.querySelector('img')!; + expect(img.getAttribute('srcset')) + .toBe(`${IMG_BASE_URL}/img?w=16 16w, ${IMG_BASE_URL}/img?w=32 32w, ${ + IMG_BASE_URL}/img?w=48 48w, ${IMG_BASE_URL}/img?w=64 64w, ${ + IMG_BASE_URL}/img?w=96 96w, ${IMG_BASE_URL}/img?w=128 128w, ${ + IMG_BASE_URL}/img?w=256 256w, ${IMG_BASE_URL}/img?w=384 384w, ${ + IMG_BASE_URL}/img?w=640 640w, ${IMG_BASE_URL}/img?w=1280 1280w, ${ + IMG_BASE_URL}/img?w=3840 3840w`); + }); + + it('should sort custom breakpoint set', () => { + const imageConfig = { + breakpoints: [48, 16, 3840, 640, 1280], + }; + setupTestingModule({imageLoader, imageConfig}); + + const template = ` + + `; + const fixture = createTestComponent(template); + fixture.detectChanges(); + const nativeElement = fixture.nativeElement as HTMLElement; + const img = nativeElement.querySelector('img')!; + expect(img.getAttribute('srcset')) + .toBe(`${IMG_BASE_URL}/img?w=16 16w, ${IMG_BASE_URL}/img?w=48 48w, ${ + IMG_BASE_URL}/img?w=640 640w, ${IMG_BASE_URL}/img?w=1280 1280w, ${ + IMG_BASE_URL}/img?w=3840 3840w`); + }); + + it('should disable automatic srcset generation if "disableOptimizedSrcset" attribute is set', + () => { + setupTestingModule({imageLoader}); + + const template = ` + + `; + const fixture = createTestComponent(template); + fixture.detectChanges(); + const nativeElement = fixture.nativeElement as HTMLElement; + const img = nativeElement.querySelector('img')!; + expect(img.getAttribute('srcset')).toBeNull(); + }); + }); }); }); @@ -1059,8 +1218,12 @@ class TestComponent { priority = false; } -function setupTestingModule( - config?: {imageLoader?: ImageLoader, extraProviders?: Provider[], component?: Type}) { +function setupTestingModule(config?: { + imageConfig?: ImageConfig, + imageLoader?: ImageLoader, + extraProviders?: Provider[], + component?: Type +}) { const defaultLoader = (config: ImageLoaderConfig) => { const isAbsolute = /^https?:\/\//.test(config.src); return isAbsolute ? config.src : window.location.origin + '/' + config.src; @@ -1072,6 +1235,9 @@ function setupTestingModule( {provide: IMAGE_LOADER, useValue: loader}, ...extraProviders, ]; + if (config?.imageConfig) { + providers.push({provide: IMAGE_CONFIG, useValue: config.imageConfig}); + } TestBed.configureTestingModule({ declarations: [config?.component ?? TestComponent], diff --git a/packages/core/test/bundling/image-directive/e2e/image-distortion/image-distortion.ts b/packages/core/test/bundling/image-directive/e2e/image-distortion/image-distortion.ts index 0ee21ca12c223..ef34535742d1b 100644 --- a/packages/core/test/bundling/image-directive/e2e/image-distortion/image-distortion.ts +++ b/packages/core/test/bundling/image-directive/e2e/image-distortion/image-distortion.ts @@ -60,18 +60,18 @@ export class ImageDistortionPassingComponent { - + - + - +
- - + + - +
`, }) diff --git a/packages/core/test/bundling/image-directive/e2e/oversized-image/oversized-image.ts b/packages/core/test/bundling/image-directive/e2e/oversized-image/oversized-image.ts index 03dc15a8fa8dc..920758bc58c96 100644 --- a/packages/core/test/bundling/image-directive/e2e/oversized-image/oversized-image.ts +++ b/packages/core/test/bundling/image-directive/e2e/oversized-image/oversized-image.ts @@ -36,7 +36,7 @@ export class OversizedImageComponentPassing { template: `
- +
`, })