_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.ts_0_5522
/*! * @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 { AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, Injector, OnInit, ViewChild, afterNextRender, inject, signal, } from '@angular/core'; import {DOCUMENT} from '@angular/common'; import {MatTabGroup, MatTabsModule} from '@angular/material/tabs'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {distinctUntilChanged, map} from 'rxjs/operators'; import {DocContent, DocViewer} from '@angular/docs'; import {ActivatedRoute, Router} from '@angular/router'; import {ApiItemType} from './../interfaces/api-item-type'; import {ReferenceScrollHandler} from '../services/reference-scroll-handler.service'; import { API_REFERENCE_DETAILS_PAGE_HEADER_CLASS_NAME, API_REFERENCE_DETAILS_PAGE_MEMBERS_CLASS_NAME, API_REFERENCE_TAB_ATTRIBUTE, API_REFERENCE_TAB_QUERY_PARAM, API_REFERENCE_TAB_API_LABEL, API_TAB_CLASS_NAME, API_REFERENCE_TAB_BODY_CLASS_NAME, API_REFERENCE_TAB_URL_ATTRIBUTE, } from '../constants/api-reference-prerender.constants'; import {AppScroller} from '../../../app-scroller'; @Component({ selector: 'adev-reference-page', standalone: true, imports: [DocViewer, MatTabsModule], templateUrl: './api-reference-details-page.component.html', styleUrls: ['./api-reference-details-page.component.scss'], providers: [ReferenceScrollHandler], changeDetection: ChangeDetectionStrategy.OnPush, }) export default class ApiReferenceDetailsPage implements OnInit, AfterViewInit { @ViewChild(MatTabGroup, {static: true}) matTabGroup!: MatTabGroup; private readonly activatedRoute = inject(ActivatedRoute); private readonly destroyRef = inject(DestroyRef); private readonly document = inject(DOCUMENT); private readonly router = inject(Router); private readonly scrollHandler = inject(ReferenceScrollHandler); private readonly appScroller = inject(AppScroller); private readonly injector = inject(Injector); ApiItemType = ApiItemType; canDisplayCards = signal<boolean>(false); tabs = signal<{url: string; title: string; content: string}[]>([]); headerInnerHtml = signal<string | undefined>(undefined); membersInnerHtml = signal<string | undefined>(undefined); membersMarginTopInPx = this.scrollHandler.membersMarginTopInPx; selectedTabIndex = signal(0); constructor() { this.appScroller.disableScrolling = true; } ngOnInit(): void { this.setPageContent(); } ngOnDestroy() { this.appScroller.disableScrolling = false; } ngAfterViewInit(): void { this.setActiveTab(); this.listenToTabChange(); } membersCardsLoaded(): void { this.scrollHandler.setupListeners(API_TAB_CLASS_NAME); } // Fetch the content for API 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); afterNextRender(() => this.setActiveTab(), {injector: this.injector}); }); } private listenToTabChange(): void { this.matTabGroup.selectedIndexChange .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((index) => { this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: {tab: this.tabs()[index].url}, queryParamsHandling: 'merge', }); }); } private setContentForPageSections(doc: DocContent | undefined): void { const element = this.document.createElement('div'); element.innerHTML = doc?.contents!; // Get the innerHTML of the header element from received document. const header = element.querySelector(API_REFERENCE_DETAILS_PAGE_HEADER_CLASS_NAME); if (header) { this.headerInnerHtml.set(header.innerHTML); } // Get the innerHTML of the card elements from received document. const members = element.querySelector(API_REFERENCE_DETAILS_PAGE_MEMBERS_CLASS_NAME); if (members) { this.membersInnerHtml.set(members.innerHTML); } // Get the tab elements from received document. // We're expecting that tab element will contain `tab` attribute. const tabs = Array.from(element.querySelectorAll(`[${API_REFERENCE_TAB_ATTRIBUTE}]`)); this.tabs.set( tabs.map((tab) => ({ url: tab.getAttribute(API_REFERENCE_TAB_URL_ATTRIBUTE)!, title: tab.getAttribute(API_REFERENCE_TAB_ATTRIBUTE)!, content: tab.innerHTML, })), ); element.remove(); } private setActiveTab(): void { this.activatedRoute.queryParamMap .pipe(distinctUntilChanged(), takeUntilDestroyed(this.destroyRef)) .subscribe((paramsMap) => { const selectedTabUrl = paramsMap.get(API_REFERENCE_TAB_QUERY_PARAM); const tabIndexToSelect = this.tabs().findIndex((tab) => tab.url === selectedTabUrl); this.selectedTabIndex.set(tabIndexToSelect < 0 ? 0 : tabIndexToSelect); this.scrollHandler.updateMembersMarginTop(API_REFERENCE_TAB_BODY_CLASS_NAME); const isApiTabActive = this.tabs()[this.selectedTabIndex()]?.title === API_REFERENCE_TAB_API_LABEL || this.tabs()[this.selectedTabIndex()]?.title === 'CLI'; this.canDisplayCards.set(isApiTabActive); }); } }
{ "commit_id": "cb34e406ba", "end_byte": 5522, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.ts" }
angular/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.spec.ts_0_3831
/*! * @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 {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {TestBed} from '@angular/core/testing'; import {MatTabGroupHarness} from '@angular/material/tabs/testing'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {ReferenceScrollHandler} from '../services/reference-scroll-handler.service'; import {signal} from '@angular/core'; import {provideRouter} from '@angular/router'; import {RouterTestingHarness, RouterTestingModule} from '@angular/router/testing'; import ApiReferenceDetailsPage from './api-reference-details-page.component'; import {By} from '@angular/platform-browser'; describe('ApiReferenceDetailsPage', () => { let component: ApiReferenceDetailsPage; let loader: HarnessLoader; let harness: RouterTestingHarness; let fakeApiReferenceScrollHandler = { setupListeners: () => {}, membersMarginTopInPx: signal(10), updateMembersMarginTop: () => {}, }; const SAMPLE_CONTENT_WITH_TABS = `<div class="docs-reference-tabs"> <div data-tab="API" data-tab-url="api" class="adev-reference-tab"></div> <div data-tab="Description" data-tab-url="description" class="adev-reference-tab"></div> <div data-tab="Examples" data-tab-url="examples" class="adev-reference-tab"></div> <div data-tab="Usage Notes" data-tab-url="usage-notes" class="adev-reference-tab"></div> <div class="docs-reference-members-container"></div> </div>`; beforeEach(async () => { TestBed.configureTestingModule({ imports: [ApiReferenceDetailsPage, RouterTestingModule, NoopAnimationsModule], providers: [ provideRouter([ { path: '**', component: ApiReferenceDetailsPage, data: { 'docContent': { id: 'id', contents: SAMPLE_CONTENT_WITH_TABS, }, }, }, ]), ], }); TestBed.overrideProvider(ReferenceScrollHandler, {useValue: fakeApiReferenceScrollHandler}); harness = await RouterTestingHarness.create(); const {fixture} = harness; component = await harness.navigateByUrl('/', ApiReferenceDetailsPage); loader = TestbedHarnessEnvironment.loader(fixture); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should render tabs for all elements with tab attribute', async () => { const matTabGroup = await loader.getHarness(MatTabGroupHarness); const tabs = await matTabGroup.getTabs(); expect(tabs.length).toBe(4); }); it('should display members cards when API tab is active', async () => { const matTabGroup = await loader.getHarness(MatTabGroupHarness); const tabs = await matTabGroup.getTabs(); let membersCard = harness.fixture.debugElement.query( By.css('.docs-reference-members-container'), ); expect(membersCard).toBeTruthy(); await matTabGroup.selectTab({label: await tabs[1].getLabel()}); membersCard = harness.fixture.debugElement.query(By.css('.docs-reference-members-container')); expect(membersCard).toBeFalsy(); await matTabGroup.selectTab({label: await tabs[0].getLabel()}); membersCard = harness.fixture.debugElement.query(By.css('.docs-reference-members-container')); expect(membersCard).toBeTruthy(); }); it('should setup scroll listeners when API members are loaded', () => { const setupListenersSpy = spyOn(fakeApiReferenceScrollHandler, 'setupListeners'); component.membersCardsLoaded(); expect(setupListenersSpy).toHaveBeenCalled(); }); });
{ "commit_id": "cb34e406ba", "end_byte": 3831, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.spec.ts" }
angular/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.html_0_878
<div class="adev-header-and-tabs docs-scroll-track-transparent"> <docs-viewer [docContent]="headerInnerHtml()" class="docs-reference-header"></docs-viewer> <mat-tab-group class="docs-reference-tabs" animationDuration="0ms" mat-stretch-tabs="false" [selectedIndex]="selectedTabIndex()"> @for (tab of tabs(); track tab) { <mat-tab [label]="tab.title"> <div class="adev-reference-tab-body"> <docs-viewer [docContent]="tab.content"></docs-viewer> </div> </mat-tab> } </mat-tab-group> </div> @if (canDisplayCards() && membersMarginTopInPx() > 0) { <docs-viewer class="docs-reference-members-container" [docContent]="membersInnerHtml()" [style.marginTop.px]="membersMarginTopInPx()" (contentLoaded)="membersCardsLoaded()"> </docs-viewer> } <div id="jump-msg" class="cdk-visually-hidden">Jump to details</div>
{ "commit_id": "cb34e406ba", "end_byte": 878, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.html" }
angular/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.scss_0_434
@use '@angular/docs/styles/media-queries' as mq; :host { display: flex; gap: 1rem; width: 100%; box-sizing: border-box; @include mq.for-desktop-down { flex-direction: column; } h1 { font-size: 1.5rem; } h2 { font-size: 1.25rem; } h3 { font-size: 1rem; } h4 { font-size: 0.95rem; } h5 { font-size: 0.875rem; } h6 { font-size: 0.6rem; } } // stylelint-disable-next-line
{ "commit_id": "cb34e406ba", "end_byte": 434, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.scss" }
angular/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.scss_435_7432
::ng-deep { .adev-header-and-tabs { padding: var(--layout-padding) 0 1rem var(--layout-padding); box-sizing: border-box; @include mq.for-desktop-up { // this section should only be independently scrollable if // the API tab is active & the screen is wide enough &:has(.docs-reference-api-tab), &.adev-cli-content { position: sticky; top: 0; padding-inline-end: 1rem; max-height: 100vh; height: max-content; overflow-y: scroll; width: 50%; } &:has(.docs-reference-api-tab) { width: 60%; } &:not(:has(.docs-reference-api-tab)) { width: 100%; max-width: var(--page-width); } } @include mq.for-desktop-down { padding: var(--layout-padding); width: 100%; } &::-webkit-scrollbar-thumb { background-color: var(--septenary-contrast); border-radius: 10px; transition: background-color 0.3s ease; } } .docs-code { pre { margin-block: 0; } } .docs-reference-header { > p { color: var(--secondary-contrast); margin-block-start: 0; margin-block-end: 1.5rem; } .docs-code { margin-block-end: 1.5rem; } } .adev-reference-tab-body { margin-block-start: 1.5rem; docs-viewer > div { :first-child { margin-top: 0; } } } .docs-reference-api-tab { display: flex; gap: 1.81rem; align-items: flex-start; margin-bottom: 1px; @include mq.for-desktop-down { flex-direction: column; } & > .docs-code { box-sizing: border-box; width: 100%; overflow: hidden; padding: 0; @include mq.for-desktop-down { width: 100%; position: static; } button { transition: background-color 0.3s ease; font-family: monospace; &.line { font-weight: 400; text-align: left; padding-block: 0.25rem; } &.shiki-ln-line-highlighted { background-color: var(--senary-contrast); } &:hover { background-color: var(--septenary-contrast); } &:focus { background-color: var(--senary-contrast); } } // Hide copy source code button button[docs-copy-source-code] { display: none; } } code { margin-block: 0; } pre { white-space: pre; overflow-x: auto; margin: 0; } } .docs-reference-cli-toc { margin-bottom: 1rem; } .adev-reference-tab { min-width: 50ch; margin-block-start: 2.5rem; } .docs-reference-members-container { width: 40%; padding: 0 var(--layout-padding) 1rem 0; box-sizing: border-box; max-width: 60ch; @include mq.for-desktop-down { width: 100%; padding: var(--layout-padding); max-width: none; // override javascript-applied margin-top: // determined by how much space the sticky header takes up // to align the selected card member with the code block margin-block-start: 0 !important; } } // Sidebar .docs-reference-members { display: flex; flex-direction: column; gap: 20px; @include mq.for-desktop-down { width: 100%; } } .docs-reference-title { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; padding-block-end: 0; gap: 0.5rem; > div { margin-block: 0.67em; display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; h1 { margin-block: 0; } } a { fill: var(--quinary-contrast); transition: fill 0.3s ease; &:hover { fill: var(--primary-contrast); } } } .adev-reference-labels { display: flex; gap: 0.5rem; } .docs-reference-category { color: var(--gray-400); font-size: 0.875rem; font-weight: 500; line-height: 1.4rem; letter-spacing: -0.00875rem; } .docs-reference-card-header { display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; flex-wrap: wrap; padding: 0.7rem 1rem; code:not(pre *) { padding: 0 0.3rem; } } .docs-reference-member-card { border: 1px solid var(--senary-contrast); border-radius: 0.25rem; position: relative; transition: border 0.3s ease; &::before { content: ''; inset: -1px; position: absolute; background: transparent; border-radius: 0.35rem; z-index: 0; } &:focus { box-shadow: 10px 4px 40px 0 rgba(0, 0, 0, 0.01); &::before { background: var(--red-to-pink-to-purple-horizontal-gradient); } } header { display: flex; flex-direction: column; border-radius: 0.25rem; background-color: var(--octonary-contrast); position: relative; z-index: 10; cursor: pointer; transition: background-color 0.3s ease, border 0.3s ease; & > code { max-width: 100%; } code:has(pre) { padding: 0; } pre { margin: 0; /* Do we have a better alternative ? */ overflow: auto; } } .docs-reference-card-header { h3 { display: inline-block; font-family: var(--code-font); font-size: 1.25rem; letter-spacing: -0.025rem; margin: 0; } code, span { font-size: 0.875rem; } } > p { padding-inline: 1.25rem; margin-block-end: 0; } } .docs-reference-card-body { padding: 0.25rem 1.25rem; background: var(--septenary-contrast); transition: background-color 0.3s ease; color: var(--quaternary-contrast); border-radius: 0 0 0.25rem 0.25rem; position: relative; z-index: 10; hr { margin-block: 2rem; } .docs-code { margin-block-end: 1rem; } &:empty { display: none; } } // when it's not the only card... .docs-reference-card-item:has(~ .docs-reference-card-item) { border: 1px solid var(--senary-contrast); margin-block: 1rem; border-radius: 0.25rem; padding-inline: 1rem; } // & the last card .docs-reference-card-item:last-child { &:not(:first-of-type) { border: 1px solid var(--senary-contrast); margin-block: 1rem; border-radius: 0.25rem; padding-inline: 1rem; } } .docs-reference-card-item { span { display: inline-block; font-size: 0.875rem; } code { font-size: 0.875rem; } } .docs-function-definition { &:has(*) { border-block-end: 1px solid var(--senary-contrast); } } .docs-deprecation-message { border-block-end: 1px solid var(--senary-contrast); } .docs-param-group { margin-block-start: 1rem; } // If it's the only param group...
{ "commit_id": "cb34e406ba", "end_byte": 7432, "start_byte": 435, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.scss" }
angular/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.scss_7435_8694
.docs-param-group:not(:has(~ .docs-param-group)) { margin-block: 1rem; } .docs-return-type { padding-block: 1rem; // & does not follow a function definition &:not(.docs-function-definition + .docs-return-type) { border-block-start: 1px solid var(--senary-contrast); } } .docs-param-keyword { color: var(--primary-contrast); font-family: var(--code-font); margin-inline-end: 0.5rem; } .docs-param-name { color: var(--vivid-pink); font-family: var(--code-font); margin-inline-end: 0.25rem; &::after { content: ':'; } } .docs-deprecated { color: var(--page-background); background-color: var(--quaternary-contrast); width: max-content; border-radius: 0.25rem; padding: 0.1rem 0.25rem; margin-block-start: 1rem; } // deprecated markers beside header .docs-reference-header ~ .docs-deprecated { margin-block-start: 0.5rem; } .docs-parameter-description { p:first-child { margin-block-start: 0; } } .docs-ref-content { padding: 1rem 0; &:not(:first-child) { border-block-start: 1px solid var(--senary-contrast); } .docs-param-keyword { display: block; margin: 0 0 0.5rem 0; } } }
{ "commit_id": "cb34e406ba", "end_byte": 8694, "start_byte": 7435, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-details-page/api-reference-details-page.component.scss" }
angular/adev/src/app/features/references/constants/api-reference-prerender.constants.ts_0_1100
/*! * @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 const API_REFERENCE_DETAILS_PAGE_CONTENT_CLASS_NAME = '.adev-reference-content'; export const API_REFERENCE_DETAILS_PAGE_HEADER_CLASS_NAME = '.docs-reference-header'; export const API_REFERENCE_DETAILS_PAGE_MEMBERS_CLASS_NAME = '.docs-reference-members-container'; export const API_REFERENCE_TAB_BODY_CLASS_NAME = '.adev-reference-tab-body'; export const API_REFERENCE_TAB_ATTRIBUTE = 'data-tab'; export const API_REFERENCE_TAB_URL_ATTRIBUTE = 'data-tab-url'; export const API_REFERENCE_TAB_API_LABEL = 'API'; export const API_REFERENCE_TAB_QUERY_PARAM = 'tab'; export const API_TAB_CLASS_NAME = '.docs-reference-api-tab'; export const API_REFERENCE_MEMBER_CARD_CLASS_NAME = '.docs-reference-member-card'; export const API_TAB_ACTIVE_CODE_LINE = 'shiki-ln-line-highlighted'; export const HIGHLIGHT_JS_CODE_LINE_CLASS_NAME = 'shiki-ln-line'; export const MEMBER_ID_ATTRIBUTE = 'member-id';
{ "commit_id": "cb34e406ba", "end_byte": 1100, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/constants/api-reference-prerender.constants.ts" }
angular/adev/src/app/features/references/api-items-section/api-items-section.component.scss_0_2164
@use '@angular/docs/styles/anchor' as anchor; .adev-api-items-section-header { display: flex; svg { fill: var(--primary-contrast); } h3 { flex: 1; display: flex; gap: 0.75em; align-items: flex-start; margin-top: 1.43rem; font-size: 1.25rem; } .adev-link-icon { color: var(--quinary-contrast); cursor: pointer; &:hover { color: var(--primary-contrast); } } } .adev-api-items-section-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; padding: 0; @container api-ref-page (max-width: 798px) { grid-template-columns: 1fr 1fr; } @container api-ref-page (max-width: 600px) { grid-template-columns: 1fr; } li { display: flex; align-items: center; border-inline-start: 1px solid var(--senary-contrast); padding: 0.3rem; padding-inline-start: 0.75rem; font-size: 0.875rem; a { color: var(--quaternary-contrast); display: flex; align-items: center; } .adev-item-title { margin-block-start: 3px; } // star icon .adev-api-items-section-item-featured { opacity: 0; border: none; background-color: transparent; color: var(--quinary-contrast); cursor: pointer; margin-top: -2px; transition: color 0.3s ease; &-active { opacity: 1; color: var(--quinary-contrast); } } &:hover { border-inline-start: 1px solid var(--quaternary-contrast); background-color: var(--septenary-contrast); a { color: var(--primary-contrast); } .adev-api-items-section-item-featured-active { color: var(--tertiary-contrast); } } } } .adev-api-item-in-featured-section { display: none; } .adev-api-items-section-item { display: flex; flex: 1; gap: 1em; } .docs-deprecated { font-family: var(--code-font); background-color: var(--senary-contrast); color: var(--tertiary-contrast); width: max-content; border-radius: 0.25rem; padding: 0.001rem 0.2rem 0.005rem; margin-inline-start: 0.5rem; } .adev-api-anchor { color: inherit; @include anchor.docs-anchor(); }
{ "commit_id": "cb34e406ba", "end_byte": 2164, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-items-section/api-items-section.component.scss" }
angular/adev/src/app/features/references/api-items-section/api-items-section.component.html_0_1473
<header class="adev-api-items-section-header"> <h3 [attr.id]="group.id"> @if (group.isFeatured) { <docs-icon aria-hidden>star</docs-icon> } <!-- we use innerHtml because the title can be an html string--> <a routerLink="/api" [fragment]="group.id" queryParamsHandling="preserve" class="adev-api-anchor" tabindex="-1" [innerHtml]="group.title" ></a> </h3> </header> <ul class="adev-api-items-section-grid"> @for (apiItem of group.items; track apiItem.url) { <li [class.adev-api-items-section-item-deprecated]="apiItem.isDeprecated"> <a [routerLink]="'/' + apiItem.url" class="adev-api-items-section-item" [attr.aria-describedby]="apiItem.isDeprecated ? 'deprecated-description' : null" > <docs-api-item-label [type]="apiItem.itemType" mode="short" class="docs-api-item-label" aria-hidden="true" /> <span class="adev-item-title">{{ apiItem.title }}</span> </a> @if (apiItem.isDeprecated) { <span class="docs-deprecated"> &lt;!&gt; </span> } @if (apiItem.isFeatured) { <docs-icon class="adev-api-items-section-item-featured" [class.adev-api-item-in-featured-section]="group.isFeatured" [class.adev-api-items-section-item-featured-active]="apiItem.isFeatured" > star </docs-icon> } </li> } </ul>
{ "commit_id": "cb34e406ba", "end_byte": 1473, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-items-section/api-items-section.component.html" }
angular/adev/src/app/features/references/api-items-section/api-items-section.component.ts_0_875
/*! * @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, Input} from '@angular/core'; import {RouterLink} from '@angular/router'; import {ApiItemsGroup} from '../interfaces/api-items-group'; import ApiItemLabel from '../api-item-label/api-item-label.component'; import {IconComponent} from '@angular/docs'; @Component({ selector: 'adev-api-items-section', standalone: true, imports: [ApiItemLabel, RouterLink, IconComponent], templateUrl: './api-items-section.component.html', styleUrls: ['./api-items-section.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export default class ApiItemsSection { @Input({required: true}) group!: ApiItemsGroup; }
{ "commit_id": "cb34e406ba", "end_byte": 875, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-items-section/api-items-section.component.ts" }
angular/adev/src/app/features/references/api-items-section/api-items-section.component.spec.ts_0_3941
/*! * @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 ApiItemsSection from './api-items-section.component'; import {ApiItemsGroup} from '../interfaces/api-items-group'; import {ApiReferenceManager} from '../api-reference-list/api-reference-manager.service'; import {ApiItemType} from '../interfaces/api-item-type'; import {RouterTestingModule} from '@angular/router/testing'; import {By} from '@angular/platform-browser'; describe('ApiItemsSection', () => { let component: ApiItemsSection; let fixture: ComponentFixture<ApiItemsSection>; let apiReferenceManagerSpy: jasmine.SpyObj<ApiReferenceManager>; const fakeFeaturedGroup: ApiItemsGroup = { title: 'Featured', id: 'featured', isFeatured: true, items: [ { title: 'Fake Featured Title', itemType: ApiItemType.CLASS, url: 'api/fakeFeaturedTitle', isFeatured: true, }, { title: 'Fake Deprecated Title', itemType: ApiItemType.CONST, url: 'api/fakeDeprecatedTitle', isFeatured: false, isDeprecated: true, }, { title: 'Fake Standard Title', itemType: ApiItemType.DIRECTIVE, url: 'api/fakeTitle', isFeatured: false, }, ], }; const fakeGroup: ApiItemsGroup = { title: 'Example group', id: 'example', isFeatured: false, items: [ {title: 'Fake Title', itemType: ApiItemType.CONST, url: 'api/fakeTitle', isFeatured: false}, ], }; beforeEach(() => { TestBed.configureTestingModule({ imports: [ApiItemsSection, RouterTestingModule], providers: [{provide: ApiReferenceManager, useValue: apiReferenceManagerSpy}], }); fixture = TestBed.createComponent(ApiItemsSection); component = fixture.componentInstance; }); it('should render star icon for featured group', () => { component.group = fakeFeaturedGroup; fixture.detectChanges(); const starIcon = fixture.debugElement.query(By.css('.adev-api-items-section-header docs-icon')); expect(starIcon).toBeTruthy(); }); it('should not render star icon for standard group', () => { component.group = fakeGroup; fixture.detectChanges(); const starIcon = fixture.debugElement.query(By.css('.adev-api-items-section-header docs-icon')); expect(starIcon).toBeFalsy(); }); it('should render list of all APIs of provided group', () => { component.group = fakeFeaturedGroup; fixture.detectChanges(); const apis = fixture.debugElement.queryAll(By.css('.adev-api-items-section-grid li')); expect(apis.length).toBe(3); }); it('should display deprecated icon for deprecated API', () => { component.group = fakeFeaturedGroup; fixture.detectChanges(); const deprecatedApiIcons = fixture.debugElement.queryAll( By.css('.adev-api-items-section-grid li .docs-deprecated'), ); const deprecatedApiTitle = deprecatedApiIcons[0].parent?.query(By.css('.adev-item-title')); expect(deprecatedApiIcons.length).toBe(1); expect(deprecatedApiIcons[0]).toBeTruthy(); expect(deprecatedApiTitle?.nativeElement.innerText).toBe('Fake Deprecated Title'); }); it('should display star icon for featured API', () => { component.group = fakeFeaturedGroup; fixture.detectChanges(); const featuredApiIcons = fixture.debugElement.queryAll( By.css('.adev-api-items-section-grid li .adev-api-items-section-item-featured'), ); const featuredApiTitle = featuredApiIcons[0].parent?.query(By.css('.adev-item-title')); expect(featuredApiIcons.length).toBe(1); expect(featuredApiIcons[0]).toBeTruthy(); expect(featuredApiTitle?.nativeElement.innerText).toBe('Fake Featured Title'); }); });
{ "commit_id": "cb34e406ba", "end_byte": 3941, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-items-section/api-items-section.component.spec.ts" }
angular/adev/src/app/features/references/api-reference-list/api-reference-manager.service.spec.ts_0_814
/*! * @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 {ApiReferenceManager} from './api-reference-manager.service'; import {LOCAL_STORAGE} from '@angular/docs'; describe('ApiReferenceManager', () => { let service: ApiReferenceManager; let localStorageSpy: jasmine.SpyObj<Storage>; beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: LOCAL_STORAGE, useValue: localStorageSpy, }, ], }); service = TestBed.inject(ApiReferenceManager); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
{ "commit_id": "cb34e406ba", "end_byte": 814, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-list/api-reference-manager.service.spec.ts" }
angular/adev/src/app/features/references/api-reference-list/api-reference-list.component.ts_0_3781
/*! * @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, ElementRef, Injector, afterNextRender, computed, effect, inject, model, signal, viewChild, } from '@angular/core'; import ApiItemsSection from '../api-items-section/api-items-section.component'; import {FormsModule} from '@angular/forms'; import {SlideToggle, TextField} from '@angular/docs'; import {Params, Router} from '@angular/router'; import {ApiItemType} from '../interfaces/api-item-type'; import {ApiReferenceManager} from './api-reference-manager.service'; import ApiItemLabel from '../api-item-label/api-item-label.component'; import {ApiLabel} from '../pipes/api-label.pipe'; import {ApiItemsGroup} from '../interfaces/api-items-group'; export const ALL_STATUSES_KEY = 'All'; @Component({ selector: 'adev-reference-list', standalone: true, imports: [ApiItemsSection, ApiItemLabel, FormsModule, SlideToggle, TextField, ApiLabel], templateUrl: './api-reference-list.component.html', styleUrls: ['./api-reference-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export default class ApiReferenceList { private readonly apiReferenceManager = inject(ApiReferenceManager); private readonly router = inject(Router); filterInput = viewChild.required(TextField, {read: ElementRef}); private readonly injector = inject(Injector); private readonly allGroups = this.apiReferenceManager.apiGroups; constructor() { effect(() => { const filterInput = this.filterInput(); afterNextRender( { write: () => { // Lord forgive me for I have sinned // Use the CVA to focus when https://github.com/angular/angular/issues/31133 is implemented if (matchMedia('(hover: hover) and (pointer:fine)').matches) { filterInput.nativeElement.querySelector('input').focus(); } }, }, {injector: this.injector}, ); }); effect( () => { const params: Params = { 'query': this.query() ? this.query() : null, 'type': this.type() ? this.type() : null, }; this.router.navigate([], { queryParams: params, replaceUrl: true, preserveFragment: true, info: { disableScrolling: true, }, }); }, {allowSignalWrites: true}, ); } query = model<string | undefined>(''); includeDeprecated = signal(false); type = model<string | undefined>(ALL_STATUSES_KEY); featuredGroup = this.apiReferenceManager.featuredGroup; filteredGroups = computed((): ApiItemsGroup[] => { return this.allGroups() .map((group) => ({ title: group.title, isFeatured: group.isFeatured, id: group.id, items: group.items.filter((apiItem) => { return ( (this.query() !== undefined ? apiItem.title .toLocaleLowerCase() .includes((this.query() as string).toLocaleLowerCase()) : true) && (this.includeDeprecated() ? true : apiItem.isDeprecated === this.includeDeprecated()) && (this.type() === undefined || this.type() === ALL_STATUSES_KEY || apiItem.itemType === this.type()) ); }), })) .filter((group) => group.items.length > 0); }); itemTypes = Object.values(ApiItemType); filterByItemType(itemType: ApiItemType): void { this.type.update((currentType) => (currentType === itemType ? ALL_STATUSES_KEY : itemType)); } }
{ "commit_id": "cb34e406ba", "end_byte": 3781, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-list/api-reference-list.component.ts" }
angular/adev/src/app/features/references/api-reference-list/api-reference-list.component.html_0_1360
<div class="adev-reference-list-page"> <header> <h6>Getting Started</h6> <h1>API Reference</h1> </header> @if (featuredGroup().items.length) { <adev-api-items-section [group]="featuredGroup()" class="adev-featured-list" /> } <form class="adev-reference-list-form"> <ul class="adev-reference-list-legend"> @for (itemType of itemTypes; track itemType) { <li class="adev-reference-list-legend-item" [class.adev-reference-list-legend-item-active]="type() === itemType" (click)="filterByItemType(itemType)" > <docs-api-item-label [type]="itemType" mode="short" class="docs-api-item-label" /> <span class="docs-api-item-label-full">{{ itemType | adevApiLabel : 'full' }}</span> </li> } </ul> <docs-text-field name="query" placeholder="Filter" [(ngModel)]="query" /> <div class="adev-reference-list-form-part-two"> <docs-slide-toggle buttonId="includeDeprecated" label="Show @deprecated" name="includeDeprecated" [(ngModel)]="includeDeprecated" /> </div> @for (group of filteredGroups(); track group.id) { <adev-api-items-section [group]="group" /> } @empty { <div class="adev-reference-list-empty"> <p>No API items found.</p> </div> } </form> </div>
{ "commit_id": "cb34e406ba", "end_byte": 1360, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-list/api-reference-list.component.html" }
angular/adev/src/app/features/references/api-reference-list/api-reference-list.component.scss_0_2285
.adev-reference-list-page { padding: var(--layout-padding); max-width: var(--page-width); container: api-ref-page / inline-size; header { margin-block-end: 2.75rem; // small page label: "Getting Started" h6 { color: var(--quaternary-contrast); font-weight: 500; font-size: 0.875rem; margin: 0; } p { max-width: 78ch; color: var(--secondary-contrast); } } } .adev-reference-list-legend { display: grid; grid-template-columns: repeat(6, 1fr); margin-block-start: 0; padding-inline: 0; cursor: pointer; width: 100%; @container api-ref-page (max-width: 775px) { grid-template-columns: repeat(5, 1fr); } @container api-ref-page (max-width: 600px) { grid-template-columns: repeat(4, 1fr); } @container api-ref-page (max-width: 500px) { grid-template-columns: repeat(3, 1fr); } @container api-ref-page (max-width: 350px) { grid-template-columns: repeat(2, 1fr); } li { display: flex; gap: 0.5rem; align-items: center; padding: 0.3rem; font-size: 0.875rem; color: var(--quaternary-contrast); font-weight: 500; text-transform: capitalize; border: 1px solid transparent; border-radius: 0.25rem; margin-inline-end: 0.5rem; margin-block-end: 0.5rem; transition: color 0.3s ease, background 0.3s ease, border 0.3s ease; &:hover { color: var(--primary-contrast); border: 1px solid var(--senary-contrast); } &.adev-reference-list-legend-item-active { background: var(--septenary-contrast); border: 1px solid var(--quinary-contrast); color: var(--primary-contrast); } } } .adev-reference-list-form { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 1.5rem; padding-block-start: 1.5rem; padding-block-end: 2rem; border-block: 1px solid var(--senary-contrast); } .adev-reference-list-form-part-two { display: flex; gap: 1.5rem; flex-wrap: wrap; } .adev-reference-list-empty { text-align: center; p { font-size: 1rem; } } .adev-featured-list { display: block; padding-block-end: 1rem; margin-block: 1rem; border-top: 0; margin-top: -1.5rem; } .docs-api-item-label-full { white-space: nowrap; }
{ "commit_id": "cb34e406ba", "end_byte": 2285, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-list/api-reference-list.component.scss" }
angular/adev/src/app/features/references/api-reference-list/api-reference-list.component.spec.ts_0_4994
/*! * @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 ApiReferenceList, {ALL_STATUSES_KEY} from './api-reference-list.component'; import {ApiReferenceManager} from './api-reference-manager.service'; import {signal} from '@angular/core'; import {ApiItemType} from '../interfaces/api-item-type'; import {RouterTestingHarness} from '@angular/router/testing'; import {provideRouter} from '@angular/router'; import {Location} from '@angular/common'; describe('ApiReferenceList', () => { let component: ApiReferenceList; let fixture: ComponentFixture<ApiReferenceList>; let fakeItem1 = { 'title': 'fakeItem1', 'url': 'api/animations/fakeItem1', 'itemType': ApiItemType.FUNCTION, 'isDeprecated': false, }; let fakeItem2 = { 'title': 'fakeItem2', 'url': 'api/animations/fakeItem2', 'itemType': ApiItemType.CLASS, 'isDeprecated': false, }; let fakeDeprecatedFeaturedItem = { 'title': 'fakeItemDeprecated', 'url': 'api/animations/fakeItemDeprecated', 'itemType': ApiItemType.INTERFACE, 'isDeprecated': true, }; const fakeApiReferenceManager = { apiGroups: signal([ { title: 'Fake Group', items: [fakeItem1, fakeItem2, fakeDeprecatedFeaturedItem], isFeatured: false, }, ]), featuredGroup: signal({ title: 'Featured Group', items: [], isFeatured: true, }), }; beforeEach(() => { TestBed.configureTestingModule({ imports: [ApiReferenceList], providers: [ {provide: ApiReferenceManager, useValue: fakeApiReferenceManager}, provideRouter([{path: 'api', component: ApiReferenceList}]), ], }); fixture = TestBed.createComponent(ApiReferenceList); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should display both Deprecated and Non-deprecated APIs when includeDeprecated toggle is set to true', () => { component.includeDeprecated.set(true); fixture.detectChanges(); expect(component.filteredGroups()![0].items).toEqual([ fakeItem1, fakeItem2, fakeDeprecatedFeaturedItem, ]); }); it('should display both Non-deprecated APIs when includeDeprecated toggle is set to false', () => { component.includeDeprecated.set(false); fixture.detectChanges(); expect(component.filteredGroups()![0].items).toEqual([fakeItem1, fakeItem2]); }); it('should display only items which contains provided query when query is not empty', () => { component.query.set('Item1'); fixture.detectChanges(); expect(component.filteredGroups()![0].items).toEqual([fakeItem1]); }); it('should display only class items when user selects Class in the Type select', () => { fixture.componentInstance.type.set(ApiItemType.CLASS); fixture.detectChanges(); expect(component.type()).toEqual(ApiItemType.CLASS); expect(component.filteredGroups()![0].items).toEqual([fakeItem2]); }); it('should set selected type when provided type is different than selected', async () => { expect(component.type()).toBe(ALL_STATUSES_KEY); component.filterByItemType(ApiItemType.BLOCK); await RouterTestingHarness.create(`/api?type=${ApiItemType.BLOCK}`); expect(component.type()).toBe(ApiItemType.BLOCK); }); it('should reset selected type when provided type is equal to selected', async () => { component.filterByItemType(ApiItemType.BLOCK); const harness = await RouterTestingHarness.create(`/api?type=${ApiItemType.BLOCK}`); expect(component.type()).toBe(ApiItemType.BLOCK); component.filterByItemType(ApiItemType.BLOCK); harness.navigateByUrl(`/api`); expect(component.type()).toBe(ALL_STATUSES_KEY); }); it('should set the value of the queryParam equal to the query value', async () => { const location = TestBed.inject(Location); component.query.set('item1'); await fixture.whenStable(); expect(location.path()).toBe(`?query=item1&type=All`); }); it('should keep the values of existing queryParams and set new queryParam equal to the type', async () => { const location = TestBed.inject(Location); component.query.set('item1'); await fixture.whenStable(); expect(location.path()).toBe(`?query=item1&type=All`); component.filterByItemType(ApiItemType.BLOCK); await fixture.whenStable(); expect(location.path()).toBe(`?query=item1&type=${ApiItemType.BLOCK}`); }); it('should display all items when query and type are undefined', async () => { component.query.set(undefined); component.type.set(undefined); await fixture.whenStable(); expect(component.filteredGroups()![0].items).toEqual([fakeItem1, fakeItem2]); }); });
{ "commit_id": "cb34e406ba", "end_byte": 4994, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-list/api-reference-list.component.spec.ts" }
angular/adev/src/app/features/references/api-reference-list/api-reference-manager.service.ts_0_2505
/*! * @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, signal} from '@angular/core'; // This file is generated at build-time, error is expected here. import API_MANIFEST_JSON from '../../../../../src/assets/api/manifest.json'; import {getApiUrl} from '../helpers/manifest.helper'; import {ApiItem} from '../interfaces/api-item'; import {ApiItemsGroup} from '../interfaces/api-items-group'; import {ApiManifest} from '../interfaces/api-manifest'; export const FEATURED_API_ITEMS_KEY = 'apiFeaturedItems'; export const FEATURED_GROUP_TITLE = 'Most Common'; export type FeaturedItemsByGroup = Record<string, ApiItem[]>; export const FEATURED_ITEMS_URLS = [ 'api/common/DatePipe', 'api/common/NgIf', 'api/common/NgFor', 'api/common/NgClass', 'api/core/ViewChild', 'api/forms/NgModel', 'api/router/RouterLink', 'api/forms/FormControl', 'api/common/http/HttpClient', 'api/core/OnChanges', 'api/forms/FormGroup', 'api/router/CanActivate', ]; const manifest = API_MANIFEST_JSON as ApiManifest; @Injectable({ providedIn: 'root', }) export class ApiReferenceManager { // Represents group of the featured items. featuredGroup = signal<ApiItemsGroup>({ title: FEATURED_GROUP_TITLE, id: 'featured', items: [], isFeatured: true, }); apiGroups = signal<ApiItemsGroup[]>(this.mapManifestToApiGroups()); private mapManifestToApiGroups(): ApiItemsGroup[] { const groups: ApiItemsGroup[] = []; for (const module of manifest) { groups.push({ title: module.moduleLabel.replace('@angular/', ''), id: module.normalizedModuleName, items: module.entries .map((api) => { const url = getApiUrl(module, api.name); const isFeatured = FEATURED_ITEMS_URLS.some((featuredUrl) => featuredUrl === url); const apiItem = { itemType: api.type, title: api.name, isDeprecated: !!api.isDeprecated, isFeatured, url, }; if (isFeatured) { this.featuredGroup.update((group) => { group.items.push(apiItem); return group; }); } return apiItem; }) .sort((a, b) => a.title.localeCompare(b.title)), }); } return groups; } }
{ "commit_id": "cb34e406ba", "end_byte": 2505, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-reference-list/api-reference-manager.service.ts" }
angular/adev/src/app/features/references/api-item-label/api-item-label.component.html_0_75
@if (apiItemType()) { {{ apiItemType()! | adevApiLabel: labelMode() }} }
{ "commit_id": "cb34e406ba", "end_byte": 75, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-item-label/api-item-label.component.html" }
angular/adev/src/app/features/references/api-item-label/api-item-label.component.ts_0_1044
/*! * @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, Input, signal} from '@angular/core'; import {ApiItemType} from '../interfaces/api-item-type'; import {ApiLabel} from '../pipes/api-label.pipe'; @Component({ selector: 'docs-api-item-label', standalone: true, templateUrl: './api-item-label.component.html', changeDetection: ChangeDetectionStrategy.OnPush, host: { '[attr.data-type]': 'apiItemType()', '[attr.data-mode]': 'labelMode()', }, imports: [ApiLabel], }) export default class ApiItemLabel { @Input({required: true}) set type(value: ApiItemType) { this.apiItemType.set(value); } @Input({required: true}) set mode(value: 'short' | 'full') { this.labelMode.set(value); } protected apiItemType = signal<ApiItemType | undefined>(undefined); protected labelMode = signal<'short' | 'full'>('short'); }
{ "commit_id": "cb34e406ba", "end_byte": 1044, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-item-label/api-item-label.component.ts" }
angular/adev/src/app/features/references/api-item-label/api-item-label.component.spec.ts_0_1488
/*! * @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 ApiItemLabel from './api-item-label.component'; import {ApiItemType} from '../interfaces/api-item-type'; describe('ApiItemLabel', () => { let component: ApiItemLabel; let fixture: ComponentFixture<ApiItemLabel>; beforeEach(() => { TestBed.configureTestingModule({ imports: [ApiItemLabel], }); fixture = TestBed.createComponent(ApiItemLabel); component = fixture.componentInstance; fixture.detectChanges(); }); it('should by default display short label for Class', () => { component.type = ApiItemType.CLASS; fixture.detectChanges(); const label = fixture.nativeElement.innerText; expect(label).toBe('C'); }); it('should display full label for Class when labelMode equals full', () => { component.type = ApiItemType.CLASS; component.mode = 'full'; fixture.detectChanges(); const label = fixture.nativeElement.innerText; expect(label).toBe('Class'); }); it('should display short label for Class when labelMode equals short', () => { component.type = ApiItemType.CLASS; component.mode = 'short'; fixture.detectChanges(); const label = fixture.nativeElement.innerText; expect(label).toBe('C'); }); });
{ "commit_id": "cb34e406ba", "end_byte": 1488, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/api-item-label/api-item-label.component.spec.ts" }
angular/adev/src/app/features/references/pipes/api-label.pipe.spec.ts_0_758
/*! * @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 {ApiItemType} from '../interfaces/api-item-type'; import {ApiLabel} from './api-label.pipe'; describe('ApiLabel', () => { let pipe: ApiLabel; beforeEach(() => { pipe = new ApiLabel(); }); it(`should return short label when labelType equals short`, () => { const result = pipe.transform(ApiItemType.CLASS, 'short'); expect(result).toBe('C'); }); it(`should return short label when labelType equals short`, () => { const result = pipe.transform(ApiItemType.CLASS, 'full'); expect(result).toBe('Class'); }); });
{ "commit_id": "cb34e406ba", "end_byte": 758, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/pipes/api-label.pipe.spec.ts" }
angular/adev/src/app/features/references/pipes/api-label.pipe.ts_0_1681
/*! * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Pipe, PipeTransform} from '@angular/core'; import {ApiItemType} from '../interfaces/api-item-type'; @Pipe({ name: 'adevApiLabel', standalone: true, }) export class ApiLabel implements PipeTransform { private readonly shortLabelsMap: Record<ApiItemType, string> = { [ApiItemType.BLOCK]: 'B', [ApiItemType.CLASS]: 'C', [ApiItemType.CONST]: 'K', [ApiItemType.DECORATOR]: '@', [ApiItemType.DIRECTIVE]: 'D', [ApiItemType.ELEMENT]: 'El', [ApiItemType.ENUM]: 'E', [ApiItemType.FUNCTION]: 'F', [ApiItemType.INTERFACE]: 'I', [ApiItemType.PIPE]: 'P', [ApiItemType.NG_MODULE]: 'M', [ApiItemType.TYPE_ALIAS]: 'T', [ApiItemType.INITIALIZER_API_FUNCTION]: 'IA', }; private readonly fullLabelsMap: Record<ApiItemType, string> = { [ApiItemType.BLOCK]: 'Block', [ApiItemType.CLASS]: 'Class', [ApiItemType.CONST]: 'Const', [ApiItemType.DECORATOR]: 'Decorator', [ApiItemType.DIRECTIVE]: 'Directive', [ApiItemType.ELEMENT]: 'Element', [ApiItemType.ENUM]: 'Enum', [ApiItemType.FUNCTION]: 'Function', [ApiItemType.INTERFACE]: 'Interface', [ApiItemType.PIPE]: 'Pipe', [ApiItemType.NG_MODULE]: 'Module', [ApiItemType.TYPE_ALIAS]: 'Type Alias', [ApiItemType.INITIALIZER_API_FUNCTION]: 'Initializer API', }; transform(value: ApiItemType, labelType: 'short' | 'full'): string { return labelType === 'full' ? this.fullLabelsMap[value] : this.shortLabelsMap[value]; } }
{ "commit_id": "cb34e406ba", "end_byte": 1681, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/pipes/api-label.pipe.ts" }
angular/adev/src/app/features/references/helpers/manifest.helper.spec.ts_0_1528
/*! * @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 {ApiManifestPackage} from '../interfaces/api-manifest'; import {getApiUrl} from './manifest.helper'; describe('ManiferHelper', () => { describe('getApiUrl', () => { it('should return the correct URL for a given package and API name', () => { const packageEntry: ApiManifestPackage = { moduleName: '@angular/common', moduleLabel: 'common', normalizedModuleName: 'angular_common', entries: [], }; const apiName = 'DatePipe'; const result = getApiUrl(packageEntry, apiName); expect(result).toBe('api/common/DatePipe'); const packageEntry2: ApiManifestPackage = { moduleName: '@angular/animations/browser', moduleLabel: 'animations/browser', normalizedModuleName: 'angular_animations_browser', entries: [], }; const result2 = getApiUrl(packageEntry2, apiName); expect(result2).toBe('api/animations/browser/DatePipe'); const packageEntry3: ApiManifestPackage = { moduleName: '@angular/common/http/testing', moduleLabel: 'common/http/testing', normalizedModuleName: 'angular_common_http_testing', entries: [], }; const result3 = getApiUrl(packageEntry3, apiName); expect(result3).toBe('api/common/http/testing/DatePipe'); }); }); });
{ "commit_id": "cb34e406ba", "end_byte": 1528, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/helpers/manifest.helper.spec.ts" }
angular/adev/src/app/features/references/helpers/manifest.helper.ts_0_2340
/*! * @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 {Route} from '@angular/router'; import API_MANIFEST_JSON from '../../../../../src/assets/api/manifest.json'; import {ApiManifest, ApiManifestEntry, ApiManifestPackage} from '../interfaces/api-manifest'; import {PagePrefix} from '../../../core/enums/pages'; import {NavigationItem, contentResolver} from '@angular/docs'; const manifest = API_MANIFEST_JSON as ApiManifest; export function mapApiManifestToRoutes(): Route[] { const apiRoutes: Route[] = []; for (const packageEntry of manifest) { for (const api of packageEntry.entries) { apiRoutes.push({ path: getApiUrl(packageEntry, api.name), loadComponent: () => import('./../api-reference-details-page/api-reference-details-page.component'), resolve: { docContent: contentResolver(`api/${getNormalizedFilename(packageEntry, api)}`), }, data: { label: api.name, displaySecondaryNav: true, }, }); } } return apiRoutes; } export function getApiNavigationItems(): NavigationItem[] { const apiNavigationItems: NavigationItem[] = []; for (const packageEntry of manifest) { const packageNavigationItem: NavigationItem = { label: packageEntry.moduleLabel, children: packageEntry.entries .map((api) => ({ path: getApiUrl(packageEntry, api.name), label: api.name, })) .sort((a, b) => a.label.localeCompare(b.label)), }; apiNavigationItems.push(packageNavigationItem); } return apiNavigationItems; } export function getApiUrl(packageEntry: ApiManifestPackage, apiName: string): string { const packageName = packageEntry.normalizedModuleName // packages like `angular_core` should be `core` // packages like `angular_animation_browser` should be `animation/browser` .replace('angular_', '') .replaceAll('_', '/'); return `${PagePrefix.API}/${packageName}/${apiName}`; } function getNormalizedFilename( manifestPackage: ApiManifestPackage, entry: ApiManifestEntry, ): string { return `${manifestPackage.normalizedModuleName}_${entry.name}_${entry.type}.html`; }
{ "commit_id": "cb34e406ba", "end_byte": 2340, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/helpers/manifest.helper.ts" }
angular/adev/src/app/features/references/services/reference-scroll-handler.service.ts_0_7856
/*! * @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 { DestroyRef, EnvironmentInjector, Injectable, OnDestroy, PLATFORM_ID, afterNextRender, inject, signal, } from '@angular/core'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {fromEvent} from 'rxjs'; import {auditTime} from 'rxjs/operators'; import { API_REFERENCE_DETAILS_PAGE_MEMBERS_CLASS_NAME, API_REFERENCE_MEMBER_CARD_CLASS_NAME, API_TAB_ACTIVE_CODE_LINE, MEMBER_ID_ATTRIBUTE, } from '../constants/api-reference-prerender.constants'; import {WINDOW} from '@angular/docs'; import {Router} from '@angular/router'; import {AppScroller} from '../../../app-scroller'; export const SCROLL_EVENT_DELAY = 20; export const SCROLL_THRESHOLD = 20; @Injectable() export class ReferenceScrollHandler implements OnDestroy { private readonly destroyRef = inject(DestroyRef); private readonly document = inject(DOCUMENT); private readonly injector = inject(EnvironmentInjector); private readonly window = inject(WINDOW); private readonly router = inject(Router); private readonly appScroller = inject(AppScroller); private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); private readonly cardOffsetTop = new Map<string, number>(); private resizeObserver: ResizeObserver | null = null; membersMarginTopInPx = signal<number>(0); ngOnDestroy(): void { this.resizeObserver?.disconnect(); } setupListeners(tocSelector: string): void { if (!this.isBrowser) { return; } this.setupCodeToCListeners(tocSelector); this.setupMemberCardListeners(); this.setScrollEventHandlers(); this.listenToResizeCardContainer(); this.setupFragmentChangeListener(); } private setupFragmentChangeListener() { this.router.routerState.root.fragment .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((fragment) => { // If there is no fragment or the scroll event has a position (traversing through history), // allow the scroller to handler scrolling instead of going to the fragment if (!fragment || this.appScroller.lastScrollEvent?.position) { this.appScroller.scroll(); return; } const card = this.document.getElementById(fragment) as HTMLDivElement | null; this.scrollToCard(card); }); } updateMembersMarginTop(selectorOfTheElementToAlign: string): void { if (!this.isBrowser) { return; } const elementToAlign = this.document.querySelector<HTMLElement>(selectorOfTheElementToAlign); if (elementToAlign) { this.updateMarginTopWhenTabBodyIsResized(elementToAlign); } } private setupCodeToCListeners(tocSelector: string): void { const tocContainer = this.document.querySelector<HTMLDivElement>(tocSelector); if (!tocContainer) { return; } fromEvent(tocContainer, 'click') .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((event) => { if (event.target instanceof HTMLAnchorElement) { event.stopPropagation(); return; } // Get the card member ID from the attributes const target = event.target instanceof HTMLButtonElement ? event.target : this.findButtonElement(event.target as HTMLElement); const memberId = this.getMemberId(target); if (memberId) { this.router.navigate([], {fragment: memberId, replaceUrl: true}); } }); } private setupMemberCardListeners(): void { this.getAllMemberCards().forEach((card) => { this.cardOffsetTop.set(card.id, card.offsetTop); const header = card.querySelector('header'); if (!header) { return; } fromEvent(header, 'click') .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((event) => { const target = event.target as HTMLElement; if (target instanceof HTMLAnchorElement) { return; } this.router.navigate([], {fragment: card.id, replaceUrl: true}); }); }); } private setScrollEventHandlers(): void { const scroll$ = fromEvent(this.document, 'scroll').pipe( auditTime(SCROLL_EVENT_DELAY), takeUntilDestroyed(this.destroyRef), ); scroll$.subscribe(() => this.setActiveCodeLine()); } private listenToResizeCardContainer(): void { const membersCardContainer = this.document.querySelector( API_REFERENCE_DETAILS_PAGE_MEMBERS_CLASS_NAME, ); if (membersCardContainer) { afterNextRender( () => { const resizeObserver = new ResizeObserver(() => { this.updateCardsOffsetTop(); this.setActiveCodeLine(); }); resizeObserver.observe(membersCardContainer); this.destroyRef.onDestroy(() => resizeObserver.disconnect()); }, {injector: this.injector}, ); } } private setActiveCodeLine(): void { const activeCard = Array.from(this.cardOffsetTop) .filter(([_, offsetTop]) => { return offsetTop < this.window.scrollY + this.membersMarginTopInPx() + SCROLL_THRESHOLD; }) .pop(); if (!activeCard) { return; } const activeLines = this.document.querySelectorAll<HTMLButtonElement>( `button.${API_TAB_ACTIVE_CODE_LINE}`, ); const activeLine = activeLines.length > 0 ? activeLines.item(0) : null; const previousActiveMemberId = this.getMemberId(activeLine); const currentActiveMemberId = activeCard[0]; if (previousActiveMemberId && previousActiveMemberId !== currentActiveMemberId) { for (const line of Array.from(activeLines)) { line.classList.remove(API_TAB_ACTIVE_CODE_LINE); } } else { const lines = this.document.querySelectorAll<HTMLButtonElement>( `button[${MEMBER_ID_ATTRIBUTE}="${currentActiveMemberId}"]`, ); for (const line of Array.from(lines)) { line.classList.add(API_TAB_ACTIVE_CODE_LINE); } this.document.getElementById(`${currentActiveMemberId}`)?.focus({preventScroll: true}); } } private scrollToCard(card: HTMLDivElement | null): void { if (!card) { return; } if (card !== <HTMLElement>document.activeElement) { (<HTMLElement>document.activeElement).blur(); } this.window.scrollTo({ top: card!.offsetTop - this.membersMarginTopInPx(), behavior: 'smooth', }); } private updateCardsOffsetTop(): void { this.getAllMemberCards().forEach((card) => { this.cardOffsetTop.set(card.id, card.offsetTop); }); } private getAllMemberCards(): NodeListOf<HTMLDivElement> { return this.document.querySelectorAll<HTMLDivElement>( `${API_REFERENCE_MEMBER_CARD_CLASS_NAME}`, ); } private getMemberId(lineButton: HTMLButtonElement | null): string | undefined { if (!lineButton) { return undefined; } return lineButton.attributes.getNamedItem(MEMBER_ID_ATTRIBUTE)?.value; } private updateMarginTopWhenTabBodyIsResized(tabBody: HTMLElement): void { this.resizeObserver?.disconnect(); this.resizeObserver = new ResizeObserver((_) => { const offsetTop = tabBody.getBoundingClientRect().top; if (offsetTop) { this.membersMarginTopInPx.set(offsetTop); } }); this.resizeObserver.observe(tabBody); } private findButtonElement(element: HTMLElement) { let parent = element.parentElement; while (parent) { if (parent instanceof HTMLButtonElement) { return parent; } parent = parent.parentElement; } return null; } }
{ "commit_id": "cb34e406ba", "end_byte": 7856, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/services/reference-scroll-handler.service.ts" }
angular/adev/src/app/features/references/interfaces/api-item-type.ts_0_580
/*! * @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 enum ApiItemType { BLOCK = 'block', CLASS = 'undecorated_class', CONST = 'constant', DECORATOR = 'decorator', DIRECTIVE = 'directive', ELEMENT = 'element', ENUM = 'enum', FUNCTION = 'function', INTERFACE = 'interface', PIPE = 'pipe', NG_MODULE = 'ng_module', TYPE_ALIAS = 'type_alias', INITIALIZER_API_FUNCTION = 'initializer_api_function', }
{ "commit_id": "cb34e406ba", "end_byte": 580, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/interfaces/api-item-type.ts" }
angular/adev/src/app/features/references/interfaces/api-items-group.ts_0_351
/*! * @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 {ApiItem} from './api-item'; export interface ApiItemsGroup { title: string; id: string; items: ApiItem[]; isFeatured?: boolean; }
{ "commit_id": "cb34e406ba", "end_byte": 351, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/interfaces/api-items-group.ts" }
angular/adev/src/app/features/references/interfaces/api-manifest.ts_0_549
/*! * @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 {ApiItemType} from './api-item-type'; export interface ApiManifestEntry { name: string; type: ApiItemType; isDeprecated?: boolean; } export interface ApiManifestPackage { moduleName: string; normalizedModuleName: string; moduleLabel: string; entries: ApiManifestEntry[]; } export type ApiManifest = ApiManifestPackage[];
{ "commit_id": "cb34e406ba", "end_byte": 549, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/interfaces/api-manifest.ts" }
angular/adev/src/app/features/references/interfaces/api-item.ts_0_408
/*! * @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 {ApiItemType} from './api-item-type'; export interface ApiItem { title: string; itemType: ApiItemType; url: string; isFeatured?: boolean; isDeprecated?: boolean; groupName?: string; }
{ "commit_id": "cb34e406ba", "end_byte": 408, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/references/interfaces/api-item.ts" }
angular/adev/src/app/features/docs/docs.component.ts_0_1157
/*! * @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 {DocContent, DocViewer} from '@angular/docs'; import {ChangeDetectionStrategy, Component, inject} from '@angular/core'; import {toSignal} from '@angular/core/rxjs-interop'; import {ActivatedRoute} from '@angular/router'; import {map} from 'rxjs/operators'; @Component({ selector: 'docs-docs', changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [DocViewer], styleUrls: ['./docs.component.scss'], templateUrl: './docs.component.html', }) export default class DocsComponent { private readonly activatedRoute = inject(ActivatedRoute); // Based on current route, proper static content for doc page is fetched. // In case when exists example-viewer placeholders, then ExampleViewer // components are going to be rendered. private readonly documentContent$ = this.activatedRoute.data.pipe( map((data) => data['docContent'] as DocContent), ); documentContent = toSignal(this.documentContent$); }
{ "commit_id": "cb34e406ba", "end_byte": 1157, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/docs/docs.component.ts" }
angular/adev/src/app/features/docs/docs.component.html_0_139
@if (documentContent()) { <docs-viewer class="docs-viewer" [docContent]="documentContent()!.contents" [hasToc]="true" /> }
{ "commit_id": "cb34e406ba", "end_byte": 139, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/docs/docs.component.html" }
angular/adev/src/app/features/docs/docs.component.scss_0_179
:host { .docs-viewer { &.docs-animate-content { animation: fade-in 500ms; } } } @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
{ "commit_id": "cb34e406ba", "end_byte": 179, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/docs/docs.component.scss" }
angular/adev/src/app/features/docs/docs.component.spec.ts_0_1261
/*! * @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 DocsComponent from './docs.component'; import {RouterTestingModule} from '@angular/router/testing'; import {DOCS_CONTENT_LOADER, WINDOW} from '@angular/docs'; describe('DocsComponent', () => { let component: DocsComponent; let fixture: ComponentFixture<DocsComponent>; const fakeWindow = { addEventListener: () => {}, removeEventListener: () => {}, }; const fakeContentLoader = { getContent: (id: string) => undefined, }; beforeEach(() => { TestBed.configureTestingModule({ imports: [DocsComponent, RouterTestingModule], providers: [ { provide: WINDOW, useValue: fakeWindow, }, { provide: DOCS_CONTENT_LOADER, useValue: fakeContentLoader, }, ], }); fixture = TestBed.createComponent(DocsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
{ "commit_id": "cb34e406ba", "end_byte": 1261, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/features/docs/docs.component.spec.ts" }
angular/adev/src/app/editor/typings-loader.service.ts_0_4838
/*! * @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, signal} from '@angular/core'; import {toObservable} from '@angular/core/rxjs-interop'; import {WebContainer} from '@webcontainer/api'; import {Typing} from './code-editor/workers/interfaces/define-types-request'; /** * This service is responsible for retrieving the types definitions for the * predefined dependencies. */ @Injectable({providedIn: 'root'}) export class TypingsLoader { private readonly librariesToGetTypesFrom = [ '@angular/common', '@angular/core', '@angular/forms', '@angular/router', '@angular/platform-browser', '@angular/material', '@angular/cdk', ]; private webContainer: WebContainer | undefined; private _typings = signal<Typing[]>([]); readonly typings = this._typings.asReadonly(); readonly typings$ = toObservable(this._typings); /** * Retrieve types from the predefined libraries and set the types files and contents in the `typings` signal */ async retrieveTypeDefinitions(webContainer: WebContainer): Promise<void> { this.webContainer = webContainer; const typesDefinitions: Typing[] = []; try { const filesToRead = await this.getFilesToRead(); if (filesToRead && filesToRead.length > 0) { await Promise.all( filesToRead.map((path) => webContainer.fs.readFile(path, 'utf-8').then((content) => { typesDefinitions.push({path, content}); }), ), ); this._typings.set(typesDefinitions); } } catch (error: any) { // ignore "ENOENT" errors as this can happen while reading files and resetting the WebContainer if (error?.message.startsWith('ENOENT')) { return; } else { throw error; } } } /** * Get the list of files to read the types definitions from the predefined libraries */ private async getFilesToRead() { if (!this.webContainer) return; const filesToRead: string[] = []; const directoriesToRead: string[] = []; for (const library of this.librariesToGetTypesFrom) { // The library's package.json is where the type definitions are defined const packageJsonContent = await this.webContainer.fs .readFile(`./node_modules/${library}/package.json`, 'utf-8') .catch((error) => { // Note: "ENOENT" errors occurs: // - While resetting the NodeRuntimeSandbox. // - When the library is not a dependency in the project, its package.json won't exist. // // In both cases we ignore the error to continue the process. if (error?.message.startsWith('ENOENT')) { return; } throw error; }); // if the package.json content is empty, skip this library if (!packageJsonContent) continue; const packageJson = JSON.parse(packageJsonContent); // If the package.json doesn't have `exports`, skip this library if (!packageJson?.exports) continue; // Based on `exports` we can identify paths to the types definition files for (const exportKey of Object.keys(packageJson.exports)) { const exportEntry = packageJson.exports[exportKey]; const types: string | undefined = exportEntry.typings ?? exportEntry.types; if (types) { const path = `/node_modules/${library}/${this.normalizePath(types)}`; // If the path contains `*` we need to read the directory files if (path.includes('*')) { const directory = path.substring(0, path.lastIndexOf('/')); directoriesToRead.push(directory); } else { filesToRead.push(path); } } } } const directoryFiles = ( await Promise.all( directoriesToRead.map((directory) => this.getTypeDefinitionFilesFromDirectory(directory)), ) ).flat(); for (const file of directoryFiles) { filesToRead.push(file); } return filesToRead; } private async getTypeDefinitionFilesFromDirectory(directory: string): Promise<string[]> { if (!this.webContainer) throw new Error('this.webContainer is not defined'); const files = await this.webContainer.fs.readdir(directory); return files.filter(this.isTypeDefinitionFile).map((file) => `${directory}/${file}`); } private isTypeDefinitionFile(path: string): boolean { return path.endsWith('.d.ts'); } private normalizePath(path: string): string { if (path.startsWith('./')) { return path.substring(2); } if (path.startsWith('.')) { return path.substring(1); } return path; } }
{ "commit_id": "cb34e406ba", "end_byte": 4838, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/typings-loader.service.ts" }
angular/adev/src/app/editor/editor-ui-state.service.ts_0_1855
/*! * @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, inject, Injectable, signal} from '@angular/core'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {filter, map, Subject} from 'rxjs'; import {TutorialMetadata} from '@angular/docs'; import {TutorialType} from '@angular/docs'; import {EmbeddedTutorialManager} from './embedded-tutorial-manager.service'; export interface EditorUiStateConfig { displayOnlyInteractiveTerminal: boolean; } export const DEFAULT_EDITOR_UI_STATE: EditorUiStateConfig = { displayOnlyInteractiveTerminal: false, }; @Injectable() export class EditorUiState { private readonly embeddedTutorialManager = inject(EmbeddedTutorialManager); private readonly destroyRef = inject(DestroyRef); private readonly stateChanged = new Subject<void>(); stateChanged$ = this.stateChanged.asObservable(); uiState = signal<EditorUiStateConfig>(DEFAULT_EDITOR_UI_STATE); constructor() { this.handleTutorialChange(); } patchState(patch: Partial<EditorUiStateConfig>): void { this.uiState.update((state) => ({...state, ...patch})); this.stateChanged.next(); } private handleTutorialChange() { this.embeddedTutorialManager.tutorialChanged$ .pipe( map(() => this.embeddedTutorialManager.type()), filter((tutorialType): tutorialType is TutorialMetadata['type'] => Boolean(tutorialType)), takeUntilDestroyed(this.destroyRef), ) .subscribe((tutorialType) => { if (tutorialType === TutorialType.CLI) { this.patchState({displayOnlyInteractiveTerminal: true}); } else { this.patchState(DEFAULT_EDITOR_UI_STATE); } }); } }
{ "commit_id": "cb34e406ba", "end_byte": 1855, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/editor-ui-state.service.ts" }
angular/adev/src/app/editor/idx-launcher.service.ts_0_1612
/*! * @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 {EnvironmentInjector, Injectable, inject} from '@angular/core'; import {injectAsync} from '../core/services/inject-async'; import * as IDX from 'open-in-idx'; @Injectable({ providedIn: 'root', }) export class IDXLauncher { private readonly environmentInjector = inject(EnvironmentInjector); async openCurrentSolutionInIDX(): Promise<void> { const nodeRuntimeSandbox = await injectAsync(this.environmentInjector, () => import('./node-runtime-sandbox.service').then((c) => c.NodeRuntimeSandbox), ); const runtimeFiles = await nodeRuntimeSandbox.getSolutionFiles(); const workspaceFiles: Record<string, string> = {}; for (let i = 0; i < runtimeFiles.length; i++) { const file = runtimeFiles[i]; //don't include config.json, BUILD.bazel, package-lock.json, package.json.template const doNotAllowList = [ 'config.json', 'BUILD.bazel', 'package-lock.json', 'package.json.template', ]; const path = file.path.replace(/^\//, ''); //don't include binary formats if (!doNotAllowList.includes(path) && typeof file.content === 'string') { if (path === 'idx/dev.nix') { workspaceFiles['.idx/dev.nix'] = file.content as string; } else { workspaceFiles[path] = file.content as string; } } } IDX.newAdhocWorkspace({files: workspaceFiles}); } }
{ "commit_id": "cb34e406ba", "end_byte": 1612, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/idx-launcher.service.ts" }
angular/adev/src/app/editor/download-manager.service.ts_0_1587
/*! * @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 {EnvironmentInjector, Injectable, PLATFORM_ID, inject} from '@angular/core'; import {generateZip} from '@angular/docs'; import {injectAsync} from '../core/services/inject-async'; @Injectable({ providedIn: 'root', }) export class DownloadManager { private readonly document = inject(DOCUMENT); private readonly environmentInjector = inject(EnvironmentInjector); private readonly platformId = inject(PLATFORM_ID); /** * Generate ZIP with the current state of the solution in the EmbeddedEditor */ async downloadCurrentStateOfTheSolution(name: string) { const nodeRuntimeSandbox = await injectAsync(this.environmentInjector, () => import('./node-runtime-sandbox.service').then((c) => c.NodeRuntimeSandbox), ); const files = await nodeRuntimeSandbox.getSolutionFiles(); const content = await generateZip(files); this.saveFile([content], name); } private saveFile(blobParts: BlobPart[], name: string): void { if (!isPlatformBrowser(this.platformId)) { return; } const blob = new Blob(blobParts, { type: 'application/zip', }); const url = window.URL.createObjectURL(blob); const anchor = this.document.createElement('a'); anchor.href = url; anchor.download = `${name}.zip`; anchor.click(); anchor.remove(); } }
{ "commit_id": "cb34e406ba", "end_byte": 1587, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/download-manager.service.ts" }
angular/adev/src/app/editor/embedded-editor.component.html_0_2871
<div class="adev-editor-container" #editorContainer> <as-split class="docs-editor" [direction]="splitDirection" restrictMove="true" gutterSize="5"> <as-split-area class="adev-left-side" [size]="50"> <!-- Code Editor --> @if (!displayOnlyTerminal()) { <docs-tutorial-code-editor class="adev-tutorial-code-editor" /> } <!-- CLI Terminal --> @if (displayOnlyTerminal()) { <docs-tutorial-terminal class="docs-tutorial-terminal-only" [type]="TerminalType.INTERACTIVE" /> } </as-split-area> <as-split-area [size]="50"> <!-- Preview, Terminal & Console --> @if (!displayOnlyTerminal()) { <as-split class="docs-right-side" direction="vertical" restrictMove="true" gutterSize="5"> <!-- Preview Section: for larger screens --> @if (!displayPreviewInMatTabGroup()) { <as-split-area [size]="50" [order]="1"> <!-- Preview Section: for larger screens --> <div class="adev-preview-section"> <div class="adev-preview-header"> <span>Preview</span> </div> @if (!displayPreviewInMatTabGroup()) { <docs-tutorial-preview /> } </div> </as-split-area> } <as-split-area class="docs-editor-tabs-and-refresh" [size]="50" [order]="2"> <!-- Container to hide preview, console and footer when only the interactive terminal is used --> <mat-tab-group class="docs-editor-tabs" animationDuration="0ms" mat-stretch-tabs="false"> @if (displayPreviewInMatTabGroup()) { <mat-tab label="Preview"> <docs-tutorial-preview /> </mat-tab> } <mat-tab label="Console"> <ng-template mat-tab-label> Console @if (errorsCount()) { <docs-icon class="docs-icon_high-contrast">error</docs-icon> <span> {{ errorsCount() }} </span> } </ng-template> <docs-tutorial-terminal [type]="TerminalType.READONLY" class="docs-tutorial-terminal" /> </mat-tab> <mat-tab label="Terminal"> <docs-tutorial-terminal [type]="TerminalType.INTERACTIVE" class="docs-tutorial-terminal" /> </mat-tab> </mat-tab-group> <button type="button" (click)="reset()" title="Refresh the preview" [disabled]="!shouldEnableReset()" class="adev-refresh-btn" > <docs-icon class="docs-icon">refresh</docs-icon> </button> </as-split-area> </as-split> } </as-split-area> </as-split> </div>
{ "commit_id": "cb34e406ba", "end_byte": 2871, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/embedded-editor.component.html" }
angular/adev/src/app/editor/stackblitz-opener.service.spec.ts_0_580
/*! * @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 {StackBlitzOpener} from './stackblitz-opener.service'; describe('StackBlitzOpener', () => { let service: StackBlitzOpener; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(StackBlitzOpener); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
{ "commit_id": "cb34e406ba", "end_byte": 580, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/stackblitz-opener.service.spec.ts" }
angular/adev/src/app/editor/embedded-editor.component.scss_0_4396
@use '@angular/docs/styles/_split.scss'; $pane-border: 1px solid var(--senary-contrast); $width-breakpoint: 950px; .adev-editor-container { container-type: size; container-name: embedded-editor; height: 100%; position: relative; border: 1px solid var(--senary-contrast); } // The entire thing - editor, terminal, console .adev-editor { display: flex; flex-direction: column; align-items: stretch; border: $pane-border; transition: border-color 0.3s ease; border-radius: 0.25rem; overflow: hidden; height: 100%; @container embedded-editor (min-width: $width-breakpoint) { flex-direction: row; } @container embedded-editor (max-width: $width-breakpoint) { > div { height: 50%; } } // If files are displayed, share the space &:has(.docs-editor-tabs) { .adev-tutorial-code-editor { display: block; box-sizing: border-box; // prevent border flicker when resizing editor transition: border-color 0s; @container embedded-editor (min-width: $width-breakpoint) { // row : embedded-editor's flex-direction border-inline-end: $pane-border; } @container embedded-editor (max-width: $width-breakpoint) { // column : embedded-editor's flex-direction border-block-end: $pane-border; } } } } .adev-tutorial-code-editor { width: 100%; height: 100%; } .docs-right-side { height: 100%; // prevent border flicker when resizing editor transition: border-color 0s; @container embedded-editor (min-width: $width-breakpoint) { // row : embedded-editor's flex-direction border-inline-start: $pane-border; } @container embedded-editor (max-width: $width-breakpoint) { // column : embedded-editor's flex-direction border-block-start: $pane-border; } } .docs-editor-tabs-and-refresh { position: relative; height: 100%; // prevent border flicker when resizing editor transition: border-color 0s; border-block-start: $pane-border; } // preview, terminal, console side/container of the embedded editor .docs-editor-tabs { height: 100%; display: block; } .adev-refresh-btn { position: absolute; top: 0; right: 0; height: 48px; width: 46px; display: flex; align-items: center; flex-grow: 1; border-inline-start: $pane-border; background: var(--octonary-contrast); z-index: var(--z-index-content); docs-icon { color: var(--gray-400); margin: auto; font-size: 1.3rem; transition: color 0.3s ease; } &:hover { docs-icon { color: var(--primary-contrast); } } &:disabled { docs-icon { color: var(--gray-400); } } } .adev-console-section { display: block; } .adev-preview-section { height: 100%; // prevent border flicker when resizing editor transition: border-color 0s; @container embedded-editor (min-width: $width-breakpoint) { // row : embedded-editor's flex-direction border-block-end: $pane-border; } @container embedded-editor (max-width: $width-breakpoint) { // column : embedded-editor's flex-direction border-block-start: $pane-border; } } .adev-preview-header { border-block-end: $pane-border; font-size: 0.875rem; padding: 0.98rem 1.25rem; display: flex; align-items: center; background-color: var(--octonary-contrast); transition: background-color 0.3s ease, border-color 0.3s ease; i { color: var(--bright-blue); margin-inline-start: 0.5rem; margin-inline-end: 0.25rem; font-size: 1.25rem; } span { color: var(--primary-contrast); } } .adev-alert { position: absolute; inset: 0; border-radius: 0.25rem; display: flex; justify-content: center; align-items: center; background-color: color-mix(var(--page-background) 50%, transparent); backdrop-filter: blur(3px); height: 100%; width: 100%; z-index: 100; h2 { margin-block: 0; } p { margin-block-end: 1rem; } div { display: flex; flex-direction: column; max-width: 300px; border: 1px solid var(--quinary-contrast); border-radius: 0.25rem; background-color: color-mix(in srgb, var(--page-background) 90%, transparent); button { align-self: flex-end; } padding: 1.5rem; } } ::ng-deep mat-tab-group { .mat-mdc-tab-body-wrapper, .mat-mdc-tab-body, .mat-mdc-tab-body-content { display: contents; } }
{ "commit_id": "cb34e406ba", "end_byte": 4396, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/embedded-editor.component.scss" }
angular/adev/src/app/editor/node-runtime-sandbox.service.ts_0_1773
/*! * @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, inject, Injectable, signal} from '@angular/core'; import {checkFilesInDirectory} from '@angular/docs'; import {FileSystemTree, WebContainer, WebContainerProcess} from '@webcontainer/api'; import {BehaviorSubject, filter, map, Subject} from 'rxjs'; import type {FileAndContent} from '@angular/docs'; import {TutorialType} from '@angular/docs'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {AlertManager} from './alert-manager.service'; import {EmbeddedTutorialManager} from './embedded-tutorial-manager.service'; import {LoadingStep} from './enums/loading-steps'; import {ErrorType, NodeRuntimeState} from './node-runtime-state.service'; import {TerminalHandler} from './terminal/terminal-handler.service'; import {TypingsLoader} from './typings-loader.service'; export const DEV_SERVER_READY_MSG = 'Watch mode enabled. Watching for file changes...'; export const OUT_OF_MEMORY_MSG = 'Out of memory'; const enum PROCESS_EXIT_CODE { SUCCESS = 0, // process exited successfully ERROR = 10, // process exited with error SIGTERM = 143, // 143 = gracefully terminated by SIGTERM, e.g. Ctrl + C } export const PACKAGE_MANAGER = 'npm'; /** * This service is responsible for handling the WebContainer instance, which * allows running a Node.js environment in the browser. It is used by the * embedded editor to run an executable Angular project in the browser. * * It boots the WebContainer, loads the project files into the WebContainer * filesystem, install the project dependencies and starts the dev server. */
{ "commit_id": "cb34e406ba", "end_byte": 1773, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/node-runtime-sandbox.service.ts" }
angular/adev/src/app/editor/node-runtime-sandbox.service.ts_1774_9764
@Injectable({providedIn: 'root'}) export class NodeRuntimeSandbox { private readonly _createdFile$ = new Subject<string>(); readonly createdFile$ = this._createdFile$.asObservable(); private readonly _createdFiles = signal<Set<string>>(new Set()); private interactiveShellProcess: WebContainerProcess | undefined; private interactiveShellWriter: WritableStreamDefaultWriter | undefined; private readonly destroyRef = inject(DestroyRef); private readonly alertManager = inject(AlertManager); private readonly terminalHandler = inject(TerminalHandler); private embeddedTutorialManager = inject(EmbeddedTutorialManager); private readonly nodeRuntimeState = inject(NodeRuntimeState); private readonly typingsLoader = inject(TypingsLoader); private readonly _isProjectInitialized = signal(false); private readonly _isAngularCliInitialized = signal(false); private urlToPreview$ = new BehaviorSubject<string | null>(''); private readonly _previewUrl$ = this.urlToPreview$.asObservable(); private readonly processes: Set<WebContainerProcess> = new Set(); private devServerProcess: WebContainerProcess | undefined; private webContainerPromise: Promise<WebContainer> | undefined; get previewUrl$() { return this._previewUrl$; } async init(): Promise<void> { // Note: the error state can already be set when loading the NodeRuntimeSandbox // in an unsupported environment. if (this.nodeRuntimeState.error()) { return; } try { if (!this.embeddedTutorialManager.type()) throw Error("Tutorial type isn't available, can not initialize the NodeRuntimeSandbox"); console.time('Load time'); let webContainer: WebContainer; if (this.nodeRuntimeState.loadingStep() === LoadingStep.NOT_STARTED) { this.alertManager.init(); webContainer = await this.boot(); await this.handleWebcontainerErrors(); } else { webContainer = await this.webContainerPromise!; } await this.startInteractiveTerminal(webContainer); this.terminalHandler.clearTerminals(); if (this.embeddedTutorialManager.type() === TutorialType.CLI) { await this.initAngularCli(); } else { await this.initProject(); } console.timeEnd('Load time'); } catch (error: any) { // If we're already in an error state, throw away the most recent error which may have happened because // we were in the error state already and tried to do more things after terminating. const message = this.nodeRuntimeState.error()?.message ?? error.message; this.setErrorState(message); } } async reset(): Promise<void> { // if a reset is running, don't allow another to start if (this.nodeRuntimeState.isResetting()) { return; } this.nodeRuntimeState.setIsResetting(true); if (this.nodeRuntimeState.loadingStep() === LoadingStep.READY) { await this.restartDevServer(); } else { await this.cleanup(); this.setLoading(LoadingStep.BOOT); // force re-initialization this._isProjectInitialized.set(false); await this.init(); } this.nodeRuntimeState.setIsResetting(false); } async restartDevServer(): Promise<void> { this.devServerProcess?.kill(); await this.startDevServer(); } async getSolutionFiles(): Promise<FileAndContent[]> { const webContainer = await this.webContainerPromise!; const excludeFolders = ['node_modules', '.angular', 'dist']; return await checkFilesInDirectory( '/', webContainer.fs, (path?: string) => !!path && !excludeFolders.includes(path), ); } /** * Initialize the WebContainer for an Angular project */ private async initProject(): Promise<void> { // prevent re-initialization if (this._isProjectInitialized()) return; // clean up the sandbox if it was initialized before so that the CLI can // be initialized without conflicts if (this._isAngularCliInitialized()) { await this.cleanup(); this._isAngularCliInitialized.set(false); } this._isProjectInitialized.set(true); await this.mountProjectFiles(); this.handleProjectChanges(); const exitCode = await this.installDependencies(); if (![PROCESS_EXIT_CODE.SIGTERM, PROCESS_EXIT_CODE.SUCCESS].includes(exitCode)) throw new Error('Installation failed'); await Promise.all([this.loadTypes(), this.startDevServer()]); } private handleProjectChanges() { this.embeddedTutorialManager.tutorialChanged$ .pipe( map((tutorialChanged) => ({ tutorialChanged, tutorialFiles: this.embeddedTutorialManager.tutorialFiles(), })), filter( ({tutorialChanged, tutorialFiles}) => tutorialChanged && Object.keys(tutorialFiles).length > 0, ), takeUntilDestroyed(this.destroyRef), ) .subscribe(async () => { await Promise.all([this.mountProjectFiles(), this.handleFilesToDeleteOnProjectChange()]); if (this.embeddedTutorialManager.shouldReInstallDependencies()) { await this.handleInstallDependenciesOnProjectChange(); } }); } private async handleFilesToDeleteOnProjectChange() { const filesToDelete = Array.from( new Set([ ...this.embeddedTutorialManager.filesToDeleteFromPreviousProject(), ...Array.from(this._createdFiles()), ]), ); if (filesToDelete.length) { await Promise.all(filesToDelete.map((file) => this.deleteFile(file))); } // reset created files this._createdFiles.set(new Set()); } private async handleInstallDependenciesOnProjectChange() { // Note: restartDevServer is not used here because we need to kill // the dev server process before installing dependencies to avoid // errors in the console this.devServerProcess?.kill(); await this.installDependencies(); await Promise.all([this.loadTypes(), this.startDevServer()]); } /** * Initialize the WebContainer for the Angular CLI */ private async initAngularCli() { // prevent re-initialization if (this._isAngularCliInitialized()) return; // clean up the sandbox if a project was initialized before so the CLI can // be initialized without conflicts if (this._isProjectInitialized()) { await this.cleanup(); this.urlToPreview$.next(null); this._isProjectInitialized.set(false); } this._isAngularCliInitialized.set(true); this.setLoading(LoadingStep.INSTALL); const exitCode = await this.installAngularCli(); if (![PROCESS_EXIT_CODE.SIGTERM, PROCESS_EXIT_CODE.SUCCESS].includes(exitCode)) this.setLoading(LoadingStep.READY); } async writeFile(path: string, content: string | Uint8Array): Promise<void> { const webContainer = await this.webContainerPromise!; try { await webContainer.fs.writeFile(path, content); } catch (err: any) { if (err.message.startsWith('ENOENT')) { const directory = path.split('/').slice(0, -1).join('/'); await webContainer.fs.mkdir(directory, { recursive: true, }); await webContainer.fs.writeFile(path, content); } else { throw err; } } } async renameFile(oldPath: string, newPath: string): Promise<void> { const webContainer = await this.webContainerPromise!; try { await webContainer.fs.rename(oldPath, newPath); } catch (err: any) { throw err; } } async readFile(filePath: string): Promise<string> { const webContainer = await this.webContainerPromise!; return webContainer.fs.readFile(filePath, 'utf-8'); } async deleteFile(filepath: string): Promise<void> { const webContainer = await this.webContainerPromise!; return webContainer.fs.rm(filepath); } /** * Implemented based on: * https://webcontainers.io/tutorial/7-add-interactivity#_2-start-the-shell */
{ "commit_id": "cb34e406ba", "end_byte": 9764, "start_byte": 1774, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/node-runtime-sandbox.service.ts" }
angular/adev/src/app/editor/node-runtime-sandbox.service.ts_9767_17417
private async startInteractiveTerminal(webContainer: WebContainer): Promise<WebContainerProcess> { // return existing shell process if it's already running if (this.interactiveShellProcess) return this.interactiveShellProcess; const terminal = this.terminalHandler.interactiveTerminalInstance; // use WebContainer spawn directly so that the process isn't killed on // cleanup const shellProcess = await webContainer.spawn('bash'); this.interactiveShellProcess = shellProcess; // keep the regex out of the write stream to avoid recreating on every write const ngGenerateTerminalOutputRegex = /(\u001b\[\d+m)?([^\s]+)(\u001b\[\d+m)?/g; shellProcess.output.pipeTo( new WritableStream({ write: (data) => { this.checkForOutOfMemoryError(data.toString()); terminal.write(data); if (data.includes('CREATE') && data.endsWith('\r\n')) { const match = data.match(ngGenerateTerminalOutputRegex); const filename = match?.[1]; if (filename) { this._createdFile$.next(filename); this._createdFiles.update((files) => files.add(filename)); } } }, }), ); const input = shellProcess.input.getWriter(); this.interactiveShellWriter = input; terminal.onData((data) => { input.write(data); }); terminal.breakProcess$.subscribe(() => { // Write CTRL + C into shell to break active process input.write('\x03'); }); return shellProcess; } private async mountProjectFiles() { if (!this.embeddedTutorialManager.tutorialFilesystemTree()) { return; } // The files are mounted on init and when the project changes. If the loading step is ready, // the project changed, so we don't need to change the loading step. if (this.nodeRuntimeState.loadingStep() !== LoadingStep.READY) { this.setLoading(LoadingStep.LOAD_FILES); } const tutorialHasFiles = Object.keys(this.embeddedTutorialManager.tutorialFilesystemTree() as FileSystemTree).length > 0; if (tutorialHasFiles) { await Promise.all([ this.mountFiles(this.embeddedTutorialManager.commonFilesystemTree() as FileSystemTree), this.mountFiles(this.embeddedTutorialManager.tutorialFilesystemTree() as FileSystemTree), ]); } } private setLoading(loading: LoadingStep) { this.nodeRuntimeState.setLoadingStep(loading); } private async mountFiles(fileSystemTree: FileSystemTree): Promise<void> { const webContainer = await this.webContainerPromise!; await webContainer.mount(fileSystemTree); } private async boot(): Promise<WebContainer> { this.setLoading(LoadingStep.BOOT); if (!this.webContainerPromise) { this.webContainerPromise = WebContainer.boot({ workdirName: 'angular', }); } return await this.webContainerPromise; } private terminate(webContainer?: WebContainer): void { webContainer?.teardown(); this.webContainerPromise = undefined; } private async handleWebcontainerErrors() { const webContainer = await this.webContainerPromise!; webContainer.on('error', ({message}) => { if (this.checkForOutOfMemoryError(message)) return; this.setErrorState(message, ErrorType.UNKNOWN); }); } private checkForOutOfMemoryError(message: string): boolean { if (message.toLowerCase().includes(OUT_OF_MEMORY_MSG.toLowerCase())) { this.setErrorState(message, ErrorType.OUT_OF_MEMORY); return true; } return false; } private setErrorState(message: string | undefined, type?: ErrorType) { this.nodeRuntimeState.setError({message, type}); this.nodeRuntimeState.setLoadingStep(LoadingStep.ERROR); this.terminate(); } private async installDependencies(): Promise<number> { this.setLoading(LoadingStep.INSTALL); const installProcess = await this.spawn(PACKAGE_MANAGER, ['install']); installProcess.output.pipeTo( new WritableStream({ write: (data) => { this.terminalHandler.readonlyTerminalInstance.write(data); }, }), ); // wait for install command to exit return installProcess.exit; } private async loadTypes() { const webContainer = await this.webContainerPromise!; await this.typingsLoader.retrieveTypeDefinitions(webContainer!); } private async installAngularCli(): Promise<number> { // install Angular CLI const installProcess = await this.spawn(PACKAGE_MANAGER, ['install', '@angular/cli@latest']); installProcess.output.pipeTo( new WritableStream({ write: (data) => { this.terminalHandler.interactiveTerminalInstance.write(data); }, }), ); const exitCode = await installProcess.exit; // Simulate pressing `Enter` in shell this.interactiveShellWriter?.write('\x0D'); return exitCode; } private async startDevServer(): Promise<void> { const webContainer = await this.webContainerPromise!; this.setLoading(LoadingStep.START_DEV_SERVER); this.devServerProcess = await this.spawn(PACKAGE_MANAGER, ['run', 'start']); // wait for `server-ready` event, forward the dev server url webContainer.on('server-ready', (port: number, url: string) => { this.urlToPreview$.next(url); }); // wait until the dev server finishes the first compilation await new Promise<void>((resolve, reject) => { if (!this.devServerProcess) { reject('dev server is not running'); return; } this.devServerProcess.output.pipeTo( new WritableStream({ write: (data) => { this.terminalHandler.readonlyTerminalInstance.write(data); if (this.checkForOutOfMemoryError(data.toString())) { reject(new Error(data.toString())); return; } if ( this.nodeRuntimeState.loadingStep() !== LoadingStep.READY && data.toString().includes(DEV_SERVER_READY_MSG) ) { resolve(); this.setLoading(LoadingStep.READY); } }, }), ); }); } /** * Spawn a process in the WebContainer and store the process in the service. * Later on the stored process can be used to kill the process on `cleanup` */ private async spawn(command: string, args: string[] = []): Promise<WebContainerProcess> { const webContainer = await this.webContainerPromise!; const process = await webContainer.spawn(command, args); const transformStream = new TransformStream({ transform: (chunk, controller) => { this.checkForOutOfMemoryError(chunk.toString()); controller.enqueue(chunk); }, }); process.output = process.output.pipeThrough(transformStream); this.processes.add(process); return process; } /** * Kill existing processes and remove files from the WebContainer * when switching tutorials that have different requirements */ private async cleanup() { // await the process to be killed before removing the files because // a process can create files during the promise await this.killExistingProcesses(); await this.removeFiles(); } private async killExistingProcesses(): Promise<void> { await Promise.all(Array.from(this.processes).map((process) => process.kill())); this.processes.clear(); } private async removeFiles(): Promise<void> { const webcontainer = await this.webContainerPromise!; await webcontainer.spawn('rm', ['-rf', './**']); } }
{ "commit_id": "cb34e406ba", "end_byte": 17417, "start_byte": 9767, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/node-runtime-sandbox.service.ts" }
angular/adev/src/app/editor/embedded-tutorial-manager.service.ts_0_6507
/*! * @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, signal} from '@angular/core'; import {FileSystemTree} from '@webcontainer/api'; import {BehaviorSubject} from 'rxjs'; import {TutorialMetadata} from '@angular/docs'; import {TUTORIALS_ASSETS_WEB_PATH} from './constants'; /** * A service responsible for the current tutorial, retrieving and providing * its source code and metadata. */ @Injectable({providedIn: 'root'}) export class EmbeddedTutorialManager { readonly tutorialId = signal<string>(''); readonly tutorialFilesystemTree = signal<FileSystemTree | null>(null); readonly commonFilesystemTree = signal<FileSystemTree | null>(null); readonly type = signal<TutorialMetadata['type'] | undefined>(undefined); private readonly allFiles = signal<TutorialMetadata['allFiles']>([]); readonly hiddenFiles = signal<TutorialMetadata['hiddenFiles']>([]); readonly tutorialFiles = signal<TutorialMetadata['tutorialFiles']>({}); readonly openFiles = signal<TutorialMetadata['openFiles']>([]); readonly answerFiles = signal<NonNullable<TutorialMetadata['answerFiles']>>({}); readonly dependencies = signal<TutorialMetadata['dependencies'] | undefined>(undefined); private _shouldReInstallDependencies = signal<boolean>(false); readonly shouldReInstallDependencies = this._shouldReInstallDependencies.asReadonly(); private metadata = signal<TutorialMetadata | undefined>(undefined); private _shouldChangeTutorial$ = new BehaviorSubject<boolean>(false); readonly tutorialChanged$ = this._shouldChangeTutorial$.asObservable(); private readonly _filesToDeleteFromPreviousProject = signal(new Set<string>()); readonly filesToDeleteFromPreviousProject = this._filesToDeleteFromPreviousProject.asReadonly(); async fetchAndSetTutorialFiles(tutorial: string) { const [commonSourceCode, tutorialSourceCode, metadata] = await Promise.all([ this.fetchCommonFiles(), this.fetchTutorialSourceCode(tutorial), this.fetchTutorialMetadata(tutorial), ]); const projectChanged = !!this.tutorialId() && this.tutorialId() !== tutorial; this.tutorialId.set(tutorial); this.type.set(metadata.type); this.metadata.set(metadata); if (tutorialSourceCode) { if (projectChanged) { const filesToRemove = this.computeFilesToRemove(metadata.allFiles, this.allFiles()); if (filesToRemove) { this._filesToDeleteFromPreviousProject.set(filesToRemove); } this._shouldReInstallDependencies.set( this.checkIfDependenciesChanged(metadata.dependencies ?? {}), ); } this.tutorialFilesystemTree.set(tutorialSourceCode); this.dependencies.set(metadata.dependencies ?? {}); this.tutorialFiles.set(metadata.tutorialFiles); this.answerFiles.set(metadata.answerFiles ?? {}); this.openFiles.set(metadata.openFiles); this.hiddenFiles.set(metadata.hiddenFiles); this.allFiles.set(metadata.allFiles); // set common only once if (!this.commonFilesystemTree()) this.commonFilesystemTree.set(commonSourceCode); } this._shouldChangeTutorial$.next(projectChanged); } revealAnswer() { const answerFilenames = Object.keys(this.answerFiles()); const openFilesAndAnswer = Array.from( // use Set to remove duplicates, spread openFiles first to keep files order new Set([...this.openFiles(), ...answerFilenames]), ).filter((filename) => !this.hiddenFiles()?.includes(filename)); const tutorialFiles = Object.fromEntries( openFilesAndAnswer.map((file) => [file, this.answerFiles()[file]]), ); const allFilesWithAnswer = [...this.allFiles(), ...answerFilenames]; const filesToDelete = this.computeFilesToRemove(allFilesWithAnswer, this.allFiles()); if (filesToDelete) { this._filesToDeleteFromPreviousProject.set(filesToDelete); } this.allFiles.set(allFilesWithAnswer); this.tutorialFiles.set(tutorialFiles); this.openFiles.set(openFilesAndAnswer); this._shouldChangeTutorial$.next(true); } resetRevealAnswer() { const allFilesWithoutAnswer = this.metadata()!.allFiles; const filesToDelete = this.computeFilesToRemove(allFilesWithoutAnswer, this.allFiles()); if (filesToDelete) { this._filesToDeleteFromPreviousProject.set(filesToDelete); } this.tutorialFiles.set(this.metadata()!.tutorialFiles); this.openFiles.set(this.metadata()!.openFiles); this._shouldChangeTutorial$.next(true); } async fetchCommonFiles(): Promise<FileSystemTree> { if (this.commonFilesystemTree() !== null) return this.commonFilesystemTree() as FileSystemTree; //const commonFiles = await this.fetchTutorialSourceCode(TUTORIALS_COMMON_DIRECTORY); //this.tutorialFilesystemTree.set(commonFiles); return {}; } private async fetchTutorialSourceCode(tutorial: string): Promise<FileSystemTree> { const tutorialSourceCode = await fetch( `${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/source-code.json`, ); if (!tutorialSourceCode.ok) throw new Error(`Missing source code for tutorial ${tutorial}`); return await tutorialSourceCode.json(); } private async fetchTutorialMetadata(tutorial: string): Promise<TutorialMetadata> { const tutorialSourceCode = await fetch( `${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/metadata.json`, ); if (!tutorialSourceCode.ok) throw new Error(`Missing metadata for ${tutorial}`); return await tutorialSourceCode.json(); } /** * Compare previous and new dependencies to determine if the dependencies changed. */ private checkIfDependenciesChanged( newDeps: NonNullable<TutorialMetadata['dependencies']>, ): boolean { const existingDeps = this.dependencies(); for (const name of Object.keys(newDeps)) { if (existingDeps?.[name] !== newDeps[name]) { return true; } } return false; } private computeFilesToRemove( newFiles: TutorialMetadata['allFiles'], existingFiles: TutorialMetadata['allFiles'], ): Set<string> | undefined { // All existing files are candidates for removal. const filesToDelete = new Set(existingFiles); // Retain files that are present in the new project. for (const file of newFiles) { filesToDelete.delete(file); } return filesToDelete; } }
{ "commit_id": "cb34e406ba", "end_byte": 6507, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/embedded-tutorial-manager.service.ts" }
angular/adev/src/app/editor/editor-ui-state.service.spec.ts_0_605
/*! * @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 {EditorUiState} from './editor-ui-state.service'; describe('EditorUiState', () => { let service: EditorUiState; beforeEach(() => { TestBed.configureTestingModule({ providers: [EditorUiState], }); service = TestBed.inject(EditorUiState); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
{ "commit_id": "cb34e406ba", "end_byte": 605, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/editor-ui-state.service.spec.ts" }
angular/adev/src/app/editor/typings-loader.service.spec.ts_0_3259
/*! * @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 type {WebContainer} from '@webcontainer/api'; import {TypingsLoader} from './typings-loader.service'; describe('TypingsLoader', () => { let service: TypingsLoader; const fakePackageJson = { exports: { '.': { types: './dist/*.d.ts', }, './something': { types: 'something/index.d.ts', default: 'something/index.js', esm: 'something/index.mjs', }, }, }; const fakeTypeDefinitionFiles = ['file.d.ts']; const fakeFiles = [...fakeTypeDefinitionFiles, 'file.js', 'file.mjs']; const fakeFileContent = 'content'; const fakeWebContainer = { fs: { readFile: (path: string) => { if (path.endsWith('package.json')) { return Promise.resolve(JSON.stringify(fakePackageJson)); } else { return Promise.resolve(fakeFileContent); } }, readdir: (path: string) => { return Promise.resolve(fakeFiles.map((file) => `${path}/${file}`)); }, }, } as unknown as WebContainer; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(TypingsLoader); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should read files from directory when a glob pattern is found', async () => { await service.retrieveTypeDefinitions(fakeWebContainer); expect( service.typings().some(({path}) => path.endsWith(fakeTypeDefinitionFiles[0])), ).toBeTrue(); }); it("should read type definition file when its path doesn't contain a glob pattern", async () => { await service.retrieveTypeDefinitions(fakeWebContainer); expect( service .typings() .some(({path}) => path.endsWith(fakePackageJson.exports['./something'].types)), ).toBeTrue(); }); it('should only contain type definitions files', async () => { await service.retrieveTypeDefinitions(fakeWebContainer); for (const {path} of service.typings()) { expect(path.endsWith('.d.ts')).toBeTrue(); } }); it('should skip library if its package.json can not be found', async () => { const libraryThatIsNotADependency = service['librariesToGetTypesFrom'][0]; const fakeWebContainerThatThrowsWithPackageJson = { fs: { readFile: (path: string) => { if (path.endsWith('package.json')) { if (path.includes(libraryThatIsNotADependency)) return Promise.reject(Error('ENOENT')); else return Promise.resolve(JSON.stringify(fakePackageJson)); } else { return Promise.resolve(fakeFileContent); } }, readdir: (path: string) => { return Promise.resolve(fakeFiles.map((file) => `${path}/${file}`)); }, }, } as unknown as WebContainer; await service.retrieveTypeDefinitions(fakeWebContainerThatThrowsWithPackageJson); for (const {path} of service.typings()) { expect(path.includes(libraryThatIsNotADependency)).toBe(false); } }); });
{ "commit_id": "cb34e406ba", "end_byte": 3259, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/typings-loader.service.spec.ts" }
angular/adev/src/app/editor/README.md_0_6668
# EmbeddedEditor components, services and functionality - [Scenarios](#scenarios) - [Loading a project](#loading-a-project) - [Updating the code](#updating-the-code) - [Creating a new file](#creating-a-new-file) - [Deleting a file](#deleting-a-file) - [Switching a project](#switching-a-project) - [Components and services](#components-and-services) - [EmbeddedEditor](#EmbeddedEditor) - [CodeEditor](#CodeEditor) - [CodeMirrorEditor](#CodeMirrorEditor) - [TypeScript Web Worker](#typescript-web-worker) - [Preview](#Preview) - [Terminal](#Terminal) - [InteractiveTerminal](#InteractiveTerminal) - [Console](#Console) - [NodeRuntimeSandbox](#NodeRuntimeSandbox) - [NodeRuntimeState](#NodeRuntimeState) - [EmbeddedTutorialManager](#EmbeddedTutorialManager) - [EditorUiState](#EditorUiState) - [DownloadManager](#DownloadManager) - [AlertManager](#AlertManager) - [TypingsLoader](#TypingsLoader) ## External libraries - [WebContainers API](https://webcontainers.io/) - [CodeMirror](https://codemirror.net/) - [@typescript/vfs](https://www.npmjs.com/package/@typescript/vfs) - [Xterm.js](https://xtermjs.org/) ## Notes - See [scripts/tutorials/README.md](/scripts/tutorials/README.md) for more information about the tutorials script. - See [adev/src/content/tutorials/README.md](/adev/src/content/tutorials/README.md) for more information about the tutorials content. --- ## Scenarios ### Loading a project 1. The page responsible for the embedded editor lazy loads the [`EmbeddedEditor`](./embedded-editor.component.ts) component and the [`NodeRuntimeSandbox`](./node-runtime-sandbox.service.ts), then triggers the initialization of all components and services. The embedded editor is available in the following pages: - homepage: https://angular.dev - playground: https://angular.dev/playground - tutorial pages: https://angular.dev/tutorials 2. The project assets are fetched by the [`EmbeddedTutorialManager`](./embedded-tutorial-manager.service.ts). Meanwhile: - The code editor is initialized - The code editor initializes the TypeScript Web Worker, which initializes the "default file system map" using TypeScript's CDN. - The WebContainer is initialized - The terminal is initialized 3. The tutorial source code is mounted in the `WebContainer`'s filesystem by the [`NodeRuntimeSandbox`](./node-runtime-sandbox.service.ts) 4. The tutorial project dependencies are installed by the [`NodeRuntimeSandbox`](./node-runtime-sandbox.service.ts). 5. The development server is started by the [`NodeRuntimeSandbox`](./node-runtime-sandbox.service.ts) and the types are loaded by the [`TypingsLoader`](./typings-loader.service.ts) service. 6. The preview is loaded with the URL provided by the WebContainer API after the development server is started. 7. The project is ready. ### Updating the code 1. The user update the code in the code editor. 2. The code editor state is updated on real time, without debouncing so that the user can see the changes in the code editor and CodeMirror can handle the changes accordingly. 3. At the same time, the changes are sent to the TypeScript web worker to provide diagnostics, autocomplete and type features as soon as possible. 4. The code changes are debounced to be written in the WebContainer filesystem by the [`NodeRuntimeSandbox`](./node-runtime-sandbox.service.ts). 5. After the debounce time is reached, the code changes are written in the WebContainer filesystem by the [`NodeRuntimeSandbox`](./node-runtime-sandbox.service.ts), then the user can see the changes in the preview. ### Creating a new file 1. The user clicks on the new file button. 2. The new file tab is opened. 3. The user types the new file name. 4. If the file name is valid, the file is created in the WebContainer filesystem by the [`NodeRuntimeSandbox`](./node-runtime-sandbox.service.ts). - `..` is disallowed in the file name to prevent users to create files outside the `src` directory. 5. The file is added to the TypeScript virtual file system, allowing the TypeScript web worker to provide diagnostics, autocomplete and type features for the new file. Also, exports from the new file are available in other files. 6. The new file is added as the last tab in the code editor and the new file can be edited. Note: If the new file name matches a file that already exists but is hidden in the code editor, the content for that file will show up in the created file. An example for a file that always exists is `index.html`. ### Deleting a file 1. The user clicks on the delete file button. 2. The file is deleted from the WebContainer filesystem by the [`NodeRuntimeSandbox`](./node-runtime-sandbox.service.ts). 3. The file is removed from the TypeScript virtual file system. 4. The file is removed from the code editor tabs. Note: Some files can't be deleted to prevent users to break the app, being `src/main.ts`and `src/index.html` ### Switching a project The embedded editor considers a project change when the embedded editor was already initialized and the user changes the page in the following scenarios: - Navigating through tutorial steps - Going from the homepage after the embedded editor is initialized to the playground - Going from a tutorial page to the playground - Going from a tutorial page to the homepage - Going from the playground to the homepage When a project change is detected, the [`EmbeddedTutorialManager`](./embedded-tutorial-manager.service.ts) emits the `tutorialChanged` observable, which is listened in multiple sub-components and services, then each component/service performs the necessary operations to switch the project. The following steps are executed on project change: 1. The new project files are fetched by the [`EmbeddedTutorialManager`](./embedded-tutorial-manager.service.ts). 2. The new project files are mounted in the WebContainer filesystem. 3. The TypeScript virtual filesystem is updated with the new files and contents. 4. The previous project and new project files are compared. 1. Files that are not available in the new project are deleted from the WebContainer filesystem. 2. Files that have the same path and name have their content replaced on the previous step when the files are mounted. 5. The previous project dependencies are compared with the new project dependencies. 1. If there are differences, a `npm install` is triggered, hiding the preview and going to the install loading step. 2. If there are no differences, the project is ready. 6. Some states are reset, for example the "reveal answer" state if the previous project was in the "reveal answer" state.
{ "commit_id": "cb34e406ba", "end_byte": 6668, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/README.md" }
angular/adev/src/app/editor/README.md_6668_10769
## Components and services ### [`EmbeddedEditor`](./embedded-editor.component.ts) The embedded editor is the parent component that holds all the components and services that compose the embedded editor. #### [`CodeEditor`](./code-editor/code-editor.component.ts) The component that holds the code editor view and the code editor state. ##### [`CodeMirrorEditor`](./code-editor/code-mirror-editor.service.ts) [CodeMirror](https://codemirror.net/) is the library used to handle the code editor. The `CodeMirrorEditor` service manages the CodeMirror instance and all the interactions with the library used to handle the code editor. - handle the file edits and the CodeMirror view and state - handle the current project files in the code editor - handle the file creations and deletions - handle the file changes - handle all the CodeMirror specific events and extensions ###### [TypeScript Web Worker](./code-editor/workers/typescript-vfs.worker.ts) The TypeScript features are provided by the TypeScript web worker, that is initialized by the `CodeMirrorEditor` service. The TypeScript web worker uses `@typescript/vfs` and the TypeScript language service to provide diagnostics, autocomplete and type features. #### [`Preview`](./preview/preview.component.ts) The preview component manages the `iframe` responsible for displaying the tutorial project preview, with the URL provided by the WebContainer API after the development server is started. While the project is being initialized, the preview displays the loading state. #### [`Terminal`](./terminal/terminal.component.ts) [Xterm.js](https://xtermjs.org/) is the library used to handle the terminals. The terminal component handles the Xterm.js instance for the console and for the interactive terminal. ##### [`InteractiveTerminal`](./terminal/interactive-terminal.ts) The interactive terminal is the terminal where the user can interact with the terminal and run commands, supporting only commands for the Angular CLI. ##### Console The console displays the output for `npm install` and `ng serve`. #### [`NodeRuntimeSandbox`](./node-runtime-sandbox.service.ts) Responsible for managing the WebContainer instance and all communication with its API. This service handles: - the WebContainer instance - all Node.js scripts - the WebContainer filesystem, mounting the tutorial project files, writing new content, deleting and creating files. - the terminal session, reading and processing user inputs. - the tutorial project dependencies, installing the dependencies. - the processes running inside the WebContainer, being the npm scripts to install the dependencies, run the development server and the user inputs for the `ng` CLI. ##### [`NodeRuntimeState`](./node-runtime-state.service.ts) Manages the [`NodeRuntimeSandbox`](./node-runtime-sandbox.service.ts) loading and error state. #### [`EmbeddedTutorialManager`](./embedded-tutorial-manager.service.ts) Manages the tutorial assets, being responsible for fetching the tutorial source code and metadata. The source code is mounted in the WebContainer filesystem by the [`NodeRuntimeSandbox`](./node-runtime-sandbox.service.ts). The metadata is used to manage the project, handle the project changes and the user interactivity with the app. This service also handles the reveal answer and reset reveal answer feature. #### [`EditorUiState`](./editor-ui-state.service.ts) Manages the editor UI state, being responsible for handling the user interactions with the editor tabs, switching between the preview, the terminal and the console. #### [`DownloadManager`](./download-manager.service.ts) Responsible for handling the download button in the embedded editor, fetching the tutorial project files and generating a zip file with the project content. #### [`AlertManager`](./alert-manager.service.ts) Manage the alerts displayed in the embedded editor, being the out of memory alert when multiple tabs are opened, and unsupported environments alerts. #### [`TypingsLoader`](./typings-loader.service.ts) Manages the types definitions for the code editor.
{ "commit_id": "cb34e406ba", "end_byte": 10769, "start_byte": 6668, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/README.md" }
angular/adev/src/app/editor/embedded-tutorial-manager.service.spec.ts_0_6405
/*! * @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 type {FileSystemTree} from '@webcontainer/api'; import type {TutorialConfig, TutorialMetadata} from '@angular/docs'; import {TUTORIALS_ASSETS_WEB_PATH} from '../editor/constants'; import {TutorialType} from '@angular/docs'; import {EmbeddedTutorialManager} from './embedded-tutorial-manager.service'; describe('EmbeddedTutorialManager', () => { let service: EmbeddedTutorialManager; beforeEach(() => { TestBed.configureTestingModule({ providers: [EmbeddedTutorialManager], }); service = TestBed.inject(EmbeddedTutorialManager); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should set the tutorialFiles as the answerFiles on revealAnswer', () => { const tutorialFiles = {'file': 'content'}; const answerFiles = {'file': 'answer'}; service['answerFiles'].set(answerFiles); service['tutorialFiles'].set(tutorialFiles); service.revealAnswer(); expect(service.tutorialFiles()).toEqual(answerFiles); }); it('should reset the tutorialFiles on resetRevealAnswer', () => { const tutorialFiles = {'file': 'original'}; const answerFiles = {'file': 'answer'}; const openFiles = ['file']; const config: TutorialConfig = { title: '', type: TutorialType.EDITOR, openFiles, }; // set fake metadata as tutorialFiles will be reset based on // metadata.tutorialFiles service['metadata'].set({ answerFiles, tutorialFiles, openFiles, hiddenFiles: [], type: config.type, dependencies: {}, allFiles: [], }); service['answerFiles'].set(answerFiles); service['hiddenFiles'].set(['hidden.ts']); service.revealAnswer(); expect(service.tutorialFiles()).toEqual(answerFiles); expect(service.openFiles()).toEqual(openFiles); service.resetRevealAnswer(); expect(service.tutorialFiles()).toEqual(tutorialFiles); expect(service.openFiles()).toEqual(openFiles); }); it('should not have hiddenFiles in openFiles on reveal and reset answer', () => { const hiddenFiles = ['hidden1.ts', 'hidden2.ts']; const openFiles = ['open.ts']; const tutorialFiles = { [openFiles[0]]: 'content', [hiddenFiles[0]]: 'content', }; const answerFiles = {'answer.ts': 'answer'}; const config: TutorialConfig = { title: '', type: TutorialType.EDITOR, openFiles, }; service.hiddenFiles.set(hiddenFiles); service.openFiles.set(openFiles); service.tutorialFiles.set(tutorialFiles); service.answerFiles.set(answerFiles); service['metadata'].set({ answerFiles, tutorialFiles, openFiles, hiddenFiles, type: config.type, dependencies: {}, allFiles: [], }); service.revealAnswer(); for (const hiddenFile of hiddenFiles) { expect(service.openFiles()).not.toContain(hiddenFile); } service.resetRevealAnswer(); for (const hiddenFile of hiddenFiles) { expect(service.openFiles()).not.toContain(hiddenFile); } }); it('should have answer files that are not hidden as openFiles on reveal answer', () => { const openFiles = ['file.ts']; const tutorialFiles = { [openFiles[0]]: 'content', }; const newFile = 'new-file.ts'; const answerFiles = { [openFiles[0]]: 'answer', [newFile]: 'answer', }; const config: TutorialConfig = { title: '', type: TutorialType.EDITOR, openFiles, }; service.openFiles.set(openFiles); service.tutorialFiles.set(tutorialFiles); service.answerFiles.set(answerFiles); service['metadata'].set({ answerFiles, tutorialFiles, openFiles, hiddenFiles: [], type: config.type, dependencies: {}, allFiles: [], }); service.revealAnswer(); expect(service.openFiles()).toContain(newFile); }); it('should not have duplicate files in openFiles on reveal and reset answer', () => { const openFiles = ['file.ts']; const tutorialFiles = { [openFiles[0]]: 'content', }; const answerFiles = { [openFiles[0]]: 'answer', }; const config: TutorialConfig = { title: '', type: TutorialType.EDITOR, openFiles, }; service.openFiles.set(openFiles); service.tutorialFiles.set(tutorialFiles); service.answerFiles.set(answerFiles); service['metadata'].set({ answerFiles, tutorialFiles, openFiles, hiddenFiles: [], type: config.type, dependencies: {}, allFiles: [], }); service.revealAnswer(); expect(service.openFiles().length).toBe(1); service.resetRevealAnswer(); expect(service.openFiles().length).toBe(1); }); it('should keep openFiles order on reveal and reset answer', () => { const openFiles = ['1', '2', '3']; const tutorialFiles = { [openFiles[0]]: 'content', [openFiles[1]]: 'content', [openFiles[2]]: 'content', }; const answerFiles = { [openFiles[0]]: 'answer', [openFiles[1]]: 'answer', [openFiles[2]]: 'answer', '0': 'answer', }; const config: TutorialConfig = { title: '', type: TutorialType.EDITOR, openFiles, }; service.openFiles.set(openFiles); service.tutorialFiles.set(tutorialFiles); service.answerFiles.set(answerFiles); service['metadata'].set({ answerFiles, tutorialFiles, openFiles, hiddenFiles: [], dependencies: {}, type: config.type, allFiles: [], }); service.revealAnswer(); for (const [index, openFile] of service.openFiles().entries()) { if (openFiles[index]) { expect(openFile).toBe(openFiles[index]); } } service.resetRevealAnswer(); for (const [index, openFile] of service.openFiles().entries()) { expect(openFile).toBe(openFiles[index]); } }); it('should trigger tutorial change on reveal answer', () => { const _shouldChangeTutorial$Spy = spyOn(service['_shouldChangeTutorial$'], 'next'); service.revealAnswer(); expect(_shouldChangeTutorial$Spy).toHaveBeenCalled(); });
{ "commit_id": "cb34e406ba", "end_byte": 6405, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/embedded-tutorial-manager.service.spec.ts" }
angular/adev/src/app/editor/embedded-tutorial-manager.service.spec.ts_6409_15058
describe('fetchAndSetTutorialFiles', () => { const tutorial: string = 'tutorial-id'; it('should fetch tutorial source code and config and set signals', async () => { const tutorialSourceCode: FileSystemTree = { 'tutorial.ts': { file: { contents: 'code', }, }, }; const metadata: TutorialMetadata = { tutorialFiles: {'app.js': ''}, openFiles: ['app.js'], type: TutorialType.EDITOR, hiddenFiles: ['hidden.ts'], answerFiles: {'app.js': ''}, dependencies: {}, allFiles: [], }; const fetchMock = spyOn(window, 'fetch'); fetchMock.and.returnValues( Promise.resolve(new Response(JSON.stringify(tutorialSourceCode))), Promise.resolve(new Response(JSON.stringify(metadata))), ); await service.fetchAndSetTutorialFiles(tutorial); expect(fetchMock).toHaveBeenCalledTimes(2); expect(service.tutorialId()).toEqual(tutorial); expect(service.tutorialFilesystemTree()).toEqual(tutorialSourceCode); expect(service.openFiles()).toEqual(metadata.openFiles!); expect(service.tutorialFiles()).toEqual(metadata.tutorialFiles!); expect(service['metadata']()).toEqual(metadata); expect(service.type()).toEqual(metadata.type); expect(service.hiddenFiles()).toEqual(metadata.hiddenFiles); expect(service.answerFiles()).toEqual(metadata.answerFiles!); }); it('should throw an error if the tutorial files cannot be fetched', async () => { const fetchMock = spyOn(window, 'fetch'); fetchMock .withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/source-code.json`) .and.returnValues(Promise.resolve(new Response(null, {status: 404}))); fetchMock .withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/metadata.json`) .and.returnValues(Promise.resolve(new Response(null, {status: 404}))); await expectAsync(service.fetchAndSetTutorialFiles(tutorial)).toBeRejectedWithError( `Missing source code for tutorial ${tutorial}`, ); }); it('should not set shouldReinstallDependencies if project did not change', async () => { const fetchMock = spyOn(window, 'fetch'); fetchMock .withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/source-code.json`) .and.returnValues(Promise.resolve(new Response('{}', {status: 200}))); fetchMock.withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/metadata.json`).and.returnValues( Promise.resolve( new Response( JSON.stringify({ dependencies: { '@angular/core': '2.0.0', }, allFiles: [], }), {status: 200}, ), ), ); await service['fetchAndSetTutorialFiles'](tutorial); expect(service.shouldReInstallDependencies()).toBe(false); }); it('should trigger shouldReInstallDependencies if new metadata has different dependencies', async () => { const fetchMock = spyOn(window, 'fetch'); fetchMock .withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/source-code.json`) .and.returnValues(Promise.resolve(new Response('{}', {status: 200}))); fetchMock.withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/metadata.json`).and.returnValues( Promise.resolve( new Response( JSON.stringify({ dependencies: { '@angular/core': '2.0.0', }, allFiles: [], }), {status: 200}, ), ), ); service['tutorialId'].set('previous-tutorial'); service['dependencies'].set({ '@angular/core': '1.0.0', }); await service['fetchAndSetTutorialFiles'](tutorial); expect(service.shouldReInstallDependencies()).toBe(true); }); it('should trigger shouldReInstallDependencies if new metadata has dependencies and previous dependencies were empty', async () => { const fetchMock = spyOn(window, 'fetch'); fetchMock .withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/source-code.json`) .and.returnValues(Promise.resolve(new Response('{}', {status: 200}))); fetchMock.withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/metadata.json`).and.returnValues( Promise.resolve( new Response( JSON.stringify({ dependencies: { '@angular/core': '2.0.0', }, allFiles: [], }), {status: 200}, ), ), ); service['tutorialId'].set('previous-tutorial'); service['dependencies'].set({}); await service['fetchAndSetTutorialFiles'](tutorial); expect(service.shouldReInstallDependencies()).toBe(true); }); it('should not trigger shouldReInstallDependencies if new metadata has same dependencies', async () => { const fetchMock = spyOn(window, 'fetch'); fetchMock .withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/source-code.json`) .and.returnValues(Promise.resolve(new Response('{}', {status: 200}))); fetchMock.withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/metadata.json`).and.returnValues( Promise.resolve( new Response( JSON.stringify({ dependencies: { '@angular/core': '1.0.0', }, allFiles: [], }), {status: 200}, ), ), ); service['tutorialId'].set('previous-tutorial'); service['dependencies'].set({ '@angular/core': '1.0.0', }); await service['fetchAndSetTutorialFiles'](tutorial); expect(service.shouldReInstallDependencies()).toBe(false); }); it('should set files to delete on project change if previous project has unused files', async () => { const fetchMock = spyOn(window, 'fetch'); fetchMock .withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/source-code.json`) .and.returnValues(Promise.resolve(new Response('{}', {status: 200}))); const allFiles = ['file1.ts', 'file2.ts']; fetchMock.withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/metadata.json`).and.returnValues( Promise.resolve( new Response( JSON.stringify({ allFiles, }), {status: 200}, ), ), ); const unusedFiles = ['old-file.ts', 'old-file.css']; const previousFiles = [...allFiles, ...unusedFiles]; service['tutorialId'].set('previous-tutorial'); service['allFiles'].set(previousFiles); await service['fetchAndSetTutorialFiles'](tutorial); expect(service['filesToDeleteFromPreviousProject']()).toEqual(new Set(unusedFiles)); }); it('should set no files to delete on project change if previous project has same files as new project', async () => { const fetchMock = spyOn(window, 'fetch'); fetchMock .withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/source-code.json`) .and.returnValues(Promise.resolve(new Response('{}', {status: 200}))); const allFiles = ['file1.ts', 'file2.ts']; fetchMock.withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/metadata.json`).and.returnValues( Promise.resolve( new Response( JSON.stringify({ allFiles, }), {status: 200}, ), ), ); service['tutorialId'].set('previous-tutorial'); service['allFiles'].set(allFiles); await service['fetchAndSetTutorialFiles'](tutorial); expect(service['filesToDeleteFromPreviousProject']().size).toBe(0); }); it('should not set files to delete if project did not change', async () => { const fetchMock = spyOn(window, 'fetch'); fetchMock .withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/source-code.json`) .and.returnValues(Promise.resolve(new Response('{}', {status: 200}))); const allFiles = ['file1.ts', 'file2.ts']; fetchMock.withArgs(`${TUTORIALS_ASSETS_WEB_PATH}/${tutorial}/metadata.json`).and.returnValues( Promise.resolve( new Response( JSON.stringify({ allFiles, }), {status: 200}, ), ), ); expect(service['allFiles']().length).toBe(0); await service['fetchAndSetTutorialFiles'](tutorial); expect(service['filesToDeleteFromPreviousProject']().size).toBe(0); }); }); });
{ "commit_id": "cb34e406ba", "end_byte": 15058, "start_byte": 6409, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/embedded-tutorial-manager.service.spec.ts" }
angular/adev/src/app/editor/stackblitz-opener.service.ts_0_1496
/*! * @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 {EnvironmentInjector, Injectable, inject} from '@angular/core'; import sdk, {Project, ProjectFiles} from '@stackblitz/sdk'; import {injectAsync} from '../core/services/inject-async'; @Injectable({ providedIn: 'root', }) export class StackBlitzOpener { private readonly environmentInjector = inject(EnvironmentInjector); /** * Generate a StackBlitz project from the current state of the solution in the EmbeddedEditor */ async openCurrentSolutionInStackBlitz( projectMetadata: Pick<Project, 'title' | 'description'>, ): Promise<void> { const nodeRuntimeSandbox = await injectAsync(this.environmentInjector, () => import('./node-runtime-sandbox.service').then((c) => c.NodeRuntimeSandbox), ); const runtimeFiles = await nodeRuntimeSandbox.getSolutionFiles(); const stackblitzProjectFiles: ProjectFiles = {}; runtimeFiles.forEach((file) => { // Leading slashes are incompatible with StackBlitz SDK they are removed const path = file.path.replace(/^\//, ''); stackblitzProjectFiles[path] = typeof file.content !== 'string' ? new TextDecoder().decode(file.content) : file.content; }); sdk.openProject({ ...projectMetadata, template: 'node', files: stackblitzProjectFiles, }); } }
{ "commit_id": "cb34e406ba", "end_byte": 1496, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/stackblitz-opener.service.ts" }
angular/adev/src/app/editor/constants.ts_0_686
/*! * @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 const TUTORIALS_ASSETS_WEB_PATH = '/assets/tutorials'; export const TUTORIALS_ASSETS_SOURCE_CODE_DIRECTORY = 'source-code'; export const TUTORIALS_ASSETS_METADATA_DIRECTORY = 'metadata'; export const TUTORIALS_SOURCE_CODE_WEB_PATH = `${TUTORIALS_ASSETS_WEB_PATH}/${TUTORIALS_ASSETS_SOURCE_CODE_DIRECTORY}`; export const TUTORIALS_METADATA_WEB_PATH = `${TUTORIALS_ASSETS_WEB_PATH}/${TUTORIALS_ASSETS_METADATA_DIRECTORY}`; export const TUTORIALS_COMMON_DIRECTORY = 'common';
{ "commit_id": "cb34e406ba", "end_byte": 686, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/constants.ts" }
angular/adev/src/app/editor/alert-manager.service.ts_0_3544
/*! * @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, inject} from '@angular/core'; import {LOCAL_STORAGE, WINDOW, isMobile} from '@angular/docs'; import {MatSnackBar} from '@angular/material/snack-bar'; import {ErrorSnackBar, ErrorSnackBarData} from '../core/services/errors-handling/error-snack-bar'; export const MAX_RECOMMENDED_WEBCONTAINERS_INSTANCES = 3; export const WEBCONTAINERS_COUNTER_KEY = 'numberOfWebcontainers'; export enum AlertReason { OUT_OF_MEMORY, MOBILE, } @Injectable({providedIn: 'root'}) export class AlertManager { private readonly localStorage = inject(LOCAL_STORAGE); private readonly window = inject(WINDOW); private snackBar = inject(MatSnackBar); init(): void { this.listenToLocalStorageValuesChange(); this.increaseInstancesCounter(); this.decreaseInstancesCounterOnPageClose(); this.checkDevice(); } private listenToLocalStorageValuesChange(): void { this.window.addEventListener('storage', () => { const countOfRunningInstances = this.getStoredCountOfWebcontainerInstances(); this.validateRunningInstances(countOfRunningInstances); }); } // Increase count of the running instances of the webcontainers when user will boot the webcontainer private increaseInstancesCounter(): void { const countOfRunningInstances = this.getStoredCountOfWebcontainerInstances() + 1; this.localStorage?.setItem(WEBCONTAINERS_COUNTER_KEY, countOfRunningInstances.toString()); this.validateRunningInstances(countOfRunningInstances); } // Decrease count of running instances of the webcontainers when user close the app. private decreaseInstancesCounterOnPageClose(): void { this.window.addEventListener('beforeunload', () => { const countOfRunningInstances = this.getStoredCountOfWebcontainerInstances() - 1; this.localStorage?.setItem(WEBCONTAINERS_COUNTER_KEY, countOfRunningInstances.toString()); this.validateRunningInstances(countOfRunningInstances); }); } private getStoredCountOfWebcontainerInstances(): number { const countStoredInLocalStorage = this.localStorage?.getItem(WEBCONTAINERS_COUNTER_KEY); if (!countStoredInLocalStorage || Number.isNaN(countStoredInLocalStorage)) { return 0; } return Number(countStoredInLocalStorage); } private validateRunningInstances(countOfRunningInstances: number): void { if (countOfRunningInstances > MAX_RECOMMENDED_WEBCONTAINERS_INSTANCES) { this.openSnackBar(AlertReason.OUT_OF_MEMORY); } } private checkDevice() { if (isMobile) { this.openSnackBar(AlertReason.MOBILE); } } private openSnackBar(reason: AlertReason) { let message = ''; switch (reason) { case AlertReason.OUT_OF_MEMORY: message = `Your browser is currently limiting the memory available to run the Angular Tutorials or Playground. If you have multiple tabs open with Tutorials or Playground, please close some of them and refresh this page.`; break; case AlertReason.MOBILE: message = `You are running the embedded editor in a mobile device, this may result in an Out of memory error.`; break; } this.snackBar.openFromComponent(ErrorSnackBar, { panelClass: 'docs-invert-mode', data: { message, actionText: 'I understand', } satisfies ErrorSnackBarData, }); } }
{ "commit_id": "cb34e406ba", "end_byte": 3544, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/alert-manager.service.ts" }
angular/adev/src/app/editor/node-runtime-state.service.spec.ts_0_1538
/*! * @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 {ErrorType, NodeRuntimeState} from './node-runtime-state.service'; import {OUT_OF_MEMORY_MSG} from './node-runtime-sandbox.service'; describe('NodeRuntimeState', () => { let service: NodeRuntimeState; beforeEach(() => { TestBed.configureTestingModule({ providers: [NodeRuntimeState], }); service = TestBed.inject(NodeRuntimeState); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should set cookies error type based on error message', () => { service.setError({message: 'service worker', type: undefined}); expect(service['error']()!.type).toBe(ErrorType.COOKIES); }); it('should set out of memory error type based on error message', () => { service.setError({message: OUT_OF_MEMORY_MSG, type: undefined}); expect(service['error']()!.type).toBe(ErrorType.OUT_OF_MEMORY); }); it('should set unknown error type based on error message', () => { service.setError({message: 'something else', type: undefined}); expect(service['error']()!.type).toBe(ErrorType.UNKNOWN); }); it('should set unknown error type if error message is undefined', () => { service.setError({message: undefined, type: undefined}); expect(service['error']()!.type).toBe(ErrorType.UNKNOWN); }); });
{ "commit_id": "cb34e406ba", "end_byte": 1538, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/node-runtime-state.service.spec.ts" }
angular/adev/src/app/editor/embedded-editor.component.ts_0_5158
/*! * @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} from '@angular/common'; import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, ElementRef, OnDestroy, OnInit, PLATFORM_ID, ViewChild, computed, inject, signal, } from '@angular/core'; import {takeUntilDestroyed, toObservable} from '@angular/core/rxjs-interop'; import {IconComponent} from '@angular/docs'; import {MatTabGroup, MatTabsModule} from '@angular/material/tabs'; import {distinctUntilChanged, map} from 'rxjs'; import {MAX_RECOMMENDED_WEBCONTAINERS_INSTANCES} from './alert-manager.service'; import {AngularSplitModule} from 'angular-split'; import {CodeEditor} from './code-editor/code-editor.component'; import {DiagnosticsState} from './code-editor/services/diagnostics-state.service'; import {EditorUiState} from './editor-ui-state.service'; import {LoadingStep} from './enums/loading-steps'; import {NodeRuntimeSandbox} from './node-runtime-sandbox.service'; import {NodeRuntimeState} from './node-runtime-state.service'; import {Preview} from './preview/preview.component'; import {TerminalType} from './terminal/terminal-handler.service'; import {Terminal} from './terminal/terminal.component'; export const EMBEDDED_EDITOR_SELECTOR = 'embedded-editor'; export const LARGE_EDITOR_WIDTH_BREAKPOINT = 950; export const LARGE_EDITOR_HEIGHT_BREAKPOINT = 550; @Component({ selector: EMBEDDED_EDITOR_SELECTOR, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [AngularSplitModule, CodeEditor, Preview, Terminal, MatTabsModule, IconComponent], templateUrl: './embedded-editor.component.html', styleUrls: ['./embedded-editor.component.scss'], providers: [EditorUiState], }) export class EmbeddedEditor implements OnInit, AfterViewInit, OnDestroy { @ViewChild('editorContainer') editorContainer!: ElementRef<HTMLDivElement>; @ViewChild(MatTabGroup) matTabGroup!: MatTabGroup; private readonly platformId = inject(PLATFORM_ID); private readonly changeDetector = inject(ChangeDetectorRef); private readonly destroyRef = inject(DestroyRef); private readonly diagnosticsState = inject(DiagnosticsState); private readonly editorUiState = inject(EditorUiState); private readonly nodeRuntimeState = inject(NodeRuntimeState); private readonly nodeRuntimeSandbox = inject(NodeRuntimeSandbox); private resizeObserver?: ResizeObserver; protected splitDirection: 'horizontal' | 'vertical' = 'vertical'; readonly MAX_RECOMMENDED_WEBCONTAINERS_INSTANCES = MAX_RECOMMENDED_WEBCONTAINERS_INSTANCES; readonly TerminalType = TerminalType; readonly displayOnlyTerminal = computed( () => this.editorUiState.uiState().displayOnlyInteractiveTerminal, ); readonly errorsCount = signal<number>(0); readonly displayPreviewInMatTabGroup = signal<boolean>(true); readonly shouldEnableReset = computed( () => this.nodeRuntimeState.loadingStep() > LoadingStep.BOOT && !this.nodeRuntimeState.isResetting(), ); private readonly errorsCount$ = this.diagnosticsState.diagnostics$.pipe( map((diagnosticsItem) => diagnosticsItem.filter((item) => item.severity === 'error').length), distinctUntilChanged(), takeUntilDestroyed(this.destroyRef), ); private readonly displayPreviewInMatTabGroup$ = toObservable( this.displayPreviewInMatTabGroup, ).pipe(distinctUntilChanged(), takeUntilDestroyed(this.destroyRef)); ngOnInit(): void { this.listenToErrorsCount(); } ngAfterViewInit(): void { if (isPlatformBrowser(this.platformId)) { this.setFirstTabAsActiveAfterResize(); this.setResizeObserver(); } } ngOnDestroy(): void { this.resizeObserver?.disconnect(); } setVisibleEmbeddedEditorTabs(): void { this.displayPreviewInMatTabGroup.set(!this.isLargeEmbeddedEditor()); } async reset(): Promise<void> { await this.nodeRuntimeSandbox.reset(); } private setFirstTabAsActiveAfterResize(): void { this.displayPreviewInMatTabGroup$.subscribe(() => { this.changeDetector.detectChanges(); this.matTabGroup.selectedIndex = 0; }); } private listenToErrorsCount(): void { this.errorsCount$.subscribe((errorsCount) => { this.errorsCount.set(errorsCount); }); } // Listen to resizing of Embedded Editor and set proper list of the tabs for the current resolution. private setResizeObserver() { this.resizeObserver = new ResizeObserver((_) => { this.setVisibleEmbeddedEditorTabs(); this.splitDirection = this.isLargeEmbeddedEditor() ? 'horizontal' : 'vertical'; }); this.resizeObserver.observe(this.editorContainer.nativeElement); } private isLargeEmbeddedEditor(): boolean { const editorContainer = this.editorContainer.nativeElement; const width = editorContainer.offsetWidth; const height = editorContainer.offsetHeight; return width > LARGE_EDITOR_WIDTH_BREAKPOINT && height > LARGE_EDITOR_HEIGHT_BREAKPOINT; } }
{ "commit_id": "cb34e406ba", "end_byte": 5158, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/embedded-editor.component.ts" }
angular/adev/src/app/editor/index.ts_0_346
export {EmbeddedTutorialManager} from './embedded-tutorial-manager.service'; export {LoadingStep} from './enums/loading-steps'; export {NodeRuntimeState} from './node-runtime-state.service'; export {NodeRuntimeSandbox} from './node-runtime-sandbox.service'; export {EmbeddedEditor, EMBEDDED_EDITOR_SELECTOR} from './embedded-editor.component';
{ "commit_id": "cb34e406ba", "end_byte": 346, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/index.ts" }
angular/adev/src/app/editor/node-runtime-sandbox.service.spec.ts_0_1018
/*! * @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 {BehaviorSubject, of as observableOf} from 'rxjs'; import {signal} from '@angular/core'; import {WebContainer} from '@webcontainer/api'; import {TutorialType} from '@angular/docs'; import {FakeWebContainer, FakeWebContainerProcess} from '@angular/docs'; import {AlertManager} from './alert-manager.service'; import {EmbeddedTutorialManager} from './embedded-tutorial-manager.service'; import {LoadingStep} from './enums/loading-steps'; import { DEV_SERVER_READY_MSG, NodeRuntimeSandbox, OUT_OF_MEMORY_MSG, PACKAGE_MANAGER, } from './node-runtime-sandbox.service'; import {NodeRuntimeState} from './node-runtime-state.service'; import {TerminalHandler} from './terminal/terminal-handler.service'; import {TypingsLoader} from './typings-loader.service';
{ "commit_id": "cb34e406ba", "end_byte": 1018, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/node-runtime-sandbox.service.spec.ts" }
angular/adev/src/app/editor/node-runtime-sandbox.service.spec.ts_1020_9510
describe('NodeRuntimeSandbox', () => { let testBed: TestBed; let service: NodeRuntimeSandbox; const fakeTerminalHandler = { interactiveTerminalInstance: { write: (data: string) => {}, onData: (data: string) => {}, breakProcess$: observableOf(), }, readonlyTerminalInstance: { write: (data: string) => {}, }, clearTerminals: () => {}, }; const tutorialChanged$ = new BehaviorSubject(false); const fakeEmbeddedTutorialManager: Partial<EmbeddedTutorialManager> = { tutorialId: signal('tutorial'), tutorialFilesystemTree: signal({'app.js': {file: {contents: ''}}}), commonFilesystemTree: signal({'app.js': {file: {contents: ''}}}), openFiles: signal(['app.js']), tutorialFiles: signal({'app.js': ''}), hiddenFiles: signal(['hidden.js']), answerFiles: signal({'answer.ts': ''}), type: signal(TutorialType.EDITOR), tutorialChanged$, shouldReInstallDependencies: signal(false), filesToDeleteFromPreviousProject: signal(new Set([])), }; const setValuesToInitializeAngularCLI = () => { service['embeddedTutorialManager'].type.set(TutorialType.CLI); service['webContainerPromise'] = Promise.resolve( new FakeWebContainer() as unknown as WebContainer, ); }; const setValuesToInitializeProject = () => { service['embeddedTutorialManager'].type.set(TutorialType.EDITOR); const fakeSpawnProcess = new FakeWebContainerProcess(); fakeSpawnProcess.output = { pipeTo: (data: WritableStream) => { data.getWriter().write(DEV_SERVER_READY_MSG); }, pipeThrough: () => fakeSpawnProcess.output, } as any; service['webContainerPromise'] = Promise.resolve( new FakeWebContainer({spawn: fakeSpawnProcess}) as unknown as WebContainer, ); }; const setValuesToCatchOutOfMemoryError = () => { service['embeddedTutorialManager'].type.set(TutorialType.EDITOR); const fakeSpawnProcess = new FakeWebContainerProcess(); fakeSpawnProcess.output = { pipeTo: (data: WritableStream) => { data.getWriter().write(OUT_OF_MEMORY_MSG); }, pipeThrough: () => fakeSpawnProcess.output, } as any; service['webContainerPromise'] = Promise.resolve( new FakeWebContainer({spawn: fakeSpawnProcess}) as unknown as WebContainer, ); }; const fakeTypingsLoader: Partial<TypingsLoader> = { retrieveTypeDefinitions: (webcontainer: WebContainer) => Promise.resolve(), }; const fakeAlertManager = { init: () => {}, }; beforeEach(() => { testBed = TestBed.configureTestingModule({ providers: [ NodeRuntimeSandbox, { provide: TerminalHandler, useValue: fakeTerminalHandler, }, { provide: TypingsLoader, useValue: fakeTypingsLoader, }, { provide: EmbeddedTutorialManager, useValue: fakeEmbeddedTutorialManager, }, { provide: AlertManager, useValue: fakeAlertManager, }, { provide: NodeRuntimeState, }, ], }); service = testBed.inject(NodeRuntimeSandbox); service['embeddedTutorialManager'].type.set(TutorialType.EDITOR); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should set error message when install dependencies resolve exitCode not equal to 0', async () => { const EXPECTED_ERROR = 'Installation failed'; service['webContainerPromise'] = Promise.resolve( new FakeWebContainer() as unknown as WebContainer, ); const fakeSpawn = new FakeWebContainerProcess(); fakeSpawn.exit = Promise.resolve(10); spyOn(service, 'spawn' as any) .withArgs(PACKAGE_MANAGER, ['install']) .and.returnValue(fakeSpawn); await service.init(); expect(service['nodeRuntimeState'].error()?.message).toBe(EXPECTED_ERROR); }); it('should have ready loading state after init succeeds', async () => { setValuesToInitializeProject(); await service.init(); const state = TestBed.inject(NodeRuntimeState); expect(state.loadingStep()).toBe(LoadingStep.READY); }); it('should call writeFile with proper parameters', async () => { setValuesToInitializeProject(); const fakeWebContainer = new FakeWebContainer(); service['webContainerPromise'] = Promise.resolve(fakeWebContainer as unknown as WebContainer); const writeFileSpy = spyOn(fakeWebContainer.fs, 'writeFile'); const path = 'path'; const content = 'content'; await service.writeFile(path, content); expect(writeFileSpy).toHaveBeenCalledOnceWith(path, content); }); it('should call renameFile with proper parameters', async () => { setValuesToInitializeProject(); const fakeWebContainer = new FakeWebContainer(); service['webContainerPromise'] = Promise.resolve(fakeWebContainer as unknown as WebContainer); const renameFileSpy = spyOn(fakeWebContainer.fs, 'rename'); const oldPath = 'oldPath'; const newPath = 'newPath'; await service.renameFile(oldPath, newPath); expect(renameFileSpy).toHaveBeenCalledOnceWith(oldPath, newPath); }); it('should initialize the Angular CLI based on the tutorial config', async () => { setValuesToInitializeAngularCLI(); const initAngularCliSpy = spyOn(service, 'initAngularCli' as any); await service.init(); expect(initAngularCliSpy).toHaveBeenCalled(); }); it('should initialize a project based on the tutorial config', async () => { service['webContainerPromise'] = Promise.resolve( new FakeWebContainer() as unknown as WebContainer, ); setValuesToInitializeProject(); const initProjectSpy = spyOn(service, 'initProject' as any); await service.init(); expect(initProjectSpy).toHaveBeenCalled(); }); it('should cleanup when initializing the Angular CLI if a project was initialized before', async () => { const cleanupSpy = spyOn(service, 'cleanup' as any); setValuesToInitializeProject(); await service.init(); expect(cleanupSpy).not.toHaveBeenCalled(); setValuesToInitializeAngularCLI(); await service.init(); expect(cleanupSpy).toHaveBeenCalledOnceWith(); }); it('should cleanup when initializing a project if the Angular CLI was initialized before', async () => { const cleanupSpy = spyOn(service, 'cleanup' as any); setValuesToInitializeAngularCLI(); await service.init(); expect(cleanupSpy).not.toHaveBeenCalled(); setValuesToInitializeProject(); await service.init(); expect(cleanupSpy).toHaveBeenCalledOnceWith(); }); it("should set the error state when an out of memory message is received from the web container's output", async () => { service['webContainerPromise'] = Promise.resolve( new FakeWebContainer() as unknown as WebContainer, ); setValuesToCatchOutOfMemoryError(); await service.init(); expect(service['nodeRuntimeState'].error()!.message).toBe(OUT_OF_MEMORY_MSG); expect(service['nodeRuntimeState'].loadingStep()).toBe(LoadingStep.ERROR); }); it('should run reset only once when called twice', async () => { const cleanupSpy = spyOn(service, 'cleanup' as any); const initSpy = spyOn(service, 'init' as any); setValuesToInitializeProject(); const resetPromise = service.reset(); const secondResetPromise = service.reset(); await Promise.all([resetPromise, secondResetPromise]); expect(cleanupSpy).toHaveBeenCalledOnceWith(); expect(initSpy).toHaveBeenCalledOnceWith(); }); it('should delete files on project change', async () => { service['webContainerPromise'] = Promise.resolve( new FakeWebContainer() as unknown as WebContainer, ); setValuesToInitializeProject(); await service.init(); const filesToDeleteFromPreviousProject = ['deleteme.ts']; service['embeddedTutorialManager'] = { ...fakeEmbeddedTutorialManager, filesToDeleteFromPreviousProject: signal(new Set(filesToDeleteFromPreviousProject)), } as any; const createdFiles = ['created.ts']; service['_createdFiles'].set(new Set(createdFiles)); const deleteFileSpy = spyOn(service, 'deleteFile'); tutorialChanged$.next(true); const allFilesToDelete = [...createdFiles, ...filesToDeleteFromPreviousProject]; for (const fileToDelete of allFilesToDelete) { expect(deleteFileSpy).toHaveBeenCalledWith(fileToDelete); } }); });
{ "commit_id": "cb34e406ba", "end_byte": 9510, "start_byte": 1020, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/node-runtime-sandbox.service.spec.ts" }
angular/adev/src/app/editor/download-manager.service.spec.ts_0_575
/*! * @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 {DownloadManager} from './download-manager.service'; describe('DownloadManager', () => { let service: DownloadManager; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(DownloadManager); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
{ "commit_id": "cb34e406ba", "end_byte": 575, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/download-manager.service.spec.ts" }
angular/adev/src/app/editor/node-runtime-state.service.ts_0_2490
/*! * @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, signal} from '@angular/core'; import {isFirefox, isIos} from '@angular/docs'; import {LoadingStep} from './enums/loading-steps'; import {OUT_OF_MEMORY_MSG} from './node-runtime-sandbox.service'; export const MAX_RECOMMENDED_WEBCONTAINERS_INSTANCES = 3; export const WEBCONTAINERS_COUNTER_KEY = 'numberOfWebcontainers'; export type NodeRuntimeError = { message: string | undefined; type: ErrorType | undefined; }; export enum ErrorType { UNKNOWN, COOKIES, OUT_OF_MEMORY, UNSUPPORTED_BROWSER_ENVIRONMENT, } @Injectable({providedIn: 'root'}) export class NodeRuntimeState { private readonly _loadingStep = signal<number>(LoadingStep.NOT_STARTED); loadingStep = this._loadingStep.asReadonly(); private readonly _isResetting = signal(false); readonly isResetting = this._isResetting.asReadonly(); readonly _error = signal<NodeRuntimeError | undefined>(undefined); readonly error = this._error.asReadonly(); constructor() { this.checkUnsupportedEnvironment(); } setLoadingStep(step: LoadingStep): void { this._loadingStep.set(step); } setIsResetting(isResetting: boolean): void { this._isResetting.set(isResetting); } setError({message, type}: NodeRuntimeError) { type ??= this.getErrorType(message); this._error.set({message, type}); this.setLoadingStep(LoadingStep.ERROR); } private getErrorType(message: NodeRuntimeError['message']) { if (message?.includes(OUT_OF_MEMORY_MSG)) { return ErrorType.OUT_OF_MEMORY; } if (message?.toLowerCase().includes('service worker')) { return ErrorType.COOKIES; } return ErrorType.UNKNOWN; } /** * This method defines whether the current environment is compatible * with the NodeRuntimeSandbox. The embedded editor requires significant * CPU and memory resources and can not be ran in all browsers/devices. More * specifically, mobile devices are affected by this, so for the best user * experience (to avoid crashes), we disable the NodeRuntimeSandbox and * recommend using desktop. */ private checkUnsupportedEnvironment(): void { if (isIos) { this.setError({ message: 'Unsupported environment', type: ErrorType.UNSUPPORTED_BROWSER_ENVIRONMENT, }); } } }
{ "commit_id": "cb34e406ba", "end_byte": 2490, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/node-runtime-state.service.ts" }
angular/adev/src/app/editor/code-editor/code-editor.component.html_0_3627
<!-- Code Editor Tabs --> <div class="docs-code-editor-tabs"> <div class="adev-tabs-and-plus"> <mat-tab-group animationDuration="0ms" mat-stretch-tabs="false"> <!-- Hint: we would like to keep only one instance of #codeEditorWrapper, that's why we're not placing this element as content of mat-tab, just to not call another time init method from CodeMirrorEditor service. --> @for (file of files(); track file) { <mat-tab #tab> <ng-template mat-tab-label> @if (tab.isActive && isRenamingFile()) { <form (submit)="renameFile($event, file.filename)" (docsClickOutside)="closeRenameFile()"> <input name="rename-file" class="adev-rename-file-input" #renameFileInput (keydown)="$event.stopPropagation()" /> </form> } @else { {{ file.filename.replace('src/', '') }} } @if (tab.isActive && canRenameFile(file.filename)) { <button class="docs-rename-file" aria-label="rename file" (click)="onRenameButtonClick()" > <docs-icon>edit</docs-icon> </button> } @if (tab.isActive && canDeleteFile(file.filename)) { <button class="docs-delete-file" aria-label="Delete file" (click)="deleteFile(file.filename)" > <docs-icon>delete</docs-icon> </button> } </ng-template> </mat-tab> } @if (isCreatingFile()) { <mat-tab> <ng-template mat-tab-label> <form (submit)="createFile($event)"> <input name="new-file" class="adev-new-file-input" #createFileInput (keydown)="$event.stopPropagation()" /> </form> </ng-template> </mat-tab> } </mat-tab-group> <button class="adev-add-file" (click)="onAddButtonClick()" aria-label="Add a new file"> <docs-icon>add</docs-icon> </button> </div> <button class="adev-editor-download-button" type="button" aria-label="Open current code in editor in an online editor" [cdkMenuTriggerFor]="launcherMenu" > <docs-icon>launch</docs-icon> </button> <!-- launcher dropdown window --> <ng-template #launcherMenu> <div class="adev-editor-dropdown" cdkMenu> <button cdkMenuItem (click)="openCurrentSolutionInIDX()"> <span>Open in IDX </span> <img class="icon" src="assets/images/tutorials/common/idx_logo.svg" height="32"> </button> <button cdkMenuItem (click)="openCurrentCodeInStackBlitz()"> Open in StackBlitz </button> </div> </ng-template> <button class="adev-editor-download-button" type="button" (click)="downloadCurrentCodeEditorState()" aria-label="Download current source code" matTooltip="Download current source code" matTooltipPosition="above" > <docs-icon>download</docs-icon> </button> </div> <!-- Code Editor --> <div #codeEditorWrapper class="adev-code-editor-wrapper"></div> @if (displayErrorsBox()) { <div class="adev-inline-errors-box"> <button type="button" (click)="closeErrorsBox()"> <docs-icon class="docs-icon_high-contrast">close</docs-icon> </button> <ul> @for (error of errors(); track error) { <li>(line: {{ error.lineNumber }}:{{ error.characterPosition }}) {{ error.message }}</li> } </ul> </div> }
{ "commit_id": "cb34e406ba", "end_byte": 3627, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/code-editor.component.html" }
angular/adev/src/app/editor/code-editor/code-mirror-editor.service.spec.ts_0_5694
/*! * @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 {signal} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {BehaviorSubject, Subject} from 'rxjs'; import {EditorState} from '@codemirror/state'; import type {FileSystemTree} from '@webcontainer/api'; import {NodeRuntimeSandbox} from '../node-runtime-sandbox.service'; import {EmbeddedTutorialManager} from '../embedded-tutorial-manager.service'; import {CodeMirrorEditor, EDITOR_CONTENT_CHANGE_DELAY_MILLIES} from './code-mirror-editor.service'; import {TutorialConfig, TutorialMetadata} from '@angular/docs'; class FakeNodeRuntimeSandbox { async writeFile(path: string, content: string) {} createdFile$ = new Subject<void>(); async readFile(path: string) { return Promise.resolve('content'); } } const files = ['1.ts', '2.ts', '3.ts']; // reverse the files list to test openFiles order const filesReverse = [...files].reverse(); export class FakeEmbeddedTutorialManager { commonFilesystemTree = signal<FileSystemTree | null>(null); previousTutorial = signal<string | undefined>(undefined); nextTutorial = signal<string | undefined>(undefined); tutorialId = signal<string>('fake-tutorial'); tutorialFiles = signal<NonNullable<TutorialMetadata['tutorialFiles']>>( // use a reverse map to test openFiles order Object.fromEntries(filesReverse.map((file) => [file, ''])), ); openFiles = signal<TutorialConfig['openFiles']>(files); tutorialFilesystemTree = signal<FileSystemTree>( Object.fromEntries( files.map((file) => [ file, { file: { contents: this.tutorialFiles()![0], }, }, ]), ), ); private _shouldChangeTutorial$ = new BehaviorSubject<boolean>(false); tutorialChanged$ = this._shouldChangeTutorial$.asObservable(); fetchAndSetTutorialFiles(tutorial: string): Promise<void> { return Promise.resolve(); } fetchCommonFiles(): Promise<FileSystemTree> { return Promise.resolve({}); } } describe('CodeMirrorEditor', () => { let service: CodeMirrorEditor; const fakeNodeRuntimeSandbox = new FakeNodeRuntimeSandbox(); const fakeEmbeddedTutorialManager = new FakeEmbeddedTutorialManager(); function dispatchDocumentChange(newContent: string) { for (let i = 0; i < newContent.length; i++) { service['_editorView']?.dispatch({ changes: {from: i, insert: newContent[i]}, selection: {anchor: i, head: 0}, }); } } beforeEach(() => { TestBed.configureTestingModule({ providers: [ CodeMirrorEditor, { provide: NodeRuntimeSandbox, useValue: fakeNodeRuntimeSandbox, }, { provide: EmbeddedTutorialManager, useValue: fakeEmbeddedTutorialManager, }, ], }); service = TestBed.inject(CodeMirrorEditor); const parentElement = document.createElement('div'); service.init(parentElement); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should initialize the editor', () => { expect(service['_editorView']).toBeDefined(); expect(service.files()).toBeDefined(); expect(service.currentFile()).toBeDefined(); const editorState = service['_editorStates'].get(service.currentFile().filename); expect(editorState).toBeInstanceOf(EditorState); }); it('should change the current file', () => { const newFilename = files.at(-1)!; service.changeCurrentFile(newFilename); expect(service.currentFile().filename).toEqual(newFilename); const editorState = service['_editorStates'].get(newFilename); const editorContent = editorState?.doc.toString(); const newFileContent = service.files().find((file) => file.filename === newFilename)?.content; expect(editorContent).toBe(newFileContent); }); it('should update the current file content on change', async () => { const newContent = 'new content'; dispatchDocumentChange(newContent); const updatedEditorState = service['_editorStates'].get(service.currentFile().filename); expect(updatedEditorState?.doc.toString()).toBe(newContent); const fileContentOnFilesSignal = service .files() .find((file) => file.filename === service.currentFile().filename)?.content; expect(fileContentOnFilesSignal).toBe(newContent); expect(service.currentFile().content).toBe(newContent); }); it('should write the changed file content to the sandbox filesystem', () => { jasmine.clock().install(); jasmine.clock().mockDate(); const newContent = 'new content'; const nodeRuntimeSandboxSpy = spyOn(fakeNodeRuntimeSandbox, 'writeFile'); dispatchDocumentChange(newContent); jasmine.clock().tick(EDITOR_CONTENT_CHANGE_DELAY_MILLIES); expect(nodeRuntimeSandboxSpy).toHaveBeenCalledWith(service.currentFile().filename, newContent); jasmine.clock().uninstall(); }); it('should add created file to code editor', async () => { const newFile = 'new-component.component.ts'; await service['addCreatedFileToCodeEditor'](newFile); expect(service['embeddedTutorialManager'].tutorialFiles()[newFile]).toBeDefined(); expect(service.files().find((file) => file.filename === newFile)).toBeDefined(); }); it('should keep openFiles order', () => { service['setProjectFiles'](); for (const [index, openFile] of service['openFiles']().entries()) { expect(openFile.filename).toEqual(service['embeddedTutorialManager'].openFiles()[index]); } }); });
{ "commit_id": "cb34e406ba", "end_byte": 5694, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/code-mirror-editor.service.spec.ts" }
angular/adev/src/app/editor/code-editor/code-editor.component.spec.ts_0_8223
/*! * @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 {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {ChangeDetectorRef, signal} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {MatTabGroupHarness} from '@angular/material/tabs/testing'; import {By} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {BehaviorSubject} from 'rxjs'; import {EmbeddedTutorialManager} from '../embedded-tutorial-manager.service'; import {CodeEditor, REQUIRED_FILES} from './code-editor.component'; import {CodeMirrorEditor} from './code-mirror-editor.service'; import {FakeChangeDetectorRef} from '@angular/docs'; import {TutorialType} from '@angular/docs'; import {MatTooltip} from '@angular/material/tooltip'; import {MatTooltipHarness} from '@angular/material/tooltip/testing'; const files = [ {filename: 'a', content: '', language: {} as any}, {filename: 'b', content: '', language: {} as any}, {filename: 'c', content: '', language: {} as any}, ...Array.from(REQUIRED_FILES).map((filename) => ({ filename, content: '', language: {} as any, })), ]; class FakeCodeMirrorEditor implements Partial<CodeMirrorEditor> { init(element: HTMLElement) {} changeCurrentFile(fileName: string) {} disable() {} files = signal(files); currentFile = signal(this.files()[0]); openFiles = this.files; } const codeMirrorEditorService = new FakeCodeMirrorEditor(); const fakeChangeDetectorRef = new FakeChangeDetectorRef(); describe('CodeEditor', () => { let component: CodeEditor; let fixture: ComponentFixture<CodeEditor>; let loader: HarnessLoader; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [CodeEditor, NoopAnimationsModule, MatTooltip], providers: [ { provide: CodeMirrorEditor, useValue: codeMirrorEditorService, }, { provide: ChangeDetectorRef, useValue: fakeChangeDetectorRef, }, { provide: EmbeddedTutorialManager, useValue: { tutorialChanged$: new BehaviorSubject(true), tutorialId: () => 'tutorial', tutorialFilesystemTree: () => ({'app.component.ts': ''}), commonFilesystemTree: () => ({'app.component.ts': ''}), openFiles: () => ['app.component.ts'], tutorialFiles: () => ({'app.component.ts': ''}), nextTutorial: () => 'next-tutorial', previousTutorial: () => 'previous-tutorial', type: () => TutorialType.EDITOR, title: () => 'Tutorial', }, }, ], }).compileComponents(); fixture = TestBed.createComponent(CodeEditor); loader = TestbedHarnessEnvironment.loader(fixture); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should initialize the code editor service afterViewInit with the code editor wrapper element', () => { const codeMirrorEditorInitSpy = spyOn(codeMirrorEditorService, 'init'); component.ngAfterViewInit(); expect(codeMirrorEditorInitSpy).toHaveBeenCalledWith( component['codeEditorWrapperRef'].nativeElement, ); }); it('should render tabs based on filenames order', async () => { component.ngAfterViewInit(); const matTabGroup = await loader.getHarness(MatTabGroupHarness); const tabs = await matTabGroup.getTabs(); const expectedLabels = files.map((file, index) => { const label = file.filename.replace('src/', ''); if (index === 0) return `${label} editdelete`; return label; }); for (const [index, tab] of tabs.entries()) { const tabLabel = await tab.getLabel(); expect(tabLabel).toBe(expectedLabels[index]); } }); describe('Tabs selection', () => { let codeMirrorEditorChangeCurrentFileSpy: jasmine.Spy<(fileName: string) => void>; beforeEach(() => { codeMirrorEditorChangeCurrentFileSpy = spyOn(codeMirrorEditorService, 'changeCurrentFile'); component.ngAfterViewInit(); }); it('should change file content when clicking on an unselected tab', async () => { const matTabGroup = await loader.getHarness(MatTabGroupHarness); const tabs = await matTabGroup.getTabs(); expect(await tabs[0].isSelected()); await tabs[1].select(); expect(codeMirrorEditorChangeCurrentFileSpy).toHaveBeenCalledWith(files[1].filename); }); it('should not change file content when clicking on a selected tab', async () => { const matTabGroup = await loader.getHarness(MatTabGroupHarness); const tabs = await matTabGroup.getTabs(); expect(await tabs[0].isSelected()); await tabs[0].select(); expect(codeMirrorEditorChangeCurrentFileSpy).not.toHaveBeenCalled(); }); it('should focused on a new tab when adding a new file', async () => { const button = fixture.debugElement.query(By.css('button.adev-add-file')).nativeElement; button.click(); const matTabGroup = await loader.getHarness(MatTabGroupHarness); const tabs = await matTabGroup.getTabs(); expect(await tabs[files.length].isSelected()).toBeTrue(); }); it('should change file content when clicking on unselected tab while creating a new file', async () => { const button = fixture.debugElement.query(By.css('button.adev-add-file')).nativeElement; button.click(); const matTabGroup = await loader.getHarness(MatTabGroupHarness); const tabs = await matTabGroup.getTabs(); await tabs[2].select(); expect(codeMirrorEditorChangeCurrentFileSpy).toHaveBeenCalledWith(files[2].filename); }); it('start creating a new file, select an existing tab, should not change file content when return back on a new file tab', async () => { const button = fixture.debugElement.query(By.css('button.adev-add-file')).nativeElement; button.click(); const matTabGroup = await loader.getHarness(MatTabGroupHarness); const tabs = await matTabGroup.getTabs(); await tabs[1].select(); expect(codeMirrorEditorChangeCurrentFileSpy).toHaveBeenCalledWith(files[1].filename); codeMirrorEditorChangeCurrentFileSpy.calls.reset(); await tabs[files.length].select(); expect(codeMirrorEditorChangeCurrentFileSpy).not.toHaveBeenCalled(); }); }); it('should not allow to delete a required file', async () => { const matTabGroup = await loader.getHarness(MatTabGroupHarness); const tabs = await matTabGroup.getTabs(); const requiredFilesTabIndexes = files .filter((file) => REQUIRED_FILES.has(file.filename)) .map((file) => files.indexOf(file)); for (const tabIndex of requiredFilesTabIndexes) { const tab = tabs[tabIndex]; await tab.select(); expect(fixture.debugElement.query(By.css('[aria-label="Delete file"]'))).toBeNull(); } }); it('should be able to display the tooltip on the download button', async () => { const tooltip = await loader.getHarness( MatTooltipHarness.with({selector: '.adev-editor-download-button'}), ); expect(await tooltip.isOpen()).toBeFalse(); await tooltip.show(); expect(await tooltip.isOpen()).toBeTrue(); }); it('should be able to get the tooltip message on the download button', async () => { const tooltip = await loader.getHarness( MatTooltipHarness.with({selector: '.adev-editor-download-button'}), ); await tooltip.show(); expect(await tooltip.getTooltipText()).toBe('Download current source code'); }); it('should not be able to get the tooltip message on the download button when the tooltip is not shown', async () => { const tooltip = await loader.getHarness( MatTooltipHarness.with({selector: '.adev-editor-download-button'}), ); expect(await tooltip.getTooltipText()).toBe(''); }); });
{ "commit_id": "cb34e406ba", "end_byte": 8223, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/code-editor.component.spec.ts" }
angular/adev/src/app/editor/code-editor/code-editor.component.scss_0_5336
:host { // backgrounds --code-editor-selection-background: color-mix( in srgb, var(--selection-background) 5%, var(--octonary-contrast) ); --code-editor-focused-selection-background: color-mix( in srgb, var(--selection-background) 12%, var(--octonary-contrast) ); // text base colors --code-editor-text-base-color: var(--primary-contrast); // tooltips --code-editor-tooltip-background: color-mix( in srgb, var(--bright-blue), var(--page-background) 90% ); --code-editor-tooltip-color: var(--primary-contrast); --code-editor-tooltip-border: 1px solid color-mix(in srgb, var(--bright-blue), var(--page-background) 70%); --code-editor-tooltip-border-radius: 0.25rem; // autocomplete --code-editor-autocomplete-item-background: var(--senary-contrast); --code-editor-autocomplete-item-color: var(--primary-contrast); // cursor --code-name: var(--primary-contrast); --code-editor-cursor-color: var(--code-name); --code-variable-name: var(--bright-blue); --code-property-name: var(--code-name); --code-definition-keyword: var(--electric-violet); // comments --code-comment: var(--electric-violet); --code-line-comment: var(--symbolic-gray); --code-block-comment: var(--symbolic-brown); --code-doc-comment: var(--code-comment); // keywords --code-keyword: var(--electric-violet); --code-modifier: var(--code-keyword); --code-operator-keyword: var(--code-keyword); --code-control-keyword: var(--code-keyword); --code-module-keyword: var(--code-keyword); // structural --code-brace: var(--vivid-pink); // Misc --code-bool: var(--bright-blue); --code-string: var(--orange-red); --code-regexp: var(--orange-red); --code-tags: var(--bright-blue); --code-component: var(--primary-contrast); --code-type-name: var(--vivid-pink); --code-self: var(--orange-red); position: relative; } .docs-code-editor-tabs { display: flex; background: var(--octonary-contrast); border-block-end: 1px solid var(--senary-contrast); transition: background 0.3s ease, border 0.3s ease; } .adev-tabs-and-plus { display: flex; width: calc(100% - 2.875rem * 2); min-height: 48px; } .adev-add-file, .docs-delete-file, .docs-rename-file { docs-icon { color: var(--gray-400); transition: color 0.3s ease; font-size: 1.2rem; } &:hover { docs-icon { color: var(--primary-contrast); } } } .docs-delete-file, .docs-rename-file { padding-inline-start: 0.1rem; padding-inline-end: 0; margin-block-start: 0.2rem; docs-icon { font-size: 1rem; } } .adev-new-file-input, .adev-rename-file-input { color: var(--primary-contrast); border: none; border-radius: 0; border-block-end: 1px solid var(--senary-contrast); background: transparent; outline: none; transition: color 0.3s ease; &:focus { background: transparent; border-block-end: 1px solid var(--primary-contrast); } } .adev-code-editor-wrapper { // adjust height for terminal tabs // so that scroll bar & content do not render under tabs height: calc(100% - 49px); transition: height 0.3s ease; &-hidden { display: none; } // If error box are displayed, move inline-errors-box // to bottom of the editor and adjust height // so that scroll bar & content do not render under tabs &:has(~ .adev-inline-errors-box) ~ .adev-inline-errors-box { bottom: auto; } &:has(~ .adev-inline-errors-box) { height: min(75% - 49px); } } .adev-inline-errors-box { position: absolute; bottom: 0.5rem; left: 0.5rem; right: 0.5rem; padding: 0.25rem; background-color: color-mix(in srgb, var(--bright-blue), var(--page-background) 90%); border: 1px solid color-mix(in srgb, var(--bright-blue), var(--page-background) 70%); border-radius: 0.25rem; overflow: auto; max-height: 25%; button { position: absolute; top: 0; right: 0; padding: 0.25rem; docs-icon { font-size: 1.25rem; color: var(--quaternary-contrast); transition: color 0.3s ease; } &:hover { docs-icon { color: var(--primary-contrast); } } } ul { padding: 0; margin: 0; margin-inline: 1.25rem; color: var(--tertiary-contrast); overflow: auto; } } .adev-editor-download-button { padding: 0; width: 2.875rem; border-radius: 0 0.19rem 0 0; background: var(--octonary-contrast); border-inline-start: 1px solid var(--senary-contrast); docs-icon { color: var(--gray-400); transition: color 0.3s ease; font-size: 1.3rem; } &:hover { docs-icon { color: var(--primary-contrast); } } } .adev-editor-dropdown { border: 1px solid var(--senary-contrast); border-radius: 0.25rem; padding: 0; transform: translateY(-0.7rem); 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; display: flex; justify-content: space-between; align-items: center; &:hover { background: var(--senary-contrast); color: var(--primary-contrast); } .icon { margin: initial; padding: initial; width: auto; } } }
{ "commit_id": "cb34e406ba", "end_byte": 5336, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/code-editor.component.scss" }
angular/adev/src/app/editor/code-editor/code-mirror-editor.service.ts_0_2355
/*! * @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, Injectable, inject, signal} from '@angular/core'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {Subject, Subscription, debounceTime, filter, map} from 'rxjs'; import {LRLanguage, LanguageSupport} from '@codemirror/language'; import {EditorState, Transaction} from '@codemirror/state'; import {EditorView, placeholder as placeholderExtension} from '@codemirror/view'; import {EmbeddedTutorialManager} from '../embedded-tutorial-manager.service'; import {NodeRuntimeSandbox} from '../node-runtime-sandbox.service'; import {TypingsLoader} from '../typings-loader.service'; import {FileAndContentRecord} from '@angular/docs'; import {CODE_EDITOR_EXTENSIONS} from './constants/code-editor-extensions'; import {LANGUAGES} from './constants/code-editor-languages'; import {getAutocompleteExtension} from './extensions/autocomplete'; import {getDiagnosticsExtension} from './extensions/diagnostics'; import {getTooltipExtension} from './extensions/tooltip'; import {DiagnosticsState} from './services/diagnostics-state.service'; import {TsVfsWorkerActions} from './workers/enums/actions'; import {CodeChangeRequest} from './workers/interfaces/code-change-request'; import {ActionMessage} from './workers/interfaces/message'; import {NodeRuntimeState} from '../node-runtime-state.service'; export interface EditorFile { filename: string; content: string; language: LanguageSupport | LRLanguage; } /** * The delay between the last typed character and the actual file save. * This is used to prevent saving the file on every keystroke. * * Important! this value is intentionally set a bit higher than it needs to be, because sending * changes too frequently to the web container appears to put it in a state where it stops picking * up changes. See issue #691 for context. */ export const EDITOR_CONTENT_CHANGE_DELAY_MILLIES = 500; const INITIAL_STATES = { _editorView: null, files: [], currentFile: { filename: '', content: '', language: LANGUAGES['ts'], }, contentChangeListenerSubscription$: undefined, tutorialChangeListener$: undefined, createdFile$: undefined, };
{ "commit_id": "cb34e406ba", "end_byte": 2355, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/code-mirror-editor.service.ts" }
angular/adev/src/app/editor/code-editor/code-mirror-editor.service.ts_2357_11289
@Injectable({providedIn: 'root'}) export class CodeMirrorEditor { // TODO: handle files created by the user, e.g. after running `ng generate component` files = signal<EditorFile[]>(INITIAL_STATES.files); openFiles = signal<EditorFile[]>(INITIAL_STATES.files); currentFile = signal<EditorFile>(INITIAL_STATES.currentFile); // An instance of web worker used to run virtual TypeScript environment in the browser. // It allows to enrich CodeMirror UX for TypeScript files. private tsVfsWorker: Worker | null = null; // EventManager gives ability to communicate between tsVfsWorker and CodeMirror instance private readonly eventManager$ = new Subject<ActionMessage>(); private readonly nodeRuntimeSandbox = inject(NodeRuntimeSandbox); private readonly nodeRuntimeState = inject(NodeRuntimeState); private readonly embeddedTutorialManager = inject(EmbeddedTutorialManager); private readonly typingsLoader = inject(TypingsLoader); private readonly destroyRef = inject(DestroyRef); private readonly diagnosticsState = inject(DiagnosticsState); private _editorView: EditorView | null = INITIAL_STATES._editorView; private readonly _editorStates = new Map<EditorFile['filename'], EditorState>(); private readonly contentChanged$ = new Subject<string>(); private readonly contentChangeListener$ = this.contentChanged$.asObservable(); private contentChangeListenerSubscription$: Subscription | undefined = INITIAL_STATES.contentChangeListenerSubscription$; private tutorialChangeListener$: Subscription | undefined = INITIAL_STATES.tutorialChangeListener$; private createdFileListener$: Subscription | undefined = INITIAL_STATES.createdFile$; init(parentElement: HTMLElement): void { if (this._editorView) return; if (!this.nodeRuntimeState.error()) { this.initTypescriptVfsWorker(); this.saveLibrariesTypes(); } this._editorView = new EditorView({ parent: parentElement, state: this.createEditorState(), dispatchTransactions: (transactions, view) => { view.update(transactions); for (const transaction of transactions) { if (transaction.docChanged && this.currentFile().filename) { this.contentChanged$.next(transaction.state.doc.toString()); this.changeFileContentsOnRealTime(transaction); } } }, }); this.listenToProjectChanges(); this.contentChangeListenerSubscription$ = this.contentChangeListener$ .pipe(debounceTime(EDITOR_CONTENT_CHANGE_DELAY_MILLIES), takeUntilDestroyed(this.destroyRef)) .subscribe(async (fileContents) => { await this.changeFileContentsScheduled(fileContents); }); this.createdFileListener$ = this.nodeRuntimeSandbox.createdFile$.subscribe( async (createdFile) => { await this.addCreatedFileToCodeEditor(createdFile); }, ); // Create TypeScript virtual filesystem when default files map is created // and files are set this.eventManager$ .pipe( filter( (event) => event.action === TsVfsWorkerActions.INIT_DEFAULT_FILE_SYSTEM_MAP && this.files().length > 0, ), takeUntilDestroyed(this.destroyRef), ) .subscribe(() => { this.createVfsEnv(); }); } disable(): void { this._editorView?.destroy(); this._editorView = null; this._editorView = INITIAL_STATES._editorView; this.files.set(INITIAL_STATES.files); this.currentFile.set(INITIAL_STATES.currentFile); this._editorStates.clear(); this.contentChangeListenerSubscription$?.unsubscribe(); this.contentChangeListenerSubscription$ = INITIAL_STATES.contentChangeListenerSubscription$; this.tutorialChangeListener$?.unsubscribe(); this.tutorialChangeListener$ = INITIAL_STATES.tutorialChangeListener$; this.createdFileListener$?.unsubscribe(); this.createdFileListener$ = INITIAL_STATES.createdFile$; } changeCurrentFile(fileName: string): void { if (!this._editorView) return; const newFile = this.files().find((file) => file.filename === fileName); if (!newFile) throw new Error(`File '${fileName}' not found`); this.currentFile.set(newFile); const editorState = this._editorStates.get(newFile.filename) ?? this.createEditorState(); this._editorView.setState(editorState); } private initTypescriptVfsWorker(): void { if (this.tsVfsWorker) { return; } this.tsVfsWorker = new Worker(new URL('./workers/typescript-vfs.worker', import.meta.url), { type: 'module', }); this.tsVfsWorker.addEventListener('message', ({data}: MessageEvent<ActionMessage>) => { this.eventManager$.next(data); }); } private saveLibrariesTypes(): void { this.typingsLoader.typings$ .pipe( filter((typings) => typings.length > 0), takeUntilDestroyed(this.destroyRef), ) .subscribe((typings) => { this.sendRequestToTsVfs({ action: TsVfsWorkerActions.DEFINE_TYPES_REQUEST, data: typings, }); // Reset current file to trigger diagnostics after preload @angular libraries. this._editorView?.setState(this._editorStates.get(this.currentFile().filename)!); }); } // Method is responsible for sending request to Typescript VFS worker. private sendRequestToTsVfs = <T>(request: ActionMessage<T>) => { if (!this.tsVfsWorker) return; // Send message to tsVfsWorker only when current file is TypeScript file. if (!this.currentFile().filename.endsWith('.ts')) return; this.tsVfsWorker.postMessage(request); // tslint:disable-next-line:semicolon }; private getVfsEnvFileSystemMap(): Map<string, string> { const fileSystemMap = new Map<string, string>(); for (const file of this.files().filter((file) => file.filename.endsWith('.ts'))) { fileSystemMap.set(`/${file.filename}`, file.content); } return fileSystemMap; } /** * Create virtual environment for TypeScript files */ private createVfsEnv(): void { this.sendRequestToTsVfs<Map<string, string>>({ action: TsVfsWorkerActions.CREATE_VFS_ENV_REQUEST, data: this.getVfsEnvFileSystemMap(), }); } /** * Update virtual TypeScript file system with current code editor files */ private updateVfsEnv(): void { this.sendRequestToTsVfs<Map<string, string>>({ action: TsVfsWorkerActions.UPDATE_VFS_ENV_REQUEST, data: this.getVfsEnvFileSystemMap(), }); } private listenToProjectChanges() { this.tutorialChangeListener$ = this.embeddedTutorialManager.tutorialChanged$ .pipe( map(() => this.embeddedTutorialManager.tutorialFiles()), filter((tutorialFiles) => Object.keys(tutorialFiles).length > 0), takeUntilDestroyed(this.destroyRef), ) .subscribe(() => { this.changeProject(); }); } private changeProject() { this.setProjectFiles(); this._editorStates.clear(); this.changeCurrentFile(this.currentFile().filename); this.updateVfsEnv(); } private setProjectFiles(): void { const tutorialFiles = this.getTutorialFiles(this.embeddedTutorialManager.tutorialFiles()); const openFiles: EditorFile[] = []; // iterate openFiles to keep files order for (const openFileName of this.embeddedTutorialManager.openFiles()) { const openFile = tutorialFiles.find(({filename}) => filename === openFileName); if (openFile) { openFiles.push(openFile); } } this.files.set(tutorialFiles); this.openFiles.set(openFiles); this.changeCurrentFile(openFiles[0].filename); } /** * Update the code editor files when files are created */ private async addCreatedFileToCodeEditor(createdFile: string): Promise<void> { const fileContents = await this.nodeRuntimeSandbox.readFile(createdFile); this.embeddedTutorialManager.tutorialFiles.update((files) => ({ ...files, [createdFile]: fileContents, })); this.embeddedTutorialManager.openFiles.update((files) => [...files, createdFile]); this.setProjectFiles(); this.updateVfsEnv(); this.saveLibrariesTypes(); } async createFile(filename: string) { // if file already exists, use its content const content = await this.nodeRuntimeSandbox.readFile(filename).catch((error) => { // empty content if file does not exist if (error.message.includes('ENOENT')) return ''; else throw error; }); await this.nodeRuntimeSandbox.writeFile(filename, content); this.embeddedTutorialManager.tutorialFiles.update((files) => ({ ...files, [filename]: content, })); this.embeddedTutorialManager.openFiles.update((files) => [...files, filename]); this.setProjectFiles(); this.updateVfsEnv(); this.saveLibrariesTypes(); this.changeCurrentFile(filename); }
{ "commit_id": "cb34e406ba", "end_byte": 11289, "start_byte": 2357, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/code-mirror-editor.service.ts" }
angular/adev/src/app/editor/code-editor/code-mirror-editor.service.ts_11293_15490
async renameFile(oldPath: string, newPath: string) { const content = await this.nodeRuntimeSandbox.readFile(oldPath).catch((error) => { // empty content if file does not exist if (error.message.includes('ENOENT')) return ''; else throw error; }); await this.nodeRuntimeSandbox.renameFile(oldPath, newPath).catch((error) => { throw error; }); this.embeddedTutorialManager.tutorialFiles.update((files) => { delete files[oldPath]; files[newPath] = content; return files; }); this.embeddedTutorialManager.openFiles.update((files) => [ ...files.filter((file) => file !== oldPath), newPath, ]); this.setProjectFiles(); this.updateVfsEnv(); this.saveLibrariesTypes(); this.changeCurrentFile(newPath); } async deleteFile(deletedFile: string): Promise<void> { await this.nodeRuntimeSandbox.deleteFile(deletedFile); this.embeddedTutorialManager.tutorialFiles.update((files) => { delete files[deletedFile]; return files; }); this.embeddedTutorialManager.openFiles.update((files) => files.filter((file) => file !== deletedFile), ); this.setProjectFiles(); this.updateVfsEnv(); this.saveLibrariesTypes(); } private createEditorState(): EditorState { const newEditorState = EditorState.create({ doc: this.currentFile().content, extensions: [ ...CODE_EDITOR_EXTENSIONS, this.currentFile().language, placeholderExtension('Type your code here...'), ...this.getLanguageExtensions(), ], }); this._editorStates.set(this.currentFile().filename, newEditorState); return newEditorState; } private getLanguageExtensions() { if (this.currentFile().filename.endsWith('.ts')) { return [ getAutocompleteExtension(this.eventManager$, this.currentFile, this.sendRequestToTsVfs), getDiagnosticsExtension( this.eventManager$, this.currentFile, this.sendRequestToTsVfs, this.diagnosticsState, ), getTooltipExtension(this.eventManager$, this.currentFile, this.sendRequestToTsVfs), ]; } return []; } /** * Write the new file contents to the sandbox filesystem */ private async changeFileContentsScheduled(newContent: string): Promise<void> { try { await this.nodeRuntimeSandbox.writeFile(this.currentFile().filename, newContent); } catch (err) { // Note: `writeFile` throws if the sandbox is not initialized yet, which can happen if // the user starts typing right after the page loads. // Here the error is ignored as it is expected. } } /** * Change file contents on files signals and update the editor state */ private changeFileContentsOnRealTime(transaction: Transaction): void { this._editorStates.set(this.currentFile().filename, transaction.state); const newContent = transaction.state.doc.toString(); this.currentFile.update((currentFile) => ({...currentFile, content: newContent})); this.files.update((files) => files.map((file) => file.filename === this.currentFile().filename ? {...file, content: newContent} : file, ), ); // send current file content to Ts Vfs worker to run diagnostics on current file state this.sendRequestToTsVfs<CodeChangeRequest>({ action: TsVfsWorkerActions.CODE_CHANGED, data: { file: this.currentFile().filename, code: newContent, }, }); } private getTutorialFiles(files: FileAndContentRecord): EditorFile[] { const languagesExtensions = Object.keys(LANGUAGES); const tutorialFiles = Object.entries(files) .filter( (fileAndContent): fileAndContent is [string, string] => typeof fileAndContent[1] === 'string', ) .map(([filename, content]) => { const extension = languagesExtensions.find((extension) => filename.endsWith(extension)); const language = extension ? LANGUAGES[extension] : LANGUAGES['ts']; return { filename, content, language, }; }); return tutorialFiles; } }
{ "commit_id": "cb34e406ba", "end_byte": 15490, "start_byte": 11293, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/code-mirror-editor.service.ts" }
angular/adev/src/app/editor/code-editor/code-editor.component.ts_0_7745
/*! * @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 {Location} from '@angular/common'; import { AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, OnDestroy, ViewChild, inject, signal, } from '@angular/core'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {MatTabGroup, MatTabsModule} from '@angular/material/tabs'; import {Title} from '@angular/platform-browser'; import {debounceTime, map} from 'rxjs'; import {TerminalType} from '../terminal/terminal-handler.service'; import {EmbeddedTutorialManager} from '../embedded-tutorial-manager.service'; import {CodeMirrorEditor} from './code-mirror-editor.service'; import {DiagnosticWithLocation, DiagnosticsState} from './services/diagnostics-state.service'; import {DownloadManager} from '../download-manager.service'; import {StackBlitzOpener} from '../stackblitz-opener.service'; import {ClickOutside, IconComponent} from '@angular/docs'; import {CdkMenu, CdkMenuItem, CdkMenuTrigger} from '@angular/cdk/menu'; import {IDXLauncher} from '../idx-launcher.service'; import {MatTooltip} from '@angular/material/tooltip'; export const REQUIRED_FILES = new Set([ 'src/main.ts', 'src/index.html', 'src/app/app.component.ts', ]); const ANGULAR_DEV = 'https://angular.dev'; @Component({ selector: 'docs-tutorial-code-editor', standalone: true, templateUrl: './code-editor.component.html', styleUrls: ['./code-editor.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, imports: [ MatTabsModule, MatTooltip, IconComponent, ClickOutside, CdkMenu, CdkMenuItem, CdkMenuTrigger, ], }) export class CodeEditor implements AfterViewInit, OnDestroy { @ViewChild('codeEditorWrapper') private codeEditorWrapperRef!: ElementRef<HTMLDivElement>; @ViewChild(MatTabGroup) private matTabGroup!: MatTabGroup; private createFileInputRef?: ElementRef<HTMLInputElement>; @ViewChild('createFileInput') protected set setFileInputRef( element: ElementRef<HTMLInputElement>, ) { if (element) { element.nativeElement.focus(); this.createFileInputRef = element; } } private renameFileInputRef?: ElementRef<HTMLInputElement>; @ViewChild('renameFileInput') protected set setRenameFileInputRef( element: ElementRef<HTMLInputElement>, ) { if (element) { element.nativeElement.focus(); this.renameFileInputRef = element; } } private readonly destroyRef = inject(DestroyRef); private readonly codeMirrorEditor = inject(CodeMirrorEditor); private readonly diagnosticsState = inject(DiagnosticsState); private readonly downloadManager = inject(DownloadManager); private readonly stackblitzOpener = inject(StackBlitzOpener); private readonly idxLauncher = inject(IDXLauncher); private readonly title = inject(Title); private readonly location = inject(Location); private readonly embeddedTutorialManager = inject(EmbeddedTutorialManager); private readonly errors$ = this.diagnosticsState.diagnostics$.pipe( // Display errors one second after code update debounceTime(1000), map((diagnosticsItem) => diagnosticsItem .filter((item) => item.severity === 'error') .sort((a, b) => a.lineNumber != b.lineNumber ? a.lineNumber - b.lineNumber : a.characterPosition - b.characterPosition, ), ), takeUntilDestroyed(this.destroyRef), ); readonly TerminalType = TerminalType; readonly displayErrorsBox = signal<boolean>(false); readonly errors = signal<DiagnosticWithLocation[]>([]); readonly files = this.codeMirrorEditor.openFiles; readonly isCreatingFile = signal<boolean>(false); readonly isRenamingFile = signal<boolean>(false); ngAfterViewInit() { this.codeMirrorEditor.init(this.codeEditorWrapperRef.nativeElement); this.listenToDiagnosticsChange(); this.listenToTabChange(); this.setSelectedTabOnTutorialChange(); } ngOnDestroy(): void { this.codeMirrorEditor.disable(); } openCurrentSolutionInIDX(): void { this.idxLauncher.openCurrentSolutionInIDX(); } async openCurrentCodeInStackBlitz(): Promise<void> { const title = this.title.getTitle(); const path = this.location.path(); const editorUrl = `${ANGULAR_DEV}${path}`; const description = `Angular.dev example generated from [${editorUrl}](${editorUrl})`; await this.stackblitzOpener.openCurrentSolutionInStackBlitz({title, description}); } async downloadCurrentCodeEditorState(): Promise<void> { const name = this.embeddedTutorialManager.tutorialId(); await this.downloadManager.downloadCurrentStateOfTheSolution(name); } closeErrorsBox(): void { this.displayErrorsBox.set(false); } closeRenameFile(): void { this.isRenamingFile.set(false); } canRenameFile = (filename: string) => this.canDeleteFile(filename); canDeleteFile(filename: string) { return !REQUIRED_FILES.has(filename); } async deleteFile(filename: string) { await this.codeMirrorEditor.deleteFile(filename); this.matTabGroup.selectedIndex = 0; } onAddButtonClick() { this.isCreatingFile.set(true); this.matTabGroup.selectedIndex = this.files().length; } onRenameButtonClick() { this.isRenamingFile.set(true); } async renameFile(event: SubmitEvent, oldPath: string) { if (!this.renameFileInputRef) return; event.preventDefault(); const renameFileInputValue = this.renameFileInputRef.nativeElement.value; if (renameFileInputValue) { if (renameFileInputValue.includes('..')) { alert('File name can not contain ".."'); return; } // src is hidden from users, here we manually add it to the new filename const newFile = 'src/' + renameFileInputValue; if (this.files().find(({filename}) => filename.includes(newFile))) { alert('File name already exists'); return; } await this.codeMirrorEditor.renameFile(oldPath, newFile); } this.isRenamingFile.set(false); } async createFile(event: SubmitEvent) { if (!this.createFileInputRef) return; event.preventDefault(); const newFileInputValue = this.createFileInputRef.nativeElement.value; if (newFileInputValue) { if (newFileInputValue.includes('..')) { alert('File name can not contain ".."'); return; } // src is hidden from users, here we manually add it to the new filename const newFile = 'src/' + newFileInputValue; if (this.files().find(({filename}) => filename.includes(newFile))) { alert('File already exists'); return; } await this.codeMirrorEditor.createFile(newFile); } this.isCreatingFile.set(false); } private listenToDiagnosticsChange(): void { this.errors$.subscribe((diagnostics) => { this.errors.set(diagnostics); this.displayErrorsBox.set(diagnostics.length > 0); }); } private setSelectedTabOnTutorialChange() { this.embeddedTutorialManager.tutorialChanged$ .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe(() => { // selected file on project change is always the first this.matTabGroup.selectedIndex = 0; }); } private listenToTabChange() { this.matTabGroup.selectedIndexChange .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((index) => { const selectedFile = this.files()[index]; if (selectedFile) { this.codeMirrorEditor.changeCurrentFile(selectedFile.filename); } }); } }
{ "commit_id": "cb34e406ba", "end_byte": 7745, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/code-editor.component.ts" }
angular/adev/src/app/editor/code-editor/constants/syntax-styles.ts_0_336
/*! * @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 {TagStyle} from '@codemirror/language'; import {tags} from '@lezer/highlight'; export const SYNTAX_STYLES: TagStyle[] =
{ "commit_id": "cb34e406ba", "end_byte": 336, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/constants/syntax-styles.ts" }
angular/adev/src/app/editor/code-editor/constants/syntax-styles.ts_337_7377
[ /** A comment. */ {tag: tags.comment, color: 'var(--code-comment)'}, /** A language keyword. */ {tag: tags.keyword, color: 'var(--code-keyword)'}, /** A string literal */ {tag: tags.string, color: 'var(--code-string)'}, /** A number literal. */ {tag: tags.number, color: 'var(--code-number)'}, /** A tag name, subtag of typeName. */ {tag: tags.tagName, color: 'var(--code-tags)'}, /** The name of a class. */ {tag: tags.className, color: 'var(--code-component)'}, /** A line comment. */ {tag: tags.lineComment, color: 'var(--code-line-comment)'}, /** A block comment. */ {tag: tags.blockComment, color: 'var(--code-block-comment)'}, /** A documentation comment. */ {tag: tags.docComment, color: 'var(--code-doc-comment)'}, /** Any kind of identifier. */ {tag: tags.name, color: 'var(--code-name)'}, /** The name of a variable. */ {tag: tags.variableName, color: 'var(--code-variable-name)'}, /** A type name */ {tag: tags.typeName, color: 'var(--code-type-name)'}, /** A property or field name. */ {tag: tags.propertyName, color: 'var(--code-property-name)'}, /** An attribute name, subtag of propertyName. */ {tag: tags.attributeName, color: 'var(--code-attribute-name)'}, /** A label name. */ {tag: tags.labelName, color: 'var(--code-label-name)'}, /** A namespace name. */ {tag: tags.namespace, color: 'var(--code-namespace)'}, /** The name of a macro. */ {tag: tags.macroName, color: 'var(--code-macro-name)'}, /** A literal value. */ {tag: tags.literal, color: 'var(--code-literal)'}, /** A documentation string. */ {tag: tags.docString, color: 'var(--code-doc-string)'}, /** A character literal (subtag of string). */ {tag: tags.character, color: 'var(--code-character)'}, /** An attribute value (subtag of string). */ {tag: tags.attributeValue, color: 'var(--code-attribute-value)'}, /** An integer number literal. */ {tag: tags.integer, color: 'var(--code-integer)'}, /** A floating-point number literal. */ {tag: tags.float, color: 'var(--code-float)'}, /** A boolean literal. */ {tag: tags.bool, color: 'var(--code-bool)'}, /** Regular expression literal. */ {tag: tags.regexp, color: 'var(--code-regexp)'}, /** An escape literal, for example a backslash escape in a string. */ {tag: tags.escape, color: 'var(--code-escape)'}, /** A color literal . */ {tag: tags.color, color: 'var(--code-color)'}, /** A URL literal. */ {tag: tags.url, color: 'var(--code-url)'}, /** The keyword for the self or this object. */ {tag: tags.self, color: 'var(--code-self)'}, /** The keyword for null. */ {tag: tags.null, color: 'var(--code-null)'}, /** A keyword denoting some atomic value. */ {tag: tags.atom, color: 'var(--code-atom)'}, /** A keyword that represents a unit. */ {tag: tags.unit, color: 'var(--code-unit)'}, /** A modifier keyword. */ {tag: tags.modifier, color: 'var(--code-modifier)'}, /** A keyword that acts as an operator. */ {tag: tags.operatorKeyword, color: 'var(--code-operator-keyword)'}, /** A control-flow related keyword. */ {tag: tags.controlKeyword, color: 'var(--code-control-keyword)'}, /** A keyword that defines something. */ {tag: tags.definitionKeyword, color: 'var(--code-definition-keyword)'}, /** A keyword related to defining or interfacing with modules. */ {tag: tags.moduleKeyword, color: 'var(--code-module-keyword)'}, /** An operator. */ {tag: tags.operator, color: 'var(--code-operator)'}, /** An operator that dereferences something. */ {tag: tags.derefOperator, color: 'var(--code-deref-operator)'}, /** Arithmetic-related operator. */ {tag: tags.arithmeticOperator, color: 'var(--code-arithmetic-operator)'}, /** Logical operator. */ {tag: tags.logicOperator, color: 'var(--code-logic-operator)'}, /** Bit operator. */ {tag: tags.bitwiseOperator, color: 'var(--code-bitwise-operator)'}, /** Comparison operator. */ {tag: tags.compareOperator, color: 'var(--code-compare-operator)'}, /** Operator that updates its operand. */ {tag: tags.updateOperator, color: 'var(--code-update-operator)'}, /** Operator that defines something. */ {tag: tags.definitionOperator, color: 'var(--code-definition-operator)'}, /** Type-related operator. */ {tag: tags.typeOperator, color: 'var(--code-type-operator)'}, /** Control-flow operator. */ {tag: tags.controlOperator, color: 'var(--code-control-operator)'}, /** Program or markup punctuation. */ {tag: tags.punctuation, color: 'var(--code-punctuation)'}, /** Punctuation that separates things. */ {tag: tags.separator, color: 'var(--code-separator)'}, /** Bracket-style punctuation. */ {tag: tags.bracket, color: 'var(--code-bracket)'}, /** Angle brackets (usually `<` and `>` tokens). */ {tag: tags.angleBracket, color: 'var(--code-angle-bracket)'}, /** Square brackets (usually `[` and `]` tokens). */ {tag: tags.squareBracket, color: 'var(--code-square-bracket)'}, /** Parentheses (usually `(` and `)` tokens). Subtag of bracket. */ {tag: tags.paren, color: 'var(--code-paren)'}, /** Braces (usually `{` and `}` tokens). Subtag of bracket. */ {tag: tags.brace, color: 'var(--code-brace)'}, /** Content, for example plain text in XML or markup documents. */ {tag: tags.content, color: 'var(--code-content)'}, /** Content that represents a heading. */ {tag: tags.heading, color: 'var(--code-heading)'}, /** A level 1 heading. */ {tag: tags.heading1, color: 'var(--code-heading1)'}, /** A level 2 heading. */ {tag: tags.heading2, color: 'var(--code-heading2)'}, /** A level 3 heading. */ {tag: tags.heading3, color: 'var(--code-heading3)'}, /** A level 4 heading. */ {tag: tags.heading4, color: 'var(--code-heading4)'}, /** A level 5 heading. */ {tag: tags.heading5, color: 'var(--code-heading5)'}, /** A level 6 heading. */ {tag: tags.heading6, color: 'var(--code-heading6)'}, /** A prose separator (such as a horizontal rule). */ {tag: tags.contentSeparator, color: 'var(--code-content-separator)'}, /** Content that represents a list. */ {tag: tags.list, color: 'var(--code-list)'}, /** Content that represents a quote. */ {tag: tags.quote, color: 'var(--code-quote)'}, /** Content that is emphasized. */ {tag: tags.emphasis, color: 'var(--code-emphasis)'}, /** Content that is styled strong. */ {tag: tags.strong, color: 'var(--code-strong)'}, /** Content that is part of a link. */ {tag: tags.link, color: 'var(--code-link)'}, /** Content that is styled as code or monospace. */ {tag: tags.monospace, color: 'var(--code-monospace)'}, /** Content that has a strike-through style. */ {tag: tags.strikethrough, color: 'var(--code-strikethrough)'}, /** Inserted text in a change-tracking format. */ {tag: tags.inserted, color: 'var(--code-inserted)'}, /** Deleted text. */ {tag: tags.deleted, color: 'var(--code-deleted)'}, /** Changed text. */ {tag: tags.changed, color: 'var(--code-changed)'}
{ "commit_id": "cb34e406ba", "end_byte": 7377, "start_byte": 337, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/constants/syntax-styles.ts" }
angular/adev/src/app/editor/code-editor/constants/syntax-styles.ts_7377_7986
, /** An invalid or unsyntactic element. */ {tag: tags.invalid, color: 'var(--code-invalid)'}, /** Metadata or meta-instruction. */ {tag: tags.meta, color: 'var(--code-meta)'}, /** Metadata that applies to the entire document. */ {tag: tags.documentMeta, color: 'var(--code-document-meta)'}, /** Metadata that annotates or adds attributes to a given syntactic element. */ {tag: tags.annotation, color: 'var(--code-annotation)'}, /** Processing instruction or preprocessor directive. Subtag of meta. */ {tag: tags.processingInstruction, color: 'var(--code-processing-instruction)'}, ];
{ "commit_id": "cb34e406ba", "end_byte": 7986, "start_byte": 7377, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/constants/syntax-styles.ts" }
angular/adev/src/app/editor/code-editor/constants/code-editor-languages.ts_0_871
/*! * @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 {html} from '@codemirror/lang-html'; import {angular} from '@codemirror/lang-angular'; import {css} from '@codemirror/lang-css'; import {sass} from '@codemirror/lang-sass'; import {javascript} from '@codemirror/lang-javascript'; import {angularComponent} from '../utils/component-ts-syntax'; import {LRLanguage, LanguageSupport} from '@codemirror/language'; export const LANGUAGES: Record<string, LanguageSupport | LRLanguage> = { 'component.ts': angularComponent(), 'main.ts': angularComponent(), html: angular({base: html()}), svg: html(), ts: javascript({typescript: true}), css: css(), sass: sass(), scss: sass(), json: javascript(), };
{ "commit_id": "cb34e406ba", "end_byte": 871, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/constants/code-editor-languages.ts" }
angular/adev/src/app/editor/code-editor/constants/code-editor-extensions.ts_0_2219
/*! * @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 {EditorState, Extension} from '@codemirror/state'; import { lineNumbers, highlightActiveLineGutter, highlightSpecialChars, drawSelection, dropCursor, rectangularSelection, crosshairCursor, highlightActiveLine, keymap, EditorView, } from '@codemirror/view'; export {EditorView} from '@codemirror/view'; import { foldGutter, indentOnInput, syntaxHighlighting, defaultHighlightStyle, bracketMatching, foldKeymap, HighlightStyle, } from '@codemirror/language'; import {history, defaultKeymap, historyKeymap, indentWithTab} from '@codemirror/commands'; import {highlightSelectionMatches, searchKeymap} from '@codemirror/search'; import { closeBrackets, autocompletion, closeBracketsKeymap, completionKeymap, startCompletion, } from '@codemirror/autocomplete'; import {lintKeymap} from '@codemirror/lint'; import {SYNTAX_STYLES} from './syntax-styles'; import {CODE_EDITOR_THEME_STYLES} from './theme-styles'; export const CODE_EDITOR_EXTENSIONS: Extension[] = [ lineNumbers(), highlightActiveLineGutter(), highlightSpecialChars(), history(), foldGutter(), drawSelection(), dropCursor(), EditorState.allowMultipleSelections.of(true), indentOnInput(), bracketMatching(), closeBrackets(), autocompletion(), rectangularSelection(), crosshairCursor(), highlightActiveLine(), highlightSelectionMatches(), syntaxHighlighting(defaultHighlightStyle, {fallback: true}), syntaxHighlighting(HighlightStyle.define(SYNTAX_STYLES)), EditorView.lineWrapping, EditorView.theme( CODE_EDITOR_THEME_STYLES, // TODO: get from global theme, reconfigure on change: https://discuss.codemirror.net/t/dynamic-light-mode-dark-mode-how/4709 {dark: true}, ), keymap.of([ ...closeBracketsKeymap, ...defaultKeymap, ...searchKeymap, ...historyKeymap, ...foldKeymap, ...completionKeymap, ...lintKeymap, indentWithTab, { key: 'Ctrl-.', run: startCompletion, mac: 'Mod-.', }, ]), ];
{ "commit_id": "cb34e406ba", "end_byte": 2219, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/constants/code-editor-extensions.ts" }
angular/adev/src/app/editor/code-editor/constants/theme-styles.ts_0_2375
/*! * @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 const CODE_EDITOR_THEME_STYLES = { '&': { position: 'relative', width: '100%', height: '100%', 'background-color': 'var(--code-editor-background)', color: 'var(--code-editor-text-base-color)', }, '.cm-gutters': { border: 'none', }, '.cm-gutter': { 'background-color': 'var(--code-editor-background)', color: 'var(--code-editor-code-base-color)', }, '.cm-line.cm-activeLine': { 'background-color': 'var(--code-editor-active-line-background)', }, '.cm-activeLineGutter': { 'background-color': 'var(--code-editor-active-line-background)', }, '&.cm-focused .cm-selectionBackground': { 'background-color': 'var(--code-editor-focused-selection-background) !important', }, '.cm-selectionBackground': { 'background-color': 'var(--code-editor-selection-background) !important', }, '.cm-cursor': { 'border-color': 'var(--code-editor-cursor-color)', }, '.cm-tooltip': { color: 'var(--code-editor-tooltip-color)', border: 'var(--code-editor-tooltip-border)', 'border-radius': 'var(--code-editor-tooltip-border-radius)', background: 'var(--code-editor-tooltip-background)', 'overflow-y': 'scroll', 'max-height': '70%', 'max-width': '100%', 'margin-right': '10px', }, '.cm-tooltip.cm-tooltip-autocomplete > ul': { background: 'var(--code-editor-autocomplete-background)', }, '.cm-tooltip .keyword': { color: 'var(--code-module-keyword)', }, '.cm-tooltip .aliasName': { color: 'var(--code-variable-name)', }, '.cm-tooltip .localName': { color: 'var(--code-variable-name)', }, '.cm-tooltip-autocomplete ul li[aria-selected]': { background: 'var(--code-editor-autocomplete-item-background)', color: 'var(--code-editor-autocomplete-item-color)', }, '.cm-tooltip-lint': { background: 'var(--code-editor-lint-tooltip-background)', color: 'var(--code-editor-lint-tooltip-color)', }, '.cm-panels': { background: 'var(--code-editor-panels-background)', color: 'var(--code-editor-panels-color)', }, '.cm-foldPlaceholder': { background: 'var(--code-editor-fold-placeholder-background)', }, };
{ "commit_id": "cb34e406ba", "end_byte": 2375, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/constants/theme-styles.ts" }
angular/adev/src/app/editor/code-editor/utils/component-ts-syntax.ts_0_3716
/*! * @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 {parser as jsParser} from '@lezer/javascript'; import {parseMixed, SyntaxNode, SyntaxNodeRef, Input, NestedParse} from '@lezer/common'; import {LRLanguage} from '@codemirror/language'; import {angularLanguage} from '@codemirror/lang-angular'; import {sassLanguage} from '@codemirror/lang-sass'; export function angularComponent() { return LRLanguage.define({ parser: jsParser.configure({ dialect: 'ts', wrap: parseMixed((node, input) => getAngularComponentMixedParser(node, input)), }), }); } /** * Use the Angular template parser for inline templates in Angular components */ function getAngularComponentMixedParser(node: SyntaxNodeRef, input: Input): NestedParse | null { const nodeIsString = ['TemplateString', 'String'].includes(node.name); if (!nodeIsString) return null; if (isComponentTemplate(node, input)) return {parser: angularLanguage.parser}; if (isComponentStyles(node, input)) return {parser: sassLanguage.parser}; return null; } function isComponentTemplate(node: SyntaxNodeRef, input: Input): boolean { if (!node.node.parent) return false; const expectedParents = [ 'Property', // `template:` in `@Component({ template: "..." })` 'ObjectExpression', // `{` in `@Component({ template: "..." })` 'ArgList', // the decorator arguments in `@Component({ template: "..." })` 'CallExpression', // `()` in `@Component({ template: "..." })` 'Decorator', // `@Component` in `@Component({ template: "..." })` ]; const {node: parentNode} = node.node.parent; if (nodeHasExpectedParents(parentNode, expectedParents)) { const templateCandidateProperty = input .read(parentNode.node.from, parentNode.node.to) .toString() .trim(); // is a Component's decorator `template` if (templateCandidateProperty.startsWith('template:')) return true; } return false; } function isComponentStyles(node: SyntaxNodeRef, input: Input): boolean { if (!node.node.parent || !node.node.parent?.node.parent) return false; const expectedParents = [ 'ArrayExpression', // `[` in `@Component({ styles: [``] })` 'Property', // `styles:` in `@Component({ styles: [``] })` 'ObjectExpression', // `{` in `@Component({ styles: [``] })` 'ArgList', // the decorator arguments in `@Component({ styles: [``] })` 'CallExpression', // `()` in `@Component({ styles: [``] })` 'Decorator', // `@Component` in `@Component({ styles: [``] })` ]; const {node: parentNode} = node.node.parent; if (nodeHasExpectedParents(parentNode, expectedParents)) { const propertyNode = node.node.parent.node.parent; const stylesCandidateProperty = input .read(propertyNode.from, propertyNode.to) .toString() .trim(); // is a Component's decorator `styles` if (stylesCandidateProperty.startsWith('styles:')) { return true; } } return false; } /** * Utility function to verify if the given SyntaxNode has the expected parents */ function nodeHasExpectedParents( node: SyntaxNode, orderedParentsNames: Array<SyntaxNode['name']>, ): boolean { const parentNameToVerify = orderedParentsNames[0]; if (parentNameToVerify !== node.name) return false; // parent was found, remove from the array orderedParentsNames.shift(); // all expected parents were found, node has expected parents if (orderedParentsNames.length === 0) return true; if (!node.parent) return false; return nodeHasExpectedParents(node.parent.node, orderedParentsNames); }
{ "commit_id": "cb34e406ba", "end_byte": 3716, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/utils/component-ts-syntax.ts" }
angular/adev/src/app/editor/code-editor/extensions/autocomplete.ts_0_3715
/*! * @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 {Signal} from '@angular/core'; import { Completion, CompletionContext, CompletionResult, autocompletion, closeCompletion, completeFromList, insertCompletionText, } from '@codemirror/autocomplete'; import {EditorView} from '@codemirror/view'; import {Subject, filter, take} from 'rxjs'; import {EditorFile} from '../code-mirror-editor.service'; import {TsVfsWorkerActions} from '../workers/enums/actions'; import {AutocompleteRequest} from '../workers/interfaces/autocomplete-request'; import {AutocompleteItem, AutocompleteResponse} from '../workers/interfaces/autocomplete-response'; import {ActionMessage} from '../workers/interfaces/message'; import {TransactionSpec} from '@codemirror/state'; // Factory method for autocomplete extension. export const getAutocompleteExtension = ( emitter: Subject<ActionMessage>, currentFile: Signal<EditorFile>, sendRequestToTsVfs: (request: ActionMessage<AutocompleteRequest>) => void, ) => { return autocompletion({ activateOnTyping: true, override: [ async (context: CompletionContext): Promise<CompletionResult | null> => { try { const contextPositions = context.state.wordAt(context.pos); sendRequestToTsVfs({ action: TsVfsWorkerActions.AUTOCOMPLETE_REQUEST, data: { file: currentFile().filename, position: context.pos, from: contextPositions?.from, to: contextPositions?.to, content: context.state.doc.toString(), }, }); const completions = await new Promise<AutocompleteResponse | undefined>((resolve) => { emitter .pipe( filter((event) => event.action === TsVfsWorkerActions.AUTOCOMPLETE_RESPONSE), take(1), ) .subscribe((message: ActionMessage<AutocompleteResponse>) => { resolve(message.data); }); }); if (!completions) { return null; } const completionSource = completeFromList( completions.map((completionItem) => { const suggestions: Completion = { type: completionItem.kind, label: completionItem.name, boost: 1 / Number(completionItem.sortText), detail: completionItem?.codeActions?.[0]?.description, apply: (view, completion, from, to) => applyWithCodeAction(view, {...completion, ...completionItem}, from, to), }; return suggestions; }), ); return completionSource(context); } catch (e) { return null; } }, ], }); }; const applyWithCodeAction = ( view: EditorView, completion: Completion & AutocompleteItem, from: number, to: number, ) => { const transactionSpecs: TransactionSpec[] = [ insertCompletionText(view.state, completion.label, from, to), ]; if (completion.codeActions?.length) { const {span, newText} = completion.codeActions[0].changes[0].textChanges[0]; transactionSpecs.push( insertCompletionText(view.state, newText, span.start, span.start + span.length), ); } view.dispatch( ...transactionSpecs, // avoid moving cursor to the autocompleted text {selection: view.state.selection}, ); // Manually close the autocomplete picker after applying the completion closeCompletion(view); };
{ "commit_id": "cb34e406ba", "end_byte": 3715, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/extensions/autocomplete.ts" }
angular/adev/src/app/editor/code-editor/extensions/tooltip.ts_0_4329
/*! * @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 {Signal} from '@angular/core'; import {Tooltip, hoverTooltip} from '@codemirror/view'; import {marked} from 'marked'; import {Subject, filter, take} from 'rxjs'; import type {JSDocTagInfo, SymbolDisplayPart} from 'typescript'; import {EditorFile} from '../code-mirror-editor.service'; import {TsVfsWorkerActions} from '../workers/enums/actions'; import {DisplayTooltipRequest} from '../workers/interfaces/display-tooltip-request'; import {DisplayTooltipResponse} from '../workers/interfaces/display-tooltip-response'; import {ActionMessage} from '../workers/interfaces/message'; export const getTooltipExtension = ( emitter: Subject<ActionMessage<DisplayTooltipResponse>>, currentFile: Signal<EditorFile>, sendRequestToTsVfs: (request: ActionMessage<DisplayTooltipRequest>) => void, ) => { return hoverTooltip( async (_, pos: number): Promise<Tooltip | null> => { sendRequestToTsVfs({ action: TsVfsWorkerActions.DISPLAY_TOOLTIP_REQUEST, data: { file: currentFile().filename, position: pos, }, }); const response = await new Promise<DisplayTooltipResponse>((resolve) => { emitter .pipe( filter((event) => event.action === TsVfsWorkerActions.DISPLAY_TOOLTIP_RESPONSE), take(1), ) .subscribe((message) => { resolve(message.data!); }); }); if (!response?.displayParts) return null; const {displayParts, tags, documentation} = response; return { pos, create() { const tooltip = document.createElement('div'); tooltip.appendChild(getHtmlFromDisplayParts(displayParts)); // use documentation if available as it's more informative than tags if (documentation?.[0]?.text) { tooltip.appendChild(getMarkedHtmlFromString(documentation[0]?.text)); } else if (tags?.length) { tooltip.appendChild(getTagsHtml(tags)); } return { dom: tooltip, // Note: force the tooltip to scroll to the top on mount and on position change // because depending on the position of the mouse and the size of the tooltip content, // the tooltip might render with its initial scroll position on the bottom mount: (_) => forceTooltipScrollTop(), positioned: (_) => forceTooltipScrollTop(), resize: false, }; }, }; }, { hideOnChange: true, }, ); }; function forceTooltipScrollTop() { const activeTooltip = document.querySelector('.cm-tooltip'); // only scroll if the tooltip is scrollable if (activeTooltip && activeTooltip.scrollHeight > activeTooltip.clientHeight) { activeTooltip.scroll(0, -activeTooltip.scrollHeight); } } function getMarkedHtmlFromString(content: string): HTMLDivElement { const wrapper = document.createElement('div'); wrapper.innerHTML = marked(content) as string; return wrapper; } function getHtmlFromDisplayParts(displayParts: SymbolDisplayPart[]): HTMLDivElement { const wrapper = document.createElement('div'); let displayPartWrapper = document.createElement('div'); for (const part of displayParts) { const span = document.createElement('span'); span.classList.add(part.kind); span.textContent = part.text; // create new div to separate lines when a line break is found if (part.kind === 'lineBreak') { wrapper.appendChild(displayPartWrapper); displayPartWrapper = document.createElement('div'); } else { displayPartWrapper.appendChild(span); } } wrapper.appendChild(displayPartWrapper); return wrapper; } function getTagsHtml(tags: JSDocTagInfo[]): HTMLDivElement { const tagsWrapper = document.createElement('div'); let contentString = ''; for (let tag of tags) { contentString += `\n@${tag.name}\n`; if (tag.text) { for (const {text} of tag.text) { contentString += text; } } } tagsWrapper.innerHTML = marked(contentString) as string; return tagsWrapper; }
{ "commit_id": "cb34e406ba", "end_byte": 4329, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/extensions/tooltip.ts" }
angular/adev/src/app/editor/code-editor/extensions/diagnostics.ts_0_1746
/*! * @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 {Diagnostic, linter} from '@codemirror/lint'; import {TsVfsWorkerActions} from '../workers/enums/actions'; import {Signal} from '@angular/core'; import {EditorFile} from '../code-mirror-editor.service'; import {ActionMessage} from '../workers/interfaces/message'; import {DiagnosticsRequest} from '../workers/interfaces/diagnostics-request'; import {Subject, filter, take} from 'rxjs'; import {DiagnosticWithLocation, DiagnosticsState} from '../services/diagnostics-state.service'; // Factory method for diagnostics extension. export const getDiagnosticsExtension = ( eventManager: Subject<ActionMessage>, currentFile: Signal<EditorFile>, sendRequestToTsVfs: (request: ActionMessage<DiagnosticsRequest>) => void, diagnosticsState: DiagnosticsState, ) => { return linter( async (view): Promise<Diagnostic[]> => { sendRequestToTsVfs({ action: TsVfsWorkerActions.DIAGNOSTICS_REQUEST, data: { file: currentFile().filename, }, }); const diagnostics = await new Promise((resolve) => { eventManager .pipe( filter((event) => event.action === TsVfsWorkerActions.DIAGNOSTICS_RESPONSE), take(1), ) .subscribe((response: ActionMessage<Diagnostic[]>) => { resolve(response.data); }); }); const result = !!diagnostics ? (diagnostics as DiagnosticWithLocation[]) : []; diagnosticsState.setDiagnostics(result); return result; }, { delay: 400, }, ); };
{ "commit_id": "cb34e406ba", "end_byte": 1746, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/extensions/diagnostics.ts" }
angular/adev/src/app/editor/code-editor/workers/typescript-vfs.worker.ts_0_8875
/*! * @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 */ /// <reference lib="webworker" /> import * as ts from 'typescript'; import { VirtualTypeScriptEnvironment, createDefaultMapFromCDN, createSystem, createVirtualTypeScriptEnvironment, } from '@typescript/vfs'; import {Subject} from 'rxjs'; import {TsVfsWorkerActions} from './enums/actions'; import {AutocompleteRequest} from './interfaces/autocomplete-request'; import {AutocompleteResponse} from './interfaces/autocomplete-response'; import {CodeChangeRequest} from './interfaces/code-change-request'; import {DefineTypesRequest, Typing} from './interfaces/define-types-request'; import {DiagnosticsRequest, DiagnosticsResponse} from './interfaces/diagnostics-request'; import {DisplayTooltipRequest} from './interfaces/display-tooltip-request'; import {DisplayTooltipResponse} from './interfaces/display-tooltip-response'; import {ActionMessage} from './interfaces/message'; import {getCompilerOpts} from './utils/compiler-opts'; import {FORMAT_CODE_SETTINGS, USER_PREFERENCES} from './utils/ts-constants'; import { fileExists, normalizeFileContent, normalizeFileName, updateFile, updateOrCreateFile, } from './utils/environment'; /** * Web worker uses TypeScript Virtual File System library to enrich code editor functionality i.e. : * - provide autocomplete suggestions * - display errors * - display tooltip with types and documentation */ const eventManager = new Subject<ActionMessage>(); let languageService: ts.LanguageService | undefined; let env: VirtualTypeScriptEnvironment | undefined; let defaultFilesMap: Map<string, string> = new Map(); let compilerOpts: ts.CompilerOptions | undefined; let cachedTypingFiles: Typing[] = []; // Create virtual environment for code editor files. function createVfsEnv(request: ActionMessage<Map<string, string>>): ActionMessage { if (env) { env.languageService.dispose(); } // merge code editor ts files with default TypeScript libs const tutorialFilesMap = request.data ?? new Map(); const fileSystemMap = new Map<string, string>(); [...tutorialFilesMap, ...defaultFilesMap].forEach(([key, value]) => { fileSystemMap.set(normalizeFileName(key), normalizeFileContent(value)); }); const system = createSystem(fileSystemMap); const entryFiles: string[] = Array.from(tutorialFilesMap.keys()); env = createVirtualTypeScriptEnvironment(system, entryFiles, ts, compilerOpts); languageService = env.languageService; if (cachedTypingFiles.length > 0) defineTypes({action: TsVfsWorkerActions.DEFINE_TYPES_REQUEST, data: cachedTypingFiles}); return {action: TsVfsWorkerActions.CREATE_VFS_ENV_RESPONSE}; } function updateVfsEnv(request: ActionMessage<Map<string, string>>): void { if (!env?.sys) return; request.data?.forEach((value, key) => { updateOrCreateFile(env!, key, value); }); } // Update content of the file in virtual environment. function codeChanged(request: ActionMessage<CodeChangeRequest>): void { if (!request.data || !env) return; updateFile(env, request.data.file, request.data.code); // run diagnostics when code changed postMessage( runDiagnostics({ action: TsVfsWorkerActions.DIAGNOSTICS_REQUEST, data: {file: request.data.file}, }), ); } // Get autocomplete proposal for given position of the file. function getAutocompleteProposals( request: ActionMessage<AutocompleteRequest>, ): ActionMessage<AutocompleteResponse> { if (!env) { return { action: TsVfsWorkerActions.AUTOCOMPLETE_RESPONSE, data: [], }; } updateFile(env, request.data!.file, request.data!.content); const completions = languageService!.getCompletionsAtPosition( request.data!.file, request.data!.position, USER_PREFERENCES, FORMAT_CODE_SETTINGS, ); const completionsWithImportSuggestions = completions?.entries.map((entry) => { if (entry.source) { const entryDetails = languageService!.getCompletionEntryDetails( request.data!.file, request.data!.position, entry.name, FORMAT_CODE_SETTINGS, entry.source, USER_PREFERENCES, entry.data, ); if (entryDetails?.codeActions) { return { ...entry, codeActions: entryDetails?.codeActions, }; } } return entry; }); return { action: TsVfsWorkerActions.AUTOCOMPLETE_RESPONSE, data: completionsWithImportSuggestions, }; } // Run diagnostics after file update. function runDiagnostics( request: ActionMessage<DiagnosticsRequest>, ): ActionMessage<DiagnosticsResponse> { if (!env?.sys || !fileExists(env, request.data!.file)) { return {action: TsVfsWorkerActions.DIAGNOSTICS_RESPONSE, data: []}; } const syntacticDiagnostics = languageService?.getSyntacticDiagnostics(request.data!.file) ?? []; const semanticDiagnostic = languageService?.getSemanticDiagnostics(request.data!.file) ?? []; const suggestionDiagnostics = languageService?.getSuggestionDiagnostics(request.data!.file) ?? []; const result = [...syntacticDiagnostics, ...semanticDiagnostic, ...suggestionDiagnostics].map( (diagnostic) => { const lineAndCharacter = diagnostic.file && diagnostic.start ? diagnostic.file?.getLineAndCharacterOfPosition(diagnostic.start) : null; const from = diagnostic.start; const to = (diagnostic.start ?? 0) + (diagnostic.length ?? 0); return { from, to, message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'), source: diagnostic.source, code: diagnostic.code, severity: ['warning', 'error', 'info'][diagnostic.category], ...(lineAndCharacter && { lineNumber: lineAndCharacter.line + 1, characterPosition: lineAndCharacter.character, }), }; }, ); return {action: TsVfsWorkerActions.DIAGNOSTICS_RESPONSE, data: result}; } function defineTypes(request: ActionMessage<DefineTypesRequest>): void { if (!env?.sys || !request.data?.length) return; for (const {path, content} of request.data) { updateOrCreateFile(env, path, content); } cachedTypingFiles = request.data ?? []; } function displayTooltip( request: ActionMessage<DisplayTooltipRequest>, ): ActionMessage<DisplayTooltipResponse> { if (!languageService) { return { action: TsVfsWorkerActions.DISPLAY_TOOLTIP_RESPONSE, data: { tags: null, displayParts: null, documentation: null, }, }; } const result = languageService.getQuickInfoAtPosition(request.data!.file, request.data!.position); if (!result) { return { action: TsVfsWorkerActions.DISPLAY_TOOLTIP_RESPONSE, data: { tags: null, displayParts: null, documentation: null, }, }; } return { action: TsVfsWorkerActions.DISPLAY_TOOLTIP_RESPONSE, data: { tags: result.tags ?? null, displayParts: result.displayParts ?? null, documentation: result.documentation ?? null, }, }; } // Strategy defines what function needs to be triggered for given request. const triggerActionStrategy: Record<string, (request: ActionMessage) => ActionMessage | void> = { [TsVfsWorkerActions.CREATE_VFS_ENV_REQUEST]: (request: ActionMessage) => createVfsEnv(request), [TsVfsWorkerActions.UPDATE_VFS_ENV_REQUEST]: (request: ActionMessage) => updateVfsEnv(request), [TsVfsWorkerActions.CODE_CHANGED]: (request: ActionMessage) => codeChanged(request), [TsVfsWorkerActions.AUTOCOMPLETE_REQUEST]: (request: ActionMessage) => getAutocompleteProposals(request), [TsVfsWorkerActions.DIAGNOSTICS_REQUEST]: (request: ActionMessage) => runDiagnostics(request), [TsVfsWorkerActions.DEFINE_TYPES_REQUEST]: (request: ActionMessage) => defineTypes(request), [TsVfsWorkerActions.DISPLAY_TOOLTIP_REQUEST]: (request: ActionMessage) => displayTooltip(request), }; const bootstrapWorker = async () => { const sendResponse = (message: ActionMessage): void => { postMessage(message); }; compilerOpts = getCompilerOpts(ts); defaultFilesMap = await createDefaultMapFromCDN(compilerOpts, ts.version, false, ts); sendResponse({action: TsVfsWorkerActions.INIT_DEFAULT_FILE_SYSTEM_MAP}); eventManager.subscribe((request) => { const response = triggerActionStrategy[request.action](request); if (response) { sendResponse(response); } }); }; addEventListener('message', ({data}: MessageEvent<ActionMessage>) => { eventManager.next(data); }); // Initialize worker, create on init TypeScript Virtual Environment and setup listeners for action i.e. run diagnostics, autocomplete etc. Promise.resolve(bootstrapWorker());
{ "commit_id": "cb34e406ba", "end_byte": 8875, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/typescript-vfs.worker.ts" }
angular/adev/src/app/editor/code-editor/workers/enums/actions.ts_0_849
/*! * @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 const enum TsVfsWorkerActions { INIT_DEFAULT_FILE_SYSTEM_MAP = 'default-fs-ready', CREATE_VFS_ENV_REQUEST = 'create-vfs-env-request', CREATE_VFS_ENV_RESPONSE = 'create-vfs-env-response', CODE_CHANGED = 'code-changed', UPDATE_VFS_ENV_REQUEST = 'update-vfs-env-request', AUTOCOMPLETE_REQUEST = 'autocomplete-request', AUTOCOMPLETE_RESPONSE = 'autocomplete-response', DIAGNOSTICS_REQUEST = 'diagnostics-request', DIAGNOSTICS_RESPONSE = 'diagnostics-response', DEFINE_TYPES_REQUEST = 'define-types-request', DISPLAY_TOOLTIP_REQUEST = 'display-tooltip-request', DISPLAY_TOOLTIP_RESPONSE = 'display-tooltip-response', }
{ "commit_id": "cb34e406ba", "end_byte": 849, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/enums/actions.ts" }
angular/adev/src/app/editor/code-editor/workers/utils/environment.ts_0_1385
/*! * @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 {VirtualTypeScriptEnvironment} from '@typescript/vfs'; // Note: use a comment in empty files to avoid error in vfs // See: https://github.com/microsoft/TypeScript-Website/issues/2713 export const EMPTY_FILE_CONTENT = '// empty file'; export function updateOrCreateFile( env: VirtualTypeScriptEnvironment, file: string, content: string, ) { if (fileExists(env, file)) { updateFile(env, file, content); } else { createFile(env, file, content); } } export function updateFile(env: VirtualTypeScriptEnvironment, file: string, content: string) { env.updateFile(normalizeFileName(file), normalizeFileContent(content)); } export function createFile(env: VirtualTypeScriptEnvironment, file: string, content: string) { env.createFile(normalizeFileName(file), normalizeFileContent(content)); } export function fileExists(env: VirtualTypeScriptEnvironment, fileName: string) { return env.sys.fileExists(normalizeFileName(fileName)); } export function normalizeFileContent(content: string) { return content || EMPTY_FILE_CONTENT; } export function normalizeFileName(filename: string) { return filename.startsWith('/') ? filename : `/${filename}`; }
{ "commit_id": "cb34e406ba", "end_byte": 1385, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/utils/environment.ts" }
angular/adev/src/app/editor/code-editor/workers/utils/compiler-opts.ts_0_461
/*! * @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 const getCompilerOpts = (ts: {ScriptTarget: {ES2021: number; ES2020: number}}) => ({ target: ts.ScriptTarget.ES2021, module: ts.ScriptTarget.ES2020, lib: ['es2021', 'es2020', 'dom'], esModuleInterop: true, experimentalDecorators: true, });
{ "commit_id": "cb34e406ba", "end_byte": 461, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/utils/compiler-opts.ts" }
angular/adev/src/app/editor/code-editor/workers/utils/ts-constants.ts_0_2181
/*! * @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 {FormatCodeSettings, UserPreferences} from 'typescript'; // redeclare TypeScript's SemicolonPreference to avoid build errors on importing it enum SemicolonPreference { Ignore = 'ignore', Insert = 'insert', Remove = 'remove', } export const USER_PREFERENCES: UserPreferences = { includeCompletionsForModuleExports: true, includeCompletionsForImportStatements: true, includeCompletionsWithSnippetText: true, includeAutomaticOptionalChainCompletions: true, includeCompletionsWithInsertText: true, includeCompletionsWithClassMemberSnippets: true, includeCompletionsWithObjectLiteralMethodSnippets: true, useLabelDetailsInCompletionEntries: true, allowIncompleteCompletions: true, importModuleSpecifierPreference: 'relative', importModuleSpecifierEnding: 'auto', allowTextChangesInNewFiles: true, providePrefixAndSuffixTextForRename: true, includePackageJsonAutoImports: 'auto', provideRefactorNotApplicableReason: true, }; export const FORMAT_CODE_SETTINGS: FormatCodeSettings = { insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: false, insertSpaceAfterCommaDelimiter: true, insertSpaceAfterSemicolonInForStatements: true, insertSpaceBeforeAndAfterBinaryOperators: true, insertSpaceAfterConstructor: true, insertSpaceAfterKeywordsInControlFlowStatements: true, insertSpaceAfterFunctionKeywordForAnonymousFunctions: true, insertSpaceAfterOpeningAndBeforeClosingEmptyBraces: false, insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: true, insertSpaceAfterTypeAssertion: true, insertSpaceBeforeFunctionParenthesis: true, placeOpenBraceOnNewLineForFunctions: true, placeOpenBraceOnNewLineForControlBlocks: true, insertSpaceBeforeTypeAnnotation: true, indentMultiLineObjectLiteralBeginningOnBlankLine: true, semicolons: SemicolonPreference.Insert, };
{ "commit_id": "cb34e406ba", "end_byte": 2181, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/utils/ts-constants.ts" }
angular/adev/src/app/editor/code-editor/workers/interfaces/autocomplete-request.ts_0_416
/*! * @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 */ /** * Gets autocompletion proposal entries at a particular position in a file. */ export interface AutocompleteRequest { file: string; content: string; position: number; from?: number; to?: number; }
{ "commit_id": "cb34e406ba", "end_byte": 416, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/interfaces/autocomplete-request.ts" }
angular/adev/src/app/editor/code-editor/workers/interfaces/autocomplete-response.ts_0_496
/*! * @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 {CodeAction} from 'typescript'; export interface AutocompleteItem { kind: string; name: string; sortText: string; codeActions?: CodeAction[]; } /** * Autocomplete response which contains all proposal entries. */ export type AutocompleteResponse = AutocompleteItem[];
{ "commit_id": "cb34e406ba", "end_byte": 496, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/interfaces/autocomplete-response.ts" }
angular/adev/src/app/editor/code-editor/workers/interfaces/message.ts_0_344
/*! * @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 {TsVfsWorkerActions} from '../enums/actions'; export interface ActionMessage<T = any> { action: TsVfsWorkerActions; data?: T; }
{ "commit_id": "cb34e406ba", "end_byte": 344, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/interfaces/message.ts" }
angular/adev/src/app/editor/code-editor/workers/interfaces/define-types-request.ts_0_311
/*! * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export interface Typing { path: string; content: string; } export type DefineTypesRequest = Typing[];
{ "commit_id": "cb34e406ba", "end_byte": 311, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/interfaces/define-types-request.ts" }
angular/adev/src/app/editor/code-editor/workers/interfaces/display-tooltip-request.ts_0_367
/*! * @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 */ /** * Gets autocompletion proposal entries at a particular position in a file. */ export interface DisplayTooltipRequest { file: string; position: number; }
{ "commit_id": "cb34e406ba", "end_byte": 367, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/interfaces/display-tooltip-request.ts" }
angular/adev/src/app/editor/code-editor/workers/interfaces/display-tooltip-response.ts_0_429
/*! * @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 {JSDocTagInfo, SymbolDisplayPart} from 'typescript'; export interface DisplayTooltipResponse { displayParts: SymbolDisplayPart[] | null; tags: JSDocTagInfo[] | null; documentation: SymbolDisplayPart[] | null; }
{ "commit_id": "cb34e406ba", "end_byte": 429, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/interfaces/display-tooltip-response.ts" }
angular/adev/src/app/editor/code-editor/workers/interfaces/code-change-request.ts_0_344
/*! * @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 */ /** * Request contains current state ('code') of provided file. */ export interface CodeChangeRequest { code: string; file: string; }
{ "commit_id": "cb34e406ba", "end_byte": 344, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/interfaces/code-change-request.ts" }
angular/adev/src/app/editor/code-editor/workers/interfaces/diagnostics-request.ts_0_592
/*! * @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 */ /** * Request will be used to examine diagnostics for the given `file`. */ export interface DiagnosticsRequest { file: string; } export interface DiagnosticsResult { from?: number; to?: number; message: string; source?: string; code: number; severity: string; lineNumber?: number; characterPosition?: number; } export type DiagnosticsResponse = DiagnosticsResult[];
{ "commit_id": "cb34e406ba", "end_byte": 592, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/workers/interfaces/diagnostics-request.ts" }
angular/adev/src/app/editor/code-editor/services/diagnostics-state.service.spec.ts_0_580
/*! * @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 {DiagnosticsState} from './diagnostics-state.service'; describe('DiagnosticsState', () => { let service: DiagnosticsState; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(DiagnosticsState); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
{ "commit_id": "cb34e406ba", "end_byte": 580, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/services/diagnostics-state.service.spec.ts" }
angular/adev/src/app/editor/code-editor/services/diagnostics-state.service.ts_0_875
/*! * @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 {Diagnostic} from '@codemirror/lint'; import {BehaviorSubject, distinctUntilChanged} from 'rxjs'; export interface DiagnosticWithLocation extends Diagnostic { lineNumber: number; characterPosition: number; } @Injectable({ providedIn: 'root', }) export class DiagnosticsState { private readonly _diagnostics$ = new BehaviorSubject<DiagnosticWithLocation[]>([]); // TODO: use signals when zoneless will be turned off diagnostics$ = this._diagnostics$.asObservable().pipe(distinctUntilChanged()); setDiagnostics(diagnostics: DiagnosticWithLocation[]): void { this._diagnostics$.next(diagnostics); } }
{ "commit_id": "cb34e406ba", "end_byte": 875, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/code-editor/services/diagnostics-state.service.ts" }
angular/adev/src/app/editor/enums/loading-steps.ts_0_318
/*! * @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 enum LoadingStep { NOT_STARTED, BOOT, LOAD_FILES, INSTALL, START_DEV_SERVER, READY, ERROR, }
{ "commit_id": "cb34e406ba", "end_byte": 318, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/enums/loading-steps.ts" }
angular/adev/src/app/editor/terminal/terminal.component.ts_0_1957
/*! * @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 { AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, Input, ViewChild, ViewEncapsulation, inject, } from '@angular/core'; import {debounceTime} from 'rxjs/operators'; import {TerminalHandler, TerminalType} from './terminal-handler.service'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {Subject} from 'rxjs'; @Component({ selector: 'docs-tutorial-terminal', standalone: true, templateUrl: './terminal.component.html', styleUrls: ['./terminal.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, imports: [], // ViewEncapsulation is disabled to allow Xterm.js's styles to be applied // to the terminal element. encapsulation: ViewEncapsulation.None, }) export class Terminal implements AfterViewInit { @Input({required: true}) type!: TerminalType; @ViewChild('terminalOutput') private terminalElementRef!: ElementRef<HTMLElement>; private readonly destroyRef = inject(DestroyRef); private readonly terminalHandler = inject(TerminalHandler); private readonly resize$ = new Subject<void>(); ngAfterViewInit() { this.terminalHandler.registerTerminal(this.type, this.terminalElementRef.nativeElement); this.setResizeObserver(); this.resize$.pipe(debounceTime(50), takeUntilDestroyed(this.destroyRef)).subscribe(() => { this.handleResize(); }); } private setResizeObserver(): void { const resizeObserver = new ResizeObserver((_) => { this.resize$.next(); }); resizeObserver.observe(this.terminalElementRef.nativeElement); this.destroyRef.onDestroy(() => resizeObserver.disconnect()); } private handleResize(): void { this.terminalHandler.resizeToFitParent(this.type); } }
{ "commit_id": "cb34e406ba", "end_byte": 1957, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/terminal/terminal.component.ts" }
angular/adev/src/app/editor/terminal/command-validator.service.ts_0_800
/*! * @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'; export const ALLOWED_COMMAND_PREFIXES = [ 'ng serve', 'ng s', 'ng generate', 'ng g', 'ng version', 'ng v', 'ng update', 'ng test', 'ng t', 'ng e2e', 'ng e', 'ng add', 'ng config', 'ng new', ]; @Injectable({providedIn: 'root'}) export class CommandValidator { // Method return true when the provided command is allowed to execute, otherwise return false. validate(command: string): boolean { return ALLOWED_COMMAND_PREFIXES.some( (prefix) => prefix === command || command.startsWith(`${prefix} `), ); } }
{ "commit_id": "cb34e406ba", "end_byte": 800, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/terminal/command-validator.service.ts" }
angular/adev/src/app/editor/terminal/interactive-terminal.ts_0_3386
/*! * @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} from '@angular/core'; import {Subject} from 'rxjs'; import {Terminal} from '@xterm/xterm'; import {WINDOW} from '@angular/docs'; import {CommandValidator} from './command-validator.service'; export const NOT_VALID_COMMAND_MSG = 'Angular Documentation - Not allowed command!'; export const ALLOWED_KEYS: Array<KeyboardEvent['key']> = [ // Allow Backspace to delete what was typed 'Backspace', // Allow ArrowUp to interact with CLI 'ArrowUp', // Allow ArrowDown to interact with CLI 'ArrowDown', ]; export class InteractiveTerminal extends Terminal { private readonly window = inject(WINDOW); private readonly commandValidator = inject(CommandValidator); private readonly breakProcess = new Subject<void>(); // Using this stream, the webcontainer shell can break current process. breakProcess$ = this.breakProcess.asObservable(); constructor() { super({convertEol: true, disableStdin: false}); // bypass command validation if sudo=true is present in the query string if (!this.window.location.search.includes('sudo=true')) { this.handleCommandExecution(); } } breakCurrentProcess(): void { this.breakProcess.next(); } // Method validate if provided command by user is on the list of the allowed commands. // If so, then command is executed, otherwise error message is displayed in the terminal. private handleCommandExecution(): void { const commandLinePrefix = '❯'; const xtermRed = '\x1b[1;31m'; this.attachCustomKeyEventHandler((event) => { if (ALLOWED_KEYS.includes(event.key)) { return true; } // While user is typing, then do not validate command. if (['keydown', 'keyup'].includes(event.type)) { return false; } // When user pressed enter, then verify if command is on the list of the allowed ones. if (event.key === 'Enter') { // Xterm does not have API to receive current text/command. // In that case we can read it using DOM methods. // As command to execute we can treat the last line in terminal which starts with '❯'. // Hack: excluding `.xterm-fg-6` is required to run i.e `ng e2e`, `ng add @angular/material`. // Some steps with selecting options also starts with '❯'. let terminalContent = Array.from(this.element!.querySelectorAll('.xterm-rows>div')) .map((lines) => Array.from(lines.querySelectorAll('span:not(.xterm-fg-6)')) .map((part) => part.textContent) .join('') .trim(), ) .filter((line) => !!line && line.startsWith(commandLinePrefix)); let command = terminalContent.length > 0 ? terminalContent[terminalContent.length - 1].replace(commandLinePrefix, '').trim() : ''; // If command exist and is invalid, then write line with error message and block execution. if (command && !this.commandValidator.validate(command)) { this.writeln(`\n${xtermRed}${NOT_VALID_COMMAND_MSG}`); this.breakCurrentProcess(); return false; } } return true; }); } }
{ "commit_id": "cb34e406ba", "end_byte": 3386, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/terminal/interactive-terminal.ts" }
angular/adev/src/app/editor/terminal/command-validator.service.spec.ts_0_1026
/*! * @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 {ALLOWED_COMMAND_PREFIXES, CommandValidator} from './command-validator.service'; describe('CommandValidator', () => { let service: CommandValidator; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(CommandValidator); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should return true when user try to execute allowed commands', () => { for (const command of ALLOWED_COMMAND_PREFIXES) { const result = service.validate(`${command} other command params`); expect(result).toBeTrue(); } }); it('should return false when user try to execute illegal commands', () => { const result = service.validate(`npm install`); expect(result).toBeFalse(); }); });
{ "commit_id": "cb34e406ba", "end_byte": 1026, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/terminal/command-validator.service.spec.ts" }
angular/adev/src/app/editor/terminal/terminal-handler.service.ts_0_2059
/*! * @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 {Terminal} from '@xterm/xterm'; import {FitAddon} from '@xterm/addon-fit'; import {InteractiveTerminal} from './interactive-terminal'; export enum TerminalType { READONLY, INTERACTIVE, } @Injectable({providedIn: 'root'}) export class TerminalHandler { private terminals = { // Passing a theme with CSS custom properties colors does not work // Because colors are parsed // See https://github.com/xtermjs/xterm.js/blob/854e2736f66ca3e5d3ab5a7b65bf3fd6fba8b707/src/browser/services/ThemeService.ts#L125 [TerminalType.READONLY]: { instance: new Terminal({convertEol: true, disableStdin: true}), fitAddon: new FitAddon(), }, [TerminalType.INTERACTIVE]: { instance: new InteractiveTerminal(), fitAddon: new FitAddon(), }, } as const; constructor() { // Load fitAddon for each terminal instance for (const {instance, fitAddon} of Object.values(this.terminals)) { instance.loadAddon(fitAddon); } } get readonlyTerminalInstance(): Terminal { return this.terminals[TerminalType.READONLY].instance; } get interactiveTerminalInstance(): InteractiveTerminal { return this.terminals[TerminalType.INTERACTIVE].instance; } registerTerminal(type: TerminalType, element: HTMLElement): void { const terminal = this.terminals[type]; this.mapTerminalToElement(terminal.instance, terminal.fitAddon, element); } resizeToFitParent(type: TerminalType): void { this.terminals[type]?.fitAddon.fit(); } clearTerminals() { this.terminals[TerminalType.READONLY].instance.clear(); this.terminals[TerminalType.INTERACTIVE].instance.clear(); } private mapTerminalToElement(terminal: Terminal, fitAddon: FitAddon, element: HTMLElement): void { terminal.open(element); fitAddon.fit(); } }
{ "commit_id": "cb34e406ba", "end_byte": 2059, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/terminal/terminal-handler.service.ts" }
angular/adev/src/app/editor/terminal/terminal-handler.service.spec.ts_0_954
/*! * @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 {TerminalHandler} from './terminal-handler.service'; import {WINDOW} from '@angular/docs'; describe('TerminalHandler', () => { let service: TerminalHandler; const fakeWindow = { location: { search: '', }, }; beforeEach(() => { TestBed.configureTestingModule({ providers: [TerminalHandler, {provide: WINDOW, useValue: fakeWindow}], }); service = TestBed.inject(TerminalHandler); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should create terminal instances on init', () => { expect(service.readonlyTerminalInstance).not.toBeNull(); expect(service.interactiveTerminalInstance).not.toBeNull(); }); });
{ "commit_id": "cb34e406ba", "end_byte": 954, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/terminal/terminal-handler.service.spec.ts" }