MCPcopy Create free account
hub / github.com/babel/babel / pluginToggleBooleanFlag

Function pluginToggleBooleanFlag

scripts/babel-plugin-toggle-boolean-flag/plugin.ts:13–224  ·  view source on GitHub ↗

* If `value` is null, it will leave the conditions in code. It will remove * them in attributes by replacing them with ||

(
  { types: t, template, traverse }: PluginAPI,
  { name, value }: { name: string; value: boolean | null }
)

Source from the content-addressed store, hash-verified

11 * them in attributes by replacing them with <if true> || <if false>
12 */
13function pluginToggleBooleanFlag(
14 { types: t, template, traverse }: PluginAPI,
15 { name, value }: { name: string; value: boolean | null }
16): PluginObject {
17 if (typeof value !== "boolean" && value !== null) {
18 throw new Error(`.value must be a boolean, or null`);
19 }
20
21 function parseExpression(source: string) {
22 // eslint-disable-next-line regexp/no-useless-assertions
23 return template.expression(source, { placeholderPattern: /(?!.)./ })({});
24 }
25
26 function evaluate(test: t.Expression, value: boolean): any {
27 const res = {
28 replace: (replacement: t.Expression) => ({
29 replacement,
30 value: null,
31 unrelated: false,
32 }),
33 value: (value: boolean) => ({
34 replacement: null,
35 value,
36 unrelated: false,
37 }),
38 unrelated: () => ({ replacement: test, value: null, unrelated: true }),
39 };
40
41 if (t.isIdentifier(test, { name }) || t.matchesPattern(test, name)) {
42 return res.value(value);
43 }
44
45 if (t.isUnaryExpression(test, { operator: "!" })) {
46 const arg = evaluate(test.argument, value);
47 return arg.unrelated
48 ? res.unrelated()
49 : arg.replacement
50 ? res.replace(t.unaryExpression("!", arg.replacement))
51 : res.value(!arg.value);
52 }
53
54 if (t.isLogicalExpression(test, { operator: "||" })) {
55 const left = evaluate(test.left, value);
56 const right = evaluate(test.right, value);
57
58 if (left.value === true || right.value === true) return res.value(true);
59 if (left.value === false && right.value === false) {
60 return res.value(false);
61 }
62 if (left.value === false) return res.replace(right.replacement);
63 if (right.value === false) return res.replace(left.replacement);
64 if (left.unrelated && right.unrelated) return res.unrelated();
65 return res.replace(
66 t.logicalExpression("||", left.replacement, right.replacement)
67 );
68 }
69
70 if (t.isLogicalExpression(test, { operator: "&&" })) {

Callers

nothing calls this directly

Calls 1

explodeMethod · 0.80

Tested by

no test coverage detected