Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/configurationType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export type Configuration = {
*/
// volarLoadConfigPaths: string[]
/**
* Removes `Symbol`, `caller`, `prototype` everywhere
* Removes annoying `Symbol`, `caller`, `prototype` everywhere
* @default true
* */
'removeUselessFunctionProps.enable': boolean
Expand Down
3 changes: 2 additions & 1 deletion src/specialCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,11 +254,12 @@ export default () => {

onCompletionAcceptedOverride.value = () => {}
const { ranges, text } = await new Promise<{ text: string; ranges: vscode.Range[] }>(resolve => {
vscode.workspace.onDidChangeTextDocument(({ document, contentChanges }) => {
const { dispose } = vscode.workspace.onDidChangeTextDocument(({ document, contentChanges }) => {
if (document !== editor.document || contentChanges.length === 0) return
const ranges = contentChanges.map(
change => new vscode.Range(change.range.start, offsetPosition(document, change.range.start, change.text.length)),
)
dispose()
resolve({ ranges, text: contentChanges[0]!.text })
})
void vscode.commands.executeCommand('acceptSelectedSuggestion')
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { matchParents } from '../../utils'
import { ExtendedCodeAction } from '../getCodeActions'

export default {
codes: [2339],
kind: 'quickfix',
title: 'Declare missing property',
tryToApply({ sourceFile, node }) {
if (node && ts.isIdentifier(node) && ts.isObjectBindingPattern(node.parent.parent) && ts.isParameter(node.parent.parent.parent)) {
const param = node.parent.parent.parent
const param = matchParents(node, ['Identifier', 'ObjectBindingPattern', 'Parameter'])
if (param) {
// special react pattern
if (ts.isArrowFunction(param.parent) && ts.isVariableDeclaration(param.parent.parent)) {
const variableDecl = param.parent.parent
Expand All @@ -19,7 +20,7 @@ export default {
const hasMembers = param.type.members.length > 0
const insertPos = param.type.members.at(-1)?.end ?? param.type.end - 1
const insertComma = hasMembers && sourceFile.getFullText().slice(insertPos - 1, insertPos) !== ','
let insertText = node.text
let insertText = (node as ts.Identifier).text
if (insertComma) insertText = `, ${insertText}`
// alternatively only one snippetEdit could be used with tsFull.escapeSnippetText(insertText) + $0
return {
Expand Down
4 changes: 2 additions & 2 deletions typescript/src/codeActions/getCodeActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { ApplyExtendedCodeActionResult, IpcExtendedCodeAction } from '../ipcType
import objectSwapKeysAndValues from './custom/objectSwapKeysAndValues'
import changeStringReplaceToRegex from './custom/changeStringReplaceToRegex'
import splitDeclarationAndInitialization from './custom/splitDeclarationAndInitialization'
import addMissingProperties from './extended/addMissingProperties'
import declareMissingProperties from './extended/declareMissingProperties'
import { renameParameterToNameFromType, renameAllParametersToNameFromType } from './custom/renameParameterToNameFromType'

const codeActions: CodeAction[] = [
Expand All @@ -15,7 +15,7 @@ const codeActions: CodeAction[] = [
renameParameterToNameFromType,
renameAllParametersToNameFromType,
]
const extendedCodeActions: ExtendedCodeAction[] = [addMissingProperties]
const extendedCodeActions: ExtendedCodeAction[] = [declareMissingProperties]

type SimplifiedRefactorInfo =
| {
Expand Down
5 changes: 3 additions & 2 deletions typescript/src/completions/functionCompletions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ export default (entries: ts.CompletionEntry[]) => {
const originalText = entry.insertText ?? entry.name
const insertTextSnippetAdd = `(${methodSnippet.map((x, i) => `$\{${i + 1}:${x}}`).join(', ')})`
// https://github.com/zardoy/typescript-vscode-plugins/issues/161
const beforeDotWorkaround = prior.isMemberCompletion && prevChar === '.'
// todo implement workaround for ?. as well
const beforeDotWorkaround = !entry.replacementSpan && prior.isMemberCompletion && prevChar === '.'
return {
...entry,
insertText: (beforeDotWorkaround ? '.' : '') + insertTextAfterEntry(originalText, insertTextSnippetAdd),
Expand All @@ -63,7 +64,7 @@ export default (entries: ts.CompletionEntry[]) => {
start: position - 1,
length: (c('editorSuggestInsertModeReplace') ? wordRangeAtPos(fullText, position).length : 0) + 1,
}
: undefined,
: entry.replacementSpan,
kind: ts.ScriptElementKind.functionElement,
isSnippet: true,
}
Expand Down
14 changes: 12 additions & 2 deletions typescript/src/completions/functionPropsAndMethods.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import { oneOf } from '@zardoy/utils'
import { matchParents } from '../utils'
import { sharedCompletionContext } from './sharedContext'

export default (entries: ts.CompletionEntry[]) => {
const { c, prevCompletionsMap } = sharedCompletionContext

if (c('removeUselessFunctionProps.enable')) {
entries = entries.filter(entry => {
if (oneOf(entry.kind, ts.ScriptElementKind.warning)) return true
return !['Symbol', 'caller', 'prototype'].includes(entry.name)
const completionDeclaration = entry.symbol?.valueDeclaration
if (
['Symbol', 'caller', 'prototype'].includes(entry.name) &&
!oneOf(entry.kind, ts.ScriptElementKind.warning) &&
(entry.insertText === '[Symbol]' ||
(completionDeclaration?.getSourceFile().fileName.includes('node_modules/typescript/lib/lib') &&
matchParents(completionDeclaration.parent, ['InterfaceDeclaration'])?.name.text === 'Function'))
) {
return false
}
return true
})
}

Expand Down
11 changes: 6 additions & 5 deletions typescript/src/completionsAtPosition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ export const getCompletionsAtPosition = (
const sourceFile = program?.getSourceFile(fileName)
if (!program || !sourceFile) return
if (!scriptSnapshot || isInBannedPosition(position, scriptSnapshot, sourceFile)) return
// just pick up random setting to check if we they are here
if (c('correctSorting.enable') === undefined) {
throw new Error(
"Plugin didn't get required user settings (config). Most probably there is a problem with TypeScript. Either restart TS server, use stable TS version or disable typescript-essentials-plugin if you need to test this TS version",
)
}
const exactNode = findChildContainingExactPosition(sourceFile, position)
const isCheckedFile =
!tsFull.isSourceFileJS(sourceFile as any) || !!tsFull.isCheckJsEnabledForFile(sourceFile as any, additionalData.compilerOptions as any)
Expand Down Expand Up @@ -226,11 +232,6 @@ export const getCompletionsAtPosition = (
// if (c('completionHelpers') && node) prior.entries = objectLiteralHelpers(node, prior.entries) ?? prior.entries

if (c('patchToString.enable')) {
// const indexToPatch = arrayMoveItemToFrom(
// prior.entries,
// ({ name }) => name === 'toExponential',
// ({ name }) => name === 'toString',
// )
const indexToPatch = prior.entries.findIndex(({ name, kind }) => name === 'toString' && kind !== ts.ScriptElementKind.warning)
if (indexToPatch !== -1) {
const entryToPatch = prior.entries[indexToPatch]!
Expand Down
22 changes: 22 additions & 0 deletions typescript/test/completions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,28 @@ test('String template type completions', () => {
})
})

test('Remove Useless Function Props', () => {
const tester = fourslashLikeTester(/* ts */ `
const a = () => {}
a./*1*/
const b = {
Symbol: 5,
prototype: 5,
caller: 5,
}
b./*2*/
`)
const badProps = ['Symbol', 'caller', 'prototype']
tester.completion(1, {
excludes: badProps,
})
tester.completion(2, {
includes: {
names: badProps,
},
})
})

test('Switch Case Exclude Covered', () => {
const [, _, numPositions] = fileContentsSpecialPositions(/*ts*/ `
let test: 'foo' | 'bar'
Expand Down
4 changes: 3 additions & 1 deletion typescript/test/testing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,9 @@ export const fourslashLikeTester = (contents: string, fileName = entrypoint) =>
}
}
if (excludes) {
expect(result?.entryNames, message).not.toContain(excludes)
for (const exclude of excludes) {
expect(result?.entryNames, message).not.toContain(exclude)
}
}
}
},
Expand Down