Skip to content

feat: add config to enable auto-apply optional chaining on nullable symbol #1469

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions client/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,12 @@ function constructArgs(ctx: vscode.ExtensionContext): string[] {
args.push('--viewEngine');
}

const includeAutomaticOptionalChainCompletions =
config.get<boolean>('angular.suggest.includeAutomaticOptionalChainCompletions');
if (includeAutomaticOptionalChainCompletions) {
args.push('--includeAutomaticOptionalChainCompletions');
}

const tsdk: string|null = config.get('typescript.tsdk', null);
const tsProbeLocations = getProbeLocations(tsdk, ctx.extensionPath);
args.push('--tsProbeLocations', tsProbeLocations.join(','));
Expand Down
68 changes: 65 additions & 3 deletions integration/lsp/ivy_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {URI} from 'vscode-uri';
import {ProjectLanguageService, ProjectLanguageServiceParams, SuggestStrictMode, SuggestStrictModeParams} from '../../common/notifications';
import {NgccProgress, NgccProgressToken, NgccProgressType} from '../../common/progress';
import {GetComponentsWithTemplateFile, GetTcbRequest, IsInAngularProject} from '../../common/requests';
import {APP_COMPONENT, APP_COMPONENT_URI, FOO_COMPONENT_URI, FOO_TEMPLATE, FOO_TEMPLATE_URI, PROJECT_PATH, TSCONFIG} from '../test_constants';
import {APP_COMPONENT, APP_COMPONENT_URI, FOO_COMPONENT, FOO_COMPONENT_URI, FOO_TEMPLATE, FOO_TEMPLATE_URI, PROJECT_PATH, TSCONFIG} from '../test_constants';

import {createConnection, createTracer, initializeServer, openTextDocument} from './test_utils';

Expand Down Expand Up @@ -197,7 +197,8 @@ describe('Angular Ivy language server', () => {
}))!;
expect(response).not.toBeNull();
expect(response.signatures.length).toEqual(1);
expect(response.signatures[0].label).toEqual('substr(from: number, length?: number): string');
expect(response.signatures[0].label)
.toEqual('substr(from: number, length?: number | undefined): string');
expect(response.signatures[0].parameters).not.toBeUndefined();
expect(response.activeParameter).toBe(1);

Expand All @@ -206,7 +207,7 @@ describe('Angular Ivy language server', () => {
const [start, end] = param.label as [number, number];
return label.substring(start, end);
});
expect(paramLabels).toEqual(['from: number', 'length?: number']);
expect(paramLabels).toEqual(['from: number', 'length?: number | undefined']);
});
});

Expand Down Expand Up @@ -480,6 +481,67 @@ describe('Angular Ivy language server', () => {
})
});

describe('auto-apply optional chaining', () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; /* 10 seconds */

let client: MessageConnection;
beforeEach(async () => {
client = createConnection({
ivy: true,
includeAutomaticOptionalChainCompletions: true,
});
// If debugging, set to
// - lsp.Trace.Messages to inspect request/response/notification, or
// - lsp.Trace.Verbose to inspect payload
client.trace(lsp.Trace.Off, createTracer());
client.listen();
await initializeServer(client);
});

afterEach(() => {
client.dispose();
});

it('should work on nullable symbol', async () => {
openTextDocument(client, FOO_COMPONENT, `
import {Component} from '@angular/core';
@Component({
templateUrl: 'foo.component.html',
})
export class FooComponent {
person?: undefined|{name: string};
}
`);
openTextDocument(client, FOO_TEMPLATE, `{{ person.n }}`);
const languageServiceEnabled = await waitForNgcc(client);
expect(languageServiceEnabled).toBeTrue();
const response = await client.sendRequest(lsp.CompletionRequest.type, {
textDocument: {
uri: FOO_TEMPLATE_URI,
},
position: {line: 0, character: 11},
}) as lsp.CompletionItem[];
const completion = response.find(i => i.label === 'name')!;
expect(completion.kind).toEqual(lsp.CompletionItemKind.Property);
expect((completion.textEdit as lsp.TextEdit).newText).toEqual('?.name');
});

it('should work on NonNullable symbol', async () => {
openTextDocument(client, FOO_TEMPLATE, `{{ title.substr }}`);
const languageServiceEnabled = await waitForNgcc(client);
expect(languageServiceEnabled).toBeTrue();
const response = await client.sendRequest(lsp.CompletionRequest.type, {
textDocument: {
uri: FOO_TEMPLATE_URI,
},
position: {line: 0, character: 15},
}) as lsp.CompletionItem[];
const completion = response.find(i => i.label === 'substr')!;
expect(completion.kind).toEqual(lsp.CompletionItemKind.Method);
expect((completion.textEdit as lsp.TextEdit).newText).toEqual('substr');
});
});

function onNgccProgress(client: MessageConnection): Promise<string> {
return new Promise(resolve => {
client.onProgress(NgccProgressType, NgccProgressToken, (params: NgccProgress) => {
Expand Down
4 changes: 4 additions & 0 deletions integration/lsp/test_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {PROJECT_PATH, SERVER_PATH} from '../test_constants';

export interface ServerOptions {
ivy: boolean;
includeAutomaticOptionalChainCompletions?: boolean;
}

export function createConnection(serverOptions: ServerOptions): MessageConnection {
Expand All @@ -28,6 +29,9 @@ export function createConnection(serverOptions: ServerOptions): MessageConnectio
if (!serverOptions.ivy) {
argv.push('--viewEngine');
}
if (serverOptions.includeAutomaticOptionalChainCompletions) {
argv.push('--includeAutomaticOptionalChainCompletions');
}
const server = fork(SERVER_PATH, argv, {
cwd: PROJECT_PATH,
// uncomment to debug server process
Expand Down
1 change: 1 addition & 0 deletions integration/project/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"moduleResolution": "node",
"experimentalDecorators": true,
"target": "es2015",
"strict": true,
"typeRoots": [
"node_modules/@types"
]
Expand Down
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@
],
"default": "off",
"description": "Traces the communication between VS Code and the Angular language server."
},
"angular.suggest.includeAutomaticOptionalChainCompletions": {
"type": "boolean",
"default": true,
"description": "Enable/disable showing completions on potentially undefined values that insert an optional chain call. Requires TS 3.7+ and strict null checks to be enabled."
}
}
},
Expand Down Expand Up @@ -164,7 +169,7 @@
"test:syntaxes": "yarn compile:syntaxes-test && yarn build:syntaxes && jasmine dist/syntaxes/test/driver.js"
},
"dependencies": {
"@angular/language-service": "13.0.0-next.0",
"@angular/language-service": "13.0.0-next.2",
"typescript": "4.3.4",
"vscode-jsonrpc": "6.0.0",
"vscode-languageclient": "7.0.0",
Expand Down
2 changes: 1 addition & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"ngserver": "./bin/ngserver"
},
"dependencies": {
"@angular/language-service": "13.0.0-next.0",
"@angular/language-service": "13.0.0-next.2",
"vscode-jsonrpc": "6.0.0",
"vscode-languageserver": "7.0.0",
"vscode-uri": "3.0.2"
Expand Down
3 changes: 3 additions & 0 deletions server/src/cmdline_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ interface CommandLineOptions {
logToConsole: boolean;
ngProbeLocations: string[];
tsProbeLocations: string[];
includeAutomaticOptionalChainCompletions: boolean;
}

export function parseCommandLine(argv: string[]): CommandLineOptions {
Expand All @@ -48,6 +49,8 @@ export function parseCommandLine(argv: string[]): CommandLineOptions {
logToConsole: hasArgument(argv, '--logToConsole'),
ngProbeLocations: parseStringArray(argv, '--ngProbeLocations'),
tsProbeLocations: parseStringArray(argv, '--tsProbeLocations'),
includeAutomaticOptionalChainCompletions:
hasArgument(argv, '--includeAutomaticOptionalChainCompletions'),
};
}

Expand Down
9 changes: 8 additions & 1 deletion server/src/completion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ function ngCompletionKindToLspCompletionItemKind(kind: CompletionKind): lsp.Comp
*/
export function tsCompletionEntryToLspCompletionItem(
entry: ts.CompletionEntry, position: lsp.Position, scriptInfo: ts.server.ScriptInfo,
insertReplaceSupport: boolean): lsp.CompletionItem {
insertReplaceSupport: boolean, isIvy: boolean): lsp.CompletionItem {
const item = lsp.CompletionItem.create(entry.name);
// Even though `entry.kind` is typed as ts.ScriptElementKind, it's
// really Angular's CompletionKind. This is because ts.ScriptElementKind does
Expand All @@ -120,6 +120,13 @@ export function tsCompletionEntryToLspCompletionItem(
const insertText = entry.insertText || entry.name;
item.textEdit = createTextEdit(scriptInfo, entry, position, insertText, insertReplaceSupport);

if (isIvy) {
// If the user enables the config `includeAutomaticOptionalChainCompletions`, the `insertText`
// range will include the dot. the `insertText` should be assigned to the `filterText` to filter
// the completion items.
item.filterText = entry.insertText;
}

item.data = {
kind: 'ngCompletionOriginData',
filePath: scriptInfo.fileName,
Expand Down
1 change: 1 addition & 0 deletions server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ function main() {
resolvedNgLsPath: ng.resolvedPath,
ivy: isG3 ? true : options.ivy,
logToConsole: options.logToConsole,
includeAutomaticOptionalChainCompletions: options.includeAutomaticOptionalChainCompletions
});

// Log initialization info
Expand Down
22 changes: 16 additions & 6 deletions server/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export interface SessionOptions {
resolvedNgLsPath: string;
ivy: boolean;
logToConsole: boolean;
includeAutomaticOptionalChainCompletions: boolean;
}

enum LanguageId {
Expand All @@ -53,6 +54,7 @@ export class Session {
private readonly configuredProjToExternalProj = new Map<string, string>();
private readonly logToConsole: boolean;
private readonly openFiles = new MruTracker();
private readonly includeAutomaticOptionalChainCompletions: boolean;
// Tracks the spawn order and status of the `ngcc` processes. This allows us to ensure we enable
// the LS in the same order the projects were created in.
private projectNgccQueue: Array<{project: ts.server.Project, done: boolean}> = [];
Expand All @@ -68,6 +70,8 @@ export class Session {
private clientCapabilities: lsp.ClientCapabilities = {};

constructor(options: SessionOptions) {
this.includeAutomaticOptionalChainCompletions =
options.includeAutomaticOptionalChainCompletions;
this.logger = options.logger;
this.ivy = options.ivy;
this.logToConsole = options.logToConsole;
Expand Down Expand Up @@ -978,11 +982,17 @@ export class Session {
}
const {languageService, scriptInfo} = lsInfo;
const offset = lspPositionToTsPosition(scriptInfo, params.position);
const completions = languageService.getCompletionsAtPosition(
scriptInfo.fileName, offset,
{
// options
});

let options: ts.GetCompletionsAtPositionOptions = {};
if (this.includeAutomaticOptionalChainCompletions) {
options = {
includeAutomaticOptionalChainCompletions: this.includeAutomaticOptionalChainCompletions,
includeCompletionsWithInsertText: this.includeAutomaticOptionalChainCompletions,
};
}

const completions =
languageService.getCompletionsAtPosition(scriptInfo.fileName, offset, options);
if (!completions) {
return;
}
Expand All @@ -991,7 +1001,7 @@ export class Session {
false;
return completions.entries.map(
(e) => tsCompletionEntryToLspCompletionItem(
e, params.position, scriptInfo, clientSupportsInsertReplaceCompletion));
e, params.position, scriptInfo, clientSupportsInsertReplaceCompletion, this.ivy));
}

private onCompletionResolve(item: lsp.CompletionItem): lsp.CompletionItem {
Expand Down
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@
yaml "^1.10.0"
yargs "^17.0.0"

"@angular/[email protected].0":
version "13.0.0-next.0"
resolved "https://registry.yarnpkg.com/@angular/language-service/-/language-service-13.0.0-next.0.tgz#15bf69c67f8de05b32e3966eea63ac2cb04d6563"
integrity sha512-45nITynaQmWzD6n11eB0YK1WRsRnySpoEoznl4+sNWMGv7KociCqm94IE3ol0L4FybLVZ6qqUgial33CYNtAvw==
"@angular/[email protected].2":
version "13.0.0-next.2"
resolved "https://registry.yarnpkg.com/@angular/language-service/-/language-service-13.0.0-next.2.tgz#4027291ea734195f8518e2ea022c306b9127f49a"
integrity sha512-zgzUrpQFzxRH9YFV0Fk21zu7bYpKn5lgeGtUyqgL23fi7BdjuXXyKiB7cnT+xxT4U5yNRlIq4mDQGJRscDvOMg==

"@babel/code-frame@^7.0.0":
version "7.12.13"
Expand Down