-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1817 lines (1631 loc) · 63.8 KB
/
Copy pathscript.js
File metadata and controls
1817 lines (1631 loc) · 63.8 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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================
// CONFIG
// Change WORKER_BASE_URL to match your Cloudflare Worker deployment URL.
// See worker/README.md for setup instructions.
// ============================================================
const WORKER_BASE_URL = "https://ai-math-tutor-worker.emmanuel-simon.workers.dev";
const WORKER_URL = WORKER_BASE_URL + "/solve";
const AUTH_URL = WORKER_BASE_URL + "/auth";
// ============================================================
// DOM REFERENCES
// ============================================================
const loginOverlay = document.getElementById("login-overlay");
const loginForm = document.getElementById("login-form");
const loginPassword = document.getElementById("login-password");
const loginError = document.getElementById("login-error");
const appContainer = document.getElementById("app-container");
const loadingOverlay = document.getElementById("loading-overlay");
const darkToggleBtn = document.getElementById("dark-toggle");
const chat = document.getElementById("chat");
const form = document.getElementById("chat-form");
const userInput = document.getElementById("user-input");
const sendButton = document.getElementById("send-button");
const clearButton = document.getElementById("clear-button");
const downloadButton = document.getElementById("download-button");
const statusDiv = document.getElementById("status");
const fileInput = document.getElementById("image-file-input");
const uploadButton = document.getElementById("image-upload-btn");
const imagePreviewContainer = document.getElementById("image-preview-container");
const imagePreviewImg = document.getElementById("image-preview");
const removeImageButton = document.getElementById("remove-image-btn");
// ============================================================
// DARK MODE
// ============================================================
function applyDarkMode(dark) {
document.documentElement.setAttribute("data-theme", dark ? "dark" : "light");
localStorage.setItem("mathTutorTheme", dark ? "dark" : "light");
darkToggleBtn.textContent = dark ? "\u2600\uFE0F" : "\uD83C\uDF19";
darkToggleBtn.title = dark ? "Switch to light mode" : "Switch to dark mode";
darkToggleBtn.setAttribute("aria-label", dark ? "Switch to light mode" : "Switch to dark mode");
}
// Initialise theme: prefer saved setting, otherwise follow system preference.
(function initTheme() {
const saved = localStorage.getItem("mathTutorTheme");
if (saved) {
applyDarkMode(saved === "dark");
} else {
applyDarkMode(window.matchMedia("(prefers-color-scheme: dark)").matches);
}
})();
darkToggleBtn.addEventListener("click", () => {
const isDark = document.documentElement.getAttribute("data-theme") === "dark";
applyDarkMode(!isDark);
});
// ============================================================
// AUTH / LOGIN
// ============================================================
// The class password is intentionally stored in sessionStorage so that students
// don't have to re-enter it on every page refresh within the same tab.
// sessionStorage is automatically cleared when the tab is closed and is not
// accessible from other origins, making it an acceptable choice for this
// low-sensitivity, school-classroom use case.
let storedPassword = sessionStorage.getItem("mathTutorPassword") || "";
async function attemptLogin(password) {
try {
const response = await fetch(AUTH_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password })
});
if (response.ok) {
storedPassword = password;
sessionStorage.setItem("mathTutorPassword", password);
loginOverlay.style.display = "none";
if (loadingOverlay) loadingOverlay.style.display = "none";
appContainer.style.display = "";
restoreChatHistory();
userInput.focus();
return true;
}
return false;
} catch {
return false;
}
}
loginForm.addEventListener("submit", async (event) => {
event.preventDefault();
const pw = loginPassword.value.trim();
if (!pw) return;
loginError.textContent = "";
const success = await attemptLogin(pw);
if (!success) {
loginError.textContent = "Incorrect password. Please try again.";
loginPassword.value = "";
loginPassword.focus();
}
});
// Auto-login if a password was saved in this browser session.
// Show a loading overlay instead of a blank page.
if (storedPassword) {
if (loadingOverlay) loadingOverlay.style.display = "flex";
loginOverlay.style.display = "none";
attemptLogin(storedPassword).then(success => {
if (!success) {
sessionStorage.removeItem("mathTutorPassword");
storedPassword = "";
if (loadingOverlay) loadingOverlay.style.display = "none";
loginOverlay.style.display = "flex";
}
});
}
// ============================================================
// CHAT HISTORY PERSISTENCE
// ============================================================
const MAX_HISTORY = 20;
let messages = [];
function saveChatHistory() {
try {
sessionStorage.setItem("mathTutorMessages", JSON.stringify(messages));
} catch {
// Storage quota exceeded — silently continue.
}
}
function restoreChatHistory() {
try {
const stored = sessionStorage.getItem("mathTutorMessages");
if (!stored) return;
const saved = JSON.parse(stored);
if (!Array.isArray(saved) || saved.length === 0) return;
messages = saved;
// Clear the default welcome message and re-render saved conversation.
while (chat.firstChild) chat.removeChild(chat.firstChild);
messages.forEach(msg => renderMessageBubble(msg.role, msg.content));
} catch {
// Corrupted storage — start fresh.
}
}
// ============================================================
// KATEX
// ============================================================
const KATEX_DELIMITERS = [
{ left: "$$", right: "$$", display: true },
{ left: "$", right: "$", display: false },
{ left: "\\[", right: "\\]", display: true },
{ left: "\\(", right: "\\)", display: false }
];
function applyKatex(el) {
if (typeof renderMathInElement === "function") {
renderMathInElement(el, { delimiters: KATEX_DELIMITERS, throwOnError: false });
}
}
// ============================================================
// GRAPH UTILITIES
// ============================================================
let graphCounter = 0;
// ============================================================
// TRIANGLE DIAGRAM UTILITIES
// ============================================================
/**
* Parses a [TRIANGLE: ...] tag body into a key/value parameter object.
* Example input: "a=1, b=√3, c=2, A=30°, B=60°, C=90°"
* Returns: { a: "1", b: "√3", c: "2", A: "30°", B: "60°", C: "90°" }
*/
function parseTriangleParams(raw) {
const params = {};
for (const pair of raw.split(",")) {
const m = pair.trim().match(/^([a-zA-Z]+)\s*=\s*(.+)$/);
if (m) params[m[1]] = m[2].trim();
}
return params;
}
/**
* Parses a triangle parameter value to a number.
* Handles plain numbers, √n, m√n, and simple fractions like 1/2.
* Returns NaN if the value cannot be parsed numerically.
*/
function parseTriangleNum(s) {
if (!s) return NaN;
s = String(s).replace(/°$/, "").trim();
// m√n (e.g. "2√3", "√2", "3√5")
const sqrtMatch = s.match(/^(\d*\.?\d*)√(\d+\.?\d*)$/);
if (sqrtMatch) {
const coefficient = sqrtMatch[1] ? parseFloat(sqrtMatch[1]) : 1;
return coefficient * Math.sqrt(parseFloat(sqrtMatch[2]));
}
// Simple fraction (e.g. "1/2")
const fracMatch = s.match(/^(\d+)\/(\d+)$/);
if (fracMatch) return parseFloat(fracMatch[1]) / parseFloat(fracMatch[2]);
return parseFloat(s);
}
/**
* Examines parsed triangle parameters and returns a SHAPE params object if
* the parameters actually describe a non-triangle shape, or null if it is a
* genuine right triangle.
*
* This is a smart fallback for when the AI uses [TRIANGLE: ...] for shapes
* that it should have rendered with [SHAPE: ...].
*
* @param {Object} params - Parsed key/value pairs from a [TRIANGLE: ...] tag
* @returns {Object|null} Shape params for drawShapeSVG(), or null for a real triangle
*/
function detectShapeFromTriangleParams(params) {
// If explicit shape-type params exist, treat as a SHAPE tag directly
if (params.type || params.sides || params.width || params.height || params.r) {
return params; // Already has shape params — pass through to drawShapeSVG
}
// Collect single-lowercase-letter side keys (a, b, c, d, …)
const sideKeys = Object.keys(params).filter(k => /^[a-z]$/.test(k));
// Collect single-uppercase-letter angle keys (A, B, C, D, …)
const angleKeys = Object.keys(params).filter(k => /^[A-Z]$/.test(k));
const numSides = sideKeys.length;
const numAngles = angleKeys.length;
const maxParams = Math.max(numSides, numAngles);
// All zeros → point
const allKeys = [...sideKeys, ...angleKeys];
if (allKeys.length > 0 && allKeys.every(k => parseTriangleNum(params[k]) === 0)) {
return { type: "point" };
}
// More than 3 side/angle parameters → regular polygon
if (maxParams > 3) {
const names = { 4: "Quadrilateral", 5: "Pentagon", 6: "Hexagon",
7: "Heptagon", 8: "Octagon", 9: "Nonagon", 10: "Decagon" };
const label = names[maxParams] ? `Regular ${names[maxParams]}` : `Regular ${maxParams}-gon`;
return { type: "polygon", sides: String(maxParams), label };
}
// Examine angle values for known regular-polygon interior angles
const angleValues = angleKeys.map(k => parseTriangleNum(params[k]));
if (angleValues.length >= 3 && angleValues.every(a => a === angleValues[0])) {
const commonAngle = angleValues[0];
// All angles 90° with equal sides → square; unequal → rectangle
if (commonAngle === 90) {
const sideValues = sideKeys.map(k => parseTriangleNum(params[k]));
const allEqual = sideValues.length > 0 && sideValues.every(s => s === sideValues[0]);
if (allEqual && sideValues.length > 0) {
return { type: "square", side: params[sideKeys[0]] };
}
if (sideValues.length >= 2) {
return {
type: "rectangle",
width: params[sideKeys[1]] || params.b,
height: params[sideKeys[0]] || params.a,
};
}
}
// Map known regular-polygon interior angles → number of sides
// A regular n-gon has interior angles of (n-2)×180/n degrees.
// The heptagon's exact value is ≈128.57°; both 128 and 129 are accepted
// because the model may round either way.
const interiorAngleMap = { 108: 5, 120: 6, 128: 7, 129: 7, 135: 8, 140: 9, 144: 10 };
const rounded = Math.round(commonAngle);
if (interiorAngleMap[rounded]) {
const n = interiorAngleMap[rounded];
const names = { 5: "Pentagon", 6: "Hexagon", 7: "Heptagon",
8: "Octagon", 9: "Nonagon", 10: "Decagon" };
return { type: "polygon", sides: String(n), label: `Regular ${names[n]}` };
}
}
return null; // Genuine right triangle — let drawTriangleSVG handle it
}
/**
* Builds an inline SVG element representing a labeled right triangle.
*
* Geometric convention (matches standard geometry textbooks):
* - C is the right-angle vertex (marked with a square corner symbol)
* - A and B are the two acute-angle vertices
* - a = side BC (the leg opposite angle A)
* - b = side AC (the leg opposite angle B)
* - c = side AB (the hypotenuse, opposite the right angle C)
*
* For visual clarity, C is placed at the bottom-left, A at the bottom-right,
* and B at the top-left, so the right angle is in the lower-left corner.
*
* @param {Object} params - keys: a, b, c (side labels), A, B, C (angle labels)
* @returns {SVGElement}
*/
function drawTriangleSVG(params) {
const aNum = parseTriangleNum(params.a);
const bNum = parseTriangleNum(params.b);
const SVG_W = 280;
const SVG_H = 200;
const PAD = 44; // space around triangle for labels
const drawW = SVG_W - 2 * PAD; // 192 px available
const drawH = SVG_H - 2 * PAD; // 112 px available
let aPx, bPx; // pixel lengths of the two legs
if (!isNaN(aNum) && !isNaN(bNum) && aNum > 0 && bNum > 0) {
const scale = Math.min(drawW / bNum, drawH / aNum);
aPx = aNum * scale;
bPx = bNum * scale;
} else if (!isNaN(aNum) && aNum > 0 && isNaN(bNum)) {
// Only vertical leg known — fill available height and use a reasonable width
aPx = drawH;
bPx = drawW;
} else if (!isNaN(bNum) && bNum > 0 && isNaN(aNum)) {
// Only horizontal leg known — fill available width and use a reasonable height
aPx = drawH;
bPx = drawW;
} else {
// No numeric side info — draw a sensible default shape
aPx = drawH * 0.7;
bPx = drawW * 0.8;
}
// Centre the drawing within the canvas
const xOff = PAD + (drawW - bPx) / 2;
const yOff = PAD + (drawH - aPx) / 2;
// Vertex coordinates (SVG y increases downward)
const vC = { x: xOff, y: yOff + aPx }; // right-angle vertex (bottom-left)
const vA = { x: xOff + bPx, y: yOff + aPx }; // bottom-right
const vB = { x: xOff, y: yOff }; // top-left
const svgNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("width", SVG_W);
svg.setAttribute("height", SVG_H);
svg.setAttribute("viewBox", `0 0 ${SVG_W} ${SVG_H}`);
svg.setAttribute("class", "triangle-svg");
// Triangle outline
const poly = document.createElementNS(svgNS, "polygon");
poly.setAttribute("points", `${vC.x},${vC.y} ${vA.x},${vA.y} ${vB.x},${vB.y}`);
poly.setAttribute("fill", "none");
poly.setAttribute("stroke", "currentColor");
poly.setAttribute("stroke-width", "2");
svg.appendChild(poly);
// Right-angle square marker at C
const sq = 10;
const sqPath = document.createElementNS(svgNS, "path");
sqPath.setAttribute("d",
`M ${vC.x},${vC.y - sq} L ${vC.x + sq},${vC.y - sq} L ${vC.x + sq},${vC.y}`);
sqPath.setAttribute("fill", "none");
sqPath.setAttribute("stroke", "currentColor");
sqPath.setAttribute("stroke-width", "1.5");
svg.appendChild(sqPath);
// Helper — append a <text> element
function addText(x, y, text, anchor, fill) {
const t = document.createElementNS(svgNS, "text");
t.setAttribute("x", x);
t.setAttribute("y", y);
t.setAttribute("text-anchor", anchor || "middle");
t.setAttribute("dominant-baseline","auto");
t.setAttribute("font-family", "monospace");
t.setAttribute("font-size", "13");
if (fill) t.setAttribute("fill", fill);
t.textContent = text;
svg.appendChild(t);
}
// Side labels
if (params.a) {
// Side a = BC: left vertical leg — label to the left
addText(vC.x - 8, (vC.y + vB.y) / 2, `a = ${params.a}`, "end");
}
if (params.b) {
// Side b = AC: bottom horizontal leg — label below
addText((vC.x + vA.x) / 2, vC.y + 18, `b = ${params.b}`, "middle");
}
if (params.c) {
// Side c = AB: hypotenuse — label offset perpendicular to the line
const midX = (vA.x + vB.x) / 2;
const midY = (vA.y + vB.y) / 2;
const dx = vB.x - vA.x;
const dy = vB.y - vA.y;
const len = Math.hypot(dx, dy);
const perpX = (-dy / len) * 18;
const perpY = ( dx / len) * 18;
addText(midX + perpX, midY + perpY + 5, `c = ${params.c}`, "middle");
}
// Angle labels (rendered in blue to distinguish from side labels)
if (params.A) {
// Angle A at bottom-right vertex — label slightly up and left
addText(vA.x - 14, vA.y - 8, params.A, "end", "#2563eb");
}
if (params.B) {
// Angle B at top-left vertex — label slightly right and down
addText(vB.x + 8, vB.y + 18, params.B, "start", "#2563eb");
}
if (params.C) {
// Angle C at bottom-left (right-angle) vertex — label next to the square
addText(vC.x + 16, vC.y - 16, params.C, "start", "#2563eb");
}
return svg;
}
// ============================================================
// SHAPE DIAGRAM UTILITIES
// ============================================================
/**
* Parses a [SHAPE: ...] tag body into a key/value parameter object.
* Example input: "type=polygon, sides=6, label=Regular Hexagon"
* Returns: { type: "polygon", sides: "6", label: "Regular Hexagon" }
*/
function parseShapeParams(raw) {
const params = {};
// Support values with spaces (e.g. label=Regular Hexagon)
for (const pair of raw.split(",")) {
const m = pair.trim().match(/^([a-zA-Z_]+)\s*=\s*(.+)$/);
if (m) params[m[1].trim()] = m[2].trim();
}
return params;
}
/**
* Shared SVG setup helper — creates a 280×200 SVG element.
*/
function makeSVG() {
const svgNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("width", "280");
svg.setAttribute("height", "200");
svg.setAttribute("viewBox", "0 0 280 200");
svg.setAttribute("class", "shape-svg");
return { svg, svgNS };
}
/**
* Appends a <text> element to an SVG.
*/
function svgText(svgNS, svg, x, y, text, anchor, opts) {
const t = document.createElementNS(svgNS, "text");
t.setAttribute("x", x);
t.setAttribute("y", y);
t.setAttribute("text-anchor", anchor || "middle");
t.setAttribute("dominant-baseline", "auto");
t.setAttribute("font-family", "monospace");
t.setAttribute("font-size", (opts && opts.fontSize) || "13");
if (opts && opts.fill) t.setAttribute("fill", opts.fill);
t.textContent = text;
svg.appendChild(t);
}
/**
* Draws a regular N-sided polygon SVG.
* Vertices are evenly spaced around a center point; first vertex points up.
*
* @param {number} n - Number of sides (3–10)
* @param {string} label - Shape name to display (e.g. "Regular Hexagon")
* @returns {SVGElement}
*/
function drawRegularPolygonSVG(n, label) {
const { svg, svgNS } = makeSVG();
const cx = 140, cy = 95, r = 72;
const points = [];
for (let i = 0; i < n; i++) {
const angle = (2 * Math.PI * i) / n - Math.PI / 2;
points.push({ x: cx + r * Math.cos(angle), y: cy + r * Math.sin(angle) });
}
const poly = document.createElementNS(svgNS, "polygon");
poly.setAttribute("points", points.map(p => `${p.x.toFixed(2)},${p.y.toFixed(2)}`).join(" "));
poly.setAttribute("fill", "none");
poly.setAttribute("stroke", "currentColor");
poly.setAttribute("stroke-width", "2");
svg.appendChild(poly);
// Vertex labels (A, B, C, …)
const letters = "ABCDEFGHIJ";
points.forEach((p, i) => {
const angle = (2 * Math.PI * i) / n - Math.PI / 2;
const lx = cx + (r + 14) * Math.cos(angle);
const ly = cy + (r + 14) * Math.sin(angle);
svgText(svgNS, svg, lx.toFixed(1), (ly + 4).toFixed(1), letters[i], "middle");
});
// Shape name label at the bottom
const displayLabel = label || `Regular ${n}-gon`;
svgText(svgNS, svg, 140, 192, displayLabel, "middle", { fontSize: "11" });
return svg;
}
/**
* Draws a circle SVG with a radius line and labels.
*
* @param {Object} params - keys: r (radius label), label
* @returns {SVGElement}
*/
function drawCircleSVG(params) {
const { svg, svgNS } = makeSVG();
const cx = 140, cy = 96, r = 72;
const circle = document.createElementNS(svgNS, "circle");
circle.setAttribute("cx", cx);
circle.setAttribute("cy", cy);
circle.setAttribute("r", r);
circle.setAttribute("fill", "none");
circle.setAttribute("stroke", "currentColor");
circle.setAttribute("stroke-width", "2");
svg.appendChild(circle);
// Center dot
const dot = document.createElementNS(svgNS, "circle");
dot.setAttribute("cx", cx);
dot.setAttribute("cy", cy);
dot.setAttribute("r", 3);
dot.setAttribute("fill", "currentColor");
svg.appendChild(dot);
// Radius line from center to right edge
const line = document.createElementNS(svgNS, "line");
line.setAttribute("x1", cx);
line.setAttribute("y1", cy);
line.setAttribute("x2", cx + r);
line.setAttribute("y2", cy);
line.setAttribute("stroke", "currentColor");
line.setAttribute("stroke-width", "1.5");
svg.appendChild(line);
// Center label
svgText(svgNS, svg, cx - 6, cy - 6, "O", "middle", { fontSize: "12" });
// Radius label
const rLabel = params.r ? `r = ${params.r}` : "r";
svgText(svgNS, svg, cx + r / 2, cy - 8, rLabel, "middle", { fontSize: "12" });
// Shape name
const displayLabel = params.label || "Circle";
svgText(svgNS, svg, 140, 192, displayLabel, "middle", { fontSize: "11" });
return svg;
}
/**
* Draws a rectangle SVG with width/height labels.
*
* @param {Object} params - keys: width, height, label
* @returns {SVGElement}
*/
function drawRectangleSVG(params) {
const { svg, svgNS } = makeSVG();
const rw = 180, rh = 110;
const rx = (280 - rw) / 2; // 50
const ry = (200 - rh) / 2; // 45
const rect = document.createElementNS(svgNS, "rect");
rect.setAttribute("x", rx);
rect.setAttribute("y", ry);
rect.setAttribute("width", rw);
rect.setAttribute("height", rh);
rect.setAttribute("fill", "none");
rect.setAttribute("stroke", "currentColor");
rect.setAttribute("stroke-width", "2");
svg.appendChild(rect);
// Corner labels
const corners = [
{ x: rx - 8, y: ry - 6, label: "A", anchor: "end" },
{ x: rx + rw + 8, y: ry - 6, label: "B", anchor: "start" },
{ x: rx + rw + 8, y: ry + rh + 14, label: "C", anchor: "start" },
{ x: rx - 8, y: ry + rh + 14, label: "D", anchor: "end" },
];
corners.forEach(c => svgText(svgNS, svg, c.x, c.y, c.label, c.anchor));
// Width label (below bottom edge)
const wLabel = params.width ? `width = ${params.width}` : "width";
svgText(svgNS, svg, 140, ry + rh + 30, wLabel, "middle", { fontSize: "12" });
// Height label (to the left of left edge, rotated)
const hLabel = params.height ? `height = ${params.height}` : "height";
const hText = document.createElementNS(svgNS, "text");
hText.setAttribute("x", rx - 16);
hText.setAttribute("y", ry + rh / 2);
hText.setAttribute("text-anchor", "middle");
hText.setAttribute("dominant-baseline","middle");
hText.setAttribute("font-family", "monospace");
hText.setAttribute("font-size", "12");
hText.setAttribute("transform", `rotate(-90, ${rx - 16}, ${ry + rh / 2})`);
hText.textContent = hLabel;
svg.appendChild(hText);
// Shape name
const displayLabel = params.label || "Rectangle";
svgText(svgNS, svg, 140, 196, displayLabel, "middle", { fontSize: "11" });
return svg;
}
/**
* Draws a line SVG with arrowheads on both ends to indicate infinite extent.
*
* @returns {SVGElement}
*/
function drawLineSVG() {
const { svg, svgNS } = makeSVG();
// Arrowhead marker definition
const defs = document.createElementNS(svgNS, "defs");
const makeMarker = (id, refX) => {
const marker = document.createElementNS(svgNS, "marker");
marker.setAttribute("id", id);
marker.setAttribute("markerWidth", "8");
marker.setAttribute("markerHeight", "8");
marker.setAttribute("refX", refX);
marker.setAttribute("refY", "3");
marker.setAttribute("orient", "auto");
const path = document.createElementNS(svgNS, "path");
path.setAttribute("d", "M0,0 L0,6 L8,3 Z");
path.setAttribute("fill", "currentColor");
marker.appendChild(path);
return marker;
};
defs.appendChild(makeMarker("arrowRight", "8"));
defs.appendChild(makeMarker("arrowLeft", "0"));
svg.appendChild(defs);
const line = document.createElementNS(svgNS, "line");
line.setAttribute("x1", 20);
line.setAttribute("y1", 100);
line.setAttribute("x2", 260);
line.setAttribute("y2", 100);
line.setAttribute("stroke", "currentColor");
line.setAttribute("stroke-width", "2");
line.setAttribute("marker-end", "url(#arrowRight)");
line.setAttribute("marker-start", "url(#arrowLeft)");
svg.appendChild(line);
// Two named points on the line
[[90, "A"], [190, "B"]].forEach(([x, lbl]) => {
const tick = document.createElementNS(svgNS, "line");
tick.setAttribute("x1", x); tick.setAttribute("y1", 93);
tick.setAttribute("x2", x); tick.setAttribute("y2", 107);
tick.setAttribute("stroke", "currentColor"); tick.setAttribute("stroke-width", "1.5");
svg.appendChild(tick);
svgText(svgNS, svg, x, 86, lbl, "middle");
});
svgText(svgNS, svg, 140, 130, "Line AB", "middle", { fontSize: "12" });
svgText(svgNS, svg, 140, 192, "Line (extends infinitely)", "middle", { fontSize: "11" });
return svg;
}
/**
* Draws a point SVG — a small filled dot with a label.
*
* @returns {SVGElement}
*/
function drawPointSVG() {
const { svg, svgNS } = makeSVG();
const dot = document.createElementNS(svgNS, "circle");
dot.setAttribute("cx", 140);
dot.setAttribute("cy", 96);
dot.setAttribute("r", 5);
dot.setAttribute("fill", "currentColor");
svg.appendChild(dot);
svgText(svgNS, svg, 140, 80, "P", "middle");
svgText(svgNS, svg, 140, 130, "Point P", "middle", { fontSize: "12" });
svgText(svgNS, svg, 140, 192, "Point (zero dimensions)", "middle", { fontSize: "11" });
return svg;
}
/**
* Draws a rhombus SVG (diamond orientation).
*
* @param {Object} params - keys: side, label
* @returns {SVGElement}
*/
function drawRhombusSVG(params) {
const { svg, svgNS } = makeSVG();
const cx = 140, cy = 96;
const hw = 100, hh = 68; // half-width and half-height
const points = [
{ x: cx, y: cy - hh }, // top
{ x: cx + hw, y: cy }, // right
{ x: cx, y: cy + hh }, // bottom
{ x: cx - hw, y: cy }, // left
];
const poly = document.createElementNS(svgNS, "polygon");
poly.setAttribute("points", points.map(p => `${p.x},${p.y}`).join(" "));
poly.setAttribute("fill", "none");
poly.setAttribute("stroke", "currentColor");
poly.setAttribute("stroke-width", "2");
svg.appendChild(poly);
// Vertex labels
const labels = [
{ p: points[0], lbl: "A", anchor: "middle", dy: -8 },
{ p: points[1], lbl: "B", anchor: "start", dy: 4 },
{ p: points[2], lbl: "C", anchor: "middle", dy: 18 },
{ p: points[3], lbl: "D", anchor: "end", dy: 4 },
];
labels.forEach(({ p, lbl, anchor, dy }) => {
svgText(svgNS, svg, p.x, p.y + dy, lbl, anchor);
});
// Side label
if (params.side) {
svgText(svgNS, svg, cx + hw / 2 + 8, cy - hh / 2, `s = ${params.side}`, "start", { fontSize: "12" });
}
// Shape name
const displayLabel = params.label || "Rhombus";
svgText(svgNS, svg, 140, 192, displayLabel, "middle", { fontSize: "11" });
return svg;
}
/**
* Routes a parsed SHAPE params object to the correct drawing function.
*
* @param {Object} params - Parsed key/value pairs from [SHAPE: ...] tag
* @returns {SVGElement}
*/
function drawShapeSVG(params) {
const type = (params.type || "").toLowerCase();
switch (type) {
case "circle":
return drawCircleSVG(params);
case "rectangle":
return drawRectangleSVG(params);
case "rhombus":
return drawRhombusSVG(params);
case "square": {
// Render as a regular 4-sided polygon with a "Square" label
const svg = drawRegularPolygonSVG(4, params.label || (params.side ? `Square (side = ${params.side})` : "Square"));
return svg;
}
case "line":
return drawLineSVG();
case "point":
return drawPointSVG();
case "polygon": {
const n = parseInt(params.sides, 10);
if (!isNaN(n) && n >= 3 && n <= 10) {
return drawRegularPolygonSVG(n, params.label || `Regular ${n}-gon`);
}
// Fall back to a hexagon if sides is missing/invalid
return drawRegularPolygonSVG(6, params.label || "Regular Polygon");
}
default:
// Unknown type — draw a generic hexagon as a fallback
return drawRegularPolygonSVG(6, params.label || type || "Shape");
}
}
// Default canvas dimensions used when an SVG has no intrinsic width/height.
const DEFAULT_CANVAS_WIDTH = 400;
const DEFAULT_CANVAS_HEIGHT = 300;
// Allowlist of safe characters for graph expressions.
// This prevents passing arbitrary code to functionPlot's eval-like parser.
const SAFE_EXPRESSION_RE = /^[a-zA-Z0-9+\-*/^()._,\s]*$/;
function isSafeExpression(expr) {
return SAFE_EXPRESSION_RE.test(expr);
}
/**
* Returns a Promise that resolves when the functionPlot library is available.
* Polls every 50 ms, up to maxWait ms.
*/
function waitForFunctionPlot(maxWait = 5000) {
return new Promise((resolve, reject) => {
if (typeof functionPlot === "function") { resolve(); return; }
const start = Date.now();
const interval = setInterval(() => {
if (typeof functionPlot === "function") {
clearInterval(interval);
resolve();
} else if (Date.now() - start > maxWait) {
clearInterval(interval);
reject(new Error("Function Plot library failed to load"));
}
}, 50);
});
}
// ============================================================
// SAFE MARKDOWN RENDERING
// Converts **bold**, *italic*, `code`, and \n newlines to DOM nodes.
// No innerHTML is used, making it XSS-safe.
// ============================================================
function parseInlineFormatting(text, container) {
const inlineRegex = /\*\*(.+?)\*\*|\*(.+?)\*|`([^`]+)`/g;
let lastIndex = 0;
let match;
while ((match = inlineRegex.exec(text)) !== null) {
if (match.index > lastIndex) {
container.appendChild(document.createTextNode(text.slice(lastIndex, match.index)));
}
if (match[1] !== undefined) {
const strong = document.createElement("strong");
strong.textContent = match[1];
container.appendChild(strong);
} else if (match[2] !== undefined) {
const em = document.createElement("em");
em.textContent = match[2];
container.appendChild(em);
} else if (match[3] !== undefined) {
const code = document.createElement("code");
code.textContent = match[3];
container.appendChild(code);
}
lastIndex = match.index + match[0].length;
}
if (lastIndex < text.length) {
container.appendChild(document.createTextNode(text.slice(lastIndex)));
}
}
function renderFormattedText(text, container) {
const lines = text.split("\n");
lines.forEach((line, idx) => {
if (idx > 0) container.appendChild(document.createElement("br"));
parseInlineFormatting(line, container);
});
}
// ============================================================
// MESSAGE RENDERING
// ============================================================
/**
* Appends a chat bubble to the chat section and returns the bubble element.
* Handles user messages (plain text + optional image) and assistant messages
* (safe markdown, KaTeX, interactive graphs).
*/
function renderMessageBubble(role, content) {
const messageEl = document.createElement("div");
messageEl.className = "message " + role;
const bubbleEl = document.createElement("div");
bubbleEl.className = "message-bubble";
if (role === "assistant") {
const textContent = (typeof content === "string") ? content : "";
renderAssistantContent(bubbleEl, textContent);
} else {
// User message: content may be a plain string or an array (text + image).
if (Array.isArray(content)) {
content.forEach(part => {
if (part.type === "image_url" && part.image_url && part.image_url.url) {
const img = document.createElement("img");
img.src = part.image_url.url;
img.className = "chat-image";
img.alt = "Uploaded image";
bubbleEl.appendChild(img);
} else if (part.type === "text" && part.text) {
const textSpan = document.createElement("span");
textSpan.textContent = part.text;
bubbleEl.appendChild(textSpan);
}
});
} else {
bubbleEl.textContent = content;
}
}
messageEl.appendChild(bubbleEl);
chat.appendChild(messageEl);
chat.scrollTop = chat.scrollHeight;
return bubbleEl;
}
/**
* Renders an assistant response into bubbleEl.
* Handles [GRAPH: ...], [TRIANGLE: ...], and [SHAPE: ...] tags, KaTeX, and safe markdown.
*/
function renderAssistantContent(bubbleEl, content) {
// Collect all special tags ([GRAPH: ...], [TRIANGLE: ...], [SHAPE: ...]) in document order.
const tagRegex = /\[(GRAPH|TRIANGLE|SHAPE):\s*(.+?)\]/g;
const tags = [];
let match;
while ((match = tagRegex.exec(content)) !== null) {
tags.push({
type: match[1], // "GRAPH", "TRIANGLE", or "SHAPE"
fullMatch: match[0],
raw: match[2].trim(),
index: match.index
});
}
if (tags.length > 0) {
bubbleEl.classList.add("has-graph");
let lastIndex = 0;
tags.forEach(tag => {
// Text segment before this tag
const textBefore = content.slice(lastIndex, tag.index);
if (textBefore.trim()) {
const textEl = document.createElement("div");
renderFormattedText(textBefore, textEl);
applyKatex(textEl);
bubbleEl.appendChild(textEl);
}
if (tag.type === "GRAPH") {
// ── Graph tag ──────────────────────────────────────────────────────────
// Parse "expression | param1=default:min:max | ..."
const parts = tag.raw.split("|").map(s => s.trim());
const expression = parts[0];
// Validate expression against allowlist before passing to functionPlot
if (!isSafeExpression(expression)) {
const errorEl = document.createElement("div");
errorEl.className = "graph-error";
errorEl.textContent = "This graph couldn\u2019t be displayed \u2014 the expression contains unexpected characters. Only letters, numbers, and basic math operators (+, -, *, /, ^) are allowed.";
bubbleEl.appendChild(errorEl);
lastIndex = tag.index + tag.fullMatch.length;
return;
}
const params = [];
for (let p = 1; p < parts.length; p++) {
const paramMatch = parts[p].match(/^(\w+)=(-?[\d.]+):(-?[\d.]+):(-?[\d.]+)$/);
if (paramMatch) {
params.push({
name: paramMatch[1],
default: parseFloat(paramMatch[2]),
min: parseFloat(paramMatch[3]),
max: parseFloat(paramMatch[4])
});
}
}
// Label above the graph
const labelEl = document.createElement("div");
labelEl.className = "graph-label";
labelEl.textContent = "y = " + expression;
bubbleEl.appendChild(labelEl);
// Graph container
const graphId = "graph-" + Date.now() + "-" + (graphCounter++);
const graphDiv = document.createElement("div");
graphDiv.className = "graph-container";
graphDiv.id = graphId;
graphDiv.dataset.expression = expression;
graphDiv.dataset.params = JSON.stringify(params);
bubbleEl.appendChild(graphDiv);
// Slider controls (only when parameters exist)
if (params.length > 0) {
const slidersDiv = document.createElement("div");
slidersDiv.className = "graph-sliders";
slidersDiv.dataset.graphId = graphId;
params.forEach(param => {
const row = document.createElement("div");
row.className = "graph-slider-row";
const label = document.createElement("label");
label.textContent = param.name;
row.appendChild(label);
const slider = document.createElement("input");
slider.type = "range";
slider.min = param.min;
slider.max = param.max;
slider.step = 0.1;
slider.value = param.default;
slider.dataset.paramName = param.name;
row.appendChild(slider);
const valueDisplay = document.createElement("span");
valueDisplay.className = "slider-value";
valueDisplay.textContent = param.default;
row.appendChild(valueDisplay);