forked from SimonWaldherr/liveCalc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
315 lines (268 loc) · 9.53 KB
/
Copy pathscript.js
File metadata and controls
315 lines (268 loc) · 9.53 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
document.addEventListener('DOMContentLoaded', function() {
initializeApp();
}, false);
function initializeApp() {
math.config({
number: 'BigNumber',
precision: 64
});
extendMathJsWithBaseConversions();
const showErrorsState = localStorage.getItem('showErrors');
if (showErrorsState !== null) {
$('#showErrors').prop('checked', showErrorsState === 'true');
}
const hashvalue = window.location.hash.substring(1);
if (hashvalue.length > 4) {
$('#frame1').val(b64_to_utf8(hashvalue));
}
evalMath();
// Direct evaluation with multiple events to catch all typing scenarios
$('#frame1').on('keyup input change', function() {
evalMath();
// Only update hash when needed, not on every keypress
if (!$(this).data('typing')) {
$(this).data('typing', true);
setTimeout(() => {
const encodedMath = utf8_to_b64($('#frame1').val());
window.location.hash = encodedMath;
$(this).data('typing', false);
}, 1000); // Only update URL hash once per second
}
});
// Save checkbox state to localStorage when changed
$('#showErrors').on('change', function() {
localStorage.setItem('showErrors', $(this).is(':checked'));
evalMath();
});
// Improved scroll sync - this handles the horizontal scrolling properly
$('#frame1').on('scroll', function() {
$('.bed-highlights').css('transform', `translate(${-this.scrollLeft}px, ${-this.scrollTop}px)`);
});
}
/**
* Extends math.js with custom functions for base conversions
*/
function extendMathJsWithBaseConversions() {
// Define base conversion configurations
const baseConfigs = {
hex: { base: 16, prefix: '0x' },
bin: { base: 2, prefix: '0b' },
oct: { base: 8, prefix: '0o' },
dec: { base: 10, prefix: '' }
};
// Create conversion functions dynamically
const conversions = {};
// Create to_base functions
Object.keys(baseConfigs).forEach(baseType => {
conversions[`to_${baseType}`] = function(value) {
// Check if it's a unit
if (math.typeOf(value) === 'Unit') {
throw new Error('Must be unitless');
}
// For non-decimal bases, check for floating point
if (baseType !== 'dec' && (!Number.isInteger(Number(value)))) {
throw new Error(`Can't convert fractional numbers to ${baseType}`);
}
if (baseType === 'dec') {
return math.format(value, {notation: 'fixed'});
} else {
return math.format(value, {notation: baseType, fraction: 'decimal'}).toLowerCase();
}
};
});
// Create from_base functions (except dec which is handled by default)
Object.keys(baseConfigs).forEach(baseType => {
if (baseType === 'dec') return; // Skip dec as it's the default
const config = baseConfigs[baseType];
conversions[`from_${baseType}`] = function(value) {
if (typeof value === 'string') {
value = value.toLowerCase().replace(new RegExp(`^${config.prefix}`), '');
}
return parseInt(value, config.base);
};
});
// Import all conversion functions
math.import(conversions);
// Override math.parse to handle base conversion expressions
const originalParse = math.parse;
math.parse = function(expr) {
if (typeof expr === 'string') {
// Process base literals
Object.keys(baseConfigs).forEach(baseType => {
if (baseType === 'dec') return; // Skip dec as it has no prefix
const config = baseConfigs[baseType];
const regex = new RegExp(`${config.prefix}([0-9a-fA-F]+)`, 'g');
expr = expr.replace(regex, `from_${baseType}("$1")`);
});
// Process natural language expressions
const conversionKeywords = ['in', 'to'];
conversionKeywords.forEach(keyword => {
Object.keys(baseConfigs).forEach(baseType => {
// Match the entire expression before the conversion keyword
const pattern = new RegExp(`(.+?)\\s+${keyword}\\s+${baseType}(?:\\b|$)`, 'gi');
expr = expr.replace(pattern, (match, group) => {
// Check for balanced parentheses in the group
if (group.trim()) {
return `to_${baseType}(${group})`;
}
return match; // If no group captured, return the original match
});
});
});
}
return originalParse.call(math, expr);
};
}
function utf8_to_b64(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
function b64_to_utf8(str) {
return decodeURIComponent(escape(window.atob(str)));
}
function evalMath() {
const parser = math.parser();
let output = '';
let input = [];
let formulas = $('#frame1').val();
const showErrors = $('#showErrors').is(':checked');
if (formulas.includes(",") && !formulas.includes(".")) {
formulas = formulas.replace(/(\d+),(\d+)/gi, "$1.$2");
}
const arrayOfLines = formulas.split('\n');
let globalSum = math.bignumber(0);
let localSum = math.bignumber(0);
let units = null;
const maxLen = Math.max(...arrayOfLines.map(item => item.length));
arrayOfLines.forEach(item => {
if (containsSumKeyword(item)) {
const displaySum = units ? localSum.toString() + units.simplify() : localSum.toString();
output += `${item}\t<span class="sum-value">${displaySum}</span>\n`;
localSum = math.bignumber(0); // Reset local sum after each Summe keyword
} else {
try {
parser.evaluate(item);
} catch (err) {
if (showErrors) {
output += `${item} <span class="error-text"><${err.message}></span>\n`;
} else {
output += `${item}\n`;
}
console.error(`Error evaluating item: "${item}": ${err.message}`);
return;
}
input.push(item);
const evaluationResult = evaluateItem(parser, input, item, maxLen);
output += evaluationResult;
const lastResult = getLastResult(parser, input);
if (lastResult) {
try {
obj = {
localSum: localSum,
globalSum: globalSum,
units: units
};
updateSum(obj, lastResult);
localSum = obj.localSum;
globalSum = obj.globalSum;
units = obj.units || units;
} catch (err) {
output += `${item} <span class="error-text"><${err.message}></span>\n`;
console.error(`Error updating sum for item: ${item}`, err);
return;
}
}
}
});
$("#highlights1").html(output);
}
function containsSumKeyword(item) {
const keywords = ['total', 'sum', 'summe', 'gesamt'];
return keywords.some(keyword => item.toLowerCase().includes(keyword));
}
function getLastResult(parser, input) {
const result = parser.evaluate(input);
if (result && result.length > 0) {
return result[result.length - 1];
}
return null;
}
function updateSum(obj, lastResult) {
if (math.typeOf(lastResult) === 'Unit') {
const unitSI = lastResult.toSI();
const valueSI = unitSI.toNumeric();
// If units change, reset both sums
if (obj.units === null || !unitSI.equalBase(obj.units)) {
obj.localSum = valueSI;
obj.globalSum = valueSI;
obj.units = unitSI;
return;
}
obj.localSum = obj.localSum.add(valueSI);
obj.globalSum = obj.globalSum.add(valueSI);
obj.units = unitSI;
} else if (typeof lastResult === 'number' || math.typeOf(lastResult) === 'BigNumber') {
// If we had units before but now we don't, reset sums
if (obj.units !== null) {
obj.localSum = math.bignumber(lastResult);
obj.globalSum = math.bignumber(lastResult);
obj.units = null;
}
obj.localSum = obj.localSum.add(lastResult);
obj.globalSum = obj.globalSum.add(lastResult);
}
}
function evaluateItem(parser, input, item, maxLen) {
if (item.trim() === '') {
return `${item}\n`;
}
const result = parser.evaluate(input);
if (result === undefined) {
return `${item}\n`;
}
const ev_raw = result.slice(-1);
const ev_str = JSON.stringify(ev_raw);
if (ev_raw === undefined || ev_str === "[null]") {
return `${item}\n`;
}
const spacing = "\t";
// Check if the expression has a base conversion pattern like "to hex", "to bin", etc.
const baseMatch = item.match(/\bto\s+(hex|bin|oct|dec)\b/i);
if (baseMatch && typeof ev_raw[0] !== 'undefined') {
const base = baseMatch[1].toLowerCase();
// Use the existing conversion functions instead of duplicating logic
try {
// Use the to_base function we already defined in extendMathJsWithBaseConversions
const convertedValue = math.evaluate(`to_${base}(${ev_raw})`);
return `${item}${spacing} = ${convertedValue}\n`;
} catch (e) {
console.error(`Base conversion error: ${e.message}`);
}
}
return `${item}${spacing}${ev_raw}\n`;
}
function clearTextarea() {
$('#frame1').val('');
evalMath();
}
function insertExample() {
$('#frame1').val(b64_to_utf8('QSA9ICgxLjIgLyAoMy4zICsgMS43KSkgY20KQiA9IDUuMDggY20gKyAyLjUgaW5jaApDID0gQiAqIEIgKiBBIGluIGNtMwoKCg=='));
evalMath();
}
function download(filename, text) {
const element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
function downloadMath() {
const filename = window.prompt('Save calculation as:', 'liveCalc.txt');
const content = $("#highlights1").text().replace(/ +/g, " ");
download(filename, content);
return false;
}
function copyURLtoClipboard() {
navigator.clipboard.writeText(window.location.href);
}