|
| 1 | +import { compact } from '@zardoy/utils' |
| 2 | +import { sharedCompletionContext } from './sharedContext' |
| 3 | + |
| 4 | +export default (): ts.CompletionEntry[] | void => { |
| 5 | + const { program } = sharedCompletionContext |
| 6 | + let { node } = sharedCompletionContext |
| 7 | + if (!node || !ts.isStringLiteralLike(node)) return |
| 8 | + const checker = program.getTypeChecker()! |
| 9 | + let type: ts.Type |
| 10 | + let objType: ts.Type | undefined |
| 11 | + if (ts.isElementAccessExpression(node.parent)) { |
| 12 | + objType = checker.getTypeAtLocation(node.parent.expression) |
| 13 | + } else if (ts.isPropertyAssignment(node.parent) && ts.isObjectLiteralExpression(node.parent.parent)) { |
| 14 | + objType = checker.getContextualType(node.parent.parent) ?? checker.getTypeAtLocation(node.parent.parent) |
| 15 | + } |
| 16 | + if (objType) { |
| 17 | + const [indexInfo] = checker.getIndexInfosOfType(objType) |
| 18 | + if (indexInfo) { |
| 19 | + type = indexInfo.keyType |
| 20 | + } |
| 21 | + } |
| 22 | + type ??= checker.getContextualType(node) ?? checker.getTypeAtLocation(node) |
| 23 | + const types = type.isUnion() ? type.types : [type] |
| 24 | + if (types.some(type => type.flags & ts.TypeFlags.TemplateLiteral)) { |
| 25 | + return compact( |
| 26 | + types.map(type => { |
| 27 | + if (!(type.flags & ts.TypeFlags.TemplateLiteral)) return |
| 28 | + |
| 29 | + const { |
| 30 | + texts: [head, ...spans], |
| 31 | + } = type as ts.TemplateLiteralType |
| 32 | + const texts = [head!, ...spans.flatMap(span => (span === '' ? [''] : ['', span]))] |
| 33 | + let tabStop = 1 |
| 34 | + return { |
| 35 | + kind: ts.ScriptElementKind.string, |
| 36 | + name: texts.map(text => (text === '' ? '|' : text)).join(''), |
| 37 | + sortText: '07', |
| 38 | + insertText: texts.map(text => (text === '' ? `$${tabStop++}` : text.replace(/\$/g, '\\$'))).join(''), |
| 39 | + isSnippet: true, |
| 40 | + } |
| 41 | + }), |
| 42 | + ) |
| 43 | + } |
| 44 | + |
| 45 | + return |
| 46 | +} |
0 commit comments