_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/language-service/test/legacy/template_target_spec.ts_47447_51162 | ; track foo) { } @empty { <sp¦an></span> }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.Element);
expect((node as t.Element).name).toBe('span');
});
it('should visit body of if block', () => {
const {nodes, position} = parse(`@if (title; as foo) { {{ fo¦o }} }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('foo');
});
it('should visit when conditions on defer blocks', () => {
const {nodes, position} = parse(`@defer (when fo¦o) { }`);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('foo');
});
it('should visit numeric on conditions on defer blocks', () => {
const {nodes, position} = parse(` @defer (on timer(2¦s)) { } `);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.TimerDeferredTrigger);
expect((node as t.TimerDeferredTrigger).delay).toBe(2000);
});
// TODO: Should the parser ingest a property read for `localRef`, instead of a string?
// (Talk to Kristiyan?)
// xit('should visit on conditions on defer blocks', () => {
// const {nodes, position} = parse(`
// <div #localRef></div>
// @defer (on viewport(local¦Ref)) { }
// `);
// const {context} = getTargetAtPosition(nodes, position)!;
// const {node} = context as SingleNodeTarget;
// expect(isExpressionNode(node!)).toBe(true);
// expect(node).toBeInstanceOf(e.PropertyRead);
// expect((node as e.PropertyRead).name).toBe('localRef');
// });
it('should visit secondary blocks on defer blocks', () => {
const {nodes, position} = parse(`@defer { } @er¦ror { <span></span> } `);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.DeferredBlockError);
});
it('should descend into secondary blocks on defer blocks', () => {
const {nodes, position} = parse(`@defer (on immediate) { } @error { {{fo¦o}} } `);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isExpressionNode(node!)).toBe(true);
expect(node).toBeInstanceOf(e.PropertyRead);
expect((node as e.PropertyRead).name).toBe('foo');
});
it('should visit placeholder blocks on defer blocks', () => {
const {nodes, position} = parse(`@defer { } @placehol¦der { <span></span> } `);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.DeferredBlockPlaceholder);
});
it('should visit loading blocks on defer blocks', () => {
const {nodes, position} = parse(`@defer { } @load¦ing { } `);
const {context} = getTargetAtPosition(nodes, position)!;
const {node} = context as SingleNodeTarget;
expect(isTemplateNode(node!)).toBe(true);
expect(node).toBeInstanceOf(t.DeferredBlockLoading);
});
});
| {
"end_byte": 51162,
"start_byte": 47447,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/template_target_spec.ts"
} |
angular/packages/language-service/test/legacy/compiler_factory_spec.ts_0_3069 | /**
* @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 ts from 'typescript';
import {APP_COMPONENT, MockService, setup, TEST_TEMPLATE} from './mock_host';
/**
* The following specs do not directly test the CompilerFactory class, rather
* it asserts our understanding of the project/program/template interaction
* which forms the underlying assumption used in the CompilerFactory.
*/
describe('tsserver', () => {
let project: ts.server.Project;
let service: MockService;
beforeAll(() => {
const {project: _project, service: _service} = setup();
project = _project;
service = _service;
});
beforeEach(() => {
service.reset();
});
describe('project version', () => {
it('is updated after TS changes', () => {
const v0 = project.getProjectVersion();
service.overwriteInlineTemplate(APP_COMPONENT, `{{ foo }}`);
const v1 = project.getProjectVersion();
expect(v1).not.toBe(v0);
});
it('is updated after template changes', () => {
const v0 = project.getProjectVersion();
service.overwrite(TEST_TEMPLATE, `{{ bar }}`);
const v1 = project.getProjectVersion();
expect(v1).not.toBe(v0);
});
});
describe('program', () => {
it('is updated after TS changes', () => {
const p0 = project.getLanguageService().getProgram();
expect(p0).toBeDefined();
service.overwriteInlineTemplate(APP_COMPONENT, `{{ foo }}`);
const p1 = project.getLanguageService().getProgram();
expect(p1).not.toBe(p0);
});
it('is not updated after template changes', () => {
const p0 = project.getLanguageService().getProgram();
expect(p0).toBeDefined();
service.overwrite(TEST_TEMPLATE, `{{ bar }}`);
const p1 = project.getLanguageService().getProgram();
expect(p1).toBe(p0);
});
});
describe('external template', () => {
it('should not be part of the project root', () => {
// Templates should _never_ be added to the project root, otherwise they
// will be parsed as TS files.
const scriptInfo = service.getScriptInfo(TEST_TEMPLATE);
expect(project.isRoot(scriptInfo)).toBeFalse();
});
it('should be attached to project', () => {
const scriptInfo = service.getScriptInfo(TEST_TEMPLATE);
// Script info for external template must be attached to a project because
// that's the primary mechanism used in the extension to locate the right
// language service instance. See
// https://github.com/angular/vscode-ng-language-service/blob/b048f5f6b9996c5cf113b764c7ffe13d9eeb4285/server/src/session.ts#L192
expect(scriptInfo.isAttached(project)).toBeTrue();
// Attaching a script info to a project does not mean that the project
// will contain the script info. Kinda like friendship on social media.
expect(project.containsScriptInfo(scriptInfo)).toBeFalse();
});
});
});
| {
"end_byte": 3069,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/compiler_factory_spec.ts"
} |
angular/packages/language-service/test/legacy/definitions_spec.ts_0_4553 | /**
* @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 {LanguageService} from '../../src/language_service';
import {APP_COMPONENT, MockService, setup} from './mock_host';
import {humanizeDefinitionInfo} from './test_utils';
describe('definitions', () => {
let service: MockService;
let ngLS: LanguageService;
beforeAll(() => {
const {project, service: _service, tsLS} = setup();
service = _service;
ngLS = new LanguageService(project, tsLS, {});
});
beforeEach(() => {
service.reset();
});
describe('elements', () => {
it('should work for native elements', () => {
const defs = getDefinitionsAndAssertBoundSpan({
templateOverride: `<butt¦on></button>`,
expectedSpanText: `<button></button>`,
});
expect(defs.length).toEqual(2);
expect(defs[0].fileName).toContain('lib.dom.d.ts');
expect(defs[0].contextSpan).toContain('interface HTMLButtonElement extends HTMLElement');
expect(defs[1].contextSpan).toContain('declare var HTMLButtonElement');
});
});
describe('templates', () => {
it('should return no definitions for ng-templates', () => {
const {position} = service.overwriteInlineTemplate(
APP_COMPONENT,
`<ng-templ¦ate></ng-template>`,
);
const definitionAndBoundSpan = ngLS.getDefinitionAndBoundSpan(APP_COMPONENT, position);
expect(definitionAndBoundSpan).toBeUndefined();
});
});
describe('directives', () => {
it('should work for directives', () => {
const defs = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div string-model¦></div>`,
expectedSpanText: 'string-model',
});
expect(defs.length).toEqual(1);
expect(defs[0].contextSpan).toContain('@Directive');
expect(defs[0].contextSpan).toContain('export class StringModel');
});
it('should work for components', () => {
const templateOverride = `
<t¦est-comp>
<div>some stuff in the middle</div>
</test-comp>`;
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride,
expectedSpanText: templateOverride.replace('¦', '').trim(),
});
expect(definitions.length).toEqual(1);
expect(definitions.length).toEqual(1);
expect(definitions[0].textSpan).toEqual('TestComponent');
expect(definitions[0].contextSpan).toContain('@Component');
});
it('should work for structural directives', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div *¦ngFor="let item of heroes"></div>`,
expectedSpanText: 'ngFor',
});
expect(definitions.length).toEqual(1);
expect(definitions[0].fileName).toContain('ng_for_of.d.ts');
expect(definitions[0].textSpan).toEqual('NgForOf');
expect(definitions[0].contextSpan).toContain(
'export declare class NgForOf<T, U extends NgIterable<T> = NgIterable<T>> implements DoCheck',
);
});
it('should return binding for structural directive where key maps to a binding', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div *ng¦If="anyValue"></div>`,
expectedSpanText: 'ngIf',
});
// Because the input is also part of the selector, the directive is also returned.
expect(definitions!.length).toEqual(2);
const [inputDef, directiveDef] = definitions;
expect(inputDef.textSpan).toEqual('ngIf');
expect(inputDef.contextSpan).toEqual('set ngIf(condition: T);');
expect(directiveDef.textSpan).toEqual('NgIf');
expect(directiveDef.contextSpan).toContain('export declare class NgIf');
});
it('should work for directives with compound selectors', () => {
let defs = getDefinitionsAndAssertBoundSpan({
templateOverride: `<button com¦pound custom-button></button>`,
expectedSpanText: 'compound',
});
expect(defs.length).toEqual(1);
expect(defs[0].contextSpan).toContain('export class CompoundCustomButtonDirective');
defs = getDefinitionsAndAssertBoundSpan({
templateOverride: `<button compound cu¦stom-button></button>`,
expectedSpanText: 'custom-button',
});
expect(defs.length).toEqual(1);
expect(defs[0].contextSpan).toContain('export class CompoundCustomButtonDirective');
});
});
descr | {
"end_byte": 4553,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/definitions_spec.ts"
} |
angular/packages/language-service/test/legacy/definitions_spec.ts_4557_12539 | 'bindings', () => {
describe('inputs', () => {
it('should work for input providers', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<test-comp [tcN¦ame]="name"></test-comp>`,
expectedSpanText: 'tcName',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('name');
expect(def.contextSpan).toEqual(`@Input('tcName') name = 'test';`);
});
it('should work for text inputs', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<test-comp tcN¦ame="name"></test-comp>`,
expectedSpanText: 'tcName',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('name');
expect(def.contextSpan).toEqual(`@Input('tcName') name = 'test';`);
});
it('should work for structural directive inputs ngForTrackBy', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div *ngFor="let item of heroes; tr¦ackBy: test;"></div>`,
expectedSpanText: 'trackBy',
});
expect(definitions!.length).toEqual(2);
const [setterDef, getterDef] = definitions;
expect(setterDef.fileName).toContain('ng_for_of.d.ts');
expect(setterDef.textSpan).toEqual('ngForTrackBy');
expect(setterDef.contextSpan).toEqual('set ngForTrackBy(fn: TrackByFunction<T>);');
expect(getterDef.textSpan).toEqual('ngForTrackBy');
expect(getterDef.contextSpan).toEqual('get ngForTrackBy(): TrackByFunction<T>;');
});
it('should work for structural directive inputs ngForOf', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div *ngFor="let item o¦f heroes"></div>`,
expectedSpanText: 'of',
});
// Because the input is also part of the selector ([ngFor][ngForOf]), the directive is also
// returned.
expect(definitions!.length).toEqual(2);
const [inputDef, directiveDef] = definitions;
expect(inputDef.textSpan).toEqual('ngForOf');
expect(inputDef.contextSpan).toEqual(
'set ngForOf(ngForOf: (U & NgIterable<T>) | undefined | null);',
);
expect(directiveDef.textSpan).toEqual('NgForOf');
expect(directiveDef.contextSpan).toContain('export declare class NgForOf');
});
it('should work for two-way binding providers', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<test-comp string-model [(mo¦del)]="title"></test-comp>`,
expectedSpanText: 'model',
});
expect(definitions!.length).toEqual(2);
const [inputDef, outputDef] = definitions;
expect(inputDef.textSpan).toEqual('model');
expect(inputDef.contextSpan).toEqual(`@Input() model: string = 'model';`);
expect(outputDef.textSpan).toEqual('modelChange');
expect(outputDef.contextSpan).toEqual(
`@Output() modelChange: EventEmitter<string> = new EventEmitter();`,
);
});
});
describe('outputs', () => {
it('should work for event providers', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<test-comp (te¦st)="myClick($event)"></test-comp>`,
expectedSpanText: 'test',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('testEvent');
expect(def.contextSpan).toEqual("@Output('test') testEvent = new EventEmitter();");
});
it('should return nothing for $event from EventEmitter', () => {
const {position} = service.overwriteInlineTemplate(
APP_COMPONENT,
`<div string-model (modelChange)="myClick($e¦vent)"></div>`,
);
const definitionAndBoundSpan = ngLS.getDefinitionAndBoundSpan(APP_COMPONENT, position);
expect(definitionAndBoundSpan).toBeUndefined();
});
it('should return the directive when the event is part of the selector', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div (eventSelect¦or)="title = ''"></div>`,
expectedSpanText: `eventSelector`,
});
expect(definitions!.length).toEqual(2);
const [inputDef, directiveDef] = definitions;
expect(inputDef.textSpan).toEqual('eventSelector');
expect(inputDef.contextSpan).toEqual('@Output() eventSelector = new EventEmitter<void>();');
expect(directiveDef.textSpan).toEqual('EventSelectorDirective');
expect(directiveDef.contextSpan).toContain('export class EventSelectorDirective');
});
it('should work for $event from native element', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div (cl¦ick)="myClick($event)"></div>`,
expectedSpanText: 'click',
});
expect(definitions!.length).toEqual(1);
expect(definitions[0].textSpan).toEqual('addEventListener');
expect(definitions[0].contextSpan).toContain(
'addEventListener<K extends keyof HTMLElementEventMap>',
);
expect(definitions[0].fileName).toContain('lib.dom.d.ts');
});
});
});
describe('references', () => {
it('should work for element reference declarations', () => {
const {position} = service.overwriteInlineTemplate(
APP_COMPONENT,
`<div #cha¦rt></div>{{chart}}`,
);
const definitionAndBoundSpan = ngLS.getDefinitionAndBoundSpan(APP_COMPONENT, position);
// We're already at the definition, so nothing is returned
expect(definitionAndBoundSpan).toBeUndefined();
});
it('should work for element reference uses', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div #chart></div>{{char¦t}}`,
expectedSpanText: 'chart',
});
expect(definitions!.length).toEqual(1);
const [varDef] = definitions;
expect(varDef.textSpan).toEqual('chart');
});
});
describe('variables', () => {
it('should work for array members', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div *ngFor="let hero of heroes">{{her¦o}}</div>`,
expectedSpanText: 'hero',
});
expect(definitions!.length).toEqual(2);
const [templateDeclarationDef, contextDef] = definitions;
expect(templateDeclarationDef.textSpan).toEqual('hero');
// `$implicit` is from the `NgForOfContext`:
// https://github.com/angular/angular/blob/89c5255b8ca59eed27ede9e1fad69857ab0c6f4f/packages/common/src/directives/ng_for_of.ts#L15
expect(contextDef.textSpan).toEqual('$implicit');
expect(contextDef.contextSpan).toContain('$implicit: T;');
});
});
describe('@let declarations', () => {
it('should work for a @let declaration', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `@let value = 42; {{val¦ue}}`,
expectedSpanText: 'value',
});
expect(definitions.length).toBe(1);
const [def] = definitions;
expect(def.textSpan).toBe('@let value = 42');
});
});
describe('pipes', () => {
it('should work for pipes', () => {
const templateOverride = `<p>The hero's birthday is {{birthday | da¦te: "MM/dd/yy"}}</p>`;
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride,
expectedSpanText: 'date',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('transform');
expect(def.contextSpan).toContain('transform(value: Date | string | number, ');
});
});
describe('expressio | {
"end_byte": 12539,
"start_byte": 4557,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/definitions_spec.ts"
} |
angular/packages/language-service/test/legacy/definitions_spec.ts_12543_19802 | () => {
it('should find members in a text interpolation', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div>{{ tit¦le }}</div>`,
expectedSpanText: 'title',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('title');
expect(def.contextSpan).toEqual(`title = 'Tour of Heroes';`);
});
it('should work for accessed property reads', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div>{{title.len¦gth}}</div>`,
expectedSpanText: 'length',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('length');
expect(def.contextSpan).toEqual('readonly length: number;');
});
it('should find members in an attribute interpolation', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div string-model model="{{tit¦le}}"></div>`,
expectedSpanText: 'title',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('title');
expect(def.contextSpan).toEqual(`title = 'Tour of Heroes';`);
});
it('should find members of input binding', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<test-comp [tcName]="ti¦tle"></test-comp>`,
expectedSpanText: 'title',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('title');
expect(def.contextSpan).toEqual(`title = 'Tour of Heroes';`);
});
it('should find members of event binding', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<test-comp (test)="ti¦tle=$event"></test-comp>`,
expectedSpanText: 'title',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('title');
expect(def.contextSpan).toEqual(`title = 'Tour of Heroes';`);
});
it('should work for method calls', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div (click)="setT¦itle('title')"></div>`,
expectedSpanText: 'setTitle',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('setTitle');
expect(def.contextSpan).toContain('setTitle(newTitle: string)');
});
it('should work for accessed properties in writes', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div (click)="hero.i¦d = 2"></div>`,
expectedSpanText: 'id',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('id');
expect(def.contextSpan).toEqual('id: number;');
});
it('should work for method call arguments', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div (click)="setTitle(hero.nam¦e)"></div>`,
expectedSpanText: 'name',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('name');
expect(def.contextSpan).toEqual('name: string;');
});
it('should find members of two-way binding', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<input [(ngModel)]="ti¦tle" />`,
expectedSpanText: 'title',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('title');
expect(def.contextSpan).toEqual(`title = 'Tour of Heroes';`);
});
it('should find members in a structural directive', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div *ngIf="anyV¦alue"></div>`,
expectedSpanText: 'anyValue',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('anyValue');
expect(def.contextSpan).toEqual('anyValue: any;');
});
it('should work for variables in structural directives', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div *ngFor="let item of heroes as her¦oes2; trackBy: test;"></div>`,
expectedSpanText: 'heroes2',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('ngForOf');
expect(def.contextSpan).toEqual('ngForOf: U;');
});
it('should work for uses of members in structural directives', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div *ngFor="let item of heroes as heroes2">{{her¦oes2}}</div>`,
expectedSpanText: 'heroes2',
});
expect(definitions!.length).toEqual(2);
const [def, contextDef] = definitions;
expect(def.textSpan).toEqual('heroes2');
expect(def.contextSpan).toEqual('of heroes as heroes2');
expect(contextDef.textSpan).toEqual('ngForOf');
expect(contextDef.contextSpan).toEqual('ngForOf: U;');
});
it('should work for members in structural directives', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div *ngFor="let item of her¦oes; trackBy: test;"></div>`,
expectedSpanText: 'heroes',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('heroes');
expect(def.contextSpan).toEqual('heroes: Hero[] = [this.hero];');
});
it('should return nothing for the $any() cast function', () => {
const {position} = service.overwriteInlineTemplate(
APP_COMPONENT,
`<div>{{$an¦y(title)}}</div>`,
);
const definitionAndBoundSpan = ngLS.getDefinitionAndBoundSpan(APP_COMPONENT, position);
expect(definitionAndBoundSpan).toBeUndefined();
});
it('should work for object literals with shorthand declarations in an action', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `<div (click)="setHero({na¦me, id: 1})"></div>`,
expectedSpanText: 'name',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('name');
expect(def.fileName).toContain('/app/app.component.ts');
expect(def.contextSpan).toContain(`name = 'Frodo';`);
});
it('should work for object literals with shorthand declarations in a data binding', () => {
const definitions = getDefinitionsAndAssertBoundSpan({
templateOverride: `{{ {na¦me} }}`,
expectedSpanText: 'name',
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('name');
expect(def.fileName).toContain('/app/app.component.ts');
expect(def.contextSpan).toContain(`name = 'Frodo';`);
});
});
describe('external resources', () = | {
"end_byte": 19802,
"start_byte": 12543,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/definitions_spec.ts"
} |
angular/packages/language-service/test/legacy/definitions_spec.ts_19806_23929 | it('should be able to find a template from a url', () => {
const {position, text} = service.overwrite(
APP_COMPONENT,
`
import {Component} from '@angular/core';
@Component({
templateUrl: './tes¦t.ng',
})
export class AppComponent {}`,
);
const result = ngLS.getDefinitionAndBoundSpan(APP_COMPONENT, position);
expect(result).toBeDefined();
const {textSpan, definitions} = result!;
expect(text.substring(textSpan.start, textSpan.start + textSpan.length)).toEqual('./test.ng');
expect(definitions).toBeDefined();
expect(definitions!.length).toBe(1);
const [def] = definitions!;
expect(def.fileName).toContain('/app/test.ng');
expect(def.textSpan).toEqual({start: 0, length: 0});
});
it('should be able to find a stylesheet from a url', () => {
const {position, text} = service.overwrite(
APP_COMPONENT,
`
import {Component} from '@angular/core';
@Component({
template: 'empty',
styleUrls: ['./te¦st.css']
})
export class AppComponent {}`,
);
const result = ngLS.getDefinitionAndBoundSpan(APP_COMPONENT, position);
expect(result).toBeDefined();
const {textSpan, definitions} = result!;
expect(text.substring(textSpan.start, textSpan.start + textSpan.length)).toEqual(
'./test.css',
);
expect(definitions).toBeDefined();
expect(definitions!.length).toBe(1);
const [def] = definitions!;
expect(def.fileName).toContain('/app/test.css');
expect(def.textSpan).toEqual({start: 0, length: 0});
});
it('should be able to find a stylesheet from a style url', () => {
const {position, text} = service.overwrite(
APP_COMPONENT,
`
import {Component} from '@angular/core';
@Component({
template: 'empty',
styleUrl: './te¦st.css'
})
export class AppComponent {}`,
);
const result = ngLS.getDefinitionAndBoundSpan(APP_COMPONENT, position);
expect(result).toBeDefined();
const {textSpan, definitions} = result!;
expect(text.substring(textSpan.start, textSpan.start + textSpan.length)).toEqual(
'./test.css',
);
expect(definitions).toBeDefined();
expect(definitions!.length).toBe(1);
const [def] = definitions!;
expect(def.fileName).toContain('/app/test.css');
expect(def.textSpan).toEqual({start: 0, length: 0});
});
xit('should be able to find a resource url with malformed component meta', () => {
const {position, text} = service.overwrite(
APP_COMPONENT,
`
import {Component} from '@angular/core';
@Component({
invalidProperty: '',
styleUrls: ['./te¦st.css']
})
export class AppComponent {}`,
);
const result = ngLS.getDefinitionAndBoundSpan(APP_COMPONENT, position);
expect(result).toBeDefined();
const {textSpan, definitions} = result!;
expect(text.substring(textSpan.start, textSpan.start + textSpan.length)).toEqual(
'./test.css',
);
expect(definitions).toBeDefined();
expect(definitions![0].fileName).toContain('/app/test.css');
});
});
function getDefinitionsAndAssertBoundSpan({
templateOverride,
expectedSpanText,
}: {
templateOverride: string;
expectedSpanText: string;
}): Array<{textSpan: string; contextSpan: string | undefined; fileName: string}> {
const {position, text} = service.overwriteInlineTemplate(APP_COMPONENT, templateOverride);
const definitionAndBoundSpan = ngLS.getDefinitionAndBoundSpan(APP_COMPONENT, position);
expect(definitionAndBoundSpan).toBeTruthy();
const {textSpan, definitions} = definitionAndBoundSpan!;
expect(text.substring(textSpan.start, textSpan.start + textSpan.length)).toEqual(
expectedSpanText,
);
expect(definitions).toBeTruthy();
return definitions!.map((d) => humanizeDefinitionInfo(d, service));
}
});
| {
"end_byte": 23929,
"start_byte": 19806,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/definitions_spec.ts"
} |
angular/packages/language-service/test/legacy/BUILD.bazel_0_1150 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "legacy_lib",
testonly = True,
srcs = glob(["*.ts"]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/core:api",
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/language-service/src",
"//packages/language-service/src/utils",
"@npm//typescript",
],
)
jasmine_node_test(
name = "legacy",
data = [
# Note that we used to depend on the npm_package of common, core, and
# forms, but this is no longer the case. We did it for View Engine
# because we wanted to load the flat dts, which is only available in the
# npm_package. Ivy does not currently produce flat dts, so we might
# as well just depend on the outputs of ng_module.
"//packages/common",
"//packages/core",
"//packages/forms",
":project",
],
deps = [
":legacy_lib",
],
)
filegroup(
name = "project",
srcs = glob(["project/**/*"]),
visibility = ["//packages/language-service:__subpackages__"],
)
| {
"end_byte": 1150,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/BUILD.bazel"
} |
angular/packages/language-service/test/legacy/language_service_spec.ts_0_469 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ErrorCode, ngErrorCode} from '@angular/compiler-cli/src/ngtsc/diagnostics';
import ts from 'typescript';
import {LanguageService} from '../../src/language_service';
import {MockConfigFileFs, MockService, setup, TEST_TEMPLATE, TSCONFIG} from './mock_host'; | {
"end_byte": 469,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/language_service_spec.ts"
} |
angular/packages/language-service/test/legacy/language_service_spec.ts_471_8846 | describe('language service adapter', () => {
let project: ts.server.Project;
let service: MockService;
let ngLS: LanguageService;
let configFileFs: MockConfigFileFs;
beforeAll(() => {
const {project: _project, tsLS, service: _service, configFileFs: _configFileFs} = setup();
project = _project;
service = _service;
ngLS = new LanguageService(project, tsLS, {});
configFileFs = _configFileFs;
});
afterEach(() => {
configFileFs.clear();
});
describe('parse compiler options', () => {
it('should initialize with angularCompilerOptions from tsconfig.json', () => {
expect(ngLS.getCompilerOptions()).toEqual(
jasmine.objectContaining({
strictTemplates: true,
strictInjectionParameters: true,
}),
);
});
it('should reparse angularCompilerOptions on tsconfig.json change', () => {
expect(ngLS.getCompilerOptions()).toEqual(
jasmine.objectContaining({
strictTemplates: true,
strictInjectionParameters: true,
}),
);
configFileFs.overwriteConfigFile(TSCONFIG, {
angularCompilerOptions: {
strictTemplates: false,
},
});
expect(ngLS.getCompilerOptions()).toEqual(
jasmine.objectContaining({
strictTemplates: false,
}),
);
});
it('should always enable strictTemplates if forceStrictTemplates is true', () => {
const {project, tsLS, configFileFs} = setup();
const ngLS = new LanguageService(project, tsLS, {
forceStrictTemplates: true,
});
// First make sure the default for strictTemplates is true
expect(ngLS.getCompilerOptions()).toEqual(
jasmine.objectContaining({
strictTemplates: true,
strictInjectionParameters: true,
}),
);
// Change strictTemplates to false
configFileFs.overwriteConfigFile(TSCONFIG, {
angularCompilerOptions: {
strictTemplates: false,
},
});
// Make sure strictTemplates is still true because forceStrictTemplates
// is enabled.
expect(ngLS.getCompilerOptions()).toEqual(
jasmine.objectContaining({
strictTemplates: true,
}),
);
});
it('should always disable block syntax if enableBlockSyntax is false', () => {
const {project, tsLS} = setup();
const ngLS = new LanguageService(project, tsLS, {
enableBlockSyntax: false,
});
expect(ngLS.getCompilerOptions()).toEqual(
jasmine.objectContaining({
'_enableBlockSyntax': false,
}),
);
});
it('should always disable let declarations if enableLetSyntax is false', () => {
const {project, tsLS} = setup();
const ngLS = new LanguageService(project, tsLS, {
enableLetSyntax: false,
});
expect(ngLS.getCompilerOptions()).toEqual(
jasmine.objectContaining({
'_enableLetSyntax': false,
}),
);
});
it('should pass the @angular/core version along to the compiler', () => {
const {project, tsLS} = setup();
const ngLS = new LanguageService(project, tsLS, {
angularCoreVersion: '17.2.11-rc.8',
});
expect(ngLS.getCompilerOptions()).toEqual(
jasmine.objectContaining({
'_angularCoreVersion': '17.2.11-rc.8',
}),
);
});
});
describe('compiler options diagnostics', () => {
it('suggests turning on strict flag', () => {
configFileFs.overwriteConfigFile(TSCONFIG, {
angularCompilerOptions: {},
});
const diags = ngLS.getCompilerOptionsDiagnostics();
const diag = diags.find(isSuggestStrictTemplatesDiag);
expect(diag).toBeDefined();
expect(diag!.category).toBe(ts.DiagnosticCategory.Suggestion);
expect(diag!.file?.getSourceFile().fileName).toBe(TSCONFIG);
});
it('does not suggest turning on strict mode is strictTemplates flag is on', () => {
configFileFs.overwriteConfigFile(TSCONFIG, {
angularCompilerOptions: {
strictTemplates: true,
},
});
const diags = ngLS.getCompilerOptionsDiagnostics();
const diag = diags.find(isSuggestStrictTemplatesDiag);
expect(diag).toBeUndefined();
});
it('does not suggest turning on strict mode is fullTemplateTypeCheck flag is on', () => {
configFileFs.overwriteConfigFile(TSCONFIG, {
angularCompilerOptions: {
fullTemplateTypeCheck: true,
},
});
const diags = ngLS.getCompilerOptionsDiagnostics();
const diag = diags.find(isSuggestStrictTemplatesDiag);
expect(diag).toBeUndefined();
});
function isSuggestStrictTemplatesDiag(diag: ts.Diagnostic) {
return diag.code === ngErrorCode(ErrorCode.SUGGEST_STRICT_TEMPLATES);
}
});
describe('last known program', () => {
beforeEach(() => {
service.reset();
});
it('should be set after getSemanticDiagnostics()', () => {
const d0 = ngLS.getSemanticDiagnostics(TEST_TEMPLATE);
expect(d0.length).toBe(0);
const p0 = getLastKnownProgram(ngLS);
const d1 = ngLS.getSemanticDiagnostics(TEST_TEMPLATE);
expect(d1.length).toBe(0);
const p1 = getLastKnownProgram(ngLS);
expect(p1).toBe(p0); // last known program should not have changed
service.overwrite(TEST_TEMPLATE, `<test-c¦omp></test-comp>`);
const d2 = ngLS.getSemanticDiagnostics(TEST_TEMPLATE);
expect(d2.length).toBe(0);
const p2 = getLastKnownProgram(ngLS);
expect(p2).not.toBe(p1); // last known program should have changed
});
it('should be set after getDefinitionAndBoundSpan()', () => {
const {position: pos0} = service.overwrite(TEST_TEMPLATE, `<test-c¦omp></test-comp>`);
const d0 = ngLS.getDefinitionAndBoundSpan(TEST_TEMPLATE, pos0);
expect(d0).toBeDefined();
const p0 = getLastKnownProgram(ngLS);
const d1 = ngLS.getDefinitionAndBoundSpan(TEST_TEMPLATE, pos0);
expect(d1).toBeDefined();
const p1 = getLastKnownProgram(ngLS);
expect(p1).toBe(p0); // last known program should not have changed
const {position: pos1} = service.overwrite(TEST_TEMPLATE, `{{ ti¦tle }}`);
const d2 = ngLS.getDefinitionAndBoundSpan(TEST_TEMPLATE, pos1);
expect(d2).toBeDefined();
const p2 = getLastKnownProgram(ngLS);
expect(p2).not.toBe(p1); // last known program should have changed
});
it('should be set after getQuickInfoAtPosition()', () => {
const {position: pos0} = service.overwrite(TEST_TEMPLATE, `<test-c¦omp></test-comp>`);
const q0 = ngLS.getQuickInfoAtPosition(TEST_TEMPLATE, pos0);
expect(q0).toBeDefined();
const p0 = getLastKnownProgram(ngLS);
const q1 = ngLS.getQuickInfoAtPosition(TEST_TEMPLATE, pos0);
expect(q1).toBeDefined();
const p1 = getLastKnownProgram(ngLS);
expect(p1).toBe(p0); // last known program should not have changed
const {position: pos1} = service.overwrite(TEST_TEMPLATE, `{{ ti¦tle }}`);
const q2 = ngLS.getQuickInfoAtPosition(TEST_TEMPLATE, pos1);
expect(q2).toBeDefined();
const p2 = getLastKnownProgram(ngLS);
expect(p2).not.toBe(p1); // last known program should have changed
});
it('should be set after getTypeDefinitionAtPosition()', () => {
const {position: pos0} = service.overwrite(TEST_TEMPLATE, `<test-c¦omp></test-comp>`);
const q0 = ngLS.getTypeDefinitionAtPosition(TEST_TEMPLATE, pos0);
expect(q0).toBeDefined();
const p0 = getLastKnownProgram(ngLS);
const d1 = ngLS.getTypeDefinitionAtPosition(TEST_TEMPLATE, pos0);
expect(d1).toBeDefined();
const p1 = getLastKnownProgram(ngLS);
expect(p1).toBe(p0); // last known program should not have changed
const {position: pos1} = service.overwrite(TEST_TEMPLATE, `{{ ti¦tle }}`);
const d2 = ngLS.getTypeDefinitionAtPosition(TEST_TEMPLATE, pos1);
expect(d2).toBeDefined();
const p2 = getLastKnownProgram(ngLS);
expect(p2).not.toBe(p1); // last known program should have changed
});
});
});
function getLastKnownProgram(ngLS: LanguageService): ts.Program {
const program = ngLS['compilerFactory']['compiler']?.getCurrentProgram();
expect(program).toBeDefined();
return program!;
}
| {
"end_byte": 8846,
"start_byte": 471,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/language_service_spec.ts"
} |
angular/packages/language-service/test/legacy/test_utils.ts_0_874 | /**
* @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 ts from 'typescript';
import {MockService} from './mock_host';
export interface HumanizedDefinitionInfo {
fileName: string;
textSpan: string;
contextSpan: string | undefined;
}
export function humanizeDefinitionInfo(
def: ts.DefinitionInfo,
service: MockService,
): HumanizedDefinitionInfo {
const snapshot = service.getScriptInfo(def.fileName).getSnapshot();
return {
fileName: def.fileName,
textSpan: snapshot.getText(def.textSpan.start, def.textSpan.start + def.textSpan.length),
contextSpan: def.contextSpan
? snapshot.getText(def.contextSpan.start, def.contextSpan.start + def.contextSpan.length)
: undefined,
};
}
| {
"end_byte": 874,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/test_utils.ts"
} |
angular/packages/language-service/test/legacy/ts_plugin_spec.ts_0_1147 | /**
* @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 {LanguageService} from '../../src/language_service';
import {getExternalFiles} from '../../src/ts_plugin';
import {APP_COMPONENT, setup} from './mock_host';
describe('getExternalFiles()', () => {
it('should return all typecheck files', () => {
const {project, tsLS} = setup();
let externalFiles = getExternalFiles(project);
// Initially there are no external files because Ivy compiler hasn't done
// a global analysis
expect(externalFiles).toEqual([]);
// Trigger global analysis
const ngLS = new LanguageService(project, tsLS, {});
ngLS.getSemanticDiagnostics(APP_COMPONENT);
// Now that global analysis is run, we should have all the typecheck files
externalFiles = getExternalFiles(project);
// Includes 1 typecheck file, 1 template, and 1 css files
expect(externalFiles.length).toBe(3);
expect(externalFiles[0].endsWith('app.component.ngtypecheck.ts')).toBeTrue();
});
});
| {
"end_byte": 1147,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/ts_plugin_spec.ts"
} |
angular/packages/language-service/test/legacy/project/app/main.ts_0_970 | /**
* @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 {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {InnerComponent} from './#inner/component';
import {AppComponent} from './app.component';
import * as ParsingCases from './parsing-cases';
@NgModule({
imports: [CommonModule, FormsModule],
declarations: [
AppComponent,
InnerComponent,
ParsingCases.CounterDirective,
ParsingCases.HintModel,
ParsingCases.NumberModel,
ParsingCases.StringModel,
ParsingCases.TemplateReference,
ParsingCases.TestComponent,
ParsingCases.TestPipe,
ParsingCases.WithContextDirective,
ParsingCases.CompoundCustomButtonDirective,
ParsingCases.EventSelectorDirective,
],
})
export class AppModule {}
| {
"end_byte": 970,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/project/app/main.ts"
} |
angular/packages/language-service/test/legacy/project/app/test.ng_0_51 | <h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
| {
"end_byte": 51,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/project/app/test.ng"
} |
angular/packages/language-service/test/legacy/project/app/parsing-cases.ts_0_4199 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
Directive,
EventEmitter,
Input,
OnChanges,
Output,
Pipe,
PipeTransform,
SimpleChanges,
TemplateRef,
ViewContainerRef,
} from '@angular/core';
import {Hero} from './app.component';
@Directive({
selector: '[string-model]',
exportAs: 'stringModel',
standalone: false,
})
export class StringModel {
@Input() model: string = 'model';
@Output() modelChange: EventEmitter<string> = new EventEmitter();
}
@Directive({
selector: '[number-model]',
standalone: false,
})
export class NumberModel {
@Input('inputAlias') model: number = 0;
@Output('outputAlias') modelChange: EventEmitter<number> = new EventEmitter();
}
@Directive({
selector: '[hint-model]',
inputs: ['hint'],
outputs: ['hintChange'],
standalone: false,
})
export class HintModel {
hint: string = 'hint';
hintChange: EventEmitter<string> = new EventEmitter();
}
class CounterDirectiveContext<T> {
constructor(public $implicit: T) {}
}
@Directive({
selector: '[counterOf]',
standalone: false,
})
export class CounterDirective implements OnChanges {
// Object does not have an "$implicit" property.
constructor(
private container: ViewContainerRef,
private template: TemplateRef<Object>,
) {}
@Input('counterOf') counter: number = 0;
ngOnChanges(_changes: SimpleChanges) {
this.container.clear();
for (let i = 0; i < this.counter; ++i) {
this.container.createEmbeddedView(this.template, new CounterDirectiveContext(i + 1));
}
}
}
interface WithContextDirectiveContext {
$implicit: {implicitPerson: Hero};
nonImplicitPerson: Hero;
}
@Directive({
selector: '[withContext]',
standalone: false,
})
export class WithContextDirective {
constructor(_template: TemplateRef<WithContextDirectiveContext>) {}
static ngTemplateContextGuard(
dir: WithContextDirective,
ctx: unknown,
): ctx is WithContextDirectiveContext {
return true;
}
}
@Directive({
selector: 'button[custom-button][compound]',
standalone: false,
})
export class CompoundCustomButtonDirective {
@Input() config?: {color?: string};
}
@Directive({
selector: '[eventSelector]',
standalone: false,
})
export class EventSelectorDirective {
@Output() eventSelector = new EventEmitter<void>();
}
@Pipe({
name: 'prefixPipe',
standalone: false,
})
export class TestPipe implements PipeTransform {
transform(value: string, prefix: string): string;
transform(value: number, prefix: number): number;
transform(value: string | number, prefix: string | number): string | number {
if (typeof value === 'string') {
return `${prefix} ${value}`;
}
return parseInt(`${prefix}${value}`, 10 /* radix */);
}
}
/**
* This Component provides the `test-comp` selector.
*/
/*BeginTestComponent*/ @Component({
selector: 'test-comp',
template: '<div>Testing: {{name}}</div>',
standalone: false,
})
export class TestComponent {
@Input('tcName') name = 'test';
@Output('test') testEvent = new EventEmitter();
} /*EndTestComponent*/
@Component({
templateUrl: 'test.ng',
standalone: false,
})
export class TemplateReference {
/**
* This is the title of the `TemplateReference` Component.
*/
title = 'Tour of Heroes';
hero: Hero = {id: 1, name: 'Windstorm'};
heroP = Promise.resolve(this.hero);
heroes: Hero[] = [this.hero];
heroesP = Promise.resolve(this.heroes);
tupleArray: [string, Hero] = ['test', this.hero];
league: Hero[][] = [this.heroes];
heroesByName: {[name: string]: Hero} = {};
primitiveIndexType: {[name: string]: string} = {};
anyValue: any;
optional?: string;
// Use to test the `index` variable conflict between the `ngFor` and component context.
index = null;
myClick(event: any) {}
birthday = new Date();
readonlyHeroes: ReadonlyArray<Readonly<Hero>> = this.heroes;
constNames = [{name: 'name'}] as const;
private myField = 'My Field';
strOrNumber: string | number = '';
setTitle(newTitle: string) {
this.title = newTitle;
}
}
| {
"end_byte": 4199,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/project/app/parsing-cases.ts"
} |
angular/packages/language-service/test/legacy/project/app/app.component.ts_0_1539 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
export interface Address {
streetName: string;
}
/** The most heroic being. */
export interface Hero {
id: number;
name: string;
address?: Address;
}
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
`,
standalone: false,
})
export class AppComponent {
/** This is the title of the `AppComponent` Component. */
title = 'Tour of Heroes';
hero: Hero = {id: 1, name: 'Windstorm'};
private internal: string = 'internal';
heroP = Promise.resolve(this.hero);
heroes: Hero[] = [this.hero];
heroesP = Promise.resolve(this.heroes);
tupleArray: [string, Hero] = ['test', this.hero];
league: Hero[][] = [this.heroes];
heroesByName: {[name: string]: Hero} = {};
primitiveIndexType: {[name: string]: string} = {};
anyValue: any;
optional?: string;
// Use to test the `index` variable conflict between the `ngFor` and component context.
index = null;
myClick(event: any) {}
birthday = new Date();
readonlyHeroes: ReadonlyArray<Readonly<Hero>> = this.heroes;
constNames = [{name: 'name'}] as const;
private myField = 'My Field';
strOrNumber: string | number = '';
name = 'Frodo';
setTitle(newTitle: string) {
this.title = newTitle;
}
setHero(obj: Hero) {
this.hero = obj;
}
}
| {
"end_byte": 1539,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/project/app/app.component.ts"
} |
angular/packages/language-service/test/legacy/project/app/test.css_0_30 | body, html {
width: 100%;
}
| {
"end_byte": 30,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/project/app/test.css"
} |
angular/packages/language-service/test/legacy/project/app/#inner/component.ts_0_366 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
@Component({
selector: 'inner',
templateUrl: './inner.html',
standalone: false,
})
export class InnerComponent {}
| {
"end_byte": 366,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/project/app/#inner/component.ts"
} |
angular/packages/language-service/test/legacy/project/app/#inner/inner.html_0_17 | <div>Hello</div>
| {
"end_byte": 17,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/test/legacy/project/app/#inner/inner.html"
} |
angular/packages/language-service/testing/BUILD.bazel_0_663 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//packages/language-service:__subpackages__"])
ts_library(
name = "testing",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/core:api",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/compiler-cli/src/ngtsc/testing",
"//packages/compiler-cli/src/ngtsc/typecheck/api",
"//packages/language-service:api",
"//packages/language-service/src",
"@npm//typescript",
],
)
| {
"end_byte": 663,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/testing/BUILD.bazel"
} |
angular/packages/language-service/testing/index.ts_0_320 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './src/buffer';
export * from './src/env';
export * from './src/project';
export * from './src/util';
| {
"end_byte": 320,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/testing/index.ts"
} |
angular/packages/language-service/testing/src/project.ts_0_9103 | /**
* @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 {
InternalOptions,
LegacyNgcOptions,
StrictTemplateOptions,
} from '@angular/compiler-cli/src/ngtsc/core/api';
import {
absoluteFrom,
AbsoluteFsPath,
FileSystem,
getFileSystem,
getSourceFileOrError,
} from '@angular/compiler-cli/src/ngtsc/file_system';
import {OptimizeFor, TemplateTypeChecker} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
import {LanguageService} from '../../src/language_service';
import {ApplyRefactoringProgressFn, ApplyRefactoringResult} from '../../api';
import {OpenBuffer} from './buffer';
import {patchLanguageServiceProjectsWithTestHost} from './language_service_test_cache';
export type ProjectFiles = {
[fileName: string]: string;
};
function writeTsconfig(
fs: FileSystem,
tsConfigPath: AbsoluteFsPath,
entryFiles: AbsoluteFsPath[],
angularCompilerOptions: TestableOptions,
tsCompilerOptions: {},
): void {
fs.writeFile(
tsConfigPath,
JSON.stringify(
{
compilerOptions: {
strict: true,
experimentalDecorators: true,
moduleResolution: 'node',
target: 'es2015',
rootDir: '.',
lib: ['dom', 'es2015'],
...tsCompilerOptions,
},
files: entryFiles,
angularCompilerOptions: {
strictTemplates: true,
...angularCompilerOptions,
},
},
null,
2,
),
);
}
export type TestableOptions = StrictTemplateOptions &
InternalOptions &
Pick<LegacyNgcOptions, 'fullTemplateTypeCheck'>;
export class Project {
private tsProject: ts.server.Project;
private tsLS: ts.LanguageService;
readonly ngLS: LanguageService;
private buffers = new Map<string, OpenBuffer>();
static initialize(
projectName: string,
projectService: ts.server.ProjectService,
files: ProjectFiles,
angularCompilerOptions: TestableOptions = {},
tsCompilerOptions = {},
): Project {
const fs = getFileSystem();
const tsConfigPath = absoluteFrom(`/${projectName}/tsconfig.json`);
const entryFiles: AbsoluteFsPath[] = [];
for (const projectFilePath of Object.keys(files)) {
const contents = files[projectFilePath];
const filePath = absoluteFrom(`/${projectName}/${projectFilePath}`);
const dirPath = fs.dirname(filePath);
fs.ensureDir(dirPath);
fs.writeFile(filePath, contents);
if (projectFilePath.endsWith('.ts') && !projectFilePath.endsWith('.d.ts')) {
entryFiles.push(filePath);
}
}
writeTsconfig(fs, tsConfigPath, entryFiles, angularCompilerOptions, tsCompilerOptions);
patchLanguageServiceProjectsWithTestHost();
// Ensure the project is live in the ProjectService.
// This creates the `ts.Program` by configuring the project and loading it!
projectService.openClientFile(entryFiles[0]);
projectService.closeClientFile(entryFiles[0]);
return new Project(projectName, projectService, tsConfigPath);
}
private constructor(
readonly name: string,
private projectService: ts.server.ProjectService,
private tsConfigPath: AbsoluteFsPath,
) {
// LS for project
const tsProject = projectService.findProject(tsConfigPath);
if (tsProject === undefined) {
throw new Error(`Failed to create project for ${tsConfigPath}`);
}
this.tsProject = tsProject;
// The following operation forces a ts.Program to be created.
this.tsLS = tsProject.getLanguageService();
this.ngLS = new LanguageService(tsProject, this.tsLS, {});
}
openFile(projectFileName: string): OpenBuffer {
if (!this.buffers.has(projectFileName)) {
const fileName = absoluteFrom(`/${this.name}/${projectFileName}`);
let scriptInfo = this.tsProject.getScriptInfo(fileName);
this.projectService.openClientFile(
// By attempting to open the file, the compiler is going to try to parse it as
// TS which will throw an error. We pass in JSX which is more permissive.
fileName,
undefined,
fileName.endsWith('.html') ? ts.ScriptKind.JSX : ts.ScriptKind.TS,
);
scriptInfo = this.tsProject.getScriptInfo(fileName);
if (scriptInfo === undefined) {
throw new Error(
`Unable to open ScriptInfo for ${projectFileName} in project ${this.tsConfigPath}`,
);
}
this.buffers.set(
projectFileName,
new OpenBuffer(this.ngLS, this.tsProject, projectFileName, scriptInfo),
);
}
return this.buffers.get(projectFileName)!;
}
getSourceFile(projectFileName: string): ts.SourceFile | undefined {
const fileName = absoluteFrom(`/${this.name}/${projectFileName}`);
return this.tsProject.getSourceFile(this.projectService.toPath(fileName));
}
getTypeChecker(): ts.TypeChecker {
return this.ngLS.compilerFactory.getOrCreate().getCurrentProgram().getTypeChecker();
}
getDiagnosticsForFile(projectFileName: string): ts.Diagnostic[] {
const fileName = absoluteFrom(`/${this.name}/${projectFileName}`);
const diagnostics: ts.Diagnostic[] = [];
if (fileName.endsWith('.ts')) {
diagnostics.push(...this.tsLS.getSyntacticDiagnostics(fileName));
diagnostics.push(...this.tsLS.getSemanticDiagnostics(fileName));
}
diagnostics.push(...this.ngLS.getSemanticDiagnostics(fileName));
return diagnostics;
}
getCodeFixesAtPosition(
projectFileName: string,
start: number,
end: number,
errorCodes: readonly number[],
): readonly ts.CodeFixAction[] {
const fileName = absoluteFrom(`/${this.name}/${projectFileName}`);
return this.ngLS.getCodeFixesAtPosition(fileName, start, end, errorCodes, {}, {});
}
getRefactoringsAtPosition(
projectFileName: string,
positionOrRange: number | ts.TextRange,
): readonly ts.ApplicableRefactorInfo[] {
const fileName = absoluteFrom(`/${this.name}/${projectFileName}`);
return this.ngLS.getPossibleRefactorings(fileName, positionOrRange);
}
applyRefactoring(
projectFileName: string,
positionOrRange: number | ts.TextRange,
refactorName: string,
reportProgress: ApplyRefactoringProgressFn,
): Promise<ApplyRefactoringResult | undefined> {
const fileName = absoluteFrom(`/${this.name}/${projectFileName}`);
return this.ngLS.applyRefactoring(fileName, positionOrRange, refactorName, reportProgress);
}
getCombinedCodeFix(projectFileName: string, fixId: string): ts.CombinedCodeActions {
const fileName = absoluteFrom(`/${this.name}/${projectFileName}`);
return this.ngLS.getCombinedCodeFix(
{
type: 'file',
fileName,
},
fixId,
{},
{},
);
}
expectNoSourceDiagnostics(): void {
const program = this.tsLS.getProgram();
if (program === undefined) {
throw new Error(`Expected to get a ts.Program`);
}
const ngCompiler = this.ngLS.compilerFactory.getOrCreate();
for (const sf of program.getSourceFiles()) {
if (
sf.isDeclarationFile ||
sf.fileName.endsWith('.ngtypecheck.ts') ||
!sf.fileName.endsWith('.ts')
) {
continue;
}
const syntactic = program.getSyntacticDiagnostics(sf);
expect(syntactic.map((diag) => diag.messageText)).toEqual([]);
if (syntactic.length > 0) {
continue;
}
const semantic = program.getSemanticDiagnostics(sf);
expect(semantic.map((diag) => diag.messageText)).toEqual([]);
if (semantic.length > 0) {
continue;
}
// It's more efficient to optimize for WholeProgram since we call this with every file in the
// program.
const ngDiagnostics = ngCompiler.getDiagnosticsForFile(sf, OptimizeFor.WholeProgram);
expect(ngDiagnostics.map((diag) => diag.messageText)).toEqual([]);
}
}
expectNoTemplateDiagnostics(projectFileName: string, className: string): void {
const program = this.tsLS.getProgram();
if (program === undefined) {
throw new Error(`Expected to get a ts.Program`);
}
const fileName = absoluteFrom(`/${this.name}/${projectFileName}`);
const sf = getSourceFileOrError(program, fileName);
const component = getClassOrError(sf, className);
const diags = this.getTemplateTypeChecker().getDiagnosticsForComponent(component);
expect(diags.map((diag) => diag.messageText)).toEqual([]);
}
getTemplateTypeChecker(): TemplateTypeChecker {
return this.ngLS.compilerFactory.getOrCreate().getTemplateTypeChecker();
}
getLogger(): ts.server.Logger {
return this.tsProject.projectService.logger;
}
}
function getClassOrError(sf: ts.SourceFile, name: string): ts.ClassDeclaration {
for (const stmt of sf.statements) {
if (ts.isClassDeclaration(stmt) && stmt.name !== undefined && stmt.name.text === name) {
return stmt;
}
}
throw new Error(`Class ${name} not found in file: ${sf.fileName}: ${sf.text}`);
}
| {
"end_byte": 9103,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/testing/src/project.ts"
} |
angular/packages/language-service/testing/src/buffer.ts_0_4857 | /**
* @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 ts from 'typescript';
import {LanguageService} from '../../src/language_service';
/**
* A file that is currently open in the `ts.Project`, with a cursor position.
*/
export class OpenBuffer {
private _cursor: number = 0;
constructor(
private ngLS: LanguageService,
private project: ts.server.Project,
private projectFileName: string,
private scriptInfo: ts.server.ScriptInfo,
) {}
get cursor(): number {
return this._cursor;
}
get contents(): string {
const snapshot = this.scriptInfo.getSnapshot();
return snapshot.getText(0, snapshot.getLength());
}
set contents(newContents: string) {
const snapshot = this.scriptInfo.getSnapshot();
this.scriptInfo.editContent(0, snapshot.getLength(), newContents);
// As of TypeScript 5.2 we need to trigger graph update manually in order to satisfy the
// following assertion:
// https://github.com/microsoft/TypeScript/commit/baf872cba4eb3fbc5e5914385ce534902ae13639#diff-fad6af6557c1406192e30af30e0113a5eb327d60f9e2588bdce6667d619ebd04R1503
this.project.updateGraph();
// If the cursor goes beyond the new length of the buffer, clamp it to the end of the buffer.
if (this._cursor > newContents.length) {
this._cursor = newContents.length;
}
}
/**
* Find a snippet of text within the given buffer and position the cursor within it.
*
* @param snippetWithCursor a snippet of text which contains the '¦' symbol, representing where
* the cursor should be placed within the snippet when located in the larger buffer.
*/
moveCursorToText(snippetWithCursor: string): void {
const {text: snippet, cursor} = extractCursorInfo(snippetWithCursor);
const snippetIndex = this.contents.indexOf(snippet);
if (snippetIndex === -1) {
throw new Error(`Snippet '${snippet}' not found in ${this.projectFileName}`);
}
if (this.contents.indexOf(snippet, snippetIndex + 1) !== -1) {
throw new Error(`Snippet '${snippet}' is not unique within ${this.projectFileName}`);
}
this._cursor = snippetIndex + cursor;
}
/**
* Execute the `getDefinitionAndBoundSpan` operation in the Language Service at the cursor
* location in this buffer.
*/
getDefinitionAndBoundSpan(): ts.DefinitionInfoAndBoundSpan | undefined {
return this.ngLS.getDefinitionAndBoundSpan(this.scriptInfo.fileName, this._cursor);
}
getCompletionsAtPosition(
options?: ts.GetCompletionsAtPositionOptions,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
return this.ngLS.getCompletionsAtPosition(this.scriptInfo.fileName, this._cursor, options);
}
getCompletionEntryDetails(
entryName: string,
formatOptions?: ts.FormatCodeOptions | ts.FormatCodeSettings,
preferences?: ts.UserPreferences,
data?: ts.CompletionEntryData,
): ts.CompletionEntryDetails | undefined {
return this.ngLS.getCompletionEntryDetails(
this.scriptInfo.fileName,
this._cursor,
entryName,
formatOptions,
preferences,
data,
);
}
getTcb() {
return this.ngLS.getTcb(this.scriptInfo.fileName, this._cursor);
}
getOutliningSpans() {
return this.ngLS.getOutliningSpans(this.scriptInfo.fileName);
}
getTemplateLocationForComponent() {
return this.ngLS.getTemplateLocationForComponent(this.scriptInfo.fileName, this._cursor);
}
getQuickInfoAtPosition() {
return this.ngLS.getQuickInfoAtPosition(this.scriptInfo.fileName, this._cursor);
}
getTypeDefinitionAtPosition() {
return this.ngLS.getTypeDefinitionAtPosition(this.scriptInfo.fileName, this._cursor);
}
getReferencesAtPosition() {
return this.ngLS.getReferencesAtPosition(this.scriptInfo.fileName, this._cursor);
}
findRenameLocations() {
return this.ngLS.findRenameLocations(this.scriptInfo.fileName, this._cursor);
}
getRenameInfo() {
return this.ngLS.getRenameInfo(this.scriptInfo.fileName, this._cursor);
}
getSignatureHelpItems() {
return this.ngLS.getSignatureHelpItems(this.scriptInfo.fileName, this._cursor);
}
}
/**
* Given a text snippet which contains exactly one cursor symbol ('¦'), extract both the offset of
* that cursor within the text as well as the text snippet without the cursor.
*/
function extractCursorInfo(textWithCursor: string): {cursor: number; text: string} {
const cursor = textWithCursor.indexOf('¦');
if (cursor === -1 || textWithCursor.indexOf('¦', cursor + 1) !== -1) {
throw new Error(`Expected to find exactly one cursor symbol '¦'`);
}
return {
cursor,
text: textWithCursor.slice(0, cursor) + textWithCursor.slice(cursor + 1),
};
}
| {
"end_byte": 4857,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/testing/src/buffer.ts"
} |
angular/packages/language-service/testing/src/language_service_test_cache.ts_0_2015 | /**
* @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 {getCachedSourceFile} from '@angular/compiler-cli/src/ngtsc/testing';
import ts from 'typescript';
interface TsProjectWithInternals {
// typescript/src/server/project.ts#ConfiguredProject
setCompilerHost?(host: ts.CompilerHost): void;
}
let patchedLanguageServiceProjectHost = false;
/**
* Updates `ts.server.Project` to use efficient test caching of source files
* that aren't expected to be changed. E.g. the default libs.
*/
export function patchLanguageServiceProjectsWithTestHost() {
if (patchedLanguageServiceProjectHost) {
return;
}
patchedLanguageServiceProjectHost = true;
(ts.server.Project.prototype as TsProjectWithInternals).setCompilerHost = (host) => {
const _originalHostGetSourceFile = host.getSourceFile;
const _originalHostGetSourceFileByPath = host.getSourceFileByPath;
host.getSourceFile = (
fileName,
languageVersionOrOptions,
onError,
shouldCreateNewSourceFile,
) => {
return (
getCachedSourceFile(fileName, () => host.readFile(fileName)) ??
_originalHostGetSourceFile.call(
host,
fileName,
languageVersionOrOptions,
onError,
shouldCreateNewSourceFile,
)
);
};
if (_originalHostGetSourceFileByPath !== undefined) {
host.getSourceFileByPath = (
fileName,
path,
languageVersionOrOptions,
onError,
shouldCreateNewSourceFile,
) => {
return (
getCachedSourceFile(fileName, () => host.readFile(fileName)) ??
_originalHostGetSourceFileByPath.call(
host,
fileName,
path,
languageVersionOrOptions,
onError,
shouldCreateNewSourceFile,
)
);
};
}
};
}
| {
"end_byte": 2015,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/testing/src/language_service_test_cache.ts"
} |
angular/packages/language-service/testing/src/util.ts_0_4020 | /**
* @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 ts from 'typescript';
import {LanguageServiceTestEnv} from './env';
import {Project, ProjectFiles, TestableOptions} from './project';
/**
* Expect that a list of objects with a `fileName` property matches a set of expected files by only
* comparing the file names and not any path prefixes.
*
* This assertion is independent of the order of either list.
*/
export function assertFileNames(refs: Array<{fileName: string}>, expectedFileNames: string[]) {
const actualPaths = refs.map((r) => r.fileName);
const actualFileNames = actualPaths.map((p) => last(p.split('/')));
expect(new Set(actualFileNames)).toEqual(new Set(expectedFileNames));
}
export function assertTextSpans(items: Array<{textSpan: string}>, expectedTextSpans: string[]) {
const actualSpans = items.map((item) => item.textSpan);
expect(new Set(actualSpans)).toEqual(new Set(expectedTextSpans));
}
/**
* Returns whether the given `ts.Diagnostic` is of a type only produced by the Angular compiler (as
* opposed to being an upstream TypeScript diagnostic).
*
* Template type-checking diagnostics are not "ng-specific" in this sense, since they are plain
* TypeScript diagnostics that are produced from expressions in the template by way of a TCB.
*/
export function isNgSpecificDiagnostic(diag: ts.Diagnostic): boolean {
// Angular-specific diagnostics use a negative code space.
return diag.code < 0;
}
function getFirstClassDeclaration(declaration: string) {
const matches = declaration.match(/(?:export class )(\w+)(?:\s|\{|<)/);
if (matches === null || matches.length !== 2) {
throw new Error(`Did not find exactly one exported class in: ${declaration}`);
}
return matches[1].trim();
}
export function createModuleAndProjectWithDeclarations(
env: LanguageServiceTestEnv,
projectName: string,
projectFiles: ProjectFiles,
angularCompilerOptions: TestableOptions = {},
standaloneFiles: ProjectFiles = {},
): Project {
const externalClasses: string[] = [];
const externalImports: string[] = [];
for (const [fileName, fileContents] of Object.entries(projectFiles)) {
if (!fileName.endsWith('.ts')) {
continue;
}
const className = getFirstClassDeclaration(fileContents);
externalClasses.push(className);
externalImports.push(`import {${className}} from './${fileName.replace('.ts', '')}';`);
}
const moduleContents = `
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
${externalImports.join('\n')}
@NgModule({
declarations: [${externalClasses.join(',')}],
imports: [CommonModule],
})
export class AppModule {}
`;
projectFiles['app-module.ts'] = moduleContents;
return env.addProject(projectName, {...projectFiles, ...standaloneFiles}, angularCompilerOptions);
}
export function humanizeDocumentSpanLike<T extends ts.DocumentSpan>(
item: T,
env: LanguageServiceTestEnv,
): T & Stringy<ts.DocumentSpan> {
return {
...item,
textSpan: env.getTextFromTsSpan(item.fileName, item.textSpan),
contextSpan: item.contextSpan
? env.getTextFromTsSpan(item.fileName, item.contextSpan)
: undefined,
originalTextSpan: item.originalTextSpan
? env.getTextFromTsSpan(item.fileName, item.originalTextSpan)
: undefined,
originalContextSpan: item.originalContextSpan
? env.getTextFromTsSpan(item.fileName, item.originalContextSpan)
: undefined,
};
}
type Stringy<T> = {
[P in keyof T]: string;
};
export function getText(contents: string, textSpan: ts.TextSpan) {
return contents.slice(textSpan.start, textSpan.start + textSpan.length);
}
function last<T>(array: T[]): T {
if (array.length === 0) {
throw new Error(`last() called on empty array`);
}
return array[array.length - 1];
}
| {
"end_byte": 4020,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/testing/src/util.ts"
} |
angular/packages/language-service/testing/src/host.ts_0_3242 | /**
* @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 {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system';
import {MockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import ts from 'typescript';
const NOOP_FILE_WATCHER: ts.FileWatcher = {
close() {},
};
export class MockServerHost implements ts.server.ServerHost {
constructor(private fs: MockFileSystem) {}
get newLine(): string {
return '\n';
}
get useCaseSensitiveFileNames(): boolean {
return this.fs.isCaseSensitive();
}
readFile(path: string, encoding?: string): string | undefined {
return this.fs.readFile(absoluteFrom(path));
}
resolvePath(path: string): string {
return this.fs.resolve(path);
}
fileExists(path: string): boolean {
const absPath = absoluteFrom(path);
return this.fs.exists(absPath) && this.fs.lstat(absPath).isFile();
}
directoryExists(path: string): boolean {
const absPath = absoluteFrom(path);
return this.fs.exists(absPath) && this.fs.lstat(absPath).isDirectory();
}
createDirectory(path: string): void {
this.fs.ensureDir(absoluteFrom(path));
}
getExecutingFilePath(): string {
// This is load-bearing, as TypeScript uses the result of this call to locate the directory in
// which it expects to find .d.ts files for the "standard libraries" - DOM, ES2015, etc.
return '/node_modules/typescript/lib/tsserver.js';
}
getCurrentDirectory(): string {
return '/';
}
createHash(data: string): string {
return ts.sys.createHash!(data);
}
get args(): string[] {
throw new Error('Property not implemented.');
}
watchFile(
path: string,
callback: ts.FileWatcherCallback,
pollingInterval?: number,
options?: ts.WatchOptions,
): ts.FileWatcher {
return NOOP_FILE_WATCHER;
}
watchDirectory(
path: string,
callback: ts.DirectoryWatcherCallback,
recursive?: boolean,
options?: ts.WatchOptions,
): ts.FileWatcher {
return NOOP_FILE_WATCHER;
}
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]) {
throw new Error('Method not implemented.');
}
clearTimeout(timeoutId: any): void {
throw new Error('Method not implemented.');
}
setImmediate(callback: (...args: any[]) => void, ...args: any[]) {
throw new Error('Method not implemented.');
}
clearImmediate(timeoutId: any): void {
throw new Error('Method not implemented.');
}
write(s: string): void {
throw new Error('Method not implemented.');
}
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void {
throw new Error('Method not implemented.');
}
getDirectories(path: string): string[] {
throw new Error('Method not implemented.');
}
readDirectory(
path: string,
extensions?: readonly string[],
exclude?: readonly string[],
include?: readonly string[],
depth?: number,
): string[] {
throw new Error('Method not implemented.');
}
exit(exitCode?: number): void {
throw new Error('Method not implemented.');
}
}
| {
"end_byte": 3242,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/testing/src/host.ts"
} |
angular/packages/language-service/testing/src/env.ts_0_3007 | /**
* @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 {getFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system';
import {MockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import ts from 'typescript';
import {MockServerHost} from './host';
import {Project, ProjectFiles, TestableOptions} from './project';
/**
* Testing environment for the Angular Language Service, which creates an in-memory tsserver
* instance that backs a Language Service to emulate an IDE that uses the LS.
*/
export class LanguageServiceTestEnv {
static setup(): LanguageServiceTestEnv {
const fs = getFileSystem();
if (!(fs instanceof MockFileSystem)) {
throw new Error(`LanguageServiceTestEnvironment only works with a mock filesystem`);
}
fs.init(
loadStandardTestFiles({
fakeCommon: true,
rxjs: true,
}),
);
const host = new MockServerHost(fs);
const projectService = new ts.server.ProjectService({
logger,
cancellationToken: ts.server.nullCancellationToken,
host,
typingsInstaller: ts.server.nullTypingsInstaller,
session: undefined,
useInferredProjectPerProjectRoot: true,
useSingleInferredProject: true,
});
return new LanguageServiceTestEnv(host, projectService);
}
private projects = new Map<string, Project>();
constructor(
private host: MockServerHost,
private projectService: ts.server.ProjectService,
) {}
addProject(
name: string,
files: ProjectFiles,
angularCompilerOptions: TestableOptions = {},
tsCompilerOptions = {},
): Project {
if (this.projects.has(name)) {
throw new Error(`Project ${name} is already defined`);
}
const project = Project.initialize(
name,
this.projectService,
files,
angularCompilerOptions,
tsCompilerOptions,
);
this.projects.set(name, project);
return project;
}
getTextFromTsSpan(fileName: string, span: ts.TextSpan): string | null {
const scriptInfo = this.projectService.getScriptInfo(fileName);
if (scriptInfo === undefined) {
return null;
}
return scriptInfo.getSnapshot().getText(span.start, span.start + span.length);
}
expectNoSourceDiagnostics(): void {
for (const project of this.projects.values()) {
project.expectNoSourceDiagnostics();
}
}
}
const logger: ts.server.Logger = {
close(): void {},
hasLevel(level: ts.server.LogLevel): boolean {
return false;
},
loggingEnabled(): boolean {
return false;
},
perftrc(s: string): void {},
info(s: string): void {},
startGroup(): void {},
endGroup(): void {},
msg(s: string, type?: ts.server.Msg): void {},
getLogFileName(): string | undefined {
return;
},
};
| {
"end_byte": 3007,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/testing/src/env.ts"
} |
angular/packages/language-service/bundles/rollup.config.js_0_1443 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
const {nodeResolve} = require('@rollup/plugin-node-resolve');
const commonJs = require('@rollup/plugin-commonjs');
// This is a custom AMD file header that patches the AMD `define` call generated
// by rollup so that the bundle exposes a CJS-exported function which takes an
// instance of the TypeScript module. More details in `/language-service/index.ts`.
const amdFileHeader = `
/**
* @license Angular v0.0.0-PLACEHOLDER
* Copyright Google LLC All Rights Reserved.
* License: MIT
*/
let $deferred;
function define(modules, callback) {
$deferred = {modules, callback};
}
module.exports = function(provided) {
const ts = provided['typescript'];
if (!ts) {
throw new Error('Caller does not provide typescript module');
}
const results = {};
const resolvedModules = $deferred.modules.map(m => {
if (m === 'exports') {
return results;
}
if (m === 'typescript') {
return ts;
}
return require(m);
});
$deferred.callback(...resolvedModules);
return results;
};
`;
const external = ['os', 'fs', 'path', 'typescript'];
const config = {
external,
plugins: [nodeResolve({preferBuiltins: true}), commonJs()],
output: {
banner: amdFileHeader,
},
};
module.exports = config;
| {
"end_byte": 1443,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/bundles/rollup.config.js"
} |
angular/packages/language-service/bundles/BUILD.bazel_0_454 | load("@npm//@bazel/rollup:index.bzl", "rollup_bundle")
rollup_bundle(
name = "language-service",
config_file = "rollup.config.js",
entry_point = "//packages/language-service/src:ts_plugin.ts",
format = "amd",
silent = True,
visibility = ["//packages/language-service:__pkg__"],
deps = [
"//packages/language-service/src",
"@npm//@rollup/plugin-commonjs",
"@npm//@rollup/plugin-node-resolve",
],
)
| {
"end_byte": 454,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/bundles/BUILD.bazel"
} |
angular/packages/language-service/src/adapters.ts_0_7019 | /**
* @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
*/
/** @fileoverview provides adapters for communicating with the ng compiler */
import {ConfigurationHost} from '@angular/compiler-cli';
import {NgCompilerAdapter} from '@angular/compiler-cli/src/ngtsc/core/api';
import {
AbsoluteFsPath,
FileStats,
PathSegment,
PathString,
} from '@angular/compiler-cli/src/ngtsc/file_system';
import {isShim} from '@angular/compiler-cli/src/ngtsc/shims';
import {getRootDirs} from '@angular/compiler-cli/src/ngtsc/util/src/typescript';
import * as p from 'path';
import ts from 'typescript';
import {isTypeScriptFile} from './utils';
const PRE_COMPILED_STYLE_EXTENSIONS = ['.scss', '.sass', '.less', '.styl'];
export class LanguageServiceAdapter implements NgCompilerAdapter {
readonly entryPoint = null;
readonly constructionDiagnostics: ts.Diagnostic[] = [];
readonly ignoreForEmit: Set<ts.SourceFile> = new Set();
readonly unifiedModulesHost = null; // only used in Bazel
readonly rootDirs: AbsoluteFsPath[];
/**
* Map of resource filenames to the version of the file last read via `readResource`.
*
* Used to implement `getModifiedResourceFiles`.
*/
private readonly lastReadResourceVersion = new Map<string, string>();
constructor(private readonly project: ts.server.Project) {
this.rootDirs = getRootDirs(this, project.getCompilationSettings());
}
resourceNameToFileName(
url: string,
fromFile: string,
fallbackResolve?: (url: string, fromFile: string) => string | null,
): string | null {
// If we are trying to resolve a `.css` file, see if we can find a pre-compiled file with the
// same name instead. That way, we can provide go-to-definition for the pre-compiled files which
// would generally be the desired behavior.
if (url.endsWith('.css')) {
const styleUrl = p.resolve(fromFile, '..', url);
for (const ext of PRE_COMPILED_STYLE_EXTENSIONS) {
const precompiledFileUrl = styleUrl.replace(/\.css$/, ext);
if (this.fileExists(precompiledFileUrl)) {
return precompiledFileUrl;
}
}
}
return fallbackResolve?.(url, fromFile) ?? null;
}
isShim(sf: ts.SourceFile): boolean {
return isShim(sf);
}
isResource(sf: ts.SourceFile): boolean {
const scriptInfo = this.project.getScriptInfo(sf.fileName);
return scriptInfo?.scriptKind === ts.ScriptKind.Unknown;
}
fileExists(fileName: string): boolean {
return this.project.fileExists(fileName);
}
readFile(fileName: string): string | undefined {
return this.project.readFile(fileName);
}
getCurrentDirectory(): string {
return this.project.getCurrentDirectory();
}
getCanonicalFileName(fileName: string): string {
return this.project.projectService.toCanonicalFileName(fileName);
}
/**
* Return the real path of a symlink. This method is required in order to
* resolve symlinks in node_modules.
*/
realpath(path: string): string {
return this.project.realpath?.(path) ?? path;
}
/**
* readResource() is an Angular-specific method for reading files that are not
* managed by the TS compiler host, namely templates and stylesheets.
* It is a method on ExtendedTsCompilerHost, see
* packages/compiler-cli/src/ngtsc/core/api/src/interfaces.ts
*/
readResource(fileName: string): string {
if (isTypeScriptFile(fileName)) {
throw new Error(`readResource() should not be called on TS file: ${fileName}`);
}
// Calling getScriptSnapshot() will actually create a ScriptInfo if it does
// not exist! The same applies for getScriptVersion().
// getScriptInfo() will not create one if it does not exist.
// In this case, we *want* a script info to be created so that we could
// keep track of its version.
const version = this.project.getScriptVersion(fileName);
this.lastReadResourceVersion.set(fileName, version);
const scriptInfo = this.project.getScriptInfo(fileName);
if (!scriptInfo) {
// // This should not happen because it would have failed already at `getScriptVersion`.
throw new Error(`Failed to get script info when trying to read ${fileName}`);
}
// Add external resources as root files to the project since we project language service
// features for them (this is currently only the case for HTML files, but we could investigate
// css file features in the future). This prevents the project from being closed when navigating
// away from a resource file.
if (!this.project.isRoot(scriptInfo)) {
this.project.addRoot(scriptInfo);
}
const snapshot = scriptInfo.getSnapshot();
return snapshot.getText(0, snapshot.getLength());
}
getModifiedResourceFiles(): Set<string> | undefined {
const modifiedFiles = new Set<string>();
for (const [fileName, oldVersion] of this.lastReadResourceVersion) {
if (this.project.getScriptVersion(fileName) !== oldVersion) {
modifiedFiles.add(fileName);
}
}
return modifiedFiles.size > 0 ? modifiedFiles : undefined;
}
}
/**
* Used to read configuration files.
*
* A language service parse configuration host is independent of the adapter
* because signatures of calls like `FileSystem#readFile` are a bit stricter
* than those on the adapter.
*/
export class LSParseConfigHost implements ConfigurationHost {
constructor(private readonly serverHost: ts.server.ServerHost) {}
exists(path: AbsoluteFsPath): boolean {
return this.serverHost.fileExists(path) || this.serverHost.directoryExists(path);
}
readFile(path: AbsoluteFsPath): string {
const content = this.serverHost.readFile(path);
if (content === undefined) {
throw new Error(`LanguageServiceFS#readFile called on unavailable file ${path}`);
}
return content;
}
lstat(path: AbsoluteFsPath): FileStats {
return {
isFile: () => {
return this.serverHost.fileExists(path);
},
isDirectory: () => {
return this.serverHost.directoryExists(path);
},
isSymbolicLink: () => {
throw new Error(`LanguageServiceFS#lstat#isSymbolicLink not implemented`);
},
};
}
readdir(path: AbsoluteFsPath): PathSegment[] {
return this.serverHost.readDirectory(
path,
undefined,
undefined,
undefined,
/* depth */ 1,
) as PathSegment[];
}
pwd(): AbsoluteFsPath {
return this.serverHost.getCurrentDirectory() as AbsoluteFsPath;
}
extname(path: AbsoluteFsPath | PathSegment): string {
return p.extname(path);
}
resolve(...paths: string[]): AbsoluteFsPath {
return p.resolve(...paths) as AbsoluteFsPath;
}
dirname<T extends PathString>(file: T): T {
return p.dirname(file) as T;
}
join<T extends PathString>(basePath: T, ...paths: string[]): T {
return p.join(basePath, ...paths) as T;
}
}
| {
"end_byte": 7019,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/adapters.ts"
} |
angular/packages/language-service/src/compiler_factory.ts_0_3204 | /**
* @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 {
CompilationTicket,
freshCompilationTicket,
incrementalFromCompilerTicket,
NgCompiler,
resourceChangeTicket,
} from '@angular/compiler-cli/src/ngtsc/core';
import {NgCompilerOptions} from '@angular/compiler-cli/src/ngtsc/core/api';
import {AbsoluteFsPath, resolve} from '@angular/compiler-cli/src/ngtsc/file_system';
import {TrackedIncrementalBuildStrategy} from '@angular/compiler-cli/src/ngtsc/incremental';
import {ProgramDriver} from '@angular/compiler-cli/src/ngtsc/program_driver';
import {LanguageServiceAdapter} from './adapters';
/**
* Manages the `NgCompiler` instance which backs the language service, updating or replacing it as
* needed to produce an up-to-date understanding of the current program.
*
* TODO(alxhub): currently the options used for the compiler are specified at `CompilerFactory`
* construction, and are not changeable. In a real project, users can update `tsconfig.json`. We
* need to properly handle a change in the compiler options, either by having an API to update the
* `CompilerFactory` to use new options, or by replacing it entirely.
*/
export class CompilerFactory {
private readonly incrementalStrategy = new TrackedIncrementalBuildStrategy();
private compiler: NgCompiler | null = null;
constructor(
private readonly adapter: LanguageServiceAdapter,
private readonly programStrategy: ProgramDriver,
private readonly options: NgCompilerOptions,
) {}
getOrCreate(): NgCompiler {
const program = this.programStrategy.getProgram();
const modifiedResourceFiles = new Set<AbsoluteFsPath>();
for (const fileName of this.adapter.getModifiedResourceFiles() ?? []) {
modifiedResourceFiles.add(resolve(fileName));
}
if (this.compiler !== null && program === this.compiler.getCurrentProgram()) {
if (modifiedResourceFiles.size > 0) {
// Only resource files have changed since the last NgCompiler was created.
const ticket = resourceChangeTicket(this.compiler, modifiedResourceFiles);
this.compiler = NgCompiler.fromTicket(ticket, this.adapter);
} else {
// The previous NgCompiler is being reused, but we still want to reset its performance
// tracker to capture only the operations that are needed to service the current request.
this.compiler.perfRecorder.reset();
}
return this.compiler;
}
let ticket: CompilationTicket;
if (this.compiler === null) {
ticket = freshCompilationTicket(
program,
this.options,
this.incrementalStrategy,
this.programStrategy,
/* perfRecorder */ null,
true,
true,
);
} else {
ticket = incrementalFromCompilerTicket(
this.compiler,
program,
this.incrementalStrategy,
this.programStrategy,
modifiedResourceFiles,
/* perfRecorder */ null,
);
}
this.compiler = NgCompiler.fromTicket(ticket, this.adapter);
return this.compiler;
}
}
| {
"end_byte": 3204,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/compiler_factory.ts"
} |
angular/packages/language-service/src/quick_info.ts_0_8685 | /**
* @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 {
AST,
TmplAstBlockNode,
TmplAstBoundAttribute,
TmplAstDeferredTrigger,
TmplAstNode,
TmplAstTextAttribute,
} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {
DirectiveSymbol,
DomBindingSymbol,
ElementSymbol,
InputBindingSymbol,
LetDeclarationSymbol,
OutputBindingSymbol,
PipeSymbol,
ReferenceSymbol,
Symbol,
SymbolKind,
TcbLocation,
VariableSymbol,
} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
import {DisplayInfoKind, SYMBOL_PUNC, SYMBOL_SPACE, SYMBOL_TEXT} from './utils/display_parts';
import {
createDollarAnyQuickInfo,
createNgTemplateQuickInfo,
createQuickInfoForBuiltIn,
isDollarAny,
} from './quick_info_built_ins';
import {TemplateTarget} from './template_target';
import {
createQuickInfo,
filterAliasImports,
getDirectiveMatchesForAttribute,
getDirectiveMatchesForElementTag,
getTextSpanOfNode,
} from './utils';
export class QuickInfoBuilder {
private readonly typeChecker: ts.TypeChecker;
private readonly parent: TmplAstNode | AST | null;
constructor(
private readonly tsLS: ts.LanguageService,
private readonly compiler: NgCompiler,
private readonly component: ts.ClassDeclaration,
private node: TmplAstNode | AST,
private readonly positionDetails: TemplateTarget,
) {
this.typeChecker = this.compiler.getCurrentProgram().getTypeChecker();
this.parent = this.positionDetails.parent;
}
get(): ts.QuickInfo | undefined {
if (this.node instanceof TmplAstDeferredTrigger || this.node instanceof TmplAstBlockNode) {
return createQuickInfoForBuiltIn(this.node, this.positionDetails.position);
}
const symbol = this.compiler
.getTemplateTypeChecker()
.getSymbolOfNode(this.node, this.component);
if (symbol !== null) {
return this.getQuickInfoForSymbol(symbol);
}
if (isDollarAny(this.node)) {
return createDollarAnyQuickInfo(this.node);
}
// If the cursor lands on the receiver of a method call, we have to look
// at the entire call in order to figure out if it's a call to `$any`.
if (this.parent !== null && isDollarAny(this.parent) && this.parent.receiver === this.node) {
return createDollarAnyQuickInfo(this.parent);
}
return undefined;
}
private getQuickInfoForSymbol(symbol: Symbol): ts.QuickInfo | undefined {
switch (symbol.kind) {
case SymbolKind.Input:
case SymbolKind.Output:
return this.getQuickInfoForBindingSymbol(symbol);
case SymbolKind.Template:
return createNgTemplateQuickInfo(this.node);
case SymbolKind.Element:
return this.getQuickInfoForElementSymbol(symbol);
case SymbolKind.Variable:
return this.getQuickInfoForVariableSymbol(symbol);
case SymbolKind.LetDeclaration:
return this.getQuickInfoForLetDeclarationSymbol(symbol);
case SymbolKind.Reference:
return this.getQuickInfoForReferenceSymbol(symbol);
case SymbolKind.DomBinding:
return this.getQuickInfoForDomBinding(symbol);
case SymbolKind.Directive:
return this.getQuickInfoAtTcbLocation(symbol.tcbLocation);
case SymbolKind.Pipe:
return this.getQuickInfoForPipeSymbol(symbol);
case SymbolKind.Expression:
return this.getQuickInfoAtTcbLocation(symbol.tcbLocation);
}
}
private getQuickInfoForBindingSymbol(
symbol: InputBindingSymbol | OutputBindingSymbol,
): ts.QuickInfo | undefined {
if (symbol.bindings.length === 0) {
return undefined;
}
const kind =
symbol.kind === SymbolKind.Input ? DisplayInfoKind.PROPERTY : DisplayInfoKind.EVENT;
const quickInfo = this.getQuickInfoAtTcbLocation(symbol.bindings[0].tcbLocation);
return quickInfo === undefined ? undefined : updateQuickInfoKind(quickInfo, kind);
}
private getQuickInfoForElementSymbol(symbol: ElementSymbol): ts.QuickInfo {
const {templateNode} = symbol;
const matches = getDirectiveMatchesForElementTag(templateNode, symbol.directives);
const directiveSymbol = matches.size > 0 ? matches.values().next().value : null;
if (directiveSymbol) {
return this.getQuickInfoForDirectiveSymbol(directiveSymbol, templateNode);
}
return createQuickInfo(
templateNode.name,
DisplayInfoKind.ELEMENT,
getTextSpanOfNode(templateNode),
undefined /* containerName */,
this.typeChecker.typeToString(symbol.tsType),
);
}
private getQuickInfoForVariableSymbol(symbol: VariableSymbol): ts.QuickInfo {
const documentation = this.getDocumentationFromTypeDefAtLocation(symbol.initializerLocation);
return createQuickInfo(
symbol.declaration.name,
DisplayInfoKind.VARIABLE,
getTextSpanOfNode(this.node),
undefined /* containerName */,
this.typeChecker.typeToString(symbol.tsType),
documentation,
);
}
private getQuickInfoForLetDeclarationSymbol(symbol: LetDeclarationSymbol): ts.QuickInfo {
const documentation = this.getDocumentationFromTypeDefAtLocation(symbol.initializerLocation);
return createQuickInfo(
symbol.declaration.name,
DisplayInfoKind.LET,
getTextSpanOfNode(this.node),
undefined /* containerName */,
this.typeChecker.typeToString(symbol.tsType),
documentation,
);
}
private getQuickInfoForReferenceSymbol(symbol: ReferenceSymbol): ts.QuickInfo {
const documentation = this.getDocumentationFromTypeDefAtLocation(symbol.targetLocation);
return createQuickInfo(
symbol.declaration.name,
DisplayInfoKind.REFERENCE,
getTextSpanOfNode(this.node),
undefined /* containerName */,
this.typeChecker.typeToString(symbol.tsType),
documentation,
);
}
private getQuickInfoForPipeSymbol(symbol: PipeSymbol): ts.QuickInfo | undefined {
if (symbol.tsSymbol !== null) {
const quickInfo = this.getQuickInfoAtTcbLocation(symbol.tcbLocation);
return quickInfo === undefined
? undefined
: updateQuickInfoKind(quickInfo, DisplayInfoKind.PIPE);
} else {
return createQuickInfo(
this.typeChecker.typeToString(symbol.classSymbol.tsType),
DisplayInfoKind.PIPE,
getTextSpanOfNode(this.node),
);
}
}
private getQuickInfoForDomBinding(symbol: DomBindingSymbol) {
if (
!(this.node instanceof TmplAstTextAttribute) &&
!(this.node instanceof TmplAstBoundAttribute)
) {
return undefined;
}
const directives = getDirectiveMatchesForAttribute(
this.node.name,
symbol.host.templateNode,
symbol.host.directives,
);
const directiveSymbol = directives.size > 0 ? directives.values().next().value : null;
return directiveSymbol ? this.getQuickInfoForDirectiveSymbol(directiveSymbol) : undefined;
}
private getQuickInfoForDirectiveSymbol(
dir: DirectiveSymbol,
node: TmplAstNode | AST = this.node,
): ts.QuickInfo {
const kind = dir.isComponent ? DisplayInfoKind.COMPONENT : DisplayInfoKind.DIRECTIVE;
const documentation = this.getDocumentationFromTypeDefAtLocation(dir.tcbLocation);
let containerName: string | undefined;
if (ts.isClassDeclaration(dir.tsSymbol.valueDeclaration) && dir.ngModule !== null) {
containerName = dir.ngModule.name.getText();
}
return createQuickInfo(
this.typeChecker.typeToString(dir.tsType),
kind,
getTextSpanOfNode(this.node),
containerName,
undefined,
documentation,
);
}
private getDocumentationFromTypeDefAtLocation(
tcbLocation: TcbLocation,
): ts.SymbolDisplayPart[] | undefined {
const typeDefs = this.tsLS.getTypeDefinitionAtPosition(
tcbLocation.tcbPath,
tcbLocation.positionInFile,
);
if (typeDefs === undefined || typeDefs.length === 0) {
return undefined;
}
return this.tsLS.getQuickInfoAtPosition(typeDefs[0].fileName, typeDefs[0].textSpan.start)
?.documentation;
}
private getQuickInfoAtTcbLocation(location: TcbLocation): ts.QuickInfo | undefined {
const quickInfo = this.tsLS.getQuickInfoAtPosition(location.tcbPath, location.positionInFile);
if (quickInfo === undefined || quickInfo.displayParts === undefined) {
return quickInfo;
}
quickInfo.displayParts = filterAliasImports(quickInfo.displayParts);
const textSpan = getTextSpanOfNode(this.node);
return {...quickInfo, textSpan};
}
} | {
"end_byte": 8685,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/quick_info.ts"
} |
angular/packages/language-service/src/quick_info.ts_8687_9615 | function updateQuickInfoKind(quickInfo: ts.QuickInfo, kind: DisplayInfoKind): ts.QuickInfo {
if (quickInfo.displayParts === undefined) {
return quickInfo;
}
const startsWithKind =
quickInfo.displayParts.length >= 3 &&
displayPartsEqual(quickInfo.displayParts[0], {text: '(', kind: SYMBOL_PUNC}) &&
quickInfo.displayParts[1].kind === SYMBOL_TEXT &&
displayPartsEqual(quickInfo.displayParts[2], {text: ')', kind: SYMBOL_PUNC});
if (startsWithKind) {
quickInfo.displayParts[1].text = kind;
} else {
quickInfo.displayParts = [
{text: '(', kind: SYMBOL_PUNC},
{text: kind, kind: SYMBOL_TEXT},
{text: ')', kind: SYMBOL_PUNC},
{text: ' ', kind: SYMBOL_SPACE},
...quickInfo.displayParts,
];
}
return quickInfo;
}
function displayPartsEqual(a: {text: string; kind: string}, b: {text: string; kind: string}) {
return a.text === b.text && a.kind === b.kind;
} | {
"end_byte": 9615,
"start_byte": 8687,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/quick_info.ts"
} |
angular/packages/language-service/src/quick_info_built_ins.ts_0_8166 | /**
* @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 {
AST,
Call,
ImplicitReceiver,
ParseSourceSpan,
PropertyRead,
ThisReceiver,
TmplAstBlockNode,
TmplAstDeferredBlock,
TmplAstDeferredBlockError,
TmplAstDeferredBlockLoading,
TmplAstDeferredBlockPlaceholder,
TmplAstDeferredTrigger,
TmplAstForLoopBlock,
TmplAstForLoopBlockEmpty,
TmplAstNode,
} from '@angular/compiler';
import ts from 'typescript';
import {DisplayInfoKind, SYMBOL_TEXT} from './utils/display_parts';
import {createQuickInfo, getTextSpanOfNode, isWithin, toTextSpan} from './utils';
export function isDollarAny(node: TmplAstNode | AST): node is Call {
return (
node instanceof Call &&
node.receiver instanceof PropertyRead &&
node.receiver.receiver instanceof ImplicitReceiver &&
!(node.receiver.receiver instanceof ThisReceiver) &&
node.receiver.name === '$any' &&
node.args.length === 1
);
}
export function createDollarAnyQuickInfo(node: Call): ts.QuickInfo {
return createQuickInfo(
'$any',
DisplayInfoKind.METHOD,
getTextSpanOfNode(node.receiver),
/** containerName */ undefined,
'any',
[
{
kind: SYMBOL_TEXT,
text: 'function to cast an expression to the `any` type',
},
],
);
}
// TODO(atscott): Create special `ts.QuickInfo` for `ng-template` and `ng-container` as well.
export function createNgTemplateQuickInfo(node: TmplAstNode | AST): ts.QuickInfo {
return createQuickInfo(
'ng-template',
DisplayInfoKind.TEMPLATE,
getTextSpanOfNode(node),
/** containerName */ undefined,
/** type */ undefined,
[
{
kind: SYMBOL_TEXT,
text: 'The `<ng-template>` is an Angular element for rendering HTML. It is never displayed directly.',
},
],
);
}
export function createQuickInfoForBuiltIn(
node: TmplAstDeferredTrigger | TmplAstBlockNode,
cursorPositionInTemplate: number,
): ts.QuickInfo | undefined {
let partSpan: ParseSourceSpan;
if (node instanceof TmplAstDeferredTrigger) {
if (node.prefetchSpan !== null && isWithin(cursorPositionInTemplate, node.prefetchSpan)) {
partSpan = node.prefetchSpan;
} else if (node.hydrateSpan && isWithin(cursorPositionInTemplate, node.hydrateSpan)) {
partSpan = node.hydrateSpan;
} else if (
node.whenOrOnSourceSpan !== null &&
isWithin(cursorPositionInTemplate, node.whenOrOnSourceSpan)
) {
partSpan = node.whenOrOnSourceSpan;
} else if (node.nameSpan !== null && isWithin(cursorPositionInTemplate, node.nameSpan)) {
partSpan = node.nameSpan;
} else {
return undefined;
}
} else {
if (
node instanceof TmplAstDeferredBlock ||
node instanceof TmplAstDeferredBlockError ||
node instanceof TmplAstDeferredBlockLoading ||
node instanceof TmplAstDeferredBlockPlaceholder ||
(node instanceof TmplAstForLoopBlockEmpty &&
isWithin(cursorPositionInTemplate, node.nameSpan))
) {
partSpan = node.nameSpan;
} else if (
node instanceof TmplAstForLoopBlock &&
isWithin(cursorPositionInTemplate, node.trackKeywordSpan)
) {
partSpan = node.trackKeywordSpan;
} else {
return undefined;
}
}
const partName = partSpan.toString().trim();
const partInfo = BUILT_IN_NAMES_TO_DOC_MAP[partName];
const linkTags: ts.JSDocTagInfo[] = (partInfo?.links ?? []).map((text) => ({
text: [{kind: SYMBOL_TEXT, text}],
name: 'see',
}));
return createQuickInfo(
partName,
partInfo.displayInfoKind,
toTextSpan(partSpan),
/** containerName */ undefined,
/** type */ undefined,
[
{
kind: SYMBOL_TEXT,
text: partInfo?.docString ?? '',
},
],
linkTags,
);
}
const triggerDescriptionPreamble = 'A trigger to start loading the defer content after ';
const BUILT_IN_NAMES_TO_DOC_MAP: {
[name: string]: {docString: string; links: string[]; displayInfoKind: DisplayInfoKind};
} = {
'@defer': {
docString: `A type of block that can be used to defer load the JavaScript for components, directives and pipes used inside a component template.`,
links: ['[Reference](https://angular.dev/guide/defer#defer)'],
displayInfoKind: DisplayInfoKind.BLOCK,
},
'@placeholder': {
docString: `A block for content shown prior to defer loading (Optional)`,
links: ['[Reference](https://angular.dev/guide/defer#placeholder)'],
displayInfoKind: DisplayInfoKind.BLOCK,
},
'@error': {
docString: `A block for content shown when defer loading errors occur (Optional)`,
links: ['[Reference](https://angular.dev/guide/defer#error)'],
displayInfoKind: DisplayInfoKind.BLOCK,
},
'@loading': {
docString: `A block for content shown during defer loading (Optional)`,
links: ['[Reference](https://angular.dev/guide/defer#loading)'],
displayInfoKind: DisplayInfoKind.BLOCK,
},
'@empty': {
docString: `A block to display when the for loop variable is empty.`,
links: [
'[Reference](https://angular.dev/guide/templates/control-flow#providing-a-fallback-for-for-blocks-with-the-empty-block)',
],
displayInfoKind: DisplayInfoKind.BLOCK,
},
'track': {
docString: `Keyword to control how the for loop compares items in the list to compute updates.`,
links: [
'[Reference](https://angular.dev/guide/templates/control-flow#why-is-track-in-for-blocks-important)',
],
displayInfoKind: DisplayInfoKind.KEYWORD,
},
'idle': {
docString: triggerDescriptionPreamble + `the browser reports idle state (default).`,
links: ['[Reference](https://angular.dev/guide/defer#on-idle)'],
displayInfoKind: DisplayInfoKind.TRIGGER,
},
'immediate': {
docString: triggerDescriptionPreamble + `the page finishes rendering.`,
links: ['[Reference](https://angular.dev/guide/defer#on-immediate)'],
displayInfoKind: DisplayInfoKind.TRIGGER,
},
'hover': {
docString: triggerDescriptionPreamble + `the element has been hovered.`,
links: ['[Reference](https://angular.dev/guide/defer#on-hover)'],
displayInfoKind: DisplayInfoKind.TRIGGER,
},
'timer': {
docString: triggerDescriptionPreamble + `a specific timeout.`,
links: ['[Reference](https://angular.dev/guide/defer#on-timer)'],
displayInfoKind: DisplayInfoKind.TRIGGER,
},
'interaction': {
docString: triggerDescriptionPreamble + `the element is clicked, touched, or focused.`,
links: ['[Reference](https://angular.dev/guide/defer#on-interaction)'],
displayInfoKind: DisplayInfoKind.TRIGGER,
},
'viewport': {
docString: triggerDescriptionPreamble + `the element enters the viewport.`,
links: ['[Reference](https://angular.dev/guide/defer#on-viewport)'],
displayInfoKind: DisplayInfoKind.TRIGGER,
},
'prefetch': {
docString:
'Keyword that indicates that the trigger configures when prefetching the defer block contents should start. You can use `on` and `when` conditions as prefetch triggers.',
links: ['[Reference](https://angular.dev/guide/defer#prefetching)'],
displayInfoKind: DisplayInfoKind.KEYWORD,
},
'hydrate': {
docString:
"Keyword that indicates when the block's content will be hydrated. You can use `on` and `when` conditions as hydration triggers, or `hydrate never` to disable hydration for this block.",
// TODO(crisbeto): add link to partial hydration guide
links: [],
displayInfoKind: DisplayInfoKind.KEYWORD,
},
'when': {
docString:
'Keyword that starts the expression-based trigger section. Should be followed by an expression that returns a boolean.',
links: ['[Reference](https://angular.dev/guide/defer#triggers)'],
displayInfoKind: DisplayInfoKind.KEYWORD,
},
'on': {
docString:
'Keyword that starts the event-based trigger section. Should be followed by one of the built-in triggers.',
links: ['[Reference](https://angular.dev/guide/defer#triggers)'],
displayInfoKind: DisplayInfoKind.KEYWORD,
},
};
| {
"end_byte": 8166,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/quick_info_built_ins.ts"
} |
angular/packages/language-service/src/outlining_spans.ts_0_3264 | /**
* @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 {
ParseLocation,
ParseSourceSpan,
TmplAstBlockNode,
TmplAstDeferredBlock,
TmplAstForLoopBlock,
TmplAstIfBlock,
TmplAstNode,
TmplAstRecursiveVisitor,
tmplAstVisitAll,
} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {isExternalResource} from '@angular/compiler-cli/src/ngtsc/metadata';
import {isNamedClassDeclaration} from '@angular/compiler-cli/src/ngtsc/reflection';
import ts from 'typescript';
import {getFirstComponentForTemplateFile, isTypeScriptFile, toTextSpan} from './utils';
export function getOutliningSpans(compiler: NgCompiler, fileName: string): ts.OutliningSpan[] {
if (isTypeScriptFile(fileName)) {
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return [];
}
const templatesInFile: Array<TmplAstNode[]> = [];
for (const stmt of sf.statements) {
if (isNamedClassDeclaration(stmt)) {
const resources = compiler.getComponentResources(stmt);
if (resources === null || isExternalResource(resources.template)) {
continue;
}
const template = compiler.getTemplateTypeChecker().getTemplate(stmt);
if (template === null) {
continue;
}
templatesInFile.push(template);
}
}
return templatesInFile.map((template) => BlockVisitor.getBlockSpans(template)).flat();
} else {
const templateInfo = getFirstComponentForTemplateFile(fileName, compiler);
if (templateInfo === undefined) {
return [];
}
const {template} = templateInfo;
return BlockVisitor.getBlockSpans(template);
}
}
class BlockVisitor extends TmplAstRecursiveVisitor {
readonly blocks = [] as Array<TmplAstBlockNode>;
static getBlockSpans(templateNodes: TmplAstNode[]): ts.OutliningSpan[] {
const visitor = new BlockVisitor();
tmplAstVisitAll(visitor, templateNodes);
const {blocks} = visitor;
return blocks.map((block) => {
let mainBlockSpan = block.sourceSpan;
// The source span of for loops and deferred blocks contain all parts (ForLoopBlockEmpty,
// DeferredBlockLoading, etc.). The folding range should only include the main block span for
// these.
if (block instanceof TmplAstForLoopBlock || block instanceof TmplAstDeferredBlock) {
mainBlockSpan = block.mainBlockSpan;
}
return {
// We move the end back 1 character so we do not consume the close brace of the block in the
// range.
textSpan: toTextSpan(
new ParseSourceSpan(block.startSourceSpan.end, mainBlockSpan.end.moveBy(-1)),
),
hintSpan: toTextSpan(block.startSourceSpan),
bannerText: '...',
autoCollapse: false,
kind: ts.OutliningSpanKind.Region,
};
});
}
visit(node: TmplAstNode) {
if (
node instanceof TmplAstBlockNode &&
// Omit `IfBlock` because we include the branches individually
!(node instanceof TmplAstIfBlock)
) {
this.blocks.push(node);
}
}
}
| {
"end_byte": 3264,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/outlining_spans.ts"
} |
angular/packages/language-service/src/completions.ts_0_3532 | /**
* @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 {
AST,
ASTWithSource,
BindingPipe,
BindingType,
EmptyExpr,
ImplicitReceiver,
LiteralPrimitive,
ParsedEventType,
ParseSourceSpan,
PropertyRead,
PropertyWrite,
SafePropertyRead,
TmplAstBoundAttribute,
TmplAstBoundEvent,
TmplAstBoundEvent as BoundEvent,
TmplAstElement,
TmplAstNode,
TmplAstReference,
TmplAstSwitchBlock as SwitchBlock,
TmplAstTemplate,
TmplAstText,
TmplAstTextAttribute,
TmplAstTextAttribute as TextAttribute,
TmplAstUnknownBlock as UnknownBlock,
TmplAstVariable,
TmplAstLetDeclaration,
} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {
CompletionKind,
PotentialDirective,
SymbolKind,
TemplateDeclarationSymbol,
TemplateTypeChecker,
} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
import {
addAttributeCompletionEntries,
AsciiSortPriority,
AttributeCompletionKind,
buildAnimationCompletionEntries,
buildAttributeCompletionTable,
getAttributeCompletionSymbol,
} from './attribute_completions';
import {
DisplayInfo,
DisplayInfoKind,
getDirectiveDisplayInfo,
getSymbolDisplayInfo,
getTsSymbolDisplayInfo,
unsafeCastDisplayInfoKindToScriptElementKind,
} from './utils/display_parts';
import {TargetContext, TargetNodeKind, TemplateTarget} from './template_target';
import {
getCodeActionToImportTheDirectiveDeclaration,
standaloneTraitOrNgModule,
} from './utils/ts_utils';
import {filterAliasImports, isBoundEventWithSyntheticHandler, isWithin} from './utils';
type PropertyExpressionCompletionBuilder = CompletionBuilder<
PropertyRead | PropertyWrite | EmptyExpr | SafePropertyRead | TmplAstBoundEvent
>;
type ElementAttributeCompletionBuilder = CompletionBuilder<
TmplAstElement | TmplAstBoundAttribute | TmplAstTextAttribute | TmplAstBoundEvent
>;
type PipeCompletionBuilder = CompletionBuilder<BindingPipe>;
type LiteralCompletionBuilder = CompletionBuilder<LiteralPrimitive | TextAttribute>;
type ElementAnimationCompletionBuilder = CompletionBuilder<
TmplAstBoundAttribute | TmplAstBoundEvent
>;
type BlockCompletionBuilder = CompletionBuilder<UnknownBlock>;
type LetCompletionBuilder = CompletionBuilder<TmplAstLetDeclaration>;
export enum CompletionNodeContext {
None,
ElementTag,
ElementAttributeKey,
ElementAttributeValue,
EventValue,
TwoWayBinding,
}
const ANIMATION_PHASES = ['start', 'done'];
function buildBlockSnippet(insertSnippet: boolean, blockName: string, withParens: boolean): string {
if (!insertSnippet) {
return blockName;
}
if (blockName === 'for') {
return `${blockName} (\${1:item} of \${2:items}; track \${3:\\$index}) {$4}`;
}
if (withParens) {
return `${blockName} ($1) {$2}`;
}
return `${blockName} {$1}`;
}
/**
* Performs autocompletion operations on a given node in the template.
*
* This class acts as a closure around all of the context required to perform the 3 autocompletion
* operations (completions, get details, and get symbol) at a specific node.
*
* The generic `N` type for the template node is narrowed internally for certain operations, as the
* compiler operations required to implement completion may be different for different node types.
*
* @param N type of the template node in question, narrowed accordingly.
*/ | {
"end_byte": 3532,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/completions.ts"
} |
angular/packages/language-service/src/completions.ts_3533_12247 | export class CompletionBuilder<N extends TmplAstNode | AST> {
private readonly typeChecker: ts.TypeChecker;
private readonly templateTypeChecker: TemplateTypeChecker;
private readonly nodeParent: TmplAstNode | AST | null;
private readonly nodeContext: CompletionNodeContext;
private readonly template: TmplAstTemplate | null;
private readonly position: number;
constructor(
private readonly tsLS: ts.LanguageService,
private readonly compiler: NgCompiler,
private readonly component: ts.ClassDeclaration,
private readonly node: N,
private readonly targetDetails: TemplateTarget,
) {
this.typeChecker = this.compiler.getCurrentProgram().getTypeChecker();
this.templateTypeChecker = this.compiler.getTemplateTypeChecker();
this.nodeParent = this.targetDetails.parent;
this.nodeContext = nodeContextFromTarget(this.targetDetails.context);
this.template = this.targetDetails.template;
this.position = this.targetDetails.position;
}
/**
* Analogue for `ts.LanguageService.getCompletionsAtPosition`.
*/
getCompletionsAtPosition(
options: ts.GetCompletionsAtPositionOptions | undefined,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
if (this.isPropertyExpressionCompletion()) {
return this.getPropertyExpressionCompletion(options);
} else if (this.isElementTagCompletion()) {
return this.getElementTagCompletion();
} else if (this.isElementAttributeCompletion()) {
if (this.isAnimationCompletion()) {
return this.getAnimationCompletions();
} else {
return this.getElementAttributeCompletions(options);
}
} else if (this.isPipeCompletion()) {
return this.getPipeCompletions();
} else if (this.isLiteralCompletion()) {
return this.getLiteralCompletions(options);
} else if (this.isBlockCompletion()) {
return this.getBlockCompletions(options);
} else if (this.isLetCompletion()) {
return this.getGlobalPropertyExpressionCompletion(options);
} else {
return undefined;
}
}
private isLetCompletion(): this is LetCompletionBuilder {
return this.node instanceof TmplAstLetDeclaration;
}
private isBlockCompletion(): this is BlockCompletionBuilder {
return this.node instanceof UnknownBlock;
}
private getBlockCompletions(
this: BlockCompletionBuilder,
options: ts.GetCompletionsAtPositionOptions | undefined,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
const blocksWithParens = ['if', 'else if', 'for', 'switch', 'case', 'defer'];
const blocksWithoutParens = ['else', 'empty', 'placeholder', 'error', 'loading', 'default'];
// Determine whether to provide a snippet, which includes parens and curly braces.
// If the block has any expressions or a body, don't provide a snippet as the completion.
// TODO: We can be smarter about this, e.g. include `default` in `switch` if it is missing.
const incompleteBlockHasExpressionsOrBody =
this.node.sourceSpan
.toString()
.substring(1 + this.node.name.length)
.trim().length > 0;
const useSnippet =
(options?.includeCompletionsWithSnippetText ?? false) && !incompleteBlockHasExpressionsOrBody;
// Generate the list of completions, one for each block.
// TODO: Exclude connected blocks (e.g. `else` when the preceding block isn't `if` or `else
// if`).
const partialCompletionEntryWholeBlock = {
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.BLOCK),
replacementSpan: {
start: this.node.sourceSpan.start.offset + 1,
length: this.node.name.length,
},
};
let completionKeywords: string[] = [...blocksWithParens, ...blocksWithoutParens];
if (this.nodeParent instanceof SwitchBlock) {
completionKeywords = ['case', 'default'];
}
const completionEntries: ts.CompletionEntry[] = completionKeywords.map((name) => ({
name,
sortText: `${AsciiSortPriority.First}${name}`,
insertText: buildBlockSnippet(useSnippet, name, blocksWithParens.includes(name)),
isSnippet: useSnippet || undefined,
...partialCompletionEntryWholeBlock,
}));
// Return the completions.
const completionInfo: ts.CompletionInfo = {
flags: ts.CompletionInfoFlags.IsContinuation,
isMemberCompletion: false,
isGlobalCompletion: false,
isNewIdentifierLocation: false,
entries: completionEntries,
};
return completionInfo;
}
private isLiteralCompletion(): this is LiteralCompletionBuilder {
return (
this.node instanceof LiteralPrimitive ||
(this.node instanceof TextAttribute &&
this.nodeContext === CompletionNodeContext.ElementAttributeValue)
);
}
private getLiteralCompletions(
this: LiteralCompletionBuilder,
options: ts.GetCompletionsAtPositionOptions | undefined,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
const location = this.compiler
.getTemplateTypeChecker()
.getLiteralCompletionLocation(this.node, this.component);
if (location === null) {
return undefined;
}
const tsResults = this.tsLS.getCompletionsAtPosition(
location.tcbPath,
location.positionInFile,
options,
);
if (tsResults === undefined) {
return undefined;
}
let replacementSpan: ts.TextSpan | undefined;
if (this.node instanceof TextAttribute && this.node.value.length > 0 && this.node.valueSpan) {
replacementSpan = {
start: this.node.valueSpan.start.offset,
length: this.node.value.length,
};
}
if (this.node instanceof LiteralPrimitive) {
if (typeof this.node.value === 'string' && this.node.value.length > 0) {
replacementSpan = {
// The sourceSpan of `LiteralPrimitive` includes the open quote and the completion
// entries
// don't, so skip the open quote here.
start: this.node.sourceSpan.start + 1,
length: this.node.value.length,
};
} else if (typeof this.node.value === 'number') {
replacementSpan = {
start: this.node.sourceSpan.start,
length: this.node.value.toString().length,
};
}
}
let ngResults: ts.CompletionEntry[] = [];
for (const result of tsResults.entries) {
if (this.isValidNodeContextCompletion(result)) {
ngResults.push({
...result,
replacementSpan,
});
}
}
return {
...tsResults,
entries: ngResults,
};
}
/**
* Analogue for `ts.LanguageService.getCompletionEntryDetails`.
*/
getCompletionEntryDetails(
entryName: string,
formatOptions: ts.FormatCodeOptions | ts.FormatCodeSettings | undefined,
preferences: ts.UserPreferences | undefined,
data: ts.CompletionEntryData | undefined,
): ts.CompletionEntryDetails | undefined {
if (this.isPropertyExpressionCompletion()) {
return this.getPropertyExpressionCompletionDetails(
entryName,
formatOptions,
preferences,
data,
);
} else if (this.isElementTagCompletion()) {
return this.getElementTagCompletionDetails(entryName);
} else if (this.isElementAttributeCompletion()) {
return this.getElementAttributeCompletionDetails(entryName);
}
return undefined;
}
/**
* Analogue for `ts.LanguageService.getCompletionEntrySymbol`.
*/
getCompletionEntrySymbol(name: string): ts.Symbol | undefined {
if (this.isPropertyExpressionCompletion()) {
return this.getPropertyExpressionCompletionSymbol(name);
} else if (this.isElementTagCompletion()) {
return this.getElementTagCompletionSymbol(name);
} else if (this.isElementAttributeCompletion()) {
return this.getElementAttributeCompletionSymbol(name);
} else {
return undefined;
}
}
/**
* Determine if the current node is the completion of a property expression, and narrow the type
* of `this.node` if so.
*
* This narrowing gives access to additional methods related to completion of property
* expressions.
*/
private isPropertyExpressionCompletion(
this: CompletionBuilder<TmplAstNode | AST>,
): this is PropertyExpressionCompletionBuilder {
return (
this.node instanceof PropertyRead ||
this.node instanceof SafePropertyRead ||
this.node instanceof PropertyWrite ||
this.node instanceof EmptyExpr ||
// BoundEvent nodes only count as property completions if in an EventValue context.
(this.node instanceof BoundEvent && this.nodeContext === CompletionNodeContext.EventValue)
);
}
/**
* Get completions for property expressions.
*/ | {
"end_byte": 12247,
"start_byte": 3533,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/completions.ts"
} |
angular/packages/language-service/src/completions.ts_12250_21742 | private getPropertyExpressionCompletion(
this: PropertyExpressionCompletionBuilder,
options: ts.GetCompletionsAtPositionOptions | undefined,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
if (
this.node instanceof EmptyExpr ||
this.node instanceof BoundEvent ||
this.node.receiver instanceof ImplicitReceiver
) {
return this.getGlobalPropertyExpressionCompletion(options);
} else {
const location = this.templateTypeChecker.getExpressionCompletionLocation(
this.node,
this.component,
);
if (location === null) {
return undefined;
}
const tsResults = this.tsLS.getCompletionsAtPosition(
location.tcbPath,
location.positionInFile,
options,
);
if (tsResults === undefined) {
return undefined;
}
const replacementSpan = makeReplacementSpanFromAst(this.node);
if (
!(this.node.receiver instanceof ImplicitReceiver) &&
!(this.node instanceof SafePropertyRead) &&
options?.includeCompletionsWithInsertText &&
options.includeAutomaticOptionalChainCompletions !== false
) {
const symbol = this.templateTypeChecker.getSymbolOfNode(this.node.receiver, this.component);
if (symbol?.kind === SymbolKind.Expression) {
const type = symbol.tsType;
const nonNullableType = this.typeChecker.getNonNullableType(type);
if (type !== nonNullableType && replacementSpan !== undefined) {
// Shift the start location back one so it includes the `.` of the property access.
// In combination with the options above, this will indicate to the TS LS to include
// optional chaining completions `?.` for nullable types.
replacementSpan.start--;
replacementSpan.length++;
}
}
}
let ngResults: ts.CompletionEntry[] = [];
for (const result of tsResults.entries) {
ngResults.push({
...result,
replacementSpan,
});
}
return {
...tsResults,
entries: ngResults,
};
}
}
/**
* Get the details of a specific completion for a property expression.
*/
private getPropertyExpressionCompletionDetails(
this: PropertyExpressionCompletionBuilder,
entryName: string,
formatOptions: ts.FormatCodeOptions | ts.FormatCodeSettings | undefined,
preferences: ts.UserPreferences | undefined,
data: ts.CompletionEntryData | undefined,
): ts.CompletionEntryDetails | undefined {
let details: ts.CompletionEntryDetails | undefined = undefined;
if (
this.node instanceof EmptyExpr ||
this.node instanceof BoundEvent ||
this.node.receiver instanceof ImplicitReceiver
) {
details = this.getGlobalPropertyExpressionCompletionDetails(
entryName,
formatOptions,
preferences,
data,
);
} else {
const location = this.compiler
.getTemplateTypeChecker()
.getExpressionCompletionLocation(this.node, this.component);
if (location === null) {
return undefined;
}
details = this.tsLS.getCompletionEntryDetails(
location.tcbPath,
location.positionInFile,
entryName,
formatOptions,
/* source */ undefined,
preferences,
data,
);
}
if (details !== undefined) {
details.displayParts = filterAliasImports(details.displayParts);
}
return details;
}
/**
* Get the `ts.Symbol` for a specific completion for a property expression.
*/
private getPropertyExpressionCompletionSymbol(
this: PropertyExpressionCompletionBuilder,
name: string,
): ts.Symbol | undefined {
if (
this.node instanceof EmptyExpr ||
this.node instanceof LiteralPrimitive ||
this.node instanceof BoundEvent ||
this.node.receiver instanceof ImplicitReceiver
) {
return this.getGlobalPropertyExpressionCompletionSymbol(name);
} else {
const location = this.compiler
.getTemplateTypeChecker()
.getExpressionCompletionLocation(this.node, this.component);
if (location === null) {
return undefined;
}
return this.tsLS.getCompletionEntrySymbol(
location.tcbPath,
location.positionInFile,
name,
/* source */ undefined,
);
}
}
/**
* Get completions for a property expression in a global context (e.g. `{{y|}}`).
*/
private getGlobalPropertyExpressionCompletion(
this: PropertyExpressionCompletionBuilder | LetCompletionBuilder,
options: ts.GetCompletionsAtPositionOptions | undefined,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
const completions = this.templateTypeChecker.getGlobalCompletions(
this.template,
this.component,
this.node,
);
if (completions === null) {
return undefined;
}
const {componentContext, templateContext, nodeContext: astContext} = completions;
const replacementSpan = makeReplacementSpanFromAst(this.node);
// Merge TS completion results with results from the template scope.
let entries: ts.CompletionEntry[] = [];
const componentCompletions = this.tsLS.getCompletionsAtPosition(
componentContext.tcbPath,
componentContext.positionInFile,
options,
);
if (componentCompletions !== undefined) {
for (const tsCompletion of componentCompletions.entries) {
// Skip completions that are shadowed by a template entity definition.
if (templateContext.has(tsCompletion.name)) {
continue;
}
entries.push({
...tsCompletion,
// Substitute the TS completion's `replacementSpan` (which uses offsets within the TCB)
// with the `replacementSpan` within the template source.
replacementSpan,
});
}
}
// Merge TS completion results with results from the ast context.
if (astContext !== null) {
const nodeCompletions = this.tsLS.getCompletionsAtPosition(
astContext.tcbPath,
astContext.positionInFile,
options,
);
if (nodeCompletions !== undefined) {
for (const tsCompletion of nodeCompletions.entries) {
if (this.isValidNodeContextCompletion(tsCompletion)) {
entries.push({
...tsCompletion,
// Substitute the TS completion's `replacementSpan` (which uses offsets within the
// TCB) with the `replacementSpan` within the template source.
replacementSpan,
});
}
}
}
}
for (const [name, entity] of templateContext) {
let displayInfo: DisplayInfoKind;
if (entity.kind === CompletionKind.Reference) {
displayInfo = DisplayInfoKind.REFERENCE;
} else if (entity.kind === CompletionKind.LetDeclaration) {
displayInfo = DisplayInfoKind.LET;
} else {
displayInfo = DisplayInfoKind.VARIABLE;
}
entries.push({
name,
sortText: name,
replacementSpan,
kindModifiers: ts.ScriptElementKindModifier.none,
kind: unsafeCastDisplayInfoKindToScriptElementKind(displayInfo),
});
}
return {
entries,
// Although this completion is "global" in the sense of an Angular expression (there is no
// explicit receiver), it is not "global" in a TypeScript sense since Angular expressions
// have the component as an implicit receiver.
isGlobalCompletion: false,
isMemberCompletion: true,
isNewIdentifierLocation: false,
};
}
/**
* Get the details of a specific completion for a property expression in a global context (e.g.
* `{{y|}}`).
*/
private getGlobalPropertyExpressionCompletionDetails(
this: PropertyExpressionCompletionBuilder,
entryName: string,
formatOptions: ts.FormatCodeOptions | ts.FormatCodeSettings | undefined,
preferences: ts.UserPreferences | undefined,
data: ts.CompletionEntryData | undefined,
): ts.CompletionEntryDetails | undefined {
const completions = this.templateTypeChecker.getGlobalCompletions(
this.template,
this.component,
this.node,
);
if (completions === null) {
return undefined;
}
const {componentContext, templateContext} = completions;
if (templateContext.has(entryName)) {
const entry = templateContext.get(entryName)!;
// Entries that reference a symbol in the template context refer either to local references
// or variables.
const symbol = this.templateTypeChecker.getSymbolOfNode(
entry.node,
this.component,
) as TemplateDeclarationSymbol | null;
if (symbol === null) {
return undefined;
}
const {kind, displayParts, documentation, tags} = getSymbolDisplayInfo(
this.tsLS,
this.typeChecker,
symbol,
);
return {
kind: unsafeCastDisplayInfoKindToScriptElementKind(kind),
name: entryName,
kindModifiers: ts.ScriptElementKindModifier.none,
displayParts,
documentation,
tags,
};
} else {
return this.tsLS.getCompletionEntryDetails(
componentContext.tcbPath,
componentContext.positionInFile,
entryName,
formatOptions,
/* source */ undefined,
preferences,
data,
);
}
} | {
"end_byte": 21742,
"start_byte": 12250,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/completions.ts"
} |
angular/packages/language-service/src/completions.ts_21746_30011 | /**
* Get the `ts.Symbol` of a specific completion for a property expression in a global context
* (e.g. `{{y|}}`).
*/
private getGlobalPropertyExpressionCompletionSymbol(
this: PropertyExpressionCompletionBuilder,
entryName: string,
): ts.Symbol | undefined {
const completions = this.templateTypeChecker.getGlobalCompletions(
this.template,
this.component,
this.node,
);
if (completions === null) {
return undefined;
}
const {componentContext, templateContext} = completions;
if (templateContext.has(entryName)) {
const node: TmplAstReference | TmplAstVariable | TmplAstLetDeclaration =
templateContext.get(entryName)!.node;
const symbol = this.templateTypeChecker.getSymbolOfNode(
node,
this.component,
) as TemplateDeclarationSymbol | null;
if (symbol === null || symbol.tsSymbol === null) {
return undefined;
}
return symbol.tsSymbol;
} else {
return this.tsLS.getCompletionEntrySymbol(
componentContext.tcbPath,
componentContext.positionInFile,
entryName,
/* source */ undefined,
);
}
}
private isElementTagCompletion(): this is CompletionBuilder<TmplAstElement | TmplAstText> {
if (this.node instanceof TmplAstText) {
const positionInTextNode = this.position - this.node.sourceSpan.start.offset;
// We only provide element completions in a text node when there is an open tag immediately
// to the left of the position.
return this.node.value.substring(0, positionInTextNode).endsWith('<');
} else if (this.node instanceof TmplAstElement) {
return this.nodeContext === CompletionNodeContext.ElementTag;
}
return false;
}
private getElementTagCompletion(
this: CompletionBuilder<TmplAstElement | TmplAstText>,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
const templateTypeChecker = this.compiler.getTemplateTypeChecker();
let start: number;
let length: number;
if (this.node instanceof TmplAstElement) {
// The replacementSpan is the tag name.
start = this.node.sourceSpan.start.offset + 1; // account for leading '<'
length = this.node.name.length;
} else {
const positionInTextNode = this.position - this.node.sourceSpan.start.offset;
const textToLeftOfPosition = this.node.value.substring(0, positionInTextNode);
start = this.node.sourceSpan.start.offset + textToLeftOfPosition.lastIndexOf('<') + 1;
// We only autocomplete immediately after the < so we don't replace any existing text
length = 0;
}
const replacementSpan: ts.TextSpan = {start, length};
let potentialTags = Array.from(templateTypeChecker.getPotentialElementTags(this.component));
// Don't provide non-Angular tags (directive === null) because we expect other extensions
// (i.e. Emmet) to provide those for HTML files.
potentialTags = potentialTags.filter(([_, directive]) => directive !== null);
const entries: ts.CompletionEntry[] = potentialTags.map(([tag, directive]) => ({
kind: tagCompletionKind(directive),
name: tag,
sortText: tag,
replacementSpan,
hasAction: directive?.isInScope === true ? undefined : true,
}));
return {
entries,
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: false,
};
}
private getElementTagCompletionDetails(
this: CompletionBuilder<TmplAstElement | TmplAstText>,
entryName: string,
): ts.CompletionEntryDetails | undefined {
const templateTypeChecker = this.compiler.getTemplateTypeChecker();
const tagMap = templateTypeChecker.getPotentialElementTags(this.component);
if (!tagMap.has(entryName)) {
return undefined;
}
const directive = tagMap.get(entryName)!;
let displayParts: ts.SymbolDisplayPart[];
let documentation: ts.SymbolDisplayPart[] | undefined = undefined;
let tags: ts.JSDocTagInfo[] | undefined = undefined;
if (directive === null) {
displayParts = [];
} else {
const displayInfo = getDirectiveDisplayInfo(this.tsLS, directive);
displayParts = displayInfo.displayParts;
documentation = displayInfo.documentation;
tags = displayInfo.tags;
}
let codeActions: ts.CodeAction[] | undefined;
if (!directive.isInScope) {
const importOn = standaloneTraitOrNgModule(templateTypeChecker, this.component);
codeActions =
importOn !== null
? getCodeActionToImportTheDirectiveDeclaration(this.compiler, importOn, directive)
: undefined;
}
return {
kind: tagCompletionKind(directive),
name: entryName,
kindModifiers: ts.ScriptElementKindModifier.none,
displayParts,
documentation,
tags,
codeActions,
};
}
private getElementTagCompletionSymbol(
this: CompletionBuilder<TmplAstElement | TmplAstText>,
entryName: string,
): ts.Symbol | undefined {
const templateTypeChecker = this.compiler.getTemplateTypeChecker();
const tagMap = templateTypeChecker.getPotentialElementTags(this.component);
if (!tagMap.has(entryName)) {
return undefined;
}
const directive = tagMap.get(entryName)!;
return directive?.tsSymbol;
}
private isAnimationCompletion(): this is ElementAnimationCompletionBuilder {
return (
(this.node instanceof TmplAstBoundAttribute && this.node.type === BindingType.Animation) ||
(this.node instanceof TmplAstBoundEvent && this.node.type === ParsedEventType.Animation)
);
}
private getAnimationCompletions(
this: ElementAnimationCompletionBuilder,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
if (this.node instanceof TmplAstBoundAttribute) {
const animations = this.compiler.getTemplateTypeChecker().getDirectiveMetadata(this.component)
?.animationTriggerNames?.staticTriggerNames;
const replacementSpan = makeReplacementSpanFromParseSourceSpan(this.node.keySpan);
if (animations === undefined) {
return undefined;
}
const entries = buildAnimationCompletionEntries(
[...animations, '.disabled'],
replacementSpan,
DisplayInfoKind.ATTRIBUTE,
);
return {
entries,
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: true,
};
} else {
const animationNameSpan = buildAnimationNameSpan(this.node);
const phaseSpan = buildAnimationPhaseSpan(this.node);
if (isWithin(this.position, animationNameSpan)) {
const animations = this.compiler
.getTemplateTypeChecker()
.getDirectiveMetadata(this.component)?.animationTriggerNames?.staticTriggerNames;
const replacementSpan = makeReplacementSpanFromParseSourceSpan(animationNameSpan);
if (animations === undefined) {
return undefined;
}
const entries = buildAnimationCompletionEntries(
animations,
replacementSpan,
DisplayInfoKind.EVENT,
);
return {
entries,
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: true,
};
}
if (phaseSpan !== null && isWithin(this.position, phaseSpan)) {
const replacementSpan = makeReplacementSpanFromParseSourceSpan(phaseSpan);
const entries = buildAnimationCompletionEntries(
ANIMATION_PHASES,
replacementSpan,
DisplayInfoKind.EVENT,
);
return {
entries,
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: true,
};
}
return undefined;
}
}
private isElementAttributeCompletion(): this is ElementAttributeCompletionBuilder {
return (
(this.nodeContext === CompletionNodeContext.ElementAttributeKey ||
this.nodeContext === CompletionNodeContext.TwoWayBinding) &&
(this.node instanceof TmplAstElement ||
this.node instanceof TmplAstBoundAttribute ||
this.node instanceof TmplAstTextAttribute ||
this.node instanceof TmplAstBoundEvent)
);
} | {
"end_byte": 30011,
"start_byte": 21746,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/completions.ts"
} |
angular/packages/language-service/src/completions.ts_30015_39352 | private getElementAttributeCompletions(
this: ElementAttributeCompletionBuilder,
options: ts.GetCompletionsAtPositionOptions | undefined,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
let element: TmplAstElement | TmplAstTemplate;
if (this.node instanceof TmplAstElement) {
element = this.node;
} else if (
this.nodeParent instanceof TmplAstElement ||
this.nodeParent instanceof TmplAstTemplate
) {
element = this.nodeParent;
} else {
// Nothing to do without an element to process.
return undefined;
}
let replacementSpan: ts.TextSpan | undefined = undefined;
if (
(this.node instanceof TmplAstBoundAttribute ||
this.node instanceof TmplAstBoundEvent ||
this.node instanceof TmplAstTextAttribute) &&
this.node.keySpan !== undefined
) {
replacementSpan = makeReplacementSpanFromParseSourceSpan(this.node.keySpan);
}
let insertSnippet: true | undefined;
if (options?.includeCompletionsWithSnippetText && options.includeCompletionsWithInsertText) {
if (this.node instanceof TmplAstBoundEvent && isBoundEventWithSyntheticHandler(this.node)) {
replacementSpan = makeReplacementSpanFromParseSourceSpan(this.node.sourceSpan);
insertSnippet = true;
}
const isBoundAttributeValueEmpty =
this.node instanceof TmplAstBoundAttribute &&
(this.node.valueSpan === undefined ||
(this.node.value instanceof ASTWithSource && this.node.value.ast instanceof EmptyExpr));
if (isBoundAttributeValueEmpty) {
replacementSpan = makeReplacementSpanFromParseSourceSpan(this.node.sourceSpan);
insertSnippet = true;
}
if (this.node instanceof TmplAstTextAttribute && this.node.keySpan !== undefined) {
// The `sourceSpan` only includes `ngFor` and the `valueSpan` is always empty even if
// there is something there because we split this up into the desugared AST, `ngFor
// ngForOf=""`.
const nodeStart = this.node.keySpan.start.getContext(1, 1);
if (nodeStart?.before[0] === '*') {
const nodeEnd = this.node.keySpan.end.getContext(1, 1);
if (nodeEnd?.after[0] !== '=') {
// *ngFor -> *ngFor="¦"
insertSnippet = true;
}
} else {
if (this.node.value === '') {
replacementSpan = makeReplacementSpanFromParseSourceSpan(this.node.sourceSpan);
insertSnippet = true;
}
}
}
if (this.node instanceof TmplAstElement) {
// <div ¦ />
insertSnippet = true;
}
}
const attrTable = buildAttributeCompletionTable(
this.component,
element,
this.compiler.getTemplateTypeChecker(),
);
let entries: ts.CompletionEntry[] = [];
for (const completion of attrTable.values()) {
// First, filter out completions that don't make sense for the current node. For example, if
// the user is completing on a property binding `[foo|]`, don't offer output event
// completions.
switch (completion.kind) {
case AttributeCompletionKind.DomEvent:
if (this.node instanceof TmplAstBoundAttribute) {
continue;
}
break;
case AttributeCompletionKind.DomAttribute:
case AttributeCompletionKind.DomProperty:
if (this.node instanceof TmplAstBoundEvent) {
continue;
}
break;
case AttributeCompletionKind.DirectiveInput:
if (this.node instanceof TmplAstBoundEvent) {
continue;
}
if (
!completion.twoWayBindingSupported &&
this.nodeContext === CompletionNodeContext.TwoWayBinding
) {
continue;
}
break;
case AttributeCompletionKind.DirectiveOutput:
if (this.node instanceof TmplAstBoundAttribute) {
continue;
}
break;
case AttributeCompletionKind.DirectiveAttribute:
if (
this.node instanceof TmplAstBoundAttribute ||
this.node instanceof TmplAstBoundEvent
) {
continue;
}
break;
}
// Is the completion in an attribute context (instead of a property context)?
const isAttributeContext =
this.node instanceof TmplAstElement || this.node instanceof TmplAstTextAttribute;
// Is the completion for an element (not an <ng-template>)?
const isElementContext =
this.node instanceof TmplAstElement || this.nodeParent instanceof TmplAstElement;
addAttributeCompletionEntries(
entries,
completion,
isAttributeContext,
isElementContext,
replacementSpan,
insertSnippet,
);
}
return {
entries,
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: true,
};
}
private getElementAttributeCompletionDetails(
this: ElementAttributeCompletionBuilder,
entryName: string,
): ts.CompletionEntryDetails | undefined {
// `entryName` here may be `foo` or `[foo]`, depending on which suggested completion the user
// chose. Strip off any binding syntax to get the real attribute name.
const {name, kind} = stripBindingSugar(entryName);
let element: TmplAstElement | TmplAstTemplate;
if (this.node instanceof TmplAstElement || this.node instanceof TmplAstTemplate) {
element = this.node;
} else if (
this.nodeParent instanceof TmplAstElement ||
this.nodeParent instanceof TmplAstTemplate
) {
element = this.nodeParent;
} else {
// Nothing to do without an element to process.
return undefined;
}
const attrTable = buildAttributeCompletionTable(
this.component,
element,
this.compiler.getTemplateTypeChecker(),
);
if (!attrTable.has(name)) {
return undefined;
}
const completion = attrTable.get(name)!;
let displayParts: ts.SymbolDisplayPart[];
let documentation: ts.SymbolDisplayPart[] | undefined = undefined;
let tags: ts.JSDocTagInfo[] | undefined = undefined;
let info: DisplayInfo | null;
switch (completion.kind) {
case AttributeCompletionKind.DomEvent:
case AttributeCompletionKind.DomAttribute:
case AttributeCompletionKind.DomProperty:
// TODO(alxhub): ideally we would show the same documentation as quick info here. However,
// since these bindings don't exist in the TCB, there is no straightforward way to
// retrieve a `ts.Symbol` for the field in the TS DOM definition.
displayParts = [];
break;
case AttributeCompletionKind.DirectiveAttribute:
info = getDirectiveDisplayInfo(this.tsLS, completion.directive);
displayParts = info.displayParts;
documentation = info.documentation;
tags = info.tags;
break;
case AttributeCompletionKind.StructuralDirectiveAttribute:
case AttributeCompletionKind.DirectiveInput:
case AttributeCompletionKind.DirectiveOutput:
const propertySymbol = getAttributeCompletionSymbol(completion, this.typeChecker);
if (propertySymbol === null) {
return undefined;
}
let kind: DisplayInfoKind;
if (completion.kind === AttributeCompletionKind.DirectiveInput) {
kind = DisplayInfoKind.PROPERTY;
} else if (completion.kind === AttributeCompletionKind.DirectiveOutput) {
kind = DisplayInfoKind.EVENT;
} else {
kind = DisplayInfoKind.DIRECTIVE;
}
info = getTsSymbolDisplayInfo(
this.tsLS,
this.typeChecker,
propertySymbol,
kind,
completion.directive.tsSymbol.name,
);
if (info === null) {
return undefined;
}
displayParts = info.displayParts;
documentation = info.documentation;
tags = info.tags;
}
return {
name: entryName,
kind: unsafeCastDisplayInfoKindToScriptElementKind(kind),
kindModifiers: ts.ScriptElementKindModifier.none,
displayParts,
documentation,
tags,
};
}
private getElementAttributeCompletionSymbol(
this: ElementAttributeCompletionBuilder,
attribute: string,
): ts.Symbol | undefined {
const {name} = stripBindingSugar(attribute);
let element: TmplAstElement | TmplAstTemplate;
if (this.node instanceof TmplAstElement || this.node instanceof TmplAstTemplate) {
element = this.node;
} else if (
this.nodeParent instanceof TmplAstElement ||
this.nodeParent instanceof TmplAstTemplate
) {
element = this.nodeParent;
} else {
// Nothing to do without an element to process.
return undefined;
}
const attrTable = buildAttributeCompletionTable(
this.component,
element,
this.compiler.getTemplateTypeChecker(),
);
if (!attrTable.has(name)) {
return undefined;
}
const completion = attrTable.get(name)!;
return getAttributeCompletionSymbol(completion, this.typeChecker) ?? undefined;
}
private isPipeCompletion(): this is PipeCompletionBuilder {
return this.node instanceof BindingPipe;
}
| {
"end_byte": 39352,
"start_byte": 30015,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/completions.ts"
} |
angular/packages/language-service/src/completions.ts_39356_43777 | ivate getPipeCompletions(
this: PipeCompletionBuilder,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
const pipes = this.templateTypeChecker
.getPotentialPipes(this.component)
.filter((p) => p.isInScope);
if (pipes === null) {
return undefined;
}
const replacementSpan = makeReplacementSpanFromAst(this.node);
const entries: ts.CompletionEntry[] = pipes.map((pipe) => ({
name: pipe.name,
sortText: pipe.name,
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PIPE),
replacementSpan,
}));
return {
entries,
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: false,
};
}
/**
* From the AST node of the cursor position, include completion of string literals, number
* literals, `true`, `false`, `null`, and `undefined`.
*/
private isValidNodeContextCompletion(completion: ts.CompletionEntry): boolean {
if (completion.kind === ts.ScriptElementKind.string) {
// 'string' kind includes both string literals and number literals
return true;
}
if (completion.kind === ts.ScriptElementKind.keyword) {
return (
completion.name === 'true' || completion.name === 'false' || completion.name === 'null'
);
}
if (completion.kind === ts.ScriptElementKind.variableElement) {
return completion.name === 'undefined';
}
return false;
}
}
function makeReplacementSpanFromParseSourceSpan(span: ParseSourceSpan): ts.TextSpan {
return {
start: span.start.offset,
length: span.end.offset - span.start.offset,
};
}
function makeReplacementSpanFromAst(
node:
| PropertyRead
| PropertyWrite
| SafePropertyRead
| BindingPipe
| EmptyExpr
| LiteralPrimitive
| BoundEvent
| TmplAstLetDeclaration,
): ts.TextSpan | undefined {
if (
node instanceof EmptyExpr ||
node instanceof LiteralPrimitive ||
node instanceof BoundEvent ||
node instanceof TmplAstLetDeclaration
) {
// empty nodes do not replace any existing text
return undefined;
}
return {
start: node.nameSpan.start,
length: node.nameSpan.end - node.nameSpan.start,
};
}
function tagCompletionKind(directive: PotentialDirective | null): ts.ScriptElementKind {
let kind: DisplayInfoKind;
if (directive === null) {
kind = DisplayInfoKind.ELEMENT;
} else if (directive.isComponent) {
kind = DisplayInfoKind.COMPONENT;
} else {
kind = DisplayInfoKind.DIRECTIVE;
}
return unsafeCastDisplayInfoKindToScriptElementKind(kind);
}
const BINDING_SUGAR = /[\[\(\)\]]/g;
function stripBindingSugar(binding: string): {name: string; kind: DisplayInfoKind} {
const name = binding.replace(BINDING_SUGAR, '');
if (binding.startsWith('[')) {
return {name, kind: DisplayInfoKind.PROPERTY};
} else if (binding.startsWith('(')) {
return {name, kind: DisplayInfoKind.EVENT};
} else {
return {name, kind: DisplayInfoKind.ATTRIBUTE};
}
}
function nodeContextFromTarget(target: TargetContext): CompletionNodeContext {
switch (target.kind) {
case TargetNodeKind.ElementInTagContext:
return CompletionNodeContext.ElementTag;
case TargetNodeKind.ElementInBodyContext:
// Completions in element bodies are for new attributes.
return CompletionNodeContext.ElementAttributeKey;
case TargetNodeKind.TwoWayBindingContext:
return CompletionNodeContext.TwoWayBinding;
case TargetNodeKind.AttributeInKeyContext:
return CompletionNodeContext.ElementAttributeKey;
case TargetNodeKind.AttributeInValueContext:
if (target.node instanceof TmplAstBoundEvent) {
return CompletionNodeContext.EventValue;
} else if (target.node instanceof TextAttribute) {
return CompletionNodeContext.ElementAttributeValue;
} else {
return CompletionNodeContext.None;
}
default:
// No special context is available.
return CompletionNodeContext.None;
}
}
function buildAnimationNameSpan(node: TmplAstBoundEvent): ParseSourceSpan {
return new ParseSourceSpan(node.keySpan.start, node.keySpan.start.moveBy(node.name.length));
}
function buildAnimationPhaseSpan(node: TmplAstBoundEvent): ParseSourceSpan | null {
if (node.phase !== null) {
return new ParseSourceSpan(node.keySpan.end.moveBy(-node.phase.length), node.keySpan.end);
}
return null;
}
| {
"end_byte": 43777,
"start_byte": 39356,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/completions.ts"
} |
angular/packages/language-service/src/references_and_rename.ts_0_5247 | /**
* @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 {AST, TmplAstNode} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system';
import {MetaKind, PipeMeta} from '@angular/compiler-cli/src/ngtsc/metadata';
import {PerfPhase} from '@angular/compiler-cli/src/ngtsc/perf';
import {SymbolKind, TemplateTypeChecker} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
import {
convertToTemplateDocumentSpan,
FilePosition,
getParentClassMeta,
getRenameTextAndSpanAtPosition,
getTargetDetailsAtTemplatePosition,
TemplateLocationDetails,
} from './references_and_rename_utils';
import {collectMemberMethods, findTightestNode} from './utils/ts_utils';
import {getTemplateInfoAtPosition, TemplateInfo} from './utils';
export class ReferencesBuilder {
private readonly ttc: TemplateTypeChecker;
constructor(
private readonly tsLS: ts.LanguageService,
private readonly compiler: NgCompiler,
) {
this.ttc = this.compiler.getTemplateTypeChecker();
}
getReferencesAtPosition(filePath: string, position: number): ts.ReferenceEntry[] | undefined {
this.ttc.generateAllTypeCheckBlocks();
const templateInfo = getTemplateInfoAtPosition(filePath, position, this.compiler);
if (templateInfo === undefined) {
return this.getReferencesAtTypescriptPosition(filePath, position);
}
return this.getReferencesAtTemplatePosition(templateInfo, position);
}
private getReferencesAtTemplatePosition(
templateInfo: TemplateInfo,
position: number,
): ts.ReferenceEntry[] | undefined {
const allTargetDetails = getTargetDetailsAtTemplatePosition(templateInfo, position, this.ttc);
if (allTargetDetails === null) {
return undefined;
}
const allReferences: ts.ReferenceEntry[] = [];
for (const targetDetails of allTargetDetails) {
for (const location of targetDetails.typescriptLocations) {
const refs = this.getReferencesAtTypescriptPosition(location.fileName, location.position);
if (refs !== undefined) {
allReferences.push(...refs);
}
}
}
return allReferences.length > 0 ? allReferences : undefined;
}
private getReferencesAtTypescriptPosition(
fileName: string,
position: number,
): ts.ReferenceEntry[] | undefined {
const refs = this.tsLS.getReferencesAtPosition(fileName, position);
if (refs === undefined) {
return undefined;
}
const entries: ts.ReferenceEntry[] = [];
for (const ref of refs) {
if (this.ttc.isTrackedTypeCheckFile(absoluteFrom(ref.fileName))) {
const entry = convertToTemplateDocumentSpan(
ref,
this.ttc,
this.compiler.getCurrentProgram(),
);
if (entry !== null) {
entries.push(entry);
}
} else {
entries.push(ref);
}
}
return entries;
}
}
enum RequestKind {
DirectFromTemplate,
DirectFromTypeScript,
PipeName,
Selector,
}
/** The context needed to perform a rename of a pipe name. */
interface PipeRenameContext {
type: RequestKind.PipeName;
/** The string literal for the pipe name that appears in the @Pipe meta */
pipeNameExpr: ts.StringLiteral;
/**
* The location to use for querying the native TS LS for rename positions. This will be the
* pipe's transform method.
*/
renamePosition: FilePosition;
}
/** The context needed to perform a rename of a directive/component selector. */
interface SelectorRenameContext {
type: RequestKind.Selector;
/** The string literal that appears in the directive/component metadata. */
selectorExpr: ts.StringLiteral;
/**
* The location to use for querying the native TS LS for rename positions. This will be the
* component/directive class itself. Doing so will allow us to find the location of the
* directive/component instantiations, which map to template elements.
*/
renamePosition: FilePosition;
}
interface DirectFromTypescriptRenameContext {
type: RequestKind.DirectFromTypeScript;
/** The node that is being renamed. */
requestNode: ts.Node;
}
interface DirectFromTemplateRenameContext {
type: RequestKind.DirectFromTemplate;
/** The position in the TCB file to use as the request to the native TSLS for renaming. */
renamePosition: FilePosition;
/** The position in the template the request originated from. */
templatePosition: number;
/** The target node in the template AST that corresponds to the template position. */
requestNode: AST | TmplAstNode;
}
type IndirectRenameContext = PipeRenameContext | SelectorRenameContext;
type RenameRequest =
| IndirectRenameContext
| DirectFromTemplateRenameContext
| DirectFromTypescriptRenameContext;
function isDirectRenameContext(
context: RenameRequest,
): context is DirectFromTemplateRenameContext | DirectFromTypescriptRenameContext {
return (
context.type === RequestKind.DirectFromTemplate ||
context.type === RequestKind.DirectFromTypeScript
);
} | {
"end_byte": 5247,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/references_and_rename.ts"
} |
angular/packages/language-service/src/references_and_rename.ts_5249_14495 | export class RenameBuilder {
private readonly ttc: TemplateTypeChecker;
constructor(
private readonly tsLS: ts.LanguageService,
private readonly compiler: NgCompiler,
) {
this.ttc = this.compiler.getTemplateTypeChecker();
}
getRenameInfo(
filePath: string,
position: number,
): Omit<ts.RenameInfoSuccess, 'kind' | 'kindModifiers'> | ts.RenameInfoFailure {
return this.compiler.perfRecorder.inPhase(PerfPhase.LsReferencesAndRenames, () => {
const templateInfo = getTemplateInfoAtPosition(filePath, position, this.compiler);
// We could not get a template at position so we assume the request came from outside the
// template.
if (templateInfo === undefined) {
const renameRequest = this.buildRenameRequestAtTypescriptPosition(filePath, position);
if (renameRequest === null) {
return {
canRename: false,
localizedErrorMessage: 'Could not determine rename info at typescript position.',
};
}
if (renameRequest.type === RequestKind.PipeName) {
const pipeName = renameRequest.pipeNameExpr.text;
return {
canRename: true,
displayName: pipeName,
fullDisplayName: pipeName,
triggerSpan: {
length: pipeName.length,
// Offset the pipe name by 1 to account for start of string '/`/"
start: renameRequest.pipeNameExpr.getStart() + 1,
},
};
} else {
// TODO(atscott): Add support for other special indirect renames from typescript files.
return this.tsLS.getRenameInfo(filePath, position);
}
}
const allTargetDetails = getTargetDetailsAtTemplatePosition(templateInfo, position, this.ttc);
if (allTargetDetails === null) {
return {
canRename: false,
localizedErrorMessage: 'Could not find template node at position.',
};
}
const {templateTarget} = allTargetDetails[0];
const templateTextAndSpan = getRenameTextAndSpanAtPosition(templateTarget, position);
if (templateTextAndSpan === null) {
return {canRename: false, localizedErrorMessage: 'Could not determine template node text.'};
}
const {text, span} = templateTextAndSpan;
return {
canRename: true,
displayName: text,
fullDisplayName: text,
triggerSpan: span,
};
});
}
findRenameLocations(filePath: string, position: number): readonly ts.RenameLocation[] | null {
this.ttc.generateAllTypeCheckBlocks();
return this.compiler.perfRecorder.inPhase(PerfPhase.LsReferencesAndRenames, () => {
const templateInfo = getTemplateInfoAtPosition(filePath, position, this.compiler);
// We could not get a template at position so we assume the request came from outside the
// template.
if (templateInfo === undefined) {
const renameRequest = this.buildRenameRequestAtTypescriptPosition(filePath, position);
if (renameRequest === null) {
return null;
}
return this.findRenameLocationsAtTypescriptPosition(renameRequest);
}
return this.findRenameLocationsAtTemplatePosition(templateInfo, position);
});
}
private findRenameLocationsAtTemplatePosition(
templateInfo: TemplateInfo,
position: number,
): readonly ts.RenameLocation[] | null {
const allTargetDetails = getTargetDetailsAtTemplatePosition(templateInfo, position, this.ttc);
if (allTargetDetails === null) {
return null;
}
const renameRequests = this.buildRenameRequestsFromTemplateDetails(allTargetDetails, position);
if (renameRequests === null) {
return null;
}
const allRenameLocations: ts.RenameLocation[] = [];
for (const renameRequest of renameRequests) {
const locations = this.findRenameLocationsAtTypescriptPosition(renameRequest);
// If we couldn't find rename locations for _any_ result, we should not allow renaming to
// proceed instead of having a partially complete rename.
if (locations === null) {
return null;
}
allRenameLocations.push(...locations);
}
return allRenameLocations.length > 0 ? allRenameLocations : null;
}
findRenameLocationsAtTypescriptPosition(
renameRequest: RenameRequest,
): readonly ts.RenameLocation[] | null {
return this.compiler.perfRecorder.inPhase(PerfPhase.LsReferencesAndRenames, () => {
const renameInfo = getExpectedRenameTextAndInitialRenameEntries(renameRequest);
if (renameInfo === null) {
return null;
}
const {entries, expectedRenameText} = renameInfo;
const {fileName, position} = getRenameRequestPosition(renameRequest);
const findInStrings = false;
const findInComments = false;
const locations = this.tsLS.findRenameLocations(
fileName,
position,
findInStrings,
findInComments,
);
if (locations === undefined) {
return null;
}
for (const location of locations) {
if (this.ttc.isTrackedTypeCheckFile(absoluteFrom(location.fileName))) {
const entry = convertToTemplateDocumentSpan(
location,
this.ttc,
this.compiler.getCurrentProgram(),
expectedRenameText,
);
// There is no template node whose text matches the original rename request. Bail on
// renaming completely rather than providing incomplete results.
if (entry === null) {
return null;
}
entries.push(entry);
} else {
if (!isDirectRenameContext(renameRequest)) {
// Discard any non-template results for non-direct renames. We should only rename
// template results + the name/selector/alias `ts.Expression`. The other results
// will be the `ts.Identifier` of the transform method (pipe rename) or the
// directive class (selector rename).
continue;
}
// Ensure we only allow renaming a TS result with matching text
const refNode = this.getTsNodeAtPosition(location.fileName, location.textSpan.start);
if (refNode === null || refNode.getText() !== expectedRenameText) {
return null;
}
entries.push(location);
}
}
return entries;
});
}
private getTsNodeAtPosition(filePath: string, position: number): ts.Node | null {
const sf = this.compiler.getCurrentProgram().getSourceFile(filePath);
if (!sf) {
return null;
}
return findTightestNode(sf, position) ?? null;
}
private buildRenameRequestsFromTemplateDetails(
allTargetDetails: TemplateLocationDetails[],
templatePosition: number,
): RenameRequest[] | null {
const renameRequests: RenameRequest[] = [];
for (const targetDetails of allTargetDetails) {
for (const location of targetDetails.typescriptLocations) {
if (targetDetails.symbol.kind === SymbolKind.Pipe) {
const meta = this.compiler.getMeta(
targetDetails.symbol.classSymbol.tsSymbol.valueDeclaration,
);
if (meta === null || meta.kind !== MetaKind.Pipe) {
return null;
}
const renameRequest = this.buildPipeRenameRequest(meta);
if (renameRequest === null) {
return null;
}
renameRequests.push(renameRequest);
} else {
const renameRequest: RenameRequest = {
type: RequestKind.DirectFromTemplate,
templatePosition,
requestNode: targetDetails.templateTarget,
renamePosition: location,
};
renameRequests.push(renameRequest);
}
}
}
return renameRequests;
}
private buildRenameRequestAtTypescriptPosition(
filePath: string,
position: number,
): RenameRequest | null {
const requestNode = this.getTsNodeAtPosition(filePath, position);
if (requestNode === null) {
return null;
}
const meta = getParentClassMeta(requestNode, this.compiler);
if (meta !== null && meta.kind === MetaKind.Pipe && meta.nameExpr === requestNode) {
return this.buildPipeRenameRequest(meta);
} else {
return {type: RequestKind.DirectFromTypeScript, requestNode};
}
}
private buildPipeRenameRequest(meta: PipeMeta): PipeRenameContext | null {
if (
!ts.isClassDeclaration(meta.ref.node) ||
meta.nameExpr === null ||
!ts.isStringLiteral(meta.nameExpr)
) {
return null;
}
const typeChecker = this.compiler.getCurrentProgram().getTypeChecker();
const memberMethods = collectMemberMethods(meta.ref.node, typeChecker) ?? [];
const pipeTransformNode: ts.MethodDeclaration | undefined = memberMethods.find(
(m) => m.name.getText() === 'transform',
);
if (pipeTransformNode === undefined) {
return null;
}
return {
type: RequestKind.PipeName,
pipeNameExpr: meta.nameExpr,
renamePosition: {
fileName: pipeTransformNode.getSourceFile().fileName,
position: pipeTransformNode.getStart(),
},
};
}
} | {
"end_byte": 14495,
"start_byte": 5249,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/references_and_rename.ts"
} |
angular/packages/language-service/src/references_and_rename.ts_14497_16563 | /**
* From the provided `RenameRequest`, determines what text we should expect all produced
* `ts.RenameLocation`s to have and creates an initial entry for indirect renames (one which is
* required for the rename operation, but cannot be found by the native TS LS).
*/
function getExpectedRenameTextAndInitialRenameEntries(
renameRequest: RenameRequest,
): {expectedRenameText: string; entries: ts.RenameLocation[]} | null {
let expectedRenameText: string;
const entries: ts.RenameLocation[] = [];
if (renameRequest.type === RequestKind.DirectFromTypeScript) {
expectedRenameText = renameRequest.requestNode.getText();
} else if (renameRequest.type === RequestKind.DirectFromTemplate) {
const templateNodeText = getRenameTextAndSpanAtPosition(
renameRequest.requestNode,
renameRequest.templatePosition,
);
if (templateNodeText === null) {
return null;
}
expectedRenameText = templateNodeText.text;
} else if (renameRequest.type === RequestKind.PipeName) {
const {pipeNameExpr} = renameRequest;
expectedRenameText = pipeNameExpr.text;
const entry: ts.RenameLocation = {
fileName: renameRequest.pipeNameExpr.getSourceFile().fileName,
textSpan: {start: pipeNameExpr.getStart() + 1, length: pipeNameExpr.getText().length - 2},
};
entries.push(entry);
} else {
// TODO(atscott): Implement other types of special renames
return null;
}
return {entries, expectedRenameText};
}
/**
* Given a `RenameRequest`, determines the `FilePosition` to use asking the native TS LS for rename
* locations.
*/
function getRenameRequestPosition(renameRequest: RenameRequest): FilePosition {
const fileName =
renameRequest.type === RequestKind.DirectFromTypeScript
? renameRequest.requestNode.getSourceFile().fileName
: renameRequest.renamePosition.fileName;
const position =
renameRequest.type === RequestKind.DirectFromTypeScript
? renameRequest.requestNode.getStart()
: renameRequest.renamePosition.position;
return {fileName, position};
} | {
"end_byte": 16563,
"start_byte": 14497,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/references_and_rename.ts"
} |
angular/packages/language-service/src/references_and_rename_utils.ts_0_8372 | /**
* @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 {
AST,
BindingPipe,
LiteralPrimitive,
PropertyRead,
PropertyWrite,
SafePropertyRead,
TmplAstBoundAttribute,
TmplAstBoundEvent,
TmplAstLetDeclaration,
TmplAstNode,
TmplAstReference,
TmplAstTextAttribute,
TmplAstVariable,
} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system';
import {DirectiveMeta, PipeMeta} from '@angular/compiler-cli/src/ngtsc/metadata';
import {
DirectiveSymbol,
Symbol,
SymbolKind,
TcbLocation,
TemplateTypeChecker,
} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import {
ExpressionIdentifier,
hasExpressionIdentifier,
} from '@angular/compiler-cli/src/ngtsc/typecheck/src/comments';
import ts from 'typescript';
import {getTargetAtPosition, TargetNodeKind} from './template_target';
import {findTightestNode, getParentClassDeclaration} from './utils/ts_utils';
import {
getDirectiveMatchesForAttribute,
getDirectiveMatchesForElementTag,
getTemplateLocationFromTcbLocation,
isWithin,
TemplateInfo,
toTextSpan,
} from './utils';
/** Represents a location in a file. */
export interface FilePosition {
fileName: string;
position: number;
}
/**
* Converts a `TcbLocation` to a more genericly named `FilePosition`.
*/
function toFilePosition(tcbLocation: TcbLocation): FilePosition {
return {fileName: tcbLocation.tcbPath, position: tcbLocation.positionInFile};
}
export interface TemplateLocationDetails {
/**
* A target node in a template.
*/
templateTarget: TmplAstNode | AST;
/**
* TypeScript locations which the template node maps to. A given template node might map to
* several TS nodes. For example, a template node for an attribute might resolve to several
* directives or a directive and one of its inputs.
*/
typescriptLocations: FilePosition[];
/**
* The resolved Symbol for the template target.
*/
symbol: Symbol;
}
/**
* Takes a position in a template and finds equivalent targets in TS files as well as details about
* the targeted template node.
*/
export function getTargetDetailsAtTemplatePosition(
{template, component}: TemplateInfo,
position: number,
templateTypeChecker: TemplateTypeChecker,
): TemplateLocationDetails[] | null {
// Find the AST node in the template at the position.
const positionDetails = getTargetAtPosition(template, position);
if (positionDetails === null) {
return null;
}
const nodes =
positionDetails.context.kind === TargetNodeKind.TwoWayBindingContext
? positionDetails.context.nodes
: [positionDetails.context.node];
const details: TemplateLocationDetails[] = [];
for (const node of nodes) {
// Get the information about the TCB at the template position.
const symbol = templateTypeChecker.getSymbolOfNode(node, component);
if (symbol === null) {
continue;
}
const templateTarget = node;
switch (symbol.kind) {
case SymbolKind.Directive:
case SymbolKind.Template:
// References to elements, templates, and directives will be through template references
// (#ref). They shouldn't be used directly for a Language Service reference request.
break;
case SymbolKind.Element: {
const matches = getDirectiveMatchesForElementTag(symbol.templateNode, symbol.directives);
details.push({
typescriptLocations: getPositionsForDirectives(matches),
templateTarget,
symbol,
});
break;
}
case SymbolKind.DomBinding: {
// Dom bindings aren't currently type-checked (see `checkTypeOfDomBindings`) so they don't
// have a shim location. This means we can't match dom bindings to their lib.dom
// reference, but we can still see if they match to a directive.
if (!(node instanceof TmplAstTextAttribute) && !(node instanceof TmplAstBoundAttribute)) {
return null;
}
const directives = getDirectiveMatchesForAttribute(
node.name,
symbol.host.templateNode,
symbol.host.directives,
);
details.push({
typescriptLocations: getPositionsForDirectives(directives),
templateTarget,
symbol,
});
break;
}
case SymbolKind.Reference: {
details.push({
typescriptLocations: [toFilePosition(symbol.referenceVarLocation)],
templateTarget,
symbol,
});
break;
}
case SymbolKind.Variable: {
if (templateTarget instanceof TmplAstVariable) {
if (
templateTarget.valueSpan !== undefined &&
isWithin(position, templateTarget.valueSpan)
) {
// In the valueSpan of the variable, we want to get the reference of the initializer.
details.push({
typescriptLocations: [toFilePosition(symbol.initializerLocation)],
templateTarget,
symbol,
});
} else if (isWithin(position, templateTarget.keySpan)) {
// In the keySpan of the variable, we want to get the reference of the local variable.
details.push({
typescriptLocations: [toFilePosition(symbol.localVarLocation)],
templateTarget,
symbol,
});
}
} else {
// If the templateNode is not the `TmplAstVariable`, it must be a usage of the
// variable somewhere in the template.
details.push({
typescriptLocations: [toFilePosition(symbol.localVarLocation)],
templateTarget,
symbol,
});
}
break;
}
case SymbolKind.LetDeclaration:
// If the templateNode isn't on a let declaration, it has to be on a usage of it
// somewhere in the template. Otherwise only pick up when it's within the name.
if (
!(templateTarget instanceof TmplAstLetDeclaration) ||
isWithin(position, templateTarget.nameSpan)
) {
details.push({
typescriptLocations: [toFilePosition(symbol.localVarLocation)],
templateTarget,
symbol,
});
}
break;
case SymbolKind.Input:
case SymbolKind.Output: {
details.push({
typescriptLocations: symbol.bindings.map((binding) =>
toFilePosition(binding.tcbLocation),
),
templateTarget,
symbol,
});
break;
}
case SymbolKind.Pipe:
case SymbolKind.Expression: {
details.push({
typescriptLocations: [toFilePosition(symbol.tcbLocation)],
templateTarget,
symbol,
});
break;
}
}
}
return details.length > 0 ? details : null;
}
/**
* Given a set of `DirectiveSymbol`s, finds the equivalent `FilePosition` of the class declaration.
*/
function getPositionsForDirectives(directives: Set<DirectiveSymbol>): FilePosition[] {
const allDirectives: FilePosition[] = [];
for (const dir of directives.values()) {
const dirClass = dir.tsSymbol.valueDeclaration;
if (dirClass === undefined || !ts.isClassDeclaration(dirClass) || dirClass.name === undefined) {
continue;
}
const {fileName} = dirClass.getSourceFile();
const position = dirClass.name.getStart();
allDirectives.push({fileName, position});
}
return allDirectives;
}
/**
* Creates a "key" for a rename/reference location by concatenating file name, span start, and span
* length. This allows us to de-duplicate template results when an item may appear several times
* in the TCB but map back to the same template location.
*/
export function createLocationKey(ds: ts.DocumentSpan) {
return ds.fileName + ds.textSpan.start + ds.textSpan.length;
}
/**
* Converts a given `ts.DocumentSpan` in a shim file to its equivalent `ts.DocumentSpan` in the
* template.
*
* You can optionally provide a `requiredNodeText` that ensures the equivalent template node's text
* matches. If it does not, this function will return `null`.
*/ | {
"end_byte": 8372,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/references_and_rename_utils.ts"
} |
angular/packages/language-service/src/references_and_rename_utils.ts_8373_12755 | export function convertToTemplateDocumentSpan<T extends ts.DocumentSpan>(
shimDocumentSpan: T,
templateTypeChecker: TemplateTypeChecker,
program: ts.Program,
requiredNodeText?: string,
): T | null {
const sf = program.getSourceFile(shimDocumentSpan.fileName);
if (sf === undefined) {
return null;
}
const tcbNode = findTightestNode(sf, shimDocumentSpan.textSpan.start);
if (
tcbNode === undefined ||
hasExpressionIdentifier(sf, tcbNode, ExpressionIdentifier.EVENT_PARAMETER)
) {
// If the reference result is the $event parameter in the subscribe/addEventListener
// function in the TCB, we want to filter this result out of the references. We really only
// want to return references to the parameter in the template itself.
return null;
}
// Variables in the typecheck block are generated with the type on the right hand
// side: `var _t1 = null! as i1.DirA`. Finding references of DirA will return the type
// assertion and we need to map it back to the variable identifier _t1.
if (hasExpressionIdentifier(sf, tcbNode, ExpressionIdentifier.VARIABLE_AS_EXPRESSION)) {
let newNode = tcbNode;
while (!ts.isVariableDeclaration(newNode)) {
newNode = newNode.parent;
}
newNode = newNode.name;
shimDocumentSpan.textSpan = {
start: newNode.getStart(),
length: newNode.getEnd() - newNode.getStart(),
};
}
// TODO(atscott): Determine how to consistently resolve paths. i.e. with the project
// serverHost or LSParseConfigHost in the adapter. We should have a better defined way to
// normalize paths.
const mapping = getTemplateLocationFromTcbLocation(
templateTypeChecker,
absoluteFrom(shimDocumentSpan.fileName),
/* tcbIsShim */ true,
shimDocumentSpan.textSpan.start,
);
if (mapping === null) {
return null;
}
const {span, templateUrl} = mapping;
if (requiredNodeText !== undefined && span.toString() !== requiredNodeText) {
return null;
}
return {
...shimDocumentSpan,
fileName: templateUrl,
textSpan: toTextSpan(span),
// Specifically clear other text span values because we do not have enough knowledge to
// convert these to spans in the template.
contextSpan: undefined,
originalContextSpan: undefined,
originalTextSpan: undefined,
};
}
/**
* Finds the text and `ts.TextSpan` for the node at a position in a template.
*/
export function getRenameTextAndSpanAtPosition(
node: TmplAstNode | AST,
position: number,
): {text: string; span: ts.TextSpan} | null {
if (
node instanceof TmplAstBoundAttribute ||
node instanceof TmplAstTextAttribute ||
node instanceof TmplAstBoundEvent
) {
return node.keySpan === undefined ? null : {text: node.name, span: toTextSpan(node.keySpan)};
} else if (node instanceof TmplAstLetDeclaration && isWithin(position, node.nameSpan)) {
return {text: node.nameSpan.toString(), span: toTextSpan(node.nameSpan)};
} else if (node instanceof TmplAstVariable || node instanceof TmplAstReference) {
if (isWithin(position, node.keySpan)) {
return {text: node.keySpan.toString(), span: toTextSpan(node.keySpan)};
} else if (node.valueSpan && isWithin(position, node.valueSpan)) {
return {text: node.valueSpan.toString(), span: toTextSpan(node.valueSpan)};
}
}
if (
node instanceof PropertyRead ||
node instanceof PropertyWrite ||
node instanceof SafePropertyRead ||
node instanceof BindingPipe
) {
return {text: node.name, span: toTextSpan(node.nameSpan)};
} else if (node instanceof LiteralPrimitive) {
const span = toTextSpan(node.sourceSpan);
const text = node.value;
if (typeof text === 'string') {
// The span of a string literal includes the quotes but they should be removed for renaming.
span.start += 1;
span.length -= 2;
}
return {text, span};
}
return null;
}
/**
* Retrieves the `PipeMeta` or `DirectiveMeta` of the given `ts.Node`'s parent class.
*
* Returns `null` if the node has no parent class or there is no meta associated with the class.
*/
export function getParentClassMeta(
requestNode: ts.Node,
compiler: NgCompiler,
): PipeMeta | DirectiveMeta | null {
const parentClass = getParentClassDeclaration(requestNode);
if (parentClass === undefined) {
return null;
}
return compiler.getMeta(parentClass);
} | {
"end_byte": 12755,
"start_byte": 8373,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/references_and_rename_utils.ts"
} |
angular/packages/language-service/src/ts_plugin.ts_0_559 | /**
* @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 ts from 'typescript';
import {
ApplyRefactoringProgressFn,
ApplyRefactoringResult,
GetComponentLocationsForTemplateResponse,
GetTcbResponse,
GetTemplateLocationForComponentResponse,
isNgLanguageService,
NgLanguageService,
} from '../api';
import {LanguageService} from './language_service';
import {isTypeScriptFile} from './utils'; | {
"end_byte": 559,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/ts_plugin.ts"
} |
angular/packages/language-service/src/ts_plugin.ts_561_9524 | export function create(info: ts.server.PluginCreateInfo): NgLanguageService {
const {project, languageService, config} = info;
const tsLS = isNgLanguageService(languageService)
? languageService.getTypescriptLanguageService()
: languageService;
const angularOnly = config?.angularOnly === true;
const ngLS = new LanguageService(project, tsLS, config);
function getSyntacticDiagnostics(fileName: string): ts.DiagnosticWithLocation[] {
if (!angularOnly && isTypeScriptFile(fileName)) {
return tsLS.getSyntacticDiagnostics(fileName);
}
// Template files do not currently produce separate syntactic diagnostics and
// are instead produced during the semantic diagnostic analysis.
return [];
}
function getSuggestionDiagnostics(fileName: string): ts.DiagnosticWithLocation[] {
if (!angularOnly && isTypeScriptFile(fileName)) {
return tsLS.getSuggestionDiagnostics(fileName);
}
// Template files do not currently produce separate suggestion diagnostics
return [];
}
function getSemanticDiagnostics(fileName: string): ts.Diagnostic[] {
const diagnostics: ts.Diagnostic[] = [];
if (!angularOnly && isTypeScriptFile(fileName)) {
diagnostics.push(...tsLS.getSemanticDiagnostics(fileName));
}
diagnostics.push(...ngLS.getSemanticDiagnostics(fileName));
return diagnostics;
}
function getQuickInfoAtPosition(fileName: string, position: number): ts.QuickInfo | undefined {
if (angularOnly || !isTypeScriptFile(fileName)) {
return ngLS.getQuickInfoAtPosition(fileName, position);
} else {
// If TS could answer the query, then return that result. Otherwise, return from Angular LS.
return (
tsLS.getQuickInfoAtPosition(fileName, position) ??
ngLS.getQuickInfoAtPosition(fileName, position)
);
}
}
function getTypeDefinitionAtPosition(
fileName: string,
position: number,
): readonly ts.DefinitionInfo[] | undefined {
if (angularOnly || !isTypeScriptFile(fileName)) {
return ngLS.getTypeDefinitionAtPosition(fileName, position);
} else {
// If TS could answer the query, then return that result. Otherwise, return from Angular LS.
return (
tsLS.getTypeDefinitionAtPosition(fileName, position) ??
ngLS.getTypeDefinitionAtPosition(fileName, position)
);
}
}
function getDefinitionAndBoundSpan(
fileName: string,
position: number,
): ts.DefinitionInfoAndBoundSpan | undefined {
if (angularOnly || !isTypeScriptFile(fileName)) {
return ngLS.getDefinitionAndBoundSpan(fileName, position);
} else {
// If TS could answer the query, then return that result. Otherwise, return from Angular LS.
return (
tsLS.getDefinitionAndBoundSpan(fileName, position) ??
ngLS.getDefinitionAndBoundSpan(fileName, position)
);
}
}
function getDefinitionAtPosition(
fileName: string,
position: number,
): readonly ts.DefinitionInfo[] | undefined {
return getDefinitionAndBoundSpan(fileName, position)?.definitions;
}
function getReferencesAtPosition(
fileName: string,
position: number,
): ts.ReferenceEntry[] | undefined {
return ngLS.getReferencesAtPosition(fileName, position);
}
function findRenameLocations(
fileName: string,
position: number,
): readonly ts.RenameLocation[] | undefined {
// Most operations combine results from all extensions. However, rename locations are exclusive
// (results from only one extension are used) so our rename locations are a superset of the TS
// rename locations. As a result, we do not check the `angularOnly` flag here because we always
// want to include results at TS locations as well as locations in templates.
return ngLS.findRenameLocations(fileName, position);
}
function getRenameInfo(fileName: string, position: number): ts.RenameInfo {
// See the comment in `findRenameLocations` explaining why we don't check the `angularOnly`
// flag.
return ngLS.getRenameInfo(fileName, position);
}
function getCompletionsAtPosition(
fileName: string,
position: number,
options: ts.GetCompletionsAtPositionOptions,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
if (angularOnly || !isTypeScriptFile(fileName)) {
return ngLS.getCompletionsAtPosition(fileName, position, options);
} else {
// If TS could answer the query, then return that result. Otherwise, return from Angular LS.
return (
tsLS.getCompletionsAtPosition(fileName, position, options) ??
ngLS.getCompletionsAtPosition(fileName, position, options)
);
}
}
function getCompletionEntryDetails(
fileName: string,
position: number,
entryName: string,
formatOptions: ts.FormatCodeOptions | ts.FormatCodeSettings | undefined,
source: string | undefined,
preferences: ts.UserPreferences | undefined,
data: ts.CompletionEntryData | undefined,
): ts.CompletionEntryDetails | undefined {
if (angularOnly || !isTypeScriptFile(fileName)) {
return ngLS.getCompletionEntryDetails(
fileName,
position,
entryName,
formatOptions,
preferences,
data,
);
} else {
// If TS could answer the query, then return that result. Otherwise, return from Angular LS.
return (
tsLS.getCompletionEntryDetails(
fileName,
position,
entryName,
formatOptions,
source,
preferences,
data,
) ??
ngLS.getCompletionEntryDetails(
fileName,
position,
entryName,
formatOptions,
preferences,
data,
)
);
}
}
function getCompletionEntrySymbol(
fileName: string,
position: number,
name: string,
source: string | undefined,
): ts.Symbol | undefined {
if (angularOnly || !isTypeScriptFile(fileName)) {
return ngLS.getCompletionEntrySymbol(fileName, position, name);
} else {
// If TS could answer the query, then return that result. Otherwise, return from Angular LS.
return (
tsLS.getCompletionEntrySymbol(fileName, position, name, source) ??
ngLS.getCompletionEntrySymbol(fileName, position, name)
);
}
}
/**
* Gets global diagnostics related to the program configuration and compiler options.
*/
function getCompilerOptionsDiagnostics(): ts.Diagnostic[] {
const diagnostics: ts.Diagnostic[] = [];
if (!angularOnly) {
diagnostics.push(...tsLS.getCompilerOptionsDiagnostics());
}
diagnostics.push(...ngLS.getCompilerOptionsDiagnostics());
return diagnostics;
}
function getSignatureHelpItems(
fileName: string,
position: number,
options: ts.SignatureHelpItemsOptions,
): ts.SignatureHelpItems | undefined {
if (angularOnly || !isTypeScriptFile(fileName)) {
return ngLS.getSignatureHelpItems(fileName, position, options);
} else {
return (
tsLS.getSignatureHelpItems(fileName, position, options) ??
ngLS.getSignatureHelpItems(fileName, position, options)
);
}
}
function getOutliningSpans(fileName: string): ts.OutliningSpan[] {
if (angularOnly || !isTypeScriptFile(fileName)) {
return ngLS.getOutliningSpans(fileName);
} else {
return tsLS.getOutliningSpans(fileName) ?? ngLS.getOutliningSpans(fileName);
}
}
function getTcb(fileName: string, position: number): GetTcbResponse | undefined {
return ngLS.getTcb(fileName, position);
}
/**
* Given an external template, finds the associated components that use it as a `templateUrl`.
*/
function getComponentLocationsForTemplate(
fileName: string,
): GetComponentLocationsForTemplateResponse {
return ngLS.getComponentLocationsForTemplate(fileName);
}
/**
* Given a location inside a component, finds the location of the inline template or the file for
* the `templateUrl`.
*/
function getTemplateLocationForComponent(
fileName: string,
position: number,
): GetTemplateLocationForComponentResponse {
return ngLS.getTemplateLocationForComponent(fileName, position);
}
function getApplicableRefactors(
fileName: string,
positionOrRange: number | ts.TextRange,
): ts.ApplicableRefactorInfo[] {
// We never forward to TS for refactors because those are not handled
// properly by the LSP server implementation of the extension. The extension
// will only take care of refactorings from Angular language service.
// Code actions are tied to their provider, so this is unproblematic and will
// not hide built-in TypeScript refactorings:
// https://github.com/microsoft/vscode/blob/ea4d99921cc790d49194e897021faee02a1847f7/src/vs/editor/contrib/codeAction/codeAction.ts#L30-L31
return ngLS.getPossibleRefactorings(fileName, positionOrRange);
} | {
"end_byte": 9524,
"start_byte": 561,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/ts_plugin.ts"
} |
angular/packages/language-service/src/ts_plugin.ts_9528_13656 | function applyRefactoring(
fileName: string,
positionOrRange: number | ts.TextRange,
refactorName: string,
reportProgress: ApplyRefactoringProgressFn,
): Promise<ApplyRefactoringResult | undefined> {
return ngLS.applyRefactoring(fileName, positionOrRange, refactorName, reportProgress);
}
function getCodeFixesAtPosition(
fileName: string,
start: number,
end: number,
errorCodes: readonly number[],
formatOptions: ts.FormatCodeSettings,
preferences: ts.UserPreferences,
): readonly ts.CodeFixAction[] {
if (angularOnly || !isTypeScriptFile(fileName)) {
return ngLS.getCodeFixesAtPosition(
fileName,
start,
end,
errorCodes,
formatOptions,
preferences,
);
} else {
const tsLsCodeFixes = tsLS.getCodeFixesAtPosition(
fileName,
start,
end,
errorCodes,
formatOptions,
preferences,
);
// If TS could answer the query, then return that result. Otherwise, return from Angular LS.
return tsLsCodeFixes.length > 0
? tsLsCodeFixes
: ngLS.getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences);
}
}
function getCombinedCodeFix(
scope: ts.CombinedCodeFixScope,
fixId: string,
formatOptions: ts.FormatCodeSettings,
preferences: ts.UserPreferences,
): ts.CombinedCodeActions {
if (angularOnly) {
return ngLS.getCombinedCodeFix(scope, fixId, formatOptions, preferences);
} else {
const tsLsCombinedCodeFix = tsLS.getCombinedCodeFix(scope, fixId, formatOptions, preferences);
// If TS could answer the query, then return that result. Otherwise, return from Angular LS.
return tsLsCombinedCodeFix.changes.length > 0
? tsLsCombinedCodeFix
: ngLS.getCombinedCodeFix(scope, fixId, formatOptions, preferences);
}
}
function getTypescriptLanguageService() {
return tsLS;
}
return {
...tsLS,
getSyntacticDiagnostics,
getSemanticDiagnostics,
getSuggestionDiagnostics,
getTypeDefinitionAtPosition,
getQuickInfoAtPosition,
getDefinitionAtPosition,
getDefinitionAndBoundSpan,
getReferencesAtPosition,
findRenameLocations,
getRenameInfo,
getCompletionsAtPosition,
getCompletionEntryDetails,
getCompletionEntrySymbol,
getTcb,
getCompilerOptionsDiagnostics,
getComponentLocationsForTemplate,
getSignatureHelpItems,
getOutliningSpans,
getTemplateLocationForComponent,
hasCodeFixesForErrorCode: ngLS.hasCodeFixesForErrorCode.bind(ngLS),
getCodeFixesAtPosition,
getCombinedCodeFix,
getTypescriptLanguageService,
getApplicableRefactors,
applyRefactoring,
};
}
export function getExternalFiles(project: ts.server.Project): string[] {
if (!project.hasRoots()) {
return []; // project has not been initialized
}
const typecheckFiles: string[] = [];
const resourceFiles: string[] = [];
for (const scriptInfo of project.getScriptInfos()) {
if (scriptInfo.scriptKind === ts.ScriptKind.External) {
// script info for typecheck file is marked as external, see
// getOrCreateTypeCheckScriptInfo() in
// packages/language-service/src/language_service.ts
typecheckFiles.push(scriptInfo.fileName);
}
if (scriptInfo.scriptKind === ts.ScriptKind.Unknown) {
// script info for resource file is marked as unknown.
// Including these as external files is necessary because otherwise they will get removed from
// the project when `updateNonInferredProjectFiles` is called as part of the
// `updateProjectIfDirty` cycle.
// https://sourcegraph.com/github.com/microsoft/TypeScript@c300fea3250abd7f75920d95a58d9e742ac730ee/-/blob/src/server/editorServices.ts?L2363
resourceFiles.push(scriptInfo.fileName);
}
}
return [...typecheckFiles, ...resourceFiles];
}
/** Implementation of a ts.server.PluginModuleFactory */
export function initialize(mod: {typescript: typeof ts}): ts.server.PluginModule {
return {
create,
getExternalFiles,
};
} | {
"end_byte": 13656,
"start_byte": 9528,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/ts_plugin.ts"
} |
angular/packages/language-service/src/attribute_completions.ts_0_5772 | /**
* @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 {CssSelector, SelectorMatcher, TmplAstElement, TmplAstTemplate} from '@angular/compiler';
import {
ElementSymbol,
PotentialDirective,
TemplateSymbol,
TemplateTypeChecker,
TypeCheckableDirectiveMeta,
} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
import {DisplayInfoKind, unsafeCastDisplayInfoKindToScriptElementKind} from './utils/display_parts';
import {makeElementSelector} from './utils';
/**
* Differentiates different kinds of `AttributeCompletion`s.
*/
export enum AttributeCompletionKind {
/**
* Completion of an attribute from the HTML schema.
*
* Attributes often have a corresponding DOM property of the same name.
*/
DomAttribute,
/**
* Completion of a property from the DOM schema.
*
* `DomProperty` completions are generated only for properties which don't share their name with
* an HTML attribute.
*/
DomProperty,
/**
* Completion of an event from the DOM schema.
*/
DomEvent,
/**
* Completion of an attribute that results in a new directive being matched on an element.
*/
DirectiveAttribute,
/**
* Completion of an attribute that results in a new structural directive being matched on an
* element.
*/
StructuralDirectiveAttribute,
/**
* Completion of an input from a directive which is either present on the element, or becomes
* present after the addition of this attribute.
*/
DirectiveInput,
/**
* Completion of an output from a directive which is either present on the element, or becomes
* present after the addition of this attribute.
*/
DirectiveOutput,
}
/**
* Completion of an attribute from the DOM schema.
*/
export interface DomAttributeCompletion {
kind: AttributeCompletionKind.DomAttribute;
/**
* Name of the HTML attribute (not to be confused with the corresponding DOM property name).
*/
attribute: string;
/**
* Whether this attribute is also a DOM property. Note that this is required to be `true` because
* we only want to provide DOM attributes when there is an Angular syntax associated with them
* (`[propertyName]=""`).
*/
isAlsoProperty: true;
}
/**
* Completion of a DOM property of an element that's distinct from an HTML attribute.
*/
export interface DomPropertyCompletion {
kind: AttributeCompletionKind.DomProperty;
/**
* Name of the DOM property
*/
property: string;
}
export interface DomEventCompletion {
kind: AttributeCompletionKind.DomEvent;
/**
* Name of the DOM event
*/
eventName: string;
}
/**
* Completion of an attribute which results in a new directive being matched on an element.
*/
export interface DirectiveAttributeCompletion {
kind:
| AttributeCompletionKind.DirectiveAttribute
| AttributeCompletionKind.StructuralDirectiveAttribute;
/**
* Name of the attribute whose addition causes this directive to match the element.
*/
attribute: string;
/**
* The directive whose selector gave rise to this completion.
*/
directive: PotentialDirective;
}
/**
* Completion of an input of a directive which may either be present on the element, or become
* present when a binding to this input is added.
*/
export interface DirectiveInputCompletion {
kind: AttributeCompletionKind.DirectiveInput;
/**
* The public property name of the input (the name which would be used in any binding to that
* input).
*/
propertyName: string;
/**
* The directive which has this input.
*/
directive: PotentialDirective;
/**
* The field name on the directive class which corresponds to this input.
*
* Currently, in the case where a single property name corresponds to multiple input fields, only
* the first such field is represented here. In the future multiple results may be warranted.
*/
classPropertyName: string;
/**
* Whether this input can be used with two-way binding (that is, whether a corresponding change
* output exists on the directive).
*/
twoWayBindingSupported: boolean;
}
export interface DirectiveOutputCompletion {
kind: AttributeCompletionKind.DirectiveOutput;
/**
* The public event name of the output (the name which would be used in any binding to that
* output).
*/
eventName: string;
/**
*The directive which has this output.
*/
directive: PotentialDirective;
/**
* The field name on the directive class which corresponds to this output.
*/
classPropertyName: string;
}
/**
* Any named attribute which is available for completion on a given element.
*
* Disambiguated by the `kind` property into various types of completions.
*/
export type AttributeCompletion =
| DomAttributeCompletion
| DomPropertyCompletion
| DirectiveAttributeCompletion
| DirectiveInputCompletion
| DirectiveOutputCompletion
| DomEventCompletion;
/**
* Given an element and its context, produce a `Map` of all possible attribute completions.
*
* 3 kinds of attributes are considered for completion, from highest to lowest priority:
*
* 1. Inputs/outputs of directives present on the element already.
* 2. Inputs/outputs of directives that are not present on the element, but which would become
* present if such a binding is added.
* 3. Attributes from the DOM schema for the element.
*
* The priority of these options determines which completions are added to the `Map`. If a directive
* input shares the same name as a DOM attribute, the `Map` will reflect the directive input
* completion, not the DOM completion for that name.
*/ | {
"end_byte": 5772,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/attribute_completions.ts"
} |
angular/packages/language-service/src/attribute_completions.ts_5773_15165 | export function buildAttributeCompletionTable(
component: ts.ClassDeclaration,
element: TmplAstElement | TmplAstTemplate,
checker: TemplateTypeChecker,
): Map<string, AttributeCompletion> {
const table = new Map<string, AttributeCompletion>();
// Use the `ElementSymbol` or `TemplateSymbol` to iterate over directives present on the node, and
// their inputs/outputs. These have the highest priority of completion results.
const symbol: ElementSymbol | TemplateSymbol = checker.getSymbolOfNode(element, component) as
| ElementSymbol
| TemplateSymbol;
const presentDirectives = new Set<ts.ClassDeclaration>();
if (symbol !== null) {
// An `ElementSymbol` was available. This means inputs and outputs for directives on the
// element can be added to the completion table.
for (const dirSymbol of symbol.directives) {
const directive = dirSymbol.tsSymbol.valueDeclaration;
if (!ts.isClassDeclaration(directive)) {
continue;
}
presentDirectives.add(directive);
const meta = checker.getDirectiveMetadata(directive);
if (meta === null) {
continue;
}
for (const {classPropertyName, bindingPropertyName} of meta.inputs) {
let propertyName: string;
if (dirSymbol.isHostDirective) {
if (!dirSymbol.exposedInputs?.hasOwnProperty(bindingPropertyName)) {
continue;
}
propertyName = dirSymbol.exposedInputs[bindingPropertyName];
} else {
propertyName = bindingPropertyName;
}
if (table.has(propertyName)) {
continue;
}
table.set(propertyName, {
kind: AttributeCompletionKind.DirectiveInput,
propertyName,
directive: dirSymbol,
classPropertyName,
twoWayBindingSupported: meta.outputs.hasBindingPropertyName(propertyName + 'Change'),
});
}
for (const {classPropertyName, bindingPropertyName} of meta.outputs) {
let propertyName: string;
if (dirSymbol.isHostDirective) {
if (!dirSymbol.exposedOutputs?.hasOwnProperty(bindingPropertyName)) {
continue;
}
propertyName = dirSymbol.exposedOutputs[bindingPropertyName];
} else {
propertyName = bindingPropertyName;
}
if (table.has(propertyName)) {
continue;
}
table.set(propertyName, {
kind: AttributeCompletionKind.DirectiveOutput,
eventName: propertyName,
directive: dirSymbol,
classPropertyName,
});
}
}
}
// Next, explore hypothetical directives and determine if the addition of any single attributes
// can cause the directive to match the element.
const directivesInScope = checker
.getPotentialTemplateDirectives(component)
.filter((d) => d.isInScope);
if (directivesInScope !== null) {
const elementSelector = makeElementSelector(element);
for (const dirInScope of directivesInScope) {
const directive = dirInScope.tsSymbol.valueDeclaration;
// Skip directives that are present on the element.
if (!ts.isClassDeclaration(directive) || presentDirectives.has(directive)) {
continue;
}
const meta = checker.getDirectiveMetadata(directive);
if (meta === null || meta.selector === null) {
continue;
}
if (!meta.isStructural) {
// For non-structural directives, the directive's attribute selector(s) are matched against
// a hypothetical version of the element with those attributes. A match indicates that
// adding that attribute/input/output binding would cause the directive to become present,
// meaning that such a binding is a valid completion.
const selectors = CssSelector.parse(meta.selector);
const matcher = new SelectorMatcher();
matcher.addSelectables(selectors);
for (const selector of selectors) {
for (const [attrName, attrValue] of selectorAttributes(selector)) {
if (attrValue !== '') {
// This attribute selector requires a value, which is not supported in completion.
continue;
}
if (table.has(attrName)) {
// Skip this attribute as there's already a binding for it.
continue;
}
// Check whether adding this attribute would cause the directive to start matching.
const newElementSelector = elementSelector + `[${attrName}]`;
if (!matcher.match(CssSelector.parse(newElementSelector)[0], null)) {
// Nope, move on with our lives.
continue;
}
// Adding this attribute causes a new directive to be matched. Decide how to categorize
// it based on the directive's inputs and outputs.
if (meta.inputs.hasBindingPropertyName(attrName)) {
// This attribute corresponds to an input binding.
table.set(attrName, {
kind: AttributeCompletionKind.DirectiveInput,
directive: dirInScope,
propertyName: attrName,
classPropertyName:
meta.inputs.getByBindingPropertyName(attrName)![0].classPropertyName,
twoWayBindingSupported: meta.outputs.hasBindingPropertyName(attrName + 'Change'),
});
} else if (meta.outputs.hasBindingPropertyName(attrName)) {
// This attribute corresponds to an output binding.
table.set(attrName, {
kind: AttributeCompletionKind.DirectiveOutput,
directive: dirInScope,
eventName: attrName,
classPropertyName:
meta.outputs.getByBindingPropertyName(attrName)![0].classPropertyName,
});
} else {
// This attribute causes a new directive to be matched, but does not also correspond
// to an input or output binding.
table.set(attrName, {
kind: AttributeCompletionKind.DirectiveAttribute,
attribute: attrName,
directive: dirInScope,
});
}
}
}
} else {
// Hypothetically matching a structural directive is a little different than a plain
// directive. Use of the '*' structural directive syntactic sugar means that the actual
// directive is applied to a plain <ng-template> node, not the existing element with any
// other attributes it might already have.
// Additionally, more than one attribute/input might need to be present in order for the
// directive to match (e.g. `ngFor` has a selector of `[ngFor][ngForOf]`). This gets a
// little tricky.
const structuralAttributes = getStructuralAttributes(meta);
for (const attrName of structuralAttributes) {
table.set(attrName, {
kind: AttributeCompletionKind.StructuralDirectiveAttribute,
attribute: attrName,
directive: dirInScope,
});
}
}
}
}
// Finally, add any DOM attributes not already covered by inputs.
if (element instanceof TmplAstElement) {
for (const {attribute, property} of checker.getPotentialDomBindings(element.name)) {
const isAlsoProperty = attribute === property;
if (!table.has(attribute) && isAlsoProperty) {
table.set(attribute, {
kind: AttributeCompletionKind.DomAttribute,
attribute,
isAlsoProperty,
});
}
}
for (const event of checker.getPotentialDomEvents(element.name)) {
table.set(event, {
kind: AttributeCompletionKind.DomEvent,
eventName: event,
});
}
}
return table;
}
function buildSnippet(insertSnippet: true | undefined, text: string): string | undefined {
return insertSnippet ? `${text}="$1"` : undefined;
}
/**
* Used to ensure Angular completions appear before DOM completions. Inputs and Outputs are
* prioritized first while attributes which would match an additional directive are prioritized
* second.
*
* This sort priority is based on the ASCII table. Other than `space`, the `!` is the first
* printable character in the ASCII ordering.
*/
export enum AsciiSortPriority {
First = '!',
Second = '"',
}
/**
* Given an `AttributeCompletion`, add any available completions to a `ts.CompletionEntry` array of
* results.
*
* The kind of completions generated depends on whether the current context is an attribute context
* or not. For example, completing on `<element attr|>` will generate two results: `attribute` and
* `[attribute]` - either a static attribute can be generated, or a property binding. However,
* `<element [attr|]>` is not an attribute context, and so only the property completion `attribute`
* is generated. Note that this completion does not have the `[]` property binding sugar as its
* implicitly present in a property binding context (we're already completing within an `[attr|]`
* expression).
*
* If the `insertSnippet` is `true`, the completion entries should includes the property or event
* binding sugar in some case. For Example `<div (my¦) />`, the `replacementSpan` is `(my)`, and the
* `insertText` is `(myOutput)="$0"`.
*/
| {
"end_byte": 15165,
"start_byte": 5773,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/attribute_completions.ts"
} |
angular/packages/language-service/src/attribute_completions.ts_15166_24758 | xport function addAttributeCompletionEntries(
entries: ts.CompletionEntry[],
completion: AttributeCompletion,
isAttributeContext: boolean,
isElementContext: boolean,
replacementSpan: ts.TextSpan | undefined,
insertSnippet: true | undefined,
): void {
switch (completion.kind) {
case AttributeCompletionKind.DirectiveAttribute: {
entries.push({
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
name: completion.attribute,
sortText: AsciiSortPriority.Second + completion.attribute,
replacementSpan,
});
break;
}
case AttributeCompletionKind.StructuralDirectiveAttribute: {
// In an element, the completion is offered with a leading '*' to activate the structural
// directive. Once present, the structural attribute will be parsed as a template and not an
// element, and the prefix is no longer necessary.
const prefix = isElementContext ? '*' : '';
entries.push({
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.DIRECTIVE),
name: prefix + completion.attribute,
insertText: buildSnippet(insertSnippet, prefix + completion.attribute),
isSnippet: insertSnippet,
sortText: AsciiSortPriority.Second + prefix + completion.attribute,
replacementSpan,
});
break;
}
case AttributeCompletionKind.DirectiveInput: {
if (isAttributeContext || insertSnippet) {
// Offer a completion of a property binding.
entries.push({
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
name: `[${completion.propertyName}]`,
insertText: buildSnippet(insertSnippet, `[${completion.propertyName}]`),
isSnippet: insertSnippet,
sortText: AsciiSortPriority.First + completion.propertyName,
replacementSpan,
});
// If the directive supports banana-in-a-box for this input, offer that as well.
if (completion.twoWayBindingSupported) {
entries.push({
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
name: `[(${completion.propertyName})]`,
insertText: buildSnippet(insertSnippet, `[(${completion.propertyName})]`),
isSnippet: insertSnippet,
// This completion should sort after the property binding.
sortText: AsciiSortPriority.First + completion.propertyName + '_1',
replacementSpan,
});
}
// Offer a completion of the input binding as an attribute.
entries.push({
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.ATTRIBUTE),
name: completion.propertyName,
insertText: buildSnippet(insertSnippet, completion.propertyName),
isSnippet: insertSnippet,
// This completion should sort after both property binding options (one-way and two-way).
sortText: AsciiSortPriority.First + completion.propertyName + '_2',
replacementSpan,
});
} else {
entries.push({
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
name: completion.propertyName,
insertText: buildSnippet(insertSnippet, completion.propertyName),
isSnippet: insertSnippet,
sortText: AsciiSortPriority.First + completion.propertyName,
replacementSpan,
});
}
break;
}
case AttributeCompletionKind.DirectiveOutput: {
if (isAttributeContext || insertSnippet) {
entries.push({
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
name: `(${completion.eventName})`,
insertText: buildSnippet(insertSnippet, `(${completion.eventName})`),
isSnippet: insertSnippet,
sortText: AsciiSortPriority.First + completion.eventName,
replacementSpan,
});
} else {
entries.push({
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
name: completion.eventName,
insertText: buildSnippet(insertSnippet, completion.eventName),
isSnippet: insertSnippet,
sortText: AsciiSortPriority.First + completion.eventName,
replacementSpan,
});
}
break;
}
case AttributeCompletionKind.DomAttribute: {
if ((isAttributeContext || insertSnippet) && completion.isAlsoProperty) {
// Offer a completion of a property binding to the DOM property.
entries.push({
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
name: `[${completion.attribute}]`,
insertText: buildSnippet(insertSnippet, `[${completion.attribute}]`),
isSnippet: insertSnippet,
// In the case of DOM attributes, the property binding should sort after the attribute
// binding.
sortText: completion.attribute + '_1',
replacementSpan,
});
}
break;
}
case AttributeCompletionKind.DomProperty: {
if (!isAttributeContext) {
entries.push({
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.PROPERTY),
name: completion.property,
insertText: buildSnippet(insertSnippet, completion.property),
isSnippet: insertSnippet,
sortText: completion.property,
replacementSpan,
});
}
break;
}
case AttributeCompletionKind.DomEvent: {
entries.push({
kind: unsafeCastDisplayInfoKindToScriptElementKind(DisplayInfoKind.EVENT),
name: `(${completion.eventName})`,
insertText: buildSnippet(insertSnippet, `(${completion.eventName})`),
isSnippet: insertSnippet,
sortText: completion.eventName,
replacementSpan,
});
break;
}
}
}
export function getAttributeCompletionSymbol(
completion: AttributeCompletion,
checker: ts.TypeChecker,
): ts.Symbol | null {
switch (completion.kind) {
case AttributeCompletionKind.DomAttribute:
case AttributeCompletionKind.DomEvent:
case AttributeCompletionKind.DomProperty:
return null;
case AttributeCompletionKind.DirectiveAttribute:
case AttributeCompletionKind.StructuralDirectiveAttribute:
return completion.directive.tsSymbol;
case AttributeCompletionKind.DirectiveInput:
case AttributeCompletionKind.DirectiveOutput:
return (
checker
.getDeclaredTypeOfSymbol(completion.directive.tsSymbol)
.getProperty(completion.classPropertyName) ?? null
);
}
}
/**
* Iterates over `CssSelector` attributes, which are internally represented in a zipped array style
* which is not conducive to straightforward iteration.
*/
function* selectorAttributes(selector: CssSelector): Iterable<[string, string]> {
for (let i = 0; i < selector.attrs.length; i += 2) {
yield [selector.attrs[0], selector.attrs[1]];
}
}
function getStructuralAttributes(meta: TypeCheckableDirectiveMeta): string[] {
if (meta.selector === null) {
return [];
}
const structuralAttributes: string[] = [];
const selectors = CssSelector.parse(meta.selector);
for (const selector of selectors) {
if (selector.element !== null && selector.element !== 'ng-template') {
// This particular selector does not apply under structural directive syntax.
continue;
}
// Every attribute of this selector must be name-only - no required values.
const attributeSelectors = Array.from(selectorAttributes(selector));
if (!attributeSelectors.every(([_, attrValue]) => attrValue === '')) {
continue;
}
// Get every named selector.
const attributes = attributeSelectors.map(([attrName, _]) => attrName);
// Find the shortest attribute. This is the structural directive "base", and all potential
// input bindings must begin with the base. E.g. in `*ngFor="let a of b"`, `ngFor` is the
// base attribute, and the `of` binding key corresponds to an input of `ngForOf`.
const baseAttr = attributes.reduce(
(prev, curr) => (prev === null || curr.length < prev.length ? curr : prev),
null as string | null,
);
if (baseAttr === null) {
// No attributes in this selector?
continue;
}
// Validate that the attributes are compatible with use as a structural directive.
const isValid = (attr: string): boolean => {
// The base attribute is valid by default.
if (attr === baseAttr) {
return true;
}
// Non-base attributes must all be prefixed with the base attribute.
if (!attr.startsWith(baseAttr)) {
return false;
}
// Non-base attributes must also correspond to directive inputs.
if (!meta.inputs.hasBindingPropertyName(attr)) {
return false;
}
// This attribute is compatible.
return true;
};
if (!attributes.every(isValid)) {
continue;
}
// This attribute is valid as a structural attribute for this directive.
structuralAttributes.push(baseAttr);
}
return structuralAttributes;
}
export function buildAnimationCompletionEntries(
animations: string[],
replacementSpan: ts.TextSpan,
kind: DisplayInfoKind,
): ts.CompletionEntry[] {
return animations.map((animation) => {
return {
kind: unsafeCastDisplayInfoKindToScriptElementKind(kind),
name: animation,
sortText: animation,
replacementSpan,
};
});
}
| {
"end_byte": 24758,
"start_byte": 15166,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/attribute_completions.ts"
} |
angular/packages/language-service/src/template_target.ts_0_6313 | /**
* @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 {
AbsoluteSourceSpan,
AST,
ASTWithSource,
Call,
ImplicitReceiver,
ParseSourceSpan,
ParseSpan,
PropertyRead,
RecursiveAstVisitor,
SafeCall,
TmplAstBoundAttribute,
TmplAstBoundDeferredTrigger,
TmplAstBoundEvent,
TmplAstBoundText,
TmplAstContent,
TmplAstDeferredBlock,
TmplAstDeferredBlockError,
TmplAstDeferredBlockLoading,
TmplAstDeferredBlockPlaceholder,
TmplAstDeferredTrigger,
TmplAstElement,
TmplAstForLoopBlock,
TmplAstForLoopBlockEmpty,
TmplAstIcu,
TmplAstIfBlock,
TmplAstIfBlockBranch,
TmplAstLetDeclaration,
TmplAstNode,
TmplAstReference,
TmplAstSwitchBlock,
TmplAstSwitchBlockCase,
TmplAstTemplate,
TmplAstText,
TmplAstTextAttribute,
TmplAstUnknownBlock,
TmplAstVariable,
tmplAstVisitAll,
TmplAstVisitor,
} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {findFirstMatchingNode} from '@angular/compiler-cli/src/ngtsc/typecheck/src/comments';
import tss from 'typescript';
import {
isBoundEventWithSyntheticHandler,
isTemplateNodeWithKeyAndValue,
isWithin,
isWithinKeyValue,
TemplateInfo,
} from './utils';
/**
* Contextual information for a target position within the template.
*/
export interface TemplateTarget {
/**
* Target position within the template.
*/
position: number;
/**
* The template (or AST expression) node or nodes closest to the search position.
*/
context: TargetContext;
/**
* The `TmplAstTemplate` which contains the found node or expression (or `null` if in the root
* template).
*/
template: TmplAstTemplate | null;
/**
* The immediate parent node of the targeted node.
*/
parent: TmplAstNode | AST | null;
}
/**
* A node or nodes targeted at a given position in the template, including potential contextual
* information about the specific aspect of the node being referenced.
*
* Some nodes have multiple interior contexts. For example, `TmplAstElement` nodes have both a tag
* name as well as a body, and a given position definitively points to one or the other.
* `TargetNode` captures the node itself, as well as this additional contextual disambiguation.
*/
export type TargetContext = SingleNodeTarget | MultiNodeTarget;
/** Contexts which logically target only a single node in the template AST. */
export type SingleNodeTarget =
| RawExpression
| CallExpressionInArgContext
| RawTemplateNode
| ElementInBodyContext
| ElementInTagContext
| AttributeInKeyContext
| AttributeInValueContext;
/**
* Contexts which logically target multiple nodes in the template AST, which cannot be
* disambiguated given a single position because they are all equally relevant. For example, in the
* banana-in-a-box syntax `[(ngModel)]="formValues.person"`, the position in the template for the
* key `ngModel` refers to both the bound event `ngModelChange` and the input `ngModel`.
*/
export type MultiNodeTarget = TwoWayBindingContext;
/**
* Differentiates the various kinds of `TargetNode`s.
*/
export enum TargetNodeKind {
RawExpression,
CallExpressionInArgContext,
RawTemplateNode,
ElementInTagContext,
ElementInBodyContext,
AttributeInKeyContext,
AttributeInValueContext,
TwoWayBindingContext,
}
/**
* An `AST` expression that's targeted at a given position, with no additional context.
*/
export interface RawExpression {
kind: TargetNodeKind.RawExpression;
node: AST;
parents: AST[];
}
/**
* An `e.Call` expression with the cursor in a position where an argument could appear.
*
* This is returned when the only matching node is the method call expression, but the cursor is
* within the method call parentheses. For example, in the expression `foo(|)` there is no argument
* expression that the cursor could be targeting, but the cursor is in a position where one could
* appear.
*/
export interface CallExpressionInArgContext {
kind: TargetNodeKind.CallExpressionInArgContext;
node: Call | SafeCall;
}
/**
* A `TmplAstNode` template node that's targeted at a given position, with no additional context.
*/
export interface RawTemplateNode {
kind: TargetNodeKind.RawTemplateNode;
node: TmplAstNode;
}
/**
* A `TmplAstElement` (or `TmplAstTemplate`) element node that's targeted, where the given position
* is within the tag name.
*/
export interface ElementInTagContext {
kind: TargetNodeKind.ElementInTagContext;
node: TmplAstElement | TmplAstTemplate;
}
/**
* A `TmplAstElement` (or `TmplAstTemplate`) element node that's targeted, where the given position
* is within the element body.
*/
export interface ElementInBodyContext {
kind: TargetNodeKind.ElementInBodyContext;
node: TmplAstElement | TmplAstTemplate;
}
export interface AttributeInKeyContext {
kind: TargetNodeKind.AttributeInKeyContext;
node: TmplAstTextAttribute | TmplAstBoundAttribute | TmplAstBoundEvent;
}
export interface AttributeInValueContext {
kind: TargetNodeKind.AttributeInValueContext;
node: TmplAstTextAttribute | TmplAstBoundAttribute | TmplAstBoundEvent;
}
/**
* A `TmplAstBoundAttribute` and `TmplAstBoundEvent` pair that are targeted, where the given
* position is within the key span of both.
*/
export interface TwoWayBindingContext {
kind: TargetNodeKind.TwoWayBindingContext;
nodes: [TmplAstBoundAttribute, TmplAstBoundEvent];
}
/**
* Special marker AST that can be used when the cursor is within the `sourceSpan` but not
* the key or value span of a node with key/value spans.
*/
class OutsideKeyValueMarkerAst extends AST {
override visit(): null {
return null;
}
}
/**
* This special marker is added to the path when the cursor is within the sourceSpan but not the key
* or value span of a node with key/value spans.
*/
const OUTSIDE_K_V_MARKER = new OutsideKeyValueMarkerAst(
new ParseSpan(-1, -1),
new AbsoluteSourceSpan(-1, -1),
);
/**
* Return the template AST node or expression AST node that most accurately
* represents the node at the specified cursor `position`.
*
* @param template AST tree of the template
* @param position target cursor position
*/ | {
"end_byte": 6313,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/template_target.ts"
} |
angular/packages/language-service/src/template_target.ts_6314_11983 | export function getTargetAtPosition(
template: TmplAstNode[],
position: number,
): TemplateTarget | null {
const path = TemplateTargetVisitor.visitTemplate(template, position);
if (path.length === 0) {
return null;
}
const candidate = path[path.length - 1];
// Walk up the result nodes to find the nearest `TmplAstTemplate` which contains the targeted
// node.
let context: TmplAstTemplate | null = null;
for (let i = path.length - 2; i >= 0; i--) {
const node = path[i];
if (node instanceof TmplAstTemplate) {
context = node;
break;
}
}
// Given the candidate node, determine the full targeted context.
let nodeInContext: TargetContext;
if (
(candidate instanceof Call || candidate instanceof SafeCall) &&
isWithin(position, candidate.argumentSpan)
) {
nodeInContext = {
kind: TargetNodeKind.CallExpressionInArgContext,
node: candidate,
};
} else if (candidate instanceof AST) {
const parents = path.filter((value: AST | TmplAstNode): value is AST => value instanceof AST);
// Remove the current node from the parents list.
parents.pop();
nodeInContext = {
kind: TargetNodeKind.RawExpression,
node: candidate,
parents,
};
} else if (candidate instanceof TmplAstElement) {
// Elements have two contexts: the tag context (position is within the element tag) or the
// element body context (position is outside of the tag name, but still in the element).
// Calculate the end of the element tag name. Any position beyond this is in the element body.
const tagEndPos =
candidate.sourceSpan.start.offset + 1 /* '<' element open */ + candidate.name.length;
if (position > tagEndPos) {
// Position is within the element body
nodeInContext = {
kind: TargetNodeKind.ElementInBodyContext,
node: candidate,
};
} else {
nodeInContext = {
kind: TargetNodeKind.ElementInTagContext,
node: candidate,
};
}
} else if (
(candidate instanceof TmplAstBoundAttribute ||
candidate instanceof TmplAstBoundEvent ||
candidate instanceof TmplAstTextAttribute) &&
candidate.keySpan !== undefined
) {
const previousCandidate = path[path.length - 2];
if (
candidate instanceof TmplAstBoundEvent &&
previousCandidate instanceof TmplAstBoundAttribute &&
candidate.name === previousCandidate.name + 'Change'
) {
const boundAttribute: TmplAstBoundAttribute = previousCandidate;
const boundEvent: TmplAstBoundEvent = candidate;
nodeInContext = {
kind: TargetNodeKind.TwoWayBindingContext,
nodes: [boundAttribute, boundEvent],
};
} else if (isWithin(position, candidate.keySpan)) {
nodeInContext = {
kind: TargetNodeKind.AttributeInKeyContext,
node: candidate,
};
} else {
nodeInContext = {
kind: TargetNodeKind.AttributeInValueContext,
node: candidate,
};
}
} else {
nodeInContext = {
kind: TargetNodeKind.RawTemplateNode,
node: candidate,
};
}
let parent: TmplAstNode | AST | null = null;
if (nodeInContext.kind === TargetNodeKind.TwoWayBindingContext && path.length >= 3) {
parent = path[path.length - 3];
} else if (path.length >= 2) {
parent = path[path.length - 2];
}
return {position, context: nodeInContext, template: context, parent};
}
function findFirstMatchingNodeForSourceSpan(
tcb: tss.Node,
sourceSpan: ParseSourceSpan | AbsoluteSourceSpan,
) {
return findFirstMatchingNode(tcb, {
withSpan: sourceSpan,
filter: (node: tss.Node): node is tss.Node => true,
});
}
/**
* A tcb nodes for the template at a given position, include the tcb node of the template.
*/
interface TcbNodesInfoForTemplate {
componentTcbNode: tss.Node;
nodes: tss.Node[];
}
/**
* Return the nodes in `TCB` of the node at the specified cursor `position`.
*
*/
export function getTcbNodesOfTemplateAtPosition(
templateInfo: TemplateInfo,
position: number,
compiler: NgCompiler,
): TcbNodesInfoForTemplate | null {
const target = getTargetAtPosition(templateInfo.template, position);
if (target === null) {
return null;
}
const tcb = compiler.getTemplateTypeChecker().getTypeCheckBlock(templateInfo.component);
if (tcb === null) {
return null;
}
const tcbNodes: (tss.Node | null)[] = [];
if (target.context.kind === TargetNodeKind.RawExpression) {
const targetNode = target.context.node;
if (targetNode instanceof PropertyRead) {
const tsNode = findFirstMatchingNode(tcb, {
withSpan: targetNode.nameSpan,
filter: (node): node is tss.PropertyAccessExpression =>
tss.isPropertyAccessExpression(node),
});
tcbNodes.push(tsNode?.name ?? null);
} else {
tcbNodes.push(findFirstMatchingNodeForSourceSpan(tcb, target.context.node.sourceSpan));
}
} else if (target.context.kind === TargetNodeKind.TwoWayBindingContext) {
const targetNodes = target.context.nodes
.map((n) => n.sourceSpan)
.map((node) => {
return findFirstMatchingNodeForSourceSpan(tcb, node);
});
tcbNodes.push(...targetNodes);
} else {
tcbNodes.push(findFirstMatchingNodeForSourceSpan(tcb, target.context.node.sourceSpan));
}
return {
nodes: tcbNodes.filter((n): n is tss.Node => n !== null),
componentTcbNode: tcb,
};
}
/**
* Visitor which, given a position and a template, identifies the node within the template at that
* position, as well as records the path of increasingly nested nodes that were traversed to reach
* that position.
*/ | {
"end_byte": 11983,
"start_byte": 6314,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/template_target.ts"
} |
angular/packages/language-service/src/template_target.ts_11984_20080 | class TemplateTargetVisitor implements TmplAstVisitor {
// We need to keep a path instead of the last node because we might need more
// context for the last node, for example what is the parent node?
readonly path: Array<TmplAstNode | AST> = [];
static visitTemplate(template: TmplAstNode[], position: number): Array<TmplAstNode | AST> {
const visitor = new TemplateTargetVisitor(position);
visitor.visitAll(template);
const {path} = visitor;
const strictPath = path.filter((v) => v !== OUTSIDE_K_V_MARKER);
const candidate = strictPath[strictPath.length - 1];
const matchedASourceSpanButNotAKvSpan = path.some((v) => v === OUTSIDE_K_V_MARKER);
if (
matchedASourceSpanButNotAKvSpan &&
(candidate instanceof TmplAstTemplate || candidate instanceof TmplAstElement)
) {
// Template nodes with key and value spans are always defined on a `TmplAstTemplate` or
// `TmplAstElement`. If we found a node on a template with a `sourceSpan` that includes the
// cursor, it is possible that we are outside the k/v spans (i.e. in-between them). If this is
// the case and we do not have any other candidate matches on the `TmplAstElement` or
// `TmplAstTemplate`, we want to return no results. Otherwise, the
// `TmplAstElement`/`TmplAstTemplate` result is incorrect for that cursor position.
return [];
}
return strictPath;
}
// Position must be absolute in the source file.
private constructor(private readonly position: number) {}
visit(node: TmplAstNode) {
const {start, end} = getSpanIncludingEndTag(node);
if (end !== null && !isWithin(this.position, {start, end})) {
return;
}
const last: TmplAstNode | AST | undefined = this.path[this.path.length - 1];
const withinKeySpanOfLastNode =
last && isTemplateNodeWithKeyAndValue(last) && isWithin(this.position, last.keySpan);
const withinKeySpanOfCurrentNode =
isTemplateNodeWithKeyAndValue(node) && isWithin(this.position, node.keySpan);
if (withinKeySpanOfLastNode && !withinKeySpanOfCurrentNode) {
// We've already identified that we are within a `keySpan` of a node.
// Unless we are _also_ in the `keySpan` of the current node (happens with two way bindings),
// we should stop processing nodes at this point to prevent matching any other nodes. This can
// happen when the end span of a different node touches the start of the keySpan for the
// candidate node. Because our `isWithin` logic is inclusive on both ends, we can match both
// nodes.
return;
}
if (last instanceof TmplAstUnknownBlock && isWithin(this.position, last.nameSpan)) {
// Autocompletions such as `@\nfoo`, where a newline follows a bare `@`, would not work
// because the language service visitor sees us inside the subsequent text node. We deal with
// this with using a special-case: if we are completing inside the name span, we don't
// continue to the subsequent text node.
return;
}
if (isTemplateNodeWithKeyAndValue(node) && !isWithinKeyValue(this.position, node)) {
// If cursor is within source span but not within key span or value span,
// do not return the node.
this.path.push(OUTSIDE_K_V_MARKER);
} else {
this.path.push(node);
node.visit(this);
}
}
visitElement(element: TmplAstElement) {
this.visitElementOrTemplate(element);
}
visitTemplate(template: TmplAstTemplate) {
this.visitElementOrTemplate(template);
}
visitElementOrTemplate(element: TmplAstTemplate | TmplAstElement) {
this.visitAll(element.attributes);
this.visitAll(element.inputs);
// We allow the path to contain both the `TmplAstBoundAttribute` and `TmplAstBoundEvent` for
// two-way bindings but do not want the path to contain both the `TmplAstBoundAttribute` with
// its children when the position is in the value span because we would then logically create a
// path that also contains the `PropertyWrite` from the `TmplAstBoundEvent`. This early return
// condition ensures we target just `TmplAstBoundAttribute` for this case and exclude
// `TmplAstBoundEvent` children.
if (
this.path[this.path.length - 1] !== element &&
!(this.path[this.path.length - 1] instanceof TmplAstBoundAttribute)
) {
return;
}
this.visitAll(element.outputs);
if (element instanceof TmplAstTemplate) {
this.visitAll(element.templateAttrs);
}
this.visitAll(element.references);
if (element instanceof TmplAstTemplate) {
this.visitAll(element.variables);
}
// If we get here and have not found a candidate node on the element itself, proceed with
// looking for a more specific node on the element children.
if (this.path[this.path.length - 1] !== element) {
return;
}
this.visitAll(element.children);
}
visitContent(content: TmplAstContent) {
tmplAstVisitAll(this, content.attributes);
this.visitAll(content.children);
}
visitVariable(variable: TmplAstVariable) {
// Variable has no template nodes or expression nodes.
}
visitReference(reference: TmplAstReference) {
// Reference has no template nodes or expression nodes.
}
visitTextAttribute(attribute: TmplAstTextAttribute) {
// Text attribute has no template nodes or expression nodes.
}
visitBoundAttribute(attribute: TmplAstBoundAttribute) {
if (attribute.valueSpan !== undefined) {
this.visitBinding(attribute.value);
}
}
visitBoundEvent(event: TmplAstBoundEvent) {
if (!isBoundEventWithSyntheticHandler(event)) {
this.visitBinding(event.handler);
}
}
visitText(text: TmplAstText) {
// Text has no template nodes or expression nodes.
}
visitBoundText(text: TmplAstBoundText) {
this.visitBinding(text.value);
}
visitIcu(icu: TmplAstIcu) {
for (const boundText of Object.values(icu.vars)) {
this.visit(boundText);
}
for (const boundTextOrText of Object.values(icu.placeholders)) {
this.visit(boundTextOrText);
}
}
visitDeferredBlock(deferred: TmplAstDeferredBlock) {
deferred.visitAll(this);
}
visitDeferredBlockPlaceholder(block: TmplAstDeferredBlockPlaceholder) {
this.visitAll(block.children);
}
visitDeferredBlockError(block: TmplAstDeferredBlockError) {
this.visitAll(block.children);
}
visitDeferredBlockLoading(block: TmplAstDeferredBlockLoading) {
this.visitAll(block.children);
}
visitDeferredTrigger(trigger: TmplAstDeferredTrigger) {
if (trigger instanceof TmplAstBoundDeferredTrigger) {
this.visitBinding(trigger.value);
}
}
visitSwitchBlock(block: TmplAstSwitchBlock) {
this.visitBinding(block.expression);
this.visitAll(block.cases);
this.visitAll(block.unknownBlocks);
}
visitSwitchBlockCase(block: TmplAstSwitchBlockCase) {
block.expression && this.visitBinding(block.expression);
this.visitAll(block.children);
}
visitForLoopBlock(block: TmplAstForLoopBlock) {
this.visit(block.item);
this.visitAll(block.contextVariables);
this.visitBinding(block.expression);
this.visitBinding(block.trackBy);
this.visitAll(block.children);
block.empty && this.visit(block.empty);
}
visitForLoopBlockEmpty(block: TmplAstForLoopBlockEmpty) {
this.visitAll(block.children);
}
visitIfBlock(block: TmplAstIfBlock) {
this.visitAll(block.branches);
}
visitIfBlockBranch(block: TmplAstIfBlockBranch) {
block.expression && this.visitBinding(block.expression);
block.expressionAlias && this.visit(block.expressionAlias);
this.visitAll(block.children);
}
visitUnknownBlock(block: TmplAstUnknownBlock) {}
visitLetDeclaration(decl: TmplAstLetDeclaration) {
this.visitBinding(decl.value);
}
visitAll(nodes: TmplAstNode[]) {
for (const node of nodes) {
this.visit(node);
}
}
private visitBinding(expression: AST) {
const visitor = new ExpressionVisitor(this.position);
visitor.visit(expression, this.path);
}
} | {
"end_byte": 20080,
"start_byte": 11984,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/template_target.ts"
} |
angular/packages/language-service/src/template_target.ts_20082_21925 | class ExpressionVisitor extends RecursiveAstVisitor {
// Position must be absolute in the source file.
constructor(private readonly position: number) {
super();
}
override visit(node: AST, path: Array<TmplAstNode | AST>) {
if (node instanceof ASTWithSource) {
// In order to reduce noise, do not include `ASTWithSource` in the path.
// For the purpose of source spans, there is no difference between
// `ASTWithSource` and underlying node that it wraps.
node = node.ast;
}
// The third condition is to account for the implicit receiver, which should
// not be visited.
if (isWithin(this.position, node.sourceSpan) && !(node instanceof ImplicitReceiver)) {
path.push(node);
node.visit(this, path);
}
}
}
function getSpanIncludingEndTag(ast: TmplAstNode) {
const result = {
start: ast.sourceSpan.start.offset,
end: ast.sourceSpan.end.offset,
};
// For Element and Template node, sourceSpan.end is the end of the opening
// tag. For the purpose of language service, we need to actually recognize
// the end of the closing tag. Otherwise, for situation like
// <my-component></my-comp¦onent> where the cursor is in the closing tag
// we will not be able to return any information.
if (ast instanceof TmplAstElement || ast instanceof TmplAstTemplate) {
if (ast.endSourceSpan) {
result.end = ast.endSourceSpan.end.offset;
} else if (ast.children.length > 0) {
// If the AST has children but no end source span, then it is an unclosed element with an end
// that should be the end of the last child.
result.end = getSpanIncludingEndTag(ast.children[ast.children.length - 1]).end;
} else {
// This is likely a self-closing tag with no children so the `sourceSpan.end` is correct.
}
}
return result;
}
| {
"end_byte": 21925,
"start_byte": 20082,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/template_target.ts"
} |
angular/packages/language-service/src/language_service.ts_0_2583 | /**
* @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 {AST, TmplAstNode} from '@angular/compiler';
import {CompilerOptions, ConfigurationHost, readConfiguration} from '@angular/compiler-cli';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {ErrorCode, ngErrorCode} from '@angular/compiler-cli/src/ngtsc/diagnostics';
import {absoluteFrom, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system';
import {PerfPhase} from '@angular/compiler-cli/src/ngtsc/perf';
import {FileUpdate, ProgramDriver} from '@angular/compiler-cli/src/ngtsc/program_driver';
import {isNamedClassDeclaration} from '@angular/compiler-cli/src/ngtsc/reflection';
import {OptimizeFor} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
import {
ApplyRefactoringProgressFn,
ApplyRefactoringResult,
GetComponentLocationsForTemplateResponse,
GetTcbResponse,
GetTemplateLocationForComponentResponse,
PluginConfig,
} from '../api';
import {LanguageServiceAdapter, LSParseConfigHost} from './adapters';
import {ALL_CODE_FIXES_METAS, CodeFixes} from './codefixes';
import {CompilerFactory} from './compiler_factory';
import {CompletionBuilder} from './completions';
import {DefinitionBuilder} from './definitions';
import {getOutliningSpans} from './outlining_spans';
import {QuickInfoBuilder} from './quick_info';
import {ReferencesBuilder, RenameBuilder} from './references_and_rename';
import {createLocationKey} from './references_and_rename_utils';
import {getSignatureHelp} from './signature_help';
import {
getTargetAtPosition,
getTcbNodesOfTemplateAtPosition,
TargetNodeKind,
} from './template_target';
import {
findTightestNode,
getClassDeclFromDecoratorProp,
getParentClassDeclaration,
getPropertyAssignmentFromValue,
} from './utils/ts_utils';
import {getTemplateInfoAtPosition, isTypeScriptFile} from './utils';
import {ActiveRefactoring, allRefactorings} from './refactorings/refactoring';
type LanguageServiceConfig = Omit<PluginConfig, 'angularOnly'>;
// Whether the language service should suppress the below for google3.
const enableG3Suppression = false;
// The Copybara config that syncs the language service into g3 will be patched to
// always suppress any diagnostics in this list.
// See `angular2/copy.bara.sky` for more information.
const suppressDiagnosticsInG3: number[] = [
parseInt(`-99${ErrorCode.COMPONENT_RESOURCE_NOT_FOUND}`),
]; | {
"end_byte": 2583,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/language_service.ts"
} |
angular/packages/language-service/src/language_service.ts_2585_11691 | export class LanguageService {
private options: CompilerOptions;
readonly compilerFactory: CompilerFactory;
private readonly codeFixes: CodeFixes;
private readonly activeRefactorings = new Map<string, ActiveRefactoring>();
constructor(
private readonly project: ts.server.Project,
private readonly tsLS: ts.LanguageService,
private readonly config: Omit<PluginConfig, 'angularOnly'>,
) {
if (project.projectKind === ts.server.ProjectKind.Configured) {
const parseConfigHost = new LSParseConfigHost(project.projectService.host);
this.options = parseNgCompilerOptions(project, parseConfigHost, config);
this.watchConfigFile(project, parseConfigHost);
} else {
this.options = project.getCompilerOptions();
}
logCompilerOptions(project, this.options);
const programDriver = createProgramDriver(project);
const adapter = new LanguageServiceAdapter(project);
this.compilerFactory = new CompilerFactory(adapter, programDriver, this.options);
this.codeFixes = new CodeFixes(tsLS, ALL_CODE_FIXES_METAS);
}
getCompilerOptions(): CompilerOptions {
return this.options;
}
getSemanticDiagnostics(fileName: string): ts.Diagnostic[] {
return this.withCompilerAndPerfTracing(PerfPhase.LsDiagnostics, (compiler) => {
let diagnostics: ts.Diagnostic[] = [];
if (isTypeScriptFile(fileName)) {
const program = compiler.getCurrentProgram();
const sourceFile = program.getSourceFile(fileName);
if (sourceFile) {
let ngDiagnostics = compiler.getDiagnosticsForFile(sourceFile, OptimizeFor.SingleFile);
// There are several kinds of diagnostics returned by `NgCompiler` for a source file:
//
// 1. Angular-related non-template diagnostics from decorated classes within that
// file.
// 2. Template diagnostics for components with direct inline templates (a string
// literal).
// 3. Template diagnostics for components with indirect inline templates (templates
// computed
// by expression).
// 4. Template diagnostics for components with external templates.
//
// When showing diagnostics for a TS source file, we want to only include kinds 1 and
// 2 - those diagnostics which are reported at a location within the TS file itself.
// Diagnostics for external templates will be shown when editing that template file
// (the `else` block) below.
//
// Currently, indirect inline template diagnostics (kind 3) are not shown at all by
// the Language Service, because there is no sensible location in the user's code for
// them. Such templates are an edge case, though, and should not be common.
//
// TODO(alxhub): figure out a good user experience for indirect template diagnostics
// and show them from within the Language Service.
diagnostics.push(
...ngDiagnostics.filter(
(diag) => diag.file !== undefined && diag.file.fileName === sourceFile.fileName,
),
);
}
} else {
const components = compiler.getComponentsWithTemplateFile(fileName);
for (const component of components) {
if (ts.isClassDeclaration(component)) {
diagnostics.push(...compiler.getDiagnosticsForComponent(component));
}
}
}
if (this.config.suppressAngularDiagnosticCodes) {
diagnostics = diagnostics.filter(
(diag) => !this.config.suppressAngularDiagnosticCodes!.includes(diag.code),
);
}
if (enableG3Suppression) {
diagnostics = diagnostics.filter((diag) => !suppressDiagnosticsInG3.includes(diag.code));
}
return diagnostics;
});
}
getDefinitionAndBoundSpan(
fileName: string,
position: number,
): ts.DefinitionInfoAndBoundSpan | undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsDefinition, (compiler) => {
if (!isInAngularContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined;
}
return new DefinitionBuilder(this.tsLS, compiler).getDefinitionAndBoundSpan(
fileName,
position,
);
});
}
getTypeDefinitionAtPosition(
fileName: string,
position: number,
): readonly ts.DefinitionInfo[] | undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsDefinition, (compiler) => {
if (!isTemplateContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined;
}
return new DefinitionBuilder(this.tsLS, compiler).getTypeDefinitionsAtPosition(
fileName,
position,
);
});
}
getQuickInfoAtPosition(fileName: string, position: number): ts.QuickInfo | undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsQuickInfo, (compiler) => {
return this.getQuickInfoAtPositionImpl(fileName, position, compiler);
});
}
private getQuickInfoAtPositionImpl(
fileName: string,
position: number,
compiler: NgCompiler,
): ts.QuickInfo | undefined {
if (!isTemplateContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined;
}
const templateInfo = getTemplateInfoAtPosition(fileName, position, compiler);
if (templateInfo === undefined) {
return undefined;
}
const positionDetails = getTargetAtPosition(templateInfo.template, position);
if (positionDetails === null) {
return undefined;
}
// Because we can only show 1 quick info, just use the bound attribute if the target is a two
// way binding. We may consider concatenating additional display parts from the other target
// nodes or representing the two way binding in some other manner in the future.
const node =
positionDetails.context.kind === TargetNodeKind.TwoWayBindingContext
? positionDetails.context.nodes[0]
: positionDetails.context.node;
return new QuickInfoBuilder(
this.tsLS,
compiler,
templateInfo.component,
node,
positionDetails,
).get();
}
getReferencesAtPosition(fileName: string, position: number): ts.ReferenceEntry[] | undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsReferencesAndRenames, (compiler) => {
const results = new ReferencesBuilder(this.tsLS, compiler).getReferencesAtPosition(
fileName,
position,
);
return results === undefined ? undefined : getUniqueLocations(results);
});
}
getRenameInfo(fileName: string, position: number): ts.RenameInfo {
return this.withCompilerAndPerfTracing(PerfPhase.LsReferencesAndRenames, (compiler) => {
const renameInfo = new RenameBuilder(this.tsLS, compiler).getRenameInfo(
absoluteFrom(fileName),
position,
);
if (!renameInfo.canRename) {
return renameInfo;
}
const quickInfo =
this.getQuickInfoAtPositionImpl(fileName, position, compiler) ??
this.tsLS.getQuickInfoAtPosition(fileName, position);
const kind = quickInfo?.kind ?? ts.ScriptElementKind.unknown;
const kindModifiers = quickInfo?.kindModifiers ?? ts.ScriptElementKind.unknown;
return {...renameInfo, kind, kindModifiers};
});
}
findRenameLocations(
fileName: string,
position: number,
): readonly ts.RenameLocation[] | undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsReferencesAndRenames, (compiler) => {
const results = new RenameBuilder(this.tsLS, compiler).findRenameLocations(
fileName,
position,
);
return results === null ? undefined : getUniqueLocations(results);
});
}
private getCompletionBuilder(
fileName: string,
position: number,
compiler: NgCompiler,
): CompletionBuilder<TmplAstNode | AST> | null {
const templateInfo = getTemplateInfoAtPosition(fileName, position, compiler);
if (templateInfo === undefined) {
return null;
}
const positionDetails = getTargetAtPosition(templateInfo.template, position);
if (positionDetails === null) {
return null;
}
// For two-way bindings, we actually only need to be concerned with the bound attribute because
// the bindings in the template are written with the attribute name, not the event name.
const node =
positionDetails.context.kind === TargetNodeKind.TwoWayBindingContext
? positionDetails.context.nodes[0]
: positionDetails.context.node;
return new CompletionBuilder(
this.tsLS,
compiler,
templateInfo.component,
node,
positionDetails,
);
}
getCompletionsAtPosition(
fileName: string,
position: number,
options: ts.GetCompletionsAtPositionOptions | undefined,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsCompletions, (compiler) => {
return this.getCompletionsAtPositionImpl(fileName, position, options, compiler);
});
} | {
"end_byte": 11691,
"start_byte": 2585,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/language_service.ts"
} |
angular/packages/language-service/src/language_service.ts_11695_20332 | private getCompletionsAtPositionImpl(
fileName: string,
position: number,
options: ts.GetCompletionsAtPositionOptions | undefined,
compiler: NgCompiler,
): ts.WithMetadata<ts.CompletionInfo> | undefined {
if (!isTemplateContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined;
}
const builder = this.getCompletionBuilder(fileName, position, compiler);
if (builder === null) {
return undefined;
}
return builder.getCompletionsAtPosition(options);
}
getCompletionEntryDetails(
fileName: string,
position: number,
entryName: string,
formatOptions: ts.FormatCodeOptions | ts.FormatCodeSettings | undefined,
preferences: ts.UserPreferences | undefined,
data: ts.CompletionEntryData | undefined,
): ts.CompletionEntryDetails | undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsCompletions, (compiler) => {
if (!isTemplateContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined;
}
const builder = this.getCompletionBuilder(fileName, position, compiler);
if (builder === null) {
return undefined;
}
return builder.getCompletionEntryDetails(entryName, formatOptions, preferences, data);
});
}
getSignatureHelpItems(
fileName: string,
position: number,
options?: ts.SignatureHelpItemsOptions,
): ts.SignatureHelpItems | undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsSignatureHelp, (compiler) => {
if (!isTemplateContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined;
}
return getSignatureHelp(compiler, this.tsLS, fileName, position, options);
});
}
getOutliningSpans(fileName: string): ts.OutliningSpan[] {
return this.withCompilerAndPerfTracing(PerfPhase.OutliningSpans, (compiler) => {
return getOutliningSpans(compiler, fileName);
});
}
getCompletionEntrySymbol(
fileName: string,
position: number,
entryName: string,
): ts.Symbol | undefined {
return this.withCompilerAndPerfTracing(PerfPhase.LsCompletions, (compiler) => {
if (!isTemplateContext(compiler.getCurrentProgram(), fileName, position)) {
return undefined;
}
const builder = this.getCompletionBuilder(fileName, position, compiler);
if (builder === null) {
return undefined;
}
const result = builder.getCompletionEntrySymbol(entryName);
return result;
});
}
/**
* Performance helper that can help make quick decisions for
* the VSCode language server to decide whether a code fix exists
* for the given error code.
*
* Related context: https://github.com/angular/vscode-ng-language-service/pull/2050#discussion_r1673079263
*/
hasCodeFixesForErrorCode(errorCode: number): boolean {
return this.codeFixes.codeActionMetas.some((m) => m.errorCodes.includes(errorCode));
}
getCodeFixesAtPosition(
fileName: string,
start: number,
end: number,
errorCodes: readonly number[],
formatOptions: ts.FormatCodeSettings,
preferences: ts.UserPreferences,
): readonly ts.CodeFixAction[] {
return this.withCompilerAndPerfTracing<readonly ts.CodeFixAction[]>(
PerfPhase.LsCodeFixes,
(compiler) => {
// Fast exit if we know no code fix can exist for the given range/and error codes.
if (errorCodes.every((code) => !this.hasCodeFixesForErrorCode(code))) {
return [];
}
const templateInfo = getTemplateInfoAtPosition(fileName, start, compiler);
if (templateInfo === undefined) {
return [];
}
const diags = this.getSemanticDiagnostics(fileName);
if (diags.length === 0) {
return [];
}
return this.codeFixes.getCodeFixesAtPosition(
fileName,
templateInfo,
compiler,
start,
end,
errorCodes,
diags,
formatOptions,
preferences,
);
},
);
}
getCombinedCodeFix(
scope: ts.CombinedCodeFixScope,
fixId: string,
formatOptions: ts.FormatCodeSettings,
preferences: ts.UserPreferences,
): ts.CombinedCodeActions {
return this.withCompilerAndPerfTracing<ts.CombinedCodeActions>(
PerfPhase.LsCodeFixesAll,
(compiler) => {
const diags = this.getSemanticDiagnostics(scope.fileName);
if (diags.length === 0) {
return {changes: []};
}
return this.codeFixes.getAllCodeActions(
compiler,
diags,
scope,
fixId,
formatOptions,
preferences,
);
},
);
}
getComponentLocationsForTemplate(fileName: string): GetComponentLocationsForTemplateResponse {
return this.withCompilerAndPerfTracing<GetComponentLocationsForTemplateResponse>(
PerfPhase.LsComponentLocations,
(compiler) => {
const components = compiler.getComponentsWithTemplateFile(fileName);
const componentDeclarationLocations: ts.DocumentSpan[] = Array.from(
components.values(),
).map((c) => {
let contextSpan: ts.TextSpan | undefined = undefined;
let textSpan: ts.TextSpan;
if (isNamedClassDeclaration(c)) {
textSpan = ts.createTextSpanFromBounds(c.name.getStart(), c.name.getEnd());
contextSpan = ts.createTextSpanFromBounds(c.getStart(), c.getEnd());
} else {
textSpan = ts.createTextSpanFromBounds(c.getStart(), c.getEnd());
}
return {
fileName: c.getSourceFile().fileName,
textSpan,
contextSpan,
};
});
return componentDeclarationLocations;
},
);
}
getTemplateLocationForComponent(
fileName: string,
position: number,
): GetTemplateLocationForComponentResponse {
return this.withCompilerAndPerfTracing<GetTemplateLocationForComponentResponse>(
PerfPhase.LsComponentLocations,
(compiler) => {
const nearestNode = findTightestNodeAtPosition(
compiler.getCurrentProgram(),
fileName,
position,
);
if (nearestNode === undefined) {
return undefined;
}
const classDeclaration = getParentClassDeclaration(nearestNode);
if (classDeclaration === undefined) {
return undefined;
}
const resources = compiler.getComponentResources(classDeclaration);
if (resources === null) {
return undefined;
}
const {template} = resources;
let templateFileName: string;
let span: ts.TextSpan;
if (template.path !== null) {
span = ts.createTextSpanFromBounds(0, 0);
templateFileName = template.path;
} else {
span = ts.createTextSpanFromBounds(
template.expression.getStart(),
template.expression.getEnd(),
);
templateFileName = template.expression.getSourceFile().fileName;
}
return {fileName: templateFileName, textSpan: span, contextSpan: span};
},
);
}
getTcb(fileName: string, position: number): GetTcbResponse | undefined {
return this.withCompilerAndPerfTracing<GetTcbResponse | undefined>(
PerfPhase.LsTcb,
(compiler) => {
const templateInfo = getTemplateInfoAtPosition(fileName, position, compiler);
if (templateInfo === undefined) {
return undefined;
}
const selectionNodesInfo = getTcbNodesOfTemplateAtPosition(
templateInfo,
position,
compiler,
);
if (selectionNodesInfo === null) {
return undefined;
}
const sf = selectionNodesInfo.componentTcbNode.getSourceFile();
const selections = selectionNodesInfo.nodes.map((n) => {
return {
start: n.getStart(sf),
length: n.getEnd() - n.getStart(sf),
};
});
return {
fileName: sf.fileName,
content: sf.getFullText(),
selections,
};
},
);
}
getPossibleRefactorings(
fileName: string,
positionOrRange: number | ts.TextRange,
): ts.ApplicableRefactorInfo[] {
return this.withCompilerAndPerfTracing(
PerfPhase.LSComputeApplicableRefactorings,
(compiler) => {
return allRefactorings
.filter((r) => r.isApplicable(compiler, fileName, positionOrRange))
.map((r) => ({name: r.id, description: r.description, actions: []}));
},
);
} | {
"end_byte": 20332,
"start_byte": 11695,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/language_service.ts"
} |
angular/packages/language-service/src/language_service.ts_20336_27866 | /**
* Computes edits for applying the specified refactoring.
*
* VSCode explicitly split code actions into two stages:
*
* - 1) what actions are active?
* - 2) what are the edits? <- if the user presses the button
*
* The latter stage may take longer to compute complex edits, perform
* analysis. This stage is currently implemented via our non-LSP standard
* `applyRefactoring` method. We implemented it in a way to support asynchronous
* computation, so that it can easily integrate with migrations that aren't
* synchronous/or compute edits in parallel.
*/
async applyRefactoring(
fileName: string,
positionOrRange: number | ts.TextRange,
refactorName: string,
reportProgress: ApplyRefactoringProgressFn,
): Promise<ApplyRefactoringResult | undefined> {
const matchingRefactoring = allRefactorings.find((r) => r.id === refactorName);
if (matchingRefactoring === undefined) {
return undefined;
}
return this.withCompilerAndPerfTracing(PerfPhase.LSApplyRefactoring, (compiler) => {
if (!this.activeRefactorings.has(refactorName)) {
this.activeRefactorings.set(refactorName, new matchingRefactoring(this.project));
}
const activeRefactoring = this.activeRefactorings.get(refactorName)!;
return activeRefactoring.computeEditsForFix(
compiler,
this.options,
fileName,
positionOrRange,
reportProgress,
);
});
}
/**
* Provides an instance of the `NgCompiler` and traces perf results. Perf results are logged only
* if the log level is verbose or higher. This method is intended to be called once per public
* method call.
*
* Here is an example of the log output.
*
* Perf 245 [16:16:39.353] LanguageService#getQuickInfoAtPosition(): {"events":{},"phases":{
* "Unaccounted":379,"TtcSymbol":4},"memory":{}}
*
* Passing name of caller instead of using `arguments.caller` because 'caller', 'callee', and
* 'arguments' properties may not be accessed in strict mode.
*
* @param phase the `PerfPhase` to execute the `p` callback in
* @param p callback to be run synchronously with an instance of the `NgCompiler` as argument
* @return the result of running the `p` callback
*/
private withCompilerAndPerfTracing<T>(phase: PerfPhase, p: (compiler: NgCompiler) => T): T {
const compiler = this.compilerFactory.getOrCreate();
const result = compiler.perfRecorder.inPhase(phase, () => p(compiler));
const logger = this.project.projectService.logger;
if (logger.hasLevel(ts.server.LogLevel.verbose)) {
logger.perftrc(
`LanguageService#${PerfPhase[phase]}: ${JSON.stringify(compiler.perfRecorder.finalize())}`,
);
}
return result;
}
getCompilerOptionsDiagnostics(): ts.Diagnostic[] {
const project = this.project;
if (!(project instanceof ts.server.ConfiguredProject)) {
return [];
}
return this.withCompilerAndPerfTracing(PerfPhase.LsDiagnostics, (compiler) => {
const diagnostics: ts.Diagnostic[] = [];
const configSourceFile = ts.readJsonConfigFile(project.getConfigFilePath(), (path: string) =>
project.readFile(path),
);
if (!this.options.strictTemplates && !this.options.fullTemplateTypeCheck) {
diagnostics.push({
messageText:
'Some language features are not available. ' +
'To access all features, enable `strictTemplates` in `angularCompilerOptions`.',
category: ts.DiagnosticCategory.Suggestion,
code: ngErrorCode(ErrorCode.SUGGEST_STRICT_TEMPLATES),
file: configSourceFile,
start: undefined,
length: undefined,
});
}
diagnostics.push(...compiler.getOptionDiagnostics());
return diagnostics;
});
}
private watchConfigFile(project: ts.server.Project, parseConfigHost: LSParseConfigHost) {
// TODO: Check the case when the project is disposed. An InferredProject
// could be disposed when a tsconfig.json is added to the workspace,
// in which case it becomes a ConfiguredProject (or vice-versa).
// We need to make sure that the FileWatcher is closed.
if (!(project instanceof ts.server.ConfiguredProject)) {
return;
}
const {host} = project.projectService;
host.watchFile(
project.getConfigFilePath(),
(fileName: string, eventKind: ts.FileWatcherEventKind) => {
project.log(`Config file changed: ${fileName}`);
if (eventKind === ts.FileWatcherEventKind.Changed) {
this.options = parseNgCompilerOptions(project, parseConfigHost, this.config);
logCompilerOptions(project, this.options);
}
},
);
}
}
function logCompilerOptions(project: ts.server.Project, options: CompilerOptions) {
const {logger} = project.projectService;
const projectName = project.getProjectName();
logger.info(`Angular compiler options for ${projectName}: ` + JSON.stringify(options, null, 2));
}
function parseNgCompilerOptions(
project: ts.server.Project,
host: ConfigurationHost,
config: LanguageServiceConfig,
): CompilerOptions {
if (!(project instanceof ts.server.ConfiguredProject)) {
return {};
}
const {options, errors} = readConfiguration(
project.getConfigFilePath(),
/* existingOptions */ undefined,
host,
);
if (errors.length > 0) {
project.setProjectErrors(errors);
}
// Projects loaded into the Language Service often include test files which are not part of the
// app's main compilation unit, and these test files often include inline NgModules that declare
// components from the app. These declarations conflict with the main declarations of such
// components in the app's NgModules. This conflict is not normally present during regular
// compilation because the app and the tests are part of separate compilation units.
//
// As a temporary mitigation of this problem, we instruct the compiler to ignore classes which
// are not exported. In many cases, this ensures the test NgModules are ignored by the compiler
// and only the real component declaration is used.
options.compileNonExportedClasses = false;
// If `forceStrictTemplates` is true, always enable `strictTemplates`
// regardless of its value in tsconfig.json.
if (config['forceStrictTemplates'] === true) {
options.strictTemplates = true;
}
if (config['enableBlockSyntax'] === false) {
options['_enableBlockSyntax'] = false;
}
if (config['enableLetSyntax'] === false) {
options['_enableLetSyntax'] = false;
}
options['_angularCoreVersion'] = config['angularCoreVersion'];
return options;
}
function createProgramDriver(project: ts.server.Project): ProgramDriver {
return {
supportsInlineOperations: false,
getProgram(): ts.Program {
const program = project.getLanguageService().getProgram();
if (!program) {
throw new Error('Language service does not have a program!');
}
return program;
},
updateFiles(contents: Map<AbsoluteFsPath, FileUpdate>) {
for (const [fileName, {newText}] of contents) {
const scriptInfo = getOrCreateTypeCheckScriptInfo(project, fileName);
const snapshot = scriptInfo.getSnapshot();
const length = snapshot.getLength();
scriptInfo.editContent(0, length, newText);
}
},
getSourceFileVersion(sf: ts.SourceFile): string {
return project.getScriptVersion(sf.fileName);
},
};
} | {
"end_byte": 27866,
"start_byte": 20336,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/language_service.ts"
} |
angular/packages/language-service/src/language_service.ts_27868_30965 | function getOrCreateTypeCheckScriptInfo(
project: ts.server.Project,
tcf: string,
): ts.server.ScriptInfo {
// First check if there is already a ScriptInfo for the tcf
const {projectService} = project;
let scriptInfo = projectService.getScriptInfo(tcf);
if (!scriptInfo) {
// ScriptInfo needs to be opened by client to be able to set its user-defined
// content. We must also provide file content, otherwise the service will
// attempt to fetch the content from disk and fail.
scriptInfo = projectService.getOrCreateScriptInfoForNormalizedPath(
ts.server.toNormalizedPath(tcf),
true, // openedByClient
'', // fileContent
// script info added by plugins should be marked as external, see
// https://github.com/microsoft/TypeScript/blob/b217f22e798c781f55d17da72ed099a9dee5c650/src/compiler/program.ts#L1897-L1899
ts.ScriptKind.External, // scriptKind
);
if (!scriptInfo) {
throw new Error(`Failed to create script info for ${tcf}`);
}
}
// Add ScriptInfo to project if it's missing. A ScriptInfo needs to be part of
// the project so that it becomes part of the program.
if (!project.containsScriptInfo(scriptInfo)) {
project.addRoot(scriptInfo);
}
return scriptInfo;
}
function isTemplateContext(program: ts.Program, fileName: string, position: number): boolean {
if (!isTypeScriptFile(fileName)) {
// If we aren't in a TS file, we must be in an HTML file, which we treat as template context
return true;
}
const node = findTightestNodeAtPosition(program, fileName, position);
if (node === undefined) {
return false;
}
let asgn = getPropertyAssignmentFromValue(node, 'template');
if (asgn === null) {
return false;
}
return getClassDeclFromDecoratorProp(asgn) !== null;
}
function isInAngularContext(program: ts.Program, fileName: string, position: number) {
if (!isTypeScriptFile(fileName)) {
return true;
}
const node = findTightestNodeAtPosition(program, fileName, position);
if (node === undefined) {
return false;
}
const assignment =
getPropertyAssignmentFromValue(node, 'template') ??
getPropertyAssignmentFromValue(node, 'templateUrl') ??
// `node.parent` is used because the string is a child of an array element and we want to get
// the property name
getPropertyAssignmentFromValue(node.parent, 'styleUrls') ??
getPropertyAssignmentFromValue(node, 'styleUrl');
return assignment !== null && getClassDeclFromDecoratorProp(assignment) !== null;
}
function findTightestNodeAtPosition(program: ts.Program, fileName: string, position: number) {
const sourceFile = program.getSourceFile(fileName);
if (sourceFile === undefined) {
return undefined;
}
return findTightestNode(sourceFile, position);
}
function getUniqueLocations<T extends ts.DocumentSpan>(locations: readonly T[]): T[] {
const uniqueLocations: Map<string, T> = new Map();
for (const location of locations) {
uniqueLocations.set(createLocationKey(location), location);
}
return Array.from(uniqueLocations.values());
} | {
"end_byte": 30965,
"start_byte": 27868,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/language_service.ts"
} |
angular/packages/language-service/src/BUILD.bazel_0_1340 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//packages/language-service:__subpackages__"])
ts_library(
name = "src",
srcs = glob([
"*.ts",
"**/*.ts",
]),
deps = [
"//packages/compiler",
"//packages/compiler-cli",
"//packages/compiler-cli/src/ngtsc/core",
"//packages/compiler-cli/src/ngtsc/core:api",
"//packages/compiler-cli/src/ngtsc/diagnostics",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/incremental",
"//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/perf",
"//packages/compiler-cli/src/ngtsc/program_driver",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/shims",
"//packages/compiler-cli/src/ngtsc/typecheck",
"//packages/compiler-cli/src/ngtsc/typecheck/api",
"//packages/compiler-cli/src/ngtsc/util",
"//packages/core/schematics/migrations/signal-migration/src",
"//packages/language-service:api",
"//packages/language-service/src/refactorings",
"//packages/language-service/src/utils",
"@npm//@types/node",
"@npm//typescript",
],
)
| {
"end_byte": 1340,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/BUILD.bazel"
} |
angular/packages/language-service/src/definitions.ts_0_1464 | /**
* @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 {
AST,
TmplAstBoundAttribute,
TmplAstBoundEvent,
TmplAstElement,
TmplAstNode,
TmplAstTemplate,
TmplAstTextAttribute,
} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system';
import {isExternalResource} from '@angular/compiler-cli/src/ngtsc/metadata';
import {
DirectiveSymbol,
DomBindingSymbol,
ElementSymbol,
Symbol,
SymbolKind,
TcbLocation,
TemplateSymbol,
TemplateTypeChecker,
} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
import {convertToTemplateDocumentSpan} from './references_and_rename_utils';
import {getTargetAtPosition, TargetNodeKind} from './template_target';
import {findTightestNode, getParentClassDeclaration} from './utils/ts_utils';
import {
getDirectiveMatchesForAttribute,
getDirectiveMatchesForElementTag,
getTemplateInfoAtPosition,
getTemplateLocationFromTcbLocation,
getTextSpanOfNode,
isDollarEvent,
isTypeScriptFile,
TemplateInfo,
toTextSpan,
} from './utils';
interface DefinitionMeta {
node: AST | TmplAstNode;
parent: AST | TmplAstNode | null;
symbol: Symbol;
}
interface HasTcbLocation {
tcbLocation: TcbLocation;
} | {
"end_byte": 1464,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/definitions.ts"
} |
angular/packages/language-service/src/definitions.ts_1466_10097 | export class DefinitionBuilder {
private readonly ttc: TemplateTypeChecker;
constructor(
private readonly tsLS: ts.LanguageService,
private readonly compiler: NgCompiler,
) {
this.ttc = this.compiler.getTemplateTypeChecker();
}
getDefinitionAndBoundSpan(
fileName: string,
position: number,
): ts.DefinitionInfoAndBoundSpan | undefined {
const templateInfo = getTemplateInfoAtPosition(fileName, position, this.compiler);
if (templateInfo === undefined) {
// We were unable to get a template at the given position. If we are in a TS file, instead
// attempt to get an Angular definition at the location inside a TS file (examples of this
// would be templateUrl or a url in styleUrls).
if (!isTypeScriptFile(fileName)) {
return;
}
return getDefinitionForExpressionAtPosition(fileName, position, this.compiler);
}
const definitionMetas = this.getDefinitionMetaAtPosition(templateInfo, position);
if (definitionMetas === undefined) {
return undefined;
}
const definitions: ts.DefinitionInfo[] = [];
for (const definitionMeta of definitionMetas) {
// The `$event` of event handlers would point to the $event parameter in the shim file, as in
// `_t3["x"].subscribe(function ($event): any { $event }) ;`
// If we wanted to return something for this, it would be more appropriate for something like
// `getTypeDefinition`.
if (isDollarEvent(definitionMeta.node)) {
continue;
}
definitions.push(
...(this.getDefinitionsForSymbol({...definitionMeta, ...templateInfo}) ?? []),
);
}
if (definitions.length === 0) {
return undefined;
}
return {definitions, textSpan: getTextSpanOfNode(definitionMetas[0].node)};
}
private getDefinitionsForSymbol({
symbol,
node,
parent,
component,
}: DefinitionMeta & TemplateInfo): readonly ts.DefinitionInfo[] | undefined {
switch (symbol.kind) {
case SymbolKind.Directive:
case SymbolKind.Element:
case SymbolKind.Template:
case SymbolKind.DomBinding:
// Though it is generally more appropriate for the above symbol definitions to be
// associated with "type definitions" since the location in the template is the
// actual definition location, the better user experience would be to allow
// LS users to "go to definition" on an item in the template that maps to a class and be
// taken to the directive or HTML class.
return this.getTypeDefinitionsForTemplateInstance(symbol, node);
case SymbolKind.Pipe: {
if (symbol.tsSymbol !== null) {
return this.getDefinitionsForSymbols(symbol);
} else {
// If there is no `ts.Symbol` for the pipe transform, we want to return the
// type definition (the pipe class).
return this.getTypeDefinitionsForSymbols(symbol.classSymbol);
}
}
case SymbolKind.Output:
case SymbolKind.Input: {
const bindingDefs = this.getDefinitionsForSymbols(...symbol.bindings);
// Also attempt to get directive matches for the input name. If there is a directive that
// has the input name as part of the selector, we want to return that as well.
const directiveDefs = this.getDirectiveTypeDefsForBindingNode(node, parent, component);
return [...bindingDefs, ...directiveDefs];
}
case SymbolKind.LetDeclaration:
case SymbolKind.Variable:
case SymbolKind.Reference: {
const definitions: ts.DefinitionInfo[] = [];
if (symbol.declaration !== node) {
const tcbLocation =
symbol.kind === SymbolKind.Reference
? symbol.referenceVarLocation
: symbol.localVarLocation;
const mapping = getTemplateLocationFromTcbLocation(
this.compiler.getTemplateTypeChecker(),
tcbLocation.tcbPath,
tcbLocation.isShimFile,
tcbLocation.positionInFile,
);
if (mapping !== null) {
definitions.push({
name: symbol.declaration.name,
containerName: '',
containerKind: ts.ScriptElementKind.unknown,
kind: ts.ScriptElementKind.variableElement,
textSpan: getTextSpanOfNode(symbol.declaration),
contextSpan: toTextSpan(symbol.declaration.sourceSpan),
fileName: mapping.templateUrl,
});
}
}
if (symbol.kind === SymbolKind.Variable || symbol.kind === SymbolKind.LetDeclaration) {
definitions.push(
...this.getDefinitionsForSymbols({tcbLocation: symbol.initializerLocation}),
);
}
return definitions;
}
case SymbolKind.Expression: {
return this.getDefinitionsForSymbols(symbol);
}
}
}
private getDefinitionsForSymbols(...symbols: HasTcbLocation[]): ts.DefinitionInfo[] {
return symbols.flatMap(({tcbLocation}) => {
const {tcbPath, positionInFile} = tcbLocation;
const definitionInfos = this.tsLS.getDefinitionAtPosition(tcbPath, positionInFile);
if (definitionInfos === undefined) {
return [];
}
return this.mapShimResultsToTemplates(definitionInfos);
});
}
/**
* Converts and definition info result that points to a template typecheck file to a reference to
* the corresponding location in the template.
*/
private mapShimResultsToTemplates(
definitionInfos: readonly ts.DefinitionInfo[],
): readonly ts.DefinitionInfo[] {
const result: ts.DefinitionInfo[] = [];
for (const info of definitionInfos) {
if (this.ttc.isTrackedTypeCheckFile(absoluteFrom(info.fileName))) {
const templateDefinitionInfo = convertToTemplateDocumentSpan(
info,
this.ttc,
this.compiler.getCurrentProgram(),
);
if (templateDefinitionInfo === null) {
continue;
}
result.push(templateDefinitionInfo);
} else {
result.push(info);
}
}
return result;
}
getTypeDefinitionsAtPosition(
fileName: string,
position: number,
): readonly ts.DefinitionInfo[] | undefined {
const templateInfo = getTemplateInfoAtPosition(fileName, position, this.compiler);
if (templateInfo === undefined) {
return undefined;
}
const definitionMetas = this.getDefinitionMetaAtPosition(templateInfo, position);
if (definitionMetas === undefined) {
return undefined;
}
const definitions: ts.DefinitionInfo[] = [];
for (const {symbol, node, parent} of definitionMetas) {
switch (symbol.kind) {
case SymbolKind.Directive:
case SymbolKind.DomBinding:
case SymbolKind.Element:
case SymbolKind.Template:
definitions.push(...this.getTypeDefinitionsForTemplateInstance(symbol, node));
break;
case SymbolKind.Output:
case SymbolKind.Input: {
const bindingDefs = this.getTypeDefinitionsForSymbols(...symbol.bindings);
definitions.push(...bindingDefs);
// Also attempt to get directive matches for the input name. If there is a directive that
// has the input name as part of the selector, we want to return that as well.
const directiveDefs = this.getDirectiveTypeDefsForBindingNode(
node,
parent,
templateInfo.component,
);
definitions.push(...directiveDefs);
break;
}
case SymbolKind.Pipe: {
if (symbol.tsSymbol !== null) {
definitions.push(...this.getTypeDefinitionsForSymbols(symbol));
} else {
// If there is no `ts.Symbol` for the pipe transform, we want to return the
// type definition (the pipe class).
definitions.push(...this.getTypeDefinitionsForSymbols(symbol.classSymbol));
}
break;
}
case SymbolKind.Reference:
definitions.push(
...this.getTypeDefinitionsForSymbols({tcbLocation: symbol.targetLocation}),
);
break;
case SymbolKind.Expression:
definitions.push(...this.getTypeDefinitionsForSymbols(symbol));
break;
case SymbolKind.Variable:
case SymbolKind.LetDeclaration: {
definitions.push(
...this.getTypeDefinitionsForSymbols({tcbLocation: symbol.initializerLocation}),
);
break;
}
}
return definitions;
}
return undefined;
} | {
"end_byte": 10097,
"start_byte": 1466,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/definitions.ts"
} |
angular/packages/language-service/src/definitions.ts_10101_15305 | private getTypeDefinitionsForTemplateInstance(
symbol: TemplateSymbol | ElementSymbol | DomBindingSymbol | DirectiveSymbol,
node: AST | TmplAstNode,
): ts.DefinitionInfo[] {
switch (symbol.kind) {
case SymbolKind.Template: {
const matches = getDirectiveMatchesForElementTag(symbol.templateNode, symbol.directives);
return this.getTypeDefinitionsForSymbols(...matches);
}
case SymbolKind.Element: {
const matches = getDirectiveMatchesForElementTag(symbol.templateNode, symbol.directives);
// If one of the directive matches is a component, we should not include the native element
// in the results because it is replaced by the component.
return Array.from(matches).some((dir) => dir.isComponent)
? this.getTypeDefinitionsForSymbols(...matches)
: this.getTypeDefinitionsForSymbols(...matches, symbol);
}
case SymbolKind.DomBinding: {
if (!(node instanceof TmplAstTextAttribute)) {
return [];
}
const dirs = getDirectiveMatchesForAttribute(
node.name,
symbol.host.templateNode,
symbol.host.directives,
);
return this.getTypeDefinitionsForSymbols(...dirs);
}
case SymbolKind.Directive:
return this.getTypeDefinitionsForSymbols(symbol);
}
}
private getDirectiveTypeDefsForBindingNode(
node: TmplAstNode | AST,
parent: TmplAstNode | AST | null,
component: ts.ClassDeclaration,
) {
if (
!(node instanceof TmplAstBoundAttribute) &&
!(node instanceof TmplAstTextAttribute) &&
!(node instanceof TmplAstBoundEvent)
) {
return [];
}
if (
parent === null ||
!(parent instanceof TmplAstTemplate || parent instanceof TmplAstElement)
) {
return [];
}
const templateOrElementSymbol = this.compiler
.getTemplateTypeChecker()
.getSymbolOfNode(parent, component);
if (
templateOrElementSymbol === null ||
(templateOrElementSymbol.kind !== SymbolKind.Template &&
templateOrElementSymbol.kind !== SymbolKind.Element)
) {
return [];
}
const dirs = getDirectiveMatchesForAttribute(
node.name,
parent,
templateOrElementSymbol.directives,
);
return this.getTypeDefinitionsForSymbols(...dirs);
}
private getTypeDefinitionsForSymbols(...symbols: HasTcbLocation[]): ts.DefinitionInfo[] {
return symbols.flatMap(({tcbLocation}) => {
const {tcbPath, positionInFile} = tcbLocation;
return this.tsLS.getTypeDefinitionAtPosition(tcbPath, positionInFile) ?? [];
});
}
private getDefinitionMetaAtPosition(
{template, component}: TemplateInfo,
position: number,
): DefinitionMeta[] | undefined {
const target = getTargetAtPosition(template, position);
if (target === null) {
return undefined;
}
const {context, parent} = target;
const nodes =
context.kind === TargetNodeKind.TwoWayBindingContext ? context.nodes : [context.node];
const definitionMetas: DefinitionMeta[] = [];
for (const node of nodes) {
const symbol = this.compiler.getTemplateTypeChecker().getSymbolOfNode(node, component);
if (symbol === null) {
continue;
}
definitionMetas.push({node, parent, symbol});
}
return definitionMetas.length > 0 ? definitionMetas : undefined;
}
}
/**
* Gets an Angular-specific definition in a TypeScript source file.
*/
function getDefinitionForExpressionAtPosition(
fileName: string,
position: number,
compiler: NgCompiler,
): ts.DefinitionInfoAndBoundSpan | undefined {
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return;
}
const expression = findTightestNode(sf, position);
if (expression === undefined) {
return;
}
const classDeclaration = getParentClassDeclaration(expression);
if (classDeclaration === undefined) {
return;
}
const componentResources = compiler.getComponentResources(classDeclaration);
if (componentResources === null) {
return;
}
const allResources = [...componentResources.styles, componentResources.template];
const resourceForExpression = allResources.find((resource) => resource.expression === expression);
if (resourceForExpression === undefined || !isExternalResource(resourceForExpression)) {
return;
}
const templateDefinitions: ts.DefinitionInfo[] = [
{
kind: ts.ScriptElementKind.externalModuleName,
name: resourceForExpression.path,
containerKind: ts.ScriptElementKind.unknown,
containerName: '',
// Reading the template is expensive, so don't provide a preview.
// TODO(ayazhafiz): Consider providing an actual span:
// 1. We're likely to read the template anyway
// 2. We could show just the first 100 chars or so
textSpan: {start: 0, length: 0},
fileName: resourceForExpression.path,
},
];
return {
definitions: templateDefinitions,
textSpan: {
// Exclude opening and closing quotes in the url span.
start: expression.getStart() + 1,
length: expression.getWidth() - 2,
},
};
} | {
"end_byte": 15305,
"start_byte": 10101,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/definitions.ts"
} |
angular/packages/language-service/src/signature_help.ts_0_5620 | /**
* @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 {Call, SafeCall} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {getSourceFileOrError} from '@angular/compiler-cli/src/ngtsc/file_system';
import {SymbolKind} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
import {getTargetAtPosition, TargetNodeKind} from './template_target';
import {findTightestNode} from './utils/ts_utils';
import {getTemplateInfoAtPosition} from './utils';
/**
* Queries the TypeScript Language Service to get signature help for a template position.
*/
export function getSignatureHelp(
compiler: NgCompiler,
tsLS: ts.LanguageService,
fileName: string,
position: number,
options: ts.SignatureHelpItemsOptions | undefined,
): ts.SignatureHelpItems | undefined {
const templateInfo = getTemplateInfoAtPosition(fileName, position, compiler);
if (templateInfo === undefined) {
return undefined;
}
const targetInfo = getTargetAtPosition(templateInfo.template, position);
if (targetInfo === null) {
return undefined;
}
if (
targetInfo.context.kind !== TargetNodeKind.RawExpression &&
targetInfo.context.kind !== TargetNodeKind.CallExpressionInArgContext
) {
// Signature completions are only available in expressions.
return undefined;
}
const symbol = compiler
.getTemplateTypeChecker()
.getSymbolOfNode(targetInfo.context.node, templateInfo.component);
if (symbol === null || symbol.kind !== SymbolKind.Expression) {
return undefined;
}
// Determine a shim position to use in the request to the TypeScript Language Service.
// Additionally, extract the `Call` node for which signature help is being queried, as this
// is needed to construct the correct span for the results later.
let shimPosition: number;
let expr: Call | SafeCall;
switch (targetInfo.context.kind) {
case TargetNodeKind.RawExpression:
// For normal expressions, just use the primary TCB position of the expression.
shimPosition = symbol.tcbLocation.positionInFile;
// Walk up the parents of this expression and try to find a
// `Call` for which signature information is being fetched.
let callExpr: Call | SafeCall | null = null;
const parents = targetInfo.context.parents;
for (let i = parents.length - 1; i >= 0; i--) {
const parent = parents[i];
if (parent instanceof Call || parent instanceof SafeCall) {
callExpr = parent;
break;
}
}
// If no Call node could be found, then this query cannot be safely
// answered as a correct span for the results will not be obtainable.
if (callExpr === null) {
return undefined;
}
expr = callExpr;
break;
case TargetNodeKind.CallExpressionInArgContext:
// The `Symbol` points to a `Call` expression in the TCB (where it will be represented as a
// `ts.CallExpression`) *and* the template position was within the argument list of the method
// call. This happens when there was no narrower expression inside the argument list that
// matched the template position, such as when the call has no arguments: `foo(|)`.
//
// The `Symbol`'s shim position is to the start of the call expression (`|foo()`) and
// therefore wouldn't return accurate signature help from the TS language service. For that, a
// position within the argument list for the `ts.CallExpression` in the TCB will need to be
// determined. This is done by finding that call expression and extracting a viable position
// from it directly.
//
// First, use `findTightestNode` to locate the `ts.Node` at `symbol`'s location.
const shimSf = getSourceFileOrError(compiler.getCurrentProgram(), symbol.tcbLocation.tcbPath);
let shimNode: ts.Node | null =
findTightestNode(shimSf, symbol.tcbLocation.positionInFile) ?? null;
// This node should be somewhere inside a `ts.CallExpression`. Walk up the AST to find it.
while (shimNode !== null) {
if (ts.isCallExpression(shimNode)) {
break;
}
shimNode = shimNode.parent ?? null;
}
// If one couldn't be found, something is wrong, so bail rather than report incorrect results.
if (shimNode === null || !ts.isCallExpression(shimNode)) {
return undefined;
}
// Position the cursor in the TCB at the start of the argument list for the
// `ts.CallExpression`. This will allow us to get the correct signature help, even though the
// template itself doesn't have an expression inside the argument list.
shimPosition = shimNode.arguments.pos;
// In this case, getting the right call AST node is easy.
expr = targetInfo.context.node;
break;
}
const res = tsLS.getSignatureHelpItems(symbol.tcbLocation.tcbPath, shimPosition, options);
if (res === undefined) {
return undefined;
}
// The TS language service results are almost returnable as-is. However, they contain an
// `applicableSpan` which marks the entire argument list, and that span is in the context of the
// TCB's `ts.CallExpression`. It needs to be replaced with the span for the `Call` argument list.
return {
...res,
applicableSpan: {
start: expr.argumentSpan.start,
length: expr.argumentSpan.end - expr.argumentSpan.start,
},
};
}
| {
"end_byte": 5620,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/signature_help.ts"
} |
angular/packages/language-service/src/refactorings/refactoring.ts_0_3111 | /**
* @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 {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import ts from 'typescript';
import {ApplyRefactoringProgressFn, ApplyRefactoringResult} from '@angular/language-service/api';
import {CompilerOptions} from '@angular/compiler-cli';
import {
ConvertFieldToSignalInputBestEffortRefactoring,
ConvertFieldToSignalInputRefactoring,
} from './convert_to_signal_input/individual_input_refactoring';
import {
ConvertFullClassToSignalInputsBestEffortRefactoring,
ConvertFullClassToSignalInputsRefactoring,
} from './convert_to_signal_input/full_class_input_refactoring';
import {
ConvertFieldToSignalQueryBestEffortRefactoring,
ConvertFieldToSignalQueryRefactoring,
} from './convert_to_signal_queries/individual_query_refactoring';
import {
ConvertFullClassToSignalQueriesBestEffortRefactoring,
ConvertFullClassToSignalQueriesRefactoring,
} from './convert_to_signal_queries/full_class_query_refactoring';
/**
* Interface exposing static metadata for a {@link Refactoring},
* exposed via static fields.
*
* A refactoring may be applicable at a given position inside
* a file. If it becomes applicable, the language service will suggest
* it as a code action.
*
* Later, the user can request edits for the refactoring lazily, upon
* e.g. click. The refactoring class is then instantiated and will be
* re-used for future applications, allowing for efficient re-use of e.g
* analysis data.
*/
export interface Refactoring {
new (project: ts.server.Project): ActiveRefactoring;
/** Unique id of the refactoring. */
id: string;
/** Description of the refactoring. Shown in e.g. VSCode as the code action. */
description: string;
/** Whether the refactoring is applicable at the given location. */
isApplicable(
compiler: NgCompiler,
fileName: string,
positionOrRange: number | ts.TextRange,
): boolean;
}
/**
* Interface that describes an active refactoring instance. A
* refactoring may be lazily instantiated whenever the refactoring
* is requested to be applied.
*
* More information can be found in {@link Refactoring}
*/
export interface ActiveRefactoring {
/** Computes the edits for the refactoring. */
computeEditsForFix(
compiler: NgCompiler,
compilerOptions: CompilerOptions,
fileName: string,
positionOrRange: number | ts.TextRange,
reportProgress: ApplyRefactoringProgressFn,
): Promise<ApplyRefactoringResult>;
}
export const allRefactorings: Refactoring[] = [
// Signal Input migration
ConvertFieldToSignalInputRefactoring,
ConvertFieldToSignalInputBestEffortRefactoring,
ConvertFullClassToSignalInputsRefactoring,
ConvertFullClassToSignalInputsBestEffortRefactoring,
// Queries migration
ConvertFieldToSignalQueryRefactoring,
ConvertFieldToSignalQueryBestEffortRefactoring,
ConvertFullClassToSignalQueriesRefactoring,
ConvertFullClassToSignalQueriesBestEffortRefactoring,
];
| {
"end_byte": 3111,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/refactorings/refactoring.ts"
} |
angular/packages/language-service/src/refactorings/BUILD.bazel_0_892 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//packages/language-service:__subpackages__"])
ts_library(
name = "refactorings",
srcs = glob([
"**/*.ts",
]),
deps = [
"//packages/compiler-cli",
"//packages/compiler-cli/src/ngtsc/annotations",
"//packages/compiler-cli/src/ngtsc/core",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/core/schematics/migrations/signal-migration/src",
"//packages/core/schematics/migrations/signal-queries-migration:migration",
"//packages/core/schematics/utils/tsurge",
"//packages/language-service:api",
"//packages/language-service/src/utils",
"@npm//@types/node",
"@npm//typescript",
],
)
| {
"end_byte": 892,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/refactorings/BUILD.bazel"
} |
angular/packages/language-service/src/refactorings/convert_to_signal_queries/decorators.ts_0_1132 | /**
* @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 ts from 'typescript';
import {getAngularDecorators} from '@angular/compiler-cli/src/ngtsc/annotations';
import {ReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection';
import {isDirectiveOrComponent} from '../../utils/decorators';
export function isDecoratorQueryClassField(
node: ts.ClassElement,
reflector: ReflectionHost,
): boolean {
const decorators = reflector.getDecoratorsOfDeclaration(node);
if (decorators === null) {
return false;
}
return (
getAngularDecorators(
decorators,
['ViewChild', 'ViewChildren', 'ContentChild', 'ContentChildren'],
/* isCore */ false,
).length > 0
);
}
export function isDirectiveOrComponentWithQueries(
node: ts.ClassDeclaration,
reflector: ReflectionHost,
): boolean {
if (!isDirectiveOrComponent(node, reflector)) {
return false;
}
return node.members.some((m) => isDecoratorQueryClassField(m, reflector));
}
| {
"end_byte": 1132,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/refactorings/convert_to_signal_queries/decorators.ts"
} |
angular/packages/language-service/src/refactorings/convert_to_signal_queries/apply_query_refactoring.ts_0_5831 | /**
* @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 {CompilerOptions} from '@angular/compiler-cli';
import {getFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import ts from 'typescript';
import {groupReplacementsByFile} from '@angular/core/schematics/utils/tsurge/helpers/group_replacements';
import {ApplyRefactoringProgressFn, ApplyRefactoringResult} from '../../../api';
import {
MigrationConfig,
SignalQueriesMigration,
} from '@angular/core/schematics/migrations/signal-queries-migration';
import assert from 'assert';
import {projectFile} from '../../../../core/schematics/utils/tsurge';
import {FieldIncompatibilityReason} from '../../../../core/schematics/migrations/signal-migration/src';
import {
isFieldIncompatibility,
nonIgnorableFieldIncompatibilities,
} from '../../../../core/schematics/migrations/signal-migration/src/passes/problematic_patterns/incompatibility';
export async function applySignalQueriesRefactoring(
compiler: NgCompiler,
compilerOptions: CompilerOptions,
config: MigrationConfig,
project: ts.server.Project,
reportProgress: ApplyRefactoringProgressFn,
shouldMigrateQuery: NonNullable<MigrationConfig['shouldMigrateQuery']>,
multiMode: boolean,
): Promise<ApplyRefactoringResult> {
reportProgress(0, 'Starting queries migration. Analyzing..');
const fs = getFileSystem();
const migration = new SignalQueriesMigration({
...config,
assumeNonBatch: true,
reportProgressFn: reportProgress,
shouldMigrateQuery,
});
const programInfo = migration.prepareProgram({
ngCompiler: compiler,
program: compiler.getCurrentProgram(),
userOptions: compilerOptions,
programAbsoluteRootFileNames: [],
host: {
getCanonicalFileName: (file) => project.projectService.toCanonicalFileName(file),
getCurrentDirectory: () => project.getCurrentDirectory(),
},
});
const unitData = await migration.analyze(programInfo);
const globalMeta = await migration.globalMeta(unitData);
const {replacements, knownQueries} = await migration.migrate(globalMeta, programInfo);
const targetQueries = Array.from(knownQueries.knownQueryIDs.values()).filter((descriptor) =>
shouldMigrateQuery(descriptor, projectFile(descriptor.node.getSourceFile(), programInfo)),
);
if (targetQueries.length === 0) {
return {
edits: [],
errorMessage: 'Unexpected error. Could not find target queries in registry.',
};
}
const incompatibilityMessages = new Map<string, string>();
const incompatibilityReasons = new Set<FieldIncompatibilityReason>();
for (const query of targetQueries.filter((i) => knownQueries.isFieldIncompatible(i))) {
// TODO: Improve type safety around this.
assert(
query.node.name !== undefined && ts.isIdentifier(query.node.name),
'Expected query to have an analyzable field name.',
);
const incompatibility = knownQueries.getIncompatibilityForField(query);
const text = knownQueries.getIncompatibilityTextForField(query);
if (incompatibility === null || text === null) {
return {
edits: [],
errorMessage:
'Queries could not be migrated, but no reasons were found. ' +
'Consider reporting a bug to the Angular team.',
};
}
incompatibilityMessages.set(query.node.name.text, `${text.short}\n${text.extra}`);
// Track field incompatibilities as those may be "ignored" via best effort mode.
if (isFieldIncompatibility(incompatibility)) {
incompatibilityReasons.add(incompatibility.reason);
}
}
let message: string | undefined = undefined;
if (!multiMode && incompatibilityMessages.size === 1) {
const [fieldName, reason] = incompatibilityMessages.entries().next().value!;
message = `Query field "${fieldName}" could not be migrated. ${reason}\n`;
} else if (incompatibilityMessages.size > 0) {
const queryPlural = incompatibilityMessages.size === 1 ? 'query' : `queries`;
message = `${incompatibilityMessages.size} ${queryPlural} could not be migrated.\n`;
message += `For more details, click on the skipped queries and try to migrate individually.\n`;
}
// Only suggest the "force ignoring" option if there are actually
// ignorable incompatibilities.
const canBeForciblyIgnored = Array.from(incompatibilityReasons).some(
(r) => !nonIgnorableFieldIncompatibilities.includes(r),
);
if (!config.bestEffortMode && canBeForciblyIgnored) {
message += `Use the "(forcibly, ignoring errors)" action to forcibly convert.\n`;
}
// In multi mode, partial migration is allowed.
if (!multiMode && incompatibilityMessages.size > 0) {
return {
edits: [],
errorMessage: message,
};
}
const fileUpdates = Array.from(groupReplacementsByFile(replacements).entries());
const edits: ts.FileTextChanges[] = fileUpdates.map(([relativePath, changes]) => {
return {
fileName: fs.join(programInfo.projectRoot, relativePath),
textChanges: changes.map((c) => ({
newText: c.data.toInsert,
span: {
start: c.data.position,
length: c.data.end - c.data.position,
},
})),
};
});
const allQueriesIncompatible = incompatibilityMessages.size === targetQueries.length;
// Depending on whether all queries were incompatible, the message is either
// an error, or just a warning (in case of partial migration still succeeding).
const errorMessage = allQueriesIncompatible ? message : undefined;
const warningMessage = allQueriesIncompatible ? undefined : message;
return {edits, warningMessage, errorMessage};
}
| {
"end_byte": 5831,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/refactorings/convert_to_signal_queries/apply_query_refactoring.ts"
} |
angular/packages/language-service/src/refactorings/convert_to_signal_queries/full_class_query_refactoring.ts_0_4277 | /**
* @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 {CompilerOptions} from '@angular/compiler-cli';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {MigrationConfig} from '@angular/core/schematics/migrations/signal-migration/src';
import {ApplyRefactoringProgressFn, ApplyRefactoringResult} from '@angular/language-service/api';
import ts from 'typescript';
import {isTypeScriptFile} from '../../utils';
import {findTightestNode, getParentClassDeclaration} from '../../utils/ts_utils';
import type {ActiveRefactoring} from '../refactoring';
import {isDecoratorQueryClassField, isDirectiveOrComponentWithQueries} from './decorators';
import {applySignalQueriesRefactoring} from './apply_query_refactoring';
/**
* Base language service refactoring action that can convert decorator
* queries of a full class to signal queries.
*
* The user can click on an class with decorator queries and ask for all the queries
* to be migrated. All references, imports and the declaration are updated automatically.
*/
abstract class BaseConvertFullClassToSignalQueriesRefactoring implements ActiveRefactoring {
abstract config: MigrationConfig;
constructor(private project: ts.server.Project) {}
static isApplicable(
compiler: NgCompiler,
fileName: string,
positionOrRange: number | ts.TextRange,
): boolean {
if (!isTypeScriptFile(fileName)) {
return false;
}
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return false;
}
const start = typeof positionOrRange === 'number' ? positionOrRange : positionOrRange.pos;
const node = findTightestNode(sf, start);
if (node === undefined) {
return false;
}
const classDecl = getParentClassDeclaration(node);
if (classDecl === undefined) {
return false;
}
const {reflector} = compiler['ensureAnalyzed']();
if (!isDirectiveOrComponentWithQueries(classDecl, reflector)) {
return false;
}
const parentClassElement = ts.findAncestor(node, (n) => ts.isClassElement(n) || ts.isBlock(n));
if (parentClassElement === undefined) {
return true;
}
// If we are inside a body of e.g. an accessor, this action should not show up.
if (ts.isBlock(parentClassElement)) {
return false;
}
return isDecoratorQueryClassField(parentClassElement, reflector);
}
async computeEditsForFix(
compiler: NgCompiler,
compilerOptions: CompilerOptions,
fileName: string,
positionOrRange: number | ts.TextRange,
reportProgress: ApplyRefactoringProgressFn,
): Promise<ApplyRefactoringResult> {
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return {edits: []};
}
const start = typeof positionOrRange === 'number' ? positionOrRange : positionOrRange.pos;
const node = findTightestNode(sf, start);
if (node === undefined) {
return {edits: []};
}
const containingClass = getParentClassDeclaration(node);
if (containingClass === null) {
return {edits: [], errorMessage: 'Could not find a class for the refactoring.'};
}
return await applySignalQueriesRefactoring(
compiler,
compilerOptions,
this.config,
this.project,
reportProgress,
(queryID) => queryID.node.parent === containingClass,
/** allowPartialMigration */ true,
);
}
}
export class ConvertFullClassToSignalQueriesRefactoring extends BaseConvertFullClassToSignalQueriesRefactoring {
static id = 'convert-full-class-to-signal-queries-safe-mode';
static description = 'Full class: Convert all decorator queries to signal queries (safe)';
override config: MigrationConfig = {};
}
export class ConvertFullClassToSignalQueriesBestEffortRefactoring extends BaseConvertFullClassToSignalQueriesRefactoring {
static id = 'convert-full-class-to-signal-queries-best-effort-mode';
static description =
'Full class: Convert all decorator queries to signal queries (forcibly, ignoring errors)';
override config: MigrationConfig = {bestEffortMode: true};
}
| {
"end_byte": 4277,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/refactorings/convert_to_signal_queries/full_class_query_refactoring.ts"
} |
angular/packages/language-service/src/refactorings/convert_to_signal_queries/individual_query_refactoring.ts_0_4264 | /**
* @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 {CompilerOptions} from '@angular/compiler-cli';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {ApplyRefactoringProgressFn, ApplyRefactoringResult} from '@angular/language-service/api';
import ts from 'typescript';
import {isTypeScriptFile} from '../../utils';
import {findTightestNode, getParentClassDeclaration} from '../../utils/ts_utils';
import type {ActiveRefactoring} from '../refactoring';
import {applySignalQueriesRefactoring} from './apply_query_refactoring';
import {isDecoratorQueryClassField} from './decorators';
import {isDirectiveOrComponent} from '../../utils/decorators';
import {MigrationConfig} from '../../../../core/schematics/migrations/signal-queries-migration';
/**
* Base language service refactoring action that can convert a
* single individual decorator query declaration to a signal query
*
* The user can click on an `@ViewChild` property declaration in e.g. the VSCode
* extension and ask for the query to be migrated. All references, imports and
* the declaration are updated automatically.
*/
abstract class BaseConvertFieldToSignalQueryRefactoring implements ActiveRefactoring {
abstract config: MigrationConfig;
constructor(private project: ts.server.Project) {}
static isApplicable(
compiler: NgCompiler,
fileName: string,
positionOrRange: number | ts.TextRange,
): boolean {
if (!isTypeScriptFile(fileName)) {
return false;
}
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return false;
}
const start = typeof positionOrRange === 'number' ? positionOrRange : positionOrRange.pos;
const node = findTightestNode(sf, start);
if (node === undefined) {
return false;
}
const classDecl = getParentClassDeclaration(node);
if (classDecl === undefined) {
return false;
}
const {reflector} = compiler['ensureAnalyzed']();
if (!isDirectiveOrComponent(classDecl, reflector)) {
return false;
}
const parentClassElement = ts.findAncestor(node, (n) => ts.isClassElement(n) || ts.isBlock(n));
// If we are inside a body of e.g. an accessor, this action should not show up.
if (parentClassElement === undefined || ts.isBlock(parentClassElement)) {
return false;
}
return isDecoratorQueryClassField(parentClassElement, reflector);
}
async computeEditsForFix(
compiler: NgCompiler,
compilerOptions: CompilerOptions,
fileName: string,
positionOrRange: number | ts.TextRange,
reportProgress: ApplyRefactoringProgressFn,
): Promise<ApplyRefactoringResult> {
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return {edits: []};
}
const start = typeof positionOrRange === 'number' ? positionOrRange : positionOrRange.pos;
const node = findTightestNode(sf, start);
if (node === undefined) {
return {edits: []};
}
const containingClassElement = ts.findAncestor(node, ts.isClassElement);
if (containingClassElement === undefined) {
return {edits: [], errorMessage: 'Selected node does not belong to a query.'};
}
return await applySignalQueriesRefactoring(
compiler,
compilerOptions,
this.config,
this.project,
reportProgress,
(query) => query.node === containingClassElement,
/** allowPartialMigration */ false,
);
}
}
export class ConvertFieldToSignalQueryRefactoring extends BaseConvertFieldToSignalQueryRefactoring {
static id = 'convert-field-to-signal-query-safe-mode';
static description = 'Convert this decorator query to a signal query (safe)';
override config: MigrationConfig = {};
}
export class ConvertFieldToSignalQueryBestEffortRefactoring extends BaseConvertFieldToSignalQueryRefactoring {
static id = 'convert-field-to-signal-query-best-effort-mode';
static description = 'Convert this decorator query to a signal query (forcibly, ignoring errors)';
override config: MigrationConfig = {bestEffortMode: true};
}
| {
"end_byte": 4264,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/refactorings/convert_to_signal_queries/individual_query_refactoring.ts"
} |
angular/packages/language-service/src/refactorings/convert_to_signal_input/decorators.ts_0_1041 | /**
* @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 ts from 'typescript';
import {getAngularDecorators} from '@angular/compiler-cli/src/ngtsc/annotations';
import {ReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection';
import {isDirectiveOrComponent} from '../../utils/decorators';
export function isDecoratorInputClassField(
node: ts.ClassElement,
reflector: ReflectionHost,
): boolean {
const decorators = reflector.getDecoratorsOfDeclaration(node);
if (decorators === null) {
return false;
}
return getAngularDecorators(decorators, ['Input'], /* isCore */ false).length > 0;
}
export function isDirectiveOrComponentWithInputs(
node: ts.ClassDeclaration,
reflector: ReflectionHost,
): boolean {
if (!isDirectiveOrComponent(node, reflector)) {
return false;
}
return node.members.some((m) => isDecoratorInputClassField(m, reflector));
}
| {
"end_byte": 1041,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/refactorings/convert_to_signal_input/decorators.ts"
} |
angular/packages/language-service/src/refactorings/convert_to_signal_input/individual_input_refactoring.ts_0_4320 | /**
* @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 {CompilerOptions} from '@angular/compiler-cli';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {
isInputContainerNode,
MigrationConfig,
} from '@angular/core/schematics/migrations/signal-migration/src';
import {ApplyRefactoringProgressFn, ApplyRefactoringResult} from '@angular/language-service/api';
import ts from 'typescript';
import {isTypeScriptFile} from '../../utils';
import {findTightestNode, getParentClassDeclaration} from '../../utils/ts_utils';
import type {ActiveRefactoring} from '../refactoring';
import {applySignalInputRefactoring} from './apply_input_refactoring';
import {isDecoratorInputClassField} from './decorators';
import {isDirectiveOrComponent} from '../../utils/decorators';
/**
* Base language service refactoring action that can convert a
* single individual `@Input()` declaration to a signal inputs
*
* The user can click on an `@Input` property declaration in e.g. the VSCode
* extension and ask for the input to be migrated. All references, imports and
* the declaration are updated automatically.
*/
abstract class BaseConvertFieldToSignalInputRefactoring implements ActiveRefactoring {
abstract config: MigrationConfig;
constructor(private project: ts.server.Project) {}
static isApplicable(
compiler: NgCompiler,
fileName: string,
positionOrRange: number | ts.TextRange,
): boolean {
if (!isTypeScriptFile(fileName)) {
return false;
}
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return false;
}
const start = typeof positionOrRange === 'number' ? positionOrRange : positionOrRange.pos;
const node = findTightestNode(sf, start);
if (node === undefined) {
return false;
}
const classDecl = getParentClassDeclaration(node);
if (classDecl === undefined) {
return false;
}
const {reflector} = compiler['ensureAnalyzed']();
if (!isDirectiveOrComponent(classDecl, reflector)) {
return false;
}
const parentClassElement = ts.findAncestor(node, (n) => ts.isClassElement(n) || ts.isBlock(n));
// If we are inside a body of e.g. an accessor, this action should not show up.
if (parentClassElement === undefined || ts.isBlock(parentClassElement)) {
return false;
}
return isDecoratorInputClassField(parentClassElement, reflector);
}
async computeEditsForFix(
compiler: NgCompiler,
compilerOptions: CompilerOptions,
fileName: string,
positionOrRange: number | ts.TextRange,
reportProgress: ApplyRefactoringProgressFn,
): Promise<ApplyRefactoringResult> {
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return {edits: []};
}
const start = typeof positionOrRange === 'number' ? positionOrRange : positionOrRange.pos;
const node = findTightestNode(sf, start);
if (node === undefined) {
return {edits: []};
}
const containingClassElement = ts.findAncestor(node, ts.isClassElement);
if (containingClassElement === undefined || !isInputContainerNode(containingClassElement)) {
return {edits: [], errorMessage: 'Selected node does not belong to an input.'};
}
return await applySignalInputRefactoring(
compiler,
compilerOptions,
this.config,
this.project,
reportProgress,
(input) => input.descriptor.node === containingClassElement,
/** allowPartialMigration */ false,
);
}
}
export class ConvertFieldToSignalInputRefactoring extends BaseConvertFieldToSignalInputRefactoring {
static id = 'convert-field-to-signal-input-safe-mode';
static description = 'Convert this @Input() to a signal input (safe)';
override config: MigrationConfig = {};
}
export class ConvertFieldToSignalInputBestEffortRefactoring extends BaseConvertFieldToSignalInputRefactoring {
static id = 'convert-field-to-signal-input-best-effort-mode';
static description = 'Convert this @Input() to a signal input (forcibly, ignoring errors)';
override config: MigrationConfig = {bestEffortMode: true};
}
| {
"end_byte": 4320,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/refactorings/convert_to_signal_input/individual_input_refactoring.ts"
} |
angular/packages/language-service/src/refactorings/convert_to_signal_input/full_class_input_refactoring.ts_0_4246 | /**
* @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 {CompilerOptions} from '@angular/compiler-cli';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {MigrationConfig} from '@angular/core/schematics/migrations/signal-migration/src';
import {ApplyRefactoringProgressFn, ApplyRefactoringResult} from '@angular/language-service/api';
import ts from 'typescript';
import {isTypeScriptFile} from '../../utils';
import {findTightestNode, getParentClassDeclaration} from '../../utils/ts_utils';
import type {ActiveRefactoring} from '../refactoring';
import {applySignalInputRefactoring} from './apply_input_refactoring';
import {isDecoratorInputClassField, isDirectiveOrComponentWithInputs} from './decorators';
/**
* Base language service refactoring action that can convert `@Input()`
* declarations of a full class to signal inputs.
*
* The user can click on an class with `@Input`s and ask for all the input to be migrated.
* All references, imports and the declaration are updated automatically.
*/
abstract class BaseConvertFullClassToSignalInputsRefactoring implements ActiveRefactoring {
abstract config: MigrationConfig;
constructor(private project: ts.server.Project) {}
static isApplicable(
compiler: NgCompiler,
fileName: string,
positionOrRange: number | ts.TextRange,
): boolean {
if (!isTypeScriptFile(fileName)) {
return false;
}
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return false;
}
const start = typeof positionOrRange === 'number' ? positionOrRange : positionOrRange.pos;
const node = findTightestNode(sf, start);
if (node === undefined) {
return false;
}
const classDecl = getParentClassDeclaration(node);
if (classDecl === undefined) {
return false;
}
const {reflector} = compiler['ensureAnalyzed']();
if (!isDirectiveOrComponentWithInputs(classDecl, reflector)) {
return false;
}
const parentClassElement = ts.findAncestor(node, (n) => ts.isClassElement(n) || ts.isBlock(n));
if (parentClassElement === undefined) {
return true;
}
// If we are inside a body of e.g. an accessor, this action should not show up.
if (ts.isBlock(parentClassElement)) {
return false;
}
return isDecoratorInputClassField(parentClassElement, reflector);
}
async computeEditsForFix(
compiler: NgCompiler,
compilerOptions: CompilerOptions,
fileName: string,
positionOrRange: number | ts.TextRange,
reportProgress: ApplyRefactoringProgressFn,
): Promise<ApplyRefactoringResult> {
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return {edits: []};
}
const start = typeof positionOrRange === 'number' ? positionOrRange : positionOrRange.pos;
const node = findTightestNode(sf, start);
if (node === undefined) {
return {edits: []};
}
const containingClass = getParentClassDeclaration(node);
if (containingClass === null) {
return {edits: [], errorMessage: 'Could not find a class for the refactoring.'};
}
return await applySignalInputRefactoring(
compiler,
compilerOptions,
this.config,
this.project,
reportProgress,
(input) => input.descriptor.node.parent === containingClass,
/** allowPartialMigration */ true,
);
}
}
export class ConvertFullClassToSignalInputsRefactoring extends BaseConvertFullClassToSignalInputsRefactoring {
static id = 'convert-full-class-to-signal-inputs-safe-mode';
static description = "Full class: Convert all @Input's to signal inputs (safe)";
override config: MigrationConfig = {};
}
export class ConvertFullClassToSignalInputsBestEffortRefactoring extends BaseConvertFullClassToSignalInputsRefactoring {
static id = 'convert-full-class-to-signal-inputs-best-effort-mode';
static description =
"Full class: Convert all @Input's to signal inputs (forcibly, ignoring errors)";
override config: MigrationConfig = {bestEffortMode: true};
}
| {
"end_byte": 4246,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/refactorings/convert_to_signal_input/full_class_input_refactoring.ts"
} |
angular/packages/language-service/src/refactorings/convert_to_signal_input/apply_input_refactoring.ts_0_5744 | /**
* @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 {CompilerOptions} from '@angular/compiler-cli';
import {getFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import ts from 'typescript';
import {
getMessageForClassIncompatibility,
getMessageForFieldIncompatibility,
FieldIncompatibilityReason,
KnownInputInfo,
MigrationConfig,
nonIgnorableFieldIncompatibilities,
SignalInputMigration,
} from '@angular/core/schematics/migrations/signal-migration/src';
import {groupReplacementsByFile} from '@angular/core/schematics/utils/tsurge/helpers/group_replacements';
import {ApplyRefactoringProgressFn, ApplyRefactoringResult} from '../../../api';
export async function applySignalInputRefactoring(
compiler: NgCompiler,
compilerOptions: CompilerOptions,
config: MigrationConfig,
project: ts.server.Project,
reportProgress: ApplyRefactoringProgressFn,
shouldMigrateInput: (input: KnownInputInfo) => boolean,
multiMode: boolean,
): Promise<ApplyRefactoringResult> {
reportProgress(0, 'Starting input migration. Analyzing..');
const fs = getFileSystem();
const migration = new SignalInputMigration({
...config,
upgradeAnalysisPhaseToAvoidBatch: true,
reportProgressFn: reportProgress,
shouldMigrateInput: shouldMigrateInput,
});
await migration.analyze(
migration.prepareProgram({
ngCompiler: compiler,
program: compiler.getCurrentProgram(),
userOptions: compilerOptions,
programAbsoluteRootFileNames: [],
host: {
getCanonicalFileName: (file) => project.projectService.toCanonicalFileName(file),
getCurrentDirectory: () => project.getCurrentDirectory(),
},
}),
);
if (migration.upgradedAnalysisPhaseResults === null) {
return {
edits: [],
errorMessage: 'Unexpected error. No analysis result is available.',
};
}
const {knownInputs, replacements, projectRoot} = migration.upgradedAnalysisPhaseResults;
const targetInputs = Array.from(knownInputs.knownInputIds.values()).filter(shouldMigrateInput);
if (targetInputs.length === 0) {
return {
edits: [],
errorMessage: 'Unexpected error. Could not find target inputs in registry.',
};
}
const incompatibilityMessages = new Map<string, string>();
const incompatibilityReasons = new Set<FieldIncompatibilityReason>();
for (const incompatibleInput of targetInputs.filter((i) => i.isIncompatible())) {
const {container, descriptor} = incompatibleInput;
const memberIncompatibility = container.memberIncompatibility.get(descriptor.key);
const classIncompatibility = container.incompatible;
if (memberIncompatibility !== undefined) {
const {short, extra} = getMessageForFieldIncompatibility(memberIncompatibility.reason, {
single: 'input',
plural: 'inputs',
});
incompatibilityMessages.set(descriptor.node.name.text, `${short}\n${extra}`);
incompatibilityReasons.add(memberIncompatibility.reason);
continue;
}
if (classIncompatibility !== null) {
const {short, extra} = getMessageForClassIncompatibility(classIncompatibility, {
single: 'input',
plural: 'inputs',
});
incompatibilityMessages.set(descriptor.node.name.text, `${short}\n${extra}`);
continue;
}
return {
edits: [],
errorMessage:
'Inputs could not be migrated, but no reasons were found. ' +
'Consider reporting a bug to the Angular team.',
};
}
let message: string | undefined = undefined;
if (!multiMode && incompatibilityMessages.size === 1) {
const [inputName, reason] = incompatibilityMessages.entries().next().value!;
message = `Input field "${inputName}" could not be migrated. ${reason}\n`;
} else if (incompatibilityMessages.size > 0) {
const inputPlural = incompatibilityMessages.size === 1 ? 'input' : `inputs`;
message = `${incompatibilityMessages.size} ${inputPlural} could not be migrated.\n`;
message += `For more details, click on the skipped inputs and try to migrate individually.\n`;
}
// Only suggest the "force ignoring" option if there are actually
// ignorable incompatibilities.
const canBeForciblyIgnored = Array.from(incompatibilityReasons).some(
(r) => !nonIgnorableFieldIncompatibilities.includes(r),
);
if (!config.bestEffortMode && canBeForciblyIgnored) {
message += `Use the "(forcibly, ignoring errors)" action to forcibly convert.\n`;
}
// In multi mode, partial migration is allowed.
if (!multiMode && incompatibilityMessages.size > 0) {
return {
edits: [],
errorMessage: message,
};
}
const fileUpdates = Array.from(groupReplacementsByFile(replacements).entries());
const edits: ts.FileTextChanges[] = fileUpdates.map(([relativePath, changes]) => {
return {
fileName: fs.join(projectRoot, relativePath),
textChanges: changes.map((c) => ({
newText: c.data.toInsert,
span: {
start: c.data.position,
length: c.data.end - c.data.position,
},
})),
};
});
const allInputsIncompatible = incompatibilityMessages.size === targetInputs.length;
// Depending on whether all inputs were incompatible, the message is either
// an error, or just a warning (in case of partial migration still succeeding).
const errorMessage = allInputsIncompatible ? message : undefined;
const warningMessage = allInputsIncompatible ? undefined : message;
return {edits, warningMessage, errorMessage};
}
| {
"end_byte": 5744,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/refactorings/convert_to_signal_input/apply_input_refactoring.ts"
} |
angular/packages/language-service/src/utils/decorators.ts_0_732 | /**
* @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 ts from 'typescript';
import {ReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection';
import {getAngularDecorators} from '@angular/compiler-cli/src/ngtsc/annotations';
export function isDirectiveOrComponent(
node: ts.ClassDeclaration,
reflector: ReflectionHost,
): boolean {
const decorators = reflector.getDecoratorsOfDeclaration(node);
if (decorators === null) {
return false;
}
return (
getAngularDecorators(decorators, ['Directive', 'Component'], /* isCore */ false).length > 0
);
}
| {
"end_byte": 732,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/utils/decorators.ts"
} |
angular/packages/language-service/src/utils/ts_utils.ts_0_8358 | /**
* @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 {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {
PotentialDirective,
PotentialImportMode,
PotentialPipe,
TemplateTypeChecker,
} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
import {guessIndentationInSingleLine} from './format';
/**
* Return the node that most tightly encompasses the specified `position`.
* @param node The starting node to start the top-down search.
* @param position The target position within the `node`.
*/
export function findTightestNode(node: ts.Node, position: number): ts.Node | undefined {
if (node.getStart() <= position && position < node.getEnd()) {
return node.forEachChild((c) => findTightestNode(c, position)) ?? node;
}
return undefined;
}
export interface FindOptions<T extends ts.Node> {
filter: (node: ts.Node) => node is T;
}
/**
* Finds TypeScript nodes descending from the provided root which match the given filter.
*/
export function findAllMatchingNodes<T extends ts.Node>(root: ts.Node, opts: FindOptions<T>): T[] {
const matches: T[] = [];
const explore = (currNode: ts.Node) => {
if (opts.filter(currNode)) {
matches.push(currNode);
}
currNode.forEachChild((descendent) => explore(descendent));
};
explore(root);
return matches;
}
/**
* Finds TypeScript nodes descending from the provided root which match the given filter.
*/
export function findFirstMatchingNode<T extends ts.Node>(
root: ts.Node,
opts: FindOptions<T>,
): T | null {
let match: T | null = null;
const explore = (currNode: ts.Node) => {
if (match !== null) {
return;
}
if (opts.filter(currNode)) {
match = currNode;
return;
}
currNode.forEachChild((descendent) => explore(descendent));
};
explore(root);
return match;
}
export function getParentClassDeclaration(startNode: ts.Node): ts.ClassDeclaration | undefined {
while (startNode) {
if (ts.isClassDeclaration(startNode)) {
return startNode;
}
startNode = startNode.parent;
}
return undefined;
}
/**
* Returns a property assignment from the assignment value if the property name
* matches the specified `key`, or `null` if there is no match.
*/
export function getPropertyAssignmentFromValue(
value: ts.Node,
key: string,
): ts.PropertyAssignment | null {
const propAssignment = value.parent;
if (
!propAssignment ||
!ts.isPropertyAssignment(propAssignment) ||
propAssignment.name.getText() !== key
) {
return null;
}
return propAssignment;
}
/**
* Given a decorator property assignment, return the ClassDeclaration node that corresponds to the
* directive class the property applies to.
* If the property assignment is not on a class decorator, no declaration is returned.
*
* For example,
*
* @Component({
* template: '<div></div>'
* ^^^^^^^^^^^^^^^^^^^^^^^---- property assignment
* })
* class AppComponent {}
* ^---- class declaration node
*
* @param propAsgnNode property assignment
*/
export function getClassDeclFromDecoratorProp(
propAsgnNode: ts.PropertyAssignment,
): ts.ClassDeclaration | undefined {
if (!propAsgnNode.parent || !ts.isObjectLiteralExpression(propAsgnNode.parent)) {
return;
}
const objLitExprNode = propAsgnNode.parent;
if (!objLitExprNode.parent || !ts.isCallExpression(objLitExprNode.parent)) {
return;
}
const callExprNode = objLitExprNode.parent;
if (!callExprNode.parent || !ts.isDecorator(callExprNode.parent)) {
return;
}
const decorator = callExprNode.parent;
if (!decorator.parent || !ts.isClassDeclaration(decorator.parent)) {
return;
}
const classDeclNode = decorator.parent;
return classDeclNode;
}
/**
* Collects all member methods, including those from base classes.
*/
export function collectMemberMethods(
clazz: ts.ClassDeclaration,
typeChecker: ts.TypeChecker,
): ts.MethodDeclaration[] {
const members: ts.MethodDeclaration[] = [];
const apparentProps = typeChecker.getTypeAtLocation(clazz).getApparentProperties();
for (const prop of apparentProps) {
if (prop.valueDeclaration && ts.isMethodDeclaration(prop.valueDeclaration)) {
members.push(prop.valueDeclaration);
}
}
return members;
}
/**
* Given an existing array literal expression, update it by pushing a new expression.
*/
export function addElementToArrayLiteral(
arr: ts.ArrayLiteralExpression,
elem: ts.Expression,
): ts.ArrayLiteralExpression {
return ts.factory.updateArrayLiteralExpression(arr, [...arr.elements, elem]);
}
/**
* Given an ObjectLiteralExpression node, extract and return the PropertyAssignment corresponding to
* the given key. `null` if no such key exists.
*/
export function objectPropertyAssignmentForKey(
obj: ts.ObjectLiteralExpression,
key: string,
): ts.PropertyAssignment | null {
const matchingProperty = obj.properties.filter(
(a) => a.name !== undefined && ts.isIdentifier(a.name) && a.name.escapedText === key,
)[0];
return matchingProperty && ts.isPropertyAssignment(matchingProperty) ? matchingProperty : null;
}
/**
* Given an ObjectLiteralExpression node, create or update the specified key, using the provided
* callback to generate the new value (possibly based on an old value), and return the `ts.PropertyAssignment`
* for the key.
*/
export function updateObjectValueForKey(
obj: ts.ObjectLiteralExpression,
key: string,
newValueFn: (oldValue?: ts.Expression) => ts.Expression,
): ts.PropertyAssignment {
const existingProp = objectPropertyAssignmentForKey(obj, key);
return ts.factory.createPropertyAssignment(
ts.factory.createIdentifier(key),
newValueFn(existingProp?.initializer),
);
}
/**
* Create a new ArrayLiteralExpression, or accept an existing one.
* Ensure the array contains the provided identifier.
* Returns the array, either updated or newly created.
* If no update is needed, returns `null`.
*/
export function ensureArrayWithIdentifier(
identifierText: string,
expression: ts.Expression,
arr?: ts.ArrayLiteralExpression,
): ts.ArrayLiteralExpression | null {
if (arr === undefined) {
return ts.factory.createArrayLiteralExpression([expression]);
}
if (arr.elements.find((v) => ts.isIdentifier(v) && v.text === identifierText)) {
return null;
}
return ts.factory.updateArrayLiteralExpression(arr, [...arr.elements, expression]);
}
export function moduleSpecifierPointsToFile(
tsChecker: ts.TypeChecker,
moduleSpecifier: ts.Expression,
file: ts.SourceFile,
): boolean {
const specifierSymbol = tsChecker.getSymbolAtLocation(moduleSpecifier);
if (specifierSymbol === undefined) {
console.error(`Undefined symbol for module specifier ${moduleSpecifier.getText()}`);
return false;
}
const symbolDeclarations = specifierSymbol.declarations;
if (symbolDeclarations === undefined || symbolDeclarations.length === 0) {
console.error(`Unknown symbol declarations for module specifier ${moduleSpecifier.getText()}`);
return false;
}
for (const symbolDeclaration of symbolDeclarations) {
if (symbolDeclaration.getSourceFile().fileName === file.fileName) {
return true;
}
}
return false;
}
/**
* Determine whether this an import of the given `propertyName` from a particular module
* specifier already exists. If so, return the local name for that import, which might be an
* alias.
*/
export function hasImport(
tsChecker: ts.TypeChecker,
importDeclarations: ts.ImportDeclaration[],
propName: string,
origin: ts.SourceFile,
): string | null {
return (
importDeclarations
.filter((declaration) =>
moduleSpecifierPointsToFile(tsChecker, declaration.moduleSpecifier, origin),
)
.map((declaration) => importHas(declaration, propName))
.find((prop) => prop !== null) ?? null
);
}
function nameInExportScope(importSpecifier: ts.ImportSpecifier): string {
return importSpecifier.propertyName?.text ?? importSpecifier.name.text;
}
/**
* Determine whether this import declaration already contains an import of the given
* `propertyName`, and if so, the name it can be referred to with in the local scope.
*/ | {
"end_byte": 8358,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/utils/ts_utils.ts"
} |
angular/packages/language-service/src/utils/ts_utils.ts_8359_14389 | function importHas(importDecl: ts.ImportDeclaration, propName: string): string | null {
const importClauseName = importDecl.importClause?.name?.getText();
if (propName === 'default' && importClauseName !== undefined) {
return importClauseName;
}
const bindings = importDecl.importClause?.namedBindings;
if (bindings === undefined) {
return null;
}
// First, we handle the case of explicit named imports.
if (ts.isNamedImports(bindings)) {
// Find any import specifier whose property name in the *export* scope equals the expected
// name.
const specifier = bindings.elements.find(
(importSpecifier) => propName == nameInExportScope(importSpecifier),
);
// Return the name of the property in the *local* scope.
if (specifier === undefined) {
return null;
}
return specifier.name.text;
}
// The other case is a namespace import.
return `${bindings.name.text}.${propName}`;
}
/**
* Given an unqualified name, determine whether an existing import is already using this name in
* the current scope.
* TODO: It would be better to check if *any* symbol uses this name in the current scope.
*/
function importCollisionExists(importDeclaration: ts.ImportDeclaration[], name: string): boolean {
const bindings = importDeclaration.map((declaration) => declaration.importClause?.namedBindings);
const namedBindings: ts.NamedImports[] = bindings.filter(
(binding) => binding !== undefined && ts.isNamedImports(binding),
) as ts.NamedImports[];
const specifiers = namedBindings.flatMap((b) => b.elements);
return specifiers.some((s) => s.name.text === name);
}
/**
* Generator function that yields an infinite sequence of alternative aliases for a given symbol
* name.
*/
function* suggestAlternativeSymbolNames(name: string): Iterator<string> {
for (let i = 1; true; i++) {
yield `${name}_${i}`; // The _n suffix is the same style as TS generated aliases
}
}
/**
* Transform the given import name into an alias that does not collide with any other import
* symbol.
*/
export function nonCollidingImportName(
importDeclarations: ts.ImportDeclaration[],
name: string,
): string {
const possibleNames = suggestAlternativeSymbolNames(name);
while (importCollisionExists(importDeclarations, name)) {
name = possibleNames.next().value;
}
return name;
}
/**
* If the provided trait is standalone, just return it. Otherwise, returns the owning ngModule.
*/
export function standaloneTraitOrNgModule(
checker: TemplateTypeChecker,
trait: ts.ClassDeclaration,
): ts.ClassDeclaration | null {
const componentDecorator = checker.getPrimaryAngularDecorator(trait);
if (componentDecorator == null) {
return null;
}
const owningNgModule = checker.getOwningNgModule(trait);
const isMarkedStandalone = isStandaloneDecorator(componentDecorator);
if (owningNgModule === null && !isMarkedStandalone) {
// TODO(dylhunn): This is a "moduleless component." We should probably suggest the user add
// `standalone: true`.
return null;
}
return owningNgModule ?? trait;
}
/**
* Updates the imports on a TypeScript file, by ensuring the provided import is present.
* Returns the text changes, as well as the name with which the imported symbol can be referred to.
*
* When the component is exported by default, the `symbolName` is `default`, and the `declarationName`
* should be used as the import name.
*/
export function updateImportsForTypescriptFile(
tsChecker: ts.TypeChecker,
file: ts.SourceFile,
symbolName: string,
declarationName: string,
moduleSpecifier: string,
tsFileToImport: ts.SourceFile,
): [ts.TextChange[], string] {
// The trait might already be imported, possibly under a different name. If so, determine the
// local name of the imported trait.
const allImports = findAllMatchingNodes(file, {filter: ts.isImportDeclaration});
const existingImportName: string | null = hasImport(
tsChecker,
allImports,
symbolName,
tsFileToImport,
);
if (existingImportName !== null) {
return [[], existingImportName];
}
// If the trait has not already been imported, we need to insert the new import.
const existingImportDeclaration = allImports.find((decl) =>
moduleSpecifierPointsToFile(tsChecker, decl.moduleSpecifier, tsFileToImport),
);
const importName = nonCollidingImportName(
allImports,
symbolName === 'default' ? declarationName : symbolName,
);
if (existingImportDeclaration !== undefined) {
// Update an existing import declaration.
const importClause = existingImportDeclaration.importClause;
if (importClause === undefined) {
return [[], ''];
}
let span = {start: importClause.getStart(), length: importClause.getWidth()};
const updatedBindings = updateImport(existingImportDeclaration, symbolName, importName);
if (updatedBindings === undefined) {
return [[], ''];
}
const importString = printNode(updatedBindings, file);
return [[{span, newText: importString}], importName];
}
// Find the last import in the file.
let lastImport: ts.ImportDeclaration | null = null;
file.forEachChild((child) => {
if (ts.isImportDeclaration(child)) lastImport = child;
});
// Generate a new import declaration, and insert it after the last import declaration, only
// looking at root nodes in the AST. If no import exists, place it at the start of the file.
let span: ts.TextSpan = {start: 0, length: 0};
if ((lastImport as any) !== null) {
// TODO: Why does the compiler insist this is null?
span.start = lastImport!.getStart() + lastImport!.getWidth();
}
const newImportDeclaration = generateImport(symbolName, importName, moduleSpecifier);
const importString = '\n' + printNode(newImportDeclaration, file);
return [[{span, newText: importString}], importName];
}
/**
* Updates a given Angular trait, such as an NgModule or standalone Component, by adding
* `importName` to the list of imports on the decorator arguments.
*/ | {
"end_byte": 14389,
"start_byte": 8359,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/utils/ts_utils.ts"
} |
angular/packages/language-service/src/utils/ts_utils.ts_14390_23031 | export function updateImportsForAngularTrait(
checker: TemplateTypeChecker,
trait: ts.ClassDeclaration,
importName: string,
forwardRefName: string | null,
): ts.TextChange[] {
// Get the object with arguments passed into the primary Angular decorator for this trait.
const decorator = checker.getPrimaryAngularDecorator(trait);
if (decorator === null) {
return [];
}
const decoratorProps = findFirstMatchingNode(decorator, {filter: ts.isObjectLiteralExpression});
if (decoratorProps === null) {
return [];
}
/**
* The assumption here is that there is a `template` or `templateUrl` in the decorator.
*/
if (decoratorProps.properties.length === 0) {
return [];
}
const lastProp = decoratorProps.properties[decoratorProps.properties.length - 1];
const trailRange = ts.getTrailingCommentRanges(decoratorProps.getSourceFile().text, lastProp.end);
const lastTrailRange =
trailRange !== undefined && trailRange.length > 0
? trailRange[trailRange.length - 1]
: undefined;
const lastTrailRangePos = lastTrailRange?.end ?? lastProp.end;
const oldImports = decoratorProps.properties.find((prop) => prop.name?.getText() === 'imports');
let updateRequired = true;
// Update the trait's imports.
const newDecoratorProps = updateObjectValueForKey(
decoratorProps,
'imports',
(oldValue?: ts.Expression) => {
if (oldValue && !ts.isArrayLiteralExpression(oldValue)) {
return oldValue;
}
const identifier = ts.factory.createIdentifier(importName);
const expression = forwardRefName
? ts.factory.createCallExpression(ts.factory.createIdentifier(forwardRefName), undefined, [
ts.factory.createArrowFunction(
undefined,
undefined,
[],
undefined,
undefined,
identifier,
),
])
: identifier;
const newArr = ensureArrayWithIdentifier(importName, expression, oldValue);
updateRequired = newArr !== null;
return newArr!;
},
);
if (!updateRequired) {
return [];
}
const indentationNumber = guessIndentationInSingleLine(lastProp, lastProp.getSourceFile());
const indentationString = indentationNumber !== undefined ? ' '.repeat(indentationNumber) : '';
let indentationPrefix = ',\n' + indentationString;
/**
* If the last trail range is a single line comment, the `,` should be placed in the next line and the
* `imports` arrays should be placed in the next line of `,`.
*
* For example:
*
* {
* template: "" // this is a comment
* }
*
* =>
*
* {
* template: "" // this is an comment
* ,
* imports: []
* }
*/
if (lastTrailRange?.kind === ts.SyntaxKind.SingleLineCommentTrivia) {
indentationPrefix = '\n' + indentationString + ',\n' + indentationString;
}
return [
{
/**
* If the `imports` exists in the object, replace the old `imports` array with the new `imports` array.
* If the `imports` doesn't exist in the object, append the `imports` array after the last property of the object.
*
* There is a weird usage, but it's acceptable. For example:
*
* {
* template: ``, // This is a comment for the template
* _____________^ // The new `imports` array is appended here before the `,`
* }
*
* =>
*
* {
* template: ``,
* imports: [], // This is a comment for the template
* }
*
*/
span: {
start: oldImports !== undefined ? oldImports.getStart() : lastTrailRangePos,
length: oldImports !== undefined ? oldImports.getEnd() - oldImports.getStart() : 0,
},
newText:
(oldImports !== undefined ? '' : indentationPrefix) +
printNode(newDecoratorProps, trait.getSourceFile()),
},
];
}
/**
* Return whether a given Angular decorator specifies `standalone: true`.
*/
export function isStandaloneDecorator(decorator: ts.Decorator): boolean | null {
const decoratorProps = findFirstMatchingNode(decorator, {filter: ts.isObjectLiteralExpression});
if (decoratorProps === null) {
return null;
}
for (const property of decoratorProps.properties) {
if (!ts.isPropertyAssignment(property)) {
continue;
}
// TODO(dylhunn): What if this is a dynamically evaluated expression?
if (property.name.getText() === 'standalone' && property.initializer.getText() === 'false') {
return false;
}
}
return true;
}
/**
* Generate a new import. Follows the format:
* ```
* import {exportedSpecifierName as localName} from 'rawModuleSpecifier';
* ```
*
* If the component is exported by default, follows the format:
*
* ```
* import exportedSpecifierName from 'rawModuleSpecifier';
* ```
*
* If `exportedSpecifierName` is null, or is equal to `name`, then the qualified import alias will
* be omitted.
*/
export function generateImport(
localName: string,
exportedSpecifierName: string | null,
rawModuleSpecifier: string,
): ts.ImportDeclaration {
let propName: ts.Identifier | undefined;
if (exportedSpecifierName !== null && exportedSpecifierName !== localName) {
propName = ts.factory.createIdentifier(exportedSpecifierName);
}
const name = ts.factory.createIdentifier(localName);
const moduleSpec = ts.factory.createStringLiteral(rawModuleSpecifier);
let importClauseName: ts.Identifier | undefined;
let importBindings: ts.NamedImportBindings | undefined;
if (localName === 'default' && exportedSpecifierName !== null) {
importClauseName = ts.factory.createIdentifier(exportedSpecifierName);
} else {
importBindings = ts.factory.createNamedImports([
ts.factory.createImportSpecifier(false, propName, name),
]);
}
return ts.factory.createImportDeclaration(
undefined,
ts.factory.createImportClause(false, importClauseName, importBindings),
moduleSpec,
undefined,
);
}
/**
* Update an existing named import with a new member.
* If `exportedSpecifierName` is null, or is equal to `name`, then the qualified import alias will
* be omitted.
* If the `localName` is `default` and `exportedSpecifierName` is not null, the `exportedSpecifierName`
* is used as the default import name.
*/
export function updateImport(
importDeclaration: ts.ImportDeclaration,
localName: string,
exportedSpecifierName: string | null,
): ts.ImportClause | undefined {
const importClause = importDeclaration.importClause;
if (importClause === undefined) {
return undefined;
}
const bindings = importClause.namedBindings;
if (bindings !== undefined && ts.isNamespaceImport(bindings)) {
// This should be impossible. If a namespace import is present, the symbol was already
// considered imported above.
console.error(`Unexpected namespace import ${importDeclaration.getText()}`);
return undefined;
}
if (localName === 'default' && exportedSpecifierName !== null) {
const importClauseName = ts.factory.createIdentifier(exportedSpecifierName);
return ts.factory.updateImportClause(
importClause,
false,
importClauseName,
importClause.namedBindings,
);
}
let propertyName: ts.Identifier | undefined;
if (exportedSpecifierName !== null && exportedSpecifierName !== localName) {
propertyName = ts.factory.createIdentifier(exportedSpecifierName);
}
const name = ts.factory.createIdentifier(localName);
const newImport = ts.factory.createImportSpecifier(false, propertyName, name);
let namedImport: ts.NamedImports;
if (bindings === undefined) {
namedImport = ts.factory.createNamedImports([newImport]);
} else {
namedImport = ts.factory.updateNamedImports(bindings, [...bindings.elements, newImport]);
}
return ts.factory.updateImportClause(importClause, false, importClause.name, namedImport);
}
let printer: ts.Printer | null = null;
/**
* Get a ts.Printer for printing AST nodes, reusing the previous Printer if already created.
*/
function getOrCreatePrinter(): ts.Printer {
if (printer === null) {
printer = ts.createPrinter();
}
return printer;
}
/**
* Print a given TypeScript node into a string. Used to serialize entirely synthetic generated AST,
* which will not have `.text` or `.fullText` set.
*/
export function printNode(node: ts.Node, sourceFile: ts.SourceFile): string {
return getOrCreatePrinter().printNode(ts.EmitHint.Unspecified, node, sourceFile);
}
/**
* Get the code actions to tell the vscode how to import the directive into the standalone component or ng module.
*/ | {
"end_byte": 23031,
"start_byte": 14390,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/utils/ts_utils.ts"
} |
angular/packages/language-service/src/utils/ts_utils.ts_23032_25654 | export function getCodeActionToImportTheDirectiveDeclaration(
compiler: NgCompiler,
importOn: ts.ClassDeclaration,
directive: PotentialDirective | PotentialPipe,
): ts.CodeAction[] | undefined {
const codeActions: ts.CodeAction[] = [];
const currMatchSymbol = directive.tsSymbol.valueDeclaration!;
const potentialImports = compiler
.getTemplateTypeChecker()
.getPotentialImportsFor(directive.ref, importOn, PotentialImportMode.Normal);
const declarationName = directive.ref.node.name.getText();
for (const potentialImport of potentialImports) {
const fileImportChanges: ts.TextChange[] = [];
let importName: string;
let forwardRefName: string | null = null;
if (potentialImport.moduleSpecifier) {
const [importChanges, generatedImportName] = updateImportsForTypescriptFile(
compiler.getCurrentProgram().getTypeChecker(),
importOn.getSourceFile(),
potentialImport.symbolName,
declarationName,
potentialImport.moduleSpecifier,
currMatchSymbol.getSourceFile(),
);
importName = generatedImportName;
fileImportChanges.push(...importChanges);
} else {
if (potentialImport.isForwardReference) {
// Note that we pass the `importOn` file twice since we know that the potential import
// is within the same file, because it doesn't have a `moduleSpecifier`.
const [forwardRefImports, generatedForwardRefName] = updateImportsForTypescriptFile(
compiler.getCurrentProgram().getTypeChecker(),
importOn.getSourceFile(),
'forwardRef',
declarationName,
'@angular/core',
importOn.getSourceFile(),
);
fileImportChanges.push(...forwardRefImports);
forwardRefName = generatedForwardRefName;
}
importName = potentialImport.symbolName;
}
// Always update the trait import, although the TS import might already be present.
const traitImportChanges = updateImportsForAngularTrait(
compiler.getTemplateTypeChecker(),
importOn,
importName,
forwardRefName,
);
if (traitImportChanges.length === 0) continue;
let description = `Import ${importName}`;
if (potentialImport.moduleSpecifier !== undefined) {
description += ` from '${potentialImport.moduleSpecifier}' on ${importOn.name!.text}`;
}
codeActions.push({
description,
changes: [
{
fileName: importOn.getSourceFile().fileName,
textChanges: [...fileImportChanges, ...traitImportChanges],
},
],
});
}
return codeActions;
} | {
"end_byte": 25654,
"start_byte": 23032,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/utils/ts_utils.ts"
} |
angular/packages/language-service/src/utils/display_parts.ts_0_6841 | /**
* @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 {isNamedClassDeclaration} from '@angular/compiler-cli/src/ngtsc/reflection';
import {
LetDeclarationSymbol,
PotentialDirective,
ReferenceSymbol,
Symbol,
SymbolKind,
TcbLocation,
VariableSymbol,
} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
// Reverse mappings of enum would generate strings
export const ALIAS_NAME = ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.aliasName];
export const SYMBOL_INTERFACE = ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.interfaceName];
export const SYMBOL_PUNC = ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.punctuation];
export const SYMBOL_SPACE = ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.space];
export const SYMBOL_TEXT = ts.SymbolDisplayPartKind[ts.SymbolDisplayPartKind.text];
/**
* Label for various kinds of Angular entities for TS display info.
*/
export enum DisplayInfoKind {
ATTRIBUTE = 'attribute',
BLOCK = 'block',
TRIGGER = 'trigger',
COMPONENT = 'component',
DIRECTIVE = 'directive',
EVENT = 'event',
REFERENCE = 'reference',
ELEMENT = 'element',
VARIABLE = 'variable',
PIPE = 'pipe',
PROPERTY = 'property',
METHOD = 'method',
TEMPLATE = 'template',
KEYWORD = 'keyword',
LET = 'let',
}
export interface DisplayInfo {
kind: DisplayInfoKind;
displayParts: ts.SymbolDisplayPart[];
documentation: ts.SymbolDisplayPart[] | undefined;
tags: ts.JSDocTagInfo[] | undefined;
}
export function getSymbolDisplayInfo(
tsLS: ts.LanguageService,
typeChecker: ts.TypeChecker,
symbol: ReferenceSymbol | VariableSymbol | LetDeclarationSymbol,
): DisplayInfo {
let kind: DisplayInfoKind;
if (symbol.kind === SymbolKind.Reference) {
kind = DisplayInfoKind.REFERENCE;
} else if (symbol.kind === SymbolKind.Variable) {
kind = DisplayInfoKind.VARIABLE;
} else if (symbol.kind === SymbolKind.LetDeclaration) {
kind = DisplayInfoKind.LET;
} else {
throw new Error(
`AssertionError: unexpected symbol kind ${SymbolKind[(symbol as Symbol).kind]}`,
);
}
const displayParts = createDisplayParts(
symbol.declaration.name,
kind,
/* containerName */ undefined,
typeChecker.typeToString(symbol.tsType),
);
const quickInfo =
symbol.kind === SymbolKind.Reference
? getQuickInfoFromTypeDefAtLocation(tsLS, symbol.targetLocation)
: getQuickInfoFromTypeDefAtLocation(tsLS, symbol.initializerLocation);
return {
kind,
displayParts,
documentation: quickInfo?.documentation,
tags: quickInfo?.tags,
};
}
/**
* Construct a compound `ts.SymbolDisplayPart[]` which incorporates the container and type of a
* target declaration.
* @param name Name of the target
* @param kind component, directive, pipe, etc.
* @param containerName either the Symbol's container or the NgModule that contains the directive
* @param type user-friendly name of the type
* @param documentation docstring or comment
*/
export function createDisplayParts(
name: string,
kind: DisplayInfoKind,
containerName: string | undefined,
type: string | undefined,
): ts.SymbolDisplayPart[] {
const containerDisplayParts =
containerName !== undefined
? [
{text: containerName, kind: SYMBOL_INTERFACE},
{text: '.', kind: SYMBOL_PUNC},
]
: [];
const typeDisplayParts =
type !== undefined
? [
{text: ':', kind: SYMBOL_PUNC},
{text: ' ', kind: SYMBOL_SPACE},
{text: type, kind: SYMBOL_INTERFACE},
]
: [];
return [
{text: '(', kind: SYMBOL_PUNC},
{text: kind, kind: SYMBOL_TEXT},
{text: ')', kind: SYMBOL_PUNC},
{text: ' ', kind: SYMBOL_SPACE},
...containerDisplayParts,
{text: name, kind: SYMBOL_INTERFACE},
...typeDisplayParts,
];
}
/**
* Convert a `SymbolDisplayInfoKind` to a `ts.ScriptElementKind` type, allowing it to pass through
* TypeScript APIs.
*
* In practice, this is an "illegal" type cast. Since `ts.ScriptElementKind` is a string, this is
* safe to do if TypeScript only uses the value in a string context. Consumers of this conversion
* function are responsible for ensuring this is the case.
*/
export function unsafeCastDisplayInfoKindToScriptElementKind(
kind: DisplayInfoKind,
): ts.ScriptElementKind {
return kind as string as ts.ScriptElementKind;
}
function getQuickInfoFromTypeDefAtLocation(
tsLS: ts.LanguageService,
tcbLocation: TcbLocation,
): ts.QuickInfo | undefined {
const typeDefs = tsLS.getTypeDefinitionAtPosition(
tcbLocation.tcbPath,
tcbLocation.positionInFile,
);
if (typeDefs === undefined || typeDefs.length === 0) {
return undefined;
}
return tsLS.getQuickInfoAtPosition(typeDefs[0].fileName, typeDefs[0].textSpan.start);
}
export function getDirectiveDisplayInfo(
tsLS: ts.LanguageService,
dir: PotentialDirective,
): DisplayInfo {
const kind = dir.isComponent ? DisplayInfoKind.COMPONENT : DisplayInfoKind.DIRECTIVE;
const decl = dir.tsSymbol.declarations.find(ts.isClassDeclaration);
if (decl === undefined || decl.name === undefined) {
return {
kind,
displayParts: [],
documentation: [],
tags: undefined,
};
}
const res = tsLS.getQuickInfoAtPosition(decl.getSourceFile().fileName, decl.name.getStart());
if (res === undefined) {
return {
kind,
displayParts: [],
documentation: [],
tags: undefined,
};
}
const displayParts = createDisplayParts(
dir.tsSymbol.name,
kind,
dir.ngModule?.name?.text,
undefined,
);
return {
kind,
displayParts,
documentation: res.documentation,
tags: res.tags,
};
}
export function getTsSymbolDisplayInfo(
tsLS: ts.LanguageService,
checker: ts.TypeChecker,
symbol: ts.Symbol,
kind: DisplayInfoKind,
ownerName: string | null,
): DisplayInfo | null {
const decl = symbol.valueDeclaration;
if (
decl === undefined ||
(!ts.isPropertyDeclaration(decl) &&
!ts.isMethodDeclaration(decl) &&
!isNamedClassDeclaration(decl)) ||
!ts.isIdentifier(decl.name)
) {
return null;
}
const res = tsLS.getQuickInfoAtPosition(decl.getSourceFile().fileName, decl.name.getStart());
if (res === undefined) {
return {
kind,
displayParts: [],
documentation: [],
tags: undefined,
};
}
const type = checker.getDeclaredTypeOfSymbol(symbol);
const typeString = checker.typeToString(type);
const displayParts = createDisplayParts(symbol.name, kind, ownerName ?? undefined, typeString);
return {
kind,
displayParts,
documentation: res.documentation,
tags: res.tags,
};
}
| {
"end_byte": 6841,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/utils/display_parts.ts"
} |
angular/packages/language-service/src/utils/format.ts_0_1402 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
/**
* Try to guess the indentation of the node.
*
* This function returns the indentation only if the start character of this node is
* the first non-whitespace character in a line where the node is, otherwise,
* it returns `undefined`. When computing the start of the node, it should include
* the leading comments.
*/
export function guessIndentationInSingleLine(
node: ts.Node,
sourceFile: ts.SourceFile,
): number | undefined {
const leadingComment = ts.getLeadingCommentRanges(sourceFile.text, node.pos);
const firstLeadingComment =
leadingComment !== undefined && leadingComment.length > 0 ? leadingComment[0] : undefined;
const nodeStartWithComment = firstLeadingComment?.pos ?? node.getStart();
const lineNumber = sourceFile.getLineAndCharacterOfPosition(nodeStartWithComment).line;
const lineStart = sourceFile.getLineStarts()[lineNumber];
let haveChar = false;
for (let pos = lineStart; pos < nodeStartWithComment; pos++) {
const ch = sourceFile.text.charCodeAt(pos);
if (!ts.isWhiteSpaceSingleLine(ch)) {
haveChar = true;
break;
}
}
return haveChar ? undefined : nodeStartWithComment - lineStart;
}
| {
"end_byte": 1402,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/utils/format.ts"
} |
angular/packages/language-service/src/utils/BUILD.bazel_0_596 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//packages/language-service:__subpackages__"])
ts_library(
name = "utils",
srcs = glob(["*.ts"]),
deps = [
"//packages/compiler",
"//packages/compiler-cli/src/ngtsc/annotations",
"//packages/compiler-cli/src/ngtsc/core",
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/metadata",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/typecheck/api",
"@npm//typescript",
],
)
| {
"end_byte": 596,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/utils/BUILD.bazel"
} |
angular/packages/language-service/src/utils/index.ts_0_7854 | /**
* @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 {
AbsoluteSourceSpan,
AST,
ASTWithSource,
BindingPipe,
CssSelector,
ImplicitReceiver,
LiteralPrimitive,
ParseSourceSpan,
ParseSpan,
PropertyRead,
PropertyWrite,
SelectorMatcher,
ThisReceiver,
TmplAstBoundAttribute,
TmplAstBoundEvent,
TmplAstElement,
TmplAstNode,
TmplAstTemplate,
TmplAstTextAttribute,
} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {
absoluteFrom,
absoluteFromSourceFile,
AbsoluteFsPath,
} from '@angular/compiler-cli/src/ngtsc/file_system';
import {isExternalResource} from '@angular/compiler-cli/src/ngtsc/metadata';
import {DeclarationNode} from '@angular/compiler-cli/src/ngtsc/reflection';
import {DirectiveSymbol, TemplateTypeChecker} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
import {
ALIAS_NAME,
createDisplayParts,
DisplayInfoKind,
SYMBOL_PUNC,
unsafeCastDisplayInfoKindToScriptElementKind,
} from './display_parts';
import {findTightestNode, getParentClassDeclaration} from './ts_utils';
export function getTextSpanOfNode(node: TmplAstNode | AST): ts.TextSpan {
if (isTemplateNodeWithKeyAndValue(node)) {
return toTextSpan(node.keySpan);
} else if (
node instanceof PropertyWrite ||
node instanceof BindingPipe ||
node instanceof PropertyRead
) {
// The `name` part of a `PropertyWrite` and `BindingPipe` does not have its own AST
// so there is no way to retrieve a `Symbol` for just the `name` via a specific node.
return toTextSpan(node.nameSpan);
} else {
return toTextSpan(node.sourceSpan);
}
}
export function toTextSpan(span: AbsoluteSourceSpan | ParseSourceSpan | ParseSpan): ts.TextSpan {
let start: number, end: number;
if (span instanceof AbsoluteSourceSpan || span instanceof ParseSpan) {
start = span.start;
end = span.end;
} else {
start = span.start.offset;
end = span.end.offset;
}
return {start, length: end - start};
}
interface NodeWithKeyAndValue extends TmplAstNode {
keySpan: ParseSourceSpan;
valueSpan?: ParseSourceSpan;
}
export function isTemplateNodeWithKeyAndValue(
node: TmplAstNode | AST,
): node is NodeWithKeyAndValue {
return isTemplateNode(node) && node.hasOwnProperty('keySpan');
}
export function isWithinKey(position: number, node: NodeWithKeyAndValue): boolean {
let {keySpan, valueSpan} = node;
if (valueSpan === undefined && node instanceof TmplAstBoundEvent) {
valueSpan = node.handlerSpan;
}
const isWithinKeyValue =
isWithin(position, keySpan) || !!(valueSpan && isWithin(position, valueSpan));
return isWithinKeyValue;
}
export function isWithinKeyValue(position: number, node: NodeWithKeyAndValue): boolean {
let {keySpan, valueSpan} = node;
if (valueSpan === undefined && node instanceof TmplAstBoundEvent) {
valueSpan = node.handlerSpan;
}
const isWithinKeyValue =
isWithin(position, keySpan) || !!(valueSpan && isWithin(position, valueSpan));
return isWithinKeyValue;
}
export function isTemplateNode(node: TmplAstNode | AST): node is TmplAstNode {
// Template node implements the Node interface so we cannot use instanceof.
return node.sourceSpan instanceof ParseSourceSpan;
}
export function isExpressionNode(node: TmplAstNode | AST): node is AST {
return node instanceof AST;
}
export interface TemplateInfo {
template: TmplAstNode[];
component: ts.ClassDeclaration;
}
function getInlineTemplateInfoAtPosition(
sf: ts.SourceFile,
position: number,
compiler: NgCompiler,
): TemplateInfo | undefined {
const expression = findTightestNode(sf, position);
if (expression === undefined) {
return undefined;
}
const classDecl = getParentClassDeclaration(expression);
if (classDecl === undefined) {
return undefined;
}
// Return `undefined` if the position is not on the template expression or the template resource
// is not inline.
const resources = compiler.getComponentResources(classDecl);
if (
resources === null ||
isExternalResource(resources.template) ||
expression !== resources.template.expression
) {
return undefined;
}
const template = compiler.getTemplateTypeChecker().getTemplate(classDecl);
if (template === null) {
return undefined;
}
return {template, component: classDecl};
}
/**
* Retrieves the `ts.ClassDeclaration` at a location along with its template nodes.
*/
export function getTemplateInfoAtPosition(
fileName: string,
position: number,
compiler: NgCompiler,
): TemplateInfo | undefined {
if (isTypeScriptFile(fileName)) {
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return undefined;
}
return getInlineTemplateInfoAtPosition(sf, position, compiler);
} else {
return getFirstComponentForTemplateFile(fileName, compiler);
}
}
/**
* First, attempt to sort component declarations by file name.
* If the files are the same, sort by start location of the declaration.
*/
function tsDeclarationSortComparator(a: DeclarationNode, b: DeclarationNode): number {
const aFile = a.getSourceFile().fileName;
const bFile = b.getSourceFile().fileName;
if (aFile < bFile) {
return -1;
} else if (aFile > bFile) {
return 1;
} else {
return b.getFullStart() - a.getFullStart();
}
}
export function getFirstComponentForTemplateFile(
fileName: string,
compiler: NgCompiler,
): TemplateInfo | undefined {
const templateTypeChecker = compiler.getTemplateTypeChecker();
const components = compiler.getComponentsWithTemplateFile(fileName);
const sortedComponents = Array.from(components).sort(tsDeclarationSortComparator);
for (const component of sortedComponents) {
if (!ts.isClassDeclaration(component)) {
continue;
}
const template = templateTypeChecker.getTemplate(component);
if (template === null) {
continue;
}
return {template, component};
}
return undefined;
}
/**
* Given an attribute node, converts it to string form for use as a CSS selector.
*/
function toAttributeCssSelector(
attribute: TmplAstTextAttribute | TmplAstBoundAttribute | TmplAstBoundEvent,
): string {
let selector: string;
if (attribute instanceof TmplAstBoundEvent || attribute instanceof TmplAstBoundAttribute) {
selector = `[${attribute.name}]`;
} else {
selector = `[${attribute.name}=${attribute.valueSpan?.toString() ?? ''}]`;
}
// Any dollar signs that appear in the attribute name and/or value need to be escaped because they
// need to be taken as literal characters rather than special selector behavior of dollar signs in
// CSS.
return selector.replace(/\$/g, '\\$');
}
function getNodeName(node: TmplAstTemplate | TmplAstElement): string {
return node instanceof TmplAstTemplate ? (node.tagName ?? 'ng-template') : node.name;
}
/**
* Given a template or element node, returns all attributes on the node.
*/
function getAttributes(
node: TmplAstTemplate | TmplAstElement,
): Array<TmplAstTextAttribute | TmplAstBoundAttribute | TmplAstBoundEvent> {
const attributes: Array<TmplAstTextAttribute | TmplAstBoundAttribute | TmplAstBoundEvent> = [
...node.attributes,
...node.inputs,
...node.outputs,
];
if (node instanceof TmplAstTemplate) {
attributes.push(...node.templateAttrs);
}
return attributes;
}
/**
* Given two `Set`s, returns all items in the `left` which do not appear in the `right`.
*/
function difference<T>(left: Set<T>, right: Set<T>): Set<T> {
const result = new Set<T>();
for (const dir of left) {
if (!right.has(dir)) {
result.add(dir);
}
}
return result;
} | {
"end_byte": 7854,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/utils/index.ts"
} |
angular/packages/language-service/src/utils/index.ts_7856_16421 | /**
* Given an element or template, determines which directives match because the tag is present. For
* example, if a directive selector is `div[myAttr]`, this would match div elements but would not if
* the selector were just `[myAttr]`. We find which directives are applied because of this tag by
* elimination: compare the directive matches with the tag present against the directive matches
* without it. The difference would be the directives which match because the tag is present.
*
* @param element The element or template node that the attribute/tag is part of.
* @param directives The list of directives to match against.
* @returns The list of directives matching the tag name via the strategy described above.
*/
// TODO(atscott): Add unit tests for this and the one for attributes
export function getDirectiveMatchesForElementTag<T extends {selector: string | null}>(
element: TmplAstTemplate | TmplAstElement,
directives: T[],
): Set<T> {
const attributes = getAttributes(element);
const allAttrs = attributes.map(toAttributeCssSelector);
const allDirectiveMatches = getDirectiveMatchesForSelector(
directives,
getNodeName(element) + allAttrs.join(''),
);
const matchesWithoutElement = getDirectiveMatchesForSelector(directives, allAttrs.join(''));
return difference(allDirectiveMatches, matchesWithoutElement);
}
export function makeElementSelector(element: TmplAstElement | TmplAstTemplate): string {
const attributes = getAttributes(element);
const allAttrs = attributes.map(toAttributeCssSelector);
return getNodeName(element) + allAttrs.join('');
}
/**
* Given an attribute name, determines which directives match because the attribute is present. We
* find which directives are applied because of this attribute by elimination: compare the directive
* matches with the attribute present against the directive matches without it. The difference would
* be the directives which match because the attribute is present.
*
* @param name The name of the attribute
* @param hostNode The node which the attribute appears on
* @param directives The list of directives to match against.
* @returns The list of directives matching the tag name via the strategy described above.
*/
export function getDirectiveMatchesForAttribute(
name: string,
hostNode: TmplAstTemplate | TmplAstElement,
directives: DirectiveSymbol[],
): Set<DirectiveSymbol> {
const attributes = getAttributes(hostNode);
const allAttrs = attributes.map(toAttributeCssSelector);
const allDirectiveMatches = getDirectiveMatchesForSelector(
directives,
getNodeName(hostNode) + allAttrs.join(''),
);
const attrsExcludingName = attributes.filter((a) => a.name !== name).map(toAttributeCssSelector);
const matchesWithoutAttr = getDirectiveMatchesForSelector(
directives,
getNodeName(hostNode) + attrsExcludingName.join(''),
);
return difference(allDirectiveMatches, matchesWithoutAttr);
}
/**
* Given a list of directives and a text to use as a selector, returns the directives which match
* for the selector.
*/
function getDirectiveMatchesForSelector<T extends {selector: string | null}>(
directives: T[],
selector: string,
): Set<T> {
try {
const selectors = CssSelector.parse(selector);
if (selectors.length === 0) {
return new Set();
}
return new Set(
directives.filter((dir: T) => {
if (dir.selector === null) {
return false;
}
const matcher = new SelectorMatcher();
matcher.addSelectables(CssSelector.parse(dir.selector));
return selectors.some((selector) => matcher.match(selector, null));
}),
);
} catch {
// An invalid selector may throw an error. There would be no directive matches for an invalid
// selector.
return new Set();
}
}
/**
* Returns a new `ts.SymbolDisplayPart` array which has the alias imports from the tcb filtered
* out, i.e. `i0.NgForOf`.
*/
export function filterAliasImports(displayParts: ts.SymbolDisplayPart[]): ts.SymbolDisplayPart[] {
const tcbAliasImportRegex = /i\d+/;
function isImportAlias(part: {kind: string; text: string}) {
return part.kind === ALIAS_NAME && tcbAliasImportRegex.test(part.text);
}
function isDotPunctuation(part: {kind: string; text: string}) {
return part.kind === SYMBOL_PUNC && part.text === '.';
}
return displayParts.filter((part, i) => {
const previousPart = displayParts[i - 1];
const nextPart = displayParts[i + 1];
const aliasNameFollowedByDot =
isImportAlias(part) && nextPart !== undefined && isDotPunctuation(nextPart);
const dotPrecededByAlias =
isDotPunctuation(part) && previousPart !== undefined && isImportAlias(previousPart);
return !aliasNameFollowedByDot && !dotPrecededByAlias;
});
}
export function isDollarEvent(n: TmplAstNode | AST): n is PropertyRead {
return (
n instanceof PropertyRead &&
n.name === '$event' &&
n.receiver instanceof ImplicitReceiver &&
!(n.receiver instanceof ThisReceiver)
);
}
export function isTypeScriptFile(fileName: string): boolean {
return /\.[cm]?tsx?$/i.test(fileName);
}
export function isExternalTemplate(fileName: string): boolean {
return !isTypeScriptFile(fileName);
}
export function isWithin(position: number, span: AbsoluteSourceSpan | ParseSourceSpan): boolean {
let start: number, end: number;
if (span instanceof ParseSourceSpan) {
start = span.start.offset;
end = span.end.offset;
} else {
start = span.start;
end = span.end;
}
// Note both start and end are inclusive because we want to match conditions
// like ¦start and end¦ where ¦ is the cursor.
return start <= position && position <= end;
}
/**
* For a given location in a shim file, retrieves the corresponding file url for the template and
* the span in the template.
*/
export function getTemplateLocationFromTcbLocation(
templateTypeChecker: TemplateTypeChecker,
tcbPath: AbsoluteFsPath,
tcbIsShim: boolean,
positionInFile: number,
): {templateUrl: AbsoluteFsPath; span: ParseSourceSpan} | null {
const mapping = templateTypeChecker.getTemplateMappingAtTcbLocation({
tcbPath,
isShimFile: tcbIsShim,
positionInFile,
});
if (mapping === null) {
return null;
}
const {templateSourceMapping, span} = mapping;
let templateUrl: AbsoluteFsPath;
if (templateSourceMapping.type === 'direct') {
templateUrl = absoluteFromSourceFile(templateSourceMapping.node.getSourceFile());
} else if (templateSourceMapping.type === 'external') {
templateUrl = absoluteFrom(templateSourceMapping.templateUrl);
} else {
// This includes indirect mappings, which are difficult to map directly to the code
// location. Diagnostics similarly return a synthetic template string for this case rather
// than a real location.
return null;
}
return {templateUrl, span};
}
export function isBoundEventWithSyntheticHandler(event: TmplAstBoundEvent): boolean {
// An event binding with no value (e.g. `(event|)`) parses to a `BoundEvent` with a
// `LiteralPrimitive` handler with value `'ERROR'`, as opposed to a property binding with no
// value which has an `EmptyExpr` as its value. This is a synthetic node created by the binding
// parser, and is not suitable to use for Language Service analysis. Skip it.
//
// TODO(alxhub): modify the parser to generate an `EmptyExpr` instead.
let handler: AST = event.handler;
if (handler instanceof ASTWithSource) {
handler = handler.ast;
}
if (handler instanceof LiteralPrimitive && handler.value === 'ERROR') {
return true;
}
return false;
}
/**
* Construct a QuickInfo object taking into account its container and type.
* @param name Name of the QuickInfo target
* @param kind component, directive, pipe, etc.
* @param textSpan span of the target
* @param containerName either the Symbol's container or the NgModule that contains the directive
* @param type user-friendly name of the type
* @param documentation docstring or comment
*/
export function createQuickInfo(
name: string,
kind: DisplayInfoKind,
textSpan: ts.TextSpan,
containerName?: string,
type?: string,
documentation?: ts.SymbolDisplayPart[],
tags?: ts.JSDocTagInfo[],
): ts.QuickInfo {
const displayParts = createDisplayParts(name, kind, containerName, type);
return {
kind: unsafeCastDisplayInfoKindToScriptElementKind(kind),
kindModifiers: ts.ScriptElementKindModifier.none,
textSpan: textSpan,
displayParts,
documentation,
tags,
};
}
| {
"end_byte": 16421,
"start_byte": 7856,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/utils/index.ts"
} |
angular/packages/language-service/src/codefixes/fix_missing_member.ts_0_3518 | /**
* @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 tss from 'typescript';
import {
getTargetAtPosition,
getTcbNodesOfTemplateAtPosition,
TargetNodeKind,
} from '../template_target';
import {getTemplateInfoAtPosition} from '../utils';
import {CodeActionMeta, convertFileTextChangeInTcb, FixIdForCodeFixesAll} from './utils';
const errorCodes: number[] = [
2551, // https://github.com/microsoft/TypeScript/blob/8e6e87fea6463e153822e88431720f846c3b8dfa/src/compiler/diagnosticMessages.json#L2493
2339, // https://github.com/microsoft/TypeScript/blob/8e6e87fea6463e153822e88431720f846c3b8dfa/src/compiler/diagnosticMessages.json#L1717
];
/**
* This code action will fix the missing member of a type. For example, add the missing member to
* the type or try to get the spelling suggestion for the name from the type.
*/
export const missingMemberMeta: CodeActionMeta = {
errorCodes,
getCodeActions: function ({
templateInfo,
start,
compiler,
formatOptions,
preferences,
errorCode,
tsLs,
}) {
const tcbNodesInfo = getTcbNodesOfTemplateAtPosition(templateInfo, start, compiler);
if (tcbNodesInfo === null) {
return [];
}
const codeActions: tss.CodeFixAction[] = [];
const tcb = tcbNodesInfo.componentTcbNode;
for (const tcbNode of tcbNodesInfo.nodes) {
const tsLsCodeActions = tsLs.getCodeFixesAtPosition(
tcb.getSourceFile().fileName,
tcbNode.getStart(),
tcbNode.getEnd(),
[errorCode],
formatOptions,
preferences,
);
codeActions.push(...tsLsCodeActions);
}
return codeActions.map((codeAction) => {
return {
fixName: codeAction.fixName,
fixId: codeAction.fixId,
fixAllDescription: codeAction.fixAllDescription,
description: codeAction.description,
changes: convertFileTextChangeInTcb(codeAction.changes, compiler),
commands: codeAction.commands,
};
});
},
fixIds: [FixIdForCodeFixesAll.FIX_SPELLING, FixIdForCodeFixesAll.FIX_MISSING_MEMBER],
getAllCodeActions: function ({
tsLs,
scope,
fixId,
formatOptions,
preferences,
compiler,
diagnostics,
}) {
const changes: tss.FileTextChanges[] = [];
const seen: Set<tss.ClassDeclaration> = new Set();
for (const diag of diagnostics) {
if (!errorCodes.includes(diag.code)) {
continue;
}
const fileName = diag.file?.fileName;
if (fileName === undefined) {
continue;
}
if (diag.start === undefined) {
continue;
}
const componentClass = getTemplateInfoAtPosition(fileName, diag.start, compiler)?.component;
if (componentClass === undefined) {
continue;
}
if (seen.has(componentClass)) {
continue;
}
seen.add(componentClass);
const tcb = compiler.getTemplateTypeChecker().getTypeCheckBlock(componentClass);
if (tcb === null) {
continue;
}
const combinedCodeActions = tsLs.getCombinedCodeFix(
{
type: scope.type,
fileName: tcb.getSourceFile().fileName,
},
fixId,
formatOptions,
preferences,
);
changes.push(...combinedCodeActions.changes);
}
return {
changes: convertFileTextChangeInTcb(changes, compiler),
};
},
};
| {
"end_byte": 3518,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/codefixes/fix_missing_member.ts"
} |
angular/packages/language-service/src/codefixes/utils.ts_0_4622 | /**
* @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 {absoluteFrom} from '@angular/compiler-cli';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import tss from 'typescript';
import {TemplateInfo} from '../utils';
/**
* This context is the info includes the `errorCode` at the given span the user selected in the
* editor and the `NgCompiler` could help to fix it.
*
* When the editor tries to provide a code fix for a diagnostic in a span of a template file, this
* context will be provided to the `CodeActionMeta` which could handle the `errorCode`.
*/
export interface CodeActionContext {
templateInfo: TemplateInfo;
fileName: string;
compiler: NgCompiler;
start: number;
end: number;
errorCode: number;
formatOptions: tss.FormatCodeSettings;
preferences: tss.UserPreferences;
tsLs: tss.LanguageService;
}
/**
* This context is the info includes all diagnostics in the `scope` and the `NgCompiler` that could
* help to fix it.
*
* When the editor tries to fix the all same type of diagnostics selected by the user in the
* `scope`, this context will be provided to the `CodeActionMeta` which could handle the `fixId`.
*/
export interface CodeFixAllContext {
scope: tss.CombinedCodeFixScope;
compiler: NgCompiler;
// https://github.com/microsoft/TypeScript/blob/5c4caafc2a2d0fceb03fce80fb14d3ee4407d918/src/services/types.ts#L781-L785
fixId: string;
formatOptions: tss.FormatCodeSettings;
preferences: tss.UserPreferences;
tsLs: tss.LanguageService;
diagnostics: tss.Diagnostic[];
}
export interface CodeActionMeta {
errorCodes: Array<number>;
getCodeActions: (context: CodeActionContext) => readonly tss.CodeFixAction[];
fixIds: FixIdForCodeFixesAll[];
getAllCodeActions: (context: CodeFixAllContext) => tss.CombinedCodeActions;
}
/**
* Convert the span of `textChange` in the TCB to the span of the template.
*/
export function convertFileTextChangeInTcb(
changes: readonly tss.FileTextChanges[],
compiler: NgCompiler,
): tss.FileTextChanges[] {
const ttc = compiler.getTemplateTypeChecker();
const fileTextChanges: tss.FileTextChanges[] = [];
for (const fileTextChange of changes) {
if (!ttc.isTrackedTypeCheckFile(absoluteFrom(fileTextChange.fileName))) {
fileTextChanges.push(fileTextChange);
continue;
}
const textChanges: tss.TextChange[] = [];
let fileName: string | undefined;
const seenTextChangeInTemplate = new Set<string>();
for (const textChange of fileTextChange.textChanges) {
const templateMap = ttc.getTemplateMappingAtTcbLocation({
tcbPath: absoluteFrom(fileTextChange.fileName),
isShimFile: true,
positionInFile: textChange.span.start,
});
if (templateMap === null) {
continue;
}
const mapping = templateMap.templateSourceMapping;
if (mapping.type === 'external') {
fileName = mapping.templateUrl;
} else if (mapping.type === 'direct') {
fileName = mapping.node.getSourceFile().fileName;
} else {
continue;
}
const start = templateMap.span.start.offset;
const length = templateMap.span.end.offset - templateMap.span.start.offset;
const changeSpanKey = `${start},${length}`;
if (seenTextChangeInTemplate.has(changeSpanKey)) {
continue;
}
seenTextChangeInTemplate.add(changeSpanKey);
textChanges.push({
newText: textChange.newText,
span: {
start,
length,
},
});
}
if (fileName === undefined) {
continue;
}
fileTextChanges.push({
fileName,
isNewFile: fileTextChange.isNewFile,
textChanges,
});
}
return fileTextChanges;
}
/**
* 'fix all' is only available when there are multiple diagnostics that the code action meta
* indicates it can fix.
*/
export function isFixAllAvailable(meta: CodeActionMeta, diagnostics: tss.Diagnostic[]) {
const errorCodes = meta.errorCodes;
let maybeFixableDiagnostics = 0;
for (const diag of diagnostics) {
if (errorCodes.includes(diag.code)) maybeFixableDiagnostics++;
if (maybeFixableDiagnostics > 1) return true;
}
return false;
}
export enum FixIdForCodeFixesAll {
FIX_SPELLING = 'fixSpelling',
FIX_MISSING_MEMBER = 'fixMissingMember',
FIX_INVALID_BANANA_IN_BOX = 'fixInvalidBananaInBox',
FIX_MISSING_IMPORT = 'fixMissingImport',
FIX_UNUSED_STANDALONE_IMPORTS = 'fixUnusedStandaloneImports',
}
| {
"end_byte": 4622,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/codefixes/utils.ts"
} |
angular/packages/language-service/src/codefixes/fix_missing_import.ts_0_3198 | /**
* @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 {ASTWithName, TmplAstElement} from '@angular/compiler';
import {
ErrorCode as NgCompilerErrorCode,
ngErrorCode,
} from '@angular/compiler-cli/src/ngtsc/diagnostics/index';
import {
PotentialDirective,
PotentialImportMode,
PotentialPipe,
} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import ts from 'typescript';
import {getTargetAtPosition, TargetNodeKind} from '../template_target';
import {
getCodeActionToImportTheDirectiveDeclaration,
standaloneTraitOrNgModule,
} from '../utils/ts_utils';
import {getDirectiveMatchesForElementTag} from '../utils';
import {CodeActionContext, CodeActionMeta, FixIdForCodeFixesAll} from './utils';
const errorCodes: number[] = [
ngErrorCode(NgCompilerErrorCode.SCHEMA_INVALID_ELEMENT),
ngErrorCode(NgCompilerErrorCode.MISSING_PIPE),
];
/**
* This code action will generate a new import for an unknown selector.
*/
export const missingImportMeta: CodeActionMeta = {
errorCodes,
getCodeActions,
fixIds: [FixIdForCodeFixesAll.FIX_MISSING_IMPORT],
// TODO(dylhunn): implement "Fix All"
getAllCodeActions: ({tsLs, scope, fixId, formatOptions, preferences, compiler, diagnostics}) => {
return {
changes: [],
};
},
};
function getCodeActions({
templateInfo,
start,
compiler,
formatOptions,
preferences,
errorCode,
tsLs,
}: CodeActionContext) {
let codeActions: ts.CodeFixAction[] = [];
const checker = compiler.getTemplateTypeChecker();
const tsChecker = compiler.programDriver.getProgram().getTypeChecker();
const target = getTargetAtPosition(templateInfo.template, start);
if (target === null) {
return [];
}
let matches: Set<PotentialDirective> | Set<PotentialPipe>;
if (
target.context.kind === TargetNodeKind.ElementInTagContext &&
target.context.node instanceof TmplAstElement
) {
const allPossibleDirectives = checker.getPotentialTemplateDirectives(templateInfo.component);
matches = getDirectiveMatchesForElementTag(target.context.node, allPossibleDirectives);
} else if (
target.context.kind === TargetNodeKind.RawExpression &&
target.context.node instanceof ASTWithName
) {
const name = (target.context.node as any).name;
const allPossiblePipes = checker.getPotentialPipes(templateInfo.component);
matches = new Set(allPossiblePipes.filter((p) => p.name === name));
} else {
return [];
}
// Find all possible importable directives with a matching selector.
const importOn = standaloneTraitOrNgModule(checker, templateInfo.component);
if (importOn === null) {
return [];
}
for (const currMatch of matches.values()) {
const currentMatchCodeAction =
getCodeActionToImportTheDirectiveDeclaration(compiler, importOn, currMatch) ?? [];
codeActions.push(
...currentMatchCodeAction.map<ts.CodeFixAction>((action) => {
return {
fixName: FixIdForCodeFixesAll.FIX_MISSING_IMPORT,
...action,
};
}),
);
}
return codeActions;
}
| {
"end_byte": 3198,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/codefixes/fix_missing_import.ts"
} |
angular/packages/language-service/src/codefixes/fix_unused_standalone_imports.ts_0_2527 | /**
* @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 {ErrorCode, ngErrorCode} from '@angular/compiler-cli/src/ngtsc/diagnostics';
import tss from 'typescript';
import {CodeActionMeta, FixIdForCodeFixesAll} from './utils';
import {findFirstMatchingNode} from '../utils/ts_utils';
/**
* Fix for [unused standalone imports](https://angular.io/extended-diagnostics/NG8113)
*/
export const fixUnusedStandaloneImportsMeta: CodeActionMeta = {
errorCodes: [ngErrorCode(ErrorCode.UNUSED_STANDALONE_IMPORTS)],
getCodeActions: () => [],
fixIds: [FixIdForCodeFixesAll.FIX_UNUSED_STANDALONE_IMPORTS],
getAllCodeActions: ({diagnostics}) => {
const changes: tss.FileTextChanges[] = [];
for (const diag of diagnostics) {
const {start, length, file, relatedInformation} = diag;
if (file === undefined || start === undefined || length == undefined) {
continue;
}
const node = findFirstMatchingNode(file, {
filter: (current): current is tss.ArrayLiteralExpression =>
current.getStart() === start &&
current.getWidth() === length &&
tss.isArrayLiteralExpression(current),
});
if (node === null) {
continue;
}
let newText: string;
// If `relatedInformation` is empty, it means that all the imports are unused.
// Replace the array with an empty array.
if (relatedInformation === undefined || relatedInformation.length === 0) {
newText = '[]';
} else {
// Otherwise each `relatedInformation` entry points to an unused import that should be
// filtered out. We make a set of ranges corresponding to nodes which will be deleted and
// remove all nodes that belong to the set.
const excludeRanges = new Set(
relatedInformation.map((info) => `${info.start}-${info.length}`),
);
const newArray = tss.factory.updateArrayLiteralExpression(
node,
node.elements.filter((el) => !excludeRanges.has(`${el.getStart()}-${el.getWidth()}`)),
);
newText = tss.createPrinter().printNode(tss.EmitHint.Unspecified, newArray, file);
}
changes.push({
fileName: file.fileName,
textChanges: [
{
span: {start, length},
newText,
},
],
});
}
return {changes};
},
};
| {
"end_byte": 2527,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/codefixes/fix_unused_standalone_imports.ts"
} |
angular/packages/language-service/src/codefixes/index.ts_0_304 | /**
* @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 {ALL_CODE_FIXES_METAS} from './all_codefixes_metas';
export {CodeFixes} from './code_fixes';
| {
"end_byte": 304,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/codefixes/index.ts"
} |
angular/packages/language-service/src/codefixes/all_codefixes_metas.ts_0_672 | /**
* @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 {fixInvalidBananaInBoxMeta} from './fix_invalid_banana_in_box';
import {missingImportMeta} from './fix_missing_import';
import {missingMemberMeta} from './fix_missing_member';
import {fixUnusedStandaloneImportsMeta} from './fix_unused_standalone_imports';
import {CodeActionMeta} from './utils';
export const ALL_CODE_FIXES_METAS: CodeActionMeta[] = [
missingMemberMeta,
fixInvalidBananaInBoxMeta,
missingImportMeta,
fixUnusedStandaloneImportsMeta,
];
| {
"end_byte": 672,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/codefixes/all_codefixes_metas.ts"
} |
angular/packages/language-service/src/codefixes/fix_invalid_banana_in_box.ts_0_4546 | /**
* @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 {TmplAstBoundEvent} from '@angular/compiler';
import {ErrorCode, ngErrorCode} from '@angular/compiler-cli/src/ngtsc/diagnostics';
import tss from 'typescript';
import {getTargetAtPosition, TargetNodeKind} from '../template_target';
import {getTemplateInfoAtPosition, TemplateInfo} from '../utils';
import {CodeActionMeta, FixIdForCodeFixesAll} from './utils';
/**
* fix [invalid banana-in-box](https://angular.io/extended-diagnostics/NG8101)
*/
export const fixInvalidBananaInBoxMeta: CodeActionMeta = {
errorCodes: [ngErrorCode(ErrorCode.INVALID_BANANA_IN_BOX)],
getCodeActions({start, fileName, templateInfo}) {
const boundEvent = getTheBoundEventAtPosition(templateInfo, start);
if (boundEvent === null) {
return [];
}
const textChanges = convertBoundEventToTsTextChange(boundEvent);
return [
{
fixName: FixIdForCodeFixesAll.FIX_INVALID_BANANA_IN_BOX,
fixId: FixIdForCodeFixesAll.FIX_INVALID_BANANA_IN_BOX,
fixAllDescription: 'fix all invalid banana-in-box',
description: `fix invalid banana-in-box for '${boundEvent.sourceSpan.toString()}'`,
changes: [
{
fileName,
textChanges,
},
],
},
];
},
fixIds: [FixIdForCodeFixesAll.FIX_INVALID_BANANA_IN_BOX],
getAllCodeActions({diagnostics, compiler}) {
const fileNameToTextChangesMap = new Map<string, tss.TextChange[]>();
for (const diag of diagnostics) {
const fileName = diag.file?.fileName;
if (fileName === undefined) {
continue;
}
const start = diag.start;
if (start === undefined) {
continue;
}
const templateInfo = getTemplateInfoAtPosition(fileName, start, compiler);
if (templateInfo === undefined) {
continue;
}
/**
* This diagnostic has detected a likely mistake that puts the square brackets inside the
* parens (the BoundEvent `([thing])`) when it should be the other way around `[(thing)]` so
* this function is trying to find the bound event in order to flip the syntax.
*/
const boundEvent = getTheBoundEventAtPosition(templateInfo, start);
if (boundEvent === null) {
continue;
}
if (!fileNameToTextChangesMap.has(fileName)) {
fileNameToTextChangesMap.set(fileName, []);
}
const fileTextChanges = fileNameToTextChangesMap.get(fileName)!;
const textChanges = convertBoundEventToTsTextChange(boundEvent);
fileTextChanges.push(...textChanges);
}
const fileTextChanges: tss.FileTextChanges[] = [];
for (const [fileName, textChanges] of fileNameToTextChangesMap) {
fileTextChanges.push({
fileName,
textChanges,
});
}
return {
changes: fileTextChanges,
};
},
};
function getTheBoundEventAtPosition(
templateInfo: TemplateInfo,
start: number,
): TmplAstBoundEvent | null {
// It's safe to get the bound event at the position `start + 1` because the `start` is at the
// start of the diagnostic, and the node outside the attribute key and value spans are skipped by
// the function `getTargetAtPosition`.
// https://github.com/angular/vscode-ng-language-service/blob/8553115972ca40a55602747667c3d11d6f47a6f8/server/src/session.ts#L220
// https://github.com/angular/angular/blob/4e10a7494130b9bb4772ee8f76b66675867b2145/packages/language-service/src/template_target.ts#L347-L356
const positionDetail = getTargetAtPosition(templateInfo.template, start + 1);
if (positionDetail === null) {
return null;
}
if (
positionDetail.context.kind !== TargetNodeKind.AttributeInKeyContext ||
!(positionDetail.context.node instanceof TmplAstBoundEvent)
) {
return null;
}
return positionDetail.context.node;
}
/**
* Flip the invalid "box in a banana" `([thing])` to the correct "banana in a box" `[(thing)]`.
*/
function convertBoundEventToTsTextChange(node: TmplAstBoundEvent): readonly tss.TextChange[] {
const name = node.name;
const boundSyntax = node.sourceSpan.toString();
const expectedBoundSyntax = boundSyntax.replace(`(${name})`, `[(${name.slice(1, -1)})]`);
return [
{
span: {
start: node.sourceSpan.start.offset,
length: boundSyntax.length,
},
newText: expectedBoundSyntax,
},
];
}
| {
"end_byte": 4546,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/codefixes/fix_invalid_banana_in_box.ts"
} |
angular/packages/language-service/src/codefixes/code_fixes.ts_0_3861 | /**
* @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 {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import tss from 'typescript';
import {TemplateInfo} from '../utils';
import {CodeActionMeta, FixIdForCodeFixesAll, isFixAllAvailable} from './utils';
export class CodeFixes {
private errorCodeToFixes: Map<number, CodeActionMeta[]> = new Map();
private fixIdToRegistration = new Map<FixIdForCodeFixesAll, CodeActionMeta>();
constructor(
private readonly tsLS: tss.LanguageService,
readonly codeActionMetas: CodeActionMeta[],
) {
for (const meta of codeActionMetas) {
for (const err of meta.errorCodes) {
let errMeta = this.errorCodeToFixes.get(err);
if (errMeta === undefined) {
this.errorCodeToFixes.set(err, (errMeta = []));
}
errMeta.push(meta);
}
for (const fixId of meta.fixIds) {
if (this.fixIdToRegistration.has(fixId)) {
// https://github.com/microsoft/TypeScript/blob/28dc248e5c500c7be9a8c3a7341d303e026b023f/src/services/codeFixProvider.ts#L28
// In ts services, only one meta can be registered for a fixId.
continue;
}
this.fixIdToRegistration.set(fixId, meta);
}
}
}
/**
* When the user moves the cursor or hovers on a diagnostics, this function will be invoked by LS,
* and collect all the responses from the `codeActionMetas` which could handle the `errorCodes`.
*/
getCodeFixesAtPosition(
fileName: string,
templateInfo: TemplateInfo,
compiler: NgCompiler,
start: number,
end: number,
errorCodes: readonly number[],
diagnostics: tss.Diagnostic[],
formatOptions: tss.FormatCodeSettings,
preferences: tss.UserPreferences,
): readonly tss.CodeFixAction[] {
const codeActions: tss.CodeFixAction[] = [];
for (const code of errorCodes) {
const metas = this.errorCodeToFixes.get(code);
if (metas === undefined) {
continue;
}
for (const meta of metas) {
const codeActionsForMeta = meta.getCodeActions({
fileName,
templateInfo,
compiler,
start,
end,
errorCode: code,
formatOptions,
preferences,
tsLs: this.tsLS,
});
const fixAllAvailable = isFixAllAvailable(meta, diagnostics);
const removeFixIdForCodeActions = codeActionsForMeta.map(
({fixId, fixAllDescription, ...codeActionForMeta}) => {
return fixAllAvailable
? {...codeActionForMeta, fixId, fixAllDescription}
: codeActionForMeta;
},
);
codeActions.push(...removeFixIdForCodeActions);
}
}
return codeActions;
}
/**
* When the user wants to fix the all same type of diagnostics in the `scope`, this function will
* be called and fix all diagnostics which will be filtered by the `errorCodes` from the
* `CodeActionMeta` that the `fixId` belongs to.
*/
getAllCodeActions(
compiler: NgCompiler,
diagnostics: tss.Diagnostic[],
scope: tss.CombinedCodeFixScope,
fixId: string,
formatOptions: tss.FormatCodeSettings,
preferences: tss.UserPreferences,
): tss.CombinedCodeActions {
const meta = this.fixIdToRegistration.get(fixId as FixIdForCodeFixesAll);
if (meta === undefined) {
return {
changes: [],
};
}
return meta.getAllCodeActions({
compiler,
fixId,
formatOptions,
preferences,
tsLs: this.tsLS,
scope,
// only pass the diagnostics the `meta` cares about.
diagnostics: diagnostics.filter((diag) => meta.errorCodes.includes(diag.code)),
});
}
}
| {
"end_byte": 3861,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/language-service/src/codefixes/code_fixes.ts"
} |
angular/packages/docs/di/di_advanced.md_0_7885 | # Dependency Injection (DI): Documentation (Advanced Topics)
This document talks about advanced topics related to the DI module and how it is used in Angular. You don't have to know this to use DI in Angular or independently.
### Key
Most of the time we do not have to deal with keys.
```
var inj = Injector.resolveAndCreate([
bind(Engine).toFactory(() => new TurboEngine()) //the passed in token Engine gets mapped to a key
]);
var engine = inj.get(Engine); //the passed in token Engine gets mapped to a key
```
Now, the same example, but with keys.
```
var ENGINE_KEY = Key.get(Engine);
var inj = Injector.resolveAndCreate([
bind(ENGINE_KEY).toFactory(() => new TurboEngine()) // no mapping
]);
var engine = inj.get(ENGINE_KEY); // no mapping
```
Every key has an id, which we utilize to store providers and instances. So Injector uses keys internally for performance reasons.
### ProtoInjector and Injector
Often there is a need to create multiple instances of essentially the same injector. In Angular, for example, every component element type gets an injector configured in the same way.
Doing the following would be very inefficient.
```
function createComponentInjector(parent, providers: Binding[]) {
return parent.resolveAndCreateChild(providers);
}
```
This would require us to resolve and store providers for every single component instance. Instead, we want to resolve and store the providers for every component type, and create a set of instances for every component. To enable that DI separates the meta information about injectables (providers and their dependencies), which are stored in `ProtoInjector`, and injectables themselves, which are stored in `Injector`.
```
var proto = new ProtoInjector(providers); // done once
function createComponentInjector(parent, proto) {
return new Injector(proto, parent);
}
```
`Injector.resolveAndCreate` creates both a `ProtoInjector` and an `Injector`.
### Host & Visibility
An injector can have a parent. The parent relationship can be marked as a "host" as follows:
```
var child = new Injector(proto, parent, true /* host */);
```
Hosts are used to constraint dependency resolution. For instance, in the following example, DI will stop looking for `Engine` after reaching the host.
```
class Car {
constructor(@Host() e: Engine) {}
}
```
Imagine the following scenario:
```
ParentInjector
/ \
/ \ host
Child1 Child2
```
Here both Child1 and Child2 are children of ParentInjector. Child2 marks this relationship as host. ParentInjector might want to expose two different sets of providers for its "regular" children and its "host" children. providers visible to "regular" children are called "public" and providers visible to "host" children are called "private". This is an advanced use case used by Angular, where components can provide different sets of providers for their children and their view.
Let's look at this example.
```
class Car {
constructor(@Host() e: Engine) {}
}
var parentProto = new ProtoInjector([
new BindingWithVisibility(Engine, Visibility.Public),
new BindingWithVisibility(Car, Visibility.Public)
]);
var parent = new Injector(parentProto);
var hostChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
var hostChild = new Injector(hostChildProto, parent, true);
var regularChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
var regularChild = new Injector(regularChildProto, parent, false);
hostChild.get(Car); // will throw because public dependencies declared at the host cannot be seen by child injectors
parent.get(Car); // this works
regularChild.get(Car); // this works
```
Now, let's mark `Engine` as private:
```
class Car {
constructor(@Host() e: Engine) {}
}
var parentProto = new ProtoInjector([
new BindingWithVisibility(Engine, Visibility.Private),
new BindingWithVisibility(Car, Visibility.Public)
]);
var parent = new Injector(parentProto);
var hostChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
var hostChild = new Injector(hostChildProto, parent, true);
var regularChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
var regularChild = new Injector(regularChildProto, parent, false);
hostChild.get(Car); // this works
parent.get(Car); // this throws
regularChild.get(Car); // this throws
```
Now, let's mark `Engine` as both public and private:
```
class Car {
constructor(@Host() e: Engine) {}
}
var parentProto = new ProtoInjector([
new BindingWithVisibility(Engine, Visibility.PublicAndPrivate),
new BindingWithVisibility(Car, Visibility.Public)
]);
var parent = new Injector(parentProto);
var hostChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
var hostChild = new Injector(hostChildProto, parent, true);
var regularChildProto = new ProtoInjector([new BindingWithVisibility(Car, Visibility.Public)]);
var regularChild = new Injector(regularChildProto, parent, false);
hostChild.get(Car); // this works
parent.get(Car); // this works
regularChild.get(Car); // this works
```
## Angular and DI
Now let's see how Angular uses DI behind the scenes.
The right mental model is to think that every DOM element has an Injector. (In practice, only interesting elements containing directives will have an injector, but this is a performance optimization)
There are two properties that can be used to configure DI: providers and viewProviders.
- `providers` affects the element and its children.
- `viewProviders` affects the component's view.
Every directive can declare injectables via `providers`, but only components can declare `viewProviders`.
Let's look at a complex example that shows how the injector tree gets created.
```
<my-component my-directive>
<needs-service></needs-service>
</my-component>
```
Both `MyComponent` and `MyDirective` are created on the same element.
```
@Component({
selector: 'my-component',
providers: [
bind('componentService').toValue('Host_MyComponentService')
],
viewProviders: [
bind('viewService').toValue('View_MyComponentService')
],
template: `<needs-view-service></needs-view-service>`,
directives: [NeedsViewService]
})
class MyComponent {}
@Directive({
selector: '[my-directive]',
providers: [
bind('directiveService').toValue('MyDirectiveService')
]
})
class MyDirective {
}
```
`NeedsService` and `NeedsViewService` look like this:
```
@Directive({
selector: 'needs-view-service'
})
class NeedsViewService {
constructor(@Host() @Inject('viewService') viewService) {}
}
@Directive({
selector: 'needs-service'
})
class NeedsService {
constructor(@Host() @Inject('componentService') service1,
@Host() @Inject('directiveService') service2) {}
}
```
This will create the following injector tree.
```
Injector1 [
{binding: MyComponent, visibility: Visibility.PublicAndPrivate},
{binding: 'componentService', visibility: Visibility.PublicAndPrivate},
{binding: 'viewService', visibility: Visibility.Private},
{binding: MyDirective visibility: Visibility.Public},
{binding: 'directiveService', visibility: Visibility.Public}
]
/ \
| \ host
Injector2 [ Injector3 [
{binding: NeedsService, visibility: Visibility.Public} {binding: NeedsViewService, visibility: Visibility.Public}
] ]
```
As you can see the component and its providers can be seen by its children and its view. The view providers can be seen only by the view. And the providers of other directives can be seen only their children.
| {
"end_byte": 7885,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/docs/di/di_advanced.md"
} |
angular/packages/docs/di/di.md_0_7140 | # Dependency Injection (DI): Documentation
This document describes in detail how the DI module works in Angular.
## Core Abstractions
The library is built on top of the following core abstractions: `Injector`, `Binding`, and `Dependency`.
* An injector is created from a set of bindings.
* An injector resolves dependencies and creates objects.
* A binding maps a token, such as a string or class, to a factory function and a list of dependencies. So a binding defines how to create an object.
* A dependency points to a token and contains extra information on how the object corresponding to that token should be injected.
```
[Injector]
|
|
|*
[Binding]
|----------|-----------------|
| | |*
[Token] [FactoryFn] [Dependency]
|---------|
| |
[Token] [Flags]
```
## Example
```
class Engine {
}
class Car {
constructor(@Inject(Engine) engine) {
}
}
var inj = Injector.resolveAndCreate([
bind(Car).toClass(Car),
bind(Engine).toClass(Engine)
]);
var car = inj.get(Car);
```
In this example we create two bindings: one for `Car` and one for `Engine`. `@Inject(Engine)` declares a dependency on Engine.
## Injector
An injector instantiates objects lazily, only when asked for, and then caches them.
Compare
```
var car = inj.get(Car); //instantiates both an Engine and a Car
```
with
```
var engine = inj.get(Engine); //instantiates an Engine
var car = inj.get(Car); //instantiates a Car (reuses Engine)
```
and with
```
var car = inj.get(Car); //instantiates both an Engine and a Car
var engine = inj.get(Engine); //reads the Engine from the cache
```
To avoid bugs make sure the registered objects have side-effect-free constructors. In this case, an injector acts like a hash map, where the order in which the objects got created does not matter.
## Child Injectors and Dependencies
Injectors are hierarchical.
```
var parent = Injector.resolveAndCreate([
bind(Engine).toClass(TurboEngine)
]);
var child = parent.resolveAndCreateChild([Car]);
var car = child.get(Car); // uses the Car binding from the child injector and Engine from the parent injector.
```
Injectors form a tree.
```
GrandParentInjector
/ \
Parent1Injector Parent2Injector
|
ChildInjector
```
The dependency resolution algorithm works as follows:
```
// this is pseudocode.
var inj = this;
while (inj) {
if (inj.hasKey(requestedKey)) {
return inj.get(requestedKey);
} else {
inj = inj.parent;
}
}
throw new NoProviderError(requestedKey);
```
So in the following example
```
class Car {
constructor(e: Engine){}
}
```
DI will start resolving `Engine` in the same injector where the `Car` binding is defined. It will check whether that injector has the `Engine` binding. If it is the case, it will return that instance. If not, the injector will ask its parent whether it has an instance of `Engine`. The process continues until either an instance of `Engine` has been found, or we have reached the root of the injector tree.
### Constraints
You can put upper and lower bound constraints on a dependency. For instance, the `@Self` decorator tells DI to look for `Engine` only in the same injector where `Car` is defined. So it will not walk up the tree.
```
class Car {
constructor(@Self() e: Engine){}
}
```
A more realistic example is having two bindings that have to be provided together (e.g., NgModel and NgRequiredValidator.)
The `@Host` decorator tells DI to look for `Engine` in this injector, its parent, until it reaches a host (see the section on hosts.)
```
class Car {
constructor(@Host() e: Engine){}
}
```
The `@SkipSelf` decorator tells DI to look for `Engine` in the whole tree starting from the parent injector.
```
class Car {
constructor(@SkipSelf() e: Engine){}
}
```
### DI Does Not Walk Down
Dependency resolution only walks up the tree. The following will throw because DI will look for an instance of `Engine` starting from `parent`.
```
var parent = Injector.resolveAndCreate([Car]);
var child = parent.resolveAndCreateChild([
bind(Engine).toClass(TurboEngine)
]);
parent.get(Car); // will throw NoProviderError
```
## Bindings
You can bind to a class, a value, or a factory. It is also possible to alias existing bindings.
```
var inj = Injector.resolveAndCreate([
bind(Car).toClass(Car),
bind(Engine).toClass(Engine)
]);
var inj = Injector.resolveAndCreate([
Car, // syntax sugar for bind(Car).toClass(Car)
Engine
]);
var inj = Injector.resolveAndCreate([
bind(Car).toValue(new Car(new Engine()))
]);
var inj = Injector.resolveAndCreate([
bind(Car).toFactory((e) => new Car(e), [Engine]),
bind(Engine).toFactory(() => new Engine())
]);
```
You can bind any token.
```
var inj = Injector.resolveAndCreate([
bind(Car).toFactory((e) => new Car(), ["engine!"]),
bind("engine!").toClass(Engine)
]);
```
If you want to alias an existing binding, you can do so using `toAlias`:
```
var inj = Injector.resolveAndCreate([
bind(Engine).toClass(Engine),
bind("engine!").toAlias(Engine)
]);
```
which implies `inj.get(Engine) === inj.get("engine!")`.
Note that tokens and factory functions are decoupled.
```
bind("some token").toFactory(someFactory);
```
The `someFactory` function does not have to know that it creates an object for `some token`.
### Resolved Bindings
When DI receives `bind(Car).toClass(Car)`, it needs to do a few things before it can create an instance of `Car`:
- It needs to reflect on `Car` to create a factory function.
- It needs to normalize the dependencies (e.g., calculate lower and upper bounds).
The result of these two operations is a `ResolvedBinding`.
The `resolveAndCreate` and `resolveAndCreateChild` functions resolve passed-in bindings before creating an injector. But you can resolve bindings yourself using `Injector.resolve([bind(Car).toClass(Car)])`. Creating an injector from pre-resolved bindings is faster, and may be needed for performance sensitive areas.
You can create an injector using a list of resolved bindings.
```
var listOfResolvingProviders = Injector.resolve([Provider1, Provider2]);
var inj = Injector.fromResolvedProviders(listOfResolvingProviders);
inj.createChildFromResolvedProviders(listOfResolvedProviders);
```
### Transient Dependencies
An injector has only one instance created by each registered binding.
```
inj.get(MyClass) === inj.get(MyClass); //always holds
```
If we need a transient dependency, something that we want a new instance of every single time, we have two options.
We can create a child injector for each new instance:
```
var child = inj.resolveAndCreateChild([MyClass]);
child.get(MyClass);
```
Or we can register a factory function:
```
var inj = Injector.resolveAndCreate([
bind('MyClassFactory').toFactory(dep => () => new MyClass(dep), [SomeDependency])
]);
var factory = inj.get('MyClassFactory');
var instance1 = factory(), instance2 = factory();
// Depends on the implementation of MyClass, but generally holds.
expect(instance1).not.toBe(instance2);
```
| {
"end_byte": 7140,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/docs/di/di.md"
} |
angular/packages/localize/private.ts_0_1139 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file exports all the `utils` as private exports so that other parts of `@angular/localize`
// can make use of them.
export {
$localize as ɵ$localize,
LocalizeFn as ɵLocalizeFn,
TranslateFn as ɵTranslateFn,
} from './src/localize';
export {
computeMsgId as ɵcomputeMsgId,
findEndOfBlock as ɵfindEndOfBlock,
isMissingTranslationError as ɵisMissingTranslationError,
makeParsedTranslation as ɵmakeParsedTranslation,
makeTemplateObject as ɵmakeTemplateObject,
MissingTranslationError as ɵMissingTranslationError,
ParsedMessage as ɵParsedMessage,
ParsedTranslation as ɵParsedTranslation,
ParsedTranslations as ɵParsedTranslations,
parseMessage as ɵparseMessage,
parseMetadata as ɵparseMetadata,
parseTranslation as ɵparseTranslation,
SourceLocation as ɵSourceLocation,
SourceMessage as ɵSourceMessage,
splitBlock as ɵsplitBlock,
translate as ɵtranslate,
} from './src/utils';
| {
"end_byte": 1139,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/private.ts"
} |
angular/packages/localize/localize.ts_0_479 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file contains the public API of the `@angular/localize` entry-point
export {clearTranslations, loadTranslations} from './src/translate';
export {MessageId, TargetMessage} from './src/utils';
// Exports that are not part of the public API
export * from './private';
| {
"end_byte": 479,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/localize.ts"
} |
angular/packages/localize/PACKAGE.md_0_1919 | The `@angular/localize` package contains helpers and tools for localizing your application.
You should install this package using `ng add @angular/localize` if you need to tag text in your
application that you want to be translatable.
The approach is based around the concept of tagging strings in code with a [template literal tag handler][tagged-templates]
called `$localize`. The idea is that strings that need to be translated are “marked” using this tag:
```ts
const message = $localize`Hello, World!`;
```
---
This `$localize` identifier can be a real function that can do the translation at runtime, in the browser.
But, significantly, it is also a global identifier that survives minification.
This means it can act simply as a marker in the code that a static post-processing tool can use to replace
the original text with translated text before the code is deployed.
For example, the following code:
```ts
warning = $localize`${this.process} is not right`;
```
could be replaced with:
```ts
warning = "" + this.process + ", n'est pas bon.";
```
The result is that all references to `$localize` are removed, and there is **zero runtime cost** to rendering
the translated text.
---
The Angular template compiler also generates `$localize` tagged strings rather than doing the translation itself.
For example, the following template:
```html
<h1 i18n>Hello, World!</h1>
```
would be compiled to something like:
```ts
ɵɵelementStart(0, "h1"); // <h1>
ɵɵi18n(1, $localize`Hello, World!`); // Hello, World!
ɵɵelementEnd(); // </h1>
```
This means that after the Angular compiler has completed its work, all the template text marked with `i18n`
attributes have been converted to `$localize` tagged strings, which can be processed just like any other
tagged string.
[tagged-templates]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates
| {
"end_byte": 1919,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/PACKAGE.md"
} |
angular/packages/localize/BUILD.bazel_0_2760 | load("//tools:defaults.bzl", "api_golden_test_npm_package", "generate_api_docs", "ng_package", "ts_library")
load("//packages/bazel:index.bzl", "types_bundle")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "localize",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
module_name = "@angular/localize",
deps = [
"//packages/localize/src/localize",
"//packages/localize/src/utils",
],
)
types_bundle(
name = "api_type_definitions",
entry_point = "localize.d.ts",
output_name = "localize/index.d.ts",
deps = [":localize"],
)
ng_package(
name = "npm_package",
package_name = "@angular/localize",
srcs = [
"package.json",
":api_type_definitions",
],
nested_packages = [
"//packages/localize/schematics:npm_package",
"//packages/localize/tools:npm_package",
],
skip_type_bundling = [
# For the primary entry-point we disable automatic type bundling because API extractor
# does not properly handle module augmentation.
# To workaround this issue, type bundling is done as a separate step for all types
# except the main `index.d.ts` file which contains the module augmentation. The main
# file is reference in the package.json and also imports the bundle types. The bundled
# types are created via `api_type_definitions` above.
# TODO: Remove once https://github.com/microsoft/rushstack/issues/2090 is solved.
"",
],
tags = [
"release-with-framework",
],
deps = [
":localize",
"//packages/localize/init",
],
)
api_golden_test_npm_package(
name = "localize_api",
data = [
":npm_package",
"//goldens:public-api",
],
golden_dir = "angular/goldens/public-api/localize",
npm_package = "angular/packages/localize/npm_package",
# The logic for the localize function is exported in the primary entry-point, but users
# are not supposed to import it from there. We still want to guard these exports though.
strip_export_pattern = "^ɵ(?!.localize|LocalizeFn|TranslateFn)",
# The tool entry-point uses namespace aliases and API extractor needs to be
# able to resolve `@babel/core` to fully understand the `types` re-export/alias.
types = ["@npm//@types/babel__core"],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "localize_docs",
srcs = [
":files_for_docgen",
"//packages/localize/src/utils:files_for_docgen",
],
entry_point = ":index.ts",
module_name = "@angular/localize",
)
| {
"end_byte": 2760,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/BUILD.bazel"
} |
angular/packages/localize/index.ts_0_4386 | /**
* @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
*/
// DO NOT ADD public exports to this file.
// The public API exports are specified in the `./localize` module, which is checked by the
// public_api_guard rules
export * from './localize';
// The global declaration must be in the index.d.ts as otherwise it will not be picked up when used
// with
// /// <reference types="@angular/localize" />
import {ɵLocalizeFn} from './localize';
// `declare global` allows us to escape the current module and place types on the global namespace
declare global {
/**
* Tag a template literal string for localization.
*
* For example:
*
* ```ts
* $localize `some string to localize`
* ```
*
* **Providing meaning, description and id**
*
* You can optionally specify one or more of `meaning`, `description` and `id` for a localized
* string by pre-pending it with a colon delimited block of the form:
*
* ```ts
* $localize`:meaning|description@@id:source message text`;
*
* $localize`:meaning|:source message text`;
* $localize`:description:source message text`;
* $localize`:@@id:source message text`;
* ```
*
* This format is the same as that used for `i18n` markers in Angular templates. See the
* [Angular i18n guide](guide/i18n/prepare#mark-text-in-component-template).
*
* **Naming placeholders**
*
* If the template literal string contains expressions, then the expressions will be automatically
* associated with placeholder names for you.
*
* For example:
*
* ```ts
* $localize `Hi ${name}! There are ${items.length} items.`;
* ```
*
* will generate a message-source of `Hi {$PH}! There are {$PH_1} items`.
*
* The recommended practice is to name the placeholder associated with each expression though.
*
* Do this by providing the placeholder name wrapped in `:` characters directly after the
* expression. These placeholder names are stripped out of the rendered localized string.
*
* For example, to name the `items.length` expression placeholder `itemCount` you write:
*
* ```ts
* $localize `There are ${items.length}:itemCount: items`;
* ```
*
* **Escaping colon markers**
*
* If you need to use a `:` character directly at the start of a tagged string that has no
* metadata block, or directly after a substitution expression that has no name you must escape
* the `:` by preceding it with a backslash:
*
* For example:
*
* ```ts
* // message has a metadata block so no need to escape colon
* $localize `:some description::this message starts with a colon (:)`;
* // no metadata block so the colon must be escaped
* $localize `\:this message starts with a colon (:)`;
* ```
*
* ```ts
* // named substitution so no need to escape colon
* $localize `${label}:label:: ${}`
* // anonymous substitution so colon must be escaped
* $localize `${label}\: ${}`
* ```
*
* **Processing localized strings:**
*
* There are three scenarios:
*
* * **compile-time inlining**: the `$localize` tag is transformed at compile time by a
* transpiler, removing the tag and replacing the template literal string with a translated
* literal string from a collection of translations provided to the transpilation tool.
*
* * **run-time evaluation**: the `$localize` tag is a run-time function that replaces and
* reorders the parts (static strings and expressions) of the template literal string with strings
* from a collection of translations loaded at run-time.
*
* * **pass-through evaluation**: the `$localize` tag is a run-time function that simply evaluates
* the original template literal string without applying any translations to the parts. This
* version is used during development or where there is no need to translate the localized
* template literals.
*
* @param messageParts a collection of the static parts of the template string.
* @param expressions a collection of the values of each placeholder in the template string.
* @returns the translated string, with the `messageParts` and `expressions` interleaved together.
*/
const $localize: ɵLocalizeFn;
}
| {
"end_byte": 4386,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/localize/index.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.