Skip to content

Commit 7ef054f

Browse files
committed
fix: added comments
1 parent 2a79157 commit 7ef054f

File tree

1 file changed

+49
-20
lines changed

1 file changed

+49
-20
lines changed

src/index.js

Lines changed: 49 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,59 @@
1-
import observer from "@cocreate/observer";
2-
import { queryElements } from "@cocreate/utils";
3-
// import { renderValue } from '@cocreate/render';
4-
import "@cocreate/element-prototype";
1+
import observer from "@cocreate/observer"; // Module for observing DOM mutations.
2+
import { queryElements } from "@cocreate/utils"; // Utility for querying DOM elements.
3+
import "@cocreate/element-prototype"; // Include custom element prototype extensions.
54

5+
// Initializes the calculation elements within the document.
66
function init() {
7+
// Select all elements in the document with a "calculate" attribute.
78
let calculateElements = document.querySelectorAll("[calculate]");
9+
// Initialize each of the selected elements.
810
initElements(calculateElements);
911
}
1012

13+
// Initialize multiple elements by invoking initElement for each.
1114
function initElements(elements) {
15+
// Iterate through the collection of elements and initialize each one.
1216
for (let el of elements) initElement(el);
1317
}
1418

19+
// Asynchronously initializes an individual element with setup for calculations.
1520
async function initElement(element) {
21+
// Fetch the calculate string from the element's attribute.
1622
let calculate = element.getAttribute("calculate");
23+
// Return early if the calculate string contains placeholders or template syntax.
1724
if (calculate.includes("{{") || calculate.includes("{[")) return;
1825

26+
// Extract selectors from the calculate attribute value.
1927
let selectors = getSelectors(element.attributes["calculate"].value);
2028

29+
// Iterate through each selector and set up elements impacted by them.
2130
for (let i = 0; i < selectors.length; i++) {
31+
// Find input elements based on the selector criteria.
2232
let inputs = queryElements({
2333
element,
2434
selector: selectors[i],
2535
type: "selector"
2636
});
2737

38+
// Set up events for each found input element.
2839
for (let input of inputs) {
2940
initEvent(element, input);
3041
}
3142

43+
// Initialize an observer to monitor newly added nodes that match the selector.
3244
observer.init({
3345
name: "calculateSelectorInit",
3446
types: ["addedNodes"],
3547
selector: selectors[i],
48+
// Callback function to run when nodes matching the selector are added.
3649
callback(mutation) {
50+
// Initialize events for the new element and update calculation.
3751
initEvent(element, mutation.target);
3852
setCalcationValue(element);
3953
}
4054
});
4155
}
56+
// Set initial calculation value when an element is being initialized.
4257
setCalcationValue(element);
4358
}
4459

@@ -110,63 +125,77 @@ function initEvent(element, input) {
110125
});
111126
}
112127

128+
// Asynchronously set the calculated value for the given element.
113129
async function setCalcationValue(element) {
130+
// Get the expression or formula from the element's "calculate" attribute.
114131
let calString = await getValues(element);
132+
// Evaluate the formula and set the calculated value back to the element.
115133
element.setValue(calculate(calString));
116134
}
117135

136+
// Asynchronously retrieve values necessary for computing the calculation attribute of an element.
118137
async function getValues(element) {
138+
// Get the expression that needs to be evaluated from the "calculate" attribute.
119139
let calculate = element.getAttribute("calculate");
120140

141+
// Parse the expression to extract any selectors which values need to contribute to calculation.
121142
let selectors = getSelectors(element.attributes["calculate"].value);
122143

144+
// For each selector, retrieve and calculate the respective value.
123145
for (let i = 0; i < selectors.length; i++) {
124-
let value = 0; // Default to 0 for missing inputs
146+
let value = 0; // Default value in case no input is found for the selector.
147+
148+
// Query DOM elements based on selector.
125149
let inputs = queryElements({
126150
element,
127151
selector: selectors[i],
128152
type: "selector"
129153
});
130154

155+
// Iterate through inputs/elements matched by the selector.
131156
for (let input of inputs) {
157+
// Initialize event listeners on inputs so that changes can update the calculation.
132158
initEvent(element, input);
133159
let val = null;
160+
161+
// Attempt to get the value from the input element, if it can provide it.
134162
if (input.getValue) {
135163
val = Number(await input.getValue());
136164
}
137165

166+
// Only accumulate valid numeric values.
138167
if (!Number.isNaN(val)) {
139-
value += val; // Accumulate valid numeric values
168+
value += val;
140169
} else {
141170
console.warn(
142171
`Invalid value for selector "${selectors[i]}". Defaulting to 0.`
143172
);
144173
}
145174
}
146175

176+
// Replace the placeholder in the calculation expression with the accumulated value.
147177
calculate = calculate.replaceAll(`(${selectors[i]})`, value);
148178
}
149-
150-
return calculate;
179+
return calculate; // Return the resolved calculation expression.
151180
}
152181

153182
// Defines mathematical constants available in expressions.
154183
const constants = { PI: Math.PI, E: Math.E };
155184

156-
// Defines allowed mathematical functions and maps them to their JavaScript Math counterparts.
185+
// Defines allowed mathematical functions and maps them to their respective JavaScript Math counterparts.
157186
const functions = {
158-
abs: Math.abs,
159-
ceil: Math.ceil,
160-
floor: Math.floor,
161-
round: Math.round,
162-
max: Math.max, // Note: RPN evaluator assumes arity 2 for max/min
163-
min: Math.min, // Note: RPN evaluator assumes arity 2 for max/min
164-
pow: Math.pow,
165-
sqrt: Math.sqrt,
187+
abs: Math.abs, // Absolute value
188+
ceil: Math.ceil, // Ceiling function
189+
floor: Math.floor, // Floor function
190+
round: Math.round, // Round to nearest integer
191+
max: Math.max, // Maximum value (assumes arity 2 in RPN)
192+
min: Math.min, // Minimum value (assumes arity 2 in RPN)
193+
pow: Math.pow, // Exponentiation
194+
sqrt: Math.sqrt, // Square root
166195
log: Math.log, // Natural logarithm
167-
sin: Math.sin,
168-
cos: Math.cos,
169-
tan: Math.tan
196+
sin: Math.sin, // Sine function
197+
cos: Math.cos, // Cosine function
198+
tan: Math.tan // Tangent function
170199
};
171200

172201
/**

0 commit comments

Comments
 (0)