-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathmount-utils.ts
60 lines (49 loc) · 1.48 KB
/
mount-utils.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
// Inspired by Vitest fixture implementation:
// https://github.com/vitest-dev/vitest/blob/200a4349a2f85686bc7005dce686d9d1b48b84d2/packages/runner/src/fixture.ts
import { type PreparedStory, type Renderer } from '@storybook/core/types';
export function mountDestructured<TRenderer extends Renderer>(
playFunction: PreparedStory<TRenderer>['playFunction']
): boolean {
return playFunction != null && getUsedProps(playFunction).includes('mount');
}
export function getUsedProps(fn: Function) {
const match = fn.toString().match(/[^(]*\(([^)]*)/);
if (!match) {
return [];
}
const args = splitByComma(match[1]);
if (!args.length) {
return [];
}
const first = args[0];
if (!(first.startsWith('{') && first.endsWith('}'))) {
return [];
}
const props = splitByComma(first.slice(1, -1).replace(/\s/g, '')).map((prop) => {
return prop.replace(/:.*|=.*/g, '');
});
return props;
}
function splitByComma(s: string) {
const result = [];
const stack = [];
let start = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === '{' || s[i] === '[') {
stack.push(s[i] === '{' ? '}' : ']');
} else if (s[i] === stack[stack.length - 1]) {
stack.pop();
} else if (!stack.length && s[i] === ',') {
const token = s.substring(start, i).trim();
if (token) {
result.push(token);
}
start = i + 1;
}
}
const lastToken = s.substring(start).trim();
if (lastToken) {
result.push(lastToken);
}
return result;
}