Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
TextEdit
} from 'vscode-languageserver';
import { mapObjWithRangeToOriginal, offsetAt, positionAt } from '../../../../lib/documents';
import { pathToUrl } from '../../../../utils';
import { getIndent, pathToUrl } from '../../../../utils';
import { SvelteDocument } from '../../SvelteDocument';
import ts from 'typescript';
// estree does not have start/end in their public Node interface,
Expand Down Expand Up @@ -111,7 +111,7 @@ async function getSvelteIgnoreEdit(svelteDoc: SvelteDocument, ast: Ast, diagnost
transpiled.getText()
);
const afterStartLineStart = content.slice(nodeLineStart);
const indent = /^[ |\t]+/.exec(afterStartLineStart)?.[0] ?? '';
const indent = getIndent(afterStartLineStart);

// TODO: Make all code action's new line consistent
const ignore = `${indent}<!-- svelte-ignore ${code} -->${EOL}`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
isInTag,
getLineAtPosition
} from '../../../lib/documents';
import { pathToUrl, flatten, isNotNullOrUndefined, modifyLines } from '../../../utils';
import { pathToUrl, flatten, isNotNullOrUndefined, modifyLines, getIndent } from '../../../utils';
import { CodeActionsProvider } from '../../interfaces';
import { SnapshotFragment, SvelteSnapshotFragment } from '../DocumentSnapshot';
import { LSAndTSDocResolver } from '../LSAndTSDocResolver';
Expand Down Expand Up @@ -163,76 +163,93 @@ export class CodeActionsProviderImpl implements CodeActionsProvider {
const docs = new SnapshotFragmentMap(this.lsAndTsDocResolver);
docs.set(tsDoc.filePath, { fragment, snapshot: tsDoc });

return await Promise.all(
codeFixes.map(async (fix) => {
const documentChanges = await Promise.all(
fix.changes.map(async (change) => {
const { snapshot, fragment } = await docs.retrieve(change.fileName);
return TextDocumentEdit.create(
OptionalVersionedTextDocumentIdentifier.create(
pathToUrl(change.fileName),
null
),
change.textChanges
.map((edit) => {
if (
fix.fixName === 'import' &&
fragment instanceof SvelteSnapshotFragment
) {
return this.completionProvider.codeActionChangeToTextEdit(
document,
fragment,
edit,
true,
isInTag(range.start, document.scriptInfo) ||
isInTag(range.start, document.moduleScriptInfo)
);
}

if (
!isNoTextSpanInGeneratedCode(
snapshot.getFullText(),
edit.span
)
) {
return undefined;
}

let originalRange = mapRangeToOriginal(
fragment,
convertRange(fragment, edit.span)
);

if (fix.fixName === 'unusedIdentifier') {
originalRange = this.checkRemoveImportCodeActionRange(
edit,
fragment,
originalRange
);
}

if (fix.fixName === 'fixMissingFunctionDeclaration') {
originalRange = this.checkEndOfFileCodeInsert(
originalRange,
range,
document
);
}

return TextEdit.replace(originalRange, edit.newText);
})
.filter(isNotNullOrUndefined)
);
})
);
return CodeAction.create(
fix.description,
{
documentChanges
},
CodeActionKind.QuickFix
const codeActionsPromises = codeFixes.map(async (fix) => {
const documentChangesPromises = fix.changes.map(async (change) => {
const { snapshot, fragment } = await docs.retrieve(change.fileName);
return TextDocumentEdit.create(
OptionalVersionedTextDocumentIdentifier.create(
pathToUrl(change.fileName),
null
),
change.textChanges
.map((edit) => {
if (
fix.fixName === 'import' &&
fragment instanceof SvelteSnapshotFragment
) {
return this.completionProvider.codeActionChangeToTextEdit(
document,
fragment,
edit,
true,
isInTag(range.start, document.scriptInfo) ||
isInTag(range.start, document.moduleScriptInfo)
);
}

if (!isNoTextSpanInGeneratedCode(snapshot.getFullText(), edit.span)) {
return undefined;
}

let originalRange = mapRangeToOriginal(
fragment,
convertRange(fragment, edit.span)
);

if (fix.fixName === 'unusedIdentifier') {
originalRange = this.checkRemoveImportCodeActionRange(
edit,
fragment,
originalRange
);
}

if (fix.fixName === 'fixMissingFunctionDeclaration') {
originalRange = this.checkEndOfFileCodeInsert(
originalRange,
range,
document
);
}

if (fix.fixName === 'disableJsDiagnostics') {
if (edit.newText.includes('ts-nocheck')) {
return this.checkTsNoCheckCodeInsert(document, edit);
}

return this.checkDisableJsDiagnosticsCodeInsert(
originalRange,
document,
edit
);
}

if (originalRange.start.line < 0 || originalRange.end.line < 0) {
return undefined;
}

return TextEdit.replace(originalRange, edit.newText);
})
.filter(isNotNullOrUndefined)
);
})
});
const documentChanges = await Promise.all(documentChangesPromises);
return CodeAction.create(
fix.description,
{
documentChanges
},
CodeActionKind.QuickFix
);
});

const codeActions = await Promise.all(codeActionsPromises);

// filter out empty code action
return codeActions.filter((codeAction) =>
codeAction.edit?.documentChanges?.every(
(change) => (<TextDocumentEdit>change).edits.length > 0
)
);
}

Expand Down Expand Up @@ -398,6 +415,47 @@ export class CodeActionsProviderImpl implements CodeActionsProvider {
return resultRange;
}

private checkTsNoCheckCodeInsert(
document: Document,
edit: ts.TextChange
): TextEdit | undefined {
if (!document.scriptInfo) {
return undefined;
}

const newText = ts.sys.newLine + edit.newText;

return TextEdit.insert(document.scriptInfo.startPos, newText);
}

private checkDisableJsDiagnosticsCodeInsert(
originalRange: Range,
document: Document,
edit: ts.TextChange
): TextEdit {
const startOffset = document.offsetAt(originalRange.start);
const text = document.getText();

// svetlte2tsx removes export in instance script
const insertedAfterExport = text.slice(0, startOffset).trim().endsWith('export');

if (!insertedAfterExport) {
return TextEdit.replace(originalRange, edit.newText);
}

const position = document.positionAt(text.lastIndexOf('export', startOffset));

// fix the length of trailing indent
const linesOfNewText = edit.newText.split('\n');
if (/^[ \t]*$/.test(linesOfNewText[linesOfNewText.length - 1])) {
const line = getLineAtPosition(originalRange.start, document.getText());
const indent = getIndent(line);
linesOfNewText[linesOfNewText.length - 1] = indent;
}

return TextEdit.insert(position, linesOfNewText.join('\n'));
}

private async getLSAndTSDoc(document: Document) {
return this.lsAndTsDocResolver.getLSAndTSDoc(document);
}
Expand Down
4 changes: 4 additions & 0 deletions packages/language-server/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,7 @@ export async function filterAsync<T>(
)
).filter((i) => i !== fail) as T[];
}

export function getIndent(text: string) {
return /^[ |\t]+/.exec(text)?.[0] ?? '';
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,21 @@ import { pathToUrl } from '../../../../src/utils';
import ts from 'typescript';
import * as path from 'path';
import * as assert from 'assert';
import { Range, Position, CodeActionKind, TextDocumentEdit } from 'vscode-languageserver';
import {
Range,
Position,
CodeActionKind,
TextDocumentEdit,
CodeAction
} from 'vscode-languageserver';
import { CompletionsProviderImpl } from '../../../../src/plugins/typescript/features/CompletionProvider';
import { LSConfigManager } from '../../../../src/ls-config';

const testDir = path.join(__dirname, '..');

describe('CodeActionsProvider', () => {
function getFullPath(filename: string) {
return path.join(testDir, 'testfiles', filename);
return path.join(testDir, 'testfiles', 'code-actions', filename);
}

function getUri(filename: string) {
Expand Down Expand Up @@ -152,6 +158,95 @@ describe('CodeActionsProvider', () => {
]);
});

it('provides quickfix for ts-checked-js', async () => {
const { provider, document } = setup('codeaction-checkJs.svelte');
const errorRange = Range.create(Position.create(2, 21), Position.create(2, 26));

const codeActions = await provider.getCodeActions(document, errorRange, {
diagnostics: [
{
code: 2304,
message: "Cannot find name 'blubb'.",
range: errorRange
}
]
});

for (const codeAction of codeActions) {
(<TextDocumentEdit>codeAction.edit?.documentChanges?.[0])?.edits.forEach(
(edit) => (edit.newText = harmonizeNewLines(edit.newText))
);
}

const textDocument = {
uri: getUri('codeaction-checkJs.svelte'),
version: null
};
assert.deepStrictEqual(codeActions, <CodeAction[]>[
{
edit: {
documentChanges: [
{
edits: [
{
newText: '\nimport { blubb } from "../definitions";\n\n',
range: Range.create(
Position.create(0, 8),
Position.create(0, 8)
)
}
],
textDocument
}
]
},
kind: 'quickfix',
title: 'Import \'blubb\' from module "../definitions"'
},
{
edit: {
documentChanges: [
{
edits: [
{
newText: '// @ts-ignore\n ',
range: Range.create(
Position.create(2, 4),
Position.create(2, 4)
)
}
],
textDocument
}
]
},
kind: 'quickfix',
title: 'Ignore this error message'
},
{
edit: {
documentChanges: [
{
edits: [
{
newText: '\n// @ts-nocheck',
range: Range.create(
Position.create(0, 8),
Position.create(0, 8)
)
}
],
textDocument
}
]
},

kind: 'quickfix',
title: 'Disable checking for this file'
}
]);
});

it('organizes imports', async () => {
const { provider, document } = setup('codeactions.svelte');

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<script>
// @ts-check
export let abc = blubb;
</script>