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

Selection Range support. Part of Microsoft/vscode#65925 #46

Merged
merged 3 commits into from
Jan 23, 2019
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
5 changes: 2 additions & 3 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"version": "0.1.0",
// List of configurations. Add new configurations or edit existing ones.
"version": "0.2.0",
"configurations": [
{
"name": "Attach",
Expand All @@ -27,7 +26,7 @@
"env": {},
"sourceMaps": true,
"outFiles": ["${workspaceRoot}/lib/umd/**"],
"preLaunchTask": "compile"
"preLaunchTask": "npm: compile"
}
]
}
31 changes: 17 additions & 14 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "npm",
"isShellCommand": true,
"showOutput": "always",
"suppressTaskName": true,
"tasks": [
{
"taskName": "compile",
"args": ["run", "compile"]
}
]
}
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "compile",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"presentation": {
"reveal": "never"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
3 changes: 3 additions & 0 deletions src/htmlLanguageService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { Scanner, HTMLDocument, CompletionConfiguration, ICompletionParticipant,
import { getFoldingRanges } from './services/htmlFolding';
import { handleCustomData } from './languageFacts';
import { HTMLData } from './languageFacts';
import { getSelectionRanges } from './services/htmlSelectionRange';

export * from './htmlLanguageTypes';
export * from 'vscode-languageserver-types';
Expand All @@ -33,6 +34,7 @@ export interface LanguageService {
findDocumentSymbols(document: TextDocument, htmlDocument: HTMLDocument): SymbolInformation[];
doTagComplete(document: TextDocument, position: Position, htmlDocument: HTMLDocument): string | null;
getFoldingRanges(document: TextDocument, context?: { rangeLimit?: number }): FoldingRange[];
getSelectionRanges(document: TextDocument, position: Position): Range[];
}

export interface LanguageServiceOptions {
Expand All @@ -57,6 +59,7 @@ export function getLanguageService(options?: LanguageServiceOptions): LanguageSe
findDocumentLinks,
findDocumentSymbols,
getFoldingRanges,
getSelectionRanges,
doTagComplete: htmlCompletion.doTagComplete.bind(htmlCompletion),
};
}
1 change: 1 addition & 0 deletions src/htmlLanguageTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export interface CompletionConfiguration {
export interface Node {
tag: string | undefined;
start: number;
startTagEnd: number | undefined;
end: number;
endTagStart: number | undefined;
children: Node[];
Expand Down
4 changes: 3 additions & 1 deletion src/parser/htmlParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { TokenType } from '../htmlLanguageTypes';
export class Node {
public tag: string | undefined;
public closed: boolean = false;
public startTagEnd: number | undefined;
public endTagStart: number | undefined;
public attributes: { [name: string]: string | null } | undefined;
public get attributeNames(): string[] { return this.attributes ? Object.keys(this.attributes) : []; }
Expand Down Expand Up @@ -80,6 +81,7 @@ export function parse(text: string): HTMLDocument {
break;
case TokenType.StartTagClose:
curr.end = scanner.getTokenEnd(); // might be later set to end tag position
curr.startTagEnd = scanner.getTokenEnd();
if (curr.tag && isEmptyElement(curr.tag) && curr.parent) {
curr.closed = true;
curr = curr.parent;
Expand All @@ -89,6 +91,7 @@ export function parse(text: string): HTMLDocument {
if (curr.parent) {
curr.closed = true;
curr.end = scanner.getTokenEnd();
curr.startTagEnd = scanner.getTokenEnd();
curr = curr.parent;
}
break;
Expand Down Expand Up @@ -150,5 +153,4 @@ export function parse(text: string): HTMLDocument {
findNodeBefore: htmlDocument.findNodeBefore.bind(htmlDocument),
findNodeAt: htmlDocument.findNodeAt.bind(htmlDocument)
};

}
167 changes: 167 additions & 0 deletions src/services/htmlSelectionRange.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
/**
* Until SelectionRange lands in LSP, we'll return Range from server and convert it to
* SelectionRange on client side
*/
import { Range, TextDocument, Position } from 'vscode-languageserver-types';
import { createScanner } from '../parser/htmlScanner';
import { parse, Node } from '../parser/htmlParser';
import { TokenType } from '../htmlLanguageTypes';

export function getSelectionRanges(document: TextDocument, position: Position) {
const applicableRanges = getApplicableRanges(document, position);
const ranges = applicableRanges.map(pair => {
return Range.create(
document.positionAt(pair[0]),
document.positionAt(pair[1])
);
});
return ranges;
}

export function getApplicableRanges(document: TextDocument, position: Position): number[][] {
const htmlDoc = parse(document.getText());
const currOffset = document.offsetAt(position);
const currNode = htmlDoc.findNodeAt(currOffset);

let result = getAllParentTagRanges(currNode);

if (!currNode.startTagEnd || !currNode.endTagStart) {
return result;
}

/**
* For html like
* `<div class="foo">bar</div>`
*/

/**
* Cursor inside `<div class="foo">`
*/
if (currNode.start < currOffset && currOffset < currNode.startTagEnd) {
result.unshift([currNode.start + 1, currNode.startTagEnd - 1]);
const attributeLevelRanges = getAttributeLevelRanges(document, currNode, currOffset);
result = attributeLevelRanges.concat(result);
return result;
}
/**
* Cursor inside `bar`
*/
else if (currNode.startTagEnd <= currOffset && currOffset <= currNode.endTagStart) {
result.unshift([currNode.startTagEnd, currNode.endTagStart]);

return result;
}
/**
* Cursor inside `</div>`
*/
else {
// `div` inside `</div>`
if (currOffset >= currNode.endTagStart + 2) {
result.unshift([currNode.endTagStart + 2, currNode.end - 1]);
}
return result;
}
}

function getAllParentTagRanges(initialNode: Node) {
let currNode = initialNode;

const getNodeRanges = (n: Node) => {
if (n.startTagEnd && n.endTagStart && n.startTagEnd < n.endTagStart) {
return [
[n.startTagEnd, n.endTagStart],
[n.start, n.end]
];
}

return [
[n.start, n.end]
];
};

const result: number[][] = [];

while (currNode.parent) {
currNode = currNode.parent;
getNodeRanges(currNode).forEach(r => result.push(r));
}

return result;
}

function getAttributeLevelRanges(document: TextDocument, currNode: Node, currOffset: number) {
const currNodeRange = Range.create(document.positionAt(currNode.start), document.positionAt(currNode.end));
const currNodeText = document.getText(currNodeRange);
const relativeOffset = currOffset - currNode.start;

/**
* Tag level semantic selection
*/

const scanner = createScanner(currNodeText);
let token = scanner.scan();

/**
* For text like
* <div class="foo">bar</div>
*/
const positionOffset = currNode.start;

const result = [];

let isInsideAttribute = false;
let attrStart = -1;
while (token !== TokenType.EOS) {
switch (token) {
case TokenType.AttributeName: {
if (relativeOffset < scanner.getTokenOffset()) {
isInsideAttribute = false;
break;
}

if (relativeOffset <= scanner.getTokenEnd()) {
// `class`
result.unshift([scanner.getTokenOffset(), scanner.getTokenEnd()]);
}

isInsideAttribute = true;
attrStart = scanner.getTokenOffset();
break;
}
case TokenType.AttributeValue: {
if (!isInsideAttribute) {
break;
}

const valueText = scanner.getTokenText();
if (relativeOffset < scanner.getTokenOffset()) {
// `class="foo"`
result.push([attrStart, scanner.getTokenEnd()]);
break;
}

if (relativeOffset >= scanner.getTokenOffset() && relativeOffset <= scanner.getTokenEnd()) {
// `"foo"`
result.unshift([scanner.getTokenOffset(), scanner.getTokenEnd()]);

// `foo`
if ((valueText[0] === `"` && valueText[valueText.length - 1] === `"`) || (valueText[0] === `'` && valueText[valueText.length - 1] === `'`)) {
if (relativeOffset >= scanner.getTokenOffset() + 1 && relativeOffset <= scanner.getTokenEnd() - 1) {
result.unshift([scanner.getTokenOffset() + 1, scanner.getTokenEnd() - 1]);
}
}

// `class="foo"`
result.push([attrStart, scanner.getTokenEnd()]);
}

break;
}
}
token = scanner.scan();
}

return result.map(pair => {
return [pair[0] + positionOffset, pair[1] + positionOffset];
});
}
70 changes: 70 additions & 0 deletions src/test/selectionRange.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

'use strict';

import 'mocha';
import * as assert from 'assert';
import { TextDocument } from 'vscode-languageserver-types';
import { getApplicableRanges } from '../services/htmlSelectionRange';

function assertRanges(lines: string[] | string, expected: number[][]): void {
let content: string = '';
if (Array.isArray(lines)) {
content = lines.join('\n');
} else {
content = lines;
}
let message = `Test ${content}`;

let offset = content.indexOf('|');
content = content.substr(0, offset) + content.substr(offset + 1);

const document = TextDocument.create('test://foo/bar.html', 'html', 1, content);
const actualRanges = getApplicableRanges(document, document.positionAt(offset));
Copy link
Contributor

Choose a reason for hiding this comment

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

Ideally write the tests against the public API (htmlLanguageService.getSelectionRanges), that way we are sure it works end-to-end and the implementation can be changed freely without impacting any tests.


message += `\n${JSON.stringify(actualRanges)} should equal to ${JSON.stringify(expected)}`;
assert.deepEqual(actualRanges, expected, message);
}

suite('HTML SelectionRange', () => {
test('Basic', () => {
assertRanges('<div|>foo</div>', [[1, 4], [0, 14]]);
Copy link
Contributor

Choose a reason for hiding this comment

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

shouldn't [1,4] be [1,3]?
For readability, maybe format the expected ranges like [ "1:div", "0:<div>foo</div>"]

assertRanges('<|div>foo</div>', [[1, 4], [0, 14]]);
assertRanges('<d|iv>foo</div>', [[1, 4], [0, 14]]);

assertRanges('<div>|foo</div>', [[5, 8], [0, 14]]);
assertRanges('<div>f|oo</div>', [[5, 8], [0, 14]]);
assertRanges('<div>foo|</div>', [[5, 8], [0, 14]]);

assertRanges('<div>foo<|/div>', [[0, 14]]);

assertRanges('<div>foo</|div>', [[10, 13], [0, 14]]);
assertRanges('<div>foo</di|v>', [[10, 13], [0, 14]]);
assertRanges('<div>foo</div|>', [[10, 13], [0, 14]]);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

also test self closed tags (<div foo="sdsdd"/>)


test('Attribute Name', () => {
assertRanges('<div |class="foo">foo</div>', [[5, 10], [5, 16], [1, 16], [0, 26]]);
assertRanges('<div cl|ass="foo">foo</div>', [[5, 10], [5, 16], [1, 16], [0, 26]]);
assertRanges('<div class|="foo">foo</div>', [[5, 10], [5, 16], [1, 16], [0, 26]]);
});

test('Attribute Value', () => {
assertRanges('<div class=|"foo">foo</div>', [[11, 16], [5, 16], [1, 16], [0, 26]]);
assertRanges('<div class="foo"|>foo</div>', [[11, 16], [5, 16], [1, 16], [0, 26]]);

assertRanges('<div class="|foo">foo</div>', [[12, 15], [11, 16], [5, 16], [1, 16], [0, 26]]);
assertRanges('<div class="f|oo">foo</div>', [[12, 15], [11, 16], [5, 16], [1, 16], [0, 26]]);
});

test('Unquoted Attribute Value', () => {
assertRanges('<div class=|foo>foo</div>', [[11, 14], [5, 14], [1, 14], [0, 24]]);
});

test('Multiple Attribute Value', () => {
assertRanges('<div class="foo" id="|bar">foo</div>', [[21, 24], [20, 25], [17, 25], [1, 25], [0, 35]]);
});
});
Copy link
Contributor

Choose a reason for hiding this comment

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

test comments and doctypes as well