Skip to content

Commit cc49905

Browse files
committed
feat: update locality bonus!
Now variables defined before have more priority, added a setting so you can return old behavior, which was also improved.
1 parent eee48c3 commit cc49905

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

src/configurationType.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,11 @@ export type Configuration = {
127127
* @default false
128128
*/
129129
'suggestions.localityBonus': boolean
130+
/**
131+
* position = cursor position
132+
* @default prefer-before-position
133+
*/
134+
'suggestions.localityBonusMode': 'prefer-before-position' | 'nearest-to-position'
130135
// TODO! corrent watching!
131136
/**
132137
* Wether to enable snippets for array methods like `items.map(item => )`
Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,27 @@
11
import { sharedCompletionContext } from './sharedContext'
22

33
export default (entries: ts.CompletionEntry[]) => {
4-
const { node, sourceFile, c } = sharedCompletionContext
4+
const { node, sourceFile, c, position } = sharedCompletionContext
55
if (!c('suggestions.localityBonus')) return
66

7-
const getScore = entry => {
8-
// TODO once TS is updated resolve
9-
// eslint-disable-next-line prefer-destructuring
10-
const symbol: ts.Symbol | undefined = entry['symbol']
7+
if (!node) return
8+
const LOWEST_SCORE = node.getSourceFile().getFullText().length
9+
const getScore = (entry: ts.CompletionEntry) => {
10+
const { symbol } = entry
1111
if (!symbol) return
1212
const { valueDeclaration = symbol.declarations?.[0] } = symbol
1313
if (!valueDeclaration) return
14-
if (valueDeclaration.getSourceFile().fileName !== sourceFile.fileName) return -1
15-
return valueDeclaration.pos
14+
if (valueDeclaration.getSourceFile().fileName !== sourceFile.fileName) return LOWEST_SCORE
15+
const completionPos = valueDeclaration.pos + valueDeclaration.getLeadingTriviaWidth()
16+
if (c('suggestions.localityBonusMode') === 'nearest-to-position') {
17+
return Math.abs(completionPos - position)
18+
}
19+
return completionPos < position ? -position - completionPos : completionPos - position
1620
}
17-
if (!node) return
1821
return [...entries].sort((a, b) => {
1922
const aScore = getScore(a)
2023
const bScore = getScore(b)
2124
if (aScore === undefined || bScore === undefined) return 0
22-
return bScore - aScore
25+
return aScore - bScore
2326
})
2427
}

0 commit comments

Comments
 (0)