-
Notifications
You must be signed in to change notification settings - Fork 0
/
if.js
85 lines (73 loc) · 2.11 KB
/
if.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
/**
* @classdesc Represents a FabrIf component.
* @extends FabrCoreComponent
*/
fbr.FabrIf = class extends fbr.FabrCoreComponent {
constructor() {
super();
this.componentName = "FabrIf";
this.componentStyleClass = "fabr-if";
this.selector = "[fabr-if]";
this.eventMap = {};
this.observedVariables = new Map();
this.sharedMemoryHelper = new fbr.FabrHelperSharedMemory();
this.sharedMemoryHelper.init(this);
}
/**
* Initialize the condition component.
*/
init() {
super.init();
this.processElements();
}
/**
* Process the condition elements.
*/
processElements() {
for (const element of this.elements) {
const variableName = element.getAttribute("fabr-if");
const target = element;
if (!variableName) {
continue;
}
this.observeVariable(variableName);
this.observedVariables.set(variableName, {
target,
parent: target.parentNode,
});
this.updateTargetVisibility(variableName);
}
}
/**
* Start observing a variable in sharedMemory for changes.
* @param {string} variableName - The name of the variable.
*/
observeVariable(variableName) {
console.log(this.sharedMemoryHelper.getKeys());
this.sharedMemoryHelper.connect(variableName, this, (_, newValue) => {
this.updateTargetVisibility(variableName, newValue);
});
this.observedVariables.set(variableName, []);
}
/**
* Update the visibility of the targets associated with the variable.
* @param {string} variableName - The name of the variable.
* @param {boolean} [newValue] - The new value of the variable (optional).
*/
updateTargetVisibility(variableName, newValue) {
const targetData = this.observedVariables.get(variableName);
if (newValue === undefined) {
newValue = this.sharedMemoryHelper.get(variableName);
}
const { target, parent } = targetData;
if (newValue === true) {
if (!parent.contains(target)) {
parent.appendChild(target);
}
} else {
if (parent.contains(target)) {
parent.removeChild(target);
}
}
}
};