|
| 1 | +import { findChildContainingPositionIncludingStartTrivia } from '../utils' |
| 2 | + |
| 3 | +export const getJsdocDefaultTypes = (position: number, sourceFile: ts.SourceFile, languageService: ts.LanguageService) => { |
| 4 | + const fileText = sourceFile.getFullText().slice(0, position) |
| 5 | + const textBeforeWord = fileText.slice(0, /[-\w\d]*$/i.exec(fileText)!.index) |
| 6 | + if (!textBeforeWord.endsWith('@default ')) return |
| 7 | + const comment = languageService.getSpanOfEnclosingComment(sourceFile.fileName, position, false) |
| 8 | + if (!comment) return |
| 9 | + let node = findChildContainingPositionIncludingStartTrivia(ts, sourceFile, position) |
| 10 | + if (!node) return |
| 11 | + if (ts.isVariableDeclarationList(node)) node = node.declarations[0] |
| 12 | + if (!node) return |
| 13 | + const typeChecker = languageService.getProgram()!.getTypeChecker()! |
| 14 | + try { |
| 15 | + const type = typeChecker.getTypeAtLocation(node) |
| 16 | + if (!type.isUnion()) return |
| 17 | + const suggestions: [name: string, type: ts.Type, isLiteral: boolean][] = [] |
| 18 | + for (const nextType of type.types) { |
| 19 | + const addSuggestions = (isLiteral: boolean, ...addSuggestions: string[]) => { |
| 20 | + suggestions.push(...addSuggestions.map(suggestion => [suggestion, nextType, isLiteral] as [string, ts.Type, boolean])) |
| 21 | + } |
| 22 | + if (nextType.isLiteral()) addSuggestions(true, nextType.value.toString()) |
| 23 | + else if (nextType.flags & ts.TypeFlags.BooleanLiteral) addSuggestions(true, nextType['intrinsicName']) |
| 24 | + else if (nextType.flags & ts.TypeFlags.Boolean) addSuggestions(false, 'true', 'false') |
| 25 | + else if (nextType.flags & ts.TypeFlags.Undefined) addSuggestions(false, 'undefined') |
| 26 | + else if (nextType.flags & ts.TypeFlags.Null) addSuggestions(false, 'null') |
| 27 | + } |
| 28 | + return suggestions |
| 29 | + } catch (err) { |
| 30 | + return |
| 31 | + } |
| 32 | + |
| 33 | + return |
| 34 | +} |
| 35 | + |
| 36 | +export default ( |
| 37 | + entries: ts.CompletionEntry[], |
| 38 | + position: number, |
| 39 | + sourceFile: ts.SourceFile, |
| 40 | + languageService: ts.LanguageService, |
| 41 | +): ts.CompletionEntry[] | undefined => { |
| 42 | + const suggestions = getJsdocDefaultTypes(position, sourceFile, languageService) |
| 43 | + if (!suggestions) return |
| 44 | + return [ |
| 45 | + ...[...new Set(suggestions)].map( |
| 46 | + ([s]): ts.CompletionEntry => ({ |
| 47 | + name: s, |
| 48 | + sortText: '07', |
| 49 | + kind: ts.ScriptElementKind.string, |
| 50 | + }), |
| 51 | + ), |
| 52 | + ...entries, |
| 53 | + ] as ts.CompletionEntry[] |
| 54 | +} |
0 commit comments