feat(language-service): Implement go to definition for style and template urls (#39202)
This commit enables the Ivy Language Service to 'go to definition' of a templateUrl or styleUrl, which would jump to the template/style file itself. PR Close #39202
This commit is contained in:

committed by
Andrew Kushnir

parent
087596bbde
commit
563fb6cdbe
@ -13,6 +13,7 @@ ts_library(
|
||||
"//packages/compiler-cli/src/ngtsc/file_system",
|
||||
"//packages/compiler-cli/src/ngtsc/incremental",
|
||||
"//packages/compiler-cli/src/ngtsc/reflection",
|
||||
"//packages/compiler-cli/src/ngtsc/resource",
|
||||
"//packages/compiler-cli/src/ngtsc/shims",
|
||||
"//packages/compiler-cli/src/ngtsc/typecheck",
|
||||
"//packages/compiler-cli/src/ngtsc/typecheck/api",
|
||||
|
@ -12,7 +12,8 @@ import {TrackedIncrementalBuildStrategy} from '@angular/compiler-cli/src/ngtsc/i
|
||||
import {TypeCheckingProgramStrategy} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
|
||||
import * as ts from 'typescript/lib/tsserverlibrary';
|
||||
|
||||
import {isExternalTemplate, LanguageServiceAdapter} from './language_service_adapter';
|
||||
import {LanguageServiceAdapter} from './language_service_adapter';
|
||||
import {isExternalTemplate} from './utils';
|
||||
|
||||
export class CompilerFactory {
|
||||
private readonly incrementalStrategy = new TrackedIncrementalBuildStrategy();
|
||||
|
@ -11,8 +11,10 @@ import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
|
||||
import {DirectiveSymbol, DomBindingSymbol, ElementSymbol, ShimLocation, Symbol, SymbolKind, TemplateSymbol} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {getTsDefinitionAndBoundSpan, ResourceResolver} from '../common/definitions';
|
||||
|
||||
import {getPathToNodeAtPosition} from './hybrid_visitor';
|
||||
import {flatMap, getDirectiveMatchesForAttribute, getDirectiveMatchesForElementTag, getTemplateInfoAtPosition, getTextSpanOfNode, isDollarEvent, TemplateInfo, toTextSpan} from './utils';
|
||||
import {flatMap, getDirectiveMatchesForAttribute, getDirectiveMatchesForElementTag, getTemplateInfoAtPosition, getTextSpanOfNode, isDollarEvent, isTypeScriptFile, TemplateInfo, toTextSpan} from './utils';
|
||||
|
||||
interface DefinitionMeta {
|
||||
node: AST|TmplAstNode;
|
||||
@ -25,13 +27,25 @@ interface HasShimLocation {
|
||||
}
|
||||
|
||||
export class DefinitionBuilder {
|
||||
constructor(private readonly tsLS: ts.LanguageService, private readonly compiler: NgCompiler) {}
|
||||
constructor(
|
||||
private readonly tsLS: ts.LanguageService, private readonly compiler: NgCompiler,
|
||||
private readonly resourceResolver: ResourceResolver) {}
|
||||
|
||||
getDefinitionAndBoundSpan(fileName: string, position: number): ts.DefinitionInfoAndBoundSpan
|
||||
|undefined {
|
||||
const templateInfo = getTemplateInfoAtPosition(fileName, position, this.compiler);
|
||||
if (templateInfo === undefined) {
|
||||
return;
|
||||
// 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;
|
||||
}
|
||||
const sf = this.compiler.getNextProgram().getSourceFile(fileName);
|
||||
if (!sf) {
|
||||
return;
|
||||
}
|
||||
return getTsDefinitionAndBoundSpan(sf, position, this.resourceResolver);
|
||||
}
|
||||
const definitionMeta = this.getDefinitionMetaAtPosition(templateInfo, position);
|
||||
// The `$event` of event handlers would point to the $event parameter in the shim file, as in
|
||||
|
@ -7,7 +7,6 @@
|
||||
*/
|
||||
|
||||
import {CompilerOptions, createNgCompilerOptions} from '@angular/compiler-cli';
|
||||
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
|
||||
import {absoluteFromSourceFile, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system';
|
||||
import {TypeCheckShimGenerator} from '@angular/compiler-cli/src/ngtsc/typecheck';
|
||||
import {OptimizeFor, TypeCheckingProgramStrategy} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
|
||||
@ -15,8 +14,9 @@ import * as ts from 'typescript/lib/tsserverlibrary';
|
||||
|
||||
import {CompilerFactory} from './compiler_factory';
|
||||
import {DefinitionBuilder} from './definitions';
|
||||
import {isExternalTemplate, isTypeScriptFile, LanguageServiceAdapter} from './language_service_adapter';
|
||||
import {LanguageServiceAdapter} from './language_service_adapter';
|
||||
import {QuickInfoBuilder} from './quick_info';
|
||||
import {isTypeScriptFile} from './utils';
|
||||
|
||||
export class LanguageService {
|
||||
private options: CompilerOptions;
|
||||
@ -57,8 +57,8 @@ export class LanguageService {
|
||||
getDefinitionAndBoundSpan(fileName: string, position: number): ts.DefinitionInfoAndBoundSpan
|
||||
|undefined {
|
||||
const compiler = this.compilerFactory.getOrCreateWithChangedFile(fileName, this.options);
|
||||
const results =
|
||||
new DefinitionBuilder(this.tsLS, compiler).getDefinitionAndBoundSpan(fileName, position);
|
||||
const results = new DefinitionBuilder(this.tsLS, compiler, this.adapter)
|
||||
.getDefinitionAndBoundSpan(fileName, position);
|
||||
this.compilerFactory.registerLastKnownProgram();
|
||||
return results;
|
||||
}
|
||||
@ -66,8 +66,8 @@ export class LanguageService {
|
||||
getTypeDefinitionAtPosition(fileName: string, position: number):
|
||||
readonly ts.DefinitionInfo[]|undefined {
|
||||
const compiler = this.compilerFactory.getOrCreateWithChangedFile(fileName, this.options);
|
||||
const results =
|
||||
new DefinitionBuilder(this.tsLS, compiler).getTypeDefinitionsAtPosition(fileName, position);
|
||||
const results = new DefinitionBuilder(this.tsLS, compiler, this.adapter)
|
||||
.getTypeDefinitionsAtPosition(fileName, position);
|
||||
this.compilerFactory.registerLastKnownProgram();
|
||||
return results;
|
||||
}
|
||||
|
@ -8,10 +8,15 @@
|
||||
|
||||
import {NgCompilerAdapter} from '@angular/compiler-cli/src/ngtsc/core/api';
|
||||
import {absoluteFrom, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system';
|
||||
import {AdapterResourceLoader} from '@angular/compiler-cli/src/ngtsc/resource';
|
||||
import {isShim} from '@angular/compiler-cli/src/ngtsc/shims';
|
||||
import * as ts from 'typescript/lib/tsserverlibrary';
|
||||
|
||||
export class LanguageServiceAdapter implements NgCompilerAdapter {
|
||||
import {ResourceResolver} from '../common/definitions';
|
||||
|
||||
import {isTypeScriptFile} from './utils';
|
||||
|
||||
export class LanguageServiceAdapter implements NgCompilerAdapter, ResourceResolver {
|
||||
readonly entryPoint = null;
|
||||
readonly constructionDiagnostics: ts.Diagnostic[] = [];
|
||||
readonly ignoreForEmit: Set<ts.SourceFile> = new Set();
|
||||
@ -75,12 +80,9 @@ export class LanguageServiceAdapter implements NgCompilerAdapter {
|
||||
const latestVersion = this.project.getScriptVersion(fileName);
|
||||
return lastVersion !== latestVersion;
|
||||
}
|
||||
}
|
||||
|
||||
export function isTypeScriptFile(fileName: string): boolean {
|
||||
return fileName.endsWith('.ts');
|
||||
}
|
||||
|
||||
export function isExternalTemplate(fileName: string): boolean {
|
||||
return !isTypeScriptFile(fileName);
|
||||
resolve(file: string, basePath: string): string {
|
||||
const loader = new AdapterResourceLoader(this, this.project.getCompilationSettings());
|
||||
return loader.resolve(file, basePath);
|
||||
}
|
||||
}
|
||||
|
@ -448,6 +448,53 @@ describe('definitions', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('external resources', () => {
|
||||
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 MyComponent {}`);
|
||||
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 MyComponent {}`);
|
||||
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});
|
||||
});
|
||||
});
|
||||
|
||||
function getDefinitionsAndAssertBoundSpan(
|
||||
{templateOverride, expectedSpanText}: {templateOverride: string, expectedSpanText: string}):
|
||||
Array<{textSpan: string, contextSpan: string | undefined, fileName: string}> {
|
||||
|
@ -8,7 +8,8 @@
|
||||
|
||||
import {join} from 'path';
|
||||
import * as ts from 'typescript/lib/tsserverlibrary';
|
||||
import {isTypeScriptFile} from '../language_service_adapter';
|
||||
|
||||
import {isTypeScriptFile} from '../utils';
|
||||
|
||||
const logger: ts.server.Logger = {
|
||||
close(): void{},
|
||||
|
@ -14,6 +14,7 @@ import * as t from '@angular/compiler/src/render3/r3_ast'; // t for temp
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {ALIAS_NAME, SYMBOL_PUNC} from '../common/quick_info';
|
||||
import {findTightestNode, getClassDeclOfInlineTemplateNode} from '../common/ts_utils';
|
||||
|
||||
export function getTextSpanOfNode(node: t.Node|e.AST): ts.TextSpan {
|
||||
if (isTemplateNodeWithKeyAndValue(node)) {
|
||||
@ -70,8 +71,8 @@ export interface TemplateInfo {
|
||||
*/
|
||||
export function getTemplateInfoAtPosition(
|
||||
fileName: string, position: number, compiler: NgCompiler): TemplateInfo|undefined {
|
||||
if (fileName.endsWith('.ts')) {
|
||||
return getInlineTemplateInfoAtPosition(fileName, position, compiler);
|
||||
if (isTypeScriptFile(fileName)) {
|
||||
return getTemplateInfoFromClassMeta(fileName, position, compiler);
|
||||
} else {
|
||||
return getFirstComponentForTemplateFile(fileName, compiler);
|
||||
}
|
||||
@ -116,28 +117,29 @@ function getFirstComponentForTemplateFile(fileName: string, compiler: NgCompiler
|
||||
/**
|
||||
* Retrieves the `ts.ClassDeclaration` at a location along with its template nodes.
|
||||
*/
|
||||
function getInlineTemplateInfoAtPosition(
|
||||
function getTemplateInfoFromClassMeta(
|
||||
fileName: string, position: number, compiler: NgCompiler): TemplateInfo|undefined {
|
||||
const classDecl = getClassDeclForInlineTemplateAtPosition(fileName, position, compiler);
|
||||
if (!classDecl || !classDecl.name) { // Does not handle anonymous class
|
||||
return;
|
||||
}
|
||||
const template = compiler.getTemplateTypeChecker().getTemplate(classDecl);
|
||||
if (template === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
return {template, component: classDecl};
|
||||
}
|
||||
|
||||
function getClassDeclForInlineTemplateAtPosition(
|
||||
fileName: string, position: number, compiler: NgCompiler): ts.ClassDeclaration|undefined {
|
||||
const sourceFile = compiler.getNextProgram().getSourceFile(fileName);
|
||||
if (!sourceFile) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// We only support top level statements / class declarations
|
||||
for (const statement of sourceFile.statements) {
|
||||
if (!ts.isClassDeclaration(statement) || position < statement.pos || position > statement.end) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const template = compiler.getTemplateTypeChecker().getTemplate(statement);
|
||||
if (template === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {template, component: statement};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
const node = findTightestNode(sourceFile, position);
|
||||
if (!node) return;
|
||||
return getClassDeclOfInlineTemplateNode(node);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -291,3 +293,11 @@ export function flatMap<T, R>(items: T[]|readonly T[], f: (item: T) => R[] | rea
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
export function isTypeScriptFile(fileName: string): boolean {
|
||||
return fileName.endsWith('.ts');
|
||||
}
|
||||
|
||||
export function isExternalTemplate(fileName: string): boolean {
|
||||
return !isTypeScriptFile(fileName);
|
||||
}
|
||||
|
Reference in New Issue
Block a user