-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpr.html
More file actions
846 lines (737 loc) · 35.5 KB
/
expr.html
File metadata and controls
846 lines (737 loc) · 35.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>BODMAS Engine - Exponents Visuals</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap');
/* --- Page Layout --- */
body {
font-family: 'Inter', sans-serif;
background-color: #ffffff;
color: #1a1a1a;
display: flex;
flex-direction: column;
height: 100vh;
width: 100vw;
overflow: hidden;
}
header { flex: none; z-index: 50; }
main {
flex: 1;
position: relative;
overflow: hidden;
display: flex;
flex-direction: column;
}
.tree-viewport {
flex: 1;
overflow: auto;
position: relative;
touch-action: pan-x pan-y;
background-color: #fcfcfc;
background-image: radial-gradient(#e5e7eb 1px, transparent 1px);
background-size: 24px 24px;
}
#treeContainer {
min-width: 1500px;
min-height: 1200px;
display: grid;
place-items: center;
padding: 100px;
}
/* --- Node Styles --- */
.node {
transition: all 0.2s cubic-bezier(0.25, 0.8, 0.25, 1);
background: white;
user-select: none;
position: relative;
z-index: 20;
-webkit-tap-highlight-color: transparent;
}
.node-operator {
border-color: #e5e7eb;
color: #9ca3af;
background-color: #f9fafb;
}
/* --- Interactive States --- */
body.mode-simplify .node-operator.can-evaluate,
body.mode-rearrange .node-operator.can-transform {
cursor: pointer;
}
/* Simplify Mode - Highlighting */
body.mode-simplify.hints-active .node-operator.can-evaluate {
border-color: #2563eb;
color: #2563eb;
background-color: #eff6ff;
}
body.mode-simplify .node-operator.can-evaluate:active {
background-color: #2563eb;
color: #ffffff;
transform: scale(0.95);
border-color: #2563eb;
}
/* Rearrange Mode - Highlighting */
body.mode-rearrange.hints-active .node-operator.can-transform {
border-color: #9333ea;
color: #9333ea;
background-color: #f3e8ff;
}
body.mode-rearrange .node-operator.can-transform:active {
background-color: #9333ea;
color: #ffffff;
transform: scale(0.95);
border-color: #9333ea;
}
/* Active Menu State */
.node-operator.menu-open {
background-color: #1f2937 !important;
border-color: #1f2937 !important;
color: white !important;
box-shadow: 0 0 0 4px rgba(31, 41, 55, 0.15);
transform: scale(1.05);
}
.frac {
display: inline-flex;
flex-direction: column;
vertical-align: middle;
text-align: center;
line-height: 1.1;
font-size: 0.9em;
}
.frac span.top { border-bottom: 1px solid currentColor; padding: 0 2px; }
.connector {
stroke: #94a3b8;
stroke-width: 1.5;
fill: none;
}
/* --- Expression View --- */
.expression-view-active #treeContainer {
background: none;
display: flex;
align-items: center;
justify-content: center;
}
.expression-view-active #treeContent {
display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: center; padding: 20px;
}
.expression-bracket { font-size: 2rem; color: #94a3b8; font-weight: 300; margin: 0 2px; }
/* --- Exponent Styles (NEW) --- */
.exponent-block {
display: inline-flex;
align-items: flex-start;
vertical-align: middle;
margin: 0 2px;
}
.exponent-base {
display: flex;
align-items: center;
}
.exponent-power {
font-size: 0.75em;
margin-left: 2px;
margin-top: -8px;
color: #4b5563;
display: flex;
align-items: center;
transform:scale(0.5);
}
.exponent-block.node-operator {
background: none;
border: none;
padding: 0;
min-width: auto;
height: auto;
}
/* Highlight the exponent power when interactive */
body.mode-simplify .exponent-block.can-evaluate .exponent-power,
body.mode-rearrange .exponent-block.can-transform .exponent-power {
color: #2563eb;
font-weight: bold;
cursor: pointer;
}
body.mode-rearrange.hints-active .exponent-block.can-transform .exponent-power {
color: #9333ea;
}
/* --- Context Menu --- */
#contextMenu {
position: fixed;
z-index: 1000;
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(8px);
border: 1px solid #e5e7eb;
box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.15), 0 4px 10px -2px rgba(0, 0, 0, 0.05);
border-radius: 12px;
padding: 6px;
display: flex;
flex-direction: column;
gap: 2px;
min-width: 180px;
opacity: 0;
transform: scale(0.95);
transition: opacity 0.1s, transform 0.1s;
pointer-events: none;
}
#contextMenu.active {
opacity: 1;
transform: scale(1);
pointer-events: auto;
}
.menu-item {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
text-align: left;
padding: 10px 12px;
font-size: 0.95rem;
font-weight: 500;
color: #374151;
border-radius: 8px;
background: transparent;
border: none;
cursor: pointer;
transition: background-color 0.1s;
}
.menu-item:active { background-color: #f3f4f6; }
@media (hover: hover) {
.menu-item:hover { background-color: #f9fafb; }
}
.menu-item-icon {
width: 24px; height: 24px;
display: flex; align-items: center; justify-content: center;
background: #f3f4f6;
border-radius: 6px;
color: #4b5563; font-weight: bold; font-size: 1.1em;
}
</style>
</head>
<body class="mode-simplify"> <header class="bg-white border-b border-gray-200 shadow-sm p-3">
<div class="max-w-4xl mx-auto flex flex-col gap-3">
<div class="flex justify-between items-center gap-2">
<div class="bg-gray-100 p-1 rounded-lg flex text-xs font-medium border border-gray-200 shrink-0">
<button id="modeSimplifyBtn" class="flex items-center gap-1.5 px-3 py-2 rounded-md transition-all touch-manipulation">
<span>Simplify</span>
</button>
<button id="modeRearrangeBtn" class="flex items-center gap-1.5 px-3 py-2 rounded-md transition-all touch-manipulation">
<span>Move</span>
</button>
</div>
<div class="bg-gray-100 p-1 rounded-lg flex text-xs font-medium border border-gray-200 shrink-0">
<button id="viewTreeBtn" class="px-3 py-2 rounded-md transition-all touch-manipulation">Tree</button>
<button id="viewExprBtn" class="px-3 py-2 rounded-md transition-all touch-manipulation">Expr</button>
</div>
</div>
<div class="flex justify-between items-center gap-3">
<div class="flex gap-3 w-full">
<button id="undoBtn" disabled class="flex items-center justify-center gap-2 border border-gray-200 bg-white text-gray-700 px-4 py-2.5 rounded-lg text-sm font-bold hover:bg-gray-50 transition-all disabled:opacity-40 disabled:bg-gray-50 touch-manipulation flex-1">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"/></svg>
Undo
</button>
<button id="regenerateBtn" class="flex items-center justify-center bg-gray-900 text-white px-4 py-2.5 rounded-lg text-sm font-bold active:bg-gray-700 transition-colors touch-manipulation shadow-sm flex-1">
New
</button>
</div>
<button id="hintsBtn" class="flex items-center gap-1.5 px-3 py-2.5 rounded-lg text-sm font-semibold transition-all touch-manipulation border border-gray-200 text-gray-500 hover:text-gray-900">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5"/><path d="M8.5 8.5A2.5 2.5 0 0 1 11 6"/></svg>
Hints
</button>
</div>
</div>
</header>
<main id="mainArea">
<div id="treeViewport" class="tree-viewport cursor-grab active:cursor-grabbing">
<div id="treeContainer" class="relative">
<svg id="svgConnectors" class="absolute inset-0 w-full h-full pointer-events-none" style="z-index: 10;"></svg>
<div id="treeContent" class="relative z-20"></div>
</div>
</div>
</main>
<div id="contextMenu"></div>
<footer class="absolute bottom-6 left-0 right-0 px-4 flex justify-center z-40 pointer-events-none">
<div class="pointer-events-auto bg-white/95 backdrop-blur border border-gray-200 px-4 py-3 rounded-xl shadow-lg max-w-lg w-full text-center">
<div class="text-[10px] font-bold uppercase text-gray-400 mb-1 tracking-wider">Current Expression</div>
<div id="expressionText" class="text-lg font-medium text-gray-800 font-mono"></div>
</div>
</footer>
<script>
// --- Utils ---
const generateId = () => 'node-' + Math.random().toString(36).substr(2, 9);
const gcd = (a, b) => { a = Math.abs(a); b = Math.abs(b); while (b) { a %= b; [a, b] = [b, a]; } return a; };
const simplify = (n, d) => {
if (d === 0) return { n, d };
const common = gcd(n, d);
return { n: n/common, d: d/common };
};
const fracOps = {
'+': (a, b) => simplify(a.n * b.d + b.n * a.d, a.d * b.d),
'-': (a, b) => simplify(a.n * b.d - b.n * a.d, a.d * b.d),
'×': (a, b) => simplify(a.n * b.n, a.d * b.d),
'÷': (a, b) => simplify(a.n * b.d, a.d * b.n),
'^': (a, b) => {
const exponent = b.n / b.d;
return simplify(Math.pow(a.n, exponent), Math.pow(a.d, exponent));
}
};
// --- State ---
let treeData = null;
let historyStack = [];
let currentView = 'expression';
let interactionMode = 'simplify';
let showHints = false;
// --- Tree Generation ---
function generateRandomTree(depth = 0, maxDepth = 3) {
const id = generateId();
const isLeaf = depth >= maxDepth || (depth > 0 && Math.random() > 0.4);
if (isLeaf) {
return { id, type: 'operand', value: { n: Math.floor(Math.random() * 10) + 1, d: 1 } };
} else {
const symbols = ['+', '-', '×', '÷', '^'];
const symbol = symbols[Math.floor(Math.random() * symbols.length)];
let rightNode = generateRandomTree(depth + 1, maxDepth);
if (symbol === '^') {
rightNode = {
id: generateId(),
type: 'operand',
value: { n: Math.floor(Math.random() * 3) + 1, d: 1 }
};
}
return {
id,
type: 'operator',
value: symbol,
left: generateRandomTree(depth + 1, maxDepth),
right: rightNode
};
}
}
// --- Transforms ---
const canCommute = (node) => node.type === 'operator' && ['+', '×'].includes(node.value);
function doCommute(node) { return { ...node, left: node.right, right: node.left }; }
const canAssociateRight = (node) => {
if (node.type !== 'operator' || !['+', '×'].includes(node.value)) return false;
return node.left && node.left.type === 'operator' && node.left.value === node.value;
};
function doAssociateRight(node) {
const A = node.left.left;
const B = node.left.right;
const C = node.right;
const newRight = { ...node, id: generateId(), left: B, right: C };
return { ...node.left, id: node.id, left: A, right: newRight };
}
const canAssociateLeft = (node) => {
if (node.type !== 'operator' || !['+', '×'].includes(node.value)) return false;
return node.right && node.right.type === 'operator' && node.right.value === node.value;
};
function doAssociateLeft(node) {
const A = node.left;
const B = node.right.left;
const C = node.right.right;
const newLeft = { ...node, id: generateId(), left: A, right: B };
return { ...node.right, id: node.id, left: newLeft, right: C };
}
// UPDATED: Distributive Law Logic
const canDistribute = (node) => {
if (node.type !== 'operator') return false;
// Case 1: Multiplication over Addition/Subtraction
if (node.value === '×') {
if (node.right.type === 'operator' && ['+', '-'].includes(node.right.value) && node.left.type==='operand') return 'right';
if (node.left.type === 'operator' && ['+', '-'].includes(node.left.value) && node.right.type==='operand') return 'left';
}
// Case 2: Exponentiation over Multiplication
if (node.value === '^') {
if (node.left.type === 'operator' && node.left.value === '×') return 'exponent';
}
return false;
}
function doDistribute(node) {
const dir = canDistribute(node);
if (!dir) return node;
// UPDATED: Exponent Distribution Logic
if (dir === 'exponent') {
// (A × B) ^ n -> A^n × B^n
const baseGroup = node.left;
const exponent = node.right;
const exp1 = JSON.parse(JSON.stringify(exponent)); exp1.id = generateId();
const exp2 = JSON.parse(JSON.stringify(exponent)); exp2.id = generateId();
const leftPow = { id: generateId(), type: 'operator', value: '^', left: baseGroup.left, right: exp1 };
const rightPow = { id: generateId(), type: 'operator', value: '^', left: baseGroup.right, right: exp2 };
return { id: node.id, type: 'operator', value: baseGroup.value, left: leftPow, right: rightPow };
}
// Existing Logic
let scalar, group;
if (dir === 'right') { scalar = node.left; group = node.right; }
else { scalar = node.right; group = node.left; }
const s1 = JSON.parse(JSON.stringify(scalar)); s1.id = generateId();
const s2 = JSON.parse(JSON.stringify(scalar)); s2.id = generateId();
const leftMult = { id: generateId(), type: 'operator', value: '×', left: dir==='right'?s1:group.left, right: dir==='right'?group.left:s1 };
const rightMult = { id: generateId(), type: 'operator', value: '×', left: dir==='right'?s2:group.right, right: dir==='right'?group.right:s2 };
return { id: node.id, type: 'operator', value: group.value, left: leftMult, right: rightMult };
}
function getPossibleTransforms(node) {
const moves = [];
if (canCommute(node)) moves.push({ name: 'Swap', action: 'commute', icon: '⇄' });
if (canAssociateRight(node)) moves.push({ name: 'Group Right', action: 'assoc-right', icon: '⤵' });
if (canAssociateLeft(node)) moves.push({ name: 'Group Left', action: 'assoc-left', icon: '⤴' });
if (canDistribute(node)) moves.push({ name: 'Distribute', action: 'distribute', icon: '⑃' });
return moves;
}
// --- Helper: Precedence Logic ---
const getPrecedence = (op) => {
if (op === '^') return 3;
if (op === '×' || op === '÷') return 2;
return 1;
};
// --- Render Helpers ---
function getExpressionString(node) {
if (node.type === 'operand') return node.value.d === 1 ? node.value.n : `${node.value.n}/${node.value.d}`;
const myPrec = getPrecedence(node.value);
let l = getExpressionString(node.left);
let r = getExpressionString(node.right);
if (node.left.type === 'operator') {
const lPrec = getPrecedence(node.left.value);
if (lPrec < myPrec) l = `(${l})`;
}
if (node.right.type === 'operator') {
const rPrec = getPrecedence(node.right.value);
if (rPrec < myPrec) {
r = `(${r})`;
} else if (rPrec === myPrec) {
if (node.value !== '^') r = `(${r})`;
}
}
if (node.value === '^') return `${l}<sup>${r}</sup>`;
return `${l} ${node.value} ${r}`;
}
function getExpressionNodes(node) {
if (node.type === 'operand') return [{ type: 'operand', source: node }];
const myPrec = getPrecedence(node.value);
// UPDATED: Logic for Superscripts
// For ^, return a grouped object instead of flat list
if (node.value === '^') {
let base = getExpressionNodes(node.left);
// Respect precedence for base
if (node.left.type === 'operator' && getPrecedence(node.left.value) < myPrec) {
base = [{type:'b',v:'('}, ...base, {type:'b',v:')'}];
}
const exp = getExpressionNodes(node.right);
return [{
type: 'exponent-block',
source: node,
baseNodes: base,
expNodes: exp
}];
}
let l = getExpressionNodes(node.left);
let r = getExpressionNodes(node.right);
if (node.left.type === 'operator') {
const lPrec = getPrecedence(node.left.value);
if (lPrec < myPrec) l = [{type:'b',v:'('}, ...l, {type:'b',v:')'}];
}
if (node.right.type === 'operator') {
const rPrec = getPrecedence(node.right.value);
if (rPrec < myPrec) {
r = [{type:'b',v:'('}, ...r, {type:'b',v:')'}];
} else if (rPrec === myPrec) {
r = [{type:'b',v:'('}, ...r, {type:'b',v:')'}];
}
}
return [...l, { type: 'operator', source: node }, ...r];
}
// --- Logic ---
function updateTree(actionFn, targetId) {
saveToHistory();
const rebuild = (node) => {
if (node.id === targetId) {
if (interactionMode === 'simplify') {
const res = fracOps[node.value](node.left.value, node.right.value);
return { id: generateId(), type: 'operand', value: res };
} else {
return actionFn(node);
}
}
if (node.type === 'operator') {
return { ...node, left: rebuild(node.left), right: rebuild(node.right) };
}
return node;
};
treeData = rebuild(treeData);
render();
}
function handleNodeClick(e, node) {
e.stopPropagation();
hideContextMenu();
if (interactionMode === 'simplify') {
const canEval = node.left.type === 'operand' && node.right.type === 'operand';
if (canEval) updateTree(null, node.id);
} else {
const moves = getPossibleTransforms(node);
if (moves.length === 0) return;
if (moves.length === 1) {
executeTransform(moves[0].action, node.id);
} else {
showContextMenu(e.clientX, e.clientY, node, moves);
}
}
}
function executeTransform(actionStr, nodeId) {
let fn = null;
if (actionStr === 'commute') fn = doCommute;
if (actionStr === 'assoc-right') fn = doAssociateRight;
if (actionStr === 'assoc-left') fn = doAssociateLeft;
if (actionStr === 'distribute') fn = doDistribute;
if (fn) updateTree(fn, nodeId);
}
// --- Context Menu ---
const ctxMenu = document.getElementById('contextMenu');
const handleGlobalClick = (e) => {
const menu = document.getElementById('contextMenu');
if (menu.contains(e.target)) return;
hideContextMenu();
};
function showContextMenu(x, y, node, moves) {
const el = document.getElementById(node.id);
if(el) el.classList.add('menu-open');
ctxMenu.innerHTML = '';
moves.forEach(m => {
const btn = document.createElement('button');
btn.className = 'menu-item';
btn.innerHTML = `<span class="menu-item-icon">${m.icon}</span> ${m.name}`;
btn.onclick = (e) => {
e.stopPropagation();
executeTransform(m.action, node.id);
hideContextMenu();
};
ctxMenu.appendChild(btn);
});
let finalX = x;
let finalY = y + 10;
const menuRect = { width: 200, height: moves.length * 50 + 20 };
if (finalX + menuRect.width > window.innerWidth) finalX = window.innerWidth - menuRect.width - 16;
if (finalY + menuRect.height > window.innerHeight) finalY = y - menuRect.height - 10;
if (finalX < 16) finalX = 16;
ctxMenu.style.left = finalX + 'px';
ctxMenu.style.top = finalY + 'px';
ctxMenu.classList.add('active');
setTimeout(() => {
document.addEventListener('click', handleGlobalClick);
}, 50);
}
function hideContextMenu() {
ctxMenu.classList.remove('active');
document.querySelectorAll('.menu-open').forEach(el => el.classList.remove('menu-open'));
document.removeEventListener('click', handleGlobalClick);
}
// --- History ---
function saveToHistory() {
historyStack.push(JSON.parse(JSON.stringify(treeData)));
document.getElementById('undoBtn').disabled = false;
}
function undo() {
if (historyStack.length === 0) return;
treeData = historyStack.pop();
document.getElementById('undoBtn').disabled = historyStack.length === 0;
render();
}
// --- DOM Generation ---
function createNodeDOM(node) {
const div = document.createElement('div');
const isLeaf = node.type === 'operand';
const canEval = !isLeaf && node.left.type === 'operand' && node.right.type === 'operand';
const moves = !isLeaf ? getPossibleTransforms(node) : [];
const canTransform = moves.length > 0;
div.id = node.id;
div.className = "node rounded-full flex items-center justify-center shrink-0 border-2 font-medium shadow-sm relative w-12 h-12 md:w-14 md:h-14 text-lg ";
if (isLeaf) {
div.className += "border-gray-300 text-gray-700";
const val = node.value;
div.innerHTML = val.d === 1 ? `<span>${val.n}</span>` : `<div class="frac"><span class="top">${val.n}</span><span class="bottom">${val.d}</span></div>`;
} else {
div.className += "node-operator ";
if (interactionMode === 'simplify' && canEval) div.className += "can-evaluate";
if (interactionMode === 'rearrange' && canTransform) div.className += "can-transform";
div.textContent = node.value;
if ((interactionMode === 'simplify' && canEval) || (interactionMode === 'rearrange' && canTransform)) {
div.onclick = (e) => handleNodeClick(e, node);
}
}
return div;
}
function buildTreeDOM(node) {
const wrapper = document.createElement('div');
wrapper.className = "flex flex-col items-center";
wrapper.appendChild(createNodeDOM(node));
if (node.type !== 'operand') {
const childrenWrapper = document.createElement('div');
childrenWrapper.className = "flex gap-8 md:gap-24 mt-12 md:mt-20";
childrenWrapper.appendChild(buildTreeDOM(node.left));
childrenWrapper.appendChild(buildTreeDOM(node.right));
wrapper.appendChild(childrenWrapper);
}
return wrapper;
}
function drawConnectors(node) {
if (node.type === 'operand') return;
const p = document.getElementById(node.id);
const l = document.getElementById(node.left.id);
const r = document.getElementById(node.right.id);
if (p && l && r) {
const svg = document.getElementById('svgConnectors');
const cRect = document.getElementById('treeContainer').getBoundingClientRect();
const draw = (e1, e2) => {
const r1 = e1.getBoundingClientRect();
const r2 = e2.getBoundingClientRect();
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', r1.left + r1.width/2 - cRect.left);
line.setAttribute('y1', r1.top + r1.height/2 - cRect.top);
line.setAttribute('x2', r2.left + r2.width/2 - cRect.left);
line.setAttribute('y2', r2.top + r2.height/2 - cRect.top);
line.setAttribute('class', 'connector');
svg.appendChild(line);
};
draw(p, l); draw(p, r);
}
drawConnectors(node.left);
drawConnectors(node.right);
}
function render() {
const container = document.getElementById('treeContent');
const svg = document.getElementById('svgConnectors');
const exprText = document.getElementById('expressionText');
container.innerHTML = '';
svg.innerHTML = '';
exprText.innerHTML = getExpressionString(treeData);
// Add 'hints-active' class to body if enabled
const hintsClass = showHints ? 'hints-active' : '';
document.body.className = `mode-${interactionMode} ${currentView === 'tree' ? 'tree-view-active' : 'expression-view-active'} ${hintsClass}`;
if (treeData.type === 'operand') {
container.innerHTML = `<div class="text-7xl font-bold text-gray-900">${treeData.value.n}${treeData.value.d === 1 ? '' : '/' + treeData.value.d}</div>`;
return;
}
if (currentView === 'tree') {
svg.style.display = 'block';
container.appendChild(buildTreeDOM(treeData));
setTimeout(() => { requestAnimationFrame(() => { svg.innerHTML = ''; drawConnectors(treeData); }); }, 0);
} else {
svg.style.display = 'none';
// UPDATED: Recursive Renderer for Superscripts
const renderNodesToContainer = (nodes, parentEl) => {
nodes.forEach(item => {
if (item.type === 'b') {
const s = document.createElement('span');
s.textContent = item.v;
s.className = 'expression-bracket';
parentEl.appendChild(s);
}
else if (item.type === 'exponent-block') {
const wrapper = document.createElement('div');
wrapper.className = 'exponent-block node-operator';
const node = item.source;
const isLeaf = false;
const canEval = node.left.type === 'operand' && node.right.type === 'operand';
const moves = getPossibleTransforms(node);
const canTransform = moves.length > 0;
if (interactionMode === 'simplify' && canEval) wrapper.classList.add("can-evaluate");
if (interactionMode === 'rearrange' && canTransform) wrapper.classList.add("can-transform");
if ((interactionMode === 'simplify' && canEval) || (interactionMode === 'rearrange' && canTransform)) {
wrapper.onclick = (e) => handleNodeClick(e, node);
wrapper.id = node.id;
}
const baseDiv = document.createElement('div');
baseDiv.className = 'exponent-base';
renderNodesToContainer(item.baseNodes, baseDiv);
const powerDiv = document.createElement('div');
powerDiv.className = 'exponent-power';
renderNodesToContainer(item.expNodes, powerDiv);
wrapper.appendChild(baseDiv);
wrapper.appendChild(powerDiv);
parentEl.appendChild(wrapper);
}
else {
parentEl.appendChild(createNodeDOM(item.source));
}
});
};
renderNodesToContainer(getExpressionNodes(treeData), container);
}
}
// --- Initialization ---
window.onload = () => {
treeData = generateRandomTree(0, 3);
const btnSimp = document.getElementById('modeSimplifyBtn');
const btnRear = document.getElementById('modeRearrangeBtn');
const btnViewTree = document.getElementById('viewTreeBtn');
const btnViewExpr = document.getElementById('viewExprBtn');
const btnHints = document.getElementById('hintsBtn');
const viewport = document.getElementById('treeViewport');
viewport.addEventListener('scroll', () => {
if (ctxMenu.classList.contains('active')) hideContextMenu();
});
const centerViewport = () => {
const ct = document.getElementById('treeContainer');
if(viewport && ct) {
viewport.scrollLeft = (ct.offsetWidth - viewport.offsetWidth) / 2;
viewport.scrollTop = (ct.offsetHeight - viewport.offsetHeight) / 2 - 50;
}
};
const updateUI = () => {
const activeMode = "bg-white text-blue-600 shadow-sm ring-1 ring-gray-200";
const activeModePurple = "bg-white text-purple-600 shadow-sm ring-1 ring-gray-200";
const inactive = "text-gray-500 hover:text-gray-900 bg-transparent";
// Mode Buttons
if(interactionMode === 'simplify') {
btnSimp.className = `flex items-center gap-1.5 px-3 py-2 rounded-md transition-all touch-manipulation ${activeMode}`;
btnRear.className = `flex items-center gap-1.5 px-3 py-2 rounded-md transition-all touch-manipulation ${inactive}`;
} else {
btnSimp.className = `flex items-center gap-1.5 px-3 py-2 rounded-md transition-all touch-manipulation ${inactive}`;
btnRear.className = `flex items-center gap-1.5 px-3 py-2 rounded-md transition-all touch-manipulation ${activeModePurple}`;
}
// View Buttons
if(currentView === 'tree') {
btnViewTree.className = `px-3 py-2 rounded-md transition-all touch-manipulation bg-white text-gray-900 shadow-sm ring-1 ring-gray-200`;
btnViewExpr.className = `px-3 py-2 rounded-md transition-all touch-manipulation ${inactive}`;
} else {
btnViewTree.className = `px-3 py-2 rounded-md transition-all touch-manipulation ${inactive}`;
btnViewExpr.className = `px-3 py-2 rounded-md transition-all touch-manipulation bg-white text-gray-900 shadow-sm ring-1 ring-gray-200`;
}
// Hints Button
if(showHints) {
btnHints.className = "flex items-center gap-1.5 px-3 py-2.5 rounded-lg text-sm font-semibold transition-all touch-manipulation border border-amber-200 bg-amber-50 text-amber-700 shadow-sm";
} else {
btnHints.className = "flex items-center gap-1.5 px-3 py-2.5 rounded-lg text-sm font-semibold transition-all touch-manipulation border border-gray-200 text-gray-500 hover:text-gray-900";
}
hideContextMenu();
render();
}
btnSimp.onclick = () => { interactionMode = 'simplify'; updateUI(); };
btnRear.onclick = () => { interactionMode = 'rearrange'; updateUI(); };
btnViewTree.onclick = () => {
currentView = 'tree';
updateUI();
setTimeout(centerViewport, 10);
};
btnViewExpr.onclick = () => {
currentView = 'expression';
updateUI();
setTimeout(centerViewport, 10);
};
btnHints.onclick = () => {
showHints = !showHints;
updateUI();
};
document.getElementById('regenerateBtn').onclick = () => {
historyStack = []; treeData = generateRandomTree(0, 3); render();
centerViewport();
};
document.getElementById('undoBtn').onclick = undo;
window.addEventListener('resize', () => {
if(currentView==='tree') { document.getElementById('svgConnectors').innerHTML=''; drawConnectors(treeData); }
});
updateUI();
setTimeout(centerViewport, 100);
};
</script>
</body>
</html>