|
1 | 1 | import { sharedCompletionContext } from './sharedContext'
|
2 | 2 |
|
3 | 3 | export default (entries: ts.CompletionEntry[]) => {
|
4 |
| - const { node, sourceFile, c } = sharedCompletionContext |
| 4 | + const { node, sourceFile, c, position } = sharedCompletionContext |
5 | 5 | if (!c('suggestions.localityBonus')) return
|
6 | 6 |
|
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 |
11 | 11 | if (!symbol) return
|
12 | 12 | const { valueDeclaration = symbol.declarations?.[0] } = symbol
|
13 | 13 | 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 |
16 | 20 | }
|
17 |
| - if (!node) return |
18 | 21 | return [...entries].sort((a, b) => {
|
19 | 22 | const aScore = getScore(a)
|
20 | 23 | const bScore = getScore(b)
|
21 | 24 | if (aScore === undefined || bScore === undefined) return 0
|
22 |
| - return bScore - aScore |
| 25 | + return aScore - bScore |
23 | 26 | })
|
24 | 27 | }
|
0 commit comments