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

(feat) rewrite svelte2tsx #1237

Merged
merged 104 commits into from
Jan 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
104 commits
Select commit Hold shift + click to select a range
09205d0
(feat) rewrite svelte2tsx
Nov 9, 2021
12f6ca2
debug update
Nov 9, 2021
37e7a96
fix: don't hand Style/Script attributes
Nov 9, 2021
0d5526a
if/else support
Nov 9, 2021
2ab4748
add missing shims
Nov 9, 2021
f86523e
handle each
Nov 9, 2021
260df70
handle mustache tags in markup
Nov 9, 2021
0489f90
make tests generate new versions
Nov 9, 2021
9900099
generate ts/js, not jsx/tsx
Nov 9, 2021
38d65f0
add test outputs that are correct already
Nov 9, 2021
840e5d0
await support
Nov 10, 2021
4a849f6
create svelte namespace alias for less confusion when errors or hover…
Nov 10, 2021
ee3f1dd
refine API a little - new option for mode instead of new setting, typ…
Nov 11, 2021
8804d9e
support action/animation/transition directives
Nov 11, 2021
ff31a8c
fix action/animation/transitions: add shims, handle no params case di…
Nov 11, 2021
65d444a
support key,debug,html
Nov 11, 2021
e451db5
adjust transform util: replace overwritten content with one whitespac…
Nov 11, 2021
51b0bcb
support class, binding
Nov 11, 2021
9cf937f
transform shorthands to property shorthands for better source mapping…
Nov 15, 2021
85bf360
options/window/head/body svelte element support
Nov 16, 2021
51e4fef
support slot tag
Nov 16, 2021
1408f8c
support slot let
Nov 17, 2021
8c80637
Merge branch 'master' into svelte2tsx-rewrite
Nov 17, 2021
732662f
fix mappings
Nov 17, 2021
7449447
support svelteself/sveltecomponent
Nov 18, 2021
66add32
better svelte:component/self handling, tests
Nov 19, 2021
4214e0c
fix animation/transition params case
Nov 19, 2021
2077646
quotes fix
Nov 19, 2021
704ff92
css custom properties, multiple/empty attr fix
Nov 20, 2021
6e63f16
fix "used before defined" edge case error when let:x {x} used on same…
Nov 20, 2021
1869f3b
fix auto-closing
Nov 24, 2021
7144ef0
fix EachBlock startEnd
Nov 24, 2021
e9b9fd7
document limitation of each/await transformation
Nov 24, 2021
7766e86
handle empty script/style tags
Nov 24, 2021
0130e4d
handle namespaced attributes
Nov 24, 2021
c86788f
move test
Nov 24, 2021
fee80d1
handle event modifiers
Nov 24, 2021
6182956
fix default slot positioning + sveltefragment
Nov 24, 2021
be56c9c
module script processing
Nov 27, 2021
d0a0b23
text finetuning
Nov 27, 2021
18d3cd7
fix autocompletion for last attr of node
Nov 27, 2021
0f22a7f
Merge branch 'master' into svelte2tsx-rewrite
Nov 29, 2021
ee17d6b
several fixes: wrap html with async lambda for await, adjust class,ea…
Dec 1, 2021
465c5aa
fix each block edge case, dont add unused consts, adjust node-utils f…
Dec 1, 2021
f0b8892
more fixes
Dec 3, 2021
508cdc7
tests
Dec 10, 2021
a511009
tests
Dec 10, 2021
6028c30
Merge branch 'master' into svelte2tsx-rewrite
Dec 10, 2021
b724c47
ignore samples
Dec 10, 2021
7cc11bc
test
Dec 10, 2021
d0bc000
fix attribute error + helpers + tests
Dec 10, 2021
d0aff56
Merge branch 'master' into svelte2tsx-rewrite
Dec 17, 2021
d7e7a68
Merge branch 'master' into svelte2tsx-rewrite
Dec 18, 2021
d996715
Merge branch 'master' into svelte2tsx-rewrite
Dec 18, 2021
b53ad68
add config to enable/disable new transformation, disabled by default
Dec 19, 2021
7eebe2c
better mapping for on:xx on html elements
Dec 22, 2021
5c8cf93
tests
Dec 22, 2021
d8cc465
fix
Dec 22, 2021
e0a0148
fix
Dec 22, 2021
f6cb638
Merge branch 'master' into svelte2tsx-rewrite
Jan 10, 2022
de9e546
tests
Jan 10, 2022
c20d273
better event name mapping
Jan 10, 2022
c28296e
update diagnostic tests so that they can run both new and old transfo…
Jan 10, 2022
007d0f1
update test
Jan 10, 2022
541f286
Fix await block transformation to deal with cases mentioned in its fu…
Jan 10, 2022
195da86
handle each block shadowing and ensure it's an arraylike
Jan 10, 2022
54567b2
fix typing to any else TS will create a weird type
Jan 10, 2022
aee8fd0
remap "missing prop" error
Jan 10, 2022
5183973
Merge branch 'master' into svelte2tsx-rewrite
Jan 13, 2022
9361888
Merge branch 'master' into svelte2tsx-rewrite
Jan 13, 2022
bcb991d
Add support for StyleDirective and ConstTag, fix some bugs
Jan 14, 2022
dea6cb7
ensure test doesn't mess with other tests
Jan 14, 2022
627584d
adjust renameprovider
Jan 17, 2022
f8f4863
ensure test is not flaky
Jan 17, 2022
d4f3c03
fix html attribute util
Jan 17, 2022
74fa41d
fix jsx
Jan 17, 2022
6d50025
lint
Jan 17, 2022
efeb165
cleanup
Jan 17, 2022
3533b3c
ensure no shims appear in definitions
Jan 17, 2022
8813a0f
code actions tests for new and old
Jan 17, 2022
5bee32d
completion tests for old and new
Jan 17, 2022
fb32450
find references tests for old and new
Jan 17, 2022
81aa288
hover provider tests for old and new
Jan 17, 2022
dbf1187
lint
Jan 17, 2022
3e81db8
handle spread
Jan 19, 2022
90512c4
better event name mapping
Jan 19, 2022
fc680aa
fix typo
Jan 19, 2022
2ba6c59
fix regex
Jan 19, 2022
1c0ee88
simplify selfclosing logic
Jan 19, 2022
6faa3f8
add missing expectedv2 files
Jan 19, 2022
aae863b
map component end tag
Jan 19, 2022
51106ac
add support for namespacing createElement, default namespace is svelt…
Jan 20, 2022
5a7d824
better document symbols for new transformation
Jan 20, 2022
32ec15d
fix tests
Jan 21, 2022
c4a7e8a
update typescript plugin to use new version, bump svelte2tsx version
Jan 21, 2022
d620ab6
lint
Jan 21, 2022
61bfc07
lint, try fix tests
Jan 21, 2022
fc57843
comment out part of test
Jan 22, 2022
46db627
no semantic highlighting for on:event
Jan 22, 2022
b984540
ensure whitespace is mapped to props/attrs for better completion
Jan 27, 2022
ffd2c8f
tests
Jan 27, 2022
cefd1ca
better slot name mapping
Jan 27, 2022
f442854
fix dev script
Jan 27, 2022
3063337
deduplicate html tag completions
Jan 27, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ packages/svelte2tsx/test/**/*
packages/svelte2tsx/index.*
declare module '*.svelte'
packages/svelte2tsx/svelte-shims.d.ts
packages/svelte2tsx/svelte-jsx.d.ts
4 changes: 2 additions & 2 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
packages/svelte2tsx/*.d.ts
packages/svelte2tsx/test/*/samples/*/*sx
packages/svelte2tsx/test/*/samples/*/*.svelte
packages/svelte2tsx/repl/*
packages/svelte2tsx/test/*/samples/**/*
packages/svelte2tsx/test/sourcemaps/samples/*
packages/svelte2tsx/test/emitDts/samples/*/expected/**
packages/language-server/test/**/*.svelte
Expand Down
4 changes: 2 additions & 2 deletions packages/language-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "dist/src/index.js",
"typings": "dist/src/index",
"scripts": {
"test": "cross-env TS_NODE_TRANSPILE_ONLY=true mocha --require ts-node/register \"test/**/*.ts\"",
"test": "cross-env TS_NODE_TRANSPILE_ONLY=true mocha --require ts-node/register \"test/**/*.ts\" --exclude \"test/**/*.d.ts\"",
"build": "tsc",
"prepublishOnly": "npm run build",
"watch": "tsc -w"
Expand Down Expand Up @@ -57,7 +57,7 @@
"source-map": "^0.7.3",
"svelte": "^3.46.1",
"svelte-preprocess": "~4.10.1",
"svelte2tsx": "~0.4.0",
"svelte2tsx": "~0.5.0",
"typescript": "*",
"vscode-css-languageservice": "~5.1.0",
"vscode-emmet-helper": "~2.6.0",
Expand Down
13 changes: 13 additions & 0 deletions packages/language-server/src/lib/documents/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,19 @@ export function getNodeIfIsInStartTag(html: HTMLDocument, offset: number): Node
}
}

/**
* Returns `true` if `offset` is a html tag and within the name of the start tag or end tag
*/
export function isInHTMLTagRange(html: HTMLDocument, offset: number): boolean {
const node = html.findNodeAt(offset);
return (
!!node.tag &&
node.tag[0] === node.tag[0].toLowerCase() &&
(node.start + node.tag.length + 1 >= offset ||
(!!node.endTagStart && node.endTagStart <= offset))
);
}

/**
* Gets word range at position.
* Delimiter is by default a whitespace, but can be adjusted.
Expand Down
2 changes: 2 additions & 0 deletions packages/language-server/src/ls-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const defaultLSConfig: LSConfig = {
},
svelte: {
enable: true,
useNewTransformation: false,
Copy link
Member Author

Choose a reason for hiding this comment

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

This is used to determine whether or not to use the new transformation. My idea is to go into a month-long beta phase where this is false by default and we encourage people to switch it on to try it out. After that we toggle it to true by default and then see what the feedback is. If everything is good, we can remove it ~2 months afterwards and remove all the old code, simplifying the code base.

This boolean is used in a few places in some Providers to do something differently.

compilerWarnings: {},
diagnostics: { enable: true },
rename: { enable: true },
Expand Down Expand Up @@ -176,6 +177,7 @@ export type CompilerWarningsSettings = Record<string, 'ignore' | 'error'>;

export interface LSSvelteConfig {
enable: boolean;
useNewTransformation: boolean;
compilerWarnings: CompilerWarningsSettings;
diagnostics: {
enable: boolean;
Expand Down
60 changes: 48 additions & 12 deletions packages/language-server/src/plugins/PluginHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ import {
TextEdit,
WorkspaceEdit
} from 'vscode-languageserver';
import { DocumentManager } from '../lib/documents';
import { DocumentManager, getNodeIfIsInHTMLStartTag } from '../lib/documents';
import { Logger } from '../logger';
import { regexLastIndexOf } from '../utils';
import { isNotNullOrUndefined, regexLastIndexOf } from '../utils';
import {
AppCompletionItem,
FileRename,
Expand Down Expand Up @@ -115,18 +115,54 @@ export class PluginHost implements LSProvider, OnWatchFileChanges {
): Promise<CompletionList> {
const document = this.getDocument(textDocument.uri);

const completions = (
await this.execute<CompletionList>(
'getCompletions',
[document, position, completionContext, cancellationToken],
ExecuteMode.Collect,
'high'
)
).filter((completion) => completion != null);
const completions = await Promise.all(
this.plugins.map(async (plugin) => {
const result = await this.tryExecutePlugin(
plugin,
'getCompletions',
[document, position, completionContext, cancellationToken],
null
);
if (result) {
return { result: result as CompletionList, plugin: plugin.__name };
}
})
).then((completions) => completions.filter(isNotNullOrUndefined));

const html = completions.find((completion) => completion.plugin === 'html');
const ts = completions.find((completion) => completion.plugin === 'ts');
if (html && ts && getNodeIfIsInHTMLStartTag(document.html, document.offsetAt(position))) {
// Completion in a component or html start tag and both html and ts
// suggest something -> filter out all duplicates from TS completions
const htmlCompletions = new Set(html.result.items.map((item) => item.label));
ts.result.items = ts.result.items.filter((item) => {
const label = item.label;
if (htmlCompletions.has(label)) {
return false;
}
if (label[0] === '"' && label[label.length - 1] === '"') {
if (htmlCompletions.has(label.slice(1, -1))) {
// "aria-label" -> aria-label -> exists in html completions
return false;
}
}
if (label.startsWith('on')) {
if (htmlCompletions.has('on:' + label.slice(2))) {
// onclick -> on:click -> exists in html completions
return false;
}
}
// adjust sort text so it does appear after html completions
item.sortText = 'Z' + (item.sortText || '');
return true;
});
}

let flattenedCompletions = flatten(completions.map((completion) => completion.items));
let flattenedCompletions = flatten(
completions.map((completion) => completion.result.items)
);
const isIncomplete = completions.reduce(
(incomplete, completion) => incomplete || completion.isIncomplete,
(incomplete, completion) => incomplete || completion.result.isIncomplete,
false as boolean
);

Expand Down
1 change: 1 addition & 0 deletions packages/language-server/src/plugins/css/CSSPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export class CSSPlugin
DocumentSymbolsProvider,
SelectionRangeProvider
{
__name = 'css';
private configManager: LSConfigManager;
private cssDocuments = new WeakMap<Document, CSSDocument>();
private triggerCharacters = ['.', ':', '-', '/'];
Expand Down
1 change: 1 addition & 0 deletions packages/language-server/src/plugins/html/HTMLPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { possiblyComponent } from '../../utils';
export class HTMLPlugin
implements HoverProvider, CompletionsProvider, RenameProvider, LinkedEditingRangesProvider
{
__name = 'html';
private configManager: LSConfigManager;
private lang = getLanguageService({
customDataProviders: [svelteHtmlDataProvider],
Expand Down
2 changes: 1 addition & 1 deletion packages/language-server/src/plugins/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,4 +226,4 @@ export type Plugin = Partial<
OnWatchFileChanges &
SelectionRangeProvider &
UpdateTsOrJsFile
>;
> & { __name: string };
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export class SveltePlugin
CodeActionsProvider,
SelectionRangeProvider
{
__name = 'svelte';
private docManager = new Map<Document, SvelteDocument>();

constructor(private configManager: LSConfigManager) {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ export interface SnapshotFragment extends DocumentMapper {
*/
export interface SvelteSnapshotOptions {
transformOnTemplateError: boolean;
useNewTransformation: boolean;
typingsNamespace: string;
}

export namespace DocumentSnapshot {
Expand Down Expand Up @@ -159,13 +161,21 @@ function preprocessSvelteFile(document: Document, options: SvelteSnapshotOptions
getScriptKindFromAttributes(document.scriptInfo?.attributes ?? {}),
getScriptKindFromAttributes(document.moduleScriptInfo?.attributes ?? {})
].includes(ts.ScriptKind.TSX)
? ts.ScriptKind.TSX
? options.useNewTransformation
? ts.ScriptKind.TS
: ts.ScriptKind.TSX
: options.useNewTransformation
? ts.ScriptKind.JS
: ts.ScriptKind.JSX;

try {
const tsx = svelte2tsx(text, {
filename: document.getFilePath() ?? undefined,
isTsFile: scriptKind === ts.ScriptKind.TSX,
isTsFile: options.useNewTransformation
? scriptKind === ts.ScriptKind.TS
: scriptKind === ts.ScriptKind.TSX,
mode: options.useNewTransformation ? 'ts' : 'tsx',
typingsNamespace: options.useNewTransformation ? options.typingsNamespace : undefined,
emitOnTemplateError: options.transformOnTemplateError,
namespace: document.config?.compilerOptions?.namespace,
accessors:
Expand Down Expand Up @@ -388,7 +398,7 @@ export class SvelteSnapshotFragment implements SnapshotFragment {
constructor(
private readonly mapper: DocumentMapper,
public readonly text: string,
private readonly parent: Document,
public readonly parent: Document,
private readonly url: string
) {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export class LSAndTSDocResolver {
return {
ambientTypesSource: this.isSvelteCheck ? 'svelte-check' : 'svelte2tsx',
createDocument: this.createDocument,
useNewTransformation: this.configManager.getConfig().svelte.useNewTransformation,
transformOnTemplateError: !this.isSvelteCheck,
globalSnapshotsManager: this.globalSnapshotsManager,
notifyExceedSizeLimit: this.notifyExceedSizeLimit
Expand Down
Loading