_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/adev/src/app/core/services/theme-manager.service.ts_0_3240
/*! * @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, isPlatformBrowser} from '@angular/common'; import {Injectable, PLATFORM_ID, inject, signal} from '@angular/core'; import {LOCAL_STORAGE} from '@angular/docs'; import {Subject} from 'rxjs'; // Keep these constants in sync with the code in index.html export const THEME_PREFERENCE_LOCAL_STORAGE_KEY = 'themePreference'; export const DARK_MODE_CLASS_NAME = 'docs-dark-mode'; export const LIGHT_MODE_CLASS_NAME = 'docs-light-mode'; export const PREFERS_COLOR_SCHEME_DARK = '(prefers-color-scheme: dark)'; export type Theme = 'dark' | 'light' | 'auto'; @Injectable({ providedIn: 'root', }) export class ThemeManager { private readonly document = inject(DOCUMENT); private readonly localStorage = inject(LOCAL_STORAGE); private readonly platformId = inject(PLATFORM_ID); readonly theme = signal<Theme | null>(this.getThemeFromLocalStorageValue()); // Zoneless - it's required to notify that theme was changed. It could be removed when signal-based components will be available. readonly themeChanged$ = new Subject<void>(); constructor() { if (!isPlatformBrowser(this.platformId)) { return; } this.loadThemePreference(); this.watchPreferredColorScheme(); } setTheme(theme: Theme): void { this.theme.set(theme); this.setThemeInLocalStorage(); this.setThemeBodyClasses(theme === 'auto' ? preferredScheme() : theme); } // 1. Read theme preferences stored in localStorage // 2. In case when there are no stored user preferences, then read them from device preferences. private loadThemePreference(): void { const savedUserPreference = this.getThemeFromLocalStorageValue(); const useTheme = savedUserPreference ?? 'auto'; this.theme.set(useTheme); this.setThemeBodyClasses(useTheme === 'auto' ? preferredScheme() : useTheme); } // Set theme classes on the body element private setThemeBodyClasses(theme: 'dark' | 'light'): void { const documentClassList = this.document.documentElement.classList; if (theme === 'dark') { documentClassList.add(DARK_MODE_CLASS_NAME); documentClassList.remove(LIGHT_MODE_CLASS_NAME); } else { documentClassList.add(LIGHT_MODE_CLASS_NAME); documentClassList.remove(DARK_MODE_CLASS_NAME); } this.themeChanged$.next(); } private getThemeFromLocalStorageValue(): Theme | null { const theme = this.localStorage?.getItem(THEME_PREFERENCE_LOCAL_STORAGE_KEY) as Theme | null; return theme ?? null; } private setThemeInLocalStorage(): void { if (this.theme()) { this.localStorage?.setItem(THEME_PREFERENCE_LOCAL_STORAGE_KEY, this.theme()!); } } private watchPreferredColorScheme() { window.matchMedia(PREFERS_COLOR_SCHEME_DARK).addEventListener('change', (event) => { const preferredScheme = event.matches ? 'dark' : 'light'; this.setThemeBodyClasses(preferredScheme); }); } } function preferredScheme(): 'dark' | 'light' { return window.matchMedia(PREFERS_COLOR_SCHEME_DARK).matches ? 'dark' : 'light'; }
{ "end_byte": 3240, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/theme-manager.service.ts" }
angular/adev/src/app/core/services/theme-manager.service.spec.ts_0_1879
/*! * @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 {TestBed} from '@angular/core/testing'; import {ThemeManager} from './theme-manager.service'; import {LOCAL_STORAGE} from '@angular/docs'; describe('ThemeManager', () => { let service: ThemeManager; let localStorageSpy: jasmine.SpyObj<Storage>; beforeEach(() => { localStorageSpy = jasmine.createSpyObj<Storage>('localStorage', ['getItem', 'setItem']); localStorageSpy.getItem.and.returnValue(null); localStorageSpy.setItem.and.returnValue(); TestBed.configureTestingModule({ providers: [ { provide: LOCAL_STORAGE, useValue: localStorageSpy, }, ], }); }); it('should set theme based on device preferences (auto) when user did not set theme manually', () => { localStorageSpy.getItem.and.returnValue(null); service = TestBed.inject(ThemeManager); expect(service.theme()).toBe('auto'); }); it('should set theme based on stored user preferences (dark) when user already set theme manually', () => { localStorageSpy.getItem.and.returnValue('dark'); service = TestBed.inject(ThemeManager); expect(service.theme()).toBe('dark'); }); it('should set theme based on stored user preferences (light) when user already set theme manually', () => { localStorageSpy.getItem.and.returnValue('light'); service = TestBed.inject(ThemeManager); expect(service.theme()).toBe('light'); }); it('should set theme based on stored user preferences (auto) when user already set theme manually', () => { localStorageSpy.getItem.and.returnValue('auto'); service = TestBed.inject(ThemeManager); expect(service.theme()).toBe('auto'); }); });
{ "end_byte": 1879, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/theme-manager.service.spec.ts" }
angular/adev/src/app/core/services/example-content-loader.service.ts_0_532
/*! * @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, Type, inject} from '@angular/core'; import {PREVIEWS_COMPONENTS} from '@angular/docs'; @Injectable() export class ExampleContentLoader { private readonly previewsComponents = inject(PREVIEWS_COMPONENTS); loadPreview(id: string): Promise<Type<unknown>> { return this.previewsComponents[id](); } }
{ "end_byte": 532, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/example-content-loader.service.ts" }
angular/adev/src/app/core/services/header.service.spec.ts_0_863
/*! * @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 {TestBed} from '@angular/core/testing'; import {HeaderService} from './header.service'; describe('HeaderService', () => { let service: HeaderService; beforeEach(() => { service = TestBed.inject(HeaderService); }); it('setCanonical', () => { // setCanonical assumes there is a preexisting element const linkEl = document.createElement('link'); linkEl.setAttribute('rel', 'canonical'); document.querySelector('head')?.appendChild(linkEl); service.setCanonical('/some/link'); expect(document.querySelector('link[rel=canonical]')!.getAttribute('href')).toBe( 'https://angular.dev/some/link', ); }); });
{ "end_byte": 863, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/header.service.spec.ts" }
angular/adev/src/app/core/services/header.service.ts_0_983
import {DOCUMENT} from '@angular/common'; import {Injectable, inject} from '@angular/core'; const ANGULAR_DEV = 'https://angular.dev'; /** * Information about the deployment of this application. */ @Injectable({providedIn: 'root'}) export class HeaderService { private readonly document = inject(DOCUMENT); /** * Sets the canonical link in the header. * It supposes the header link is already present in the index.html * * The function behave invariably and will always point to angular.dev, * no matter if it's a specific version build */ setCanonical(absolutePath: string): void { const pathWithoutFragment = this.normalizePath(absolutePath).split('#')[0]; const fullPath = `${ANGULAR_DEV}/${pathWithoutFragment}`; this.document.querySelector('link[rel=canonical]')?.setAttribute('href', fullPath); } private normalizePath(path: string): string { if (path[0] === '/') { return path.substring(1); } return path; } }
{ "end_byte": 983, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/header.service.ts" }
angular/adev/src/app/core/services/content-loader.service.ts_0_1402
/*! * @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 {HttpClient} from '@angular/common/http'; import {Injectable, inject} from '@angular/core'; import {DocContent, DocsContentLoader} from '@angular/docs'; import {Router} from '@angular/router'; import {firstValueFrom, of} from 'rxjs'; import {catchError, map} from 'rxjs/operators'; @Injectable() export class ContentLoader implements DocsContentLoader { private readonly cache = new Map<string, Promise<DocContent | undefined>>(); private readonly httpClient = inject(HttpClient); private readonly router = inject(Router); async getContent(path: string): Promise<DocContent | undefined> { // If the path does not end with a file extension, add `.md.html` as the default if (!path.match(/\.\w+$/)) { path += '.md.html'; } if (!this.cache.has(path)) { try { this.cache.set( path, firstValueFrom( this.httpClient .get(`assets/content/${path}`, { responseType: 'text', }) .pipe(map((contents) => ({contents, id: path}))), ), ); } catch { this.router.navigateByUrl('/404'); } } return this.cache.get(path)!; } }
{ "end_byte": 1402, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/content-loader.service.ts" }
angular/adev/src/app/core/services/version-manager.service.ts_0_3821
/*! * @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, computed, inject, signal} from '@angular/core'; import {VERSIONS_CONFIG} from '../constants/versions'; import {WINDOW} from '@angular/docs'; import {CURRENT_MAJOR_VERSION} from '../providers/current-version'; export interface Version { displayName: string; version: VersionMode; url: string; } export type VersionMode = 'stable' | 'deprecated' | 'rc' | 'next' | number; export const INITIAL_ADEV_DOCS_VERSION = 18; export const VERSION_PLACEHOLDER = '{{version}}'; export const MODE_PLACEHOLDER = '{{prefix}}'; @Injectable({ providedIn: 'root', }) export class VersionManager { private readonly currentMajorVersion = inject(CURRENT_MAJOR_VERSION); private readonly window = inject(WINDOW); // Note: We can assume that if the URL starts with v{{version}}, it is documentation for previous versions of Angular. // Based on URL we can indicate as well if it's rc or next Docs version. private get currentVersionMode(): VersionMode { const hostname = this.window.location.hostname; if (hostname.startsWith('v')) return 'deprecated'; if (hostname.startsWith('rc')) return 'rc'; if (hostname.startsWith('next')) return 'next'; return 'stable'; } versions = signal<Version[]>([ ...this.getRecentVersions(), ...this.getAdevVersions(), ...this.getAioVersions(), ]); currentDocsVersion = computed(() => { return this.versions().find( (version) => version.version.toString() === this.currentVersionMode, ); }); // List of Angular Docs versions which includes current version, next and rc. private getRecentVersions(): Version[] { return [ { url: this.getAdevDocsUrl('next'), displayName: `next`, version: 'next', }, // Note: 'rc' should not be visible for now // { // url: this.getAdevDocsUrl('rc'), // displayName: `rc`, // version: 'rc', // }, { url: 'https://angular.dev/', displayName: this.getVersion(this.currentMajorVersion), version: this.currentVersionMode, }, ]; } // List of Angular Docs versions hosted on angular.dev domain. private getAdevVersions(): Version[] { const adevVersions: Version[] = []; for ( let version = this.currentMajorVersion - 1; version >= INITIAL_ADEV_DOCS_VERSION; version-- ) { adevVersions.push({ url: this.getAdevDocsUrl(version), displayName: this.getVersion(version), version: 'deprecated', }); } return adevVersions; } // List of Angular Docs versions hosted on angular.io domain. private getAioVersions(): Version[] { return VERSIONS_CONFIG.aioVersions.map((item) => this.mapToVersion(item as Pick<Version, 'url' | 'version'>), ); } private mapToVersion(value: Pick<Version, 'url' | 'version'>): Version { return { ...value, displayName: this.getVersion(value.version), }; } private getVersion(versionMode: VersionMode): string { if (versionMode === 'stable' || versionMode === 'deprecated') { return `v${this.currentMajorVersion}`; } if (Number.isInteger(versionMode)) { return `v${versionMode}`; } return versionMode.toString(); } private getAdevDocsUrl(version: VersionMode): string { const docsUrlPrefix = isNaN(Number(version)) ? `` : 'v'; return VERSIONS_CONFIG.aDevVersionsLinkPattern .replace(MODE_PLACEHOLDER, docsUrlPrefix) .replace( VERSION_PLACEHOLDER, `${version.toString() === 'stable' ? '' : `${version.toString()}.`}`, ); } }
{ "end_byte": 3821, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/version-manager.service.ts" }
angular/adev/src/app/core/services/a-dev-title-strategy.ts_0_1522
/*! * @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 {NavigationItem} from '@angular/docs'; import {Title} from '@angular/platform-browser'; import {ActivatedRouteSnapshot, RouterStateSnapshot, TitleStrategy} from '@angular/router'; export const ROUTE_TITLE_PROPERTY = 'label'; export const ROUTE_PARENT_PROPERTY = 'parent'; export const TITLE_SUFFIX = 'Angular'; export const TITLE_SEPARATOR = ' • '; export const DEFAULT_PAGE_TITLE = 'Overview'; @Injectable({providedIn: 'root'}) export class ADevTitleStrategy extends TitleStrategy { constructor(private readonly title: Title) { super(); } override updateTitle(routerState: RouterStateSnapshot) { const title = this.buildTitle(routerState); if (title !== undefined) { this.title.setTitle(title); } } override buildTitle(snapshot: RouterStateSnapshot): string { let route: ActivatedRouteSnapshot = snapshot.root; while (route.firstChild) { route = route.firstChild; } const data = route.data as NavigationItem; const routeTitle = data.label ?? ''; const prefix = routeTitle.startsWith(DEFAULT_PAGE_TITLE) && data.parent ? `${data.parent.label}${TITLE_SEPARATOR}` : ''; return !!routeTitle ? `${prefix}${routeTitle}${TITLE_SEPARATOR}${TITLE_SUFFIX}` : TITLE_SUFFIX; } }
{ "end_byte": 1522, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/a-dev-title-strategy.ts" }
angular/adev/src/app/core/services/inject-async.ts_0_2558
/*! * @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 { DestroyRef, ENVIRONMENT_INITIALIZER, EnvironmentInjector, Injectable, Injector, Provider, ProviderToken, Type, createEnvironmentInjector, inject, } from '@angular/core'; /** * inject a service asynchronously * * @param: injector. If the injector is a NodeInjector the loaded module will be destroyed alonside its injector */ export async function injectAsync<T>( injector: Injector, providerLoader: () => Promise<ProviderToken<T>>, ): Promise<T> { const injectImpl = injector.get(InjectAsyncImpl); return injectImpl.get(injector, providerLoader); } @Injectable({providedIn: 'root'}) class InjectAsyncImpl<T> { private overrides = new WeakMap(); // no need to cleanup override<T>(type: Type<T>, mock: Type<unknown>) { this.overrides.set(type, mock); } async get(injector: Injector, providerLoader: () => Promise<ProviderToken<T>>): Promise<T> { const type = await providerLoader(); // Check if we have overrides, O(1), low overhead if (this.overrides.has(type)) { const override = this.overrides.get(type); return new override(); } if (!(injector instanceof EnvironmentInjector)) { // this is the DestroyRef of the component const destroyRef = injector.get(DestroyRef); // This is the parent injector of the injector we're creating const environmentInjector = injector.get(EnvironmentInjector); // Creating an environment injector to destroy it afterwards const newInjector = createEnvironmentInjector([type as Provider], environmentInjector); // Destroy the injector to trigger DestroyRef.onDestroy on our service destroyRef.onDestroy(() => { newInjector.destroy(); }); // We want to create the new instance of our service with our new injector injector = newInjector; } return injector.get(type)!; } } /** * Helper function to mock the lazy loaded module in `injectAsync` * * @usage * TestBed.configureTestingModule({ * providers: [ * mockAsyncProvider(SandboxService, fakeSandboxService) * ] * }); */ export function mockAsyncProvider<T>(type: Type<T>, mock: Type<unknown>) { return [ { provide: ENVIRONMENT_INITIALIZER, multi: true, useValue: () => { inject(InjectAsyncImpl).override(type, mock); }, }, ]; }
{ "end_byte": 2558, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/inject-async.ts" }
angular/adev/src/app/core/services/version-manager.service.spec.ts_0_1820
/*! * @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 {TestBed} from '@angular/core/testing'; import {INITIAL_ADEV_DOCS_VERSION, VersionManager} from './version-manager.service'; import {WINDOW} from '@angular/docs'; import {CURRENT_MAJOR_VERSION} from '../providers/current-version'; describe('VersionManager', () => { const fakeWindow = {location: {hostname: 'angular.dev'}}; const fakeCurrentMajorVersion = 19; let service: VersionManager; beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: WINDOW, useValue: fakeWindow, }, { provide: CURRENT_MAJOR_VERSION, useValue: fakeCurrentMajorVersion, }, ], }); service = TestBed.inject(VersionManager); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should contain correct number of Angular Docs versions', () => { // Note: From v2 to v17 (inclusive), there were no v3 const expectedAioDocsVersionsCount = 15; // Last stable version and next const expectedRecentDocsVersionCount = 2; const expectedPreviousAdevVersionsCount = fakeCurrentMajorVersion - INITIAL_ADEV_DOCS_VERSION; expect(service['getAioVersions']().length).toBe(expectedAioDocsVersionsCount); expect(service['getRecentVersions']().length).toBe(expectedRecentDocsVersionCount); expect(service['getAdevVersions']().length).toBe(expectedPreviousAdevVersionsCount); expect(service.versions().length).toBe( expectedAioDocsVersionsCount + expectedRecentDocsVersionCount + expectedPreviousAdevVersionsCount, ); }); });
{ "end_byte": 1820, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/version-manager.service.spec.ts" }
angular/adev/src/app/core/services/a-dev-title-strategy.spec.ts_0_2854
/*! * @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 {TestBed} from '@angular/core/testing'; import {TITLE_SUFFIX, ADevTitleStrategy, DEFAULT_PAGE_TITLE} from './a-dev-title-strategy'; import {Router, provideRouter} from '@angular/router'; import {Title} from '@angular/platform-browser'; import {Component} from '@angular/core'; @Component({}) class FakeComponent {} describe('ADevTitleStrategy', () => { let service: ADevTitleStrategy; let router: Router; let title: Title; const routes = [ {path: 'first', data: {label: 'First'}, component: FakeComponent}, {path: 'second', component: FakeComponent}, { path: 'third', data: {label: 'Third'}, component: FakeComponent, children: [{path: 'child', data: {label: 'Child'}, component: FakeComponent}], }, { path: 'fourth', data: {label: 'Fourth'}, component: FakeComponent, children: [ { path: 'child', data: {label: 'Overview', parent: {label: 'Fourth'}}, component: FakeComponent, }, ], }, ]; beforeEach(() => { TestBed.configureTestingModule({ providers: [provideRouter(routes)], }); service = TestBed.inject(ADevTitleStrategy); router = TestBed.inject(Router); title = TestBed.inject(Title); }); it('should be created', () => { expect(service).toBeTruthy(); }); it(`should set '${TITLE_SUFFIX}' when route doesn't have defined label`, async () => { spyOn(title, 'setTitle'); await router.navigateByUrl('/second'); service.updateTitle(router.routerState.snapshot); expect(title.setTitle).toHaveBeenCalledOnceWith(TITLE_SUFFIX); }); it(`should set 'Third - ${TITLE_SUFFIX}' when route has defined label equal to 'Third'`, async () => { spyOn(title, 'setTitle'); await router.navigateByUrl('/third'); service.updateTitle(router.routerState.snapshot); expect(title.setTitle).toHaveBeenCalledOnceWith('Third • Angular'); }); it(`shouldn't take label from the parent route when current route label is not equal to ${DEFAULT_PAGE_TITLE}`, async () => { spyOn(title, 'setTitle'); await router.navigateByUrl('/third/child'); service.updateTitle(router.routerState.snapshot); expect(title.setTitle).toHaveBeenCalledOnceWith('Child • Angular'); }); it(`should take label from the parent route when current route label is equal to ${DEFAULT_PAGE_TITLE}`, async () => { spyOn(title, 'setTitle'); await router.navigateByUrl('/fourth/child'); service.updateTitle(router.routerState.snapshot); expect(title.setTitle).toHaveBeenCalledOnceWith('Fourth • Overview • Angular'); }); });
{ "end_byte": 2854, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/a-dev-title-strategy.spec.ts" }
angular/adev/src/app/core/services/content-loader.service.spec.ts_0_716
/*! * @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 {TestBed} from '@angular/core/testing'; import {ContentLoader} from './content-loader.service'; import {HttpClientTestingModule} from '@angular/common/http/testing'; describe('ContentLoader', () => { let service: ContentLoader; beforeEach(() => { TestBed.configureTestingModule({ providers: [ContentLoader], imports: [HttpClientTestingModule], }); service = TestBed.inject(ContentLoader); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
{ "end_byte": 716, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/content-loader.service.spec.ts" }
angular/adev/src/app/core/services/errors-handling/error-handler.ts_0_1948
/*! * @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, isPlatformServer} from '@angular/common'; import {ErrorHandler, PLATFORM_ID, inject} from '@angular/core'; import {MatSnackBar} from '@angular/material/snack-bar'; import {AnalyticsService} from '../analytics/analytics.service'; import {ErrorSnackBar, ErrorSnackBarData} from './error-snack-bar'; export class CustomErrorHandler implements ErrorHandler { snackBar = inject(MatSnackBar); document = inject(DOCUMENT); isServer = isPlatformServer(inject(PLATFORM_ID)); analyticsService = inject(AnalyticsService); get isOnline(): boolean { if (this.isServer) return false; const win = this.document.defaultView; return win?.navigator.onLine ?? true; } handleError(error: any) { if (typeof error.message === 'string') { // Just looking at the first line of the error message (ignoring the call stack part), // which should contain a pattern that we are looking for. const firstLine = error.message.split('\n')[0]; if (this.isOnline && firstLine?.match(/chunk-(.*?)\.js/)) { // Trying to load a chunk that doesn't exist anymore // Users should reload the app. this.openErrorSnackBar(); this.analyticsService.reportError('Chunk loading error'); } } // We still want to log every error console.error(error); } openErrorSnackBar(): void { this.snackBar .openFromComponent(ErrorSnackBar, { panelClass: 'docs-invert-mode', data: { message: `Our docs have been updated, reload the page to see the latest.`, actionText: `Reload`, } satisfies ErrorSnackBarData, }) .onAction() .subscribe(() => { this.document.location.reload(); }); } }
{ "end_byte": 1948, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/errors-handling/error-handler.ts" }
angular/adev/src/app/core/services/errors-handling/error-snack-bar.ts_0_1257
/*! * @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 {ChangeDetectionStrategy, Component, Inject, inject} from '@angular/core'; import {MAT_SNACK_BAR_DATA, MatSnackBarAction, MatSnackBarRef} from '@angular/material/snack-bar'; export interface ErrorSnackBarData { message: string; actionText?: string; } @Component({ selector: 'error-snack-bar', changeDetection: ChangeDetectionStrategy.OnPush, template: ` {{ message }} <button class="docs-primary-btn" type="button" matSnackBarAction [attr.text]="actionText" (click)="snackBarRef.dismissWithAction()" > {{ actionText }} </button> `, standalone: true, imports: [MatSnackBarAction], styles: `:host { display: flex; align-items: center; button { margin-left: 16px }}`, }) export class ErrorSnackBar { protected message: string; protected actionText?: string; constructor(protected snackBarRef: MatSnackBarRef<ErrorSnackBar>) { const data = inject(MAT_SNACK_BAR_DATA) as ErrorSnackBarData; this.message = data.message; this.actionText = data.actionText; } }
{ "end_byte": 1257, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/errors-handling/error-snack-bar.ts" }
angular/adev/src/app/core/services/analytics/analytics-format-error.ts_0_1597
/*! * @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 */ /** * Formats an `ErrorEvent` to a human-readable string that can * be sent to Google Analytics. */ export function formatErrorEventForAnalytics(event: ErrorEvent): string { const {message, filename, colno, lineno, error} = event; if (error instanceof Error) { return formatErrorForAnalytics(error); } return `${stripErrorMessagePrefix(message)}\n${filename}:` + `${lineno || '?'}:${colno || '?'}`; } /** * Formats an `Error` to a human-readable string that can be sent * to Google Analytics. */ export function formatErrorForAnalytics(error: Error): string { let stack = '<no-stack>'; if (error.stack) { stack = stripErrorMessagePrefix(error.stack) // strip the message from the stack trace, if present .replace(error.message + '\n', '') // strip leading spaces .replace(/^ +/gm, '') // strip all leading "at " for each frame .replace(/^at /gm, '') // replace long urls with just the last segment: `filename:line:column` .replace(/(?: \(|@)http.+\/([^/)]+)\)?(?:\n|$)/gm, '@$1\n') // replace "eval code" in Edge .replace(/ *\(eval code(:\d+:\d+)\)(?:\n|$)/gm, '@???$1\n'); } return `${error.message}\n${stack}`; } /** Strips the error message prefix from a message or stack trace. */ function stripErrorMessagePrefix(input: string): string { return input.replace(/^(Uncaught )?Error: /, ''); }
{ "end_byte": 1597, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/analytics/analytics-format-error.ts" }
angular/adev/src/app/core/services/analytics/reporting-error-handler.ts_0_2057
/*! * @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 {ErrorHandler, Injectable, VERSION} from '@angular/core'; import {formatErrorForAnalytics} from './analytics-format-error'; import {AnalyticsService} from './analytics.service'; /** * Extend the default error handling to report errors to an external service - e.g Google Analytics. * * Errors outside the Angular application may also be handled by `window.onerror`. */ @Injectable() export class ReportingErrorHandler extends ErrorHandler { constructor(private _analytics: AnalyticsService) { super(); } /** * Send error info to Google Analytics, in addition to the default handling. * * @param error Information about the error. */ override handleError(error: any) { const versionedError = this.prefixErrorWithVersion(error); try { super.handleError(versionedError); } catch (e) { this.reportError(e); } this.reportError(versionedError); } private prefixErrorWithVersion<T>(error: T): T { const prefix = `[v${VERSION.full}] `; if (error instanceof Error) { const oldMessage = error.message; const oldStack = error.stack; error.message = prefix + oldMessage; error.stack = oldStack?.replace(oldMessage, error.message); } else if (typeof error === 'string') { error = (prefix + error) as unknown as T; } // If it is a different type, omit the version to avoid altering the original `error` object. return error; } private reportError(error: unknown) { if (error instanceof Error) { this._analytics.reportError(formatErrorForAnalytics(error)); } else { if (typeof error === 'object') { try { error = JSON.stringify(error); } catch { // Ignore the error and just let it be stringified. } } this._analytics.reportError(`${error}`); } } }
{ "end_byte": 2057, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/analytics/reporting-error-handler.ts" }
angular/adev/src/app/core/services/analytics/analytics.service.spec.ts_0_2750
/*! * @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 {ENVIRONMENT, WINDOW, LOCAL_STORAGE} from '@angular/docs'; import {AnalyticsService} from './analytics.service'; import {MockLocalStorage} from '@angular/docs'; describe('AnalyticsService', () => { let service: AnalyticsService; let injector: Injector; let gtagSpy: jasmine.Spy; let gtagAppendNodeSpy: jasmine.Spy; let windowOnErrorHandler: (event: ErrorEvent) => void; let mockWindow: any; let mockLocalStorage = new MockLocalStorage(); beforeEach(() => { gtagSpy = jasmine.createSpy('gtag'); gtagAppendNodeSpy = jasmine.createSpy('gtag.js script head attach'); mockWindow = { name: 'Some name', document: { head: {appendChild: gtagAppendNodeSpy}, createElement: (tag: string) => document.createElement(tag), querySelector: (_gtagIdSelector: string) => null, }, addEventListener: (_name: string, handler: typeof windowOnErrorHandler) => (windowOnErrorHandler = handler), }; injector = Injector.create({ providers: [ {provide: ENVIRONMENT, useValue: {}}, {provide: AnalyticsService, deps: [WINDOW]}, {provide: WINDOW, useFactory: () => mockWindow, deps: []}, {provide: LOCAL_STORAGE, useValue: mockLocalStorage}, ], }); service = injector.get(AnalyticsService); // The `gtag` function is attached to the `Window`, so we can spy on it // after the service has been initialized. gtagSpy = spyOn(mockWindow, 'gtag'); }); describe('error reporting', () => { it('should subscribe to window uncaught errors and report them', () => { spyOn(service, 'reportError'); windowOnErrorHandler( new ErrorEvent('error', { error: new Error('Test Error'), }), ); expect(service.reportError).toHaveBeenCalledTimes(1); expect(service.reportError).toHaveBeenCalledWith( jasmine.stringContaining('Test Error\n'), true, ); }); it('should report errors to analytics by dispatching `gtag` and `ga` events', () => { gtagSpy.calls.reset(); windowOnErrorHandler( new ErrorEvent('error', { error: new Error('Test Error'), }), ); expect(gtagSpy).toHaveBeenCalledTimes(1); expect(gtagSpy).toHaveBeenCalledWith( 'event', 'exception', jasmine.objectContaining({ description: jasmine.stringContaining('Test Error\n'), fatal: true, }), ); }); }); });
{ "end_byte": 2750, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/analytics/analytics.service.spec.ts" }
angular/adev/src/app/core/services/analytics/analytics.service.ts_0_3678
/*! * @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} from '@angular/core'; import {WINDOW, ENVIRONMENT, LOCAL_STORAGE, STORAGE_KEY, setCookieConsent} from '@angular/docs'; import {formatErrorEventForAnalytics} from './analytics-format-error'; /** Extension of `Window` with potential Google Analytics fields. */ interface WindowWithAnalytics extends Window { dataLayer?: any[]; gtag?(...args: any[]): void; } @Injectable({providedIn: 'root'}) /** * Google Analytics Service - captures app behaviors and sends them to Google Analytics. * * Associates data wi`th properties determined from the environment configurations: * - Data is uploaded to our main Google Analytics 4+ property. */ export class AnalyticsService { private environment = inject(ENVIRONMENT); private window: WindowWithAnalytics = inject(WINDOW); private readonly localStorage = inject(LOCAL_STORAGE); constructor() { this._installGlobalSiteTag(); this._installWindowErrorHandler(); } reportError(description: string, fatal = true) { // Limit descriptions to maximum of 150 characters. // See: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#exd. description = description.substring(0, 150); this._gtag('event', 'exception', {description, fatal}); } sendEvent(name: string, parameters: Record<string, string | boolean | number>) { this._gtag('event', name, parameters); } private _gtag(...args: any[]) { if (this.window.gtag) { this.window.gtag(...args); } } private _installGlobalSiteTag() { const window = this.window; const url = `https://www.googletagmanager.com/gtag/js?id=${this.environment.googleAnalyticsId}`; // Note: This cannot be an arrow function as `gtag.js` expects an actual `Arguments` // instance with e.g. `callee` to be set. Do not attempt to change this and keep this // as much as possible in sync with the tracking code snippet suggested by the Google // Analytics 4 web UI under `Data Streams`. window.dataLayer = this.window.dataLayer || []; window.gtag = function () { window.dataLayer?.push(arguments); }; // Cookie banner consent initial state // This code is modified in the @angular/docs package in the cookie-popup component. // Docs: https://developers.google.com/tag-platform/security/guides/consent if (this.localStorage) { if (this.localStorage.getItem(STORAGE_KEY) === 'true') { setCookieConsent('granted'); } else { setCookieConsent('denied'); } } else { // In case localStorage is not available, we default to denying cookies. setCookieConsent('denied'); } window.gtag('js', new Date()); // Configure properties before loading the script. This is necessary to avoid // loading multiple instances of the gtag JS scripts. window.gtag('config', this.environment.googleAnalyticsId); // Only add the element if `gtag` is not loaded yet. It might already // be inlined into the `index.html` via SSR. if (window.document.querySelector('#gtag-script') === null) { const el = window.document.createElement('script'); el.async = true; el.src = url as string; el.id = 'gtag-script'; window.document.head.appendChild(el); } } private _installWindowErrorHandler() { this.window.addEventListener('error', (event) => this.reportError(formatErrorEventForAnalytics(event), true), ); } }
{ "end_byte": 3678, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/analytics/analytics.service.ts" }
angular/adev/src/app/core/services/analytics/reporting-error-handler.spec.ts_0_4284
/*! * @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 {ErrorHandler, Injector, VERSION} from '@angular/core'; import {ReportingErrorHandler} from './reporting-error-handler'; import {AnalyticsService} from './analytics.service'; describe('ReportingErrorHandler service', () => { let handler: ReportingErrorHandler; let superHandler: jasmine.Spy; let reportErrorSpy: jasmine.Spy; beforeEach(() => { superHandler = spyOn(ErrorHandler.prototype, 'handleError'); reportErrorSpy = jasmine.createSpy('analytics report error'); const injector = Injector.create({ providers: [ {provide: AnalyticsService, useValue: {reportError: reportErrorSpy}}, {provide: ErrorHandler, useClass: ReportingErrorHandler, deps: [AnalyticsService]}, ], }); handler = injector.get(ErrorHandler) as unknown as ReportingErrorHandler; }); describe('handleError', () => { it('should call the super class handleError', () => { const error = new Error(); handler.handleError(error); expect(superHandler).toHaveBeenCalledWith(error); }); it('should cope with the super handler throwing an error', () => { const error = new Error('initial error'); superHandler.and.throwError('super handler error'); handler.handleError(error); expect(reportErrorSpy).toHaveBeenCalledTimes(2); // Error from super handler is reported first expect(reportErrorSpy.calls.argsFor(0)[0]).toEqual( jasmine.stringContaining('super handler error\n'), ); // Then error from initial exception expect(reportErrorSpy.calls.argsFor(1)[0]).toEqual( jasmine.stringContaining(`[v${VERSION.full}] initial error\n`), ); }); it('should augment an error object with version info', () => { const originalMessage = 'this is an error message'; const error = new Error(originalMessage); expect(error.message).toBe(originalMessage); // NOTE: // Intentionally not checking `error.stack` here, because accessing it causes the property to // be computed and may affect the observed behavior of `handleError()`. handler.handleError(error); expect(error.message).toBe(`[v${VERSION.full}] ${originalMessage}`); if (error.stack) { const expected = `Error: [v${VERSION.full}] ${originalMessage}`; const actual = error.stack.split('\n', 1)[0]; expect(actual.startsWith(expected)) .withContext(`Expected '${actual}' to start with '${expected}'.`) .toBeTrue(); } }); it('should send an error object to analytics', () => { const error = new Error('this is an error message'); handler.handleError(error); expect(reportErrorSpy).toHaveBeenCalledWith( jasmine.stringContaining('this is an error message\n'), ); }); it('should send a non-error object to analytics', () => { const error = {reason: 'this is an error message'}; handler.handleError(error); expect(reportErrorSpy).toHaveBeenCalledWith(JSON.stringify(error)); }); it('should send a non-error object with circular references to analytics', () => { const error = { reason: 'this is an error message', get self() { return this; }, toString() { return `{reason: ${this.reason}}`; }, }; handler.handleError(error); expect(reportErrorSpy).toHaveBeenCalledWith('{reason: this is an error message}'); }); it('should send an error string to analytics (prefixed with version info)', () => { const error = 'this is an error message'; handler.handleError(error); expect(reportErrorSpy).toHaveBeenCalledWith(`[v${VERSION.full}] ${error}`); }); it('should send a non-object, non-string error stringified to analytics', () => { handler.handleError(404); handler.handleError(false); handler.handleError(null); handler.handleError(undefined); expect(reportErrorSpy.calls.allArgs()).toEqual([['404'], ['false'], ['null'], ['undefined']]); }); }); });
{ "end_byte": 4284, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/core/services/analytics/reporting-error-handler.spec.ts" }
angular/adev/src/app/features/home/home.component.ts_0_4256
/*! * @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, isPlatformBrowser} from '@angular/common'; import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Injector, OnDestroy, OnInit, PLATFORM_ID, ViewChild, inject, } from '@angular/core'; import {WINDOW, shouldReduceMotion, isIos} from '@angular/docs'; import {ActivatedRoute, RouterLink} from '@angular/router'; import {injectAsync} from '../../core/services/inject-async'; import {CodeEditorComponent} from './components/home-editor.component'; import {HEADER_CLASS_NAME} from './home-animation-constants'; import type {HomeAnimation} from './services/home-animation.service'; export const TUTORIALS_HOMEPAGE_DIRECTORY = 'homepage'; @Component({ standalone: true, selector: 'adev-home', imports: [RouterLink, CodeEditorComponent], templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export default class Home implements OnInit, AfterViewInit, OnDestroy { @ViewChild('home') home!: ElementRef<HTMLDivElement>; private readonly document = inject(DOCUMENT); private readonly injector = inject(Injector); private readonly platformId = inject(PLATFORM_ID); private readonly window = inject(WINDOW); private readonly activatedRoute = inject(ActivatedRoute); protected readonly tutorialFiles = TUTORIALS_HOMEPAGE_DIRECTORY; protected readonly isUwu = 'uwu' in this.activatedRoute.snapshot.queryParams; private element!: HTMLDivElement; private homeAnimation?: HomeAnimation; private intersectionObserver: IntersectionObserver | undefined; ctaLink = 'tutorials/learn-angular'; ctaIosLink = 'overview'; ngOnInit(): void { if (isIos) { this.ctaLink = this.ctaIosLink; } } ngAfterViewInit() { this.element = this.home.nativeElement; if (isPlatformBrowser(this.platformId)) { // Always scroll to top on home page (even for navigating back) this.window.scrollTo({top: 0, left: 0, behavior: 'instant'}); // Create a single intersection observer used for disabling the animation // at the end of the page, and to load the embedded editor. this.initIntersectionObserver(); if (this.isWebGLAvailable() && !shouldReduceMotion() && !this.isUwu) { this.loadHomeAnimation(); } } } ngOnDestroy(): void { if (isPlatformBrowser(this.platformId)) { // Stop observing and disconnect this.intersectionObserver?.disconnect(); if (this.homeAnimation) { this.homeAnimation.destroy(); } } } private initIntersectionObserver(): void { const header = this.document.querySelector('.adev-top'); const footer = this.document.querySelector('footer'); this.intersectionObserver = new IntersectionObserver((entries) => { const headerEntry = entries.find((entry) => entry.target === header); const footerEntry = entries.find((entry) => entry.target === footer); // CTA and arrow animation this.headerTop(headerEntry); // Disable animation at end of page if (this.homeAnimation) { this.homeAnimation.disableEnd(footerEntry); } }); // Start observing this.intersectionObserver.observe(header!); this.intersectionObserver.observe(footer!); } private headerTop(headerEntry: IntersectionObserverEntry | undefined): void { if (!headerEntry) { return; } if (headerEntry.isIntersecting) { this.element.classList.add(HEADER_CLASS_NAME); } else { this.element.classList.remove(HEADER_CLASS_NAME); } } private async loadHomeAnimation() { this.homeAnimation = await injectAsync(this.injector, () => import('./services/home-animation.service').then((c) => c.HomeAnimation), ); await this.homeAnimation.init(this.element); } private isWebGLAvailable() { try { return !!document .createElement('canvas') .getContext('webgl', {failIfMajorPerformanceCaveat: true}); } catch (e) { return false; } } }
{ "end_byte": 4256, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/home.component.ts" }
angular/adev/src/app/features/home/home.component.html_0_854
<div class="adev-home" #home> <div class="adev-top"> <div class="adev-top-content"> <!-- Banner(s) can be edited here! --> <a href="https://goo.gle/angular-v18" class="adev-banner" target="_blank"> <h1 tabindex="-1">Angular v18 is now available!</h1> <p class="adev-banner-cta">Read about our newest release</p> </a> </div> </div> <div class="adev-canvas"></div> <div class="adev-logo"> <div class="adev-logo-wordmark"> @if (!isUwu) { <svg class="angular-logo" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 982 241" style="width: max(calc(700 * min(100vw, 2560px) / 1470), 350px); height: auto;" > <g clip-path="url(#wordmark_a)"> <path fill="url(#wordmark_b)" d="
{ "end_byte": 854, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/home.component.html" }
angular/adev/src/app/features/home/home.component.html_0_3154
M388.676 191.625h30.849L363.31 31.828h-35.758l-56.215 159.797h30.848l13.174-39.356h60.061l13.256 39.356Zm-65.461-62.675 21.602-64.311h1.227l21.603 64.311h-44.432Zm126.831-7.527v70.202h-28.23V71.839h27.002v20.374h1.392c2.782-6.71 7.2-12.028 13.255-15.956 6.056-3.927 13.584-5.89 22.503-5.89 8.264 0 15.465 1.8 21.684 5.318 6.137 3.518 10.964 8.673 14.319 15.382 3.437 6.71 5.074 14.81 4.992 24.383v76.175h-28.23v-71.92c0-8.019-2.046-14.237-6.219-18.819-4.173-4.5-9.819-6.791-17.102-6.791-4.91 0-9.328 1.063-13.174 3.272-3.846 2.128-6.792 5.237-9.001 9.328-2.046 4.009-3.191 8.918-3.191 14.728ZM589.233 239c-10.147 0-18.82-1.391-26.103-4.091-7.282-2.7-13.092-6.382-17.511-10.964-4.418-4.582-7.528-9.655-9.164-15.219l25.448-6.136c1.145 2.372 2.782 4.663 4.991 6.954 2.209 2.291 5.155 4.255 8.837 5.81 3.683 1.554 8.428 2.291 14.074 2.291 8.019 0 14.647-1.964 19.884-5.81 5.237-3.845 7.856-10.227 7.856-19.064v-22.665h-1.391c-1.473 2.946-3.601 5.892-6.383 9.001-2.782 3.109-6.464 5.645-10.965 7.691-4.582 2.046-10.228 3.109-17.101 3.109-9.165 0-17.511-2.209-25.039-6.545-7.446-4.337-13.42-10.883-17.757-19.474-4.418-8.673-6.628-19.473-6.628-32.565 0-13.091 2.21-24.301 6.628-33.383 4.419-9.082 10.311-15.955 17.839-20.7 7.528-4.746 15.874-7.037 25.038-7.037 7.038 0 12.847 1.145 17.348 3.518 4.582 2.373 8.182 5.236 10.883 8.51 2.7 3.272 4.746 6.382 6.137 9.327h1.554v-19.8h27.821v121.749c0 10.228-2.454 18.737-7.364 25.447-4.91 6.709-11.538 11.7-20.048 15.055-8.509 3.355-18.165 4.991-28.884 4.991Zm.245-71.266c5.974 0 11.047-1.473 15.302-4.337 4.173-2.945 7.446-7.118 9.573-12.519 2.21-5.482 3.274-12.027 3.274-19.637 0-7.609-1.064-14.155-3.274-19.8-2.127-5.646-5.318-10.064-9.491-13.255-4.174-3.11-9.329-4.746-15.384-4.746s-11.537 1.636-15.792 4.91c-4.173 3.272-7.365 7.772-9.492 13.418-2.128 5.727-3.191 12.191-3.191 19.392 0 7.2 1.063 13.746 3.273 19.228 2.127 5.482 5.318 9.736 9.573 12.764 4.174 3.027 9.41 4.582 15.629 4.582Zm141.56-26.51V71.839h28.23v119.786h-27.412v-21.273h-1.227c-2.7 6.709-7.119 12.191-13.338 16.446-6.137 4.255-13.747 6.382-22.748 6.382-7.855 0-14.81-1.718-20.783-5.237-5.974-3.518-10.72-8.591-14.075-15.382-3.355-6.709-5.073-14.891-5.073-24.464V71.839h28.312v71.921c0 7.609 2.046 13.664 6.219 18.083 4.173 4.5 9.655 6.709 16.365 6.709 4.173 0 8.183-.982 12.111-3.028 3.927-2.045 7.118-5.072 9.655-9.082 2.537-4.091 3.764-9.164 3.764-15.218Zm65.707-109.395v159.796h-28.23V31.828h28.23Zm44.841 162.169c-7.61 0-14.402-1.391-20.457-4.091-6.055-2.7-10.883-6.791-14.32-12.109-3.518-5.319-5.237-11.946-5.237-19.801 0-6.791 1.228-12.355 3.765-16.773 2.536-4.419 5.891-7.937 10.228-10.637 4.337-2.619 9.164-4.664 14.647-6.055 5.4-1.391 11.046-2.373 16.856-3.027 7.037-.737 12.683-1.391 17.102-1.964 4.337-.573 7.528-1.555 9.574-2.782 1.963-1.309 3.027-3.273 3.027-5.973v-.491c0-5.891-1.718-10.391-5.237-13.664-3.518-3.191-8.51-4.828-15.056-4.828-6.955 0-12.356 1.473-16.447 4.5-4.01 3.028-6.71 6.546-8.183 10.719l-26.348-3.764c2.046-7.282 5.483-13.336 10.31-18.328 4.746-4.909 10.638-8.59 17.511-11.045 6.955-2.455 14.565-3.682 22.912-3.682 5.809 0 11.537.654 17.265 2.045s10.965 3.6 15.711 6.71c4.746 3.109 8.51 7.282 11.455 12.6 2.864
{ "end_byte": 3154, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/home.component.html" }
angular/adev/src/app/features/home/home.component.html_3155_5294
.045 7.118-5.072 9.655-9.082 2.537-4.091 3.764-9.164 3.764-15.218Zm65.707-109.395v159.796h-28.23V31.828h28.23Zm44.841 162.169c-7.61 0-14.402-1.391-20.457-4.091-6.055-2.7-10.883-6.791-14.32-12.109-3.518-5.319-5.237-11.946-5.237-19.801 0-6.791 1.228-12.355 3.765-16.773 2.536-4.419 5.891-7.937 10.228-10.637 4.337-2.619 9.164-4.664 14.647-6.055 5.4-1.391 11.046-2.373 16.856-3.027 7.037-.737 12.683-1.391 17.102-1.964 4.337-.573 7.528-1.555 9.574-2.782 1.963-1.309 3.027-3.273 3.027-5.973v-.491c0-5.891-1.718-10.391-5.237-13.664-3.518-3.191-8.51-4.828-15.056-4.828-6.955 0-12.356 1.473-16.447 4.5-4.01 3.028-6.71 6.546-8.183 10.719l-26.348-3.764c2.046-7.282 5.483-13.336 10.31-18.328 4.746-4.909 10.638-8.59 17.511-11.045 6.955-2.455 14.565-3.682 22.912-3.682 5.809 0 11.537.654 17.265 2.045s10.965 3.6 15.711 6.71c4.746 3.109 8.51 7.282 11.455 12.6 2.864 5.318 4.337 11.946 4.337 19.883v80.184h-27.166v-16.446h-.9c-1.719 3.355-4.091 6.464-7.201 9.328-3.109 2.864-6.955 5.237-11.619 6.955-4.828 1.718-10.229 2.536-16.529 2.536Zm7.364-20.701c5.646 0 10.556-1.145 14.729-3.354 4.173-2.291 7.364-5.237 9.655-9.001 2.292-3.763 3.355-7.854 3.355-12.273v-14.155c-.9.737-2.373 1.391-4.5 2.046-2.128.654-4.419 1.145-7.037 1.636-2.619.491-5.155.9-7.692 1.227-2.537.328-4.746.655-6.628.901-4.173.572-8.019 1.472-11.292 2.781-3.355 1.31-5.973 3.11-7.855 5.401-1.964 2.291-2.864 5.318-2.864 8.918 0 5.237 1.882 9.164 5.728 11.782 3.682 2.782 8.51 4.091 14.401 4.091Zm64.643 18.328V71.839h27.412v19.965h1.227c2.21-6.955 5.974-12.274 11.292-16.038 5.319-3.763 11.456-5.645 18.329-5.645 1.555 0 3.355.082 5.237.163 1.964.164 3.601.328 4.91.573v25.938c-1.227-.41-3.109-.819-5.646-1.146a58.815 58.815 0 0 0-7.446-.49c-5.155 0-9.738 1.145-13.829 3.354-4.091 2.209-7.282 5.236-9.655 9.164-2.373 3.927-3.519 8.427-3.519 13.5v70.448h-28.312ZM222.077 39.192l-8.019 125.923L137.387 0l84.69 39.192Zm-53.105 162.825-57.933 33.056-57.934-33.056 11.783-28.556h92.301l11.783 28.556ZM111.039 62.675l30.357 73.803H80.681l30.358-73.803ZM7.937 165.115 0 39.192 84.69 0 7.937 165.115Z" /> <path fill="url(#wordmark_c)" d="
{ "end_byte": 5294, "start_byte": 3155, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/home.component.html" }
angular/adev/src/app/features/home/home.component.html_0_3154
M388.676 191.625h30.849L363.31 31.828h-35.758l-56.215 159.797h30.848l13.174-39.356h60.061l13.256 39.356Zm-65.461-62.675 21.602-64.311h1.227l21.603 64.311h-44.432Zm126.831-7.527v70.202h-28.23V71.839h27.002v20.374h1.392c2.782-6.71 7.2-12.028 13.255-15.956 6.056-3.927 13.584-5.89 22.503-5.89 8.264 0 15.465 1.8 21.684 5.318 6.137 3.518 10.964 8.673 14.319 15.382 3.437 6.71 5.074 14.81 4.992 24.383v76.175h-28.23v-71.92c0-8.019-2.046-14.237-6.219-18.819-4.173-4.5-9.819-6.791-17.102-6.791-4.91 0-9.328 1.063-13.174 3.272-3.846 2.128-6.792 5.237-9.001 9.328-2.046 4.009-3.191 8.918-3.191 14.728ZM589.233 239c-10.147 0-18.82-1.391-26.103-4.091-7.282-2.7-13.092-6.382-17.511-10.964-4.418-4.582-7.528-9.655-9.164-15.219l25.448-6.136c1.145 2.372 2.782 4.663 4.991 6.954 2.209 2.291 5.155 4.255 8.837 5.81 3.683 1.554 8.428 2.291 14.074 2.291 8.019 0 14.647-1.964 19.884-5.81 5.237-3.845 7.856-10.227 7.856-19.064v-22.665h-1.391c-1.473 2.946-3.601 5.892-6.383 9.001-2.782 3.109-6.464 5.645-10.965 7.691-4.582 2.046-10.228 3.109-17.101 3.109-9.165 0-17.511-2.209-25.039-6.545-7.446-4.337-13.42-10.883-17.757-19.474-4.418-8.673-6.628-19.473-6.628-32.565 0-13.091 2.21-24.301 6.628-33.383 4.419-9.082 10.311-15.955 17.839-20.7 7.528-4.746 15.874-7.037 25.038-7.037 7.038 0 12.847 1.145 17.348 3.518 4.582 2.373 8.182 5.236 10.883 8.51 2.7 3.272 4.746 6.382 6.137 9.327h1.554v-19.8h27.821v121.749c0 10.228-2.454 18.737-7.364 25.447-4.91 6.709-11.538 11.7-20.048 15.055-8.509 3.355-18.165 4.991-28.884 4.991Zm.245-71.266c5.974 0 11.047-1.473 15.302-4.337 4.173-2.945 7.446-7.118 9.573-12.519 2.21-5.482 3.274-12.027 3.274-19.637 0-7.609-1.064-14.155-3.274-19.8-2.127-5.646-5.318-10.064-9.491-13.255-4.174-3.11-9.329-4.746-15.384-4.746s-11.537 1.636-15.792 4.91c-4.173 3.272-7.365 7.772-9.492 13.418-2.128 5.727-3.191 12.191-3.191 19.392 0 7.2 1.063 13.746 3.273 19.228 2.127 5.482 5.318 9.736 9.573 12.764 4.174 3.027 9.41 4.582 15.629 4.582Zm141.56-26.51V71.839h28.23v119.786h-27.412v-21.273h-1.227c-2.7 6.709-7.119 12.191-13.338 16.446-6.137 4.255-13.747 6.382-22.748 6.382-7.855 0-14.81-1.718-20.783-5.237-5.974-3.518-10.72-8.591-14.075-15.382-3.355-6.709-5.073-14.891-5.073-24.464V71.839h28.312v71.921c0 7.609 2.046 13.664 6.219 18.083 4.173 4.5 9.655 6.709 16.365 6.709 4.173 0 8.183-.982 12.111-3.028 3.927-2.045 7.118-5.072 9.655-9.082 2.537-4.091 3.764-9.164 3.764-15.218Zm65.707-109.395v159.796h-28.23V31.828h28.23Zm44.841 162.169c-7.61 0-14.402-1.391-20.457-4.091-6.055-2.7-10.883-6.791-14.32-12.109-3.518-5.319-5.237-11.946-5.237-19.801 0-6.791 1.228-12.355 3.765-16.773 2.536-4.419 5.891-7.937 10.228-10.637 4.337-2.619 9.164-4.664 14.647-6.055 5.4-1.391 11.046-2.373 16.856-3.027 7.037-.737 12.683-1.391 17.102-1.964 4.337-.573 7.528-1.555 9.574-2.782 1.963-1.309 3.027-3.273 3.027-5.973v-.491c0-5.891-1.718-10.391-5.237-13.664-3.518-3.191-8.51-4.828-15.056-4.828-6.955 0-12.356 1.473-16.447 4.5-4.01 3.028-6.71 6.546-8.183 10.719l-26.348-3.764c2.046-7.282 5.483-13.336 10.31-18.328 4.746-4.909 10.638-8.59 17.511-11.045 6.955-2.455 14.565-3.682 22.912-3.682 5.809 0 11.537.654 17.265 2.045s10.965 3.6 15.711 6.71c4.746 3.109 8.51 7.282 11.455 12.6 2.864
{ "end_byte": 3154, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/home.component.html" }
angular/adev/src/app/features/home/home.component.html_3155_4350
5.318 4.337 11.946 4.337 19.883v80.184h-27.166v-16.446h-.9c-1.719 3.355-4.091 6.464-7.201 9.328-3.109 2.864-6.955 5.237-11.619 6.955-4.828 1.718-10.229 2.536-16.529 2.536Zm7.364-20.701c5.646 0 10.556-1.145 14.729-3.354 4.173-2.291 7.364-5.237 9.655-9.001 2.292-3.763 3.355-7.854 3.355-12.273v-14.155c-.9.737-2.373 1.391-4.5 2.046-2.128.654-4.419 1.145-7.037 1.636-2.619.491-5.155.9-7.692 1.227-2.537.328-4.746.655-6.628.901-4.173.572-8.019 1.472-11.292 2.781-3.355 1.31-5.973 3.11-7.855 5.401-1.964 2.291-2.864 5.318-2.864 8.918 0 5.237 1.882 9.164 5.728 11.782 3.682 2.782 8.51 4.091 14.401 4.091Zm64.643 18.328V71.839h27.412v19.965h1.227c2.21-6.955 5.974-12.274 11.292-16.038 5.319-3.763 11.456-5.645 18.329-5.645 1.555 0 3.355.082 5.237.163 1.964.164 3.601.328 4.91.573v25.938c-1.227-.41-3.109-.819-5.646-1.146a58.815 58.815 0 0 0-7.446-.49c-5.155 0-9.738 1.145-13.829 3.354-4.091 2.209-7.282 5.236-9.655 9.164-2.373 3.927-3.519 8.427-3.519 13.5v70.448h-28.312ZM222.077 39.192l-8.019 125.923L137.387 0l84.69 39.192Zm-53.105 162.825-57.933 33.056-57.934-33.056 11.783-28.556h92.301l11.783 28.556ZM111.039 62.675l30.357 73.803H80.681l30.358-73.803ZM7.937 165.115 0 39.192 84.69 0 7.937 165.115Z
{ "end_byte": 4350, "start_byte": 3155, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/home.component.html" }
angular/adev/src/app/features/home/home.component.html_9644_13334
" /> </g> <defs> <radialGradient id="wordmark_c" cx="0" cy="0" r="1" gradientTransform="rotate(118.122 171.182 60.81) scale(205.794)" gradientUnits="userSpaceOnUse" > <stop stop-color="#FF41F8" /> <stop offset=".707" stop-color="#FF41F8" stop-opacity=".5" /> <stop offset="1" stop-color="#FF41F8" stop-opacity="0" /> </radialGradient> <linearGradient id="wordmark_b" x1="0" x2="982" y1="192" y2="192" gradientUnits="userSpaceOnUse" > <stop stop-color="#F0060B" /> <stop offset="0" stop-color="#F0070C" /> <stop offset=".526" stop-color="#CC26D5" /> <stop offset="1" stop-color="#7702FF" /> </linearGradient> <clipPath id="wordmark_a"><path fill="#fff" d="M0 0h982v239H0z" /></clipPath> </defs> </svg> } @else { <img src="assets/images/uwu.png" class="uwu-logo" alt="Angular logo" style="width: max(calc(700 * min(100vw, 2560px) / 1470), 350px); height: auto;" /> } </div> </div> <div class="adev-scale"> <div class="adev-scale-text"> <div class="adev-scale-container"> <div class="adev-scale-wrapper"> <h2>Works at any scale</h2> <p> Angular lets you start small on a well-lit path and supports you as your team and apps grow. </p> </div> </div> </div> </div> <div class="adev-lines" #lovedByMillions> <div class="adev-lines-text"> <div class="adev-lines-container"> <div class="adev-lines-wrapper"> <h2>Loved by millions</h2> <p> Join the millions of developers all over the world building with Angular in a thriving and friendly&nbsp;community. </p> </div> </div> </div> </div> <div class="adev-build" #buildForEveryone> <div class="adev-build-text"> <div class="adev-build-container"> <div class="adev-build-wrapper"> <h2> Build for everyone <div class="adev-gradient" aria-hidden="true">Build for everyone</div> </h2> <p> Rely on Angular's built-in hydration, internationalization, security, and accessibility support to build for everyone around the world. </p> </div> </div> </div> <div class="adev-build-webgl-text" aria-hidden="true"> <div class="adev-build-container"> <div class="adev-build-wrapper"> <h2>Build for everyone</h2> <p> Rely on Angular's built-in hydration, internationalization, security, and accessibility support to build for everyone around the world. </p> </div> </div> </div> </div> <div class="adev-code-editor-gradient"></div> <div class="adev-editor-scroll-container"> <div class="adev-code-editor adev-sticky-editor"> @defer (on viewport(buildForEveryone); prefetch on viewport(lovedByMillions)) { <adev-code-editor [tutorialFiles]="tutorialFiles" /> } @loading { <img alt="Code editor" /> } </div> </div> <div class="adev-arrow"></div> <a routerLink="{{ctaLink}}" class="adev-cta"> <button class="docs-primary-btn" [attr.text]="'Learn Angular'" aria-label="Learn Angular"> Learn Angular </button> </a> </div>
{ "end_byte": 13334, "start_byte": 9644, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/home.component.html" }
angular/adev/src/app/features/home/home.component.scss_0_2504
@use '@angular/docs/styles/media-queries' as mq; :host { width: 100%; // While editor is loading, display an svg of the editor .docs-dark-mode & { .adev-editor-scroll-container img { content: url('../../../assets/images/editor-dark-horizontal.svg'); @include mq.for-tablet-down { content: url('../../../assets/images/editor-dark-vertical.svg'); } } } .docs-light-mode & { .adev-editor-scroll-container img { content: url('../../../assets/images/editor-light-horizontal.svg'); @include mq.for-tablet-down { content: url('../../../assets/images/editor-light-vertical.svg'); } } } .adev-banner { display: flex; align-items: center; flex-wrap: wrap; gap: 0.5rem; z-index: 10; border: 1px solid var(--senary-contrast); background: var(--page-background); position: relative; border-radius: 0.25rem; padding: 10px; max-width: 100%; width: fit-content; box-sizing: border-box; transition: background 0.3s ease, border 0.3s ease; h1, p { display: inline; font-size: 0.875rem; margin: 0; background-image: var(--red-to-pink-to-purple-horizontal-gradient); background-clip: text; -webkit-background-clip: text; color: transparent; width: fit-content; font-weight: 500; &.adev-banner-cta { color: var(--tertiary-contrast); &::after { content: ''; position: absolute; width: 100%; transform: scaleX(0); height: 1px; bottom: -2px; left: 0; background: var(--red-to-pink-to-purple-horizontal-gradient); transform-origin: bottom right; transition: transform 0.3s ease; } } } &:hover { .adev-banner-cta { &::after { transform: scaleX(1); transform-origin: bottom left; } } } } } .adev-top { position: absolute; top: 0; @include mq.for-tablet-landscape-down { top: 6rem; } @include mq.for-phone-only { top: 4.5rem; } .adev-top-content { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; padding-top: 10px; padding-inline: var(--layout-padding); gap: 0.5rem; @include mq.for-tablet-landscape-up { padding-top: var(--layout-padding); padding-left: calc(var(--layout-padding) + var(--primary-nav-width)); } } }
{ "end_byte": 2504, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/home.component.scss" }
angular/adev/src/app/features/home/home.component.scss_2506_7894
.adev-home { img, svg { user-select: none; } h2, p { position: relative; } h2 { font-size: 4vw; font-weight: 600; white-space: nowrap; margin-top: 0; margin-bottom: 0.5em; @media screen and (max-width: 1000px) { font-size: 2rem; } } p { font-weight: 400; color: var(--quaternary-contrast); font-size: clamp(1rem, 1vw, 2rem); line-height: 1.5; width: clamp(375px, 50%, 600px); margin: 0 auto; } .adev-cta { position: fixed; left: 50%; bottom: 10%; transform: translateX(-50%); display: inline-block; padding: 7px; opacity: 0; visibility: hidden; transition: opacity 0.5s linear, visibility 0.5s linear; button { font-size: 1rem; padding: 1rem 1.75rem; &::after { font-size: 1rem; } } } .adev-arrow { position: fixed; left: 50%; bottom: 5%; transform: translateX(-50%) rotate(45deg); border: solid var(--primary-contrast); border-width: 0 2px 2px 0; display: inline-block; padding: 7px; opacity: 0; transition: opacity 0.5s linear; } .adev-canvas { position: fixed; top: 0; width: calc(100vw - 8px); height: 100vh; max-width: 2560px; margin-inline: auto; pointer-events: none; overflow: hidden; // hide canvas to prevent fouc opacity: 0; // large viewport height for canvas @supports (height: 100lvh) { height: 100lvh; } } .adev-logo, .adev-scale, .adev-lines, .adev-build { height: 130vh; overflow: hidden; @supports (height: 100lvh) { height: 130lvh; } } .adev-logo-wordmark, .adev-scale-text, .adev-lines-text, .adev-build-text, .adev-build-webgl-text { display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; top: 0; width: 100vw; height: 100vh; max-width: 2560px; margin-inline: auto; pointer-events: none; overflow: hidden; @supports (height: 100lvh) { height: 100lvh; } } .adev-build-webgl-text { display: none; visibility: hidden; position: fixed; } .adev-scale-container, .adev-lines-container, .adev-build-container { position: relative; } .adev-lines-container { &::before { content: ''; position: absolute; left: -50px; top: 0; right: -50px; bottom: -50px; background-color: var(--page-background); filter: blur(25px); } } .adev-scale-wrapper, .adev-lines-wrapper, .adev-build-wrapper { position: relative; } .adev-build-text, .adev-build-webgl-text { h2 { color: var(--gray-unfilled); @media screen and (max-width: 1000px) { font-size: 2.75rem; } } .adev-gradient { position: absolute; left: 0; top: 0; right: 0; background: url('../../../assets/textures/gradient.jpg'); background-size: cover; background-position: center; background-clip: text; -webkit-background-clip: text; -webkit-text-fill-color: transparent; clip-path: inset(0%); } } .adev-editor-scroll-container { position: relative; height: 300vh; background-color: var(--page-background); .adev-sticky-editor { position: sticky; top: calc((100vh - (100vh - 110px)) / 2); @include mq.for-tablet { top: calc(((100vh - (100vh - 110px)) / 2) + 36px); } @include mq.for-phone-only { top: calc(((100vh - (100vh - 110px)) / 2) + 25px); } } img { margin: 0 auto; display: flex; justify-content: center; align-items: center; height: auto; min-height: 60vh; width: 75vw; } } &.adev-header { .adev-cta, .adev-arrow { opacity: 1; visibility: visible; } } &.adev-webgl { .adev-logo, .adev-scale, .adev-lines { height: 200vh; @supports (height: 100lvh) { height: 200lvh; } } .adev-logo-wordmark, .adev-scale-text, .adev-lines-text, .adev-build-text { position: fixed; } .adev-scale-text, .adev-lines-text, .adev-build-text { opacity: 0; } .adev-build { height: 300vh; @supports (height: 100lvh) { height: 300lvh; } } .adev-build-text { h2 { opacity: 0; } } .adev-build-webgl-text { display: flex; } &.adev-loaded { .adev-canvas { opacity: unset; } .adev-logo-wordmark { opacity: 0; } } } } .adev-code-editor { background-color: var(--page-background); padding-bottom: 60px; // stylelint-disable-next-line ::ng-deep { embedded-editor { margin: 0 auto; display: flex; width: 75vw; @include mq.for-phone-only { width: 95vw; } height: calc(100vh - 110px); .adev-editor-container { width: 100%; } } } } .adev-code-editor-gradient { position: absolute; left: 0; right: 0; margin-top: -100vh; height: 100vh; background: linear-gradient(to top, var(--page-background), transparent); pointer-events: none; @supports (height: 100svh) { margin-top: -100svh; height: 100svh; } }
{ "end_byte": 7894, "start_byte": 2506, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/home.component.scss" }
angular/adev/src/app/features/home/home-animation-constants.ts_0_1249
/*! * @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 */ // Defines one breakpoint (in px) between mobile and desktop sizing. export const BREAKPOINT = 1000; // Defines maximum application size (in px) that can be rendered on a page. // If a viewport width is bigger than this size, we limit the width to this value. export const MAX_APP_WIDTH = 2560; // Defines the "Build for everyone" heading height ratio. // The computed CSS heading size (in px) is multiplied by this value to compensate for the // difference in height of the MSDF texture. export const BUILD_TEXT_HEIGHT_RATIO = 0.88; export const SCALE_DIV = '.adev-scale'; export const LINES_TEXT = '.adev-lines-text'; export const LINES_DIV = '.adev-lines'; export const BUILD_TEXT = '.adev-build-text'; export const CTA = '.adev-cta'; export const ARROW = '.adev-arrow'; export const SCALE_TEXT = '.adev-scale-text'; export const CANVAS = '.adev-canvas'; export const MOVING_LOGO = '.adev-logo'; export const HEADER_CLASS_NAME = 'adev-header'; export const WEBGL_CLASS_NAME = 'adev-webgl'; export const LOADED_CLASS_NAME = 'adev-loaded';
{ "end_byte": 1249, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/home-animation-constants.ts" }
angular/adev/src/app/features/home/home.component.spec.ts_0_1381
/*! * @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 {ComponentFixture, TestBed} from '@angular/core/testing'; // import Home from './home.component'; // import {HomeAnimation} from './services/home-animation.service'; // TODO: refactor for lazy-loading when both conditions are met // 1. WebGL is available with isWebGLAvailable() // 2. When a user's device settings are not set to reduced motion with !shouldReduceMotion() /* describe('Home', () => { let component: Home; let fixture: ComponentFixture<Home>; let fakeHomeAnimation = { init: () => Promise.resolve(), destroy: () => {}, }; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [Home], }).compileComponents(); TestBed.overrideProvider(HomeAnimation, {useValue: fakeHomeAnimation}); fixture = TestBed.createComponent(Home); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should call homeAnimation.destroy() on ngOnDestroy', () => { const destroySpy = spyOn(fakeHomeAnimation, 'destroy'); component.ngOnDestroy(); expect(destroySpy).toHaveBeenCalled(); }); }); */
{ "end_byte": 1381, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/home.component.spec.ts" }
angular/adev/src/app/features/home/utils/math.ts_0_295
/*! * @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 function toRadians(degrees: number): number { return degrees * (Math.PI / 180); }
{ "end_byte": 295, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/utils/math.ts" }
angular/adev/src/app/features/home/utils/ogl.ts_0_637
/*! * @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 {OGLRenderingContext, Texture, TextureLoader} from 'ogl'; /** * Load a texture. * @example * const texture = await loadTexture(gl, 'assets/textures/line-msdf.png'); * texture.minFilter = gl.LINEAR; * texture.generateMipmaps = false; */ export function loadTexture(gl: OGLRenderingContext, src: string): Promise<Texture> { const texture = TextureLoader.load(gl, {src}); return texture.loaded!.then(() => texture); }
{ "end_byte": 637, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/utils/ogl.ts" }
angular/adev/src/app/features/home/components/canvas.ts_0_719
/*! * @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 { Camera, Color, Mesh, OGLRenderingContext, RenderTarget, Renderer, Transform, Triangle, } from 'ogl'; import {MaskProgram} from './programs/mask-program'; import {GradientView} from './views/gradient-view'; import {AngularView} from './views/angular-view'; import {LinesView} from './views/lines-view'; import {BuildView} from './views/build-view'; import {BREAKPOINT} from '../home-animation-constants'; /** * Controller class for managing the WebGL canvas, OGL renderer and scenes. */
{ "end_byte": 719, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/canvas.ts" }
angular/adev/src/app/features/home/components/canvas.ts_720_8925
export class Canvas { private renderer!: Renderer; private gl!: OGLRenderingContext; private gradientScene!: Transform; private gradientCamera!: Camera; private angularScene!: Transform; private angularCamera!: Camera; private linesScene!: Transform; private linesCamera!: Camera; private buildScene!: Transform; private buildCamera!: Camera; private screen!: Mesh; private renderTargetA!: RenderTarget; private renderTargetB!: RenderTarget; private maskProgram!: MaskProgram; private currentClearColor: Color = new Color(); private needsUpdate: boolean = false; gradient!: GradientView; angular!: AngularView; lines!: LinesView; build!: BuildView; linesProgress = 0; /** * Create the controller. */ constructor( private readonly element: Element, private readonly document: Document, private readonly window: Window, ) { this.init(); this.initMesh(); this.initViews(); } /** * Initialize the OGL renderer and scenes. */ init(): void { this.renderer = new Renderer({ powerPreference: 'high-performance', depth: false, }); this.gl = this.renderer.gl; this.element.appendChild(this.gl.canvas as HTMLCanvasElement); // Gradient scene this.gradientScene = new Transform(); this.gradientCamera = new Camera(this.gl, { left: -1, right: 1, top: 1, bottom: -1, near: 0, far: 1, }); // Angular scene this.angularScene = new Transform(); this.angularCamera = new Camera(this.gl, { left: -1, right: 1, top: 1, bottom: -1, near: 0, far: 1, }); // Lines scene this.linesScene = new Transform(); this.linesCamera = new Camera(this.gl, {fov: 30, near: 0.5, far: 40}); this.linesCamera.position.z = 10; this.linesCamera.lookAt([0, 0, 0]); // Build scene this.buildScene = new Transform(); this.buildCamera = new Camera(this.gl, { left: -1, right: 1, top: 1, bottom: -1, near: 0, far: 1, }); } /** * Initialize a fullscreen triangle geometry and mesh for rendering scene composites or * post-processing, plus render targets and programs. */ initMesh(): void { // Fullscreen triangle const geometry = new Triangle(this.gl); this.screen = new Mesh(this.gl, {geometry}); this.screen.frustumCulled = false; // Render targets this.renderTargetA = new RenderTarget(this.gl, {depth: false}); this.renderTargetB = new RenderTarget(this.gl, {depth: false}); // Mask program this.maskProgram = new MaskProgram(this.gl, this.window); this.maskProgram.uniforms['tMap'].value = this.renderTargetA.texture; this.maskProgram.uniforms['tMask'].value = this.renderTargetB.texture; this.screen.program = this.maskProgram; } /** * Initialize views. */ initViews(): void { this.gradient = new GradientView(this.gl, this.document, this.window); this.gradientScene.addChild(this.gradient); this.angular = new AngularView(this.gl); this.angularScene.addChild(this.angular); this.lines = new LinesView(this.gl); this.linesScene.addChild(this.lines); this.build = new BuildView(this.gl, this.document); this.buildScene.addChild(this.build); } /** * Theme event handler. */ theme(): void { const rootStyle = getComputedStyle(this.document.querySelector(':root')!); this.currentClearColor.set(rootStyle.getPropertyValue('--webgl-page-background').trim()); this.gl.clearColor( ...(this.currentClearColor as unknown as [red: number, green: number, blue: number]), 1, ); // Views this.gradient.theme(); } /** * Resize event handler. */ resize(width: number, height: number, dpr: number, scale: number): void { this.renderer.dpr = dpr; this.renderer.setSize(width, height); // Views this.gradient.resize(width, height, dpr, scale); this.angular.resize(width, height, dpr, scale); this.build.resize(width, height, dpr, scale); // Gradient scene this.gradientCamera.left = -width / 2; this.gradientCamera.right = width / 2; this.gradientCamera.top = height / 2; this.gradientCamera.bottom = -height / 2; this.gradientCamera.orthographic(); // The camera position is offset for 2D positioning of objects top left this.gradientCamera.position.x = width / 2; this.gradientCamera.position.y = -height / 2; // Angular scene this.angularCamera.left = -width / 2; this.angularCamera.right = width / 2; this.angularCamera.top = height / 2; this.angularCamera.bottom = -height / 2; this.angularCamera.orthographic(); // The camera position is offset for 2D positioning of objects top left this.angularCamera.position.x = width / 2; this.angularCamera.position.y = -height / 2; // Lines scene this.linesCamera.aspect = width / height; this.linesCamera.perspective(); if (width < BREAKPOINT) { this.linesCamera.position.z = 20; } else { this.linesCamera.position.z = height / 60; } // Build scene this.buildCamera.left = -width / 2; this.buildCamera.right = width / 2; this.buildCamera.top = height / 2; this.buildCamera.bottom = -height / 2; this.buildCamera.orthographic(); // The camera position is offset for 2D positioning of objects top left this.buildCamera.position.x = width / 2; this.buildCamera.position.y = -height / 2; // Render targets const effectiveWidth = width * dpr; const effectiveHeight = height * dpr; this.renderTargetA.setSize(effectiveWidth, effectiveHeight); this.renderTargetB.setSize(effectiveWidth, effectiveHeight); } /** * Update event handler. */ update(time: number, deltaTime: number, frame: number, progress: number): void { // Reset gradient progress if (progress >= 0 && progress <= 0.16) { this.gradient.background.userData['progress'] = 0; } this.gradient.update(time); this.angular.update(); this.lines.update(time); this.build.update(); // Disable animation at end of page if ( !this.gradient.visible && !this.angular.visible && !this.lines.visible && !this.build.visible ) { if (this.needsUpdate) { this.needsUpdate = false; } else { return; } } else { this.needsUpdate = true; } const {renderer, renderTargetA, renderTargetB} = this; // Gradient pass renderer.render({ scene: this.gradientScene, camera: this.gradientCamera, target: renderTargetA, }); // Angular pass (mask on transparent background) this.gl.clearColor(0, 0, 0, 0); renderer.render({ scene: this.angularScene, camera: this.angularCamera, target: renderTargetB, }); // Build pass (mask on transparent background) renderer.render({ scene: this.buildScene, camera: this.buildCamera, target: renderTargetB, clear: false, }); // Set clear color back to default this.gl.clearColor( ...(this.currentClearColor as unknown as [red: number, green: number, blue: number]), 1, ); // Mask pass (render to screen) renderer.render({scene: this.screen}); // Camera parallax/pan/zoom by moving the entire scene this.linesScene.position.z = -6 + 6 * (1 - (-0.5 + this.linesProgress)); this.linesCamera.lookAt([0, 0, 0]); // Lines pass renderer.render({ scene: this.linesScene, camera: this.linesCamera, clear: false, }); } /** * Promise for the views when they're ready. */ ready(): Promise<void[]> { return Promise.all([ this.gradient.ready(), this.angular.ready(), this.lines.ready(), this.build.ready(), ]); } /** * Destroys the views, all child views and WebGL context. */ destroy(): void { this.gradient.destroy(); this.angular.destroy(); this.lines.destroy(); this.build.destroy(); const extension = this.gl.getExtension('WEBGL_lose_context'); if (extension) extension.loseContext(); } }
{ "end_byte": 8925, "start_byte": 720, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/canvas.ts" }
angular/adev/src/app/features/home/components/home-editor.component.ts_0_1408
/*! * @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 { ChangeDetectionStrategy, ChangeDetectorRef, Component, EnvironmentInjector, inject, Input, OnInit, } from '@angular/core'; import {injectAsync} from '../../../core/services/inject-async'; import {EmbeddedEditor, EmbeddedTutorialManager} from '../../../editor'; @Component({ selector: 'adev-code-editor', changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [EmbeddedEditor], template: ` <embedded-editor /> `, }) export class CodeEditorComponent implements OnInit { private readonly cdRef = inject(ChangeDetectorRef); private readonly environmentInjector = inject(EnvironmentInjector); private readonly embeddedTutorialManager = inject(EmbeddedTutorialManager); @Input({required: true}) tutorialFiles!: string; ngOnInit(): void { this.loadEmbeddedEditor(); } private async loadEmbeddedEditor() { const nodeRuntimeSandbox = await injectAsync(this.environmentInjector, () => import('../../../editor/index').then((c) => c.NodeRuntimeSandbox), ); await this.embeddedTutorialManager.fetchAndSetTutorialFiles(this.tutorialFiles); this.cdRef.markForCheck(); await nodeRuntimeSandbox.init(); } }
{ "end_byte": 1408, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/home-editor.component.ts" }
angular/adev/src/app/features/home/components/programs/line-glyph-program.ts_0_1425
/*! * @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 {Color, OGLRenderingContext, Program, Texture} from 'ogl'; import LineGlyphShader from '../shaders/line-glyph-shader'; const {vertex100, fragment100, vertex300, fragment300} = LineGlyphShader; /** * Multi-channel signed distance field (MSDF) shader program for a line instance. * * Textures generated with `msdfgen`, which includes support for advanced SVG decoding: * `msdfgen -svg line.svg -o line-msdf.png -size 235 300 -testrender line-render.png 235 300` * * @see {@link LineGlyphShader} for the GLSL shader. */ export class LineGlyphProgram extends Program { /** * Create the shader program. */ constructor(gl: OGLRenderingContext, texture: Texture) { super(gl, { uniforms: { tMap: {value: texture}, uPinkColor: {value: [new Color(0xf65fe3), new Color(0x873df5)]}, uPurpleColor: {value: [new Color(0xb666f2), new Color(0xea3a8a)]}, uRedColor: {value: [new Color(0xe92d64), new Color(0xf469e4)]}, uTime: {value: 0}, }, vertex: gl.renderer.isWebgl2 ? vertex300 : vertex100, fragment: gl.renderer.isWebgl2 ? fragment300 : fragment100, transparent: true, depthTest: false, depthWrite: false, }); } }
{ "end_byte": 1425, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/programs/line-glyph-program.ts" }
angular/adev/src/app/features/home/components/programs/basic-program.ts_0_1004
/*! * @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 {OGLRenderingContext, Program, Texture} from 'ogl'; import BasicShader from '../shaders/basic-shader'; const {vertex100, fragment100, vertex300, fragment300} = BasicShader; /** * Basic texture map shader program with alpha channel for the "Build for everyone" heading. * * @see {@link BasicShader} for the GLSL shader. */ export class BasicProgram extends Program { /** * Create the shader program. */ constructor(gl: OGLRenderingContext, texture: Texture) { super(gl, { uniforms: { tMap: {value: texture}, uAlpha: {value: 1}, }, vertex: gl.renderer.isWebgl2 ? vertex300 : vertex100, fragment: gl.renderer.isWebgl2 ? fragment300 : fragment100, transparent: true, depthTest: false, depthWrite: false, }); } }
{ "end_byte": 1004, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/programs/basic-program.ts" }
angular/adev/src/app/features/home/components/programs/glyph-program.ts_0_1449
/*! * @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 {Color, OGLRenderingContext, Program, Texture} from 'ogl'; import GlyphShader from '../shaders/glyph-shader'; const {vertex100, fragment100, vertex300, fragment300} = GlyphShader; /** * Multi-channel signed distance field (MSDF) shader program for the inner triangle and "Angular" * letters of the logo, and the "Build for everyone" heading. * * Textures generated with `msdfgen`, which includes support for advanced SVG decoding: * `msdfgen -svg logo-lockup.svg -o logo-lockup-msdf.png -size 700 172 -testrender logo-lockup-render.png 700 172` * `msdfgen -svg build-for-everyone.svg -o build-msdf.png -size 433 58 -autoframe -testrender build-render.png 433 58` * * @see {@link GlyphShader} for the GLSL shader. */ export class GlyphProgram extends Program { /** * Create the shader program. */ constructor(gl: OGLRenderingContext, texture: Texture, color: Color) { super(gl, { uniforms: { tMap: {value: texture}, uColor: {value: color}, uAlpha: {value: 1}, }, vertex: gl.renderer.isWebgl2 ? vertex300 : vertex100, fragment: gl.renderer.isWebgl2 ? fragment300 : fragment100, transparent: true, depthTest: false, depthWrite: false, }); } }
{ "end_byte": 1449, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/programs/glyph-program.ts" }
angular/adev/src/app/features/home/components/programs/logo-program.ts_0_1013
/*! * @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 {Color, OGLRenderingContext, Program} from 'ogl'; import LogoShader from '../shaders/logo-shader'; const {vertex100, fragment100, vertex300, fragment300} = LogoShader; /** * Signed distance field (SDF) shader program for the outer polygons of the logo. * * @see {@link LogoShader} for the GLSL shader. */ export class LogoProgram extends Program { /** * Create the shader program. */ constructor(gl: OGLRenderingContext, color: Color) { super(gl, { uniforms: { uColor: {value: color}, uProgress: {value: 0}, uAlpha: {value: 1}, }, vertex: gl.renderer.isWebgl2 ? vertex300 : vertex100, fragment: gl.renderer.isWebgl2 ? fragment300 : fragment100, transparent: true, depthTest: false, depthWrite: false, }); } }
{ "end_byte": 1013, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/programs/logo-program.ts" }
angular/adev/src/app/features/home/components/programs/mask-program.ts_0_1212
/*! * @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 {OGLRenderingContext, Program} from 'ogl'; import MaskShader from '../shaders/mask-shader'; const {vertex100, fragment100, vertex300, fragment300} = MaskShader; /** * Alpha mask shader program for the Angular logo. * * Uses the green channel of the mask texture as the output alpha channel of the gradient map * texture, creating a mask of the logo with the gradient background inside the logo. * * @see {@link MaskShader} for the GLSL shader. */ export class MaskProgram extends Program { /** * Create the shader program. */ constructor(gl: OGLRenderingContext, window: Window) { super(gl, { uniforms: { tMap: {value: null}, tMask: {value: null}, uDebug: {value: /[?&]debug|gradient/.test(window.location.search) ? 1 : 0}, }, vertex: gl.renderer.isWebgl2 ? vertex300 : vertex100, fragment: gl.renderer.isWebgl2 ? fragment300 : fragment100, transparent: true, depthTest: false, depthWrite: false, }); } }
{ "end_byte": 1212, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/programs/mask-program.ts" }
angular/adev/src/app/features/home/components/programs/gradient-program.ts_0_1202
/*! * @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 {Color, OGLRenderingContext, Program, Texture} from 'ogl'; import GradientShader from '../shaders/gradient-shader'; const {vertex100, fragment100, vertex300, fragment300} = GradientShader; /** * Gradient shader program for the background of the Angular logo. * * @see {@link GradientShader} for the GLSL shader. */ export class GradientProgram extends Program { /** * Create the shader program. */ constructor(gl: OGLRenderingContext, texture: Texture, window: Window) { super(gl, { uniforms: { tMap: {value: texture}, uGrayColor: {value: new Color(0xa39fa9)}, uProgress: {value: 0}, uAlpha: {value: 1}, uDebug: {value: /[?&]gradient/.test(window.location.search) ? 1 : 0}, uTime: {value: 0}, }, vertex: gl.renderer.isWebgl2 ? vertex300 : vertex100, fragment: gl.renderer.isWebgl2 ? fragment300 : fragment100, transparent: true, depthTest: false, depthWrite: false, }); } }
{ "end_byte": 1202, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/programs/gradient-program.ts" }
angular/adev/src/app/features/home/components/shaders/basic-shader.ts_0_1098
/*! * @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 */ const vertex = /* glsl */ ` attribute vec3 position; attribute vec2 uv; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `; const fragment = /* glsl */ ` precision highp float; uniform sampler2D tMap; uniform float uAlpha; varying vec2 vUv; void main() { gl_FragColor = texture2D(tMap, vUv); gl_FragColor.a *= uAlpha; } `; export default { vertex100: vertex, fragment100: /* glsl */ `#extension GL_OES_standard_derivatives : enable precision highp float; ${fragment}`, vertex300: /* glsl */ `#version 300 es #define attribute in #define varying out ${vertex}`, fragment300: /* glsl */ `#version 300 es precision highp float; #define varying in #define texture2D texture #define gl_FragColor FragColor out vec4 FragColor; ${fragment}`, };
{ "end_byte": 1098, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/shaders/basic-shader.ts" }
angular/adev/src/app/features/home/components/shaders/line-glyph-shader.ts_0_2422
/*! * @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 msdf from './modules/msdf/msdf.glsl'; const vertex = /* glsl */ ` attribute vec3 position; attribute vec2 uv; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; attribute mat4 instanceMatrix; attribute float instanceColorIndex; attribute float instanceRandom; attribute float instanceOpacity; uniform vec3 uPinkColor[2]; uniform vec3 uPurpleColor[2]; uniform vec3 uRedColor[2]; varying vec2 vUv; varying vec3 vColor[2]; varying float vInstanceRandom; varying float vInstanceOpacity; void main() { vUv = uv; if (instanceColorIndex == 0.0) { vColor[0] = uPinkColor[0]; vColor[1] = uPinkColor[1]; } else if (instanceColorIndex == 1.0) { vColor[0] = uPurpleColor[0]; vColor[1] = uPurpleColor[1]; } else if (instanceColorIndex == 2.0) { vColor[0] = uRedColor[0]; vColor[1] = uRedColor[1]; } vInstanceRandom = instanceRandom; vInstanceOpacity = instanceOpacity; gl_Position = projectionMatrix * modelViewMatrix * instanceMatrix * vec4(position, 1.0); } `; const fragment = /* glsl */ ` precision highp float; uniform sampler2D tMap; uniform float uTime; varying vec2 vUv; varying vec3 vColor[2]; varying float vInstanceRandom; varying float vInstanceOpacity; ${msdf} void main() { float alpha = msdf(tMap, vUv); alpha *= vInstanceOpacity; if (alpha < 0.01) { discard; } vec2 uv = vUv; uv.x += vInstanceRandom * uTime * 0.5; uv.x = fract(uv.x); // Wrap around 1.0 // Linear gradient, mirrored for wrapping vec3 color = mix(vColor[0], vColor[1], smoothstep(0.0, 0.3333, uv.x)); color = mix(color, vColor[1], smoothstep(0.3333, 0.6666, uv.x)); color = mix(color, vColor[0], smoothstep(0.6666, 1.0, uv.x)); gl_FragColor.rgb = color; gl_FragColor.a = smoothstep(1.0, 0.3333, vUv.x) * alpha; } `; export default { vertex100: vertex, fragment100: /* glsl */ `#extension GL_OES_standard_derivatives : enable precision highp float; ${fragment}`, vertex300: /* glsl */ `#version 300 es #define attribute in #define varying out ${vertex}`, fragment300: /* glsl */ `#version 300 es precision highp float; #define varying in #define texture2D texture #define gl_FragColor FragColor out vec4 FragColor; ${fragment}`, };
{ "end_byte": 2422, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/shaders/line-glyph-shader.ts" }
angular/adev/src/app/features/home/components/shaders/logo-shader.ts_0_2727
/*! * @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 sdPolygon from './modules/sdf-primitives/sd-polygon.glsl'; const vertex = /* glsl */ ` attribute vec3 position; attribute vec2 uv; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `; const fragment = /* glsl */ ` precision highp float; uniform vec3 uColor; uniform float uProgress; uniform float uAlpha; varying vec2 vUv; #define MAX_NUM_VERTICES 5 ${sdPolygon} void main() { // Polygon animation vec2[MAX_NUM_VERTICES] bottom; bottom[0] = vec2(0.292446808510638, 1.0 - mix(0.7381, 0.7781, uProgress)); bottom[1] = vec2(mix(0.239468085106383, 0.133085106382979, uProgress), 1.0 - mix(0.8592, 0.7781, uProgress)); bottom[2] = vec2(0.50031914893617, 1.0 - 1.0); bottom[3] = vec2(mix(0.761170212765957, 0.867553191489362, uProgress), 1.0 - mix(0.8592, 0.7781, uProgress)); bottom[4] = vec2(0.707553191489362, 1.0 - mix(0.7381, 0.7781, uProgress)); vec2[MAX_NUM_VERTICES] right; right[0] = vec2(mix(0.618404255319149, 0.597127659574468, uProgress), 1.0 - 0.0); right[1] = vec2(0.964042553191489, 1.0 - mix(0.7023, 0.6623, uProgress)); right[2] = vec2(1.0, 1.0 - 0.1665); vec2[MAX_NUM_VERTICES] left; left[0] = vec2(mix(0.381595744680851, 0.402872340425532, uProgress), 1.0 - 0.0); left[1] = vec2(0.035957446808511, 1.0 - mix(0.7023, 0.6623, uProgress)); left[2] = vec2(0.0, 1.0 - 0.1665); float sdBottom = sdPolygon(vUv, bottom, 5); float sdRight = sdPolygon(vUv, right, 3); float sdLeft = sdPolygon(vUv, left, 3); // Anti-alias float dBottom = fwidth(sdBottom); float alphaBottom = smoothstep(dBottom, -dBottom, sdBottom); float dRight = fwidth(sdRight); float alphaRight = smoothstep(dRight, -dRight, sdRight); float dLeft = fwidth(sdLeft); float alphaLeft = smoothstep(dLeft, -dLeft, sdLeft); float alpha = max(alphaBottom, alphaRight); alpha = max(alpha, alphaLeft); alpha *= uAlpha; if (alpha < 0.01) { discard; } gl_FragColor.rgb = uColor; gl_FragColor.a = alpha; } `; export default { vertex100: vertex, fragment100: /* glsl */ `#extension GL_OES_standard_derivatives : enable precision highp float; ${fragment}`, vertex300: /* glsl */ `#version 300 es #define attribute in #define varying out ${vertex}`, fragment300: /* glsl */ `#version 300 es precision highp float; #define varying in #define texture2D texture #define gl_FragColor FragColor out vec4 FragColor; ${fragment}`, };
{ "end_byte": 2727, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/shaders/logo-shader.ts" }
angular/adev/src/app/features/home/components/shaders/mask-shader.ts_0_1151
/*! * @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 */ const vertex = /* glsl */ ` attribute vec3 position; attribute vec2 uv; varying vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position, 1.0); } `; const fragment = /* glsl */ ` precision highp float; uniform sampler2D tMap; uniform sampler2D tMask; uniform float uDebug; varying vec2 vUv; void main() { if (uDebug == 1.0) { gl_FragColor = max(texture2D(tMap, vUv), texture2D(tMask, vUv)); } else { gl_FragColor = texture2D(tMap, vUv); gl_FragColor.a = texture2D(tMask, vUv).g; } } `; export default { vertex100: vertex, fragment100: /* glsl */ `#extension GL_OES_standard_derivatives : enable precision highp float; ${fragment}`, vertex300: /* glsl */ `#version 300 es #define attribute in #define varying out ${vertex}`, fragment300: /* glsl */ `#version 300 es precision highp float; #define varying in #define texture2D texture #define gl_FragColor FragColor out vec4 FragColor; ${fragment}`, };
{ "end_byte": 1151, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/shaders/mask-shader.ts" }
angular/adev/src/app/features/home/components/shaders/gradient-shader.ts_0_2503
/*! * @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 sineInOut from './modules/easing/sine-in-out.glsl'; const vertex = /* glsl */ ` attribute vec3 position; attribute vec2 uv; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `; const fragment = /* glsl */ ` precision highp float; uniform sampler2D tMap; uniform vec3 uGrayColor; uniform float uProgress; uniform float uAlpha; uniform float uDebug; uniform float uTime; varying vec2 vUv; ${sineInOut} void main() { float time = fract(uTime / 6.0); float t = abs(2.0 * time - 1.0); // Rotation starts at 35.642°, 3 sec 180° and 6 sec 360° float currentAngle = 35.642 + time * 360.0; vec2 uv = vUv; uv.x -= 0.1 * (1.0 - sineInOut(t)); vec2 origin = vec2(0.5, 0.5); uv -= origin; float angle = radians(currentAngle) + atan(uv.y, uv.x); float len = length(uv); uv = vec2(cos(angle) * len, sin(angle) * len) + origin; gl_FragColor = texture2D(tMap, uv); if (uDebug == 1.0) { // Anti-aliased outer circle float radius = 0.5; float d = fwidth(len); float circle = smoothstep(radius - d, radius + d, len); gl_FragColor.a = (1.0 - circle) * uAlpha; // Anti-aliased center point radius = 0.005; circle = smoothstep(radius - d, radius + d, len); gl_FragColor.rgb = mix(vec3(1), gl_FragColor.rgb, circle); } else { gl_FragColor.a *= uAlpha; } if (uProgress > 0.0) { // Anti-aliased gray unfilled angle float theta = radians(20.0); uv = vec2(cos(theta) * vUv.x - sin(theta) * vUv.y, sin(theta) * vUv.x + cos(theta) * vUv.y); float progress = 2.0 * uProgress - 1.0; float d = 0.001; float angle = smoothstep(uv.x - d, uv.x + d, progress); gl_FragColor.rgb = mix(uGrayColor, gl_FragColor.rgb, angle); } } `; export default { vertex100: vertex, fragment100: /* glsl */ `#extension GL_OES_standard_derivatives : enable precision highp float; ${fragment}`, vertex300: /* glsl */ `#version 300 es #define attribute in #define varying out ${vertex}`, fragment300: /* glsl */ `#version 300 es precision highp float; #define varying in #define texture2D texture #define gl_FragColor FragColor out vec4 FragColor; ${fragment}`, };
{ "end_byte": 2503, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/shaders/gradient-shader.ts" }
angular/adev/src/app/features/home/components/shaders/glyph-shader.ts_0_1255
/*! * @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 msdf from './modules/msdf/msdf.glsl'; const vertex = /* glsl */ ` attribute vec3 position; attribute vec2 uv; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `; const fragment = /* glsl */ ` precision highp float; uniform sampler2D tMap; uniform vec3 uColor; uniform float uAlpha; varying vec2 vUv; ${msdf} void main() { float alpha = msdf(tMap, vUv); alpha *= uAlpha; if (alpha < 0.01) { discard; } gl_FragColor.rgb = uColor; gl_FragColor.a = alpha; } `; export default { vertex100: vertex, fragment100: /* glsl */ `#extension GL_OES_standard_derivatives : enable precision highp float; ${fragment}`, vertex300: /* glsl */ `#version 300 es #define attribute in #define varying out ${vertex}`, fragment300: /* glsl */ `#version 300 es precision highp float; #define varying in #define texture2D texture #define gl_FragColor FragColor out vec4 FragColor; ${fragment}`, };
{ "end_byte": 1255, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/shaders/glyph-shader.ts" }
angular/adev/src/app/features/home/components/shaders/modules/easing/sine-in-out.glsl.ts_0_349
/*! * @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 default /* glsl */ ` #ifndef PI #define PI 3.141592653589793 #endif float sineInOut(float t) { return -0.5 * (cos(PI * t) - 1.0); } `;
{ "end_byte": 349, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/shaders/modules/easing/sine-in-out.glsl.ts" }
angular/adev/src/app/features/home/components/shaders/modules/sdf-primitives/sd-polygon.glsl.ts_0_750
/*! * @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 default /* glsl */ ` #ifndef MAX_NUM_VERTICES #define MAX_NUM_VERTICES 5 #endif float sdPolygon(vec2 p, vec2[MAX_NUM_VERTICES] v, int num) { float d = dot(p - v[0], p - v[0]); float s = 1.0; for (int i = 0, j = num - 1; i < num; j = i, i++) { vec2 e = v[j] - v[i]; vec2 w = p - v[i]; vec2 b = w - e * clamp(dot(w, e) / dot(e, e), 0.0, 1.0); d = min(d, dot(b, b)); bvec3 cond = bvec3(p.y >= v[i].y, p.y < v[j].y, e.x * w.y > e.y * w.x); if (all(cond) || all(not(cond))) s = -s; } return s * sqrt(d); } `;
{ "end_byte": 750, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/shaders/modules/sdf-primitives/sd-polygon.glsl.ts" }
angular/adev/src/app/features/home/components/shaders/modules/msdf/msdf.glsl.ts_0_469
/*! * @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 default /* glsl */ ` float msdf(sampler2D image, vec2 uv) { vec3 tex = texture2D(image, uv).rgb; float signedDist = max(min(tex.r, tex.g), min(max(tex.r, tex.g), tex.b)) - 0.5; float d = fwidth(signedDist); return smoothstep(-d, d, signedDist); } `;
{ "end_byte": 469, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/shaders/modules/msdf/msdf.glsl.ts" }
angular/adev/src/app/features/home/components/views/build-text.ts_0_3360
/*! * @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 {Color, Mesh, OGLRenderingContext, Plane} from 'ogl'; import {View} from './view'; import {GlyphProgram} from '../programs/glyph-program'; import {toRadians} from '../../utils/math'; import {loadTexture} from '../../utils/ogl'; import {BREAKPOINT, BUILD_TEXT_HEIGHT_RATIO} from '../../home-animation-constants'; /** * An OGL `Transform` used for the animation of the "Build for everyone" heading. * * The `userData` object is used for the GSAP animation, and the `override update(): void` method * applies the values to the `Transform`. */ export class BuildText extends View { private viewWidth = 433; private viewHeight = 58; private aspect = this.viewWidth / this.viewHeight; private mesh!: Mesh; /** * Create the build text. */ constructor( private readonly gl: OGLRenderingContext, private readonly document: Document, ) { super(); this.userData['x'] = 0; this.userData['y'] = 0; this.userData['rotation'] = 0; this.userData['scale'] = 1; this.userData['opacity'] = 1; } /** * Initialize child views. */ override async init(): Promise<void> { const texture = await loadTexture(this.gl, 'assets/textures/build-msdf.png'); texture.minFilter = this.gl.LINEAR; texture.generateMipmaps = false; const geometry = new Plane(this.gl); const program = new GlyphProgram(this.gl, texture, new Color(1, 1, 1)); const mesh = new Mesh(this.gl, {geometry, program}); mesh.frustumCulled = false; this.addChild(mesh); this.mesh = mesh; } /** * Update size and position of the view, based on the CSS heading. */ override resize(width: number, height: number, dpr: number, scale: number): void { const heading = this.document.querySelector('.adev-build-webgl-text h2')!; const bounds = heading.getBoundingClientRect(); let textHeight; if (width < BREAKPOINT) { // Mobile fixed size (in px) textHeight = 48; } else { // Desktop calculation (in px) textHeight = bounds.height * BUILD_TEXT_HEIGHT_RATIO; } this.userData['width'] = textHeight * this.aspect; this.userData['height'] = textHeight; // Positioned relative to the CSS heading, vertical offset from the center, Y flipped let y = 1 - (bounds.y - (height - bounds.height) / 2); // Vertical offset adjustment (in px) if (width < BREAKPOINT) { y -= 4; } else { y -= 6 * scale; } this.mesh.position.set(0, y, 0); this.mesh.scale.set(this.userData['width'], this.userData['height'], 1); } /** * Update position, rotation and scale of the view, and alpha uniform of the program. */ override update(): void { this.position.x = this.userData['x']; this.position.y = -this.userData['y']; // Y flipped this.rotation.z = -toRadians(this.userData['rotation']); this.scale.set(this.userData['scale']); this.mesh.program.uniforms['uAlpha'].value = this.userData['opacity'] * this.parent!.userData['opacity']; } /** * Promise for the child views when they're ready. */ override ready(): Promise<void> { return this.init(); } }
{ "end_byte": 3360, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/build-text.ts" }
angular/adev/src/app/features/home/components/views/line-object.ts_0_1561
/*! * @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 {Mesh, Vec3} from 'ogl'; import {View} from './view'; import {toRadians} from '../../utils/math'; /** * An OGL `Transform` used for the animation of a line instance. * * The `userData` object is used for the GSAP animation, and the `override update(): void` method * applies the values to the `Transform`. */ export class LineObject extends View { /** * Create a line view. */ constructor( private readonly origin: Vec3, private readonly mesh: Mesh, private readonly index: number, ) { super(); this.userData['x'] = 0; this.userData['y'] = 0; this.userData['rotation'] = 0; this.userData['scale'] = 1; this.userData['opacity'] = 1; } /** * Update position, rotation and scale of the view, and alpha attribute of the geometry. */ override update(): void { this.position.x = this.origin.x + this.userData['x']; this.position.y = this.origin.y + -this.userData['y']; // Y flipped this.rotation.z = -toRadians(this.userData['rotation']); this.scale.set(this.userData['scale']); this.updateMatrix(); this.matrix.toArray(this.mesh.geometry.attributes['instanceMatrix'].data, this.index * 16); this.mesh.geometry.attributes['instanceOpacity'].data!.set( [this.userData['opacity'] * this.parent!.userData['opacity']], this.index, ); } }
{ "end_byte": 1561, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/line-object.ts" }
angular/adev/src/app/features/home/components/views/build-view.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 {OGLRenderingContext, Vec2} from 'ogl'; import {View} from './view'; import {BuildText} from './build-text'; import {toRadians} from '../../utils/math'; /** * An OGL `Transform` used for the top-level view of the build section. * * The `userData` object is used for the GSAP animation, and the `override update(): void` method * applies the values to the `Transform`. */ export class BuildView extends View { private origin: Vec2; text!: BuildText; /** * Create the build view. */ constructor( private readonly gl: OGLRenderingContext, private readonly document: Document, ) { super(); this.visible = false; this.userData['x'] = 0; this.userData['y'] = 0; this.userData['rotation'] = 0; this.userData['scale'] = 1; this.userData['opacity'] = 1; this.origin = new Vec2(); this.init(); } /** * Initialize child views. */ override init(): void { this.text = new BuildText(this.gl, this.document); this.addChild(this.text); } /** * Update size and position of the view, based on the size of the screen, and child views. */ override resize(width: number, height: number, dpr: number, scale: number): void { // Centered this.origin.set(Math.round(width / 2), Math.round(height / 2)); this.text.resize(width, height, dpr, scale); } /** * Update position, rotation and scale of the view, and child views. */ override update(): void { this.position.x = this.origin.x + this.userData['x']; this.position.y = -this.origin.y + -this.userData['y']; // Y flipped this.rotation.z = -toRadians(this.userData['rotation']); this.scale.set(this.userData['scale']); this.visible = this.userData['opacity'] > 0; this.text.update(); } /** * Promise for the child views when they're ready. */ override ready(): Promise<void> { return this.text.init(); } }
{ "end_byte": 2125, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/build-view.ts" }
angular/adev/src/app/features/home/components/views/lines-view.ts_0_1399
/*! * @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 {isMobile} from '@angular/docs'; import type {OGLRenderingContext} from 'ogl'; import {View} from './view'; import {Lines} from './lines'; /** * An OGL `Transform` used for the top-level view of the lines section. */ export class LinesView extends View { // Number of divisions on a square grid // For example 9 × 9 = 81 line instances private divisions = isMobile ? 9 : 14; container!: Lines; /** * Create the lines view. */ constructor(private readonly gl: OGLRenderingContext) { super(); this.visible = false; // Center the container const offset = this.divisions - 2; this.position.x = -offset; this.position.y = -offset; this.init(); } /** * Initialize child views. */ override init(): void { this.container = new Lines(this.gl, this.divisions); this.addChild(this.container); } /** * Update the child views. */ override update(time: number): void { this.visible = this.container.userData['opacity'] > 0; this.container.update(time); } /** * Promise for the child views when they're ready. */ override ready(): Promise<void> { return this.container.init(); } }
{ "end_byte": 1399, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/lines-view.ts" }
angular/adev/src/app/features/home/components/views/gradient-view.ts_0_2533
/*! * @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 {OGLRenderingContext, Vec2} from 'ogl'; import {View} from './view'; import {Gradient} from './gradient'; import {toRadians} from '../../utils/math'; /** * An OGL `Transform` used for the top-level view of the gradient background. * * The `userData` object is used for the GSAP animation, and the `override update(): void` method * applies the values to the `Transform`. */ export class GradientView extends View { private origin: Vec2; background!: Gradient; /** * Create the gradient view. */ constructor( private readonly gl: OGLRenderingContext, private readonly document: Document, private readonly window: Window, ) { super(); this.visible = false; this.userData['x'] = 0; this.userData['y'] = 0; this.userData['rotation'] = 0; this.userData['scale'] = 1; this.userData['opacity'] = 1; this.origin = new Vec2(); this.init(); } /** * Initialize child views. */ override init(): void { this.background = new Gradient(this.gl, this.document, this.window); this.addChild(this.background); } /** * Update the theme of child views. */ override theme(): void { this.background.theme(); } /** * Resize the child views. */ override resize(width: number, height: number, dpr: number, scale: number): void { // Centered this.origin.set(Math.round(width / 2), Math.round(height / 2)); this.background.resize(width, height, dpr, scale); } /** * Update position, rotation and scale of the view, and child views. */ override update(time: number): void { this.position.x = this.origin.x + this.userData['x']; this.position.y = -this.origin.y + -this.userData['y']; // Y flipped this.rotation.z = -toRadians(this.userData['rotation']); this.scale.set(this.userData['scale']); // "Build for everyone" gradient centered, scale set by the child view if (this.background.userData['progress'] > 0) { this.position.x = this.origin.x; this.position.y = -this.origin.y; // Y flipped this.scale.set(1); } this.visible = this.userData['opacity'] > 0; this.background.update(time); } /** * Promise for the child views when they're ready. */ override ready(): Promise<void> { return this.background.init(); } }
{ "end_byte": 2533, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/gradient-view.ts" }
angular/adev/src/app/features/home/components/views/view.ts_0_1412
/*! * @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 {Transform} from 'ogl'; /** * An OGL `Transform` used as a base class for implementing views. */ export class View extends Transform { /** * The parent. */ override parent: View | null = null; /** * An array with the children. */ override children: View[] = []; /** * An object for storing custom data. */ userData: Record<string, any> = {}; /** * Stub for initializing child views. */ init(): void {} /** * Stub for updating child views, based on the current theme. */ theme(): void {} /** * Stub for resizing child views. */ resize(width?: number, height?: number, dpr?: number, scale?: number): void {} /** * Stub for updating child views. */ update(time?: number, deltaTime?: number, frame?: number, progress?: number): void {} /** * Stub for initializing child views when they're ready. */ ready(): void | Promise<void> {} /** * Destroys the child views and empties the children array. */ destroy(): void { for (let i = this.children.length - 1; i >= 0; i--) { if ('destroy' in this.children[i]) { this.children[i].destroy(); } } this.children.length = 0; } }
{ "end_byte": 1412, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/view.ts" }
angular/adev/src/app/features/home/components/views/lines.ts_0_4079
/*! * @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 {InstancedMesh, OGLRenderingContext, Plane, Transform} from 'ogl'; import {View} from './view'; import {LineGlyphProgram} from '../programs/line-glyph-program'; import {LineObject} from './line-object'; import {toRadians} from '../../utils/math'; import {loadTexture} from '../../utils/ogl'; // An index number used for the color of the line instance enum InstanceColorIndex { Pink = 0, Purple = 1, Red = 2, } /** * An OGL `Transform` used for the animation of the lines section. * * The `userData` object is used for the GSAP animation, and the `override update(): void` method * applies the values to the `Transform`. */ export class Lines extends View { private mesh!: InstancedMesh; /** * Create the container view. */ constructor( private readonly gl: OGLRenderingContext, private readonly divisions: number, ) { super(); this.userData['x'] = 0; this.userData['y'] = 0; this.userData['rotation'] = 0; this.userData['scale'] = 1; this.userData['opacity'] = 1; } /** * Initialize geometry, program and mesh for the view. */ override async init(): Promise<void> { const texture = await loadTexture(this.gl, 'assets/textures/line-msdf.png'); texture.minFilter = this.gl.LINEAR; texture.generateMipmaps = false; const viewWidth = 235; const viewHeight = 300; const aspect = viewWidth / viewHeight; const size = 1.6; const width = size * aspect; const height = size; const widthDivisions = this.divisions; const heightDivisions = this.divisions; const numInstances = widthDivisions * heightDivisions; const geometry = new Plane(this.gl, {width, height}); geometry.addAttribute('instanceMatrix', { instanced: 1, size: 16, data: new Float32Array(numInstances * 16), }); geometry.addAttribute('instanceColorIndex', { instanced: 1, size: 1, data: new Float32Array(numInstances).map( (): InstanceColorIndex => Math.floor(Math.random() * 3), ), }); geometry.addAttribute('instanceRandom', { instanced: 1, size: 1, data: new Float32Array(numInstances).map(() => Math.random()), }); geometry.addAttribute('instanceOpacity', { instanced: 1, size: 1, data: new Float32Array(numInstances).fill(1), }); const program = new LineGlyphProgram(this.gl, texture); const mesh = new InstancedMesh(this.gl, {geometry, program}); // TODO: @pschroen add support for instanced mesh frustum culling // mesh.addFrustumCull(); const object = new Transform(); let index = 0; for (let y = 0; y < heightDivisions; y++) { for (let x = 0; x < widthDivisions; x++) { object.position.set(2 * x, 2 * y, 0); object.updateMatrix(); object.matrix.toArray(mesh.geometry.attributes['instanceMatrix'].data, index * 16); const line = new LineObject(object.position.clone(), mesh, index); this.addChild(line); index++; } } mesh.geometry.attributes['instanceMatrix'].needsUpdate = true; // Add instanced mesh last this.addChild(mesh); this.mesh = mesh; } /** * Update position, rotation and scale of the view, time uniform of the program, and child views. */ override update(time: number): void { this.position.x = this.userData['x']; this.position.y = -this.userData['y']; // Y flipped this.rotation.z = -toRadians(this.userData['rotation']); this.scale.set(this.userData['scale']); this.mesh.program.uniforms['uTime'].value = time; this.children.forEach((node: Transform) => { if (node instanceof View) { node.update(); } }); this.mesh.geometry.attributes['instanceMatrix'].needsUpdate = true; this.mesh.geometry.attributes['instanceOpacity'].needsUpdate = true; } }
{ "end_byte": 4079, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/lines.ts" }
angular/adev/src/app/features/home/components/views/angular-glyph.ts_0_2609
/*! * @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 {Color, Mesh, OGLRenderingContext, Plane, Texture, Vec2} from 'ogl'; import {View} from './view'; import {GlyphProgram} from '../programs/glyph-program'; import {toRadians} from '../../utils/math'; /** * An OGL `Transform` used for the animation of the inner triangle and "Angular" letters of the logo. * * The `userData` object is used for the GSAP animation, and the `override update(): void` method * applies the values to the `Transform`. */ export class AngularGlyph extends View { private origin: Vec2; private mesh!: Mesh; /** * Create a glyph view. */ constructor( private readonly gl: OGLRenderingContext, private readonly texture: Texture, private readonly color: Color, private translate: Vec2 = new Vec2(0.5, -0.5), // Top left ) { super(); this.userData['x'] = 0; this.userData['y'] = 0; this.userData['rotation'] = 0; this.userData['scale'] = 1; this.userData['opacity'] = 1; this.userData['width'] = 700; this.userData['height'] = 172; this.origin = new Vec2( Math.round(this.userData['width'] * (this.translate.x - 0.5)), Math.round(this.userData['height'] * (this.translate.y + 0.5)), ); this.translate = new Vec2( Math.round(this.userData['width'] * this.translate.x), Math.round(this.userData['height'] * this.translate.y), ); this.init(); } /** * Initialize geometry, program and mesh for the view. */ override init(): void { const geometry = new Plane(this.gl); const program = new GlyphProgram(this.gl, this.texture, this.color); const mesh = new Mesh(this.gl, {geometry, program}); mesh.frustumCulled = false; mesh.position.set(this.translate.x, this.translate.y, 0); // Offset mesh for transform origin mesh.scale.set(this.userData['width'], this.userData['height'], 1); this.addChild(mesh); this.mesh = mesh; } /** * Update position, rotation and scale of the view, and alpha uniform of the program. */ override update(): void { this.position.x = -this.origin.x + this.userData['x']; this.position.y = -this.origin.y + -this.userData['y']; // Y flipped this.rotation.z = -toRadians(this.userData['rotation']); this.scale.set(this.userData['scale']); this.mesh.program.uniforms['uAlpha'].value = this.userData['opacity'] * this.parent!.userData['opacity']; } }
{ "end_byte": 2609, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/angular-glyph.ts" }
angular/adev/src/app/features/home/components/views/gradient.ts_0_3700
/*! * @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 {Mesh, OGLRenderingContext, Plane} from 'ogl'; import {View} from './view'; import {GradientProgram} from '../programs/gradient-program'; import {toRadians} from '../../utils/math'; import {loadTexture} from '../../utils/ogl'; /** * An OGL `Transform` used for the animation of the gradient background. * * The `userData` object is used for the GSAP animation, and the `override update(): void` method * applies the values to the `Transform`. */ export class Gradient extends View { private viewWidth = 700; private viewScale = 1; private mesh!: Mesh; /** * Create the gradient background. */ constructor( private readonly gl: OGLRenderingContext, private readonly document: Document, private readonly window: Window, ) { super(); this.userData['x'] = 0; this.userData['y'] = 0; this.userData['rotation'] = 0; this.userData['scale'] = 1; this.userData['opacity'] = 1; this.userData['progress'] = 0; this.userData['buildWidth'] = 0; // Used for the "Build for everyone" heading width } /** * Initialize geometry, program and mesh for the view. */ override async init(): Promise<void> { const texture = await loadTexture(this.gl, 'assets/textures/gradient.jpg'); const geometry = new Plane(this.gl); const program = new GradientProgram(this.gl, texture, this.window); const mesh = new Mesh(this.gl, {geometry, program}); mesh.frustumCulled = false; this.addChild(mesh); this.mesh = mesh; } /** * Update color uniforms of the material, based on the current theme. */ override theme(): void { const rootStyle = getComputedStyle(this.document.querySelector(':root')!); this.mesh.program.uniforms['uGrayColor'].value.set( rootStyle.getPropertyValue('--webgl-gray-unfilled').trim(), ); } /** * Update size and position of the view, based on the size of the screen. */ override resize(width: number, height: number, dpr: number, scale: number): void { this.viewScale = scale; // The gradient is 1.34x the width of the Angular logo const size = this.viewWidth * this.viewScale * 1.34; this.userData['width'] = size; this.userData['height'] = size; } /** * Update position, rotation and scale of the view, position and scale of the mesh, and progress, * alpha and time uniforms of the program. */ override update(time: number): void { this.position.x = this.userData['x']; this.position.y = -this.userData['y']; // Y flipped this.rotation.z = -toRadians(this.userData['rotation']); this.scale.set(this.userData['scale']); if (this.userData['progress'] > 0) { // "Build for everyone" gradient centered, same width as the heading this.mesh.position.set(0); this.mesh.scale.set(this.userData['buildWidth'], this.userData['buildWidth'], 1); } else { // Positioned relative to the Angular logo, Y flipped this.mesh.position.set(-102 * this.viewScale, -40 * this.viewScale, 0); this.mesh.scale.set(this.userData['width'], this.userData['height'], 1); } this.mesh.program.uniforms['uProgress'].value = this.userData['progress']; this.mesh.program.uniforms['uAlpha'].value = this.userData['opacity'] * this.parent!.userData['opacity']; this.mesh.program.uniforms['uTime'].value = time; } /** * Promise for the child views when they're ready. */ override ready(): Promise<void> { return this.init(); } }
{ "end_byte": 3700, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/gradient.ts" }
angular/adev/src/app/features/home/components/views/angular-view.ts_0_1289
/*! * @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 {OGLRenderingContext} from 'ogl'; import {View} from './view'; import {Angular} from './angular'; /** * An OGL `Transform` used for the top-level view of the Angular logo mask. */ export class AngularView extends View { wordmark!: Angular; /** * Create the mask view. */ constructor(private readonly gl: OGLRenderingContext) { super(); this.visible = false; this.userData['visible'] = this.visible; this.init(); } /** * Initialize child views. */ override init(): void { this.wordmark = new Angular(this.gl); this.addChild(this.wordmark); } /** * Resize the child views. */ override resize(width: number, height: number, dpr: number, scale: number): void { this.wordmark.resize(width, height, dpr, scale); } /** * Update the child views. */ override update(): void { this.visible = this.userData['visible']; this.wordmark.update(); } /** * Promise for the child views when they're ready. */ override ready(): Promise<void> { return this.wordmark.init(); } }
{ "end_byte": 1289, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/angular-view.ts" }
angular/adev/src/app/features/home/components/views/angular-logo.ts_0_2646
/*! * @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 {Color, Mesh, OGLRenderingContext, Plane, Vec2} from 'ogl'; import {View} from './view'; import {LogoProgram} from '../programs/logo-program'; import {toRadians} from '../../utils/math'; /** * An OGL `Transform` used for the animation of the outer polygons of the logo. * * The `userData` object is used for the GSAP animation, and the `override update(): void` method * applies the values to the `Transform`. */ export class AngularLogo extends View { private origin: Vec2; private mesh!: Mesh; /** * Create the logo view. */ constructor( private readonly gl: OGLRenderingContext, private readonly color: Color, private translate: Vec2 = new Vec2(), // Center ) { super(); this.userData['x'] = 0; this.userData['y'] = 0; this.userData['rotation'] = 0; this.userData['scale'] = 1; this.userData['opacity'] = 1; this.userData['width'] = 158.6; this.userData['height'] = 168; this.userData['progress'] = 0; this.origin = new Vec2( Math.round(this.userData['width'] * (this.translate.x - 0.5)), Math.round(this.userData['height'] * (this.translate.y + 0.5)), ); this.translate = new Vec2( Math.round(this.userData['width'] * this.translate.x), Math.round(this.userData['height'] * this.translate.y), ); this.init(); } /** * Initialize geometry, program and mesh for the view. */ override init(): void { const geometry = new Plane(this.gl); const program = new LogoProgram(this.gl, this.color); const mesh = new Mesh(this.gl, {geometry, program}); mesh.frustumCulled = false; mesh.position.set(this.translate.x, this.translate.y, 0); // Offset mesh for transform origin mesh.scale.set(this.userData['width'], this.userData['height'], 1); this.addChild(mesh); this.mesh = mesh; } /** * Update position, rotation and scale of the view, and progress and alpha uniforms of the * program. */ override update(): void { this.position.x = -this.origin.x + this.userData['x']; this.position.y = -this.origin.y + -this.userData['y']; // Y flipped this.rotation.z = -toRadians(this.userData['rotation']); this.scale.set(this.userData['scale']); this.mesh.program.uniforms['uProgress'].value = this.userData['progress']; this.mesh.program.uniforms['uAlpha'].value = this.userData['opacity'] * this.parent!.userData['opacity']; } }
{ "end_byte": 2646, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/angular-logo.ts" }
angular/adev/src/app/features/home/components/views/angular.ts_0_3124
/*! * @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 {Color, OGLRenderingContext, Vec2} from 'ogl'; import {AngularGlyph} from './angular-glyph'; import {AngularLogo} from './angular-logo'; import {View} from './view'; import {toRadians} from '../../utils/math'; import {loadTexture} from '../../utils/ogl'; /** * An OGL `Transform` used for the animation of the Angular logo. * * The `userData` object is used for the GSAP animation, and the `override update(): void` method * applies the values to the `Transform`. */ export class Angular extends View { private viewWidth = 700; private viewHeight = 172; private viewScale = 1; private origin: Vec2; /** * Create the Angular logo view. */ constructor(private readonly gl: OGLRenderingContext) { super(); this.userData['x'] = 0; this.userData['y'] = 0; this.userData['rotation'] = 0; this.userData['scale'] = 1; this.userData['opacity'] = 1; this.origin = new Vec2(); } /** * Initialize child views. */ override async init(): Promise<void> { const logo = new AngularLogo(this.gl, new Color(1, 1, 1)); this.addChild(logo); const msdf = await Promise.all([ loadTexture(this.gl, 'assets/textures/logo-2-msdf.png'), loadTexture(this.gl, 'assets/textures/logo-3-msdf.png'), loadTexture(this.gl, 'assets/textures/logo-4-msdf.png'), loadTexture(this.gl, 'assets/textures/logo-5-msdf.png'), loadTexture(this.gl, 'assets/textures/logo-6-msdf.png'), loadTexture(this.gl, 'assets/textures/logo-7-msdf.png'), loadTexture(this.gl, 'assets/textures/logo-8-msdf.png'), loadTexture(this.gl, 'assets/textures/logo-9-msdf.png'), ]); msdf.forEach((texture, i) => { texture.minFilter = this.gl.LINEAR; texture.generateMipmaps = false; const glyph = new AngularGlyph( this.gl, texture, new Color(1, 1, 1), i < 1 ? new Vec2(0.5 - 0.1123, 0) : new Vec2(0.5, -0.5), ); this.addChild(glyph); }); } /** * Update size and position of the view, based on the size of the screen. */ override resize(width: number, height: number, dpr: number, scale: number): void { this.viewScale = scale; this.userData['width'] = this.viewWidth * this.viewScale; this.userData['height'] = this.viewHeight * this.viewScale; // Centered this.origin.set( Math.round((width - this.userData['width']) / 2), Math.round((height - this.userData['height']) / 2), ); } /** * Update position, rotation and scale of the view, and child views. */ override update(): void { this.position.x = this.origin.x + this.userData['x']; this.position.y = -this.origin.y + -this.userData['y']; // Y flipped this.rotation.z = -toRadians(this.userData['rotation']); this.scale.set(this.viewScale * this.userData['scale']); this.children.forEach((node) => { node.update(); }); } }
{ "end_byte": 3124, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/components/views/angular.ts" }
angular/adev/src/app/features/home/services/home-animation.service.ts_0_1503
/*! * @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} from '@angular/common'; import {DestroyRef, Injectable, inject} from '@angular/core'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {RESIZE_EVENT_DELAY, WEBGL_LOADED_DELAY, WINDOW} from '@angular/docs'; import {gsap} from 'gsap'; import {ScrollTrigger} from 'gsap/ScrollTrigger'; import {fromEvent} from 'rxjs'; import {debounceTime} from 'rxjs/operators'; import {ThemeManager} from '../../../core/services/theme-manager.service'; import {Canvas} from '../components/canvas'; import {View} from '../components/views/view'; import { BREAKPOINT, BUILD_TEXT, CANVAS, LINES_DIV, LINES_TEXT, LOADED_CLASS_NAME, MAX_APP_WIDTH, MOVING_LOGO, SCALE_DIV, SCALE_TEXT, WEBGL_CLASS_NAME, } from '../home-animation-constants'; /** * Injectable service for the WebGL animation of the home page. * * This class contains your usual script for GSAP animations, however it's been extended with a * number of classes and utilities that follow a simple MVC design pattern of views and programs * for OGL. * * A view is an OGL `Transform`, the `userData: View["userData"]` object is used for the GSAP animation, * and the `update` method applies the values to the `Transform`. * * @see {@link Canvas} for the controller class implementation. */
{ "end_byte": 1503, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/services/home-animation.service.ts" }
angular/adev/src/app/features/home/services/home-animation.service.ts_1504_9385
@Injectable() export class HomeAnimation { private readonly destroyRef = inject(DestroyRef); private readonly document = inject(DOCUMENT); private readonly window = inject(WINDOW); private readonly themeManager = inject(ThemeManager); private scale = 1; private progress = 0; private logoMovement = 0; private logoAnimation!: gsap.core.Timeline; private logoProgress = 0; private logoProgressTarget = 0; private lerpSpeed = 0.1; private canvas!: Canvas; private gradientView!: View['userData']; private gradient!: View['userData']; private angularView!: View['userData']; private wordmark!: View['userData']; private glyphs!: View[]; private logo!: View['userData']; private logoInner!: View['userData']; private angular!: View['userData']; private linesContainer!: View['userData']; private lines!: View['userData']; private buildView!: View['userData']; private element!: HTMLDivElement; private animations: Array<gsap.core.Animation> = []; private refreshRate = 60; private playbackRate = 1; /** * Initialize CSS styles, GSAP, the WebGL canvas and animations. */ async init(element: HTMLDivElement): Promise<void> { this.element = element; // CSS styles needed for the animation this.element.classList.add(WEBGL_CLASS_NAME); // Initialize ScrollTrigger gsap.registerPlugin(ScrollTrigger); ScrollTrigger.enable(); ScrollTrigger.config({ ignoreMobileResize: true, }); await this.initCanvas(); this.getViews(); // Call theme and resize handlers once before setting the animations this.onTheme(); this.onResize(); this.setAnimations(); // Call update handler once before starting the animation this.onUpdate(0, 0, 0, 0); this.enable(); // Workaround for the flash of white before the programs are ready setTimeout(() => { // Show the canvas this.element.classList.add(LOADED_CLASS_NAME); }, WEBGL_LOADED_DELAY); } /** * Initialize the canvas controller. */ private async initCanvas(): Promise<void> { this.canvas = new Canvas(this.document.querySelector(CANVAS)!, this.document, this.window); await this.canvas.ready(); } /** * Get the views. */ private getViews(): void { this.gradientView = this.canvas.gradient.userData; this.gradient = this.canvas.gradient.background.userData; this.angularView = this.canvas.angular.userData; this.wordmark = this.canvas.angular.wordmark.userData; this.glyphs = this.canvas.angular.wordmark.children.slice(); this.logo = this.glyphs[0].userData; this.logoInner = this.glyphs[1].userData; this.angular = this.glyphs.slice(2).map((glyph) => glyph.userData); this.linesContainer = this.canvas.lines.container.userData; this.lines = this.canvas.lines.container.children .slice(0, -1) // Skip the last child, the instanced mesh .map((line) => line.userData); this.buildView = this.canvas.build.userData; } /** * Set the animations. */ private setAnimations(): void { this.animations = [ ...this.setLogoAnimation(), this.setWorksAtAnyScaleAnimation(), ...this.setColorfulLinesAnimation(), this.setLovedByMillionsAnimation(), this.setBuildForEveryoneAnimation(), this.setBuildForEveryoneGradientAnimation(), this.setScrollProgressAnimation(), ]; } /** * Gradient, logo icon and "Angular" letters animation. */ private setLogoAnimation(): Array<gsap.core.Animation> { // Gradient and logo movement to the right const movementAnimation = gsap.timeline({ scrollTrigger: { trigger: MOVING_LOGO, start: 'center bottom', end: 'center center', scrub: 0.5, invalidateOnRefresh: true, }, }); movementAnimation.fromTo( [this.gradientView, this.wordmark], { x: 0, }, { x: () => this.logoMovement, ease: 'none', }, ); // "Angular" letters const lettersAnimation = gsap.timeline({ scrollTrigger: { trigger: MOVING_LOGO, start: 'center bottom', end: 'center center', scrub: 0.5, }, }); lettersAnimation.fromTo( this.angular, { opacity: 1, }, { opacity: 0, stagger: { each: 0.2, from: 'end', }, ease: 'none', }, ); // Logo icon "explosion" const logoAnimation = gsap .timeline({paused: true}) .to(this.gradientView, {scale: 10, duration: 1, ease: 'power1.in'}) .to(this.logo, {scale: 40, duration: 1, ease: 'power1.in'}, 0) .to(this.logo, {rotation: -270, duration: 1, ease: 'power1.in'}, 0) .to(this.logo, {progress: 1, duration: 0.25, ease: 'power1.in'}, 0) .to(this.logoInner, {scale: 0, opacity: 0, duration: 0.25, ease: 'power1.out'}, 0) .set(this.angularView, {visible: false}, 0.8); // Logo progress used for icon "transformation" const logoProgressAnimation = gsap.timeline({ scrollTrigger: { trigger: MOVING_LOGO, start: 'center center', end: () => `bottom+=${this.document.body.clientHeight} bottom`, scrub: 0.5, onUpdate: ({progress}) => { if (progress > 0.25) { this.logoProgressTarget = progress; } else if (progress > 0.125) { this.logoProgressTarget = 0.25; } else { this.logoProgressTarget = 0; } }, }, }); // Logo animation is scrubbed by the `onUpdate` method this.logoAnimation = logoAnimation; return [movementAnimation, lettersAnimation, logoAnimation, logoProgressAnimation]; } /** * "Works at any scale" animation. */ private setWorksAtAnyScaleAnimation(): gsap.core.Animation { const scaleTextAnimation = gsap.timeline({ scrollTrigger: { trigger: MOVING_LOGO, start: 'center+=10% center', end: () => `bottom+=${this.document.body.clientHeight} bottom`, scrub: 0.5, }, }); scaleTextAnimation.fromTo( SCALE_TEXT, {scale: 0.1, opacity: 0}, {scale: 1, opacity: 1, duration: 1, ease: 'power1.in'}, ); // "Works at any scale" fade out animation scaleTextAnimation.to(SCALE_TEXT, {scale: 1.3, opacity: 0, delay: 0.8}); return scaleTextAnimation; } /** * Colorful lines animation. */ private setColorfulLinesAnimation(): Array<gsap.core.Animation> { const linesAnimation = gsap.timeline({ scrollTrigger: { trigger: SCALE_DIV, start: 'top+=18% bottom', end: () => `bottom+=${this.document.body.clientHeight * 2} bottom`, scrub: 0.5, }, }); linesAnimation .fromTo( this.lines, { x: 3, y: 4, scale: 0, opacity: 0, }, { x: 0, y: 0, scale: 1, opacity: 1, duration: 1, stagger: { each: 0.05, from: 'random', }, ease: 'power1.out', }, 0, ) .set(this.linesContainer, {opacity: 1}, 0); // Lines fade out animation linesAnimation.to(this.linesContainer, { x: -1.5, y: -2, opacity: 0, ease: 'power1.in', }); // Lines progress used for camera zoom const linesProgressAnimation = gsap.timeline({ scrollTrigger: { trigger: SCALE_DIV, start: 'top+=18% bottom', end: () => `bottom+=${this.document.body.clientHeight * 2} bottom`, scrub: 0.5, }, }); linesProgressAnimation.to(this.canvas, {linesProgress: 1, duration: 1, ease: 'none'}); return [linesAnimation, linesProgressAnimation]; } /** * "Loved by millions" animation. */
{ "end_byte": 9385, "start_byte": 1504, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/services/home-animation.service.ts" }
angular/adev/src/app/features/home/services/home-animation.service.ts_9388_15010
private setLovedByMillionsAnimation(): gsap.core.Animation { const linesTextAnimation = gsap.timeline({ scrollTrigger: { trigger: SCALE_DIV, start: 'bottom bottom', end: () => `bottom+=${this.document.body.clientHeight * 2} bottom`, scrub: 0.5, }, }); linesTextAnimation.fromTo(LINES_TEXT, {scale: 0.8, opacity: 0}, {scale: 1, opacity: 1}); // "Loved by millions" fade out animation linesTextAnimation.to(LINES_TEXT, {scale: 1.3, opacity: 0, delay: 0.8}); return linesTextAnimation; } /** * "Build for everyone" animation. */ private setBuildForEveryoneAnimation(): gsap.core.Animation { const buildTextAnimation = gsap.timeline({ scrollTrigger: { trigger: LINES_DIV, start: 'bottom bottom', end: () => `bottom+=${this.document.body.clientHeight * 2} bottom`, scrub: 0.5, }, }); buildTextAnimation .fromTo(BUILD_TEXT, {scale: 0.8, opacity: 0}, {scale: 1, opacity: 1}) .fromTo(this.buildView, {scale: 0.8, opacity: 0}, {scale: 1, opacity: 1}, 0); return buildTextAnimation; } /** * "Build for everyone" gradient animation. */ private setBuildForEveryoneGradientAnimation(): gsap.core.Animation { const buildTextGradientAnimation = gsap.timeline({ scrollTrigger: { trigger: LINES_DIV, start: 'bottom bottom', end: () => `bottom+=${this.document.body.clientHeight * 2} bottom`, scrub: 0.5, }, }); buildTextGradientAnimation.fromTo(this.gradient, {progress: 0}, {progress: 1}, 0); return buildTextGradientAnimation; } /** * Scroll progress animation. */ private setScrollProgressAnimation(): gsap.core.Animation { const scrollProgressAnimation = gsap.timeline({ scrollTrigger: { trigger: '.adev-home', start: 'top top', end: 'bottom bottom', scrub: 0.5, onUpdate: ({progress}) => { this.progress = progress; }, }, }); // Initial values scrollProgressAnimation.set(this.angularView, {visible: true, immediateRender: true}); return scrollProgressAnimation; } /** * Add event handlers. */ private addListeners(): void { // TODO: This doesn't unsubscribe because of https://github.com/angular/angular/issues/50221 // We need to update angular this.themeManager.themeChanged$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => { this.onTheme(); }); fromEvent(this.window, 'resize') .pipe(debounceTime(RESIZE_EVENT_DELAY), takeUntilDestroyed(this.destroyRef)) .subscribe(() => { this.onResize(); }); gsap.ticker.add(this.onUpdate); } /** * Remove event handlers. */ private removeListeners(): void { gsap.ticker.remove(this.onUpdate); } /** * Theme event handler. */ private onTheme(): void { this.canvas.theme(); } /** * Resize event handler. */ private onResize(): void { let width = this.window.innerWidth; const height = this.document.body.clientHeight; const dpr = this.window.devicePixelRatio; if (width > MAX_APP_WIDTH) { width = MAX_APP_WIDTH; } if (width < BREAKPOINT) { this.scale = 0.5; } else { this.scale = width / 1470; } this.canvas.resize(width, height, dpr, this.scale); if (width < BREAKPOINT) { this.logoMovement = 136; } else { this.logoMovement = 272 * this.scale; } // "Build for everyone" gradient is the same width as the heading gsap.set(this.gradient, {buildWidth: this.canvas.build.text.userData['width']}); ScrollTrigger.refresh(); } /** * Update event handler. * An arrow function is required for binding to the listener. */ private onUpdate: gsap.TickerCallback = (time: number, deltaTime: number, frame: number) => { this.playbackRate = this.refreshRate / (1000 / deltaTime); this.logoProgress = gsap.utils.interpolate( this.logoProgress, this.logoProgressTarget, this.lerpSpeed * this.playbackRate, ); this.logoAnimation.progress(this.logoProgress); this.canvas.update(time, deltaTime, frame, this.progress); // TODO: add support for class fields arrow function // Using disable-next-line to avoid tslint errors - An arrow function is required for binding to the listener // tslint:disable-next-line:semicolon }; /** * Starts the WebGL animation. */ private enable(): void { this.addListeners(); } /** * Stops the WebGL animation. */ private disable(): void { this.removeListeners(); } /** * Disables the animation at the end of the page. */ disableEnd(footerEntry: IntersectionObserverEntry | undefined): void { if (!footerEntry) { return; } // Note: the views disable themselves based on opacity: // `this.visible = this.userData['opacity'] > 0;` if (footerEntry.isIntersecting) { gsap?.set([this.gradientView, this.buildView], {opacity: 0}); } else if (this.progress > 0.8) { gsap?.set([this.gradientView, this.buildView], {opacity: 1}); } } /** * Destroys the animations, removes the listeners, CSS classes and releases the objects for * garbage collection. */ destroy(): void { this.element.classList.remove(LOADED_CLASS_NAME); this.element.classList.remove(WEBGL_CLASS_NAME); this.disable(); ScrollTrigger.disable(); this.animations.forEach((animation) => animation.kill()); this.animations = []; this.canvas.destroy(); } }
{ "end_byte": 15010, "start_byte": 9388, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/home/services/home-animation.service.ts" }
angular/adev/src/app/features/tutorial/tutorial.component.ts_0_8784
/*! * @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 {isPlatformBrowser, NgComponentOutlet, NgTemplateOutlet} from '@angular/common'; import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, computed, ElementRef, EnvironmentInjector, inject, PLATFORM_ID, Signal, signal, Type, ViewChild, } from '@angular/core'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import { ClickOutside, DocContent, DocViewer, IconComponent, NavigationItem, NavigationList, } from '@angular/docs'; import {ActivatedRoute, RouterLink} from '@angular/router'; import {filter} from 'rxjs/operators'; import {PagePrefix} from '../../core/enums/pages'; import {injectAsync} from '../../core/services/inject-async'; import { EmbeddedTutorialManager, LoadingStep, NodeRuntimeState, EmbeddedEditor, } from '../../editor/index'; import {SplitResizerHandler} from './split-resizer-handler.service'; import {TutorialType} from '@angular/docs'; import {TutorialNavigationData, TutorialNavigationItem} from '@angular/docs'; const INTRODUCTION_LABEL = 'Introduction'; @Component({ selector: 'adev-tutorial', standalone: true, imports: [ NgComponentOutlet, NgTemplateOutlet, DocViewer, NavigationList, ClickOutside, RouterLink, IconComponent, ], templateUrl: './tutorial.component.html', styleUrls: [ './tutorial.component.scss', './tutorial-navigation.scss', './tutorial-navigation-list.scss', ], changeDetection: ChangeDetectionStrategy.OnPush, providers: [SplitResizerHandler], }) export default class Tutorial implements AfterViewInit { @ViewChild('content') content!: ElementRef<HTMLDivElement>; @ViewChild('editor') editor: ElementRef<HTMLDivElement> | undefined; @ViewChild('resizer') resizer!: ElementRef<HTMLDivElement>; @ViewChild('revealAnswerButton') readonly revealAnswerButton: ElementRef<HTMLButtonElement> | undefined; private readonly changeDetectorRef = inject(ChangeDetectorRef); private readonly environmentInjector = inject(EnvironmentInjector); private readonly elementRef = inject(ElementRef<unknown>); private readonly embeddedTutorialManager = inject(EmbeddedTutorialManager); private readonly nodeRuntimeState = inject(NodeRuntimeState); private readonly platformId = inject(PLATFORM_ID); private readonly route = inject(ActivatedRoute); private readonly splitResizerHandler = inject(SplitResizerHandler); readonly documentContent = signal<string | null>(null); readonly localTutorialZipUrl = signal<string | undefined>(undefined); readonly nextTutorialPath = signal<string | null>(null); readonly stepName = signal<string | null>(null); readonly tutorialName = signal<string | null>(null); readonly tutorialNavigationItems = signal<NavigationItem[]>([]); readonly showNavigationDropdown = signal<boolean>(false); readonly shouldRenderContent = signal<boolean>(false); readonly shouldRenderEmbeddedEditor = signal<boolean>(false); readonly shouldRenderRevealAnswer = signal<boolean>(false); nextStepPath: string | undefined; previousStepPath: string | undefined; embeddedEditorComponent?: Type<unknown>; canRevealAnswer: Signal<boolean> = signal(false); readonly answerRevealed = signal<boolean>(false); constructor() { this.route.data .pipe( filter(() => Boolean(this.route?.routeConfig?.path?.startsWith(`${PagePrefix.TUTORIALS}/`)), ), takeUntilDestroyed(), ) .subscribe((data) => { const docContent = (data['docContent'] as DocContent | undefined)?.contents ?? null; this.documentContent.set(docContent); this.setTutorialData(data as TutorialNavigationItem); }); } async ngAfterViewInit(): Promise<void> { if (isPlatformBrowser(this.platformId)) { this.splitResizerHandler.init(this.elementRef, this.content, this.resizer, this.editor); this.loadEmbeddedEditorComponent().then((editorComponent) => { this.embeddedEditorComponent = editorComponent; this.changeDetectorRef.markForCheck(); }); } } toggleNavigationDropdown($event: MouseEvent): void { // Stop propagation required to avoid detecting click inside ClickOutside // directive. $event.stopPropagation(); this.showNavigationDropdown.update((state) => !state); } hideNavigationDropdown(): void { this.showNavigationDropdown.set(false); } async handleRevealAnswer() { if (!this.canRevealAnswer()) return; this.embeddedTutorialManager.revealAnswer(); const nodeRuntimeSandbox = await injectAsync(this.environmentInjector, () => import('../../editor/index').then((s) => s.NodeRuntimeSandbox), ); await Promise.all( Object.entries(this.embeddedTutorialManager.answerFiles()).map(([path, contents]) => nodeRuntimeSandbox.writeFile(path, contents as string | Uint8Array), ), ); this.answerRevealed.set(true); } async handleResetAnswer() { if (!this.canRevealAnswer()) return; this.embeddedTutorialManager.resetRevealAnswer(); const nodeRuntimeSandbox = await injectAsync(this.environmentInjector, () => import('../../editor/index').then((s) => s.NodeRuntimeSandbox), ); await Promise.all( Object.entries(this.embeddedTutorialManager.tutorialFiles()).map(([path, contents]) => nodeRuntimeSandbox.writeFile(path, contents as string | Uint8Array), ), ); this.answerRevealed.set(false); } /** * Set tutorial data based on current tutorial */ private async setTutorialData(tutorialNavigationItem: TutorialNavigationItem): Promise<void> { this.showNavigationDropdown.set(false); this.answerRevealed.set(false); this.setRouteData(tutorialNavigationItem); const {tutorialData: routeData} = tutorialNavigationItem; if (routeData.type === TutorialType.LOCAL) { this.setLocalTutorialData(routeData); } else if (routeData.type === TutorialType.EDITOR && isPlatformBrowser(this.platformId)) { await this.setEditorTutorialData( tutorialNavigationItem.path.replace(`${PagePrefix.TUTORIALS}/`, ''), ); } } /** * Set tutorial data from route data */ private setRouteData(tutorialNavigationItem: TutorialNavigationItem) { const {tutorialData: routeData} = tutorialNavigationItem; const tutorialName = tutorialNavigationItem.parent ? tutorialNavigationItem.parent.label : tutorialNavigationItem.label; const stepName = routeData.title === tutorialName ? INTRODUCTION_LABEL : routeData.title; this.tutorialName.set(tutorialName); this.stepName.set(stepName); this.tutorialNavigationItems.set( tutorialNavigationItem.parent ? [{...tutorialNavigationItem.parent, label: INTRODUCTION_LABEL}] : [{...tutorialNavigationItem, label: INTRODUCTION_LABEL}], ); this.shouldRenderContent.set(routeData.type !== TutorialType.EDITOR_ONLY); this.nextStepPath = routeData.nextStep ? `/${routeData.nextStep}` : undefined; this.previousStepPath = routeData.previousStep ? `/${routeData.previousStep}` : undefined; this.nextTutorialPath.set(routeData.nextTutorial ? `/${routeData.nextTutorial}` : null); } /** * Set values for tutorials that do not use the embedded editor */ private setLocalTutorialData(routeData: TutorialNavigationData) { this.localTutorialZipUrl.set(routeData.sourceCodeZipPath); this.shouldRenderEmbeddedEditor.set(false); this.shouldRenderRevealAnswer.set(false); } /** * Set values for tutorials that use the embedded editor */ private async setEditorTutorialData(tutorialPath: string) { this.shouldRenderEmbeddedEditor.set(true); const currentTutorial = tutorialPath.replace(`${PagePrefix.TUTORIALS}/`, ''); await this.embeddedTutorialManager.fetchAndSetTutorialFiles(currentTutorial); const hasAnswers = Object.keys(this.embeddedTutorialManager.answerFiles()).length > 0; this.shouldRenderRevealAnswer.set(hasAnswers); await this.loadEmbeddedEditor(); } private async loadEmbeddedEditor() { const nodeRuntimeSandbox = await injectAsync(this.environmentInjector, () => import('../../editor/index').then((s) => s.NodeRuntimeSandbox), ); this.canRevealAnswer = computed(() => this.nodeRuntimeState.loadingStep() > LoadingStep.BOOT); await nodeRuntimeSandbox.init(); } private async loadEmbeddedEditorComponent(): Promise<typeof EmbeddedEditor> { return await import('../../editor/index').then((c) => c.EmbeddedEditor); } }
{ "end_byte": 8784, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/tutorial/tutorial.component.ts" }
angular/adev/src/app/features/tutorial/tutorial.component.spec.ts_0_6210
/*! * @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 {DOCS_VIEWER_SELECTOR, DocViewer, WINDOW} from '@angular/docs'; import {Component, Input, signal} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {RouterTestingModule} from '@angular/router/testing'; import {of} from 'rxjs'; import { EMBEDDED_EDITOR_SELECTOR, EmbeddedEditor, EmbeddedTutorialManager, NodeRuntimeSandbox, } from '../../editor'; import {mockAsyncProvider} from '../../core/services/inject-async'; import Tutorial from './tutorial.component'; import {TutorialConfig, TutorialType} from '@angular/docs'; @Component({ selector: EMBEDDED_EDITOR_SELECTOR, template: '<div>FakeEmbeddedEditor</div>', standalone: true, }) class FakeEmbeddedEditor {} @Component({ selector: DOCS_VIEWER_SELECTOR, template: '<div>FakeDocsViewer</div>', standalone: true, }) class FakeDocViewer { @Input('documentFilePath') documentFilePath: string | undefined; } // TODO: export this class, it's a helpful mock we could you on other tests. class FakeNodeRuntimeSandbox { loadingStep = signal(0); previewUrl$ = of(); writeFile(path: string, content: string) { return Promise.resolve(); } init() { return Promise.resolve(); } } describe('Tutorial', () => { let component: Tutorial; let fixture: ComponentFixture<Tutorial>; const fakeWindow = { addEventListener: () => {}, removeEventListener: () => {}, }; const fakeEmbeddedTutorialManager: Partial<EmbeddedTutorialManager> = { tutorialFiles: signal({'app.component.ts': 'original'}), answerFiles: signal({'app.component.ts': 'answer'}), type: signal(TutorialType.EDITOR), revealAnswer: () => {}, resetRevealAnswer: () => {}, tutorialChanged$: of(false), openFiles: signal<NonNullable<TutorialConfig['openFiles']>>(['app.component.ts']), }; function setupRevealAnswerValues() { component['shouldRenderRevealAnswer'].set(true); component['canRevealAnswer'] = signal(true); component['embeddedTutorialManager'].answerFiles.set({'app.component.ts': 'answer'}); } function setupDisabledRevealAnswerValues() { component['shouldRenderRevealAnswer'].set(true); component['canRevealAnswer'] = signal(false); component['embeddedTutorialManager'].answerFiles.set({'app.component.ts': 'answer'}); } function setupNoRevealAnswerValues() { component['shouldRenderRevealAnswer'].set(false); component['canRevealAnswer'] = signal(true); component['embeddedTutorialManager'].answerFiles.set({}); } function setupResetRevealAnswerValues() { setupRevealAnswerValues(); component['answerRevealed'].set(true); } beforeEach(async () => { TestBed.configureTestingModule({ imports: [Tutorial, RouterTestingModule, EmbeddedEditor, DocViewer, NoopAnimationsModule], providers: [ { provide: WINDOW, useValue: fakeWindow, }, { provide: EmbeddedTutorialManager, useValue: fakeEmbeddedTutorialManager, }, mockAsyncProvider(NodeRuntimeSandbox, FakeNodeRuntimeSandbox), ], }); TestBed.overrideComponent(Tutorial, { remove: { imports: [DocViewer], }, add: { imports: [FakeDocViewer], }, }); await TestBed.compileComponents(); fixture = TestBed.createComponent(Tutorial); component = fixture.componentInstance; // Replace EmbeddedEditor with FakeEmbeddedEditor spyOn(component as any, 'loadEmbeddedEditorComponent').and.resolveTo(FakeEmbeddedEditor); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); // TODO: Add tests in a future PR // it('should render the embedded editor based on the tutorial config', () => {}); // it('should not render the embedded editor based on the tutorial config', () => {}); // it('should load the tutorial', () => {}); it('should reset the reveal answer', async () => { setupResetRevealAnswerValues(); fixture.detectChanges(); if (!component.revealAnswerButton) throw new Error('revealAnswerButton is undefined'); const revealAnswerSpy = spyOn(component['embeddedTutorialManager'], 'revealAnswer'); const resetRevealAnswerSpy = spyOn(component['embeddedTutorialManager'], 'resetRevealAnswer'); component.revealAnswerButton.nativeElement.click(); expect(revealAnswerSpy).not.toHaveBeenCalled(); expect(resetRevealAnswerSpy).toHaveBeenCalled(); }); it('should reveal the answer on button click', async () => { setupRevealAnswerValues(); fixture.detectChanges(); if (!component.revealAnswerButton) throw new Error('revealAnswerButton is undefined'); const embeddedTutorialManagerRevealAnswerSpy = spyOn( component['embeddedTutorialManager'], 'revealAnswer', ); component.revealAnswerButton.nativeElement.click(); expect(embeddedTutorialManagerRevealAnswerSpy).toHaveBeenCalled(); await fixture.whenStable(); fixture.detectChanges(); expect(component.revealAnswerButton.nativeElement.textContent?.trim()).toBe('Reset'); }); it('should not reveal the answer when button is disabled', async () => { setupDisabledRevealAnswerValues(); fixture.detectChanges(); if (!component.revealAnswerButton) throw new Error('revealAnswerButton is undefined'); spyOn(component, 'canRevealAnswer').and.returnValue(false); const handleRevealAnswerSpy = spyOn(component, 'handleRevealAnswer'); component.revealAnswerButton.nativeElement.click(); expect(component.revealAnswerButton.nativeElement.getAttribute('disabled')).toBeDefined(); expect(handleRevealAnswerSpy).not.toHaveBeenCalled(); }); it('should not render the reveal answer button when there are no answers', () => { setupNoRevealAnswerValues(); fixture.detectChanges(); expect(component.revealAnswerButton).toBe(undefined); }); });
{ "end_byte": 6210, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/tutorial/tutorial.component.spec.ts" }
angular/adev/src/app/features/tutorial/tutorials-route-reuse-strategy.ts_0_1306
/*! * @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 {ActivatedRouteSnapshot, BaseRouteReuseStrategy} from '@angular/router'; // Match tutorial pages, apart of /tutorials. export const IS_TUTORIAL_PAGE_RULE = /(^tutorials)\/(\S*)/s; export class ReuseTutorialsRouteStrategy extends BaseRouteReuseStrategy { // reuse route when not navigating to a new one or when navigating between tutorial pages override shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { return ( future.routeConfig === curr.routeConfig || (this.isTutorialPage(this.getPathFromActivatedRouteSnapshot(future)) && this.isTutorialPage(this.getPathFromActivatedRouteSnapshot(curr))) ); } private isTutorialPage(path: string | undefined): boolean { if (!path) { return false; } return IS_TUTORIAL_PAGE_RULE.test(path); } private getPathFromActivatedRouteSnapshot(snapshot: ActivatedRouteSnapshot): string | undefined { let route: ActivatedRouteSnapshot = snapshot; while (route.firstChild) { route = route.firstChild; } return route.routeConfig?.path; } }
{ "end_byte": 1306, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/tutorial/tutorials-route-reuse-strategy.ts" }
angular/adev/src/app/features/tutorial/tutorial-navigation.scss_0_3247
@use '@angular/docs/styles/media-queries' as mq; // horizontal tutorial nav bar .adev-tutorial-nav-container { position: sticky; top: 0; @include mq.for-tablet-landscape-down { top: 60px; } @include mq.for-phone-only { top: 55px; } width: 100%; background-color: var(--page-background); padding-block-start: var(--layout-padding); padding-block-end: calc(1.5rem + 50px); margin-block-end: 1rem; border-block-end: 1px solid var(--septenary-contrast); z-index: var(--z-index-nav); transition: background-color 0.3s ease; container: nav-container / inline-size; &:has(.docs-reveal-answer-button) { @container tutorial-content (max-width: 430px) { padding-block-end: calc(1.5rem + 85px); } @container page-content (max-width: 430px) { padding-block-end: calc(1.5rem + 85px); } } } .adev-tutorial-nav { position: absolute; display: flex; justify-content: space-between; align-items: center; gap: 0.5rem; width: 100%; flex-wrap: wrap; z-index: var(--z-index-nav); } .adev-unfold-button { display: flex; gap: 0.5rem; align-items: center; padding-inline: 0; border: none; background-color: transparent; cursor: pointer; flex: 1; z-index: var(--z-index-nav); docs-icon { min-width: 1.5rem; color: var(--quinary-contrast); transition: color 0.2s ease-in-out; } .adev-nav-open &, &:hover { docs-icon { color: var(--primary-contrast); } } } .adev-current-tutorial { text-align: left; letter-spacing: 0.00875rem; span:first-child { margin-block-end: 0.2rem; color: var(--quaternary-contrast); display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; } span { color: var(--primary-contrast); font-weight: 500; font-size: 0.875rem; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; } } .adev-download-button { width: 2.875rem; height: 2.875rem; padding: 0; } .adev-reveal-desktop-button { @container nav-container (max-width: 430px) { display: none; } } .adev-reveal-mobile-button-container { display: flex; @container nav-container (max-width: 430px) { width: 100%; justify-content: end; } @container nav-container (min-width: 430px) { display: none; } } .docs-reveal-answer-button { height: 2.875rem; width: 120px; } .adev-reset-answer-button { background: var(--senary-contrast); transition: opacity 0.3s ease, background 0.3s ease; &:hover { background: var(--quinary-contrast); &::after { opacity: 0; } &::before { background: var(--octonary-contrast); } } } .adev-nav-arrows { display: flex; gap: 0.5rem; margin-left: auto; button { width: 2.875rem; height: 2.875rem; display: flex; justify-content: center; align-items: center; &:disabled { //gradient stroke background: var(--quinary-contrast); docs-icon { color: var(--quinary-contrast); } } docs-icon { z-index: var(--z-index-icon); color: var(--primary-contrast); } } }
{ "end_byte": 3247, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/tutorial/tutorial-navigation.scss" }
angular/adev/src/app/features/tutorial/tutorial.component.html_0_4809
<div class="adev-page-content" [class.adev-nav-open]="showNavigationDropdown()"> <ng-container *ngTemplateOutlet="tutorialNav" /> @if (shouldRenderContent()) { <div #content class="docs-tutorial-content" [class.adev-nav-open]="showNavigationDropdown()" > <!-- Tutorial Nav: Current Tutorial Title and Nav Buttons --> <ng-container *ngTemplateOutlet="tutorialNav" /> <!-- Tutorial Content --> @if (documentContent(); as documentContent) { <docs-viewer [docContent]="documentContent" class="docs-viewer docs-viewer-scroll-margin-large" /> } </div>} <!-- Split View Resizer --> <button role="separator" #resizer class="adev-tutorial-resizer" [class.adev-tutorial-resizer-hidden]="!shouldRenderEmbeddedEditor() || !shouldRenderContent()" ></button> <!-- Embedded Editor --> @if (shouldRenderEmbeddedEditor()) { <div #editor class="docs-tutorial-editor" [class.adev-split-tutorial]="shouldRenderContent()" > @if (embeddedEditorComponent) { <ng-container *ngComponentOutlet="embeddedEditorComponent" /> } </div> } </div> <!-- Tutorial Nav Template --> <ng-template #tutorialNav> <div class="adev-tutorial-nav-container"> <div class="adev-tutorial-nav" [class.adev-nav-open]="showNavigationDropdown()"> <!-- Toggle Nav Button --> <button class="adev-unfold-button" (click)="toggleNavigationDropdown($event)"> <docs-icon>unfold_more</docs-icon> <div class="adev-current-tutorial"> <span>{{ tutorialName() }}</span> <span>{{ stepName() }}</span> </div> </button> <!-- Reveal Answer Button --> @if (shouldRenderRevealAnswer()) { <button #revealAnswerButton (click)="answerRevealed() ? handleResetAnswer() : handleRevealAnswer()" [disabled]="!canRevealAnswer()" class="docs-reveal-answer-button adev-reveal-desktop-button docs-primary-btn" [attr.text]="answerRevealed() ? 'Reset' : 'Reveal Answer'" [attr.aria-label]="answerRevealed() ? 'Reset' : 'Reveal Answer'" [class.adev-reset-answer-button]="answerRevealed()" > {{ answerRevealed() ? 'Reset' : 'Reveal Answer' }} </button> } <!-- Download code --> @if (localTutorialZipUrl()) { <a [download]="stepName() + '.zip'" [href]="localTutorialZipUrl()" > <button class="adev-download-button docs-primary-btn"> <docs-icon>download</docs-icon> </button> </a> } <div class="adev-nav-arrows"> @if (previousStepPath) { <a [routerLink]="previousStepPath"> <button class="docs-primary-btn"> <docs-icon>chevron_left</docs-icon> </button> </a> } @if (!previousStepPath) { <button class="docs-primary-btn" disabled> <docs-icon>chevron_left</docs-icon> </button> } @if (nextStepPath) { <a [routerLink]="nextStepPath"> <button class="docs-primary-btn"> <docs-icon>chevron_right</docs-icon> </button> </a> } @if (!nextStepPath) { <button class="docs-primary-btn" disabled> <docs-icon>chevron_right</docs-icon> </button> } </div> <!-- Reveal Answer Button: for smaller container --> <div class="adev-reveal-mobile-button-container"> @if (shouldRenderRevealAnswer()) { <button #revealAnswerButton (click)="answerRevealed() ? handleResetAnswer() : handleRevealAnswer()" [disabled]="!canRevealAnswer()" class="docs-reveal-answer-button adev-reveal-mobile-button docs-primary-btn" [attr.text]="answerRevealed() ? 'Reset' : 'Reveal Answer'" [attr.aria-label]="answerRevealed() ? 'Reset' : 'Reveal Answer'" [class.adev-reset-answer-button]="answerRevealed()" > {{ answerRevealed() ? 'Reset' : 'Reveal Answer' }} </button> } </div> <!-- Tutorial Nav: List --> @if (showNavigationDropdown()) { <div class="adev-tutorial-nav-list-dropdown" (docsClickOutside)="hideNavigationDropdown()" > <docs-navigation-list [isDropdownView]="true" [navigationItems]="tutorialNavigationItems()" class="adev-nav-list" /> @if (nextTutorialPath()) { <a [routerLink]="'/' + nextTutorialPath()">Next Tutorial</a> } </div> } </div> </div> </ng-template>
{ "end_byte": 4809, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/tutorial/tutorial.component.html" }
angular/adev/src/app/features/tutorial/tutorial.component.scss_0_3141
@use '@angular/docs/styles/media-queries' as mq; $resizer-width: 0.0625rem; $column-width: calc(50% - #{$resizer-width} - var(--layout-padding)); .adev-page-content { display: flex; align-items: flex-start; flex-direction: row; position: relative; padding: 0 var(--layout-padding) var(--layout-padding); max-width: calc(100vw - var(--layout-padding) * 2); container: page-content / inline-size; @include mq.for-tablet-landscape-down { flex-direction: column; } // Tablet / Mobile Tutorial Nav @include mq.for-tablet-landscape-up { > .adev-tutorial-nav-container { display: none; } } // blur code editor too when nav is open &.adev-nav-open { &::after { content: ''; position: absolute; inset: 0; width: 100%; height: 100%; backdrop-filter: blur(3px); } } // if there is an embedded editor in view, apply column width &:has(.docs-tutorial-editor) { .docs-tutorial-content { width: $column-width; @include mq.for-tablet-landscape-down { // override js applied width from split view resizer width: 100% !important; } } } // if tutorial nav exists, size editor to fit vertically within viewport on mobile @include mq.for-tablet-landscape-down { &:has(.adev-tutorial-nav-container) { .docs-tutorial-editor { height: calc(100vh - 200px); } } } @include mq.for-phone-only { &:has(.adev-tutorial-nav-container) { .docs-tutorial-editor { // account for reveal answer button height when on smaller screens height: calc(100vh - 200px); } } } } .docs-tutorial-content { max-width: var(--page-width); min-width: 300px; width: 100%; box-sizing: content-box; container: tutorial-content / inline-size; z-index: var(--z-index-content); // Desktop Tutorial Nav @include mq.for-tablet-landscape-down { > .adev-tutorial-nav-container { display: none; } } &.adev-nav-open { &::after { content: ''; position: absolute; inset: 0; width: 100%; height: 100%; backdrop-filter: blur(3px); } } } .docs-viewer { padding: 0; } .adev-tutorial-resizer { position: sticky; top: var(--layout-padding); width: $resizer-width; padding-inline: 1.56rem; margin-block-start: var(--layout-padding); cursor: col-resize; align-self: stretch; height: 100vh; &::before { content: ''; position: absolute; left: calc(50% - 0.5px); top: 0; bottom: 0; background: var(--senary-contrast); transition: background 0.3s ease; width: 1px; } &-hidden { display: none; } @include mq.for-tablet-landscape-down { display: none; } } .docs-tutorial-editor { position: sticky; top: 0; width: 100%; min-width: 300px; padding-block-start: var(--layout-padding); height: 100vh; } .adev-split-tutorial { width: 50%; @include mq.for-big-desktop-up { width: 100%; } @include mq.for-tablet-landscape-down { // override js applied width from split view resizer width: 100% !important; } }
{ "end_byte": 3141, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/tutorial/tutorial.component.scss" }
angular/adev/src/app/features/tutorial/split-resizer-handler.service.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 {FocusMonitor} from '@angular/cdk/a11y'; import {DOCUMENT} from '@angular/common'; import {DestroyRef, ElementRef, Injectable, inject, signal} from '@angular/core'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {fromEvent, combineLatest} from 'rxjs'; import {map, filter, finalize} from 'rxjs/operators'; interface ResizingData { isProgress: boolean; initialContentContainerWidthInPercentage: number; initialDividerPosition: number; initialEditorContainerWidthInPercentage: number; } interface MouseEventAndEditor { event: MouseEvent; editor: ElementRef<HTMLDivElement>; } const MIN_WIDTH_OF_CONTENT_IN_PX = 300; const MAX_WIDTH_OF_CONTENT_IN_PX = 800; @Injectable() export class SplitResizerHandler { private readonly destroyRef = inject(DestroyRef); private readonly document = inject(DOCUMENT); private readonly focusMonitor = inject(FocusMonitor); private container!: ElementRef<any>; private content!: ElementRef<HTMLDivElement>; private editor: ElementRef<HTMLDivElement> | undefined; private resizer!: ElementRef<HTMLDivElement>; private readonly resizeData = signal<ResizingData>({ initialContentContainerWidthInPercentage: 0, initialDividerPosition: 0, initialEditorContainerWidthInPercentage: 0, isProgress: false, }); init( container: ElementRef<unknown>, content: ElementRef<HTMLDivElement>, resizer: ElementRef<HTMLDivElement>, editor?: ElementRef<HTMLDivElement>, ): void { this.container = container; this.content = content; this.resizer = resizer; this.editor = editor; this.listenToResizeStart(); this.listenToResize(); this.listenToResizeEnd(); this.resizeContainersUsingKeyArrows(); } private listenToResizeStart(): void { fromEvent<MouseEvent>(this.resizer.nativeElement, 'mousedown') .pipe( map((event) => ({editor: this.editor, event})), filter( (eventAndEditor): eventAndEditor is MouseEventAndEditor => !!eventAndEditor.editor?.nativeElement, ), takeUntilDestroyed(this.destroyRef), ) .subscribe(({event}) => { const contentWidthInPercentage = this.getCurrentContainerWidth(this.content.nativeElement); const editorWidthInPercentage = this.getCurrentContainerWidth(this.editor!.nativeElement); this.content.nativeElement.style.minWidth = `${MIN_WIDTH_OF_CONTENT_IN_PX}px`; this.resizeData.update((data) => { data.initialDividerPosition = event.pageX; data.isProgress = true; data.initialContentContainerWidthInPercentage = contentWidthInPercentage; data.initialEditorContainerWidthInPercentage = editorWidthInPercentage; return {...data}; }); }); } private listenToResize(): void { fromEvent<MouseEvent>(this.document, 'mousemove') .pipe( map((event) => ({editor: this.editor, event})), filter( (eventAndEditor): eventAndEditor is MouseEventAndEditor => !!eventAndEditor.editor?.nativeElement, ), takeUntilDestroyed(this.destroyRef), ) .subscribe(({event}) => { if (this.resizeData().isProgress) { const newDividerPosition = event.pageX; const containerWidth = this.getParentContainerWidth(); const shift = ((newDividerPosition - this.resizeData().initialDividerPosition) / containerWidth) * 100; const newContentWidthInPercentage = this.resizeData().initialContentContainerWidthInPercentage + shift; const newEditorWidthInPercentage = this.resizeData().initialEditorContainerWidthInPercentage - shift; this.setWidthOfTheContainers(newContentWidthInPercentage, newEditorWidthInPercentage); } }); } private listenToResizeEnd(): void { fromEvent(this.document, 'mouseup') .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe(() => { if (this.resizeData().isProgress) { this.content.nativeElement.style.minWidth = `${MIN_WIDTH_OF_CONTENT_IN_PX}px`; this.resizeData.update((data) => { data.isProgress = false; data.initialDividerPosition = 0; data.initialContentContainerWidthInPercentage = 0; data.initialEditorContainerWidthInPercentage = 0; return {...data}; }); } }); } // When resizer bar is focused, resize containers when user presses key arrows. private resizeContainersUsingKeyArrows(): void { combineLatest([ this.focusMonitor.monitor(this.resizer), fromEvent<KeyboardEvent>(this.document, 'keydown'), ]) .pipe( filter( ([origin, keyEvent]) => !!origin && (keyEvent.key === 'ArrowLeft' || keyEvent.key === 'ArrowRight'), ), takeUntilDestroyed(this.destroyRef), finalize(() => this.focusMonitor.stopMonitoring(this.resizer)), ) .subscribe(([_, keyEvent]) => { const shift = keyEvent.key === 'ArrowLeft' ? -1 : 1; const contentWidth = this.getCurrentContainerWidth(this.content.nativeElement); const editorWidth = this.getCurrentContainerWidth(this.editor!.nativeElement); this.setWidthOfTheContainers(contentWidth + shift, editorWidth - shift); }); } private setWidthOfTheContainers( newContentWidthInPercentage: number, newEditorWidthInPercentage: number, ) { const containerWidth = this.container.nativeElement.offsetWidth; const newContentWidthInPx = (containerWidth * newContentWidthInPercentage) / 100; if ( newContentWidthInPx > MIN_WIDTH_OF_CONTENT_IN_PX && newContentWidthInPx < MAX_WIDTH_OF_CONTENT_IN_PX && this.editor ) { this.content.nativeElement.style.width = `${newContentWidthInPercentage}%`; this.editor.nativeElement.style.width = `${newEditorWidthInPercentage}%`; } } private getCurrentContainerWidth(element: HTMLDivElement): number { const savedWidth = Number(element.style.width.replace('%', '')); return savedWidth > 0 ? savedWidth : (element.offsetWidth / this.getParentContainerWidth()) * 100; } private getParentContainerWidth(): number { return ( this.resizer.nativeElement.offsetWidth + this.content.nativeElement.offsetWidth + this.editor!.nativeElement.offsetWidth ); } }
{ "end_byte": 6662, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/tutorial/split-resizer-handler.service.ts" }
angular/adev/src/app/features/tutorial/tutorial-navigation-list.scss_0_1665
@use '@angular/docs/styles/media-queries' as mq; .adev-tutorial-nav-list-dropdown { background-color: var(--page-background); border: 1px solid var(--senary-contrast); border-radius: 0.25rem; z-index: var(--z-index-nav); margin-top: 1rem; width: 100%; box-shadow: 10px 4px 40px 0 rgba(0, 0, 0, 0.05); display: flex; flex-direction: column; @container tutorial-content (max-width: 430px) { margin-top: 0; } ul { padding-block-end: 1rem; } // "Next Tutorial" link a { position: sticky; display: flex; align-items: center; justify-content: flex-end; color: var(--gray-400); background-color: var(--page-background); border-block-start: 1px solid var(--senary-contrast); border-radius: 0 0 0.25rem 0.25rem; text-align: right; padding: 1rem; font-size: 0.875rem; transition: color 0.3s ease; &:hover { color: var(--primary-contrast); background-color: var(--octonary-contrast); } &::after { content: 'chevron_right'; font-family: var(--icons); font-size: 1.3rem; margin-inline-start: 0.2rem; } } } .adev-nav-list { height: max-content; max-height: calc(var(--fixed-content-height) - var(--layout-padding) - 67px); padding-block-start: 1rem; padding-block-end: 0; @container tutorial-content (max-width: 430px) { max-height: calc(var(--fixed-content-height) - var(--layout-padding) - 105px); } @include mq.for-tablet-landscape-down { max-height: calc(var(--fixed-content-height) - var(--layout-padding) - 167px); } &::-webkit-scrollbar-thumb { background-color: var(--senary-contrast); } }
{ "end_byte": 1665, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/tutorial/tutorial-navigation-list.scss" }
angular/adev/src/app/features/update/update.component.scss_0_1880
.page { padding: var(--layout-padding); max-width: var(--page-width); container: update-guide-page / inline-size; } h3, h4 { margin-block-start: 2em; } .wizard { padding-inline: 1rem; .show-button { display: block; margin-block-start: 2rem; } } .adev-version-selector { display: flex; gap: 1rem; } .adev-template-dropdown { border: 1px solid var(--senary-contrast); border-radius: 0.25rem; padding: 0; transform: translateY(-0.7rem); max-height: 200px; overflow-y: auto; li { list-style: none; width: 198px; box-sizing: border-box; button { background: var(--page-background); font-size: 0.875rem; width: 100%; text-align: left; padding-block: 0.5rem; color: var(--quaternary-contrast); transition: color 0.3s ease, background 0.3s ease; font-weight: 400; &:hover { background: var(--senary-contrast); color: var(--primary-contrast); } } } } .adev-template-select { margin-block-end: 0.5rem; // cdk select button button { font-size: 0.875rem; border: 1px solid var(--senary-contrast); border-radius: 0.25rem; width: 200px; display: inline-flex; justify-content: space-between; align-items: center; padding-block: 0.5rem; font-weight: 400; transition: border 0.3s ease; span { color: var(--primary-contrast); transition: color 0.3s ease; margin-inline-start: 0.1rem; } docs-icon { font-size: 1.3rem; color: var(--quaternary-contrast); transition: color 0.3s ease; } } } .adev-recommentation-item { display: flex; align-items: center; > div { margin-inline-start: 2rem; } // Code blocks are generable from the markdown, we need to opt-out of the scoping ::ng-deep code { cursor: pointer; } }
{ "end_byte": 1880, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/update.component.scss" }
angular/adev/src/app/features/update/update.component.html_0_6159
<div class="page docs-viewer"> <h1 tabindex="-1">Update Guide</h1> <div class="wizard"> <div> <h2>Select the options that match your update</h2> <h3>Angular versions</h3> <div class="adev-version-selector"> <span class="adev-template-select"> From v. <button [cdkMenuTriggerFor]="templatesMenuFrom"> <span>{{ from.name }}</span> <docs-icon>expand_more</docs-icon> </button> <ng-template #templatesMenuFrom> <ul class="adev-template-dropdown" cdkMenu> @for (version of versions; track $index) { <li> <button cdkMenuItem type="button" (click)="from=version; showUpdatePath()"> <span>{{ version.name }}</span> </button> </li> } </ul> </ng-template> </span> <span> <span class="adev-template-select"> To v. <button [cdkMenuTriggerFor]="templatesMenuTo"> <span>{{ to.name }}</span> <docs-icon>expand_more</docs-icon> </button> <ng-template #templatesMenuTo> <ul class="adev-template-dropdown" cdkMenu> @for (version of versions; track $index) { <li> <button cdkMenuItem type="button" (click)="to=version; showUpdatePath()"> <span>{{ version.name }}</span> </button> </li> } </ul> </ng-template> </span> </span> </div> @if (from.number >= futureVersion || to.number >= futureVersion) { <div class="docs-alert docs-alert-critical"> <p> <strong>Warning:</strong> Plans for releases after the current major release are not finalized and may change. These recommendations are based on scheduled deprecations. </p> </div> } @if (from.number > to.number) { <div class="docs-alert docs-alert-critical"> <p> <strong>Warning:</strong> We do not support downgrading versions of Angular. </p> </div> } @if ((to.number - from.number > 150) && from.number > 240) { <div class="docs-alert docs-alert-critical"> <p> <strong>Warning:</strong> Be sure to follow the guide below to migrate your application to the new version. You can't run <code>ng update</code> to update Angular applications more than one major version at a time. </p> </div> } <h3>Application complexity</h3> <mat-button-toggle-group (change)="level = $event.value;" [value]="level" style="margin-bottom:16px;" > <mat-button-toggle [value]="1">Basic</mat-button-toggle> <mat-button-toggle [value]="2">Medium</mat-button-toggle> <mat-button-toggle [value]="3">Advanced</mat-button-toggle> </mat-button-toggle-group> @if (level === 1) { <p>Shows information for all Angular developers.</p> } @else if (level === 2) { <p>Shows information that's of interest to more advanced Angular developers.</p> } @else if (level === 3) { <p>Shows all the information we have about this update.</p> } <h3>Other dependencies</h3> @for (option of optionList; track $index) { <div> <mat-checkbox (change)="options[option.id] = $event.checked; showUpdatePath()" [checked]="options[option.id]" >I use {{option.name}} {{option.description}}</mat-checkbox > </div> } @if (from.number < 600) { <h4>Package Manager</h4> <mat-button-toggle-group (change)="packageManager = $event.value; showUpdatePath()" [value]="packageManager" > <mat-button-toggle value="npm install">npm</mat-button-toggle> <mat-button-toggle value="yarn add">yarn</mat-button-toggle> </mat-button-toggle-group> } <button type="button" (click)="showUpdatePath()" class="docs-primary-btn show-button" [attr.text]="'Show me how to update!'" > Show me how to update! </button> </div> </div> <hr /> <!-- RECOMMENDATIONS SECTION --> @if ( beforeRecommendations.length > 0 || duringRecommendations.length > 0 || afterRecommendations.length > 0 ) { <div class="recommendations"> <h2>{{title}}</h2> <h3>Before you update</h3> @for (r of beforeRecommendations; track $index) { <div class="adev-recommentation-item"> <mat-checkbox></mat-checkbox> <div [innerHTML]="r.renderedStep"></div> </div> } @if (beforeRecommendations.length <= 0) { <div> <em>You don't need to do anything before moving between these versions.</em> </div> } <h3>Update to the new version</h3> @if (duringRecommendations.length > 0) { <div> <em>Review these changes and perform the actions to update your application.</em> </div> } @for (r of duringRecommendations; track $index) { <div class="adev-recommentation-item"> <mat-checkbox></mat-checkbox> <div [innerHTML]="r.renderedStep"></div> </div> } @if (duringRecommendations.length <= 0) { <div> <em>There aren't any recommendations for moving between these versions.</em> </div> } <h3>After you update</h3> @for (r of afterRecommendations; track $index) { <div class="adev-recommentation-item"> <mat-checkbox></mat-checkbox> <div [innerHTML]="r.renderedStep"></div> </div> } @if (afterRecommendations.length <= 0) { <div> <em>You don't need to do anything after moving between these versions.</em> </div> } </div> } </div>
{ "end_byte": 6159, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/update.component.html" }
angular/adev/src/app/features/update/recommendations.ts_0_352
export enum ApplicationComplexity { Basic = 1, Medium = 2, Advanced = 3, } export interface Step { step: string; action: string; possibleIn: number; necessaryAsOf: number; level: ApplicationComplexity; angularCLI?: boolean; ngUpgrade?: boolean; pwa?: boolean; material?: boolean; renderedStep?: string; windows?: boolean; }
{ "end_byte": 352, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_354_7669
export const RECOMMENDATIONS: Step[] = [ { possibleIn: 200, necessaryAsOf: 400, level: ApplicationComplexity.Basic, step: 'Extends OnInit', action: "Ensure you don't use `extends OnInit`, or use `extends` with any lifecycle event. Instead use `implements <lifecycle event>.`", }, { possibleIn: 200, necessaryAsOf: 400, level: ApplicationComplexity.Advanced, step: 'Deep Imports', action: 'Stop using deep imports, these symbols are now marked with ɵ and are not part of our public API.', }, { possibleIn: 200, necessaryAsOf: 400, level: ApplicationComplexity.Advanced, step: 'invokeElementMethod', action: 'Stop using `Renderer.invokeElementMethod` as this method has been removed. There is not currently a replacement.', }, { possibleIn: 400, necessaryAsOf: 400, level: ApplicationComplexity.Basic, step: 'Non Animations Module', action: 'If you use animations in your application, you should import `BrowserAnimationsModule` from `@angular/platform-browser/animations` in your App `NgModule`.', }, { possibleIn: 400, necessaryAsOf: 400, level: ApplicationComplexity.Medium, step: 'Native Form Validation', action: 'Angular began adding a `novalidate` attribute to form elements when you include `FormsModule`. To re-enable native forms behaviors, use `ngNoForm` or add `ngNativeValidate`.', }, { possibleIn: 400, necessaryAsOf: 400, level: ApplicationComplexity.Advanced, step: 'RootRenderer', action: 'Replace `RootRenderer` with `RendererFactoryV2` instead.', }, { possibleIn: 400, necessaryAsOf: 400, level: ApplicationComplexity.Advanced, ngUpgrade: true, step: 'downgradeInjectable', action: 'The return value of `upgrade/static/downgradeInjectable` has changed.', }, { possibleIn: 400, necessaryAsOf: 400, level: ApplicationComplexity.Advanced, step: 'Animations Tests', action: 'If you use Animations and tests, add `mods[1].NoopAnimationsModule` to your `TestBed.initTestEnvironment` call.', }, { possibleIn: 200, necessaryAsOf: 500, level: ApplicationComplexity.Advanced, step: 'DefaultIterableDiffer', action: 'Stop using `DefaultIterableDiffer`, `KeyValueDiffers#factories`, or `IterableDiffers#factories`', }, { possibleIn: 400, necessaryAsOf: 500, level: ApplicationComplexity.Basic, step: 'Template Tag', action: 'Rename your `template` tags to `ng-template`', }, { possibleIn: 400, necessaryAsOf: 500, level: ApplicationComplexity.Medium, step: 'OpaqueToken', action: 'Replace any `OpaqueToken` with `InjectionToken`.', }, { possibleIn: 400, necessaryAsOf: 500, level: ApplicationComplexity.Advanced, step: 'DifferFactory', action: 'If you call `DifferFactory.create(...)` remove the `ChangeDetectorRef` argument.', }, { possibleIn: 400, necessaryAsOf: 500, level: ApplicationComplexity.Advanced, step: 'ErrorHandler Parameter', action: 'Stop passing any arguments to the constructor for ErrorHandler', }, { possibleIn: 400, necessaryAsOf: 500, level: ApplicationComplexity.Advanced, step: 'ngProbeToken', action: 'If you use ngProbeToken, make sure you import it from @angular/core instead of @angular/platform-browser', }, { possibleIn: 400, necessaryAsOf: 500, level: ApplicationComplexity.Advanced, step: 'TrackByFn', action: 'If you use TrackByFn, instead use TrackByFunction', }, { possibleIn: 500, necessaryAsOf: 500, level: ApplicationComplexity.Basic, step: 'i18n Pipe Change', action: 'If you rely on the date, currency, decimal, or percent pipes, in 5 you will see minor changes to the format. For applications using locales other than en-us you will need to import it and optionally `locale_extended_fr` from `@angular/common/i18n_data/locale_fr` and registerLocaleData(local).', }, { possibleIn: 500, necessaryAsOf: 500, level: ApplicationComplexity.Advanced, step: 'gendir', action: 'Do not rely on `gendir`, instead look at using `skipTemplateCodeGen`. <a href=https://github.com/angular/angular/issues/19339#issuecomment-332607471" target="_blank">Read More</a>', }, { possibleIn: 220, necessaryAsOf: 600, level: ApplicationComplexity.Basic, ngUpgrade: true, step: 'Dynamic ngUpgrade', action: 'Replace `downgradeComponent`, `downgradeInjectable`, `UpgradeComponent`, and `UpgradeModule` imported from `@angular/upgrade`. Instead use the new versions in `@angular/upgrade/static`', }, { possibleIn: 400, necessaryAsOf: 600, level: ApplicationComplexity.Medium, step: 'Animations in Core', action: 'If you import any animations services or tools from @angular/core, you should import them from @angular/animations', }, { possibleIn: 400, necessaryAsOf: 600, level: ApplicationComplexity.Advanced, step: 'ngOutletContext', action: 'Replace `ngOutletContext` with `ngTemplateOutletContext`.', }, { possibleIn: 400, necessaryAsOf: 600, level: ApplicationComplexity.Advanced, step: 'collectionChangeRecord', action: 'Replace `CollectionChangeRecord` with `IterableChangeRecord`', }, { possibleIn: 400, necessaryAsOf: 900, level: ApplicationComplexity.Advanced, step: 'Renderer', action: 'Anywhere you use Renderer, now use Renderer2', }, { possibleIn: 400, necessaryAsOf: 600, level: ApplicationComplexity.Advanced, step: 'Router Query Params', action: 'If you use preserveQueryParams, instead use queryParamsHandling', }, { possibleIn: 430, necessaryAsOf: 800, level: ApplicationComplexity.Basic, step: 'Http', action: "If you use the legacy `HttpModule` and the `Http` service, switch to `HttpClientModule` and the `HttpClient` service. HttpClient simplifies the default ergonomics (you don't need to map to JSON anymore) and now supports typed return values and interceptors. Read more on [angular.dev](https://angular.io/guide/http).", }, { possibleIn: 430, necessaryAsOf: 600, level: ApplicationComplexity.Advanced, step: 'DOCUMENT in @angular/platform-browser', action: 'If you use DOCUMENT from @angular/platform-browser, you should start to import this from @angular/common', }, { possibleIn: 500, necessaryAsOf: 600, level: ApplicationComplexity.Advanced, step: 'ReflectiveInjector', action: 'Anywhere you use ReflectiveInjector, now use StaticInjector', }, { possibleIn: 500, necessaryAsOf: 550, level: ApplicationComplexity.Medium, step: 'Whitespace', action: 'Choose a value of `off` for `preserveWhitespaces` in your `tsconfig.json` under the `angularCompilerOptions` key to gain the benefits of this setting, which was set to `off` by default in v6.', }, { possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Basic, step: 'node 8', action: 'Make sure you are using <a href="http://www.hostingadvice.com/how-to/update-node-js-latest-version/" target="_blank">Node 8 or later</a>', },
{ "end_byte": 7669, "start_byte": 354, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_7672_15014
possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Basic, windows: false, step: 'Update to CLI v6', action: 'Update your Angular CLI, and migrate the configuration to the <a href="https://github.com/angular/angular-cli/wiki/angular-workspace" target="_blank">new angular.json format</a> by running the following:<br/><br/>`NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@6 update @angular/cli@6`<br/>', }, { possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Basic, windows: true, step: 'Update to CLI v6', action: 'Update your Angular CLI, and migrate the configuration to the <a href="https://github.com/angular/angular-cli/wiki/angular-workspace" target="_blank">new angular.json format</a> by running the following:<br/><br/>`cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@6 update @angular/cli@6 @angular/core@6"`<br/>', }, { possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Medium, step: 'cli v6 scripts', action: 'Update any `scripts` you may have in your `package.json` to use the latest Angular CLI commands. All CLI commands now use two dashes for flags (eg `ng build --prod --source-map`) to be POSIX compliant.', }, { possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Basic, windows: false, step: 'Update to Angular v6', action: "Update all of your Angular framework packages to v6, and the correct version of RxJS and TypeScript.<br/><br/>`NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@6 update @angular/core@6`<br/><br/>After the update, TypeScript and RxJS will more accurately flow types across your application, which may expose existing errors in your application's typings", }, { possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Basic, windows: true, step: 'Update to Angular v6', action: 'Update all of your Angular framework packages to v6, and the correct version of RxJS and TypeScript.<br/><br/>`cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@6 update @angular/cli@6 @angular/core@6"`<br/><br/>After the update, TypeScript and RxJS will more accurately flow types across your application, which may expose existing errors in your application\'s typings', }, { possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Advanced, step: 'forms v6', action: 'In Angular Forms, `AbstractControl#statusChanges` now emits an event of `PENDING` when you call `AbstractControl#markAsPending`. Ensure that if you are filtering or checking events from `statusChanges` that you account for the new event when calling `markAsPending`.', }, { possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Advanced, step: 'animations timing', action: 'If you use totalTime from an `AnimationEvent` within a disabled Zone, it will no longer report a time of 0. To detect if an animation event is reporting a disabled animation then the `event.disabled` property can be used instead.', }, { possibleIn: 600, necessaryAsOf: 700, level: ApplicationComplexity.Advanced, step: 'ngModel on form control', action: 'Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in v6 and removed in v7.', }, { possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Medium, step: 'ngModelChange order', action: 'ngModelChange is now emitted after the value/validity is updated on its control instead of before to better match expectations. If you rely on the order of these events, you will need to begin tracking the old value in your component.', }, { possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Basic, windows: false, material: true, step: 'Update Dependencies for v6', action: 'Update Angular Material to the latest version.<br/><br/>`NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@6 update @angular/material@6`<br/><br/>This will also automatically migrate deprecated APIs.', }, { possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Basic, windows: true, material: true, step: 'Update Dependencies for v6', action: 'Update Angular Material to the latest version.<br/><br/>`cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@6 update @angular/material@6"`<br/><br/>This will also automatically migrate deprecated APIs.', }, { possibleIn: 600, necessaryAsOf: 600, level: ApplicationComplexity.Medium, step: 'strictPropertyInitializer', action: 'If you have TypeScript configured to be strict (if you have set `strict` to `true` in your `tsconfig.json` file), update your `tsconfig.json` to disable `strictPropertyInitialization` or move property initialization from `ngOnInit` to your constructor. You can learn more about this flag on the <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#strict-class-initialization">TypeScript 2.7 release notes</a>.', }, { possibleIn: 600, necessaryAsOf: 700, level: ApplicationComplexity.Basic, step: 'update to RxJS 6', action: 'Remove deprecated RxJS 5 features using <a href="https://github.com/ReactiveX/rxjs-tslint" target="_blank">rxjs-tslint auto update rules</a><br/><br/>For most applications this will mean running the following two commands:<br/><br/>`npx rxjs-tslint`<br/>`rxjs-5-to-6-migrate -p src/tsconfig.app.json`', }, { possibleIn: 600, necessaryAsOf: 800, level: ApplicationComplexity.Medium, step: 'remove rxjs-compat', action: 'Once you and all of your dependencies have updated to RxJS 6, remove `rxjs-compat`.', }, { possibleIn: 610, necessaryAsOf: 800, level: ApplicationComplexity.Medium, step: 'use files instead of versionedFiles', action: 'If you use the Angular Service worker, migrate any `versionedFiles` to the `files` array. The behavior is the same.', }, { possibleIn: 700, necessaryAsOf: 700, level: ApplicationComplexity.Basic, step: 'TypeScript 3.1', action: 'Angular now uses TypeScript 3.1, read more about any potential breaking changes: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html', }, { possibleIn: 700, necessaryAsOf: 700, level: ApplicationComplexity.Basic, step: 'Node 10', action: 'Angular has now added support for Node 10: https://nodejs.org/en/blog/release/v10.0.0/', }, { possibleIn: 700, necessaryAsOf: 700, level: ApplicationComplexity.Basic, windows: false, step: 'v7 update', action: 'Update to v7 of the core framework and CLI by running `NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@7 update @angular/cli@7 @angular/core@7` in your terminal.', }, { possibleIn: 700, necessaryAsOf: 700, level: ApplicationComplexity.Basic, windows: true, step: 'v7 update', action: 'Update to v7 of the core framework and CLI by running `cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@7 update @angular/cli@7 @angular/core@7"` in your terminal.', },
{ "end_byte": 15014, "start_byte": 7672, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_15017_22555
possibleIn: 700, necessaryAsOf: 700, level: ApplicationComplexity.Basic, windows: false, material: true, step: 'v7 material update', action: 'Update Angular Material to v7 by running `NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@7 update @angular/material@7` in your terminal. You should test your application for sizing and layout changes.', }, { possibleIn: 700, necessaryAsOf: 700, level: ApplicationComplexity.Basic, windows: true, material: true, step: 'v7 material update', action: 'Update Angular Material to v7 by running `cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@7 update @angular/material@7"` in your terminal. You should test your application for sizing and layout changes.', }, { possibleIn: 700, necessaryAsOf: 700, level: ApplicationComplexity.Medium, material: true, step: 'v7 material changes', action: "If you use screenshot tests, you'll need to regenerate your screenshot golden files as many minor visual tweaks have landed.", }, { possibleIn: 700, necessaryAsOf: 800, level: ApplicationComplexity.Advanced, material: true, step: 'v7 material deprecations', action: 'Stop using `matRippleSpeedFactor` and `baseSpeedFactor` for ripples, using Animation config instead.', }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Basic, windows: false, step: 'v8 update', action: 'Update to version 8 of the core framework and CLI by running `NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@8 update @angular/cli@8 @angular/core@8` in your terminal and review and commit the changes.', }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Basic, windows: true, step: 'v8 update', action: 'Update to version 8 of the core framework and CLI by running `cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@8 update @angular/cli@8 @angular/core@8"` in your terminal and review and commit the changes.', }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Basic, step: 'use ::ng-deep instead of /deep/', action: 'Replace `/deep/` with `::ng-deep` in your styles, [read more about angular component styles and ::ng-deep](https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep). `/deep/` and `::ng-deep` both are deprecated but using `::ng-deep` is preferred until the shadow-piercing descendant combinator is [removed from browsers and tools](https://www.chromestatus.com/features/6750456638341120) completely.', }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Basic, step: 'TypeScript 3.4', action: 'Angular now uses TypeScript 3.4, [read more about errors that might arise from improved type checking](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html).', }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Basic, step: 'node 10', action: 'Make sure you are using <a href="http://www.hostingadvice.com/how-to/update-node-js-latest-version/" target="_blank">Node 10 or later</a>.', }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Basic, step: 'Differential Loading', action: "The CLI's build command now automatically creates a modern ES2015 build with minimal polyfills and a compatible ES5 build for older browsers, and loads the appropriate file based on the browser. You may opt-out of this change by setting your `target` back to `es5` in your `tsconfig.json`. Learn more on [angular.io](https://angular.io/guide/deployment#differential-loading).", }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Basic, step: 'CLI Telemetry', action: 'When using new versions of the CLI, you will be asked if you want to opt-in to share your CLI usage data. You can also add your own Google Analytics account. This lets us make better decisions about which CLI features to prioritize, and measure the impact of our improvements. Learn more on [angular.io](https://angular.io/analytics).', }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Basic, step: 'static query timing', action: "If you use `ViewChild` or `ContentChild`, we're updating the way we resolve these queries to give developers more control. You must now specify that change detection should run before results are set. Example: `@ContentChild('foo', {static: false}) foo !: ElementRef;`. `ng update` will update your queries automatically, but it will err on the side of making your queries `static` for compatibility. Learn more on [angular.io](https://angular.io/guide/static-query-migration).", }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Basic, windows: false, material: true, step: 'v8 material update', action: 'Update Angular Material to version 8 by running `NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@8 update @angular/material@8` in your terminal.', }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Basic, windows: true, material: true, step: 'v8 material update', action: 'Update Angular Material to version 8 by running `cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@8 update @angular/material@8"` in your terminal.', }, { possibleIn: 800, necessaryAsOf: 900, level: ApplicationComplexity.Basic, material: true, step: 'deep imports', action: 'Instead of importing from `@angular/material`, you should import deeply from the specific component. E.g. `@angular/material/button`. `ng update` will do this automatically for you.', }, { possibleIn: 800, necessaryAsOf: 900, level: ApplicationComplexity.Basic, step: 'new loadChildren', action: 'For lazy loaded modules via the router, make sure you are [using dynamic imports](https://angular.io/guide/deprecations#loadchildren-string-syntax). Importing via string is removed in v9. `ng update` should take care of this automatically. Learn more on [angular.io](https://angular.io/guide/deprecations#loadchildren-string-syntax).', }, { possibleIn: 800, necessaryAsOf: 900, level: ApplicationComplexity.Advanced, step: 'platform deprecated', action: "We are deprecating support for `@angular/platform-webworker`, as it has been incompatible with the CLI. Running Angular's rendering architecture in a web worker did not meet developer needs. You can still use web workers with Angular. Learn more in our [web worker guide](https://v9.angular.io/guide/web-worker). If you have use cases where you need this, let us know at [email protected]!", }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Advanced, step: 'node-sass', action: 'We have switched from the native Sass compiler to the JavaScript compiler. To switch back to the native version, install it as a devDependency: `npm install node-sass --save-dev`.', }, { possibleIn: 800, necessaryAsOf: 800, level: ApplicationComplexity.Advanced, step: 'schematics async', action: 'If you are building your own Schematics, they have previously been *potentially* asynchronous. As of 8.0, all schematics will be asynchronous.', },
{ "end_byte": 22555, "start_byte": 15017, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_22558_29862
possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Basic, step: 'node 10.13', action: 'Make sure you are using <a href="http://www.hostingadvice.com/how-to/update-node-js-latest-version/" target="_blank">Node 10.13 or later</a>.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Basic, windows: false, step: 'cli v8 latest', action: 'Run `NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@8 update @angular/core@8 @angular/cli@8` in your workspace directory to update to the latest 8.x version of `@angular/core` and `@angular/cli` and commit these changes.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Basic, windows: true, step: 'cli v8 latest', action: 'Run `cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@8 update @angular/cli@8 @angular/core@8"` in your workspace directory to update to the latest 8.x version of `@angular/core` and `@angular/cli` and commit these changes.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Medium, step: 'create commits', action: 'You can optionally pass the `--create-commits` (or `-C`) flag to [ng update](https://angular.io/cli/update) commands to create a git commit per individual migration.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Basic, windows: false, step: 'ng update v9', action: 'Run `NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@9 update @angular/core@9 @angular/cli@9` which should bring you to version 9 of Angular.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Basic, windows: true, step: 'ng update v9', action: 'Run `cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@9 update @angular/cli@9 @angular/core@9"` which should bring you to version 9 of Angular.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Basic, step: 'typescript 3.8', action: 'Your project has now been updated to TypeScript 3.8, read more about new compiler checks and errors that might require you to fix issues in your code in the [TypeScript 3.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html) or [TypeScript 3.8](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html) announcements.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Basic, windows: false, material: true, step: 'update @angular/material', action: 'Run `NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@9 update @angular/material@9`.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Basic, windows: true, material: true, step: 'update @angular/material', action: 'Run `cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@9 update @angular/material@9"`.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Advanced, windows: false, step: 'update @nguniversal/hapi-engine', action: 'If you use Angular Universal, run `NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@9 update @nguniversal/hapi-engine@9` or `NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@9 update @nguniversal/express-engine@9` depending on the engine you use. This step may require the `--force` flag if any of your third-party dependencies have not updated the Angular version of their peer dependencies.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Advanced, windows: true, step: 'update @nguniversal/hapi-engine', action: 'If you use Angular Universal, run `cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@9 update @nguniversal/hapi-engine@9"` or `cmd /C "set "NG_DISABLE_VERSION_CHECK=1" && npx @angular/cli@9 update @nguniversal/express-engine@9"` depending on the engine you use. This step may require the `--force` flag if any of your third-party dependencies have not updated the Angular version of their peer dependencies.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Basic, step: 'dependencies update', action: 'If your project depends on other Angular libraries, we recommend that you consider updating to their latest version. In some cases this update might be required in order to resolve API incompatibilities. Consult `ng update` or `npm outdated` to learn about your outdated libraries.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Basic, step: 'ivy update', action: 'During the update to version 9, your project was transformed as necessary via code migrations in order to remove any incompatible or deprecated API calls from your code base. You can now review these changes, and consult the [Updating to version 9 guide](https://v9.angular.io/guide/updating-to-version-9) to learn more about the changes.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Medium, step: 'stylesUpdate', action: 'Bound CSS styles and classes previously were applied with a "last change wins" strategy, but now follow a defined precedence. Learn more about [Styling Precedence](https://angular.io/guide/attribute-binding#styling-precedence).', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Advanced, step: 'ModuleWithProviders', action: 'If you are a library author and you had a method returning `ModuleWithProviders` (typically via a method named `forRoot()`), you will need to specify the generic type. Learn more [angular.io](https://v9.angular.io/guide/deprecations#modulewithproviders-type-without-a-generic)', }, { possibleIn: 800, necessaryAsOf: 900, level: ApplicationComplexity.Advanced, step: 'wtf', action: 'Support for web tracing framework in Angular was deprecated in version 8. You should stop using any of the `wtf*` APIs. To do performance tracing, we recommend using [browser performance tools](https://developers.google.com/web/tools/lighthouse/audits/user-timing).', }, { possibleIn: 800, necessaryAsOf: 900, level: ApplicationComplexity.Medium, step: 'es5browser', action: 'Remove any `es5BrowserSupport` flags in your `angular.json` and set your `target` to `es2015` in your `tsconfig.json`. Angular now uses your browserslist to determine if an ES5 build is needed. `ng update` will migrate you automatically.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Medium, step: 'ngForm selector', action: 'If you use `ngForm` element selector to create Angular Forms, you should instead use `ng-form`.', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Advanced, step: 'typings compilation', action: 'We have updated the `tsconfig.app.json` to limit the files compiled. If you rely on other files being included in the compilation, such as a `typings.d.ts` file, you need to manually add it to the compilation.', },
{ "end_byte": 29862, "start_byte": 22558, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_29865_37335
possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'debug', action: 'With Angular 9 Ivy is now the default rendering engine, for any compatibility problems that might arise, read the [Ivy compatibility guide](https://v9.angular.io/guide/ivy-compatibility).', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Advanced, step: 'express-universal-server', action: 'If you use Angular Universal with `@nguniversal/express-engine` or `@nguniversal/hapi-engine`, several backup files will be created. One of them for `server.ts`. If this file defers from the default one, you may need to copy some changes from the `server.ts.bak` to `server.ts` manually.', }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Basic, step: 'ivy i18n', action: "Angular 9 introduced a global `$localize()` function that needs to be loaded if you depend on Angular's internationalization (i18n). Run `ng add @angular/localize` to add the necessary packages and code modifications. Consult the [$localize Global Import Migration guide](https://v9.angular.io/guide/migration-localize) to learn more about the changes.", }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'entryComponents', action: 'In your application projects, you can remove `entryComponents` NgModules and any uses of `ANALYZE_FOR_ENTRY_COMPONENTS`. They are no longer required with the Ivy compiler and runtime. You may need to keep these if building a library that will be consumed by a View Engine application.', }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'testbed-get', action: 'If you use `TestBed.get`, you should instead use `TestBed.inject`. This new method has the same behavior, but is type safe.', }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: '$localize', action: "If you use [Angular's i18n support](http://angular.io/guide/i18n), you will need to begin using `@angular/localize`. Learn more about the [$localize Global Import Migration](https://v9.angular.io/guide/migration-localize).", }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Basic, step: 'v10 NodeJS 12', action: 'Make sure you are using <a href="https://nodejs.org/dist/latest-v12.x/" target="_blank">Node 12 or later</a>.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Basic, step: 'ng update v10', action: 'Run `npx @angular/cli@10 update @angular/core@10 @angular/cli@10` which should bring you to version 10 of Angular.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `npx @angular/cli@10 update @angular/material@10`.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Basic, step: 'browserlist', action: 'New projects use the filename `.browserslistrc` instead of `browserslist`. `ng update` will migrate you automatically.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'v10-versions', action: 'Angular now requires `tslint` v6, `tslib` v2, and [TypeScript 3.9](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-9.html). `ng update` will migrate you automatically.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Advanced, step: 'styleext', action: 'Stop using `styleext` or `spec` in your Angular schematics. `ng update` will migrate you automatically.', }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'classes-without-decorators', action: 'In version 10, classes that use Angular features and do not have an Angular decorator are no longer supported. [Read more](https://v10.angular.io/guide/migration-undecorated-classes). `ng update` will migrate you automatically.', }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'injectable-definitions', action: 'As of Angular 9, enforcement of @Injectable decorators for DI is stricter and incomplete provider definitions behave differently. [Read more](https://v9.angular.io/guide/migration-injectable). `ng update` will migrate you automatically.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Advanced, step: 'closure-jsdoc-comments', action: "Angular's NPM packages no longer contain jsdoc comments, which are necessary for use with closure compiler (extremely uncommon). This support was experimental and only worked in some use cases. There will be an alternative recommended path announced shortly.", }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'forms-number-input', action: 'If you use Angular forms, inputs of type `number` no longer listen to [change events](https://developer.mozilla.org/docs/Web/API/HTMLElement/change_event) (this events are not necessarily fired for each alteration the value), instead listen for an [input events](https://developer.mozilla.org/docs/Web/API/HTMLElement/input_event). ', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'forms-length-input', action: "For Angular forms validation, the `minLength` and `maxLength` validators now verify that the form control's value has a numeric length property, and only validate for length if that's the case.", }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'esm5-bundles', action: "The [Angular Package Format](https://g.co/ng/apf) has been updated to remove `esm5` and `fesm5` formats. These are no longer distributed in our npm packages. If you don't use the CLI, you may need to downlevel Angular code to ES5 yourself.", }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'console-errors', action: "Warnings about unknown elements are now logged as errors. This won't break your app, but it may trip up tools that expect nothing to be logged via `console.error`.", }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Advanced, step: 'router-resolver-empty', action: 'Any resolver which returns `EMPTY` will cancel navigation. If you want to allow navigation to continue, you will need to update the resolvers to emit some value, (i.e. `defaultIfEmpty(...)`, `of(...)`, etc).', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Advanced, step: 'sw-vary-headers', action: 'If you use the Angular service worker and rely on resources with [Vary](https://developer.mozilla.org/docs/Web/HTTP/Headers/Vary) headers, these headers are now ignored to avoid unpredictable behavior across browsers. To avoid this, [configure](https://angular.io/guide/service-worker-config) your service worker to avoid caching these resources.', },
{ "end_byte": 37335, "start_byte": 29865, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_37338_45322
possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'expression-changed-after-checked-new', action: 'You may see `ExpressionChangedAfterItHasBeenChecked` errors that were not detected before when using the `async` pipe. The error could previously have gone undetected because two `WrappedValues` are considered "equal" in all cases for the purposes of the check, even if their respective unwrapped values are not. In version 10, `WrappedValue` has been removed.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Advanced, step: 'property-binding-change-detection', action: 'If you have a property binding such as `[val]=(observable | async).someProperty`, this will no longer trigger change detection if the value of `someProperty` is identical to the previous emit. If you rely on this, either manually subscribe and call `markForCheck` as needed or update the binding to ensure the reference changes.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Advanced, step: 'day-periods-crossing-midnight', action: 'If you use either `formatDate()` or `DatePipe` and any of the `b` or `B` format codes, the logic has been updated so that it matches times that are within a day period that spans midnight, so it will now render the correct output, such as at `night` in the case of English.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Advanced, step: 'urlmatcher-null', action: 'If you use the `UrlMatcher`, the type now reflects that it could always return `null`.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Basic, step: 'v10-more-details', action: 'For more details about deprecations, automated migrations, and changes visit the [guide angular.io](https://v10.angular.io/guide/updating-to-version-10)', }, { possibleIn: 1020, necessaryAsOf: 1020, level: ApplicationComplexity.Medium, step: 'universal-baseurl', action: 'For Angular Universal users, if you use `useAbsoluteUrl` to setup `platform-server`, you now need to also specify `baseUrl`.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Basic, step: 'v11 ng update', action: 'Run `ng update @angular/core@11 @angular/cli@11` which should bring you to version 11 of Angular.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `ng update @angular/material@11`.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Basic, step: 'v11 versions', action: 'Angular now requires [TypeScript 4.0](https://devblogs.microsoft.com/typescript/announcing-typescript-4-0/). `ng update` will migrate you automatically.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Basic, step: 'v11 browser support', action: 'Support for IE9, IE10, and IE mobile has been removed. This was announced in the [v10 update](http://blog.angular.dev/version-10-of-angular-now-available-78960babd41#c357). ', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Medium, step: 'webpack5 optin', action: 'You can now opt-in to use webpack 5 by using Yarn and adding `"resolutions": {"webpack": "^5.0.0"}` to your `package.json`.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Medium, step: 'ng new strict prompt', action: 'When generating new projects, you will be asked if you want to enable strict mode. This will configure TypeScript and the Angular compiler for stricter type checking, and apply smaller bundle budgets by default. You can use the `--strict=true` or `--strict=false` to skip the prompt.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'v11 router relativeLinkResolution', action: "If you use the router, the default value of `relativeLinkResolution` has changed from `legacy` to `corrected`. If your application previously used the default by not specifying a value in the `ExtraOptions` and uses relative links when navigating from children of empty path routes, you will need to update your `RouterModule`'s configuration to specifically specify `legacy` for `relativeLinkResolution`. See [the documentation](https://v11.angular.io/api/router/ExtraOptions#relativeLinkResolution) for more details.", }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'router initialNavigation', action: 'In the Angular Router, the options deprecated in v4 for `initialNavigation` have been removed. If you previously used `enabled` or `true`, now choose `enabledNonBlocking` or `enabledBlocking`. If you previously used `false` or `legacy_disabled`, now use `disabled`.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Medium, step: 'routerlink preserveQueryParams', action: 'In the Angular Router\'s `routerLink`, `preserveQueryParams` has been removed, use `queryParamsHandling="preserve"` instead.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'routerlink queryParams typing', action: 'If you were accessing the `routerLink` values of `queryParams`, `fragment` or `queryParamsHandling` you might need to relax the typing to also accept `undefined` and `null`.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'viewencapsulation native removed', action: 'The component view encapsulation option `ViewEncapsulation.Native` has been removed. Use `ViewEncapsulation.ShadowDom` instead. `ng update` will migrate you automatically.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'ICU expressions typechecked', action: 'If you use i18n, expressions within International Components for Unicode (ICUs) expressions are now type-checked again. This may cause compilation failures if errors are found in expressions that appear within an ICU. ', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'forms validators asyncValidators typing', action: "Directives in the `@angular/forms` package used to have `any[]` as the type of the expected `validators` and `asyncValidators` arguments in constructors. Now these arguments are properly typed, so if your code relies on form's directive constructor types it may require some updates to improve type safety.", }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'forms AbstractFormControl', action: "If you use Angular Forms, the type of `AbstractFormControl.parent` now includes null. `ng update` will migrate you automatically, but in an unlikely case your code was testing the parent against undefined with strict equality, you'll need to change this to `=== null` instead, since the parent is now explicitly initialized with `null` instead of being left undefined.", }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'platform-webworker', action: 'The rarely used `@angular/platform-webworker` and `@angular/platform-webworker-dynamic` were deprecated in v8 and have been removed. Running parts of Angular in a web worker was an experiment that never worked well for common use cases. Angular still has great support for [Web Workers](https://angular.io/guide/web-worker). ', },
{ "end_byte": 45322, "start_byte": 37338, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_45325_52931
possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'v11 slice pipe typing', action: 'The `slice` pipe now returns null for the undefined input value, which is consistent with the behavior of most pipes.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'v11 keyvalue typing', action: 'The `keyvalue` pipe has been fixed to report that for input objects that have number keys, the result type will contain the string representation of the keys. This was already the case and the code has simply been updated to reflect this. Please update the consumers of the pipe output if they were relying on the incorrect types. Note that this does not affect use cases where the input values are `Map`s, so if you need to preserve `number`s, this is an effective way.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'v11 number pipe typing', action: 'The number pipes (`decimal`, `percent`, `currency`, etc) now explicitly state which types are accepted.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'v11 date pipe typing', action: 'The `date` pipe now explicitly states which types are accepted.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'v11 datetime rounding', action: 'When passing a date-time formatted string to the `DatePipe` in a format that contains fractions of a millisecond, the milliseconds will now always be rounded down rather than to the nearest millisecond. Most applications will not be affected by this change. If this is not the desired behaviour then consider pre-processing the string to round the millisecond part before passing it to the `DatePipe`.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'v11 async pipe typing', action: 'The `async` pipe no longer claims to return undefined for an input that was typed as undefined. Note that the code actually returned null on undefined inputs.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Medium, step: 'v11 case pipe update', action: 'The `uppercase` and `lowercase` pipes no longer let falsy values through. They now map both `null` and `undefined` to `null` and raise an exception on invalid input (`0`, `false`, `NaN`). This matches other Angular pipes.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'v11 router NavigationExtras typing', action: 'If you use the router with `NavigationExtras`, new typings allow a variable of type `NavigationExtras` to be passed in, but they will not allow object literals, as they may only specify known properties. They will also not accept types that do not have properties in common with the ones in the `Pick`. If you are affected by this change, only specify properties from the NavigationExtras which are actually used in the respective function calls or use a type assertion on the object or variable: `as NavigationExtras`.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Medium, step: 'v11 TestBed.overrideProvider', action: 'In your tests if you call `TestBed.overrideProvider` after TestBed initialization, provider overrides are no longer applied. This behavior is consistent with other override methods (such as `TestBed.overrideDirective`, etc) but they throw an error to indicate that. The check was previously missing in the TestBed.overrideProvider function. If you see this error, you should move `TestBed.overrideProvider` calls before TestBed initialization is completed.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Medium, step: 'v11 router RouteReuseStrategy', action: "If you use the Router's RouteReuseStrategy, the argument order has changed. When calling `RouteReuseStrategy#shouldReuseRoute` previously when evaluating child routes, they would be called with the `future` and `current` arguments swapped. If your `RouteReuseStrategy` relies specifically on only the future or current snapshot state, you may need to update the `shouldReuseRoute` implementation's use of `future` and `current` `ActivateRouteSnapshots`.", }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'v11 locale data readonly', action: 'If you use locale data arrays, this API will now return readonly arrays. If you were mutating them (e.g. calling `sort()`, `push()`, `splice()`, etc) then your code will not longer compile. If you need to mutate the array, you should now take a copy (e.g. by calling `slice()`) and mutate the copy.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Advanced, step: 'v11 CollectionChangeRecord', action: 'In change detection, `CollectionChangeRecord` has been removed, use `IterableChangeRecord` instead.', }, { possibleIn: 1100, necessaryAsOf: 1100, level: ApplicationComplexity.Medium, step: 'v11 forms async validators', action: 'If you use Angular Forms with async validators defined at initialization time on class instances of `FormControl`, `FormGroup` or `FormArray` , the status change event was not previously emitted once async validator completed. This has been changed so that the status event is emitted into the `statusChanges` observable. If your code relies on the old behavior, you can filter/ignore this additional status change event.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Basic, step: 'v12 ng update', action: 'Run `ng update @angular/core@12 @angular/cli@12` which should bring you to version 12 of Angular.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `ng update @angular/material@12`.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Basic, step: 'v12 versions', action: 'Angular now requires [TypeScript 4.2](https://devblogs.microsoft.com/typescript/announcing-typescript-4-2/). `ng update` will update you automatically.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Basic, step: 'v12 browser support', action: 'IE11 support has been deprecated. Find details in the [RFC for IE11 removal](https://github.com/angular/angular/issues/41840).', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Basic, step: 'v12 minimum Node.js version', action: 'You can no longer use Angular with Node.js version 10 or older', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Medium, step: 'v12 `XhrFactory` relocation', action: 'Change the import of `XhrFactory` from `@angular/common/http` to `@angular/common`.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Medium, step: 'v12 i18n message ids', action: 'If you rely on legacy i18n message IDs use the `localize-migrate` tool to [move away from them](https://angular.io/guide/migration-legacy-message-id).', },
{ "end_byte": 52931, "start_byte": 45325, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_52934_60217
possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Medium, step: 'v12 deprecates `emitDistinctChangesOnly`', action: 'If you are using `emitDistinctChangesOnly` to configure `@ContentChildren` and `@ViewChildren` queries, you may need to update its value to `false` to align with its previous behavior. In v12 `emitDistinctChangesOnly` has default value `true`, and in future releases we will remove this configuration option to prevent triggering of unnecessary changes.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Medium, step: 'v12 prod by default', action: 'You can run the optional migration for enabling production builds by default `ng update @angular/cli@12 --migrate-only production-by-default`.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Advanced, step: 'v12 min and max form attributes', action: 'If you use Angular forms, `min` and `max` attributes on `<input type="number">` will now trigger validation logic.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Advanced, step: 'v12 `emitEvent` in `FormArray` and `FormGroup`', action: 'If your app has custom classes that extend `FormArray` or `FormGroup` classes and override the above-mentioned methods, you may need to update your implementation', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Advanced, step: 'v12 zone.js minimum version', action: 'Update zone.js to version 0.11.4. `ng update` will update this dependency automatically.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Advanced, step: 'v12 `HttpParams` method params update', action: 'If you extend the `HttpParams` class you may have to update the signature of its method to reflect changes in the parameter types.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Advanced, step: 'v12 `routerLinkActiveOptions`', action: '`routerLinkActiveOptions` property of `RouterLinkActive` now has a more specific type. You may need to update code accessing this property to align with the changes.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Advanced, step: 'v12 `APP_INITIALIZER` callback types', action: 'The initializer callbacks now have more specific return types, which may require update of your code if you are getting an `APP_INITIALIZER` instance via `Injector.get` or `TestBed.inject`.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Advanced, step: 'v12 fragment typings', action: 'The router fragments now could be `null`. Add `null` checks to avoid TypeScript failing with type errors.', }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Advanced, step: 'v12 `ng.getDirectives`', action: "Make sure you don't rely on `ng.getDirectives` throwing an error if it can't find a directive associated with a particular DOM node.", }, { possibleIn: 1200, necessaryAsOf: 1200, level: ApplicationComplexity.Advanced, step: 'v12 `optimization.styles.inlineCritical`', action: 'Check out `optimization.styles.inlineCritical` option in your angular.json file. It now defaults to `true`. Remember that the whole `optimization` option can be set as boolean which will set all the suboptions to defaults.', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Basic, step: 'v13 ng update', action: 'Run `ng update @angular/core@13 @angular/cli@13` which should bring you to version 13 of Angular.', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `ng update @angular/material@13`.', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Basic, step: 'TypeScript 4.4', action: 'Angular now uses TypeScript 4.4, read more about any potential breaking changes: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-4.html', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Basic, step: 'v13 node', action: 'Make sure you are using <a href="http://www.hostingadvice.com/how-to/update-node-js-latest-version/" target="_blank">Node 12.20.0 or later</a>', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Medium, step: 'v13 routerLink', action: 'You can now disable the navigation of a `routerLink` by passing `undefined` and `null`. Previously the `routerLink` directive used to accept these two values as equivalent to an empty string.', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Medium, step: 'v13 router loadChildren', action: 'You can no longer specify lazy-loaded routes by setting a string value to `loadChildren`. Make sure you move to dynamic ESM import statements.', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Medium, step: 'v13 service worker activated', action: 'The `activated` observable of `SwUpdate` is now deprecated. To check the activation status of a service worker use the `activatedUpdate` method instead.', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Medium, step: 'v13 service worker available', action: 'The `available` observable of `SwUpdate` is now deprecated. To get the same information use `versionUpdates` and filter only the `VersionReadyEvent` events.', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Medium, step: 'v13 renderModuleFactory', action: 'The `renderModuleFactory` from `@angular/platform-server` is no longer necessary with Ivy. Use `renderModule` instead.', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Advanced, step: 'v13 forms status', action: 'We narrowed the type of `AbstractControl.status` to `FormControlStatus` and `AbstractControl.status` to `Observable<FormControlStatus>`. `FormControlStatus` is the union of all possible status strings for form controls.', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Advanced, step: 'v13 router serializer', action: 'To align with the URI spec, now the URL serializer respects question marks in the query parameters. For example `/path?q=hello?&q2=2` will now be parsed to `{ q: `hello?`, q2: 2 }`', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Advanced, step: 'v13 host binding', action: "`href` is now an attribute binding. This means that `DebugElement.properties['href']` now returns the `href` value returned by the native element, rather than the internal value of the `href` property of the `routerLink`.", },
{ "end_byte": 60217, "start_byte": 52934, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_60220_67517
possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Advanced, step: 'v13 spy location', action: '`SpyLocation` no longer emits the `popstate` event when `location.go` is called. In addition, `simulateHashChange` now triggers both `haschange` and `popstate`. Tests that rely on `location.go` most likely need to now use `simulateHashChange` to capture `popstate`.', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Advanced, ngUpgrade: true, step: 'v13 router URL replacement', action: 'The router will no longer replace the browser URL when a new navigation cancels an ongoing navigation. Hybrid applications which rely on the `navigationId` being present on initial navigations that were handled by the Angular router should subscribe to `NavigationCancel` events and perform the `location.replaceState` to add `navigationId` to the `Router` state. In addition, tests which assert `urlChanges` on the `SpyLocation` may need to be adjusted to account for the `replaceState` which is no longer triggered.', }, { possibleIn: 1300, necessaryAsOf: 1300, level: ApplicationComplexity.Advanced, step: 'v13 removed symbols', action: 'The route package no longer exports `SpyNgModuleFactoryLoader` and `DeprecatedLoadChildren`. In case you use them, make sure you remove their corresponding import statements.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Basic, step: 'v14 ng update', action: 'Run `ng update @angular/core@14 @angular/cli@14` which should bring you to version 14 of Angular.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `ng update @angular/material@14`.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Basic, step: 'TypeScript 4.6', action: 'Angular now uses TypeScript 4.6, read more about any potential breaking changes: https://devblogs.microsoft.com/typescript/announcing-typescript-4-6/', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Basic, step: 'v14 node', action: 'Make sure you are using <a href="http://www.hostingadvice.com/how-to/update-node-js-latest-version/" target="_blank">Node 14.15.0 or later</a>', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Medium, step: 'v14 strict forms', action: 'Form models now require a generic type parameter. For gradual migration you can opt-out using the untyped version of the form model classes.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Medium, step: 'v14 aotSummaries', action: 'Remove `aotSummaries` from `TestBed` since Angular no longer needs them in Ivy.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Medium, material: true, step: 'v14 MatVertical and Horizontal Stepper', action: 'If you are using `MatVerticalStepper` or `MatHorizontalStepper` make sure you switch to `MatStepper`.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Medium, step: 'v14 JSONP', action: 'Remove headers from JSONP requests. JSONP does not supports headers and if specified the HTTP module will now throw an error rather than ignoring them.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Medium, step: 'v14 resolvers', action: 'Resolvers now will take the first emitted value by an observable and after that proceed to navigation to better align with other guards rather than taking the last emitted value.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, material: true, step: 'v14 deprecate protractor entry', action: 'The deprecated `angular/cdk/testing/protractor` entry point is now removed.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, material: true, step: 'v14 chipInput', action: 'Make sure you specify `chipInput` of `MatChipInputEvent` because it is now required.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, material: true, step: 'v14 mixinErrorState', action: 'You need to implement `stateChanges` class member in abstractions using `mixinErrorState` because the mixin no longer provides it.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, material: true, step: 'v14 CdkStepper orientation', action: 'Use `CdkStepper.orientation` instead of `CdkStepper._orientation`.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, material: true, step: 'v14 CdkStepper and MatStepper', action: 'If you are extending or using `CdkStepper` or `MatStepper` in the constructor you should no longer pass the `_document` parameter since it is now removed.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, material: true, step: 'v14 mat-list-item-avatar', action: 'Rename the `mat-list-item-avatar` CSS class to `mat-list-item-with-avatar`.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, material: true, step: 'v14 MatSelectionListChange.option', action: 'Use `MatSelectionListChange.options` rather than `MatSelectionListChange.option`.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, material: true, step: 'v14 getHarnessLoaderForContent', action: 'Use `getChildLoader(MatListItemSection.CONTENT)` rather than `getHarnessLoaderForContent`.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, material: true, step: 'v14 MatSelectionList', action: 'If you are using `MatSelectionList` make sure you pass `_focusMonitor` in its constructor because it is now required. Additionally, this class no longer has `tabIndex` property and a `tabIndex` constructor parameter.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, step: 'v14 initialNavigation', action: "Update `initialNavigation: 'enabled'` to `initialNavigation: 'enabledBlocking'`.", }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, step: 'v14 Route.pathMatch', action: 'If you are defining routes with `pathMatch`, you may have to cast it to `Route` or `Routes` explicitly. `Route.pathMatch` is no longer compatible with `string` type.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, step: 'v14 stricter LoadChildrenCallback', action: 'The promise returned by `LoadChildrenCallback` now has a stricter type parameter `Type<any>|NgModuleFactory<any>` rather than `any`.', },
{ "end_byte": 67517, "start_byte": 60220, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_67520_74978
possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, step: 'v14 router scheduling', action: 'The router does no longer schedule redirect navigation within a `setTimeout`. Make sure your tests do not rely on this behavior.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, step: 'v14 LocationStrategy', action: 'Implementing the `LocationStrategy` interface now requires definition of `getState()`.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, step: 'v14 http queries', action: 'Sending `+` as part of a query no longer requires workarounds since `+` no longer sends a space.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, step: 'v14 AnimationDriver.getParentElement', action: 'Implementing `AnimationDriver` now requires the `getParentElement` method.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, step: 'v14 invalid config', action: 'Invalid route configurations of lazy-loaded modules will now throw an error rather than being ignored.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, step: 'v14 router resolver', action: 'Remove the `resolver` from `RouterOutletContract.activateWith` function and the `resolver` from `OutletContext` class since factory resolvers are no longer needed.', }, { possibleIn: 1400, necessaryAsOf: 1400, level: ApplicationComplexity.Advanced, step: 'v14 initialUrl', action: '`Router.initialUrl` accepts only `UrlTree` to prevent a misuse of the API by assigning a `string` value.', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 node support', action: 'Make sure that you are using a supported version of node.js before you upgrade your application. Angular v15 supports node.js versions: 14.20.x, 16.13.x and 18.10.x. <a href="https://v15.angular.io/guide/update-to-version-15#v15-bc-01" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 ts support', action: 'Make sure that you are using a supported version of TypeScript before you upgrade your application. Angular v15 supports TypeScript version 4.8 or later. <a href="https://v15.angular.io/guide/update-to-version-15#v15-bc-02" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 ng update', action: "In the application's project directory, run `ng update @angular/core@15 @angular/cli@15` to update your application to Angular v15.", }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, material: true, step: 'V15 update @angular/material', action: 'Run `ng update @angular/material@15` to update the Material components.', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 keyframe', action: 'In v15, the Angular compiler prefixes `@keyframes` in CSS with the component\'s scope. This means that any TypeScript code that relies on `keyframes` names no longer works in v15. Update any such instances to: define keyframes programmatically, use global stylesheets, or change the component\'s view encapsulation. <a href="https://v15.angular.io/guide/update-to-version-15#v15-bc-03" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 no-ivy', action: "In your application's `tsconfig.json` file, remove `enableIvy`. In v15, Ivy is the only rendering engine so `enableIvy` is not required.", }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 base-decorators', action: 'Make sure to use decorators in base classes with child classes that inherit constructors and use dependency injection. Such base classes should be decorated with either `@Injectable` or `@Directive` or the compiler returns an error. <a href="https://v15.angular.io/guide/update-to-version-15#v15-bc-05" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 setDisabledState', action: 'In v15, `setDisabledState` is always called when a `ControlValueAccessor` is attached. To opt-out of this behavior, use `FormsModule.withConfig` or `ReactiveFormsModule.withConfig`. <a href="https://v15.angular.io/guide/update-to-version-15#v15-bc-06" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Advanced, step: 'v15 canParse', action: 'Applications that use `canParse` should use `analyze` from `@angular/localize/tools` instead. In v15, the `canParse` method was removed from all translation parsers in `@angular/localize/tools`. <a href="https://v15.angular.io/guide/update-to-version-15#v15-bc-07" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 ActivatedRoutSnapshot', action: 'Make sure that all `ActivatedRouteSnapshot` objects have a `title` property. In v15, the `title` property is a required property of `ActivatedRouteSnapshot`. <a href="https://v15.angular.io/guide/update-to-version-15#v15-bc-08" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Advanced, step: 'v15 RouterOutlet', action: 'If your tests with `RouterOutlet` break, make sure they don\'t depend on the instantiation order of the corresponding component relative to change detection. In v15, `RouterOutlet` instantiates the component after change detection. <a href="https://v15.angular.io/guide/update-to-version-15#v15-bc-09" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 relativeLinkResolution', action: 'In v15, `relativeLinkResolution` is not configurable in the Router. It was used to opt out of an earlier bug fix that is now standard. <a href="https://v15.angular.io/guide/update-to-version-15#v15-bc-10" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 DATE_PIPE_DEFAULT_OPTIONS', action: 'Change instances of the `DATE_PIPE_DEFAULT_TIMEZONE` token to use `DATE_PIPE_DEFAULT_OPTIONS` to configure time zones. In v15, the `DATE_PIPE_DEFAULT_TIMEZONE` token is deprecated. <a href="https://v15.angular.io/guide/update-to-version-15#v15-dp-01" alt="Link to more information about this change">Read further</a>', },
{ "end_byte": 74978, "start_byte": 67520, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_74981_82410
possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 iframe', action: "Existing `<iframe>` instances might have security-sensitive attributes applied to them as an attribute or property binding. These security-sensitive attributes can occur in a template or in a directive's host bindings. Such occurrences require an update to ensure compliance with the new and stricter rules about `<iframe>` bindings. For more information, see [the error page](https://v15.angular.io/errors/NG0910).", }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 Injector.get', action: 'Update instances of `Injector.get()` that use an `InjectFlags` parameter to use an `InjectOptions` parameter. The `InjectFlags` parameter of `Injector.get()` is deprecated in v15. <a href="https://v15.angular.io/guide/update-to-version-15#v15-dp-02" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 TestBed.inject', action: 'Update instances of `TestBed.inject()` that use an `InjectFlags` parameter to use an `InjectOptions` parameter. The `InjectFlags` parameter of `TestBed.inject()` is deprecated in v15. <a href="https://v15.angular.io/guide/update-to-version-15#v15-dp-01" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 ngModule in providedIn', action: 'Using `providedIn: ngModule` for an `@Injectable` and `InjectionToken` is deprecated in v15. <a href="https://v15.angular.io/guide/update-to-version-15#v15-dp-04" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 providedIn any', action: 'Using `providedIn: \'any\'` for an `@Injectable` or `InjectionToken` is deprecated in v15. <a href="https://v15.angular.io/guide/update-to-version-15#v15-dp-05" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 RouterLinkWithHref', action: 'Update instances of the `RouterLinkWithHref`directive to use the `RouterLink` directive. The `RouterLinkWithHref` directive is deprecated in v15. <a href="https://v15.angular.io/guide/update-to-version-15#v15-dp-06" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, material: true, step: 'v15 mat refactor', action: 'In Angular Material v15, many of the components have been refactored to be based on the official Material Design Components for Web (MDC). This change affected the DOM and CSS classes of many components. <a href="https://rc.material.angular.io/guide/mdc-migration" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 visual review', action: 'After you update your application to v15, visually review your application and its interactions to ensure everything is working as it should.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 node support', action: 'Make sure that you are using a supported version of node.js before you upgrade your application. Angular v16 supports node.js versions: v16 and v18.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 ts support', action: 'Make sure that you are using a supported version of TypeScript before you upgrade your application. Angular v16 supports TypeScript version 4.9.3 or later.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 ng update', action: "In the application's project directory, run `ng update @angular/core@16 @angular/cli@16` to update your application to Angular v16.", }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `ng update @angular/material@16`.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 zone.js support', action: 'Make sure that you are using a supported version of Zone.js before you upgrade your application. Angular v16 supports Zone.js version 0.13.x or later.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 RouterEvent', action: "The Event union no longer contains `RouterEvent`, which means that if you're using the Event type you may have to change the type definition from `(e: Event)` to `(e: Event|RouterEvent)`", }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 routerEvent prop type', action: 'In addition to `NavigationEnd` the `routerEvent` property now also accepts type `NavigationSkipped`', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 RendererType2', action: 'Pass only flat arrays to `RendererType2.styles` because it no longer accepts nested arrays', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 BrowserPlatformLocation', action: 'You may have to update tests that use `BrowserPlatformLocation` because `MockPlatformLocation` is now provided by default in tests. [Read further](https://github.com/angular/angular/blob/main/CHANGELOG.md#common-9).', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 ngcc', action: 'Due to the removal of the Angular Compatibility Compiler (ngcc) in v16, projects on v16 and later no longer support View Engine libraries.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 createUrlTree', action: 'After bug fixes in `Router.createUrlTree` you may have to readjust tests which mock `ActiveRoute`. [Read further](https://github.com/angular/angular/blob/main/CHANGELOG.md#1600-next1-2023-03-01)', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 ApplicationConfig imports', action: 'Change imports of `ApplicationConfig` to be from `@angular/core`.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 renderModule', action: 'Revise your code to use `renderModule` instead of `renderModuleFactory` because it has been deleted.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 XhrFactory', action: 'Revise your code to use `XhrFactory` from `@angular/common` instead of `XhrFactory` export from `@angular/common/http`.', },
{ "end_byte": 82410, "start_byte": 74981, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_82413_89911
possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 withServerTransition', action: "If you're running multiple Angular apps on the same page and you're using `BrowserModule.withServerTransition({ appId: 'serverApp' })` make sure you set the `APP_ID` instead since `withServerTransition` is now deprecated. [Read further](https://github.com/angular/angular/blob/main/CHANGELOG.md#platform-browser-4)", }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 EnvironmentInjector', action: 'Change `EnvironmentInjector.runInContext` to `runInInjectionContext` and pass the environment injector as the first parameter.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 ViewContainerRef.createComponent', action: 'Update your code to use `ViewContainerRef.createComponent` without the factory resolver. `ComponentFactoryResolver` has been removed from Router APIs.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 APP_ID', action: 'If you bootstrap multiple apps on the same page, make sure you set unique `APP_IDs`.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 server renderApplication', action: 'Update your code to revise `renderApplication` method as it no longer accepts a root component as first argument, but instead a callback that should bootstrap your app. [Read further](https://github.com/angular/angular/blob/main/CHANGELOG.md#platform-server-3)', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 PlatformConfig.baseUrl', action: 'Update your code to remove any reference to `PlatformConfig.baseUrl` and `PlatformConfig.useAbsoluteUrl` platform-server config options as it has been deprecated.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 moduleid', action: 'Update your code to remove any reference to `@Directive`/`@Component` `moduleId` property as it does not have any effect and will be removed in v17.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 transfer state imports', action: "Update imports from `import {makeStateKey, StateKey, TransferState} from '@angular/platform-browser'` to `import {makeStateKey, StateKey, TransferState} from '@angular/core'`", }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 ComponentRef', action: "If you rely on `ComponentRef.setInput` to set the component input even if it's the same based on `Object.is` equality check, make sure you copy its value.", }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 ANALYZE_FOR_ENTRY_COMPONENTS', action: 'Update your code to remove any reference to `ANALYZE_FOR_ENTRY_COMPONENTS` injection token as it has been deleted.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 entry components', action: '`entryComponents` is no longer available and any reference to it can be removed from the `@NgModule` and `@Component` public APIs.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 ngTemplateOutletContext', action: 'ngTemplateOutletContext has stricter type checking which requires you to declare all the properties in the corresponding object. [Read further](https://github.com/angular/angular/blob/main/CHANGELOG.md#common-1).', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 APF', action: 'Angular packages no longer include FESM2015 and the distributed ECMScript has been updated from 2020 to 2022.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 EventManager', action: 'The deprecated `EventManager` method `addGlobalEventListener` has been removed as it is not used by Ivy.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 BrowserTransferStateModule', action: '`BrowserTransferStateModule` is no longer available and any reference to it can be removed from your applications.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 ReflectiveInjector', action: 'Update your code to use `Injector.create` rather than `ReflectiveInjector` since `ReflectiveInjector` is removed.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 QueryList', action: '`QueryList.filter` now supports type guard functions. Since the type will be narrowed, you may have to update your application code that relies on the old behavior.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 node support', action: 'Make sure that you are using a supported version of node.js before you upgrade your application. Angular v17 supports node.js versions: v18.13.0 and newer', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 ts support', action: 'Make sure that you are using a supported version of TypeScript before you upgrade your application. Angular v17 supports TypeScript version 5.2 or later.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 zone.js support', action: 'Make sure that you are using a supported version of Zone.js before you upgrade your application. Angular v17 supports Zone.js version 0.14.x or later.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 ng update', action: "In the application's project directory, run `ng update @angular/core@17 @angular/cli@17` to update your application to Angular v17.", }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `ng update @angular/material@17`.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Medium, step: 'v17 style removal', action: 'Angular now automatically removes styles of destroyed components, which may impact your existing apps in cases you rely on leaked styles. To change this update the value of the `REMOVE_STYLES_ON_COMPONENT_DESTROY` provider to `false`.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 router removals', action: "Make sure you configure `setupTestingRouter`, `canceledNavigationResolution`, `paramsInheritanceStrategy`, `titleStrategy`, `urlUpdateStrategy`, `urlHandlingStrategy`, and `malformedUriErrorHandler` in `provideRouter` or `RouterModule.forRoot` since these properties are now not part of the `Router`'s public API", },
{ "end_byte": 89911, "start_byte": 82413, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_89914_97539
possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Advanced, step: 'v17 ngDoCheck dynamic components', action: 'For dynamically instantiated components we now execute `ngDoCheck` during change detection if the component is marked as dirty. You may need to update your tests or logic within `ngDoCheck` for dynamically instantiated components.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Medium, step: 'v17 malformedUriErrorHandler', action: "Handle URL parsing errors in the `UrlSerializer.parse` instead of `malformedUriErrorHandler` because it's now part of the public API surface.", }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Medium, step: 'v17 zone deep imports', action: 'Change Zone.js deep imports like `zone.js/bundles/zone-testing.js` and `zone.js/dist/zone` to `zone.js` and `zone.js/testing`.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Advanced, step: 'v17 absolute redirects', action: 'You may need to adjust your router configuration to prevent infinite redirects after absolute redirects. In v17 we no longer prevent additional redirects after absolute redirects.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Medium, step: 'v17 AnimationDriver', action: 'Change references to `AnimationDriver.NOOP` to use `NoopAnimationDriver` because `AnimationDriver.NOOP` is now deprecated.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 switch strictness', action: "You may need to adjust the equality check for `NgSwitch` because now it defaults to stricter check with `===` instead of `==`. Angular will log a warning message for the usages where you'd need to provide an adjustment.", }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Advanced, step: 'v17 mutate in signals', action: 'Use `update` instead of `mutate` in Angular Signals. For example `items.mutate(itemsArray => itemsArray.push(newItem));` will now be `items.update(itemsArray => [itemsArray, …newItem]);`', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Medium, step: 'v17 withNoDomReuse', action: 'To disable hydration use `ngSkipHydration` or remove the `provideClientHydration` call from the provider list since `withNoDomReuse` is no longer part of the public API.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 paramsInheritanceStrategy', action: 'If you want the child routes of `loadComponent` routes to inherit data from their parent specify the `paramsInheritanceStrategy` to `always`, which in v17 is now set to `emptyOnly`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Basic, step: 'v18 node support', action: 'Make sure that you are using a supported version of node.js before you upgrade your application. Angular v18 supports node.js versions: v18.19.0 and newer', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Basic, step: 'v18 ng update', action: "In the application's project directory, run `ng update @angular/core@18 @angular/cli@18` to update your application to Angular v18.", }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `ng update @angular/material@18`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Basic, step: '18.0.0 Upgrade TypeScript', action: 'Update TypeScript to versions 5.4 or newer.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0: async has been removed, use `waitForAsync` instead', action: 'Replace `async` from `@angular/core` with `waitForAsync`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0: Deprecated matchesElement method removed from AnimationDriver', action: "Remove calls to `matchesElement` because it's now not part of `AnimationDriver`.", }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0. Use `@angular/core` StateKey and TransferState', action: 'Import `StateKey` and `TransferState` from `@angular/core` instead of `@angular/platform-browser`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0. Opt-in of caching for HTTP requests with auth headers', action: 'Use `includeRequestsWithAuthHeaders: true` in `withHttpTransferCache` to opt-in of caching for HTTP requests that require authorization.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0.REMOVE_OBSOLETE_IS_WORKER', action: 'Update the application to remove `isPlatformWorkerUi` and `isPlatformWorkerApp` since they were part of platform WebWorker which is now not part of Angular.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0.FORCE_ZONE_CHANGE_DETECTION', action: 'Tests may run additional rounds of change detection to fully reflect test state in the DOM. As a last resort, revert to the old behavior by adding `provideZoneChangeDetection({ignoreChangesOutsideZone: true})` to the TestBed providers.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0: Remove two-way binding expressions in writable bindings', action: 'Remove expressions that write to properties in templates that use `[(ngModel)]`', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0: Use zones to track pending requests', action: 'Remove calls to `Testability` methods `increasePendingRequestCount`, `decreasePendingRequestCount`, and `getPendingRequestCount`. This information is tracked by ZoneJS.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0: Move shared providers to the routed component', action: 'Move any environment providers that should be available to routed components from the component that defines the `RouterOutlet` to the providers of `bootstrapApplication` or the `Route` config.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0 Use RedirectCommand or new NavigationBehaviorOptions', action: 'When a guard returns a `UrlTree` as a redirect, the redirecting navigation will now use `replaceUrl` if the initial navigation was also using the `replaceUrl` option. If you prefer the previous behavior, configure the redirect using the new `NavigationBehaviorOptions` by returning a `RedirectCommand` with the desired options instead of `UrlTree`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0: Remove deprecated resource cache providers', action: "Remove dependencies of `RESOURCE_CACHE_PROVIDER` since it's no longer part of the Angular runtime.", },
{ "end_byte": 97539, "start_byte": 89914, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/recommendations.ts_97542_101136
possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0: Update Node.js URL parsing in `ServerPlatformLocation`', action: 'In `@angular/platform-server` now `pathname` is always suffixed with `/` and the default ports for http: and https: respectively are 80 and 443.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0. Use absolute URLs', action: 'Provide an absolute `url` instead of using `useAbsoluteUrl` and `baseUrl` from `PlatformConfig`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0. Switch from `platformDynamicServer` to `platformServer`.', action: 'Replace the usage of `platformDynamicServer` with `platformServer`. Also, add an `import @angular/compiler`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0. Remove `ServerTransferStateModule` from app imports', action: 'Remove all imports of `ServerTransferStateModule` from your application. It is no longer needed.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0. Update `Route.redirectTo` to accept functions', action: '`Route.redirectTo` can now include a function in addition to a string. Any code which reads `Route` objects directly and expects `redirectTo` to be a string may need to update to account for functions as well.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0: Guards can return `RedirectCommand`', action: '`Route` guards and resolvers can now return a `RedirectCommand` object in addition to a `UrlTree` and `boolean`. Any code which reads `Route` objects directly and expects only `boolean` or `UrlTree` may need to update to account for `RedirectCommand` as well.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0: Mark `OnPush` views dirty', action: 'For any components using `OnPush` change detection, ensure they are properly marked dirty to enable host binding updates.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0-Refresh-Newly-Created-Views', action: 'Be aware that newly created views or views marked for check and reattached during change detection are now guaranteed to be refreshed in that same change detection cycle.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0: `ComponentFixture.whenStable` matches `ApplicationRef.isStable`', action: 'After aligning the semantics of `ComponentFixture.whenStable` and `ApplicationRef.isStable`, your tests may wait longer when using `whenStable`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0. `ComponentFixture.autoDetect` behavior more closely matches Application behavior', action: 'You may experience tests failures if you have tests that rely on change detection execution order when using `ComponentFixture.autoDetect` because it now executes change detection for fixtures within `ApplicationRef.tick`. For example, this will cause test fixture to refresh before any dialogs that it creates whereas this may have been the other way around in the past.', }, ];
{ "end_byte": 101136, "start_byte": 97542, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/recommendations.ts" }
angular/adev/src/app/features/update/update.component.ts_0_7235
import {ChangeDetectionStrategy, Component, HostListener, inject} from '@angular/core'; import {Step, RECOMMENDATIONS} from './recommendations'; import {Clipboard} from '@angular/cdk/clipboard'; import {CdkMenuModule} from '@angular/cdk/menu'; import {MatCheckboxModule} from '@angular/material/checkbox'; import {MatInputModule} from '@angular/material/input'; import {MatCardModule} from '@angular/material/card'; import {MatGridListModule} from '@angular/material/grid-list'; import {MatButtonToggleModule} from '@angular/material/button-toggle'; import {IconComponent} from '@angular/docs'; import {ActivatedRoute, Router} from '@angular/router'; import {marked} from 'marked'; interface Option { id: keyof Step; name: string; description: string; } @Component({ selector: 'adev-update-guide', templateUrl: './update.component.html', styleUrl: './update.component.scss', imports: [ MatCheckboxModule, MatInputModule, MatCardModule, MatGridListModule, MatButtonToggleModule, CdkMenuModule, IconComponent, ], standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, }) export default class AppComponent { protected title = ''; protected level = 1; protected options: Record<string, boolean> = { ngUpgrade: false, material: false, windows: isWindows(), }; protected readonly optionList: Option[] = [ {id: 'ngUpgrade', name: 'ngUpgrade', description: 'to combine AngularJS & Angular'}, {id: 'material', name: 'Angular Material', description: ''}, {id: 'windows', name: 'Windows', description: ''}, ]; protected packageManager: 'npm install' | 'yarn add' = 'npm install'; protected beforeRecommendations: Step[] = []; protected duringRecommendations: Step[] = []; protected afterRecommendations: Step[] = []; protected readonly versions = [ {name: '18.0', number: 1800}, {name: '17.0', number: 1700}, {name: '16.0', number: 1600}, {name: '15.0', number: 1500}, {name: '14.0', number: 1400}, {name: '13.0', number: 1300}, {name: '12.0', number: 1200}, {name: '11.0', number: 1100}, {name: '10.2', number: 1020}, {name: '10.1', number: 1010}, {name: '10.0', number: 1000}, {name: '9.1', number: 910}, {name: '9.0', number: 900}, {name: '8.2', number: 820}, {name: '8.1', number: 810}, {name: '8.0', number: 800}, {name: '7.2', number: 720}, {name: '7.1', number: 710}, {name: '7.0', number: 700}, {name: '6.1', number: 610}, {name: '6.0', number: 600}, {name: '5.2', number: 520}, {name: '5.1', number: 510}, {name: '5.0', number: 500}, {name: '4.4', number: 440}, {name: '4.3', number: 430}, {name: '4.2', number: 420}, {name: '4.1', number: 410}, {name: '4.0', number: 400}, {name: '2.4', number: 204}, {name: '2.3', number: 203}, {name: '2.2', number: 202}, {name: '2.1', number: 201}, {name: '2.0', number: 200}, ]; protected from = this.versions.find((version) => version.name === '17.0')!; protected to = this.versions.find((version) => version.name === '18.0')!; protected futureVersion = 1900; protected readonly steps: Step[] = RECOMMENDATIONS; private readonly clipboard = inject(Clipboard); private readonly router = inject(Router); private readonly activatedRoute = inject(ActivatedRoute); constructor() { const queryMap = this.activatedRoute.snapshot.queryParamMap; // Detect settings in URL this.level = parseInt(queryMap.get('l')!, 10) || this.level; // Detect versions of from and to const versions = queryMap.get('v'); if (versions) { const [from, to] = versions.split('-'); this.from = this.versions.find((version) => version.name === from)!; this.to = this.versions.find((version) => version.name === to)!; this.showUpdatePath(); } } @HostListener('click', ['$event.target']) copyCode({tagName, textContent}: Element) { if (tagName === 'CODE') { // TODO: add a toast notification this.clipboard.copy(textContent!); } } async showUpdatePath() { this.beforeRecommendations = []; this.duringRecommendations = []; this.afterRecommendations = []; // Refuse to generate recommendations for downgrades if (this.to.number < this.from.number) { alert('We do not support downgrading versions of Angular.'); return; } const labelTitle = 'Guide to update your Angular application'; const labelBasic = 'basic applications'; const labelMedium = 'medium applications'; const labelAdvanced = 'advanced applications'; this.title = `${labelTitle} v${this.from.name} -> v${this.to.name} for ${this.level < 2 ? labelBasic : this.level < 3 ? labelMedium : labelAdvanced}`; // Find applicable steps and organize them into before, during, and after upgrade for (const step of this.steps) { if (step.level <= this.level && step.necessaryAsOf > this.from.number) { // Check Options // Only show steps that don't have a required option // Or when the user has a matching option selected let skip = false; for (const option of this.optionList) { // Skip steps which require an option not set by the user. if (step[option.id] && !this.options[option.id]) { skip = true; } // Skip steps which require **not** using an option which **is** set // by the user. if (step[option.id] === false && this.options[option.id]) { skip = true; } } if (skip) { continue; } // Render and replace variables step.renderedStep = await marked(this.replaceVariables(step.action)); // If you could do it before now, but didn't have to finish it before now if (step.possibleIn <= this.from.number && step.necessaryAsOf >= this.from.number) { this.beforeRecommendations.push(step); // If you couldn't do it before now, and you must do it now } else if (step.possibleIn > this.from.number && step.necessaryAsOf <= this.to.number) { this.duringRecommendations.push(step); } else if (step.possibleIn <= this.to.number) { this.afterRecommendations.push(step); } } } // Update the URL so users can link to this transition this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: {v: `${this.from.name}-${this.to.name}`, l: this.level}, queryParamsHandling: 'merge', }); // Tell everyone how to upgrade for v6 or earlier this.renderPreV6Instructions(); } private getAdditionalDependencies(version: number): string { if (version < 500) { return `typescript@'>=2.1.0 <2.4.0'`; } else if (version < 600) { return `[email protected] rxjs@^5.5.2`; } else { return `[email protected] rxjs@^6.0.0`; } } private getAngularVersion(version: number): string { if (version < 400) { return `'^2.0.0'`; } else { const major = Math.floor(version / 100); const minor = Math.floor((version - major * 100) / 10); return `^${major}.${minor}.0`; } }
{ "end_byte": 7235, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/update.component.ts" }
angular/adev/src/app/features/update/update.component.ts_7239_9753
private async renderPreV6Instructions(): Promise<void> { let upgradeStep: Step; const additionalDeps = this.getAdditionalDependencies(this.to.number); const angularVersion = this.getAngularVersion(this.to.number); const angularPackages = [ 'animations', 'common', 'compiler', 'compiler-cli', 'core', 'forms', 'http', 'platform-browser', 'platform-browser-dynamic', 'platform-server', 'router', ]; // Provide npm/yarn instructions for versions before 6 if (this.to.number < 600) { const actionMessage = `Update all of your dependencies to the latest Angular and the right version of TypeScript.`; if (isWindows()) { const packages = angularPackages .map((packageName) => `@angular/${packageName}@${angularVersion}`) .join(' ') + ' ' + additionalDeps; upgradeStep = { step: 'General Update', action: `${actionMessage} If you are using Windows, you can use: \`${this.packageManager} ${packages}\``, } as Step; } else { const packages = `@angular/{${angularPackages.join(',')}}@${angularVersion} ${additionalDeps}`; upgradeStep = { step: 'General update', action: `${actionMessage} If you are using Linux/Mac, you can use: \`${this.packageManager} ${packages}\``, } as Step; } // Npm installs typescript wrong in v5, let's manually specify // https://github.com/npm/npm/issues/16813 if (this.packageManager === 'npm install' && this.to.number === 500) { upgradeStep.action += ` \`npm install [email protected] --save-exact\``; } upgradeStep.renderedStep = await marked(upgradeStep.action); this.duringRecommendations.push(upgradeStep); } } private replaceVariables(action: string): string { let newAction = action; newAction = newAction.replace( '${packageManagerGlobalInstall}', this.packageManager === 'npm install' ? 'npm install -g' : 'yarn global add', ); newAction = newAction.replace('${packageManagerInstall}', this.packageManager); return newAction; } } /** Whether or not the user is running on a Windows OS. */ function isWindows(): boolean { if (typeof navigator === 'undefined') { return false; } const platform = navigator.platform.toLowerCase(); return platform.includes('windows') || platform.includes('win32'); }
{ "end_byte": 9753, "start_byte": 7239, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/update/update.component.ts" }
angular/adev/src/app/features/playground/playground.component.ts_0_2881
/*! * @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 {isPlatformBrowser, NgComponentOutlet} from '@angular/common'; import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, EnvironmentInjector, PLATFORM_ID, Type, inject, } from '@angular/core'; import {IconComponent} from '@angular/docs'; import {PlaygroundTemplate} from '@angular/docs'; import {injectAsync} from '../../core/services/inject-async'; import {EmbeddedTutorialManager} from '../../editor/index'; import PLAYGROUND_ROUTE_DATA_JSON from '../../../../src/assets/tutorials/playground/routes.json'; import {CdkMenu, CdkMenuItem, CdkMenuTrigger} from '@angular/cdk/menu'; @Component({ selector: 'adev-playground', standalone: true, imports: [NgComponentOutlet, IconComponent, CdkMenu, CdkMenuItem, CdkMenuTrigger], templateUrl: './playground.component.html', styleUrls: [ './playground.component.scss', '../tutorial/tutorial-navigation.scss', '../tutorial/tutorial-navigation-list.scss', ], changeDetection: ChangeDetectionStrategy.OnPush, }) export default class PlaygroundComponent implements AfterViewInit { private readonly changeDetectorRef = inject(ChangeDetectorRef); private readonly embeddedTutorialManager = inject(EmbeddedTutorialManager); private readonly environmentInjector = inject(EnvironmentInjector); private readonly platformId = inject(PLATFORM_ID); readonly templates = PLAYGROUND_ROUTE_DATA_JSON.templates; readonly defaultTemplate = PLAYGROUND_ROUTE_DATA_JSON.defaultTemplate; readonly starterTemplate = PLAYGROUND_ROUTE_DATA_JSON.starterTemplate; protected embeddedEditorComponent?: Type<unknown>; protected selectedTemplate: PlaygroundTemplate = this.defaultTemplate; async ngAfterViewInit(): Promise<void> { if (isPlatformBrowser(this.platformId)) { const [embeddedEditorComponent, nodeRuntimeSandbox] = await Promise.all([ import('../../editor/index').then((c) => c.EmbeddedEditor), injectAsync(this.environmentInjector, () => import('../../editor/index').then((c) => c.NodeRuntimeSandbox), ), ]); this.embeddedEditorComponent = embeddedEditorComponent; this.changeDetectorRef.markForCheck(); await this.loadTemplate(this.defaultTemplate.path); await nodeRuntimeSandbox.init(); } } async newProject() { await this.loadTemplate(this.starterTemplate.path); } async changeTemplate(template: PlaygroundTemplate): Promise<void> { this.selectedTemplate = template; await this.loadTemplate(template.path); } private async loadTemplate(tutorialPath: string) { await this.embeddedTutorialManager.fetchAndSetTutorialFiles(tutorialPath); } }
{ "end_byte": 2881, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/playground/playground.component.ts" }
angular/adev/src/app/features/playground/playground.component.html_0_784
<div class="adev-playground-header"> <header> <h1 tabindex="-1">Angular Playground</h1> </header> <div class="adev-template-select"> <label for="playgroundTemplate">Select a template</label> <button [cdkMenuTriggerFor]="templatesMenu"> <span>{{ selectedTemplate.label }}</span> <docs-icon>expand_more</docs-icon> </button> </div> </div> @if (embeddedEditorComponent) { <ng-container *ngComponentOutlet="embeddedEditorComponent" /> } <ng-template #templatesMenu> <ul class="adev-template-dropdown" cdkMenu> @for (template of templates; track template.path) { <li> <button cdkMenuItem type="button" (click)="changeTemplate(template)"> <span>{{ template.label }}</span> </button> </li> } </ul> </ng-template>
{ "end_byte": 784, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/playground/playground.component.html" }
angular/adev/src/app/features/playground/playground.component.scss_0_1818
:host { display: block; padding: var(--layout-padding); padding-block-end: 100px; height: 100vh; width: 100%; box-sizing: border-box; header { display: flex; gap: 1rem; h1 { margin-block: 0; } } } .adev-playground-header { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem; margin-block: 1rem; } .adev-template-select { margin-block-end: 0.5rem; label { color: var(--quaternary-contrast); font-size: 0.875rem; margin-block-end: 0.3rem; margin-inline-start: 0.45rem; display: block; } // cdk select button button { font-size: 0.875rem; border: 1px solid var(--senary-contrast); border-radius: 0.25rem; width: 200px; display: flex; justify-content: space-between; align-items: center; padding-block: 0.5rem; font-weight: 400; transition: border 0.3s ease; span { color: var(--primary-contrast); transition: color 0.3s ease; margin-inline-start: 0.1rem; } docs-icon { font-size: 1.3rem; color: var(--quaternary-contrast); transition: color 0.3s ease; } } } // select dropdown .adev-template-dropdown { border: 1px solid var(--senary-contrast); border-radius: 0.25rem; padding: 0; transform: translateY(-0.7rem); li { list-style: none; width: 198px; box-sizing: border-box; button { background: var(--page-background); font-size: 0.875rem; width: 100%; text-align: left; padding-block: 0.5rem; color: var(--quaternary-contrast); transition: color 0.3s ease, background 0.3s ease; font-weight: 400; &:hover { background: var(--senary-contrast); color: var(--primary-contrast); } } } }
{ "end_byte": 1818, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/playground/playground.component.scss" }
angular/adev/src/app/features/playground/playground.component.spec.ts_0_1669
/*! * @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 {ComponentFixture, TestBed} from '@angular/core/testing'; import { EMBEDDED_EDITOR_SELECTOR, EmbeddedEditor, NodeRuntimeSandbox, EmbeddedTutorialManager, } from '../../editor'; import {mockAsyncProvider} from '../../core/services/inject-async'; import TutorialPlayground from './playground.component'; @Component({ selector: EMBEDDED_EDITOR_SELECTOR, template: '<div>FakeEmbeddedEditor</div>', standalone: true, }) class FakeEmbeddedEditor {} class FakeNodeRuntimeSandbox { init() { return Promise.resolve(); } } describe('TutorialPlayground', () => { let component: TutorialPlayground; let fixture: ComponentFixture<TutorialPlayground>; beforeEach(() => { TestBed.configureTestingModule({ imports: [TutorialPlayground], providers: [ { provide: EmbeddedTutorialManager, useValue: { fetchAndSetTutorialFiles: () => {}, }, }, mockAsyncProvider(NodeRuntimeSandbox, FakeNodeRuntimeSandbox), ], }); TestBed.overrideComponent(TutorialPlayground, { remove: { imports: [EmbeddedEditor], }, add: { imports: [FakeEmbeddedEditor], }, }); fixture = TestBed.createComponent(TutorialPlayground); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
{ "end_byte": 1669, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/playground/playground.component.spec.ts" }
angular/adev/src/app/features/references/cli-reference-details-page/cli-reference-details-page.component.html_0_339
<div class="adev-header-and-tabs adev-cli-content docs-scroll-track-transparent"> <docs-viewer [docContent]="mainContentInnerHtml()" /> </div> <docs-viewer class="adev-cli-members-container" [docContent]="cardsInnerHtml()" (contentLoaded)="contentLoaded()" /> <div id="jump-msg" class="cdk-visually-hidden">Jump to details</div>
{ "end_byte": 339, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/cli-reference-details-page/cli-reference-details-page.component.html" }
angular/adev/src/app/features/references/cli-reference-details-page/cli-reference-details-page.component.scss_0_2602
@use '@angular/docs/styles/media-queries' as mq; // Note: cli-reference-details-page is receiving page styles // from api-reference-details-page.component.scss // stylelint-disable-next-line ::ng-deep { .adev-ref-content { display: flex; padding-block: 1rem; gap: 1rem; &:not(:last-of-type) { border-block-end: 1px solid var(--senary-contrast); } } .adev-header-and-tabs { &.adev-cli-content { width: 50%; @include mq.for-desktop-down { width: 100%; } } } .adev-cli-members-container { width: 50%; padding: 0 var(--layout-padding) 1rem 0; margin-top: 8.3125rem; padding-bottom: 1rem; box-sizing: border-box; max-width: 60ch; @include mq.for-desktop-down { width: 100%; padding: var(--layout-padding); // override js applied margin top margin-block-start: 0 !important; max-width: none; } } .adev-ref-option-and-description { flex-grow: 1; max-width: calc(100% - 80px); p { margin-block-end: 0; } } .docs-reference-type-and-default { width: 4.375rem; flex-shrink: 0; span { display: block; font-size: 0.875rem; margin-block-end: 0.2rem; white-space: nowrap; &:not(:first-child) { margin-block-start: 1rem; } } code { font-size: 0.775rem; } } .adev-reference-cli-toc { border: 1px solid var(--senary-contrast); border-radius: 0.3rem; position: relative; transition: border 0.3s ease; &::before { content: ''; inset: -1px; position: absolute; background: transparent; border-radius: 0.35rem; z-index: 0; } &:has(.shiki-ln-line-highlighted) { &::before { background: var(--red-to-pink-to-purple-horizontal-gradient); } } pre { border-radius: 0.25rem; position: relative; z-index: 100; background: var(--octonary-contrast); } } .shiki-ln-line-argument, .shiki-ln-line-option { padding: 0.1rem 0.2rem 0.2rem; margin-inline: 0.1rem; color: var(--quaternary-contrast); background: transparent; border-radius: 0.25rem; position: relative; transition: color 0.3s ease, background 0.3s ease, border 0.3s ease; &:hover { color: var(--primary-contrast); background: var(--septenary-contrast); } &.shiki-ln-line-highlighted { color: var(--primary-contrast); background: var(--senary-contrast); } } .shiki-ln-line-argument { margin-inline-start: 0.2rem; } }
{ "end_byte": 2602, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/cli-reference-details-page/cli-reference-details-page.component.scss" }
angular/adev/src/app/features/references/cli-reference-details-page/cli-reference-details-page.component.ts_0_2920
/*! * @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} from '@angular/common'; import { ChangeDetectionStrategy, Component, DestroyRef, OnInit, inject, signal, } from '@angular/core'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {DocContent, DocViewer} from '@angular/docs'; import {ActivatedRoute} from '@angular/router'; import {map} from 'rxjs/operators'; import {ReferenceScrollHandler} from '../services/reference-scroll-handler.service'; import {API_REFERENCE_DETAILS_PAGE_MEMBERS_CLASS_NAME} from '../constants/api-reference-prerender.constants'; export const CLI_MAIN_CONTENT_SELECTOR = '.docs-reference-cli-content'; export const CLI_TOC = '.adev-reference-cli-toc'; @Component({ selector: 'adev-cli-reference-page', standalone: true, imports: [DocViewer], templateUrl: './cli-reference-details-page.component.html', styleUrls: [ './cli-reference-details-page.component.scss', '../api-reference-details-page/api-reference-details-page.component.scss', ], providers: [ReferenceScrollHandler], changeDetection: ChangeDetectionStrategy.OnPush, }) export default class CliReferenceDetailsPage implements OnInit { private readonly activatedRoute = inject(ActivatedRoute); private readonly destroyRef = inject(DestroyRef); private readonly document = inject(DOCUMENT); private readonly scrollHandler = inject(ReferenceScrollHandler); cardsInnerHtml = signal<string>(''); mainContentInnerHtml = signal<string>(''); membersMarginTopInPx = this.scrollHandler.membersMarginTopInPx; ngOnInit(): void { this.setPageContent(); } contentLoaded(): void { this.scrollHandler.setupListeners(CLI_TOC); this.scrollHandler.updateMembersMarginTop(CLI_TOC); } // Fetch the content for CLI Reference page based on the active route. private setPageContent(): void { this.activatedRoute.data .pipe( map((data) => data['docContent']), takeUntilDestroyed(this.destroyRef), ) .subscribe((doc: DocContent | undefined) => { this.setContentForPageSections(doc); }); } private setContentForPageSections(doc: DocContent | undefined) { const element = this.document.createElement('div'); element.innerHTML = doc?.contents!; // Get the innerHTML of the main content from received document. const mainContent = element.querySelector(CLI_MAIN_CONTENT_SELECTOR); if (mainContent) { this.mainContentInnerHtml.set(mainContent.innerHTML); } // Get the innerHTML of the cards from received document. const cards = element.querySelector(API_REFERENCE_DETAILS_PAGE_MEMBERS_CLASS_NAME); if (cards) { this.cardsInnerHtml.set(cards.innerHTML); } element.remove(); } }
{ "end_byte": 2920, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/cli-reference-details-page/cli-reference-details-page.component.ts" }
angular/adev/src/app/features/references/cli-reference-details-page/cli-reference-details-page.component.spec.ts_0_2120
/*! * @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 {TestBed} from '@angular/core/testing'; import CliReferenceDetailsPage from './cli-reference-details-page.component'; import {RouterTestingHarness, RouterTestingModule} from '@angular/router/testing'; import {signal} from '@angular/core'; import {ReferenceScrollHandler} from '../services/reference-scroll-handler.service'; import {provideRouter} from '@angular/router'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; describe('CliReferenceDetailsPage', () => { let component: CliReferenceDetailsPage; let harness: RouterTestingHarness; let fakeApiReferenceScrollHandler = { setupListeners: () => {}, membersMarginTopInPx: signal(0), updateMembersMarginTop: () => {}, }; const SAMPLE_CONTENT = ` <div class="cli"> <div class="docs-reference-cli-content">First column content</div> <div class="docs-reference-members-container">Members content</div> </div> `; beforeEach(async () => { TestBed.configureTestingModule({ imports: [CliReferenceDetailsPage, RouterTestingModule], providers: [ provideRouter([ { path: '**', component: CliReferenceDetailsPage, data: { 'docContent': { id: 'id', contents: SAMPLE_CONTENT, }, }, }, ]), ], }); TestBed.overrideProvider(ReferenceScrollHandler, {useValue: fakeApiReferenceScrollHandler}); harness = await RouterTestingHarness.create(); const {fixture} = harness; component = await harness.navigateByUrl('/', CliReferenceDetailsPage); TestbedHarnessEnvironment.loader(fixture); fixture.detectChanges(); }); it('should set content on init', () => { expect(component.mainContentInnerHtml()).toBe('First column content'); expect(component.cardsInnerHtml()).toBe('Members content'); }); });
{ "end_byte": 2120, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/cli-reference-details-page/cli-reference-details-page.component.spec.ts" }