@teachinglab/omd 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,460 +1,460 @@
1
- import { omdNode } from "./omdNode.js";
2
- import { getNodeForAST } from "../core/omdUtilities.js";
3
- import { omdOperatorNode } from "./omdOperatorNode.js";
4
- import { omdConstantNode } from "./omdConstantNode.js";
5
- import { omdVariableNode } from "./omdVariableNode.js";
6
- import { omdPowerNode } from "./omdPowerNode.js";
7
- import { omdParenthesisNode } from "./omdParenthesisNode.js";
8
- import { useImplicitMultiplication } from "../config/omdConfigManager.js";
9
- import { simplifyStep } from "../simplification/omdSimplification.js";
10
-
11
- /**
12
- * Represents a binary expression node in the mathematical expression tree
13
- * Handles rendering of expressions with two operands and an operator
14
- * @extends omdNode
15
- */
16
- export class omdBinaryExpressionNode extends omdNode {
17
- /**
18
- * Creates a binary expression node from AST data
19
- * @param {Object} ast - The AST node containing binary expression information
20
- */
21
- constructor(ast) {
22
- super(ast);
23
- this.type = "omdBinaryExpressionNode";
24
- if (!ast.args?.length || ast.args.length < 2) {
25
- throw new Error(`omdBinaryExpressionNode requires an AST node with at least 2 arguments. Received: ${JSON.stringify(ast)}`);
26
- }
27
-
28
- this.left = this.createExpressionNode(ast.args[0]);
29
- this.argumentNodeList.left = this.left;
30
-
31
- this.operation = this.parseOperation();
32
- this.op = !ast.implicit ? this.createOperatorNode(ast) : null; // Gerard: Implicit multiplication does not include operator node
33
- this.isImplicit = ast.implicit || false;
34
-
35
- this.right = this.createExpressionNode(ast.args[1]);
36
- this.argumentNodeList.right = this.right;
37
-
38
- // Convert explicit multiplication to implicit based on configuration
39
- if (this.op && (ast.op === '*' || ast.op === '×' || ast.fn === 'multiply')) {
40
- // Check if we should reorder operands (e.g., x*2 -> 2x)
41
- if (this._shouldReorderMultiplication(this.left, this.right)) {
42
- // Swap left and right operands
43
- const temp = this.left;
44
- this.left = this.right;
45
- this.right = temp;
46
-
47
- // Update argument list
48
- this.argumentNodeList.left = this.left;
49
- this.argumentNodeList.right = this.right;
50
-
51
- // Update AST args as well for consistency
52
- const tempArg = this.astNodeData.args[0];
53
- this.astNodeData.args[0] = this.astNodeData.args[1];
54
- this.astNodeData.args[1] = tempArg;
55
- }
56
-
57
- if (this._shouldUseImplicitMultiplication(this.left, this.right)) {
58
- // Remove the operator node to treat as implicit multiplication
59
- this.removeChild(this.op);
60
- this.op = null;
61
-
62
- // Mark AST as implicit for cloning/mathjs compatibility
63
- this.astNodeData.implicit = true;
64
- }
65
- }
66
- }
67
-
68
- parseOperation() {
69
- return this.astNodeData.fn;
70
- }
71
-
72
- createExpressionNode(ast) {
73
- let NodeType = getNodeForAST(ast);
74
- let child = new NodeType(ast);
75
- this.addChild(child);
76
-
77
- return child;
78
- }
79
-
80
- createOperatorNode(ast) {
81
- let opAst = { type: "OperatorNode", op: ast.op };
82
- if (ast.operatorProvenance) {
83
- opAst.provenance = ast.operatorProvenance;
84
- }
85
- let op = new omdOperatorNode(opAst);
86
- this.addChild(op);
87
-
88
- return op;
89
- }
90
-
91
- computeDimensions() {
92
- // Compute dimensions for all children first
93
- this.left.computeDimensions();
94
- this.op?.computeDimensions();
95
- this.right.computeDimensions();
96
-
97
- // Gerard: Calculate dimensions based on child dimensions
98
- let sumChildrenWidth = this.left.width + this.right.width + (this.op !== null ? this.op.width : 0);
99
- let maxChildrenHeight = Math.max(this.left.height, this.right.height);
100
-
101
- // Gerard: Add spacing between op and operands, if there is an op (not implicit)
102
- let padding = 0 * this.getFontSize() / this.getRootFontSize(); // Gerard: Vertical padding, should scale with fontSize
103
- let spacedWidth = sumChildrenWidth + this.getSpacing() * 2;
104
- let spacedHeight = maxChildrenHeight + padding;
105
-
106
- this.setWidthAndHeight(spacedWidth, spacedHeight);
107
- }
108
-
109
- updateLayout() {
110
- const spacing = this.getSpacing();
111
- const maxBaseline = Math.max(this.left.getAlignmentBaseline(), this.right.getAlignmentBaseline());
112
- let xOffset = 0;
113
-
114
- // Position children so their baselines align.
115
- this.left.updateLayout();
116
- this.left.setPosition(xOffset, maxBaseline - this.left.getAlignmentBaseline());
117
- xOffset += this.left.width + spacing;
118
-
119
- if (this.op !== null) {
120
- // Center the operator on the max baseline.
121
- const opBaseline = this.op.getAlignmentBaseline();
122
- this.op.updateLayout();
123
- this.op.setPosition(xOffset, maxBaseline - opBaseline);
124
- xOffset += this.op.width + spacing;
125
- }
126
-
127
- this.right.updateLayout();
128
- this.right.setPosition(xOffset, maxBaseline - this.right.getAlignmentBaseline());
129
- }
130
-
131
- /**
132
- * The alignment baseline for a binary expression should be the baseline of its operator,
133
- * adjusted for its position within the expression's bounding box.
134
- * @override
135
- * @returns {number} The y-coordinate for alignment.
136
- */
137
- getAlignmentBaseline() {
138
- if (this.op) {
139
- // The true baseline is the baseline of the operator, plus the operator's y-offset.
140
- const maxChildBaseline = Math.max(this.left.getAlignmentBaseline(), this.right.getAlignmentBaseline());
141
- const op_yOffset = maxChildBaseline - this.op.getAlignmentBaseline();
142
- return op_yOffset + this.op.getAlignmentBaseline();
143
- }
144
- // If there's no operator (implicit multiplication), the expression's baseline
145
- // is the shared alignment baseline of its children.
146
- return Math.max(this.left.getAlignmentBaseline(), this.right.getAlignmentBaseline());
147
- }
148
-
149
- clone() {
150
- // Create a new node. The constructor will add a backRect and temporary children.
151
- const tempAst = { type: 'OperatorNode', op: '+', args: [{type: 'ConstantNode', value: 1}, {type: 'ConstantNode', value: 1}] };
152
- const clone = new omdBinaryExpressionNode(tempAst);
153
-
154
- // Keep the backRect, but get rid of the temporary children.
155
- const backRect = clone.backRect;
156
- clone.removeAllChildren();
157
- clone.addChild(backRect);
158
-
159
- // Manually clone the real children to ensure the entire tree has correct provenance.
160
- clone.left = this.left.clone();
161
- clone.addChild(clone.left);
162
-
163
- if (this.op) {
164
- clone.op = this.op.clone();
165
- clone.addChild(clone.op);
166
- } else {
167
- clone.op = null;
168
- }
169
-
170
- clone.right = this.right.clone();
171
- clone.addChild(clone.right);
172
-
173
- // Rebuild the argument list, operation, and copy AST data.
174
- clone.argumentNodeList = { left: clone.left, right: clone.right };
175
- clone.operation = this.operation;
176
- clone.astNodeData = JSON.parse(JSON.stringify(this.astNodeData));
177
-
178
- // The crucial step: link the clone to its origin.
179
- clone.provenance.push(this.id);
180
-
181
- return clone;
182
- }
183
-
184
- // Gerard: Calculator horizontal spacing depending on whether op is implicit and scaling with font size
185
- getSpacing() {
186
- if (this.op === null) return 0;
187
-
188
- return 6 * this.getFontSize() / this.getRootFontSize();
189
- }
190
-
191
- /**
192
- * Determines if implicit multiplication should be used based on configuration
193
- * @private
194
- * @param {omdNode} left - Left operand
195
- * @param {omdNode} right - Right operand
196
- * @returns {boolean}
197
- */
198
- _shouldUseImplicitMultiplication(left, right) {
199
- // If global implicit multiplication is disabled, use traditional logic
200
- if (!useImplicitMultiplication()) {
201
- return this._isCoefficientMultiplication(left, right);
202
- }
203
-
204
- // Check specific combinations based on configuration
205
- const leftType = this._getNodeCategory(left);
206
- const rightType = this._getNodeCategory(right);
207
-
208
- const combinationKey = `${leftType}-${rightType}`;
209
- return this._getImplicitMultiplicationSetting(combinationKey);
210
- }
211
-
212
- /**
213
- * Gets the implicit multiplication setting for a given combination
214
- * Converts kebab-case combination keys to camelCase config keys
215
- * @private
216
- * @param {string} combinationKey - The combination key (e.g., 'constant-variable')
217
- * @returns {boolean} Whether implicit multiplication should be used
218
- */
219
- _getImplicitMultiplicationSetting(combinationKey) {
220
- // Handle special reordering cases that map to the same config setting
221
- const reorderingMappings = {
222
- 'variable-constant': 'constant-variable', // x*3 -> 3x (reordered)
223
- 'parenthesis-constant': 'constant-parenthesis' // (x+1)*3 -> 3(x+1) (reordered)
224
- };
225
-
226
- // Use the mapping if it exists, otherwise use the original key
227
- const normalizedKey = reorderingMappings[combinationKey] || combinationKey;
228
-
229
- // Convert kebab-case to camelCase (e.g., 'constant-variable' -> 'constantVariable')
230
- const camelCaseKey = normalizedKey.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase());
231
-
232
- return useImplicitMultiplication(camelCaseKey);
233
- }
234
-
235
- /**
236
- * Categorizes a node for implicit multiplication rules
237
- * @private
238
- * @param {omdNode} node - The node to categorize
239
- * @returns {string} The category name
240
- */
241
- _getNodeCategory(node) {
242
- if (node instanceof omdConstantNode && node.isConstant()) {
243
- return 'constant';
244
- }
245
- if (node instanceof omdVariableNode) {
246
- return 'variable';
247
- }
248
- if (node instanceof omdPowerNode) {
249
- return 'power';
250
- }
251
- if (node instanceof omdParenthesisNode) {
252
- return 'parenthesis';
253
- }
254
- return 'other';
255
- }
256
-
257
- /**
258
- * Determines if multiplication operands should be reordered for conventional display
259
- * (e.g., x*2 -> 2x, y*3 -> 3y)
260
- * @private
261
- * @param {omdNode} left - Left operand
262
- * @param {omdNode} right - Right operand
263
- * @returns {boolean} True if operands should be swapped
264
- */
265
- _shouldReorderMultiplication(left, right) {
266
- const leftType = this._getNodeCategory(left);
267
- const rightType = this._getNodeCategory(right);
268
-
269
- // Reorder if: left is non-constant and right is constant
270
- // Examples: x*2 -> 2x, y*3 -> 3y, (x+1)*5 -> 5(x+1)
271
- return (leftType !== 'constant' && rightType === 'constant');
272
- }
273
-
274
- /**
275
- * Determines if the multiplication represents a coefficient (e.g. 3*x -> 3x)
276
- * @private
277
- * @param {omdNode} left - Left operand
278
- * @param {omdNode} right - Right operand
279
- * @returns {boolean}
280
- */
281
- _isCoefficientMultiplication(left, right) {
282
- const leftIsNumericConstant = left instanceof omdConstantNode && left.isConstant();
283
- const rightIsVariableLike = (
284
- right instanceof omdVariableNode ||
285
- right instanceof omdPowerNode ||
286
- right instanceof omdParenthesisNode
287
- );
288
- return leftIsNumericConstant && rightIsVariableLike;
289
- }
290
-
291
- /**
292
- * Converts the omdBinaryExpressionNode to a math.js AST node.
293
- * @returns {Object} A math.js-compatible AST node.
294
- */
295
- toMathJSNode() {
296
- const astNode = {
297
- type: 'OperatorNode',
298
- op: this.op ? this.op.opName : '*',
299
- fn: this.operation,
300
- args: [this.left.toMathJSNode(), this.right.toMathJSNode()],
301
- implicit: !this.op,
302
- id: this.id,
303
- provenance: this.provenance
304
- };
305
-
306
- // Add a clone method to maintain compatibility with math.js's expectations.
307
- astNode.clone = function() {
308
- const clonedNode = { ...this };
309
- clonedNode.args = this.args.map(arg => arg.clone());
310
- return clonedNode;
311
- };
312
- return astNode;
313
- }
314
-
315
- /**
316
- * Converts the binary expression node to a string.
317
- * @returns {string} The string representation of the expression.
318
- */
319
- toString() {
320
- const leftStr = this.left.toString();
321
- const rightStr = this.right.toString();
322
- const opStr = this.op ? ` ${this.op.toString()} ` : '';
323
-
324
- // Handle implicit multiplication case (no operator)
325
- if (!this.op) {
326
- return `${leftStr}${rightStr}`;
327
- }
328
-
329
- // Wrap children in parentheses if their precedence is lower than this node's.
330
- const finalLeft = this.left.needsParentheses && this.left.needsParentheses(this.op.value) ? `(${leftStr})` : leftStr;
331
- const finalRight = this.right.needsParentheses && this.right.needsParentheses(this.op.value) ? `(${rightStr})` : rightStr;
332
-
333
- return `${finalLeft}${opStr}${finalRight}`;
334
- }
335
-
336
- /**
337
- * Evaluates the expression by recursively evaluating children.
338
- * @param {Object} variables - A map of variable names to their numeric values.
339
- * @returns {number} The result of the expression.
340
- */
341
- evaluate(variables = {}) {
342
- const operations = {
343
- 'add': (a, b) => a + b,
344
- 'subtract': (a, b) => a - b,
345
- 'multiply': (a, b) => a * b,
346
- 'divide': (a, b) => {
347
- if (b === 0) throw new Error("Division by zero.");
348
- return a / b;
349
- }
350
- };
351
-
352
- const leftVal = this.left.evaluate(variables);
353
- const rightVal = this.right.evaluate(variables);
354
-
355
- if (this.isImplicit) {
356
- return leftVal * rightVal;
357
- }
358
-
359
- const func = operations[this.operation];
360
-
361
- if (func) {
362
- return func(leftVal, rightVal);
363
- }
364
-
365
- throw new Error(`Unsupported operation for evaluation: ${this.operation}`);
366
- }
367
-
368
- /**
369
- * Determine if parentheses are needed based on parent operator
370
- * @returns {boolean} Whether parentheses are required
371
- */
372
- needsParentheses() {
373
- const parent = this.parent;
374
- if (!parent || !(parent instanceof omdBinaryExpressionNode)) {
375
- return false;
376
- }
377
-
378
- const thisOp = this.op ? this.op.opName : '*';
379
- const parentOp = parent.op ? parent.op.opName : '*';
380
-
381
- const precedence = {
382
- '+': 1,
383
- '-': 1,
384
- '*': 2,
385
- '×': 2,
386
- '/': 2,
387
- '÷': 2,
388
- '^': 3
389
- };
390
-
391
- const thisPrecedence = precedence[thisOp] || 0;
392
- const parentPrecedence = precedence[parentOp] || 0;
393
-
394
- // Need parentheses if this operation has lower precedence than parent
395
- if (thisPrecedence < parentPrecedence) {
396
- return true;
397
- }
398
-
399
- // Special case: subtraction and division are left-associative
400
- // So (a - b) - c needs parentheses on the right: a - (b - c)
401
- if (thisPrecedence === parentPrecedence && parent.right === this) {
402
- if (thisOp === '-' || thisOp === '/' || thisOp === '÷') {
403
- return true;
404
- }
405
- }
406
-
407
- return false;
408
- }
409
-
410
- /**
411
- * Helper method to get function name from operator
412
- * @private
413
- * @param {string} op - The operator symbol
414
- * @returns {string} The function name
415
- */
416
- getFunctionForOperator(op) {
417
- const opMap = {
418
- '+': 'add',
419
- '-': 'subtract',
420
- '*': 'multiply',
421
- '×': 'multiply',
422
- '/': 'divide',
423
- '÷': 'divide'
424
- };
425
- return opMap[op] || 'unknown';
426
- }
427
-
428
- setHighlight(highlightOn = true, color = omdColor.highlightColor) {
429
- if (this.isExplainHighlighted) return; // Respect the lock
430
-
431
- // Highlight/unhighlight the binary expression itself
432
- super.setHighlight(highlightOn, color);
433
-
434
- // Also highlight/unhighlight the children (left operand, operator, right operand)
435
- if (this.left && typeof this.left.setHighlight === 'function') {
436
- this.left.setHighlight(highlightOn, color);
437
- }
438
- if (this.op && typeof this.op.setHighlight === 'function') {
439
- this.op.setHighlight(highlightOn, color);
440
- }
441
- if (this.right && typeof this.right.setHighlight === 'function') {
442
- this.right.setHighlight(highlightOn, color);
443
- }
444
- }
445
-
446
- clearProvenanceHighlights() {
447
- super.clearProvenanceHighlights();
448
-
449
- // Also clear highlights from children
450
- if (this.left && typeof this.left.clearProvenanceHighlights === 'function') {
451
- this.left.clearProvenanceHighlights();
452
- }
453
- if (this.op && typeof this.op.clearProvenanceHighlights === 'function') {
454
- this.op.clearProvenanceHighlights();
455
- }
456
- if (this.right && typeof this.right.clearProvenanceHighlights === 'function') {
457
- this.right.clearProvenanceHighlights();
458
- }
459
- }
1
+ import { omdNode } from "./omdNode.js";
2
+ import { getNodeForAST } from "../core/omdUtilities.js";
3
+ import { omdOperatorNode } from "./omdOperatorNode.js";
4
+ import { omdConstantNode } from "./omdConstantNode.js";
5
+ import { omdVariableNode } from "./omdVariableNode.js";
6
+ import { omdPowerNode } from "./omdPowerNode.js";
7
+ import { omdParenthesisNode } from "./omdParenthesisNode.js";
8
+ import { useImplicitMultiplication } from "../config/omdConfigManager.js";
9
+ import { simplifyStep } from "../simplification/omdSimplification.js";
10
+
11
+ /**
12
+ * Represents a binary expression node in the mathematical expression tree
13
+ * Handles rendering of expressions with two operands and an operator
14
+ * @extends omdNode
15
+ */
16
+ export class omdBinaryExpressionNode extends omdNode {
17
+ /**
18
+ * Creates a binary expression node from AST data
19
+ * @param {Object} ast - The AST node containing binary expression information
20
+ */
21
+ constructor(ast) {
22
+ super(ast);
23
+ this.type = "omdBinaryExpressionNode";
24
+ if (!ast.args?.length || ast.args.length < 2) {
25
+ throw new Error(`omdBinaryExpressionNode requires an AST node with at least 2 arguments. Received: ${JSON.stringify(ast)}`);
26
+ }
27
+
28
+ this.left = this.createExpressionNode(ast.args[0]);
29
+ this.argumentNodeList.left = this.left;
30
+
31
+ this.operation = this.parseOperation();
32
+ this.op = !ast.implicit ? this.createOperatorNode(ast) : null; // Gerard: Implicit multiplication does not include operator node
33
+ this.isImplicit = ast.implicit || false;
34
+
35
+ this.right = this.createExpressionNode(ast.args[1]);
36
+ this.argumentNodeList.right = this.right;
37
+
38
+ // Convert explicit multiplication to implicit based on configuration
39
+ if (this.op && (ast.op === '*' || ast.op === '×' || ast.fn === 'multiply')) {
40
+ // Check if we should reorder operands (e.g., x*2 -> 2x)
41
+ if (this._shouldReorderMultiplication(this.left, this.right)) {
42
+ // Swap left and right operands
43
+ const temp = this.left;
44
+ this.left = this.right;
45
+ this.right = temp;
46
+
47
+ // Update argument list
48
+ this.argumentNodeList.left = this.left;
49
+ this.argumentNodeList.right = this.right;
50
+
51
+ // Update AST args as well for consistency
52
+ const tempArg = this.astNodeData.args[0];
53
+ this.astNodeData.args[0] = this.astNodeData.args[1];
54
+ this.astNodeData.args[1] = tempArg;
55
+ }
56
+
57
+ if (this._shouldUseImplicitMultiplication(this.left, this.right)) {
58
+ // Remove the operator node to treat as implicit multiplication
59
+ this.removeChild(this.op);
60
+ this.op = null;
61
+
62
+ // Mark AST as implicit for cloning/mathjs compatibility
63
+ this.astNodeData.implicit = true;
64
+ }
65
+ }
66
+ }
67
+
68
+ parseOperation() {
69
+ return this.astNodeData.fn;
70
+ }
71
+
72
+ createExpressionNode(ast) {
73
+ let NodeType = getNodeForAST(ast);
74
+ let child = new NodeType(ast);
75
+ this.addChild(child);
76
+
77
+ return child;
78
+ }
79
+
80
+ createOperatorNode(ast) {
81
+ let opAst = { type: "OperatorNode", op: ast.op };
82
+ if (ast.operatorProvenance) {
83
+ opAst.provenance = ast.operatorProvenance;
84
+ }
85
+ let op = new omdOperatorNode(opAst);
86
+ this.addChild(op);
87
+
88
+ return op;
89
+ }
90
+
91
+ computeDimensions() {
92
+ // Compute dimensions for all children first
93
+ this.left.computeDimensions();
94
+ this.op?.computeDimensions();
95
+ this.right.computeDimensions();
96
+
97
+ // Gerard: Calculate dimensions based on child dimensions
98
+ let sumChildrenWidth = this.left.width + this.right.width + (this.op !== null ? this.op.width : 0);
99
+ let maxChildrenHeight = Math.max(this.left.height, this.right.height);
100
+
101
+ // Gerard: Add spacing between op and operands, if there is an op (not implicit)
102
+ let padding = 0 * this.getFontSize() / this.getRootFontSize(); // Gerard: Vertical padding, should scale with fontSize
103
+ let spacedWidth = sumChildrenWidth + this.getSpacing() * 2;
104
+ let spacedHeight = maxChildrenHeight + padding;
105
+
106
+ this.setWidthAndHeight(spacedWidth, spacedHeight);
107
+ }
108
+
109
+ updateLayout() {
110
+ const spacing = this.getSpacing();
111
+ const maxBaseline = Math.max(this.left.getAlignmentBaseline(), this.right.getAlignmentBaseline());
112
+ let xOffset = 0;
113
+
114
+ // Position children so their baselines align.
115
+ this.left.updateLayout();
116
+ this.left.setPosition(xOffset, maxBaseline - this.left.getAlignmentBaseline());
117
+ xOffset += this.left.width + spacing;
118
+
119
+ if (this.op !== null) {
120
+ // Center the operator on the max baseline.
121
+ const opBaseline = this.op.getAlignmentBaseline();
122
+ this.op.updateLayout();
123
+ this.op.setPosition(xOffset, maxBaseline - opBaseline);
124
+ xOffset += this.op.width + spacing;
125
+ }
126
+
127
+ this.right.updateLayout();
128
+ this.right.setPosition(xOffset, maxBaseline - this.right.getAlignmentBaseline());
129
+ }
130
+
131
+ /**
132
+ * The alignment baseline for a binary expression should be the baseline of its operator,
133
+ * adjusted for its position within the expression's bounding box.
134
+ * @override
135
+ * @returns {number} The y-coordinate for alignment.
136
+ */
137
+ getAlignmentBaseline() {
138
+ if (this.op) {
139
+ // The true baseline is the baseline of the operator, plus the operator's y-offset.
140
+ const maxChildBaseline = Math.max(this.left.getAlignmentBaseline(), this.right.getAlignmentBaseline());
141
+ const op_yOffset = maxChildBaseline - this.op.getAlignmentBaseline();
142
+ return op_yOffset + this.op.getAlignmentBaseline();
143
+ }
144
+ // If there's no operator (implicit multiplication), the expression's baseline
145
+ // is the shared alignment baseline of its children.
146
+ return Math.max(this.left.getAlignmentBaseline(), this.right.getAlignmentBaseline());
147
+ }
148
+
149
+ clone() {
150
+ // Create a new node. The constructor will add a backRect and temporary children.
151
+ const tempAst = { type: 'OperatorNode', op: '+', args: [{type: 'ConstantNode', value: 1}, {type: 'ConstantNode', value: 1}] };
152
+ const clone = new omdBinaryExpressionNode(tempAst);
153
+
154
+ // Keep the backRect, but get rid of the temporary children.
155
+ const backRect = clone.backRect;
156
+ clone.removeAllChildren();
157
+ clone.addChild(backRect);
158
+
159
+ // Manually clone the real children to ensure the entire tree has correct provenance.
160
+ clone.left = this.left.clone();
161
+ clone.addChild(clone.left);
162
+
163
+ if (this.op) {
164
+ clone.op = this.op.clone();
165
+ clone.addChild(clone.op);
166
+ } else {
167
+ clone.op = null;
168
+ }
169
+
170
+ clone.right = this.right.clone();
171
+ clone.addChild(clone.right);
172
+
173
+ // Rebuild the argument list, operation, and copy AST data.
174
+ clone.argumentNodeList = { left: clone.left, right: clone.right };
175
+ clone.operation = this.operation;
176
+ clone.astNodeData = JSON.parse(JSON.stringify(this.astNodeData));
177
+
178
+ // The crucial step: link the clone to its origin.
179
+ clone.provenance.push(this.id);
180
+
181
+ return clone;
182
+ }
183
+
184
+ // Gerard: Calculator horizontal spacing depending on whether op is implicit and scaling with font size
185
+ getSpacing() {
186
+ if (this.op === null) return 0;
187
+
188
+ return 6 * this.getFontSize() / this.getRootFontSize();
189
+ }
190
+
191
+ /**
192
+ * Determines if implicit multiplication should be used based on configuration
193
+ * @private
194
+ * @param {omdNode} left - Left operand
195
+ * @param {omdNode} right - Right operand
196
+ * @returns {boolean}
197
+ */
198
+ _shouldUseImplicitMultiplication(left, right) {
199
+ // If global implicit multiplication is disabled, use traditional logic
200
+ if (!useImplicitMultiplication()) {
201
+ return this._isCoefficientMultiplication(left, right);
202
+ }
203
+
204
+ // Check specific combinations based on configuration
205
+ const leftType = this._getNodeCategory(left);
206
+ const rightType = this._getNodeCategory(right);
207
+
208
+ const combinationKey = `${leftType}-${rightType}`;
209
+ return this._getImplicitMultiplicationSetting(combinationKey);
210
+ }
211
+
212
+ /**
213
+ * Gets the implicit multiplication setting for a given combination
214
+ * Converts kebab-case combination keys to camelCase config keys
215
+ * @private
216
+ * @param {string} combinationKey - The combination key (e.g., 'constant-variable')
217
+ * @returns {boolean} Whether implicit multiplication should be used
218
+ */
219
+ _getImplicitMultiplicationSetting(combinationKey) {
220
+ // Handle special reordering cases that map to the same config setting
221
+ const reorderingMappings = {
222
+ 'variable-constant': 'constant-variable', // x*3 -> 3x (reordered)
223
+ 'parenthesis-constant': 'constant-parenthesis' // (x+1)*3 -> 3(x+1) (reordered)
224
+ };
225
+
226
+ // Use the mapping if it exists, otherwise use the original key
227
+ const normalizedKey = reorderingMappings[combinationKey] || combinationKey;
228
+
229
+ // Convert kebab-case to camelCase (e.g., 'constant-variable' -> 'constantVariable')
230
+ const camelCaseKey = normalizedKey.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase());
231
+
232
+ return useImplicitMultiplication(camelCaseKey);
233
+ }
234
+
235
+ /**
236
+ * Categorizes a node for implicit multiplication rules
237
+ * @private
238
+ * @param {omdNode} node - The node to categorize
239
+ * @returns {string} The category name
240
+ */
241
+ _getNodeCategory(node) {
242
+ if (node instanceof omdConstantNode && node.isConstant()) {
243
+ return 'constant';
244
+ }
245
+ if (node instanceof omdVariableNode) {
246
+ return 'variable';
247
+ }
248
+ if (node instanceof omdPowerNode) {
249
+ return 'power';
250
+ }
251
+ if (node instanceof omdParenthesisNode) {
252
+ return 'parenthesis';
253
+ }
254
+ return 'other';
255
+ }
256
+
257
+ /**
258
+ * Determines if multiplication operands should be reordered for conventional display
259
+ * (e.g., x*2 -> 2x, y*3 -> 3y)
260
+ * @private
261
+ * @param {omdNode} left - Left operand
262
+ * @param {omdNode} right - Right operand
263
+ * @returns {boolean} True if operands should be swapped
264
+ */
265
+ _shouldReorderMultiplication(left, right) {
266
+ const leftType = this._getNodeCategory(left);
267
+ const rightType = this._getNodeCategory(right);
268
+
269
+ // Reorder if: left is non-constant and right is constant
270
+ // Examples: x*2 -> 2x, y*3 -> 3y, (x+1)*5 -> 5(x+1)
271
+ return (leftType !== 'constant' && rightType === 'constant');
272
+ }
273
+
274
+ /**
275
+ * Determines if the multiplication represents a coefficient (e.g. 3*x -> 3x)
276
+ * @private
277
+ * @param {omdNode} left - Left operand
278
+ * @param {omdNode} right - Right operand
279
+ * @returns {boolean}
280
+ */
281
+ _isCoefficientMultiplication(left, right) {
282
+ const leftIsNumericConstant = left instanceof omdConstantNode && left.isConstant();
283
+ const rightIsVariableLike = (
284
+ right instanceof omdVariableNode ||
285
+ right instanceof omdPowerNode ||
286
+ right instanceof omdParenthesisNode
287
+ );
288
+ return leftIsNumericConstant && rightIsVariableLike;
289
+ }
290
+
291
+ /**
292
+ * Converts the omdBinaryExpressionNode to a math.js AST node.
293
+ * @returns {Object} A math.js-compatible AST node.
294
+ */
295
+ toMathJSNode() {
296
+ const astNode = {
297
+ type: 'OperatorNode',
298
+ op: this.op ? this.op.opName : '*',
299
+ fn: this.operation,
300
+ args: [this.left.toMathJSNode(), this.right.toMathJSNode()],
301
+ implicit: !this.op,
302
+ id: this.id,
303
+ provenance: this.provenance
304
+ };
305
+
306
+ // Add a clone method to maintain compatibility with math.js's expectations.
307
+ astNode.clone = function() {
308
+ const clonedNode = { ...this };
309
+ clonedNode.args = this.args.map(arg => arg.clone());
310
+ return clonedNode;
311
+ };
312
+ return astNode;
313
+ }
314
+
315
+ /**
316
+ * Converts the binary expression node to a string.
317
+ * @returns {string} The string representation of the expression.
318
+ */
319
+ toString() {
320
+ const leftStr = this.left.toString();
321
+ const rightStr = this.right.toString();
322
+ const opStr = this.op ? ` ${this.op.toString()} ` : '';
323
+
324
+ // Handle implicit multiplication case (no operator)
325
+ if (!this.op) {
326
+ return `${leftStr}${rightStr}`;
327
+ }
328
+
329
+ // Wrap children in parentheses if their precedence is lower than this node's.
330
+ const finalLeft = this.left.needsParentheses && this.left.needsParentheses(this.op.value) ? `(${leftStr})` : leftStr;
331
+ const finalRight = this.right.needsParentheses && this.right.needsParentheses(this.op.value) ? `(${rightStr})` : rightStr;
332
+
333
+ return `${finalLeft}${opStr}${finalRight}`;
334
+ }
335
+
336
+ /**
337
+ * Evaluates the expression by recursively evaluating children.
338
+ * @param {Object} variables - A map of variable names to their numeric values.
339
+ * @returns {number} The result of the expression.
340
+ */
341
+ evaluate(variables = {}) {
342
+ const operations = {
343
+ 'add': (a, b) => a + b,
344
+ 'subtract': (a, b) => a - b,
345
+ 'multiply': (a, b) => a * b,
346
+ 'divide': (a, b) => {
347
+ if (b === 0) throw new Error("Division by zero.");
348
+ return a / b;
349
+ }
350
+ };
351
+
352
+ const leftVal = this.left.evaluate(variables);
353
+ const rightVal = this.right.evaluate(variables);
354
+
355
+ if (this.isImplicit) {
356
+ return leftVal * rightVal;
357
+ }
358
+
359
+ const func = operations[this.operation];
360
+
361
+ if (func) {
362
+ return func(leftVal, rightVal);
363
+ }
364
+
365
+ throw new Error(`Unsupported operation for evaluation: ${this.operation}`);
366
+ }
367
+
368
+ /**
369
+ * Determine if parentheses are needed based on parent operator
370
+ * @returns {boolean} Whether parentheses are required
371
+ */
372
+ needsParentheses() {
373
+ const parent = this.parent;
374
+ if (!parent || !(parent instanceof omdBinaryExpressionNode)) {
375
+ return false;
376
+ }
377
+
378
+ const thisOp = this.op ? this.op.opName : '*';
379
+ const parentOp = parent.op ? parent.op.opName : '*';
380
+
381
+ const precedence = {
382
+ '+': 1,
383
+ '-': 1,
384
+ '*': 2,
385
+ '×': 2,
386
+ '/': 2,
387
+ '÷': 2,
388
+ '^': 3
389
+ };
390
+
391
+ const thisPrecedence = precedence[thisOp] || 0;
392
+ const parentPrecedence = precedence[parentOp] || 0;
393
+
394
+ // Need parentheses if this operation has lower precedence than parent
395
+ if (thisPrecedence < parentPrecedence) {
396
+ return true;
397
+ }
398
+
399
+ // Special case: subtraction and division are left-associative
400
+ // So (a - b) - c needs parentheses on the right: a - (b - c)
401
+ if (thisPrecedence === parentPrecedence && parent.right === this) {
402
+ if (thisOp === '-' || thisOp === '/' || thisOp === '÷') {
403
+ return true;
404
+ }
405
+ }
406
+
407
+ return false;
408
+ }
409
+
410
+ /**
411
+ * Helper method to get function name from operator
412
+ * @private
413
+ * @param {string} op - The operator symbol
414
+ * @returns {string} The function name
415
+ */
416
+ getFunctionForOperator(op) {
417
+ const opMap = {
418
+ '+': 'add',
419
+ '-': 'subtract',
420
+ '*': 'multiply',
421
+ '×': 'multiply',
422
+ '/': 'divide',
423
+ '÷': 'divide'
424
+ };
425
+ return opMap[op] || 'unknown';
426
+ }
427
+
428
+ setHighlight(highlightOn = true, color = omdColor.highlightColor) {
429
+ if (this.isExplainHighlighted) return; // Respect the lock
430
+
431
+ // Highlight/unhighlight the binary expression itself
432
+ super.setHighlight(highlightOn, color);
433
+
434
+ // Also highlight/unhighlight the children (left operand, operator, right operand)
435
+ if (this.left && typeof this.left.setHighlight === 'function') {
436
+ this.left.setHighlight(highlightOn, color);
437
+ }
438
+ if (this.op && typeof this.op.setHighlight === 'function') {
439
+ this.op.setHighlight(highlightOn, color);
440
+ }
441
+ if (this.right && typeof this.right.setHighlight === 'function') {
442
+ this.right.setHighlight(highlightOn, color);
443
+ }
444
+ }
445
+
446
+ clearProvenanceHighlights() {
447
+ super.clearProvenanceHighlights();
448
+
449
+ // Also clear highlights from children
450
+ if (this.left && typeof this.left.clearProvenanceHighlights === 'function') {
451
+ this.left.clearProvenanceHighlights();
452
+ }
453
+ if (this.op && typeof this.op.clearProvenanceHighlights === 'function') {
454
+ this.op.clearProvenanceHighlights();
455
+ }
456
+ if (this.right && typeof this.right.clearProvenanceHighlights === 'function') {
457
+ this.right.clearProvenanceHighlights();
458
+ }
459
+ }
460
460
  }