1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 | const { ConcatSource, PrefixSource } = require("webpack-sources");
|
9 | const InitFragment = require("./InitFragment");
|
10 | const Template = require("./Template");
|
11 | const { mergeRuntime } = require("./util/runtime");
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const wrapInCondition = (condition, source) => {
|
18 | if (typeof source === "string") {
|
19 | return Template.asString([
|
20 | `if (${condition}) {`,
|
21 | Template.indent(source),
|
22 | "}",
|
23 | ""
|
24 | ]);
|
25 | } else {
|
26 | return new ConcatSource(
|
27 | `if (${condition}) {\n`,
|
28 | new PrefixSource("\t", source),
|
29 | "}\n"
|
30 | );
|
31 | }
|
32 | };
|
33 |
|
34 | class ConditionalInitFragment extends InitFragment {
|
35 | |
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 | constructor(
|
44 | content,
|
45 | stage,
|
46 | position,
|
47 | key,
|
48 | runtimeCondition = true,
|
49 | endContent
|
50 | ) {
|
51 | super(content, stage, position, key, endContent);
|
52 | this.runtimeCondition = runtimeCondition;
|
53 | }
|
54 |
|
55 | |
56 |
|
57 |
|
58 |
|
59 | getContent(generateContext) {
|
60 | if (this.runtimeCondition === false || !this.content) return "";
|
61 | if (this.runtimeCondition === true) return this.content;
|
62 | const expr = generateContext.runtimeTemplate.runtimeConditionExpression({
|
63 | chunkGraph: generateContext.chunkGraph,
|
64 | runtimeRequirements: generateContext.runtimeRequirements,
|
65 | runtime: generateContext.runtime,
|
66 | runtimeCondition: this.runtimeCondition
|
67 | });
|
68 | if (expr === "true") return this.content;
|
69 | return wrapInCondition(expr, this.content);
|
70 | }
|
71 |
|
72 | |
73 |
|
74 |
|
75 |
|
76 | getEndContent(generateContext) {
|
77 | if (this.runtimeCondition === false || !this.endContent) return "";
|
78 | if (this.runtimeCondition === true) return this.endContent;
|
79 | const expr = generateContext.runtimeTemplate.runtimeConditionExpression({
|
80 | chunkGraph: generateContext.chunkGraph,
|
81 | runtimeRequirements: generateContext.runtimeRequirements,
|
82 | runtime: generateContext.runtime,
|
83 | runtimeCondition: this.runtimeCondition
|
84 | });
|
85 | if (expr === "true") return this.endContent;
|
86 | return wrapInCondition(expr, this.endContent);
|
87 | }
|
88 |
|
89 | merge(other) {
|
90 | if (this.runtimeCondition === true) return this;
|
91 | if (other.runtimeCondition === true) return other;
|
92 | if (this.runtimeCondition === false) return other;
|
93 | if (other.runtimeCondition === false) return this;
|
94 | const runtimeCondition = mergeRuntime(
|
95 | this.runtimeCondition,
|
96 | other.runtimeCondition
|
97 | );
|
98 | return new ConditionalInitFragment(
|
99 | this.content,
|
100 | this.stage,
|
101 | this.position,
|
102 | this.key,
|
103 | runtimeCondition,
|
104 | this.endContent
|
105 | );
|
106 | }
|
107 | }
|
108 |
|
109 | module.exports = ConditionalInitFragment;
|