/
formatTypeBlock.ts
76 lines (70 loc) 路 2.5 KB
/
formatTypeBlock.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import {
inlineCodeBlock,
multiLineCodeBlock,
unStyledCodeBlock,
} from "../components";
import { addMissingParentheses } from "./addMissingParentheses";
export function formatTypeBlock(
prefix: string,
type: string,
format: (type: string) => string
) {
// Return a simple code block if it's just a parenthesis
if (type.match(/^(\[\]|\{\})$/)) {
return `${prefix} ${unStyledCodeBlock(type)}`;
}
if (
// Skip formatting if it's a simple type
type.match(
/^((void|null|undefined|any|number|string|bigint|symbol|readonly|typeof)(\[\])?)$/
)
) {
return `${prefix} ${inlineCodeBlock(type, "type")}`;
}
const prettyType = prettifyType(type, format);
if (prettyType.includes("\n")) {
return `${prefix}: ${multiLineCodeBlock(prettyType, "type")}`;
} else {
return `${prefix} ${inlineCodeBlock(prettyType, "type")}`;
}
}
/**
* Try to make type prettier with prettier
*/
export function prettifyType(
type: string,
format: (type: string) => string,
options?: { throwOnError?: boolean }
) {
try {
// Wrap type with valid statement, format it and extract the type back
return convertToOriginalType(format(convertToValidType(type)));
} catch (e) {
if (options?.throwOnError) {
throw e;
}
return type;
}
}
const convertToValidType = (type: string) =>
`type x = ${type
// Add missing parentheses when the type ends with "...""
.replace(/(.*)\.\.\.$/, (_, p1) => addMissingParentheses(p1))
// Replace single parameter function destructuring because it's not a valid type
// .replaceAll(/\((\{.*\})\:/g, (_, p1) => `(param: /* ${p1} */`)
// Change `(...): return` which is invalid to `(...) => return`
.replace(/^(\(.*\)): /, (_, p1) => `${p1} =>`)
.replaceAll(/... (\d{0,}) more .../g, (_, p1) => `___${p1}MORE___`)
.replaceAll(/... (\d{0,}) more ...;/g, (_, p1) => `___MORE___: ${p1};`)
.replaceAll("...;", "___KEY___: ___THREE_DOTS___;")
.replaceAll("...", "__THREE_DOTS__")};`;
const convertToOriginalType = (type: string) =>
type
.replaceAll("___KEY___: ___THREE_DOTS___", "...;")
.replaceAll("__THREE_DOTS__", "...")
.replaceAll(/___MORE___: (\d{0,});/g, (_, p1) => `... ${p1} more ...;`)
.replaceAll(/___(\d{0,})MORE___/g, (_, p1) => `... ${p1} more ...`)
.replaceAll(/... (\d{0,}) more .../g, (_, p1) => `/* ${p1} more */`) // ... x more ... not shown sell
// .replaceAll(/\(param\: \/\* (\{ .* \}) \*\//g, (_, p1) => `(${p1}: `)
.replace(/type x =[ ]?((.|\n)*);.*/g, "$1")
.trim();