@teachinglab/omd 0.1.0

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.
Files changed (144) hide show
  1. package/README.md +138 -0
  2. package/canvas/core/canvasConfig.js +203 -0
  3. package/canvas/core/omdCanvas.js +475 -0
  4. package/canvas/drawing/segment.js +168 -0
  5. package/canvas/drawing/stroke.js +386 -0
  6. package/canvas/events/eventManager.js +435 -0
  7. package/canvas/events/pointerEventHandler.js +263 -0
  8. package/canvas/features/focusFrameManager.js +287 -0
  9. package/canvas/index.js +49 -0
  10. package/canvas/tools/eraserTool.js +322 -0
  11. package/canvas/tools/pencilTool.js +319 -0
  12. package/canvas/tools/selectTool.js +457 -0
  13. package/canvas/tools/tool.js +223 -0
  14. package/canvas/tools/toolManager.js +394 -0
  15. package/canvas/ui/cursor.js +438 -0
  16. package/canvas/ui/toolbar.js +304 -0
  17. package/canvas/utils/boundingBox.js +378 -0
  18. package/canvas/utils/mathUtils.js +259 -0
  19. package/docs/api/configuration-options.md +104 -0
  20. package/docs/api/eventManager.md +68 -0
  21. package/docs/api/focusFrameManager.md +150 -0
  22. package/docs/api/index.md +91 -0
  23. package/docs/api/main.md +58 -0
  24. package/docs/api/omdBinaryExpressionNode.md +227 -0
  25. package/docs/api/omdCanvas.md +142 -0
  26. package/docs/api/omdConfigManager.md +192 -0
  27. package/docs/api/omdConstantNode.md +117 -0
  28. package/docs/api/omdDisplay.md +121 -0
  29. package/docs/api/omdEquationNode.md +161 -0
  30. package/docs/api/omdEquationSequenceNode.md +301 -0
  31. package/docs/api/omdEquationStack.md +139 -0
  32. package/docs/api/omdFunctionNode.md +141 -0
  33. package/docs/api/omdGroupNode.md +182 -0
  34. package/docs/api/omdHelpers.md +96 -0
  35. package/docs/api/omdLeafNode.md +163 -0
  36. package/docs/api/omdNode.md +101 -0
  37. package/docs/api/omdOperationDisplayNode.md +139 -0
  38. package/docs/api/omdOperatorNode.md +127 -0
  39. package/docs/api/omdParenthesisNode.md +122 -0
  40. package/docs/api/omdPopup.md +117 -0
  41. package/docs/api/omdPowerNode.md +127 -0
  42. package/docs/api/omdRationalNode.md +128 -0
  43. package/docs/api/omdSequenceNode.md +128 -0
  44. package/docs/api/omdSimplification.md +110 -0
  45. package/docs/api/omdSqrtNode.md +79 -0
  46. package/docs/api/omdStepVisualizer.md +115 -0
  47. package/docs/api/omdStepVisualizerHighlighting.md +61 -0
  48. package/docs/api/omdStepVisualizerInteractiveSteps.md +129 -0
  49. package/docs/api/omdStepVisualizerLayout.md +60 -0
  50. package/docs/api/omdStepVisualizerNodeUtils.md +140 -0
  51. package/docs/api/omdStepVisualizerTextBoxes.md +68 -0
  52. package/docs/api/omdToolbar.md +102 -0
  53. package/docs/api/omdTranscriptionService.md +76 -0
  54. package/docs/api/omdTreeDiff.md +134 -0
  55. package/docs/api/omdUnaryExpressionNode.md +174 -0
  56. package/docs/api/omdUtilities.md +70 -0
  57. package/docs/api/omdVariableNode.md +148 -0
  58. package/docs/api/selectTool.md +74 -0
  59. package/docs/api/simplificationEngine.md +98 -0
  60. package/docs/api/simplificationRules.md +77 -0
  61. package/docs/api/simplificationUtils.md +64 -0
  62. package/docs/api/transcribe.md +43 -0
  63. package/docs/api-reference.md +85 -0
  64. package/docs/index.html +454 -0
  65. package/docs/user-guide.md +9 -0
  66. package/index.js +67 -0
  67. package/omd/config/omdConfigManager.js +267 -0
  68. package/omd/core/index.js +150 -0
  69. package/omd/core/omdEquationStack.js +347 -0
  70. package/omd/core/omdUtilities.js +115 -0
  71. package/omd/display/omdDisplay.js +443 -0
  72. package/omd/display/omdToolbar.js +502 -0
  73. package/omd/nodes/omdBinaryExpressionNode.js +460 -0
  74. package/omd/nodes/omdConstantNode.js +142 -0
  75. package/omd/nodes/omdEquationNode.js +1223 -0
  76. package/omd/nodes/omdEquationSequenceNode.js +1273 -0
  77. package/omd/nodes/omdFunctionNode.js +352 -0
  78. package/omd/nodes/omdGroupNode.js +68 -0
  79. package/omd/nodes/omdLeafNode.js +77 -0
  80. package/omd/nodes/omdNode.js +557 -0
  81. package/omd/nodes/omdOperationDisplayNode.js +322 -0
  82. package/omd/nodes/omdOperatorNode.js +109 -0
  83. package/omd/nodes/omdParenthesisNode.js +293 -0
  84. package/omd/nodes/omdPowerNode.js +236 -0
  85. package/omd/nodes/omdRationalNode.js +295 -0
  86. package/omd/nodes/omdSqrtNode.js +308 -0
  87. package/omd/nodes/omdUnaryExpressionNode.js +178 -0
  88. package/omd/nodes/omdVariableNode.js +123 -0
  89. package/omd/simplification/omdSimplification.js +171 -0
  90. package/omd/simplification/omdSimplificationEngine.js +886 -0
  91. package/omd/simplification/package.json +6 -0
  92. package/omd/simplification/rules/binaryRules.js +1037 -0
  93. package/omd/simplification/rules/functionRules.js +111 -0
  94. package/omd/simplification/rules/index.js +48 -0
  95. package/omd/simplification/rules/parenthesisRules.js +19 -0
  96. package/omd/simplification/rules/powerRules.js +143 -0
  97. package/omd/simplification/rules/rationalRules.js +475 -0
  98. package/omd/simplification/rules/sqrtRules.js +48 -0
  99. package/omd/simplification/rules/unaryRules.js +37 -0
  100. package/omd/simplification/simplificationRules.js +32 -0
  101. package/omd/simplification/simplificationUtils.js +1056 -0
  102. package/omd/step-visualizer/omdStepVisualizer.js +597 -0
  103. package/omd/step-visualizer/omdStepVisualizerHighlighting.js +206 -0
  104. package/omd/step-visualizer/omdStepVisualizerLayout.js +245 -0
  105. package/omd/step-visualizer/omdStepVisualizerTextBoxes.js +163 -0
  106. package/omd/utils/omdNodeOverlay.js +638 -0
  107. package/omd/utils/omdPopup.js +1084 -0
  108. package/omd/utils/omdStepVisualizerInteractiveSteps.js +491 -0
  109. package/omd/utils/omdStepVisualizerNodeUtils.js +268 -0
  110. package/omd/utils/omdTranscriptionService.js +125 -0
  111. package/omd/utils/omdTreeDiff.js +734 -0
  112. package/package.json +46 -0
  113. package/src/index.js +62 -0
  114. package/src/json-schemas.md +109 -0
  115. package/src/omd-json-samples.js +115 -0
  116. package/src/omd.js +109 -0
  117. package/src/omdApp.js +391 -0
  118. package/src/omdAppCanvas.js +336 -0
  119. package/src/omdBalanceHanger.js +172 -0
  120. package/src/omdColor.js +13 -0
  121. package/src/omdCoordinatePlane.js +467 -0
  122. package/src/omdEquation.js +125 -0
  123. package/src/omdExpression.js +104 -0
  124. package/src/omdFunction.js +113 -0
  125. package/src/omdMetaExpression.js +287 -0
  126. package/src/omdNaturalExpression.js +564 -0
  127. package/src/omdNode.js +384 -0
  128. package/src/omdNumber.js +53 -0
  129. package/src/omdNumberLine.js +107 -0
  130. package/src/omdNumberTile.js +119 -0
  131. package/src/omdOperator.js +73 -0
  132. package/src/omdPowerExpression.js +92 -0
  133. package/src/omdProblem.js +55 -0
  134. package/src/omdRatioChart.js +232 -0
  135. package/src/omdRationalExpression.js +115 -0
  136. package/src/omdSampleData.js +215 -0
  137. package/src/omdShapes.js +476 -0
  138. package/src/omdSpinner.js +148 -0
  139. package/src/omdString.js +39 -0
  140. package/src/omdTable.js +369 -0
  141. package/src/omdTapeDiagram.js +245 -0
  142. package/src/omdTerm.js +92 -0
  143. package/src/omdTileEquation.js +349 -0
  144. package/src/omdVariable.js +51 -0
@@ -0,0 +1,245 @@
1
+ import { omdColor } from "./omdColor.js";
2
+ import { jsvgGroup, jsvgRect, jsvgTextBox } from "@teachinglab/jsvg";
3
+
4
+ export class omdTapeLabel extends jsvgGroup
5
+ {
6
+ constructor()
7
+ {
8
+ // initialization
9
+ super();
10
+
11
+ this.startValue = 1;
12
+ this.endValue = 3;
13
+ this.startIndex = 0;
14
+ this.endIndex = 1;
15
+ this.label = "label";
16
+ this.showBelow = false;
17
+ this.unitWidth = 30;
18
+ this.indexPositions = [];
19
+
20
+ this.startPos = 0;
21
+ this.endPos = 0;
22
+
23
+ this.updateLayout();
24
+ }
25
+
26
+ setIndexPositions( xPosArray )
27
+ {
28
+ this.indexPositions = xPosArray
29
+ }
30
+
31
+ loadFromJSON( data )
32
+ {
33
+ if (!data || typeof data !== "object") { return; }
34
+
35
+ const { startIndex, endIndex, label, showBelow } = data;
36
+
37
+ if (startIndex !== undefined) {
38
+ this.startIndex = startIndex;
39
+ if (startIndex >= 0 && startIndex <= this.indexPositions.length) {
40
+ this.startPos = this.indexPositions[startIndex];
41
+ }
42
+ }
43
+
44
+ if (endIndex !== undefined) {
45
+ this.endIndex = endIndex;
46
+ if (endIndex >= 0 && endIndex <= this.indexPositions.length) {
47
+ this.endPos = this.indexPositions[endIndex];
48
+ }
49
+ }
50
+
51
+ // startValue/endValue no longer supported; use startIndex/endIndex only
52
+
53
+ if (label !== undefined) { this.label = label; }
54
+ if (showBelow !== undefined) { this.showBelow = showBelow; }
55
+
56
+ this.updateLayout();
57
+ }
58
+
59
+ updateLayout()
60
+ {
61
+ this.removeAllChildren();
62
+
63
+ // make line
64
+ var startX = this.startPos;
65
+ var endX = this.endPos;
66
+ var W = endX - startX;
67
+ this.line = new jsvgLine();
68
+ this.line.setEndpoints( startX, 0, endX, 0 );
69
+ this.addChild( this.line );
70
+
71
+ // make ticks
72
+ var tick = new jsvgLine();
73
+ tick.setEndpoints( startX, -3, startX, 3 );
74
+ this.addChild( tick );
75
+
76
+ tick = new jsvgLine();
77
+ tick.setEndpoints( endX, -3, endX, 3 );
78
+ this.addChild( tick );
79
+
80
+ // make label text
81
+ var labelText = new jsvgTextBox();
82
+ labelText.setWidthAndHeight( W,30 );
83
+ labelText.setText ( this.name );
84
+ labelText.setFontFamily( "Albert Sans" );
85
+ labelText.setFontColor( "black" );
86
+ labelText.setFontSize( 14 );
87
+ labelText.setAlignment("center");
88
+ labelText.setText( this.label );
89
+ if ( this.showBelow )
90
+ labelText.setPosition( startX, 5 );
91
+ else
92
+ labelText.setPosition( startX, -20 );
93
+ this.addChild( labelText );
94
+
95
+ // Calculate dimensions for this label
96
+ var labelWidth = Math.max(W, endX);
97
+ var labelHeight = this.showBelow ? 35 : 30; // Account for text position
98
+
99
+ // Set proper bounds and viewBox for the label
100
+ this.setWidthAndHeight( labelWidth, labelHeight );
101
+ this.svgObject.setAttribute("viewBox", `0 ${this.showBelow ? -5 : -25} ${labelWidth} ${labelHeight}`);
102
+ }
103
+ }
104
+
105
+ export class omdTapeDiagram extends jsvgGroup
106
+ {
107
+ constructor()
108
+ {
109
+ // initialization
110
+ super();
111
+
112
+ this.type = "omdTapeDiagram";
113
+
114
+ this.values = [];
115
+ this.showValues = true;
116
+ this.colors = [];
117
+ this.labelSet = [];
118
+ this.unitWidth = 30;
119
+ this.updateLayout();
120
+ }
121
+
122
+ loadFromJSON( data )
123
+ {
124
+ if ( typeof data.values != "undefined" )
125
+ this.values = data.values;
126
+
127
+ if ( typeof data.showValues != "undefined" )
128
+ this.showValues = data.showValues;
129
+
130
+ if ( typeof data.colors != "undefined" )
131
+ this.colors = data.colors;
132
+
133
+ if ( typeof data.labelSet != "undefined" )
134
+ this.labelSet = data.labelSet;
135
+
136
+ if ( typeof data.unitWidth != "undefined" )
137
+ this.unitWidth = data.unitWidth;
138
+
139
+ this.updateLayout();
140
+ }
141
+
142
+ setValues( newValues )
143
+ {
144
+ this.values = newValues;
145
+ }
146
+
147
+ updateLayout()
148
+ {
149
+ this.removeAllChildren();
150
+
151
+ // console.log( this.values );
152
+
153
+ // make box with text
154
+ var pX = 0;
155
+ var indexPositions = [];
156
+ for( var i=0; i<this.values.length; i++ )
157
+ {
158
+ indexPositions.push(pX);
159
+
160
+ var value = this.values[i];
161
+ var W = 30;
162
+ if ( typeof value == "string" )
163
+ {
164
+ W = 20 + value.length*10;
165
+ }
166
+ else
167
+ {
168
+ W = value * this.unitWidth;
169
+ }
170
+
171
+
172
+ // make box
173
+ var box = new jsvgRect();
174
+ box.setWidthAndHeight( W, 30 );
175
+ box.setCornerRadius(5);
176
+ box.setStrokeColor( "white" );
177
+ box.setStrokeWidth( 1 );
178
+
179
+ // Use custom color if available, otherwise default to light gray
180
+ var boxColor = omdColor.lightGray;
181
+ if ( this.colors && this.colors.length > i && this.colors[i] )
182
+ {
183
+ boxColor = this.colors[i];
184
+ }
185
+ box.setFillColor( boxColor );
186
+
187
+ box.setPosition( pX, 0 );
188
+ this.addChild( box );
189
+
190
+ // make box text
191
+ var boxText = new jsvgTextBox();
192
+ boxText.setWidthAndHeight( W,30 );
193
+ boxText.setText ( this.name );
194
+ boxText.setFontFamily( "Albert Sans" );
195
+ boxText.setFontColor( "black" );
196
+ boxText.setFontSize( 18 );
197
+ boxText.setAlignment("center");
198
+ boxText.setVerticalCentering();
199
+ boxText.setText( value.toString() );
200
+ boxText.setPosition( pX, 0 );
201
+ this.addChild( boxText );
202
+
203
+ pX += W;
204
+ }
205
+
206
+ indexPositions.push(pX);
207
+
208
+ // Calculate actual content dimensions
209
+ var contentWidth = pX; // Total width of all boxes
210
+ var contentHeight = 30; // Height of the tape
211
+ var labelHeight = 0;
212
+
213
+ // Check if labels extend the height
214
+ for ( var labelData of this.labelSet )
215
+ {
216
+ if ( labelData.showBelow )
217
+ labelHeight = Math.max(labelHeight, 70); // 40 offset + 30 text height
218
+ else
219
+ labelHeight = Math.max(labelHeight, 30); // 20 offset above + 10 buffer
220
+ }
221
+
222
+ if ( labelHeight > 0 )
223
+ contentHeight += labelHeight;
224
+
225
+ // make label text
226
+ for ( var labelData of this.labelSet )
227
+ {
228
+ var T = new omdTapeLabel();
229
+ T.unitWidth = this.unitWidth;
230
+ T.setIndexPositions( indexPositions );
231
+ T.loadFromJSON( labelData );
232
+ if ( T.showBelow )
233
+ T.setPosition( 0, 40 );
234
+ else
235
+ T.setPosition( 0, -10 );
236
+ this.addChild( T )
237
+ }
238
+
239
+ // Set proper bounds to hug the content
240
+ this.setWidthAndHeight( contentWidth, contentHeight );
241
+ // Fix the viewBox to match our actual content dimensions (no padding)
242
+ this.svgObject.setAttribute("viewBox", `0 0 ${contentWidth} ${contentHeight}`);
243
+ }
244
+
245
+ }
package/src/omdTerm.js ADDED
@@ -0,0 +1,92 @@
1
+
2
+ import { omdColor } from "./omdColor.js";
3
+ import { omdMetaExpression } from "./omdMetaExpression.js"
4
+
5
+ export class omdTerm extends omdMetaExpression
6
+ {
7
+ constructor( coefficient=1, variable='', exponent=1 )
8
+ {
9
+ // initialization
10
+ super();
11
+
12
+ this.type = "omdTerm";
13
+ this.coefficient = coefficient;
14
+ this.variable = variable;
15
+ this.exponent = exponent;
16
+
17
+ this.numText = new jsvgTextBox();
18
+ this.numText.setWidthAndHeight( 30,30 );
19
+ this.numText.setText ( this.name );
20
+ this.numText.setFontFamily( "Albert Sans" );
21
+ this.numText.setFontColor( "black" );
22
+ this.numText.setFontSize( 18 );
23
+ this.numText.setVerticalCentering();
24
+ this.numText.setAlignment("center");
25
+ // this.numText.div.style.border = "1px solid black";
26
+ this.addChild( this.numText );
27
+
28
+ this.setValue( coefficient, variable, exponent );
29
+ this.updateLayout();
30
+ }
31
+
32
+ loadFromJSON( data )
33
+ {
34
+ if ( typeof data.coefficient != "undefined" )
35
+ this.coefficient = data.coefficient;
36
+
37
+ if ( typeof data.variable != "undefined" )
38
+ this.variable = data.variable;
39
+
40
+ if ( typeof data.exponent != "undefined" )
41
+ this.exponent = data.exponent;
42
+
43
+ this.updateLayout();
44
+ }
45
+
46
+ setValue( coefficient, variable='', exponent=1 )
47
+ {
48
+ this.coefficient = coefficient;
49
+ this.variable = variable;
50
+ this.exponent = exponent;
51
+
52
+ this.updateLayout();
53
+ }
54
+
55
+ updateLayout()
56
+ {
57
+ var T = "";
58
+ if ( this.variable && this.variable.length != 0 )
59
+ {
60
+ T = this.coefficient.toString() + this.variable;
61
+ if ( this.coefficient == 1)
62
+ {
63
+ T = this.variable;
64
+ }
65
+ }
66
+ else
67
+ {
68
+ T = this.coefficient.toString();
69
+ }
70
+
71
+ if ( this.exponent )
72
+ {
73
+ if ( this.exponent == 1 )
74
+ {
75
+ // don't show it
76
+ }
77
+ else if ( this.exponent == 2 )
78
+ T += "²";
79
+ else if ( this.exponent == 3 )
80
+ T += "³";
81
+ else
82
+ T += "<sup>" + this.exponent.toString() + "</sup>";
83
+ }
84
+
85
+ var W = 15 + T.length*10;
86
+ this.backRect.setWidthAndHeight( W, 30 );
87
+ this.numText.setWidthAndHeight( W, 30 );
88
+ this.numText.setText ( T );
89
+
90
+ this.setWidthAndHeight( this.backRect.width, this.backRect.height );
91
+ }
92
+ }
@@ -0,0 +1,349 @@
1
+ import { omdColor } from "./omdColor.js";
2
+ import { omdNumberTile } from "./omdNumberTile.js";
3
+ import { jsvgGroup, jsvgRect, jsvgTextBox, jsvgTextLine } from "@teachinglab/jsvg";
4
+
5
+ export class omdTileEquation extends jsvgGroup {
6
+ constructor() {
7
+ super();
8
+ this.type = "omdTileEquation";
9
+ this.left = []; // generic mode
10
+ this.right = [];
11
+ this.equation = null; // special mode: { x:number, units:number, total:number, xLabel?:string }
12
+ this.tileSize = 28;
13
+ this.tileGap = 6;
14
+ this.rowGap = 10;
15
+ this.equalGap = 24; // gap between left and right
16
+ this.tileRadius = 6;
17
+ this.showLabels = true;
18
+ this.fontFamily = 'Albert Sans';
19
+ this.fontSize = 16;
20
+ // Styles
21
+ this.plusColor = '#79BBFD';
22
+ this.equalsColor = '#FF6B6B';
23
+ this.xPillColor = omdColor.lightGray;
24
+ this.numberTileDefaults = { backgroundColor: omdColor.lightGray, dotColor: 'black' };
25
+ this.updateLayout();
26
+ }
27
+
28
+ loadFromJSON(data) {
29
+ if (!data || typeof data !== 'object') return;
30
+ if (Array.isArray(data.left)) this.left = data.left;
31
+ if (Array.isArray(data.right)) this.right = data.right;
32
+ if (typeof data.equation === 'string') {
33
+ this.equation = this._parseEquationString(data.equation);
34
+ } else if (data.equation && typeof data.equation === 'object') {
35
+ this.equation = data.equation;
36
+ } else if (typeof data.equationString === 'string') {
37
+ this.equation = this._parseEquationString(data.equationString);
38
+ }
39
+ if (typeof data.tileSize === 'number') this.tileSize = data.tileSize;
40
+ if (typeof data.tileGap === 'number') this.tileGap = data.tileGap;
41
+ if (typeof data.equalGap === 'number') this.equalGap = data.equalGap;
42
+ if (typeof data.tileRadius === 'number') this.tileRadius = data.tileRadius;
43
+ if (typeof data.showLabels === 'boolean') this.showLabels = data.showLabels;
44
+ if (typeof data.fontFamily === 'string') this.fontFamily = data.fontFamily;
45
+ if (typeof data.fontSize === 'number') this.fontSize = data.fontSize;
46
+ if (typeof data.plusColor === 'string') this.plusColor = data.plusColor;
47
+ if (typeof data.equalsColor === 'string') this.equalsColor = data.equalsColor;
48
+ if (data.xPill && typeof data.xPill.color === 'string') this.xPillColor = data.xPill.color;
49
+ if (typeof data.xPillColor === 'string') this.xPillColor = data.xPillColor;
50
+ if (data.numberTileDefaults && typeof data.numberTileDefaults === 'object') {
51
+ this.numberTileDefaults = {
52
+ backgroundColor: data.numberTileDefaults.backgroundColor ?? this.numberTileDefaults.backgroundColor,
53
+ dotColor: data.numberTileDefaults.dotColor ?? this.numberTileDefaults.dotColor
54
+ };
55
+ }
56
+ this.updateLayout();
57
+ }
58
+
59
+ // Parse equations like "5x+4+2=23+12x" or with subtraction like "4x+3=23-x".
60
+ // Returns an object with positive counts arranged on each side by moving negatives across '='.
61
+ _parseEquationString(str) {
62
+ try {
63
+ const raw = String(str || '').replace(/\s+/g, '');
64
+ const parts = raw.split('=');
65
+ if (parts.length !== 2) return null;
66
+ const left = parts[0];
67
+ const right = parts[1];
68
+
69
+ const parseSide = (sideStr) => {
70
+ const cleaned = String(sideStr || '').replace(/[\s−–]/g, ch => (ch === ' ' ? '' : '-'));
71
+ const tokenRe = /([+-]?\d*[a-zA-Z])|([+-]?\d+)/g;
72
+ let varLabel = null;
73
+ const tokens = [];
74
+ const matches = cleaned.match(tokenRe) || [];
75
+ matches.forEach(tok => {
76
+ if (/[a-zA-Z]/.test(tok)) {
77
+ const m = tok.match(/^([+-]?)(\d*)([a-zA-Z])$/);
78
+ const sign = (m[1] || '+') === '-' ? '-' : '+';
79
+ const coef = m[2] ? parseInt(m[2], 10) : 1;
80
+ varLabel = varLabel || m[3];
81
+ tokens.push({ kind: 'x', count: Math.max(1, coef), sign });
82
+ } else {
83
+ const sign = tok[0] === '-' ? '-' : '+';
84
+ const val = Math.abs(parseInt(tok, 10));
85
+ tokens.push({ kind: 'const', value: Math.max(0, val), sign });
86
+ }
87
+ });
88
+ return { varLabel, tokens };
89
+ };
90
+
91
+ const L = parseSide(left);
92
+ const R = parseSide(right);
93
+ const useLabel = L.varLabel || R.varLabel || 'X';
94
+
95
+ return {
96
+ leftTokens: L.tokens,
97
+ rightTokens: R.tokens,
98
+ xLabel: useLabel
99
+ };
100
+ } catch (_) {
101
+ return null;
102
+ }
103
+ }
104
+
105
+ updateLayout() {
106
+ this.removeAllChildren();
107
+
108
+ if (this.equation) {
109
+ const dims = this._renderEquation(this.equation);
110
+ this.setWidthAndHeight(dims.width, dims.height);
111
+ this.svgObject.setAttribute('viewBox', `0 0 ${dims.width} ${dims.height}`);
112
+ return;
113
+ }
114
+
115
+ const leftGroup = new jsvgGroup();
116
+ const rightGroup = new jsvgGroup();
117
+ this.addChild(leftGroup);
118
+ this.addChild(rightGroup);
119
+
120
+ const leftDims = this._renderSide(leftGroup, this.left);
121
+ const rightDims = this._renderSide(rightGroup, this.right);
122
+
123
+ rightGroup.setPosition(leftDims.width + this.equalGap, 0);
124
+
125
+ const totalWidth = leftDims.width + this.equalGap + rightDims.width;
126
+ const totalHeight = Math.max(leftDims.height, rightDims.height);
127
+ this.setWidthAndHeight(totalWidth, totalHeight);
128
+ this.svgObject.setAttribute('viewBox', `0 0 ${totalWidth} ${totalHeight}`);
129
+ }
130
+
131
+ _renderSide(holder, terms) {
132
+ let x = 0;
133
+ let baseY = 0;
134
+ let maxHeight = 0;
135
+
136
+ terms.forEach(term => {
137
+ const kind = term?.kind || 'var';
138
+ const color = term?.color || (kind === 'var' ? '#79BBFD' : '#FFA26D');
139
+ const count = Math.max(1, Number(term?.count || 1));
140
+
141
+ if (kind === 'text') {
142
+ const t = new jsvgTextBox();
143
+ const padX = 8, padY = 6;
144
+ t.setWidthAndHeight(this.fontSize * (String(term.value).length * 0.7) + padX * 2, this.fontSize + padY * 2);
145
+ t.setFontFamily(this.fontFamily);
146
+ t.setFontSize(this.fontSize);
147
+ t.setFontColor('black');
148
+ t.setAlignment('center');
149
+ t.setVerticalCentering();
150
+ t.setText(String(term.value));
151
+
152
+ const r = new jsvgRect();
153
+ r.setWidthAndHeight(t.width, t.height);
154
+ r.setCornerRadius(Math.min(this.tileRadius, t.height / 2));
155
+ r.setFillColor(omdColor.lightGray);
156
+ const g = new jsvgGroup();
157
+ g.setPosition(x, baseY);
158
+ g.addChild(r);
159
+ g.addChild(t);
160
+ holder.addChild(g);
161
+ x += t.width + this.tileGap;
162
+ maxHeight = Math.max(maxHeight, t.height);
163
+ return;
164
+ }
165
+
166
+ const g = new jsvgGroup();
167
+ g.setPosition(x, baseY);
168
+ holder.addChild(g);
169
+
170
+ // Arrange as vertical stack if 'stack' true; otherwise single row
171
+ const stack = !!term.stack;
172
+ let localWidth = 0;
173
+ let localHeight = 0;
174
+ for (let i = 0; i < count; i++) {
175
+ const box = new jsvgRect();
176
+ box.setWidthAndHeight(this.tileSize, this.tileSize);
177
+ box.setCornerRadius(Math.min(this.tileRadius, this.tileSize / 2));
178
+ box.setFillColor(color);
179
+ const bx = stack ? 0 : i * (this.tileSize + this.tileGap);
180
+ const by = stack ? i * (this.tileSize + this.rowGap) : 0;
181
+ box.setPosition(bx, by);
182
+ g.addChild(box);
183
+ localWidth = Math.max(localWidth, bx + this.tileSize);
184
+ localHeight = Math.max(localHeight, by + this.tileSize);
185
+ }
186
+ x += localWidth + this.tileGap;
187
+ maxHeight = Math.max(maxHeight, localHeight);
188
+ });
189
+
190
+ return { width: x > 0 ? x - this.tileGap : 0, height: maxHeight };
191
+ }
192
+
193
+ _renderEquation(eq) {
194
+ // Prefer new token format; fall back to legacy counts if provided
195
+ const hasTokens = Array.isArray(eq.leftTokens) && Array.isArray(eq.rightTokens);
196
+ const leftTokens = hasTokens ? eq.leftTokens : [];
197
+ const rightTokens = hasTokens ? eq.rightTokens : [];
198
+ const legacyLeftX = Math.max(0, Number(eq.leftX ?? eq.x ?? 0));
199
+ const legacyLeftUnits = Array.isArray(eq.leftUnitList) ? eq.leftUnitList : (Number.isFinite(eq.leftUnits ?? eq.units) ? [Math.max(0, Number(eq.leftUnits ?? eq.units))] : []);
200
+ const legacyRightX = Math.max(0, Number(eq.rightX ?? 0));
201
+ const legacyRightUnits = Array.isArray(eq.rightUnitList) ? eq.rightUnitList : (Number.isFinite(eq.rightUnits ?? eq.total) ? [Math.max(0, Number(eq.rightUnits ?? eq.total))] : []);
202
+ const xLabel = String(eq.xLabel || 'X');
203
+
204
+ // Pre-compute sizes and local top-center offsets
205
+ // Configure X pill appearance
206
+ const xPillColor = this.xPillColor || omdColor.lightGray;
207
+ // Pill width: ~5x the "X" glyph width (fontSize 0.7 * tileSize; glyph width ~0.62*fontSize)
208
+ const xFont = this.tileSize;
209
+ const xGlyphWidth = 0.62 * xFont;
210
+ const tileW = Math.max(this.tileSize * 1.6, Math.round(5 * xGlyphWidth));
211
+ const tileH = this.tileSize;
212
+ // Pre-create number tiles for measurement (tokens or legacy)
213
+ const countLeftX = hasTokens ? (leftTokens.filter(t => t.kind === 'x').reduce((a, t) => a + t.count, 0)) : legacyLeftX;
214
+ const countRightX = hasTokens ? (rightTokens.filter(t => t.kind === 'x').reduce((a, t) => a + t.count, 0)) : legacyRightX;
215
+ const stackH = countLeftX > 0 ? (countLeftX * (tileH + this.rowGap) - this.rowGap) : 0;
216
+ const unitTilesL = (hasTokens
217
+ ? leftTokens.filter(t => t.kind === 'const').map(tk => { const t = new omdNumberTile(); t.loadFromJSON({ value: tk.value, size: 'medium', backgroundColor: this.numberTileDefaults.backgroundColor, dotColor: this.numberTileDefaults.dotColor }); return t; })
218
+ : legacyLeftUnits.map(v => { const t = new omdNumberTile(); t.loadFromJSON({ value: v, size: 'medium', backgroundColor: this.numberTileDefaults.backgroundColor, dotColor: this.numberTileDefaults.dotColor }); return t; })
219
+ );
220
+ const unitTilesR = (hasTokens
221
+ ? rightTokens.filter(t => t.kind === 'const').map(tk => { const t = new omdNumberTile(); t.loadFromJSON({ value: tk.value, size: 'medium', backgroundColor: this.numberTileDefaults.backgroundColor, dotColor: this.numberTileDefaults.dotColor }); return t; })
222
+ : legacyRightUnits.map(v => { const t = new omdNumberTile(); t.loadFromJSON({ value: v, size: 'medium', backgroundColor: this.numberTileDefaults.backgroundColor, dotColor: this.numberTileDefaults.dotColor }); return t; })
223
+ );
224
+
225
+ const xTopLocal = countLeftX > 0 ? (tileH / 2) : 0;
226
+ const unitTopLocalL = unitTilesL.length ? Math.min(...unitTilesL.map(t => t.getTopDotCenterY())) : 0;
227
+ const unitTopLocalR = unitTilesR.length ? Math.min(...unitTilesR.map(t => t.getTopDotCenterY())) : 0;
228
+
229
+ // Choose a baseline so all components have non-negative Y positions when aligned
230
+ const baselineY = Math.max(xTopLocal, unitTopLocalL, unitTopLocalR, this.tileSize * 0.6);
231
+
232
+ // Compute Y positions such that each component's top anchor equals baselineY
233
+ const yX = countLeftX > 0 ? (baselineY - xTopLocal) : 0;
234
+ const yUnitL = unitTilesL.length ? (baselineY - unitTopLocalL) : 0;
235
+ const yUnitR = unitTilesR.length ? (baselineY - unitTopLocalR) : 0;
236
+
237
+ // Compute overall height from bottoms
238
+ const bottoms = [];
239
+ if (countLeftX > 0) bottoms.push(yX + stackH);
240
+ unitTilesL.forEach(t => bottoms.push(yUnitL + t.height));
241
+ unitTilesR.forEach(t => bottoms.push(yUnitR + t.height));
242
+ const maxH = bottoms.length ? Math.max(...bottoms) : this.tileSize * 2;
243
+
244
+ let cursorX = 0;
245
+
246
+ // Helper to add an operator centered in the upcoming gap
247
+ const addOp = (opChar, x) => {
248
+ const op = new jsvgTextLine();
249
+ op.setText(opChar);
250
+ op.setFontSize(this.tileSize);
251
+ op.setFontColor(this.plusColor);
252
+ op.setAlignment('center');
253
+ op.svgObject.setAttribute('dominant-baseline', 'middle');
254
+ op.setPosition(x + this.equalGap / 2, baselineY);
255
+ this.addChild(op);
256
+ };
257
+
258
+ // Render left side tokens (or legacy)
259
+ const renderXStack = () => {
260
+ const g = new jsvgGroup();
261
+ for (let i = 0; i < countLeftX; i++) {
262
+ const y = i * (tileH + this.rowGap);
263
+ const r = new jsvgRect();
264
+ r.setWidthAndHeight(tileW, tileH);
265
+ r.setCornerRadius(tileH / 2);
266
+ r.setFillColor(xPillColor);
267
+ r.setPosition(0, y);
268
+ g.addChild(r);
269
+ const t = new jsvgTextLine();
270
+ t.setText(xLabel);
271
+ t.setFontWeight('bold');
272
+ t.setFontSize(this.tileSize * 0.7);
273
+ t.setFontFamily(this.fontFamily);
274
+ t.setFontColor('black');
275
+ t.setAlignment('center');
276
+ t.svgObject.setAttribute('dominant-baseline', 'middle');
277
+ const textBias = tileH * 0.06;
278
+ t.setPosition(tileW / 2, y + tileH / 2 + textBias);
279
+ g.addChild(t);
280
+ }
281
+ return g;
282
+ };
283
+
284
+ const renderSide = (tokens, startX, yUnitTop, countX, isLeft) => {
285
+ let x = startX;
286
+ let hasPrev = false;
287
+ // If legacy, synthesize token sequence: X then each unit
288
+ const seq = hasTokens ? tokens.slice() : [
289
+ ...(countX > 0 ? [{ kind: 'x', count: countX, sign: '+' }] : []),
290
+ ...((isLeft ? legacyLeftUnits : legacyRightUnits).map(v => ({ kind: 'const', value: v, sign: '+' })))
291
+ ];
292
+
293
+ seq.forEach(tok => {
294
+ const sign = tok.sign === '-' ? '-' : '+';
295
+ // operator before this token
296
+ if (hasPrev || sign === '-') {
297
+ addOp(sign === '-' ? '−' : '+', x);
298
+ x += this.equalGap;
299
+ }
300
+ if (tok.kind === 'x') {
301
+ const g = renderXStack();
302
+ g.setPosition(x, baselineY - xTopLocal);
303
+ this.addChild(g);
304
+ x += tileW;
305
+ hasPrev = true;
306
+ } else {
307
+ // const tile
308
+ const tile = new omdNumberTile();
309
+ tile.loadFromJSON({ value: tok.value, size: 'medium', backgroundColor: this.numberTileDefaults.backgroundColor, dotColor: this.numberTileDefaults.dotColor });
310
+ tile.setPosition(x, yUnitTop);
311
+ this.addChild(tile);
312
+ x += tile.width;
313
+ hasPrev = true;
314
+ }
315
+ });
316
+ return x;
317
+ };
318
+
319
+ // Render left side
320
+ if (hasTokens ? (leftTokens.length > 0) : (countLeftX > 0 || unitTilesL.length)) {
321
+ const g = new jsvgGroup();
322
+ g.setPosition(0, 0); // placeholder container (not strictly needed)
323
+ // Ensure left starts with any minus/plus operators between tokens
324
+ cursorX = renderSide(leftTokens, cursorX, yUnitL, countLeftX, true);
325
+ }
326
+ // Reserve equals gap
327
+ cursorX += this.equalGap;
328
+
329
+ // Equals sign aligned to baselineY
330
+ const eqWidth = this.tileSize * 1.2;
331
+ const eqTxt = new jsvgTextLine();
332
+ eqTxt.setText('=');
333
+ eqTxt.setFontSize(this.tileSize * 1.1);
334
+ eqTxt.setFontColor(this.equalsColor);
335
+ eqTxt.setAlignment('center');
336
+ eqTxt.svgObject.setAttribute('dominant-baseline', 'middle');
337
+ // Center equals in the equals gap we just reserved
338
+ const eqMid = cursorX - this.equalGap / 2;
339
+ eqTxt.setPosition(eqMid, baselineY);
340
+ this.addChild(eqTxt);
341
+
342
+ // Render right side tokens
343
+ cursorX = renderSide(rightTokens, cursorX, yUnitR, countRightX, false);
344
+
345
+ return { width: cursorX, height: maxH };
346
+ }
347
+ }
348
+
349
+