Skip to content

feat: add in keyword completions #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ You can quickly disable this plugin functionality by setting this setting to fal

Web-only feature: `import` path resolution

### `in` Keyword Suggestions

[Demo](https://github.com/zardoy/typescript-vscode-plugins/pull/19)

### Highlight non-function Methods

(*enabled by default*)
Expand Down
12 changes: 12 additions & 0 deletions typescript/src/completionsAtPosition.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import _ from 'lodash'
import type tslib from 'typescript/lib/tsserverlibrary'
import inKeywordCompletions from './inKeywordCompletions'
// import * as emmet from '@vscode/emmet-helper'
import isInBannedPosition from './completions/isInBannedPosition'
import { GetConfig } from './types'
Expand Down Expand Up @@ -186,6 +187,17 @@ export const getCompletionsAtPosition = (
return !banAutoImportPackages.includes(text)
})

const inKeywordCompletionsResult = inKeywordCompletions(position, node, sourceFile, program, languageService)
if (inKeywordCompletionsResult) {
prior.entries.push(...inKeywordCompletionsResult.completions)
Object.assign(
prevCompletionsMap,
_.mapValues(inKeywordCompletionsResult.docPerCompletion, value => ({
documentationOverride: value,
})),
)
}

if (c('suggestions.keywordsInsertText') === 'space') {
prior.entries = keywordsSpace(prior.entries, scriptSnapshot, position, exactNode)
}
Expand Down
67 changes: 67 additions & 0 deletions typescript/src/inKeywordCompletions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
export default (position: number, node: ts.Node | undefined, sourceFile: ts.SourceFile, program: ts.Program, languageService: ts.LanguageService) => {
if (!node) return
function isBinaryExpression(node: ts.Node): node is ts.BinaryExpression {
return node.kind === ts.SyntaxKind.BinaryExpression
}
const typeChecker = program.getTypeChecker()
// TODO info diagnostic if used that doesn't exist
if (
ts.isStringLiteralLike(node) &&
isBinaryExpression(node.parent) &&
node.parent.left === node &&
node.parent.operatorToken.kind === ts.SyntaxKind.InKeyword
) {
const quote = node.getText()[0]!
const type = typeChecker.getTypeAtLocation(node.parent.right)
const suggestionsData = new Map<
string,
{
insertText: string
usingDisplayIndexes: number[]
documentations: string[]
}
>()
const types = type.isUnion() ? type.types : [type]
for (let [typeIndex, typeEntry] of types.entries()) {
// improved DX: not breaking other completions as TS would display error anyway
if (!(typeEntry.flags & ts.TypeFlags.Object)) continue
for (const prop of typeEntry.getProperties()) {
const { name } = prop
if (!suggestionsData.has(name)) {
suggestionsData.set(name, {
insertText: prop.name.replace(quote, `\\${quote}`),
usingDisplayIndexes: [],
documentations: [],
})
}
suggestionsData.get(name)!.usingDisplayIndexes.push(typeIndex + 1)
// const doc = prop.getDocumentationComment(typeChecker)
const declaration = prop.getDeclarations()?.[0]
suggestionsData
.get(name)!
.documentations.push(`${typeIndex + 1}: ${declaration && typeChecker.typeToString(typeChecker.getTypeAtLocation(declaration))}`)
}
}
const docPerCompletion: Record<string, string> = {}
const maxUsingDisplayIndex = Math.max(...[...suggestionsData.entries()].map(([, { usingDisplayIndexes }]) => usingDisplayIndexes.length))
const completions: ts.CompletionEntry[] = [...suggestionsData.entries()]
.map(([originaName, { insertText, usingDisplayIndexes, documentations }], i) => {
const name = types.length > 1 && usingDisplayIndexes.length === 1 ? `☆${originaName}` : originaName
docPerCompletion[name] = documentations.join('\n\n')
return {
// ⚀ ⚁ ⚂ ⚃ ⚄ ⚅
name,
kind: ts.ScriptElementKind.string,
insertText,
sourceDisplay: [{ kind: 'text', text: usingDisplayIndexes.join(', ') }],
sortText: `${maxUsingDisplayIndex - usingDisplayIndexes.length}_${i}`,
}
})
.sort((a, b) => a.sortText.localeCompare(b.sortText))
return {
completions,
docPerCompletion,
}
}
return
}
8 changes: 8 additions & 0 deletions typescript/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,14 @@ export const isWeb = () => {
}
}

// spec isnt strict as well
export const notStrictStringCompletion = (entry: ts.CompletionEntry): ts.CompletionEntry => ({
...entry,
// todo
name: `◯${entry.name}`,
insertText: entry.insertText ?? entry.name,
})

export function addObjectMethodResultInterceptors<T extends Record<string, any>>(
object: T,
interceptors: Partial<{
Expand Down
69 changes: 68 additions & 1 deletion typescript/test/completions.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//@ts-ignore plugin expect it to set globallly
globalThis.__WEB__ = false
import { pickObj } from '@zardoy/utils'
import { createLanguageService } from '../src/dummyLanguageService'
import { getCompletionsAtPosition as getCompletionsAtPositionRaw } from '../src/completionsAtPosition'
import type {} from 'vitest/globals'
Expand Down Expand Up @@ -73,9 +74,10 @@ const settingsOverride = {
//@ts-ignore
const defaultConfigFunc = await getDefaultConfigFunc(settingsOverride)

const getCompletionsAtPosition = (pos: number, fileName = entrypoint) => {
const getCompletionsAtPosition = (pos: number, { fileName = entrypoint, shouldHave }: { fileName?: string; shouldHave?: boolean } = {}) => {
if (pos === undefined) throw new Error('getCompletionsAtPosition: pos is undefined')
const result = getCompletionsAtPositionRaw(fileName, pos, {}, defaultConfigFunc, languageService, ts.ScriptSnapshot.fromString(files[entrypoint]), ts)
if (shouldHave) expect(result).not.toBeUndefined()
if (!result) return
return {
...result,
Expand Down Expand Up @@ -422,3 +424,68 @@ test('Patched navtree (outline)', () => {
]
`)
})

test('In Keyword Completions', () => {
const [pos] = newFileContents(/* ts */ `
declare const a: { a: boolean, b: string } | { a: number, c: number } | string
if ('/*|*/' in a) {}
`)
const completion = pickObj(getCompletionsAtPosition(pos!, { shouldHave: true })!, 'entriesSorted', 'prevCompletionsMap')
// TODO this test is bad case of demonstrating how it can be used with string in union (IT SHOULDNT!)
// but it is here to ensure this is no previous crash issue, indexes are correct when used only with objects
expect(completion).toMatchInlineSnapshot(`
{
"entriesSorted": [
{
"insertText": "a",
"isSnippet": true,
"kind": "string",
"name": "a",
"sourceDisplay": [
{
"kind": "text",
"text": "2, 3",
},
],
},
{
"insertText": "b",
"isSnippet": true,
"kind": "string",
"name": "☆b",
"sourceDisplay": [
{
"kind": "text",
"text": "2",
},
],
},
{
"insertText": "c",
"isSnippet": true,
"kind": "string",
"name": "☆c",
"sourceDisplay": [
{
"kind": "text",
"text": "3",
},
],
},
],
"prevCompletionsMap": {
"a": {
"documentationOverride": "2: boolean

3: number",
},
"☆b": {
"documentationOverride": "2: string",
},
"☆c": {
"documentationOverride": "3: number",
},
},
}
`)
})