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 |
|
35 |
|
36 |
|
37 | class ConditionalInitFragment extends InitFragment {
|
38 | |
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | constructor(
|
47 | content,
|
48 | stage,
|
49 | position,
|
50 | key,
|
51 | runtimeCondition = true,
|
52 | endContent
|
53 | ) {
|
54 | super(content, stage, position, key, endContent);
|
55 | this.runtimeCondition = runtimeCondition;
|
56 | }
|
57 |
|
58 | |
59 |
|
60 |
|
61 |
|
62 | getContent(context) {
|
63 | if (this.runtimeCondition === false || !this.content) return "";
|
64 | if (this.runtimeCondition === true) return this.content;
|
65 | const expr = context.runtimeTemplate.runtimeConditionExpression({
|
66 | chunkGraph: context.chunkGraph,
|
67 | runtimeRequirements: context.runtimeRequirements,
|
68 | runtime: context.runtime,
|
69 | runtimeCondition: this.runtimeCondition
|
70 | });
|
71 | if (expr === "true") return this.content;
|
72 | return wrapInCondition(expr, this.content);
|
73 | }
|
74 |
|
75 | |
76 |
|
77 |
|
78 |
|
79 | getEndContent(context) {
|
80 | if (this.runtimeCondition === false || !this.endContent) return "";
|
81 | if (this.runtimeCondition === true) return this.endContent;
|
82 | const expr = context.runtimeTemplate.runtimeConditionExpression({
|
83 | chunkGraph: context.chunkGraph,
|
84 | runtimeRequirements: context.runtimeRequirements,
|
85 | runtime: context.runtime,
|
86 | runtimeCondition: this.runtimeCondition
|
87 | });
|
88 | if (expr === "true") return this.endContent;
|
89 | return wrapInCondition(expr, this.endContent);
|
90 | }
|
91 |
|
92 | merge(other) {
|
93 | if (this.runtimeCondition === true) return this;
|
94 | if (other.runtimeCondition === true) return other;
|
95 | if (this.runtimeCondition === false) return other;
|
96 | if (other.runtimeCondition === false) return this;
|
97 | const runtimeCondition = mergeRuntime(
|
98 | this.runtimeCondition,
|
99 | other.runtimeCondition
|
100 | );
|
101 | return new ConditionalInitFragment(
|
102 | this.content,
|
103 | this.stage,
|
104 | this.position,
|
105 | this.key,
|
106 | runtimeCondition,
|
107 | this.endContent
|
108 | );
|
109 | }
|
110 | }
|
111 |
|
112 | module.exports = ConditionalInitFragment;
|