@angular/common
Version:
Angular - commonly needed directives and services
1,206 lines (1,186 loc) • 90.8 kB
JavaScript
/**
* @license Angular v19.2.12
* (c) 2010-2025 Google LLC. https://angular.io/
* License: MIT
*/
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-Dx7dWex5.mjs';
import * as i0 from '@angular/core';
import { ɵregisterLocaleData as _registerLocaleData, Version, ɵɵdefineInjectable as __defineInjectable, inject, InjectionToken, ɵRuntimeError as _RuntimeError, ɵformatRuntimeError as _formatRuntimeError, PLATFORM_ID, Injectable, ɵIMAGE_CONFIG as _IMAGE_CONFIG, Renderer2, ElementRef, Injector, DestroyRef, ɵperformanceMarkFeature as _performanceMarkFeature, NgZone, ApplicationRef, booleanAttribute, numberAttribute, ChangeDetectorRef, ɵIMAGE_CONFIG_DEFAULTS as _IMAGE_CONFIG_DEFAULTS, ɵunwrapSafeValue as _unwrapSafeValue, Input, Directive } from '@angular/core';
export { ɵIMAGE_CONFIG as IMAGE_CONFIG } from '@angular/core';
import { isPlatformBrowser } from './xhr-BfNfxNDv.mjs';
export { XhrFactory, isPlatformServer, PLATFORM_BROWSER_ID as ɵPLATFORM_BROWSER_ID, PLATFORM_SERVER_ID as ɵPLATFORM_SERVER_ID, parseCookieValue as ɵparseCookieValue } from './xhr-BfNfxNDv.mjs';
import { DOCUMENT } from './dom_tokens-rA0ACyx7.mjs';
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-Dq4mJT-A.mjs';
export { PlatformNavigation as ɵPlatformNavigation } from './platform_navigation-B45Jeakb.mjs';
import 'rxjs';
/**
* Register global data to be used internally by Angular. See the
* ["I18n guide"](guide/i18n/format-data-locale) to know how to import additional locale
* data.
*
* The signature registerLocaleData(data: any, extraData?: any) is deprecated since v5.1
*
* @publicApi
*/
function registerLocaleData(data, localeId, extraData) {
return _registerLocaleData(data, localeId, extraData);
}
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* @publicApi
*/
const VERSION = new Version('19.2.12');
/**
* Defines a scroll position manager. Implemented by `BrowserViewportScroller`.
*
* @publicApi
*/
class ViewportScroller {
// De-sugared tree-shakable injection
// See #23917
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ __defineInjectable({
token: ViewportScroller,
providedIn: 'root',
factory: () => typeof ngServerMode !== 'undefined' && ngServerMode
? new NullViewportScroller()
: new BrowserViewportScroller(inject(DOCUMENT), window),
});
}
/**
* Manages the scroll position for a browser window.
*/
class BrowserViewportScroller {
document;
window;
offset = () => [0, 0];
constructor(document, window) {
this.document = document;
this.window = window;
}
/**
* Configures the top offset used when scrolling to an anchor.
* @param offset A position in screen coordinates (a tuple with x and y values)
* or a function that returns the top offset position.
*
*/
setOffset(offset) {
if (Array.isArray(offset)) {
this.offset = () => offset;
}
else {
this.offset = offset;
}
}
/**
* Retrieves the current scroll position.
* @returns The position in screen coordinates.
*/
getScrollPosition() {
return [this.window.scrollX, this.window.scrollY];
}
/**
* Sets the scroll position.
* @param position The new position in screen coordinates.
*/
scrollToPosition(position) {
this.window.scrollTo(position[0], position[1]);
}
/**
* Scrolls to an element and attempts to focus the element.
*
* Note that the function name here is misleading in that the target string may be an ID for a
* non-anchor element.
*
* @param target The ID of an element or name of the anchor.
*
* @see https://html.spec.whatwg.org/#the-indicated-part-of-the-document
* @see https://html.spec.whatwg.org/#scroll-to-fragid
*/
scrollToAnchor(target) {
const elSelected = findAnchorFromDocument(this.document, target);
if (elSelected) {
this.scrollToElement(elSelected);
// After scrolling to the element, the spec dictates that we follow the focus steps for the
// target. Rather than following the robust steps, simply attempt focus.
//
// @see https://html.spec.whatwg.org/#get-the-focusable-area
// @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus
// @see https://html.spec.whatwg.org/#focusable-area
elSelected.focus();
}
}
/**
* Disables automatic scroll restoration provided by the browser.
*/
setHistoryScrollRestoration(scrollRestoration) {
this.window.history.scrollRestoration = scrollRestoration;
}
/**
* Scrolls to an element using the native offset and the specified offset set on this scroller.
*
* The offset can be used when we know that there is a floating header and scrolling naively to an
* element (ex: `scrollIntoView`) leaves the element hidden behind the floating header.
*/
scrollToElement(el) {
const rect = el.getBoundingClientRect();
const left = rect.left + this.window.pageXOffset;
const top = rect.top + this.window.pageYOffset;
const offset = this.offset();
this.window.scrollTo(left - offset[0], top - offset[1]);
}
}
function findAnchorFromDocument(document, target) {
const documentResult = document.getElementById(target) || document.getElementsByName(target)[0];
if (documentResult) {
return documentResult;
}
// `getElementById` and `getElementsByName` won't pierce through the shadow DOM so we
// have to traverse the DOM manually and do the lookup through the shadow roots.
if (typeof document.createTreeWalker === 'function' &&
document.body &&
typeof document.body.attachShadow === 'function') {
const treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
let currentNode = treeWalker.currentNode;
while (currentNode) {
const shadowRoot = currentNode.shadowRoot;
if (shadowRoot) {
// Note that `ShadowRoot` doesn't support `getElementsByName`
// so we have to fall back to `querySelector`.
const result = shadowRoot.getElementById(target) || shadowRoot.querySelector(`[name="${target}"]`);
if (result) {
return result;
}
}
currentNode = treeWalker.nextNode();
}
}
return null;
}
/**
* Provides an empty implementation of the viewport scroller.
*/
class NullViewportScroller {
/**
* Empty implementation
*/
setOffset(offset) { }
/**
* Empty implementation
*/
getScrollPosition() {
return [0, 0];
}
/**
* Empty implementation
*/
scrollToPosition(position) { }
/**
* Empty implementation
*/
scrollToAnchor(anchor) { }
/**
* Empty implementation
*/
setHistoryScrollRestoration(scrollRestoration) { }
}
/**
* Value (out of 100) of the requested quality for placeholder images.
*/
const PLACEHOLDER_QUALITY = '20';
// Converts a string that represents a URL into a URL class instance.
function getUrl(src, win) {
// Don't use a base URL is the URL is absolute.
return isAbsoluteUrl(src) ? new URL(src) : new URL(src, win.location.href);
}
// Checks whether a URL is absolute (i.e. starts with `http://` or `https://`).
function isAbsoluteUrl(src) {
return /^https?:\/\//.test(src);
}
// Given a URL, extract the hostname part.
// If a URL is a relative one - the URL is returned as is.
function extractHostname(url) {
return isAbsoluteUrl(url) ? new URL(url).hostname : url;
}
function isValidPath(path) {
const isString = typeof path === 'string';
if (!isString || path.trim() === '') {
return false;
}
// Calling new URL() will throw if the path string is malformed
try {
const url = new URL(path);
return true;
}
catch {
return false;
}
}
function normalizePath(path) {
return path.endsWith('/') ? path.slice(0, -1) : path;
}
function normalizeSrc(src) {
return src.startsWith('/') ? src.slice(1) : src;
}
/**
* Noop image loader that does no transformation to the original src and just returns it as is.
* This loader is used as a default one if more specific logic is not provided in an app config.
*
* @see {@link ImageLoader}
* @see {@link NgOptimizedImage}
*/
const noopImageLoader = (config) => config.src;
/**
* Injection token that configures the image loader function.
*
* @see {@link ImageLoader}
* @see {@link NgOptimizedImage}
* @publicApi
*/
const IMAGE_LOADER = new InjectionToken(ngDevMode ? 'ImageLoader' : '', {
providedIn: 'root',
factory: () => noopImageLoader,
});
/**
* Internal helper function that makes it easier to introduce custom image loaders for the
* `NgOptimizedImage` directive. It is enough to specify a URL builder function to obtain full DI
* configuration for a given loader: a DI token corresponding to the actual loader function, plus DI
* tokens managing preconnect check functionality.
* @param buildUrlFn a function returning a full URL based on loader's configuration
* @param exampleUrls example of full URLs for a given loader (used in error messages)
* @returns a set of DI providers corresponding to the configured image loader
*/
function createImageLoader(buildUrlFn, exampleUrls) {
return function provideImageLoader(path) {
if (!isValidPath(path)) {
throwInvalidPathError(path, exampleUrls || []);
}
// The trailing / is stripped (if provided) to make URL construction (concatenation) easier in
// the individual loader functions.
path = normalizePath(path);
const loaderFn = (config) => {
if (isAbsoluteUrl(config.src)) {
// Image loader functions expect an image file name (e.g. `my-image.png`)
// or a relative path + a file name (e.g. `/a/b/c/my-image.png`) as an input,
// so the final absolute URL can be constructed.
// When an absolute URL is provided instead - the loader can not
// build a final URL, thus the error is thrown to indicate that.
throwUnexpectedAbsoluteUrlError(path, config.src);
}
return buildUrlFn(path, { ...config, src: normalizeSrc(config.src) });
};
const providers = [{ provide: IMAGE_LOADER, useValue: loaderFn }];
return providers;
};
}
function throwInvalidPathError(path, exampleUrls) {
throw new _RuntimeError(2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, ngDevMode &&
`Image loader has detected an invalid path (\`${path}\`). ` +
`To fix this, supply a path using one of the following formats: ${exampleUrls.join(' or ')}`);
}
function throwUnexpectedAbsoluteUrlError(path, url) {
throw new _RuntimeError(2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, 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}\`).`);
}
/**
* Function that generates an ImageLoader for [Cloudflare Image
* Resizing](https://developers.cloudflare.com/images/image-resizing/) and turns it into an Angular
* provider. Note: Cloudflare has multiple image products - this provider is specifically for
* Cloudflare Image Resizing; it will not work with Cloudflare Images or Cloudflare Polish.
*
* @param path Your domain name, e.g. https://mysite.com
* @returns Provider that provides an ImageLoader function
*
* @publicApi
*/
const provideCloudflareLoader = createImageLoader(createCloudflareUrl, ngDevMode ? ['https://<ZONE>/cdn-cgi/image/<OPTIONS>/<SOURCE-IMAGE>'] : undefined);
function createCloudflareUrl(path, config) {
let params = `format=auto`;
if (config.width) {
params += `,width=${config.width}`;
}
// When requesting a placeholder image we ask for a low quality image to reduce the load time.
if (config.isPlaceholder) {
params += `,quality=${PLACEHOLDER_QUALITY}`;
}
// Cloudflare image URLs format:
// https://developers.cloudflare.com/images/image-resizing/url-format/
return `${path}/cdn-cgi/image/${params}/${config.src}`;
}
/**
* Name and URL tester for Cloudinary.
*/
const cloudinaryLoaderInfo = {
name: 'Cloudinary',
testUrl: isCloudinaryUrl,
};
const CLOUDINARY_LOADER_REGEX = /https?\:\/\/[^\/]+\.cloudinary\.com\/.+/;
/**
* Tests whether a URL is from Cloudinary CDN.
*/
function isCloudinaryUrl(url) {
return CLOUDINARY_LOADER_REGEX.test(url);
}
/**
* Function that generates an ImageLoader for Cloudinary and turns it into an Angular provider.
*
* @param path Base URL of your Cloudinary images
* This URL should match one of the following formats:
* https://res.cloudinary.com/mysite
* https://mysite.cloudinary.com
* https://subdomain.mysite.com
* @returns Set of providers to configure the Cloudinary loader.
*
* @publicApi
*/
const provideCloudinaryLoader = createImageLoader(createCloudinaryUrl, ngDevMode
? [
'https://res.cloudinary.com/mysite',
'https://mysite.cloudinary.com',
'https://subdomain.mysite.com',
]
: undefined);
function createCloudinaryUrl(path, config) {
// Cloudinary image URLformat:
// https://cloudinary.com/documentation/image_transformations#transformation_url_structure
// Example of a Cloudinary image URL:
// https://res.cloudinary.com/mysite/image/upload/c_scale,f_auto,q_auto,w_600/marketing/tile-topics-m.png
// For a placeholder image, we use the lowest image setting available to reduce the load time
// else we use the auto size
const quality = config.isPlaceholder ? 'q_auto:low' : 'q_auto';
let params = `f_auto,${quality}`;
if (config.width) {
params += `,w_${config.width}`;
}
if (config.loaderParams?.['rounded']) {
params += `,r_max`;
}
return `${path}/image/upload/${params}/${config.src}`;
}
/**
* Name and URL tester for ImageKit.
*/
const imageKitLoaderInfo = {
name: 'ImageKit',
testUrl: isImageKitUrl,
};
const IMAGE_KIT_LOADER_REGEX = /https?\:\/\/[^\/]+\.imagekit\.io\/.+/;
/**
* Tests whether a URL is from ImageKit CDN.
*/
function isImageKitUrl(url) {
return IMAGE_KIT_LOADER_REGEX.test(url);
}
/**
* Function that generates an ImageLoader for ImageKit and turns it into an Angular provider.
*
* @param path Base URL of your ImageKit images
* This URL should match one of the following formats:
* https://ik.imagekit.io/myaccount
* https://subdomain.mysite.com
* @returns Set of providers to configure the ImageKit loader.
*
* @publicApi
*/
const provideImageKitLoader = createImageLoader(createImagekitUrl, ngDevMode ? ['https://ik.imagekit.io/mysite', 'https://subdomain.mysite.com'] : undefined);
function createImagekitUrl(path, config) {
// Example of an ImageKit image URL:
// https://ik.imagekit.io/demo/tr:w-300,h-300/medium_cafe_B1iTdD0C.jpg
const { src, width } = config;
const params = [];
if (width) {
params.push(`w-${width}`);
}
// When requesting a placeholder image we ask for a low quality image to reduce the load time.
if (config.isPlaceholder) {
params.push(`q-${PLACEHOLDER_QUALITY}`);
}
const urlSegments = params.length ? [path, `tr:${params.join(',')}`, src] : [path, src];
const url = new URL(urlSegments.join('/'));
return url.href;
}
/**
* Name and URL tester for Imgix.
*/
const imgixLoaderInfo = {
name: 'Imgix',
testUrl: isImgixUrl,
};
const IMGIX_LOADER_REGEX = /https?\:\/\/[^\/]+\.imgix\.net\/.+/;
/**
* Tests whether a URL is from Imgix CDN.
*/
function isImgixUrl(url) {
return IMGIX_LOADER_REGEX.test(url);
}
/**
* Function that generates an ImageLoader for Imgix and turns it into an Angular provider.
*
* @param path path to the desired Imgix origin,
* e.g. https://somepath.imgix.net or https://images.mysite.com
* @returns Set of providers to configure the Imgix loader.
*
* @publicApi
*/
const provideImgixLoader = createImageLoader(createImgixUrl, ngDevMode ? ['https://somepath.imgix.net/'] : undefined);
function createImgixUrl(path, config) {
const url = new URL(`${path}/${config.src}`);
// This setting ensures the smallest allowable format is set.
url.searchParams.set('auto', 'format');
if (config.width) {
url.searchParams.set('w', config.width.toString());
}
// When requesting a placeholder image we ask a low quality image to reduce the load time.
if (config.isPlaceholder) {
url.searchParams.set('q', PLACEHOLDER_QUALITY);
}
return url.href;
}
/**
* Name and URL tester for Netlify.
*/
const netlifyLoaderInfo = {
name: 'Netlify',
testUrl: isNetlifyUrl,
};
const NETLIFY_LOADER_REGEX = /https?\:\/\/[^\/]+\.netlify\.app\/.+/;
/**
* Tests whether a URL is from a Netlify site. This won't catch sites with a custom domain,
* but it's a good start for sites in development. This is only used to warn users who haven't
* configured an image loader.
*/
function isNetlifyUrl(url) {
return NETLIFY_LOADER_REGEX.test(url);
}
/**
* Function that generates an ImageLoader for Netlify and turns it into an Angular provider.
*
* @param path optional URL of the desired Netlify site. Defaults to the current site.
* @returns Set of providers to configure the Netlify loader.
*
* @publicApi
*/
function provideNetlifyLoader(path) {
if (path && !isValidPath(path)) {
throw new _RuntimeError(2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, 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.`);
}
if (path) {
const url = new URL(path);
path = url.origin;
}
const loaderFn = (config) => {
return createNetlifyUrl(config, path);
};
const providers = [{ provide: IMAGE_LOADER, useValue: loaderFn }];
return providers;
}
const validParams = new Map([
['height', 'h'],
['fit', 'fit'],
['quality', 'q'],
['q', 'q'],
['position', 'position'],
]);
function createNetlifyUrl(config, path) {
// Note: `path` can be undefined, in which case we use a fake one to construct a `URL` instance.
const url = new URL(path ?? 'https://a/');
url.pathname = '/.netlify/images';
if (!isAbsoluteUrl(config.src) && !config.src.startsWith('/')) {
config.src = '/' + config.src;
}
url.searchParams.set('url', config.src);
if (config.width) {
url.searchParams.set('w', config.width.toString());
}
// When requesting a placeholder image we ask for a low quality image to reduce the load time.
// If the quality is specified in the loader config - always use provided value.
const configQuality = config.loaderParams?.['quality'] ?? config.loaderParams?.['q'];
if (config.isPlaceholder && !configQuality) {
url.searchParams.set('q', PLACEHOLDER_QUALITY);
}
for (const [param, value] of Object.entries(config.loaderParams ?? {})) {
if (validParams.has(param)) {
url.searchParams.set(validParams.get(param), value.toString());
}
else {
if (ngDevMode) {
console.warn(_formatRuntimeError(2959 /* RuntimeErrorCode.INVALID_LOADER_ARGUMENTS */, `The Netlify image loader has detected an \`<img>\` tag with the unsupported attribute "\`${param}\`".`));
}
}
}
// The "a" hostname is used for relative URLs, so we can remove it from the final URL.
return url.hostname === 'a' ? url.href.replace(url.origin, '') : url.href;
}
// Assembles directive details string, useful for error messages.
function imgDirectiveDetails(ngSrc, includeNgSrc = true) {
const ngSrcInfo = includeNgSrc
? `(activated on an <img> element with the \`ngSrc="${ngSrc}"\`) `
: '';
return `The NgOptimizedImage directive ${ngSrcInfo}has detected that`;
}
/**
* Asserts that the application is in development mode. Throws an error if the application is in
* production mode. This assert can be used to make sure that there is no dev-mode code invoked in
* the prod mode accidentally.
*/
function assertDevMode(checkName) {
if (!ngDevMode) {
throw new _RuntimeError(2958 /* RuntimeErrorCode.UNEXPECTED_DEV_MODE_CHECK_IN_PROD_MODE */, `Unexpected invocation of the ${checkName} in the prod mode. ` +
`Please make sure that the prod mode is enabled for production builds.`);
}
}
/**
* Observer that detects whether an image with `NgOptimizedImage`
* is treated as a Largest Contentful Paint (LCP) element. If so,
* asserts that the image has the `priority` attribute.
*
* Note: this is a dev-mode only class and it does not appear in prod bundles,
* thus there is no `ngDevMode` use in the code.
*
* Based on https://web.dev/lcp/#measure-lcp-in-javascript.
*/
class LCPImageObserver {
// Map of full image URLs -> original `ngSrc` values.
images = new Map();
window = null;
observer = null;
constructor() {
const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
assertDevMode('LCP checker');
const win = inject(DOCUMENT).defaultView;
if (isBrowser && typeof PerformanceObserver !== 'undefined') {
this.window = win;
this.observer = this.initPerformanceObserver();
}
}
/**
* Inits PerformanceObserver and subscribes to LCP events.
* Based on https://web.dev/lcp/#measure-lcp-in-javascript
*/
initPerformanceObserver() {
const observer = new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
if (entries.length === 0)
return;
// We use the latest entry produced by the `PerformanceObserver` as the best
// signal on which element is actually an LCP one. As an example, the first image to load on
// a page, by virtue of being the only thing on the page so far, is often a LCP candidate
// and gets reported by PerformanceObserver, but isn't necessarily the LCP element.
const lcpElement = entries[entries.length - 1];
// Cast to `any` due to missing `element` on the `LargestContentfulPaint` type of entry.
// See https://developer.mozilla.org/en-US/docs/Web/API/LargestContentfulPaint
const imgSrc = lcpElement.element?.src ?? '';
// Exclude `data:` and `blob:` URLs, since they are not supported by the directive.
if (imgSrc.startsWith('data:') || imgSrc.startsWith('blob:'))
return;
const img = this.images.get(imgSrc);
if (!img)
return;
if (!img.priority && !img.alreadyWarnedPriority) {
img.alreadyWarnedPriority = true;
logMissingPriorityError(imgSrc);
}
if (img.modified && !img.alreadyWarnedModified) {
img.alreadyWarnedModified = true;
logModifiedWarning(imgSrc);
}
});
observer.observe({ type: 'largest-contentful-paint', buffered: true });
return observer;
}
registerImage(rewrittenSrc, originalNgSrc, isPriority) {
if (!this.observer)
return;
const newObservedImageState = {
priority: isPriority,
modified: false,
alreadyWarnedModified: false,
alreadyWarnedPriority: false,
};
this.images.set(getUrl(rewrittenSrc, this.window).href, newObservedImageState);
}
unregisterImage(rewrittenSrc) {
if (!this.observer)
return;
this.images.delete(getUrl(rewrittenSrc, this.window).href);
}
updateImage(originalSrc, newSrc) {
if (!this.observer)
return;
const originalUrl = getUrl(originalSrc, this.window).href;
const img = this.images.get(originalUrl);
if (img) {
img.modified = true;
this.images.set(getUrl(newSrc, this.window).href, img);
this.images.delete(originalUrl);
}
}
ngOnDestroy() {
if (!this.observer)
return;
this.observer.disconnect();
this.images.clear();
}
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: LCPImageObserver, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: LCPImageObserver, providedIn: 'root' });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: LCPImageObserver, decorators: [{
type: Injectable,
args: [{ providedIn: 'root' }]
}], ctorParameters: () => [] });
function logMissingPriorityError(ngSrc) {
const directiveDetails = imgDirectiveDetails(ngSrc);
console.error(_formatRuntimeError(2955 /* RuntimeErrorCode.LCP_IMG_MISSING_PRIORITY */, `${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.`));
}
function logModifiedWarning(ngSrc) {
const directiveDetails = imgDirectiveDetails(ngSrc);
console.warn(_formatRuntimeError(2964 /* RuntimeErrorCode.LCP_IMG_NGSRC_MODIFIED */, `${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.`));
}
// Set of origins that are always excluded from the preconnect checks.
const INTERNAL_PRECONNECT_CHECK_BLOCKLIST = new Set(['localhost', '127.0.0.1', '0.0.0.0']);
/**
* Injection token to configure which origins should be excluded
* from the preconnect checks. It can either be a single string or an array of strings
* to represent a group of origins, for example:
*
* ```ts
* {provide: PRECONNECT_CHECK_BLOCKLIST, useValue: 'https://your-domain.com'}
* ```
*
* or:
*
* ```ts
* {provide: PRECONNECT_CHECK_BLOCKLIST,
* useValue: ['https://your-domain-1.com', 'https://your-domain-2.com']}
* ```
*
* @publicApi
*/
const PRECONNECT_CHECK_BLOCKLIST = new InjectionToken(ngDevMode ? 'PRECONNECT_CHECK_BLOCKLIST' : '');
/**
* Contains the logic to detect whether an image, marked with the "priority" attribute
* has a corresponding `<link rel="preconnect">` tag in the `document.head`.
*
* Note: this is a dev-mode only class, which should not appear in prod bundles,
* thus there is no `ngDevMode` use in the code.
*/
class PreconnectLinkChecker {
document = inject(DOCUMENT);
/**
* Set of <link rel="preconnect"> tags found on this page.
* The `null` value indicates that there was no DOM query operation performed.
*/
preconnectLinks = null;
/*
* Keep track of all already seen origin URLs to avoid repeating the same check.
*/
alreadySeen = new Set();
window = this.document.defaultView;
blocklist = new Set(INTERNAL_PRECONNECT_CHECK_BLOCKLIST);
constructor() {
assertDevMode('preconnect link checker');
const blocklist = inject(PRECONNECT_CHECK_BLOCKLIST, { optional: true });
if (blocklist) {
this.populateBlocklist(blocklist);
}
}
populateBlocklist(origins) {
if (Array.isArray(origins)) {
deepForEach(origins, (origin) => {
this.blocklist.add(extractHostname(origin));
});
}
else {
this.blocklist.add(extractHostname(origins));
}
}
/**
* Checks that a preconnect resource hint exists in the head for the
* given src.
*
* @param rewrittenSrc src formatted with loader
* @param originalNgSrc ngSrc value
*/
assertPreconnect(rewrittenSrc, originalNgSrc) {
if (typeof ngServerMode !== 'undefined' && ngServerMode)
return;
const imgUrl = getUrl(rewrittenSrc, this.window);
if (this.blocklist.has(imgUrl.hostname) || this.alreadySeen.has(imgUrl.origin))
return;
// Register this origin as seen, so we don't check it again later.
this.alreadySeen.add(imgUrl.origin);
// Note: we query for preconnect links only *once* and cache the results
// for the entire lifespan of an application, since it's unlikely that the
// list would change frequently. This allows to make sure there are no
// performance implications of making extra DOM lookups for each image.
this.preconnectLinks ??= this.queryPreconnectLinks();
if (!this.preconnectLinks.has(imgUrl.origin)) {
console.warn(_formatRuntimeError(2956 /* RuntimeErrorCode.PRIORITY_IMG_MISSING_PRECONNECT_TAG */, `${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}">`));
}
}
queryPreconnectLinks() {
const preconnectUrls = new Set();
const links = this.document.querySelectorAll('link[rel=preconnect]');
for (const link of links) {
const url = getUrl(link.href, this.window);
preconnectUrls.add(url.origin);
}
return preconnectUrls;
}
ngOnDestroy() {
this.preconnectLinks?.clear();
this.alreadySeen.clear();
}
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: PreconnectLinkChecker, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: PreconnectLinkChecker, providedIn: 'root' });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: PreconnectLinkChecker, decorators: [{
type: Injectable,
args: [{ providedIn: 'root' }]
}], ctorParameters: () => [] });
/**
* Invokes a callback for each element in the array. Also invokes a callback
* recursively for each nested array.
*/
function deepForEach(input, fn) {
for (let value of input) {
Array.isArray(value) ? deepForEach(value, fn) : fn(value);
}
}
/**
* In SSR scenarios, a preload `<link>` element is generated for priority images.
* Having a large number of preload tags may negatively affect the performance,
* so we warn developers (by throwing an error) if the number of preloaded images
* is above a certain threshold. This const specifies this threshold.
*/
const DEFAULT_PRELOADED_IMAGES_LIMIT = 5;
/**
* Helps to keep track of priority images that already have a corresponding
* preload tag (to avoid generating multiple preload tags with the same URL).
*
* This Set tracks the original src passed into the `ngSrc` input not the src after it has been
* run through the specified `IMAGE_LOADER`.
*/
const PRELOADED_IMAGES = new InjectionToken(typeof ngDevMode === 'undefined' || ngDevMode ? 'NG_OPTIMIZED_PRELOADED_IMAGES' : '', {
providedIn: 'root',
factory: () => new Set(),
});
/**
* @description Contains the logic needed to track and add preload link tags to the `<head>` tag. It
* will also track what images have already had preload link tags added so as to not duplicate link
* tags.
*
* In dev mode this service will validate that the number of preloaded images does not exceed the
* configured default preloaded images limit: {@link DEFAULT_PRELOADED_IMAGES_LIMIT}.
*/
class PreloadLinkCreator {
preloadedImages = inject(PRELOADED_IMAGES);
document = inject(DOCUMENT);
errorShown = false;
/**
* @description Add a preload `<link>` to the `<head>` of the `index.html` that is served from the
* server while using Angular Universal and SSR to kick off image loads for high priority images.
*
* The `sizes` (passed in from the user) and `srcset` (parsed and formatted from `ngSrcset`)
* properties used to set the corresponding attributes, `imagesizes` and `imagesrcset`
* respectively, on the preload `<link>` tag so that the correctly sized image is preloaded from
* the CDN.
*
* {@link https://web.dev/preload-responsive-images/#imagesrcset-and-imagesizes}
*
* @param renderer The `Renderer2` passed in from the directive
* @param src The original src of the image that is set on the `ngSrc` input.
* @param srcset The parsed and formatted srcset created from the `ngSrcset` input
* @param sizes The value of the `sizes` attribute passed in to the `<img>` tag
*/
createPreloadLinkTag(renderer, src, srcset, sizes) {
if (ngDevMode &&
!this.errorShown &&
this.preloadedImages.size >= DEFAULT_PRELOADED_IMAGES_LIMIT) {
this.errorShown = true;
console.warn(_formatRuntimeError(2961 /* RuntimeErrorCode.TOO_MANY_PRELOADED_IMAGES */, `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.`));
}
if (this.preloadedImages.has(src)) {
return;
}
this.preloadedImages.add(src);
const preload = renderer.createElement('link');
renderer.setAttribute(preload, 'as', 'image');
renderer.setAttribute(preload, 'href', src);
renderer.setAttribute(preload, 'rel', 'preload');
renderer.setAttribute(preload, 'fetchpriority', 'high');
if (sizes) {
renderer.setAttribute(preload, 'imageSizes', sizes);
}
if (srcset) {
renderer.setAttribute(preload, 'imageSrcset', srcset);
}
renderer.appendChild(this.document.head, preload);
}
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: PreloadLinkCreator, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: PreloadLinkCreator, providedIn: 'root' });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: PreloadLinkCreator, decorators: [{
type: Injectable,
args: [{ providedIn: 'root' }]
}] });
/**
* When a Base64-encoded image is passed as an input to the `NgOptimizedImage` directive,
* an error is thrown. The image content (as a string) might be very long, thus making
* it hard to read an error message if the entire string is included. This const defines
* the number of characters that should be included into the error message. The rest
* of the content is truncated.
*/
const BASE64_IMG_MAX_LENGTH_IN_ERROR = 50;
/**
* RegExpr to determine whether a src in a srcset is using width descriptors.
* Should match something like: "100w, 200w".
*/
const VALID_WIDTH_DESCRIPTOR_SRCSET = /^((\s*\d+w\s*(,|$)){1,})$/;
/**
* RegExpr to determine whether a src in a srcset is using density descriptors.
* Should match something like: "1x, 2x, 50x". Also supports decimals like "1.5x, 1.50x".
*/
const VALID_DENSITY_DESCRIPTOR_SRCSET = /^((\s*\d+(\.\d+)?x\s*(,|$)){1,})$/;
/**
* Srcset values with a density descriptor higher than this value will actively
* throw an error. Such densities are not permitted as they cause image sizes
* to be unreasonably large and slow down LCP.
*/
const ABSOLUTE_SRCSET_DENSITY_CAP = 3;
/**
* Used only in error message text to communicate best practices, as we will
* only throw based on the slightly more conservative ABSOLUTE_SRCSET_DENSITY_CAP.
*/
const RECOMMENDED_SRCSET_DENSITY_CAP = 2;
/**
* Used in generating automatic density-based srcsets
*/
const DENSITY_SRCSET_MULTIPLIERS = [1, 2];
/**
* Used to determine which breakpoints to use on full-width images
*/
const VIEWPORT_BREAKPOINT_CUTOFF = 640;
/**
* Used to determine whether two aspect ratios are similar in value.
*/
const ASPECT_RATIO_TOLERANCE = 0.1;
/**
* Used to determine whether the image has been requested at an overly
* large size compared to the actual rendered image size (after taking
* into account a typical device pixel ratio). In pixels.
*/
const OVERSIZED_IMAGE_TOLERANCE = 1000;
/**
* Used to limit automatic srcset generation of very large sources for
* fixed-size images. In pixels.
*/
const FIXED_SRCSET_WIDTH_LIMIT = 1920;
const FIXED_SRCSET_HEIGHT_LIMIT = 1080;
/**
* Default blur radius of the CSS filter used on placeholder images, in pixels
*/
const PLACEHOLDER_BLUR_AMOUNT = 15;
/**
* Placeholder dimension (height or width) limit in pixels. Angular produces a warning
* when this limit is crossed.
*/
const PLACEHOLDER_DIMENSION_LIMIT = 1000;
/**
* Used to warn or error when the user provides an overly large dataURL for the placeholder
* attribute.
* Character count of Base64 images is 1 character per byte, and base64 encoding is approximately
* 33% larger than base images, so 4000 characters is around 3KB on disk and 10000 characters is
* around 7.7KB. Experimentally, 4000 characters is about 20x20px in PNG or medium-quality JPEG
* format, and 10,000 is around 50x50px, but there's quite a bit of variation depending on how the
* image is saved.
*/
const DATA_URL_WARN_LIMIT = 4000;
const DATA_URL_ERROR_LIMIT = 10000;
/** Info about built-in loaders we can test for. */
const BUILT_IN_LOADERS = [
imgixLoaderInfo,
imageKitLoaderInfo,
cloudinaryLoaderInfo,
netlifyLoaderInfo,
];
/**
* Threshold for the PRIORITY_TRUE_COUNT
*/
const PRIORITY_COUNT_THRESHOLD = 10;
/**
* This count is used to log a devMode warning
* when the count of directive instances with priority=true
* exceeds the threshold PRIORITY_COUNT_THRESHOLD
*/
let IMGS_WITH_PRIORITY_ATTR_COUNT = 0;
/**
* Directive that improves image loading performance by enforcing best practices.
*
* `NgOptimizedImage` ensures that the loading of the Largest Contentful Paint (LCP) image is
* prioritized by:
* - Automatically setting the `fetchpriority` attribute on the `<img>` tag
* - Lazy loading non-priority images by default
* - Automatically generating a preconnect link tag in the document head
*
* In addition, the directive:
* - Generates appropriate asset URLs if a corresponding `ImageLoader` function is provided
* - Automatically generates a srcset
* - Requires that `width` and `height` are set
* - Warns if `width` or `height` have been set incorrectly
* - Warns if the image will be visually distorted when rendered
*
* @usageNotes
* The `NgOptimizedImage` directive is marked as [standalone](guide/components/importing) and can
* be imported directly.
*
* Follow the steps below to enable and use the directive:
* 1. Import it into the necessary NgModule or a standalone Component.
* 2. Optionally provide an `ImageLoader` if you use an image hosting service.
* 3. Update the necessary `<img>` tags in templates and replace `src` attributes with `ngSrc`.
* Using a `ngSrc` allows the directive to control when the `src` gets set, which triggers an image
* download.
*
* Step 1: import the `NgOptimizedImage` directive.
*
* ```ts
* import { NgOptimizedImage } from '@angular/common';
*
* // Include it into the necessary NgModule
* @NgModule({
* imports: [NgOptimizedImage],
* })
* class AppModule {}
*
* // ... or a standalone Component
* @Component({
* imports: [NgOptimizedImage],
* })
* class MyStandaloneComponent {}
* ```
*
* Step 2: configure a loader.
*
* To use the **default loader**: no additional code changes are necessary. The URL returned by the
* generic loader will always match the value of "src". In other words, this loader applies no
* transformations to the resource URL and the value of the `ngSrc` attribute will be used as is.
*
* To use an existing loader for a **third-party image service**: add the provider factory for your
* chosen service to the `providers` array. In the example below, the Imgix loader is used:
*
* ```ts
* import {provideImgixLoader} from '@angular/common';
*
* // Call the function and add the result to the `providers` array:
* providers: [
* provideImgixLoader("https://my.base.url/"),
* ],
* ```
*
* The `NgOptimizedImage` directive provides the following functions:
* - `provideCloudflareLoader`
* - `provideCloudinaryLoader`
* - `provideImageKitLoader`
* - `provideImgixLoader`
*
* If you use a different image provider, you can create a custom loader function as described
* below.
*
* To use a **custom loader**: provide your loader function as a value for the `IMAGE_LOADER` DI
* token.
*
* ```ts
* import {IMAGE_LOADER, ImageLoaderConfig} from '@angular/common';
*
* // Configure the loader using the `IMAGE_LOADER` token.
* providers: [
* {
* provide: IMAGE_LOADER,
* useValue: (config: ImageLoaderConfig) => {
* return `https://example.com/${config.src}-${config.width}.jpg`;
* }
* },
* ],
* ```
*
* Step 3: update `<img>` tags in templates to use `ngSrc` instead of `src`.
*
* ```html
* <img ngSrc="logo.png" width="200" height="100">
* ```
*
* @publicApi
*/
class NgOptimizedImage {
imageLoader = inject(IMAGE_LOADER);
config = processConfig(inject(_IMAGE_CONFIG));
renderer = inject(Renderer2);
imgElement = inject(ElementRef).nativeElement;
injector = inject(Injector);
// An LCP image observer should be injected only in development mode.
// Do not assign it to `null` to avoid having a redundant property in the production bundle.
lcpObserver;
/**
* Calculate the rewritten `src` once and store it.
* This is needed to avoid repetitive calculations and make sure the directive cleanup in the
* `ngOnDestroy` does not rely on the `IMAGE_LOADER` logic (which in turn can rely on some other
* instance that might be already destroyed).
*/
_renderedSrc = null;
/**
* Name of the source image.
* Image name will be processed by the image loader and the final URL will be applied as the `src`
* property of the image.
*/
ngSrc;
/**
* A comma separated list of width or density descriptors.
* The image name will be taken from `ngSrc` and combined with the list of width or density
* descriptors to generate the final `srcset` property of the image.
*
* Example:
* ```html
* <img ngSrc="hello.jpg" ngSrcset="100w, 200w" /> =>
* <img src="path/hello.jpg" srcset="path/hello.jpg?w=100 100w, path/hello.jpg?w=200 200w" />
* ```
*/
ngSrcset;
/**
* The base `sizes` attribute passed through to the `<img>` element.
* Providing sizes causes the image to create an automatic responsive srcset.
*/
sizes;
/**
* For responsive images: the intrinsic width of the image in pixels.
* For fixed size images: the desired rendered width of the image in pixels.
*/
width;
/**
* For responsive images: the intrinsic height of the image in pixels.
* For fixed size images: the desired rendered height of the image in pixels.
*/
height;
/**
* The desired loading behavior (lazy, eager, or auto). Defaults to `lazy`,
* which is recommended for most images.
*
* Warning: Setting images as loading="eager" or loading="auto" marks them
* as non-priority images and can hurt loading performance. For images which
* may be the LCP element, use the `priority` attribute instead of `loading`.
*/
loading;
/**
* Indicates whether this image should have a high priority.
*/
priority = false;
/**
* Data to pass through to custom loaders.
*/
loaderParams;
/**
* Disables automatic srcset generation for this image.
*/
disableOptimizedSrcset = false;
/**
* Sets the image to "fill mode", which eliminates the height/width requirement and adds
* styles such that the image fills its containing element.
*/
fill = false;
/**
* A URL or data URL for an image to be used as a placeholder while this image loads.
*/
placeholder;
/**
* Configuration object for placeholder settings. Options:
* * blur: Setting this to false disables the automatic CSS blur.
*/
placeholderConfig;
/**
* Value of the `src` attribute if set on the host `<img>` element.
* This input is exclusively read to assert that `src` is not set in conflict
* with `ngSrc` and that images don't start to load until a lazy loading strategy is set.
* @internal
*/
src;
/**
* Value of the `srcset` attribute if set on the host `<img>` element.
* This input is exclusively read to assert that `srcset` is not set in conflict
* with `ngSrcset` and that images don't start to load until a lazy loading strategy is set.
* @internal
*/
srcset;
constructor() {
if (ngDevMode) {
this.lcpObserver = this.injector.get(LCPImageObserver);
// Using `DestroyRef` to avoid having an empty `ngOnDestroy` method since this
// is only run in development mode.
const destroyRef = inject(DestroyRef);
destroyRef.onDestroy(() => {
if (!this.priority && this._renderedSrc !== null) {
this.lcpObserver.unregisterImage(this._renderedSrc);
}
});
}
}
/** @docs-private */
ngOnInit() {
_performanceMarkFeature('NgOptimizedImage');
if (ngDevMode) {
const ngZone = this.injector.get(NgZone);
assertNonEmptyInput(this, 'ngSrc', this.ngSrc);
assertValidNgSrcset(this, this.ngSrcset);
assertNoConflictingSrc(this);
if (this.ngSrcset) {
assertNoConflictingSrcset(this);
}
assertNotBase64Image(this);
assertNotBlobUrl(this);
if (this.fill) {
assertEmptyWidthAndHeight(this);
// This leaves the Angular zone to avoid triggering unnecessary change detection cycles when
// `load` tasks are invoked on images.
ngZone.runOutsideAngular(() => assertNonZeroRenderedHeight(this, this.imgElement, this.renderer));
}
else {
assertNonEmptyWidthAndHeight(this);
if (this.height !== undefined) {
assertGreaterThanZero(this, this.height, 'height');
}
if (this.width !== undefined) {
assertGreaterThanZero(this, this.width, 'width');
}
// Only check for distorted images when not in fill mode, where
// images may be intentionally stretched, cropped or letterboxed.
ngZone.runOutsideAngular(() => assertNoImageDistortion(this, this.imgElement, this.renderer));
}
assertValidLoadingInput(this);
if (!this.ngSrcset) {
assertNoComplexSizes(this);
}
assertValidPlaceholder(this, this.imageLoader);
assertNotMissingBuiltInLoader(this.ngSrc, this.imageLoader);
assertNoNgSrcsetWithoutLoader(this, this.imageLoader);
assertNoLoaderParamsWithoutLoader(this, this.imageLoader);