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 @@ -21,9 +21,9 @@ import { flatten, getIndent, isNotNullOrUndefined, modifyLines, pathToUrl } from
import { CodeActionsProvider } from '../../interfaces';
import { SnapshotFragment, SvelteSnapshotFragment } from '../DocumentSnapshot';
import { LSAndTSDocResolver } from '../LSAndTSDocResolver';
import { convertRange } from '../utils';
import { changeSvelteComponentName, convertRange } from '../utils';
import { CompletionsProviderImpl } from './CompletionProvider';
import { isNoTextSpanInGeneratedCode, SnapshotFragmentMap } from './utils';
import { findContainingNode, isNoTextSpanInGeneratedCode, SnapshotFragmentMap } from './utils';

interface RefactorArgs {
type: 'refactor';
Expand Down Expand Up @@ -187,10 +187,15 @@ export class CodeActionsProviderImpl implements CodeActionsProvider {
userPreferences
);

const componentQuickFix = errorCodes.includes(2304) // "Cannot find name '...'."
? this.getComponentImportQuickFix(start, end, lang, tsDoc.filePath, userPreferences) ??
[]
: [];

const docs = new SnapshotFragmentMap(this.lsAndTsDocResolver);
docs.set(tsDoc.filePath, { fragment, snapshot: tsDoc });

const codeActionsPromises = codeFixes.map(async (fix) => {
const codeActionsPromises = codeFixes.concat(componentQuickFix).map(async (fix) => {
const documentChangesPromises = fix.changes.map(async (change) => {
const { snapshot, fragment } = await docs.retrieve(change.fileName);
return TextDocumentEdit.create(
Expand Down Expand Up @@ -279,6 +284,72 @@ export class CodeActionsProviderImpl implements CodeActionsProvider {
);
}

/**
* import quick fix requires the symbol name to be the same as where it's defined.
* But we have suffix on component default export to prevent conflict with
* a local variable. So we use auto-import completion as a workaround here.
*/
private getComponentImportQuickFix(
start: number,
end: number,
lang: ts.LanguageService,
filePath: string,
userPreferences: ts.UserPreferences
): ts.CodeFixAction[] | undefined {
const sourceFile = lang.getProgram()?.getSourceFile(filePath);

if (!sourceFile) {
return;
}

const node = findContainingNode(
sourceFile,
{
start,
length: end - start
},
(node): node is ts.JsxOpeningLikeElement | ts.JsxClosingElement =>
ts.isJsxClosingElement(node) || ts.isJsxOpeningLikeElement(node)
);

if (!node) {
return;
}

const completion = lang.getCompletionsAtPosition(
filePath,
node.tagName.getEnd(),
userPreferences
);

if (!completion) {
return;
}

const name = node.tagName.getText();
const suffixedName = name + '__SvelteComponent_';
const toFix = (c: ts.CompletionEntry) =>
lang
.getCompletionEntryDetails(
filePath,
end,
c.name,
{},
c.source,
userPreferences,
c.data
)
?.codeActions?.map((a) => ({
...a,
description: changeSvelteComponentName(a.description),
fixName: 'import'
})) ?? [];

return flatten(
completion.entries.filter((c) => c.name === name || c.name === suffixedName).map(toFix)
);
}

private async getApplicableRefactors(
document: Document,
range: Range,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { SvelteDocumentSnapshot, SvelteSnapshotFragment } from '../DocumentSnaps
import { LSAndTSDocResolver } from '../LSAndTSDocResolver';
import { getMarkdownDocumentation } from '../previewer';
import {
changeSvelteComponentName,
convertRange,
getCommitCharactersForScriptElement,
isInScript,
Expand Down Expand Up @@ -306,7 +307,7 @@ export class CompletionsProviderImpl implements CompletionsProvider<CompletionEn
const hasModifier = Boolean(comp.kindModifiers);
const isSvelteComp = this.isSvelteComponentImport(name);
if (isSvelteComp) {
name = this.changeSvelteComponentName(name);
name = changeSvelteComponentName(name);

if (this.isExistingSvelteComponentImport(fragment, name, comp.source)) {
return null;
Expand All @@ -327,7 +328,7 @@ export class CompletionsProviderImpl implements CompletionsProvider<CompletionEn
return {
label: name,
isSvelteComp,
insertText: this.changeSvelteComponentName(insertText),
insertText: changeSvelteComponentName(insertText),
replacementSpan: comp.replacementSpan
};
}
Expand Down Expand Up @@ -458,7 +459,7 @@ export class CompletionsProviderImpl implements CompletionsProvider<CompletionEn

private getCompletionDocument(compDetail: ts.CompletionEntryDetails) {
const { sourceDisplay, documentation: tsDocumentation, displayParts, tags } = compDetail;
let detail: string = this.changeSvelteComponentName(ts.displayPartsToString(displayParts));
let detail: string = changeSvelteComponentName(ts.displayPartsToString(displayParts));

if (sourceDisplay) {
const importPath = ts.displayPartsToString(sourceDisplay);
Expand Down Expand Up @@ -578,12 +579,8 @@ export class CompletionsProviderImpl implements CompletionsProvider<CompletionEn
return className.endsWith('__SvelteComponent_');
}

private changeSvelteComponentName(name: string) {
return name.replace(/(\w+)__SvelteComponent_/, '$1');
}

private changeComponentImport(importText: string, actionTriggeredInScript: boolean) {
const changedName = this.changeSvelteComponentName(importText);
const changedName = changeSvelteComponentName(importText);
if (importText !== changedName || !actionTriggeredInScript) {
// For some reason, TS sometimes adds the `type` modifier. Remove it
// in case of Svelte component imports or if import triggered from markup.
Expand Down
4 changes: 4 additions & 0 deletions packages/language-server/src/plugins/typescript/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,10 @@ export function getDiagnosticTag(diagnostic: ts.Diagnostic): DiagnosticTag[] {
return tags;
}

export function changeSvelteComponentName(name: string) {
return name.replace(/(\w+)__SvelteComponent_/, '$1');
}

export function hasTsExtensions(fileName: string) {
return (
fileName.endsWith(ts.Extension.Dts) ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,52 @@ describe('CodeActionsProvider', () => {
]);
});

it('provides quickfix for component import', async () => {
const { provider, document } = setup('codeactions.svelte');

const codeActions = await provider.getCodeActions(
document,
Range.create(Position.create(12, 1), Position.create(12, 1)),
{
diagnostics: [
{
code: 2304,
message: "Cannot find name 'Empty'.",
range: Range.create(Position.create(12, 1), Position.create(12, 6)),
source: 'ts'
}
],
only: [CodeActionKind.QuickFix]
}
);

assert.deepStrictEqual(codeActions, <CodeAction[]>[
{
edit: {
documentChanges: [
{
edits: [
{
newText: "import Empty from '../empty.svelte';\r\n",
range: {
end: Position.create(5, 0),
start: Position.create(5, 0)
}
}
],
textDocument: {
uri: getUri('codeactions.svelte'),
version: null
}
}
]
},
kind: 'quickfix',
title: 'Import default \'Empty\' from module "../empty.svelte"'
}
]);
});

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ let b = Math.random() > 0.5 ? true : false;
abc();
</script>
{abc()}
<Empty />