/
extract-arguments-usage.ts
97 lines (95 loc) · 2.57 KB
/
extract-arguments-usage.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
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { TraverseOptions } from '@babel/traverse';
import {
Story,
StoryArguments,
StoryArgument,
ArgUsageLocation,
} from '@component-controls/core';
import { adjustSourceLocation } from '../misc/source-location';
const findArguments = (
args: StoryArguments,
paramName: string,
): StoryArgument | undefined => {
let result: StoryArgument | undefined;
for (let i = 0; i < args.length; i += 1) {
const p = args[i];
if (Array.isArray(p.value)) {
result = findArguments(p.value, paramName);
if (result) {
break;
}
} else {
if (p.value === paramName) {
result = p;
break;
}
}
}
return result;
};
export const addArgumentUsage = (
story: Story,
args: StoryArguments,
node: any,
shorthand?: boolean,
): ArgUsageLocation | undefined => {
const param = findArguments(args, node.name);
if (param) {
if (param.usage === undefined) {
param.usage = [];
}
const loc = adjustSourceLocation(story, node.loc);
const existing = param.usage.find(
p =>
p.loc.start.line === loc.start.line &&
p.loc.start.column === loc.start.column &&
p.loc.end.line === loc.end.line &&
p.loc.end.column === loc.end.column,
);
const usage: ArgUsageLocation = { loc };
if (shorthand) {
usage.shorthand = shorthand;
}
if (!existing) {
param.usage.push(usage);
return usage;
}
}
return undefined;
};
export const extractArgumentsUsage = (
story: Story,
args: StoryArguments,
): TraverseOptions => {
return {
TemplateLiteral: (path: any) => {
path.node.expressions.forEach((expression: any) => {
if (expression.type === 'Identifier') {
addArgumentUsage(story, args, expression, expression.shorthand);
}
});
},
JSXSpreadAttribute: (path: any) => {
if (path.node.argument.type === 'Identifier') {
addArgumentUsage(story, args, path.node.argument, path.node.shorthand);
}
},
Identifier: (path: any) => {
addArgumentUsage(story, args, path.node, path.node.shorthand);
},
Property: (path: any) => {
const node = path.node;
if (node.value.type === 'Identifier' && node.key.type === 'Identifier') {
const usage = addArgumentUsage(story, args, node.value, node.shorthand);
if (usage) {
usage.name = {
loc: adjustSourceLocation(story, node.key.loc),
name: node.key.name,
};
path.skip();
}
}
},
};
};