_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts_41789_50179
assertNonEmptyWidthAndHeight(dir: NgOptimizedImage) { let missingAttributes = []; if (dir.width === undefined) missingAttributes.push('width'); if (dir.height === undefined) missingAttributes.push('height'); if (missingAttributes.length > 0) { throw new RuntimeError( RuntimeErrorCode.REQUIRED_INPUT_MISSING, `${imgDirectiveDetails(dir.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.`, ); } } /** * Verifies that width and height are not set. Used in fill mode, where those attributes don't make * sense. */ function assertEmptyWidthAndHeight(dir: NgOptimizedImage) { if (dir.width || dir.height) { throw new RuntimeError( RuntimeErrorCode.INVALID_INPUT, `${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.`, ); } } /** * Verifies that the rendered image has a nonzero height. If the image is in fill mode, provides * guidance that this can be caused by the containing element's CSS position property. */ function assertNonZeroRenderedHeight( dir: NgOptimizedImage, img: HTMLImageElement, renderer: Renderer2, ) { const callback = () => { removeLoadListenerFn(); removeErrorListenerFn(); const renderedHeight = img.clientHeight; if (dir.fill && renderedHeight === 0) { console.warn( formatRuntimeError( RuntimeErrorCode.INVALID_INPUT, `${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.`, ), ); } }; const removeLoadListenerFn = renderer.listen(img, 'load', callback); // See comments in the `assertNoImageDistortion`. const removeErrorListenerFn = renderer.listen(img, 'error', () => { removeLoadListenerFn(); removeErrorListenerFn(); }); callOnLoadIfImageIsLoaded(img, callback); } /** * Verifies that the `loading` attribute is set to a valid input & * is not used on priority images. */ function assertValidLoadingInput(dir: NgOptimizedImage) { if (dir.loading && dir.priority) { throw new RuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails(dir.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.`, ); } const validInputs = ['auto', 'eager', 'lazy']; if (typeof dir.loading === 'string' && !validInputs.includes(dir.loading)) { throw new RuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails(dir.ngSrc)} the \`loading\` attribute ` + `has an invalid value (\`${dir.loading}\`). ` + `To fix this, provide a valid value ("lazy", "eager", or "auto").`, ); } } /** * Warns if NOT using a loader (falling back to the generic loader) and * the image appears to be hosted on one of the image CDNs for which * we do have a built-in image loader. Suggests switching to the * built-in loader. * * @param ngSrc Value of the ngSrc attribute * @param imageLoader ImageLoader provided */ function assertNotMissingBuiltInLoader(ngSrc: string, imageLoader: ImageLoader) { if (imageLoader === noopImageLoader) { let builtInLoaderName = ''; for (const loader of BUILT_IN_LOADERS) { if (loader.testUrl(ngSrc)) { builtInLoaderName = loader.name; break; } } if (builtInLoaderName) { console.warn( formatRuntimeError( RuntimeErrorCode.MISSING_BUILTIN_LOADER, `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.`, ), ); } } } /** * Warns if ngSrcset is present and no loader is configured (i.e. the default one is being used). */ function assertNoNgSrcsetWithoutLoader(dir: NgOptimizedImage, imageLoader: ImageLoader) { if (dir.ngSrcset && imageLoader === noopImageLoader) { console.warn( formatRuntimeError( RuntimeErrorCode.MISSING_NECESSARY_LOADER, `${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.`, ), ); } } /** * Warns if loaderParams is present and no loader is configured (i.e. the default one is being * used). */ function assertNoLoaderParamsWithoutLoader(dir: NgOptimizedImage, imageLoader: ImageLoader) { if (dir.loaderParams && imageLoader === noopImageLoader) { console.warn( formatRuntimeError( RuntimeErrorCode.MISSING_NECESSARY_LOADER, `${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.`, ), ); } } /** * Warns if the priority attribute is used too often on page load */ async function assetPriorityCountBelowThreshold(appRef: ApplicationRef) { if (IMGS_WITH_PRIORITY_ATTR_COUNT === 0) { IMGS_WITH_PRIORITY_ATTR_COUNT++; await whenStable(appRef); if (IMGS_WITH_PRIORITY_ATTR_COUNT > PRIORITY_COUNT_THRESHOLD) { console.warn( formatRuntimeError( 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). ` + `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.`, ), ); } } else { IMGS_WITH_PRIORITY_ATTR_COUNT++; } } /** * Warns if placeholder's dimension are over a threshold. * * This assert function is meant to only run on the browser. */ function assertPlaceholderDimensions(dir: NgOptimizedImage, imgElement: HTMLImageElement) { const computedStyle = window.getComputedStyle(imgElement); let renderedWidth = parseFloat(computedStyle.getPropertyValue('width')); let renderedHeight = parseFloat(computedStyle.getPropertyValue('height')); if (renderedWidth > PLACEHOLDER_DIMENSION_LIMIT || renderedHeight > PLACEHOLDER_DIMENSION_LIMIT) { console.warn( formatRuntimeError( RuntimeErrorCode.PLACEHOLDER_DIMENSION_LIMIT_EXCEEDED, `${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.`, ), ); } } function ca
{ "end_byte": 50179, "start_byte": 41789, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts" }
angular/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts_50181_51977
OnLoadIfImageIsLoaded(img: HTMLImageElement, callback: VoidFunction): void { // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-complete // The spec defines that `complete` is truthy once its request state is fully available. // The image may already be available if it’s loaded from the browser cache. // In that case, the `load` event will not fire at all, meaning that all setup // callbacks listening for the `load` event will not be invoked. // In Safari, there is a known behavior where the `complete` property of an // `HTMLImageElement` may sometimes return `true` even when the image is not fully loaded. // Checking both `img.complete` and `img.naturalWidth` is the most reliable way to // determine if an image has been fully loaded, especially in browsers where the // `complete` property may return `true` prematurely. if (img.complete && img.naturalWidth) { callback(); } } function round(input: number): number | string { return Number.isInteger(input) ? input : input.toFixed(2); } // Transform function to handle SafeValue input for ngSrc. This doesn't do any sanitization, // as that is not needed for img.src and img.srcset. This transform is purely for compatibility. function unwrapSafeUrl(value: string | SafeValue): string { if (typeof value === 'string') { return value; } return unwrapSafeValue(value); } // Transform function to handle inputs which may be booleans, strings, or string representations // of boolean values. Used for the placeholder attribute. export function booleanOrUrlAttribute(value: boolean | string): boolean | string { if (typeof value === 'string' && value !== 'true' && value !== 'false' && value !== '') { return value; } return booleanAttribute(value); }
{ "end_byte": 51977, "start_byte": 50181, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts" }
angular/packages/common/src/directives/ng_optimized_image/image_loaders/imagekit_loader.ts_0_1881
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {PLACEHOLDER_QUALITY} from './constants'; import {createImageLoader, ImageLoaderConfig, ImageLoaderInfo} from './image_loader'; /** * Name and URL tester for ImageKit. */ export const imageKitLoaderInfo: ImageLoaderInfo = { name: 'ImageKit', testUrl: isImageKitUrl, }; const IMAGE_KIT_LOADER_REGEX = /https?\:\/\/[^\/]+\.imagekit\.io\/.+/; /** * Tests whether a URL is from ImageKit CDN. */ function isImageKitUrl(url: string): boolean { 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 */ export const provideImageKitLoader = createImageLoader( createImagekitUrl, ngDevMode ? ['https://ik.imagekit.io/mysite', 'https://subdomain.mysite.com'] : undefined, ); export function createImagekitUrl(path: string, config: ImageLoaderConfig): string { // 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: string[] = []; 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; }
{ "end_byte": 1881, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/image_loaders/imagekit_loader.ts" }
angular/packages/common/src/directives/ng_optimized_image/image_loaders/cloudflare_loader.ts_0_1505
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {PLACEHOLDER_QUALITY} from './constants'; import {createImageLoader, ImageLoaderConfig} from './image_loader'; /** * 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 */ export const provideCloudflareLoader = createImageLoader( createCloudflareUrl, ngDevMode ? ['https://<ZONE>/cdn-cgi/image/<OPTIONS>/<SOURCE-IMAGE>'] : undefined, ); function createCloudflareUrl(path: string, config: ImageLoaderConfig) { 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}`; }
{ "end_byte": 1505, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/image_loaders/cloudflare_loader.ts" }
angular/packages/common/src/directives/ng_optimized_image/image_loaders/imgix_loader.ts_0_1607
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {PLACEHOLDER_QUALITY} from './constants'; import {createImageLoader, ImageLoaderConfig, ImageLoaderInfo} from './image_loader'; /** * Name and URL tester for Imgix. */ export const imgixLoaderInfo: ImageLoaderInfo = { name: 'Imgix', testUrl: isImgixUrl, }; const IMGIX_LOADER_REGEX = /https?\:\/\/[^\/]+\.imgix\.net\/.+/; /** * Tests whether a URL is from Imgix CDN. */ function isImgixUrl(url: string): boolean { 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 */ export const provideImgixLoader = createImageLoader( createImgixUrl, ngDevMode ? ['https://somepath.imgix.net/'] : undefined, ); function createImgixUrl(path: string, config: ImageLoaderConfig) { 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; }
{ "end_byte": 1607, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/image_loaders/imgix_loader.ts" }
angular/packages/common/src/directives/ng_optimized_image/image_loaders/image_loader.ts_0_4785
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {InjectionToken, Provider, ɵRuntimeError as RuntimeError} from '@angular/core'; import {RuntimeErrorCode} from '../../../errors'; import {isAbsoluteUrl, isValidPath, normalizePath, normalizeSrc} from '../url'; /** * Config options recognized by the image loader function. * * @see {@link ImageLoader} * @see {@link NgOptimizedImage} * @publicApi */ export interface ImageLoaderConfig { /** * Image file name to be added to the image request URL. */ src: string; /** * Width of the requested image (to be used when generating srcset). */ width?: number; /** * Whether the loader should generate a URL for a small image placeholder instead of a full-sized * image. */ isPlaceholder?: boolean; /** * Additional user-provided parameters for use by the ImageLoader. */ loaderParams?: {[key: string]: any}; } /** * Represents an image loader function. Image loader functions are used by the * NgOptimizedImage directive to produce full image URL based on the image name and its width. * * @publicApi */ export type ImageLoader = (config: ImageLoaderConfig) => string; /** * 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} */ export const noopImageLoader = (config: ImageLoaderConfig) => config.src; /** * Metadata about the image loader. */ export type ImageLoaderInfo = { name: string; testUrl: (url: string) => boolean; }; /** * Injection token that configures the image loader function. * * @see {@link ImageLoader} * @see {@link NgOptimizedImage} * @publicApi */ export const IMAGE_LOADER = new InjectionToken<ImageLoader>(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 */ export function createImageLoader( buildUrlFn: (path: string, config: ImageLoaderConfig) => string, exampleUrls?: string[], ) { return function provideImageLoader(path: string) { 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: ImageLoaderConfig) => { 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: Provider[] = [{provide: IMAGE_LOADER, useValue: loaderFn}]; return providers; }; } function throwInvalidPathError(path: unknown, exampleUrls: string[]): never { throw new RuntimeError( 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: string, url: string): never { throw new RuntimeError( 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}\`).`, ); }
{ "end_byte": 4785, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/image_loaders/image_loader.ts" }
angular/packages/common/src/directives/ng_optimized_image/image_loaders/netlify_loader.ts_0_3684
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Provider, ɵformatRuntimeError as formatRuntimeError, ɵRuntimeError as RuntimeError, } from '@angular/core'; import {RuntimeErrorCode} from '../../../errors'; import {isAbsoluteUrl, isValidPath} from '../url'; import {IMAGE_LOADER, ImageLoaderConfig, ImageLoaderInfo} from './image_loader'; import {PLACEHOLDER_QUALITY} from './constants'; /** * Name and URL tester for Netlify. */ export const netlifyLoaderInfo: ImageLoaderInfo = { 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: string): boolean { 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 */ export function provideNetlifyLoader(path?: string) { if (path && !isValidPath(path)) { throw new RuntimeError( 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: ImageLoaderConfig) => { return createNetlifyUrl(config, path); }; const providers: Provider[] = [{provide: IMAGE_LOADER, useValue: loaderFn}]; return providers; } const validParams = new Map<string, string>([ ['height', 'h'], ['fit', 'fit'], ['quality', 'q'], ['q', 'q'], ['position', 'position'], ]); function createNetlifyUrl(config: ImageLoaderConfig, path?: string) { // 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( 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; }
{ "end_byte": 3684, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/image_loaders/netlify_loader.ts" }
angular/packages/common/src/directives/ng_optimized_image/image_loaders/constants.ts_0_324
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * Value (out of 100) of the requested quality for placeholder images. */ export const PLACEHOLDER_QUALITY = '20';
{ "end_byte": 324, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/image_loaders/constants.ts" }
angular/packages/common/src/directives/ng_optimized_image/image_loaders/cloudinary_loader.ts_0_2095
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {createImageLoader, ImageLoaderConfig, ImageLoaderInfo} from './image_loader'; /** * Name and URL tester for Cloudinary. */ export const cloudinaryLoaderInfo: ImageLoaderInfo = { name: 'Cloudinary', testUrl: isCloudinaryUrl, }; const CLOUDINARY_LOADER_REGEX = /https?\:\/\/[^\/]+\.cloudinary\.com\/.+/; /** * Tests whether a URL is from Cloudinary CDN. */ function isCloudinaryUrl(url: string): boolean { 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 */ export const provideCloudinaryLoader = createImageLoader( createCloudinaryUrl, ngDevMode ? [ 'https://res.cloudinary.com/mysite', 'https://mysite.cloudinary.com', 'https://subdomain.mysite.com', ] : undefined, ); function createCloudinaryUrl(path: string, config: ImageLoaderConfig) { // 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}`; }
{ "end_byte": 2095, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/image_loaders/cloudinary_loader.ts" }
angular/packages/common/src/location/hash_location_strategy.ts_0_3188
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Inject, Injectable, OnDestroy, Optional} from '@angular/core'; import {APP_BASE_HREF, LocationStrategy} from './location_strategy'; import {LocationChangeListener, PlatformLocation} from './platform_location'; import {joinWithSlash, normalizeQueryParams} from './util'; /** * @description * A {@link LocationStrategy} used to configure the {@link Location} service to * represent its state in the * [hash fragment](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) * of the browser's URL. * * For instance, if you call `location.go('/foo')`, the browser's URL will become * `example.com#/foo`. * * @usageNotes * * ### Example * * {@example common/location/ts/hash_location_component.ts region='LocationComponent'} * * @publicApi */ @Injectable() export class HashLocationStrategy extends LocationStrategy implements OnDestroy { private _baseHref: string = ''; private _removeListenerFns: (() => void)[] = []; constructor( private _platformLocation: PlatformLocation, @Optional() @Inject(APP_BASE_HREF) _baseHref?: string, ) { super(); if (_baseHref != null) { this._baseHref = _baseHref; } } /** @nodoc */ ngOnDestroy(): void { while (this._removeListenerFns.length) { this._removeListenerFns.pop()!(); } } override onPopState(fn: LocationChangeListener): void { this._removeListenerFns.push( this._platformLocation.onPopState(fn), this._platformLocation.onHashChange(fn), ); } override getBaseHref(): string { return this._baseHref; } override path(includeHash: boolean = false): string { // the hash value is always prefixed with a `#` // and if it is empty then it will stay empty const path = this._platformLocation.hash ?? '#'; return path.length > 0 ? path.substring(1) : path; } override prepareExternalUrl(internal: string): string { const url = joinWithSlash(this._baseHref, internal); return url.length > 0 ? '#' + url : url; } override pushState(state: any, title: string, path: string, queryParams: string) { let url: string | null = this.prepareExternalUrl(path + normalizeQueryParams(queryParams)); if (url.length == 0) { url = this._platformLocation.pathname; } this._platformLocation.pushState(state, title, url); } override replaceState(state: any, title: string, path: string, queryParams: string) { let url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams)); if (url.length == 0) { url = this._platformLocation.pathname; } this._platformLocation.replaceState(state, title, url); } override forward(): void { this._platformLocation.forward(); } override back(): void { this._platformLocation.back(); } override getState(): unknown { return this._platformLocation.getState(); } override historyGo(relativePosition: number = 0): void { this._platformLocation.historyGo?.(relativePosition); } }
{ "end_byte": 3188, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/location/hash_location_strategy.ts" }
angular/packages/common/src/location/platform_location.ts_0_5340
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {inject, Injectable, InjectionToken} from '@angular/core'; import {getDOM} from '../dom_adapter'; import {DOCUMENT} from '../dom_tokens'; /** * This class should not be used directly by an application developer. Instead, use * {@link Location}. * * `PlatformLocation` encapsulates all calls to DOM APIs, which allows the Router to be * platform-agnostic. * This means that we can have different implementation of `PlatformLocation` for the different * platforms that Angular supports. For example, `@angular/platform-browser` provides an * implementation specific to the browser environment, while `@angular/platform-server` provides * one suitable for use with server-side rendering. * * The `PlatformLocation` class is used directly by all implementations of {@link LocationStrategy} * when they need to interact with the DOM APIs like pushState, popState, etc. * * {@link LocationStrategy} in turn is used by the {@link Location} service which is used directly * by the {@link Router} in order to navigate between routes. Since all interactions between {@link * Router} / * {@link Location} / {@link LocationStrategy} and DOM APIs flow through the `PlatformLocation` * class, they are all platform-agnostic. * * @publicApi */ @Injectable({providedIn: 'platform', useFactory: () => inject(BrowserPlatformLocation)}) export abstract class PlatformLocation { abstract getBaseHrefFromDOM(): string; abstract getState(): unknown; /** * Returns a function that, when executed, removes the `popstate` event handler. */ abstract onPopState(fn: LocationChangeListener): VoidFunction; /** * Returns a function that, when executed, removes the `hashchange` event handler. */ abstract onHashChange(fn: LocationChangeListener): VoidFunction; abstract get href(): string; abstract get protocol(): string; abstract get hostname(): string; abstract get port(): string; abstract get pathname(): string; abstract get search(): string; abstract get hash(): string; abstract replaceState(state: any, title: string, url: string): void; abstract pushState(state: any, title: string, url: string): void; abstract forward(): void; abstract back(): void; historyGo?(relativePosition: number): void { throw new Error(ngDevMode ? 'Not implemented' : ''); } } /** * @description * Indicates when a location is initialized. * * @publicApi */ export const LOCATION_INITIALIZED = new InjectionToken<Promise<any>>( ngDevMode ? 'Location Initialized' : '', ); /** * @description * A serializable version of the event from `onPopState` or `onHashChange` * * @publicApi */ export interface LocationChangeEvent { type: string; state: any; } /** * @publicApi */ export interface LocationChangeListener { (event: LocationChangeEvent): any; } /** * `PlatformLocation` encapsulates all of the direct calls to platform APIs. * This class should not be used directly by an application developer. Instead, use * {@link Location}. * * @publicApi */ @Injectable({ providedIn: 'platform', useFactory: () => new BrowserPlatformLocation(), }) export class BrowserPlatformLocation extends PlatformLocation { private _location: Location; private _history: History; private _doc = inject(DOCUMENT); constructor() { super(); this._location = window.location; this._history = window.history; } override getBaseHrefFromDOM(): string { return getDOM().getBaseHref(this._doc)!; } override onPopState(fn: LocationChangeListener): VoidFunction { const window = getDOM().getGlobalEventTarget(this._doc, 'window'); window.addEventListener('popstate', fn, false); return () => window.removeEventListener('popstate', fn); } override onHashChange(fn: LocationChangeListener): VoidFunction { const window = getDOM().getGlobalEventTarget(this._doc, 'window'); window.addEventListener('hashchange', fn, false); return () => window.removeEventListener('hashchange', fn); } override get href(): string { return this._location.href; } override get protocol(): string { return this._location.protocol; } override get hostname(): string { return this._location.hostname; } override get port(): string { return this._location.port; } override get pathname(): string { return this._location.pathname; } override get search(): string { return this._location.search; } override get hash(): string { return this._location.hash; } override set pathname(newPath: string) { this._location.pathname = newPath; } override pushState(state: any, title: string, url: string): void { this._history.pushState(state, title, url); } override replaceState(state: any, title: string, url: string): void { this._history.replaceState(state, title, url); } override forward(): void { this._history.forward(); } override back(): void { this._history.back(); } override historyGo(relativePosition: number = 0): void { this._history.go(relativePosition); } override getState(): unknown { return this._history.state; } }
{ "end_byte": 5340, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/location/platform_location.ts" }
angular/packages/common/src/location/location.ts_0_1485
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Injectable, OnDestroy, ɵɵinject} from '@angular/core'; import {Subject, SubscriptionLike} from 'rxjs'; import {LocationStrategy} from './location_strategy'; import {joinWithSlash, normalizeQueryParams, stripTrailingSlash} from './util'; /** @publicApi */ export interface PopStateEvent { pop?: boolean; state?: any; type?: string; url?: string; } /** * @description * * A service that applications can use to interact with a browser's URL. * * Depending on the `LocationStrategy` used, `Location` persists * to the URL's path or the URL's hash segment. * * @usageNotes * * It's better to use the `Router.navigate()` service to trigger route changes. Use * `Location` only if you need to interact with or create normalized URLs outside of * routing. * * `Location` is responsible for normalizing the URL against the application's base href. * A normalized URL is absolute from the URL host, includes the application's base href, and has no * trailing slash: * - `/my/app/user/123` is normalized * - `my/app/user/123` **is not** normalized * - `/my/app/user/123/` **is not** normalized * * ### Example * * <code-example path='common/location/ts/path_location_component.ts' * region='LocationComponent'></code-example> * * @publicApi */ @
{ "end_byte": 1485, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/location/location.ts" }
angular/packages/common/src/location/location.ts_1486_9750
njectable({ providedIn: 'root', // See #23917 useFactory: createLocation, }) export class Location implements OnDestroy { /** @internal */ _subject = new Subject<PopStateEvent>(); /** @internal */ _basePath: string; /** @internal */ _locationStrategy: LocationStrategy; /** @internal */ _urlChangeListeners: ((url: string, state: unknown) => void)[] = []; /** @internal */ _urlChangeSubscription: SubscriptionLike | null = null; constructor(locationStrategy: LocationStrategy) { this._locationStrategy = locationStrategy; const baseHref = this._locationStrategy.getBaseHref(); // Note: This class's interaction with base HREF does not fully follow the rules // outlined in the spec https://www.freesoft.org/CIE/RFC/1808/18.htm. // Instead of trying to fix individual bugs with more and more code, we should // investigate using the URL constructor and providing the base as a second // argument. // https://developer.mozilla.org/en-US/docs/Web/API/URL/URL#parameters this._basePath = _stripOrigin(stripTrailingSlash(_stripIndexHtml(baseHref))); this._locationStrategy.onPopState((ev) => { this._subject.next({ 'url': this.path(true), 'pop': true, 'state': ev.state, 'type': ev.type, }); }); } /** @nodoc */ ngOnDestroy(): void { this._urlChangeSubscription?.unsubscribe(); this._urlChangeListeners = []; } /** * Normalizes the URL path for this location. * * @param includeHash True to include an anchor fragment in the path. * * @returns The normalized URL path. */ // TODO: vsavkin. Remove the boolean flag and always include hash once the deprecated router is // removed. path(includeHash: boolean = false): string { return this.normalize(this._locationStrategy.path(includeHash)); } /** * Reports the current state of the location history. * @returns The current value of the `history.state` object. */ getState(): unknown { return this._locationStrategy.getState(); } /** * Normalizes the given path and compares to the current normalized path. * * @param path The given URL path. * @param query Query parameters. * * @returns True if the given URL path is equal to the current normalized path, false * otherwise. */ isCurrentPathEqualTo(path: string, query: string = ''): boolean { return this.path() == this.normalize(path + normalizeQueryParams(query)); } /** * Normalizes a URL path by stripping any trailing slashes. * * @param url String representing a URL. * * @returns The normalized URL string. */ normalize(url: string): string { return Location.stripTrailingSlash(_stripBasePath(this._basePath, _stripIndexHtml(url))); } /** * Normalizes an external URL path. * If the given URL doesn't begin with a leading slash (`'/'`), adds one * before normalizing. Adds a hash if `HashLocationStrategy` is * in use, or the `APP_BASE_HREF` if the `PathLocationStrategy` is in use. * * @param url String representing a URL. * * @returns A normalized platform-specific URL. */ prepareExternalUrl(url: string): string { if (url && url[0] !== '/') { url = '/' + url; } return this._locationStrategy.prepareExternalUrl(url); } // TODO: rename this method to pushState /** * Changes the browser's URL to a normalized version of a given URL, and pushes a * new item onto the platform's history. * * @param path URL path to normalize. * @param query Query parameters. * @param state Location history state. * */ go(path: string, query: string = '', state: any = null): void { this._locationStrategy.pushState(state, '', path, query); this._notifyUrlChangeListeners( this.prepareExternalUrl(path + normalizeQueryParams(query)), state, ); } /** * Changes the browser's URL to a normalized version of the given URL, and replaces * the top item on the platform's history stack. * * @param path URL path to normalize. * @param query Query parameters. * @param state Location history state. */ replaceState(path: string, query: string = '', state: any = null): void { this._locationStrategy.replaceState(state, '', path, query); this._notifyUrlChangeListeners( this.prepareExternalUrl(path + normalizeQueryParams(query)), state, ); } /** * Navigates forward in the platform's history. */ forward(): void { this._locationStrategy.forward(); } /** * Navigates back in the platform's history. */ back(): void { this._locationStrategy.back(); } /** * Navigate to a specific page from session history, identified by its relative position to the * current page. * * @param relativePosition Position of the target page in the history relative to the current * page. * A negative value moves backwards, a positive value moves forwards, e.g. `location.historyGo(2)` * moves forward two pages and `location.historyGo(-2)` moves back two pages. When we try to go * beyond what's stored in the history session, we stay in the current page. Same behaviour occurs * when `relativePosition` equals 0. * @see https://developer.mozilla.org/en-US/docs/Web/API/History_API#Moving_to_a_specific_point_in_history */ historyGo(relativePosition: number = 0): void { this._locationStrategy.historyGo?.(relativePosition); } /** * Registers a URL change listener. Use to catch updates performed by the Angular * framework that are not detectible through "popstate" or "hashchange" events. * * @param fn The change handler function, which take a URL and a location history state. * @returns A function that, when executed, unregisters a URL change listener. */ onUrlChange(fn: (url: string, state: unknown) => void): VoidFunction { this._urlChangeListeners.push(fn); this._urlChangeSubscription ??= this.subscribe((v) => { this._notifyUrlChangeListeners(v.url, v.state); }); return () => { const fnIndex = this._urlChangeListeners.indexOf(fn); this._urlChangeListeners.splice(fnIndex, 1); if (this._urlChangeListeners.length === 0) { this._urlChangeSubscription?.unsubscribe(); this._urlChangeSubscription = null; } }; } /** @internal */ _notifyUrlChangeListeners(url: string = '', state: unknown) { this._urlChangeListeners.forEach((fn) => fn(url, state)); } /** * Subscribes to the platform's `popState` events. * * Note: `Location.go()` does not trigger the `popState` event in the browser. Use * `Location.onUrlChange()` to subscribe to URL changes instead. * * @param value Event that is triggered when the state history changes. * @param exception The exception to throw. * * @see [onpopstate](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate) * * @returns Subscribed events. */ subscribe( onNext: (value: PopStateEvent) => void, onThrow?: ((exception: any) => void) | null, onReturn?: (() => void) | null, ): SubscriptionLike { return this._subject.subscribe({ next: onNext, error: onThrow ?? undefined, complete: onReturn ?? undefined, }); } /** * Normalizes URL parameters by prepending with `?` if needed. * * @param params String of URL parameters. * * @returns The normalized URL parameters string. */ public static normalizeQueryParams: (params: string) => string = normalizeQueryParams; /** * Joins two parts of a URL with a slash if needed. * * @param start URL string * @param end URL string * * * @returns The joined URL string. */ public static joinWithSlash: (start: string, end: string) => string = joinWithSlash; /** * Removes a trailing slash from a URL string if needed. * Looks for the first occurrence of either `#`, `?`, or the end of the * line as `/` characters and removes the trailing slash if one exists. * * @param url URL string. * * @returns The URL string, modified if needed. */ public static stripTrailingSlash: (url: string) => string = stripTrailingSlash; }
{ "end_byte": 9750, "start_byte": 1486, "url": "https://github.com/angular/angular/blob/main/packages/common/src/location/location.ts" }
angular/packages/common/src/location/location.ts_9752_10818
port function createLocation() { return new Location(ɵɵinject(LocationStrategy as any)); } function _stripBasePath(basePath: string, url: string): string { if (!basePath || !url.startsWith(basePath)) { return url; } const strippedUrl = url.substring(basePath.length); if (strippedUrl === '' || ['/', ';', '?', '#'].includes(strippedUrl[0])) { return strippedUrl; } return url; } function _stripIndexHtml(url: string): string { return url.replace(/\/index.html$/, ''); } function _stripOrigin(baseHref: string): string { // DO NOT REFACTOR! Previously, this check looked like this: // `/^(https?:)?\/\//.test(baseHref)`, but that resulted in // syntactically incorrect code after Closure Compiler minification. // This was likely caused by a bug in Closure Compiler, but // for now, the check is rewritten to use `new RegExp` instead. const isAbsoluteUrl = new RegExp('^(https?:)?//').test(baseHref); if (isAbsoluteUrl) { const [, pathname] = baseHref.split(/\/\/[^\/]+/); return pathname; } return baseHref; }
{ "end_byte": 10818, "start_byte": 9752, "url": "https://github.com/angular/angular/blob/main/packages/common/src/location/location.ts" }
angular/packages/common/src/location/location_strategy.ts_0_5816
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Inject, inject, Injectable, InjectionToken, OnDestroy, Optional} from '@angular/core'; import {DOCUMENT} from '../dom_tokens'; import {LocationChangeListener, PlatformLocation} from './platform_location'; import {joinWithSlash, normalizeQueryParams} from './util'; /** * Enables the `Location` service to read route state from the browser's URL. * Angular provides two strategies: * `HashLocationStrategy` and `PathLocationStrategy`. * * Applications should use the `Router` or `Location` services to * interact with application route state. * * For instance, `HashLocationStrategy` produces URLs like * <code class="no-auto-link">http://example.com/#/foo</code>, * and `PathLocationStrategy` produces * <code class="no-auto-link">http://example.com/foo</code> as an equivalent URL. * * See these two classes for more. * * @publicApi */ @Injectable({providedIn: 'root', useFactory: () => inject(PathLocationStrategy)}) export abstract class LocationStrategy { abstract path(includeHash?: boolean): string; abstract prepareExternalUrl(internal: string): string; abstract getState(): unknown; abstract pushState(state: any, title: string, url: string, queryParams: string): void; abstract replaceState(state: any, title: string, url: string, queryParams: string): void; abstract forward(): void; abstract back(): void; historyGo?(relativePosition: number): void { throw new Error(ngDevMode ? 'Not implemented' : ''); } abstract onPopState(fn: LocationChangeListener): void; abstract getBaseHref(): string; } /** * A predefined DI token for the base href * to be used with the `PathLocationStrategy`. * The base href is the URL prefix that should be preserved when generating * and recognizing URLs. * * @usageNotes * * The following example shows how to use this token to configure the root app injector * with a base href value, so that the DI framework can supply the dependency anywhere in the app. * * ```typescript * import {NgModule} from '@angular/core'; * import {APP_BASE_HREF} from '@angular/common'; * * @NgModule({ * providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}] * }) * class AppModule {} * ``` * * @publicApi */ export const APP_BASE_HREF = new InjectionToken<string>(ngDevMode ? 'appBaseHref' : ''); /** * @description * A {@link LocationStrategy} used to configure the {@link Location} service to * represent its state in the * [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the * browser's URL. * * If you're using `PathLocationStrategy`, you may provide a {@link APP_BASE_HREF} * or add a `<base href>` element to the document to override the default. * * For instance, if you provide an `APP_BASE_HREF` of `'/my/app/'` and call * `location.go('/foo')`, the browser's URL will become * `example.com/my/app/foo`. To ensure all relative URIs resolve correctly, * the `<base href>` and/or `APP_BASE_HREF` should end with a `/`. * * Similarly, if you add `<base href='/my/app/'/>` to the document and call * `location.go('/foo')`, the browser's URL will become * `example.com/my/app/foo`. * * Note that when using `PathLocationStrategy`, neither the query nor * the fragment in the `<base href>` will be preserved, as outlined * by the [RFC](https://tools.ietf.org/html/rfc3986#section-5.2.2). * * @usageNotes * * ### Example * * {@example common/location/ts/path_location_component.ts region='LocationComponent'} * * @publicApi */ @Injectable({providedIn: 'root'}) export class PathLocationStrategy extends LocationStrategy implements OnDestroy { private _baseHref: string; private _removeListenerFns: (() => void)[] = []; constructor( private _platformLocation: PlatformLocation, @Optional() @Inject(APP_BASE_HREF) href?: string, ) { super(); this._baseHref = href ?? this._platformLocation.getBaseHrefFromDOM() ?? inject(DOCUMENT).location?.origin ?? ''; } /** @nodoc */ ngOnDestroy(): void { while (this._removeListenerFns.length) { this._removeListenerFns.pop()!(); } } override onPopState(fn: LocationChangeListener): void { this._removeListenerFns.push( this._platformLocation.onPopState(fn), this._platformLocation.onHashChange(fn), ); } override getBaseHref(): string { return this._baseHref; } override prepareExternalUrl(internal: string): string { return joinWithSlash(this._baseHref, internal); } override path(includeHash: boolean = false): string { const pathname = this._platformLocation.pathname + normalizeQueryParams(this._platformLocation.search); const hash = this._platformLocation.hash; return hash && includeHash ? `${pathname}${hash}` : pathname; } override pushState(state: any, title: string, url: string, queryParams: string) { const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams)); this._platformLocation.pushState(state, title, externalUrl); } override replaceState(state: any, title: string, url: string, queryParams: string) { const externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams)); this._platformLocation.replaceState(state, title, externalUrl); } override forward(): void { this._platformLocation.forward(); } override back(): void { this._platformLocation.back(); } override getState(): unknown { return this._platformLocation.getState(); } override historyGo(relativePosition: number = 0): void { this._platformLocation.historyGo?.(relativePosition); } }
{ "end_byte": 5816, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/location/location_strategy.ts" }
angular/packages/common/src/location/util.ts_0_1671
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * Joins two parts of a URL with a slash if needed. * * @param start URL string * @param end URL string * * * @returns The joined URL string. */ export function joinWithSlash(start: string, end: string): string { if (start.length == 0) { return end; } if (end.length == 0) { return start; } let slashes = 0; if (start.endsWith('/')) { slashes++; } if (end.startsWith('/')) { slashes++; } if (slashes == 2) { return start + end.substring(1); } if (slashes == 1) { return start + end; } return start + '/' + end; } /** * Removes a trailing slash from a URL string if needed. * Looks for the first occurrence of either `#`, `?`, or the end of the * line as `/` characters and removes the trailing slash if one exists. * * @param url URL string. * * @returns The URL string, modified if needed. */ export function stripTrailingSlash(url: string): string { const match = url.match(/#|\?|$/); const pathEndIdx = (match && match.index) || url.length; const droppedSlashIdx = pathEndIdx - (url[pathEndIdx - 1] === '/' ? 1 : 0); return url.slice(0, droppedSlashIdx) + url.slice(pathEndIdx); } /** * Normalizes URL parameters by prepending with `?` if needed. * * @param params String of URL parameters. * * @returns The normalized URL parameters string. */ export function normalizeQueryParams(params: string): string { return params && params[0] !== '?' ? '?' + params : params; }
{ "end_byte": 1671, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/location/util.ts" }
angular/packages/common/src/location/index.ts_0_569
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export {HashLocationStrategy} from './hash_location_strategy'; export {Location, PopStateEvent} from './location'; export {APP_BASE_HREF, LocationStrategy, PathLocationStrategy} from './location_strategy'; export { BrowserPlatformLocation, LOCATION_INITIALIZED, LocationChangeEvent, LocationChangeListener, PlatformLocation, } from './platform_location';
{ "end_byte": 569, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/location/index.ts" }
angular/packages/common/src/navigation/platform_navigation.ts_0_2125
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Injectable} from '@angular/core'; import { NavigateEvent, Navigation, NavigationCurrentEntryChangeEvent, NavigationHistoryEntry, NavigationNavigateOptions, NavigationOptions, NavigationReloadOptions, NavigationResult, NavigationTransition, NavigationUpdateCurrentEntryOptions, } from './navigation_types'; /** * This class wraps the platform Navigation API which allows server-specific and test * implementations. */ @Injectable({providedIn: 'platform', useFactory: () => (window as any).navigation}) export abstract class PlatformNavigation implements Navigation { abstract entries(): NavigationHistoryEntry[]; abstract currentEntry: NavigationHistoryEntry | null; abstract updateCurrentEntry(options: NavigationUpdateCurrentEntryOptions): void; abstract transition: NavigationTransition | null; abstract canGoBack: boolean; abstract canGoForward: boolean; abstract navigate(url: string, options?: NavigationNavigateOptions | undefined): NavigationResult; abstract reload(options?: NavigationReloadOptions | undefined): NavigationResult; abstract traverseTo(key: string, options?: NavigationOptions | undefined): NavigationResult; abstract back(options?: NavigationOptions | undefined): NavigationResult; abstract forward(options?: NavigationOptions | undefined): NavigationResult; abstract onnavigate: ((this: Navigation, ev: NavigateEvent) => any) | null; abstract onnavigatesuccess: ((this: Navigation, ev: Event) => any) | null; abstract onnavigateerror: ((this: Navigation, ev: ErrorEvent) => any) | null; abstract oncurrententrychange: | ((this: Navigation, ev: NavigationCurrentEntryChangeEvent) => any) | null; abstract addEventListener(type: unknown, listener: unknown, options?: unknown): void; abstract removeEventListener(type: unknown, listener: unknown, options?: unknown): void; abstract dispatchEvent(event: Event): boolean; }
{ "end_byte": 2125, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/navigation/platform_navigation.ts" }
angular/packages/common/src/navigation/navigation_types.ts_0_5576
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export interface NavigationEventMap { navigate: NavigateEvent; navigatesuccess: Event; navigateerror: ErrorEvent; currententrychange: NavigationCurrentEntryChangeEvent; } export interface NavigationResult { committed: Promise<NavigationHistoryEntry>; finished: Promise<NavigationHistoryEntry>; } export declare class Navigation extends EventTarget { entries(): NavigationHistoryEntry[]; readonly currentEntry: NavigationHistoryEntry | null; updateCurrentEntry(options: NavigationUpdateCurrentEntryOptions): void; readonly transition: NavigationTransition | null; readonly canGoBack: boolean; readonly canGoForward: boolean; navigate(url: string, options?: NavigationNavigateOptions): NavigationResult; reload(options?: NavigationReloadOptions): NavigationResult; traverseTo(key: string, options?: NavigationOptions): NavigationResult; back(options?: NavigationOptions): NavigationResult; forward(options?: NavigationOptions): NavigationResult; onnavigate: ((this: Navigation, ev: NavigateEvent) => any) | null; onnavigatesuccess: ((this: Navigation, ev: Event) => any) | null; onnavigateerror: ((this: Navigation, ev: ErrorEvent) => any) | null; oncurrententrychange: ((this: Navigation, ev: NavigationCurrentEntryChangeEvent) => any) | null; addEventListener<K extends keyof NavigationEventMap>( type: K, listener: (this: Navigation, ev: NavigationEventMap[K]) => any, options?: boolean | AddEventListenerOptions, ): void; addEventListener( type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions, ): void; removeEventListener<K extends keyof NavigationEventMap>( type: K, listener: (this: Navigation, ev: NavigationEventMap[K]) => any, options?: boolean | EventListenerOptions, ): void; removeEventListener( type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions, ): void; } export declare class NavigationTransition { readonly navigationType: NavigationTypeString; readonly from: NavigationHistoryEntry; readonly finished: Promise<void>; } export interface NavigationHistoryEntryEventMap { dispose: Event; } export declare class NavigationHistoryEntry extends EventTarget { readonly key: string; readonly id: string; readonly url: string | null; readonly index: number; readonly sameDocument: boolean; getState(): unknown; ondispose: ((this: NavigationHistoryEntry, ev: Event) => any) | null; addEventListener<K extends keyof NavigationHistoryEntryEventMap>( type: K, listener: (this: NavigationHistoryEntry, ev: NavigationHistoryEntryEventMap[K]) => any, options?: boolean | AddEventListenerOptions, ): void; addEventListener( type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions, ): void; removeEventListener<K extends keyof NavigationHistoryEntryEventMap>( type: K, listener: (this: NavigationHistoryEntry, ev: NavigationHistoryEntryEventMap[K]) => any, options?: boolean | EventListenerOptions, ): void; removeEventListener( type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions, ): void; } type NavigationTypeString = 'reload' | 'push' | 'replace' | 'traverse'; export interface NavigationUpdateCurrentEntryOptions { state: unknown; } export interface NavigationOptions { info?: unknown; } export interface NavigationNavigateOptions extends NavigationOptions { state?: unknown; history?: 'auto' | 'push' | 'replace'; } export interface NavigationReloadOptions extends NavigationOptions { state?: unknown; } export declare class NavigationCurrentEntryChangeEvent extends Event { constructor(type: string, eventInit?: NavigationCurrentEntryChangeEventInit); readonly navigationType: NavigationTypeString | null; readonly from: NavigationHistoryEntry; } export interface NavigationCurrentEntryChangeEventInit extends EventInit { navigationType?: NavigationTypeString | null; from: NavigationHistoryEntry; } export declare class NavigateEvent extends Event { constructor(type: string, eventInit?: NavigateEventInit); readonly navigationType: NavigationTypeString; readonly canIntercept: boolean; readonly userInitiated: boolean; readonly hashChange: boolean; readonly destination: NavigationDestination; readonly signal: AbortSignal; readonly formData: FormData | null; readonly downloadRequest: string | null; readonly info?: unknown; intercept(options?: NavigationInterceptOptions): void; scroll(): void; } export interface NavigateEventInit extends EventInit { navigationType?: NavigationTypeString; canIntercept?: boolean; userInitiated?: boolean; hashChange?: boolean; destination: NavigationDestination; signal: AbortSignal; formData?: FormData | null; downloadRequest?: string | null; info?: unknown; } export interface NavigationInterceptOptions { handler?: () => Promise<void>; focusReset?: 'after-transition' | 'manual'; scroll?: 'after-transition' | 'manual'; } export declare class NavigationDestination { readonly url: string; readonly key: string | null; readonly id: string | null; readonly index: number; readonly sameDocument: boolean; getState(): unknown; }
{ "end_byte": 5576, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/navigation/navigation_types.ts" }
angular/packages/common/src/pipes/async_pipe.ts_0_6662
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { ChangeDetectorRef, EventEmitter, OnDestroy, Pipe, PipeTransform, untracked, ɵisPromise, ɵisSubscribable, } from '@angular/core'; import {Observable, Subscribable, Unsubscribable} from 'rxjs'; import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; interface SubscriptionStrategy { createSubscription( async: Subscribable<any> | Promise<any>, updateLatestValue: any, ): Unsubscribable | Promise<any>; dispose(subscription: Unsubscribable | Promise<any>): void; } class SubscribableStrategy implements SubscriptionStrategy { createSubscription(async: Subscribable<any>, updateLatestValue: any): Unsubscribable { // Subscription can be side-effectful, and we don't want any signal reads which happen in the // side effect of the subscription to be tracked by a component's template when that // subscription is triggered via the async pipe. So we wrap the subscription in `untracked` to // decouple from the current reactive context. // // `untracked` also prevents signal _writes_ which happen in the subscription side effect from // being treated as signal writes during the template evaluation (which throws errors). return untracked(() => async.subscribe({ next: updateLatestValue, error: (e: any) => { throw e; }, }), ); } dispose(subscription: Unsubscribable): void { // See the comment in `createSubscription` above on the use of `untracked`. untracked(() => subscription.unsubscribe()); } } class PromiseStrategy implements SubscriptionStrategy { createSubscription(async: Promise<any>, updateLatestValue: (v: any) => any): Promise<any> { return async.then(updateLatestValue, (e) => { throw e; }); } dispose(subscription: Promise<any>): void {} } const _promiseStrategy = new PromiseStrategy(); const _subscribableStrategy = new SubscribableStrategy(); /** * @ngModule CommonModule * @description * * Unwraps a value from an asynchronous primitive. * * The `async` pipe subscribes to an `Observable` or `Promise` and returns the latest value it has * emitted. When a new value is emitted, the `async` pipe marks the component to be checked for * changes. When the component gets destroyed, the `async` pipe unsubscribes automatically to avoid * potential memory leaks. When the reference of the expression changes, the `async` pipe * automatically unsubscribes from the old `Observable` or `Promise` and subscribes to the new one. * * @usageNotes * * ### Examples * * This example binds a `Promise` to the view. Clicking the `Resolve` button resolves the * promise. * * {@example common/pipes/ts/async_pipe.ts region='AsyncPipePromise'} * * It's also possible to use `async` with Observables. The example below binds the `time` Observable * to the view. The Observable continuously updates the view with the current time. * * {@example common/pipes/ts/async_pipe.ts region='AsyncPipeObservable'} * * @publicApi */ @Pipe({ name: 'async', pure: false, standalone: true, }) export class AsyncPipe implements OnDestroy, PipeTransform { private _ref: ChangeDetectorRef | null; private _latestValue: any = null; private markForCheckOnValueUpdate = true; private _subscription: Unsubscribable | Promise<any> | null = null; private _obj: Subscribable<any> | Promise<any> | EventEmitter<any> | null = null; private _strategy: SubscriptionStrategy | null = null; constructor(ref: ChangeDetectorRef) { // Assign `ref` into `this._ref` manually instead of declaring `_ref` in the constructor // parameter list, as the type of `this._ref` includes `null` unlike the type of `ref`. this._ref = ref; } ngOnDestroy(): void { if (this._subscription) { this._dispose(); } // Clear the `ChangeDetectorRef` and its association with the view data, to mitigate // potential memory leaks in Observables that could otherwise cause the view data to // be retained. // https://github.com/angular/angular/issues/17624 this._ref = null; } // NOTE(@benlesh): Because Observable has deprecated a few call patterns for `subscribe`, // TypeScript has a hard time matching Observable to Subscribable, for more information // see https://github.com/microsoft/TypeScript/issues/43643 transform<T>(obj: Observable<T> | Subscribable<T> | Promise<T>): T | null; transform<T>(obj: null | undefined): null; transform<T>(obj: Observable<T> | Subscribable<T> | Promise<T> | null | undefined): T | null; transform<T>(obj: Observable<T> | Subscribable<T> | Promise<T> | null | undefined): T | null { if (!this._obj) { if (obj) { try { // Only call `markForCheck` if the value is updated asynchronously. // Synchronous updates _during_ subscription should not wastefully mark for check - // this value is already going to be returned from the transform function. this.markForCheckOnValueUpdate = false; this._subscribe(obj); } finally { this.markForCheckOnValueUpdate = true; } } return this._latestValue; } if (obj !== this._obj) { this._dispose(); return this.transform(obj); } return this._latestValue; } private _subscribe(obj: Subscribable<any> | Promise<any> | EventEmitter<any>): void { this._obj = obj; this._strategy = this._selectStrategy(obj); this._subscription = this._strategy.createSubscription(obj, (value: Object) => this._updateLatestValue(obj, value), ); } private _selectStrategy( obj: Subscribable<any> | Promise<any> | EventEmitter<any>, ): SubscriptionStrategy { if (ɵisPromise(obj)) { return _promiseStrategy; } if (ɵisSubscribable(obj)) { return _subscribableStrategy; } throw invalidPipeArgumentError(AsyncPipe, obj); } private _dispose(): void { // Note: `dispose` is only called if a subscription has been initialized before, indicating // that `this._strategy` is also available. this._strategy!.dispose(this._subscription!); this._latestValue = null; this._subscription = null; this._obj = null; } private _updateLatestValue(async: any, value: Object): void { if (async === this._obj) { this._latestValue = value; if (this.markForCheckOnValueUpdate) { this._ref?.markForCheck(); } } } }
{ "end_byte": 6662, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/async_pipe.ts" }
angular/packages/common/src/pipes/slice_pipe.ts_0_2995
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Pipe, PipeTransform} from '@angular/core'; import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; /** * @ngModule CommonModule * @description * * Creates a new `Array` or `String` containing a subset (slice) of the elements. * * @usageNotes * * All behavior is based on the expected behavior of the JavaScript API `Array.prototype.slice()` * and `String.prototype.slice()`. * * When operating on an `Array`, the returned `Array` is always a copy even when all * the elements are being returned. * * When operating on a blank value, the pipe returns the blank value. * * ### List Example * * This `ngFor` example: * * {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_list'} * * produces the following: * * ```html * <li>b</li> * <li>c</li> * ``` * * ### String Examples * * {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_string'} * * @publicApi */ @Pipe({ name: 'slice', pure: false, standalone: true, }) export class SlicePipe implements PipeTransform { /** * @param value a list or a string to be sliced. * @param start the starting index of the subset to return: * - **a positive integer**: return the item at `start` index and all items after * in the list or string expression. * - **a negative integer**: return the item at `start` index from the end and all items after * in the list or string expression. * - **if positive and greater than the size of the expression**: return an empty list or * string. * - **if negative and greater than the size of the expression**: return entire list or string. * @param end the ending index of the subset to return: * - **omitted**: return all items until the end. * - **if positive**: return all items before `end` index of the list or string. * - **if negative**: return all items before `end` index from the end of the list or string. */ transform<T>(value: ReadonlyArray<T>, start: number, end?: number): Array<T>; transform(value: null | undefined, start: number, end?: number): null; transform<T>( value: ReadonlyArray<T> | null | undefined, start: number, end?: number, ): Array<T> | null; transform(value: string, start: number, end?: number): string; transform(value: string | null | undefined, start: number, end?: number): string | null; transform<T>( value: ReadonlyArray<T> | string | null | undefined, start: number, end?: number, ): Array<T> | string | null { if (value == null) return null; if (!this.supports(value)) { throw invalidPipeArgumentError(SlicePipe, value); } return value.slice(start, end); } private supports(obj: any): boolean { return typeof obj === 'string' || Array.isArray(obj); } }
{ "end_byte": 2995, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/slice_pipe.ts" }
angular/packages/common/src/pipes/invalid_pipe_argument_error.ts_0_579
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Type, ɵRuntimeError as RuntimeError, ɵstringify as stringify} from '@angular/core'; import {RuntimeErrorCode} from '../errors'; export function invalidPipeArgumentError(type: Type<any>, value: Object) { return new RuntimeError( RuntimeErrorCode.INVALID_PIPE_ARGUMENT, ngDevMode && `InvalidPipeArgument: '${value}' for pipe '${stringify(type)}'`, ); }
{ "end_byte": 579, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/invalid_pipe_argument_error.ts" }
angular/packages/common/src/pipes/i18n_select_pipe.ts_0_1501
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Pipe, PipeTransform} from '@angular/core'; import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; /** * @ngModule CommonModule * @description * * Generic selector that displays the string that matches the current value. * * If none of the keys of the `mapping` match the `value`, then the content * of the `other` key is returned when present, otherwise an empty string is returned. * * @usageNotes * * ### Example * * {@example common/pipes/ts/i18n_pipe.ts region='I18nSelectPipeComponent'} * * @publicApi */ @Pipe({ name: 'i18nSelect', standalone: true, }) export class I18nSelectPipe implements PipeTransform { /** * @param value a string to be internationalized. * @param mapping an object that indicates the text that should be displayed * for different values of the provided `value`. */ transform(value: string | null | undefined, mapping: {[key: string]: string}): string { if (value == null) return ''; if (typeof mapping !== 'object' || typeof value !== 'string') { throw invalidPipeArgumentError(I18nSelectPipe, mapping); } if (mapping.hasOwnProperty(value)) { return mapping[value]; } if (mapping.hasOwnProperty('other')) { return mapping['other']; } return ''; } }
{ "end_byte": 1501, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/i18n_select_pipe.ts" }
angular/packages/common/src/pipes/date_pipe_config.ts_0_671
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * An interface that describes the date pipe configuration, which can be provided using the * `DATE_PIPE_DEFAULT_OPTIONS` token. * * @see {@link DATE_PIPE_DEFAULT_OPTIONS} * * @publicApi */ export interface DatePipeConfig { dateFormat?: string; timezone?: string; } /** * The default date format of Angular date pipe, which corresponds to the following format: * `'MMM d,y'` (e.g. `Jun 15, 2015`) */ export const DEFAULT_DATE_FORMAT = 'mediumDate';
{ "end_byte": 671, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/date_pipe_config.ts" }
angular/packages/common/src/pipes/keyvalue_pipe.ts_0_5004
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { KeyValueChangeRecord, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Pipe, PipeTransform, } from '@angular/core'; function makeKeyValuePair<K, V>(key: K, value: V): KeyValue<K, V> { return {key: key, value: value}; } /** * A key value pair. * Usually used to represent the key value pairs from a Map or Object. * * @publicApi */ export interface KeyValue<K, V> { key: K; value: V; } /** * @ngModule CommonModule * @description * * Transforms Object or Map into an array of key value pairs. * * The output array will be ordered by keys. * By default the comparator will be by Unicode point value. * You can optionally pass a compareFn if your keys are complex types. * Passing `null` as the compareFn will use natural ordering of the input. * * @usageNotes * ### Examples * * This examples show how an Object or a Map can be iterated by ngFor with the use of this * keyvalue pipe. * * {@example common/pipes/ts/keyvalue_pipe.ts region='KeyValuePipe'} * * @publicApi */ @Pipe({ name: 'keyvalue', pure: false, standalone: true, }) export class KeyValuePipe implements PipeTransform { constructor(private readonly differs: KeyValueDiffers) {} private differ!: KeyValueDiffer<any, any>; private keyValues: Array<KeyValue<any, any>> = []; private compareFn: ((a: KeyValue<any, any>, b: KeyValue<any, any>) => number) | null = defaultComparator; /* * NOTE: when the `input` value is a simple Record<K, V> object, the keys are extracted with * Object.keys(). This means that even if the `input` type is Record<number, V> the keys are * compared/returned as `string`s. */ transform<K, V>( input: ReadonlyMap<K, V>, compareFn?: ((a: KeyValue<K, V>, b: KeyValue<K, V>) => number) | null, ): Array<KeyValue<K, V>>; transform<K extends number, V>( input: Record<K, V>, compareFn?: ((a: KeyValue<string, V>, b: KeyValue<string, V>) => number) | null, ): Array<KeyValue<string, V>>; transform<K extends string, V>( input: Record<K, V> | ReadonlyMap<K, V>, compareFn?: ((a: KeyValue<K, V>, b: KeyValue<K, V>) => number) | null, ): Array<KeyValue<K, V>>; transform( input: null | undefined, compareFn?: ((a: KeyValue<unknown, unknown>, b: KeyValue<unknown, unknown>) => number) | null, ): null; transform<K, V>( input: ReadonlyMap<K, V> | null | undefined, compareFn?: ((a: KeyValue<K, V>, b: KeyValue<K, V>) => number) | null, ): Array<KeyValue<K, V>> | null; transform<K extends number, V>( input: Record<K, V> | null | undefined, compareFn?: ((a: KeyValue<string, V>, b: KeyValue<string, V>) => number) | null, ): Array<KeyValue<string, V>> | null; transform<K extends string, V>( input: Record<K, V> | ReadonlyMap<K, V> | null | undefined, compareFn?: ((a: KeyValue<K, V>, b: KeyValue<K, V>) => number) | null, ): Array<KeyValue<K, V>> | null; transform<K, V>( input: undefined | null | {[key: string]: V; [key: number]: V} | ReadonlyMap<K, V>, compareFn: ((a: KeyValue<K, V>, b: KeyValue<K, V>) => number) | null = defaultComparator, ): Array<KeyValue<K, V>> | null { if (!input || (!(input instanceof Map) && typeof input !== 'object')) { return null; } // make a differ for whatever type we've been passed in this.differ ??= this.differs.find(input).create(); const differChanges: KeyValueChanges<K, V> | null = this.differ.diff(input as any); const compareFnChanged = compareFn !== this.compareFn; if (differChanges) { this.keyValues = []; differChanges.forEachItem((r: KeyValueChangeRecord<K, V>) => { this.keyValues.push(makeKeyValuePair(r.key, r.currentValue!)); }); } if (differChanges || compareFnChanged) { if (compareFn) { this.keyValues.sort(compareFn); } this.compareFn = compareFn; } return this.keyValues; } } export function defaultComparator<K, V>( keyValueA: KeyValue<K, V>, keyValueB: KeyValue<K, V>, ): number { const a = keyValueA.key; const b = keyValueB.key; // if same exit with 0; if (a === b) return 0; // make sure that undefined are at the end of the sort. if (a === undefined) return 1; if (b === undefined) return -1; // make sure that nulls are at the end of the sort. if (a === null) return 1; if (b === null) return -1; if (typeof a == 'string' && typeof b == 'string') { return a < b ? -1 : 1; } if (typeof a == 'number' && typeof b == 'number') { return a - b; } if (typeof a == 'boolean' && typeof b == 'boolean') { return a < b ? -1 : 1; } // `a` and `b` are of different types. Compare their string values. const aString = String(a); const bString = String(b); return aString == bString ? 0 : aString < bString ? -1 : 1; }
{ "end_byte": 5004, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/keyvalue_pipe.ts" }
angular/packages/common/src/pipes/case_conversion_pipes.ts_0_4
/**
{ "end_byte": 4, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/case_conversion_pipes.ts" }
angular/packages/common/src/pipes/case_conversion_pipes.ts_4_3153
0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE
{ "end_byte": 3153, "start_byte": 4, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/case_conversion_pipes.ts" }
angular/packages/common/src/pipes/case_conversion_pipes.ts_3153_4306
u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\
{ "end_byte": 4306, "start_byte": 3153, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/case_conversion_pipes.ts" }
angular/packages/common/src/pipes/case_conversion_pipes.ts_4306_7854
\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])
{ "end_byte": 7854, "start_byte": 4306, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/case_conversion_pipes.ts" }
angular/packages/common/src/pipes/case_conversion_pipes.ts_7854_11664
\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])\S*/g; /** * Transforms text to title case. * Capitalizes the first letter of each word and transforms the * rest of the word to lower case. * Words are delimited by any whitespace character, such as a space, tab, or line-feed character. * * @see {@link LowerCasePipe} * @see {@link UpperCasePipe} * * @usageNotes * The following example shows the result of transforming various strings into title case. * * <code-example path="common/pipes/ts/titlecase_pipe.ts" region='TitleCasePipe'></code-example> * * @ngModule CommonModule * @publicApi */ @Pipe({ name: 'titlecase', standalone: true, }) export class TitleCasePipe implements PipeTransform { /** * @param value The string to transform to title case. */ transform(value: string): string; transform(value: null | undefined): null; transform(value: string | null | undefined): string | null; transform(value: string | null | undefined): string | null { if (value == null) return null; if (typeof value !== 'string') { throw invalidPipeArgumentError(TitleCasePipe, value); } return value.replace( unicodeWordMatch, (txt) => txt[0].toUpperCase() + txt.slice(1).toLowerCase(), ); } } /** * Transforms text to all upper case. * @see {@link LowerCasePipe} * @see {@link TitleCasePipe} * * @ngModule CommonModule * @publicApi */ @Pipe({ name: 'uppercase', standalone: true, }) export class UpperCasePipe implements PipeTransform { /** * @param value The string to transform to upper case. */ transform(value: string): string; transform(value: null | undefined): null; transform(value: string | null | undefined): string | null; transform(value: string | null | undefined): string | null { if (value == null) return null; if (typeof value !== 'string') { throw invalidPipeArgumentError(UpperCasePipe, value); } return value.toUpperCase(); } }
{ "end_byte": 11664, "start_byte": 7854, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/case_conversion_pipes.ts" }
angular/packages/common/src/pipes/i18n_plural_pipe.ts_0_1658
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Pipe, PipeTransform} from '@angular/core'; import {getPluralCategory, NgLocalization} from '../i18n/localization'; import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; const _INTERPOLATION_REGEXP: RegExp = /#/g; /** * @ngModule CommonModule * @description * * Maps a value to a string that pluralizes the value according to locale rules. * * @usageNotes * * ### Example * * {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'} * * @publicApi */ @Pipe({ name: 'i18nPlural', standalone: true, }) export class I18nPluralPipe implements PipeTransform { constructor(private _localization: NgLocalization) {} /** * @param value the number to be formatted * @param pluralMap an object that mimics the ICU format, see * https://unicode-org.github.io/icu/userguide/format_parse/messages/. * @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by * default). */ transform( value: number | null | undefined, pluralMap: {[count: string]: string}, locale?: string, ): string { if (value == null) return ''; if (typeof pluralMap !== 'object' || pluralMap === null) { throw invalidPipeArgumentError(I18nPluralPipe, pluralMap); } const key = getPluralCategory(value, Object.keys(pluralMap), this._localization, locale); return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString()); } }
{ "end_byte": 1658, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/i18n_plural_pipe.ts" }
angular/packages/common/src/pipes/index.ts_0_1494
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * @module * @description * This module provides a set of common Pipes. */ import {AsyncPipe} from './async_pipe'; import {LowerCasePipe, TitleCasePipe, UpperCasePipe} from './case_conversion_pipes'; import {DATE_PIPE_DEFAULT_OPTIONS, DATE_PIPE_DEFAULT_TIMEZONE, DatePipe} from './date_pipe'; import {DatePipeConfig} from './date_pipe_config'; import {I18nPluralPipe} from './i18n_plural_pipe'; import {I18nSelectPipe} from './i18n_select_pipe'; import {JsonPipe} from './json_pipe'; import {KeyValue, KeyValuePipe} from './keyvalue_pipe'; import {CurrencyPipe, DecimalPipe, PercentPipe} from './number_pipe'; import {SlicePipe} from './slice_pipe'; export { AsyncPipe, CurrencyPipe, DATE_PIPE_DEFAULT_OPTIONS, DATE_PIPE_DEFAULT_TIMEZONE, DatePipe, DatePipeConfig, DecimalPipe, I18nPluralPipe, I18nSelectPipe, JsonPipe, KeyValue, KeyValuePipe, LowerCasePipe, PercentPipe, SlicePipe, TitleCasePipe, UpperCasePipe, }; /** * A collection of Angular pipes that are likely to be used in each and every application. */ export const COMMON_PIPES = [ AsyncPipe, UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, TitleCasePipe, CurrencyPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, KeyValuePipe, ];
{ "end_byte": 1494, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/index.ts" }
angular/packages/common/src/pipes/date_pipe.ts_0_2051
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Inject, InjectionToken, LOCALE_ID, Optional, Pipe, PipeTransform} from '@angular/core'; import {formatDate} from '../i18n/format_date'; import {DatePipeConfig, DEFAULT_DATE_FORMAT} from './date_pipe_config'; import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; /** * Optionally-provided default timezone to use for all instances of `DatePipe` (such as `'+0430'`). * If the value isn't provided, the `DatePipe` will use the end-user's local system timezone. * * @deprecated use DATE_PIPE_DEFAULT_OPTIONS token to configure DatePipe */ export const DATE_PIPE_DEFAULT_TIMEZONE = new InjectionToken<string>( ngDevMode ? 'DATE_PIPE_DEFAULT_TIMEZONE' : '', ); /** * DI token that allows to provide default configuration for the `DatePipe` instances in an * application. The value is an object which can include the following fields: * - `dateFormat`: configures the default date format. If not provided, the `DatePipe` * will use the 'mediumDate' as a value. * - `timezone`: configures the default timezone. If not provided, the `DatePipe` will * use the end-user's local system timezone. * * @see {@link DatePipeConfig} * * @usageNotes * * Various date pipe default values can be overwritten by providing this token with * the value that has this interface. * * For example: * * Override the default date format by providing a value using the token: * ```typescript * providers: [ * {provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {dateFormat: 'shortDate'}} * ] * ``` * * Override the default timezone by providing a value using the token: * ```typescript * providers: [ * {provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {timezone: '-1200'}} * ] * ``` */ export const DATE_PIPE_DEFAULT_OPTIONS = new InjectionToken<DatePipeConfig>( ngDevMode ? 'DATE_PIPE_DEFAULT_OPTIONS' : '', );
{ "end_byte": 2051, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/date_pipe.ts" }
angular/packages/common/src/pipes/date_pipe.ts_0_12169
/** * @ngModule CommonModule * @description * * Formats a date value according to locale rules. * * `DatePipe` is executed only when it detects a pure change to the input value. * A pure change is either a change to a primitive input value * (such as `String`, `Number`, `Boolean`, or `Symbol`), * or a changed object reference (such as `Date`, `Array`, `Function`, or `Object`). * * Note that mutating a `Date` object does not cause the pipe to be rendered again. * To ensure that the pipe is executed, you must create a new `Date` object. * * Only the `en-US` locale data comes with Angular. To localize dates * in another language, you must import the corresponding locale data. * See the [I18n guide](guide/i18n/format-data-locale) for more information. * * The time zone of the formatted value can be specified either by passing it in as the second * parameter of the pipe, or by setting the default through the `DATE_PIPE_DEFAULT_OPTIONS` * injection token. The value that is passed in as the second parameter takes precedence over * the one defined using the injection token. * * @see {@link formatDate} * * * @usageNotes * * The result of this pipe is not reevaluated when the input is mutated. To avoid the need to * reformat the date on every change-detection cycle, treat the date as an immutable object * and change the reference when the pipe needs to run again. * * ### Pre-defined format options * * | Option | Equivalent to | Examples (given in `en-US` locale) | * |---------------|-------------------------------------|-------------------------------------------------| * | `'short'` | `'M/d/yy, h:mm a'` | `6/15/15, 9:03 AM` | * | `'medium'` | `'MMM d, y, h:mm:ss a'` | `Jun 15, 2015, 9:03:01 AM` | * | `'long'` | `'MMMM d, y, h:mm:ss a z'` | `June 15, 2015 at 9:03:01 AM GMT+1` | * | `'full'` | `'EEEE, MMMM d, y, h:mm:ss a zzzz'` | `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00` | * | `'shortDate'` | `'M/d/yy'` | `6/15/15` | * | `'mediumDate'`| `'MMM d, y'` | `Jun 15, 2015` | * | `'longDate'` | `'MMMM d, y'` | `June 15, 2015` | * | `'fullDate'` | `'EEEE, MMMM d, y'` | `Monday, June 15, 2015` | * | `'shortTime'` | `'h:mm a'` | `9:03 AM` | * | `'mediumTime'`| `'h:mm:ss a'` | `9:03:01 AM` | * | `'longTime'` | `'h:mm:ss a z'` | `9:03:01 AM GMT+1` | * | `'fullTime'` | `'h:mm:ss a zzzz'` | `9:03:01 AM GMT+01:00` | * * ### Custom format options * * You can construct a format string using symbols to specify the components * of a date-time value, as described in the following table. * Format details depend on the locale. * Fields marked with (*) are only available in the extra data set for the given locale. * * | Field type | Format | Description | Example Value | * |-------------------------|-------------|---------------------------------------------------------------|------------------------------------------------------------| * | Era | G, GG & GGG | Abbreviated | AD | * | | GGGG | Wide | Anno Domini | * | | GGGGG | Narrow | A | * | Year | y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 | * | | yy | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 | * | | yyy | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 | * | | yyyy | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 | * | ISO Week-numbering year | Y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 | * | | YY | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 | * | | YYY | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 | * | | YYYY | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 | * | Month | M | Numeric: 1 digit | 9, 12 | * | | MM | Numeric: 2 digits + zero padded | 09, 12 | * | | MMM | Abbreviated | Sep | * | | MMMM | Wide | September | * | | MMMMM | Narrow | S | * | Month standalone | L | Numeric: 1 digit | 9, 12 | * | | LL | Numeric: 2 digits + zero padded | 09, 12 | * | | LLL | Abbreviated | Sep | * | | LLLL | Wide | September | * | | LLLLL | Narrow | S | * | ISO Week of year | w | Numeric: minimum digits | 1... 53 | * | | ww | Numeric: 2 digits + zero padded | 01... 53 | * | Week of month | W | Numeric: 1 digit | 1... 5 | * | Day of month | d | Numeric: minimum digits | 1 | * | | dd | Numeric: 2 digits + zero padded | 01 | * | Week day | E, EE & EEE | Abbreviated | Tue | * | | EEEE | Wide | Tuesday | * | | EEEEE | Narrow | T | * | | EEEEEE | Short | Tu | * | Week day standalone | c, cc | Numeric: 1 digit | 2 | * | | ccc | Abbreviated | Tue | * | | cccc | Wide | Tuesday | * | | ccccc | Narrow | T | * | | cccccc | Short | Tu | * | Period | a, aa & aaa | Abbreviated | am/pm or AM/PM | * | | aaaa | Wide (fallback to `a` when missing) | ante meridiem/post meridiem | * | | aaaaa | Narrow | a/p | * | Period* | B, BB & BBB | Abbreviated | mid. | * | | BBBB | Wide | am, pm, midnight, noon, morning, afternoon, evening, night | * | | BBBBB | Narrow | md | * | Period standalone* | b, bb & bbb | Abbreviated | mid. | * | | bbbb | Wide | am, pm, midnight, noon, morning, afternoon, evening, night | * | | bbbbb | Narrow | md | * | Hour 1-12 | h | Numeric: minimum digits | 1, 12 | * | | hh | Numeric: 2 digits + zero padded | 01, 12 | * | Hour 0-23 | H | Numeric: minimum digits | 0, 23 | * | | HH | Numeric: 2 digits + zero padded | 00, 23 | * | Minute | m | Numeric: minimum digits | 8, 59 | * | | mm | Numeric: 2 digits + zero padded | 08, 59 |
{ "end_byte": 12169, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/date_pipe.ts" }
angular/packages/common/src/pipes/date_pipe.ts_12170_19935
* | Period* | B, BB & BBB | Abbreviated | mid. | * | | BBBB | Wide | am, pm, midnight, noon, morning, afternoon, evening, night | * | | BBBBB | Narrow | md | * | Period standalone* | b, bb & bbb | Abbreviated | mid. | * | | bbbb | Wide | am, pm, midnight, noon, morning, afternoon, evening, night | * | | bbbbb | Narrow | md | * | Hour 1-12 | h | Numeric: minimum digits | 1, 12 | * | | hh | Numeric: 2 digits + zero padded | 01, 12 | * | Hour 0-23 | H | Numeric: minimum digits | 0, 23 | * | | HH | Numeric: 2 digits + zero padded | 00, 23 | * | Minute | m | Numeric: minimum digits | 8, 59 | * | | mm | Numeric: 2 digits + zero padded | 08, 59 | * | Second | s | Numeric: minimum digits | 0... 59 | * | | ss | Numeric: 2 digits + zero padded | 00... 59 | * | Fractional seconds | S | Numeric: 1 digit | 0... 9 | * | | SS | Numeric: 2 digits + zero padded | 00... 99 | * | | SSS | Numeric: 3 digits + zero padded (= milliseconds) | 000... 999 | * | Zone | z, zz & zzz | Short specific non location format (fallback to O) | GMT-8 | * | | zzzz | Long specific non location format (fallback to OOOO) | GMT-08:00 | * | | Z, ZZ & ZZZ | ISO8601 basic format | -0800 | * | | ZZZZ | Long localized GMT format | GMT-8:00 | * | | ZZZZZ | ISO8601 extended format + Z indicator for offset 0 (= XXXXX) | -08:00 | * | | O, OO & OOO | Short localized GMT format | GMT-8 | * | | OOOO | Long localized GMT format | GMT-08:00 | * * * ### Format examples * * These examples transform a date into various formats, * assuming that `dateObj` is a JavaScript `Date` object for * year: 2015, month: 6, day: 15, hour: 21, minute: 43, second: 11, * given in the local time for the `en-US` locale. * * ``` * {{ dateObj | date }} // output is 'Jun 15, 2015' * {{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM' * {{ dateObj | date:'shortTime' }} // output is '9:43 PM' * {{ dateObj | date:'mm:ss' }} // output is '43:11' * {{ dateObj | date:"MMM dd, yyyy 'at' hh:mm a" }} // output is 'Jun 15, 2015 at 09:43 PM' * ``` * * ### Usage example * * The following component uses a date pipe to display the current date in different formats. * * ``` * @Component({ * selector: 'date-pipe', * template: `<div> * <p>Today is {{today | date}}</p> * <p>Or if you prefer, {{today | date:'fullDate'}}</p> * <p>The time is {{today | date:'h:mm a z'}}</p> * </div>` * }) * // Get the current date and time as a date-time value. * export class DatePipeComponent { * today: number = Date.now(); * } * ``` * * @publicApi */ @Pipe({ name: 'date', standalone: true, }) export class DatePipe implements PipeTransform { constructor( @Inject(LOCALE_ID) private locale: string, @Inject(DATE_PIPE_DEFAULT_TIMEZONE) @Optional() private defaultTimezone?: string | null, @Inject(DATE_PIPE_DEFAULT_OPTIONS) @Optional() private defaultOptions?: DatePipeConfig | null, ) {} /** * @param value The date expression: a `Date` object, a number * (milliseconds since UTC epoch), or an ISO string (https://www.w3.org/TR/NOTE-datetime). * @param format The date/time components to include, using predefined options or a * custom format string. When not provided, the `DatePipe` looks for the value using the * `DATE_PIPE_DEFAULT_OPTIONS` injection token (and reads the `dateFormat` property). * If the token is not configured, the `mediumDate` is used as a value. * @param timezone A timezone offset (such as `'+0430'`). When not provided, the `DatePipe` * looks for the value using the `DATE_PIPE_DEFAULT_OPTIONS` injection token (and reads * the `timezone` property). If the token is not configured, the end-user's local system * timezone is used as a value. * @param locale A locale code for the locale format rules to use. * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default. * See [Setting your app locale](guide/i18n/locale-id). * * @see {@link DATE_PIPE_DEFAULT_OPTIONS} * * @returns A date string in the desired format. */ transform( value: Date | string | number, format?: string, timezone?: string, locale?: string, ): string | null; transform(value: null | undefined, format?: string, timezone?: string, locale?: string): null; transform( value: Date | string | number | null | undefined, format?: string, timezone?: string, locale?: string, ): string | null; transform( value: Date | string | number | null | undefined, format?: string, timezone?: string, locale?: string, ): string | null { if (value == null || value === '' || value !== value) return null; try { const _format = format ?? this.defaultOptions?.dateFormat ?? DEFAULT_DATE_FORMAT; const _timezone = timezone ?? this.defaultOptions?.timezone ?? this.defaultTimezone ?? undefined; return formatDate(value, _format, locale || this.locale, _timezone); } catch (error) { throw invalidPipeArgumentError(DatePipe, (error as Error).message); } } }
{ "end_byte": 19935, "start_byte": 12170, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/date_pipe.ts" }
angular/packages/common/src/pipes/json_pipe.ts_0_913
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Pipe, PipeTransform} from '@angular/core'; /** * @ngModule CommonModule * @description * * Converts a value into its JSON-format representation. Useful for debugging. * * @usageNotes * * The following component uses a JSON pipe to convert an object * to JSON format, and displays the string in both formats for comparison. * * {@example common/pipes/ts/json_pipe.ts region='JsonPipe'} * * @publicApi */ @Pipe({ name: 'json', pure: false, standalone: true, }) export class JsonPipe implements PipeTransform { /** * @param value A value of any type to convert into a JSON-format string. */ transform(value: any): string { return JSON.stringify(value, null, 2); } }
{ "end_byte": 913, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/json_pipe.ts" }
angular/packages/common/src/pipes/number_pipe.ts_0_6195
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {DEFAULT_CURRENCY_CODE, Inject, LOCALE_ID, Pipe, PipeTransform} from '@angular/core'; import {formatCurrency, formatNumber, formatPercent} from '../i18n/format_number'; import {getCurrencySymbol} from '../i18n/locale_data_api'; import {invalidPipeArgumentError} from './invalid_pipe_argument_error'; /** * @ngModule CommonModule * @description * * Formats a value according to digit options and locale rules. * Locale determines group sizing and separator, * decimal point character, and other locale-specific configurations. * * @see {@link formatNumber} * * @usageNotes * * ### digitsInfo * * The value's decimal representation is specified by the `digitsInfo` * parameter, written in the following format:<br> * * ``` * {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits} * ``` * * - `minIntegerDigits`: * The minimum number of integer digits before the decimal point. * Default is 1. * * - `minFractionDigits`: * The minimum number of digits after the decimal point. * Default is 0. * * - `maxFractionDigits`: * The maximum number of digits after the decimal point. * Default is 3. * * If the formatted value is truncated it will be rounded using the "to-nearest" method: * * ``` * {{3.6 | number: '1.0-0'}} * <!--will output '4'--> * * {{-3.6 | number:'1.0-0'}} * <!--will output '-4'--> * ``` * * ### locale * * `locale` will format a value according to locale rules. * Locale determines group sizing and separator, * decimal point character, and other locale-specific configurations. * * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default. * * See [Setting your app locale](guide/i18n/locale-id). * * ### Example * * The following code shows how the pipe transforms values * according to various format specifications, * where the caller's default locale is `en-US`. * * <code-example path="common/pipes/ts/number_pipe.ts" region='NumberPipe'></code-example> * * @publicApi */ @Pipe({ name: 'number', standalone: true, }) export class DecimalPipe implements PipeTransform { constructor(@Inject(LOCALE_ID) private _locale: string) {} /** * @param value The value to be formatted. * @param digitsInfo Sets digit and decimal representation. * [See more](#digitsinfo). * @param locale Specifies what locale format rules to use. * [See more](#locale). */ transform(value: number | string, digitsInfo?: string, locale?: string): string | null; transform(value: null | undefined, digitsInfo?: string, locale?: string): null; transform( value: number | string | null | undefined, digitsInfo?: string, locale?: string, ): string | null; transform( value: number | string | null | undefined, digitsInfo?: string, locale?: string, ): string | null { if (!isValue(value)) return null; locale ||= this._locale; try { const num = strToNumber(value); return formatNumber(num, locale, digitsInfo); } catch (error) { throw invalidPipeArgumentError(DecimalPipe, (error as Error).message); } } } /** * @ngModule CommonModule * @description * * Transforms a number to a percentage * string, formatted according to locale rules that determine group sizing and * separator, decimal-point character, and other locale-specific * configurations. * * @see {@link formatPercent} * * @usageNotes * The following code shows how the pipe transforms numbers * into text strings, according to various format specifications, * where the caller's default locale is `en-US`. * * <code-example path="common/pipes/ts/percent_pipe.ts" region='PercentPipe'></code-example> * * @publicApi */ @Pipe({ name: 'percent', standalone: true, }) export class PercentPipe implements PipeTransform { constructor(@Inject(LOCALE_ID) private _locale: string) {} transform(value: number | string, digitsInfo?: string, locale?: string): string | null; transform(value: null | undefined, digitsInfo?: string, locale?: string): null; transform( value: number | string | null | undefined, digitsInfo?: string, locale?: string, ): string | null; /** * * @param value The number to be formatted as a percentage. * @param digitsInfo Decimal representation options, specified by a string * in the following format:<br> * <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>. * - `minIntegerDigits`: The minimum number of integer digits before the decimal point. * Default is `1`. * - `minFractionDigits`: The minimum number of digits after the decimal point. * Default is `0`. * - `maxFractionDigits`: The maximum number of digits after the decimal point. * Default is `0`. * @param locale A locale code for the locale format rules to use. * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default. * See [Setting your app locale](guide/i18n/locale-id). */ transform( value: number | string | null | undefined, digitsInfo?: string, locale?: string, ): string | null { if (!isValue(value)) return null; locale ||= this._locale; try { const num = strToNumber(value); return formatPercent(num, locale, digitsInfo); } catch (error) { throw invalidPipeArgumentError(PercentPipe, (error as Error).message); } } } /** * @ngModule CommonModule * @description * * Transforms a number to a currency string, formatted according to locale rules * that determine group sizing and separator, decimal-point character, * and other locale-specific configurations. * * * @see {@link getCurrencySymbol} * @see {@link formatCurrency} * * @usageNotes * The following code shows how the pipe transforms numbers * into text strings, according to various format specifications, * where the caller's default locale is `en-US`. * * <code-example path="common/pipes/ts/currency_pipe.ts" region='CurrencyPipe'></code-example> * * @publicApi */
{ "end_byte": 6195, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/number_pipe.ts" }
angular/packages/common/src/pipes/number_pipe.ts_6196_10939
@Pipe({ name: 'currency', standalone: true, }) export class CurrencyPipe implements PipeTransform { constructor( @Inject(LOCALE_ID) private _locale: string, @Inject(DEFAULT_CURRENCY_CODE) private _defaultCurrencyCode: string = 'USD', ) {} /** * * @param value The number to be formatted as currency. * @param currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, * such as `USD` for the US dollar and `EUR` for the euro. The default currency code can be * configured using the `DEFAULT_CURRENCY_CODE` injection token. * @param display The format for the currency indicator. One of the following: * - `code`: Show the code (such as `USD`). * - `symbol`(default): Show the symbol (such as `$`). * - `symbol-narrow`: Use the narrow symbol for locales that have two symbols for their * currency. * For example, the Canadian dollar CAD has the symbol `CA$` and the symbol-narrow `$`. If the * locale has no narrow symbol, uses the standard symbol for the locale. * - String: Use the given string value instead of a code or a symbol. * For example, an empty string will suppress the currency & symbol. * - Boolean (marked deprecated in v5): `true` for symbol and false for `code`. * * @param digitsInfo Decimal representation options, specified by a string * in the following format:<br> * <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>. * - `minIntegerDigits`: The minimum number of integer digits before the decimal point. * Default is `1`. * - `minFractionDigits`: The minimum number of digits after the decimal point. * Default is `2`. * - `maxFractionDigits`: The maximum number of digits after the decimal point. * Default is `2`. * If not provided, the number will be formatted with the proper amount of digits, * depending on what the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) specifies. * For example, the Canadian dollar has 2 digits, whereas the Chilean peso has none. * @param locale A locale code for the locale format rules to use. * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default. * See [Setting your app locale](guide/i18n/locale-id). */ transform( value: number | string, currencyCode?: string, display?: 'code' | 'symbol' | 'symbol-narrow' | string | boolean, digitsInfo?: string, locale?: string, ): string | null; transform( value: null | undefined, currencyCode?: string, display?: 'code' | 'symbol' | 'symbol-narrow' | string | boolean, digitsInfo?: string, locale?: string, ): null; transform( value: number | string | null | undefined, currencyCode?: string, display?: 'code' | 'symbol' | 'symbol-narrow' | string | boolean, digitsInfo?: string, locale?: string, ): string | null; transform( value: number | string | null | undefined, currencyCode: string = this._defaultCurrencyCode, display: 'code' | 'symbol' | 'symbol-narrow' | string | boolean = 'symbol', digitsInfo?: string, locale?: string, ): string | null { if (!isValue(value)) return null; locale ||= this._locale; if (typeof display === 'boolean') { if ((typeof ngDevMode === 'undefined' || ngDevMode) && <any>console && <any>console.warn) { console.warn( `Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are "code", "symbol" or "symbol-narrow".`, ); } display = display ? 'symbol' : 'code'; } let currency: string = currencyCode || this._defaultCurrencyCode; if (display !== 'code') { if (display === 'symbol' || display === 'symbol-narrow') { currency = getCurrencySymbol(currency, display === 'symbol' ? 'wide' : 'narrow', locale); } else { currency = display; } } try { const num = strToNumber(value); return formatCurrency(num, locale, currency, currencyCode, digitsInfo); } catch (error) { throw invalidPipeArgumentError(CurrencyPipe, (error as Error).message); } } } function isValue(value: number | string | null | undefined): value is number | string { return !(value == null || value === '' || value !== value); } /** * Transforms a string into a number (if needed). */ function strToNumber(value: number | string): number { // Convert strings to numbers if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) { return Number(value); } if (typeof value !== 'number') { throw new Error(`${value} is not a number`); } return value; }
{ "end_byte": 10939, "start_byte": 6196, "url": "https://github.com/angular/angular/blob/main/packages/common/src/pipes/number_pipe.ts" }
angular/packages/common/src/i18n/format_date.ts_0_7153
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { FormatWidth, FormStyle, getLocaleDateFormat, getLocaleDateTimeFormat, getLocaleDayNames, getLocaleDayPeriods, getLocaleEraNames, getLocaleExtraDayPeriodRules, getLocaleExtraDayPeriods, getLocaleId, getLocaleMonthNames, getLocaleNumberSymbol, getLocaleTimeFormat, NumberSymbol, Time, TranslationWidth, } from './locale_data_api'; export const ISO8601_DATE_REGEX = /^(\d{4,})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; // 1 2 3 4 5 6 7 8 9 10 11 const NAMED_FORMATS: {[localeId: string]: {[format: string]: string}} = {}; const DATE_FORMATS_SPLIT = /((?:[^BEGHLMOSWYZabcdhmswyz']+)|(?:'(?:[^']|'')*')|(?:G{1,5}|y{1,4}|Y{1,4}|M{1,5}|L{1,5}|w{1,2}|W{1}|d{1,2}|E{1,6}|c{1,6}|a{1,5}|b{1,5}|B{1,5}|h{1,2}|H{1,2}|m{1,2}|s{1,2}|S{1,3}|z{1,4}|Z{1,5}|O{1,4}))([\s\S]*)/; enum ZoneWidth { Short, ShortGMT, Long, Extended, } enum DateType { FullYear, Month, Date, Hours, Minutes, Seconds, FractionalSeconds, Day, } enum TranslationType { DayPeriods, Days, Months, Eras, } /** * @ngModule CommonModule * @description * * Formats a date according to locale rules. * * @param value The date to format, as a Date, or a number (milliseconds since UTC epoch) * or an [ISO date-time string](https://www.w3.org/TR/NOTE-datetime). * @param format The date-time components to include. See `DatePipe` for details. * @param locale A locale code for the locale format rules to use. * @param timezone The time zone. A time zone offset from GMT (such as `'+0430'`). * If not specified, uses host system settings. * * @returns The formatted date string. * * @see {@link DatePipe} * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi */ export function formatDate( value: string | number | Date, format: string, locale: string, timezone?: string, ): string { let date = toDate(value); const namedFormat = getNamedFormat(locale, format); format = namedFormat || format; let parts: string[] = []; let match; while (format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = parts.concat(match.slice(1)); const part = parts.pop(); if (!part) { break; } format = part; } else { parts.push(format); break; } } let dateTimezoneOffset = date.getTimezoneOffset(); if (timezone) { dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); date = convertTimezoneToLocal(date, timezone, true); } let text = ''; parts.forEach((value) => { const dateFormatter = getDateFormatter(value); text += dateFormatter ? dateFormatter(date, locale, dateTimezoneOffset) : value === "''" ? "'" : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; } /** * Create a new Date object with the given date value, and the time set to midnight. * * We cannot use `new Date(year, month, date)` because it maps years between 0 and 99 to 1900-1999. * See: https://github.com/angular/angular/issues/40377 * * Note that this function returns a Date object whose time is midnight in the current locale's * timezone. In the future we might want to change this to be midnight in UTC, but this would be a * considerable breaking change. */ function createDate(year: number, month: number, date: number): Date { // The `newDate` is set to midnight (UTC) on January 1st 1970. // - In PST this will be December 31st 1969 at 4pm. // - In GMT this will be January 1st 1970 at 1am. // Note that they even have different years, dates and months! const newDate = new Date(0); // `setFullYear()` allows years like 0001 to be set correctly. This function does not // change the internal time of the date. // Consider calling `setFullYear(2019, 8, 20)` (September 20, 2019). // - In PST this will now be September 20, 2019 at 4pm // - In GMT this will now be September 20, 2019 at 1am newDate.setFullYear(year, month, date); // We want the final date to be at local midnight, so we reset the time. // - In PST this will now be September 20, 2019 at 12am // - In GMT this will now be September 20, 2019 at 12am newDate.setHours(0, 0, 0); return newDate; } function getNamedFormat(locale: string, format: string): string { const localeId = getLocaleId(locale); NAMED_FORMATS[localeId] ??= {}; if (NAMED_FORMATS[localeId][format]) { return NAMED_FORMATS[localeId][format]; } let formatValue = ''; switch (format) { case 'shortDate': formatValue = getLocaleDateFormat(locale, FormatWidth.Short); break; case 'mediumDate': formatValue = getLocaleDateFormat(locale, FormatWidth.Medium); break; case 'longDate': formatValue = getLocaleDateFormat(locale, FormatWidth.Long); break; case 'fullDate': formatValue = getLocaleDateFormat(locale, FormatWidth.Full); break; case 'shortTime': formatValue = getLocaleTimeFormat(locale, FormatWidth.Short); break; case 'mediumTime': formatValue = getLocaleTimeFormat(locale, FormatWidth.Medium); break; case 'longTime': formatValue = getLocaleTimeFormat(locale, FormatWidth.Long); break; case 'fullTime': formatValue = getLocaleTimeFormat(locale, FormatWidth.Full); break; case 'short': const shortTime = getNamedFormat(locale, 'shortTime'); const shortDate = getNamedFormat(locale, 'shortDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Short), [ shortTime, shortDate, ]); break; case 'medium': const mediumTime = getNamedFormat(locale, 'mediumTime'); const mediumDate = getNamedFormat(locale, 'mediumDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Medium), [ mediumTime, mediumDate, ]); break; case 'long': const longTime = getNamedFormat(locale, 'longTime'); const longDate = getNamedFormat(locale, 'longDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Long), [ longTime, longDate, ]); break; case 'full': const fullTime = getNamedFormat(locale, 'fullTime'); const fullDate = getNamedFormat(locale, 'fullDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Full), [ fullTime, fullDate, ]); break; } if (formatValue) { NAMED_FORMATS[localeId][format] = formatValue; } return formatValue; } function formatDateTime(str: string, opt_values: string[]) { if (opt_values) { str = str.replace(/\{([^}]+)}/g, function (match, key) { return opt_values != null && key in opt_values ? opt_values[key] : match; }); } return str; }
{ "end_byte": 7153, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/format_date.ts" }
angular/packages/common/src/i18n/format_date.ts_7155_14891
function padNumber( num: number, digits: number, minusSign = '-', trim?: boolean, negWrap?: boolean, ): string { let neg = ''; if (num < 0 || (negWrap && num <= 0)) { if (negWrap) { num = -num + 1; } else { num = -num; neg = minusSign; } } let strNum = String(num); while (strNum.length < digits) { strNum = '0' + strNum; } if (trim) { strNum = strNum.slice(strNum.length - digits); } return neg + strNum; } function formatFractionalSeconds(milliseconds: number, digits: number): string { const strMs = padNumber(milliseconds, 3); return strMs.substring(0, digits); } /** * Returns a date formatter that transforms a date into its locale digit representation */ function dateGetter( name: DateType, size: number, offset: number = 0, trim = false, negWrap = false, ): DateFormatter { return function (date: Date, locale: string): string { let part = getDatePart(name, date); if (offset > 0 || part > -offset) { part += offset; } if (name === DateType.Hours) { if (part === 0 && offset === -12) { part = 12; } } else if (name === DateType.FractionalSeconds) { return formatFractionalSeconds(part, size); } const localeMinus = getLocaleNumberSymbol(locale, NumberSymbol.MinusSign); return padNumber(part, size, localeMinus, trim, negWrap); }; } function getDatePart(part: DateType, date: Date): number { switch (part) { case DateType.FullYear: return date.getFullYear(); case DateType.Month: return date.getMonth(); case DateType.Date: return date.getDate(); case DateType.Hours: return date.getHours(); case DateType.Minutes: return date.getMinutes(); case DateType.Seconds: return date.getSeconds(); case DateType.FractionalSeconds: return date.getMilliseconds(); case DateType.Day: return date.getDay(); default: throw new Error(`Unknown DateType value "${part}".`); } } /** * Returns a date formatter that transforms a date into its locale string representation */ function dateStrGetter( name: TranslationType, width: TranslationWidth, form: FormStyle = FormStyle.Format, extended = false, ): DateFormatter { return function (date: Date, locale: string): string { return getDateTranslation(date, locale, name, width, form, extended); }; } /** * Returns the locale translation of a date for a given form, type and width */ function getDateTranslation( date: Date, locale: string, name: TranslationType, width: TranslationWidth, form: FormStyle, extended: boolean, ) { switch (name) { case TranslationType.Months: return getLocaleMonthNames(locale, form, width)[date.getMonth()]; case TranslationType.Days: return getLocaleDayNames(locale, form, width)[date.getDay()]; case TranslationType.DayPeriods: const currentHours = date.getHours(); const currentMinutes = date.getMinutes(); if (extended) { const rules = getLocaleExtraDayPeriodRules(locale); const dayPeriods = getLocaleExtraDayPeriods(locale, form, width); const index = rules.findIndex((rule) => { if (Array.isArray(rule)) { // morning, afternoon, evening, night const [from, to] = rule; const afterFrom = currentHours >= from.hours && currentMinutes >= from.minutes; const beforeTo = currentHours < to.hours || (currentHours === to.hours && currentMinutes < to.minutes); // We must account for normal rules that span a period during the day (e.g. 6am-9am) // where `from` is less (earlier) than `to`. But also rules that span midnight (e.g. // 10pm - 5am) where `from` is greater (later!) than `to`. // // In the first case the current time must be BOTH after `from` AND before `to` // (e.g. 8am is after 6am AND before 10am). // // In the second case the current time must be EITHER after `from` OR before `to` // (e.g. 4am is before 5am but not after 10pm; and 11pm is not before 5am but it is // after 10pm). if (from.hours < to.hours) { if (afterFrom && beforeTo) { return true; } } else if (afterFrom || beforeTo) { return true; } } else { // noon or midnight if (rule.hours === currentHours && rule.minutes === currentMinutes) { return true; } } return false; }); if (index !== -1) { return dayPeriods[index]; } } // if no rules for the day periods, we use am/pm by default return getLocaleDayPeriods(locale, form, <TranslationWidth>width)[currentHours < 12 ? 0 : 1]; case TranslationType.Eras: return getLocaleEraNames(locale, <TranslationWidth>width)[date.getFullYear() <= 0 ? 0 : 1]; default: // This default case is not needed by TypeScript compiler, as the switch is exhaustive. // However Closure Compiler does not understand that and reports an error in typed mode. // The `throw new Error` below works around the problem, and the unexpected: never variable // makes sure tsc still checks this code is unreachable. const unexpected: never = name; throw new Error(`unexpected translation type ${unexpected}`); } } /** * Returns a date formatter that transforms a date and an offset into a timezone with ISO8601 or * GMT format depending on the width (eg: short = +0430, short:GMT = GMT+4, long = GMT+04:30, * extended = +04:30) */ function timeZoneGetter(width: ZoneWidth): DateFormatter { return function (date: Date, locale: string, offset: number) { const zone = -1 * offset; const minusSign = getLocaleNumberSymbol(locale, NumberSymbol.MinusSign); const hours = zone > 0 ? Math.floor(zone / 60) : Math.ceil(zone / 60); switch (width) { case ZoneWidth.Short: return ( (zone >= 0 ? '+' : '') + padNumber(hours, 2, minusSign) + padNumber(Math.abs(zone % 60), 2, minusSign) ); case ZoneWidth.ShortGMT: return 'GMT' + (zone >= 0 ? '+' : '') + padNumber(hours, 1, minusSign); case ZoneWidth.Long: return ( 'GMT' + (zone >= 0 ? '+' : '') + padNumber(hours, 2, minusSign) + ':' + padNumber(Math.abs(zone % 60), 2, minusSign) ); case ZoneWidth.Extended: if (offset === 0) { return 'Z'; } else { return ( (zone >= 0 ? '+' : '') + padNumber(hours, 2, minusSign) + ':' + padNumber(Math.abs(zone % 60), 2, minusSign) ); } default: throw new Error(`Unknown zone width "${width}"`); } }; } const JANUARY = 0; const THURSDAY = 4; function getFirstThursdayOfYear(year: number) { const firstDayOfYear = createDate(year, JANUARY, 1).getDay(); return createDate( year, 0, 1 + (firstDayOfYear <= THURSDAY ? THURSDAY : THURSDAY + 7) - firstDayOfYear, ); } /** * ISO Week starts on day 1 (Monday) and ends with day 0 (Sunday) */ export function getThursdayThisIsoWeek(datetime: Date) { // getDay returns 0-6 range with sunday as 0. const currentDay = datetime.getDay(); // On a Sunday, read the previous Thursday since ISO weeks start on Monday. const deltaToThursday = currentDay === 0 ? -3 : THURSDAY - currentDay; return createDate( datetime.getFullYear(), datetime.getMonth(), datetime.getDate() + deltaToThursday, ); }
{ "end_byte": 14891, "start_byte": 7155, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/format_date.ts" }
angular/packages/common/src/i18n/format_date.ts_14893_16842
function weekGetter(size: number, monthBased = false): DateFormatter { return function (date: Date, locale: string) { let result; if (monthBased) { const nbDaysBefore1stDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1).getDay() - 1; const today = date.getDate(); result = 1 + Math.floor((today + nbDaysBefore1stDayOfMonth) / 7); } else { const thisThurs = getThursdayThisIsoWeek(date); // Some days of a year are part of next year according to ISO 8601. // Compute the firstThurs from the year of this week's Thursday const firstThurs = getFirstThursdayOfYear(thisThurs.getFullYear()); const diff = thisThurs.getTime() - firstThurs.getTime(); result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week } return padNumber(result, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign)); }; } /** * Returns a date formatter that provides the week-numbering year for the input date. */ function weekNumberingYearGetter(size: number, trim = false): DateFormatter { return function (date: Date, locale: string) { const thisThurs = getThursdayThisIsoWeek(date); const weekNumberingYear = thisThurs.getFullYear(); return padNumber( weekNumberingYear, size, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign), trim, ); }; } type DateFormatter = (date: Date, locale: string, offset: number) => string; const DATE_FORMATS: {[format: string]: DateFormatter} = {}; // Based on CLDR formats: // See complete list: http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table // See also explanations: http://cldr.unicode.org/translation/date-time // TODO(ocombe): support all missing cldr formats: U, Q, D, F, e, j, J, C, A, v, V, X, x function getDateFormatter(format: string): DateFormatter | null { if (DATE_FORMATS[format]) { return DATE_FORMATS[format]; } let formatter;
{ "end_byte": 16842, "start_byte": 14893, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/format_date.ts" }
angular/packages/common/src/i18n/format_date.ts_16845_24310
switch (format) { // Era name (AD/BC) case 'G': case 'GG': case 'GGG': formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Abbreviated); break; case 'GGGG': formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Wide); break; case 'GGGGG': formatter = dateStrGetter(TranslationType.Eras, TranslationWidth.Narrow); break; // 1 digit representation of the year, e.g. (AD 1 => 1, AD 199 => 199) case 'y': formatter = dateGetter(DateType.FullYear, 1, 0, false, true); break; // 2 digit representation of the year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) case 'yy': formatter = dateGetter(DateType.FullYear, 2, 0, true, true); break; // 3 digit representation of the year, padded (000-999). (e.g. AD 2001 => 01, AD 2010 => 10) case 'yyy': formatter = dateGetter(DateType.FullYear, 3, 0, false, true); break; // 4 digit representation of the year (e.g. AD 1 => 0001, AD 2010 => 2010) case 'yyyy': formatter = dateGetter(DateType.FullYear, 4, 0, false, true); break; // 1 digit representation of the week-numbering year, e.g. (AD 1 => 1, AD 199 => 199) case 'Y': formatter = weekNumberingYearGetter(1); break; // 2 digit representation of the week-numbering year, padded (00-99). (e.g. AD 2001 => 01, AD // 2010 => 10) case 'YY': formatter = weekNumberingYearGetter(2, true); break; // 3 digit representation of the week-numbering year, padded (000-999). (e.g. AD 1 => 001, AD // 2010 => 2010) case 'YYY': formatter = weekNumberingYearGetter(3); break; // 4 digit representation of the week-numbering year (e.g. AD 1 => 0001, AD 2010 => 2010) case 'YYYY': formatter = weekNumberingYearGetter(4); break; // Month of the year (1-12), numeric case 'M': case 'L': formatter = dateGetter(DateType.Month, 1, 1); break; case 'MM': case 'LL': formatter = dateGetter(DateType.Month, 2, 1); break; // Month of the year (January, ...), string, format case 'MMM': formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Abbreviated); break; case 'MMMM': formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Wide); break; case 'MMMMM': formatter = dateStrGetter(TranslationType.Months, TranslationWidth.Narrow); break; // Month of the year (January, ...), string, standalone case 'LLL': formatter = dateStrGetter( TranslationType.Months, TranslationWidth.Abbreviated, FormStyle.Standalone, ); break; case 'LLLL': formatter = dateStrGetter( TranslationType.Months, TranslationWidth.Wide, FormStyle.Standalone, ); break; case 'LLLLL': formatter = dateStrGetter( TranslationType.Months, TranslationWidth.Narrow, FormStyle.Standalone, ); break; // Week of the year (1, ... 52) case 'w': formatter = weekGetter(1); break; case 'ww': formatter = weekGetter(2); break; // Week of the month (1, ...) case 'W': formatter = weekGetter(1, true); break; // Day of the month (1-31) case 'd': formatter = dateGetter(DateType.Date, 1); break; case 'dd': formatter = dateGetter(DateType.Date, 2); break; // Day of the Week StandAlone (1, 1, Mon, Monday, M, Mo) case 'c': case 'cc': formatter = dateGetter(DateType.Day, 1); break; case 'ccc': formatter = dateStrGetter( TranslationType.Days, TranslationWidth.Abbreviated, FormStyle.Standalone, ); break; case 'cccc': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Wide, FormStyle.Standalone); break; case 'ccccc': formatter = dateStrGetter( TranslationType.Days, TranslationWidth.Narrow, FormStyle.Standalone, ); break; case 'cccccc': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Short, FormStyle.Standalone); break; // Day of the Week case 'E': case 'EE': case 'EEE': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Abbreviated); break; case 'EEEE': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Wide); break; case 'EEEEE': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Narrow); break; case 'EEEEEE': formatter = dateStrGetter(TranslationType.Days, TranslationWidth.Short); break; // Generic period of the day (am-pm) case 'a': case 'aa': case 'aaa': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Abbreviated); break; case 'aaaa': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Wide); break; case 'aaaaa': formatter = dateStrGetter(TranslationType.DayPeriods, TranslationWidth.Narrow); break; // Extended period of the day (midnight, at night, ...), standalone case 'b': case 'bb': case 'bbb': formatter = dateStrGetter( TranslationType.DayPeriods, TranslationWidth.Abbreviated, FormStyle.Standalone, true, ); break; case 'bbbb': formatter = dateStrGetter( TranslationType.DayPeriods, TranslationWidth.Wide, FormStyle.Standalone, true, ); break; case 'bbbbb': formatter = dateStrGetter( TranslationType.DayPeriods, TranslationWidth.Narrow, FormStyle.Standalone, true, ); break; // Extended period of the day (midnight, night, ...), standalone case 'B': case 'BB': case 'BBB': formatter = dateStrGetter( TranslationType.DayPeriods, TranslationWidth.Abbreviated, FormStyle.Format, true, ); break; case 'BBBB': formatter = dateStrGetter( TranslationType.DayPeriods, TranslationWidth.Wide, FormStyle.Format, true, ); break; case 'BBBBB': formatter = dateStrGetter( TranslationType.DayPeriods, TranslationWidth.Narrow, FormStyle.Format, true, ); break; // Hour in AM/PM, (1-12) case 'h': formatter = dateGetter(DateType.Hours, 1, -12); break; case 'hh': formatter = dateGetter(DateType.Hours, 2, -12); break; // Hour of the day (0-23) case 'H': formatter = dateGetter(DateType.Hours, 1); break; // Hour in day, padded (00-23) case 'HH': formatter = dateGetter(DateType.Hours, 2); break; // Minute of the hour (0-59) case 'm': formatter = dateGetter(DateType.Minutes, 1); break; case 'mm': formatter = dateGetter(DateType.Minutes, 2); break; // Second of the minute (0-59) case 's': formatter = dateGetter(DateType.Seconds, 1); break; case 'ss': formatter = dateGetter(DateType.Seconds, 2); break; // Fractional second case 'S': formatter = dateGetter(DateType.FractionalSeconds, 1); break; case 'SS': formatter = dateGetter(DateType.FractionalSeconds, 2); break;
{ "end_byte": 24310, "start_byte": 16845, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/format_date.ts" }
angular/packages/common/src/i18n/format_date.ts_24315_29383
case 'SSS': formatter = dateGetter(DateType.FractionalSeconds, 3); break; // Timezone ISO8601 short format (-0430) case 'Z': case 'ZZ': case 'ZZZ': formatter = timeZoneGetter(ZoneWidth.Short); break; // Timezone ISO8601 extended format (-04:30) case 'ZZZZZ': formatter = timeZoneGetter(ZoneWidth.Extended); break; // Timezone GMT short format (GMT+4) case 'O': case 'OO': case 'OOO': // Should be location, but fallback to format O instead because we don't have the data yet case 'z': case 'zz': case 'zzz': formatter = timeZoneGetter(ZoneWidth.ShortGMT); break; // Timezone GMT long format (GMT+0430) case 'OOOO': case 'ZZZZ': // Should be location, but fallback to format O instead because we don't have the data yet case 'zzzz': formatter = timeZoneGetter(ZoneWidth.Long); break; default: return null; } DATE_FORMATS[format] = formatter; return formatter; } function timezoneToOffset(timezone: string, fallback: number): number { // Support: IE 11 only, Edge 13-15+ // IE/Edge do not "understand" colon (`:`) in timezone timezone = timezone.replace(/:/g, ''); const requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000; return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset; } function addDateMinutes(date: Date, minutes: number) { date = new Date(date.getTime()); date.setMinutes(date.getMinutes() + minutes); return date; } function convertTimezoneToLocal(date: Date, timezone: string, reverse: boolean): Date { const reverseValue = reverse ? -1 : 1; const dateTimezoneOffset = date.getTimezoneOffset(); const timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); return addDateMinutes(date, reverseValue * (timezoneOffset - dateTimezoneOffset)); } /** * Converts a value to date. * * Supported input formats: * - `Date` * - number: timestamp * - string: numeric (e.g. "1234"), ISO and date strings in a format supported by * [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse). * Note: ISO strings without time return a date without timeoffset. * * Throws if unable to convert to a date. */ export function toDate(value: string | number | Date): Date { if (isDate(value)) { return value; } if (typeof value === 'number' && !isNaN(value)) { return new Date(value); } if (typeof value === 'string') { value = value.trim(); if (/^(\d{4}(-\d{1,2}(-\d{1,2})?)?)$/.test(value)) { /* For ISO Strings without time the day, month and year must be extracted from the ISO String before Date creation to avoid time offset and errors in the new Date. If we only replace '-' with ',' in the ISO String ("2015,01,01"), and try to create a new date, some browsers (e.g. IE 9) will throw an invalid Date error. If we leave the '-' ("2015-01-01") and try to create a new Date("2015-01-01") the timeoffset is applied. Note: ISO months are 0 for January, 1 for February, ... */ const [y, m = 1, d = 1] = value.split('-').map((val: string) => +val); return createDate(y, m - 1, d); } const parsedNb = parseFloat(value); // any string that only contains numbers, like "1234" but not like "1234hello" if (!isNaN((value as any) - parsedNb)) { return new Date(parsedNb); } let match: RegExpMatchArray | null; if ((match = value.match(ISO8601_DATE_REGEX))) { return isoStringToDate(match); } } const date = new Date(value as any); if (!isDate(date)) { throw new Error(`Unable to convert "${value}" into a date`); } return date; } /** * Converts a date in ISO8601 to a Date. * Used instead of `Date.parse` because of browser discrepancies. */ export function isoStringToDate(match: RegExpMatchArray): Date { const date = new Date(0); let tzHour = 0; let tzMin = 0; // match[8] means that the string contains "Z" (UTC) or a timezone like "+01:00" or "+0100" const dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear; const timeSetter = match[8] ? date.setUTCHours : date.setHours; // if there is a timezone defined like "+01:00" or "+0100" if (match[9]) { tzHour = Number(match[9] + match[10]); tzMin = Number(match[9] + match[11]); } dateSetter.call(date, Number(match[1]), Number(match[2]) - 1, Number(match[3])); const h = Number(match[4] || 0) - tzHour; const m = Number(match[5] || 0) - tzMin; const s = Number(match[6] || 0); // The ECMAScript specification (https://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.11) // defines that `DateTime` milliseconds should always be rounded down, so that `999.9ms` // becomes `999ms`. const ms = Math.floor(parseFloat('0.' + (match[7] || 0)) * 1000); timeSetter.call(date, h, m, s, ms); return date; } export function isDate(value: any): value is Date { return value instanceof Date && !isNaN(value.valueOf()); }
{ "end_byte": 29383, "start_byte": 24315, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/format_date.ts" }
angular/packages/common/src/i18n/currencies.ts_0_3894
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // THIS CODE IS GENERATED - DO NOT MODIFY. export type CurrenciesSymbols = [string] | [string | undefined, string]; /** @internal */ export const CURRENCIES_EN: {[code: string]: CurrenciesSymbols | [string | undefined, string | undefined, number]} = {"ADP":[undefined,undefined,0],"AFN":[undefined,"؋",0],"ALL":[undefined,undefined,0],"AMD":[undefined,"֏",2],"AOA":[undefined,"Kz"],"ARS":[undefined,"$"],"AUD":["A$","$"],"AZN":[undefined,"₼"],"BAM":[undefined,"KM"],"BBD":[undefined,"$"],"BDT":[undefined,"৳"],"BHD":[undefined,undefined,3],"BIF":[undefined,undefined,0],"BMD":[undefined,"$"],"BND":[undefined,"$"],"BOB":[undefined,"Bs"],"BRL":["R$"],"BSD":[undefined,"$"],"BWP":[undefined,"P"],"BYN":[undefined,undefined,2],"BYR":[undefined,undefined,0],"BZD":[undefined,"$"],"CAD":["CA$","$",2],"CHF":[undefined,undefined,2],"CLF":[undefined,undefined,4],"CLP":[undefined,"$",0],"CNY":["CN¥","¥"],"COP":[undefined,"$",2],"CRC":[undefined,"₡",2],"CUC":[undefined,"$"],"CUP":[undefined,"$"],"CZK":[undefined,"Kč",2],"DJF":[undefined,undefined,0],"DKK":[undefined,"kr",2],"DOP":[undefined,"$"],"EGP":[undefined,"E£"],"ESP":[undefined,"₧",0],"EUR":["€"],"FJD":[undefined,"$"],"FKP":[undefined,"£"],"GBP":["£"],"GEL":[undefined,"₾"],"GHS":[undefined,"GH₵"],"GIP":[undefined,"£"],"GNF":[undefined,"FG",0],"GTQ":[undefined,"Q"],"GYD":[undefined,"$",2],"HKD":["HK$","$"],"HNL":[undefined,"L"],"HRK":[undefined,"kn"],"HUF":[undefined,"Ft",2],"IDR":[undefined,"Rp",2],"ILS":["₪"],"INR":["₹"],"IQD":[undefined,undefined,0],"IRR":[undefined,undefined,0],"ISK":[undefined,"kr",0],"ITL":[undefined,undefined,0],"JMD":[undefined,"$"],"JOD":[undefined,undefined,3],"JPY":["¥",undefined,0],"KHR":[undefined,"៛"],"KMF":[undefined,"CF",0],"KPW":[undefined,"₩",0],"KRW":["₩",undefined,0],"KWD":[undefined,undefined,3],"KYD":[undefined,"$"],"KZT":[undefined,"₸"],"LAK":[undefined,"₭",0],"LBP":[undefined,"L£",0],"LKR":[undefined,"Rs"],"LRD":[undefined,"$"],"LTL":[undefined,"Lt"],"LUF":[undefined,undefined,0],"LVL":[undefined,"Ls"],"LYD":[undefined,undefined,3],"MGA":[undefined,"Ar",0],"MGF":[undefined,undefined,0],"MMK":[undefined,"K",0],"MNT":[undefined,"₮",2],"MRO":[undefined,undefined,0],"MUR":[undefined,"Rs",2],"MXN":["MX$","$"],"MYR":[undefined,"RM"],"NAD":[undefined,"$"],"NGN":[undefined,"₦"],"NIO":[undefined,"C$"],"NOK":[undefined,"kr",2],"NPR":[undefined,"Rs"],"NZD":["NZ$","$"],"OMR":[undefined,undefined,3],"PHP":["₱"],"PKR":[undefined,"Rs",2],"PLN":[undefined,"zł"],"PYG":[undefined,"₲",0],"RON":[undefined,"lei"],"RSD":[undefined,undefined,0],"RUB":[undefined,"₽"],"RWF":[undefined,"RF",0],"SBD":[undefined,"$"],"SEK":[undefined,"kr",2],"SGD":[undefined,"$"],"SHP":[undefined,"£"],"SLE":[undefined,undefined,2],"SLL":[undefined,undefined,0],"SOS":[undefined,undefined,0],"SRD":[undefined,"$"],"SSP":[undefined,"£"],"STD":[undefined,undefined,0],"STN":[undefined,"Db"],"SYP":[undefined,"£",0],"THB":[undefined,"฿"],"TMM":[undefined,undefined,0],"TND":[undefined,undefined,3],"TOP":[undefined,"T$"],"TRL":[undefined,undefined,0],"TRY":[undefined,"₺"],"TTD":[undefined,"$"],"TWD":["NT$","$",2],"TZS":[undefined,undefined,2],"UAH":[undefined,"₴"],"UGX":[undefined,undefined,0],"USD":["$"],"UYI":[undefined,undefined,0],"UYU":[undefined,"$"],"UYW":[undefined,undefined,4],"UZS":[undefined,undefined,2],"VEF":[undefined,"Bs",2],"VND":["₫",undefined,0],"VUV":[undefined,undefined,0],"XAF":["FCFA",undefined,0],"XCD":["EC$","$"],"XOF":["F CFA",undefined,0],"XPF":["CFPF",undefined,0],"XXX":["¤"],"YER":[undefined,undefined,0],"ZAR":[undefined,"R"],"ZMK":[undefined,undefined,0],"ZMW":[undefined,"ZK"],"ZWD":[undefined,undefined,0]};
{ "end_byte": 3894, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/currencies.ts" }
angular/packages/common/src/i18n/locale_data_api.ts_0_6758
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { ɵCurrencyIndex, ɵExtraLocaleDataIndex, ɵfindLocaleData, ɵgetLocaleCurrencyCode, ɵgetLocalePluralCase, ɵLocaleDataIndex, } from '@angular/core'; import {CURRENCIES_EN, CurrenciesSymbols} from './currencies'; /** * Format styles that can be used to represent numbers. * @see {@link getLocaleNumberFormat} * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated `getLocaleNumberFormat` is deprecated */ export enum NumberFormatStyle { Decimal, Percent, Currency, Scientific, } /** * Plurality cases used for translating plurals to different languages. * * @see {@link NgPlural} * @see {@link NgPluralCase} * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated `getLocalePluralCase` is deprecated */ export enum Plural { Zero = 0, One = 1, Two = 2, Few = 3, Many = 4, Other = 5, } /** * Context-dependant translation forms for strings. * Typically the standalone version is for the nominative form of the word, * and the format version is used for the genitive case. * @see [CLDR website](http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles) * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated locale data getters are deprecated */ export enum FormStyle { Format, Standalone, } /** * String widths available for translations. * The specific character widths are locale-specific. * Examples are given for the word "Sunday" in English. * * @publicApi * * @deprecated locale data getters are deprecated */ export enum TranslationWidth { /** 1 character for `en-US`. For example: 'S' */ Narrow, /** 3 characters for `en-US`. For example: 'Sun' */ Abbreviated, /** Full length for `en-US`. For example: "Sunday" */ Wide, /** 2 characters for `en-US`, For example: "Su" */ Short, } /** * String widths available for date-time formats. * The specific character widths are locale-specific. * Examples are given for `en-US`. * * @see {@link getLocaleDateFormat} * @see {@link getLocaleTimeFormat} * @see {@link getLocaleDateTimeFormat} * @see [Internationalization (i18n) Guide](guide/i18n) * @publicApi * * @deprecated Date locale data getters are deprecated */ export enum FormatWidth { /** * For `en-US`, `'M/d/yy, h:mm a'` * (Example: `6/15/15, 9:03 AM`) */ Short, /** * For `en-US`, `'MMM d, y, h:mm:ss a'` * (Example: `Jun 15, 2015, 9:03:01 AM`) */ Medium, /** * For `en-US`, `'MMMM d, y, h:mm:ss a z'` * (Example: `June 15, 2015 at 9:03:01 AM GMT+1`) */ Long, /** * For `en-US`, `'EEEE, MMMM d, y, h:mm:ss a zzzz'` * (Example: `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00`) */ Full, } // This needs to be an object literal, rather than an enum, because TypeScript 5.4+ // doesn't allow numeric keys and we have `Infinity` and `NaN`. /** * Symbols that can be used to replace placeholders in number patterns. * Examples are based on `en-US` values. * * @see {@link getLocaleNumberSymbol} * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated `getLocaleNumberSymbol` is deprecated * * @object-literal-as-enum */ export const NumberSymbol = { /** * Decimal separator. * For `en-US`, the dot character. * Example: 2,345`.`67 */ Decimal: 0, /** * Grouping separator, typically for thousands. * For `en-US`, the comma character. * Example: 2`,`345.67 */ Group: 1, /** * List-item separator. * Example: "one, two, and three" */ List: 2, /** * Sign for percentage (out of 100). * Example: 23.4% */ PercentSign: 3, /** * Sign for positive numbers. * Example: +23 */ PlusSign: 4, /** * Sign for negative numbers. * Example: -23 */ MinusSign: 5, /** * Computer notation for exponential value (n times a power of 10). * Example: 1.2E3 */ Exponential: 6, /** * Human-readable format of exponential. * Example: 1.2x103 */ SuperscriptingExponent: 7, /** * Sign for permille (out of 1000). * Example: 23.4‰ */ PerMille: 8, /** * Infinity, can be used with plus and minus. * Example: ∞, +∞, -∞ */ Infinity: 9, /** * Not a number. * Example: NaN */ NaN: 10, /** * Symbol used between time units. * Example: 10:52 */ TimeSeparator: 11, /** * Decimal separator for currency values (fallback to `Decimal`). * Example: $2,345.67 */ CurrencyDecimal: 12, /** * Group separator for currency values (fallback to `Group`). * Example: $2,345.67 */ CurrencyGroup: 13, } as const; export type NumberSymbol = (typeof NumberSymbol)[keyof typeof NumberSymbol]; /** * The value for each day of the week, based on the `en-US` locale * * @publicApi * * @deprecated Week locale getters are deprecated */ export enum WeekDay { Sunday = 0, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, } /** * Retrieves the locale ID from the currently loaded locale. * The loaded locale could be, for example, a global one rather than a regional one. * @param locale A locale code, such as `fr-FR`. * @returns The locale code. For example, `fr`. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * This function serves no purpose when relying on the `Intl` API. */ export function getLocaleId(locale: string): string { return ɵfindLocaleData(locale)[ɵLocaleDataIndex.LocaleId]; } /** * Retrieves day period strings for the given locale. * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns An array of localized period strings. For example, `[AM, PM]` for `en-US`. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Use `Intl.DateTimeFormat` for date formating instead. */ export function getLocaleDayPeriods( locale: string, formStyle: FormStyle, width: TranslationWidth, ): Readonly<[string, string]> { const data = ɵfindLocaleData(locale); const amPmData = <[string, string][][]>[ data[ɵLocaleDataIndex.DayPeriodsFormat], data[ɵLocaleDataIndex.DayPeriodsStandalone], ]; const amPm = getLastDefinedValue(amPmData, formStyle); return getLastDefinedValue(amPm, width); } /** * Retrieves
{ "end_byte": 6758, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/locale_data_api.ts" }
angular/packages/common/src/i18n/locale_data_api.ts_6760_14578
ys of the week for the given locale, using the Gregorian calendar. * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns An array of localized name strings. * For example,`[Sunday, Monday, ... Saturday]` for `en-US`. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Use `Intl.DateTimeFormat` for date formating instead. */ export function getLocaleDayNames( locale: string, formStyle: FormStyle, width: TranslationWidth, ): ReadonlyArray<string> { const data = ɵfindLocaleData(locale); const daysData = <string[][][]>[ data[ɵLocaleDataIndex.DaysFormat], data[ɵLocaleDataIndex.DaysStandalone], ]; const days = getLastDefinedValue(daysData, formStyle); return getLastDefinedValue(days, width); } /** * Retrieves months of the year for the given locale, using the Gregorian calendar. * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns An array of localized name strings. * For example, `[January, February, ...]` for `en-US`. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Use `Intl.DateTimeFormat` for date formating instead. */ export function getLocaleMonthNames( locale: string, formStyle: FormStyle, width: TranslationWidth, ): ReadonlyArray<string> { const data = ɵfindLocaleData(locale); const monthsData = <string[][][]>[ data[ɵLocaleDataIndex.MonthsFormat], data[ɵLocaleDataIndex.MonthsStandalone], ]; const months = getLastDefinedValue(monthsData, formStyle); return getLastDefinedValue(months, width); } /** * Retrieves Gregorian-calendar eras for the given locale. * @param locale A locale code for the locale format rules to use. * @param width The required character width. * @returns An array of localized era strings. * For example, `[AD, BC]` for `en-US`. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Use `Intl.DateTimeFormat` for date formating instead. */ export function getLocaleEraNames( locale: string, width: TranslationWidth, ): Readonly<[string, string]> { const data = ɵfindLocaleData(locale); const erasData = <[string, string][]>data[ɵLocaleDataIndex.Eras]; return getLastDefinedValue(erasData, width); } /** * Retrieves the first day of the week for the given locale. * * @param locale A locale code for the locale format rules to use. * @returns A day index number, using the 0-based week-day index for `en-US` * (Sunday = 0, Monday = 1, ...). * For example, for `fr-FR`, returns 1 to indicate that the first day is Monday. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Intl's [`getWeekInfo`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getWeekInfo) has partial support (Chromium M99 & Safari 17). * You may want to rely on the following alternatives: * - Libraries like [`Luxon`](https://moment.github.io/luxon/#/) rely on `Intl` but fallback on the ISO 8601 definition (monday) if `getWeekInfo` is not supported. * - Other librairies like [`date-fns`](https://date-fns.org/), [`day.js`](https://day.js.org/en/) or [`weekstart`](https://www.npmjs.com/package/weekstart) library provide their own locale based data for the first day of the week. */ export function getLocaleFirstDayOfWeek(locale: string): WeekDay { const data = ɵfindLocaleData(locale); return data[ɵLocaleDataIndex.FirstDayOfWeek]; } /** * Range of week days that are considered the week-end for the given locale. * * @param locale A locale code for the locale format rules to use. * @returns The range of day values, `[startDay, endDay]`. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Intl's [`getWeekInfo`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getWeekInfo) has partial support (Chromium M99 & Safari 17). * Libraries like [`Luxon`](https://moment.github.io/luxon/#/) rely on `Intl` but fallback on the ISO 8601 definition (Saturday+Sunday) if `getWeekInfo` is not supported . */ export function getLocaleWeekEndRange(locale: string): [WeekDay, WeekDay] { const data = ɵfindLocaleData(locale); return data[ɵLocaleDataIndex.WeekendRange]; } /** * Retrieves a localized date-value formatting string. * * @param locale A locale code for the locale format rules to use. * @param width The format type. * @returns The localized formatting string. * @see {@link FormatWidth} * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Use `Intl.DateTimeFormat` for date formating instead. */ export function getLocaleDateFormat(locale: string, width: FormatWidth): string { const data = ɵfindLocaleData(locale); return getLastDefinedValue(data[ɵLocaleDataIndex.DateFormat], width); } /** * Retrieves a localized time-value formatting string. * * @param locale A locale code for the locale format rules to use. * @param width The format type. * @returns The localized formatting string. * @see {@link FormatWidth} * @see [Internationalization (i18n) Guide](guide/i18n) * @publicApi * @deprecated Angular recommends relying on the `Intl` API for i18n. * Use `Intl.DateTimeFormat` for date formating instead. */ export function getLocaleTimeFormat(locale: string, width: FormatWidth): string { const data = ɵfindLocaleData(locale); return getLastDefinedValue(data[ɵLocaleDataIndex.TimeFormat], width); } /** * Retrieves a localized date-time formatting string. * * @param locale A locale code for the locale format rules to use. * @param width The format type. * @returns The localized formatting string. * @see {@link FormatWidth} * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Use `Intl.DateTimeFormat` for date formating instead. */ export function getLocaleDateTimeFormat(locale: string, width: FormatWidth): string { const data = ɵfindLocaleData(locale); const dateTimeFormatData = <string[]>data[ɵLocaleDataIndex.DateTimeFormat]; return getLastDefinedValue(dateTimeFormatData, width); } /** * Retrieves a localized number symbol that can be used to replace placeholders in number formats. * @param locale The locale code. * @param symbol The symbol to localize. Must be one of `NumberSymbol`. * @returns The character for the localized symbol. * @see {@link NumberSymbol} * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Use `Intl.NumberFormat` to format numbers instead. */ export function getLocaleNumberSymbol(locale: string, symbol: NumberSymbol): string { const data = ɵfindLocaleData(locale); const res = data[ɵLocaleDataIndex.NumberSymbols][symbol]; if (typeof res === 'undefined') { if (symbol === NumberSymbol.CurrencyDecimal) { return data[ɵLocaleDataIndex.NumberSymbols][NumberSymbol.Decimal]; } else if (symbol === NumberSymbol.CurrencyGroup) { return data[ɵLocaleDataIndex.NumberSymbols][NumberSymbol.Group]; } } return res; } /** * Retrieves a number format for a
{ "end_byte": 14578, "start_byte": 6760, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/locale_data_api.ts" }
angular/packages/common/src/i18n/locale_data_api.ts_14580_22521
ven locale. * * Numbers are formatted using patterns, like `#,###.00`. For example, the pattern `#,###.00` * when used to format the number 12345.678 could result in "12'345,678". That would happen if the * grouping separator for your language is an apostrophe, and the decimal separator is a comma. * * <b>Important:</b> The characters `.` `,` `0` `#` (and others below) are special placeholders * that stand for the decimal separator, and so on, and are NOT real characters. * You must NOT "translate" the placeholders. For example, don't change `.` to `,` even though in * your language the decimal point is written with a comma. The symbols should be replaced by the * local equivalents, using the appropriate `NumberSymbol` for your language. * * Here are the special characters used in number patterns: * * | Symbol | Meaning | * |--------|---------| * | . | Replaced automatically by the character used for the decimal point. | * | , | Replaced by the "grouping" (thousands) separator. | * | 0 | Replaced by a digit (or zero if there aren't enough digits). | * | # | Replaced by a digit (or nothing if there aren't enough). | * | ¤ | Replaced by a currency symbol, such as $ or USD. | * | % | Marks a percent format. The % symbol may change position, but must be retained. | * | E | Marks a scientific format. The E symbol may change position, but must be retained. | * | ' | Special characters used as literal characters are quoted with ASCII single quotes. | * * @param locale A locale code for the locale format rules to use. * @param type The type of numeric value to be formatted (such as `Decimal` or `Currency`.) * @returns The localized format string. * @see {@link NumberFormatStyle} * @see [CLDR website](http://cldr.unicode.org/translation/number-patterns) * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Let `Intl.NumberFormat` determine the number format instead */ export function getLocaleNumberFormat(locale: string, type: NumberFormatStyle): string { const data = ɵfindLocaleData(locale); return data[ɵLocaleDataIndex.NumberFormats][type]; } /** * Retrieves the symbol used to represent the currency for the main country * corresponding to a given locale. For example, '$' for `en-US`. * * @param locale A locale code for the locale format rules to use. * @returns The localized symbol character, * or `null` if the main country cannot be determined. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Use the `Intl` API to format a currency with from currency code */ export function getLocaleCurrencySymbol(locale: string): string | null { const data = ɵfindLocaleData(locale); return data[ɵLocaleDataIndex.CurrencySymbol] || null; } /** * Retrieves the name of the currency for the main country corresponding * to a given locale. For example, 'US Dollar' for `en-US`. * @param locale A locale code for the locale format rules to use. * @returns The currency name, * or `null` if the main country cannot be determined. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Use the `Intl` API to format a currency with from currency code */ export function getLocaleCurrencyName(locale: string): string | null { const data = ɵfindLocaleData(locale); return data[ɵLocaleDataIndex.CurrencyName] || null; } /** * Retrieves the default currency code for the given locale. * * The default is defined as the first currency which is still in use. * * @param locale The code of the locale whose currency code we want. * @returns The code of the default currency for the given locale. * * @publicApi * * @deprecated We recommend you create a map of locale to ISO 4217 currency codes. * Time relative currency data is provided by the CLDR project. See https://www.unicode.org/cldr/charts/44/supplemental/detailed_territory_currency_information.html */ export function getLocaleCurrencyCode(locale: string): string | null { return ɵgetLocaleCurrencyCode(locale); } /** * Retrieves the currency values for a given locale. * @param locale A locale code for the locale format rules to use. * @returns The currency values. * @see [Internationalization (i18n) Guide](guide/i18n) */ function getLocaleCurrencies(locale: string): {[code: string]: CurrenciesSymbols} { const data = ɵfindLocaleData(locale); return data[ɵLocaleDataIndex.Currencies]; } /** * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Use `Intl.PluralRules` instead */ export const getLocalePluralCase: (locale: string) => (value: number) => Plural = ɵgetLocalePluralCase; function checkFullData(data: any) { if (!data[ɵLocaleDataIndex.ExtraData]) { throw new Error( `Missing extra locale data for the locale "${ data[ɵLocaleDataIndex.LocaleId] }". Use "registerLocaleData" to load new data. See the "I18n guide" on angular.io to know more.`, ); } } /** * Retrieves locale-specific rules used to determine which day period to use * when more than one period is defined for a locale. * * There is a rule for each defined day period. The * first rule is applied to the first day period and so on. * Fall back to AM/PM when no rules are available. * * A rule can specify a period as time range, or as a single time value. * * This functionality is only available when you have loaded the full locale data. * See the ["I18n guide"](guide/i18n/format-data-locale). * * @param locale A locale code for the locale format rules to use. * @returns The rules for the locale, a single time value or array of *from-time, to-time*, * or null if no periods are available. * * @see {@link getLocaleExtraDayPeriods} * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * Let `Intl.DateTimeFormat` determine the day period instead. */ export function getLocaleExtraDayPeriodRules(locale: string): (Time | [Time, Time])[] { const data = ɵfindLocaleData(locale); checkFullData(data); const rules = data[ɵLocaleDataIndex.ExtraData][ɵExtraLocaleDataIndex.ExtraDayPeriodsRules] || []; return rules.map((rule: string | [string, string]) => { if (typeof rule === 'string') { return extractTime(rule); } return [extractTime(rule[0]), extractTime(rule[1])]; }); } /** * Retrieves locale-specific day periods, which indicate roughly how a day is broken up * in different languages. * For example, for `en-US`, periods are morning, noon, afternoon, evening, and midnight. * * This functionality is only available when you have loaded the full locale data. * See the ["I18n guide"](guide/i18n/format-data-locale). * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns The translated day-period strings. * @see {@link getLocaleExtraDayPeriodRules} * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * To extract a day period use `Intl.DateTimeFormat` with the `dayPeriod` option instead. */ export function getLocaleExtraDayPeriods( locale: string, formStyle: FormStyle, width: TranslationWidth, ): string[] { const data = ɵfindLocaleData(locale); checkFullData(data); const dayPeriodsData = <string[][][]>[ data[ɵLocaleDataIndex.ExtraData][ɵExtraLocaleDataIndex.ExtraDayPeriodFormats], data[ɵLocaleDataIndex.ExtraData][ɵExtraLocaleDataIndex.ExtraDayPeriodStandalone], ]; const dayPeriods = getLastDefinedValue(dayPeriodsData, formStyle) || []; return getLastDefinedValue(dayPeriods, width) || []; } /** * Retrieves the writing direction of a specified locale
{ "end_byte": 22521, "start_byte": 14580, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/locale_data_api.ts" }
angular/packages/common/src/i18n/locale_data_api.ts_22523_26811
* @param locale A locale code for the locale format rules to use. * @publicApi * @returns 'rtl' or 'ltr' * @see [Internationalization (i18n) Guide](guide/i18n) * * @deprecated Angular recommends relying on the `Intl` API for i18n. * For dates and numbers, let `Intl.DateTimeFormat()` and `Intl.NumberFormat()` determine the writing direction. * The `Intl` alternative [`getTextInfo`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getTextInfo). * has only partial support (Chromium M99 & Safari 17). * 3rd party alternatives like [`rtl-detect`](https://www.npmjs.com/package/rtl-detect) can work around this issue. */ export function getLocaleDirection(locale: string): 'ltr' | 'rtl' { const data = ɵfindLocaleData(locale); return data[ɵLocaleDataIndex.Directionality]; } /** * Retrieves the first value that is defined in an array, going backwards from an index position. * * To avoid repeating the same data (as when the "format" and "standalone" forms are the same) * add the first value to the locale data arrays, and add other values only if they are different. * * @param data The data array to retrieve from. * @param index A 0-based index into the array to start from. * @returns The value immediately before the given index position. * @see [Internationalization (i18n) Guide](guide/i18n) * */ function getLastDefinedValue<T>(data: T[], index: number): T { for (let i = index; i > -1; i--) { if (typeof data[i] !== 'undefined') { return data[i]; } } throw new Error('Locale data API: locale data undefined'); } /** * Represents a time value with hours and minutes. * * @publicApi * * @deprecated Locale date getters are deprecated */ export type Time = { hours: number; minutes: number; }; /** * Extracts the hours and minutes from a string like "15:45" */ function extractTime(time: string): Time { const [h, m] = time.split(':'); return {hours: +h, minutes: +m}; } /** * Retrieves the currency symbol for a given currency code. * * For example, for the default `en-US` locale, the code `USD` can * be represented by the narrow symbol `$` or the wide symbol `US$`. * * @param code The currency code. * @param format The format, `wide` or `narrow`. * @param locale A locale code for the locale format rules to use. * * @returns The symbol, or the currency code if no symbol is available. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * You can use `Intl.NumberFormat().formatToParts()` to extract the currency symbol. * For example: `Intl.NumberFormat('en', {style:'currency', currency: 'USD'}).formatToParts().find(part => part.type === 'currency').value` * returns `$` for USD currency code in the `en` locale. * Note: `US$` is a currency symbol for the `en-ca` locale but not the `en-us` locale. */ export function getCurrencySymbol(code: string, format: 'wide' | 'narrow', locale = 'en'): string { const currency = getLocaleCurrencies(locale)[code] || CURRENCIES_EN[code] || []; const symbolNarrow = currency[ɵCurrencyIndex.SymbolNarrow]; if (format === 'narrow' && typeof symbolNarrow === 'string') { return symbolNarrow; } return currency[ɵCurrencyIndex.Symbol] || code; } // Most currencies have cents, that's why the default is 2 const DEFAULT_NB_OF_CURRENCY_DIGITS = 2; /** * Reports the number of decimal digits for a given currency. * The value depends upon the presence of cents in that particular currency. * * @param code The currency code. * @returns The number of decimal digits, typically 0 or 2. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi * * @deprecated Angular recommends relying on the `Intl` API for i18n. * This function should not be used anymore. Let `Intl.NumberFormat` determine the number of digits to display for the currency */ export function getNumberOfCurrencyDigits(code: string): number { let digits; const currency = CURRENCIES_EN[code]; if (currency) { digits = currency[ɵCurrencyIndex.NbOfDigits]; } return typeof digits === 'number' ? digits : DEFAULT_NB_OF_CURRENCY_DIGITS; }
{ "end_byte": 26811, "start_byte": 22523, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/locale_data_api.ts" }
angular/packages/common/src/i18n/format_number.ts_0_7833
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { getLocaleNumberFormat, getLocaleNumberSymbol, getNumberOfCurrencyDigits, NumberFormatStyle, NumberSymbol, } from './locale_data_api'; export const NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/; const MAX_DIGITS = 22; const DECIMAL_SEP = '.'; const ZERO_CHAR = '0'; const PATTERN_SEP = ';'; const GROUP_SEP = ','; const DIGIT_CHAR = '#'; const CURRENCY_CHAR = '¤'; const PERCENT_CHAR = '%'; /** * Transforms a number to a locale string based on a style and a format. */ function formatNumberToLocaleString( value: number, pattern: ParsedNumberFormat, locale: string, groupSymbol: NumberSymbol, decimalSymbol: NumberSymbol, digitsInfo?: string, isPercent = false, ): string { let formattedText = ''; let isZero = false; if (!isFinite(value)) { formattedText = getLocaleNumberSymbol(locale, NumberSymbol.Infinity); } else { let parsedNumber = parseNumber(value); if (isPercent) { parsedNumber = toPercent(parsedNumber); } let minInt = pattern.minInt; let minFraction = pattern.minFrac; let maxFraction = pattern.maxFrac; if (digitsInfo) { const parts = digitsInfo.match(NUMBER_FORMAT_REGEXP); if (parts === null) { throw new Error(`${digitsInfo} is not a valid digit info`); } const minIntPart = parts[1]; const minFractionPart = parts[3]; const maxFractionPart = parts[5]; if (minIntPart != null) { minInt = parseIntAutoRadix(minIntPart); } if (minFractionPart != null) { minFraction = parseIntAutoRadix(minFractionPart); } if (maxFractionPart != null) { maxFraction = parseIntAutoRadix(maxFractionPart); } else if (minFractionPart != null && minFraction > maxFraction) { maxFraction = minFraction; } } roundNumber(parsedNumber, minFraction, maxFraction); let digits = parsedNumber.digits; let integerLen = parsedNumber.integerLen; const exponent = parsedNumber.exponent; let decimals = []; isZero = digits.every((d) => !d); // pad zeros for small numbers for (; integerLen < minInt; integerLen++) { digits.unshift(0); } // pad zeros for small numbers for (; integerLen < 0; integerLen++) { digits.unshift(0); } // extract decimals digits if (integerLen > 0) { decimals = digits.splice(integerLen, digits.length); } else { decimals = digits; digits = [0]; } // format the integer digits with grouping separators const groups = []; if (digits.length >= pattern.lgSize) { groups.unshift(digits.splice(-pattern.lgSize, digits.length).join('')); } while (digits.length > pattern.gSize) { groups.unshift(digits.splice(-pattern.gSize, digits.length).join('')); } if (digits.length) { groups.unshift(digits.join('')); } formattedText = groups.join(getLocaleNumberSymbol(locale, groupSymbol)); // append the decimal digits if (decimals.length) { formattedText += getLocaleNumberSymbol(locale, decimalSymbol) + decimals.join(''); } if (exponent) { formattedText += getLocaleNumberSymbol(locale, NumberSymbol.Exponential) + '+' + exponent; } } if (value < 0 && !isZero) { formattedText = pattern.negPre + formattedText + pattern.negSuf; } else { formattedText = pattern.posPre + formattedText + pattern.posSuf; } return formattedText; } /** * @ngModule CommonModule * @description * * Formats a number as currency using locale rules. * * @param value The number to format. * @param locale A locale code for the locale format rules to use. * @param currency A string containing the currency symbol or its name, * such as "$" or "Canadian Dollar". Used in output string, but does not affect the operation * of the function. * @param currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) * currency code, such as `USD` for the US dollar and `EUR` for the euro. * Used to determine the number of digits in the decimal part. * @param digitsInfo Decimal representation options, specified by a string in the following format: * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details. * * @returns The formatted currency value. * * @see {@link formatNumber} * @see {@link DecimalPipe} * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi */ export function formatCurrency( value: number, locale: string, currency: string, currencyCode?: string, digitsInfo?: string, ): string { const format = getLocaleNumberFormat(locale, NumberFormatStyle.Currency); const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign)); pattern.minFrac = getNumberOfCurrencyDigits(currencyCode!); pattern.maxFrac = pattern.minFrac; const res = formatNumberToLocaleString( value, pattern, locale, NumberSymbol.CurrencyGroup, NumberSymbol.CurrencyDecimal, digitsInfo, ); return ( res .replace(CURRENCY_CHAR, currency) // if we have 2 time the currency character, the second one is ignored .replace(CURRENCY_CHAR, '') // If there is a spacing between currency character and the value and // the currency character is suppressed by passing an empty string, the // spacing character would remain as part of the string. Then we // should remove it. .trim() ); } /** * @ngModule CommonModule * @description * * Formats a number as a percentage according to locale rules. * * @param value The number to format. * @param locale A locale code for the locale format rules to use. * @param digitsInfo Decimal representation options, specified by a string in the following format: * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details. * * @returns The formatted percentage value. * * @see {@link formatNumber} * @see {@link DecimalPipe} * @see [Internationalization (i18n) Guide](guide/i18n) * @publicApi * */ export function formatPercent(value: number, locale: string, digitsInfo?: string): string { const format = getLocaleNumberFormat(locale, NumberFormatStyle.Percent); const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign)); const res = formatNumberToLocaleString( value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo, true, ); return res.replace( new RegExp(PERCENT_CHAR, 'g'), getLocaleNumberSymbol(locale, NumberSymbol.PercentSign), ); } /** * @ngModule CommonModule * @description * * Formats a number as text, with group sizing, separator, and other * parameters based on the locale. * * @param value The number to format. * @param locale A locale code for the locale format rules to use. * @param digitsInfo Decimal representation options, specified by a string in the following format: * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details. * * @returns The formatted text string. * @see [Internationalization (i18n) Guide](guide/i18n) * * @publicApi */ export function formatNumber(value: number, locale: string, digitsInfo?: string): string { const format = getLocaleNumberFormat(locale, NumberFormatStyle.Decimal); const pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign)); return formatNumberToLocaleString( value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo, ); }
{ "end_byte": 7833, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/format_number.ts" }
angular/packages/common/src/i18n/format_number.ts_7835_12748
nterface ParsedNumberFormat { minInt: number; // the minimum number of digits required in the fraction part of the number minFrac: number; // the maximum number of digits required in the fraction part of the number maxFrac: number; // the prefix for a positive number posPre: string; // the suffix for a positive number posSuf: string; // the prefix for a negative number (e.g. `-` or `(`)) negPre: string; // the suffix for a negative number (e.g. `)`) negSuf: string; // number of digits in each group of separated digits gSize: number; // number of digits in the last group of digits before the decimal separator lgSize: number; } function parseNumberFormat(format: string, minusSign = '-'): ParsedNumberFormat { const p = { minInt: 1, minFrac: 0, maxFrac: 0, posPre: '', posSuf: '', negPre: '', negSuf: '', gSize: 0, lgSize: 0, }; const patternParts = format.split(PATTERN_SEP); const positive = patternParts[0]; const negative = patternParts[1]; const positiveParts = positive.indexOf(DECIMAL_SEP) !== -1 ? positive.split(DECIMAL_SEP) : [ positive.substring(0, positive.lastIndexOf(ZERO_CHAR) + 1), positive.substring(positive.lastIndexOf(ZERO_CHAR) + 1), ], integer = positiveParts[0], fraction = positiveParts[1] || ''; p.posPre = integer.substring(0, integer.indexOf(DIGIT_CHAR)); for (let i = 0; i < fraction.length; i++) { const ch = fraction.charAt(i); if (ch === ZERO_CHAR) { p.minFrac = p.maxFrac = i + 1; } else if (ch === DIGIT_CHAR) { p.maxFrac = i + 1; } else { p.posSuf += ch; } } const groups = integer.split(GROUP_SEP); p.gSize = groups[1] ? groups[1].length : 0; p.lgSize = groups[2] || groups[1] ? (groups[2] || groups[1]).length : 0; if (negative) { const trunkLen = positive.length - p.posPre.length - p.posSuf.length, pos = negative.indexOf(DIGIT_CHAR); p.negPre = negative.substring(0, pos).replace(/'/g, ''); p.negSuf = negative.slice(pos + trunkLen).replace(/'/g, ''); } else { p.negPre = minusSign + p.posPre; p.negSuf = p.posSuf; } return p; } interface ParsedNumber { // an array of digits containing leading zeros as necessary digits: number[]; // the exponent for numbers that would need more than `MAX_DIGITS` digits in `d` exponent: number; // the number of the digits in `d` that are to the left of the decimal point integerLen: number; } // Transforms a parsed number into a percentage by multiplying it by 100 function toPercent(parsedNumber: ParsedNumber): ParsedNumber { // if the number is 0, don't do anything if (parsedNumber.digits[0] === 0) { return parsedNumber; } // Getting the current number of decimals const fractionLen = parsedNumber.digits.length - parsedNumber.integerLen; if (parsedNumber.exponent) { parsedNumber.exponent += 2; } else { if (fractionLen === 0) { parsedNumber.digits.push(0, 0); } else if (fractionLen === 1) { parsedNumber.digits.push(0); } parsedNumber.integerLen += 2; } return parsedNumber; } /** * Parses a number. * Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/ */ function parseNumber(num: number): ParsedNumber { let numStr = Math.abs(num) + ''; let exponent = 0, digits, integerLen; let i, j, zeros; // Decimal point? if ((integerLen = numStr.indexOf(DECIMAL_SEP)) > -1) { numStr = numStr.replace(DECIMAL_SEP, ''); } // Exponential form? if ((i = numStr.search(/e/i)) > 0) { // Work out the exponent. if (integerLen < 0) integerLen = i; integerLen += +numStr.slice(i + 1); numStr = numStr.substring(0, i); } else if (integerLen < 0) { // There was no decimal point or exponent so it is an integer. integerLen = numStr.length; } // Count the number of leading zeros. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ } if (i === (zeros = numStr.length)) { // The digits are all zero. digits = [0]; integerLen = 1; } else { // Count the number of trailing zeros zeros--; while (numStr.charAt(zeros) === ZERO_CHAR) zeros--; // Trailing zeros are insignificant so ignore them integerLen -= i; digits = []; // Convert string to array of digits without leading/trailing zeros. for (j = 0; i <= zeros; i++, j++) { digits[j] = Number(numStr.charAt(i)); } } // If the number overflows the maximum allowed digits then use an exponent. if (integerLen > MAX_DIGITS) { digits = digits.splice(0, MAX_DIGITS - 1); exponent = integerLen - 1; integerLen = 1; } return {digits, exponent, integerLen}; } /** * Round the parsed number to the specified number of decimal places * This function changes the parsedNumber in-place */
{ "end_byte": 12748, "start_byte": 7835, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/format_number.ts" }
angular/packages/common/src/i18n/format_number.ts_12749_15314
unction roundNumber(parsedNumber: ParsedNumber, minFrac: number, maxFrac: number) { if (minFrac > maxFrac) { throw new Error( `The minimum number of digits after fraction (${minFrac}) is higher than the maximum (${maxFrac}).`, ); } let digits = parsedNumber.digits; let fractionLen = digits.length - parsedNumber.integerLen; const fractionSize = Math.min(Math.max(minFrac, fractionLen), maxFrac); // The index of the digit to where rounding is to occur let roundAt = fractionSize + parsedNumber.integerLen; let digit = digits[roundAt]; if (roundAt > 0) { // Drop fractional digits beyond `roundAt` digits.splice(Math.max(parsedNumber.integerLen, roundAt)); // Set non-fractional digits beyond `roundAt` to 0 for (let j = roundAt; j < digits.length; j++) { digits[j] = 0; } } else { // We rounded to zero so reset the parsedNumber fractionLen = Math.max(0, fractionLen); parsedNumber.integerLen = 1; digits.length = Math.max(1, (roundAt = fractionSize + 1)); digits[0] = 0; for (let i = 1; i < roundAt; i++) digits[i] = 0; } if (digit >= 5) { if (roundAt - 1 < 0) { for (let k = 0; k > roundAt; k--) { digits.unshift(0); parsedNumber.integerLen++; } digits.unshift(1); parsedNumber.integerLen++; } else { digits[roundAt - 1]++; } } // Pad out with zeros to get the required fraction length for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); let dropTrailingZeros = fractionSize !== 0; // Minimal length = nb of decimals required + current nb of integers // Any number besides that is optional and can be removed if it's a trailing 0 const minLen = minFrac + parsedNumber.integerLen; // Do any carrying, e.g. a digit was rounded up to 10 const carry = digits.reduceRight(function (carry, d, i, digits) { d = d + carry; digits[i] = d < 10 ? d : d - 10; // d % 10 if (dropTrailingZeros) { // Do not keep meaningless fractional trailing zeros (e.g. 15.52000 --> 15.52) if (digits[i] === 0 && i >= minLen) { digits.pop(); } else { dropTrailingZeros = false; } } return d >= 10 ? 1 : 0; // Math.floor(d / 10); }, 0); if (carry) { digits.unshift(carry); parsedNumber.integerLen++; } } export function parseIntAutoRadix(text: string): number { const result: number = parseInt(text); if (isNaN(result)) { throw new Error('Invalid integer literal when parsing ' + text); } return result; }
{ "end_byte": 15314, "start_byte": 12749, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/format_number.ts" }
angular/packages/common/src/i18n/localization.ts_0_1843
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Inject, Injectable, LOCALE_ID} from '@angular/core'; import {getLocalePluralCase, Plural} from './locale_data_api'; /** * @publicApi */ @Injectable({ providedIn: 'root', useFactory: (locale: string) => new NgLocaleLocalization(locale), deps: [LOCALE_ID], }) export abstract class NgLocalization { abstract getPluralCategory(value: any, locale?: string): string; } /** * Returns the plural category for a given value. * - "=value" when the case exists, * - the plural category otherwise */ export function getPluralCategory( value: number, cases: string[], ngLocalization: NgLocalization, locale?: string, ): string { let key = `=${value}`; if (cases.indexOf(key) > -1) { return key; } key = ngLocalization.getPluralCategory(value, locale); if (cases.indexOf(key) > -1) { return key; } if (cases.indexOf('other') > -1) { return 'other'; } throw new Error(`No plural message found for value "${value}"`); } /** * Returns the plural case based on the locale * * @publicApi */ @Injectable() export class NgLocaleLocalization extends NgLocalization { constructor(@Inject(LOCALE_ID) protected locale: string) { super(); } override getPluralCategory(value: any, locale?: string): string { const plural = getLocalePluralCase(locale || this.locale)(value); switch (plural) { case Plural.Zero: return 'zero'; case Plural.One: return 'one'; case Plural.Two: return 'two'; case Plural.Few: return 'few'; case Plural.Many: return 'many'; default: return 'other'; } } }
{ "end_byte": 1843, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/localization.ts" }
angular/packages/common/src/i18n/locale_data.ts_0_694
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ɵregisterLocaleData} from '@angular/core'; /** * 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 */ export function registerLocaleData(data: any, localeId?: string | any, extraData?: any): void { return ɵregisterLocaleData(data, localeId, extraData); }
{ "end_byte": 694, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/i18n/locale_data.ts" }
angular/packages/elements/PACKAGE.md_0_697
Implements Angular's custom-element API, which enables you to package components as [custom elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements). A custom element extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code. The browser maintains a `CustomElementRegistry` of defined custom elements (also called Web Components), which maps an instantiable JavaScript class to an HTML tag. The `createCustomElement()` function provides a bridge from Angular's component interface and change detection functionality to the built-in DOM API. For more information, see [Angular Elements Overview](guide/elements).
{ "end_byte": 697, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/PACKAGE.md" }
angular/packages/elements/BUILD.bazel_0_1424
load("//tools:defaults.bzl", "api_golden_test_npm_package", "generate_api_docs", "ng_module", "ng_package") package(default_visibility = ["//visibility:public"]) ng_module( name = "elements", srcs = glob( [ "*.ts", "src/**/*.ts", ], ), deps = [ "//packages/core", "//packages/platform-browser", "@npm//rxjs", ], ) ng_package( name = "npm_package", package_name = "@angular/elements", srcs = ["package.json"], tags = [ "release-with-framework", ], # Do not add more to this list. # Dependencies on the full npm_package cause long re-builds. visibility = [ "//integration:__subpackages__", "//modules/ssr-benchmarks:__subpackages__", ], deps = [ ":elements", ], ) api_golden_test_npm_package( name = "elements_api", data = [ ":npm_package", "//goldens:public-api", ], golden_dir = "angular/goldens/public-api/elements", npm_package = "angular/packages/elements/npm_package", ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", "src/**/*.ts", ]) + ["PACKAGE.md"], ) generate_api_docs( name = "elements_docs", srcs = [ ":files_for_docgen", "//packages:common_files_and_deps_for_docs", ], entry_point = ":index.ts", module_name = "@angular/elements", )
{ "end_byte": 1424, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/BUILD.bazel" }
angular/packages/elements/index.ts_0_481
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // This file is not used to build this module. It is only used during editing // by the TypeScript language service and during build for verification. `ngc` // replaces this file with production index.ts when it rewrites private symbol // names. export * from './public_api';
{ "end_byte": 481, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/index.ts" }
angular/packages/elements/public_api.ts_0_677
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * @module * @description * Entry point for all public APIs of the `elements` package. */ export { createCustomElement, NgElement, NgElementConfig, NgElementConstructor, WithProperties, } from './src/create-custom-element'; export { NgElementStrategy, NgElementStrategyEvent, NgElementStrategyFactory, } from './src/element-strategy'; export {VERSION} from './src/version'; // This file only reexports content of the `src` folder. Keep it that way.
{ "end_byte": 677, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/public_api.ts" }
angular/packages/elements/test/create-custom-element_spec.ts_0_832
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Component, destroyPlatform, DoBootstrap, EventEmitter, Injector, Input, NgModule, Output, } from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {Subject} from 'rxjs'; import {createCustomElement, NgElementConstructor} from '../src/create-custom-element'; import { NgElementStrategy, NgElementStrategyEvent, NgElementStrategyFactory, } from '../src/element-strategy'; interface WithFooBar { fooFoo: string; barBar: string; fooTransformed: unknown; } describe('createCustomElement',
{ "end_byte": 832, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/test/create-custom-element_spec.ts" }
angular/packages/elements/test/create-custom-element_spec.ts_833_9697
() => { let selectorUid = 0; let testContainer: HTMLDivElement; let NgElementCtor: NgElementConstructor<WithFooBar>; let strategy: TestStrategy; let strategyFactory: TestStrategyFactory; let injector: Injector; beforeAll((done) => { testContainer = document.createElement('div'); document.body.appendChild(testContainer); destroyPlatform(); platformBrowserDynamic() .bootstrapModule(TestModule) .then((ref) => { injector = ref.injector; strategyFactory = new TestStrategyFactory(); strategy = strategyFactory.testStrategy; NgElementCtor = createAndRegisterTestCustomElement(strategyFactory); }) .then(done, done.fail); }); afterEach(() => strategy.reset()); afterAll(() => { destroyPlatform(); testContainer.remove(); (testContainer as any) = null; }); it('should use a default strategy for converting component inputs', () => { expect(NgElementCtor.observedAttributes).toEqual(['foo-foo', 'barbar', 'foo-transformed']); }); it('should send input values from attributes when connected', () => { const element = new NgElementCtor(injector); element.setAttribute('foo-foo', 'value-foo-foo'); element.setAttribute('barbar', 'value-barbar'); element.setAttribute('foo-transformed', 'truthy'); element.connectedCallback(); expect(strategy.connectedElement).toBe(element); expect(strategy.getInputValue('fooFoo')).toBe('value-foo-foo'); expect(strategy.getInputValue('barBar')).toBe('value-barbar'); expect(strategy.getInputValue('fooTransformed')).toBe(true); }); it('should work even if the constructor is not called (due to polyfill)', () => { // Currently, all the constructor does is initialize the `injector` property. This // test simulates not having called the constructor by "unsetting" the property. // // NOTE: // If the constructor implementation changes in the future, this test needs to be adjusted // accordingly. const element = new NgElementCtor(injector); delete (element as any).injector; element.setAttribute('foo-foo', 'value-foo-foo'); element.setAttribute('barbar', 'value-barbar'); element.setAttribute('foo-transformed', 'truthy'); element.connectedCallback(); expect(strategy.connectedElement).toBe(element); expect(strategy.getInputValue('fooFoo')).toBe('value-foo-foo'); expect(strategy.getInputValue('barBar')).toBe('value-barbar'); expect(strategy.getInputValue('fooTransformed')).toBe(true); }); it('should listen to output events after connected', () => { const element = new NgElementCtor(injector); element.connectedCallback(); let eventValue: any = null; element.addEventListener('some-event', (e: Event) => (eventValue = (e as CustomEvent).detail)); strategy.events.next({name: 'some-event', value: 'event-value'}); expect(eventValue).toEqual('event-value'); }); it('should not listen to output events after disconnected', () => { const element = new NgElementCtor(injector); element.connectedCallback(); element.disconnectedCallback(); expect(strategy.disconnectCalled).toBe(true); let eventValue: any = null; element.addEventListener('some-event', (e: Event) => (eventValue = (e as CustomEvent).detail)); strategy.events.next({name: 'some-event', value: 'event-value'}); expect(eventValue).toEqual(null); }); it('should listen to output events during initialization', () => { const events: string[] = []; const element = new NgElementCtor(injector); element.addEventListener('strategy-event', (evt) => events.push((evt as CustomEvent).detail)); element.connectedCallback(); expect(events).toEqual(['connect']); }); it('should not break if `NgElementStrategy#events` is not available before calling `NgElementStrategy#connect()`', () => { class TestStrategyWithLateEvents extends TestStrategy { override events: Subject<NgElementStrategyEvent> = undefined!; override connect(element: HTMLElement): void { this.connectedElement = element; this.events = new Subject<NgElementStrategyEvent>(); this.events.next({name: 'strategy-event', value: 'connect'}); } } const strategyWithLateEvents = new TestStrategyWithLateEvents(); const capturedEvents: string[] = []; const NgElementCtorWithLateEventsStrategy = createAndRegisterTestCustomElement({ create: () => strategyWithLateEvents, }); const element = new NgElementCtorWithLateEventsStrategy(injector); element.addEventListener('strategy-event', (evt) => capturedEvents.push((evt as CustomEvent).detail), ); element.connectedCallback(); // The "connect" event (emitted during initialization) was missed, but things didn't break. expect(capturedEvents).toEqual([]); // Subsequent events are still captured. strategyWithLateEvents.events.next({name: 'strategy-event', value: 'after-connect'}); expect(capturedEvents).toEqual(['after-connect']); }); it('should properly set getters/setters on the element', () => { const element = new NgElementCtor(injector); element.fooFoo = 'foo-foo-value'; element.barBar = 'barBar-value'; element.fooTransformed = 'truthy'; expect(strategy.inputs.get('fooFoo')).toBe('foo-foo-value'); expect(strategy.inputs.get('barBar')).toBe('barBar-value'); expect(strategy.inputs.get('fooTransformed')).toBe(true); }); it('should properly handle getting/setting properties on the element even if the constructor is not called', () => { // Create a custom element while ensuring that the `NgElementStrategy` is not created // inside the constructor. This is done to emulate the behavior of some polyfills that do // not call the constructor. strategyFactory.create = () => undefined as unknown as NgElementStrategy; const element = new NgElementCtor(injector); strategyFactory.create = TestStrategyFactory.prototype.create; element.fooFoo = 'foo-foo-value'; element.barBar = 'barBar-value'; element.fooTransformed = 'truthy'; expect(strategy.inputs.get('fooFoo')).toBe('foo-foo-value'); expect(strategy.inputs.get('barBar')).toBe('barBar-value'); expect(strategy.inputs.get('fooTransformed')).toBe(true); }); it('should capture properties set before upgrading the element', () => { // Create a regular element and set properties on it. const {selector, ElementCtor} = createTestCustomElement(strategyFactory); const element = Object.assign(document.createElement(selector), { fooFoo: 'foo-prop-value', barBar: 'bar-prop-value', fooTransformed: 'truthy' as unknown, }); expect(element.fooFoo).toBe('foo-prop-value'); expect(element.barBar).toBe('bar-prop-value'); expect(element.fooTransformed).toBe('truthy'); // Upgrade the element to a Custom Element and insert it into the DOM. customElements.define(selector, ElementCtor); testContainer.appendChild(element); expect(element.fooFoo).toBe('foo-prop-value'); expect(element.barBar).toBe('bar-prop-value'); expect(element.fooTransformed).toBe(true); expect(strategy.inputs.get('fooFoo')).toBe('foo-prop-value'); expect(strategy.inputs.get('barBar')).toBe('bar-prop-value'); expect(strategy.inputs.get('fooTransformed')).toBe(true); }); it('should capture properties set after upgrading the element but before inserting it into the DOM', () => { // Create a regular element and set properties on it. const {selector, ElementCtor} = createTestCustomElement(strategyFactory); const element = Object.assign(document.createElement(selector), { fooFoo: 'foo-prop-value', barBar: 'bar-prop-value', fooTransformed: 'truthy' as unknown, }); expect(element.fooFoo).toBe('foo-prop-value'); expect(element.barBar).toBe('bar-prop-value'); expect(element.fooTransformed).toBe('truthy'); // Upgrade the element to a Custom Element (without inserting it into the DOM) and update a // property. customElements.define(selector, ElementCtor); customElements.upgrade(element); element.barBar = 'bar-prop-value-2'; element.fooTransformed = ''; expect(element.fooFoo).toBe('foo-prop-value'); expect(element.barBar).toBe('bar-prop-value-2'); expect(element.fooTransformed).toBe(''); // Insert the element into the DOM. testContainer.appendChild(element); expect(element.fooFoo).toBe('foo-prop-value'); expect(element.barBar).toBe('bar-prop-value-2'); expect(element.fooTransformed).toBe(false); expect(strategy.inputs.get('fooFoo')).toBe('foo-prop-value'); expect(strategy.inputs.get('barBar')).toBe('bar-prop-value-2'); expect(strategy.inputs.get('fooTransformed')).toBe(false); });
{ "end_byte": 9697, "start_byte": 833, "url": "https://github.com/angular/angular/blob/main/packages/elements/test/create-custom-element_spec.ts" }
angular/packages/elements/test/create-custom-element_spec.ts_9701_13649
it('should allow overwriting properties with attributes after upgrading the element but before inserting it into the DOM', () => { // Create a regular element and set properties on it. const {selector, ElementCtor} = createTestCustomElement(strategyFactory); const element = Object.assign(document.createElement(selector), { fooFoo: 'foo-prop-value', barBar: 'bar-prop-value', fooTransformed: 'truthy' as unknown, }); expect(element.fooFoo).toBe('foo-prop-value'); expect(element.barBar).toBe('bar-prop-value'); expect(element.fooTransformed).toBe('truthy'); // Upgrade the element to a Custom Element (without inserting it into the DOM) and set an // attribute. customElements.define(selector, ElementCtor); customElements.upgrade(element); element.setAttribute('barbar', 'bar-attr-value'); element.setAttribute('foo-transformed', ''); expect(element.fooFoo).toBe('foo-prop-value'); expect(element.barBar).toBe('bar-attr-value'); expect(element.fooTransformed).toBe(false); // Insert the element into the DOM. testContainer.appendChild(element); expect(element.fooFoo).toBe('foo-prop-value'); expect(element.barBar).toBe('bar-attr-value'); expect(element.fooTransformed).toBe(false); expect(strategy.inputs.get('fooFoo')).toBe('foo-prop-value'); expect(strategy.inputs.get('barBar')).toBe('bar-attr-value'); expect(strategy.inputs.get('fooTransformed')).toBe(false); }); // Helpers function createAndRegisterTestCustomElement(strategyFactory: NgElementStrategyFactory) { const {selector, ElementCtor} = createTestCustomElement(strategyFactory); customElements.define(selector, ElementCtor); return ElementCtor; } function createTestCustomElement(strategyFactory: NgElementStrategyFactory) { return { selector: `test-element-${++selectorUid}`, ElementCtor: createCustomElement<WithFooBar>(TestComponent, {injector, strategyFactory}), }; } @Component({ selector: 'test-component', template: 'TestComponent|foo({{ fooFoo }})|bar({{ barBar }})', standalone: false, }) class TestComponent { @Input() fooFoo: string = 'foo'; @Input('barbar') barBar!: string; @Input({transform: (value: unknown) => !!value}) fooTransformed!: boolean; @Output() bazBaz = new EventEmitter<boolean>(); @Output('quxqux') quxQux = new EventEmitter<Object>(); } @NgModule({ imports: [BrowserModule], declarations: [TestComponent], }) class TestModule implements DoBootstrap { ngDoBootstrap() {} } class TestStrategy implements NgElementStrategy { connectedElement: HTMLElement | null = null; disconnectCalled = false; inputs = new Map<string, any>(); events = new Subject<NgElementStrategyEvent>(); connect(element: HTMLElement): void { this.events.next({name: 'strategy-event', value: 'connect'}); this.connectedElement = element; } disconnect(): void { this.disconnectCalled = true; } getInputValue(propName: string): any { return this.inputs.get(propName); } setInputValue(propName: string, value: string, transform?: (value: any) => any): void { this.inputs.set(propName, transform ? transform(value) : value); } reset(): void { this.connectedElement = null; this.disconnectCalled = false; this.inputs.clear(); } } class TestStrategyFactory implements NgElementStrategyFactory { testStrategy = new TestStrategy(); create(injector: Injector): NgElementStrategy { // Although not used by the `TestStrategy`, verify that the injector is provided. if (!injector) { throw new Error( 'Expected injector to be passed to `TestStrategyFactory#create()`, but received ' + `value of type ${typeof injector}: ${injector}`, ); } return this.testStrategy; } } });
{ "end_byte": 13649, "start_byte": 9701, "url": "https://github.com/angular/angular/blob/main/packages/elements/test/create-custom-element_spec.ts" }
angular/packages/elements/test/slots_spec.ts_0_5190
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Component, ComponentFactoryResolver, destroyPlatform, EventEmitter, Input, NgModule, Output, ViewEncapsulation, } from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {createCustomElement, NgElement} from '../src/create-custom-element'; describe('slots', () => { let testContainer: HTMLDivElement; beforeAll((done) => { testContainer = document.createElement('div'); document.body.appendChild(testContainer); destroyPlatform(); platformBrowserDynamic() .bootstrapModule(TestModule) .then((ref) => { const injector = ref.injector; const cfr: ComponentFactoryResolver = injector.get(ComponentFactoryResolver); testElements.forEach((comp) => { const compFactory = cfr.resolveComponentFactory(comp); customElements.define(compFactory.selector, createCustomElement(comp, {injector})); }); }) .then(done, done.fail); }); afterAll(() => { destroyPlatform(); testContainer.remove(); (testContainer as any) = null; }); it('should use slots to project content', () => { const tpl = `<default-slot-el><span class="projected"></span></default-slot-el>`; testContainer.innerHTML = tpl; const testEl = testContainer.querySelector('default-slot-el')!; const content = testContainer.querySelector('span.projected')!; const slot = testEl.shadowRoot!.querySelector('slot')!; const assignedNodes = slot.assignedNodes(); expect(assignedNodes[0]).toBe(content); }); it('should use a named slot to project content', () => { const tpl = `<named-slot-el><span class="projected" slot="header"></span></named-slot-el>`; testContainer.innerHTML = tpl; const testEl = testContainer.querySelector('named-slot-el')!; const content = testContainer.querySelector('span.projected')!; const slot = testEl.shadowRoot!.querySelector('slot[name=header]') as HTMLSlotElement; const assignedNodes = slot.assignedNodes(); expect(assignedNodes[0]).toBe(content); }); it('should use named slots to project content', () => { const tpl = ` <named-slots-el> <span class="projected-header" slot="header"></span> <span class="projected-body" slot="body"></span> </named-slots-el>`; testContainer.innerHTML = tpl; const testEl = testContainer.querySelector('named-slots-el')!; const headerContent = testContainer.querySelector('span.projected-header')!; const bodyContent = testContainer.querySelector('span.projected-body')!; const headerSlot = testEl.shadowRoot!.querySelector('slot[name=header]') as HTMLSlotElement; const bodySlot = testEl.shadowRoot!.querySelector('slot[name=body]') as HTMLSlotElement; expect(headerContent.assignedSlot).toBe(headerSlot); expect(bodyContent.assignedSlot).toBe(bodySlot); }); it('should listen to slotchange events', (done) => { const templateEl = document.createElement('template'); const tpl = ` <slot-events-el> <span class="projected">Content</span> </slot-events-el>`; templateEl.innerHTML = tpl; const template = templateEl.content.cloneNode(true) as DocumentFragment; const testEl = template.querySelector('slot-events-el')! as NgElement & SlotEventsComponent; testEl.addEventListener('slotEventsChange', (e) => { expect(testEl.slotEvents.length).toEqual(1); done(); }); testContainer.appendChild(template); expect(testEl.slotEvents.length).toEqual(0); }); }); // Helpers @Component({ selector: 'default-slot-el', template: '<div class="slotparent"><slot></slot></div>', encapsulation: ViewEncapsulation.ShadowDom, standalone: false, }) class DefaultSlotComponent { constructor() {} } @Component({ selector: 'named-slot-el', template: '<div class="slotparent"><slot name="header"></slot></div>', encapsulation: ViewEncapsulation.ShadowDom, standalone: false, }) class NamedSlotComponent { constructor() {} } @Component({ selector: 'named-slots-el', template: '<div class="slotparent"><slot name="header"></slot><slot name="body"></slot></div>', encapsulation: ViewEncapsulation.ShadowDom, standalone: false, }) class NamedSlotsComponent { constructor() {} } @Component({ selector: 'slot-events-el', template: '<slot (slotchange)="onSlotChange($event)"></slot>', encapsulation: ViewEncapsulation.ShadowDom, standalone: false, }) class SlotEventsComponent { @Input() slotEvents: Event[] = []; @Output() slotEventsChange = new EventEmitter(); constructor() {} onSlotChange(event: Event) { this.slotEvents.push(event); this.slotEventsChange.emit(event); } } const testElements = [ DefaultSlotComponent, NamedSlotComponent, NamedSlotsComponent, SlotEventsComponent, ]; @NgModule({imports: [BrowserModule], declarations: testElements}) class TestModule { ngDoBootstrap() {} }
{ "end_byte": 5190, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/test/slots_spec.ts" }
angular/packages/elements/test/extract-projectable-nodes_spec.ts_0_2418
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {extractProjectableNodes} from '../src/extract-projectable-nodes'; describe('extractProjectableNodes()', () => { let elem: HTMLElement; let childNodes: ChildNode[]; const expectProjectableNodes = (matches: {[selector: string]: number[]}) => { const selectors = Object.keys(matches); const expected = selectors.map((selector) => { const matchingIndices = matches[selector]; return matchingIndices.map((idx) => childNodes[idx]); }); expect(extractProjectableNodes(elem, selectors)).toEqual(expected); }; const test = (matches: {[selector: string]: number[]}) => () => expectProjectableNodes(matches); beforeEach(() => { elem = document.createElement('div'); elem.innerHTML = '<div class="foo" first="">' + '<span class="bar"></span>' + '</div>' + '<span id="bar"></span>' + '<!-- Comment -->' + 'Text' + '<blink class="foo" id="quux"></blink>' + 'More text'; childNodes = Array.prototype.slice.call(elem.childNodes); }); it( 'should match each node to the corresponding selector', test({ '[first]': [0], '#bar': [1], '#quux': [4], }), ); it( 'should ignore non-matching nodes', test({ '.zoo': [], }), ); it( 'should only match top-level child nodes', test({ 'span': [1], '.bar': [], }), ); it( 'should support complex selectors', test({ '.foo:not(div)': [4], 'div + #bar': [1], }), ); it( 'should match each node with the first matching selector', test({ 'div': [0], '.foo': [4], 'blink': [], }), ); describe('(with wildcard selector)', () => { it( 'should match non-element nodes to `*` (but still ignore comments)', test({ 'div,span,blink': [0, 1, 4], '*': [2, 3, 5], }), ); it( 'should match otherwise unmatched nodes to `*`', test({ 'div,blink': [0, 4], '*': [1, 2, 3, 5], }), ); it( 'should give higher priority to `*` (eve if it appears first)', test({ '*': [2, 3, 5], 'div,span,blink': [0, 1, 4], }), ); }); });
{ "end_byte": 2418, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/test/extract-projectable-nodes_spec.ts" }
angular/packages/elements/test/component-factory-strategy_spec.ts_0_6974
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { ApplicationRef, Component, ComponentRef, Directive, EnvironmentInjector, Injector, Input, NgZone, Output, OutputEmitterRef, SimpleChange, SimpleChanges, createComponent, inject, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {Subject, filter, firstValueFrom} from 'rxjs'; import { ComponentNgElementStrategy, ComponentNgElementStrategyFactory, } from '../src/component-factory-strategy'; import {NgElementStrategyEvent} from '../src/element-strategy'; describe('ComponentFactoryNgElementStrategy', () => { let strategy: ComponentNgElementStrategy; let injector: Injector; beforeEach(() => { TestBed.configureTestingModule({}); injector = TestBed.inject(Injector); const strategyFactory = new ComponentNgElementStrategyFactory(TestComponent, injector); strategy = strategyFactory.create(injector); }); async function whenStable(): Promise<void> { const appRef = injector.get(ApplicationRef); await firstValueFrom(appRef.isStable.pipe(filter((stable) => stable))); return; } it('should create a new strategy from the factory', () => { const strategyFactory = new ComponentNgElementStrategyFactory(TestComponent, injector); expect(strategyFactory.create(injector)).toBeTruthy(); }); describe('before connected', () => { it('should allow subscribing to output events', () => { const events: NgElementStrategyEvent[] = []; strategy.events.subscribe((e) => events.push(e)); // No events upon connecting (since events are not cached/played back). strategy.connect(document.createElement('div')); expect(events).toEqual([]); // Events emitted once connected. const componentRef = getComponentRef(strategy)!; componentRef.instance.output1.next('output-1c'); componentRef.instance.output1.next('output-1d'); componentRef.instance.output2.next('output-2b'); expect(events).toEqual([ {name: 'templateOutput1', value: 'output-1c'}, {name: 'templateOutput1', value: 'output-1d'}, {name: 'templateOutput2', value: 'output-2b'}, ]); }); }); describe('after connected', () => { let componentRef: ComponentRef<TestComponent>; beforeEach(() => { // Set up an initial value to make sure it is passed to the component strategy.setInputValue('fooFoo', 'fooFoo-1'); strategy.setInputValue('falsyUndefined', undefined); strategy.setInputValue('falsyNull', null); strategy.setInputValue('falsyEmpty', ''); strategy.setInputValue('falsyFalse', false); strategy.setInputValue('falsyZero', 0); strategy.connect(document.createElement('div')); componentRef = getComponentRef(strategy)!; expect(componentRef).not.toBeNull(); }); it('should attach the component to the view', () => { expect((TestBed.inject(ApplicationRef) as any).allViews).toContain(componentRef.hostView); }); it('should detect changes', () => { expect(componentRef.instance.cdCalls).toBe(2); }); it('should listen to output events', () => { const events: NgElementStrategyEvent[] = []; strategy.events.subscribe((e) => events.push(e)); componentRef.instance.output1.next('output-1a'); componentRef.instance.output1.next('output-1b'); componentRef.instance.output2.next('output-2a'); expect(events).toEqual([ {name: 'templateOutput1', value: 'output-1a'}, {name: 'templateOutput1', value: 'output-1b'}, {name: 'templateOutput2', value: 'output-2a'}, ]); }); it('should listen to output() emitters', () => { const events: NgElementStrategyEvent[] = []; strategy.events.subscribe((e) => events.push(e)); componentRef.instance.output3.emit('output-a'); componentRef.instance.output3.emit('output-b'); expect(events).toEqual([ {name: 'templateOutput3', value: 'output-a'}, {name: 'templateOutput3', value: 'output-b'}, ]); }); it('should initialize the component with initial values', () => { expect(strategy.getInputValue('fooFoo')).toBe('fooFoo-1'); expect(componentRef.instance.fooFoo).toBe('fooFoo-1'); }); it('should initialize the component with falsy initial values', () => { expect(strategy.getInputValue('falsyUndefined')).toEqual(undefined); expect(componentRef.instance.falsyUndefined).toEqual(undefined); expect(strategy.getInputValue('falsyNull')).toEqual(null); expect(componentRef.instance.falsyNull).toEqual(null); expect(strategy.getInputValue('falsyEmpty')).toEqual(''); expect(componentRef.instance.falsyEmpty).toEqual(''); expect(strategy.getInputValue('falsyFalse')).toEqual(false); expect(componentRef.instance.falsyFalse).toEqual(false); expect(strategy.getInputValue('falsyZero')).toEqual(0); expect(componentRef.instance.falsyZero).toEqual(0); }); it('should call ngOnChanges with the change', () => { expectSimpleChanges(componentRef.instance.simpleChanges[0], { fooFoo: new SimpleChange(undefined, 'fooFoo-1', true), falsyUndefined: new SimpleChange(undefined, undefined, true), falsyNull: new SimpleChange(undefined, null, true), falsyEmpty: new SimpleChange(undefined, '', true), falsyFalse: new SimpleChange(undefined, false, true), falsyZero: new SimpleChange(undefined, 0, true), }); }); // Disabled: this is not actually how `NgOnChanges` works. The test appears to encode correct // behavior, but the `ngOnChanges` implementation has a bug. xit('should call ngOnChanges with proper firstChange value', async () => { strategy.setInputValue('fooFoo', 'fooFoo-2'); strategy.setInputValue('barBar', 'barBar-1'); strategy.setInputValue('falsyUndefined', 'notanymore'); await whenStable(); expectSimpleChanges(componentRef.instance.simpleChanges[1], { fooFoo: new SimpleChange('fooFoo-1', 'fooFoo-2', false), barBar: new SimpleChange(undefined, 'barBar-1', true), falsyUndefined: new SimpleChange(undefined, 'notanymore', false), }); }); }); describe('when inputs change and not connected', () => { it('should cache the value', () => { strategy.setInputValue('fooFoo', 'fooFoo-1'); expect(strategy.getInputValue('fooFoo')).toBe('fooFoo-1'); // Sanity check: componentRef doesn't exist. expect(getComponentRef(strategy)).toBeNull(); }); it('should not detect changes', () => { strategy.setInputValue('fooFoo', 'fooFoo-1'); // Sanity check: componentRef doesn't exist. expect(getComponentRef(strategy)).toBeNull(); }); });
{ "end_byte": 6974, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/test/component-factory-strategy_spec.ts" }
angular/packages/elements/test/component-factory-strategy_spec.ts_6978_15394
describe('when inputs change and is connected', () => { let componentRef: ComponentRef<TestComponent>; beforeEach(async () => { strategy.connect(document.createElement('div')); componentRef = getComponentRef(strategy)!; expect(componentRef).not.toBeNull(); await whenStable(); expect(componentRef.instance.cdCalls).toBe(2); componentRef.instance.cdCalls = 0; }); it('should be set on the component instance', () => { strategy.setInputValue('fooFoo', 'fooFoo-1'); expect(componentRef.instance.fooFoo).toBe('fooFoo-1'); expect(strategy.getInputValue('fooFoo')).toBe('fooFoo-1'); }); it('should detect changes', async () => { expect(componentRef.instance.cdCalls).toBe(0); strategy.setInputValue('fooFoo', 'fooFoo-1'); await whenStable(); // Connect detected changes automatically expect(componentRef.instance.cdCalls).toBe(1); }); it('should detect changes even when updated during CD', async () => { @Component({ standalone: true, template: ``, }) class DriverCmp { ngAfterViewChecked(): void { // This runs within the Angular zone, within change detection. NgZone.assertInAngularZone(); // Because we're inside the zone, setting the input won't cause a fresh tick() to be // scheduled (the scheduler knows we're in the zone and in fact that a tick() is in // progress). However, setting the input should cause the view to be marked for _refresh_ // as well as dirty, allowing CD to revisit this view and pick up the change. strategy.setInputValue('fooFoo', 'fooFoo-2'); } } const appRef = TestBed.inject(ApplicationRef); const cmpRef = createComponent(DriverCmp, {environmentInjector: appRef.injector}); appRef.attachView(cmpRef.hostView); // Wait for CD of the application, which needs to check `TestComponent` twice since it only // becomes dirty after `DriverCmp.ngAfterViewChecked`. await whenStable(); expect(componentRef.instance.fooFoo).toBe('fooFoo-2'); expect(componentRef.instance.cdCalls).toBe(2); }); // Disabled: when `setInputValue()` is called from outside the zone (like in this test), CD will // be forced to run after each `setInputValue()` call, thanks to `setInputValue()` running // `NgZone.run()`. // // Previously, this test spied on `.detectChanges()` and therefore did not detect that this was // happening, since the CD triggered from `ApplicationRef.tick()` didn't go through // `.detectChanges()`. xit('should detect changes once for multiple input changes', async () => { strategy.setInputValue('fooFoo', 'fooFoo-1'); expect(componentRef.instance.cdCalls).toBe(0); strategy.setInputValue('barBar', 'barBar-1'); await whenStable(); expect(componentRef.instance.cdCalls).toBe(1); }); it('should call ngOnChanges', async () => { strategy.setInputValue('fooFoo', 'fooFoo-1'); await whenStable(); expectSimpleChanges(componentRef.instance.simpleChanges[0], { fooFoo: new SimpleChange(undefined, 'fooFoo-1', true), }); }); // Disabled: as in "should detect changes once for multiple input changes" above, CD runs after // each `setInputValue`, with `ngOnChanges` delivered for each one. xit('should call ngOnChanges once for multiple input changes', async () => { strategy.setInputValue('fooFoo', 'fooFoo-1'); strategy.setInputValue('barBar', 'barBar-1'); await whenStable(); expectSimpleChanges(componentRef.instance.simpleChanges[0], { fooFoo: new SimpleChange(undefined, 'fooFoo-1', true), barBar: new SimpleChange(undefined, 'barBar-1', true), }); }); // Disabled: as in "should detect changes once for multiple input changes" above, CD runs after // each `setInputValue`, with `ngOnChanges` delivered for each one. xit('should call ngOnChanges twice for changes in different rounds with previous values', async () => { strategy.setInputValue('fooFoo', 'fooFoo-1'); strategy.setInputValue('barBar', 'barBar-1'); await whenStable(); expectSimpleChanges(componentRef.instance.simpleChanges[0], { fooFoo: new SimpleChange(undefined, 'fooFoo-1', true), barBar: new SimpleChange(undefined, 'barBar-1', true), }); strategy.setInputValue('fooFoo', 'fooFoo-2'); strategy.setInputValue('barBar', 'barBar-2'); await whenStable(); expectSimpleChanges(componentRef.instance.simpleChanges[1], { fooFoo: new SimpleChange('fooFoo-1', 'fooFoo-2', false), barBar: new SimpleChange('barBar-1', 'barBar-2', false), }); }); }); describe('disconnect', () => { it('should be able to call if not connected', () => { expect(() => strategy.disconnect()).not.toThrow(); // Sanity check: componentRef doesn't exist. expect(getComponentRef(strategy)).toBeNull(); }); it('should destroy the component after the destroy delay', async () => { strategy.connect(document.createElement('div')); const componentRef = getComponentRef(strategy)!; let destroyed = false; componentRef.onDestroy(() => (destroyed = true)); strategy.disconnect(); expect(destroyed).toBeFalse(); await new Promise((resolve) => setTimeout(resolve, 10)); expect(destroyed).toBeTrue(); }); }); describe('runInZone', () => { const param = 'foofoo'; it("should run the callback directly when invoked in element's zone", () => { expect( strategy['runInZone'](() => { expect(Zone.current.name).toBe('angular'); return param; }), ).toEqual('foofoo'); }); it("should run the callback inside the element's zone when invoked in a different zone", () => { expect( Zone.root.run(() => strategy['runInZone'](() => { expect(Zone.current.name).toBe('angular'); return param; }), ), ).toEqual('foofoo'); }); xit('should run the callback directly when called without zone.js loaded', () => { // simulate no zone.js loaded (strategy as any)['elementZone'] = null; expect( Zone.root.run(() => strategy['runInZone'](() => { return param; }), ), ).toEqual('foofoo'); }); }); }); @Directive({ standalone: true, selector: '[cdTracker]', }) export class CdTrackerDir { parent = inject(TestComponent); ngDoCheck(): void { this.parent.cdCalls++; } } @Component({ selector: 'fake-component', standalone: true, imports: [CdTrackerDir], template: ` <ng-container cdTracker></ng-container> <ng-content select="content-1"></ng-content> <ng-content select="content-2"></ng-content> `, }) export class TestComponent { @Output('templateOutput1') output1 = new Subject(); @Output('templateOutput2') output2 = new Subject(); @Output('templateOutput3') output3 = new OutputEmitterRef(); @Input() fooFoo: unknown; @Input({alias: 'my-bar-bar'}) barBar: unknown; @Input() falsyUndefined: unknown; @Input() falsyNull: unknown; @Input() falsyEmpty: unknown; @Input() falsyFalse: unknown; @Input() falsyZero: unknown; // Keep track of the simple changes passed to ngOnChanges simpleChanges: SimpleChanges[] = []; ngOnChanges(simpleChanges: SimpleChanges) { this.simpleChanges.push(simpleChanges); } cdCalls = 0; } function expectSimpleChanges(actual: SimpleChanges, expected: SimpleChanges) { Object.keys(actual).forEach((key) => { expect(expected[key]).toBeTruthy(`Change included additional key ${key}`); }); Object.keys(expected).forEach((key) => { expect(actual[key]).toBeTruthy(`Change should have included key ${key}`); if (actual[key]) { expect(actual[key].previousValue).toBe(expected[key].previousValue, `${key}.previousValue`); expect(actual[key].currentValue).toBe(expected[key].currentValue, `${key}.currentValue`); expect(actual[key].firstChange).toBe(expected[key].firstChange, `${key}.firstChange`); } }); } function getComponentRef(strategy: ComponentNgElementStrategy): ComponentRef<TestComponent> | null { return (strategy as any).componentRef; }
{ "end_byte": 15394, "start_byte": 6978, "url": "https://github.com/angular/angular/blob/main/packages/elements/test/component-factory-strategy_spec.ts" }
angular/packages/elements/test/create-custom-element-env_spec.ts_0_1351
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component} from '@angular/core'; import {createApplication} from '@angular/platform-browser'; import {createCustomElement} from '../public_api'; describe('createCustomElement with env injector', () => { let testContainer: HTMLDivElement; beforeEach(() => { testContainer = document.createElement('div'); document.body.appendChild(testContainer); }); afterEach(() => { testContainer.remove(); (testContainer as any) = null; }); it('should use provided EnvironmentInjector to create a custom element', async () => { @Component({ standalone: true, template: `Hello, standalone element!`, }) class TestStandaloneCmp {} const appRef = await createApplication(); try { const NgElementCtor = createCustomElement(TestStandaloneCmp, {injector: appRef.injector}); customElements.define('test-standalone-cmp', NgElementCtor); const customEl = document.createElement('test-standalone-cmp'); testContainer.appendChild(customEl); expect(testContainer.innerText).toBe('Hello, standalone element!'); } finally { appRef.destroy(); } }); });
{ "end_byte": 1351, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/test/create-custom-element-env_spec.ts" }
angular/packages/elements/test/BUILD.bazel_0_857
load("//tools:defaults.bzl", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/elements/index.mjs", deps = ["//packages/elements"], ) ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), deps = [ "//packages:types", "//packages/compiler", "//packages/core", "//packages/core/testing", "//packages/elements", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/platform-browser-dynamic/testing", "//packages/platform-browser/testing", "@npm//rxjs", ], ) karma_web_test_suite( name = "test", deps = [ ":test_lib", ], )
{ "end_byte": 857, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/test/BUILD.bazel" }
angular/packages/elements/test/utils_spec.ts_0_5567
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { camelToDashCase, isElement, isFunction, kebabToCamelCase, matchesSelector, scheduler, strictEquals, } from '../src/utils'; describe('utils', () => { describe('scheduler', () => { describe('schedule()', () => { let setTimeoutSpy: jasmine.Spy; let clearTimeoutSpy: jasmine.Spy; beforeEach(() => { // TODO: @JiaLiPassion, need to wait @types/jasmine to fix the wrong return // type infer issue. // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43486 setTimeoutSpy = spyOn(window, 'setTimeout').and.returnValue(42 as any); clearTimeoutSpy = spyOn(window, 'clearTimeout'); }); it('should delegate to `window.setTimeout()`', () => { const cb = () => null; const delay = 1337; scheduler.schedule(cb, delay); expect(setTimeoutSpy).toHaveBeenCalledWith(cb, delay); }); it('should return a function for cancelling the scheduled job', () => { const cancelFn = scheduler.schedule(() => null, 0); expect(clearTimeoutSpy).not.toHaveBeenCalled(); cancelFn(); expect(clearTimeoutSpy).toHaveBeenCalledWith(42); }); }); }); describe('camelToKebabCase()', () => { it('should convert camel-case to kebab-case', () => { expect(camelToDashCase('fooBarBazQux')).toBe('foo-bar-baz-qux'); expect(camelToDashCase('foo1Bar2Baz3Qux4')).toBe('foo1-bar2-baz3-qux4'); }); it('should keep existing dashes', () => { expect(camelToDashCase('fooBar-baz-Qux')).toBe('foo-bar-baz--qux'); }); }); describe('isElement()', () => { it('should return true for Element nodes', () => { const elems = [ document.body, document.createElement('div'), document.createElement('option'), document.documentElement, ]; elems.forEach((n) => expect(isElement(n)).toBe(true)); }); it('should return false for non-Element nodes', () => { const nonElems = [ document, document.createAttribute('foo'), document.createDocumentFragment(), document.createComment('bar'), document.createTextNode('baz'), ]; nonElems.forEach((n) => expect(isElement(n)).toBe(false)); }); }); describe('isFunction()', () => { it('should return true for functions', () => { const obj = {foo: function () {}, bar: () => null, baz() {}}; const fns = [function () {}, () => null, obj.foo, obj.bar, obj.baz, Function, Date]; fns.forEach((v) => expect(isFunction(v)).toBe(true)); }); it('should return false for non-functions', () => { const nonFns = [undefined, null, true, 42, {}]; nonFns.forEach((v) => expect(isFunction(v)).toBe(false)); }); }); describe('kebabToCamelCase()', () => { it('should convert camel-case to kebab-case', () => { expect(kebabToCamelCase('foo-bar-baz-qux')).toBe('fooBarBazQux'); expect(kebabToCamelCase('foo1-bar2-baz3-qux4')).toBe('foo1Bar2Baz3Qux4'); expect(kebabToCamelCase('foo-1-bar-2-baz-3-qux-4')).toBe('foo1Bar2Baz3Qux4'); }); it('should keep uppercase letters', () => { expect(kebabToCamelCase('foo-barBaz-Qux')).toBe('fooBarBaz-Qux'); expect(kebabToCamelCase('foo-barBaz--qux')).toBe('fooBarBaz-Qux'); }); }); describe('matchesSelector()', () => { let li: HTMLLIElement; beforeEach(() => { const div = document.createElement('div'); div.innerHTML = ` <div class="bar" id="barDiv"> <span class="baz"></span> <ul class="baz" id="bazUl"> <li class="qux" id="quxLi"></li> </ul> </div> `; li = div.querySelector('li')!; }); it('should return whether the element matches the selector', () => { expect(matchesSelector(li, 'li')).toBe(true); expect(matchesSelector(li, '.qux')).toBe(true); expect(matchesSelector(li, '#quxLi')).toBe(true); expect(matchesSelector(li, '.qux#quxLi:not(.quux)')).toBe(true); expect(matchesSelector(li, '.bar > #bazUl > li')).toBe(true); expect(matchesSelector(li, '.bar .baz ~ .baz li')).toBe(true); expect(matchesSelector(li, 'ol')).toBe(false); expect(matchesSelector(li, '.quux')).toBe(false); expect(matchesSelector(li, '#quuxOl')).toBe(false); expect(matchesSelector(li, '.qux#quxLi:not(li)')).toBe(false); expect(matchesSelector(li, '.bar > #bazUl > .quxLi')).toBe(false); expect(matchesSelector(li, 'div span ul li')).toBe(false); }); }); describe('strictEquals()', () => { it('should perform strict equality check', () => { const values = [ undefined, null, true, false, 42, '42', () => undefined, () => undefined, {}, {}, ]; values.forEach((v1, i) => { values.forEach((v2, j) => { expect(strictEquals(v1, v2)).toBe(i === j); }); }); }); it('should consider two `NaN` values equals', () => { expect(strictEquals(NaN, NaN)).toBe(true); expect(strictEquals(NaN, 'foo')).toBe(false); expect(strictEquals(NaN, 42)).toBe(false); expect(strictEquals(NaN, null)).toBe(false); expect(strictEquals(NaN, undefined)).toBe(false); }); }); });
{ "end_byte": 5567, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/test/utils_spec.ts" }
angular/packages/elements/src/element-strategy.ts_0_1105
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Injector} from '@angular/core'; import {Observable} from 'rxjs'; /** * Interface for the events emitted through the NgElementStrategy. * * @publicApi */ export interface NgElementStrategyEvent { name: string; value: any; } /** * Underlying strategy used by the NgElement to create/destroy the component and react to input * changes. * * @publicApi */ export interface NgElementStrategy { events: Observable<NgElementStrategyEvent>; connect(element: HTMLElement): void; disconnect(): void; getInputValue(propName: string): any; setInputValue(propName: string, value: string, transform?: (value: any) => any): void; } /** * Factory used to create new strategies for each NgElement instance. * * @publicApi */ export interface NgElementStrategyFactory { /** Creates a new instance to be used for an NgElement. */ create(injector: Injector): NgElementStrategy; }
{ "end_byte": 1105, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/src/element-strategy.ts" }
angular/packages/elements/src/create-custom-element.ts_0_9060
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Injector, Type} from '@angular/core'; import {Subscription} from 'rxjs'; import {ComponentNgElementStrategyFactory} from './component-factory-strategy'; import {NgElementStrategy, NgElementStrategyFactory} from './element-strategy'; import {getComponentInputs, getDefaultAttributeToPropertyInputs} from './utils'; /** * Prototype for a class constructor based on an Angular component * that can be used for custom element registration. Implemented and returned * by the {@link createCustomElement createCustomElement() function}. * * @see [Angular Elements Overview](guide/elements "Turning Angular components into custom elements") * * @publicApi */ export interface NgElementConstructor<P> { /** * An array of observed attribute names for the custom element, * derived by transforming input property names from the source component. */ readonly observedAttributes: string[]; /** * Initializes a constructor instance. * @param injector If provided, overrides the configured injector. */ new (injector?: Injector): NgElement & WithProperties<P>; } /** * Implements the functionality needed for a custom element. * * @publicApi */ export abstract class NgElement extends HTMLElement { /** * The strategy that controls how a component is transformed in a custom element. */ protected abstract ngElementStrategy: NgElementStrategy; /** * A subscription to change, connect, and disconnect events in the custom element. */ protected ngElementEventsSubscription: Subscription | null = null; /** * Prototype for a handler that responds to a change in an observed attribute. * @param attrName The name of the attribute that has changed. * @param oldValue The previous value of the attribute. * @param newValue The new value of the attribute. * @param namespace The namespace in which the attribute is defined. * @returns Nothing. */ abstract attributeChangedCallback( attrName: string, oldValue: string | null, newValue: string, namespace?: string, ): void; /** * Prototype for a handler that responds to the insertion of the custom element in the DOM. * @returns Nothing. */ abstract connectedCallback(): void; /** * Prototype for a handler that responds to the deletion of the custom element from the DOM. * @returns Nothing. */ abstract disconnectedCallback(): void; } /** * Additional type information that can be added to the NgElement class, * for properties that are added based * on the inputs and methods of the underlying component. * * @publicApi */ export type WithProperties<P> = { [property in keyof P]: P[property]; }; /** * A configuration that initializes an NgElementConstructor with the * dependencies and strategy it needs to transform a component into * a custom element class. * * @publicApi */ export interface NgElementConfig { /** * The injector to use for retrieving the component's factory. */ injector: Injector; /** * An optional custom strategy factory to use instead of the default. * The strategy controls how the transformation is performed. */ strategyFactory?: NgElementStrategyFactory; } /** * @description Creates a custom element class based on an Angular component. * * Builds a class that encapsulates the functionality of the provided component and * uses the configuration information to provide more context to the class. * Takes the component factory's inputs and outputs to convert them to the proper * custom element API and add hooks to input changes. * * The configuration's injector is the initial injector set on the class, * and used by default for each created instance.This behavior can be overridden with the * static property to affect all newly created instances, or as a constructor argument for * one-off creations. * * @see [Angular Elements Overview](guide/elements "Turning Angular components into custom elements") * * @param component The component to transform. * @param config A configuration that provides initialization information to the created class. * @returns The custom-element construction class, which can be registered with * a browser's `CustomElementRegistry`. * * @publicApi */ export function createCustomElement<P>( component: Type<any>, config: NgElementConfig, ): NgElementConstructor<P> { const inputs = getComponentInputs(component, config.injector); const strategyFactory = config.strategyFactory || new ComponentNgElementStrategyFactory(component, config.injector); const attributeToPropertyInputs = getDefaultAttributeToPropertyInputs(inputs); class NgElementImpl extends NgElement { // Work around a bug in closure typed optimizations(b/79557487) where it is not honoring static // field externs. So using quoted access to explicitly prevent renaming. static readonly ['observedAttributes'] = Object.keys(attributeToPropertyInputs); protected override get ngElementStrategy(): NgElementStrategy { // TODO(andrewseguin): Add e2e tests that cover cases where the constructor isn't called. For // now this is tested using a Google internal test suite. if (!this._ngElementStrategy) { const strategy = (this._ngElementStrategy = strategyFactory.create( this.injector || config.injector, )); // Re-apply pre-existing input values (set as properties on the element) through the // strategy. // TODO(alxhub): why are we doing this? this makes no sense. inputs.forEach(({propName, transform, isSignal}) => { if (!this.hasOwnProperty(propName) || isSignal) { // No pre-existing value for `propName`, or a signal input. return; } // Delete the property from the instance and re-apply it through the strategy. const value = (this as any)[propName]; delete (this as any)[propName]; strategy.setInputValue(propName, value, transform); }); } return this._ngElementStrategy!; } private _ngElementStrategy?: NgElementStrategy; constructor(private readonly injector?: Injector) { super(); } override attributeChangedCallback( attrName: string, oldValue: string | null, newValue: string, namespace?: string, ): void { const [propName, transform] = attributeToPropertyInputs[attrName]!; this.ngElementStrategy.setInputValue(propName, newValue, transform); } override connectedCallback(): void { // For historical reasons, some strategies may not have initialized the `events` property // until after `connect()` is run. Subscribe to `events` if it is available before running // `connect()` (in order to capture events emitted during initialization), otherwise subscribe // afterwards. // // TODO: Consider deprecating/removing the post-connect subscription in a future major version // (e.g. v11). let subscribedToEvents = false; if (this.ngElementStrategy.events) { // `events` are already available: Subscribe to it asap. this.subscribeToEvents(); subscribedToEvents = true; } this.ngElementStrategy.connect(this); if (!subscribedToEvents) { // `events` were not initialized before running `connect()`: Subscribe to them now. // The events emitted during the component initialization have been missed, but at least // future events will be captured. this.subscribeToEvents(); } } override disconnectedCallback(): void { // Not using `this.ngElementStrategy` to avoid unnecessarily creating the `NgElementStrategy`. if (this._ngElementStrategy) { this._ngElementStrategy.disconnect(); } if (this.ngElementEventsSubscription) { this.ngElementEventsSubscription.unsubscribe(); this.ngElementEventsSubscription = null; } } private subscribeToEvents(): void { // Listen for events from the strategy and dispatch them as custom events. this.ngElementEventsSubscription = this.ngElementStrategy.events.subscribe((e) => { const customEvent = new CustomEvent(e.name, {detail: e.value}); this.dispatchEvent(customEvent); }); } } // Add getters and setters to the prototype for each property input. inputs.forEach(({propName, transform}) => { Object.defineProperty(NgElementImpl.prototype, propName, { get(): any { return this.ngElementStrategy.getInputValue(propName); }, set(newValue: any): void { this.ngElementStrategy.setInputValue(propName, newValue, transform); }, configurable: true, enumerable: true, }); }); return NgElementImpl as any as NgElementConstructor<P>; }
{ "end_byte": 9060, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/src/create-custom-element.ts" }
angular/packages/elements/src/utils.ts_0_3327
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ComponentFactoryResolver, Injector, Type} from '@angular/core'; /** * Provide methods for scheduling the execution of a callback. */ export const scheduler = { /** * Schedule a callback to be called after some delay. * * Returns a function that when executed will cancel the scheduled function. */ schedule(taskFn: () => void, delay: number): () => void { const id = setTimeout(taskFn, delay); return () => clearTimeout(id); }, }; /** * Convert a camelCased string to kebab-cased. */ export function camelToDashCase(input: string): string { return input.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`); } /** * Check whether the input is an `Element`. */ export function isElement(node: Node | null): node is Element { return !!node && node.nodeType === Node.ELEMENT_NODE; } /** * Check whether the input is a function. */ export function isFunction(value: any): value is Function { return typeof value === 'function'; } /** * Convert a kebab-cased string to camelCased. */ export function kebabToCamelCase(input: string): string { return input.replace(/-([a-z\d])/g, (_, char) => char.toUpperCase()); } let _matches: (this: any, selector: string) => boolean; /** * Check whether an `Element` matches a CSS selector. * NOTE: this is duplicated from @angular/upgrade, and can * be consolidated in the future */ export function matchesSelector(el: any, selector: string): boolean { if (!_matches) { const elProto = <any>Element.prototype; _matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector || elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector; } return el.nodeType === Node.ELEMENT_NODE ? _matches.call(el, selector) : false; } /** * Test two values for strict equality, accounting for the fact that `NaN !== NaN`. */ export function strictEquals(value1: any, value2: any): boolean { return value1 === value2 || (value1 !== value1 && value2 !== value2); } /** Gets a map of default set of attributes to observe and the properties they affect. */ export function getDefaultAttributeToPropertyInputs( inputs: {propName: string; templateName: string; transform?: (value: any) => any}[], ) { const attributeToPropertyInputs: { [key: string]: [propName: string, transform: ((value: any) => any) | undefined]; } = {}; inputs.forEach(({propName, templateName, transform}) => { attributeToPropertyInputs[camelToDashCase(templateName)] = [propName, transform]; }); return attributeToPropertyInputs; } /** * Gets a component's set of inputs. Uses the injector to get the component factory where the inputs * are defined. */ export function getComponentInputs( component: Type<any>, injector: Injector, ): { propName: string; templateName: string; transform?: (value: any) => any; isSignal: boolean; }[] { const componentFactoryResolver = injector.get(ComponentFactoryResolver); const componentFactory = componentFactoryResolver.resolveComponentFactory(component); return componentFactory.inputs; }
{ "end_byte": 3327, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/src/utils.ts" }
angular/packages/elements/src/extract-projectable-nodes.ts_0_1485
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // NOTE: This is a (slightly improved) version of what is used in ngUpgrade's // `DowngradeComponentAdapter`. // TODO(gkalpak): Investigate if it makes sense to share the code. import {isElement, matchesSelector} from './utils'; export function extractProjectableNodes(host: HTMLElement, ngContentSelectors: string[]): Node[][] { const nodes = host.childNodes; const projectableNodes: Node[][] = ngContentSelectors.map(() => []); let wildcardIndex = -1; ngContentSelectors.some((selector, i) => { if (selector === '*') { wildcardIndex = i; return true; } return false; }); for (let i = 0, ii = nodes.length; i < ii; ++i) { const node = nodes[i]; const ngContentIndex = findMatchingIndex(node, ngContentSelectors, wildcardIndex); if (ngContentIndex !== -1) { projectableNodes[ngContentIndex].push(node); } } return projectableNodes; } function findMatchingIndex(node: Node, selectors: string[], defaultIndex: number): number { let matchingIndex = defaultIndex; if (isElement(node)) { selectors.some((selector, i) => { if (selector !== '*' && matchesSelector(node, selector)) { matchingIndex = i; return true; } return false; }); } return matchingIndex; }
{ "end_byte": 1485, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/src/extract-projectable-nodes.ts" }
angular/packages/elements/src/component-factory-strategy.ts_0_8491
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { ApplicationRef, ComponentFactory, ComponentFactoryResolver, ComponentRef, EventEmitter, Injector, NgZone, Type, ɵChangeDetectionScheduler as ChangeDetectionScheduler, ɵNotificationSource as NotificationSource, ɵViewRef as ViewRef, OutputRef, } from '@angular/core'; import {merge, Observable, ReplaySubject} from 'rxjs'; import {switchMap} from 'rxjs/operators'; import { NgElementStrategy, NgElementStrategyEvent, NgElementStrategyFactory, } from './element-strategy'; import {extractProjectableNodes} from './extract-projectable-nodes'; import {scheduler} from './utils'; /** Time in milliseconds to wait before destroying the component ref when disconnected. */ const DESTROY_DELAY = 10; /** * Factory that creates new ComponentNgElementStrategy instance. Gets the component factory with the * constructor's injector's factory resolver and passes that factory to each strategy. */ export class ComponentNgElementStrategyFactory implements NgElementStrategyFactory { componentFactory: ComponentFactory<any>; inputMap = new Map<string, string>(); constructor(component: Type<any>, injector: Injector) { this.componentFactory = injector .get(ComponentFactoryResolver) .resolveComponentFactory(component); for (const input of this.componentFactory.inputs) { this.inputMap.set(input.propName, input.templateName); } } create(injector: Injector) { return new ComponentNgElementStrategy(this.componentFactory, injector, this.inputMap); } } /** * Creates and destroys a component ref using a component factory and handles change detection * in response to input changes. */ export class ComponentNgElementStrategy implements NgElementStrategy { // Subject of `NgElementStrategyEvent` observables corresponding to the component's outputs. private eventEmitters = new ReplaySubject<Observable<NgElementStrategyEvent>[]>(1); /** Merged stream of the component's output events. */ readonly events = this.eventEmitters.pipe(switchMap((emitters) => merge(...emitters))); /** Reference to the component that was created on connect. */ private componentRef: ComponentRef<any> | null = null; /** Callback function that when called will cancel a scheduled destruction on the component. */ private scheduledDestroyFn: (() => void) | null = null; /** Initial input values that were set before the component was created. */ private readonly initialInputValues = new Map<string, any>(); /** Service for setting zone context. */ private readonly ngZone: NgZone; /** The zone the element was created in or `null` if Zone.js is not loaded. */ private readonly elementZone: Zone | null; /** * The `ApplicationRef` shared by all instances of this custom element (and potentially others). */ private readonly appRef: ApplicationRef; /** * Angular's change detection scheduler, which works independently of zone.js. */ private cdScheduler: ChangeDetectionScheduler; constructor( private componentFactory: ComponentFactory<any>, private injector: Injector, private inputMap: Map<string, string>, ) { this.ngZone = this.injector.get(NgZone); this.appRef = this.injector.get(ApplicationRef); this.cdScheduler = injector.get(ChangeDetectionScheduler); this.elementZone = typeof Zone === 'undefined' ? null : this.ngZone.run(() => Zone.current); } /** * Initializes a new component if one has not yet been created and cancels any scheduled * destruction. */ connect(element: HTMLElement) { this.runInZone(() => { // If the element is marked to be destroyed, cancel the task since the component was // reconnected if (this.scheduledDestroyFn !== null) { this.scheduledDestroyFn(); this.scheduledDestroyFn = null; return; } if (this.componentRef === null) { this.initializeComponent(element); } }); } /** * Schedules the component to be destroyed after some small delay in case the element is just * being moved across the DOM. */ disconnect() { this.runInZone(() => { // Return if there is no componentRef or the component is already scheduled for destruction if (this.componentRef === null || this.scheduledDestroyFn !== null) { return; } // Schedule the component to be destroyed after a small timeout in case it is being // moved elsewhere in the DOM this.scheduledDestroyFn = scheduler.schedule(() => { if (this.componentRef !== null) { this.componentRef.destroy(); this.componentRef = null; } }, DESTROY_DELAY); }); } /** * Returns the component property value. If the component has not yet been created, the value is * retrieved from the cached initialization values. */ getInputValue(property: string): any { return this.runInZone(() => { if (this.componentRef === null) { return this.initialInputValues.get(property); } return this.componentRef.instance[property]; }); } /** * Sets the input value for the property. If the component has not yet been created, the value is * cached and set when the component is created. */ setInputValue(property: string, value: any): void { if (this.componentRef === null) { this.initialInputValues.set(property, value); return; } this.runInZone(() => { this.componentRef!.setInput(this.inputMap.get(property) ?? property, value); // `setInput` won't mark the view dirty if the input didn't change from its previous value. if ((this.componentRef!.hostView as ViewRef<unknown>).dirty) { // `setInput` will have marked the view dirty already, but also mark it for refresh. This // guarantees the view will be checked even if the input is being set from within change // detection. This provides backwards compatibility, since we used to unconditionally // schedule change detection in addition to the current zone run. (this.componentRef!.changeDetectorRef as ViewRef<unknown>).markForRefresh(); // Notifying the scheduler with `NotificationSource.CustomElement` causes a `tick()` to be // scheduled unconditionally, even if the scheduler is otherwise disabled. this.cdScheduler.notify(NotificationSource.CustomElement); } }); } /** * Creates a new component through the component factory with the provided element host and * sets up its initial inputs, listens for outputs changes, and runs an initial change detection. */ protected initializeComponent(element: HTMLElement) { const childInjector = Injector.create({providers: [], parent: this.injector}); const projectableNodes = extractProjectableNodes( element, this.componentFactory.ngContentSelectors, ); this.componentRef = this.componentFactory.create(childInjector, projectableNodes, element); this.initializeInputs(); this.initializeOutputs(this.componentRef); this.appRef.attachView(this.componentRef.hostView); this.componentRef.hostView.detectChanges(); } /** Set any stored initial inputs on the component's properties. */ protected initializeInputs(): void { for (const [propName, value] of this.initialInputValues) { this.setInputValue(propName, value); } this.initialInputValues.clear(); } /** Sets up listeners for the component's outputs so that the events stream emits the events. */ protected initializeOutputs(componentRef: ComponentRef<any>): void { const eventEmitters: Observable<NgElementStrategyEvent>[] = this.componentFactory.outputs.map( ({propName, templateName}) => { const emitter: EventEmitter<any> | OutputRef<any> = componentRef.instance[propName]; return new Observable((observer) => { const sub = emitter.subscribe((value) => observer.next({name: templateName, value})); return () => sub.unsubscribe(); }); }, ); this.eventEmitters.next(eventEmitters); } /** Runs in the angular zone, if present. */ private runInZone(fn: () => unknown) { return this.elementZone && Zone.current !== this.elementZone ? this.ngZone.run(fn) : fn(); } }
{ "end_byte": 8491, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/src/component-factory-strategy.ts" }
angular/packages/elements/src/version.ts_0_323
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Version} from '@angular/core'; /** * @publicApi */ export const VERSION = new Version('0.0.0-PLACEHOLDER');
{ "end_byte": 323, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/elements/src/version.ts" }
angular/packages/private/testing/BUILD.bazel_0_621
load("//tools:defaults.bzl", "ng_module") package(default_visibility = [ "//adev/src/content/api-examples/forms:__subpackages__", "//adev/src/content/api-examples/upgrade/static/ts:__subpackages__", "//modules/playground:__subpackages__", "//packages:__subpackages__", ]) exports_files(["package.json"]) ng_module( name = "testing", package_name = "@angular/private/testing", testonly = True, srcs = glob( ["**/*.ts"], ), module_name = "@angular/private/testing", deps = [ "//packages/core", "//packages/platform-server:bundled_domino_lib", ], )
{ "end_byte": 621, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/private/testing/BUILD.bazel" }
angular/packages/private/testing/index.ts_0_233
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './src/utils';
{ "end_byte": 233, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/private/testing/index.ts" }
angular/packages/private/testing/src/utils.ts_0_6116
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ɵresetJitOptions as resetJitOptions} from '@angular/core'; /** * Wraps a function in a new function which sets up document and HTML for running a test. * * This function wraps an existing testing function. The wrapper adds HTML to the `body` element of * the `document` and subsequently tears it down. * * This function can be used with `async await` and `Promise`s. If the wrapped function returns a * promise (or is `async`) then the teardown is delayed until that `Promise` is resolved. * * In the NodeJS environment this function detects if `document` is present and if not, it creates * one by loading `domino` and installing it. * * Example: * * ``` * describe('something', () => { * it('should do something', withBody('<app-root></app-root>', async () => { * const fixture = TestBed.createComponent(MyApp); * fixture.detectChanges(); * expect(fixture.nativeElement.textContent).toEqual('Hello World!'); * })); * }); * ``` * * @param html HTML which should be inserted into the `body` of the `document`. * @param blockFn function to wrap. The function can return promise or be `async`. */ export function withBody( html: string, blockFn: () => Promise<unknown> | void, ): jasmine.ImplementationCallback { return wrapTestFn(() => document.body, html, blockFn); } /** * Wraps a function in a new function which sets up document and HTML for running a test. * * This function wraps an existing testing function. The wrapper adds HTML to the `head` element of * the `document` and subsequently tears it down. * * This function can be used with `async await` and `Promise`s. If the wrapped function returns a * promise (or is `async`) then the teardown is delayed until that `Promise` is resolved. * * In the NodeJS environment this function detects if `document` is present and if not, it creates * one by loading `domino` and installing it. * * Example: * * ``` * describe('something', () => { * it('should do something', withHead('<link rel="preconnect" href="...">', async () => { * // ... * })); * }); * ``` * * @param html HTML which should be inserted into the `head` of the `document`. * @param blockFn function to wrap. The function can return promise or be `async`. */ export function withHead( html: string, blockFn: () => Promise<unknown> | void, ): jasmine.ImplementationCallback { return wrapTestFn(() => document.head, html, blockFn); } /** * Wraps provided function (which typically contains the code of a test) into a new function that * performs the necessary setup of the environment. */ function wrapTestFn( elementGetter: () => HTMLElement, html: string, blockFn: () => Promise<unknown> | void, ): jasmine.ImplementationCallback { return () => { elementGetter().innerHTML = html; return blockFn(); }; } /** * Runs jasmine expectations against the provided keys for `ngDevMode`. * * Will not perform expectations for keys that are not provided. * * ```ts * // Expect that `ngDevMode.styleMap` is `1`, and `ngDevMode.tNode` is `3`, but we don't care * // about the other values. * expectPerfCounters({ * stylingMap: 1, * tNode: 3, * }) * ``` */ export function expectPerfCounters(expectedCounters: Partial<NgDevModePerfCounters>): void { Object.keys(expectedCounters).forEach((key) => { const expected = (expectedCounters as any)[key]; const actual = (ngDevMode as any)[key]; expect(actual).toBe(expected, `ngDevMode.${key}`); }); } let savedDocument: Document | undefined = undefined; let savedRequestAnimationFrame: ((callback: FrameRequestCallback) => number) | undefined = undefined; let savedNode: typeof Node | undefined = undefined; let requestAnimationFrameCount = 0; let domino: | (typeof import('../../../platform-server/src/bundled-domino'))['default'] | null | undefined = undefined; async function loadDominoOrNull(): Promise< (typeof import('../../../platform-server/src/bundled-domino'))['default'] | null > { if (domino !== undefined) { return domino; } try { return (domino = (await import('../../../platform-server/src/bundled-domino')).default); } catch { return (domino = null); } } /** * Ensure that global has `Document` if we are in node.js */ export async function ensureDocument(): Promise<void> { if ((global as any).isBrowser) { return; } const domino = await loadDominoOrNull(); if (domino === null) { return; } // we are in node.js. const window = domino.createWindow('', 'http://localhost'); savedDocument = (global as any).document; (global as any).window = window; (global as any).document = window.document; savedNode = (global as any).Node; // Domino types do not type `impl`, but it's a documented field. // See: https://www.npmjs.com/package/domino#usage. (global as any).Event = (domino as typeof domino & {impl: any}).impl.Event; (global as any).Node = (domino as typeof domino & {impl: any}).impl.Node; savedRequestAnimationFrame = (global as any).requestAnimationFrame; (global as any).requestAnimationFrame = function (cb: () => void): number { setImmediate(cb); return requestAnimationFrameCount++; }; } /** * Restore the state of `Document` between tests. * @publicApi */ export function cleanupDocument(): void { if (savedDocument) { (global as any).document = savedDocument; (global as any).window = undefined; savedDocument = undefined; } if (savedNode) { (global as any).Node = savedNode; savedNode = undefined; } if (savedRequestAnimationFrame) { (global as any).requestAnimationFrame = savedRequestAnimationFrame; savedRequestAnimationFrame = undefined; } } if (typeof beforeEach == 'function') beforeEach(ensureDocument); if (typeof afterEach == 'function') afterEach(cleanupDocument); if (typeof afterEach === 'function') afterEach(resetJitOptions);
{ "end_byte": 6116, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/private/testing/src/utils.ts" }
angular/packages/platform-browser-dynamic/PACKAGE.md_0_87
Supports JIT compilation and execution of Angular apps on different supported browsers.
{ "end_byte": 87, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/PACKAGE.md" }
angular/packages/platform-browser-dynamic/BUILD.bazel_0_1773
load("//tools:defaults.bzl", "api_golden_test_npm_package", "generate_api_docs", "ng_module", "ng_package") package(default_visibility = ["//visibility:public"]) ng_module( name = "platform-browser-dynamic", package_name = "@angular/platform-browser-dynamic", srcs = glob( [ "*.ts", "src/**/*.ts", ], ), deps = [ "//packages:types", "//packages/common", "//packages/compiler", "//packages/core", "//packages/platform-browser", ], ) ng_package( name = "npm_package", srcs = [ "package.json", ], tags = [ "release-with-framework", ], # Do not add more to this list. # Dependencies on the full npm_package cause long re-builds. visibility = [ "//adev:__pkg__", "//integration:__subpackages__", "//modules/ssr-benchmarks:__subpackages__", "//packages/compiler-cli/integrationtest:__pkg__", ], deps = [ ":platform-browser-dynamic", "//packages/platform-browser-dynamic/testing", ], ) api_golden_test_npm_package( name = "platform-browser-dynamic_api", data = [ ":npm_package", "//goldens:public-api", ], golden_dir = "angular/goldens/public-api/platform-browser-dynamic", npm_package = "angular/packages/platform-browser-dynamic/npm_package", ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", "src/**/*.ts", ]) + ["PACKAGE.md"], ) generate_api_docs( name = "platform-browser_dynamic_docs", srcs = [ ":files_for_docgen", "//packages:common_files_and_deps_for_docs", ], entry_point = ":index.ts", module_name = "@angular/platform-browser-dynamic", )
{ "end_byte": 1773, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/BUILD.bazel" }
angular/packages/platform-browser-dynamic/index.ts_0_481
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // This file is not used to build this module. It is only used during editing // by the TypeScript language service and during build for verification. `ngc` // replaces this file with production index.ts when it rewrites private symbol // names. export * from './public_api';
{ "end_byte": 481, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/index.ts" }
angular/packages/platform-browser-dynamic/public_api.ts_0_415
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * @module * @description * Entry point for all public APIs of this package. */ export * from './src/platform-browser-dynamic'; // This file only reexports content of the `src` folder. Keep it that way.
{ "end_byte": 415, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/public_api.ts" }
angular/packages/platform-browser-dynamic/test/metadata_overrider_spec.ts_0_5806
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ɵMetadataOverrider as MetadataOverrider} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; interface SomeMetadataType { plainProp?: string; getterProp?: string; arrayProp?: any[]; } interface OtherMetadataType extends SomeMetadataType { otherPlainProp?: string; } class SomeMetadata implements SomeMetadataType { plainProp: string; private _getterProp: string; arrayProp: any[]; constructor(options: SomeMetadataType) { this.plainProp = options.plainProp!; this._getterProp = options.getterProp!; this.arrayProp = options.arrayProp!; Object.defineProperty(this, 'getterProp', { enumerable: true, // getters are non-enumerable by default in es2015 get: () => this._getterProp, }); } } class OtherMetadata extends SomeMetadata implements OtherMetadataType { otherPlainProp: string; constructor(options: OtherMetadataType) { super({ plainProp: options.plainProp, getterProp: options.getterProp, arrayProp: options.arrayProp, }); this.otherPlainProp = options.otherPlainProp!; } } describe('metadata overrider', () => { let overrider: MetadataOverrider; beforeEach(() => { overrider = new MetadataOverrider(); }); it('should return a new instance with the same values', () => { const oldInstance = new SomeMetadata({plainProp: 'somePlainProp', getterProp: 'someInput'}); const newInstance = overrider.overrideMetadata(SomeMetadata, oldInstance, {}); expect(newInstance).not.toBe(oldInstance); expect(newInstance).toBeInstanceOf(SomeMetadata); expect(newInstance).toEqual(oldInstance); }); it('should set individual properties and keep others', () => { const oldInstance = new SomeMetadata({ plainProp: 'somePlainProp', getterProp: 'someGetterProp', }); const newInstance = overrider.overrideMetadata(SomeMetadata, oldInstance, { set: {plainProp: 'newPlainProp'}, }); expect(newInstance).toEqual( new SomeMetadata({plainProp: 'newPlainProp', getterProp: 'someGetterProp'}), ); }); describe('add properties', () => { it('should replace non array values', () => { const oldInstance = new SomeMetadata({ plainProp: 'somePlainProp', getterProp: 'someGetterProp', }); const newInstance = overrider.overrideMetadata(SomeMetadata, oldInstance, { add: {plainProp: 'newPlainProp'}, }); expect(newInstance).toEqual( new SomeMetadata({plainProp: 'newPlainProp', getterProp: 'someGetterProp'}), ); }); it('should add to array values', () => { const oldInstance = new SomeMetadata({arrayProp: ['a']}); const newInstance = overrider.overrideMetadata(SomeMetadata, oldInstance, { add: {arrayProp: ['b']}, }); expect(newInstance).toEqual(new SomeMetadata({arrayProp: ['a', 'b']})); }); }); describe('remove', () => { it('should set values to undefined if their value matches', () => { const oldInstance = new SomeMetadata({ plainProp: 'somePlainProp', getterProp: 'someGetterProp', }); const newInstance = overrider.overrideMetadata(SomeMetadata, oldInstance, { remove: {plainProp: 'somePlainProp'}, }); expect(newInstance).toEqual( new SomeMetadata({plainProp: undefined, getterProp: 'someGetterProp'}), ); }); it('should leave values if their value does not match', () => { const oldInstance = new SomeMetadata({ plainProp: 'somePlainProp', getterProp: 'someGetterProp', }); const newInstance = overrider.overrideMetadata(SomeMetadata, oldInstance, { remove: {plainProp: 'newPlainProp'}, }); expect(newInstance).toEqual( new SomeMetadata({plainProp: 'somePlainProp', getterProp: 'someGetterProp'}), ); }); it('should remove a value from an array', () => { const oldInstance = new SomeMetadata({ arrayProp: ['a', 'b', 'c'], getterProp: 'someGetterProp', }); const newInstance = overrider.overrideMetadata(SomeMetadata, oldInstance, { remove: {arrayProp: ['a', 'c']}, }); expect(newInstance).toEqual( new SomeMetadata({arrayProp: ['b'], getterProp: 'someGetterProp'}), ); }); it('should support types as values', () => { class Class1 {} class Class2 {} class Class3 {} const instance1 = new SomeMetadata({arrayProp: [Class1, Class2, Class3]}); const instance2 = overrider.overrideMetadata(SomeMetadata, instance1, { remove: {arrayProp: [Class1]}, }); expect(instance2).toEqual(new SomeMetadata({arrayProp: [Class2, Class3]})); const instance3 = overrider.overrideMetadata(SomeMetadata, instance2, { remove: {arrayProp: [Class3]}, }); expect(instance3).toEqual(new SomeMetadata({arrayProp: [Class2]})); }); }); describe('subclasses', () => { it('should set individual properties and keep others', () => { const oldInstance = new OtherMetadata({ plainProp: 'somePlainProp', getterProp: 'someGetterProp', otherPlainProp: 'newOtherProp', }); const newInstance = overrider.overrideMetadata(OtherMetadata, oldInstance, { set: {plainProp: 'newPlainProp'}, }); expect(newInstance).toEqual( new OtherMetadata({ plainProp: 'newPlainProp', getterProp: 'someGetterProp', otherPlainProp: 'newOtherProp', }), ); }); }); });
{ "end_byte": 5806, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/test/metadata_overrider_spec.ts" }
angular/packages/platform-browser-dynamic/test/testing_public_browser_spec.ts_0_4611
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ResourceLoader} from '@angular/compiler'; import {Compiler, Component, NgModule} from '@angular/core'; import {fakeAsync, inject, TestBed, tick, waitForAsync} from '@angular/core/testing'; import {ResourceLoaderImpl} from '@angular/platform-browser-dynamic/src/resource_loader/resource_loader_impl'; // Components for the tests. class FancyService { value: string = 'real value'; getAsyncValue() { return Promise.resolve('async value'); } getTimeoutValue() { return new Promise((resolve, reject) => { setTimeout(() => { resolve('timeout value'); }, 10); }); } } // Tests for angular/testing bundle specific to the browser environment. // For general tests, see test/testing/testing_public_spec.ts. if (isBrowser) { describe('test APIs for the browser', () => { describe('using the async helper', () => { let actuallyDone: boolean; beforeEach(() => { actuallyDone = false; }); afterEach(() => { expect(actuallyDone).toEqual(true); }); it('should run async tests with ResourceLoaders', waitForAsync(() => { const resourceLoader = new ResourceLoaderImpl(); resourceLoader .get('/base/angular/packages/platform-browser/test/static_assets/test.html') .then(() => { actuallyDone = true; }); }), 10000); // Long timeout here because this test makes an actual ResourceLoader. }); describe('using the test injector with the inject helper', () => { describe('setting up Providers', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{provide: FancyService, useValue: new FancyService()}], }); }); it('provides a real ResourceLoader instance', inject( [ResourceLoader], (resourceLoader: ResourceLoader) => { expect(resourceLoader instanceof ResourceLoaderImpl).toBeTruthy(); }, )); it('should allow the use of fakeAsync', fakeAsync( inject([FancyService], (service: FancyService) => { let value: string | undefined; service.getAsyncValue().then(function (val: string) { value = val; }); tick(); expect(value).toEqual('async value'); }), )); }); }); describe('Compiler', () => { it('should return NgModule id when asked', () => { @NgModule({ id: 'test-module', }) class TestModule {} TestBed.configureTestingModule({ imports: [TestModule], }); const compiler = TestBed.inject(Compiler); expect(compiler.getModuleId(TestModule)).toBe('test-module'); }); }); describe('errors', () => { describe('should fail when an ResourceLoader fails', () => { // TODO(alxhub): figure out why this is failing on saucelabs xit('should fail with an error from a promise', async () => { @Component({ selector: 'bad-template-comp', templateUrl: 'non-existent.html', standalone: false, }) class BadTemplateUrl {} TestBed.configureTestingModule({declarations: [BadTemplateUrl]}); await expectAsync(TestBed.compileComponents()).toBeRejectedWith( 'Failed to load non-existent.html', ); }, 10000); }); }); describe('TestBed createComponent', function () { // TODO(alxhub): disable while we figure out how this should work xit('should allow an external templateUrl', waitForAsync(() => { @Component({ selector: 'external-template-comp', templateUrl: '/base/angular/packages/platform-browser/test/static_assets/test.html', standalone: false, }) class ExternalTemplateComp {} TestBed.configureTestingModule({declarations: [ExternalTemplateComp]}); TestBed.compileComponents().then(() => { const componentFixture = TestBed.createComponent(ExternalTemplateComp); componentFixture.detectChanges(); expect(componentFixture.nativeElement.textContent).toEqual('from external template'); }); }), 10000); // Long timeout here because this test makes an actual ResourceLoader // request, and is slow on Edge. }); }); }
{ "end_byte": 4611, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/test/testing_public_browser_spec.ts" }
angular/packages/platform-browser-dynamic/test/BUILD.bazel_0_1155
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/platform-browser-dynamic/index.mjs", deps = ["//packages/platform-browser-dynamic"], ) ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), deps = [ "//packages:types", "//packages/compiler", "//packages/core", "//packages/core/testing", "//packages/platform-browser-dynamic", "//packages/platform-browser-dynamic/testing", "//packages/platform-browser/testing", "//packages/private/testing", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":test_lib", ], ) karma_web_test_suite( name = "test_web", static_files = [ "//packages/platform-browser/test:static_assets/test.html", "//packages/platform-browser/test:browser/static_assets/200.html", ], deps = [ ":test_lib", ], )
{ "end_byte": 1155, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/test/BUILD.bazel" }
angular/packages/platform-browser-dynamic/test/resource_loader/resource_loader_impl_spec.ts_0_1097
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ResourceLoaderImpl} from '@angular/platform-browser-dynamic/src/resource_loader/resource_loader_impl'; if (isBrowser) { describe('ResourceLoaderImpl', () => { let resourceLoader: ResourceLoaderImpl; const url200 = '/base/angular/packages/platform-browser/test/browser/static_assets/200.html'; const url404 = '/bad/path/404.html'; beforeEach(() => { resourceLoader = new ResourceLoaderImpl(); }); it('should resolve the Promise with the file content on success', (done) => { resourceLoader.get(url200).then((text) => { expect(text.trim()).toEqual('<p>hey</p>'); done(); }); }, 10000); it('should reject the Promise on failure', (done) => { resourceLoader.get(url404).catch((e) => { expect(e).toEqual(`Failed to load ${url404}`); done(); return null; }); }, 10000); }); }
{ "end_byte": 1097, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/test/resource_loader/resource_loader_impl_spec.ts" }
angular/packages/platform-browser-dynamic/testing/PACKAGE.md_0_73
Supplies a testing module for the Angular JIT platform-browser subsystem.
{ "end_byte": 73, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/testing/PACKAGE.md" }
angular/packages/platform-browser-dynamic/testing/BUILD.bazel_0_889
load("//tools:defaults.bzl", "generate_api_docs", "ng_module") package(default_visibility = ["//visibility:public"]) exports_files(["package.json"]) ng_module( name = "testing", srcs = glob(["**/*.ts"]), deps = [ "//packages/common", "//packages/compiler", "//packages/core", "//packages/core/testing", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/platform-browser/testing", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", "src/**/*.ts", ]) + ["PACKAGE.md"], ) generate_api_docs( name = "platform-browser_dynamic_testing_docs", srcs = [ ":files_for_docgen", "//packages:common_files_and_deps_for_docs", ], entry_point = ":index.ts", module_name = "@angular/platform-browser-dynamic/testing", )
{ "end_byte": 889, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/testing/BUILD.bazel" }
angular/packages/platform-browser-dynamic/testing/index.ts_0_481
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // This file is not used to build this module. It is only used during editing // by the TypeScript language service and during build for verification. `ngc` // replaces this file with production index.ts when it rewrites private symbol // names. export * from './public_api';
{ "end_byte": 481, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/testing/index.ts" }
angular/packages/platform-browser-dynamic/testing/public_api.ts_0_322
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * @module * @description * Entry point for all public APIs of this package. */ export * from './src/testing';
{ "end_byte": 322, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/testing/public_api.ts" }
angular/packages/platform-browser-dynamic/testing/src/private_export_testing.ts_0_414
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export {DOMTestComponentRenderer as ɵDOMTestComponentRenderer} from './dom_test_component_renderer'; export {platformCoreDynamicTesting as ɵplatformCoreDynamicTesting} from './platform_core_dynamic_testing';
{ "end_byte": 414, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/testing/src/private_export_testing.ts" }
angular/packages/platform-browser-dynamic/testing/src/testing.ts_0_1193
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {createPlatformFactory, NgModule, PlatformRef, StaticProvider} from '@angular/core'; import {TestComponentRenderer} from '@angular/core/testing'; import {ɵINTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS as INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS} from '@angular/platform-browser-dynamic'; import {BrowserTestingModule} from '@angular/platform-browser/testing'; import {DOMTestComponentRenderer} from './dom_test_component_renderer'; import {platformCoreDynamicTesting} from './platform_core_dynamic_testing'; export * from './private_export_testing'; /** * @publicApi */ export const platformBrowserDynamicTesting = createPlatformFactory( platformCoreDynamicTesting, 'browserDynamicTesting', INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, ); /** * NgModule for testing. * * @publicApi */ @NgModule({ exports: [BrowserTestingModule], providers: [{provide: TestComponentRenderer, useClass: DOMTestComponentRenderer}], }) export class BrowserDynamicTestingModule {}
{ "end_byte": 1193, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/testing/src/testing.ts" }
angular/packages/platform-browser-dynamic/testing/src/platform_core_dynamic_testing.ts_0_577
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {createPlatformFactory, PlatformRef} from '@angular/core'; import {ɵplatformCoreDynamic as platformCoreDynamic} from '@angular/platform-browser-dynamic'; /** * Platform for dynamic tests * * @publicApi */ export const platformCoreDynamicTesting: (extraProviders?: any[]) => PlatformRef = createPlatformFactory(platformCoreDynamic, 'coreDynamicTesting', []);
{ "end_byte": 577, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/testing/src/platform_core_dynamic_testing.ts" }
angular/packages/platform-browser-dynamic/testing/src/dom_test_component_renderer.ts_0_1560
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {DOCUMENT, ɵgetDOM as getDOM} from '@angular/common'; import {Inject, Injectable} from '@angular/core'; import {TestComponentRenderer} from '@angular/core/testing'; /** * A DOM based implementation of the TestComponentRenderer. */ @Injectable() export class DOMTestComponentRenderer extends TestComponentRenderer { constructor(@Inject(DOCUMENT) private _doc: any) { super(); } override insertRootElement(rootElId: string) { this.removeAllRootElementsImpl(); const rootElement = getDOM().getDefaultDocument().createElement('div'); rootElement.setAttribute('id', rootElId); this._doc.body.appendChild(rootElement); } override removeAllRootElements() { // Check whether the `DOCUMENT` instance retrieved from DI contains // the necessary function to complete the cleanup. In tests that don't // interact with DOM, the `DOCUMENT` might be mocked and some functions // might be missing. For such tests, DOM cleanup is not required and // we skip the logic if there are missing functions. if (typeof this._doc.querySelectorAll === 'function') { this.removeAllRootElementsImpl(); } } private removeAllRootElementsImpl() { const oldRoots = this._doc.querySelectorAll('[id^=root]'); for (let i = 0; i < oldRoots.length; i++) { getDOM().remove(oldRoots[i]); } } }
{ "end_byte": 1560, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/testing/src/dom_test_component_renderer.ts" }
angular/packages/platform-browser-dynamic/src/platform_core_dynamic.ts_0_694
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { COMPILER_OPTIONS, CompilerFactory, createPlatformFactory, platformCore, } from '@angular/core'; import {JitCompilerFactory} from './compiler_factory'; /** * A platform that included corePlatform and the compiler. * * @publicApi */ export const platformCoreDynamic = createPlatformFactory(platformCore, 'coreDynamic', [ {provide: COMPILER_OPTIONS, useValue: {}, multi: true}, {provide: CompilerFactory, useClass: JitCompilerFactory, deps: [COMPILER_OPTIONS]}, ]);
{ "end_byte": 694, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/src/platform_core_dynamic.ts" }
angular/packages/platform-browser-dynamic/src/compiler_factory.ts_0_2263
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {CompilerConfig} from '@angular/compiler'; import { Compiler, CompilerFactory, CompilerOptions, Injector, StaticProvider, ViewEncapsulation, } from '@angular/core'; export const COMPILER_PROVIDERS = <StaticProvider[]>[ {provide: Compiler, useFactory: () => new Compiler()}, ]; /** * @publicApi * * @deprecated * Ivy JIT mode doesn't require accessing this symbol. */ export class JitCompilerFactory implements CompilerFactory { private _defaultOptions: CompilerOptions[]; /** @internal */ constructor(defaultOptions: CompilerOptions[]) { const compilerOptions: CompilerOptions = { defaultEncapsulation: ViewEncapsulation.Emulated, }; this._defaultOptions = [compilerOptions, ...defaultOptions]; } createCompiler(options: CompilerOptions[] = []): Compiler { const opts = _mergeOptions(this._defaultOptions.concat(options)); const injector = Injector.create({ providers: [ COMPILER_PROVIDERS, { provide: CompilerConfig, useFactory: () => { return new CompilerConfig({ defaultEncapsulation: opts.defaultEncapsulation, preserveWhitespaces: opts.preserveWhitespaces, }); }, deps: [], }, opts.providers!, ], }); return injector.get(Compiler); } } function _mergeOptions(optionsArr: CompilerOptions[]): CompilerOptions { return { defaultEncapsulation: _lastDefined(optionsArr.map((options) => options.defaultEncapsulation)), providers: _mergeArrays(optionsArr.map((options) => options.providers!)), preserveWhitespaces: _lastDefined(optionsArr.map((options) => options.preserveWhitespaces)), }; } function _lastDefined<T>(args: T[]): T | undefined { for (let i = args.length - 1; i >= 0; i--) { if (args[i] !== undefined) { return args[i]; } } return undefined; } function _mergeArrays(parts: any[][]): any[] { const result: any[] = []; parts.forEach((part) => part && result.push(...part)); return result; }
{ "end_byte": 2263, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/src/compiler_factory.ts" }
angular/packages/platform-browser-dynamic/src/private_export.ts_0_421
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export {platformCoreDynamic as ɵplatformCoreDynamic} from './platform_core_dynamic'; export {INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS as ɵINTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS} from './platform_providers';
{ "end_byte": 421, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/src/private_export.ts" }
angular/packages/platform-browser-dynamic/src/platform_providers.ts_0_959
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ɵPLATFORM_BROWSER_ID as PLATFORM_BROWSER_ID} from '@angular/common'; import {ResourceLoader} from '@angular/compiler'; import {COMPILER_OPTIONS, PLATFORM_ID, StaticProvider} from '@angular/core'; import {ɵINTERNAL_BROWSER_PLATFORM_PROVIDERS as INTERNAL_BROWSER_PLATFORM_PROVIDERS} from '@angular/platform-browser'; import {ResourceLoaderImpl} from './resource_loader/resource_loader_impl'; /** * @publicApi */ export const INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS: StaticProvider[] = [ INTERNAL_BROWSER_PLATFORM_PROVIDERS, { provide: COMPILER_OPTIONS, useValue: {providers: [{provide: ResourceLoader, useClass: ResourceLoaderImpl, deps: []}]}, multi: true, }, {provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}, ];
{ "end_byte": 959, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/src/platform_providers.ts" }
angular/packages/platform-browser-dynamic/src/version.ts_0_435
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * @module * @description * Entry point for all public APIs of the platform-browser-dynamic package. */ import {Version} from '@angular/core'; /** * @publicApi */ export const VERSION = new Version('0.0.0-PLACEHOLDER');
{ "end_byte": 435, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/src/version.ts" }
angular/packages/platform-browser-dynamic/src/platform-browser-dynamic.ts_0_703
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {createPlatformFactory} from '@angular/core'; import {platformCoreDynamic} from './platform_core_dynamic'; import {INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS} from './platform_providers'; export * from './private_export'; export {VERSION} from './version'; export {JitCompilerFactory} from './compiler_factory'; /** * @publicApi */ export const platformBrowserDynamic = createPlatformFactory( platformCoreDynamic, 'browserDynamic', INTERNAL_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, );
{ "end_byte": 703, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/src/platform-browser-dynamic.ts" }
angular/packages/platform-browser-dynamic/src/resource_loader/resource_loader_impl.ts_0_1336
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ResourceLoader} from '@angular/compiler'; import {Injectable} from '@angular/core'; @Injectable() export class ResourceLoaderImpl extends ResourceLoader { override get(url: string): Promise<string> { let resolve: (result: any) => void; let reject: (error: any) => void; const promise = new Promise<string>((res, rej) => { resolve = res; reject = rej; }); const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'text'; xhr.onload = function () { const response = xhr.response; let status = xhr.status; // fix status code when it is 0 (0 status is undocumented). // Occurs when accessing file resources or on Android 4.1 stock browser // while retrieving files from application cache. if (status === 0) { status = response ? 200 : 0; } if (200 <= status && status <= 300) { resolve(response); } else { reject(`Failed to load ${url}`); } }; xhr.onerror = function () { reject(`Failed to load ${url}`); }; xhr.send(); return promise; } }
{ "end_byte": 1336, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser-dynamic/src/resource_loader/resource_loader_impl.ts" }
angular/packages/examples/index.html_0_406
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Angular Examples</title> <base href="/" /> <!-- Prevent the browser from requesting any favicon. This could throw off the console output checks. --> <link rel="icon" href="data:," /> </head> <body> <example-app>Loading...</example-app> <script src="/app_bundle.js"></script> </body> </html>
{ "end_byte": 406, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/examples/index.html" }