Skip to content
Open
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
6 changes: 6 additions & 0 deletions .changeset/metal-numbers-brush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'svelte-language-server': patch
'svelte2tsx': patch
---

fix: improve diagnostics mapping for bind/transition directive
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { FileMap, FileSet } from '../../../lib/documents/fileCollection';
import { Logger } from '../../../logger';
import {
clamp,
isPositionEqual,
memoize,
normalizePath,
passMap,
Expand Down Expand Up @@ -55,6 +56,7 @@ import {
isInReactiveStatement,
isReactiveStatement
} from './utils';
import { getAttributeContextAtPosition } from '../../../lib/documents/parseHtml';

const VIRTUAL_SUFFIX = '_virtual__';
const SVELTE_EXT_LENGTH = '.svelte'.length;
Expand Down Expand Up @@ -837,6 +839,9 @@ function mapAndFilterDiagnostics(
if (!hasNoNegativeLines(diagnostic) || !noFalsePositive(diagnostic)) {
continue;
}
if (isPositionEqual(diagnostic.range.start, diagnostic.range.end)) {
adjustDirectiveRange(diagnostic, document);
}

diagnostic = adjustIfNecessary(diagnostic, tsDoc.isSvelte5Plus);
diagnostic = swapDiagRangeStartEndIfNecessary(diagnostic);
Expand All @@ -846,6 +851,29 @@ function mapAndFilterDiagnostics(
return converted;
}

function adjustDirectiveRange(diagnostic: Diagnostic, document: Document) {
const attributeContext = getAttributeContextAtPosition(document, diagnostic.range.start);
if (!attributeContext || attributeContext.inValue) {
return;
}

const colonIndex = attributeContext.name.indexOf(':');
if (colonIndex === -1) {
return;
}

const attributeStart = document
.getText()
.lastIndexOf(attributeContext.name, document.offsetAt(diagnostic.range.start));
const end = attributeStart + attributeContext.name.length;
const start = attributeContext.name.startsWith('bind:')
? attributeStart
: attributeStart + colonIndex + 1;

diagnostic.range.start = document.positionAt(start);
diagnostic.range.end = document.positionAt(end);
}

function flattenDiagnosticMessage(diag: tsApiSync.Diagnostic, level = 0): string {
if (!diag.messageChain) {
return diag.text;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,17 @@ import {
isStoreVariableIn$storeDeclaration,
get$storeOffsetOf$storeDeclaration
} from './utils';
import { not, passMap, swapRangeStartEndIfNecessary, memoize } from '../../../utils';
import {
not,
passMap,
swapRangeStartEndIfNecessary,
memoize,
isPositionEqual
} from '../../../utils';
import { LSConfigManager } from '../../../ls-config';
import { isAttributeName, isEventHandler } from '../svelte-ast-utils';
import { internalHelpers } from 'svelte2tsx';
import { getAttributeContextAtPosition } from '../../../lib/documents/parseHtml';

export enum DiagnosticCode {
MODIFIERS_CANNOT_APPEAR_HERE = 1184, // "Modifiers cannot appear here."
Expand Down Expand Up @@ -220,6 +227,10 @@ export function mapAndFilterDiagnostics(
continue;
}

if (isPositionEqual(diagnostic.range.start, diagnostic.range.end)) {
adjustDirectiveRange(diagnostic, document);
}

diagnostic = adjustIfNecessary(diagnostic, tsDoc.isSvelte5Plus);
diagnostic = swapDiagRangeStartEndIfNecessary(diagnostic);
converted.push(diagnostic);
Expand All @@ -228,6 +239,29 @@ export function mapAndFilterDiagnostics(
return converted;
}

function adjustDirectiveRange(diagnostic: Diagnostic, document: Document) {
const attributeContext = getAttributeContextAtPosition(document, diagnostic.range.start);
if (!attributeContext || attributeContext.inValue) {
return;
}

const colonIndex = attributeContext.name.indexOf(':');
if (colonIndex === -1) {
return;
}

const attributeStart = document
.getText()
.lastIndexOf(attributeContext.name, document.offsetAt(diagnostic.range.start));
const end = attributeStart + attributeContext.name.length;
const start = attributeContext.name.startsWith('bind:')
? attributeStart
: attributeStart + colonIndex + 1;

diagnostic.range.start = document.positionAt(start);
diagnostic.range.end = document.positionAt(end);
}

function moveBindingErrorMessage(
tsDiag: ts.Diagnostic,
tsDoc: SvelteDocumentSnapshot,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
## By design

- `fixtures/parser-error`, `fixtures/svelte-element-error`: the Svelte plugin reports the compiler error, the middleware drops the mapper's duplicate. TS6 reported it as a TS diagnostic, too.
- `fixtures/actions-animations-transitions-typechecks`: an element that doesn't fit a `transition:`/`use:` function is reported on the directive name, instead of TS6's empty range next to it.

## Not handled yet

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[
{
"range": { "start": { "line": 9, "character": 19 }, "end": { "line": 9, "character": 19 } },
"range": { "start": { "line": 9, "character": 16 }, "end": { "line": 9, "character": 20 } },
"severity": 1,
"source": "ts",
"message": "Argument of type 'HTMLDivElement' is not assignable to parameter of type 'SVGElement & { getTotalLength(): number; }'.\n Type 'HTMLDivElement' is missing the following properties from type 'SVGElement': ownerSVGElement, viewportElement",
Expand All @@ -9,8 +9,8 @@
},
{
"range": {
"start": { "line": 14, "character": 12 },
"end": { "line": 14, "character": 12 }
"start": { "line": 14, "character": 7 },
"end": { "line": 14, "character": 13 }
},
"severity": 1,
"source": "ts",
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[
{
"range": { "start": { "line": 9, "character": 19 }, "end": { "line": 9, "character": 19 } },
"range": { "start": { "line": 9, "character": 16 }, "end": { "line": 9, "character": 20 } },
"severity": 1,
"source": "ts",
"message": "Argument of type 'HTMLDivElement' is not assignable to parameter of type 'SVGElement & { getTotalLength(): number; }'.\n Type 'HTMLDivElement' is missing the following properties from type 'SVGElement': ownerSVGElement, viewportElement",
Expand All @@ -9,8 +9,8 @@
},
{
"range": {
"start": { "line": 14, "character": 12 },
"end": { "line": 14, "character": 12 }
"start": { "line": 14, "character": 7 },
"end": { "line": 14, "character": 13 }
},
"severity": 1,
"source": "ts",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
[
{
"range": { "start": { "line": 8, "character": 1 }, "end": { "line": 8, "character": 13 } },
"severity": 1,
"source": "ts",
"message": "Type 'string' is not assignable to type 'boolean | null | undefined'.",
"code": 2322,
"tags": []
},
{
"range": {
"start": { "line": 13, "character": 9 },
"end": { "line": 13, "character": 18 }
},
"severity": 1,
"source": "ts",
"message": "Type 'string' is not assignable to type 'boolean | null | undefined'.",
"code": 2322,
"tags": []
},
{
"range": {
"start": { "line": 14, "character": 23 },
"end": { "line": 14, "character": 35 }
},
"severity": 1,
"source": "ts",
"message": "Type 'string' is not assignable to type 'boolean | null | undefined'.",
"code": 2322,
"tags": []
},
{
"range": {
"start": { "line": 15, "character": 7 },
"end": { "line": 15, "character": 19 }
},
"severity": 1,
"source": "ts",
"message": "Type 'string' is not assignable to type 'boolean | null | undefined'.",
"code": 2322,
"tags": []
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<script lang="ts">
let v = '';
let count = '';
let checked = ''
</script>

<input
type="checkbox"
bind:checked={v}
/>

<p>text</p>

<details bind:open={count}>text</details>
<input type="checkbox" bind:checked={count} />
<input bind:checked type="checkbox" />
3 changes: 2 additions & 1 deletion packages/svelte2tsx/src/htmlxtojsx_v2/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,8 @@ export function convertHtmlxToJsx(
options.typingsNamespace === 'svelteHTML',
options.svelte5Plus,
emitJsDoc,
isTsFile
isTsFile,
options.spanMapGenerator
);
break;
case 'Class':
Expand Down
53 changes: 32 additions & 21 deletions packages/svelte2tsx/src/htmlxtojsx_v2/nodes/Binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { InlineComponent } from './InlineComponent';
import { surroundWithIgnoreComments } from '../../utils/ignore';
import { SequenceExpression } from 'estree';
import { getLeadingCommentTransformation, getTrailingCommentTransformation } from './Comment';
import { mapGenerated, SpanMapGenerator } from '../../utils/spanMap';

/**
* List of binding names that are transformed to sth like `binding = variable`.
Expand Down Expand Up @@ -60,7 +61,8 @@ export function handleBinding(
preserveBind: boolean,
isSvelte5Plus: boolean,
emitJsDoc: boolean,
isTsFile: boolean
isTsFile: boolean,
spanMapGenerator: SpanMapGenerator | undefined
): void {
const isGetSetBinding = attr.expression.type === 'SequenceExpression';
const [get, set] = isGetSetBinding ? (attr.expression as SequenceExpression).expressions : [];
Expand Down Expand Up @@ -148,27 +150,36 @@ export function handleBinding(

// other bindings which are transformed to normal attributes/props
const isShorthand = attr.expression.start === attr.start + 'bind:'.length;
const name: TransformationArray =
preserveBind && element instanceof Element
? // HTML typings - preserve the bind: prefix
isShorthand
? [...leadingComments, `"${str.original.substring(attr.start, attr.end)}"`]
: [
...leadingComments,
'"',
[attr.start, str.original.lastIndexOf('=', attr.expression.start)],
'"'
let name: TransformationArray;
if (preserveBind && element instanceof Element) {
// HTML typings - preserve the bind: prefix
if (isShorthand) {
const withQuote = mapGenerated(
spanMapGenerator,
`"${str.original.substring(attr.start, attr.end)}"`,
[attr.start, attr.end]
);
name = [...leadingComments, withQuote];
} else {
const endIndex = str.original.lastIndexOf('=', attr.expression.start);
name = [...leadingComments, [attr.start, endIndex], '"'];
str.overwrite(attr.start, attr.start + 1, '"' + str.original.charAt(attr.start), {
contentOnly: true
});
spanMapGenerator?.addSourceSpan(attr.start, endIndex);
}
} else {
// Other typings - remove the bind: prefix
name = isShorthand
? [...leadingComments, [attr.expression.start, attr.expression.end]]
: [
...leadingComments,
[
attr.start + 'bind:'.length,
str.original.lastIndexOf('=', attr.expression.start)
]
: // Other typings - remove the bind: prefix
isShorthand
? [...leadingComments, [attr.expression.start, attr.expression.end]]
: [
...leadingComments,
[
attr.start + 'bind:'.length,
str.original.lastIndexOf('=', attr.expression.start)
]
];
];
}

const value: TransformationArray | undefined = isShorthand
? preserveBind && element instanceof Element
Expand Down
1 change: 1 addition & 0 deletions packages/svelte2tsx/src/utils/spanMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ export class SpanMapGenerator {
const originalStart = original[segmentIndex];
const generatedStart = generated[segmentIndex];
if (this.ignoreMappings.has(originalStart)) {
current = undefined;
continue;
}
const sourceSpan = sourceSpanMap.get(originalStart);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,8 @@

<element
bind:foo={bar}
/>

<input
bind:checked={v}
/>
Loading