@teachinglab/omd 0.6.1 → 0.6.3

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 (198) hide show
  1. package/README.md +257 -251
  2. package/README.old.md +137 -137
  3. package/canvas/core/canvasConfig.js +202 -202
  4. package/canvas/drawing/segment.js +167 -167
  5. package/canvas/drawing/stroke.js +385 -385
  6. package/canvas/events/eventManager.js +444 -444
  7. package/canvas/events/pointerEventHandler.js +262 -262
  8. package/canvas/index.js +48 -48
  9. package/canvas/tools/PointerTool.js +71 -71
  10. package/canvas/tools/tool.js +222 -222
  11. package/canvas/utils/boundingBox.js +377 -377
  12. package/canvas/utils/mathUtils.js +258 -258
  13. package/docs/api/configuration-options.md +198 -198
  14. package/docs/api/eventManager.md +82 -82
  15. package/docs/api/focusFrameManager.md +144 -144
  16. package/docs/api/index.md +105 -105
  17. package/docs/api/main.md +62 -62
  18. package/docs/api/omdBinaryExpressionNode.md +86 -86
  19. package/docs/api/omdCanvas.md +83 -83
  20. package/docs/api/omdConfigManager.md +112 -112
  21. package/docs/api/omdConstantNode.md +52 -52
  22. package/docs/api/omdDisplay.md +87 -87
  23. package/docs/api/omdEquationNode.md +174 -174
  24. package/docs/api/omdEquationSequenceNode.md +258 -258
  25. package/docs/api/omdEquationStack.md +192 -192
  26. package/docs/api/omdFunctionNode.md +82 -82
  27. package/docs/api/omdGroupNode.md +78 -78
  28. package/docs/api/omdHelpers.md +87 -87
  29. package/docs/api/omdLeafNode.md +85 -85
  30. package/docs/api/omdNode.md +201 -201
  31. package/docs/api/omdOperationDisplayNode.md +117 -117
  32. package/docs/api/omdOperatorNode.md +91 -91
  33. package/docs/api/omdParenthesisNode.md +133 -133
  34. package/docs/api/omdPopup.md +191 -191
  35. package/docs/api/omdPowerNode.md +131 -131
  36. package/docs/api/omdRationalNode.md +144 -144
  37. package/docs/api/omdSequenceNode.md +128 -128
  38. package/docs/api/omdSimplification.md +78 -78
  39. package/docs/api/omdSqrtNode.md +144 -144
  40. package/docs/api/omdStepVisualizer.md +146 -146
  41. package/docs/api/omdStepVisualizerHighlighting.md +65 -65
  42. package/docs/api/omdStepVisualizerInteractiveSteps.md +108 -108
  43. package/docs/api/omdStepVisualizerLayout.md +70 -70
  44. package/docs/api/omdStepVisualizerNodeUtils.md +140 -140
  45. package/docs/api/omdStepVisualizerTextBoxes.md +76 -76
  46. package/docs/api/omdToolbar.md +130 -130
  47. package/docs/api/omdTranscriptionService.md +95 -95
  48. package/docs/api/omdTreeDiff.md +169 -169
  49. package/docs/api/omdUnaryExpressionNode.md +137 -137
  50. package/docs/api/omdUtilities.md +82 -82
  51. package/docs/api/omdVariableNode.md +123 -123
  52. package/docs/api/selectTool.md +74 -74
  53. package/docs/api/simplificationEngine.md +97 -97
  54. package/docs/api/simplificationRules.md +76 -76
  55. package/docs/api/simplificationUtils.md +64 -64
  56. package/docs/api/transcribe.md +43 -43
  57. package/docs/api-reference.md +85 -85
  58. package/docs/index.html +453 -453
  59. package/docs/index.md +38 -38
  60. package/docs/omd-objects.md +258 -258
  61. package/index.js +79 -79
  62. package/jsvg/index.js +3 -0
  63. package/jsvg/jsvg.js +898 -898
  64. package/jsvg/jsvgComponents.js +357 -358
  65. package/npm-docs/DOCUMENTATION_SUMMARY.md +220 -220
  66. package/npm-docs/README.md +251 -251
  67. package/npm-docs/api/api-reference.md +85 -85
  68. package/npm-docs/api/configuration-options.md +198 -198
  69. package/npm-docs/api/eventManager.md +82 -82
  70. package/npm-docs/api/expression-nodes.md +561 -561
  71. package/npm-docs/api/focusFrameManager.md +144 -144
  72. package/npm-docs/api/index.md +105 -105
  73. package/npm-docs/api/main.md +62 -62
  74. package/npm-docs/api/omdBinaryExpressionNode.md +86 -86
  75. package/npm-docs/api/omdCanvas.md +83 -83
  76. package/npm-docs/api/omdConfigManager.md +112 -112
  77. package/npm-docs/api/omdConstantNode.md +52 -52
  78. package/npm-docs/api/omdDisplay.md +87 -87
  79. package/npm-docs/api/omdEquationNode.md +174 -174
  80. package/npm-docs/api/omdEquationSequenceNode.md +258 -258
  81. package/npm-docs/api/omdEquationStack.md +192 -192
  82. package/npm-docs/api/omdFunctionNode.md +82 -82
  83. package/npm-docs/api/omdGroupNode.md +78 -78
  84. package/npm-docs/api/omdHelpers.md +87 -87
  85. package/npm-docs/api/omdLeafNode.md +85 -85
  86. package/npm-docs/api/omdNode.md +201 -201
  87. package/npm-docs/api/omdOperationDisplayNode.md +117 -117
  88. package/npm-docs/api/omdOperatorNode.md +91 -91
  89. package/npm-docs/api/omdParenthesisNode.md +133 -133
  90. package/npm-docs/api/omdPopup.md +191 -191
  91. package/npm-docs/api/omdPowerNode.md +131 -131
  92. package/npm-docs/api/omdRationalNode.md +144 -144
  93. package/npm-docs/api/omdSequenceNode.md +128 -128
  94. package/npm-docs/api/omdSimplification.md +78 -78
  95. package/npm-docs/api/omdSqrtNode.md +144 -144
  96. package/npm-docs/api/omdStepVisualizer.md +146 -146
  97. package/npm-docs/api/omdStepVisualizerHighlighting.md +65 -65
  98. package/npm-docs/api/omdStepVisualizerInteractiveSteps.md +108 -108
  99. package/npm-docs/api/omdStepVisualizerLayout.md +70 -70
  100. package/npm-docs/api/omdStepVisualizerNodeUtils.md +140 -140
  101. package/npm-docs/api/omdStepVisualizerTextBoxes.md +76 -76
  102. package/npm-docs/api/omdToolbar.md +130 -130
  103. package/npm-docs/api/omdTranscriptionService.md +95 -95
  104. package/npm-docs/api/omdTreeDiff.md +169 -169
  105. package/npm-docs/api/omdUnaryExpressionNode.md +137 -137
  106. package/npm-docs/api/omdUtilities.md +82 -82
  107. package/npm-docs/api/omdVariableNode.md +123 -123
  108. package/npm-docs/api/selectTool.md +74 -74
  109. package/npm-docs/api/simplificationEngine.md +97 -97
  110. package/npm-docs/api/simplificationRules.md +76 -76
  111. package/npm-docs/api/simplificationUtils.md +64 -64
  112. package/npm-docs/api/transcribe.md +43 -43
  113. package/npm-docs/guides/equations.md +854 -854
  114. package/npm-docs/guides/factory-functions.md +354 -354
  115. package/npm-docs/guides/getting-started.md +318 -318
  116. package/npm-docs/guides/quick-examples.md +525 -525
  117. package/npm-docs/guides/visualizations.md +682 -682
  118. package/npm-docs/index.html +12 -0
  119. package/npm-docs/json-schemas.md +826 -826
  120. package/omd/config/omdConfigManager.js +279 -267
  121. package/omd/core/index.js +158 -158
  122. package/omd/core/omdEquationStack.js +606 -547
  123. package/omd/core/omdUtilities.js +113 -113
  124. package/omd/display/omdDisplay.js +1045 -963
  125. package/omd/display/omdToolbar.js +501 -501
  126. package/omd/nodes/omdBinaryExpressionNode.js +459 -459
  127. package/omd/nodes/omdConstantNode.js +141 -141
  128. package/omd/nodes/omdEquationNode.js +1327 -1327
  129. package/omd/nodes/omdFunctionNode.js +351 -351
  130. package/omd/nodes/omdGroupNode.js +67 -67
  131. package/omd/nodes/omdLeafNode.js +76 -76
  132. package/omd/nodes/omdNode.js +556 -556
  133. package/omd/nodes/omdOperationDisplayNode.js +321 -321
  134. package/omd/nodes/omdOperatorNode.js +108 -108
  135. package/omd/nodes/omdParenthesisNode.js +292 -292
  136. package/omd/nodes/omdPowerNode.js +235 -235
  137. package/omd/nodes/omdRationalNode.js +295 -295
  138. package/omd/nodes/omdSqrtNode.js +307 -307
  139. package/omd/nodes/omdUnaryExpressionNode.js +227 -227
  140. package/omd/nodes/omdVariableNode.js +122 -122
  141. package/omd/simplification/omdSimplification.js +140 -140
  142. package/omd/simplification/omdSimplificationEngine.js +887 -887
  143. package/omd/simplification/package.json +5 -5
  144. package/omd/simplification/rules/binaryRules.js +1037 -1037
  145. package/omd/simplification/rules/functionRules.js +111 -111
  146. package/omd/simplification/rules/index.js +48 -48
  147. package/omd/simplification/rules/parenthesisRules.js +19 -19
  148. package/omd/simplification/rules/powerRules.js +143 -143
  149. package/omd/simplification/rules/rationalRules.js +725 -725
  150. package/omd/simplification/rules/sqrtRules.js +48 -48
  151. package/omd/simplification/rules/unaryRules.js +37 -37
  152. package/omd/simplification/simplificationRules.js +31 -31
  153. package/omd/simplification/simplificationUtils.js +1055 -1055
  154. package/omd/step-visualizer/omdStepVisualizer.js +947 -947
  155. package/omd/step-visualizer/omdStepVisualizerHighlighting.js +246 -246
  156. package/omd/step-visualizer/omdStepVisualizerLayout.js +892 -892
  157. package/omd/step-visualizer/omdStepVisualizerTextBoxes.js +200 -200
  158. package/omd/utils/aiNextEquationStep.js +106 -106
  159. package/omd/utils/omdNodeOverlay.js +638 -638
  160. package/omd/utils/omdPopup.js +1203 -1203
  161. package/omd/utils/omdStepVisualizerInteractiveSteps.js +684 -684
  162. package/omd/utils/omdStepVisualizerNodeUtils.js +267 -267
  163. package/omd/utils/omdTranscriptionService.js +123 -123
  164. package/omd/utils/omdTreeDiff.js +733 -733
  165. package/package.json +59 -57
  166. package/readme.html +184 -120
  167. package/src/index.js +74 -74
  168. package/src/json-schemas.md +576 -576
  169. package/src/omd-json-samples.js +147 -147
  170. package/src/omdApp.js +391 -391
  171. package/src/omdAppCanvas.js +335 -335
  172. package/src/omdBalanceHanger.js +199 -199
  173. package/src/omdColor.js +13 -13
  174. package/src/omdCoordinatePlane.js +541 -541
  175. package/src/omdExpression.js +115 -115
  176. package/src/omdFactory.js +150 -150
  177. package/src/omdFunction.js +114 -114
  178. package/src/omdMetaExpression.js +290 -290
  179. package/src/omdNaturalExpression.js +563 -563
  180. package/src/omdNode.js +383 -383
  181. package/src/omdNumber.js +52 -52
  182. package/src/omdNumberLine.js +114 -112
  183. package/src/omdNumberTile.js +118 -118
  184. package/src/omdOperator.js +72 -72
  185. package/src/omdPowerExpression.js +91 -91
  186. package/src/omdProblem.js +259 -259
  187. package/src/omdRatioChart.js +251 -251
  188. package/src/omdRationalExpression.js +114 -114
  189. package/src/omdSampleData.js +215 -215
  190. package/src/omdShapes.js +512 -512
  191. package/src/omdSpinner.js +151 -151
  192. package/src/omdString.js +49 -49
  193. package/src/omdTable.js +498 -498
  194. package/src/omdTapeDiagram.js +244 -244
  195. package/src/omdTerm.js +91 -91
  196. package/src/omdTileEquation.js +349 -349
  197. package/src/omdUtils.js +84 -84
  198. package/src/omdVariable.js +51 -51
@@ -1,547 +1,606 @@
1
- import { omdEquationSequenceNode } from '../nodes/omdEquationSequenceNode.js';
2
- import { omdStepVisualizer } from '../step-visualizer/omdStepVisualizer.js';
3
- import { omdToolbar } from '../display/omdToolbar.js';
4
- import { jsvgGroup, jsvgLayoutGroup } from '@teachinglab/jsvg';
5
- import { omdEquationNode } from '../nodes/omdEquationNode.js';
6
- import { omdOperationDisplayNode } from '../nodes/omdOperationDisplayNode.js';
7
-
8
- /**
9
- * A renderable component that bundles a sequence and optional UI controls.
10
- * It acts as a node that can be rendered by an omdDisplay.
11
- * @extends jsvgGroup
12
- */
13
- export class omdEquationStack extends jsvgGroup {
14
- /**
15
- * @param {Array<omdNode>} [steps=[]] - An initial array of equation steps.
16
- * @param {Object} [options={}] - Configuration options.
17
- * @param {boolean} [options.toolbar=false] - If true, creates a toolbar-driven sequence.
18
- * @param {boolean} [options.stepVisualizer=false] - If true, creates a sequence with a step visualizer.
19
- */
20
- constructor(steps = [], options = {}) {
21
- super();
22
- this.options = { ...options };
23
-
24
- // Normalize new structured options
25
- this.toolbarOptions = null;
26
- if (typeof options.toolbar === 'object') {
27
- this.toolbarOptions = { enabled: true, ...options.toolbar };
28
- } else if (options.toolbar === true) {
29
- this.toolbarOptions = { enabled: true };
30
- } else if (options.toolbar === false) {
31
- this.toolbarOptions = { enabled: false };
32
- }
33
- this.stylingOptions = options.styling || null;
34
-
35
- // The sequence is the core. If a visualizer is needed, that's our sequence.
36
- if (options.stepVisualizer) {
37
- // Pass through step visualizer styling options
38
- const stepVisualizerStyling = this.stylingOptions?.stepVisualizer || {};
39
- this.sequence = new omdStepVisualizer(steps, stepVisualizerStyling);
40
- } else {
41
- this.sequence = new omdEquationSequenceNode(steps);
42
- }
43
-
44
- // Apply equation background styling if provided
45
- if (this.stylingOptions?.equationBackground) {
46
- this.sequence.setDefaultEquationBackground(this.stylingOptions.equationBackground);
47
- }
48
-
49
- // Apply step visualizer background styling if provided
50
- if (options.stepVisualizer && this.stylingOptions?.stepVisualizerBackground) {
51
- if (typeof this.sequence.setBackgroundStyle === 'function') {
52
- this.sequence.setBackgroundStyle(this.stylingOptions.stepVisualizerBackground);
53
- }
54
- }
55
-
56
- // If a toolbar is needed, create it.
57
- if (this.toolbarOptions?.enabled) {
58
- // Default undo: call global hook if provided
59
- const toolbarOpts = { ...this.toolbarOptions };
60
- if (toolbarOpts.showUndoButton && !toolbarOpts.onUndo) {
61
- toolbarOpts.onUndo = () => {
62
- if (typeof window !== 'undefined' && typeof window.onOMDToolbarUndo === 'function') {
63
- try { window.onOMDToolbarUndo(this.sequence); } catch (_) {}
64
- }
65
- };
66
- }
67
- this.toolbar = new omdToolbar(this, this.sequence, toolbarOpts);
68
- }
69
-
70
- // Overlay padding (distance from bottom when overlayed)
71
- this.overlayPadding = typeof this.toolbarOptions?.overlayPadding === 'number'
72
- ? this.toolbarOptions.overlayPadding
73
- : 34; // Default a bit above the very bottom to match buttons
74
-
75
- // Create a vertical layout group to hold the sequence and toolbar
76
- this.layoutGroup = new jsvgLayoutGroup();
77
- this.layoutGroup.setSpacer(16); // Adjust as needed for spacing
78
- this.layoutGroup.addChild(this.sequence);
79
- this._overlayChildren = [];
80
-
81
- // Handle toolbar positioning
82
- const position = this.toolbarOptions?.position || this.options.toolbarPosition; // backward compat
83
- const overlayBottom = position === 'bottom' || position === 'overlay-bottom';
84
-
85
- if (this.toolbar) {
86
- if (overlayBottom) {
87
- // For overlay positioning, add toolbar directly to this (not layoutGroup)
88
- this.addChild(this.toolbar.elements.toolbarGroup);
89
- } else {
90
- // For in-flow positioning, add to layout group
91
- this.layoutGroup.addChild(this.toolbar.elements.toolbarGroup);
92
- }
93
- }
94
-
95
- this.addChild(this.layoutGroup);
96
- this.updateLayout();
97
- }
98
-
99
- /**
100
- * Updates the layout and positioning of internal components.
101
- */
102
- updateLayout() {
103
- this.sequence.updateLayout();
104
- this.layoutGroup.doVerticalLayout();
105
-
106
- // Handle toolbar positioning based on overlay flag
107
- const position = this.toolbarOptions?.position || this.options.toolbarPosition; // backward compat
108
- const overlayBottom = position === 'bottom' || position === 'overlay-bottom';
109
-
110
- if (this.toolbar && !overlayBottom) {
111
- // Center the toolbar under the stack if in-flow and their widths differ
112
- const stackWidth = this.sequence.width;
113
- const toolbarWidth = this.toolbar.elements.background.width;
114
- const toolbarGroup = this.toolbar.elements.toolbarGroup;
115
- // Center toolbar horizontally under the stack
116
- toolbarGroup.setPosition(
117
- (stackWidth - toolbarWidth) / 2,
118
- toolbarGroup.ypos // y is handled by layout group
119
- );
120
- }
121
-
122
- this.width = this.layoutGroup.width;
123
- this.height = this.layoutGroup.height;
124
- }
125
-
126
- /**
127
- * Returns the underlying sequence instance.
128
- * @returns {omdEquationSequenceNode|omdStepVisualizer} The managed sequence instance.
129
- */
130
- getSequence() {
131
- return this.sequence;
132
- }
133
-
134
- /**
135
- * Expose overlay padding to the display so it can pass it during reposition
136
- */
137
- getOverlayPadding() {
138
- return this.overlayPadding;
139
- }
140
-
141
- /**
142
- * Returns the visual height in pixels of the toolbar background (unscaled), if present.
143
- * Useful for reserving space when overlaying the toolbar.
144
- */
145
- getToolbarVisualHeight() {
146
- if (this.toolbar && this.toolbar.elements && this.toolbar.elements.background) {
147
- return this.toolbar.elements.background.height || 0;
148
- }
149
- return 0;
150
- }
151
-
152
- /**
153
- * Whether the toolbar is configured to be overlayed at the bottom of the container
154
- * @returns {boolean}
155
- */
156
- isToolbarOverlay() {
157
- const position = this.toolbarOptions?.position || this.options.toolbarPosition; // backward compat
158
- return !!(this.toolbar && (position === 'bottom' || position === 'overlay-bottom'));
159
- }
160
-
161
- /**
162
- * Positions the toolbar overlay at the bottom center of the container
163
- * @param {number} containerWidth - Width of the container
164
- * @param {number} containerHeight - Height of the container
165
- * @param {number} [padding=16] - Padding from the bottom edge
166
- */
167
- positionToolbarOverlay(containerWidth, containerHeight, padding = 16) {
168
- if (!this.toolbar || !this.isToolbarOverlay()) return;
169
-
170
- const toolbarGroup = this.toolbar.elements.toolbarGroup;
171
- const toolbarWidth = this.toolbar.elements.background.width;
172
- const toolbarHeight = this.toolbar.elements.background.height;
173
-
174
- // Position at bottom center of the DISPLAY (container) while this toolbar
175
- // lives inside the stack's local coordinate system, which may be scaled.
176
- // Convert container (global) coordinates to stack-local by subtracting
177
- // the stack's position and dividing by its scale.
178
- const stackX = this.xpos || 0;
179
- const stackY = this.ypos || 0;
180
- const s = (typeof this.scale === 'number' && this.scale > 0) ? this.scale : 1;
181
- const effectivePadding = (typeof padding === 'number') ? padding : this.overlayPadding;
182
-
183
- // Compute top-left of toolbar in container coordinates using UN-SCALED toolbar size
184
- // because we counter-scale the toolbar by 1/s to keep constant on-screen size.
185
- let containerX = (containerWidth - toolbarWidth) / 2;
186
- let containerY = containerHeight - toolbarHeight - effectivePadding;
187
- // Snap to integer pixels to avoid subpixel jitter when scaling
188
- containerX = Math.round(containerX);
189
- containerY = Math.round(containerY);
190
-
191
- // Convert to stack-local coordinates
192
- const x = (containerX - stackX) / s;
193
- const y = (containerY - stackY) / s;
194
-
195
- // Find the root SVG to check its viewBox
196
- let rootSVG = toolbarGroup.svgObject;
197
- while (rootSVG && rootSVG.tagName !== 'svg' && rootSVG.parentElement) {
198
- rootSVG = rootSVG.parentElement;
199
- }
200
- const svgViewBox = rootSVG?.getAttribute?.('viewBox') || 'unknown';
201
-
202
-
203
- // Counter-scale the toolbar so it remains a constant on-screen size
204
- if (typeof toolbarGroup.setScale === 'function') {
205
- toolbarGroup.setScale(1 / s);
206
- }
207
- toolbarGroup.setPosition(x, y);
208
-
209
- // Ensure toolbar is visible and on top
210
- if (toolbarGroup.svgObject) {
211
- toolbarGroup.svgObject.style.display = 'block';
212
- toolbarGroup.svgObject.style.zIndex = '1000';
213
- }
214
-
215
- // Update any overlay children so they remain locked to container anchors
216
- try {
217
- this.updateOverlayChildren(containerWidth, containerHeight, padding);
218
- } catch (_) {}
219
- }
220
- /**
221
- * General helper to position an overlay child relative to a chosen anchor.
222
- * Does not assume only the toolbar; supports various anchors and options.
223
- * @param {object} child - A jsvg node (or any object with setPosition/setScale)
224
- * @param {number} containerWidth - Width of the container (px)
225
- * @param {number} containerHeight - Height of the container (px)
226
- * @param {object} [opts] - Options
227
- * @param {string} [opts.anchor='toolbar-center'] - One of: 'toolbar-center','toolbar-left','toolbar-right','top-left','top-center','top-right','custom'
228
- * @param {number} [opts.offsetX=0] - Horizontal offset in screen pixels (positive -> right)
229
- * @param {number} [opts.offsetY=0] - Vertical offset in screen pixels (positive -> down)
230
- * @param {number} [opts.padding=16] - Padding from edges when computing anchor
231
- * @param {boolean} [opts.counterScale=true] - Whether to counter-scale the child to keep constant on-screen size
232
- * @param {boolean} [opts.addToStack=true] - Whether to add the child to this stack's children (default true)
233
- * @param {{x:number,y:number}|null} [opts.customCoords=null] - If anchor==='custom', use these screen coords
234
- * @returns {object|null} The child or null if not applicable
235
- */
236
- addOverlayChild(child, containerWidth, containerHeight, opts = {}) {
237
- const {
238
- anchor = 'toolbar-center',
239
- offsetX = 0,
240
- offsetY = 0,
241
- padding = 16,
242
- counterScale = true,
243
- addToStack = true,
244
- customCoords = null
245
- } = opts || {};
246
-
247
- // Basic validation
248
- if (!child || typeof containerWidth !== 'number' || typeof containerHeight !== 'number') return null;
249
-
250
- const stackX = this.xpos || 0;
251
- const stackY = this.ypos || 0;
252
- const s = (typeof this.scale === 'number' && this.scale > 0) ? this.scale : 1;
253
-
254
- // Determine base container (screen) coordinates for the anchor
255
- let containerX = 0;
256
- let containerY = 0;
257
-
258
- if (anchor === 'custom' && customCoords && typeof customCoords.x === 'number' && typeof customCoords.y === 'number') {
259
- containerX = Math.round(customCoords.x);
260
- containerY = Math.round(customCoords.y);
261
- } else if (anchor.startsWith('toolbar')) {
262
- if (!this.toolbar) return null;
263
- const tbW = this.toolbar.elements?.background?.width || 0;
264
- const tbH = this.toolbar.elements?.background?.height || 0;
265
- const left = (containerWidth - tbW) / 2;
266
- const right = left + tbW;
267
- const center = left + (tbW / 2);
268
- containerY = Math.round(containerHeight - tbH - (typeof padding === 'number' ? padding : this.overlayPadding));
269
- if (anchor === 'toolbar-center') containerX = Math.round(center);
270
- else if (anchor === 'toolbar-left') containerX = Math.round(left);
271
- else if (anchor === 'toolbar-right') containerX = Math.round(right);
272
- else containerX = Math.round(center);
273
- } else if (anchor.startsWith('top')) {
274
- const topY = Math.round(typeof padding === 'number' ? padding : 16);
275
- const leftX = Math.round(typeof padding === 'number' ? padding : 16);
276
- const rightX = Math.round(containerWidth - (typeof padding === 'number' ? padding : 16));
277
- containerY = topY;
278
- if (anchor === 'top-left') containerX = leftX;
279
- else if (anchor === 'top-center') containerX = Math.round(containerWidth / 2);
280
- else if (anchor === 'top-right') containerX = rightX;
281
- else containerX = leftX;
282
- } else {
283
- // fallback: center
284
- containerX = Math.round(containerWidth / 2);
285
- containerY = Math.round(containerHeight / 2);
286
- }
287
-
288
- // Apply offsets (in screen pixels)
289
- containerX = Math.round(containerX + (offsetX || 0));
290
- containerY = Math.round(containerY + (offsetY || 0));
291
-
292
- // Convert to stack-local coordinates
293
- const x = (containerX - stackX) / s;
294
- const y = (containerY - stackY) / s;
295
-
296
- // Optionally counter-scale child to keep constant on-screen size
297
- if (counterScale && child && typeof child.setScale === 'function') {
298
- try { child.setScale(1 / s); } catch (_) {}
299
- }
300
-
301
- // Position child in stack-local coords
302
- if (child && typeof child.setPosition === 'function') {
303
- try { child.setPosition(x, y); } catch (_) {}
304
- }
305
-
306
- // Optionally add to this stack
307
- if (addToStack) {
308
- try { this.addChild(child); } catch (_) {
309
- try { this.layoutGroup.addChild(child); } catch (_) {}
310
- }
311
- }
312
-
313
- // Remember the overlay child and its options so we can reposition it when
314
- // the stack's scale/position changes (e.g., during zoom/center operations).
315
- try {
316
- // Store a shallow copy of opts to avoid external mutation surprises
317
- const stored = { anchor, offsetX, offsetY, padding, counterScale, addToStack, customCoords };
318
- this._overlayChildren.push({ child, opts: stored });
319
- } catch (_) {}
320
-
321
- // Make sure it's visible and above toolbar
322
- if (child && child.svgObject) {
323
- try { child.svgObject.style.zIndex = '1001'; } catch (_) {}
324
- try { child.svgObject.style.display = 'block'; } catch (_) {}
325
- }
326
-
327
- return child;
328
- }
329
-
330
- /**
331
- * Recompute and apply positions for tracked overlay children.
332
- * Called automatically during `positionToolbarOverlay` and can be called
333
- * manually if you change container size/stack position outside normal flows.
334
- */
335
- updateOverlayChildren(containerWidth, containerHeight, padding = 16) {
336
- if (!Array.isArray(this._overlayChildren) || this._overlayChildren.length === 0) return;
337
-
338
- const stackX = this.xpos || 0;
339
- const stackY = this.ypos || 0;
340
- const s = (typeof this.scale === 'number' && this.scale > 0) ? this.scale : 1;
341
-
342
- for (const entry of this._overlayChildren) {
343
- if (!entry || !entry.child) continue;
344
- const child = entry.child;
345
- const o = entry.opts || {};
346
- const anchor = o.anchor || 'toolbar-center';
347
- const offsetX = o.offsetX || 0;
348
- const offsetY = o.offsetY || 0;
349
- const pad = (typeof o.padding === 'number') ? o.padding : padding;
350
- const counterScale = (typeof o.counterScale === 'boolean') ? o.counterScale : true;
351
- const customCoords = o.customCoords || null;
352
-
353
- // Compute container anchor coords (duplicated logic from addOverlayChild)
354
- let containerX = 0;
355
- let containerY = 0;
356
- if (anchor === 'custom' && customCoords && typeof customCoords.x === 'number' && typeof customCoords.y === 'number') {
357
- containerX = Math.round(customCoords.x + offsetX);
358
- containerY = Math.round(customCoords.y + offsetY);
359
- } else if (anchor.startsWith('toolbar')) {
360
- if (!this.toolbar) continue;
361
- const tbW = this.toolbar.elements?.background?.width || 0;
362
- const tbH = this.toolbar.elements?.background?.height || 0;
363
- const left = (containerWidth - tbW) / 2;
364
- const right = left + tbW;
365
- const center = left + (tbW / 2);
366
- containerY = Math.round(containerHeight - tbH - pad + offsetY);
367
- if (anchor === 'toolbar-center') containerX = Math.round(center + offsetX);
368
- else if (anchor === 'toolbar-left') containerX = Math.round(left + offsetX);
369
- else if (anchor === 'toolbar-right') containerX = Math.round(right + offsetX);
370
- else containerX = Math.round(center + offsetX);
371
- } else if (anchor.startsWith('top')) {
372
- const topY = Math.round(pad);
373
- const leftX = Math.round(pad);
374
- const rightX = Math.round(containerWidth - pad);
375
- containerY = topY + offsetY;
376
- if (anchor === 'top-left') containerX = leftX + offsetX;
377
- else if (anchor === 'top-center') containerX = Math.round(containerWidth / 2) + offsetX;
378
- else if (anchor === 'top-right') containerX = rightX + offsetX;
379
- else containerX = leftX + offsetX;
380
- } else {
381
- containerX = Math.round(containerWidth / 2 + offsetX);
382
- containerY = Math.round(containerHeight / 2 + offsetY);
383
- }
384
-
385
- // Convert to stack-local coordinates
386
- const x = (containerX - stackX) / s;
387
- const y = (containerY - stackY) / s;
388
-
389
- // Apply counter-scaling and position
390
- if (counterScale && child && typeof child.setScale === 'function') {
391
- try { child.setScale(1 / s); } catch (_) {}
392
- }
393
- if (child && typeof child.setPosition === 'function') {
394
- try { child.setPosition(x, y); } catch (_) {}
395
- }
396
- }
397
- }
398
-
399
- /**
400
- * Remove a previously added overlay child (if present).
401
- */
402
- removeOverlayChild(child) {
403
- if (!child || !Array.isArray(this._overlayChildren)) return false;
404
- let idx = -1;
405
- for (let i = 0; i < this._overlayChildren.length; i++) {
406
- if (this._overlayChildren[i].child === child) { idx = i; break; }
407
- }
408
- if (idx === -1) return false;
409
- this._overlayChildren.splice(idx, 1);
410
- try { this.removeChild(child); } catch (_) {}
411
- return true;
412
- }
413
-
414
- /**
415
- * Returns the toolbar instance, if one was created.
416
- * @returns {omdToolbar|undefined}
417
- */
418
- getToolbar() {
419
- return this.toolbar;
420
- }
421
-
422
- /**
423
- * Undo the last operation (remove bottom-most equation and its preceding operation display)
424
- * Also updates a step visualizer if present.
425
- * @returns {boolean} Whether an operation was undone
426
- */
427
- undoLastOperation() {
428
- const seq = this.sequence;
429
- if (!seq || !Array.isArray(seq.steps) || seq.steps.length === 0) return false;
430
-
431
- // Find bottom-most equation
432
- let eqIndex = -1;
433
- for (let i = seq.steps.length - 1; i >= 0; i--) {
434
- const st = seq.steps[i];
435
- const name = st?.constructor?.name;
436
- if (st instanceof omdEquationNode || name === 'omdEquationNode') { eqIndex = i; break; }
437
- }
438
- if (eqIndex === -1) return false;
439
-
440
- // Find nearest preceding operation display (if any)
441
- let startIndex = eqIndex;
442
- for (let i = eqIndex; i >= 0; i--) {
443
- const st = seq.steps[i];
444
- const name = st?.constructor?.name;
445
- if (st instanceof omdOperationDisplayNode || name === 'omdOperationDisplayNode') { startIndex = i; break; }
446
- }
447
- // Remove DOM children and steps from startIndex to end
448
- for (let i = seq.steps.length - 1; i >= startIndex; i--) {
449
- const step = seq.steps[i];
450
- try { seq.removeChild(step); } catch (_) {}
451
- }
452
- seq.steps.splice(startIndex);
453
- seq.argumentNodeList.steps = seq.steps;
454
- if (Array.isArray(seq.stepDescriptions)) seq.stepDescriptions.length = seq.steps.length;
455
- if (Array.isArray(seq.importanceLevels)) seq.importanceLevels.length = seq.steps.length;
456
-
457
- // Adjust current index
458
- if (typeof seq.currentStepIndex === 'number' && seq.currentStepIndex >= seq.steps.length) {
459
- seq.currentStepIndex = Math.max(0, seq.steps.length - 1);
460
- }
461
-
462
- // Rebuild maps and layout on sequence
463
- if (typeof seq.rebuildNodeMap === 'function') seq.rebuildNodeMap();
464
- if (typeof seq.computeDimensions === 'function') seq.computeDimensions();
465
- if (typeof seq.updateLayout === 'function') seq.updateLayout();
466
-
467
- // If this is a step visualizer, rebuild its dots/lines
468
- if (typeof seq.rebuildVisualizer === 'function') {
469
- try {
470
- // Clear all step visualizer highlights before rebuilding
471
- if (seq.highlighting && typeof seq.highlighting.clearAllExplainHighlights === 'function') {
472
- seq.highlighting.clearAllExplainHighlights();
473
- }
474
- seq.rebuildVisualizer();
475
- } catch (_) {}
476
- } else if (typeof seq._initializeVisualElements === 'function') {
477
- try {
478
- // Clear all step visualizer highlights before rebuilding
479
- if (seq.highlighting && typeof seq.highlighting.clearAllExplainHighlights === 'function') {
480
- seq.highlighting.clearAllExplainHighlights();
481
- }
482
- seq._initializeVisualElements();
483
- if (typeof seq.computeDimensions === 'function') seq.computeDimensions();
484
- if (typeof seq.updateLayout === 'function') seq.updateLayout();
485
- } catch (_) {}
486
- }
487
-
488
- // Safety: ensure dot/line counts match equations and prune orphan dots
489
- try {
490
- const isEquation = (s) => (s instanceof omdEquationNode) || (s?.constructor?.name === 'omdEquationNode');
491
- const equationsCount = Array.isArray(seq.steps) ? seq.steps.filter(isEquation).length : 0;
492
-
493
- // Remove dots whose equationRef is no longer present in steps
494
- if (Array.isArray(seq.stepDots) && seq.visualContainer) {
495
- const eqSet = new Set(seq.steps.filter(isEquation));
496
- const keptDots = [];
497
- for (const dot of seq.stepDots) {
498
- if (!dot || !dot.equationRef || !eqSet.has(dot.equationRef)) {
499
- try { seq.visualContainer.removeChild(dot); } catch (_) {}
500
- } else {
501
- keptDots.push(dot);
502
- }
503
- }
504
- seq.stepDots = keptDots;
505
- }
506
- // Also purge any children in visualContainer that are not current dots or lines
507
- if (seq.visualContainer && Array.isArray(seq.visualContainer.childList)) {
508
- const valid = new Set([...(seq.stepDots||[]), ...(seq.stepLines||[])]);
509
- const toRemove = [];
510
- seq.visualContainer.childList.forEach(child => { if (!valid.has(child)) toRemove.push(child); });
511
- toRemove.forEach(child => { try { seq.visualContainer.removeChild(child); } catch (_) {} });
512
- }
513
- if (Array.isArray(seq.stepDots) && seq.visualContainer) {
514
- while (seq.stepDots.length > equationsCount) {
515
- const dot = seq.stepDots.pop();
516
- try { seq.visualContainer.removeChild(dot); } catch (_) {}
517
- }
518
- }
519
- if (Array.isArray(seq.stepLines) && seq.visualContainer) {
520
- const targetLines = Math.max(0, equationsCount - 1);
521
- while (seq.stepLines.length > targetLines) {
522
- const line = seq.stepLines.pop();
523
- try { seq.visualContainer.removeChild(line); } catch (_) {}
524
- }
525
- }
526
- if (seq.layoutManager) {
527
- try {
528
- seq.layoutManager.updateVisualLayout(true); // Allow repositioning for equation stack changes
529
- seq.layoutManager.updateVisualVisibility();
530
- seq.layoutManager.updateAllLinePositions();
531
- } catch (_) {}
532
- }
533
- } catch (_) {}
534
-
535
- // Refresh stack layout
536
- this.updateLayout();
537
- return true;
538
- }
539
-
540
- /**
541
- * Returns the SVG element for the entire equation stack.
542
- * @returns {SVGElement} The SVG element representing the equation stack.
543
- */
544
- getSvg() {
545
- return this.svgObject;
546
- }
547
- }
1
+ import { omdEquationSequenceNode } from '../nodes/omdEquationSequenceNode.js';
2
+ import { omdStepVisualizer } from '../step-visualizer/omdStepVisualizer.js';
3
+ import { omdToolbar } from '../display/omdToolbar.js';
4
+ import { jsvgGroup, jsvgLayoutGroup } from '@teachinglab/jsvg';
5
+ import { omdEquationNode } from '../nodes/omdEquationNode.js';
6
+ import { omdOperationDisplayNode } from '../nodes/omdOperationDisplayNode.js';
7
+
8
+ /**
9
+ * A renderable component that bundles a sequence and optional UI controls.
10
+ * It acts as a node that can be rendered by an omdDisplay.
11
+ * @extends jsvgGroup
12
+ */
13
+ export class omdEquationStack extends jsvgGroup {
14
+ /**
15
+ * @param {Array<omdNode>} [steps=[]] - An initial array of equation steps.
16
+ * @param {Object} [options={}] - Configuration options.
17
+ * @param {boolean} [options.toolbar=false] - If true, creates a toolbar-driven sequence.
18
+ * @param {boolean} [options.stepVisualizer=false] - If true, creates a sequence with a step visualizer.
19
+ */
20
+ constructor(steps = [], options = {}) {
21
+ super();
22
+ this.options = { ...options };
23
+
24
+ // Normalize new structured options
25
+ this.toolbarOptions = null;
26
+ if (typeof options.toolbar === 'object') {
27
+ this.toolbarOptions = { enabled: true, ...options.toolbar };
28
+ } else if (options.toolbar === true) {
29
+ this.toolbarOptions = { enabled: true };
30
+ } else if (options.toolbar === false) {
31
+ this.toolbarOptions = { enabled: false };
32
+ }
33
+ this.stylingOptions = options.styling || null;
34
+
35
+ // The sequence is the core. If a visualizer is needed, that's our sequence.
36
+ if (options.stepVisualizer) {
37
+ // Pass through step visualizer styling options
38
+ const stepVisualizerStyling = this.stylingOptions?.stepVisualizer || {};
39
+ this.sequence = new omdStepVisualizer(steps, stepVisualizerStyling);
40
+ } else {
41
+ this.sequence = new omdEquationSequenceNode(steps);
42
+ }
43
+
44
+ // Apply equation background styling if provided
45
+ if (this.stylingOptions?.equationBackground) {
46
+ this.sequence.setDefaultEquationBackground(this.stylingOptions.equationBackground);
47
+ }
48
+
49
+ // Apply step visualizer background styling if provided
50
+ if (options.stepVisualizer && this.stylingOptions?.stepVisualizerBackground) {
51
+ if (typeof this.sequence.setBackgroundStyle === 'function') {
52
+ this.sequence.setBackgroundStyle(this.stylingOptions.stepVisualizerBackground);
53
+ }
54
+ }
55
+
56
+ // If a toolbar is needed, create it.
57
+ if (this.toolbarOptions?.enabled) {
58
+ // Default undo: call global hook if provided
59
+ const toolbarOpts = { ...this.toolbarOptions };
60
+ if (toolbarOpts.showUndoButton && !toolbarOpts.onUndo) {
61
+ toolbarOpts.onUndo = () => {
62
+ if (typeof window !== 'undefined' && typeof window.onOMDToolbarUndo === 'function') {
63
+ try { window.onOMDToolbarUndo(this.sequence); } catch (_) {}
64
+ }
65
+ };
66
+ }
67
+ this.toolbar = new omdToolbar(this, this.sequence, toolbarOpts);
68
+ }
69
+
70
+ // Overlay padding (distance from bottom when overlayed)
71
+ this.overlayPadding = typeof this.toolbarOptions?.overlayPadding === 'number'
72
+ ? this.toolbarOptions.overlayPadding
73
+ : 34; // Default a bit above the very bottom to match buttons
74
+
75
+ // Create a vertical layout group to hold the sequence and toolbar
76
+ this.layoutGroup = new jsvgLayoutGroup();
77
+ this.layoutGroup.setSpacer(16); // Adjust as needed for spacing
78
+ this.layoutGroup.addChild(this.sequence);
79
+ this._overlayChildren = [];
80
+
81
+ // Handle toolbar positioning
82
+ const position = this.toolbarOptions?.position || this.options.toolbarPosition; // backward compat
83
+ const overlayBottom = position === 'bottom' || position === 'overlay-bottom';
84
+
85
+ if (this.toolbar) {
86
+ if (overlayBottom) {
87
+ // For overlay positioning, add toolbar directly to this (not layoutGroup)
88
+ this.addChild(this.toolbar.elements.toolbarGroup);
89
+ } else {
90
+ // For in-flow positioning, add to layout group
91
+ this.layoutGroup.addChild(this.toolbar.elements.toolbarGroup);
92
+ }
93
+ }
94
+
95
+ this.addChild(this.layoutGroup);
96
+ this.updateLayout();
97
+ }
98
+
99
+ /**
100
+ * Updates the layout and positioning of internal components.
101
+ */
102
+ updateLayout() {
103
+ this.sequence.updateLayout();
104
+ this.layoutGroup.doVerticalLayout();
105
+
106
+ // Handle toolbar positioning based on overlay flag
107
+ const position = this.toolbarOptions?.position || this.options.toolbarPosition; // backward compat
108
+ const overlayBottom = position === 'bottom' || position === 'overlay-bottom';
109
+
110
+ if (this.toolbar && !overlayBottom) {
111
+ // Center the toolbar under the stack if in-flow and their widths differ
112
+ const stackWidth = this.sequence.width;
113
+ const toolbarWidth = this.toolbar.elements.background.width;
114
+ const toolbarGroup = this.toolbar.elements.toolbarGroup;
115
+ // Center toolbar horizontally under the stack
116
+ toolbarGroup.setPosition(
117
+ (stackWidth - toolbarWidth) / 2,
118
+ toolbarGroup.ypos // y is handled by layout group
119
+ );
120
+ }
121
+
122
+ this.width = this.layoutGroup.width;
123
+ this.height = this.layoutGroup.height;
124
+ }
125
+
126
+ /**
127
+ * Initializes the stack and its underlying sequence.
128
+ */
129
+ initialize() {
130
+ if (this.sequence && typeof this.sequence.initialize === 'function') {
131
+ this.sequence.initialize();
132
+ } else if (this.sequence) {
133
+ if (typeof this.sequence.computeDimensions === 'function') {
134
+ this.sequence.computeDimensions();
135
+ }
136
+ if (typeof this.sequence.updateLayout === 'function') {
137
+ this.sequence.updateLayout();
138
+ }
139
+ }
140
+ this.updateLayout();
141
+ }
142
+
143
+ /**
144
+ * Propagates font size changes to the underlying sequence and recomputes layout.
145
+ * @param {number} fontSize
146
+ */
147
+ setFontSize(fontSize) {
148
+ if (this.sequence && typeof this.sequence.setFontSize === 'function') {
149
+ this.sequence.setFontSize(fontSize);
150
+ }
151
+ this.updateLayout();
152
+ }
153
+
154
+ /**
155
+ * Delegate to close the currently active step visualizer dot (if present).
156
+ */
157
+ closeActiveDot() {
158
+ if (this.sequence && typeof this.sequence.closeActiveDot === 'function') {
159
+ this.sequence.closeActiveDot();
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Delegate to close all step visualizer text boxes (if present).
165
+ */
166
+ closeAllTextBoxes() {
167
+ if (this.sequence && typeof this.sequence.closeAllTextBoxes === 'function') {
168
+ this.sequence.closeAllTextBoxes();
169
+ } else if (this.sequence && typeof this.sequence.closeActiveDot === 'function') {
170
+ this.sequence.closeActiveDot();
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Delegate to force close all step visualizer UI (if present).
176
+ */
177
+ forceCloseAll() {
178
+ if (this.sequence && typeof this.sequence.forceCloseAll === 'function') {
179
+ this.sequence.forceCloseAll();
180
+ } else {
181
+ this.closeAllTextBoxes();
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Returns the underlying sequence instance.
187
+ * @returns {omdEquationSequenceNode|omdStepVisualizer} The managed sequence instance.
188
+ */
189
+ getSequence() {
190
+ return this.sequence;
191
+ }
192
+
193
+ /**
194
+ * Expose overlay padding to the display so it can pass it during reposition
195
+ */
196
+ getOverlayPadding() {
197
+ return this.overlayPadding;
198
+ }
199
+
200
+ /**
201
+ * Returns the visual height in pixels of the toolbar background (unscaled), if present.
202
+ * Useful for reserving space when overlaying the toolbar.
203
+ */
204
+ getToolbarVisualHeight() {
205
+ if (this.toolbar && this.toolbar.elements && this.toolbar.elements.background) {
206
+ return this.toolbar.elements.background.height || 0;
207
+ }
208
+ return 0;
209
+ }
210
+
211
+ /**
212
+ * Whether the toolbar is configured to be overlayed at the bottom of the container
213
+ * @returns {boolean}
214
+ */
215
+ isToolbarOverlay() {
216
+ const position = this.toolbarOptions?.position || this.options.toolbarPosition; // backward compat
217
+ return !!(this.toolbar && (position === 'bottom' || position === 'overlay-bottom'));
218
+ }
219
+
220
+ /**
221
+ * Positions the toolbar overlay at the bottom center of the container
222
+ * @param {number} containerWidth - Width of the container
223
+ * @param {number} containerHeight - Height of the container
224
+ * @param {number} [padding=16] - Padding from the bottom edge
225
+ */
226
+ positionToolbarOverlay(containerWidth, containerHeight, padding = 16) {
227
+ if (!this.toolbar || !this.isToolbarOverlay()) return;
228
+
229
+ const toolbarGroup = this.toolbar.elements.toolbarGroup;
230
+ const toolbarWidth = this.toolbar.elements.background.width;
231
+ const toolbarHeight = this.toolbar.elements.background.height;
232
+
233
+ // Position at bottom center of the DISPLAY (container) while this toolbar
234
+ // lives inside the stack's local coordinate system, which may be scaled.
235
+ // Convert container (global) coordinates to stack-local by subtracting
236
+ // the stack's position and dividing by its scale.
237
+ const stackX = this.xpos || 0;
238
+ const stackY = this.ypos || 0;
239
+ const s = (typeof this.scale === 'number' && this.scale > 0) ? this.scale : 1;
240
+ const effectivePadding = (typeof padding === 'number') ? padding : this.overlayPadding;
241
+
242
+ // Compute top-left of toolbar in container coordinates using UN-SCALED toolbar size
243
+ // because we counter-scale the toolbar by 1/s to keep constant on-screen size.
244
+ let containerX = (containerWidth - toolbarWidth) / 2;
245
+ let containerY = containerHeight - toolbarHeight - effectivePadding;
246
+ // Snap to integer pixels to avoid subpixel jitter when scaling
247
+ containerX = Math.round(containerX);
248
+ containerY = Math.round(containerY);
249
+
250
+ // Convert to stack-local coordinates
251
+ const x = (containerX - stackX) / s;
252
+ const y = (containerY - stackY) / s;
253
+
254
+ // Find the root SVG to check its viewBox
255
+ let rootSVG = toolbarGroup.svgObject;
256
+ while (rootSVG && rootSVG.tagName !== 'svg' && rootSVG.parentElement) {
257
+ rootSVG = rootSVG.parentElement;
258
+ }
259
+ const svgViewBox = rootSVG?.getAttribute?.('viewBox') || 'unknown';
260
+
261
+
262
+ // Counter-scale the toolbar so it remains a constant on-screen size
263
+ if (typeof toolbarGroup.setScale === 'function') {
264
+ toolbarGroup.setScale(1 / s);
265
+ }
266
+ toolbarGroup.setPosition(x, y);
267
+
268
+ // Ensure toolbar is visible and on top
269
+ if (toolbarGroup.svgObject) {
270
+ toolbarGroup.svgObject.style.display = 'block';
271
+ toolbarGroup.svgObject.style.zIndex = '1000';
272
+ }
273
+
274
+ // Update any overlay children so they remain locked to container anchors
275
+ try {
276
+ this.updateOverlayChildren(containerWidth, containerHeight, padding);
277
+ } catch (_) {}
278
+ }
279
+ /**
280
+ * General helper to position an overlay child relative to a chosen anchor.
281
+ * Does not assume only the toolbar; supports various anchors and options.
282
+ * @param {object} child - A jsvg node (or any object with setPosition/setScale)
283
+ * @param {number} containerWidth - Width of the container (px)
284
+ * @param {number} containerHeight - Height of the container (px)
285
+ * @param {object} [opts] - Options
286
+ * @param {string} [opts.anchor='toolbar-center'] - One of: 'toolbar-center','toolbar-left','toolbar-right','top-left','top-center','top-right','custom'
287
+ * @param {number} [opts.offsetX=0] - Horizontal offset in screen pixels (positive -> right)
288
+ * @param {number} [opts.offsetY=0] - Vertical offset in screen pixels (positive -> down)
289
+ * @param {number} [opts.padding=16] - Padding from edges when computing anchor
290
+ * @param {boolean} [opts.counterScale=true] - Whether to counter-scale the child to keep constant on-screen size
291
+ * @param {boolean} [opts.addToStack=true] - Whether to add the child to this stack's children (default true)
292
+ * @param {{x:number,y:number}|null} [opts.customCoords=null] - If anchor==='custom', use these screen coords
293
+ * @returns {object|null} The child or null if not applicable
294
+ */
295
+ addOverlayChild(child, containerWidth, containerHeight, opts = {}) {
296
+ const {
297
+ anchor = 'toolbar-center',
298
+ offsetX = 0,
299
+ offsetY = 0,
300
+ padding = 16,
301
+ counterScale = true,
302
+ addToStack = true,
303
+ customCoords = null
304
+ } = opts || {};
305
+
306
+ // Basic validation
307
+ if (!child || typeof containerWidth !== 'number' || typeof containerHeight !== 'number') return null;
308
+
309
+ const stackX = this.xpos || 0;
310
+ const stackY = this.ypos || 0;
311
+ const s = (typeof this.scale === 'number' && this.scale > 0) ? this.scale : 1;
312
+
313
+ // Determine base container (screen) coordinates for the anchor
314
+ let containerX = 0;
315
+ let containerY = 0;
316
+
317
+ if (anchor === 'custom' && customCoords && typeof customCoords.x === 'number' && typeof customCoords.y === 'number') {
318
+ containerX = Math.round(customCoords.x);
319
+ containerY = Math.round(customCoords.y);
320
+ } else if (anchor.startsWith('toolbar')) {
321
+ if (!this.toolbar) return null;
322
+ const tbW = this.toolbar.elements?.background?.width || 0;
323
+ const tbH = this.toolbar.elements?.background?.height || 0;
324
+ const left = (containerWidth - tbW) / 2;
325
+ const right = left + tbW;
326
+ const center = left + (tbW / 2);
327
+ containerY = Math.round(containerHeight - tbH - (typeof padding === 'number' ? padding : this.overlayPadding));
328
+ if (anchor === 'toolbar-center') containerX = Math.round(center);
329
+ else if (anchor === 'toolbar-left') containerX = Math.round(left);
330
+ else if (anchor === 'toolbar-right') containerX = Math.round(right);
331
+ else containerX = Math.round(center);
332
+ } else if (anchor.startsWith('top')) {
333
+ const topY = Math.round(typeof padding === 'number' ? padding : 16);
334
+ const leftX = Math.round(typeof padding === 'number' ? padding : 16);
335
+ const rightX = Math.round(containerWidth - (typeof padding === 'number' ? padding : 16));
336
+ containerY = topY;
337
+ if (anchor === 'top-left') containerX = leftX;
338
+ else if (anchor === 'top-center') containerX = Math.round(containerWidth / 2);
339
+ else if (anchor === 'top-right') containerX = rightX;
340
+ else containerX = leftX;
341
+ } else {
342
+ // fallback: center
343
+ containerX = Math.round(containerWidth / 2);
344
+ containerY = Math.round(containerHeight / 2);
345
+ }
346
+
347
+ // Apply offsets (in screen pixels)
348
+ containerX = Math.round(containerX + (offsetX || 0));
349
+ containerY = Math.round(containerY + (offsetY || 0));
350
+
351
+ // Convert to stack-local coordinates
352
+ const x = (containerX - stackX) / s;
353
+ const y = (containerY - stackY) / s;
354
+
355
+ // Optionally counter-scale child to keep constant on-screen size
356
+ if (counterScale && child && typeof child.setScale === 'function') {
357
+ try { child.setScale(1 / s); } catch (_) {}
358
+ }
359
+
360
+ // Position child in stack-local coords
361
+ if (child && typeof child.setPosition === 'function') {
362
+ try { child.setPosition(x, y); } catch (_) {}
363
+ }
364
+
365
+ // Optionally add to this stack
366
+ if (addToStack) {
367
+ try { this.addChild(child); } catch (_) {
368
+ try { this.layoutGroup.addChild(child); } catch (_) {}
369
+ }
370
+ }
371
+
372
+ // Remember the overlay child and its options so we can reposition it when
373
+ // the stack's scale/position changes (e.g., during zoom/center operations).
374
+ try {
375
+ // Store a shallow copy of opts to avoid external mutation surprises
376
+ const stored = { anchor, offsetX, offsetY, padding, counterScale, addToStack, customCoords };
377
+ this._overlayChildren.push({ child, opts: stored });
378
+ } catch (_) {}
379
+
380
+ // Make sure it's visible and above toolbar
381
+ if (child && child.svgObject) {
382
+ try { child.svgObject.style.zIndex = '1001'; } catch (_) {}
383
+ try { child.svgObject.style.display = 'block'; } catch (_) {}
384
+ }
385
+
386
+ return child;
387
+ }
388
+
389
+ /**
390
+ * Recompute and apply positions for tracked overlay children.
391
+ * Called automatically during `positionToolbarOverlay` and can be called
392
+ * manually if you change container size/stack position outside normal flows.
393
+ */
394
+ updateOverlayChildren(containerWidth, containerHeight, padding = 16) {
395
+ if (!Array.isArray(this._overlayChildren) || this._overlayChildren.length === 0) return;
396
+
397
+ const stackX = this.xpos || 0;
398
+ const stackY = this.ypos || 0;
399
+ const s = (typeof this.scale === 'number' && this.scale > 0) ? this.scale : 1;
400
+
401
+ for (const entry of this._overlayChildren) {
402
+ if (!entry || !entry.child) continue;
403
+ const child = entry.child;
404
+ const o = entry.opts || {};
405
+ const anchor = o.anchor || 'toolbar-center';
406
+ const offsetX = o.offsetX || 0;
407
+ const offsetY = o.offsetY || 0;
408
+ const pad = (typeof o.padding === 'number') ? o.padding : padding;
409
+ const counterScale = (typeof o.counterScale === 'boolean') ? o.counterScale : true;
410
+ const customCoords = o.customCoords || null;
411
+
412
+ // Compute container anchor coords (duplicated logic from addOverlayChild)
413
+ let containerX = 0;
414
+ let containerY = 0;
415
+ if (anchor === 'custom' && customCoords && typeof customCoords.x === 'number' && typeof customCoords.y === 'number') {
416
+ containerX = Math.round(customCoords.x + offsetX);
417
+ containerY = Math.round(customCoords.y + offsetY);
418
+ } else if (anchor.startsWith('toolbar')) {
419
+ if (!this.toolbar) continue;
420
+ const tbW = this.toolbar.elements?.background?.width || 0;
421
+ const tbH = this.toolbar.elements?.background?.height || 0;
422
+ const left = (containerWidth - tbW) / 2;
423
+ const right = left + tbW;
424
+ const center = left + (tbW / 2);
425
+ containerY = Math.round(containerHeight - tbH - pad + offsetY);
426
+ if (anchor === 'toolbar-center') containerX = Math.round(center + offsetX);
427
+ else if (anchor === 'toolbar-left') containerX = Math.round(left + offsetX);
428
+ else if (anchor === 'toolbar-right') containerX = Math.round(right + offsetX);
429
+ else containerX = Math.round(center + offsetX);
430
+ } else if (anchor.startsWith('top')) {
431
+ const topY = Math.round(pad);
432
+ const leftX = Math.round(pad);
433
+ const rightX = Math.round(containerWidth - pad);
434
+ containerY = topY + offsetY;
435
+ if (anchor === 'top-left') containerX = leftX + offsetX;
436
+ else if (anchor === 'top-center') containerX = Math.round(containerWidth / 2) + offsetX;
437
+ else if (anchor === 'top-right') containerX = rightX + offsetX;
438
+ else containerX = leftX + offsetX;
439
+ } else {
440
+ containerX = Math.round(containerWidth / 2 + offsetX);
441
+ containerY = Math.round(containerHeight / 2 + offsetY);
442
+ }
443
+
444
+ // Convert to stack-local coordinates
445
+ const x = (containerX - stackX) / s;
446
+ const y = (containerY - stackY) / s;
447
+
448
+ // Apply counter-scaling and position
449
+ if (counterScale && child && typeof child.setScale === 'function') {
450
+ try { child.setScale(1 / s); } catch (_) {}
451
+ }
452
+ if (child && typeof child.setPosition === 'function') {
453
+ try { child.setPosition(x, y); } catch (_) {}
454
+ }
455
+ }
456
+ }
457
+
458
+ /**
459
+ * Remove a previously added overlay child (if present).
460
+ */
461
+ removeOverlayChild(child) {
462
+ if (!child || !Array.isArray(this._overlayChildren)) return false;
463
+ let idx = -1;
464
+ for (let i = 0; i < this._overlayChildren.length; i++) {
465
+ if (this._overlayChildren[i].child === child) { idx = i; break; }
466
+ }
467
+ if (idx === -1) return false;
468
+ this._overlayChildren.splice(idx, 1);
469
+ try { this.removeChild(child); } catch (_) {}
470
+ return true;
471
+ }
472
+
473
+ /**
474
+ * Returns the toolbar instance, if one was created.
475
+ * @returns {omdToolbar|undefined}
476
+ */
477
+ getToolbar() {
478
+ return this.toolbar;
479
+ }
480
+
481
+ /**
482
+ * Undo the last operation (remove bottom-most equation and its preceding operation display)
483
+ * Also updates a step visualizer if present.
484
+ * @returns {boolean} Whether an operation was undone
485
+ */
486
+ undoLastOperation() {
487
+ const seq = this.sequence;
488
+ if (!seq || !Array.isArray(seq.steps) || seq.steps.length === 0) return false;
489
+
490
+ // Find bottom-most equation
491
+ let eqIndex = -1;
492
+ for (let i = seq.steps.length - 1; i >= 0; i--) {
493
+ const st = seq.steps[i];
494
+ const name = st?.constructor?.name;
495
+ if (st instanceof omdEquationNode || name === 'omdEquationNode') { eqIndex = i; break; }
496
+ }
497
+ if (eqIndex === -1) return false;
498
+
499
+ // Find nearest preceding operation display (if any)
500
+ let startIndex = eqIndex;
501
+ for (let i = eqIndex; i >= 0; i--) {
502
+ const st = seq.steps[i];
503
+ const name = st?.constructor?.name;
504
+ if (st instanceof omdOperationDisplayNode || name === 'omdOperationDisplayNode') { startIndex = i; break; }
505
+ }
506
+ // Remove DOM children and steps from startIndex to end
507
+ for (let i = seq.steps.length - 1; i >= startIndex; i--) {
508
+ const step = seq.steps[i];
509
+ try { seq.removeChild(step); } catch (_) {}
510
+ }
511
+ seq.steps.splice(startIndex);
512
+ seq.argumentNodeList.steps = seq.steps;
513
+ if (Array.isArray(seq.stepDescriptions)) seq.stepDescriptions.length = seq.steps.length;
514
+ if (Array.isArray(seq.importanceLevels)) seq.importanceLevels.length = seq.steps.length;
515
+
516
+ // Adjust current index
517
+ if (typeof seq.currentStepIndex === 'number' && seq.currentStepIndex >= seq.steps.length) {
518
+ seq.currentStepIndex = Math.max(0, seq.steps.length - 1);
519
+ }
520
+
521
+ // Rebuild maps and layout on sequence
522
+ if (typeof seq.rebuildNodeMap === 'function') seq.rebuildNodeMap();
523
+ if (typeof seq.computeDimensions === 'function') seq.computeDimensions();
524
+ if (typeof seq.updateLayout === 'function') seq.updateLayout();
525
+
526
+ // If this is a step visualizer, rebuild its dots/lines
527
+ if (typeof seq.rebuildVisualizer === 'function') {
528
+ try {
529
+ // Clear all step visualizer highlights before rebuilding
530
+ if (seq.highlighting && typeof seq.highlighting.clearAllExplainHighlights === 'function') {
531
+ seq.highlighting.clearAllExplainHighlights();
532
+ }
533
+ seq.rebuildVisualizer();
534
+ } catch (_) {}
535
+ } else if (typeof seq._initializeVisualElements === 'function') {
536
+ try {
537
+ // Clear all step visualizer highlights before rebuilding
538
+ if (seq.highlighting && typeof seq.highlighting.clearAllExplainHighlights === 'function') {
539
+ seq.highlighting.clearAllExplainHighlights();
540
+ }
541
+ seq._initializeVisualElements();
542
+ if (typeof seq.computeDimensions === 'function') seq.computeDimensions();
543
+ if (typeof seq.updateLayout === 'function') seq.updateLayout();
544
+ } catch (_) {}
545
+ }
546
+
547
+ // Safety: ensure dot/line counts match equations and prune orphan dots
548
+ try {
549
+ const isEquation = (s) => (s instanceof omdEquationNode) || (s?.constructor?.name === 'omdEquationNode');
550
+ const equationsCount = Array.isArray(seq.steps) ? seq.steps.filter(isEquation).length : 0;
551
+
552
+ // Remove dots whose equationRef is no longer present in steps
553
+ if (Array.isArray(seq.stepDots) && seq.visualContainer) {
554
+ const eqSet = new Set(seq.steps.filter(isEquation));
555
+ const keptDots = [];
556
+ for (const dot of seq.stepDots) {
557
+ if (!dot || !dot.equationRef || !eqSet.has(dot.equationRef)) {
558
+ try { seq.visualContainer.removeChild(dot); } catch (_) {}
559
+ } else {
560
+ keptDots.push(dot);
561
+ }
562
+ }
563
+ seq.stepDots = keptDots;
564
+ }
565
+ // Also purge any children in visualContainer that are not current dots or lines
566
+ if (seq.visualContainer && Array.isArray(seq.visualContainer.childList)) {
567
+ const valid = new Set([...(seq.stepDots||[]), ...(seq.stepLines||[])]);
568
+ const toRemove = [];
569
+ seq.visualContainer.childList.forEach(child => { if (!valid.has(child)) toRemove.push(child); });
570
+ toRemove.forEach(child => { try { seq.visualContainer.removeChild(child); } catch (_) {} });
571
+ }
572
+ if (Array.isArray(seq.stepDots) && seq.visualContainer) {
573
+ while (seq.stepDots.length > equationsCount) {
574
+ const dot = seq.stepDots.pop();
575
+ try { seq.visualContainer.removeChild(dot); } catch (_) {}
576
+ }
577
+ }
578
+ if (Array.isArray(seq.stepLines) && seq.visualContainer) {
579
+ const targetLines = Math.max(0, equationsCount - 1);
580
+ while (seq.stepLines.length > targetLines) {
581
+ const line = seq.stepLines.pop();
582
+ try { seq.visualContainer.removeChild(line); } catch (_) {}
583
+ }
584
+ }
585
+ if (seq.layoutManager) {
586
+ try {
587
+ seq.layoutManager.updateVisualLayout(true); // Allow repositioning for equation stack changes
588
+ seq.layoutManager.updateVisualVisibility();
589
+ seq.layoutManager.updateAllLinePositions();
590
+ } catch (_) {}
591
+ }
592
+ } catch (_) {}
593
+
594
+ // Refresh stack layout
595
+ this.updateLayout();
596
+ return true;
597
+ }
598
+
599
+ /**
600
+ * Returns the SVG element for the entire equation stack.
601
+ * @returns {SVGElement} The SVG element representing the equation stack.
602
+ */
603
+ getSvg() {
604
+ return this.svgObject;
605
+ }
606
+ }