@angular/common 21.0.0-next.9 → 21.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2048 +1,1344 @@
1
1
  /**
2
- * @license Angular v21.0.0-next.9
2
+ * @license Angular v21.0.0-rc.1
3
3
  * (c) 2010-2025 Google LLC. https://angular.dev/
4
4
  * License: MIT
5
5
  */
6
6
 
7
7
  export { AsyncPipe, CommonModule, CurrencyPipe, DATE_PIPE_DEFAULT_OPTIONS, DATE_PIPE_DEFAULT_TIMEZONE, DatePipe, DecimalPipe, FormStyle, FormatWidth, HashLocationStrategy, I18nPluralPipe, I18nSelectPipe, JsonPipe, KeyValuePipe, LowerCasePipe, NgClass, NgComponentOutlet, NgForOf as NgFor, NgForOf, NgForOfContext, NgIf, NgIfContext, NgLocaleLocalization, NgLocalization, NgPlural, NgPluralCase, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgTemplateOutlet, NumberFormatStyle, NumberSymbol, PercentPipe, Plural, SlicePipe, TitleCasePipe, TranslationWidth, UpperCasePipe, WeekDay, formatCurrency, formatDate, formatNumber, formatPercent, getCurrencySymbol, getLocaleCurrencyCode, getLocaleCurrencyName, getLocaleCurrencySymbol, getLocaleDateFormat, getLocaleDateTimeFormat, getLocaleDayNames, getLocaleDayPeriods, getLocaleDirection, getLocaleEraNames, getLocaleExtraDayPeriodRules, getLocaleExtraDayPeriods, getLocaleFirstDayOfWeek, getLocaleId, getLocaleMonthNames, getLocaleNumberFormat, getLocaleNumberSymbol, getLocalePluralCase, getLocaleTimeFormat, getLocaleWeekEndRange, getNumberOfCurrencyDigits } from './_common_module-chunk.mjs';
8
8
  import * as i0 from '@angular/core';
9
- import { ɵregisterLocaleData as _registerLocaleData, Version, ɵɵdefineInjectable as __defineInjectable, inject, DOCUMENT, ɵformatRuntimeError as _formatRuntimeError, InjectionToken, ɵRuntimeError as _RuntimeError, Injectable, ɵIMAGE_CONFIG as _IMAGE_CONFIG, Renderer2, ElementRef, Injector, DestroyRef, ɵperformanceMarkFeature as _performanceMarkFeature, NgZone, ApplicationRef, numberAttribute, booleanAttribute, Directive, Input, ɵIMAGE_CONFIG_DEFAULTS as _IMAGE_CONFIG_DEFAULTS, ɵunwrapSafeValue as _unwrapSafeValue, ChangeDetectorRef } from '@angular/core';
9
+ import { inject, DestroyRef, Injectable, ɵregisterLocaleData as _registerLocaleData, Version, ɵɵdefineInjectable as __defineInjectable, DOCUMENT, ɵformatRuntimeError as _formatRuntimeError, InjectionToken, ɵRuntimeError as _RuntimeError, ɵIMAGE_CONFIG as _IMAGE_CONFIG, Renderer2, ElementRef, Injector, ɵperformanceMarkFeature as _performanceMarkFeature, NgZone, ApplicationRef, numberAttribute, booleanAttribute, Directive, Input, ɵIMAGE_CONFIG_DEFAULTS as _IMAGE_CONFIG_DEFAULTS, ɵunwrapSafeValue as _unwrapSafeValue, ChangeDetectorRef } from '@angular/core';
10
10
  export { DOCUMENT, ɵIMAGE_CONFIG as IMAGE_CONFIG } from '@angular/core';
11
- export { PlatformNavigation } from './_platform_navigation-chunk.mjs';
11
+ import { PlatformNavigation } from './_platform_navigation-chunk.mjs';
12
12
  export { XhrFactory, parseCookieValue as ɵparseCookieValue } from './_xhr-chunk.mjs';
13
- export { APP_BASE_HREF, BrowserPlatformLocation, LOCATION_INITIALIZED, Location, LocationStrategy, PathLocationStrategy, PlatformLocation, DomAdapter as ɵDomAdapter, getDOM as ɵgetDOM, normalizeQueryParams as ɵnormalizeQueryParams, setRootDomAdapter as ɵsetRootDomAdapter } from './_location-chunk.mjs';
13
+ import { Location, LocationStrategy, normalizeQueryParams } from './_location-chunk.mjs';
14
+ export { APP_BASE_HREF, BrowserPlatformLocation, LOCATION_INITIALIZED, PathLocationStrategy, PlatformLocation, DomAdapter as ɵDomAdapter, getDOM as ɵgetDOM, setRootDomAdapter as ɵsetRootDomAdapter } from './_location-chunk.mjs';
14
15
  import 'rxjs';
15
16
 
16
- /**
17
- * Register global data to be used internally by Angular. See the
18
- * ["I18n guide"](guide/i18n/format-data-locale) to know how to import additional locale
19
- * data.
20
- *
21
- * The signature registerLocaleData(data: any, extraData?: any) is deprecated since v5.1
22
- *
23
- * @publicApi
24
- */
17
+ class NavigationAdapterForLocation extends Location {
18
+ navigation = inject(PlatformNavigation);
19
+ destroyRef = inject(DestroyRef);
20
+ constructor() {
21
+ super(inject(LocationStrategy));
22
+ this.registerNavigationListeners();
23
+ }
24
+ registerNavigationListeners() {
25
+ const currentEntryChangeListener = () => {
26
+ this._notifyUrlChangeListeners(this.path(true), this.getState());
27
+ };
28
+ this.navigation.addEventListener('currententrychange', currentEntryChangeListener);
29
+ this.destroyRef.onDestroy(() => {
30
+ this.navigation.removeEventListener('currententrychange', currentEntryChangeListener);
31
+ });
32
+ }
33
+ getState() {
34
+ return this.navigation.currentEntry?.getState();
35
+ }
36
+ replaceState(path, query = '', state = null) {
37
+ const url = this.prepareExternalUrl(path + normalizeQueryParams(query));
38
+ this.navigation.navigate(url, {
39
+ state,
40
+ history: 'replace'
41
+ });
42
+ }
43
+ go(path, query = '', state = null) {
44
+ const url = this.prepareExternalUrl(path + normalizeQueryParams(query));
45
+ this.navigation.navigate(url, {
46
+ state,
47
+ history: 'push'
48
+ });
49
+ }
50
+ back() {
51
+ this.navigation.back();
52
+ }
53
+ forward() {
54
+ this.navigation.forward();
55
+ }
56
+ onUrlChange(fn) {
57
+ this._urlChangeListeners.push(fn);
58
+ return () => {
59
+ const fnIndex = this._urlChangeListeners.indexOf(fn);
60
+ this._urlChangeListeners.splice(fnIndex, 1);
61
+ };
62
+ }
63
+ static ɵfac = i0.ɵɵngDeclareFactory({
64
+ minVersion: "12.0.0",
65
+ version: "21.0.0-rc.1",
66
+ ngImport: i0,
67
+ type: NavigationAdapterForLocation,
68
+ deps: [],
69
+ target: i0.ɵɵFactoryTarget.Injectable
70
+ });
71
+ static ɵprov = i0.ɵɵngDeclareInjectable({
72
+ minVersion: "12.0.0",
73
+ version: "21.0.0-rc.1",
74
+ ngImport: i0,
75
+ type: NavigationAdapterForLocation
76
+ });
77
+ }
78
+ i0.ɵɵngDeclareClassMetadata({
79
+ minVersion: "12.0.0",
80
+ version: "21.0.0-rc.1",
81
+ ngImport: i0,
82
+ type: NavigationAdapterForLocation,
83
+ decorators: [{
84
+ type: Injectable
85
+ }],
86
+ ctorParameters: () => []
87
+ });
88
+
25
89
  function registerLocaleData(data, localeId, extraData) {
26
- return _registerLocaleData(data, localeId, extraData);
90
+ return _registerLocaleData(data, localeId, extraData);
27
91
  }
28
92
 
29
93
  const PLATFORM_BROWSER_ID = 'browser';
30
94
  const PLATFORM_SERVER_ID = 'server';
31
- /**
32
- * Returns whether a platform id represents a browser platform.
33
- * @publicApi
34
- */
35
95
  function isPlatformBrowser(platformId) {
36
- return platformId === PLATFORM_BROWSER_ID;
96
+ return platformId === PLATFORM_BROWSER_ID;
37
97
  }
38
- /**
39
- * Returns whether a platform id represents a server platform.
40
- * @publicApi
41
- */
42
98
  function isPlatformServer(platformId) {
43
- return platformId === PLATFORM_SERVER_ID;
99
+ return platformId === PLATFORM_SERVER_ID;
44
100
  }
45
101
 
46
- /**
47
- * @module
48
- * @description
49
- * Entry point for all public APIs of the common package.
50
- */
51
- /**
52
- * @publicApi
53
- */
54
- const VERSION = new Version('21.0.0-next.9');
102
+ const VERSION = new Version('21.0.0-rc.1');
55
103
 
56
- /**
57
- * Defines a scroll position manager. Implemented by `BrowserViewportScroller`.
58
- *
59
- * @publicApi
60
- */
61
104
  class ViewportScroller {
62
- // De-sugared tree-shakable injection
63
- // See #23917
64
- /** @nocollapse */
65
- static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ __defineInjectable({
66
- token: ViewportScroller,
67
- providedIn: 'root',
68
- factory: () => typeof ngServerMode !== 'undefined' && ngServerMode
69
- ? new NullViewportScroller()
70
- : new BrowserViewportScroller(inject(DOCUMENT), window),
71
- });
105
+ static ɵprov =
106
+ /* @__PURE__ */
107
+ __defineInjectable({
108
+ token: ViewportScroller,
109
+ providedIn: 'root',
110
+ factory: () => typeof ngServerMode !== 'undefined' && ngServerMode ? new NullViewportScroller() : new BrowserViewportScroller(inject(DOCUMENT), window)
111
+ });
72
112
  }
73
- /**
74
- * Manages the scroll position for a browser window.
75
- */
76
113
  class BrowserViewportScroller {
77
- document;
78
- window;
79
- offset = () => [0, 0];
80
- constructor(document, window) {
81
- this.document = document;
82
- this.window = window;
83
- }
84
- /**
85
- * Configures the top offset used when scrolling to an anchor.
86
- * @param offset A position in screen coordinates (a tuple with x and y values)
87
- * or a function that returns the top offset position.
88
- *
89
- */
90
- setOffset(offset) {
91
- if (Array.isArray(offset)) {
92
- this.offset = () => offset;
93
- }
94
- else {
95
- this.offset = offset;
96
- }
97
- }
98
- /**
99
- * Retrieves the current scroll position.
100
- * @returns The position in screen coordinates.
101
- */
102
- getScrollPosition() {
103
- return [this.window.scrollX, this.window.scrollY];
104
- }
105
- /**
106
- * Sets the scroll position.
107
- * @param position The new position in screen coordinates.
108
- */
109
- scrollToPosition(position, options) {
110
- this.window.scrollTo({ ...options, left: position[0], top: position[1] });
111
- }
112
- /**
113
- * Scrolls to an element and attempts to focus the element.
114
- *
115
- * Note that the function name here is misleading in that the target string may be an ID for a
116
- * non-anchor element.
117
- *
118
- * @param target The ID of an element or name of the anchor.
119
- *
120
- * @see https://html.spec.whatwg.org/#the-indicated-part-of-the-document
121
- * @see https://html.spec.whatwg.org/#scroll-to-fragid
122
- */
123
- scrollToAnchor(target, options) {
124
- const elSelected = findAnchorFromDocument(this.document, target);
125
- if (elSelected) {
126
- this.scrollToElement(elSelected, options);
127
- // After scrolling to the element, the spec dictates that we follow the focus steps for the
128
- // target. Rather than following the robust steps, simply attempt focus.
129
- //
130
- // @see https://html.spec.whatwg.org/#get-the-focusable-area
131
- // @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus
132
- // @see https://html.spec.whatwg.org/#focusable-area
133
- elSelected.focus();
134
- }
135
- }
136
- /**
137
- * Disables automatic scroll restoration provided by the browser.
138
- */
139
- setHistoryScrollRestoration(scrollRestoration) {
140
- try {
141
- this.window.history.scrollRestoration = scrollRestoration;
142
- }
143
- catch {
144
- console.warn(_formatRuntimeError(2400 /* RuntimeErrorCode.SCROLL_RESTORATION_UNSUPPORTED */, ngDevMode &&
145
- 'Failed to set `window.history.scrollRestoration`. ' +
146
- 'This may occur when:\n' +
147
- '• The script is running inside a sandboxed iframe\n' +
148
- '• The window is partially navigated or inactive\n' +
149
- '• The script is executed in an untrusted or special context (e.g., test runners, browser extensions, or content previews)\n' +
150
- 'Scroll position may not be preserved across navigation.'));
151
- }
152
- }
153
- /**
154
- * Scrolls to an element using the native offset and the specified offset set on this scroller.
155
- *
156
- * The offset can be used when we know that there is a floating header and scrolling naively to an
157
- * element (ex: `scrollIntoView`) leaves the element hidden behind the floating header.
158
- */
159
- scrollToElement(el, options) {
160
- const rect = el.getBoundingClientRect();
161
- const left = rect.left + this.window.pageXOffset;
162
- const top = rect.top + this.window.pageYOffset;
163
- const offset = this.offset();
164
- this.window.scrollTo({
165
- ...options,
166
- left: left - offset[0],
167
- top: top - offset[1],
168
- });
169
- }
114
+ document;
115
+ window;
116
+ offset = () => [0, 0];
117
+ constructor(document, window) {
118
+ this.document = document;
119
+ this.window = window;
120
+ }
121
+ setOffset(offset) {
122
+ if (Array.isArray(offset)) {
123
+ this.offset = () => offset;
124
+ } else {
125
+ this.offset = offset;
126
+ }
127
+ }
128
+ getScrollPosition() {
129
+ return [this.window.scrollX, this.window.scrollY];
130
+ }
131
+ scrollToPosition(position, options) {
132
+ this.window.scrollTo({
133
+ ...options,
134
+ left: position[0],
135
+ top: position[1]
136
+ });
137
+ }
138
+ scrollToAnchor(target, options) {
139
+ const elSelected = findAnchorFromDocument(this.document, target);
140
+ if (elSelected) {
141
+ this.scrollToElement(elSelected, options);
142
+ elSelected.focus();
143
+ }
144
+ }
145
+ setHistoryScrollRestoration(scrollRestoration) {
146
+ try {
147
+ this.window.history.scrollRestoration = scrollRestoration;
148
+ } catch {
149
+ console.warn(_formatRuntimeError(2400, ngDevMode && 'Failed to set `window.history.scrollRestoration`. ' + 'This may occur when:\n' + '• The script is running inside a sandboxed iframe\n' + '• The window is partially navigated or inactive\n' + '• The script is executed in an untrusted or special context (e.g., test runners, browser extensions, or content previews)\n' + 'Scroll position may not be preserved across navigation.'));
150
+ }
151
+ }
152
+ scrollToElement(el, options) {
153
+ const rect = el.getBoundingClientRect();
154
+ const left = rect.left + this.window.pageXOffset;
155
+ const top = rect.top + this.window.pageYOffset;
156
+ const offset = this.offset();
157
+ this.window.scrollTo({
158
+ ...options,
159
+ left: left - offset[0],
160
+ top: top - offset[1]
161
+ });
162
+ }
170
163
  }
171
164
  function findAnchorFromDocument(document, target) {
172
- const documentResult = document.getElementById(target) || document.getElementsByName(target)[0];
173
- if (documentResult) {
174
- return documentResult;
175
- }
176
- // `getElementById` and `getElementsByName` won't pierce through the shadow DOM so we
177
- // have to traverse the DOM manually and do the lookup through the shadow roots.
178
- if (typeof document.createTreeWalker === 'function' &&
179
- document.body &&
180
- typeof document.body.attachShadow === 'function') {
181
- const treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
182
- let currentNode = treeWalker.currentNode;
183
- while (currentNode) {
184
- const shadowRoot = currentNode.shadowRoot;
185
- if (shadowRoot) {
186
- // Note that `ShadowRoot` doesn't support `getElementsByName`
187
- // so we have to fall back to `querySelector`.
188
- const result = shadowRoot.getElementById(target) || shadowRoot.querySelector(`[name="${target}"]`);
189
- if (result) {
190
- return result;
191
- }
192
- }
193
- currentNode = treeWalker.nextNode();
165
+ const documentResult = document.getElementById(target) || document.getElementsByName(target)[0];
166
+ if (documentResult) {
167
+ return documentResult;
168
+ }
169
+ if (typeof document.createTreeWalker === 'function' && document.body && typeof document.body.attachShadow === 'function') {
170
+ const treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
171
+ let currentNode = treeWalker.currentNode;
172
+ while (currentNode) {
173
+ const shadowRoot = currentNode.shadowRoot;
174
+ if (shadowRoot) {
175
+ const result = shadowRoot.getElementById(target) || shadowRoot.querySelector(`[name="${target}"]`);
176
+ if (result) {
177
+ return result;
194
178
  }
179
+ }
180
+ currentNode = treeWalker.nextNode();
195
181
  }
196
- return null;
182
+ }
183
+ return null;
197
184
  }
198
- /**
199
- * Provides an empty implementation of the viewport scroller.
200
- */
201
185
  class NullViewportScroller {
202
- /**
203
- * Empty implementation
204
- */
205
- setOffset(offset) { }
206
- /**
207
- * Empty implementation
208
- */
209
- getScrollPosition() {
210
- return [0, 0];
211
- }
212
- /**
213
- * Empty implementation
214
- */
215
- scrollToPosition(position) { }
216
- /**
217
- * Empty implementation
218
- */
219
- scrollToAnchor(anchor) { }
220
- /**
221
- * Empty implementation
222
- */
223
- setHistoryScrollRestoration(scrollRestoration) { }
186
+ setOffset(offset) {}
187
+ getScrollPosition() {
188
+ return [0, 0];
189
+ }
190
+ scrollToPosition(position) {}
191
+ scrollToAnchor(anchor) {}
192
+ setHistoryScrollRestoration(scrollRestoration) {}
224
193
  }
225
194
 
226
- /**
227
- * Value (out of 100) of the requested quality for placeholder images.
228
- */
229
195
  const PLACEHOLDER_QUALITY = '20';
230
196
 
231
- // Converts a string that represents a URL into a URL class instance.
232
197
  function getUrl(src, win) {
233
- // Don't use a base URL is the URL is absolute.
234
- return isAbsoluteUrl(src) ? new URL(src) : new URL(src, win.location.href);
198
+ return isAbsoluteUrl(src) ? new URL(src) : new URL(src, win.location.href);
235
199
  }
236
- // Checks whether a URL is absolute (i.e. starts with `http://` or `https://`).
237
200
  function isAbsoluteUrl(src) {
238
- return /^https?:\/\//.test(src);
201
+ return /^https?:\/\//.test(src);
239
202
  }
240
- // Given a URL, extract the hostname part.
241
- // If a URL is a relative one - the URL is returned as is.
242
203
  function extractHostname(url) {
243
- return isAbsoluteUrl(url) ? new URL(url).hostname : url;
204
+ return isAbsoluteUrl(url) ? new URL(url).hostname : url;
244
205
  }
245
206
  function isValidPath(path) {
246
- const isString = typeof path === 'string';
247
- if (!isString || path.trim() === '') {
248
- return false;
249
- }
250
- // Calling new URL() will throw if the path string is malformed
251
- try {
252
- const url = new URL(path);
253
- return true;
254
- }
255
- catch {
256
- return false;
257
- }
207
+ const isString = typeof path === 'string';
208
+ if (!isString || path.trim() === '') {
209
+ return false;
210
+ }
211
+ try {
212
+ const url = new URL(path);
213
+ return true;
214
+ } catch {
215
+ return false;
216
+ }
258
217
  }
259
218
  function normalizePath(path) {
260
- return path.endsWith('/') ? path.slice(0, -1) : path;
219
+ return path.endsWith('/') ? path.slice(0, -1) : path;
261
220
  }
262
221
  function normalizeSrc(src) {
263
- return src.startsWith('/') ? src.slice(1) : src;
222
+ return src.startsWith('/') ? src.slice(1) : src;
264
223
  }
265
224
 
266
- /**
267
- * Noop image loader that does no transformation to the original src and just returns it as is.
268
- * This loader is used as a default one if more specific logic is not provided in an app config.
269
- *
270
- * @see {@link ImageLoader}
271
- * @see {@link NgOptimizedImage}
272
- */
273
- const noopImageLoader = (config) => config.src;
274
- /**
275
- * Injection token that configures the image loader function.
276
- *
277
- * @see {@link ImageLoader}
278
- * @see {@link NgOptimizedImage}
279
- * @publicApi
280
- */
225
+ const noopImageLoader = config => config.src;
281
226
  const IMAGE_LOADER = new InjectionToken(typeof ngDevMode !== undefined && ngDevMode ? 'ImageLoader' : '', {
282
- providedIn: 'root',
283
- factory: () => noopImageLoader,
227
+ factory: () => noopImageLoader
284
228
  });
285
- /**
286
- * Internal helper function that makes it easier to introduce custom image loaders for the
287
- * `NgOptimizedImage` directive. It is enough to specify a URL builder function to obtain full DI
288
- * configuration for a given loader: a DI token corresponding to the actual loader function, plus DI
289
- * tokens managing preconnect check functionality.
290
- * @param buildUrlFn a function returning a full URL based on loader's configuration
291
- * @param exampleUrls example of full URLs for a given loader (used in error messages)
292
- * @returns a set of DI providers corresponding to the configured image loader
293
- */
294
229
  function createImageLoader(buildUrlFn, exampleUrls) {
295
- return function provideImageLoader(path) {
296
- if (!isValidPath(path)) {
297
- throwInvalidPathError(path, exampleUrls || []);
298
- }
299
- // The trailing / is stripped (if provided) to make URL construction (concatenation) easier in
300
- // the individual loader functions.
301
- path = normalizePath(path);
302
- const loaderFn = (config) => {
303
- if (isAbsoluteUrl(config.src)) {
304
- // Image loader functions expect an image file name (e.g. `my-image.png`)
305
- // or a relative path + a file name (e.g. `/a/b/c/my-image.png`) as an input,
306
- // so the final absolute URL can be constructed.
307
- // When an absolute URL is provided instead - the loader can not
308
- // build a final URL, thus the error is thrown to indicate that.
309
- throwUnexpectedAbsoluteUrlError(path, config.src);
310
- }
311
- return buildUrlFn(path, { ...config, src: normalizeSrc(config.src) });
312
- };
313
- const providers = [{ provide: IMAGE_LOADER, useValue: loaderFn }];
314
- return providers;
230
+ return function provideImageLoader(path) {
231
+ if (!isValidPath(path)) {
232
+ throwInvalidPathError(path, exampleUrls || []);
233
+ }
234
+ path = normalizePath(path);
235
+ const loaderFn = config => {
236
+ if (isAbsoluteUrl(config.src)) {
237
+ throwUnexpectedAbsoluteUrlError(path, config.src);
238
+ }
239
+ return buildUrlFn(path, {
240
+ ...config,
241
+ src: normalizeSrc(config.src)
242
+ });
315
243
  };
244
+ const providers = [{
245
+ provide: IMAGE_LOADER,
246
+ useValue: loaderFn
247
+ }];
248
+ return providers;
249
+ };
316
250
  }
317
251
  function throwInvalidPathError(path, exampleUrls) {
318
- throw new _RuntimeError(2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, ngDevMode &&
319
- `Image loader has detected an invalid path (\`${path}\`). ` +
320
- `To fix this, supply a path using one of the following formats: ${exampleUrls.join(' or ')}`);
252
+ throw new _RuntimeError(2959, ngDevMode && `Image loader has detected an invalid path (\`${path}\`). ` + `To fix this, supply a path using one of the following formats: ${exampleUrls.join(' or ')}`);
321
253
  }
322
254
  function throwUnexpectedAbsoluteUrlError(path, url) {
323
- throw new _RuntimeError(2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, ngDevMode &&
324
- `Image loader has detected a \`<img>\` tag with an invalid \`ngSrc\` attribute: ${url}. ` +
325
- `This image loader expects \`ngSrc\` to be a relative URL - ` +
326
- `however the provided value is an absolute URL. ` +
327
- `To fix this, provide \`ngSrc\` as a path relative to the base URL ` +
328
- `configured for this loader (\`${path}\`).`);
255
+ throw new _RuntimeError(2959, ngDevMode && `Image loader has detected a \`<img>\` tag with an invalid \`ngSrc\` attribute: ${url}. ` + `This image loader expects \`ngSrc\` to be a relative URL - ` + `however the provided value is an absolute URL. ` + `To fix this, provide \`ngSrc\` as a path relative to the base URL ` + `configured for this loader (\`${path}\`).`);
329
256
  }
330
257
 
331
- /**
332
- * Function that generates an ImageLoader for [Cloudflare Image
333
- * Resizing](https://developers.cloudflare.com/images/image-resizing/) and turns it into an Angular
334
- * provider. Note: Cloudflare has multiple image products - this provider is specifically for
335
- * Cloudflare Image Resizing; it will not work with Cloudflare Images or Cloudflare Polish.
336
- *
337
- * @param path Your domain name, e.g. https://mysite.com
338
- * @returns Provider that provides an ImageLoader function
339
- *
340
- * @publicApi
341
- */
342
258
  const provideCloudflareLoader = createImageLoader(createCloudflareUrl, ngDevMode ? ['https://<ZONE>/cdn-cgi/image/<OPTIONS>/<SOURCE-IMAGE>'] : undefined);
343
259
  function createCloudflareUrl(path, config) {
344
- let params = `format=auto`;
345
- if (config.width) {
346
- params += `,width=${config.width}`;
347
- }
348
- // When requesting a placeholder image we ask for a low quality image to reduce the load time.
349
- if (config.isPlaceholder) {
350
- params += `,quality=${PLACEHOLDER_QUALITY}`;
351
- }
352
- // Cloudflare image URLs format:
353
- // https://developers.cloudflare.com/images/image-resizing/url-format/
354
- return `${path}/cdn-cgi/image/${params}/${config.src}`;
260
+ let params = `format=auto`;
261
+ if (config.width) {
262
+ params += `,width=${config.width}`;
263
+ }
264
+ if (config.isPlaceholder) {
265
+ params += `,quality=${PLACEHOLDER_QUALITY}`;
266
+ }
267
+ return `${path}/cdn-cgi/image/${params}/${config.src}`;
355
268
  }
356
269
 
357
- /**
358
- * Name and URL tester for Cloudinary.
359
- */
360
270
  const cloudinaryLoaderInfo = {
361
- name: 'Cloudinary',
362
- testUrl: isCloudinaryUrl,
271
+ name: 'Cloudinary',
272
+ testUrl: isCloudinaryUrl
363
273
  };
364
274
  const CLOUDINARY_LOADER_REGEX = /https?\:\/\/[^\/]+\.cloudinary\.com\/.+/;
365
- /**
366
- * Tests whether a URL is from Cloudinary CDN.
367
- */
368
275
  function isCloudinaryUrl(url) {
369
- return CLOUDINARY_LOADER_REGEX.test(url);
276
+ return CLOUDINARY_LOADER_REGEX.test(url);
370
277
  }
371
- /**
372
- * Function that generates an ImageLoader for Cloudinary and turns it into an Angular provider.
373
- *
374
- * @param path Base URL of your Cloudinary images
375
- * This URL should match one of the following formats:
376
- * https://res.cloudinary.com/mysite
377
- * https://mysite.cloudinary.com
378
- * https://subdomain.mysite.com
379
- * @returns Set of providers to configure the Cloudinary loader.
380
- *
381
- * @publicApi
382
- */
383
- const provideCloudinaryLoader = createImageLoader(createCloudinaryUrl, ngDevMode
384
- ? [
385
- 'https://res.cloudinary.com/mysite',
386
- 'https://mysite.cloudinary.com',
387
- 'https://subdomain.mysite.com',
388
- ]
389
- : undefined);
278
+ const provideCloudinaryLoader = createImageLoader(createCloudinaryUrl, ngDevMode ? ['https://res.cloudinary.com/mysite', 'https://mysite.cloudinary.com', 'https://subdomain.mysite.com'] : undefined);
390
279
  function createCloudinaryUrl(path, config) {
391
- // Cloudinary image URLformat:
392
- // https://cloudinary.com/documentation/image_transformations#transformation_url_structure
393
- // Example of a Cloudinary image URL:
394
- // https://res.cloudinary.com/mysite/image/upload/c_scale,f_auto,q_auto,w_600/marketing/tile-topics-m.png
395
- // For a placeholder image, we use the lowest image setting available to reduce the load time
396
- // else we use the auto size
397
- const quality = config.isPlaceholder ? 'q_auto:low' : 'q_auto';
398
- let params = `f_auto,${quality}`;
399
- if (config.width) {
400
- params += `,w_${config.width}`;
401
- }
402
- if (config.loaderParams?.['rounded']) {
403
- params += `,r_max`;
404
- }
405
- return `${path}/image/upload/${params}/${config.src}`;
280
+ const quality = config.isPlaceholder ? 'q_auto:low' : 'q_auto';
281
+ let params = `f_auto,${quality}`;
282
+ if (config.width) {
283
+ params += `,w_${config.width}`;
284
+ }
285
+ if (config.loaderParams?.['rounded']) {
286
+ params += `,r_max`;
287
+ }
288
+ return `${path}/image/upload/${params}/${config.src}`;
406
289
  }
407
290
 
408
- /**
409
- * Name and URL tester for ImageKit.
410
- */
411
291
  const imageKitLoaderInfo = {
412
- name: 'ImageKit',
413
- testUrl: isImageKitUrl,
292
+ name: 'ImageKit',
293
+ testUrl: isImageKitUrl
414
294
  };
415
295
  const IMAGE_KIT_LOADER_REGEX = /https?\:\/\/[^\/]+\.imagekit\.io\/.+/;
416
- /**
417
- * Tests whether a URL is from ImageKit CDN.
418
- */
419
296
  function isImageKitUrl(url) {
420
- return IMAGE_KIT_LOADER_REGEX.test(url);
297
+ return IMAGE_KIT_LOADER_REGEX.test(url);
421
298
  }
422
- /**
423
- * Function that generates an ImageLoader for ImageKit and turns it into an Angular provider.
424
- *
425
- * @param path Base URL of your ImageKit images
426
- * This URL should match one of the following formats:
427
- * https://ik.imagekit.io/myaccount
428
- * https://subdomain.mysite.com
429
- * @returns Set of providers to configure the ImageKit loader.
430
- *
431
- * @publicApi
432
- */
433
299
  const provideImageKitLoader = createImageLoader(createImagekitUrl, ngDevMode ? ['https://ik.imagekit.io/mysite', 'https://subdomain.mysite.com'] : undefined);
434
300
  function createImagekitUrl(path, config) {
435
- // Example of an ImageKit image URL:
436
- // https://ik.imagekit.io/demo/tr:w-300,h-300/medium_cafe_B1iTdD0C.jpg
437
- const { src, width } = config;
438
- const params = [];
439
- if (width) {
440
- params.push(`w-${width}`);
441
- }
442
- // When requesting a placeholder image we ask for a low quality image to reduce the load time.
443
- if (config.isPlaceholder) {
444
- params.push(`q-${PLACEHOLDER_QUALITY}`);
445
- }
446
- const urlSegments = params.length ? [path, `tr:${params.join(',')}`, src] : [path, src];
447
- const url = new URL(urlSegments.join('/'));
448
- return url.href;
301
+ const {
302
+ src,
303
+ width
304
+ } = config;
305
+ const params = [];
306
+ if (width) {
307
+ params.push(`w-${width}`);
308
+ }
309
+ if (config.isPlaceholder) {
310
+ params.push(`q-${PLACEHOLDER_QUALITY}`);
311
+ }
312
+ const urlSegments = params.length ? [path, `tr:${params.join(',')}`, src] : [path, src];
313
+ const url = new URL(urlSegments.join('/'));
314
+ return url.href;
449
315
  }
450
316
 
451
- /**
452
- * Name and URL tester for Imgix.
453
- */
454
317
  const imgixLoaderInfo = {
455
- name: 'Imgix',
456
- testUrl: isImgixUrl,
318
+ name: 'Imgix',
319
+ testUrl: isImgixUrl
457
320
  };
458
321
  const IMGIX_LOADER_REGEX = /https?\:\/\/[^\/]+\.imgix\.net\/.+/;
459
- /**
460
- * Tests whether a URL is from Imgix CDN.
461
- */
462
322
  function isImgixUrl(url) {
463
- return IMGIX_LOADER_REGEX.test(url);
323
+ return IMGIX_LOADER_REGEX.test(url);
464
324
  }
465
- /**
466
- * Function that generates an ImageLoader for Imgix and turns it into an Angular provider.
467
- *
468
- * @param path path to the desired Imgix origin,
469
- * e.g. https://somepath.imgix.net or https://images.mysite.com
470
- * @returns Set of providers to configure the Imgix loader.
471
- *
472
- * @publicApi
473
- */
474
325
  const provideImgixLoader = createImageLoader(createImgixUrl, ngDevMode ? ['https://somepath.imgix.net/'] : undefined);
475
326
  function createImgixUrl(path, config) {
476
- const url = new URL(`${path}/${config.src}`);
477
- // This setting ensures the smallest allowable format is set.
478
- url.searchParams.set('auto', 'format');
479
- if (config.width) {
480
- url.searchParams.set('w', config.width.toString());
481
- }
482
- // When requesting a placeholder image we ask a low quality image to reduce the load time.
483
- if (config.isPlaceholder) {
484
- url.searchParams.set('q', PLACEHOLDER_QUALITY);
485
- }
486
- return url.href;
327
+ const url = new URL(`${path}/${config.src}`);
328
+ url.searchParams.set('auto', 'format');
329
+ if (config.width) {
330
+ url.searchParams.set('w', config.width.toString());
331
+ }
332
+ if (config.isPlaceholder) {
333
+ url.searchParams.set('q', PLACEHOLDER_QUALITY);
334
+ }
335
+ return url.href;
487
336
  }
488
337
 
489
- /**
490
- * Name and URL tester for Netlify.
491
- */
492
338
  const netlifyLoaderInfo = {
493
- name: 'Netlify',
494
- testUrl: isNetlifyUrl,
339
+ name: 'Netlify',
340
+ testUrl: isNetlifyUrl
495
341
  };
496
342
  const NETLIFY_LOADER_REGEX = /https?\:\/\/[^\/]+\.netlify\.app\/.+/;
497
- /**
498
- * Tests whether a URL is from a Netlify site. This won't catch sites with a custom domain,
499
- * but it's a good start for sites in development. This is only used to warn users who haven't
500
- * configured an image loader.
501
- */
502
343
  function isNetlifyUrl(url) {
503
- return NETLIFY_LOADER_REGEX.test(url);
344
+ return NETLIFY_LOADER_REGEX.test(url);
504
345
  }
505
- /**
506
- * Function that generates an ImageLoader for Netlify and turns it into an Angular provider.
507
- *
508
- * @param path optional URL of the desired Netlify site. Defaults to the current site.
509
- * @returns Set of providers to configure the Netlify loader.
510
- *
511
- * @publicApi
512
- */
513
346
  function provideNetlifyLoader(path) {
514
- if (path && !isValidPath(path)) {
515
- throw new _RuntimeError(2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, ngDevMode &&
516
- `Image loader has detected an invalid path (\`${path}\`). ` +
517
- `To fix this, supply either the full URL to the Netlify site, or leave it empty to use the current site.`);
518
- }
519
- if (path) {
520
- const url = new URL(path);
521
- path = url.origin;
522
- }
523
- const loaderFn = (config) => {
524
- return createNetlifyUrl(config, path);
525
- };
526
- const providers = [{ provide: IMAGE_LOADER, useValue: loaderFn }];
527
- return providers;
528
- }
529
- const validParams = new Map([
530
- ['height', 'h'],
531
- ['fit', 'fit'],
532
- ['quality', 'q'],
533
- ['q', 'q'],
534
- ['position', 'position'],
535
- ]);
347
+ if (path && !isValidPath(path)) {
348
+ throw new _RuntimeError(2959, ngDevMode && `Image loader has detected an invalid path (\`${path}\`). ` + `To fix this, supply either the full URL to the Netlify site, or leave it empty to use the current site.`);
349
+ }
350
+ if (path) {
351
+ const url = new URL(path);
352
+ path = url.origin;
353
+ }
354
+ const loaderFn = config => {
355
+ return createNetlifyUrl(config, path);
356
+ };
357
+ const providers = [{
358
+ provide: IMAGE_LOADER,
359
+ useValue: loaderFn
360
+ }];
361
+ return providers;
362
+ }
363
+ const validParams = new Map([['height', 'h'], ['fit', 'fit'], ['quality', 'q'], ['q', 'q'], ['position', 'position']]);
536
364
  function createNetlifyUrl(config, path) {
537
- // Note: `path` can be undefined, in which case we use a fake one to construct a `URL` instance.
538
- const url = new URL(path ?? 'https://a/');
539
- url.pathname = '/.netlify/images';
540
- if (!isAbsoluteUrl(config.src) && !config.src.startsWith('/')) {
541
- config.src = '/' + config.src;
542
- }
543
- url.searchParams.set('url', config.src);
544
- if (config.width) {
545
- url.searchParams.set('w', config.width.toString());
546
- }
547
- // When requesting a placeholder image we ask for a low quality image to reduce the load time.
548
- // If the quality is specified in the loader config - always use provided value.
549
- const configQuality = config.loaderParams?.['quality'] ?? config.loaderParams?.['q'];
550
- if (config.isPlaceholder && !configQuality) {
551
- url.searchParams.set('q', PLACEHOLDER_QUALITY);
552
- }
553
- for (const [param, value] of Object.entries(config.loaderParams ?? {})) {
554
- if (validParams.has(param)) {
555
- url.searchParams.set(validParams.get(param), value.toString());
556
- }
557
- else {
558
- if (ngDevMode) {
559
- console.warn(_formatRuntimeError(2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, `The Netlify image loader has detected an \`<img>\` tag with the unsupported attribute "\`${param}\`".`));
560
- }
561
- }
562
- }
563
- // The "a" hostname is used for relative URLs, so we can remove it from the final URL.
564
- return url.hostname === 'a' ? url.href.replace(url.origin, '') : url.href;
365
+ const url = new URL(path ?? 'https://a/');
366
+ url.pathname = '/.netlify/images';
367
+ if (!isAbsoluteUrl(config.src) && !config.src.startsWith('/')) {
368
+ config.src = '/' + config.src;
369
+ }
370
+ url.searchParams.set('url', config.src);
371
+ if (config.width) {
372
+ url.searchParams.set('w', config.width.toString());
373
+ }
374
+ const configQuality = config.loaderParams?.['quality'] ?? config.loaderParams?.['q'];
375
+ if (config.isPlaceholder && !configQuality) {
376
+ url.searchParams.set('q', PLACEHOLDER_QUALITY);
377
+ }
378
+ for (const [param, value] of Object.entries(config.loaderParams ?? {})) {
379
+ if (validParams.has(param)) {
380
+ url.searchParams.set(validParams.get(param), value.toString());
381
+ } else {
382
+ if (ngDevMode) {
383
+ console.warn(_formatRuntimeError(2959, `The Netlify image loader has detected an \`<img>\` tag with the unsupported attribute "\`${param}\`".`));
384
+ }
385
+ }
386
+ }
387
+ return url.hostname === 'a' ? url.href.replace(url.origin, '') : url.href;
565
388
  }
566
389
 
567
- // Assembles directive details string, useful for error messages.
568
390
  function imgDirectiveDetails(ngSrc, includeNgSrc = true) {
569
- const ngSrcInfo = includeNgSrc
570
- ? `(activated on an <img> element with the \`ngSrc="${ngSrc}"\`) `
571
- : '';
572
- return `The NgOptimizedImage directive ${ngSrcInfo}has detected that`;
391
+ const ngSrcInfo = includeNgSrc ? `(activated on an <img> element with the \`ngSrc="${ngSrc}"\`) ` : '';
392
+ return `The NgOptimizedImage directive ${ngSrcInfo}has detected that`;
573
393
  }
574
394
 
575
- /**
576
- * Asserts that the application is in development mode. Throws an error if the application is in
577
- * production mode. This assert can be used to make sure that there is no dev-mode code invoked in
578
- * the prod mode accidentally.
579
- */
580
395
  function assertDevMode(checkName) {
581
- if (!ngDevMode) {
582
- throw new _RuntimeError(2958 /* RuntimeErrorCode.UNEXPECTED_DEV_MODE_CHECK_IN_PROD_MODE */, `Unexpected invocation of the ${checkName} in the prod mode. ` +
583
- `Please make sure that the prod mode is enabled for production builds.`);
584
- }
396
+ if (!ngDevMode) {
397
+ throw new _RuntimeError(2958, `Unexpected invocation of the ${checkName} in the prod mode. ` + `Please make sure that the prod mode is enabled for production builds.`);
398
+ }
585
399
  }
586
400
 
587
- /**
588
- * Observer that detects whether an image with `NgOptimizedImage`
589
- * is treated as a Largest Contentful Paint (LCP) element. If so,
590
- * asserts that the image has the `priority` attribute.
591
- *
592
- * Note: this is a dev-mode only class and it does not appear in prod bundles,
593
- * thus there is no `ngDevMode` use in the code.
594
- *
595
- * Based on https://web.dev/lcp/#measure-lcp-in-javascript.
596
- */
597
401
  class LCPImageObserver {
598
- // Map of full image URLs -> original `ngSrc` values.
599
- images = new Map();
600
- window = inject(DOCUMENT).defaultView;
601
- observer = null;
602
- constructor() {
603
- assertDevMode('LCP checker');
604
- if ((typeof ngServerMode === 'undefined' || !ngServerMode) &&
605
- typeof PerformanceObserver !== 'undefined') {
606
- this.observer = this.initPerformanceObserver();
607
- }
608
- }
609
- /**
610
- * Inits PerformanceObserver and subscribes to LCP events.
611
- * Based on https://web.dev/lcp/#measure-lcp-in-javascript
612
- */
613
- initPerformanceObserver() {
614
- const observer = new PerformanceObserver((entryList) => {
615
- const entries = entryList.getEntries();
616
- if (entries.length === 0)
617
- return;
618
- // We use the latest entry produced by the `PerformanceObserver` as the best
619
- // signal on which element is actually an LCP one. As an example, the first image to load on
620
- // a page, by virtue of being the only thing on the page so far, is often a LCP candidate
621
- // and gets reported by PerformanceObserver, but isn't necessarily the LCP element.
622
- const lcpElement = entries[entries.length - 1];
623
- // Cast to `any` due to missing `element` on the `LargestContentfulPaint` type of entry.
624
- // See https://developer.mozilla.org/en-US/docs/Web/API/LargestContentfulPaint
625
- const imgSrc = lcpElement.element?.src ?? '';
626
- // Exclude `data:` and `blob:` URLs, since they are not supported by the directive.
627
- if (imgSrc.startsWith('data:') || imgSrc.startsWith('blob:'))
628
- return;
629
- const img = this.images.get(imgSrc);
630
- if (!img)
631
- return;
632
- if (!img.priority && !img.alreadyWarnedPriority) {
633
- img.alreadyWarnedPriority = true;
634
- logMissingPriorityError(imgSrc);
635
- }
636
- if (img.modified && !img.alreadyWarnedModified) {
637
- img.alreadyWarnedModified = true;
638
- logModifiedWarning(imgSrc);
639
- }
640
- });
641
- observer.observe({ type: 'largest-contentful-paint', buffered: true });
642
- return observer;
643
- }
644
- registerImage(rewrittenSrc, originalNgSrc, isPriority) {
645
- if (!this.observer)
646
- return;
647
- const newObservedImageState = {
648
- priority: isPriority,
649
- modified: false,
650
- alreadyWarnedModified: false,
651
- alreadyWarnedPriority: false,
652
- };
653
- this.images.set(getUrl(rewrittenSrc, this.window).href, newObservedImageState);
654
- }
655
- unregisterImage(rewrittenSrc) {
656
- if (!this.observer)
657
- return;
658
- this.images.delete(getUrl(rewrittenSrc, this.window).href);
659
- }
660
- updateImage(originalSrc, newSrc) {
661
- if (!this.observer)
662
- return;
663
- const originalUrl = getUrl(originalSrc, this.window).href;
664
- const img = this.images.get(originalUrl);
665
- if (img) {
666
- img.modified = true;
667
- this.images.set(getUrl(newSrc, this.window).href, img);
668
- this.images.delete(originalUrl);
669
- }
670
- }
671
- ngOnDestroy() {
672
- if (!this.observer)
673
- return;
674
- this.observer.disconnect();
675
- this.images.clear();
676
- }
677
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.0.0-next.9", ngImport: i0, type: LCPImageObserver, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
678
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.0.0-next.9", ngImport: i0, type: LCPImageObserver, providedIn: 'root' });
679
- }
680
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.0-next.9", ngImport: i0, type: LCPImageObserver, decorators: [{
681
- type: Injectable,
682
- args: [{ providedIn: 'root' }]
683
- }], ctorParameters: () => [] });
402
+ images = new Map();
403
+ window = inject(DOCUMENT).defaultView;
404
+ observer = null;
405
+ constructor() {
406
+ assertDevMode('LCP checker');
407
+ if ((typeof ngServerMode === 'undefined' || !ngServerMode) && typeof PerformanceObserver !== 'undefined') {
408
+ this.observer = this.initPerformanceObserver();
409
+ }
410
+ }
411
+ initPerformanceObserver() {
412
+ const observer = new PerformanceObserver(entryList => {
413
+ const entries = entryList.getEntries();
414
+ if (entries.length === 0) return;
415
+ const lcpElement = entries[entries.length - 1];
416
+ const imgSrc = lcpElement.element?.src ?? '';
417
+ if (imgSrc.startsWith('data:') || imgSrc.startsWith('blob:')) return;
418
+ const img = this.images.get(imgSrc);
419
+ if (!img) return;
420
+ if (!img.priority && !img.alreadyWarnedPriority) {
421
+ img.alreadyWarnedPriority = true;
422
+ logMissingPriorityError(imgSrc);
423
+ }
424
+ if (img.modified && !img.alreadyWarnedModified) {
425
+ img.alreadyWarnedModified = true;
426
+ logModifiedWarning(imgSrc);
427
+ }
428
+ });
429
+ observer.observe({
430
+ type: 'largest-contentful-paint',
431
+ buffered: true
432
+ });
433
+ return observer;
434
+ }
435
+ registerImage(rewrittenSrc, originalNgSrc, isPriority) {
436
+ if (!this.observer) return;
437
+ const newObservedImageState = {
438
+ priority: isPriority,
439
+ modified: false,
440
+ alreadyWarnedModified: false,
441
+ alreadyWarnedPriority: false
442
+ };
443
+ this.images.set(getUrl(rewrittenSrc, this.window).href, newObservedImageState);
444
+ }
445
+ unregisterImage(rewrittenSrc) {
446
+ if (!this.observer) return;
447
+ this.images.delete(getUrl(rewrittenSrc, this.window).href);
448
+ }
449
+ updateImage(originalSrc, newSrc) {
450
+ if (!this.observer) return;
451
+ const originalUrl = getUrl(originalSrc, this.window).href;
452
+ const img = this.images.get(originalUrl);
453
+ if (img) {
454
+ img.modified = true;
455
+ this.images.set(getUrl(newSrc, this.window).href, img);
456
+ this.images.delete(originalUrl);
457
+ }
458
+ }
459
+ ngOnDestroy() {
460
+ if (!this.observer) return;
461
+ this.observer.disconnect();
462
+ this.images.clear();
463
+ }
464
+ static ɵfac = i0.ɵɵngDeclareFactory({
465
+ minVersion: "12.0.0",
466
+ version: "21.0.0-rc.1",
467
+ ngImport: i0,
468
+ type: LCPImageObserver,
469
+ deps: [],
470
+ target: i0.ɵɵFactoryTarget.Injectable
471
+ });
472
+ static ɵprov = i0.ɵɵngDeclareInjectable({
473
+ minVersion: "12.0.0",
474
+ version: "21.0.0-rc.1",
475
+ ngImport: i0,
476
+ type: LCPImageObserver,
477
+ providedIn: 'root'
478
+ });
479
+ }
480
+ i0.ɵɵngDeclareClassMetadata({
481
+ minVersion: "12.0.0",
482
+ version: "21.0.0-rc.1",
483
+ ngImport: i0,
484
+ type: LCPImageObserver,
485
+ decorators: [{
486
+ type: Injectable,
487
+ args: [{
488
+ providedIn: 'root'
489
+ }]
490
+ }],
491
+ ctorParameters: () => []
492
+ });
684
493
  function logMissingPriorityError(ngSrc) {
685
- const directiveDetails = imgDirectiveDetails(ngSrc);
686
- console.error(_formatRuntimeError(2955 /* RuntimeErrorCode.LCP_IMG_MISSING_PRIORITY */, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` +
687
- `element but was not marked "priority". This image should be marked ` +
688
- `"priority" in order to prioritize its loading. ` +
689
- `To fix this, add the "priority" attribute.`));
494
+ const directiveDetails = imgDirectiveDetails(ngSrc);
495
+ console.error(_formatRuntimeError(2955, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` + `element but was not marked "priority". This image should be marked ` + `"priority" in order to prioritize its loading. ` + `To fix this, add the "priority" attribute.`));
690
496
  }
691
497
  function logModifiedWarning(ngSrc) {
692
- const directiveDetails = imgDirectiveDetails(ngSrc);
693
- console.warn(_formatRuntimeError(2964 /* RuntimeErrorCode.LCP_IMG_NGSRC_MODIFIED */, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` +
694
- `element and has had its "ngSrc" attribute modified. This can cause ` +
695
- `slower loading performance. It is recommended not to modify the "ngSrc" ` +
696
- `property on any image which could be the LCP element.`));
498
+ const directiveDetails = imgDirectiveDetails(ngSrc);
499
+ console.warn(_formatRuntimeError(2964, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` + `element and has had its "ngSrc" attribute modified. This can cause ` + `slower loading performance. It is recommended not to modify the "ngSrc" ` + `property on any image which could be the LCP element.`));
697
500
  }
698
501
 
699
- // Set of origins that are always excluded from the preconnect checks.
700
- const INTERNAL_PRECONNECT_CHECK_BLOCKLIST = new Set(['localhost', '127.0.0.1', '0.0.0.0']);
701
- /**
702
- * Injection token to configure which origins should be excluded
703
- * from the preconnect checks. It can either be a single string or an array of strings
704
- * to represent a group of origins, for example:
705
- *
706
- * ```ts
707
- * {provide: PRECONNECT_CHECK_BLOCKLIST, useValue: 'https://your-domain.com'}
708
- * ```
709
- *
710
- * or:
711
- *
712
- * ```ts
713
- * {provide: PRECONNECT_CHECK_BLOCKLIST,
714
- * useValue: ['https://your-domain-1.com', 'https://your-domain-2.com']}
715
- * ```
716
- *
717
- * @publicApi
718
- */
502
+ const INTERNAL_PRECONNECT_CHECK_BLOCKLIST = new Set(['localhost', '127.0.0.1', '0.0.0.0', '[::1]']);
719
503
  const PRECONNECT_CHECK_BLOCKLIST = new InjectionToken(typeof ngDevMode !== undefined && ngDevMode ? 'PRECONNECT_CHECK_BLOCKLIST' : '');
720
- /**
721
- * Contains the logic to detect whether an image, marked with the "priority" attribute
722
- * has a corresponding `<link rel="preconnect">` tag in the `document.head`.
723
- *
724
- * Note: this is a dev-mode only class, which should not appear in prod bundles,
725
- * thus there is no `ngDevMode` use in the code.
726
- */
727
504
  class PreconnectLinkChecker {
728
- document = inject(DOCUMENT);
729
- /**
730
- * Set of <link rel="preconnect"> tags found on this page.
731
- * The `null` value indicates that there was no DOM query operation performed.
732
- */
733
- preconnectLinks = null;
734
- /*
735
- * Keep track of all already seen origin URLs to avoid repeating the same check.
736
- */
737
- alreadySeen = new Set();
738
- window = this.document.defaultView;
739
- blocklist = new Set(INTERNAL_PRECONNECT_CHECK_BLOCKLIST);
740
- constructor() {
741
- assertDevMode('preconnect link checker');
742
- const blocklist = inject(PRECONNECT_CHECK_BLOCKLIST, { optional: true });
743
- if (blocklist) {
744
- this.populateBlocklist(blocklist);
745
- }
746
- }
747
- populateBlocklist(origins) {
748
- if (Array.isArray(origins)) {
749
- deepForEach(origins, (origin) => {
750
- this.blocklist.add(extractHostname(origin));
751
- });
752
- }
753
- else {
754
- this.blocklist.add(extractHostname(origins));
755
- }
756
- }
757
- /**
758
- * Checks that a preconnect resource hint exists in the head for the
759
- * given src.
760
- *
761
- * @param rewrittenSrc src formatted with loader
762
- * @param originalNgSrc ngSrc value
763
- */
764
- assertPreconnect(rewrittenSrc, originalNgSrc) {
765
- if (typeof ngServerMode !== 'undefined' && ngServerMode)
766
- return;
767
- const imgUrl = getUrl(rewrittenSrc, this.window);
768
- if (this.blocklist.has(imgUrl.hostname) || this.alreadySeen.has(imgUrl.origin))
769
- return;
770
- // Register this origin as seen, so we don't check it again later.
771
- this.alreadySeen.add(imgUrl.origin);
772
- // Note: we query for preconnect links only *once* and cache the results
773
- // for the entire lifespan of an application, since it's unlikely that the
774
- // list would change frequently. This allows to make sure there are no
775
- // performance implications of making extra DOM lookups for each image.
776
- this.preconnectLinks ??= this.queryPreconnectLinks();
777
- if (!this.preconnectLinks.has(imgUrl.origin)) {
778
- console.warn(_formatRuntimeError(2956 /* RuntimeErrorCode.PRIORITY_IMG_MISSING_PRECONNECT_TAG */, `${imgDirectiveDetails(originalNgSrc)} there is no preconnect tag present for this ` +
779
- `image. Preconnecting to the origin(s) that serve priority images ensures that these ` +
780
- `images are delivered as soon as possible. To fix this, please add the following ` +
781
- `element into the <head> of the document:\n` +
782
- ` <link rel="preconnect" href="${imgUrl.origin}">`));
783
- }
784
- }
785
- queryPreconnectLinks() {
786
- const preconnectUrls = new Set();
787
- const links = this.document.querySelectorAll('link[rel=preconnect]');
788
- for (const link of links) {
789
- const url = getUrl(link.href, this.window);
790
- preconnectUrls.add(url.origin);
791
- }
792
- return preconnectUrls;
793
- }
794
- ngOnDestroy() {
795
- this.preconnectLinks?.clear();
796
- this.alreadySeen.clear();
797
- }
798
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.0.0-next.9", ngImport: i0, type: PreconnectLinkChecker, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
799
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.0.0-next.9", ngImport: i0, type: PreconnectLinkChecker, providedIn: 'root' });
800
- }
801
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.0-next.9", ngImport: i0, type: PreconnectLinkChecker, decorators: [{
802
- type: Injectable,
803
- args: [{ providedIn: 'root' }]
804
- }], ctorParameters: () => [] });
805
- /**
806
- * Invokes a callback for each element in the array. Also invokes a callback
807
- * recursively for each nested array.
808
- */
505
+ document = inject(DOCUMENT);
506
+ preconnectLinks = null;
507
+ alreadySeen = new Set();
508
+ window = this.document.defaultView;
509
+ blocklist = new Set(INTERNAL_PRECONNECT_CHECK_BLOCKLIST);
510
+ constructor() {
511
+ assertDevMode('preconnect link checker');
512
+ const blocklist = inject(PRECONNECT_CHECK_BLOCKLIST, {
513
+ optional: true
514
+ });
515
+ if (blocklist) {
516
+ this.populateBlocklist(blocklist);
517
+ }
518
+ }
519
+ populateBlocklist(origins) {
520
+ if (Array.isArray(origins)) {
521
+ deepForEach(origins, origin => {
522
+ this.blocklist.add(extractHostname(origin));
523
+ });
524
+ } else {
525
+ this.blocklist.add(extractHostname(origins));
526
+ }
527
+ }
528
+ assertPreconnect(rewrittenSrc, originalNgSrc) {
529
+ if (typeof ngServerMode !== 'undefined' && ngServerMode) return;
530
+ const imgUrl = getUrl(rewrittenSrc, this.window);
531
+ if (this.blocklist.has(imgUrl.hostname) || this.alreadySeen.has(imgUrl.origin)) return;
532
+ this.alreadySeen.add(imgUrl.origin);
533
+ this.preconnectLinks ??= this.queryPreconnectLinks();
534
+ if (!this.preconnectLinks.has(imgUrl.origin)) {
535
+ console.warn(_formatRuntimeError(2956, `${imgDirectiveDetails(originalNgSrc)} there is no preconnect tag present for this ` + `image. Preconnecting to the origin(s) that serve priority images ensures that these ` + `images are delivered as soon as possible. To fix this, please add the following ` + `element into the <head> of the document:\n` + ` <link rel="preconnect" href="${imgUrl.origin}">`));
536
+ }
537
+ }
538
+ queryPreconnectLinks() {
539
+ const preconnectUrls = new Set();
540
+ const links = this.document.querySelectorAll('link[rel=preconnect]');
541
+ for (const link of links) {
542
+ const url = getUrl(link.href, this.window);
543
+ preconnectUrls.add(url.origin);
544
+ }
545
+ return preconnectUrls;
546
+ }
547
+ ngOnDestroy() {
548
+ this.preconnectLinks?.clear();
549
+ this.alreadySeen.clear();
550
+ }
551
+ static ɵfac = i0.ɵɵngDeclareFactory({
552
+ minVersion: "12.0.0",
553
+ version: "21.0.0-rc.1",
554
+ ngImport: i0,
555
+ type: PreconnectLinkChecker,
556
+ deps: [],
557
+ target: i0.ɵɵFactoryTarget.Injectable
558
+ });
559
+ static ɵprov = i0.ɵɵngDeclareInjectable({
560
+ minVersion: "12.0.0",
561
+ version: "21.0.0-rc.1",
562
+ ngImport: i0,
563
+ type: PreconnectLinkChecker,
564
+ providedIn: 'root'
565
+ });
566
+ }
567
+ i0.ɵɵngDeclareClassMetadata({
568
+ minVersion: "12.0.0",
569
+ version: "21.0.0-rc.1",
570
+ ngImport: i0,
571
+ type: PreconnectLinkChecker,
572
+ decorators: [{
573
+ type: Injectable,
574
+ args: [{
575
+ providedIn: 'root'
576
+ }]
577
+ }],
578
+ ctorParameters: () => []
579
+ });
809
580
  function deepForEach(input, fn) {
810
- for (let value of input) {
811
- Array.isArray(value) ? deepForEach(value, fn) : fn(value);
812
- }
581
+ for (let value of input) {
582
+ Array.isArray(value) ? deepForEach(value, fn) : fn(value);
583
+ }
813
584
  }
814
585
 
815
- /**
816
- * In SSR scenarios, a preload `<link>` element is generated for priority images.
817
- * Having a large number of preload tags may negatively affect the performance,
818
- * so we warn developers (by throwing an error) if the number of preloaded images
819
- * is above a certain threshold. This const specifies this threshold.
820
- */
821
586
  const DEFAULT_PRELOADED_IMAGES_LIMIT = 5;
822
- /**
823
- * Helps to keep track of priority images that already have a corresponding
824
- * preload tag (to avoid generating multiple preload tags with the same URL).
825
- *
826
- * This Set tracks the original src passed into the `ngSrc` input not the src after it has been
827
- * run through the specified `IMAGE_LOADER`.
828
- */
829
587
  const PRELOADED_IMAGES = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'NG_OPTIMIZED_PRELOADED_IMAGES' : '', {
830
- providedIn: 'root',
831
- factory: () => new Set(),
588
+ factory: () => new Set()
832
589
  });
833
590
 
834
- /**
835
- * @description Contains the logic needed to track and add preload link tags to the `<head>` tag. It
836
- * will also track what images have already had preload link tags added so as to not duplicate link
837
- * tags.
838
- *
839
- * In dev mode this service will validate that the number of preloaded images does not exceed the
840
- * configured default preloaded images limit: {@link DEFAULT_PRELOADED_IMAGES_LIMIT}.
841
- */
842
591
  class PreloadLinkCreator {
843
- preloadedImages = inject(PRELOADED_IMAGES);
844
- document = inject(DOCUMENT);
845
- errorShown = false;
846
- /**
847
- * @description Add a preload `<link>` to the `<head>` of the `index.html` that is served from the
848
- * server while using Angular Universal and SSR to kick off image loads for high priority images.
849
- *
850
- * The `sizes` (passed in from the user) and `srcset` (parsed and formatted from `ngSrcset`)
851
- * properties used to set the corresponding attributes, `imagesizes` and `imagesrcset`
852
- * respectively, on the preload `<link>` tag so that the correctly sized image is preloaded from
853
- * the CDN.
854
- *
855
- * {@link https://web.dev/preload-responsive-images/#imagesrcset-and-imagesizes}
856
- *
857
- * @param renderer The `Renderer2` passed in from the directive
858
- * @param src The original src of the image that is set on the `ngSrc` input.
859
- * @param srcset The parsed and formatted srcset created from the `ngSrcset` input
860
- * @param sizes The value of the `sizes` attribute passed in to the `<img>` tag
861
- */
862
- createPreloadLinkTag(renderer, src, srcset, sizes) {
863
- if (ngDevMode &&
864
- !this.errorShown &&
865
- this.preloadedImages.size >= DEFAULT_PRELOADED_IMAGES_LIMIT) {
866
- this.errorShown = true;
867
- console.warn(_formatRuntimeError(2961 /* RuntimeErrorCode.TOO_MANY_PRELOADED_IMAGES */, `The \`NgOptimizedImage\` directive has detected that more than ` +
868
- `${DEFAULT_PRELOADED_IMAGES_LIMIT} images were marked as priority. ` +
869
- `This might negatively affect an overall performance of the page. ` +
870
- `To fix this, remove the "priority" attribute from images with less priority.`));
871
- }
872
- if (this.preloadedImages.has(src)) {
873
- return;
874
- }
875
- this.preloadedImages.add(src);
876
- const preload = renderer.createElement('link');
877
- renderer.setAttribute(preload, 'as', 'image');
878
- renderer.setAttribute(preload, 'href', src);
879
- renderer.setAttribute(preload, 'rel', 'preload');
880
- renderer.setAttribute(preload, 'fetchpriority', 'high');
881
- if (sizes) {
882
- renderer.setAttribute(preload, 'imageSizes', sizes);
883
- }
884
- if (srcset) {
885
- renderer.setAttribute(preload, 'imageSrcset', srcset);
886
- }
887
- renderer.appendChild(this.document.head, preload);
888
- }
889
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.0.0-next.9", ngImport: i0, type: PreloadLinkCreator, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
890
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.0.0-next.9", ngImport: i0, type: PreloadLinkCreator, providedIn: 'root' });
891
- }
892
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.0-next.9", ngImport: i0, type: PreloadLinkCreator, decorators: [{
893
- type: Injectable,
894
- args: [{ providedIn: 'root' }]
895
- }] });
592
+ preloadedImages = inject(PRELOADED_IMAGES);
593
+ document = inject(DOCUMENT);
594
+ errorShown = false;
595
+ createPreloadLinkTag(renderer, src, srcset, sizes) {
596
+ if (ngDevMode && !this.errorShown && this.preloadedImages.size >= DEFAULT_PRELOADED_IMAGES_LIMIT) {
597
+ this.errorShown = true;
598
+ console.warn(_formatRuntimeError(2961, `The \`NgOptimizedImage\` directive has detected that more than ` + `${DEFAULT_PRELOADED_IMAGES_LIMIT} images were marked as priority. ` + `This might negatively affect an overall performance of the page. ` + `To fix this, remove the "priority" attribute from images with less priority.`));
599
+ }
600
+ if (this.preloadedImages.has(src)) {
601
+ return;
602
+ }
603
+ this.preloadedImages.add(src);
604
+ const preload = renderer.createElement('link');
605
+ renderer.setAttribute(preload, 'as', 'image');
606
+ renderer.setAttribute(preload, 'href', src);
607
+ renderer.setAttribute(preload, 'rel', 'preload');
608
+ renderer.setAttribute(preload, 'fetchpriority', 'high');
609
+ if (sizes) {
610
+ renderer.setAttribute(preload, 'imageSizes', sizes);
611
+ }
612
+ if (srcset) {
613
+ renderer.setAttribute(preload, 'imageSrcset', srcset);
614
+ }
615
+ renderer.appendChild(this.document.head, preload);
616
+ }
617
+ static ɵfac = i0.ɵɵngDeclareFactory({
618
+ minVersion: "12.0.0",
619
+ version: "21.0.0-rc.1",
620
+ ngImport: i0,
621
+ type: PreloadLinkCreator,
622
+ deps: [],
623
+ target: i0.ɵɵFactoryTarget.Injectable
624
+ });
625
+ static ɵprov = i0.ɵɵngDeclareInjectable({
626
+ minVersion: "12.0.0",
627
+ version: "21.0.0-rc.1",
628
+ ngImport: i0,
629
+ type: PreloadLinkCreator,
630
+ providedIn: 'root'
631
+ });
632
+ }
633
+ i0.ɵɵngDeclareClassMetadata({
634
+ minVersion: "12.0.0",
635
+ version: "21.0.0-rc.1",
636
+ ngImport: i0,
637
+ type: PreloadLinkCreator,
638
+ decorators: [{
639
+ type: Injectable,
640
+ args: [{
641
+ providedIn: 'root'
642
+ }]
643
+ }]
644
+ });
896
645
 
897
- /**
898
- * When a Base64-encoded image is passed as an input to the `NgOptimizedImage` directive,
899
- * an error is thrown. The image content (as a string) might be very long, thus making
900
- * it hard to read an error message if the entire string is included. This const defines
901
- * the number of characters that should be included into the error message. The rest
902
- * of the content is truncated.
903
- */
904
646
  const BASE64_IMG_MAX_LENGTH_IN_ERROR = 50;
905
- /**
906
- * RegExpr to determine whether a src in a srcset is using width descriptors.
907
- * Should match something like: "100w, 200w".
908
- */
909
647
  const VALID_WIDTH_DESCRIPTOR_SRCSET = /^((\s*\d+w\s*(,|$)){1,})$/;
910
- /**
911
- * RegExpr to determine whether a src in a srcset is using density descriptors.
912
- * Should match something like: "1x, 2x, 50x". Also supports decimals like "1.5x, 1.50x".
913
- */
914
648
  const VALID_DENSITY_DESCRIPTOR_SRCSET = /^((\s*\d+(\.\d+)?x\s*(,|$)){1,})$/;
915
- /**
916
- * Srcset values with a density descriptor higher than this value will actively
917
- * throw an error. Such densities are not permitted as they cause image sizes
918
- * to be unreasonably large and slow down LCP.
919
- */
920
649
  const ABSOLUTE_SRCSET_DENSITY_CAP = 3;
921
- /**
922
- * Used only in error message text to communicate best practices, as we will
923
- * only throw based on the slightly more conservative ABSOLUTE_SRCSET_DENSITY_CAP.
924
- */
925
650
  const RECOMMENDED_SRCSET_DENSITY_CAP = 2;
926
- /**
927
- * Used in generating automatic density-based srcsets
928
- */
929
651
  const DENSITY_SRCSET_MULTIPLIERS = [1, 2];
930
- /**
931
- * Used to determine which breakpoints to use on full-width images
932
- */
933
652
  const VIEWPORT_BREAKPOINT_CUTOFF = 640;
934
- /**
935
- * Used to determine whether two aspect ratios are similar in value.
936
- */
937
653
  const ASPECT_RATIO_TOLERANCE = 0.1;
938
- /**
939
- * Used to determine whether the image has been requested at an overly
940
- * large size compared to the actual rendered image size (after taking
941
- * into account a typical device pixel ratio). In pixels.
942
- */
943
654
  const OVERSIZED_IMAGE_TOLERANCE = 1000;
944
- /**
945
- * Used to limit automatic srcset generation of very large sources for
946
- * fixed-size images. In pixels.
947
- */
948
655
  const FIXED_SRCSET_WIDTH_LIMIT = 1920;
949
656
  const FIXED_SRCSET_HEIGHT_LIMIT = 1080;
950
- /**
951
- * Placeholder dimension (height or width) limit in pixels. Angular produces a warning
952
- * when this limit is crossed.
953
- */
954
657
  const PLACEHOLDER_DIMENSION_LIMIT = 1000;
955
- /**
956
- * Used to warn or error when the user provides an overly large dataURL for the placeholder
957
- * attribute.
958
- * Character count of Base64 images is 1 character per byte, and base64 encoding is approximately
959
- * 33% larger than base images, so 4000 characters is around 3KB on disk and 10000 characters is
960
- * around 7.7KB. Experimentally, 4000 characters is about 20x20px in PNG or medium-quality JPEG
961
- * format, and 10,000 is around 50x50px, but there's quite a bit of variation depending on how the
962
- * image is saved.
963
- */
964
658
  const DATA_URL_WARN_LIMIT = 4000;
965
659
  const DATA_URL_ERROR_LIMIT = 10000;
966
- /** Info about built-in loaders we can test for. */
967
- const BUILT_IN_LOADERS = [
968
- imgixLoaderInfo,
969
- imageKitLoaderInfo,
970
- cloudinaryLoaderInfo,
971
- netlifyLoaderInfo,
972
- ];
973
- /**
974
- * Threshold for the PRIORITY_TRUE_COUNT
975
- */
660
+ const BUILT_IN_LOADERS = [imgixLoaderInfo, imageKitLoaderInfo, cloudinaryLoaderInfo, netlifyLoaderInfo];
976
661
  const PRIORITY_COUNT_THRESHOLD = 10;
977
- /**
978
- * This count is used to log a devMode warning
979
- * when the count of directive instances with priority=true
980
- * exceeds the threshold PRIORITY_COUNT_THRESHOLD
981
- */
982
662
  let IMGS_WITH_PRIORITY_ATTR_COUNT = 0;
983
- /**
984
- * Directive that improves image loading performance by enforcing best practices.
985
- *
986
- * `NgOptimizedImage` ensures that the loading of the Largest Contentful Paint (LCP) image is
987
- * prioritized by:
988
- * - Automatically setting the `fetchpriority` attribute on the `<img>` tag
989
- * - Lazy loading non-priority images by default
990
- * - Automatically generating a preconnect link tag in the document head
991
- *
992
- * In addition, the directive:
993
- * - Generates appropriate asset URLs if a corresponding `ImageLoader` function is provided
994
- * - Automatically generates a srcset
995
- * - Requires that `width` and `height` are set
996
- * - Warns if `width` or `height` have been set incorrectly
997
- * - Warns if the image will be visually distorted when rendered
998
- *
999
- * @usageNotes
1000
- * The `NgOptimizedImage` directive is marked as [standalone](guide/components/importing) and can
1001
- * be imported directly.
1002
- *
1003
- * Follow the steps below to enable and use the directive:
1004
- * 1. Import it into the necessary NgModule or a standalone Component.
1005
- * 2. Optionally provide an `ImageLoader` if you use an image hosting service.
1006
- * 3. Update the necessary `<img>` tags in templates and replace `src` attributes with `ngSrc`.
1007
- * Using a `ngSrc` allows the directive to control when the `src` gets set, which triggers an image
1008
- * download.
1009
- *
1010
- * Step 1: import the `NgOptimizedImage` directive.
1011
- *
1012
- * ```ts
1013
- * import { NgOptimizedImage } from '@angular/common';
1014
- *
1015
- * // Include it into the necessary NgModule
1016
- * @NgModule({
1017
- * imports: [NgOptimizedImage],
1018
- * })
1019
- * class AppModule {}
1020
- *
1021
- * // ... or a standalone Component
1022
- * @Component({
1023
- * imports: [NgOptimizedImage],
1024
- * })
1025
- * class MyStandaloneComponent {}
1026
- * ```
1027
- *
1028
- * Step 2: configure a loader.
1029
- *
1030
- * To use the **default loader**: no additional code changes are necessary. The URL returned by the
1031
- * generic loader will always match the value of "src". In other words, this loader applies no
1032
- * transformations to the resource URL and the value of the `ngSrc` attribute will be used as is.
1033
- *
1034
- * To use an existing loader for a **third-party image service**: add the provider factory for your
1035
- * chosen service to the `providers` array. In the example below, the Imgix loader is used:
1036
- *
1037
- * ```ts
1038
- * import {provideImgixLoader} from '@angular/common';
1039
- *
1040
- * // Call the function and add the result to the `providers` array:
1041
- * providers: [
1042
- * provideImgixLoader("https://my.base.url/"),
1043
- * ],
1044
- * ```
1045
- *
1046
- * The `NgOptimizedImage` directive provides the following functions:
1047
- * - `provideCloudflareLoader`
1048
- * - `provideCloudinaryLoader`
1049
- * - `provideImageKitLoader`
1050
- * - `provideImgixLoader`
1051
- *
1052
- * If you use a different image provider, you can create a custom loader function as described
1053
- * below.
1054
- *
1055
- * To use a **custom loader**: provide your loader function as a value for the `IMAGE_LOADER` DI
1056
- * token.
1057
- *
1058
- * ```ts
1059
- * import {IMAGE_LOADER, ImageLoaderConfig} from '@angular/common';
1060
- *
1061
- * // Configure the loader using the `IMAGE_LOADER` token.
1062
- * providers: [
1063
- * {
1064
- * provide: IMAGE_LOADER,
1065
- * useValue: (config: ImageLoaderConfig) => {
1066
- * return `https://example.com/${config.src}-${config.width}.jpg`;
1067
- * }
1068
- * },
1069
- * ],
1070
- * ```
1071
- *
1072
- * Step 3: update `<img>` tags in templates to use `ngSrc` instead of `src`.
1073
- *
1074
- * ```html
1075
- * <img ngSrc="logo.png" width="200" height="100">
1076
- * ```
1077
- *
1078
- * @publicApi
1079
- * @see [Image Optimization Guide](guide/image-optimization)
1080
- */
1081
663
  class NgOptimizedImage {
1082
- imageLoader = inject(IMAGE_LOADER);
1083
- config = processConfig(inject(_IMAGE_CONFIG));
1084
- renderer = inject(Renderer2);
1085
- imgElement = inject(ElementRef).nativeElement;
1086
- injector = inject(Injector);
1087
- // An LCP image observer should be injected only in development mode.
1088
- // Do not assign it to `null` to avoid having a redundant property in the production bundle.
1089
- lcpObserver;
1090
- /**
1091
- * Calculate the rewritten `src` once and store it.
1092
- * This is needed to avoid repetitive calculations and make sure the directive cleanup in the
1093
- * `ngOnDestroy` does not rely on the `IMAGE_LOADER` logic (which in turn can rely on some other
1094
- * instance that might be already destroyed).
1095
- */
1096
- _renderedSrc = null;
1097
- /**
1098
- * Name of the source image.
1099
- * Image name will be processed by the image loader and the final URL will be applied as the `src`
1100
- * property of the image.
1101
- */
1102
- ngSrc;
1103
- /**
1104
- * A comma separated list of width or density descriptors.
1105
- * The image name will be taken from `ngSrc` and combined with the list of width or density
1106
- * descriptors to generate the final `srcset` property of the image.
1107
- *
1108
- * Example:
1109
- * ```html
1110
- * <img ngSrc="hello.jpg" ngSrcset="100w, 200w" /> =>
1111
- * <img src="path/hello.jpg" srcset="path/hello.jpg?w=100 100w, path/hello.jpg?w=200 200w" />
1112
- * ```
1113
- */
1114
- ngSrcset;
1115
- /**
1116
- * The base `sizes` attribute passed through to the `<img>` element.
1117
- * Providing sizes causes the image to create an automatic responsive srcset.
1118
- */
1119
- sizes;
1120
- /**
1121
- * For responsive images: the intrinsic width of the image in pixels.
1122
- * For fixed size images: the desired rendered width of the image in pixels.
1123
- */
1124
- width;
1125
- /**
1126
- * For responsive images: the intrinsic height of the image in pixels.
1127
- * For fixed size images: the desired rendered height of the image in pixels.
1128
- */
1129
- height;
1130
- /**
1131
- * The desired decoding behavior for the image. Defaults to `auto`
1132
- * if not explicitly set, matching native browser behavior.
1133
- *
1134
- * Use `async` to decode the image off the main thread (non-blocking),
1135
- * `sync` for immediate decoding (blocking), or `auto` to let the
1136
- * browser decide the optimal strategy.
1137
- *
1138
- * [Spec](https://html.spec.whatwg.org/multipage/images.html#image-decoding-hint)
1139
- */
1140
- decoding;
1141
- /**
1142
- * The desired loading behavior (lazy, eager, or auto). Defaults to `lazy`,
1143
- * which is recommended for most images.
1144
- *
1145
- * Warning: Setting images as loading="eager" or loading="auto" marks them
1146
- * as non-priority images and can hurt loading performance. For images which
1147
- * may be the LCP element, use the `priority` attribute instead of `loading`.
1148
- */
1149
- loading;
1150
- /**
1151
- * Indicates whether this image should have a high priority.
1152
- */
1153
- priority = false;
1154
- /**
1155
- * Data to pass through to custom loaders.
1156
- */
1157
- loaderParams;
1158
- /**
1159
- * Disables automatic srcset generation for this image.
1160
- */
1161
- disableOptimizedSrcset = false;
1162
- /**
1163
- * Sets the image to "fill mode", which eliminates the height/width requirement and adds
1164
- * styles such that the image fills its containing element.
1165
- */
1166
- fill = false;
1167
- /**
1168
- * A URL or data URL for an image to be used as a placeholder while this image loads.
1169
- */
1170
- placeholder;
1171
- /**
1172
- * Configuration object for placeholder settings. Options:
1173
- * * blur: Setting this to false disables the automatic CSS blur.
1174
- */
1175
- placeholderConfig;
1176
- /**
1177
- * Value of the `src` attribute if set on the host `<img>` element.
1178
- * This input is exclusively read to assert that `src` is not set in conflict
1179
- * with `ngSrc` and that images don't start to load until a lazy loading strategy is set.
1180
- * @internal
1181
- */
1182
- src;
1183
- /**
1184
- * Value of the `srcset` attribute if set on the host `<img>` element.
1185
- * This input is exclusively read to assert that `srcset` is not set in conflict
1186
- * with `ngSrcset` and that images don't start to load until a lazy loading strategy is set.
1187
- * @internal
1188
- */
1189
- srcset;
1190
- constructor() {
1191
- if (ngDevMode) {
1192
- this.lcpObserver = this.injector.get(LCPImageObserver);
1193
- // Using `DestroyRef` to avoid having an empty `ngOnDestroy` method since this
1194
- // is only run in development mode.
1195
- const destroyRef = inject(DestroyRef);
1196
- destroyRef.onDestroy(() => {
1197
- if (!this.priority && this._renderedSrc !== null) {
1198
- this.lcpObserver.unregisterImage(this._renderedSrc);
1199
- }
1200
- });
1201
- }
1202
- }
1203
- /** @docs-private */
1204
- ngOnInit() {
1205
- _performanceMarkFeature('NgOptimizedImage');
1206
- if (ngDevMode) {
1207
- const ngZone = this.injector.get(NgZone);
1208
- assertNonEmptyInput(this, 'ngSrc', this.ngSrc);
1209
- assertValidNgSrcset(this, this.ngSrcset);
1210
- assertNoConflictingSrc(this);
1211
- if (this.ngSrcset) {
1212
- assertNoConflictingSrcset(this);
1213
- }
1214
- assertNotBase64Image(this);
1215
- assertNotBlobUrl(this);
1216
- if (this.fill) {
1217
- assertEmptyWidthAndHeight(this);
1218
- // This leaves the Angular zone to avoid triggering unnecessary change detection cycles when
1219
- // `load` tasks are invoked on images.
1220
- ngZone.runOutsideAngular(() => assertNonZeroRenderedHeight(this, this.imgElement, this.renderer));
1221
- }
1222
- else {
1223
- assertNonEmptyWidthAndHeight(this);
1224
- if (this.height !== undefined) {
1225
- assertGreaterThanZero(this, this.height, 'height');
1226
- }
1227
- if (this.width !== undefined) {
1228
- assertGreaterThanZero(this, this.width, 'width');
1229
- }
1230
- // Only check for distorted images when not in fill mode, where
1231
- // images may be intentionally stretched, cropped or letterboxed.
1232
- ngZone.runOutsideAngular(() => assertNoImageDistortion(this, this.imgElement, this.renderer));
1233
- }
1234
- assertValidLoadingInput(this);
1235
- assertValidDecodingInput(this);
1236
- if (!this.ngSrcset) {
1237
- assertNoComplexSizes(this);
1238
- }
1239
- assertValidPlaceholder(this, this.imageLoader);
1240
- assertNotMissingBuiltInLoader(this.ngSrc, this.imageLoader);
1241
- assertNoNgSrcsetWithoutLoader(this, this.imageLoader);
1242
- assertNoLoaderParamsWithoutLoader(this, this.imageLoader);
1243
- ngZone.runOutsideAngular(() => {
1244
- this.lcpObserver.registerImage(this.getRewrittenSrc(), this.ngSrc, this.priority);
1245
- });
1246
- if (this.priority) {
1247
- const checker = this.injector.get(PreconnectLinkChecker);
1248
- checker.assertPreconnect(this.getRewrittenSrc(), this.ngSrc);
1249
- if (typeof ngServerMode !== 'undefined' && !ngServerMode) {
1250
- const applicationRef = this.injector.get(ApplicationRef);
1251
- assetPriorityCountBelowThreshold(applicationRef);
1252
- }
1253
- }
664
+ imageLoader = inject(IMAGE_LOADER);
665
+ config = processConfig(inject(_IMAGE_CONFIG));
666
+ renderer = inject(Renderer2);
667
+ imgElement = inject(ElementRef).nativeElement;
668
+ injector = inject(Injector);
669
+ lcpObserver;
670
+ _renderedSrc = null;
671
+ ngSrc;
672
+ ngSrcset;
673
+ sizes;
674
+ width;
675
+ height;
676
+ decoding;
677
+ loading;
678
+ priority = false;
679
+ loaderParams;
680
+ disableOptimizedSrcset = false;
681
+ fill = false;
682
+ placeholder;
683
+ placeholderConfig;
684
+ src;
685
+ srcset;
686
+ constructor() {
687
+ if (ngDevMode) {
688
+ this.lcpObserver = this.injector.get(LCPImageObserver);
689
+ const destroyRef = inject(DestroyRef);
690
+ destroyRef.onDestroy(() => {
691
+ if (!this.priority && this._renderedSrc !== null) {
692
+ this.lcpObserver.unregisterImage(this._renderedSrc);
1254
693
  }
1255
- if (this.placeholder) {
1256
- this.removePlaceholderOnLoad(this.imgElement);
1257
- }
1258
- this.setHostAttributes();
1259
- }
1260
- setHostAttributes() {
1261
- // Must set width/height explicitly in case they are bound (in which case they will
1262
- // only be reflected and not found by the browser)
1263
- if (this.fill) {
1264
- this.sizes ||= '100vw';
694
+ });
695
+ }
696
+ }
697
+ ngOnInit() {
698
+ _performanceMarkFeature('NgOptimizedImage');
699
+ if (ngDevMode) {
700
+ const ngZone = this.injector.get(NgZone);
701
+ assertNonEmptyInput(this, 'ngSrc', this.ngSrc);
702
+ assertValidNgSrcset(this, this.ngSrcset);
703
+ assertNoConflictingSrc(this);
704
+ if (this.ngSrcset) {
705
+ assertNoConflictingSrcset(this);
706
+ }
707
+ assertNotBase64Image(this);
708
+ assertNotBlobUrl(this);
709
+ if (this.fill) {
710
+ assertEmptyWidthAndHeight(this);
711
+ ngZone.runOutsideAngular(() => assertNonZeroRenderedHeight(this, this.imgElement, this.renderer));
712
+ } else {
713
+ assertNonEmptyWidthAndHeight(this);
714
+ if (this.height !== undefined) {
715
+ assertGreaterThanZero(this, this.height, 'height');
1265
716
  }
1266
- else {
1267
- this.setHostAttribute('width', this.width.toString());
1268
- this.setHostAttribute('height', this.height.toString());
717
+ if (this.width !== undefined) {
718
+ assertGreaterThanZero(this, this.width, 'width');
1269
719
  }
1270
- this.setHostAttribute('loading', this.getLoadingBehavior());
1271
- this.setHostAttribute('fetchpriority', this.getFetchPriority());
1272
- this.setHostAttribute('decoding', this.getDecoding());
1273
- // The `data-ng-img` attribute flags an image as using the directive, to allow
1274
- // for analysis of the directive's performance.
1275
- this.setHostAttribute('ng-img', 'true');
1276
- // The `src` and `srcset` attributes should be set last since other attributes
1277
- // could affect the image's loading behavior.
1278
- const rewrittenSrcset = this.updateSrcAndSrcset();
1279
- if (this.sizes) {
1280
- if (this.getLoadingBehavior() === 'lazy') {
1281
- this.setHostAttribute('sizes', 'auto, ' + this.sizes);
1282
- }
1283
- else {
1284
- this.setHostAttribute('sizes', this.sizes);
1285
- }
720
+ ngZone.runOutsideAngular(() => assertNoImageDistortion(this, this.imgElement, this.renderer));
721
+ }
722
+ assertValidLoadingInput(this);
723
+ assertValidDecodingInput(this);
724
+ if (!this.ngSrcset) {
725
+ assertNoComplexSizes(this);
726
+ }
727
+ assertValidPlaceholder(this, this.imageLoader);
728
+ assertNotMissingBuiltInLoader(this.ngSrc, this.imageLoader);
729
+ assertNoNgSrcsetWithoutLoader(this, this.imageLoader);
730
+ assertNoLoaderParamsWithoutLoader(this, this.imageLoader);
731
+ ngZone.runOutsideAngular(() => {
732
+ this.lcpObserver.registerImage(this.getRewrittenSrc(), this.ngSrc, this.priority);
733
+ });
734
+ if (this.priority) {
735
+ const checker = this.injector.get(PreconnectLinkChecker);
736
+ checker.assertPreconnect(this.getRewrittenSrc(), this.ngSrc);
737
+ if (typeof ngServerMode !== 'undefined' && !ngServerMode) {
738
+ const applicationRef = this.injector.get(ApplicationRef);
739
+ assetPriorityCountBelowThreshold(applicationRef);
1286
740
  }
1287
- else {
1288
- if (this.ngSrcset &&
1289
- VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.ngSrcset) &&
1290
- this.getLoadingBehavior() === 'lazy') {
1291
- this.setHostAttribute('sizes', 'auto, 100vw');
1292
- }
741
+ }
742
+ }
743
+ if (this.placeholder) {
744
+ this.removePlaceholderOnLoad(this.imgElement);
745
+ }
746
+ this.setHostAttributes();
747
+ }
748
+ setHostAttributes() {
749
+ if (this.fill) {
750
+ this.sizes ||= '100vw';
751
+ } else {
752
+ this.setHostAttribute('width', this.width.toString());
753
+ this.setHostAttribute('height', this.height.toString());
754
+ }
755
+ this.setHostAttribute('loading', this.getLoadingBehavior());
756
+ this.setHostAttribute('fetchpriority', this.getFetchPriority());
757
+ this.setHostAttribute('decoding', this.getDecoding());
758
+ this.setHostAttribute('ng-img', 'true');
759
+ const rewrittenSrcset = this.updateSrcAndSrcset();
760
+ if (this.sizes) {
761
+ if (this.getLoadingBehavior() === 'lazy') {
762
+ this.setHostAttribute('sizes', 'auto, ' + this.sizes);
763
+ } else {
764
+ this.setHostAttribute('sizes', this.sizes);
765
+ }
766
+ } else {
767
+ if (this.ngSrcset && VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.ngSrcset) && this.getLoadingBehavior() === 'lazy') {
768
+ this.setHostAttribute('sizes', 'auto, 100vw');
769
+ }
770
+ }
771
+ if (typeof ngServerMode !== 'undefined' && ngServerMode && this.priority) {
772
+ const preloadLinkCreator = this.injector.get(PreloadLinkCreator);
773
+ preloadLinkCreator.createPreloadLinkTag(this.renderer, this.getRewrittenSrc(), rewrittenSrcset, this.sizes);
774
+ }
775
+ }
776
+ ngOnChanges(changes) {
777
+ if (ngDevMode) {
778
+ assertNoPostInitInputChange(this, changes, ['ngSrcset', 'width', 'height', 'priority', 'fill', 'loading', 'sizes', 'loaderParams', 'disableOptimizedSrcset']);
779
+ }
780
+ if (changes['ngSrc'] && !changes['ngSrc'].isFirstChange()) {
781
+ const oldSrc = this._renderedSrc;
782
+ this.updateSrcAndSrcset(true);
783
+ if (ngDevMode) {
784
+ const newSrc = this._renderedSrc;
785
+ if (oldSrc && newSrc && oldSrc !== newSrc) {
786
+ const ngZone = this.injector.get(NgZone);
787
+ ngZone.runOutsideAngular(() => {
788
+ this.lcpObserver.updateImage(oldSrc, newSrc);
789
+ });
1293
790
  }
1294
- if (typeof ngServerMode !== 'undefined' && ngServerMode && this.priority) {
1295
- const preloadLinkCreator = this.injector.get(PreloadLinkCreator);
1296
- preloadLinkCreator.createPreloadLinkTag(this.renderer, this.getRewrittenSrc(), rewrittenSrcset, this.sizes);
1297
- }
1298
- }
1299
- /** @docs-private */
1300
- ngOnChanges(changes) {
1301
- if (ngDevMode) {
1302
- assertNoPostInitInputChange(this, changes, [
1303
- 'ngSrcset',
1304
- 'width',
1305
- 'height',
1306
- 'priority',
1307
- 'fill',
1308
- 'loading',
1309
- 'sizes',
1310
- 'loaderParams',
1311
- 'disableOptimizedSrcset',
1312
- ]);
1313
- }
1314
- if (changes['ngSrc'] && !changes['ngSrc'].isFirstChange()) {
1315
- const oldSrc = this._renderedSrc;
1316
- this.updateSrcAndSrcset(true);
1317
- if (ngDevMode) {
1318
- const newSrc = this._renderedSrc;
1319
- if (oldSrc && newSrc && oldSrc !== newSrc) {
1320
- const ngZone = this.injector.get(NgZone);
1321
- ngZone.runOutsideAngular(() => {
1322
- this.lcpObserver.updateImage(oldSrc, newSrc);
1323
- });
1324
- }
1325
- }
1326
- }
1327
- if (ngDevMode &&
1328
- changes['placeholder']?.currentValue &&
1329
- typeof ngServerMode !== 'undefined' &&
1330
- !ngServerMode) {
1331
- assertPlaceholderDimensions(this, this.imgElement);
1332
- }
1333
- }
1334
- callImageLoader(configWithoutCustomParams) {
1335
- let augmentedConfig = configWithoutCustomParams;
1336
- if (this.loaderParams) {
1337
- augmentedConfig.loaderParams = this.loaderParams;
1338
- }
1339
- return this.imageLoader(augmentedConfig);
1340
- }
1341
- getLoadingBehavior() {
1342
- if (!this.priority && this.loading !== undefined) {
1343
- return this.loading;
1344
- }
1345
- return this.priority ? 'eager' : 'lazy';
1346
- }
1347
- getFetchPriority() {
1348
- return this.priority ? 'high' : 'auto';
1349
- }
1350
- getDecoding() {
1351
- if (this.priority) {
1352
- // `sync` means the image is decoded immediately when it's loaded,
1353
- // reducing the risk of content shifting later (important for LCP).
1354
- // If we're marking an image as priority, we want it decoded and
1355
- // painted as early as possible.
1356
- return 'sync';
1357
- }
1358
- // Returns the value of the `decoding` attribute, defaulting to `auto`
1359
- // if not explicitly provided. This mimics native browser behavior and
1360
- // avoids breaking changes when no decoding strategy is specified.
1361
- return this.decoding ?? 'auto';
1362
- }
1363
- getRewrittenSrc() {
1364
- // ImageLoaderConfig supports setting a width property. However, we're not setting width here
1365
- // because if the developer uses rendered width instead of intrinsic width in the HTML width
1366
- // attribute, the image requested may be too small for 2x+ screens.
1367
- if (!this._renderedSrc) {
1368
- const imgConfig = { src: this.ngSrc };
1369
- // Cache calculated image src to reuse it later in the code.
1370
- this._renderedSrc = this.callImageLoader(imgConfig);
1371
- }
1372
- return this._renderedSrc;
1373
- }
1374
- getRewrittenSrcset() {
1375
- const widthSrcSet = VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.ngSrcset);
1376
- const finalSrcs = this.ngSrcset
1377
- .split(',')
1378
- .filter((src) => src !== '')
1379
- .map((srcStr) => {
1380
- srcStr = srcStr.trim();
1381
- const width = widthSrcSet ? parseFloat(srcStr) : parseFloat(srcStr) * this.width;
1382
- return `${this.callImageLoader({ src: this.ngSrc, width })} ${srcStr}`;
1383
- });
1384
- return finalSrcs.join(', ');
1385
- }
1386
- getAutomaticSrcset() {
1387
- if (this.sizes) {
1388
- return this.getResponsiveSrcset();
1389
- }
1390
- else {
1391
- return this.getFixedSrcset();
1392
- }
1393
- }
1394
- getResponsiveSrcset() {
1395
- const { breakpoints } = this.config;
1396
- let filteredBreakpoints = breakpoints;
1397
- if (this.sizes?.trim() === '100vw') {
1398
- // Since this is a full-screen-width image, our srcset only needs to include
1399
- // breakpoints with full viewport widths.
1400
- filteredBreakpoints = breakpoints.filter((bp) => bp >= VIEWPORT_BREAKPOINT_CUTOFF);
1401
- }
1402
- const finalSrcs = filteredBreakpoints.map((bp) => `${this.callImageLoader({ src: this.ngSrc, width: bp })} ${bp}w`);
1403
- return finalSrcs.join(', ');
1404
- }
1405
- updateSrcAndSrcset(forceSrcRecalc = false) {
1406
- if (forceSrcRecalc) {
1407
- // Reset cached value, so that the followup `getRewrittenSrc()` call
1408
- // will recalculate it and update the cache.
1409
- this._renderedSrc = null;
1410
- }
1411
- const rewrittenSrc = this.getRewrittenSrc();
1412
- this.setHostAttribute('src', rewrittenSrc);
1413
- let rewrittenSrcset = undefined;
1414
- if (this.ngSrcset) {
1415
- rewrittenSrcset = this.getRewrittenSrcset();
1416
- }
1417
- else if (this.shouldGenerateAutomaticSrcset()) {
1418
- rewrittenSrcset = this.getAutomaticSrcset();
1419
- }
1420
- if (rewrittenSrcset) {
1421
- this.setHostAttribute('srcset', rewrittenSrcset);
1422
- }
1423
- return rewrittenSrcset;
1424
- }
1425
- getFixedSrcset() {
1426
- const finalSrcs = DENSITY_SRCSET_MULTIPLIERS.map((multiplier) => `${this.callImageLoader({
1427
- src: this.ngSrc,
1428
- width: this.width * multiplier,
1429
- })} ${multiplier}x`);
1430
- return finalSrcs.join(', ');
1431
- }
1432
- shouldGenerateAutomaticSrcset() {
1433
- let oversizedImage = false;
1434
- if (!this.sizes) {
1435
- oversizedImage =
1436
- this.width > FIXED_SRCSET_WIDTH_LIMIT || this.height > FIXED_SRCSET_HEIGHT_LIMIT;
1437
- }
1438
- return (!this.disableOptimizedSrcset &&
1439
- !this.srcset &&
1440
- this.imageLoader !== noopImageLoader &&
1441
- !oversizedImage);
1442
- }
1443
- /**
1444
- * Returns an image url formatted for use with the CSS background-image property. Expects one of:
1445
- * * A base64 encoded image, which is wrapped and passed through.
1446
- * * A boolean. If true, calls the image loader to generate a small placeholder url.
1447
- */
1448
- generatePlaceholder(placeholderInput) {
1449
- const { placeholderResolution } = this.config;
1450
- if (placeholderInput === true) {
1451
- return `url(${this.callImageLoader({
1452
- src: this.ngSrc,
1453
- width: placeholderResolution,
1454
- isPlaceholder: true,
1455
- })})`;
1456
- }
1457
- else if (typeof placeholderInput === 'string') {
1458
- return `url(${placeholderInput})`;
1459
- }
1460
- return null;
1461
- }
1462
- /**
1463
- * Determines if blur should be applied, based on an optional boolean
1464
- * property `blur` within the optional configuration object `placeholderConfig`.
1465
- */
1466
- shouldBlurPlaceholder(placeholderConfig) {
1467
- if (!placeholderConfig || !placeholderConfig.hasOwnProperty('blur')) {
1468
- return true;
1469
- }
1470
- return Boolean(placeholderConfig.blur);
1471
- }
1472
- removePlaceholderOnLoad(img) {
1473
- const callback = () => {
1474
- const changeDetectorRef = this.injector.get(ChangeDetectorRef);
1475
- removeLoadListenerFn();
1476
- removeErrorListenerFn();
1477
- this.placeholder = false;
1478
- changeDetectorRef.markForCheck();
1479
- };
1480
- const removeLoadListenerFn = this.renderer.listen(img, 'load', callback);
1481
- const removeErrorListenerFn = this.renderer.listen(img, 'error', callback);
1482
- callOnLoadIfImageIsLoaded(img, callback);
1483
- }
1484
- setHostAttribute(name, value) {
1485
- this.renderer.setAttribute(this.imgElement, name, value);
791
+ }
792
+ }
793
+ if (ngDevMode && changes['placeholder']?.currentValue && typeof ngServerMode !== 'undefined' && !ngServerMode) {
794
+ assertPlaceholderDimensions(this, this.imgElement);
795
+ }
796
+ }
797
+ callImageLoader(configWithoutCustomParams) {
798
+ let augmentedConfig = configWithoutCustomParams;
799
+ if (this.loaderParams) {
800
+ augmentedConfig.loaderParams = this.loaderParams;
801
+ }
802
+ return this.imageLoader(augmentedConfig);
803
+ }
804
+ getLoadingBehavior() {
805
+ if (!this.priority && this.loading !== undefined) {
806
+ return this.loading;
807
+ }
808
+ return this.priority ? 'eager' : 'lazy';
809
+ }
810
+ getFetchPriority() {
811
+ return this.priority ? 'high' : 'auto';
812
+ }
813
+ getDecoding() {
814
+ if (this.priority) {
815
+ return 'sync';
816
+ }
817
+ return this.decoding ?? 'auto';
818
+ }
819
+ getRewrittenSrc() {
820
+ if (!this._renderedSrc) {
821
+ const imgConfig = {
822
+ src: this.ngSrc
823
+ };
824
+ this._renderedSrc = this.callImageLoader(imgConfig);
825
+ }
826
+ return this._renderedSrc;
827
+ }
828
+ getRewrittenSrcset() {
829
+ const widthSrcSet = VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.ngSrcset);
830
+ const finalSrcs = this.ngSrcset.split(',').filter(src => src !== '').map(srcStr => {
831
+ srcStr = srcStr.trim();
832
+ const width = widthSrcSet ? parseFloat(srcStr) : parseFloat(srcStr) * this.width;
833
+ return `${this.callImageLoader({
834
+ src: this.ngSrc,
835
+ width
836
+ })} ${srcStr}`;
837
+ });
838
+ return finalSrcs.join(', ');
839
+ }
840
+ getAutomaticSrcset() {
841
+ if (this.sizes) {
842
+ return this.getResponsiveSrcset();
843
+ } else {
844
+ return this.getFixedSrcset();
845
+ }
846
+ }
847
+ getResponsiveSrcset() {
848
+ const {
849
+ breakpoints
850
+ } = this.config;
851
+ let filteredBreakpoints = breakpoints;
852
+ if (this.sizes?.trim() === '100vw') {
853
+ filteredBreakpoints = breakpoints.filter(bp => bp >= VIEWPORT_BREAKPOINT_CUTOFF);
854
+ }
855
+ const finalSrcs = filteredBreakpoints.map(bp => `${this.callImageLoader({
856
+ src: this.ngSrc,
857
+ width: bp
858
+ })} ${bp}w`);
859
+ return finalSrcs.join(', ');
860
+ }
861
+ updateSrcAndSrcset(forceSrcRecalc = false) {
862
+ if (forceSrcRecalc) {
863
+ this._renderedSrc = null;
864
+ }
865
+ const rewrittenSrc = this.getRewrittenSrc();
866
+ this.setHostAttribute('src', rewrittenSrc);
867
+ let rewrittenSrcset = undefined;
868
+ if (this.ngSrcset) {
869
+ rewrittenSrcset = this.getRewrittenSrcset();
870
+ } else if (this.shouldGenerateAutomaticSrcset()) {
871
+ rewrittenSrcset = this.getAutomaticSrcset();
872
+ }
873
+ if (rewrittenSrcset) {
874
+ this.setHostAttribute('srcset', rewrittenSrcset);
875
+ }
876
+ return rewrittenSrcset;
877
+ }
878
+ getFixedSrcset() {
879
+ const finalSrcs = DENSITY_SRCSET_MULTIPLIERS.map(multiplier => `${this.callImageLoader({
880
+ src: this.ngSrc,
881
+ width: this.width * multiplier
882
+ })} ${multiplier}x`);
883
+ return finalSrcs.join(', ');
884
+ }
885
+ shouldGenerateAutomaticSrcset() {
886
+ let oversizedImage = false;
887
+ if (!this.sizes) {
888
+ oversizedImage = this.width > FIXED_SRCSET_WIDTH_LIMIT || this.height > FIXED_SRCSET_HEIGHT_LIMIT;
889
+ }
890
+ return !this.disableOptimizedSrcset && !this.srcset && this.imageLoader !== noopImageLoader && !oversizedImage;
891
+ }
892
+ generatePlaceholder(placeholderInput) {
893
+ const {
894
+ placeholderResolution
895
+ } = this.config;
896
+ if (placeholderInput === true) {
897
+ return `url(${this.callImageLoader({
898
+ src: this.ngSrc,
899
+ width: placeholderResolution,
900
+ isPlaceholder: true
901
+ })})`;
902
+ } else if (typeof placeholderInput === 'string') {
903
+ return `url(${placeholderInput})`;
1486
904
  }
1487
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.0.0-next.9", ngImport: i0, type: NgOptimizedImage, deps: [], target: i0.ɵɵFactoryTarget.Directive });
1488
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "16.1.0", version: "21.0.0-next.9", type: NgOptimizedImage, isStandalone: true, selector: "img[ngSrc]", inputs: { ngSrc: ["ngSrc", "ngSrc", unwrapSafeUrl], ngSrcset: "ngSrcset", sizes: "sizes", width: ["width", "width", numberAttribute], height: ["height", "height", numberAttribute], decoding: "decoding", loading: "loading", priority: ["priority", "priority", booleanAttribute], loaderParams: "loaderParams", disableOptimizedSrcset: ["disableOptimizedSrcset", "disableOptimizedSrcset", booleanAttribute], fill: ["fill", "fill", booleanAttribute], placeholder: ["placeholder", "placeholder", booleanOrUrlAttribute], placeholderConfig: "placeholderConfig", src: "src", srcset: "srcset" }, host: { properties: { "style.position": "fill ? \"absolute\" : null", "style.width": "fill ? \"100%\" : null", "style.height": "fill ? \"100%\" : null", "style.inset": "fill ? \"0\" : null", "style.background-size": "placeholder ? \"cover\" : null", "style.background-position": "placeholder ? \"50% 50%\" : null", "style.background-repeat": "placeholder ? \"no-repeat\" : null", "style.background-image": "placeholder ? generatePlaceholder(placeholder) : null", "style.filter": "placeholder && shouldBlurPlaceholder(placeholderConfig) ? \"blur(15px)\" : null" } }, usesOnChanges: true, ngImport: i0 });
1489
- }
1490
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.0-next.9", ngImport: i0, type: NgOptimizedImage, decorators: [{
1491
- type: Directive,
1492
- args: [{
1493
- selector: 'img[ngSrc]',
1494
- host: {
1495
- '[style.position]': 'fill ? "absolute" : null',
1496
- '[style.width]': 'fill ? "100%" : null',
1497
- '[style.height]': 'fill ? "100%" : null',
1498
- '[style.inset]': 'fill ? "0" : null',
1499
- '[style.background-size]': 'placeholder ? "cover" : null',
1500
- '[style.background-position]': 'placeholder ? "50% 50%" : null',
1501
- '[style.background-repeat]': 'placeholder ? "no-repeat" : null',
1502
- '[style.background-image]': 'placeholder ? generatePlaceholder(placeholder) : null',
1503
- '[style.filter]': 'placeholder && shouldBlurPlaceholder(placeholderConfig) ? "blur(15px)" : null',
1504
- },
1505
- }]
1506
- }], ctorParameters: () => [], propDecorators: { ngSrc: [{
1507
- type: Input,
1508
- args: [{ required: true, transform: unwrapSafeUrl }]
1509
- }], ngSrcset: [{
1510
- type: Input
1511
- }], sizes: [{
1512
- type: Input
1513
- }], width: [{
1514
- type: Input,
1515
- args: [{ transform: numberAttribute }]
1516
- }], height: [{
1517
- type: Input,
1518
- args: [{ transform: numberAttribute }]
1519
- }], decoding: [{
1520
- type: Input
1521
- }], loading: [{
1522
- type: Input
1523
- }], priority: [{
1524
- type: Input,
1525
- args: [{ transform: booleanAttribute }]
1526
- }], loaderParams: [{
1527
- type: Input
1528
- }], disableOptimizedSrcset: [{
1529
- type: Input,
1530
- args: [{ transform: booleanAttribute }]
1531
- }], fill: [{
1532
- type: Input,
1533
- args: [{ transform: booleanAttribute }]
1534
- }], placeholder: [{
1535
- type: Input,
1536
- args: [{ transform: booleanOrUrlAttribute }]
1537
- }], placeholderConfig: [{
1538
- type: Input
1539
- }], src: [{
1540
- type: Input
1541
- }], srcset: [{
1542
- type: Input
1543
- }] } });
1544
- /***** Helpers *****/
1545
- /**
1546
- * Sorts provided config breakpoints and uses defaults.
1547
- */
905
+ return null;
906
+ }
907
+ shouldBlurPlaceholder(placeholderConfig) {
908
+ if (!placeholderConfig || !placeholderConfig.hasOwnProperty('blur')) {
909
+ return true;
910
+ }
911
+ return Boolean(placeholderConfig.blur);
912
+ }
913
+ removePlaceholderOnLoad(img) {
914
+ const callback = () => {
915
+ const changeDetectorRef = this.injector.get(ChangeDetectorRef);
916
+ removeLoadListenerFn();
917
+ removeErrorListenerFn();
918
+ this.placeholder = false;
919
+ changeDetectorRef.markForCheck();
920
+ };
921
+ const removeLoadListenerFn = this.renderer.listen(img, 'load', callback);
922
+ const removeErrorListenerFn = this.renderer.listen(img, 'error', callback);
923
+ callOnLoadIfImageIsLoaded(img, callback);
924
+ }
925
+ setHostAttribute(name, value) {
926
+ this.renderer.setAttribute(this.imgElement, name, value);
927
+ }
928
+ static ɵfac = i0.ɵɵngDeclareFactory({
929
+ minVersion: "12.0.0",
930
+ version: "21.0.0-rc.1",
931
+ ngImport: i0,
932
+ type: NgOptimizedImage,
933
+ deps: [],
934
+ target: i0.ɵɵFactoryTarget.Directive
935
+ });
936
+ static ɵdir = i0.ɵɵngDeclareDirective({
937
+ minVersion: "16.1.0",
938
+ version: "21.0.0-rc.1",
939
+ type: NgOptimizedImage,
940
+ isStandalone: true,
941
+ selector: "img[ngSrc]",
942
+ inputs: {
943
+ ngSrc: ["ngSrc", "ngSrc", unwrapSafeUrl],
944
+ ngSrcset: "ngSrcset",
945
+ sizes: "sizes",
946
+ width: ["width", "width", numberAttribute],
947
+ height: ["height", "height", numberAttribute],
948
+ decoding: "decoding",
949
+ loading: "loading",
950
+ priority: ["priority", "priority", booleanAttribute],
951
+ loaderParams: "loaderParams",
952
+ disableOptimizedSrcset: ["disableOptimizedSrcset", "disableOptimizedSrcset", booleanAttribute],
953
+ fill: ["fill", "fill", booleanAttribute],
954
+ placeholder: ["placeholder", "placeholder", booleanOrUrlAttribute],
955
+ placeholderConfig: "placeholderConfig",
956
+ src: "src",
957
+ srcset: "srcset"
958
+ },
959
+ host: {
960
+ properties: {
961
+ "style.position": "fill ? \"absolute\" : null",
962
+ "style.width": "fill ? \"100%\" : null",
963
+ "style.height": "fill ? \"100%\" : null",
964
+ "style.inset": "fill ? \"0\" : null",
965
+ "style.background-size": "placeholder ? \"cover\" : null",
966
+ "style.background-position": "placeholder ? \"50% 50%\" : null",
967
+ "style.background-repeat": "placeholder ? \"no-repeat\" : null",
968
+ "style.background-image": "placeholder ? generatePlaceholder(placeholder) : null",
969
+ "style.filter": "placeholder && shouldBlurPlaceholder(placeholderConfig) ? \"blur(15px)\" : null"
970
+ }
971
+ },
972
+ usesOnChanges: true,
973
+ ngImport: i0
974
+ });
975
+ }
976
+ i0.ɵɵngDeclareClassMetadata({
977
+ minVersion: "12.0.0",
978
+ version: "21.0.0-rc.1",
979
+ ngImport: i0,
980
+ type: NgOptimizedImage,
981
+ decorators: [{
982
+ type: Directive,
983
+ args: [{
984
+ selector: 'img[ngSrc]',
985
+ host: {
986
+ '[style.position]': 'fill ? "absolute" : null',
987
+ '[style.width]': 'fill ? "100%" : null',
988
+ '[style.height]': 'fill ? "100%" : null',
989
+ '[style.inset]': 'fill ? "0" : null',
990
+ '[style.background-size]': 'placeholder ? "cover" : null',
991
+ '[style.background-position]': 'placeholder ? "50% 50%" : null',
992
+ '[style.background-repeat]': 'placeholder ? "no-repeat" : null',
993
+ '[style.background-image]': 'placeholder ? generatePlaceholder(placeholder) : null',
994
+ '[style.filter]': 'placeholder && shouldBlurPlaceholder(placeholderConfig) ? "blur(15px)" : null'
995
+ }
996
+ }]
997
+ }],
998
+ ctorParameters: () => [],
999
+ propDecorators: {
1000
+ ngSrc: [{
1001
+ type: Input,
1002
+ args: [{
1003
+ required: true,
1004
+ transform: unwrapSafeUrl
1005
+ }]
1006
+ }],
1007
+ ngSrcset: [{
1008
+ type: Input
1009
+ }],
1010
+ sizes: [{
1011
+ type: Input
1012
+ }],
1013
+ width: [{
1014
+ type: Input,
1015
+ args: [{
1016
+ transform: numberAttribute
1017
+ }]
1018
+ }],
1019
+ height: [{
1020
+ type: Input,
1021
+ args: [{
1022
+ transform: numberAttribute
1023
+ }]
1024
+ }],
1025
+ decoding: [{
1026
+ type: Input
1027
+ }],
1028
+ loading: [{
1029
+ type: Input
1030
+ }],
1031
+ priority: [{
1032
+ type: Input,
1033
+ args: [{
1034
+ transform: booleanAttribute
1035
+ }]
1036
+ }],
1037
+ loaderParams: [{
1038
+ type: Input
1039
+ }],
1040
+ disableOptimizedSrcset: [{
1041
+ type: Input,
1042
+ args: [{
1043
+ transform: booleanAttribute
1044
+ }]
1045
+ }],
1046
+ fill: [{
1047
+ type: Input,
1048
+ args: [{
1049
+ transform: booleanAttribute
1050
+ }]
1051
+ }],
1052
+ placeholder: [{
1053
+ type: Input,
1054
+ args: [{
1055
+ transform: booleanOrUrlAttribute
1056
+ }]
1057
+ }],
1058
+ placeholderConfig: [{
1059
+ type: Input
1060
+ }],
1061
+ src: [{
1062
+ type: Input
1063
+ }],
1064
+ srcset: [{
1065
+ type: Input
1066
+ }]
1067
+ }
1068
+ });
1548
1069
  function processConfig(config) {
1549
- let sortedBreakpoints = {};
1550
- if (config.breakpoints) {
1551
- sortedBreakpoints.breakpoints = config.breakpoints.sort((a, b) => a - b);
1552
- }
1553
- return Object.assign({}, _IMAGE_CONFIG_DEFAULTS, config, sortedBreakpoints);
1070
+ let sortedBreakpoints = {};
1071
+ if (config.breakpoints) {
1072
+ sortedBreakpoints.breakpoints = config.breakpoints.sort((a, b) => a - b);
1073
+ }
1074
+ return Object.assign({}, _IMAGE_CONFIG_DEFAULTS, config, sortedBreakpoints);
1554
1075
  }
1555
- /***** Assert functions *****/
1556
- /**
1557
- * Verifies that there is no `src` set on a host element.
1558
- */
1559
1076
  function assertNoConflictingSrc(dir) {
1560
- if (dir.src) {
1561
- throw new _RuntimeError(2950 /* RuntimeErrorCode.UNEXPECTED_SRC_ATTR */, `${imgDirectiveDetails(dir.ngSrc)} both \`src\` and \`ngSrc\` have been set. ` +
1562
- `Supplying both of these attributes breaks lazy loading. ` +
1563
- `The NgOptimizedImage directive sets \`src\` itself based on the value of \`ngSrc\`. ` +
1564
- `To fix this, please remove the \`src\` attribute.`);
1565
- }
1077
+ if (dir.src) {
1078
+ throw new _RuntimeError(2950, `${imgDirectiveDetails(dir.ngSrc)} both \`src\` and \`ngSrc\` have been set. ` + `Supplying both of these attributes breaks lazy loading. ` + `The NgOptimizedImage directive sets \`src\` itself based on the value of \`ngSrc\`. ` + `To fix this, please remove the \`src\` attribute.`);
1079
+ }
1566
1080
  }
1567
- /**
1568
- * Verifies that there is no `srcset` set on a host element.
1569
- */
1570
1081
  function assertNoConflictingSrcset(dir) {
1571
- if (dir.srcset) {
1572
- throw new _RuntimeError(2951 /* RuntimeErrorCode.UNEXPECTED_SRCSET_ATTR */, `${imgDirectiveDetails(dir.ngSrc)} both \`srcset\` and \`ngSrcset\` have been set. ` +
1573
- `Supplying both of these attributes breaks lazy loading. ` +
1574
- `The NgOptimizedImage directive sets \`srcset\` itself based on the value of ` +
1575
- `\`ngSrcset\`. To fix this, please remove the \`srcset\` attribute.`);
1576
- }
1082
+ if (dir.srcset) {
1083
+ throw new _RuntimeError(2951, `${imgDirectiveDetails(dir.ngSrc)} both \`srcset\` and \`ngSrcset\` have been set. ` + `Supplying both of these attributes breaks lazy loading. ` + `The NgOptimizedImage directive sets \`srcset\` itself based on the value of ` + `\`ngSrcset\`. To fix this, please remove the \`srcset\` attribute.`);
1084
+ }
1577
1085
  }
1578
- /**
1579
- * Verifies that the `ngSrc` is not a Base64-encoded image.
1580
- */
1581
1086
  function assertNotBase64Image(dir) {
1582
- let ngSrc = dir.ngSrc.trim();
1583
- if (ngSrc.startsWith('data:')) {
1584
- if (ngSrc.length > BASE64_IMG_MAX_LENGTH_IN_ERROR) {
1585
- ngSrc = ngSrc.substring(0, BASE64_IMG_MAX_LENGTH_IN_ERROR) + '...';
1586
- }
1587
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc, false)} \`ngSrc\` is a Base64-encoded string ` +
1588
- `(${ngSrc}). NgOptimizedImage does not support Base64-encoded strings. ` +
1589
- `To fix this, disable the NgOptimizedImage directive for this element ` +
1590
- `by removing \`ngSrc\` and using a standard \`src\` attribute instead.`);
1087
+ let ngSrc = dir.ngSrc.trim();
1088
+ if (ngSrc.startsWith('data:')) {
1089
+ if (ngSrc.length > BASE64_IMG_MAX_LENGTH_IN_ERROR) {
1090
+ ngSrc = ngSrc.substring(0, BASE64_IMG_MAX_LENGTH_IN_ERROR) + '...';
1591
1091
  }
1092
+ throw new _RuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc, false)} \`ngSrc\` is a Base64-encoded string ` + `(${ngSrc}). NgOptimizedImage does not support Base64-encoded strings. ` + `To fix this, disable the NgOptimizedImage directive for this element ` + `by removing \`ngSrc\` and using a standard \`src\` attribute instead.`);
1093
+ }
1592
1094
  }
1593
- /**
1594
- * Verifies that the 'sizes' only includes responsive values.
1595
- */
1596
1095
  function assertNoComplexSizes(dir) {
1597
- let sizes = dir.sizes;
1598
- if (sizes?.match(/((\)|,)\s|^)\d+px/)) {
1599
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc, false)} \`sizes\` was set to a string including ` +
1600
- `pixel values. For automatic \`srcset\` generation, \`sizes\` must only include responsive ` +
1601
- `values, such as \`sizes="50vw"\` or \`sizes="(min-width: 768px) 50vw, 100vw"\`. ` +
1602
- `To fix this, modify the \`sizes\` attribute, or provide your own \`ngSrcset\` value directly.`);
1603
- }
1096
+ let sizes = dir.sizes;
1097
+ if (sizes?.match(/((\)|,)\s|^)\d+px/)) {
1098
+ throw new _RuntimeError(2952, `${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.`);
1099
+ }
1604
1100
  }
1605
1101
  function assertValidPlaceholder(dir, imageLoader) {
1606
- assertNoPlaceholderConfigWithoutPlaceholder(dir);
1607
- assertNoRelativePlaceholderWithoutLoader(dir, imageLoader);
1608
- assertNoOversizedDataUrl(dir);
1102
+ assertNoPlaceholderConfigWithoutPlaceholder(dir);
1103
+ assertNoRelativePlaceholderWithoutLoader(dir, imageLoader);
1104
+ assertNoOversizedDataUrl(dir);
1609
1105
  }
1610
- /**
1611
- * Verifies that placeholderConfig isn't being used without placeholder
1612
- */
1613
1106
  function assertNoPlaceholderConfigWithoutPlaceholder(dir) {
1614
- if (dir.placeholderConfig && !dir.placeholder) {
1615
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc, false)} \`placeholderConfig\` options were provided for an ` +
1616
- `image that does not use the \`placeholder\` attribute, and will have no effect.`);
1617
- }
1107
+ if (dir.placeholderConfig && !dir.placeholder) {
1108
+ throw new _RuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc, false)} \`placeholderConfig\` options were provided for an ` + `image that does not use the \`placeholder\` attribute, and will have no effect.`);
1109
+ }
1618
1110
  }
1619
- /**
1620
- * Warns if a relative URL placeholder is specified, but no loader is present to provide the small
1621
- * image.
1622
- */
1623
1111
  function assertNoRelativePlaceholderWithoutLoader(dir, imageLoader) {
1624
- if (dir.placeholder === true && imageLoader === noopImageLoader) {
1625
- throw new _RuntimeError(2963 /* RuntimeErrorCode.MISSING_NECESSARY_LOADER */, `${imgDirectiveDetails(dir.ngSrc)} the \`placeholder\` attribute is set to true but ` +
1626
- `no image loader is configured (i.e. the default one is being used), ` +
1627
- `which would result in the same image being used for the primary image and its placeholder. ` +
1628
- `To fix this, provide a loader or remove the \`placeholder\` attribute from the image.`);
1629
- }
1112
+ if (dir.placeholder === true && imageLoader === noopImageLoader) {
1113
+ throw new _RuntimeError(2963, `${imgDirectiveDetails(dir.ngSrc)} the \`placeholder\` attribute is set to true but ` + `no image loader is configured (i.e. the default one is being used), ` + `which would result in the same image being used for the primary image and its placeholder. ` + `To fix this, provide a loader or remove the \`placeholder\` attribute from the image.`);
1114
+ }
1630
1115
  }
1631
- /**
1632
- * Warns or throws an error if an oversized dataURL placeholder is provided.
1633
- */
1634
1116
  function assertNoOversizedDataUrl(dir) {
1635
- if (dir.placeholder &&
1636
- typeof dir.placeholder === 'string' &&
1637
- dir.placeholder.startsWith('data:')) {
1638
- if (dir.placeholder.length > DATA_URL_ERROR_LIMIT) {
1639
- throw new _RuntimeError(2965 /* RuntimeErrorCode.OVERSIZED_PLACEHOLDER */, `${imgDirectiveDetails(dir.ngSrc)} the \`placeholder\` attribute is set to a data URL which is longer ` +
1640
- `than ${DATA_URL_ERROR_LIMIT} characters. This is strongly discouraged, as large inline placeholders ` +
1641
- `directly increase the bundle size of Angular and hurt page load performance. To fix this, generate ` +
1642
- `a smaller data URL placeholder.`);
1643
- }
1644
- if (dir.placeholder.length > DATA_URL_WARN_LIMIT) {
1645
- console.warn(_formatRuntimeError(2965 /* RuntimeErrorCode.OVERSIZED_PLACEHOLDER */, `${imgDirectiveDetails(dir.ngSrc)} the \`placeholder\` attribute is set to a data URL which is longer ` +
1646
- `than ${DATA_URL_WARN_LIMIT} characters. This is discouraged, as large inline placeholders ` +
1647
- `directly increase the bundle size of Angular and hurt page load performance. For better loading performance, ` +
1648
- `generate a smaller data URL placeholder.`));
1649
- }
1117
+ if (dir.placeholder && typeof dir.placeholder === 'string' && dir.placeholder.startsWith('data:')) {
1118
+ if (dir.placeholder.length > DATA_URL_ERROR_LIMIT) {
1119
+ throw new _RuntimeError(2965, `${imgDirectiveDetails(dir.ngSrc)} the \`placeholder\` attribute is set to a data URL which is longer ` + `than ${DATA_URL_ERROR_LIMIT} characters. This is strongly discouraged, as large inline placeholders ` + `directly increase the bundle size of Angular and hurt page load performance. To fix this, generate ` + `a smaller data URL placeholder.`);
1120
+ }
1121
+ if (dir.placeholder.length > DATA_URL_WARN_LIMIT) {
1122
+ console.warn(_formatRuntimeError(2965, `${imgDirectiveDetails(dir.ngSrc)} the \`placeholder\` attribute is set to a data URL which is longer ` + `than ${DATA_URL_WARN_LIMIT} characters. This is discouraged, as large inline placeholders ` + `directly increase the bundle size of Angular and hurt page load performance. For better loading performance, ` + `generate a smaller data URL placeholder.`));
1650
1123
  }
1124
+ }
1651
1125
  }
1652
- /**
1653
- * Verifies that the `ngSrc` is not a Blob URL.
1654
- */
1655
1126
  function assertNotBlobUrl(dir) {
1656
- const ngSrc = dir.ngSrc.trim();
1657
- if (ngSrc.startsWith('blob:')) {
1658
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`ngSrc\` was set to a blob URL (${ngSrc}). ` +
1659
- `Blob URLs are not supported by the NgOptimizedImage directive. ` +
1660
- `To fix this, disable the NgOptimizedImage directive for this element ` +
1661
- `by removing \`ngSrc\` and using a regular \`src\` attribute instead.`);
1662
- }
1127
+ const ngSrc = dir.ngSrc.trim();
1128
+ if (ngSrc.startsWith('blob:')) {
1129
+ throw new _RuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} \`ngSrc\` was set to a blob URL (${ngSrc}). ` + `Blob URLs are not supported by the NgOptimizedImage directive. ` + `To fix this, disable the NgOptimizedImage directive for this element ` + `by removing \`ngSrc\` and using a regular \`src\` attribute instead.`);
1130
+ }
1663
1131
  }
1664
- /**
1665
- * Verifies that the input is set to a non-empty string.
1666
- */
1667
1132
  function assertNonEmptyInput(dir, name, value) {
1668
- const isString = typeof value === 'string';
1669
- const isEmptyString = isString && value.trim() === '';
1670
- if (!isString || isEmptyString) {
1671
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`${name}\` has an invalid value ` +
1672
- `(\`${value}\`). To fix this, change the value to a non-empty string.`);
1673
- }
1133
+ const isString = typeof value === 'string';
1134
+ const isEmptyString = isString && value.trim() === '';
1135
+ if (!isString || isEmptyString) {
1136
+ throw new _RuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} \`${name}\` has an invalid value ` + `(\`${value}\`). To fix this, change the value to a non-empty string.`);
1137
+ }
1674
1138
  }
1675
- /**
1676
- * Verifies that the `ngSrcset` is in a valid format, e.g. "100w, 200w" or "1x, 2x".
1677
- */
1678
1139
  function assertValidNgSrcset(dir, value) {
1679
- if (value == null)
1680
- return;
1681
- assertNonEmptyInput(dir, 'ngSrcset', value);
1682
- const stringVal = value;
1683
- const isValidWidthDescriptor = VALID_WIDTH_DESCRIPTOR_SRCSET.test(stringVal);
1684
- const isValidDensityDescriptor = VALID_DENSITY_DESCRIPTOR_SRCSET.test(stringVal);
1685
- if (isValidDensityDescriptor) {
1686
- assertUnderDensityCap(dir, stringVal);
1687
- }
1688
- const isValidSrcset = isValidWidthDescriptor || isValidDensityDescriptor;
1689
- if (!isValidSrcset) {
1690
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`ngSrcset\` has an invalid value (\`${value}\`). ` +
1691
- `To fix this, supply \`ngSrcset\` using a comma-separated list of one or more width ` +
1692
- `descriptors (e.g. "100w, 200w") or density descriptors (e.g. "1x, 2x").`);
1693
- }
1140
+ if (value == null) return;
1141
+ assertNonEmptyInput(dir, 'ngSrcset', value);
1142
+ const stringVal = value;
1143
+ const isValidWidthDescriptor = VALID_WIDTH_DESCRIPTOR_SRCSET.test(stringVal);
1144
+ const isValidDensityDescriptor = VALID_DENSITY_DESCRIPTOR_SRCSET.test(stringVal);
1145
+ if (isValidDensityDescriptor) {
1146
+ assertUnderDensityCap(dir, stringVal);
1147
+ }
1148
+ const isValidSrcset = isValidWidthDescriptor || isValidDensityDescriptor;
1149
+ if (!isValidSrcset) {
1150
+ throw new _RuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} \`ngSrcset\` has an invalid value (\`${value}\`). ` + `To fix this, supply \`ngSrcset\` using a comma-separated list of one or more width ` + `descriptors (e.g. "100w, 200w") or density descriptors (e.g. "1x, 2x").`);
1151
+ }
1694
1152
  }
1695
1153
  function assertUnderDensityCap(dir, value) {
1696
- const underDensityCap = value
1697
- .split(',')
1698
- .every((num) => num === '' || parseFloat(num) <= ABSOLUTE_SRCSET_DENSITY_CAP);
1699
- if (!underDensityCap) {
1700
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \`ngSrcset\` contains an unsupported image density:` +
1701
- `\`${value}\`. NgOptimizedImage generally recommends a max image density of ` +
1702
- `${RECOMMENDED_SRCSET_DENSITY_CAP}x but supports image densities up to ` +
1703
- `${ABSOLUTE_SRCSET_DENSITY_CAP}x. The human eye cannot distinguish between image densities ` +
1704
- `greater than ${RECOMMENDED_SRCSET_DENSITY_CAP}x - which makes them unnecessary for ` +
1705
- `most use cases. Images that will be pinch-zoomed are typically the primary use case for ` +
1706
- `${ABSOLUTE_SRCSET_DENSITY_CAP}x images. Please remove the high density descriptor and try again.`);
1707
- }
1154
+ const underDensityCap = value.split(',').every(num => num === '' || parseFloat(num) <= ABSOLUTE_SRCSET_DENSITY_CAP);
1155
+ if (!underDensityCap) {
1156
+ throw new _RuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} the \`ngSrcset\` 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.`);
1157
+ }
1708
1158
  }
1709
- /**
1710
- * Creates a `RuntimeError` instance to represent a situation when an input is set after
1711
- * the directive has initialized.
1712
- */
1713
1159
  function postInitInputChangeError(dir, inputName) {
1714
- let reason;
1715
- if (inputName === 'width' || inputName === 'height') {
1716
- reason =
1717
- `Changing \`${inputName}\` may result in different attribute value ` +
1718
- `applied to the underlying image element and cause layout shifts on a page.`;
1719
- }
1720
- else {
1721
- reason =
1722
- `Changing the \`${inputName}\` would have no effect on the underlying ` +
1723
- `image element, because the resource loading has already occurred.`;
1724
- }
1725
- return new _RuntimeError(2953 /* RuntimeErrorCode.UNEXPECTED_INPUT_CHANGE */, `${imgDirectiveDetails(dir.ngSrc)} \`${inputName}\` was updated after initialization. ` +
1726
- `The NgOptimizedImage directive will not react to this input change. ${reason} ` +
1727
- `To fix this, either switch \`${inputName}\` to a static value ` +
1728
- `or wrap the image element in an @if that is gated on the necessary value.`);
1160
+ let reason;
1161
+ if (inputName === 'width' || inputName === 'height') {
1162
+ reason = `Changing \`${inputName}\` may result in different attribute value ` + `applied to the underlying image element and cause layout shifts on a page.`;
1163
+ } else {
1164
+ reason = `Changing the \`${inputName}\` would have no effect on the underlying ` + `image element, because the resource loading has already occurred.`;
1165
+ }
1166
+ return new _RuntimeError(2953, `${imgDirectiveDetails(dir.ngSrc)} \`${inputName}\` was updated after initialization. ` + `The NgOptimizedImage directive will not react to this input change. ${reason} ` + `To fix this, either switch \`${inputName}\` to a static value ` + `or wrap the image element in an @if that is gated on the necessary value.`);
1729
1167
  }
1730
- /**
1731
- * Verify that none of the listed inputs has changed.
1732
- */
1733
1168
  function assertNoPostInitInputChange(dir, changes, inputs) {
1734
- inputs.forEach((input) => {
1735
- const isUpdated = changes.hasOwnProperty(input);
1736
- if (isUpdated && !changes[input].isFirstChange()) {
1737
- if (input === 'ngSrc') {
1738
- // When the `ngSrc` input changes, we detect that only in the
1739
- // `ngOnChanges` hook, thus the `ngSrc` is already set. We use
1740
- // `ngSrc` in the error message, so we use a previous value, but
1741
- // not the updated one in it.
1742
- dir = { ngSrc: changes[input].previousValue };
1743
- }
1744
- throw postInitInputChangeError(dir, input);
1745
- }
1746
- });
1169
+ inputs.forEach(input => {
1170
+ const isUpdated = changes.hasOwnProperty(input);
1171
+ if (isUpdated && !changes[input].isFirstChange()) {
1172
+ if (input === 'ngSrc') {
1173
+ dir = {
1174
+ ngSrc: changes[input].previousValue
1175
+ };
1176
+ }
1177
+ throw postInitInputChangeError(dir, input);
1178
+ }
1179
+ });
1747
1180
  }
1748
- /**
1749
- * Verifies that a specified input is a number greater than 0.
1750
- */
1751
1181
  function assertGreaterThanZero(dir, inputValue, inputName) {
1752
- const validNumber = typeof inputValue === 'number' && inputValue > 0;
1753
- const validString = typeof inputValue === 'string' && /^\d+$/.test(inputValue.trim()) && parseInt(inputValue) > 0;
1754
- if (!validNumber && !validString) {
1755
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \`${inputName}\` has an invalid value. ` +
1756
- `To fix this, provide \`${inputName}\` as a number greater than 0.`);
1757
- }
1182
+ const validNumber = typeof inputValue === 'number' && inputValue > 0;
1183
+ const validString = typeof inputValue === 'string' && /^\d+$/.test(inputValue.trim()) && parseInt(inputValue) > 0;
1184
+ if (!validNumber && !validString) {
1185
+ throw new _RuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} \`${inputName}\` has an invalid value. ` + `To fix this, provide \`${inputName}\` as a number greater than 0.`);
1186
+ }
1758
1187
  }
1759
- /**
1760
- * Verifies that the rendered image is not visually distorted. Effectively this is checking:
1761
- * - Whether the "width" and "height" attributes reflect the actual dimensions of the image.
1762
- * - Whether image styling is "correct" (see below for a longer explanation).
1763
- */
1764
1188
  function assertNoImageDistortion(dir, img, renderer) {
1765
- const callback = () => {
1766
- removeLoadListenerFn();
1767
- removeErrorListenerFn();
1768
- const computedStyle = window.getComputedStyle(img);
1769
- let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));
1770
- let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));
1771
- const boxSizing = computedStyle.getPropertyValue('box-sizing');
1772
- if (boxSizing === 'border-box') {
1773
- const paddingTop = computedStyle.getPropertyValue('padding-top');
1774
- const paddingRight = computedStyle.getPropertyValue('padding-right');
1775
- const paddingBottom = computedStyle.getPropertyValue('padding-bottom');
1776
- const paddingLeft = computedStyle.getPropertyValue('padding-left');
1777
- renderedWidth -= parseFloat(paddingRight) + parseFloat(paddingLeft);
1778
- renderedHeight -= parseFloat(paddingTop) + parseFloat(paddingBottom);
1779
- }
1780
- const renderedAspectRatio = renderedWidth / renderedHeight;
1781
- const nonZeroRenderedDimensions = renderedWidth !== 0 && renderedHeight !== 0;
1782
- const intrinsicWidth = img.naturalWidth;
1783
- const intrinsicHeight = img.naturalHeight;
1784
- const intrinsicAspectRatio = intrinsicWidth / intrinsicHeight;
1785
- const suppliedWidth = dir.width;
1786
- const suppliedHeight = dir.height;
1787
- const suppliedAspectRatio = suppliedWidth / suppliedHeight;
1788
- // Tolerance is used to account for the impact of subpixel rendering.
1789
- // Due to subpixel rendering, the rendered, intrinsic, and supplied
1790
- // aspect ratios of a correctly configured image may not exactly match.
1791
- // For example, a `width=4030 height=3020` image might have a rendered
1792
- // size of "1062w, 796.48h". (An aspect ratio of 1.334... vs. 1.333...)
1793
- const inaccurateDimensions = Math.abs(suppliedAspectRatio - intrinsicAspectRatio) > ASPECT_RATIO_TOLERANCE;
1794
- const stylingDistortion = nonZeroRenderedDimensions &&
1795
- Math.abs(intrinsicAspectRatio - renderedAspectRatio) > ASPECT_RATIO_TOLERANCE;
1796
- if (inaccurateDimensions) {
1797
- console.warn(_formatRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the image does not match ` +
1798
- `the aspect ratio indicated by the width and height attributes. ` +
1799
- `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` +
1800
- `(aspect-ratio: ${round(intrinsicAspectRatio)}). \nSupplied width and height attributes: ` +
1801
- `${suppliedWidth}w x ${suppliedHeight}h (aspect-ratio: ${round(suppliedAspectRatio)}). ` +
1802
- `\nTo fix this, update the width and height attributes.`));
1803
- }
1804
- else if (stylingDistortion) {
1805
- console.warn(_formatRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the rendered image ` +
1806
- `does not match the image's intrinsic aspect ratio. ` +
1807
- `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` +
1808
- `(aspect-ratio: ${round(intrinsicAspectRatio)}). \nRendered image size: ` +
1809
- `${renderedWidth}w x ${renderedHeight}h (aspect-ratio: ` +
1810
- `${round(renderedAspectRatio)}). \nThis issue can occur if "width" and "height" ` +
1811
- `attributes are added to an image without updating the corresponding ` +
1812
- `image styling. To fix this, adjust image styling. In most cases, ` +
1813
- `adding "height: auto" or "width: auto" to the image styling will fix ` +
1814
- `this issue.`));
1815
- }
1816
- else if (!dir.ngSrcset && nonZeroRenderedDimensions) {
1817
- // If `ngSrcset` hasn't been set, sanity check the intrinsic size.
1818
- const recommendedWidth = RECOMMENDED_SRCSET_DENSITY_CAP * renderedWidth;
1819
- const recommendedHeight = RECOMMENDED_SRCSET_DENSITY_CAP * renderedHeight;
1820
- const oversizedWidth = intrinsicWidth - recommendedWidth >= OVERSIZED_IMAGE_TOLERANCE;
1821
- const oversizedHeight = intrinsicHeight - recommendedHeight >= OVERSIZED_IMAGE_TOLERANCE;
1822
- if (oversizedWidth || oversizedHeight) {
1823
- console.warn(_formatRuntimeError(2960 /* RuntimeErrorCode.OVERSIZED_IMAGE */, `${imgDirectiveDetails(dir.ngSrc)} the intrinsic image is significantly ` +
1824
- `larger than necessary. ` +
1825
- `\nRendered image size: ${renderedWidth}w x ${renderedHeight}h. ` +
1826
- `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h. ` +
1827
- `\nRecommended intrinsic image size: ${recommendedWidth}w x ${recommendedHeight}h. ` +
1828
- `\nNote: Recommended intrinsic image size is calculated assuming a maximum DPR of ` +
1829
- `${RECOMMENDED_SRCSET_DENSITY_CAP}. To improve loading time, resize the image ` +
1830
- `or consider using the "ngSrcset" and "sizes" attributes.`));
1831
- }
1832
- }
1833
- };
1834
- const removeLoadListenerFn = renderer.listen(img, 'load', callback);
1835
- // We only listen to the `error` event to remove the `load` event listener because it will not be
1836
- // fired if the image fails to load. This is done to prevent memory leaks in development mode
1837
- // because image elements aren't garbage-collected properly. It happens because zone.js stores the
1838
- // event listener directly on the element and closures capture `dir`.
1839
- const removeErrorListenerFn = renderer.listen(img, 'error', () => {
1840
- removeLoadListenerFn();
1841
- removeErrorListenerFn();
1842
- });
1843
- callOnLoadIfImageIsLoaded(img, callback);
1189
+ const callback = () => {
1190
+ removeLoadListenerFn();
1191
+ removeErrorListenerFn();
1192
+ const computedStyle = window.getComputedStyle(img);
1193
+ let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));
1194
+ let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));
1195
+ const boxSizing = computedStyle.getPropertyValue('box-sizing');
1196
+ if (boxSizing === 'border-box') {
1197
+ const paddingTop = computedStyle.getPropertyValue('padding-top');
1198
+ const paddingRight = computedStyle.getPropertyValue('padding-right');
1199
+ const paddingBottom = computedStyle.getPropertyValue('padding-bottom');
1200
+ const paddingLeft = computedStyle.getPropertyValue('padding-left');
1201
+ renderedWidth -= parseFloat(paddingRight) + parseFloat(paddingLeft);
1202
+ renderedHeight -= parseFloat(paddingTop) + parseFloat(paddingBottom);
1203
+ }
1204
+ const renderedAspectRatio = renderedWidth / renderedHeight;
1205
+ const nonZeroRenderedDimensions = renderedWidth !== 0 && renderedHeight !== 0;
1206
+ const intrinsicWidth = img.naturalWidth;
1207
+ const intrinsicHeight = img.naturalHeight;
1208
+ const intrinsicAspectRatio = intrinsicWidth / intrinsicHeight;
1209
+ const suppliedWidth = dir.width;
1210
+ const suppliedHeight = dir.height;
1211
+ const suppliedAspectRatio = suppliedWidth / suppliedHeight;
1212
+ const inaccurateDimensions = Math.abs(suppliedAspectRatio - intrinsicAspectRatio) > ASPECT_RATIO_TOLERANCE;
1213
+ const stylingDistortion = nonZeroRenderedDimensions && Math.abs(intrinsicAspectRatio - renderedAspectRatio) > ASPECT_RATIO_TOLERANCE;
1214
+ if (inaccurateDimensions) {
1215
+ console.warn(_formatRuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the image does not match ` + `the aspect ratio indicated by the width and height attributes. ` + `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` + `(aspect-ratio: ${round(intrinsicAspectRatio)}). \nSupplied width and height attributes: ` + `${suppliedWidth}w x ${suppliedHeight}h (aspect-ratio: ${round(suppliedAspectRatio)}). ` + `\nTo fix this, update the width and height attributes.`));
1216
+ } else if (stylingDistortion) {
1217
+ console.warn(_formatRuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the rendered image ` + `does not match the image's intrinsic aspect ratio. ` + `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` + `(aspect-ratio: ${round(intrinsicAspectRatio)}). \nRendered image size: ` + `${renderedWidth}w x ${renderedHeight}h (aspect-ratio: ` + `${round(renderedAspectRatio)}). \nThis 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.`));
1218
+ } else if (!dir.ngSrcset && nonZeroRenderedDimensions) {
1219
+ const recommendedWidth = RECOMMENDED_SRCSET_DENSITY_CAP * renderedWidth;
1220
+ const recommendedHeight = RECOMMENDED_SRCSET_DENSITY_CAP * renderedHeight;
1221
+ const oversizedWidth = intrinsicWidth - recommendedWidth >= OVERSIZED_IMAGE_TOLERANCE;
1222
+ const oversizedHeight = intrinsicHeight - recommendedHeight >= OVERSIZED_IMAGE_TOLERANCE;
1223
+ if (oversizedWidth || oversizedHeight) {
1224
+ console.warn(_formatRuntimeError(2960, `${imgDirectiveDetails(dir.ngSrc)} the intrinsic image is significantly ` + `larger than necessary. ` + `\nRendered image size: ${renderedWidth}w x ${renderedHeight}h. ` + `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h. ` + `\nRecommended intrinsic image size: ${recommendedWidth}w x ${recommendedHeight}h. ` + `\nNote: Recommended intrinsic image size is calculated assuming a maximum DPR of ` + `${RECOMMENDED_SRCSET_DENSITY_CAP}. To improve loading time, resize the image ` + `or consider using the "ngSrcset" and "sizes" attributes.`));
1225
+ }
1226
+ }
1227
+ };
1228
+ const removeLoadListenerFn = renderer.listen(img, 'load', callback);
1229
+ const removeErrorListenerFn = renderer.listen(img, 'error', () => {
1230
+ removeLoadListenerFn();
1231
+ removeErrorListenerFn();
1232
+ });
1233
+ callOnLoadIfImageIsLoaded(img, callback);
1844
1234
  }
1845
- /**
1846
- * Verifies that a specified input is set.
1847
- */
1848
1235
  function assertNonEmptyWidthAndHeight(dir) {
1849
- let missingAttributes = [];
1850
- if (dir.width === undefined)
1851
- missingAttributes.push('width');
1852
- if (dir.height === undefined)
1853
- missingAttributes.push('height');
1854
- if (missingAttributes.length > 0) {
1855
- throw new _RuntimeError(2954 /* RuntimeErrorCode.REQUIRED_INPUT_MISSING */, `${imgDirectiveDetails(dir.ngSrc)} these required attributes ` +
1856
- `are missing: ${missingAttributes.map((attr) => `"${attr}"`).join(', ')}. ` +
1857
- `Including "width" and "height" attributes will prevent image-related layout shifts. ` +
1858
- `To fix this, include "width" and "height" attributes on the image tag or turn on ` +
1859
- `"fill" mode with the \`fill\` attribute.`);
1860
- }
1236
+ let missingAttributes = [];
1237
+ if (dir.width === undefined) missingAttributes.push('width');
1238
+ if (dir.height === undefined) missingAttributes.push('height');
1239
+ if (missingAttributes.length > 0) {
1240
+ throw new _RuntimeError(2954, `${imgDirectiveDetails(dir.ngSrc)} 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 or turn on ` + `"fill" mode with the \`fill\` attribute.`);
1241
+ }
1861
1242
  }
1862
- /**
1863
- * Verifies that width and height are not set. Used in fill mode, where those attributes don't make
1864
- * sense.
1865
- */
1866
1243
  function assertEmptyWidthAndHeight(dir) {
1867
- if (dir.width || dir.height) {
1868
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the attributes \`height\` and/or \`width\` are present ` +
1869
- `along with the \`fill\` attribute. Because \`fill\` mode causes an image to fill its containing ` +
1870
- `element, the size attributes have no effect and should be removed.`);
1871
- }
1244
+ if (dir.width || dir.height) {
1245
+ throw new _RuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} the attributes \`height\` and/or \`width\` are present ` + `along with the \`fill\` attribute. Because \`fill\` mode causes an image to fill its containing ` + `element, the size attributes have no effect and should be removed.`);
1246
+ }
1872
1247
  }
1873
- /**
1874
- * Verifies that the rendered image has a nonzero height. If the image is in fill mode, provides
1875
- * guidance that this can be caused by the containing element's CSS position property.
1876
- */
1877
1248
  function assertNonZeroRenderedHeight(dir, img, renderer) {
1878
- const callback = () => {
1879
- removeLoadListenerFn();
1880
- removeErrorListenerFn();
1881
- const renderedHeight = img.clientHeight;
1882
- if (dir.fill && renderedHeight === 0) {
1883
- console.warn(_formatRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the height of the fill-mode image is zero. ` +
1884
- `This is likely because the containing element does not have the CSS 'position' ` +
1885
- `property set to one of the following: "relative", "fixed", or "absolute". ` +
1886
- `To fix this problem, make sure the container element has the CSS 'position' ` +
1887
- `property defined and the height of the element is not zero.`));
1888
- }
1889
- };
1890
- const removeLoadListenerFn = renderer.listen(img, 'load', callback);
1891
- // See comments in the `assertNoImageDistortion`.
1892
- const removeErrorListenerFn = renderer.listen(img, 'error', () => {
1893
- removeLoadListenerFn();
1894
- removeErrorListenerFn();
1895
- });
1896
- callOnLoadIfImageIsLoaded(img, callback);
1249
+ const callback = () => {
1250
+ removeLoadListenerFn();
1251
+ removeErrorListenerFn();
1252
+ const renderedHeight = img.clientHeight;
1253
+ if (dir.fill && renderedHeight === 0) {
1254
+ console.warn(_formatRuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} the height of the fill-mode image is zero. ` + `This is likely because the containing element does not have the CSS 'position' ` + `property set to one of the following: "relative", "fixed", or "absolute". ` + `To fix this problem, make sure the container element has the CSS 'position' ` + `property defined and the height of the element is not zero.`));
1255
+ }
1256
+ };
1257
+ const removeLoadListenerFn = renderer.listen(img, 'load', callback);
1258
+ const removeErrorListenerFn = renderer.listen(img, 'error', () => {
1259
+ removeLoadListenerFn();
1260
+ removeErrorListenerFn();
1261
+ });
1262
+ callOnLoadIfImageIsLoaded(img, callback);
1897
1263
  }
1898
- /**
1899
- * Verifies that the `loading` attribute is set to a valid input &
1900
- * is not used on priority images.
1901
- */
1902
1264
  function assertValidLoadingInput(dir) {
1903
- if (dir.loading && dir.priority) {
1904
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \`loading\` attribute ` +
1905
- `was used on an image that was marked "priority". ` +
1906
- `Setting \`loading\` on priority images is not allowed ` +
1907
- `because these images will always be eagerly loaded. ` +
1908
- `To fix this, remove the “loading” attribute from the priority image.`);
1909
- }
1910
- const validInputs = ['auto', 'eager', 'lazy'];
1911
- if (typeof dir.loading === 'string' && !validInputs.includes(dir.loading)) {
1912
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \`loading\` attribute ` +
1913
- `has an invalid value (\`${dir.loading}\`). ` +
1914
- `To fix this, provide a valid value ("lazy", "eager", or "auto").`);
1915
- }
1265
+ if (dir.loading && dir.priority) {
1266
+ throw new _RuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} 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.`);
1267
+ }
1268
+ const validInputs = ['auto', 'eager', 'lazy'];
1269
+ if (typeof dir.loading === 'string' && !validInputs.includes(dir.loading)) {
1270
+ throw new _RuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} the \`loading\` attribute ` + `has an invalid value (\`${dir.loading}\`). ` + `To fix this, provide a valid value ("lazy", "eager", or "auto").`);
1271
+ }
1916
1272
  }
1917
- /**
1918
- * Verifies that the `decoding` attribute is set to a valid input.
1919
- */
1920
1273
  function assertValidDecodingInput(dir) {
1921
- const validInputs = ['sync', 'async', 'auto'];
1922
- if (typeof dir.decoding === 'string' && !validInputs.includes(dir.decoding)) {
1923
- throw new _RuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \`decoding\` attribute ` +
1924
- `has an invalid value (\`${dir.decoding}\`). ` +
1925
- `To fix this, provide a valid value ("sync", "async", or "auto").`);
1926
- }
1274
+ const validInputs = ['sync', 'async', 'auto'];
1275
+ if (typeof dir.decoding === 'string' && !validInputs.includes(dir.decoding)) {
1276
+ throw new _RuntimeError(2952, `${imgDirectiveDetails(dir.ngSrc)} the \`decoding\` attribute ` + `has an invalid value (\`${dir.decoding}\`). ` + `To fix this, provide a valid value ("sync", "async", or "auto").`);
1277
+ }
1927
1278
  }
1928
- /**
1929
- * Warns if NOT using a loader (falling back to the generic loader) and
1930
- * the image appears to be hosted on one of the image CDNs for which
1931
- * we do have a built-in image loader. Suggests switching to the
1932
- * built-in loader.
1933
- *
1934
- * @param ngSrc Value of the ngSrc attribute
1935
- * @param imageLoader ImageLoader provided
1936
- */
1937
1279
  function assertNotMissingBuiltInLoader(ngSrc, imageLoader) {
1938
- if (imageLoader === noopImageLoader) {
1939
- let builtInLoaderName = '';
1940
- for (const loader of BUILT_IN_LOADERS) {
1941
- if (loader.testUrl(ngSrc)) {
1942
- builtInLoaderName = loader.name;
1943
- break;
1944
- }
1945
- }
1946
- if (builtInLoaderName) {
1947
- console.warn(_formatRuntimeError(2962 /* RuntimeErrorCode.MISSING_BUILTIN_LOADER */, `NgOptimizedImage: It looks like your images may be hosted on the ` +
1948
- `${builtInLoaderName} CDN, but your app is not using Angular's ` +
1949
- `built-in loader for that CDN. We recommend switching to use ` +
1950
- `the built-in by calling \`provide${builtInLoaderName}Loader()\` ` +
1951
- `in your \`providers\` and passing it your instance's base URL. ` +
1952
- `If you don't want to use the built-in loader, define a custom ` +
1953
- `loader function using IMAGE_LOADER to silence this warning.`));
1954
- }
1280
+ if (imageLoader === noopImageLoader) {
1281
+ let builtInLoaderName = '';
1282
+ for (const loader of BUILT_IN_LOADERS) {
1283
+ if (loader.testUrl(ngSrc)) {
1284
+ builtInLoaderName = loader.name;
1285
+ break;
1286
+ }
1287
+ }
1288
+ if (builtInLoaderName) {
1289
+ console.warn(_formatRuntimeError(2962, `NgOptimizedImage: It looks like your images may be hosted on the ` + `${builtInLoaderName} CDN, but your app is not using Angular's ` + `built-in loader for that CDN. We recommend switching to use ` + `the built-in by calling \`provide${builtInLoaderName}Loader()\` ` + `in your \`providers\` and passing it your instance's base URL. ` + `If you don't want to use the built-in loader, define a custom ` + `loader function using IMAGE_LOADER to silence this warning.`));
1955
1290
  }
1291
+ }
1956
1292
  }
1957
- /**
1958
- * Warns if ngSrcset is present and no loader is configured (i.e. the default one is being used).
1959
- */
1960
1293
  function assertNoNgSrcsetWithoutLoader(dir, imageLoader) {
1961
- if (dir.ngSrcset && imageLoader === noopImageLoader) {
1962
- console.warn(_formatRuntimeError(2963 /* RuntimeErrorCode.MISSING_NECESSARY_LOADER */, `${imgDirectiveDetails(dir.ngSrc)} the \`ngSrcset\` attribute is present but ` +
1963
- `no image loader is configured (i.e. the default one is being used), ` +
1964
- `which would result in the same image being used for all configured sizes. ` +
1965
- `To fix this, provide a loader or remove the \`ngSrcset\` attribute from the image.`));
1966
- }
1294
+ if (dir.ngSrcset && imageLoader === noopImageLoader) {
1295
+ console.warn(_formatRuntimeError(2963, `${imgDirectiveDetails(dir.ngSrc)} the \`ngSrcset\` attribute is present but ` + `no image loader is configured (i.e. the default one is being used), ` + `which would result in the same image being used for all configured sizes. ` + `To fix this, provide a loader or remove the \`ngSrcset\` attribute from the image.`));
1296
+ }
1967
1297
  }
1968
- /**
1969
- * Warns if loaderParams is present and no loader is configured (i.e. the default one is being
1970
- * used).
1971
- */
1972
1298
  function assertNoLoaderParamsWithoutLoader(dir, imageLoader) {
1973
- if (dir.loaderParams && imageLoader === noopImageLoader) {
1974
- console.warn(_formatRuntimeError(2963 /* RuntimeErrorCode.MISSING_NECESSARY_LOADER */, `${imgDirectiveDetails(dir.ngSrc)} the \`loaderParams\` attribute is present but ` +
1975
- `no image loader is configured (i.e. the default one is being used), ` +
1976
- `which means that the loaderParams data will not be consumed and will not affect the URL. ` +
1977
- `To fix this, provide a custom loader or remove the \`loaderParams\` attribute from the image.`));
1978
- }
1299
+ if (dir.loaderParams && imageLoader === noopImageLoader) {
1300
+ console.warn(_formatRuntimeError(2963, `${imgDirectiveDetails(dir.ngSrc)} the \`loaderParams\` attribute is present but ` + `no image loader is configured (i.e. the default one is being used), ` + `which means that the loaderParams data will not be consumed and will not affect the URL. ` + `To fix this, provide a custom loader or remove the \`loaderParams\` attribute from the image.`));
1301
+ }
1979
1302
  }
1980
- /**
1981
- * Warns if the priority attribute is used too often on page load
1982
- */
1983
1303
  async function assetPriorityCountBelowThreshold(appRef) {
1984
- if (IMGS_WITH_PRIORITY_ATTR_COUNT === 0) {
1985
- IMGS_WITH_PRIORITY_ATTR_COUNT++;
1986
- await appRef.whenStable();
1987
- if (IMGS_WITH_PRIORITY_ATTR_COUNT > PRIORITY_COUNT_THRESHOLD) {
1988
- console.warn(_formatRuntimeError(2966 /* RuntimeErrorCode.TOO_MANY_PRIORITY_ATTRIBUTES */, `NgOptimizedImage: The "priority" attribute is set to true more than ${PRIORITY_COUNT_THRESHOLD} times (${IMGS_WITH_PRIORITY_ATTR_COUNT} times). ` +
1989
- `Marking too many images as "high" priority can hurt your application's LCP (https://web.dev/lcp). ` +
1990
- `"Priority" should only be set on the image expected to be the page's LCP element.`));
1991
- }
1992
- }
1993
- else {
1994
- IMGS_WITH_PRIORITY_ATTR_COUNT++;
1304
+ if (IMGS_WITH_PRIORITY_ATTR_COUNT === 0) {
1305
+ IMGS_WITH_PRIORITY_ATTR_COUNT++;
1306
+ await appRef.whenStable();
1307
+ if (IMGS_WITH_PRIORITY_ATTR_COUNT > PRIORITY_COUNT_THRESHOLD) {
1308
+ console.warn(_formatRuntimeError(2966, `NgOptimizedImage: The "priority" attribute is set to true more than ${PRIORITY_COUNT_THRESHOLD} times (${IMGS_WITH_PRIORITY_ATTR_COUNT} times). ` + `Marking too many images as "high" priority can hurt your application's LCP (https://web.dev/lcp). ` + `"Priority" should only be set on the image expected to be the page's LCP element.`));
1995
1309
  }
1310
+ } else {
1311
+ IMGS_WITH_PRIORITY_ATTR_COUNT++;
1312
+ }
1996
1313
  }
1997
- /**
1998
- * Warns if placeholder's dimension are over a threshold.
1999
- *
2000
- * This assert function is meant to only run on the browser.
2001
- */
2002
1314
  function assertPlaceholderDimensions(dir, imgElement) {
2003
- const computedStyle = window.getComputedStyle(imgElement);
2004
- let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));
2005
- let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));
2006
- if (renderedWidth > PLACEHOLDER_DIMENSION_LIMIT || renderedHeight > PLACEHOLDER_DIMENSION_LIMIT) {
2007
- console.warn(_formatRuntimeError(2967 /* RuntimeErrorCode.PLACEHOLDER_DIMENSION_LIMIT_EXCEEDED */, `${imgDirectiveDetails(dir.ngSrc)} it uses a placeholder image, but at least one ` +
2008
- `of the dimensions attribute (height or width) exceeds the limit of ${PLACEHOLDER_DIMENSION_LIMIT}px. ` +
2009
- `To fix this, use a smaller image as a placeholder.`));
2010
- }
1315
+ const computedStyle = window.getComputedStyle(imgElement);
1316
+ let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));
1317
+ let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));
1318
+ if (renderedWidth > PLACEHOLDER_DIMENSION_LIMIT || renderedHeight > PLACEHOLDER_DIMENSION_LIMIT) {
1319
+ console.warn(_formatRuntimeError(2967, `${imgDirectiveDetails(dir.ngSrc)} it uses a placeholder image, but at least one ` + `of the dimensions attribute (height or width) exceeds the limit of ${PLACEHOLDER_DIMENSION_LIMIT}px. ` + `To fix this, use a smaller image as a placeholder.`));
1320
+ }
2011
1321
  }
2012
1322
  function callOnLoadIfImageIsLoaded(img, callback) {
2013
- // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-complete
2014
- // The spec defines that `complete` is truthy once its request state is fully available.
2015
- // The image may already be available if it’s loaded from the browser cache.
2016
- // In that case, the `load` event will not fire at all, meaning that all setup
2017
- // callbacks listening for the `load` event will not be invoked.
2018
- // In Safari, there is a known behavior where the `complete` property of an
2019
- // `HTMLImageElement` may sometimes return `true` even when the image is not fully loaded.
2020
- // Checking both `img.complete` and `img.naturalWidth` is the most reliable way to
2021
- // determine if an image has been fully loaded, especially in browsers where the
2022
- // `complete` property may return `true` prematurely.
2023
- if (img.complete && img.naturalWidth) {
2024
- callback();
2025
- }
1323
+ if (img.complete && img.naturalWidth) {
1324
+ callback();
1325
+ }
2026
1326
  }
2027
1327
  function round(input) {
2028
- return Number.isInteger(input) ? input : input.toFixed(2);
1328
+ return Number.isInteger(input) ? input : input.toFixed(2);
2029
1329
  }
2030
- // Transform function to handle SafeValue input for ngSrc. This doesn't do any sanitization,
2031
- // as that is not needed for img.src and img.srcset. This transform is purely for compatibility.
2032
1330
  function unwrapSafeUrl(value) {
2033
- if (typeof value === 'string') {
2034
- return value;
2035
- }
2036
- return _unwrapSafeValue(value);
1331
+ if (typeof value === 'string') {
1332
+ return value;
1333
+ }
1334
+ return _unwrapSafeValue(value);
2037
1335
  }
2038
- // Transform function to handle inputs which may be booleans, strings, or string representations
2039
- // of boolean values. Used for the placeholder attribute.
2040
1336
  function booleanOrUrlAttribute(value) {
2041
- if (typeof value === 'string' && value !== 'true' && value !== 'false' && value !== '') {
2042
- return value;
2043
- }
2044
- return booleanAttribute(value);
1337
+ if (typeof value === 'string' && value !== 'true' && value !== 'false' && value !== '') {
1338
+ return value;
1339
+ }
1340
+ return booleanAttribute(value);
2045
1341
  }
2046
1342
 
2047
- export { IMAGE_LOADER, NgOptimizedImage, PRECONNECT_CHECK_BLOCKLIST, VERSION, ViewportScroller, isPlatformBrowser, isPlatformServer, provideCloudflareLoader, provideCloudinaryLoader, provideImageKitLoader, provideImgixLoader, provideNetlifyLoader, registerLocaleData, NullViewportScroller as ɵNullViewportScroller, PLATFORM_BROWSER_ID as ɵPLATFORM_BROWSER_ID, PLATFORM_SERVER_ID as ɵPLATFORM_SERVER_ID };
1343
+ export { IMAGE_LOADER, Location, LocationStrategy, NgOptimizedImage, PRECONNECT_CHECK_BLOCKLIST, PlatformNavigation, VERSION, ViewportScroller, isPlatformBrowser, isPlatformServer, provideCloudflareLoader, provideCloudinaryLoader, provideImageKitLoader, provideImgixLoader, provideNetlifyLoader, registerLocaleData, NavigationAdapterForLocation as ɵNavigationAdapterForLocation, NullViewportScroller as ɵNullViewportScroller, PLATFORM_BROWSER_ID as ɵPLATFORM_BROWSER_ID, PLATFORM_SERVER_ID as ɵPLATFORM_SERVER_ID, normalizeQueryParams as ɵnormalizeQueryParams };
2048
1344
  //# sourceMappingURL=common.mjs.map