@teachinglab/omd 0.3.7 → 0.3.9

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.
package/src/omdProblem.js CHANGED
@@ -8,12 +8,11 @@ export class omdProblem extends jsvgGroup
8
8
  {
9
9
  // initialization
10
10
  super();
11
-
12
11
  this.type = "omdProblem";
13
12
  this.theText = "";
14
13
 
15
14
  this.problemText = new jsvgTextBox();
16
- this.problemText.setWidthAndHeight( 400,130 );
15
+ this.problemText.setWidthAndHeight( 250,30 );
17
16
  this.problemText.setText ( "this it the problem text" );
18
17
  this.problemText.setFontFamily( "Albert Sans" );
19
18
  this.problemText.setFontColor( "black" );
@@ -21,21 +20,193 @@ export class omdProblem extends jsvgGroup
21
20
  this.addChild( this.problemText );
22
21
  }
23
22
 
24
- loadFromJSON( data )
23
+ loadFromJSON( data, handleAIResponse = null )
25
24
  {
25
+ console.log(data)
26
26
  if ( typeof data.problemText != "undefined" )
27
27
  this.theText = data.problemText;
28
28
 
29
29
  if ( typeof data.visualization != "undefined" )
30
30
  {
31
- this.visualJSON = data.visualization;
31
+ console.log(data)
32
+ this.visualJSON = data.visualiation;
32
33
  console.log( this.visualJSON );
34
+ console.log('testing 1 ')
35
+
36
+ // // Fast-path: if the caller supplied an already-rendered SVG DOM element
37
+ // // (for example, captured from the canvas), use it directly instead of
38
+ // // trying to regenerate the graphic. This avoids constructing a temp
39
+ // // omd container and the related initialization issues.
40
+ if (data.svgElement) {
41
+ try {
42
+ // Ensure the problem text is set so measurement is accurate
43
+ this.problemText.setText(this.theText);
44
+
45
+ const padding = 10;
46
+ const SVG_NS = 'http://www.w3.org/2000/svg';
47
+
48
+ // utility: hidden measuring svg for getBBox when needed
49
+ function getMeasuringSVG() {
50
+ let m = document.getElementById('_omd_measuring_svg');
51
+ if (!m) {
52
+ m = document.createElementNS(SVG_NS, 'svg');
53
+ m.setAttribute('id', '_omd_measuring_svg');
54
+ m.style.position = 'absolute';
55
+ m.style.left = '-9999px';
56
+ m.style.top = '-9999px';
57
+ m.style.width = '1px';
58
+ m.style.height = '1px';
59
+ m.style.visibility = 'hidden';
60
+ document.body.appendChild(m);
61
+ }
62
+ return m;
63
+ }
64
+
65
+ const incoming = data.svgElement;
66
+ const cloneRoot = incoming.cloneNode(true);
67
+
68
+ // Attempt 1: find a clip rect inside (common pattern)
69
+ let crop = null; // {x,y,width,height}
70
+ try {
71
+ const rect = cloneRoot.querySelector && cloneRoot.querySelector('clipPath rect');
72
+ if (rect) {
73
+ const x = parseFloat(rect.getAttribute('x') || '0');
74
+ const y = parseFloat(rect.getAttribute('y') || '0');
75
+ const w = parseFloat(rect.getAttribute('width') || '0');
76
+ const h = parseFloat(rect.getAttribute('height') || '0');
77
+ if (w > 0 && h > 0) crop = { x, y, width: w, height: h };
78
+ }
79
+ } catch (e) { /* ignore */ }
80
+
81
+ // Attempt 2: viewBox on root or nested svg
82
+ if (!crop) {
83
+ try {
84
+ let vb = null;
85
+ if (cloneRoot.getAttribute) vb = cloneRoot.getAttribute('viewBox');
86
+ if (!vb) {
87
+ const nested = cloneRoot.querySelector && cloneRoot.querySelector('svg');
88
+ if (nested && nested.getAttribute) vb = nested.getAttribute('viewBox');
89
+ }
90
+ if (vb) {
91
+ const parts = vb.trim().split(/\s+/).map(Number);
92
+ if (parts.length === 4) crop = { x: parts[0], y: parts[1], width: parts[2], height: parts[3] };
93
+ }
94
+ } catch (e) { /* ignore */ }
95
+ }
96
+
97
+ // Attempt 3: measure bounding box by attaching to hidden SVG
98
+ if (!crop) {
99
+ const meas = getMeasuringSVG();
100
+ const wrapper = document.createElementNS(SVG_NS, 'g');
101
+ wrapper.appendChild(cloneRoot);
102
+ meas.appendChild(wrapper);
103
+ try {
104
+ const bb = wrapper.getBBox();
105
+ console.debug('omdProblem: measured bbox from wrapper', bb);
106
+ if (bb && bb.width > 0 && bb.height > 0) crop = { x: bb.x, y: bb.y, width: bb.width, height: bb.height };
107
+ } catch (e) {
108
+ // ignore
109
+ }
110
+ try { meas.removeChild(wrapper); } catch (_) {}
111
+ }
112
+
113
+
114
+ if (!crop) crop = { x: 0, y: 0, width: 250, height: 250 };
115
+
116
+ // Allow caller to request a small margin around the crop to avoid clipping
117
+ const cropMargin = (data && typeof data.cropMargin === 'number') ? data.cropMargin : 6;
118
+ // expand crop safely
119
+ const expandedCrop = {
120
+ x: Math.max(0, crop.x - cropMargin),
121
+ y: Math.max(0, crop.y - cropMargin),
122
+ width: crop.width + cropMargin * 2,
123
+ height: crop.height + cropMargin * 2
124
+ };
125
+ crop = expandedCrop;
126
+ console.debug('omdProblem: final crop chosen (expanded)', crop);
127
+
128
+ // Build compact svg sized to crop area
129
+ const compact = document.createElementNS(SVG_NS, 'svg');
130
+ compact.setAttribute('width', String(crop.width));
131
+ compact.setAttribute('height', String(crop.height));
132
+ compact.setAttribute('viewBox', `0 0 ${crop.width} ${crop.height}`);
133
+
134
+ const contentWrapper = document.createElementNS(SVG_NS, 'g');
135
+ // don't apply arbitrary offsets; translate content so crop.x/y maps to 0,0
136
+ contentWrapper.setAttribute('transform', `translate(-55, -80)`);
137
+ contentWrapper.appendChild(cloneRoot);
138
+ compact.appendChild(contentWrapper);
139
+
140
+ // Position compact svg under the problem text
141
+ let textBoxHeight = 0;
142
+ try {
143
+ if (this.problemText.height) textBoxHeight = this.problemText.height;
144
+ else if (this.problemText.svgObject && this.problemText.svgObject.getBBox) textBoxHeight = this.problemText.svgObject.getBBox().height;
145
+ else textBoxHeight = 30;
146
+ } catch (e) { textBoxHeight = 30; }
33
147
 
34
- var obj = window.theApp.handleAIResponse( this.visualJSON );
35
- obj.parent.removeChild( obj );
36
- this.addChild( obj );
37
- obj.setPosition( 0,150 );
38
- //obj.setPosition( obj.xpos, obj.ypos+120 );
148
+ // Center horizontally inside the problem box. Determine available width
149
+ // Caller can provide containerInfo to indicate the rounded-rect container dimensions
150
+ let containerWidth = 300;
151
+ let containerOffsetY = null;
152
+ let containerInnerPadding = 8;
153
+ try {
154
+ if (data && data.containerInfo) {
155
+ if (typeof data.containerInfo.width === 'number') containerWidth = data.containerInfo.width;
156
+ if (typeof data.containerInfo.offsetY === 'number') containerOffsetY = data.containerInfo.offsetY;
157
+ if (typeof data.containerInfo.innerPadding === 'number') containerInnerPadding = data.containerInfo.innerPadding;
158
+ } else if (this.width) containerWidth = this.width;
159
+ else if (this.problemText && this.problemText.width) containerWidth = Math.max(300, this.problemText.width);
160
+ } catch (e) { containerWidth = 300; }
161
+
162
+ const desiredY = Math.round((containerOffsetY !== null) ? (containerOffsetY + padding) : (textBoxHeight + padding));
163
+
164
+ // Ensure the compact SVG never extends outside the container: clamp and scale if needed
165
+ const innerPadding = containerInnerPadding; // keep some breathing room inside the rounded rectangle
166
+ const maxAllowedWidth = Math.max(20, containerWidth - innerPadding * 2);
167
+ let scale = 1;
168
+ if (crop.width > maxAllowedWidth) scale = maxAllowedWidth / crop.width;
169
+ const scaledWidth = Math.round(crop.width * scale);
170
+ const scaledHeight = Math.round(crop.height * scale);
171
+
172
+ // Apply scaled pixel dimensions to compact so it renders at the clamped size
173
+ compact.setAttribute('width', String(scaledWidth));
174
+ compact.setAttribute('height', String(scaledHeight));
175
+
176
+ // center: (containerWidth - scaledWidth) / 2, but don't go negative
177
+ let desiredX = Math.max(innerPadding, Math.round((containerWidth - scaledWidth) / 2));
178
+
179
+ console.debug('omdProblem: containerWidth, desiredX, desiredY', { containerWidth, desiredX, desiredY, cropWidth: crop.width, cropHeight: crop.height, scaledWidth, scaledHeight, scale });
180
+
181
+ const outerWrapper = document.createElementNS(SVG_NS, 'g');
182
+ outerWrapper.appendChild(compact);
183
+ outerWrapper.setAttribute('transform', `translate(${desiredX}, ${desiredY})`);
184
+ this.svgObject.appendChild(outerWrapper);
185
+
186
+ // Optional visual debug overlay: outlines the compact area if requested
187
+ if (data && data.debugPlacement) {
188
+ try {
189
+ const debugRect = document.createElementNS(SVG_NS, 'rect');
190
+ debugRect.setAttribute('x', '0');
191
+ debugRect.setAttribute('y', '0');
192
+ // debug rect shows the scaled layout area
193
+ debugRect.setAttribute('width', String(scaledWidth));
194
+ debugRect.setAttribute('height', String(scaledHeight));
195
+ debugRect.setAttribute('fill', 'none');
196
+ debugRect.setAttribute('stroke', 'rgba(255,0,0,0.9)');
197
+ debugRect.setAttribute('stroke-width', '2');
198
+ debugRect.setAttribute('pointer-events', 'none');
199
+ outerWrapper.appendChild(debugRect);
200
+ } catch (e) { console.warn('omdProblem: failed to add debugPlacement rect', e); }
201
+ }
202
+
203
+ this.updateLayout();
204
+ return;
205
+ } catch (e) {
206
+ console.warn('omdProblem: svgElement fast-path failed, falling back to regenerate:', e);
207
+ // fall through to regeneration attempt
208
+ }
209
+ }
39
210
  }
40
211
 
41
212
  this.updateLayout();
@@ -49,7 +220,41 @@ export class omdProblem extends jsvgGroup
49
220
 
50
221
  updateLayout()
51
222
  {
52
- this.problemText.setText ( this.theText );
53
- this.setWidthAndHeight( 300,200 );
223
+ // Update text content and size the problem container to fit the text and any child visualization
224
+ this.problemText.setText( this.theText );
225
+
226
+ // Measure the text box (use properties or fall back to getBBox)
227
+ let textBoxWidth = 400;
228
+ let textBoxHeight = 130;
229
+ try {
230
+ if (this.problemText.width) textBoxWidth = this.problemText.width;
231
+ if (this.problemText.height) textBoxHeight = this.problemText.height;
232
+ else if (this.problemText.svgObject && this.problemText.svgObject.getBBox) {
233
+ const bb = this.problemText.svgObject.getBBox();
234
+ if (bb.width) textBoxWidth = bb.width;
235
+ if (bb.height) textBoxHeight = bb.height;
236
+ }
237
+ } catch (e) {
238
+ // keep defaults
239
+ }
240
+
241
+ // Compute extra height from any visualization child we added
242
+ let extraHeight = 0;
243
+ try {
244
+ // Find a child that isn't the problemText (likely the visualization)
245
+ for (let i = 0; i < this.children.length; i++) {
246
+ const child = this.children[i];
247
+ if (child !== this.problemText && child && child.svgObject && child.svgObject.getBBox) {
248
+ const bb = child.svgObject.getBBox();
249
+ extraHeight = Math.max(extraHeight, bb.height + 20); // include padding
250
+ }
251
+ }
252
+ } catch (e) {
253
+ extraHeight = 0;
254
+ }
255
+
256
+ const totalWidth = Math.max(300, textBoxWidth);
257
+ const totalHeight = Math.max(200, textBoxHeight + extraHeight + 20);
258
+ this.setWidthAndHeight( totalWidth, totalHeight );
54
259
  }
55
260
  }
package/src/omdString.js CHANGED
@@ -9,7 +9,7 @@ export class omdString extends omdMetaExpression
9
9
  // initialization
10
10
  super();
11
11
 
12
- this.type = "omdVariable";
12
+ this.type = "omdString";
13
13
 
14
14
  this.numText = new jsvgTextBox();
15
15
  this.numText.setWidthAndHeight( 30,30 );
@@ -36,4 +36,15 @@ export class omdString extends omdMetaExpression
36
36
 
37
37
  this.setWidthAndHeight( this.backRect.width, this.backRect.height );
38
38
  }
39
+
40
+ loadFromJSON(data) {
41
+ if (typeof data === 'string') {
42
+ this.setName(data);
43
+ return;
44
+ }
45
+ if (data && typeof data.name === 'string') {
46
+ this.setName(data.name);
47
+ return;
48
+ }
49
+ }
39
50
  }
@@ -0,0 +1,84 @@
1
+ // Small parsers to convert simple equation/expression strings into OMD JSON
2
+
3
+ // Parse an expression like "3x+4-2y" into a termsAndOpers array:
4
+ // ['3x', '+', '4', '-', '2y'] -> [{omdType:'term', coefficient:3, variable:'x' }, {omdType:'operator', operator:'+'}, ...]
5
+ export function parseExpressionString(str) {
6
+ const cleaned = String(str || '').replace(/\s+/g, '');
7
+ if (!cleaned) return null;
8
+
9
+ // Tokenize numbers, variables, operators, and superscripts
10
+ // Token regex covers +/- as signs attached to numbers/vars, or standalone operators
11
+ const tokenRe = /([+-]?\d*\.?\d+[a-zA-Z]*)|([+-]?[a-zA-Z]+\^?\d*)|([+\-*/=×÷])/g;
12
+ const matches = cleaned.match(tokenRe) || [];
13
+ if (matches.length === 0) return null;
14
+
15
+ const out = [];
16
+ for (let tok of matches) {
17
+ // operator-only tokens
18
+ if (/^[+\-*/=×÷]$/.test(tok)) {
19
+ out.push({ omdType: 'operator', operator: tok.replace('*', '×') });
20
+ continue;
21
+ }
22
+ // term or number/variable
23
+ const m = tok.match(/^([+-]?)(\d*\.?\d*)([a-zA-Z]?)(?:\^(\d+))?$/);
24
+ if (m) {
25
+ const sign = m[1] === '-' ? -1 : 1;
26
+ const coefRaw = m[2];
27
+ const varChar = m[3] || '';
28
+ const exp = m[4] ? Number(m[4]) : 1;
29
+ let coef = 1;
30
+ if (coefRaw && coefRaw.length > 0) coef = Number(coefRaw);
31
+ if (!varChar && coefRaw) {
32
+ // pure number
33
+ out.push({ omdType: 'number', value: sign * coef });
34
+ } else {
35
+ out.push({ omdType: 'term', coefficient: sign * coef, variable: varChar, exponent: exp });
36
+ }
37
+ } else {
38
+ // fallback to string token
39
+ out.push({ omdType: 'string', name: tok });
40
+ }
41
+ }
42
+
43
+ // If first token is an operator like '+' or '-', and followed by a term/number, fold it
44
+ const folded = [];
45
+ for (let i = 0; i < out.length; i++) {
46
+ const t = out[i];
47
+ if (t.omdType === 'operator' && (t.operator === '+' || t.operator === '-')) {
48
+ // If it's a leading sign attached to next term, merge
49
+ const next = out[i+1];
50
+ if (next && (next.omdType === 'term' || next.omdType === 'number')) {
51
+ if (next.omdType === 'number') {
52
+ next.value = (t.operator === '-') ? -next.value : next.value;
53
+ } else if (next.omdType === 'term') {
54
+ next.coefficient = (t.operator === '-') ? -next.coefficient : next.coefficient;
55
+ }
56
+ i++; // skip next because we've merged
57
+ folded.push(next);
58
+ continue;
59
+ }
60
+ }
61
+ folded.push(t);
62
+ }
63
+
64
+ // Interleave operators where missing: if folded array alternates term/number and operator
65
+ const result = [];
66
+ for (let i = 0; i < folded.length; i++) {
67
+ result.push(folded[i]);
68
+ }
69
+
70
+ return { termsAndOpers: result };
71
+ }
72
+
73
+ // Parse an equation like "3x+4=2x+1" into left/right expression JSON
74
+ export function parseEquationString(str) {
75
+ const s = String(str || '');
76
+ const parts = s.split('=');
77
+ if (parts.length !== 2) return null;
78
+ const left = parts[0].trim();
79
+ const right = parts[1].trim();
80
+ const leftJson = parseExpressionString(left);
81
+ const rightJson = parseExpressionString(right);
82
+ if (!leftJson || !rightJson) return null;
83
+ return { leftExpression: leftJson, rightExpression: rightJson };
84
+ }
@@ -1,6 +1,7 @@
1
1
 
2
2
  import { omdColor } from "./omdColor.js";
3
3
  import { omdMetaExpression } from "./omdMetaExpression.js"
4
+ import { jsvgTextBox } from "@teachinglab/jsvg";
4
5
 
5
6
  export class omdVariable extends omdMetaExpression
6
7
  {