mirror of
https://github.com/microsoft/vscode.git
synced 2025-12-22 19:29:17 +00:00
Allow to run css language server headless
This commit is contained in:
382
extensions/css-language-features/server/src/cssServer.ts
Normal file
382
extensions/css-language-features/server/src/cssServer.ts
Normal file
@@ -0,0 +1,382 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import {
|
||||
IConnection, TextDocuments, InitializeParams, InitializeResult, ServerCapabilities, ConfigurationRequest, WorkspaceFolder, TextDocumentSyncKind, NotificationType
|
||||
} from 'vscode-languageserver';
|
||||
import { URI } from 'vscode-uri';
|
||||
import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet, TextDocument, Position } from 'vscode-css-languageservice';
|
||||
import { getLanguageModelCache } from './languageModelCache';
|
||||
import { PathCompletionParticipant } from './pathCompletion';
|
||||
import { formatError, runSafeAsync } from './utils/runner';
|
||||
import { getDocumentContext } from './utils/documentContext';
|
||||
import { fetchDataProviders } from './customData';
|
||||
import { RequestService, getRequestService } from './requests';
|
||||
|
||||
namespace CustomDataChangedNotification {
|
||||
export const type: NotificationType<string[]> = new NotificationType('css/customDataChanged');
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
css: LanguageSettings;
|
||||
less: LanguageSettings;
|
||||
scss: LanguageSettings;
|
||||
}
|
||||
|
||||
export interface RuntimeEnvironment {
|
||||
file?: RequestService;
|
||||
http?: RequestService
|
||||
}
|
||||
|
||||
export function startServer(connection: IConnection, runtime: RuntimeEnvironment) {
|
||||
|
||||
// Create a text document manager.
|
||||
const documents = new TextDocuments(TextDocument);
|
||||
// Make the text document manager listen on the connection
|
||||
// for open, change and close text document events
|
||||
documents.listen(connection);
|
||||
|
||||
const stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document));
|
||||
documents.onDidClose(e => {
|
||||
stylesheets.onDocumentRemoved(e.document);
|
||||
});
|
||||
connection.onShutdown(() => {
|
||||
stylesheets.dispose();
|
||||
});
|
||||
|
||||
let scopedSettingsSupport = false;
|
||||
let foldingRangeLimit = Number.MAX_VALUE;
|
||||
let workspaceFolders: WorkspaceFolder[];
|
||||
|
||||
let dataProvidersReady: Promise<any> = Promise.resolve();
|
||||
|
||||
const languageServices: { [id: string]: LanguageService } = {};
|
||||
|
||||
const notReady = () => Promise.reject('Not Ready');
|
||||
let requestService: RequestService = { getContent: notReady, stat: notReady, readDirectory: notReady };
|
||||
|
||||
// After the server has started the client sends an initialize request. The server receives
|
||||
// in the passed params the rootPath of the workspace plus the client capabilities.
|
||||
connection.onInitialize((params: InitializeParams): InitializeResult => {
|
||||
workspaceFolders = (<any>params).workspaceFolders;
|
||||
if (!Array.isArray(workspaceFolders)) {
|
||||
workspaceFolders = [];
|
||||
if (params.rootPath) {
|
||||
workspaceFolders.push({ name: '', uri: URI.file(params.rootPath).toString() });
|
||||
}
|
||||
}
|
||||
|
||||
requestService = getRequestService(params.initializationOptions.handledSchemas || ['file'], connection, runtime);
|
||||
|
||||
function getClientCapability<T>(name: string, def: T) {
|
||||
const keys = name.split('.');
|
||||
let c: any = params.capabilities;
|
||||
for (let i = 0; c && i < keys.length; i++) {
|
||||
if (!c.hasOwnProperty(keys[i])) {
|
||||
return def;
|
||||
}
|
||||
c = c[keys[i]];
|
||||
}
|
||||
return c;
|
||||
}
|
||||
const snippetSupport = !!getClientCapability('textDocument.completion.completionItem.snippetSupport', false);
|
||||
scopedSettingsSupport = !!getClientCapability('workspace.configuration', false);
|
||||
foldingRangeLimit = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE);
|
||||
|
||||
languageServices.css = getCSSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities });
|
||||
languageServices.scss = getSCSSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities });
|
||||
languageServices.less = getLESSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities });
|
||||
|
||||
const capabilities: ServerCapabilities = {
|
||||
textDocumentSync: TextDocumentSyncKind.Incremental,
|
||||
completionProvider: snippetSupport ? { resolveProvider: false, triggerCharacters: ['/', '-'] } : undefined,
|
||||
hoverProvider: true,
|
||||
documentSymbolProvider: true,
|
||||
referencesProvider: true,
|
||||
definitionProvider: true,
|
||||
documentHighlightProvider: true,
|
||||
documentLinkProvider: {
|
||||
resolveProvider: false
|
||||
},
|
||||
codeActionProvider: true,
|
||||
renameProvider: true,
|
||||
colorProvider: {},
|
||||
foldingRangeProvider: true,
|
||||
selectionRangeProvider: true
|
||||
};
|
||||
return { capabilities };
|
||||
});
|
||||
|
||||
function getLanguageService(document: TextDocument) {
|
||||
let service = languageServices[document.languageId];
|
||||
if (!service) {
|
||||
connection.console.log('Document type is ' + document.languageId + ', using css instead.');
|
||||
service = languageServices['css'];
|
||||
}
|
||||
return service;
|
||||
}
|
||||
|
||||
let documentSettings: { [key: string]: Thenable<LanguageSettings | undefined> } = {};
|
||||
// remove document settings on close
|
||||
documents.onDidClose(e => {
|
||||
delete documentSettings[e.document.uri];
|
||||
});
|
||||
function getDocumentSettings(textDocument: TextDocument): Thenable<LanguageSettings | undefined> {
|
||||
if (scopedSettingsSupport) {
|
||||
let promise = documentSettings[textDocument.uri];
|
||||
if (!promise) {
|
||||
const configRequestParam = { items: [{ scopeUri: textDocument.uri, section: textDocument.languageId }] };
|
||||
promise = connection.sendRequest(ConfigurationRequest.type, configRequestParam).then(s => s[0]);
|
||||
documentSettings[textDocument.uri] = promise;
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
return Promise.resolve(undefined);
|
||||
}
|
||||
|
||||
// The settings have changed. Is send on server activation as well.
|
||||
connection.onDidChangeConfiguration(change => {
|
||||
updateConfiguration(<Settings>change.settings);
|
||||
});
|
||||
|
||||
function updateConfiguration(settings: Settings) {
|
||||
for (const languageId in languageServices) {
|
||||
languageServices[languageId].configure((settings as any)[languageId]);
|
||||
}
|
||||
// reset all document settings
|
||||
documentSettings = {};
|
||||
// Revalidate any open text documents
|
||||
documents.all().forEach(triggerValidation);
|
||||
}
|
||||
|
||||
const pendingValidationRequests: { [uri: string]: NodeJS.Timer } = {};
|
||||
const validationDelayMs = 500;
|
||||
|
||||
// The content of a text document has changed. This event is emitted
|
||||
// when the text document first opened or when its content has changed.
|
||||
documents.onDidChangeContent(change => {
|
||||
triggerValidation(change.document);
|
||||
});
|
||||
|
||||
// a document has closed: clear all diagnostics
|
||||
documents.onDidClose(event => {
|
||||
cleanPendingValidation(event.document);
|
||||
connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
|
||||
});
|
||||
|
||||
function cleanPendingValidation(textDocument: TextDocument): void {
|
||||
const request = pendingValidationRequests[textDocument.uri];
|
||||
if (request) {
|
||||
clearTimeout(request);
|
||||
delete pendingValidationRequests[textDocument.uri];
|
||||
}
|
||||
}
|
||||
|
||||
function triggerValidation(textDocument: TextDocument): void {
|
||||
cleanPendingValidation(textDocument);
|
||||
pendingValidationRequests[textDocument.uri] = setTimeout(() => {
|
||||
delete pendingValidationRequests[textDocument.uri];
|
||||
validateTextDocument(textDocument);
|
||||
}, validationDelayMs);
|
||||
}
|
||||
|
||||
function validateTextDocument(textDocument: TextDocument): void {
|
||||
const settingsPromise = getDocumentSettings(textDocument);
|
||||
Promise.all([settingsPromise, dataProvidersReady]).then(async ([settings]) => {
|
||||
const stylesheet = stylesheets.get(textDocument);
|
||||
const diagnostics = getLanguageService(textDocument).doValidation(textDocument, stylesheet, settings);
|
||||
// Send the computed diagnostics to VSCode.
|
||||
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
|
||||
}, e => {
|
||||
connection.console.error(formatError(`Error while validating ${textDocument.uri}`, e));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function updateDataProviders(dataPaths: string[]) {
|
||||
dataProvidersReady = fetchDataProviders(dataPaths, requestService).then(customDataProviders => {
|
||||
for (const lang in languageServices) {
|
||||
languageServices[lang].setDataProviders(true, customDataProviders);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
connection.onCompletion((textDocumentPosition, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(textDocumentPosition.textDocument.uri);
|
||||
if (!document) {
|
||||
return null;
|
||||
}
|
||||
await dataProvidersReady;
|
||||
const cssLS = getLanguageService(document);
|
||||
const participant = new PathCompletionParticipant(requestService);
|
||||
cssLS.setCompletionParticipants([participant]);
|
||||
|
||||
const result = cssLS.doComplete(document, textDocumentPosition.position, stylesheets.get(document));
|
||||
const documentContext = getDocumentContext(document.uri, workspaceFolders);
|
||||
const pathCompletionResult = await participant.computeCompletions(document, documentContext);
|
||||
return {
|
||||
isIncomplete: result.isIncomplete || pathCompletionResult.isIncomplete,
|
||||
items: pathCompletionResult.items.concat(result.items)
|
||||
};
|
||||
}, null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onHover((textDocumentPosition, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(textDocumentPosition.textDocument.uri);
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
const styleSheet = stylesheets.get(document);
|
||||
return getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet);
|
||||
}
|
||||
return null;
|
||||
}, null, `Error while computing hover for ${textDocumentPosition.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onDocumentSymbol((documentSymbolParams, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(documentSymbolParams.textDocument.uri);
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDocumentSymbols(document, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onDefinition((documentDefinitionParams, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(documentDefinitionParams.textDocument.uri);
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDefinition(document, documentDefinitionParams.position, stylesheet);
|
||||
}
|
||||
return null;
|
||||
}, null, `Error while computing definitions for ${documentDefinitionParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onDocumentHighlight((documentHighlightParams, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(documentHighlightParams.textDocument.uri);
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDocumentHighlights(document, documentHighlightParams.position, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing document highlights for ${documentHighlightParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
|
||||
connection.onDocumentLinks(async (documentLinkParams, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(documentLinkParams.textDocument.uri);
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
const documentContext = getDocumentContext(document.uri, workspaceFolders);
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDocumentLinks2(document, stylesheet, documentContext);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing document links for ${documentLinkParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
|
||||
connection.onReferences((referenceParams, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(referenceParams.textDocument.uri);
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findReferences(document, referenceParams.position, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing references for ${referenceParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onCodeAction((codeActionParams, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(codeActionParams.textDocument.uri);
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing code actions for ${codeActionParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onDocumentColor((params, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(params.textDocument.uri);
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDocumentColors(document, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing document colors for ${params.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onColorPresentation((params, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(params.textDocument.uri);
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).getColorPresentations(document, stylesheet, params.color, params.range);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing color presentations for ${params.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onRenameRequest((renameParameters, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(renameParameters.textDocument.uri);
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet);
|
||||
}
|
||||
return null;
|
||||
}, null, `Error while computing renames for ${renameParameters.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onFoldingRanges((params, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(params.textDocument.uri);
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
return getLanguageService(document).getFoldingRanges(document, { rangeLimit: foldingRangeLimit });
|
||||
}
|
||||
return null;
|
||||
}, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onSelectionRanges((params, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(params.textDocument.uri);
|
||||
const positions: Position[] = params.positions;
|
||||
|
||||
if (document) {
|
||||
await dataProvidersReady;
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).getSelectionRanges(document, positions, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onNotification(CustomDataChangedNotification.type, updateDataProviders);
|
||||
|
||||
// Listen on the connection
|
||||
connection.listen();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,390 +0,0 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import {
|
||||
createConnection, IConnection, TextDocuments, InitializeParams, InitializeResult, ServerCapabilities, ConfigurationRequest, WorkspaceFolder, TextDocumentSyncKind
|
||||
} from 'vscode-languageserver';
|
||||
import { URI } from 'vscode-uri';
|
||||
import { stat as fsStat } from 'fs';
|
||||
import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet, FileSystemProvider, FileType, TextDocument, CompletionList, Position } from 'vscode-css-languageservice';
|
||||
import { getLanguageModelCache } from './languageModelCache';
|
||||
import { getPathCompletionParticipant } from './pathCompletion';
|
||||
import { formatError, runSafe, runSafeAsync } from './utils/runner';
|
||||
import { getDocumentContext } from './utils/documentContext';
|
||||
import { getDataProviders } from './customData';
|
||||
|
||||
export interface Settings {
|
||||
css: LanguageSettings;
|
||||
less: LanguageSettings;
|
||||
scss: LanguageSettings;
|
||||
}
|
||||
|
||||
// Create a connection for the server.
|
||||
const connection: IConnection = createConnection();
|
||||
|
||||
console.log = connection.console.log.bind(connection.console);
|
||||
console.error = connection.console.error.bind(connection.console);
|
||||
|
||||
process.on('unhandledRejection', (e: any) => {
|
||||
connection.console.error(formatError(`Unhandled exception`, e));
|
||||
});
|
||||
|
||||
// Create a text document manager.
|
||||
const documents = new TextDocuments(TextDocument);
|
||||
// Make the text document manager listen on the connection
|
||||
// for open, change and close text document events
|
||||
documents.listen(connection);
|
||||
|
||||
const stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document));
|
||||
documents.onDidClose(e => {
|
||||
stylesheets.onDocumentRemoved(e.document);
|
||||
});
|
||||
connection.onShutdown(() => {
|
||||
stylesheets.dispose();
|
||||
});
|
||||
|
||||
let scopedSettingsSupport = false;
|
||||
let foldingRangeLimit = Number.MAX_VALUE;
|
||||
let workspaceFolders: WorkspaceFolder[];
|
||||
|
||||
const languageServices: { [id: string]: LanguageService } = {};
|
||||
|
||||
const fileSystemProvider: FileSystemProvider = {
|
||||
stat(documentUri: string) {
|
||||
const filePath = URI.parse(documentUri).fsPath;
|
||||
|
||||
return new Promise((c, e) => {
|
||||
fsStat(filePath, (err, stats) => {
|
||||
if (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
return c({
|
||||
type: FileType.Unknown,
|
||||
ctime: -1,
|
||||
mtime: -1,
|
||||
size: -1
|
||||
});
|
||||
} else {
|
||||
return e(err);
|
||||
}
|
||||
}
|
||||
|
||||
let type = FileType.Unknown;
|
||||
if (stats.isFile()) {
|
||||
type = FileType.File;
|
||||
} else if (stats.isDirectory()) {
|
||||
type = FileType.Directory;
|
||||
} else if (stats.isSymbolicLink()) {
|
||||
type = FileType.SymbolicLink;
|
||||
}
|
||||
|
||||
c({
|
||||
type,
|
||||
ctime: stats.ctime.getTime(),
|
||||
mtime: stats.mtime.getTime(),
|
||||
size: stats.size
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// After the server has started the client sends an initialize request. The server receives
|
||||
// in the passed params the rootPath of the workspace plus the client capabilities.
|
||||
connection.onInitialize((params: InitializeParams): InitializeResult => {
|
||||
workspaceFolders = (<any>params).workspaceFolders;
|
||||
if (!Array.isArray(workspaceFolders)) {
|
||||
workspaceFolders = [];
|
||||
if (params.rootPath) {
|
||||
workspaceFolders.push({ name: '', uri: URI.file(params.rootPath).toString() });
|
||||
}
|
||||
}
|
||||
|
||||
const dataPaths: string[] = params.initializationOptions.dataPaths || [];
|
||||
const customDataProviders = getDataProviders(dataPaths);
|
||||
|
||||
function getClientCapability<T>(name: string, def: T) {
|
||||
const keys = name.split('.');
|
||||
let c: any = params.capabilities;
|
||||
for (let i = 0; c && i < keys.length; i++) {
|
||||
if (!c.hasOwnProperty(keys[i])) {
|
||||
return def;
|
||||
}
|
||||
c = c[keys[i]];
|
||||
}
|
||||
return c;
|
||||
}
|
||||
const snippetSupport = !!getClientCapability('textDocument.completion.completionItem.snippetSupport', false);
|
||||
scopedSettingsSupport = !!getClientCapability('workspace.configuration', false);
|
||||
foldingRangeLimit = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE);
|
||||
|
||||
languageServices.css = getCSSLanguageService({ customDataProviders, fileSystemProvider, clientCapabilities: params.capabilities });
|
||||
languageServices.scss = getSCSSLanguageService({ customDataProviders, fileSystemProvider, clientCapabilities: params.capabilities });
|
||||
languageServices.less = getLESSLanguageService({ customDataProviders, fileSystemProvider, clientCapabilities: params.capabilities });
|
||||
|
||||
const capabilities: ServerCapabilities = {
|
||||
textDocumentSync: TextDocumentSyncKind.Incremental,
|
||||
completionProvider: snippetSupport ? { resolveProvider: false, triggerCharacters: ['/', '-'] } : undefined,
|
||||
hoverProvider: true,
|
||||
documentSymbolProvider: true,
|
||||
referencesProvider: true,
|
||||
definitionProvider: true,
|
||||
documentHighlightProvider: true,
|
||||
documentLinkProvider: {
|
||||
resolveProvider: false
|
||||
},
|
||||
codeActionProvider: true,
|
||||
renameProvider: true,
|
||||
colorProvider: {},
|
||||
foldingRangeProvider: true,
|
||||
selectionRangeProvider: true
|
||||
};
|
||||
return { capabilities };
|
||||
});
|
||||
|
||||
function getLanguageService(document: TextDocument) {
|
||||
let service = languageServices[document.languageId];
|
||||
if (!service) {
|
||||
connection.console.log('Document type is ' + document.languageId + ', using css instead.');
|
||||
service = languageServices['css'];
|
||||
}
|
||||
return service;
|
||||
}
|
||||
|
||||
let documentSettings: { [key: string]: Thenable<LanguageSettings | undefined> } = {};
|
||||
// remove document settings on close
|
||||
documents.onDidClose(e => {
|
||||
delete documentSettings[e.document.uri];
|
||||
});
|
||||
function getDocumentSettings(textDocument: TextDocument): Thenable<LanguageSettings | undefined> {
|
||||
if (scopedSettingsSupport) {
|
||||
let promise = documentSettings[textDocument.uri];
|
||||
if (!promise) {
|
||||
const configRequestParam = { items: [{ scopeUri: textDocument.uri, section: textDocument.languageId }] };
|
||||
promise = connection.sendRequest(ConfigurationRequest.type, configRequestParam).then(s => s[0]);
|
||||
documentSettings[textDocument.uri] = promise;
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
return Promise.resolve(undefined);
|
||||
}
|
||||
|
||||
// The settings have changed. Is send on server activation as well.
|
||||
connection.onDidChangeConfiguration(change => {
|
||||
updateConfiguration(<Settings>change.settings);
|
||||
});
|
||||
|
||||
function updateConfiguration(settings: Settings) {
|
||||
for (const languageId in languageServices) {
|
||||
languageServices[languageId].configure((settings as any)[languageId]);
|
||||
}
|
||||
// reset all document settings
|
||||
documentSettings = {};
|
||||
// Revalidate any open text documents
|
||||
documents.all().forEach(triggerValidation);
|
||||
}
|
||||
|
||||
const pendingValidationRequests: { [uri: string]: NodeJS.Timer } = {};
|
||||
const validationDelayMs = 500;
|
||||
|
||||
// The content of a text document has changed. This event is emitted
|
||||
// when the text document first opened or when its content has changed.
|
||||
documents.onDidChangeContent(change => {
|
||||
triggerValidation(change.document);
|
||||
});
|
||||
|
||||
// a document has closed: clear all diagnostics
|
||||
documents.onDidClose(event => {
|
||||
cleanPendingValidation(event.document);
|
||||
connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
|
||||
});
|
||||
|
||||
function cleanPendingValidation(textDocument: TextDocument): void {
|
||||
const request = pendingValidationRequests[textDocument.uri];
|
||||
if (request) {
|
||||
clearTimeout(request);
|
||||
delete pendingValidationRequests[textDocument.uri];
|
||||
}
|
||||
}
|
||||
|
||||
function triggerValidation(textDocument: TextDocument): void {
|
||||
cleanPendingValidation(textDocument);
|
||||
pendingValidationRequests[textDocument.uri] = setTimeout(() => {
|
||||
delete pendingValidationRequests[textDocument.uri];
|
||||
validateTextDocument(textDocument);
|
||||
}, validationDelayMs);
|
||||
}
|
||||
|
||||
function validateTextDocument(textDocument: TextDocument): void {
|
||||
const settingsPromise = getDocumentSettings(textDocument);
|
||||
settingsPromise.then(settings => {
|
||||
const stylesheet = stylesheets.get(textDocument);
|
||||
const diagnostics = getLanguageService(textDocument).doValidation(textDocument, stylesheet, settings);
|
||||
// Send the computed diagnostics to VSCode.
|
||||
connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
|
||||
}, e => {
|
||||
connection.console.error(formatError(`Error while validating ${textDocument.uri}`, e));
|
||||
});
|
||||
}
|
||||
|
||||
connection.onCompletion((textDocumentPosition, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(textDocumentPosition.textDocument.uri);
|
||||
if (!document) {
|
||||
return null;
|
||||
}
|
||||
const cssLS = getLanguageService(document);
|
||||
const pathCompletionList: CompletionList = {
|
||||
isIncomplete: false,
|
||||
items: []
|
||||
};
|
||||
cssLS.setCompletionParticipants([getPathCompletionParticipant(document, workspaceFolders, pathCompletionList)]);
|
||||
const result = cssLS.doComplete(document, textDocumentPosition.position, stylesheets.get(document));
|
||||
return {
|
||||
isIncomplete: pathCompletionList.isIncomplete,
|
||||
items: [...pathCompletionList.items, ...result.items]
|
||||
};
|
||||
}, null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onHover((textDocumentPosition, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(textDocumentPosition.textDocument.uri);
|
||||
if (document) {
|
||||
const styleSheet = stylesheets.get(document);
|
||||
return getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet);
|
||||
}
|
||||
return null;
|
||||
}, null, `Error while computing hover for ${textDocumentPosition.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onDocumentSymbol((documentSymbolParams, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(documentSymbolParams.textDocument.uri);
|
||||
if (document) {
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDocumentSymbols(document, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onDefinition((documentDefinitionParams, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(documentDefinitionParams.textDocument.uri);
|
||||
if (document) {
|
||||
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDefinition(document, documentDefinitionParams.position, stylesheet);
|
||||
}
|
||||
return null;
|
||||
}, null, `Error while computing definitions for ${documentDefinitionParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onDocumentHighlight((documentHighlightParams, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(documentHighlightParams.textDocument.uri);
|
||||
if (document) {
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDocumentHighlights(document, documentHighlightParams.position, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing document highlights for ${documentHighlightParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
|
||||
connection.onDocumentLinks(async (documentLinkParams, token) => {
|
||||
return runSafeAsync(async () => {
|
||||
const document = documents.get(documentLinkParams.textDocument.uri);
|
||||
if (document) {
|
||||
const documentContext = getDocumentContext(document.uri, workspaceFolders);
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return await getLanguageService(document).findDocumentLinks2(document, stylesheet, documentContext);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing document links for ${documentLinkParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
|
||||
connection.onReferences((referenceParams, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(referenceParams.textDocument.uri);
|
||||
if (document) {
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findReferences(document, referenceParams.position, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing references for ${referenceParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onCodeAction((codeActionParams, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(codeActionParams.textDocument.uri);
|
||||
if (document) {
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing code actions for ${codeActionParams.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onDocumentColor((params, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(params.textDocument.uri);
|
||||
if (document) {
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).findDocumentColors(document, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing document colors for ${params.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onColorPresentation((params, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(params.textDocument.uri);
|
||||
if (document) {
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).getColorPresentations(document, stylesheet, params.color, params.range);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing color presentations for ${params.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onRenameRequest((renameParameters, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(renameParameters.textDocument.uri);
|
||||
if (document) {
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet);
|
||||
}
|
||||
return null;
|
||||
}, null, `Error while computing renames for ${renameParameters.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onFoldingRanges((params, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(params.textDocument.uri);
|
||||
if (document) {
|
||||
return getLanguageService(document).getFoldingRanges(document, { rangeLimit: foldingRangeLimit });
|
||||
}
|
||||
return null;
|
||||
}, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
connection.onSelectionRanges((params, token) => {
|
||||
return runSafe(() => {
|
||||
const document = documents.get(params.textDocument.uri);
|
||||
const positions: Position[] = params.positions;
|
||||
|
||||
if (document) {
|
||||
const stylesheet = stylesheets.get(document);
|
||||
return getLanguageService(document).getSelectionRanges(document, positions, stylesheet);
|
||||
}
|
||||
return [];
|
||||
}, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token);
|
||||
});
|
||||
|
||||
|
||||
// Listen on the connection
|
||||
connection.listen();
|
||||
@@ -3,48 +3,36 @@
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { CSSDataV1, ICSSDataProvider } from 'vscode-css-languageservice';
|
||||
import * as fs from 'fs';
|
||||
import { ICSSDataProvider, newCSSDataProvider } from 'vscode-css-languageservice';
|
||||
import { RequestService } from './requests';
|
||||
|
||||
export function getDataProviders(dataPaths: string[]): ICSSDataProvider[] {
|
||||
const providers = dataPaths.map(p => {
|
||||
if (fs.existsSync(p)) {
|
||||
const data = parseCSSData(fs.readFileSync(p, 'utf-8'));
|
||||
return {
|
||||
provideProperties: () => data.properties || [],
|
||||
provideAtDirectives: () => data.atDirectives || [],
|
||||
providePseudoClasses: () => data.pseudoClasses || [],
|
||||
providePseudoElements: () => data.pseudoElements || []
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
provideProperties: () => [],
|
||||
provideAtDirectives: () => [],
|
||||
providePseudoClasses: () => [],
|
||||
providePseudoElements: () => []
|
||||
};
|
||||
export function fetchDataProviders(dataPaths: string[], requestService: RequestService): Promise<ICSSDataProvider[]> {
|
||||
const providers = dataPaths.map(async p => {
|
||||
try {
|
||||
const content = await requestService.getContent(p);
|
||||
return parseCSSData(content);
|
||||
} catch (e) {
|
||||
return newCSSDataProvider({ version: 1 });
|
||||
}
|
||||
});
|
||||
|
||||
return providers;
|
||||
return Promise.all(providers);
|
||||
}
|
||||
|
||||
function parseCSSData(source: string): CSSDataV1 {
|
||||
function parseCSSData(source: string): ICSSDataProvider {
|
||||
let rawData: any;
|
||||
|
||||
try {
|
||||
rawData = JSON.parse(source);
|
||||
} catch (err) {
|
||||
return {
|
||||
version: 1
|
||||
};
|
||||
return newCSSDataProvider({ version: 1 });
|
||||
}
|
||||
|
||||
return {
|
||||
return newCSSDataProvider({
|
||||
version: 1,
|
||||
properties: rawData.properties || [],
|
||||
atDirectives: rawData.atDirectives || [],
|
||||
pseudoClasses: rawData.pseudoClasses || [],
|
||||
pseudoElements: rawData.pseudoElements || []
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { IConnection, createConnection } from 'vscode-languageserver';
|
||||
import { formatError } from '../utils/runner';
|
||||
import { startServer } from '../cssServer';
|
||||
import { getNodeFSRequestService } from './nodeFs';
|
||||
|
||||
// Create a connection for the server.
|
||||
const connection: IConnection = createConnection();
|
||||
|
||||
console.log = connection.console.log.bind(connection.console);
|
||||
console.error = connection.console.error.bind(connection.console);
|
||||
|
||||
process.on('unhandledRejection', (e: any) => {
|
||||
connection.console.error(formatError(`Unhandled exception`, e));
|
||||
});
|
||||
|
||||
startServer(connection, { file: getNodeFSRequestService() });
|
||||
87
extensions/css-language-features/server/src/node/nodeFs.ts
Normal file
87
extensions/css-language-features/server/src/node/nodeFs.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { RequestService, getScheme } from '../requests';
|
||||
import { URI as Uri } from 'vscode-uri';
|
||||
|
||||
import * as fs from 'fs';
|
||||
import { FileType } from 'vscode-css-languageservice';
|
||||
|
||||
export function getNodeFSRequestService(): RequestService {
|
||||
function ensureFileUri(location: string) {
|
||||
if (getScheme(location) !== 'file') {
|
||||
throw new Error('fileRequestService can only handle file URLs');
|
||||
}
|
||||
}
|
||||
return {
|
||||
getContent(location: string, encoding?: string) {
|
||||
ensureFileUri(location);
|
||||
return new Promise((c, e) => {
|
||||
const uri = Uri.parse(location);
|
||||
fs.readFile(uri.fsPath, encoding, (err, buf) => {
|
||||
if (err) {
|
||||
return e(err);
|
||||
}
|
||||
c(buf.toString());
|
||||
|
||||
});
|
||||
});
|
||||
},
|
||||
stat(location: string) {
|
||||
ensureFileUri(location);
|
||||
return new Promise((c, e) => {
|
||||
const uri = Uri.parse(location);
|
||||
fs.stat(uri.fsPath, (err, stats) => {
|
||||
if (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
return c({ type: FileType.Unknown, ctime: -1, mtime: -1, size: -1 });
|
||||
} else {
|
||||
return e(err);
|
||||
}
|
||||
}
|
||||
|
||||
let type = FileType.Unknown;
|
||||
if (stats.isFile()) {
|
||||
type = FileType.File;
|
||||
} else if (stats.isDirectory()) {
|
||||
type = FileType.Directory;
|
||||
} else if (stats.isSymbolicLink()) {
|
||||
type = FileType.SymbolicLink;
|
||||
}
|
||||
|
||||
c({
|
||||
type,
|
||||
ctime: stats.ctime.getTime(),
|
||||
mtime: stats.mtime.getTime(),
|
||||
size: stats.size
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
readDirectory(location: string) {
|
||||
ensureFileUri(location);
|
||||
return new Promise((c, e) => {
|
||||
const path = Uri.parse(location).fsPath;
|
||||
|
||||
fs.readdir(path, { withFileTypes: true }, (err, children) => {
|
||||
if (err) {
|
||||
return e(err);
|
||||
}
|
||||
c(children.map(stat => {
|
||||
if (stat.isSymbolicLink()) {
|
||||
return [stat.name, FileType.SymbolicLink];
|
||||
} else if (stat.isDirectory()) {
|
||||
return [stat.name, FileType.Directory];
|
||||
} else if (stat.isFile()) {
|
||||
return [stat.name, FileType.File];
|
||||
} else {
|
||||
return [stat.name, FileType.Unknown];
|
||||
}
|
||||
}));
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -3,101 +3,104 @@
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import { URI } from 'vscode-uri';
|
||||
|
||||
import { TextDocument, CompletionList, CompletionItemKind, CompletionItem, TextEdit, Range, Position } from 'vscode-languageserver-types';
|
||||
import { WorkspaceFolder } from 'vscode-languageserver';
|
||||
import { ICompletionParticipant } from 'vscode-css-languageservice';
|
||||
import { ICompletionParticipant, URILiteralCompletionContext, ImportPathCompletionContext, FileType, DocumentContext } from 'vscode-css-languageservice';
|
||||
|
||||
import { startsWith, endsWith } from './utils/strings';
|
||||
import { joinPath, RequestService } from './requests';
|
||||
|
||||
export function getPathCompletionParticipant(
|
||||
document: TextDocument,
|
||||
workspaceFolders: WorkspaceFolder[],
|
||||
result: CompletionList
|
||||
): ICompletionParticipant {
|
||||
return {
|
||||
onCssURILiteralValue: ({ position, range, uriValue }) => {
|
||||
const fullValue = stripQuotes(uriValue);
|
||||
if (!shouldDoPathCompletion(uriValue, workspaceFolders)) {
|
||||
if (fullValue === '.' || fullValue === '..') {
|
||||
result.isIncomplete = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
export class PathCompletionParticipant implements ICompletionParticipant {
|
||||
private literalCompletions: URILiteralCompletionContext[] = [];
|
||||
private importCompletions: ImportPathCompletionContext[] = [];
|
||||
|
||||
let suggestions = providePathSuggestions(uriValue, position, range, document, workspaceFolders);
|
||||
result.items = [...suggestions, ...result.items];
|
||||
},
|
||||
onCssImportPath: ({ position, range, pathValue }) => {
|
||||
const fullValue = stripQuotes(pathValue);
|
||||
if (!shouldDoPathCompletion(pathValue, workspaceFolders)) {
|
||||
if (fullValue === '.' || fullValue === '..') {
|
||||
result.isIncomplete = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
constructor(private readonly requestService: RequestService) {
|
||||
}
|
||||
|
||||
let suggestions = providePathSuggestions(pathValue, position, range, document, workspaceFolders);
|
||||
public onCssURILiteralValue(context: URILiteralCompletionContext) {
|
||||
this.literalCompletions.push(context);
|
||||
}
|
||||
|
||||
if (document.languageId === 'scss') {
|
||||
suggestions.forEach(s => {
|
||||
if (startsWith(s.label, '_') && endsWith(s.label, '.scss')) {
|
||||
if (s.textEdit) {
|
||||
s.textEdit.newText = s.label.slice(1, -5);
|
||||
} else {
|
||||
s.label = s.label.slice(1, -5);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
public onCssImportPath(context: ImportPathCompletionContext) {
|
||||
this.importCompletions.push(context);
|
||||
}
|
||||
|
||||
result.items = [...suggestions, ...result.items];
|
||||
public async computeCompletions(document: TextDocument, documentContext: DocumentContext): Promise<CompletionList> {
|
||||
const result: CompletionList = { items: [], isIncomplete: false };
|
||||
if (!(startsWith(document.uri, 'file:'))) {
|
||||
return result;
|
||||
}
|
||||
};
|
||||
}
|
||||
for (const literalCompletion of this.literalCompletions) {
|
||||
const uriValue = literalCompletion.uriValue;
|
||||
const fullValue = stripQuotes(uriValue);
|
||||
if (fullValue === '.' || fullValue === '..') {
|
||||
result.isIncomplete = true;
|
||||
} else {
|
||||
const items = await this.providePathSuggestions(uriValue, literalCompletion.position, literalCompletion.range, document, documentContext);
|
||||
for (let item of items) {
|
||||
result.items.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const importCompletion of this.importCompletions) {
|
||||
const pathValue = importCompletion.pathValue;
|
||||
const fullValue = stripQuotes(pathValue);
|
||||
if (fullValue === '.' || fullValue === '..') {
|
||||
result.isIncomplete = true;
|
||||
} else {
|
||||
let suggestions = await this.providePathSuggestions(pathValue, importCompletion.position, importCompletion.range, document, documentContext);
|
||||
|
||||
function providePathSuggestions(pathValue: string, position: Position, range: Range, document: TextDocument, workspaceFolders: WorkspaceFolder[]) {
|
||||
const fullValue = stripQuotes(pathValue);
|
||||
const isValueQuoted = startsWith(pathValue, `'`) || startsWith(pathValue, `"`);
|
||||
const valueBeforeCursor = isValueQuoted
|
||||
? fullValue.slice(0, position.character - (range.start.character + 1))
|
||||
: fullValue.slice(0, position.character - range.start.character);
|
||||
const workspaceRoot = resolveWorkspaceRoot(document, workspaceFolders);
|
||||
const currentDocFsPath = URI.parse(document.uri).fsPath;
|
||||
|
||||
const paths = providePaths(valueBeforeCursor, currentDocFsPath, workspaceRoot)
|
||||
.filter(p => {
|
||||
// Exclude current doc's path
|
||||
return path.resolve(currentDocFsPath, '../', p) !== currentDocFsPath;
|
||||
})
|
||||
.filter(p => {
|
||||
// Exclude paths that start with `.`
|
||||
return p[0] !== '.';
|
||||
});
|
||||
|
||||
const fullValueRange = isValueQuoted ? shiftRange(range, 1, -1) : range;
|
||||
const replaceRange = pathToReplaceRange(valueBeforeCursor, fullValue, fullValueRange);
|
||||
|
||||
const suggestions = paths.map(p => pathToSuggestion(p, replaceRange));
|
||||
return suggestions;
|
||||
}
|
||||
|
||||
function shouldDoPathCompletion(pathValue: string, workspaceFolders: WorkspaceFolder[]): boolean {
|
||||
const fullValue = stripQuotes(pathValue);
|
||||
if (fullValue === '.' || fullValue === '..') {
|
||||
return false;
|
||||
if (document.languageId === 'scss') {
|
||||
suggestions.forEach(s => {
|
||||
if (startsWith(s.label, '_') && endsWith(s.label, '.scss')) {
|
||||
if (s.textEdit) {
|
||||
s.textEdit.newText = s.label.slice(1, -5);
|
||||
} else {
|
||||
s.label = s.label.slice(1, -5);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
for (let item of suggestions) {
|
||||
result.items.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
if (!workspaceFolders || workspaceFolders.length === 0) {
|
||||
return false;
|
||||
}
|
||||
private async providePathSuggestions(pathValue: string, position: Position, range: Range, document: TextDocument, documentContext: DocumentContext): Promise<CompletionItem[]> {
|
||||
const fullValue = stripQuotes(pathValue);
|
||||
const isValueQuoted = startsWith(pathValue, `'`) || startsWith(pathValue, `"`);
|
||||
const valueBeforeCursor = isValueQuoted
|
||||
? fullValue.slice(0, position.character - (range.start.character + 1))
|
||||
: fullValue.slice(0, position.character - range.start.character);
|
||||
|
||||
return true;
|
||||
const currentDocUri = document.uri;
|
||||
|
||||
const fullValueRange = isValueQuoted ? shiftRange(range, 1, -1) : range;
|
||||
const replaceRange = pathToReplaceRange(valueBeforeCursor, fullValue, fullValueRange);
|
||||
|
||||
const valueBeforeLastSlash = valueBeforeCursor.substring(0, valueBeforeCursor.lastIndexOf('/') + 1); // keep the last slash
|
||||
|
||||
let parentDir = documentContext.resolveReference(valueBeforeLastSlash || '.', currentDocUri);
|
||||
try {
|
||||
const result: CompletionItem[] = [];
|
||||
const infos = await this.requestService.readDirectory(parentDir);
|
||||
for (const [name, type] of infos) {
|
||||
// Exclude paths that start with `.`
|
||||
if (name.charCodeAt(0) !== CharCode_dot && (type === FileType.Directory || joinPath(parentDir, name) !== currentDocUri)) {
|
||||
result.push(createCompletionItem(name, type === FileType.Directory, replaceRange));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const CharCode_dot = '.'.charCodeAt(0);
|
||||
|
||||
function stripQuotes(fullValue: string) {
|
||||
if (startsWith(fullValue, `'`) || startsWith(fullValue, `"`)) {
|
||||
return fullValue.slice(1, -1);
|
||||
@@ -106,43 +109,6 @@ function stripQuotes(fullValue: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of path suggestions. Folder suggestions are suffixed with a slash.
|
||||
*/
|
||||
function providePaths(valueBeforeCursor: string, activeDocFsPath: string, root?: string): string[] {
|
||||
const lastIndexOfSlash = valueBeforeCursor.lastIndexOf('/');
|
||||
const valueBeforeLastSlash = valueBeforeCursor.slice(0, lastIndexOfSlash + 1);
|
||||
|
||||
const startsWithSlash = startsWith(valueBeforeCursor, '/');
|
||||
let parentDir: string;
|
||||
if (startsWithSlash) {
|
||||
if (!root) {
|
||||
return [];
|
||||
}
|
||||
parentDir = path.resolve(root, '.' + valueBeforeLastSlash);
|
||||
} else {
|
||||
parentDir = path.resolve(activeDocFsPath, '..', valueBeforeLastSlash);
|
||||
}
|
||||
|
||||
try {
|
||||
return fs.readdirSync(parentDir).map(f => {
|
||||
return isDir(path.resolve(parentDir, f))
|
||||
? f + '/'
|
||||
: f;
|
||||
});
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const isDir = (p: string) => {
|
||||
try {
|
||||
return fs.statSync(p).isDirectory();
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
function pathToReplaceRange(valueBeforeCursor: string, fullValue: string, fullValueRange: Range) {
|
||||
let replaceRange: Range;
|
||||
const lastIndexOfSlash = valueBeforeCursor.lastIndexOf('/');
|
||||
@@ -167,14 +133,13 @@ function pathToReplaceRange(valueBeforeCursor: string, fullValue: string, fullVa
|
||||
return replaceRange;
|
||||
}
|
||||
|
||||
function pathToSuggestion(p: string, replaceRange: Range): CompletionItem {
|
||||
const isDir = p[p.length - 1] === '/';
|
||||
|
||||
function createCompletionItem(name: string, isDir: boolean, replaceRange: Range): CompletionItem {
|
||||
if (isDir) {
|
||||
name = name + '/';
|
||||
return {
|
||||
label: escapePath(p),
|
||||
label: escapePath(name),
|
||||
kind: CompletionItemKind.Folder,
|
||||
textEdit: TextEdit.replace(replaceRange, escapePath(p)),
|
||||
textEdit: TextEdit.replace(replaceRange, escapePath(name)),
|
||||
command: {
|
||||
title: 'Suggest',
|
||||
command: 'editor.action.triggerSuggest'
|
||||
@@ -182,9 +147,9 @@ function pathToSuggestion(p: string, replaceRange: Range): CompletionItem {
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
label: escapePath(p),
|
||||
label: escapePath(name),
|
||||
kind: CompletionItemKind.File,
|
||||
textEdit: TextEdit.replace(replaceRange, escapePath(p))
|
||||
textEdit: TextEdit.replace(replaceRange, escapePath(name))
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -193,16 +158,6 @@ function pathToSuggestion(p: string, replaceRange: Range): CompletionItem {
|
||||
function escapePath(p: string) {
|
||||
return p.replace(/(\s|\(|\)|,|"|')/g, '\\$1');
|
||||
}
|
||||
|
||||
function resolveWorkspaceRoot(activeDoc: TextDocument, workspaceFolders: WorkspaceFolder[]): string | undefined {
|
||||
for (const folder of workspaceFolders) {
|
||||
if (startsWith(activeDoc.uri, folder.uri)) {
|
||||
return path.resolve(URI.parse(folder.uri).fsPath);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function shiftPosition(pos: Position, offset: number): Position {
|
||||
return Position.create(pos.line, pos.character + offset);
|
||||
}
|
||||
@@ -211,3 +166,4 @@ function shiftRange(range: Range, startOffset: number, endOffset: number): Range
|
||||
const end = shiftPosition(range.end, endOffset);
|
||||
return Range.create(start, end);
|
||||
}
|
||||
|
||||
|
||||
127
extensions/css-language-features/server/src/requests.ts
Normal file
127
extensions/css-language-features/server/src/requests.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { URI } from 'vscode-uri';
|
||||
import { endsWith, startsWith } from './utils/strings';
|
||||
import { RequestType, IConnection } from 'vscode-languageserver';
|
||||
import { RuntimeEnvironment } from './cssServer';
|
||||
|
||||
export namespace FsContentRequest {
|
||||
export const type: RequestType<{ uri: string; encoding?: string; }, string, any, any> = new RequestType('fs/content');
|
||||
}
|
||||
export namespace FsStatRequest {
|
||||
export const type: RequestType<string, FileStat, any, any> = new RequestType('fs/stat');
|
||||
}
|
||||
|
||||
export namespace FsReadDirRequest {
|
||||
export const type: RequestType<string, [string, FileType][], any, any> = new RequestType('fs/readDir');
|
||||
}
|
||||
|
||||
export enum FileType {
|
||||
/**
|
||||
* The file type is unknown.
|
||||
*/
|
||||
Unknown = 0,
|
||||
/**
|
||||
* A regular file.
|
||||
*/
|
||||
File = 1,
|
||||
/**
|
||||
* A directory.
|
||||
*/
|
||||
Directory = 2,
|
||||
/**
|
||||
* A symbolic link to a file.
|
||||
*/
|
||||
SymbolicLink = 64
|
||||
}
|
||||
export interface FileStat {
|
||||
/**
|
||||
* The type of the file, e.g. is a regular file, a directory, or symbolic link
|
||||
* to a file.
|
||||
*/
|
||||
type: FileType;
|
||||
/**
|
||||
* The creation timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC.
|
||||
*/
|
||||
ctime: number;
|
||||
/**
|
||||
* The modification timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC.
|
||||
*/
|
||||
mtime: number;
|
||||
/**
|
||||
* The size in bytes.
|
||||
*/
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface RequestService {
|
||||
getContent(uri: string, encoding?: string): Promise<string>;
|
||||
|
||||
stat(uri: string): Promise<FileStat>;
|
||||
readDirectory(uri: string): Promise<[string, FileType][]>;
|
||||
}
|
||||
|
||||
|
||||
export function getRequestService(handledSchemas: string[], connection: IConnection, runtime: RuntimeEnvironment): RequestService {
|
||||
const builtInHandlers: { [protocol: string]: RequestService | undefined } = {};
|
||||
for (let protocol of handledSchemas) {
|
||||
if (protocol === 'file') {
|
||||
builtInHandlers[protocol] = runtime.file;
|
||||
} else if (protocol === 'http' || protocol === 'https') {
|
||||
builtInHandlers[protocol] = runtime.http;
|
||||
}
|
||||
}
|
||||
return {
|
||||
async stat(uri: string): Promise<FileStat> {
|
||||
const handler = builtInHandlers[getScheme(uri)];
|
||||
if (handler) {
|
||||
return handler.stat(uri);
|
||||
}
|
||||
const res = await connection.sendRequest(FsStatRequest.type, uri.toString());
|
||||
return res;
|
||||
},
|
||||
readDirectory(uri: string): Promise<[string, FileType][]> {
|
||||
const handler = builtInHandlers[getScheme(uri)];
|
||||
if (handler) {
|
||||
return handler.readDirectory(uri);
|
||||
}
|
||||
return connection.sendRequest(FsReadDirRequest.type, uri.toString());
|
||||
},
|
||||
getContent(uri: string, encoding?: string): Promise<string> {
|
||||
const handler = builtInHandlers[getScheme(uri)];
|
||||
if (handler) {
|
||||
return handler.getContent(uri, encoding);
|
||||
}
|
||||
return connection.sendRequest(FsContentRequest.type, { uri: uri.toString(), encoding });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function getScheme(uri: string) {
|
||||
return uri.substr(0, uri.indexOf(':'));
|
||||
}
|
||||
|
||||
export function dirname(uri: string) {
|
||||
const lastIndexOfSlash = uri.lastIndexOf('/');
|
||||
return lastIndexOfSlash !== -1 ? uri.substr(0, lastIndexOfSlash) : '';
|
||||
}
|
||||
|
||||
export function basename(uri: string) {
|
||||
const lastIndexOfSlash = uri.lastIndexOf('/');
|
||||
return uri.substr(lastIndexOfSlash + 1);
|
||||
}
|
||||
|
||||
export function joinPath(uriString: string, ...paths: string[]): string {
|
||||
const uri = URI.parse(uriString);
|
||||
let uriPath = uri.path;
|
||||
for (let path of paths) {
|
||||
if (!endsWith(uriPath, '/') && !startsWith(path, '/')) {
|
||||
uriPath += '/';
|
||||
}
|
||||
uriPath += path;
|
||||
}
|
||||
return uri.with({ path: uriPath }).toString();
|
||||
}
|
||||
@@ -8,8 +8,10 @@ import * as path from 'path';
|
||||
import { URI } from 'vscode-uri';
|
||||
import { TextDocument, CompletionList } from 'vscode-languageserver-types';
|
||||
import { WorkspaceFolder } from 'vscode-languageserver-protocol';
|
||||
import { getPathCompletionParticipant } from '../pathCompletion';
|
||||
import { PathCompletionParticipant } from '../pathCompletion';
|
||||
import { getCSSLanguageService } from 'vscode-css-languageservice';
|
||||
import { getNodeFSRequestService } from '../node/nodeFs';
|
||||
import { getDocumentContext } from '../utils/documentContext';
|
||||
|
||||
export interface ItemDescription {
|
||||
label: string;
|
||||
@@ -18,6 +20,7 @@ export interface ItemDescription {
|
||||
|
||||
suite('Completions', () => {
|
||||
const cssLanguageService = getCSSLanguageService();
|
||||
const requestService = getNodeFSRequestService();
|
||||
|
||||
let assertCompletion = function (completions: CompletionList, expected: ItemDescription, document: TextDocument, _offset: number) {
|
||||
let matches = completions.items.filter(completion => {
|
||||
@@ -31,7 +34,7 @@ suite('Completions', () => {
|
||||
}
|
||||
};
|
||||
|
||||
function assertCompletions(value: string, expected: { count?: number, items?: ItemDescription[] }, testUri: string, workspaceFolders?: WorkspaceFolder[], lang: string = 'css'): void {
|
||||
async function assertCompletions(value: string, expected: { count?: number, items?: ItemDescription[] }, testUri: string, workspaceFolders?: WorkspaceFolder[], lang: string = 'css'): Promise<any> {
|
||||
const offset = value.indexOf('|');
|
||||
value = value.substr(0, offset) + value.substr(offset + 1);
|
||||
|
||||
@@ -42,11 +45,15 @@ suite('Completions', () => {
|
||||
workspaceFolders = [{ name: 'x', uri: testUri.substr(0, testUri.lastIndexOf('/')) }];
|
||||
}
|
||||
|
||||
let participantResult = CompletionList.create([]);
|
||||
cssLanguageService.setCompletionParticipants([getPathCompletionParticipant(document, workspaceFolders, participantResult)]);
|
||||
const participant = new PathCompletionParticipant(requestService);
|
||||
cssLanguageService.setCompletionParticipants([participant]);
|
||||
|
||||
const stylesheet = cssLanguageService.parseStylesheet(document);
|
||||
let list = cssLanguageService.doComplete(document, position, stylesheet)!;
|
||||
|
||||
const context = getDocumentContext(testUri, workspaceFolders);
|
||||
|
||||
let participantResult = await participant.computeCompletions(document, context);
|
||||
list.items = list.items.concat(participantResult.items);
|
||||
|
||||
if (expected.count) {
|
||||
@@ -59,17 +66,17 @@ suite('Completions', () => {
|
||||
}
|
||||
}
|
||||
|
||||
test('CSS url() Path completion', function () {
|
||||
test('CSS url() Path completion', async function () {
|
||||
let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
|
||||
assertCompletions('html { background-image: url("./|")', {
|
||||
await assertCompletions('html { background-image: url("./|")', {
|
||||
items: [
|
||||
{ label: 'about.html', resultText: 'html { background-image: url("./about.html")' }
|
||||
]
|
||||
}, testUri, folders);
|
||||
|
||||
assertCompletions(`html { background-image: url('../|')`, {
|
||||
await assertCompletions(`html { background-image: url('../|')`, {
|
||||
items: [
|
||||
{ label: 'about/', resultText: `html { background-image: url('../about/')` },
|
||||
{ label: 'index.html', resultText: `html { background-image: url('../index.html')` },
|
||||
@@ -77,7 +84,7 @@ suite('Completions', () => {
|
||||
]
|
||||
}, testUri, folders);
|
||||
|
||||
assertCompletions(`html { background-image: url('../src/a|')`, {
|
||||
await assertCompletions(`html { background-image: url('../src/a|')`, {
|
||||
items: [
|
||||
{ label: 'feature.js', resultText: `html { background-image: url('../src/feature.js')` },
|
||||
{ label: 'data/', resultText: `html { background-image: url('../src/data/')` },
|
||||
@@ -85,25 +92,25 @@ suite('Completions', () => {
|
||||
]
|
||||
}, testUri, folders);
|
||||
|
||||
assertCompletions(`html { background-image: url('../src/data/f|.asar')`, {
|
||||
await assertCompletions(`html { background-image: url('../src/data/f|.asar')`, {
|
||||
items: [
|
||||
{ label: 'foo.asar', resultText: `html { background-image: url('../src/data/foo.asar')` }
|
||||
]
|
||||
}, testUri, folders);
|
||||
|
||||
assertCompletions(`html { background-image: url('|')`, {
|
||||
await assertCompletions(`html { background-image: url('|')`, {
|
||||
items: [
|
||||
{ label: 'about.html', resultText: `html { background-image: url('about.html')` },
|
||||
]
|
||||
}, testUri, folders);
|
||||
|
||||
assertCompletions(`html { background-image: url('/|')`, {
|
||||
await assertCompletions(`html { background-image: url('/|')`, {
|
||||
items: [
|
||||
{ label: 'pathCompletionFixtures/', resultText: `html { background-image: url('/pathCompletionFixtures/')` }
|
||||
]
|
||||
}, testUri, folders);
|
||||
|
||||
assertCompletions(`html { background-image: url('/pathCompletionFixtures/|')`, {
|
||||
await assertCompletions(`html { background-image: url('/pathCompletionFixtures/|')`, {
|
||||
items: [
|
||||
{ label: 'about/', resultText: `html { background-image: url('/pathCompletionFixtures/about/')` },
|
||||
{ label: 'index.html', resultText: `html { background-image: url('/pathCompletionFixtures/index.html')` },
|
||||
@@ -111,53 +118,53 @@ suite('Completions', () => {
|
||||
]
|
||||
}, testUri, folders);
|
||||
|
||||
assertCompletions(`html { background-image: url("/|")`, {
|
||||
await assertCompletions(`html { background-image: url("/|")`, {
|
||||
items: [
|
||||
{ label: 'pathCompletionFixtures/', resultText: `html { background-image: url("/pathCompletionFixtures/")` }
|
||||
]
|
||||
}, testUri, folders);
|
||||
});
|
||||
|
||||
test('CSS url() Path Completion - Unquoted url', function () {
|
||||
test('CSS url() Path Completion - Unquoted url', async function () {
|
||||
let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
|
||||
assertCompletions('html { background-image: url(./|)', {
|
||||
await assertCompletions('html { background-image: url(./|)', {
|
||||
items: [
|
||||
{ label: 'about.html', resultText: 'html { background-image: url(./about.html)' }
|
||||
]
|
||||
}, testUri, folders);
|
||||
|
||||
assertCompletions('html { background-image: url(./a|)', {
|
||||
await assertCompletions('html { background-image: url(./a|)', {
|
||||
items: [
|
||||
{ label: 'about.html', resultText: 'html { background-image: url(./about.html)' }
|
||||
]
|
||||
}, testUri, folders);
|
||||
|
||||
assertCompletions('html { background-image: url(../|src/)', {
|
||||
await assertCompletions('html { background-image: url(../|src/)', {
|
||||
items: [
|
||||
{ label: 'about/', resultText: 'html { background-image: url(../about/)' }
|
||||
]
|
||||
}, testUri, folders);
|
||||
|
||||
assertCompletions('html { background-image: url(../s|rc/)', {
|
||||
await assertCompletions('html { background-image: url(../s|rc/)', {
|
||||
items: [
|
||||
{ label: 'about/', resultText: 'html { background-image: url(../about/)' }
|
||||
]
|
||||
}, testUri, folders);
|
||||
});
|
||||
|
||||
test('CSS @import Path completion', function () {
|
||||
test('CSS @import Path completion', async function () {
|
||||
let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
|
||||
assertCompletions(`@import './|'`, {
|
||||
await assertCompletions(`@import './|'`, {
|
||||
items: [
|
||||
{ label: 'about.html', resultText: `@import './about.html'` },
|
||||
]
|
||||
}, testUri, folders);
|
||||
|
||||
assertCompletions(`@import '../|'`, {
|
||||
await assertCompletions(`@import '../|'`, {
|
||||
items: [
|
||||
{ label: 'about/', resultText: `@import '../about/'` },
|
||||
{ label: 'scss/', resultText: `@import '../scss/'` },
|
||||
@@ -170,14 +177,14 @@ suite('Completions', () => {
|
||||
/**
|
||||
* For SCSS, `@import 'foo';` can be used for importing partial file `_foo.scss`
|
||||
*/
|
||||
test('SCSS @import Path completion', function () {
|
||||
test('SCSS @import Path completion', async function () {
|
||||
let testCSSUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
|
||||
/**
|
||||
* We are in a CSS file, so no special treatment for SCSS partial files
|
||||
*/
|
||||
assertCompletions(`@import '../scss/|'`, {
|
||||
await assertCompletions(`@import '../scss/|'`, {
|
||||
items: [
|
||||
{ label: 'main.scss', resultText: `@import '../scss/main.scss'` },
|
||||
{ label: '_foo.scss', resultText: `@import '../scss/_foo.scss'` }
|
||||
@@ -185,18 +192,18 @@ suite('Completions', () => {
|
||||
}, testCSSUri, folders);
|
||||
|
||||
let testSCSSUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/scss/main.scss')).toString();
|
||||
assertCompletions(`@import './|'`, {
|
||||
await assertCompletions(`@import './|'`, {
|
||||
items: [
|
||||
{ label: '_foo.scss', resultText: `@import './foo'` }
|
||||
]
|
||||
}, testSCSSUri, folders, 'scss');
|
||||
});
|
||||
|
||||
test('Completion should ignore files/folders starting with dot', function () {
|
||||
test('Completion should ignore files/folders starting with dot', async function () {
|
||||
let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
|
||||
assertCompletions('html { background-image: url("../|")', {
|
||||
await assertCompletions('html { background-image: url("../|")', {
|
||||
count: 4
|
||||
}, testUri, folders);
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import { TextDocument, DocumentLink } from 'vscode-languageserver-types';
|
||||
import { WorkspaceFolder } from 'vscode-languageserver-protocol';
|
||||
import { getCSSLanguageService } from 'vscode-css-languageservice';
|
||||
import { getDocumentContext } from '../utils/documentContext';
|
||||
import { getNodeFSRequestService } from '../node/nodeFs';
|
||||
|
||||
export interface ItemDescription {
|
||||
offset: number;
|
||||
@@ -18,7 +19,7 @@ export interface ItemDescription {
|
||||
}
|
||||
|
||||
suite('Links', () => {
|
||||
const cssLanguageService = getCSSLanguageService();
|
||||
const cssLanguageService = getCSSLanguageService({ fileSystemProvider: getNodeFSRequestService() });
|
||||
|
||||
let assertLink = function (links: DocumentLink[], expected: ItemDescription, document: TextDocument) {
|
||||
let matches = links.filter(link => {
|
||||
@@ -31,7 +32,7 @@ suite('Links', () => {
|
||||
assert.equal(match.target, expected.target);
|
||||
};
|
||||
|
||||
function assertLinks(value: string, expected: ItemDescription[], testUri: string, workspaceFolders?: WorkspaceFolder[], lang: string = 'css'): void {
|
||||
async function assertLinks(value: string, expected: ItemDescription[], testUri: string, workspaceFolders?: WorkspaceFolder[], lang: string = 'css'): Promise<void> {
|
||||
const offset = value.indexOf('|');
|
||||
value = value.substr(0, offset) + value.substr(offset + 1);
|
||||
|
||||
@@ -44,7 +45,7 @@ suite('Links', () => {
|
||||
const context = getDocumentContext(testUri, workspaceFolders);
|
||||
|
||||
const stylesheet = cssLanguageService.parseStylesheet(document);
|
||||
let links = cssLanguageService.findDocumentLinks(document, stylesheet, context)!;
|
||||
let links = await cssLanguageService.findDocumentLinks2(document, stylesheet, context)!;
|
||||
|
||||
assert.equal(links.length, expected.length);
|
||||
|
||||
@@ -57,32 +58,32 @@ suite('Links', () => {
|
||||
return URI.file(resolve(__dirname, '../../test/linksTestFixtures', path)).toString();
|
||||
}
|
||||
|
||||
test('url links', function () {
|
||||
test('url links', async function () {
|
||||
|
||||
let testUri = getTestResource('about.css');
|
||||
let folders = [{ name: 'x', uri: getTestResource('') }];
|
||||
|
||||
assertLinks('html { background-image: url("hello.html|")',
|
||||
await assertLinks('html { background-image: url("hello.html|")',
|
||||
[{ offset: 29, value: '"hello.html"', target: getTestResource('hello.html') }], testUri, folders
|
||||
);
|
||||
});
|
||||
|
||||
test('node module resolving', function () {
|
||||
test('node module resolving', async function () {
|
||||
|
||||
let testUri = getTestResource('about.css');
|
||||
let folders = [{ name: 'x', uri: getTestResource('') }];
|
||||
|
||||
assertLinks('html { background-image: url("~foo/hello.html|")',
|
||||
await assertLinks('html { background-image: url("~foo/hello.html|")',
|
||||
[{ offset: 29, value: '"~foo/hello.html"', target: getTestResource('node_modules/foo/hello.html') }], testUri, folders
|
||||
);
|
||||
});
|
||||
|
||||
test('node module subfolder resolving', function () {
|
||||
test('node module subfolder resolving', async function () {
|
||||
|
||||
let testUri = getTestResource('subdir/about.css');
|
||||
let folders = [{ name: 'x', uri: getTestResource('') }];
|
||||
|
||||
assertLinks('html { background-image: url("~foo/hello.html|")',
|
||||
await assertLinks('html { background-image: url("~foo/hello.html|")',
|
||||
[{ offset: 29, value: '"~foo/hello.html"', target: getTestResource('node_modules/foo/hello.html') }], testUri, folders
|
||||
);
|
||||
});
|
||||
|
||||
@@ -7,29 +7,6 @@ import { DocumentContext } from 'vscode-css-languageservice';
|
||||
import { endsWith, startsWith } from '../utils/strings';
|
||||
import * as url from 'url';
|
||||
import { WorkspaceFolder } from 'vscode-languageserver';
|
||||
import { URI } from 'vscode-uri';
|
||||
import { join, dirname } from 'path';
|
||||
import { existsSync } from 'fs';
|
||||
|
||||
function getModuleNameFromPath(path: string) {
|
||||
// If a scoped module (starts with @) then get up until second instance of '/', otherwise get until first isntance of '/'
|
||||
if (path[0] === '@') {
|
||||
return path.substring(0, path.indexOf('/', path.indexOf('/') + 1));
|
||||
}
|
||||
return path.substring(0, path.indexOf('/'));
|
||||
}
|
||||
|
||||
function resolvePathToModule(_moduleName: string, _relativeToFolder: string, _rootFolder: string | undefined): string | undefined {
|
||||
// resolve the module relative to the document. We can't use `require` here as the code is webpacked.
|
||||
|
||||
const packPath = join(_relativeToFolder, 'node_modules', _moduleName, 'package.json');
|
||||
if (existsSync(packPath)) {
|
||||
return URI.file(packPath).toString();
|
||||
} else if (_rootFolder && _relativeToFolder.startsWith(_rootFolder) && (_relativeToFolder.length !== _rootFolder.length)) {
|
||||
return resolvePathToModule(_moduleName, dirname(_relativeToFolder), _rootFolder);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function getDocumentContext(documentUri: string, workspaceFolders: WorkspaceFolder[]): DocumentContext {
|
||||
function getRootFolder(): string | undefined {
|
||||
@@ -46,37 +23,13 @@ export function getDocumentContext(documentUri: string, workspaceFolders: Worksp
|
||||
}
|
||||
|
||||
return {
|
||||
resolveReference: (ref, base = documentUri) => {
|
||||
resolveReference: (ref: string, base = documentUri) => {
|
||||
if (ref[0] === '/') { // resolve absolute path against the current workspace folder
|
||||
if (startsWith(base, 'file://')) {
|
||||
let folderUri = getRootFolder();
|
||||
if (folderUri) {
|
||||
return folderUri + ref.substr(1);
|
||||
}
|
||||
let folderUri = getRootFolder();
|
||||
if (folderUri) {
|
||||
return folderUri + ref.substr(1);
|
||||
}
|
||||
}
|
||||
// Following [css-loader](https://github.com/webpack-contrib/css-loader#url)
|
||||
// and [sass-loader's](https://github.com/webpack-contrib/sass-loader#imports)
|
||||
// convention, if an import path starts with ~ then use node module resolution
|
||||
// *unless* it starts with "~/" as this refers to the user's home directory.
|
||||
if (ref[0] === '~' && ref[1] !== '/') {
|
||||
ref = ref.substring(1);
|
||||
if (startsWith(base, 'file://')) {
|
||||
const moduleName = getModuleNameFromPath(ref);
|
||||
const rootFolderUri = getRootFolder();
|
||||
let rootFolder;
|
||||
if (rootFolderUri) {
|
||||
rootFolder = URI.parse(rootFolderUri).fsPath;
|
||||
}
|
||||
const documentFolder = dirname(URI.parse(base).fsPath);
|
||||
const modulePath = resolvePathToModule(moduleName, documentFolder, rootFolder);
|
||||
if (modulePath) {
|
||||
const pathWithinModule = ref.substring(moduleName.length + 1);
|
||||
return url.resolve(modulePath, pathWithinModule);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return url.resolve(base, ref);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -38,30 +38,6 @@ export function runSafeAsync<T>(func: () => Thenable<T>, errorVal: T, errorMessa
|
||||
});
|
||||
}
|
||||
|
||||
export function runSafe<T, E>(func: () => T, errorVal: T, errorMessage: string, token: CancellationToken): Thenable<T | ResponseError<E>> {
|
||||
return new Promise<T | ResponseError<E>>((resolve) => {
|
||||
setImmediate(() => {
|
||||
if (token.isCancellationRequested) {
|
||||
resolve(cancelValue());
|
||||
} else {
|
||||
try {
|
||||
let result = func();
|
||||
if (token.isCancellationRequested) {
|
||||
resolve(cancelValue());
|
||||
return;
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.error(formatError(errorMessage, e));
|
||||
resolve(errorVal);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function cancelValue<E>() {
|
||||
return new ResponseError<E>(ErrorCodes.RequestCancelled, 'Request cancelled');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user