-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
conditionals.ts
46 lines (38 loc) · 1011 Bytes
/
conditionals.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
import {Modifier} from './types';
/**
* Handles if, unless, and else modifiers, as well as their always/never
* variants.
*/
export const conditionalModifier: Modifier = {
match: /^if(always|never)?\s|else$|unless\s/i,
processRaw(output, {invocation, state}) {
const type = invocation.replace(/\s.*/, '').toLowerCase();
const conditionEval = () =>
new Function('return ' + invocation.replace(/.*?\s/, '')).apply(window);
switch (type) {
case 'if':
state.conditionEval = conditionEval();
break;
case 'ifalways':
state.conditionEval = true;
break;
case 'ifnever':
state.conditionEval = false;
break;
case 'unless':
state.conditionEval = !conditionEval();
break;
case 'else':
if (state.conditionEval === undefined) {
throw new Error(
'There was no matching if modifier for an else modifier.'
);
}
state.conditionEval = !state.conditionEval;
break;
}
if (!state.conditionEval) {
output.text = '';
}
}
};