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:
parent
087596bbde
commit
563fb6cdbe
|
@ -6,7 +6,6 @@ ts_library(
|
||||||
name = "common",
|
name = "common",
|
||||||
srcs = glob(["*.ts"]),
|
srcs = glob(["*.ts"]),
|
||||||
deps = [
|
deps = [
|
||||||
"@npm//@types/node",
|
|
||||||
"@npm//typescript",
|
"@npm//typescript",
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
|
@ -6,24 +6,35 @@
|
||||||
* found in the LICENSE file at https://angular.io/license
|
* found in the LICENSE file at https://angular.io/license
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import * as path from 'path';
|
|
||||||
import * as ts from 'typescript';
|
import * as ts from 'typescript';
|
||||||
|
|
||||||
import {findTightestNode, getClassDeclFromDecoratorProp, getPropertyAssignmentFromValue} from './ts_utils';
|
import {findTightestNode, getClassDeclFromDecoratorProp, getPropertyAssignmentFromValue} from './ts_utils';
|
||||||
|
|
||||||
|
export interface ResourceResolver {
|
||||||
|
/**
|
||||||
|
* Resolve the url of a resource relative to the file that contains the reference to it.
|
||||||
|
*
|
||||||
|
* @param file The, possibly relative, url of the resource.
|
||||||
|
* @param basePath The path to the file that contains the URL of the resource.
|
||||||
|
* @returns A resolved url of resource.
|
||||||
|
* @throws An error if the resource cannot be resolved.
|
||||||
|
*/
|
||||||
|
resolve(file: string, basePath: string): string;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets an Angular-specific definition in a TypeScript source file.
|
* Gets an Angular-specific definition in a TypeScript source file.
|
||||||
*/
|
*/
|
||||||
export function getTsDefinitionAndBoundSpan(
|
export function getTsDefinitionAndBoundSpan(
|
||||||
sf: ts.SourceFile, position: number,
|
sf: ts.SourceFile, position: number,
|
||||||
tsLsHost: Pick<ts.LanguageServiceHost, 'fileExists'>): ts.DefinitionInfoAndBoundSpan|undefined {
|
resourceResolver: ResourceResolver): ts.DefinitionInfoAndBoundSpan|undefined {
|
||||||
const node = findTightestNode(sf, position);
|
const node = findTightestNode(sf, position);
|
||||||
if (!node) return;
|
if (!node) return;
|
||||||
switch (node.kind) {
|
switch (node.kind) {
|
||||||
case ts.SyntaxKind.StringLiteral:
|
case ts.SyntaxKind.StringLiteral:
|
||||||
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
|
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
|
||||||
// Attempt to extract definition of a URL in a property assignment.
|
// Attempt to extract definition of a URL in a property assignment.
|
||||||
return getUrlFromProperty(node as ts.StringLiteralLike, tsLsHost);
|
return getUrlFromProperty(node as ts.StringLiteralLike, resourceResolver);
|
||||||
default:
|
default:
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
@ -34,9 +45,8 @@ export function getTsDefinitionAndBoundSpan(
|
||||||
* directive decorator.
|
* directive decorator.
|
||||||
* Currently applies to `templateUrl` and `styleUrls` properties.
|
* Currently applies to `templateUrl` and `styleUrls` properties.
|
||||||
*/
|
*/
|
||||||
function getUrlFromProperty(
|
function getUrlFromProperty(urlNode: ts.StringLiteralLike, resourceResolver: ResourceResolver):
|
||||||
urlNode: ts.StringLiteralLike,
|
ts.DefinitionInfoAndBoundSpan|undefined {
|
||||||
tsLsHost: Pick<ts.LanguageServiceHost, 'fileExists'>): ts.DefinitionInfoAndBoundSpan|undefined {
|
|
||||||
// Get the property assignment node corresponding to the `templateUrl` or `styleUrls` assignment.
|
// Get the property assignment node corresponding to the `templateUrl` or `styleUrls` assignment.
|
||||||
// These assignments are specified differently; `templateUrl` is a string, and `styleUrls` is
|
// These assignments are specified differently; `templateUrl` is a string, and `styleUrls` is
|
||||||
// an array of strings:
|
// an array of strings:
|
||||||
|
@ -65,13 +75,13 @@ function getUrlFromProperty(
|
||||||
}
|
}
|
||||||
|
|
||||||
const sf = urlNode.getSourceFile();
|
const sf = urlNode.getSourceFile();
|
||||||
// Extract url path specified by the url node, which is relative to the TypeScript source file
|
let url: string;
|
||||||
// the url node is defined in.
|
try {
|
||||||
const url = path.join(path.dirname(sf.fileName), urlNode.text);
|
url = resourceResolver.resolve(urlNode.text, sf.fileName);
|
||||||
|
} catch {
|
||||||
// If the file does not exist, bail. It is possible that the TypeScript language service host
|
// If the file does not exist, bail.
|
||||||
// does not have a `fileExists` method, in which case optimistically assume the file exists.
|
return;
|
||||||
if (tsLsHost.fileExists && !tsLsHost.fileExists(url)) return;
|
}
|
||||||
|
|
||||||
const templateDefinitions: ts.DefinitionInfo[] = [{
|
const templateDefinitions: ts.DefinitionInfo[] = [{
|
||||||
kind: ts.ScriptElementKind.externalModuleName,
|
kind: ts.ScriptElementKind.externalModuleName,
|
||||||
|
@ -79,6 +89,9 @@ function getUrlFromProperty(
|
||||||
containerKind: ts.ScriptElementKind.unknown,
|
containerKind: ts.ScriptElementKind.unknown,
|
||||||
containerName: '',
|
containerName: '',
|
||||||
// Reading the template is expensive, so don't provide a preview.
|
// 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},
|
textSpan: {start: 0, length: 0},
|
||||||
fileName: url,
|
fileName: url,
|
||||||
}];
|
}];
|
||||||
|
|
|
@ -83,5 +83,5 @@ export function getClassDeclOfInlineTemplateNode(templateStringNode: ts.Node): t
|
||||||
if (!tmplAsgn) {
|
if (!tmplAsgn) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return getClassDeclFromDecoratorProp(tmplAsgn)
|
return getClassDeclFromDecoratorProp(tmplAsgn);
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,6 +13,7 @@ ts_library(
|
||||||
"//packages/compiler-cli/src/ngtsc/file_system",
|
"//packages/compiler-cli/src/ngtsc/file_system",
|
||||||
"//packages/compiler-cli/src/ngtsc/incremental",
|
"//packages/compiler-cli/src/ngtsc/incremental",
|
||||||
"//packages/compiler-cli/src/ngtsc/reflection",
|
"//packages/compiler-cli/src/ngtsc/reflection",
|
||||||
|
"//packages/compiler-cli/src/ngtsc/resource",
|
||||||
"//packages/compiler-cli/src/ngtsc/shims",
|
"//packages/compiler-cli/src/ngtsc/shims",
|
||||||
"//packages/compiler-cli/src/ngtsc/typecheck",
|
"//packages/compiler-cli/src/ngtsc/typecheck",
|
||||||
"//packages/compiler-cli/src/ngtsc/typecheck/api",
|
"//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 {TypeCheckingProgramStrategy} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
|
||||||
import * as ts from 'typescript/lib/tsserverlibrary';
|
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 {
|
export class CompilerFactory {
|
||||||
private readonly incrementalStrategy = new TrackedIncrementalBuildStrategy();
|
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 {DirectiveSymbol, DomBindingSymbol, ElementSymbol, ShimLocation, Symbol, SymbolKind, TemplateSymbol} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
|
||||||
import * as ts from 'typescript';
|
import * as ts from 'typescript';
|
||||||
|
|
||||||
|
import {getTsDefinitionAndBoundSpan, ResourceResolver} from '../common/definitions';
|
||||||
|
|
||||||
import {getPathToNodeAtPosition} from './hybrid_visitor';
|
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 {
|
interface DefinitionMeta {
|
||||||
node: AST|TmplAstNode;
|
node: AST|TmplAstNode;
|
||||||
|
@ -25,13 +27,25 @@ interface HasShimLocation {
|
||||||
}
|
}
|
||||||
|
|
||||||
export class DefinitionBuilder {
|
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
|
getDefinitionAndBoundSpan(fileName: string, position: number): ts.DefinitionInfoAndBoundSpan
|
||||||
|undefined {
|
|undefined {
|
||||||
const templateInfo = getTemplateInfoAtPosition(fileName, position, this.compiler);
|
const templateInfo = getTemplateInfoAtPosition(fileName, position, this.compiler);
|
||||||
if (templateInfo === undefined) {
|
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);
|
const definitionMeta = this.getDefinitionMetaAtPosition(templateInfo, position);
|
||||||
// The `$event` of event handlers would point to the $event parameter in the shim file, as in
|
// 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 {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 {absoluteFromSourceFile, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system';
|
||||||
import {TypeCheckShimGenerator} from '@angular/compiler-cli/src/ngtsc/typecheck';
|
import {TypeCheckShimGenerator} from '@angular/compiler-cli/src/ngtsc/typecheck';
|
||||||
import {OptimizeFor, TypeCheckingProgramStrategy} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
|
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 {CompilerFactory} from './compiler_factory';
|
||||||
import {DefinitionBuilder} from './definitions';
|
import {DefinitionBuilder} from './definitions';
|
||||||
import {isExternalTemplate, isTypeScriptFile, LanguageServiceAdapter} from './language_service_adapter';
|
import {LanguageServiceAdapter} from './language_service_adapter';
|
||||||
import {QuickInfoBuilder} from './quick_info';
|
import {QuickInfoBuilder} from './quick_info';
|
||||||
|
import {isTypeScriptFile} from './utils';
|
||||||
|
|
||||||
export class LanguageService {
|
export class LanguageService {
|
||||||
private options: CompilerOptions;
|
private options: CompilerOptions;
|
||||||
|
@ -57,8 +57,8 @@ export class LanguageService {
|
||||||
getDefinitionAndBoundSpan(fileName: string, position: number): ts.DefinitionInfoAndBoundSpan
|
getDefinitionAndBoundSpan(fileName: string, position: number): ts.DefinitionInfoAndBoundSpan
|
||||||
|undefined {
|
|undefined {
|
||||||
const compiler = this.compilerFactory.getOrCreateWithChangedFile(fileName, this.options);
|
const compiler = this.compilerFactory.getOrCreateWithChangedFile(fileName, this.options);
|
||||||
const results =
|
const results = new DefinitionBuilder(this.tsLS, compiler, this.adapter)
|
||||||
new DefinitionBuilder(this.tsLS, compiler).getDefinitionAndBoundSpan(fileName, position);
|
.getDefinitionAndBoundSpan(fileName, position);
|
||||||
this.compilerFactory.registerLastKnownProgram();
|
this.compilerFactory.registerLastKnownProgram();
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
@ -66,8 +66,8 @@ export class LanguageService {
|
||||||
getTypeDefinitionAtPosition(fileName: string, position: number):
|
getTypeDefinitionAtPosition(fileName: string, position: number):
|
||||||
readonly ts.DefinitionInfo[]|undefined {
|
readonly ts.DefinitionInfo[]|undefined {
|
||||||
const compiler = this.compilerFactory.getOrCreateWithChangedFile(fileName, this.options);
|
const compiler = this.compilerFactory.getOrCreateWithChangedFile(fileName, this.options);
|
||||||
const results =
|
const results = new DefinitionBuilder(this.tsLS, compiler, this.adapter)
|
||||||
new DefinitionBuilder(this.tsLS, compiler).getTypeDefinitionsAtPosition(fileName, position);
|
.getTypeDefinitionsAtPosition(fileName, position);
|
||||||
this.compilerFactory.registerLastKnownProgram();
|
this.compilerFactory.registerLastKnownProgram();
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,10 +8,15 @@
|
||||||
|
|
||||||
import {NgCompilerAdapter} from '@angular/compiler-cli/src/ngtsc/core/api';
|
import {NgCompilerAdapter} from '@angular/compiler-cli/src/ngtsc/core/api';
|
||||||
import {absoluteFrom, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system';
|
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 {isShim} from '@angular/compiler-cli/src/ngtsc/shims';
|
||||||
import * as ts from 'typescript/lib/tsserverlibrary';
|
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 entryPoint = null;
|
||||||
readonly constructionDiagnostics: ts.Diagnostic[] = [];
|
readonly constructionDiagnostics: ts.Diagnostic[] = [];
|
||||||
readonly ignoreForEmit: Set<ts.SourceFile> = new Set();
|
readonly ignoreForEmit: Set<ts.SourceFile> = new Set();
|
||||||
|
@ -75,12 +80,9 @@ export class LanguageServiceAdapter implements NgCompilerAdapter {
|
||||||
const latestVersion = this.project.getScriptVersion(fileName);
|
const latestVersion = this.project.getScriptVersion(fileName);
|
||||||
return lastVersion !== latestVersion;
|
return lastVersion !== latestVersion;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
export function isTypeScriptFile(fileName: string): boolean {
|
resolve(file: string, basePath: string): string {
|
||||||
return fileName.endsWith('.ts');
|
const loader = new AdapterResourceLoader(this, this.project.getCompilationSettings());
|
||||||
}
|
return loader.resolve(file, basePath);
|
||||||
|
}
|
||||||
export function isExternalTemplate(fileName: string): boolean {
|
|
||||||
return !isTypeScriptFile(fileName);
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -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(
|
function getDefinitionsAndAssertBoundSpan(
|
||||||
{templateOverride, expectedSpanText}: {templateOverride: string, expectedSpanText: string}):
|
{templateOverride, expectedSpanText}: {templateOverride: string, expectedSpanText: string}):
|
||||||
Array<{textSpan: string, contextSpan: string | undefined, fileName: string}> {
|
Array<{textSpan: string, contextSpan: string | undefined, fileName: string}> {
|
||||||
|
|
|
@ -8,7 +8,8 @@
|
||||||
|
|
||||||
import {join} from 'path';
|
import {join} from 'path';
|
||||||
import * as ts from 'typescript/lib/tsserverlibrary';
|
import * as ts from 'typescript/lib/tsserverlibrary';
|
||||||
import {isTypeScriptFile} from '../language_service_adapter';
|
|
||||||
|
import {isTypeScriptFile} from '../utils';
|
||||||
|
|
||||||
const logger: ts.server.Logger = {
|
const logger: ts.server.Logger = {
|
||||||
close(): void{},
|
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 * as ts from 'typescript';
|
||||||
|
|
||||||
import {ALIAS_NAME, SYMBOL_PUNC} from '../common/quick_info';
|
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 {
|
export function getTextSpanOfNode(node: t.Node|e.AST): ts.TextSpan {
|
||||||
if (isTemplateNodeWithKeyAndValue(node)) {
|
if (isTemplateNodeWithKeyAndValue(node)) {
|
||||||
|
@ -70,8 +71,8 @@ export interface TemplateInfo {
|
||||||
*/
|
*/
|
||||||
export function getTemplateInfoAtPosition(
|
export function getTemplateInfoAtPosition(
|
||||||
fileName: string, position: number, compiler: NgCompiler): TemplateInfo|undefined {
|
fileName: string, position: number, compiler: NgCompiler): TemplateInfo|undefined {
|
||||||
if (fileName.endsWith('.ts')) {
|
if (isTypeScriptFile(fileName)) {
|
||||||
return getInlineTemplateInfoAtPosition(fileName, position, compiler);
|
return getTemplateInfoFromClassMeta(fileName, position, compiler);
|
||||||
} else {
|
} else {
|
||||||
return getFirstComponentForTemplateFile(fileName, compiler);
|
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.
|
* Retrieves the `ts.ClassDeclaration` at a location along with its template nodes.
|
||||||
*/
|
*/
|
||||||
function getInlineTemplateInfoAtPosition(
|
function getTemplateInfoFromClassMeta(
|
||||||
fileName: string, position: number, compiler: NgCompiler): TemplateInfo|undefined {
|
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);
|
const sourceFile = compiler.getNextProgram().getSourceFile(fileName);
|
||||||
if (!sourceFile) {
|
if (!sourceFile) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
const node = findTightestNode(sourceFile, position);
|
||||||
// We only support top level statements / class declarations
|
if (!node) return;
|
||||||
for (const statement of sourceFile.statements) {
|
return getClassDeclOfInlineTemplateNode(node);
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -291,3 +293,11 @@ export function flatMap<T, R>(items: T[]|readonly T[], f: (item: T) => R[] | rea
|
||||||
}
|
}
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isTypeScriptFile(fileName: string): boolean {
|
||||||
|
return fileName.endsWith('.ts');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isExternalTemplate(fileName: string): boolean {
|
||||||
|
return !isTypeScriptFile(fileName);
|
||||||
|
}
|
||||||
|
|
|
@ -6,9 +6,11 @@
|
||||||
* found in the LICENSE file at https://angular.io/license
|
* found in the LICENSE file at https://angular.io/license
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import {getTsDefinitionAndBoundSpan} from '@angular/language-service/common/definitions';
|
import * as path from 'path';
|
||||||
import * as tss from 'typescript/lib/tsserverlibrary';
|
import * as tss from 'typescript/lib/tsserverlibrary';
|
||||||
|
|
||||||
|
import {getTsDefinitionAndBoundSpan, ResourceResolver} from '../common/definitions';
|
||||||
|
|
||||||
import {getTemplateCompletions} from './completions';
|
import {getTemplateCompletions} from './completions';
|
||||||
import {getDefinitionAndBoundSpan} from './definitions';
|
import {getDefinitionAndBoundSpan} from './definitions';
|
||||||
import {getDeclarationDiagnostics, getTemplateDiagnostics, ngDiagnosticToTsDiagnostic} from './diagnostics';
|
import {getDeclarationDiagnostics, getTemplateDiagnostics, ngDiagnosticToTsDiagnostic} from './diagnostics';
|
||||||
|
@ -76,13 +78,13 @@ class LanguageServiceImpl implements ng.LanguageService {
|
||||||
if (templateInfo) {
|
if (templateInfo) {
|
||||||
return getDefinitionAndBoundSpan(templateInfo, position);
|
return getDefinitionAndBoundSpan(templateInfo, position);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attempt to get Angular-specific definitions in a TypeScript file, like templates defined
|
// Attempt to get Angular-specific definitions in a TypeScript file, like templates defined
|
||||||
// in a `templateUrl` property.
|
// in a `templateUrl` property.
|
||||||
if (fileName.endsWith('.ts')) {
|
if (fileName.endsWith('.ts')) {
|
||||||
const sf = this.host.getSourceFile(fileName);
|
const sf = this.host.getSourceFile(fileName);
|
||||||
if (sf) {
|
if (sf) {
|
||||||
return getTsDefinitionAndBoundSpan(sf, position, this.host.tsLsHost);
|
return getTsDefinitionAndBoundSpan(
|
||||||
|
sf, position, new ViewEngineLSResourceResolver(this.host.tsLsHost));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -113,3 +115,20 @@ class LanguageServiceImpl implements ng.LanguageService {
|
||||||
return this.host.tsLS.getReferencesAtPosition(tsDef.fileName, tsDef.textSpan.start);
|
return this.host.tsLS.getReferencesAtPosition(tsDef.fileName, tsDef.textSpan.start);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class ViewEngineLSResourceResolver implements ResourceResolver {
|
||||||
|
constructor(private host: ts.LanguageServiceHost) {}
|
||||||
|
|
||||||
|
resolve(file: string, basePath: string): string {
|
||||||
|
// Extract url path specified by the url node, which is relative to the TypeScript source file
|
||||||
|
// the url node is defined in.
|
||||||
|
const url = path.join(path.dirname(basePath), file);
|
||||||
|
|
||||||
|
// If the file does not exist, bail. It is possible that the TypeScript language service host
|
||||||
|
// does not have a `fileExists` method, in which case optimistically assume the file exists.
|
||||||
|
if (this.host.fileExists && !this.host.fileExists(url)) {
|
||||||
|
throw new Error(`ResourceResolver: could not resolve ${url} in context of ${basePath})`);
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -59,6 +59,7 @@ ts_library(
|
||||||
"//packages/compiler",
|
"//packages/compiler",
|
||||||
"//packages/language-service",
|
"//packages/language-service",
|
||||||
"//packages/language-service:ts_utils",
|
"//packages/language-service:ts_utils",
|
||||||
|
"//packages/language-service/common",
|
||||||
"@npm//typescript",
|
"@npm//typescript",
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
|
@ -9,7 +9,8 @@
|
||||||
import * as ng from '@angular/compiler';
|
import * as ng from '@angular/compiler';
|
||||||
import * as ts from 'typescript';
|
import * as ts from 'typescript';
|
||||||
|
|
||||||
import {getClassDeclFromDecoratorProp, getDirectiveClassLike} from '../src/ts_utils';
|
import {getClassDeclFromDecoratorProp} from '../common/ts_utils';
|
||||||
|
import {getDirectiveClassLike} from '../src/ts_utils';
|
||||||
import {getPathToNodeAtPosition} from '../src/utils';
|
import {getPathToNodeAtPosition} from '../src/utils';
|
||||||
import {MockTypescriptHost} from './test_utils';
|
import {MockTypescriptHost} from './test_utils';
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue