-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert-type.ts
More file actions
64 lines (61 loc) · 1.69 KB
/
convert-type.ts
File metadata and controls
64 lines (61 loc) · 1.69 KB
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
import type { DSNode } from 'css-tree'
import { definitionSyntax } from 'css-tree'
import { toPascalCase } from './to-pascalcase'
/**
* convert type
*/
export function convertType(
type: string,
syntaxs: Record<string, { syntax: string; primitive?: boolean }>,
): string {
const ast = definitionSyntax.parse(type)
return [convertNode(ast, syntaxs), 'Globals'].filter(Boolean).join(' | ')
}
function convertNode(
node: DSNode,
syntaxs: Record<string, { syntax: string; primitive?: boolean }>,
): string {
switch (node.type) {
case 'Keyword':
return `"${node.name}"`
case 'String':
return `"${node.value}"`
case 'Type': {
const typeName = node.name
if (typeName.startsWith("'") && typeName.endsWith("'")) {
const propName = typeName.slice(1, -1)
return toPascalCase(propName)
}
if (typeName.endsWith('()')) return ''
if (syntaxs[typeName]) {
if (syntaxs[typeName].primitive) return syntaxs[typeName].syntax
return `T${toPascalCase(typeName)}`
}
return ''
}
case 'Multiplier': {
return convertNode(node.term, syntaxs)
}
case 'Group': {
return removeDuplicates(
node.terms.map((term) => convertNode(term, syntaxs)).filter(Boolean),
).join(' | ')
}
case 'Function':
return ''
case 'Comma':
return ''
case 'Property':
return `Property.${toPascalCase(node.name)}`
case 'Token':
return ''
case 'AtKeyword':
return `@${node.name}`
default:
return ''
}
}
// remove duplicates from array
function removeDuplicates<T>(array: T[]): T[] {
return array.filter((value, index, self) => self.indexOf(value) === index)
}