-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathcalculation.ts
More file actions
205 lines (168 loc) · 5.84 KB
/
calculation.ts
File metadata and controls
205 lines (168 loc) · 5.84 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// @ts-ignore
import ExpressionLanguage from 'expression-language';
const getVariablesPattern = /field:([a-zA-Z0-9_]+)/g;
const expressionLanguage = new ExpressionLanguage();
// Register sqrt function
expressionLanguage.register(
'sqrt',
// Compiler function - returns string representation
(value: string) => {
return `Math.sqrt(${value})`;
},
// Evaluator function - performs actual calculation
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(args: Record<string, any>, value: number) => {
if (typeof value !== 'number') {
return value;
}
return Math.sqrt(value);
}
);
const extractValue = (element: HTMLInputElement | HTMLSelectElement): string | number | boolean | null => {
const value = element.value;
// Return null if the value is an empty string
if (value === '') {
return null;
}
if (element.type === 'number') {
return Number(value);
}
const lowercasedValue = value.toLowerCase();
if (lowercasedValue === 'true') {
return true;
} else if (lowercasedValue === 'false') {
return false;
}
return isNaN(Number(value)) ? value : Number(value);
};
const attachCalculations = (input: HTMLInputElement) => {
const calculations = input.getAttribute('data-calculations');
const decimal = input.getAttribute('data-decimal');
// Get calculation logic & decimal count
const calculationsLogic = calculations.replace(getVariablesPattern, (_, variable) => variable);
const decimalCount = decimal ? Number(decimal) : null;
// Get variables
const variables: Record<string, string | number | boolean> = {};
let match;
while ((match = getVariablesPattern.exec(calculations)) !== null) {
variables[match[1]] = '';
}
const handleCalculation = () => {
if (!(input instanceof HTMLInputElement)) {
return;
}
const isAllValuesFilled = Object.values(variables).every((value) => value !== null && value !== '');
if (!isAllValuesFilled) {
return;
}
let result: number | string = '';
if (calculationsLogic) {
result = expressionLanguage.evaluate(calculationsLogic, variables);
} else {
result = '';
}
if (Number.isInteger(result) && !Number.isNaN(result) && decimalCount !== null) {
result = (result as number).toFixed(decimalCount);
}
const updateInputValue = (value: string | number) => {
input.value = value.toString();
input.dispatchEvent(new Event('change'));
};
if (input.type !== 'hidden') {
updateInputValue(result);
return;
}
const container = input.parentElement;
const pTag = container.querySelector('.freeform-calculation-plain-field');
if (pTag) {
pTag.textContent = String(result);
}
updateInputValue(result);
};
Object.keys(variables).forEach((variable) => {
const inputElements = input.form.querySelectorAll<HTMLInputElement | HTMLSelectElement>(
`input[name="${variable}"], select[name="${variable}"]`
);
if (inputElements.length === 0) {
return;
}
inputElements.forEach((element) => {
const updateVariables = () => {
if (element instanceof HTMLInputElement) {
if (element.type === 'radio' && !element.checked) {
return;
}
variables[variable] = extractValue(element);
} else if (element instanceof HTMLSelectElement) {
variables[variable] = extractValue(element);
}
};
const updateVariablesAndCalculate = () => {
updateVariables();
handleCalculation();
};
updateVariables(); // Initial update
if (element instanceof HTMLInputElement) {
if (element.type === 'radio') {
element.addEventListener('change', updateVariablesAndCalculate);
} else {
element.addEventListener('input', updateVariablesAndCalculate);
}
} else if (element instanceof HTMLSelectElement) {
element.addEventListener('change', updateVariablesAndCalculate);
}
});
});
// Trigger initial calculation if all values are present
const areDefaultValuesSet = Object.keys(variables).every((variable) => {
const inputElements = input.form.querySelectorAll<HTMLInputElement | HTMLSelectElement>(
`input[name="${variable}"], select[name="${variable}"]`
);
if (inputElements.length === 0) {
return false; // No matching inputs found for the variable
}
let value: string | number | boolean | null = null;
inputElements.forEach((element) => {
if (element instanceof HTMLInputElement) {
if (element.type === 'radio') {
if (element.checked) {
value = extractValue(element);
}
} else {
value = extractValue(element);
}
} else if (element instanceof HTMLSelectElement) {
value = extractValue(element);
}
});
variables[variable] = value;
// Ensure the variable has a non-null, non-empty value
return value !== null && value !== '';
});
if (areDefaultValuesSet) {
handleCalculation();
}
};
const registerCalculationInputs = async (container: HTMLElement) => {
const input = container.querySelector<HTMLInputElement>('input[data-calculations]');
if (!input) {
return;
}
attachCalculations(input);
};
document.querySelectorAll<HTMLInputElement>('*[data-field-type=calculation]').forEach(registerCalculationInputs);
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach((node) => {
if (node instanceof HTMLElement) {
const input = node.querySelector<HTMLInputElement>('input[data-calculations]');
if (input) {
attachCalculations(input);
}
}
});
}
});
});
observer.observe(document.body, { childList: true, subtree: true });