-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinstrumentor.js
85 lines (70 loc) · 2.32 KB
/
instrumentor.js
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
const t = require('babel-types');
const template = require('babel-template');
function transform() {
return {
visitor: {
ObjectProperty(path) {
if (path.node.key.name !== 'touchableHandlePress') {
// Not our target node.
return;
}
const parent = path.findParent(path => {
return (
path.isCallExpression() && path.node.callee.name === 'createReactClass'
);
});
if (!(parent && hasTouchableMixin(path))) {
return;
}
const callOriginalFunctionExpression = t.memberExpression(
path.node.value, // The actual function is the 'value' of the ObjectProperty.
t.identifier('call')
);
const calledFunction = t.callExpression(callOriginalFunctionExpression, [
t.identifier('this'), // 't.thisExpression()' doesn't give the correct identifier here.
t.identifier('e'), // The event argument.
]);
const autotrackExpression = buildAutotrackExpression({
THIS_EXPRESSION: t.identifier('this'),
});
const functionBody = buildFunctionWrapper({
AUTOTRACK_EXPRESSION: autotrackExpression,
ORIGINAL_FUNCTION_CALL: calledFunction,
});
const replacementFunction = t.arrowFunctionExpression([t.identifier('e')], functionBody);
path.get('value').replaceWith(replacementFunction);
},
},
};
}
const hasTouchableMixin = path => {
return !!path.container.find((node, i) => {
if (
node.type === 'ObjectProperty' &&
node.key.name === 'mixins' &&
node.value.type === 'ArrayExpression'
) {
const state = { hasTouchableMixin: false };
path.getSibling(i).traverse(identifierVisitor, { visitorState: state });
return state.hasTouchableMixin;
}
});
};
const identifierVisitor = {
Identifier(path) {
if (path.node.name === 'Touchable') {
this.visitorState.hasTouchableMixin = true;
}
},
};
// Creates a 'CallExpression' node.
const buildAutotrackExpression = template(`
Heap.captureTouchablePress(THIS_EXPRESSION, e);
`);
// Creates a 'BlockStatement' node.
const buildFunctionWrapper = template(`{
const Heap = require('babel-plugin-blog-post/Heap').default;
AUTOTRACK_EXPRESSION
ORIGINAL_FUNCTION_CALL
}`);
module.exports = transform;