/
compodoc.ts
243 lines (216 loc) · 7.16 KB
/
compodoc.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/* eslint-disable no-underscore-dangle */
/* global window */
import { ArgType, ArgTypes } from '@storybook/api';
import { logger } from '@storybook/client-logger';
import {
Argument,
Class,
CompodocJson,
Component,
Injectable,
Method,
Pipe,
Property,
Directive,
} from './types';
export const isMethod = (methodOrProp: Method | Property): methodOrProp is Method => {
return (methodOrProp as Method).args !== undefined;
};
export const setCompodocJson = (compodocJson: CompodocJson) => {
// @ts-ignore
window.__STORYBOOK_COMPODOC_JSON__ = compodocJson;
};
// @ts-ignore
export const getCompodocJson = (): CompodocJson => window.__STORYBOOK_COMPODOC_JSON__;
export const checkValidComponentOrDirective = (component: Component | Directive) => {
if (!component.name) {
throw new Error(`Invalid component ${JSON.stringify(component)}`);
}
};
export const checkValidCompodocJson = (compodocJson: CompodocJson) => {
if (!compodocJson || !compodocJson.components) {
throw new Error('Invalid compodoc JSON');
}
};
const hasDecorator = (item: Property, decoratorName: string) =>
item.decorators && item.decorators.find((x: any) => x.name === decoratorName);
const mapPropertyToSection = (key: string, item: Property) => {
if (hasDecorator(item, 'ViewChild')) {
return 'view child';
}
if (hasDecorator(item, 'ViewChildren')) {
return 'view children';
}
if (hasDecorator(item, 'ContentChild')) {
return 'content child';
}
if (hasDecorator(item, 'ContentChildren')) {
return 'content children';
}
return 'properties';
};
const mapItemToSection = (key: string, item: Method | Property): string => {
switch (key) {
case 'methods':
case 'methodsClass':
return 'methods';
case 'inputsClass':
return 'inputs';
case 'outputsClass':
return 'outputs';
case 'properties':
case 'propertiesClass':
if (isMethod(item)) {
throw new Error("Cannot be of type Method if key === 'propertiesClass'");
}
return mapPropertyToSection(key, item);
default:
throw new Error(`Unknown key: ${key}`);
}
};
export const findComponentByName = (name: string, compodocJson: CompodocJson) =>
compodocJson.components.find((c: Component) => c.name === name) ||
compodocJson.directives.find((c: Directive) => c.name === name) ||
compodocJson.pipes.find((c: Pipe) => c.name === name) ||
compodocJson.injectables.find((c: Injectable) => c.name === name) ||
compodocJson.classes.find((c: Class) => c.name === name);
const getComponentData = (component: Component | Directive) => {
if (!component) {
return null;
}
checkValidComponentOrDirective(component);
const compodocJson = getCompodocJson();
checkValidCompodocJson(compodocJson);
const { name } = component;
const metadata = findComponentByName(name, compodocJson);
if (!metadata) {
logger.warn(`Component not found in compodoc JSON: '${name}'`);
}
return metadata;
};
const displaySignature = (item: Method): string => {
const args = item.args.map(
(arg: Argument) => `${arg.name}${arg.optional ? '?' : ''}: ${arg.type}`
);
return `(${args.join(', ')}) => ${item.returnType}`;
};
const extractTypeFromValue = (defaultValue: any) => {
const valueType = typeof defaultValue;
return defaultValue || valueType === 'boolean' || valueType === 'string' ? valueType : null;
};
const extractEnumValues = (compodocType: any) => {
const compodocJson = getCompodocJson();
const enumType = compodocJson?.miscellaneous.enumerations.find((x) => x.name === compodocType);
if (enumType?.childs.every((x) => x.value)) {
return enumType.childs.map((x) => x.value);
}
if (typeof compodocType !== 'string' || compodocType.indexOf('|') === -1) {
return null;
}
try {
return compodocType.split('|').map((value) => JSON.parse(value));
} catch (e) {
return null;
}
};
export const extractType = (property: Property, defaultValue: any) => {
const compodocType = property.type || extractTypeFromValue(defaultValue);
switch (compodocType) {
case 'string':
case 'boolean':
case 'number':
return { name: compodocType };
case undefined:
case null:
return { name: 'void' };
default: {
const resolvedType = resolveTypealias(compodocType);
const enumValues = extractEnumValues(resolvedType);
return enumValues ? { name: 'enum', value: enumValues } : { name: 'object' };
}
}
};
const extractDefaultValue = (property: Property) => {
try {
// eslint-disable-next-line no-eval
const value = eval(property.defaultValue);
return value;
} catch (err) {
logger.debug(`Error extracting ${property.name}: ${property.defaultValue}`);
return undefined;
}
};
const resolveTypealias = (compodocType: string): string => {
const compodocJson = getCompodocJson();
const typeAlias = compodocJson?.miscellaneous.typealiases.find((x) => x.name === compodocType);
return typeAlias ? resolveTypealias(typeAlias.rawtype) : compodocType;
};
export const extractArgTypesFromData = (componentData: Class | Directive | Injectable | Pipe) => {
const sectionToItems: Record<string, ArgType[]> = {};
const compodocClasses = ['component', 'directive'].includes(componentData.type)
? ['propertiesClass', 'methodsClass', 'inputsClass', 'outputsClass']
: ['properties', 'methods'];
type COMPODOC_CLASS =
| 'properties'
| 'methods'
| 'propertiesClass'
| 'methodsClass'
| 'inputsClass'
| 'outputsClass';
compodocClasses.forEach((key: COMPODOC_CLASS) => {
const data = (componentData as any)[key] || [];
data.forEach((item: Method | Property) => {
const section = mapItemToSection(key, item);
const defaultValue = isMethod(item) ? undefined : extractDefaultValue(item as Property);
const type =
isMethod(item) || section !== 'inputs'
? { name: 'void' }
: extractType(item as Property, defaultValue);
const argType = {
name: item.name,
description: item.description,
defaultValue,
type,
table: {
category: section,
type: {
summary: isMethod(item) ? displaySignature(item) : item.type,
required: isMethod(item) ? false : !item.optional,
},
},
};
if (!sectionToItems[section]) {
sectionToItems[section] = [];
}
sectionToItems[section].push(argType);
});
});
const SECTIONS = [
'inputs',
'outputs',
'properties',
'methods',
'view child',
'view children',
'content child',
'content children',
];
const argTypes: ArgTypes = {};
SECTIONS.forEach((section) => {
const items = sectionToItems[section];
if (items) {
items.forEach((argType) => {
argTypes[argType.name] = argType;
});
}
});
return argTypes;
};
export const extractArgTypes = (component: Component | Directive) => {
const componentData = getComponentData(component);
return componentData && extractArgTypesFromData(componentData);
};
export const extractComponentDescription = (component: Component | Directive) => {
const componentData = getComponentData(component);
return componentData && (componentData.rawdescription || componentData.description);
};