Skip to content
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

Supporting korean (and boilerplates for i18n) #49

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
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
72 changes: 40 additions & 32 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,74 +4,82 @@ import {
MarkdownString,
Range,
window,
} from "vscode";
import { createConverter } from "vscode-languageclient/lib/common/codeConverter";
import { formatDiagnostic } from "./format/formatDiagnostic";
import { prettify } from "./format/prettify";
import { hoverProvider } from "./provider/hoverProvider";
import { registerSelectedTextHoverProvider } from "./provider/selectedTextHoverProvider";
import { uriStore } from "./provider/uriStore";
import { has } from "./utils";
env
} from 'vscode'
import * as vscode from 'vscode'
import { createConverter } from 'vscode-languageclient/lib/common/codeConverter'
import { formatDiagnostic } from './format/formatDiagnostic'
import { prettify } from './format/prettify'
import { hoverProvider } from './provider/hoverProvider'
import { registerSelectedTextHoverProvider } from './provider/selectedTextHoverProvider'
import { uriStore } from './provider/uriStore'
import { has } from './utils'
import { getLocale } from './format/i18n/locales'

export function activate(context: ExtensionContext) {
const registeredLanguages = new Set<string>();
const converter = createConverter();
const registeredLanguages = new Set<string>()
const converter = createConverter()
const { regexes } = getLocale(env.language)

registerSelectedTextHoverProvider(context);
registerSelectedTextHoverProvider(context, regexes)

context.subscriptions.push(
languages.onDidChangeDiagnostics(async (e) => {
e.uris.forEach((uri) => {
const diagnostics = languages.getDiagnostics(uri);
const diagnostics = languages.getDiagnostics(uri)

const items: {
range: Range;
contents: MarkdownString[];
}[] = [];
range: Range
contents: MarkdownString[]
}[] = []

let hasTsDiagnostic = false;
let hasTsDiagnostic = false

diagnostics
.filter((diagnostic) =>
diagnostic.source
? has(["ts", "deno-ts", "js"], diagnostic.source)
? has(['ts', 'deno-ts', 'js'], diagnostic.source)
: false
)
.forEach(async (diagnostic) => {
// formatDiagnostic converts message based on LSP Diagnostic type, not VSCode Diagnostic type, so it can be used in other IDEs.
// Here we convert VSCode Diagnostic to LSP Diagnostic to make formatDiagnostic recognize it.
const markdownString = new MarkdownString(
formatDiagnostic(converter.asDiagnostic(diagnostic), prettify)
);
formatDiagnostic(
converter.asDiagnostic(diagnostic),
prettify,
regexes
)
)

markdownString.isTrusted = true;
markdownString.supportHtml = true;
markdownString.isTrusted = true
markdownString.supportHtml = true

items.push({
range: diagnostic.range,
contents: [markdownString],
});
hasTsDiagnostic = true;
});
uriStore[uri.path] = items;
contents: [markdownString]
})
hasTsDiagnostic = true
})
uriStore[uri.path] = items

if (hasTsDiagnostic) {
const editor = window.visibleTextEditors.find(
(editor) => editor.document.uri.toString() === uri.toString()
);
)
if (editor && !registeredLanguages.has(editor.document.languageId)) {
registeredLanguages.add(editor.document.languageId);
registeredLanguages.add(editor.document.languageId)
context.subscriptions.push(
languages.registerHoverProvider(
{
language: editor.document.languageId,
language: editor.document.languageId
},
hoverProvider
)
);
)
}
}
});
})
})
);
)
}
10 changes: 7 additions & 3 deletions src/format/formatDiagnostic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,20 @@ import { Diagnostic } from "vscode-languageserver-types";
import { title } from "../components";
import { d } from "../utils";
import { embedSymbolLinks } from "./embedSymbolLinks";
import { formatDiagnosticMessage } from "./formatDiagnosticMessage";
import { FormatDiagnosticMessageRules, formatDiagnosticMessage } from "./formatDiagnosticMessage";
import { identSentences } from "./identSentences";

export function formatDiagnostic(diagnostic: Diagnostic, format: (type: string) => string) {
export function formatDiagnostic(diagnostic: Diagnostic, format: (type: string) => string, formatRegexes:Record<FormatDiagnosticMessageRules,RegExp>) {
const newDiagnostic = embedSymbolLinks(diagnostic);

return d/*html*/ `
${title(newDiagnostic)}
<span>
${formatDiagnosticMessage(identSentences(newDiagnostic.message), format)}
${formatDiagnosticMessage(
identSentences(newDiagnostic.message),
format,
formatRegexes
)}
</span>
`;
}
78 changes: 45 additions & 33 deletions src/format/formatDiagnosticMessage.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { inlineCodeBlock, unstyledCodeBlock } from "../components";
import { formatTypeBlock } from "./formatTypeBlock";
import { inlineCodeBlock, unstyledCodeBlock } from '../components'
import { formatTypeBlock } from './formatTypeBlock'

const formatTypeScriptBlock = (_: string, code: string) =>
inlineCodeBlock(code, "typescript");
inlineCodeBlock(code, 'typescript')

const formatSimpleTypeBlock = (_: string, code: string) =>
inlineCodeBlock(code, "type");
inlineCodeBlock(code, 'type')

const formatTypeOrModuleBlock = (
_: string,
Expand All @@ -15,88 +15,100 @@ const formatTypeOrModuleBlock = (
) =>
formatTypeBlock(
prefix,
["module", "file", "file name"].includes(prefix.toLowerCase())
['module', 'file', 'file name'].includes(prefix.toLowerCase())
? `"${code}"`
: code,
format
);
)

export type FormatDiagnosticMessageRules =
| 'DeclareModuleSnippet'
| 'MissingPropsError'
| 'TypePairs'
| 'TypeAnnotationOptions'
| 'Overloaded'
| 'SimpleStrings'
| 'Types'
| 'ReversedTypes'
| 'SimpleTypesRest'
| 'TypescriptKeywords'
| 'ReturnValues'
| 'RegularCodeBlocks'

export const formatDiagnosticMessage = (
message: string,
format: (type: string) => string
format: (type: string) => string,
regexes: Record<FormatDiagnosticMessageRules, RegExp>
) =>
message
// format declare module snippet
.replaceAll(
/'(declare module )'(.*)';'/g,
regexes['DeclareModuleSnippet'],
(_: string, p1: string, p2: string) =>
formatTypeScriptBlock(_, `${p1} "${p2}"`)
)
// format missing props error
.replaceAll(
/(is missing the following properties from type )'(.*)': (.+?)(?=and|$)/g,
regexes['MissingPropsError'],
(_, pre, type, post) =>
`${pre}${formatTypeBlock("", type, format)}: <ul>${post
.split(", ")
`${pre}${formatTypeBlock('', type, format)}: <ul>${post
.split(', ')
.filter(Boolean)
.map((prop: string) => `<li>${prop}</li>`)
.join("")}</ul>`
.join('')}</ul>`
)
// Format type pairs
.replaceAll(
/(types) '(.*?)' and '(.*?)'[\.]?/gi,
regexes['TypePairs'],
(_: string, p1: string, p2: string, p3: string) =>
`${formatTypeBlock(p1, p2, format)} and ${formatTypeBlock(
"",
'',
p3,
format
)}`
)
// Format type annotation options
.replaceAll(
/type annotation must be '(.*?)' or '(.*?)'[\.]?/gi,
regexes['TypeAnnotationOptions'],
(_: string, p1: string, p2: string, p3: string) =>
`${formatTypeBlock(p1, p2, format)} or ${formatTypeBlock(
"",
'',
p3,
format
)}`
)
// Format Overloaded
.replaceAll(
/(Overload \d of \d), '(.*?)', /gi,
(_, p1: string, p2: string) => `${p1}${formatTypeBlock("", p2, format)}`
regexes['Overloaded'],
(_, p1: string, p2: string) => `${p1}${formatTypeBlock('', p2, format)}`
)
// format simple strings
.replaceAll(/^'"[^"]*"'$/g, formatTypeScriptBlock)
.replaceAll(regexes['SimpleStrings'], formatTypeScriptBlock)
// Format types
.replaceAll(
/(type|type alias|interface|module|file|file name|method's) '(.*?)'(?=[\s.])/gi,
(_, p1: string, p2: string) => formatTypeOrModuleBlock(_, p1, p2, format)
.replaceAll(regexes['Types'], (_, p1: string, p2: string) =>
formatTypeOrModuleBlock(_, p1, p2, format)
)
// Format reversed types
.replaceAll(
/(.*)'([^>]*)' (type|interface|return type|file|module)/gi,
regexes['ReversedTypes'],
(_: string, p1: string, p2: string, p3: string) =>
`${p1}${formatTypeOrModuleBlock(_, "", p2, format)} ${p3}`
`${p1}${formatTypeOrModuleBlock(_, '', p2, format)} ${p3}`
)
// Format simple types that didn't captured before
.replaceAll(
/'((void|null|undefined|any|boolean|string|number|bigint|symbol)(\[\])?)'/g,
formatSimpleTypeBlock
)
.replaceAll(regexes['SimpleTypesRest'], formatSimpleTypeBlock)
// Format some typescript key words
.replaceAll(
/'(import|export|require|in|continue|break|let|false|true|const|new|throw|await|for await|[0-9]+)( ?.*?)'/g,
regexes['TypescriptKeywords'],
(_: string, p1: string, p2: string) =>
formatTypeScriptBlock(_, `${p1}${p2}`)
)
// Format return values
.replaceAll(
/(return|operator) '(.*?)'/gi,
(_, p1: string, p2: string) => `${p1} ${formatTypeScriptBlock("", p2)}`
regexes['ReturnValues'],
(_, p1: string, p2: string) => `${p1} ${formatTypeScriptBlock('', p2)}`
)
// Format regular code blocks
.replaceAll(
/'((?:(?!:\s*}).)*?)' (?!\s*:)/g,
regexes['RegularCodeBlocks'],
(_: string, p1: string) => `${unstyledCodeBlock(p1)} `
);
)
92 changes: 65 additions & 27 deletions src/test/suite/errorMessageMocks.ts → src/format/i18n/en.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,83 @@
import { d } from "../../utils";
import { inlineCodeBlock } from '../../components'
import { ErrorMessageMocks, TestSuites } from '../../test/suite/types'
import { d } from '../../utils'
import { FormatDiagnosticMessageRules } from '../formatDiagnosticMessage'
import { Locale } from './locales'

/**
* This file contains mocks of error messages, only some of them
* are used in tests but all of them can be used to test and debug
* the formatting visually, you can try to select them on debug and check the hover.
*/
const regexes: Record<FormatDiagnosticMessageRules, RegExp> = {
DeclareModuleSnippet: /'(declare module )'(.*)';'/g,
MissingPropsError:
/(is missing the following properties from type .*: )(.+?)(?=and|$)/g,
TypePairs: /(types) '(.*?)' and '(.*?)'[\.]?/gi,
TypeAnnotationOptions: /type annotation must be '(.*?)' or '(.*?)'[\.]?/gi,
Overloaded: /(Overload \d of \d), '(.*?)', /gi,
SimpleStrings: /^'"[^"]*"'$/g,
Types: /(.*)'([^>]*)' (type|interface|return type|file|module)/gi,
ReversedTypes: /(.*)'([^>]*)' (type|interface|return type|file|module)/gi,
SimpleTypesRest:
/'((void|null|undefined|any|boolean|string|number|bigint|symbol)(\[\])?)'/g,
TypescriptKeywords:
/'(import|export|require|in|continue|break|let|false|true|const|new|throw|await|for await|[0-9]+)( ?.*?)'/g,
ReturnValues: /(return|operator) '(.*?)'/gi,
RegularCodeBlocks: /'(.*?)'/g
}

export const errorWithSpecialCharsInObjectKeys = d`
Type 'string' is not assignable to type '{ 'abc*bc': string; }'.
`;
const testCase: Record<TestSuites, string> = {
'Test of adding missing parentheses': 'Hello, {world! [This] is a (test.)}',

export const errorWithDashInObjectKeys = d`
Type '{ person: { 'first-name': string; }; }' is not assignable to type 'string'.
`;
'Special characters in object keys':
'Type ' +
inlineCodeBlock('string', 'type') +
' is not assignable to type ' +
inlineCodeBlock(`{ "abc*bc": string }`, 'type') +
'.',

"Special method's word in the error":
'Type ' +
inlineCodeBlock(`{ person: { "first-name": string } }`, 'type') +
' is not assignable to type ' +
inlineCodeBlock('string', 'type') +
'.',

'Formatting type with params destructuring should succeed': ''
}

/**
* Formatting error from this issue: https://github.com/yoavbls/pretty-ts-errors/issues/20
*/
export const errorWithMethodsWordInIt = d`
const errorMessageMocks: Record<ErrorMessageMocks, string> = {
errorWithSpecialCharsInObjectKeys: d`
Type 'string' is not assignable to type '{ 'abc*bc': string; }'.
`,
errorWithDashInObjectKeys: d`
Type '{ person: { 'first-name': string; }; }' is not assignable to type 'string'.
`,
errorWithMethodsWordInIt: d`
The 'this' context of type 'ElementHandle<Node>' is not assignable to method's 'this' of type 'ElementHandle<Element>'.
Type 'Node' is missing the following properties from type 'Element': attributes, classList, className, clientHeight, and 114 more.
`;

const errorWithParamsDestructuring = d`
`,
errorWithParamsDestructuring: d`
Argument of type '{ $ref: null; ref: (ref: any) => any; columns: ({ label: string; prop: string; } | { label: string; formatter: ({ ip_type }: any) => any; } | { actions: { label: string; disabled: ({ contract_id }: any) => boolean; handler({ contract_id }: any): void; }[]; })[]; ... 4 more ...; load(): Promise<...>; }' is not assignable to parameter of type 'VTableConfig'.
Property 'data' is missing in type '{ $ref: null; ref: (ref: any) => any; columns: ({ label: string; prop: string; } | { label: string; formatter: ({ ip_type }: any) => any; } | { actions: { label: string; disabled: ({ contract_id }: any) => boolean; handler({ contract_id }: any): void; }[]; })[]; ... 4 more ...; load(): Promise<...>; }' but required in type 'VTableConfig'.
`;
`,

const errorWithLongType = d`
errorWithLongType: d`
Property 'isFlying' is missing in type '{ animal: { __typename?: "Animal" | undefined; id: string; name: string; age: number; isAlived: boolean; ... 8 more ...; attributes: { ...; } | ... 3 more ... | { ...; }; }; }' but required in type '{ animal: { __typename?: "Animal" | undefined; id: string; name: string; age: number; isAlived: boolean; isFlying: boolean; ... 8 more ...; attributes: { ...; } | ... 3 more ... | { ...; }; }; }'.
`;
`,

const errorWithTruncatedType2 = d`
errorWithTruncatedType2: d`
Type '{ '!top': string[]; 'xsl:declaration': { attrs: { 'default-collation': null; 'exclude-result-prefixes': null; 'extension-element-prefixes': null; 'use-when': null; 'xpath-default-namespace': null; }; }; 'xsl:instruction': { ...; }; ... 49 more ...; 'xsl:literal-result-element': {}; }' is missing the following properties from type 'GraphQLSchema': description, extensions, astNode, extensionASTNodes, and 21 more.
`;
`,

const errorWithSimpleIndentations = d`
errorWithSimpleIndentations: d`
Type '(newIds: number[]) => void' is not assignable to type '(selectedId: string[]) => void'.
Types of parameters 'newIds' and 'selectedId' are incompatible.
Type 'string[]' is not assignable to type 'number[]'.
Type 'string' is not assignable to type 'number'.
`;
`
}

const en: Locale = {
regexes,
testCase,
errorMessageMocks
}

("Property 'user' is missing in type '{ person: { username: string; email: string; }; }' but required in type '{ user: { name: string; email: `${string}@${string}.${string}`; age: number; }; }'.");
export default en
Loading