-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
ng_optimized_image.ts
621 lines (569 loc) · 25 KB
/
ng_optimized_image.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, ElementRef, Inject, Injector, Input, NgModule, NgZone, OnChanges, OnDestroy, OnInit, Renderer2, SimpleChanges, ɵformatRuntimeError as formatRuntimeError, ɵRuntimeError as RuntimeError} from '@angular/core';
import {RuntimeErrorCode} from '../../errors';
import {IMAGE_LOADER, ImageLoader} from './image_loaders/image_loader';
import {LCPImageObserver} from './lcp_image_observer';
import {PreconnectLinkChecker} from './preconnect_link_checker';
import {imgDirectiveDetails} from './util';
/**
* When a Base64-encoded image is passed as an input to the `NgOptimizedImage` directive,
* an error is thrown. The image content (as a string) might be very long, thus making
* it hard to read an error message if the entire string is included. This const defines
* the number of characters that should be included into the error message. The rest
* of the content is truncated.
*/
const BASE64_IMG_MAX_LENGTH_IN_ERROR = 50;
/**
* RegExpr to determine whether a src in a srcset is using width descriptors.
* Should match something like: "100w, 200w".
*/
const VALID_WIDTH_DESCRIPTOR_SRCSET = /^((\s*\d+w\s*(,|$)){1,})$/;
/**
* RegExpr to determine whether a src in a srcset is using density descriptors.
* Should match something like: "1x, 2x".
*/
const VALID_DENSITY_DESCRIPTOR_SRCSET = /^((\s*\d(\.\d)?x\s*(,|$)){1,})$/;
/**
* Srcset values with a density descriptor higher than this value will actively
* throw an error. Such densities are not permitted as they cause image sizes
* to be unreasonably large and slow down LCP.
*/
export const ABSOLUTE_SRCSET_DENSITY_CAP = 3;
/**
* Used only in error message text to communicate best practices, as we will
* only throw based on the slightly more conservative ABSOLUTE_SRCSET_DENSITY_CAP.
*/
export const RECOMMENDED_SRCSET_DENSITY_CAP = 2;
/**
* Used to determine whether two aspect ratios are similar in value.
*/
const ASPECT_RATIO_TOLERANCE = .1;
/**
* The directive that helps to improve image loading performance by following best practices.
*
* The `NgOptimizedImage` ensures that the loading of the LCP image is prioritized by:
* - Automatically setting the `fetchpriority` attribute on the `<img>` tag
* - Lazy loading non-priority images by default
* - Asserting that there is a corresponding preconnect link tag in the document head
*
* In addition, the directive:
* - Generates appropriate asset URLs (if a corresponding loader function is provided)
* - 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
*
* @usageNotes
* The `NgOptimizedImage` directive is marked as [standalone](guide/standalone-components) and can
* be imported directly.
*
* Follow the steps below to enable and use the directive:
* 1. Import it into the necessary NgModule or a standalone Component.
* 2. Configure a loader that you want to use.
* 3. Update the necessary `<img>` tags in templates and replace `src` attributes with `rawSrc`.
*
* Step 1: import the `NgOptimizedImage` directive.
*
* ```typescript
* import { NgOptimizedImage } from '@angular/common';
*
* // Include it into the necessary NgModule
* @NgModule({
* imports: [NgOptimizedImage],
* })
* class AppModule {}
*
* // ... or a standalone Component
* @Component({
* standalone: true
* imports: [NgOptimizedImage],
* })
* class MyStandaloneComponent {}
* ```
*
* Step 2: configure a loader.
*
* To use the **default loader**: no additional code changes are necessary. The URL returned by the
* generic loader will always match the value of "src". In other words, this loader applies no
* transformations to thr resource URL and the value of the `rawSrc` attribute will be used as is.
*
* To use an existing loader for a **third-party image service**: add the provider factory for your
* chosen service to the `providers` array. In the example below, the Imgix loader is used:
*
* ```typescript
* import {provideImgixLoader} from '@angular/common';
*
* // Call the function and add the result to the `providers` array:
* providers: [
* provideImgixLoader("https://my.base.url/"),
* ],
* ```
*
* The `NgOptimizedImage` directive provides the following functions:
* - `provideCloudflareLoader`
* - `provideCloudinaryLoader`
* - `provideImageKitLoader`
* - `provideImgixLoader`
*
* If you use a different image provider, you can create a custom loader function as described
* below.
*
* To use a **custom loader**: provide your loader function as a value for the `IMAGE_LOADER` DI
* token.
*
* ```typescript
* import {IMAGE_LOADER, ImageLoaderConfig} from '@angular/common';
*
* // Configure the loader using the `IMAGE_LOADER` token.
* providers: [
* {
* provide: IMAGE_LOADER,
* useValue: (config: ImageLoaderConfig) => {
* return `https://example.com/${config.src}-${config.width}.jpg}`;
* }
* },
* ],
* ```
*
* Step 3: update `<img>` tags in templates to use `rawSrc` instead of `rawSrc`.
*
* ```
* <img rawSrc="logo.png" width="200" height="100">
* ```
*
* @publicApi
* @developerPreview
*/
@Directive({
standalone: true,
selector: 'img[rawSrc]',
})
export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
constructor(
@Inject(IMAGE_LOADER) private imageLoader: ImageLoader, private renderer: Renderer2,
private imgElement: ElementRef, private injector: Injector) {}
// Private fields to keep normalized input values.
private _width?: number;
private _height?: number;
private _priority = false;
// Calculate the rewritten `src` once and store it.
// This is needed to avoid repetitive calculations and make sure the directive cleanup in the
// `ngOnDestroy` does not rely on the `IMAGE_LOADER` logic (which in turn can rely on some other
// instance that might be already destroyed).
private _rewrittenSrc: string|null = null;
/**
* Name of the source image.
* Image name will be processed by the image loader and the final URL will be applied as the `src`
* property of the image.
*/
@Input() rawSrc!: string;
/**
* A comma separated list of width or density descriptors.
* The image name will be taken from `rawSrc` and combined with the list of width or density
* descriptors to generate the final `srcset` property of the image.
*
* Example:
* ```
* <img rawSrc="hello.jpg" rawSrcset="100w, 200w" /> =>
* <img src="path/hello.jpg" srcset="path/hello.jpg?w=100 100w, path/hello.jpg?w=200 200w" />
* ```
*/
@Input() rawSrcset!: string;
/**
* The intrinsic width of the image in px.
*/
@Input()
set width(value: string|number|undefined) {
ngDevMode && assertGreaterThanZeroNumber(this, value, 'width');
this._width = inputToInteger(value);
}
get width(): number|undefined {
return this._width;
}
/**
* The intrinsic height of the image in px.
*/
@Input()
set height(value: string|number|undefined) {
ngDevMode && assertGreaterThanZeroNumber(this, value, 'height');
this._height = inputToInteger(value);
}
get height(): number|undefined {
return this._height;
}
/**
* The desired loading behavior (lazy, eager, or auto).
* The primary use case for this input is opting-out non-priority images
* from lazy loading by marking them loading='eager' or loading='auto'.
* This input should not be used with priority images.
*/
@Input() loading?: string;
/**
* Indicates whether this image should have a high priority.
*/
@Input()
set priority(value: string|boolean|undefined) {
this._priority = inputToBoolean(value);
}
get priority(): boolean {
return this._priority;
}
/**
* Get a value of the `src` and `srcset` if they're set on a host `<img>` element.
* These inputs are needed to verify that there are no conflicting sources provided
* at the same time (e.g. `src` and `rawSrc` together or `srcset` and `rawSrcset`,
* thus causing an ambiguity on which src to use) and that images
* don't start to load until a lazy loading strategy is set.
* @internal
*/
@Input() src?: string;
@Input() srcset?: string;
ngOnInit() {
if (ngDevMode) {
assertNonEmptyInput(this, 'rawSrc', this.rawSrc);
assertValidRawSrcset(this, this.rawSrcset);
assertNoConflictingSrc(this);
assertNoConflictingSrcset(this);
assertNotBase64Image(this);
assertNotBlobURL(this);
assertNonEmptyWidthAndHeight(this);
assertValidLoadingInput(this);
assertNoImageDistortion(this, this.imgElement, this.renderer);
if (this.priority) {
const checker = this.injector.get(PreconnectLinkChecker);
checker.check(this.getRewrittenSrc(), this.rawSrc);
} else {
// Monitor whether an image is an LCP element only in case
// the `priority` attribute is missing. Otherwise, an image
// has the necessary settings and no extra checks are required.
withLCPImageObserver(
this.injector,
(observer: LCPImageObserver) =>
observer.registerImage(this.getRewrittenSrc(), this.rawSrc));
}
}
// Must set width/height explicitly in case they are bound (in which case they will
// only be reflected and not found by the browser)
this.setHostAttribute('width', this.width!.toString());
this.setHostAttribute('height', this.height!.toString());
this.setHostAttribute('loading', this.getLoadingBehavior());
this.setHostAttribute('fetchpriority', this.getFetchPriority());
// 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.rawSrcset) {
this.setHostAttribute('srcset', this.getRewrittenSrcset());
}
}
ngOnChanges(changes: SimpleChanges) {
if (ngDevMode) {
assertNoPostInitInputChange(
this, changes, ['rawSrc', 'rawSrcset', 'width', 'height', 'priority']);
}
}
private getLoadingBehavior(): string {
if (!this.priority && this.loading !== undefined && isNonEmptyString(this.loading)) {
return this.loading;
}
return this.priority ? 'eager' : 'lazy';
}
private getFetchPriority(): string {
return this.priority ? 'high' : 'auto';
}
private getRewrittenSrc(): string {
// ImageLoaderConfig supports setting a width property. However, we're not setting width here
// because if the developer uses rendered width instead of intrinsic width in the HTML width
// attribute, the image requested may be too small for 2x+ screens.
if (!this._rewrittenSrc) {
const imgConfig = {src: this.rawSrc};
// Cache calculated image src to reuse it later in the code.
this._rewrittenSrc = this.imageLoader(imgConfig);
}
return this._rewrittenSrc;
}
private getRewrittenSrcset(): string {
const widthSrcSet = VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.rawSrcset);
const finalSrcs = this.rawSrcset.split(',').filter(src => src !== '').map(srcStr => {
srcStr = srcStr.trim();
const width = widthSrcSet ? parseFloat(srcStr) : parseFloat(srcStr) * this.width!;
return `${this.imageLoader({src: this.rawSrc, width})} ${srcStr}`;
});
return finalSrcs.join(', ');
}
ngOnDestroy() {
if (ngDevMode) {
if (!this.priority && this._rewrittenSrc !== null) {
withLCPImageObserver(
this.injector,
(observer: LCPImageObserver) => observer.unregisterImage(this._rewrittenSrc!));
}
}
}
private setHostAttribute(name: string, value: string): void {
this.renderer.setAttribute(this.imgElement.nativeElement, name, value);
}
}
/***** Helpers *****/
// Convert input value to integer.
function inputToInteger(value: string|number|undefined): number|undefined {
return typeof value === 'string' ? parseInt(value, 10) : value;
}
// Convert input value to boolean.
function inputToBoolean(value: unknown): boolean {
return value != null && `${value}` !== 'false';
}
function isNonEmptyString(value: unknown): boolean {
const isString = typeof value === 'string';
const isEmptyString = isString && value.trim() === '';
return isString && !isEmptyString;
}
/**
* Invokes a function, passing an instance of the `LCPImageObserver` as an argument.
*
* Notes:
* - the `LCPImageObserver` is a tree-shakable provider, provided in 'root',
* thus it's a singleton within this application
* - the process of `LCPImageObserver` creation and an actual operation are invoked outside of the
* NgZone to make sure none of the calls inside the `LCPImageObserver` class trigger unnecessary
* change detection
*/
function withLCPImageObserver(
injector: Injector, operation: (observer: LCPImageObserver) => void): void {
const ngZone = injector.get(NgZone);
return ngZone.runOutsideAngular(() => {
const observer = injector.get(LCPImageObserver);
operation(observer);
});
}
/***** Assert functions *****/
// Verifies that there is no `src` set on a host element.
function assertNoConflictingSrc(dir: NgOptimizedImage) {
if (dir.src) {
throw new RuntimeError(
RuntimeErrorCode.UNEXPECTED_SRC_ATTR,
`${imgDirectiveDetails(dir.rawSrc)} both \`src\` and \`rawSrc\` have been set. ` +
`Supplying both of these attributes is not necessary and will break lazy loading. ` +
`The NgOptimizedImage directive will set \`src\` itself based on the value of \`rawSrc\`. ` +
`To fix this, please remove the \`src\` attribute.`);
}
}
// Verifies that there is no `srcset` set on a host element.
function assertNoConflictingSrcset(dir: NgOptimizedImage) {
if (dir.srcset) {
throw new RuntimeError(
RuntimeErrorCode.UNEXPECTED_SRCSET_ATTR,
`${imgDirectiveDetails(dir.rawSrc)} both \`srcset\` and \`rawSrcset\` have been set. ` +
`Supplying both of these attributes is not necessary and will break lazy loading. ` +
`The NgOptimizedImage directive will set \`srcset\` itself based on the value of ` +
`\`rawSrcset\`. To fix this, please remove the \`srcset\` attribute.`);
}
}
// Verifies that the `rawSrc` is not a Base64-encoded image.
function assertNotBase64Image(dir: NgOptimizedImage) {
let rawSrc = dir.rawSrc.trim();
if (rawSrc.startsWith('data:')) {
if (rawSrc.length > BASE64_IMG_MAX_LENGTH_IN_ERROR) {
rawSrc = rawSrc.substring(0, BASE64_IMG_MAX_LENGTH_IN_ERROR) + '...';
}
throw new RuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${imgDirectiveDetails(dir.rawSrc, false)} \`rawSrc\` is a Base64-encoded string ` +
`(${rawSrc}). Base64-encoded strings are not supported by the NgOptimizedImage directive. ` +
`To fix this, disable the NgOptimizedImage directive for this element ` +
`by removing \`rawSrc\` and using a regular \`src\` attribute instead.`);
}
}
// Verifies that the `rawSrc` is not a Blob URL.
function assertNotBlobURL(dir: NgOptimizedImage) {
const rawSrc = dir.rawSrc.trim();
if (rawSrc.startsWith('blob:')) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${imgDirectiveDetails(dir.rawSrc)} \`rawSrc\` was set to a blob URL (${rawSrc}). ` +
`Blob URLs are not supported by the NgOptimizedImage directive. ` +
`To fix this, disable the NgOptimizedImage directive for this element ` +
`by removing \`rawSrc\` and using a regular \`src\` attribute instead.`);
}
}
// Verifies that the input is set to a non-empty string.
function assertNonEmptyInput(dir: NgOptimizedImage, name: string, value: unknown) {
const isString = typeof value === 'string';
const isEmptyString = isString && value.trim() === '';
if (!isString || isEmptyString) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${imgDirectiveDetails(dir.rawSrc)} \`${name}\` has an invalid value ` +
`(\`${value}\`). To fix this, change the value to a non-empty string.`);
}
}
// Verifies that the `rawSrcset` is in a valid format, e.g. "100w, 200w" or "1x, 2x"
export function assertValidRawSrcset(dir: NgOptimizedImage, value: unknown) {
if (value == null) return;
assertNonEmptyInput(dir, 'rawSrcset', value);
const stringVal = value as string;
const isValidWidthDescriptor = VALID_WIDTH_DESCRIPTOR_SRCSET.test(stringVal);
const isValidDensityDescriptor = VALID_DENSITY_DESCRIPTOR_SRCSET.test(stringVal);
if (isValidDensityDescriptor) {
assertUnderDensityCap(dir, stringVal);
}
const isValidSrcset = isValidWidthDescriptor || isValidDensityDescriptor;
if (!isValidSrcset) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${imgDirectiveDetails(dir.rawSrc)} \`rawSrcset\` has an invalid value (\`${value}\`). ` +
`To fix this, supply \`rawSrcset\` using a comma-separated list of one or more width ` +
`descriptors (e.g. "100w, 200w") or density descriptors (e.g. "1x, 2x").`);
}
}
function assertUnderDensityCap(dir: NgOptimizedImage, value: string) {
const underDensityCap =
value.split(',').every(num => num === '' || parseFloat(num) <= ABSOLUTE_SRCSET_DENSITY_CAP);
if (!underDensityCap) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${
imgDirectiveDetails(
dir.rawSrc)} the \`rawSrcset\` contains an unsupported image density:` +
`\`${value}\`. NgOptimizedImage generally recommends a max image density of ` +
`${RECOMMENDED_SRCSET_DENSITY_CAP}x but supports image densities up to ` +
`${ABSOLUTE_SRCSET_DENSITY_CAP}x. The human eye cannot distinguish between image densities ` +
`greater than ${RECOMMENDED_SRCSET_DENSITY_CAP}x - which makes them unnecessary for ` +
`most use cases. Images that will be pinch-zoomed are typically the primary use case for` +
`${ABSOLUTE_SRCSET_DENSITY_CAP}x images. Please remove the high density descriptor and try again.`);
}
}
// Creates a `RuntimeError` instance to represent a situation when an input is set after
// the directive has initialized.
function postInitInputChangeError(dir: NgOptimizedImage, inputName: string): {} {
return new RuntimeError(
RuntimeErrorCode.UNEXPECTED_INPUT_CHANGE,
`${imgDirectiveDetails(dir.rawSrc)} \`${inputName}\` was updated after initialization. ` +
`The NgOptimizedImage directive will not react to this input change. ` +
`To fix this, switch \`${inputName}\` a static value or wrap the image element ` +
`in an *ngIf that is gated on the necessary value.`);
}
// Verify that none of the listed inputs has changed.
function assertNoPostInitInputChange(
dir: NgOptimizedImage, changes: SimpleChanges, inputs: string[]) {
inputs.forEach(input => {
const isUpdated = changes.hasOwnProperty(input);
if (isUpdated && !changes[input].isFirstChange()) {
if (input === 'rawSrc') {
// When the `rawSrc` input changes, we detect that only in the
// `ngOnChanges` hook, thus the `rawSrc` is already set. We use
// `rawSrc` in the error message, so we use a previous value, but
// not the updated one in it.
dir = {rawSrc: changes[input].previousValue} as NgOptimizedImage;
}
throw postInitInputChangeError(dir, input);
}
});
}
// Verifies that a specified input is a number greater than 0.
function assertGreaterThanZeroNumber(
dir: NgOptimizedImage, inputValue: unknown, inputName: string) {
const validNumber = typeof inputValue === 'number' && inputValue > 0;
const validString =
typeof inputValue === 'string' && /^\d+$/.test(inputValue.trim()) && parseInt(inputValue) > 0;
if (!validNumber && !validString) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${imgDirectiveDetails(dir.rawSrc)} \`${inputName}\` has an invalid value ` +
`(\`${inputValue}\`). To fix this, provide \`${inputName}\` ` +
`as a number greater than 0.`);
}
}
// Verifies that the rendered image is not visually distorted. Effectively this is checking:
// - Whether the "width" and "height" attributes reflect the actual dimensions of the image.
// - Whether image styling is "correct" (see below for a longer explanation).
function assertNoImageDistortion(
dir: NgOptimizedImage, element: ElementRef<any>, renderer: Renderer2) {
const img = element.nativeElement;
const removeListenerFn = renderer.listen(img, 'load', () => {
removeListenerFn();
const renderedWidth = parseFloat(img.clientWidth);
const renderedHeight = parseFloat(img.clientHeight);
const renderedAspectRatio = renderedWidth / renderedHeight;
const nonZeroRenderedDimensions = renderedWidth !== 0 && renderedHeight !== 0;
const intrinsicWidth = parseFloat(img.naturalWidth);
const intrinsicHeight = parseFloat(img.naturalHeight);
const intrinsicAspectRatio = intrinsicWidth / intrinsicHeight;
const suppliedWidth = dir.width!;
const suppliedHeight = dir.height!;
const suppliedAspectRatio = suppliedWidth / suppliedHeight;
// Tolerance is used to account for the impact of subpixel rendering.
// Due to subpixel rendering, the rendered, intrinsic, and supplied
// aspect ratios of a correctly configured image may not exactly match.
// For example, a `width=4030 height=3020` image might have a rendered
// size of "1062w, 796.48h". (An aspect ratio of 1.334... vs. 1.333...)
const inaccurateDimensions =
Math.abs(suppliedAspectRatio - intrinsicAspectRatio) > ASPECT_RATIO_TOLERANCE;
const stylingDistortion = nonZeroRenderedDimensions &&
Math.abs(intrinsicAspectRatio - renderedAspectRatio) > ASPECT_RATIO_TOLERANCE;
if (inaccurateDimensions) {
console.warn(formatRuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${imgDirectiveDetails(dir.rawSrc)} the aspect ratio of the image does not match ` +
`the aspect ratio indicated by the width and height attributes. ` +
`Intrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` +
`(aspect-ratio: ${intrinsicAspectRatio}). Supplied width and height attributes: ` +
`${suppliedWidth}w x ${suppliedHeight}h (aspect-ratio: ${suppliedAspectRatio}). ` +
`To fix this, update the width and height attributes.`));
} else {
if (stylingDistortion) {
console.warn(formatRuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${imgDirectiveDetails(dir.rawSrc)} the aspect ratio of the rendered image ` +
`does not match the image's intrinsic aspect ratio. ` +
`Intrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` +
`(aspect-ratio: ${intrinsicAspectRatio}). Rendered image size: ` +
`${renderedWidth}w x ${renderedHeight}h (aspect-ratio: ` +
`${renderedAspectRatio}). This issue can occur if "width" and "height" ` +
`attributes are added to an image without updating the corresponding ` +
`image styling. To fix this, adjust image styling. In most cases, ` +
`adding "height: auto" or "width: auto" to the image styling will fix ` +
`this issue.`));
}
}
});
}
// Verifies that a specified input is set.
function assertNonEmptyWidthAndHeight(dir: NgOptimizedImage) {
let missingAttributes = [];
if (dir.width === undefined) missingAttributes.push('width');
if (dir.height === undefined) missingAttributes.push('height');
if (missingAttributes.length > 0) {
throw new RuntimeError(
RuntimeErrorCode.REQUIRED_INPUT_MISSING,
`${imgDirectiveDetails(dir.rawSrc)} these required attributes ` +
`are missing: ${missingAttributes.map(attr => `"${attr}"`).join(', ')}. ` +
`Including "width" and "height" attributes will prevent image-related layout shifts. ` +
`To fix this, include "width" and "height" attributes on the image tag.`);
}
}
// Verifies that the `loading` attribute is set to a valid input &
// is not used on priority images.
function assertValidLoadingInput(dir: NgOptimizedImage) {
if (dir.loading && dir.priority) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${imgDirectiveDetails(dir.rawSrc)} the \`loading\` attribute ` +
`was used on an image that was marked "priority". ` +
`Setting \`loading\` on priority images is not allowed ` +
`because these images will always be eagerly loaded. ` +
`To fix this, remove the “loading” attribute from the priority image.`);
}
const validInputs = ['auto', 'eager', 'lazy'];
if (typeof dir.loading === 'string' && !validInputs.includes(dir.loading)) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${imgDirectiveDetails(dir.rawSrc)} the \`loading\` attribute ` +
`has an invalid value (\`${dir.loading}\`). ` +
`To fix this, provide a valid value ("lazy", "eager", or "auto").`);
}
}