Skip to content
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

Add JS/TS code folding support to language server #632

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
238 changes: 238 additions & 0 deletions packages/core/__tests__/language-server/folding-ranges.test.ts
Copy link
Contributor

@NullVoxPopuli NullVoxPopuli Oct 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really appreciate you adding all these tests in your PRs <3

Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
import { Project } from 'glint-monorepo-test-utils';
import { describe, beforeEach, afterEach, test, expect } from 'vitest';
import { stripIndent } from 'common-tags';

describe('Language Server: Folding Ranges', () => {
let project!: Project;

beforeEach(async () => {
project = await Project.create();
});

afterEach(async () => {
await project.destroy();
});

test('function', () => {
project.write({
'example.ts': stripIndent`
function foo() {
return 'bar';
}
`,
});

let server = project.startLanguageServer();
let folds = server.getFoldingRanges(project.fileURI('example.ts'));

expect(folds).toEqual([
{
startLine: 0,
endLine: 1,
kind: undefined,
},
]);
});

test('nested function', () => {
project.write({
'example.ts': stripIndent`
function topLevel() {

function nested() {
return 'bar';
}

return nested();
}
`,
});

let server = project.startLanguageServer();
let folds = server.getFoldingRanges(project.fileURI('example.ts'));

expect(folds).toEqual([
{
startLine: 0,
endLine: 6,
Copy link
Contributor

@NullVoxPopuli NullVoxPopuli Oct 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this excluding the last }? I count that it should be 7?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The last line is excluded if it's just a closing bracket (https://github.com/typed-ember/glint/pull/632/files#diff-cadffc59ac4fd3c9fd1cd7488980fc9cfea40cd5a93129f1021c54c810980e20R503). This is so that folded functions keep the } visible:

// Like this when folded
function topLevel() {
}

// instead of this
function topLevel() {

this is consistent with the TS language server's folding.

kind: undefined,
},
{
startLine: 2,
endLine: 3,
kind: undefined,
},
]);
});

test('imports', () => {
project.write({
'example.ts': stripIndent`
import Component, { hbs } from '@glimmerx/component';
import foo from 'bar';
import { baz } from 'qux';

export default { foo, baz, Component };
`,
});

let server = project.startLanguageServer();
let folds = server.getFoldingRanges(project.fileURI('example.ts'));

expect(folds).toEqual([
{
startLine: 0,
endLine: 2,
kind: 'imports',
},
]);
});

test('comments', () => {
project.write({
'example.ts': stripIndent`
// This is
// a
// multiline
// comment

const foo = 'bar';
`,
});

let server = project.startLanguageServer();
let folds = server.getFoldingRanges(project.fileURI('example.ts'));

expect(folds).toEqual([
{
startLine: 0,
endLine: 3,
kind: 'comment',
},
]);
});

test('region', () => {
project.write({
'example.ts': stripIndent`
const foo = 'bar';

// #region

const bar = 'baz';

// #endregion

export default { foo, bar };
`,
});

let server = project.startLanguageServer();
let folds = server.getFoldingRanges(project.fileURI('example.ts'));

expect(folds).toEqual([
{
startLine: 2,
endLine: 6,
kind: 'region',
},
]);
});

test('simple component', () => {
project.write({
'example.ts': stripIndent`
import Component, { hbs } from '@glimmerx/component';
import { tracked } from '@glimmer/tracking';

export interface EmberComponentArgs {
message: string;
}

export interface EmberComponentSignature {
Element: HTMLDivElement;
Args: EmberComponentArgs;
}

/**
* A simple component that renders a message.
*/
export default class Greeting extends Component<EmberComponentSignature> {
@tracked message = this.args.message;

get capitalizedMessage() {
return this.message.toUpperCase();
}
}

declare module '@glint/environment-ember-loose/registry' {
export default interface Registry {
EmberComponent: typeof EmberComponent;
'ember-component': typeof EmberComponent;
}
}
`,
});

let server = project.startLanguageServer();
let folds = server.getFoldingRanges(project.fileURI('example.ts'));

expect(folds).toEqual([
// Imports
{
startLine: 0,
endLine: 1,
kind: 'imports',
},

// EmberComponentArgs
{
startLine: 3,
endLine: 4,
kind: undefined,
},

// EmberComponentSignature
{
startLine: 7,
endLine: 9,
kind: undefined,
},

// Code Comment
{
startLine: 12,
endLine: 14,
kind: 'comment',
},

// Greeting Component
{
startLine: 15,
endLine: 20,
kind: undefined,
},

// capitalizedMessage
{
startLine: 18,
endLine: 19,
kind: undefined,
},

// declare module
{
startLine: 23,
endLine: 27,
kind: undefined,
},

// interface Registry
{
startLine: 24,
endLine: 26,
kind: undefined,
},
]);
});
});
7 changes: 7 additions & 0 deletions packages/core/src/language-server/binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export const capabilities: ServerCapabilities = {
codeActionProvider: {
codeActionKinds: [CodeActionKind.QuickFix],
},
foldingRangeProvider: true,
definitionProvider: true,
workspaceSymbolProvider: true,
renameProvider: {
Expand Down Expand Up @@ -217,4 +218,10 @@ export function bindLanguageServerPool({ connection, pool, openDocuments }: Bind
scheduleDiagnostics();
});
});

connection.onFoldingRanges((params) => {
return pool.withServerForURI(params.textDocument.uri, ({ server }) =>
server.getFoldingRanges(params.textDocument.uri)
);
});
}
66 changes: 66 additions & 0 deletions packages/core/src/language-server/glint-language-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import {
OptionalVersionedTextDocumentIdentifier,
TextEdit,
MarkupContent,
FoldingRange,
FoldingRangeKind,
} from 'vscode-languageserver';
import DocumentCache from '../common/document-cache.js';
import { Position, positionToOffset } from './util/position.js';
Expand Down Expand Up @@ -561,6 +563,70 @@ export default class GlintLanguageServer {
return edits;
}

public getFoldingRanges(uri: string): FoldingRange[] {
const filePath = uriToFilePath(uri);

let foldingRanges: FoldingRange[] = [];
this.service.getOutliningSpans(filePath).forEach((outliningSpan, index) => {
const foldingRange = this.outliningSpanToFoldingRange(outliningSpan, filePath);

if (
!foldingRange ||
(index > 0 && foldingRange.startLine === 0) ||
foldingRange.startLine === foldingRange.endLine
) {
return;
}

foldingRanges.push(foldingRange);
});

return foldingRanges;
}

private outliningSpanToFoldingRange(
span: ts.OutliningSpan,
fileName: string
): FoldingRange | undefined {
// The OutliningSpan.textSpan's length is inclusive. This is a
// workaround for off-by-one & out-of-range errors caused by this.
span.textSpan.length = span.textSpan.length - 1;
const location = this.textSpanToLocation(fileName, span.textSpan);

if (!location) {
return;
}

const { start, end } = location.range;

// workaround for https://github.com/Microsoft/vscode/issues/47240
const originalContents = this.documents.getDocumentContents(fileName);
const originalEnd = positionToOffset(originalContents, end);
const lastCharOfSpan = originalContents[originalEnd];

return {
startLine: start.line,
endLine: lastCharOfSpan === '}' ? Math.max(end.line - 1, start.line) : end.line,
kind: this.outliningSpanKindToFoldingRangeKind(span),
};
}

private outliningSpanKindToFoldingRangeKind(
outliningSpan: ts.OutliningSpan
): FoldingRangeKind | undefined {
switch (outliningSpan.kind) {
case 'comment':
return FoldingRangeKind.Comment;
case 'region':
return FoldingRangeKind.Region;
case 'imports':
return FoldingRangeKind.Imports;
case 'code':
default:
return undefined;
}
}

private applyCodeAction(
uri: string,
range: Range,
Expand Down
Loading