Skip to content

Commit

Permalink
fix: inlay hint position sometimes off by one
Browse files Browse the repository at this point in the history
  • Loading branch information
BlueGreenMagick committed Jul 5, 2023
1 parent 48ae8ce commit aadaf85
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import ts from 'typescript';
import { CancellationToken } from 'vscode-languageserver';
import { Range, InlayHint, InlayHintKind } from 'vscode-languageserver-types';
import { Position, Range, InlayHint, InlayHintKind } from 'vscode-languageserver-types';
import { Document, isInTag } from '../../../lib/documents';
import { getAttributeContextAtPosition } from '../../../lib/documents/parseHtml';
import { InlayHintProvider } from '../../interfaces';
import { DocumentSnapshot } from '../DocumentSnapshot';
import { DocumentSnapshot, SvelteDocumentSnapshot } from '../DocumentSnapshot';
import { LSAndTSDocResolver } from '../LSAndTSDocResolver';
import {
findContainingNode,
Expand Down Expand Up @@ -61,7 +61,7 @@ export class InlayHintProviderImpl implements InlayHintProvider {
)
.map((inlayHint) => ({
label: inlayHint.text,
position: tsDoc.getOriginalPosition(tsDoc.positionAt(inlayHint.position)),
position: this.getOriginalPosition(document, tsDoc, inlayHint),
kind: this.convertInlayHintKind(inlayHint.kind),
paddingLeft: inlayHint.whitespaceBefore,
paddingRight: inlayHint.whitespaceAfter
Expand Down Expand Up @@ -104,6 +104,31 @@ export class InlayHintProviderImpl implements InlayHintProvider {
};
}

private getOriginalPosition(
document: Document,
tsDoc: SvelteDocumentSnapshot,
inlayHint: ts.InlayHint
): Position {
let originalPosition = tsDoc.getOriginalPosition(tsDoc.positionAt(inlayHint.position));
if (inlayHint.kind === ts.InlayHintKind.Type) {
const originalOffset = document.offsetAt(originalPosition);
const source = document.getText();
// detect if inlay hint position is off by one
// by checking if source[offset] is part of an identifier
// https://github.com/sveltejs/language-tools/pull/2070
if (
originalOffset < source.length &&
!/[\x00-\x23\x25-\x2F\x3A-\x40\x5B\x5D-\x5E\x60\x7B-\x7F]/.test(
source[originalOffset]
)
) {
originalPosition.character += 1;
}
}

return originalPosition;
}

private convertInlayHintKind(kind: ts.InlayHintKind): InlayHintKind | undefined {
switch (kind) {
case 'Parameter':
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"label": ": number[]",
"position": { "line": 1, "character": 11 },
"kind": 1,
"paddingLeft": true
},
{
"label": ": number",
"position": { "line": 4, "character": 23 },
"kind": 1,
"paddingLeft": true
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script lang="ts">
let items = [1]
</script>

{#each items as item, i}
{item}
{/each}

0 comments on commit aadaf85

Please sign in to comment.