Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1092 lines (1005 loc) · 38.3 KB
/
Copy pathscript.js
File metadata and controls
1092 lines (1005 loc) · 38.3 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
const sampleStyles = `
:root {
color-scheme: light;
font-family: Inter, Segoe UI, Arial, sans-serif;
color: #1f2937;
background: #edf5f7;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 16px;
min-height: 100vh;
background:
linear-gradient(180deg, #edf7f7 0%, #f8fafc 100%);
}
.sample {
display: grid;
gap: 12px;
min-height: calc(100vh - 32px);
align-content: start;
border: 1px solid #cbd5e1;
border-top: 5px solid #0f766e;
border-radius: 10px;
padding: 18px;
background: #ffffff;
color: #1f2937;
box-shadow: 0 12px 26px rgba(15, 23, 42, 0.12);
}
h1 {
margin: 0;
font-size: 20px;
line-height: 1.2;
color: #0f172a;
}
p {
margin: 0;
}
button,
select,
input,
textarea {
font: inherit;
}
button {
width: fit-content;
border: 0;
border-radius: 8px;
padding: 10px 14px;
color: #fff;
background: #0f766e;
font-weight: 700;
cursor: pointer;
box-shadow: 0 8px 16px rgba(15, 118, 110, 0.2);
}
button.secondary {
background: #334155;
box-shadow: 0 8px 16px rgba(51, 65, 85, 0.18);
}
button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
textarea,
input,
select,
.box {
width: 100%;
border: 1px solid #cbd5e1;
border-radius: 8px;
padding: 10px;
background: #ffffff;
color: #1f2937;
}
textarea {
min-height: 90px;
resize: vertical;
}
.row {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.status {
color: #334155;
font-size: 14px;
min-height: 20px;
}
canvas,
video {
width: 100%;
max-width: 520px;
border: 1px solid #cbd5e1;
border-radius: 8px;
background: #fff;
}
[contenteditable] {
min-height: 56px;
outline: 2px dashed #93c5fd;
}
`;
const sampleInteractives = [
{
title: 'Speech Recognition',
height: 330,
permissions: 'microphone *',
body: `
<div class="sample">
<h1>Speech Recognition</h1>
<p>Click speak, say a short answer, and the transcript appears below.</p>
<button id="speakBtn" type="button">Speak Answer</button>
<textarea id="transcript" placeholder="Your spoken answer will appear here."></textarea>
<p class="status" id="status"></p>
</div>
`,
script: `
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const btn = document.getElementById('speakBtn');
const output = document.getElementById('transcript');
const status = document.getElementById('status');
if (!SpeechRecognition) {
btn.disabled = true;
status.textContent = 'Speech recognition is not available in this browser.';
} else {
let recognition;
btn.addEventListener('click', async () => {
if (!window.isSecureContext) {
status.textContent = 'Speech recognition usually needs HTTPS or localhost.';
return;
}
if (recognition) recognition.abort();
try {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
stream.getTracks().forEach((track) => track.stop());
}
} catch (error) {
status.textContent = 'Microphone permission was blocked. Allow microphone access in the browser, then try again.';
return;
}
recognition = new SpeechRecognition();
recognition.lang = 'en-SG';
recognition.interimResults = false;
recognition.maxAlternatives = 1;
btn.disabled = true;
status.textContent = 'Listening...';
recognition.onresult = (event) => {
output.value = event.results[0][0].transcript;
status.textContent = 'Transcript captured.';
};
recognition.onerror = (event) => {
const messages = {
'not-allowed': 'Microphone permission was denied. Check the browser permission icon and allow microphone access.',
'service-not-allowed': 'Speech recognition is blocked by this browser or page context. Try Chrome or Edge over HTTPS/localhost.',
'no-speech': 'No speech was detected. Try again and speak after Listening appears.',
'audio-capture': 'No microphone was found. Check the selected input device.',
'network': 'The browser speech service could not be reached. Try again later or check the network.'
};
status.textContent = messages[event.error] || 'Speech recognition stopped: ' + event.error;
};
recognition.onend = () => {
if (status.textContent === 'Listening...') status.textContent = 'Listening ended.';
btn.disabled = false;
recognition = null;
};
try {
recognition.start();
} catch (error) {
btn.disabled = false;
recognition = null;
status.textContent = 'Speech recognition could not start. Wait a moment, then try again.';
}
});
}
`
},
{
title: 'Download Txt/CSV/JSON Files',
height: 360,
body: `
<div class="sample">
<h1>Download Txt/CSV/JSON Files</h1>
<textarea id="work">Student reflection: I can explain how evidence supports a historical claim.</textarea>
<div class="row">
<select id="format" aria-label="File format">
<option value="txt">TXT</option>
<option value="csv">CSV</option>
<option value="json">JSON</option>
</select>
<button id="downloadBtn" type="button">Download Work</button>
</div>
<p class="status" id="status">Choose a format, then download the text as a file.</p>
</div>
`,
script: `
const work = document.getElementById('work');
const format = document.getElementById('format');
const status = document.getElementById('status');
document.getElementById('downloadBtn').addEventListener('click', () => {
const value = work.value;
const selected = format.value;
const content = selected === 'csv'
? 'response\\\\n"' + value.replaceAll('"', '""') + '"'
: selected === 'json'
? JSON.stringify({ response: value }, null, 2)
: value;
const type = selected === 'json' ? 'application/json' : selected === 'csv' ? 'text/csv' : 'text/plain';
const url = URL.createObjectURL(new Blob([content], { type }));
const link = document.createElement('a');
link.href = url;
link.download = 'student-work.' + selected;
link.click();
URL.revokeObjectURL(url);
status.textContent = 'Downloaded student-work.' + selected;
});
`
},
{
title: 'Canvas Drawing Board',
height: 430,
body: `
<div class="sample">
<h1>Canvas Drawing Board</h1>
<div class="row">
<label>Colour <input id="colour" type="color" value="#2563eb"></label>
<button class="secondary" id="clearBtn" type="button">Clear</button>
</div>
<canvas id="drawCanvas" width="520" height="240" aria-label="Drawing board"></canvas>
<p class="status">Draw on the board with a mouse, trackpad, or touch.</p>
</div>
`,
script: `
const canvas = document.getElementById('drawCanvas');
const ctx = canvas.getContext('2d');
const colour = document.getElementById('colour');
let drawing = false;
ctx.lineWidth = 4;
ctx.lineCap = 'round';
function point(event) {
const rect = canvas.getBoundingClientRect();
return {
x: (event.clientX - rect.left) * (canvas.width / rect.width),
y: (event.clientY - rect.top) * (canvas.height / rect.height)
};
}
canvas.addEventListener('pointerdown', (event) => {
drawing = true;
canvas.setPointerCapture(event.pointerId);
const p = point(event);
ctx.beginPath();
ctx.moveTo(p.x, p.y);
});
canvas.addEventListener('pointermove', (event) => {
if (!drawing) return;
const p = point(event);
ctx.strokeStyle = colour.value;
ctx.lineTo(p.x, p.y);
ctx.stroke();
});
canvas.addEventListener('pointerup', () => drawing = false);
canvas.addEventListener('pointercancel', () => drawing = false);
document.getElementById('clearBtn').addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
`
},
{
title: 'ContentEditable Worksheet',
height: 360,
body: `
<div class="sample">
<h1>ContentEditable Worksheet</h1>
<p>Complete the blanks directly on the page.</p>
<div class="box">
<p>Source A is useful because <span id="blank1" contenteditable="true">type reason here</span>.</p>
<p>One limitation is <span id="blank2" contenteditable="true">type limitation here</span>.</p>
</div>
<button id="downloadBtn" type="button">Download Worksheet</button>
<p class="status" id="status"></p>
</div>
`,
script: `
document.getElementById('downloadBtn').addEventListener('click', () => {
const content = Array.from(document.querySelectorAll('.box p')).map(p => p.innerText).join('\\\\n');
const url = URL.createObjectURL(new Blob([content], { type: 'text/plain' }));
const link = document.createElement('a');
link.href = url;
link.download = 'completed-worksheet.txt';
link.click();
URL.revokeObjectURL(url);
document.getElementById('status').textContent = 'Worksheet downloaded.';
});
`
},
{
title: 'Save and Download as PDF',
height: 350,
body: `
<div class="sample">
<h1>Save and Download as PDF</h1>
<div class="box" id="work">
<strong>Exit Ticket</strong>
<p>Claim: Trade changed life in port cities.</p>
<p>Evidence: Maps show new routes and busier markets.</p>
</div>
<button id="printBtn" type="button">Save as PDF</button>
<p class="status">The browser print dialog lets the student save this page as a PDF.</p>
</div>
`,
script: `
document.getElementById('printBtn').addEventListener('click', () => window.print());
`
},
{
title: 'Confetti/Celebrations',
height: 360,
body: `
<style>
.stage { position: relative; min-height: 180px; overflow: hidden; border-radius: 8px; background: #fff; border: 1px solid #cbd5e1; }
.confetti { position: absolute; top: -12px; width: 10px; height: 14px; animation: fall 2.6s linear forwards; }
@keyframes fall { to { transform: translateY(220px) rotate(540deg); opacity: 0; } }
</style>
<div class="sample">
<h1>Confetti/Celebrations</h1>
<button id="celebrateBtn" type="button">Complete Quiz</button>
<div class="stage" id="stage" aria-label="Confetti stage"></div>
<p class="status">Use this when students complete a goal or score full marks.</p>
</div>
`,
script: `
const stage = document.getElementById('stage');
document.getElementById('celebrateBtn').addEventListener('click', () => {
for (let i = 0; i < 50; i++) {
const piece = document.createElement('div');
piece.className = 'confetti';
piece.style.left = Math.random() * 100 + '%';
piece.style.background = 'hsl(' + Math.random() * 360 + ' 85% 55%)';
piece.style.animationDelay = Math.random() * 0.5 + 's';
stage.appendChild(piece);
setTimeout(() => piece.remove(), 3000);
}
});
`
},
{
title: 'Timer/Countdown',
height: 320,
body: `
<div class="sample">
<h1>Timer/Countdown</h1>
<div class="box" style="font-size: 42px; font-weight: 800; text-align: center;" id="timer">10</div>
<div class="row">
<button id="startBtn" type="button">Start</button>
<button class="secondary" id="resetBtn" type="button">Reset</button>
</div>
<p class="status" id="status">Start a quick timed activity.</p>
</div>
`,
script: `
const timer = document.getElementById('timer');
const status = document.getElementById('status');
let timeLeft = 10;
let interval = null;
function render() {
timer.textContent = timeLeft;
}
document.getElementById('startBtn').addEventListener('click', () => {
if (interval) return;
status.textContent = 'Timer running...';
interval = setInterval(() => {
timeLeft -= 1;
render();
if (timeLeft <= 0) {
clearInterval(interval);
interval = null;
status.textContent = 'Time is up!';
}
}, 1000);
});
document.getElementById('resetBtn').addEventListener('click', () => {
clearInterval(interval);
interval = null;
timeLeft = 10;
render();
status.textContent = 'Timer reset.';
});
`
},
{
title: 'Dark Mode Toggle',
height: 320,
body: `
<style>
body.dark { background: #111827; color: #f8fafc; }
body.dark h1 { color: #fff; }
body.dark .box { background: #1f2937; border-color: #475569; color: #f8fafc; }
</style>
<div class="sample">
<h1>Dark Mode Toggle</h1>
<div class="box">This sample switches between light and dark reading modes.</div>
<button id="darkModeToggle" type="button">Toggle Dark Mode</button>
<p class="status">Only the iframe sample theme changes.</p>
</div>
`,
script: `
document.getElementById('darkModeToggle').addEventListener('click', () => {
document.body.classList.toggle('dark');
});
`
},
{
title: 'Camera Access',
height: 520,
permissions: 'camera *; microphone *',
body: `
<div class="sample">
<h1>Camera Access</h1>
<div class="row">
<button id="startBtn" type="button">Start Camera</button>
<button class="secondary" id="captureBtn" type="button" disabled>Capture Photo</button>
</div>
<video id="video" autoplay playsinline muted></video>
<canvas id="snapshot" width="520" height="260" aria-label="Captured photo"></canvas>
<p class="status" id="status" aria-live="polite"></p>
</div>
`,
script: `
const video = document.getElementById('video');
const snapshot = document.getElementById('snapshot');
const status = document.getElementById('status');
const startBtn = document.getElementById('startBtn');
const captureBtn = document.getElementById('captureBtn');
let stream = null;
function waitForVideo() {
if (video.readyState >= 2 && video.videoWidth > 0) return Promise.resolve();
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('Video metadata timed out.')), 5000);
video.addEventListener('loadedmetadata', () => {
clearTimeout(timer);
resolve();
}, { once: true });
});
}
startBtn.addEventListener('click', async () => {
try {
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
status.textContent = 'Camera access needs a secure page and a browser that supports getUserMedia.';
return;
}
captureBtn.disabled = true;
if (stream) stream.getTracks().forEach(track => track.stop());
stream = await navigator.mediaDevices.getUserMedia({
video: { width: { ideal: 640 }, height: { ideal: 360 } },
audio: false
});
video.srcObject = stream;
await waitForVideo();
await video.play();
snapshot.width = video.videoWidth || 520;
snapshot.height = video.videoHeight || 260;
captureBtn.disabled = false;
status.textContent = 'Camera ready.';
} catch (error) {
captureBtn.disabled = true;
status.textContent = 'Camera failed: ' + (error.name || 'Error') + '. ' + (error.message || 'Permission may be blocked.');
}
});
captureBtn.addEventListener('click', () => {
if (!stream || video.readyState < 2 || !video.videoWidth) {
status.textContent = 'Start the camera before capturing.';
return;
}
const ctx = snapshot.getContext('2d');
ctx.drawImage(video, 0, 0, snapshot.width, snapshot.height);
status.textContent = 'Photo captured.';
});
`
},
{
title: 'Screen Recording',
height: 420,
permissions: 'display-capture *; microphone *',
body: `
<div class="sample">
<h1>Screen Recording</h1>
<div class="row">
<button id="startBtn" type="button">Start Recording</button>
<button class="secondary" id="stopBtn" type="button" disabled>Stop</button>
</div>
<video id="playback" controls></video>
<p class="status" id="status">Record a screen demo and preview the WebM video.</p>
</div>
`,
script: `
let recorder = null;
let chunks = [];
const status = document.getElementById('status');
const playback = document.getElementById('playback');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
startBtn.addEventListener('click', async () => {
try {
if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
status.textContent = 'Screen recording needs Chrome, Edge, or Firefox on a secure page.';
return;
}
let stream;
try {
stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: true });
} catch (audioError) {
stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false });
}
chunks = [];
recorder = new MediaRecorder(stream);
recorder.ondataavailable = event => chunks.push(event.data);
recorder.onstop = () => {
const blob = new Blob(chunks, { type: 'video/webm' });
playback.src = URL.createObjectURL(blob);
stream.getTracks().forEach(track => track.stop());
status.textContent = 'Recording ready for preview.';
};
recorder.start();
startBtn.disabled = true;
stopBtn.disabled = false;
status.textContent = 'Recording...';
} catch (error) {
status.textContent = 'Screen recording failed: ' + (error.name || 'Error') + '. ' + (error.message || 'Permission may be blocked.');
}
});
stopBtn.addEventListener('click', () => {
if (!recorder) return;
recorder.stop();
startBtn.disabled = false;
stopBtn.disabled = true;
});
`
},
{
title: 'Download Screen Recording',
height: 420,
permissions: 'display-capture *; microphone *',
body: `
<div class="sample">
<h1>Download Screen Recording</h1>
<div class="row">
<button id="startBtn" type="button">Record Screen</button>
<button class="secondary" id="stopBtn" type="button" disabled>Stop</button>
<button id="downloadBtn" type="button" disabled>Download WebM</button>
</div>
<video id="playback" controls></video>
<p class="status" id="status">Record first, then download the WebM file.</p>
</div>
`,
script: `
let recorder = null;
let chunks = [];
let recordedBlob = null;
const status = document.getElementById('status');
const playback = document.getElementById('playback');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const downloadBtn = document.getElementById('downloadBtn');
startBtn.addEventListener('click', async () => {
try {
if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
status.textContent = 'Screen recording needs Chrome, Edge, or Firefox on a secure page.';
return;
}
let stream;
try {
stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: true });
} catch (audioError) {
stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false });
}
chunks = [];
recordedBlob = null;
downloadBtn.disabled = true;
recorder = new MediaRecorder(stream);
recorder.ondataavailable = event => chunks.push(event.data);
recorder.onstop = () => {
recordedBlob = new Blob(chunks, { type: 'video/webm' });
playback.src = URL.createObjectURL(recordedBlob);
stream.getTracks().forEach(track => track.stop());
downloadBtn.disabled = false;
status.textContent = 'Recording ready to download.';
};
recorder.start();
startBtn.disabled = true;
stopBtn.disabled = false;
status.textContent = 'Recording...';
} catch (error) {
status.textContent = 'Screen recording failed: ' + (error.name || 'Error') + '. ' + (error.message || 'Permission may be blocked.');
}
});
stopBtn.addEventListener('click', () => {
if (!recorder) return;
recorder.stop();
startBtn.disabled = false;
stopBtn.disabled = true;
});
downloadBtn.addEventListener('click', () => {
if (!recordedBlob) return;
const url = URL.createObjectURL(recordedBlob);
const link = document.createElement('a');
link.href = url;
link.download = 'screen-recording.webm';
link.click();
URL.revokeObjectURL(url);
});
`
},
{
title: 'Simple Charts',
height: 390,
body: `
<div class="sample">
<h1>Simple Charts</h1>
<canvas id="chart" width="520" height="260" aria-label="Canvas bar chart"></canvas>
<button id="shuffleBtn" type="button">Randomise Scores</button>
<p class="status">A canvas chart can visualise student data without libraries.</p>
</div>
`,
script: `
const canvas = document.getElementById('chart');
const ctx = canvas.getContext('2d');
const labels = ['Test 1', 'Test 2', 'Test 3', 'Test 4'];
let data = [65, 85, 92, 78];
function drawChart() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = '16px Inter, Arial';
data.forEach((value, index) => {
const x = index * 115 + 45;
const height = value * 2;
const y = 220 - height;
ctx.fillStyle = '#2563eb';
ctx.fillRect(x, y, 58, height);
ctx.fillStyle = '#0f172a';
ctx.fillText(value, x + 15, y - 8);
ctx.fillText(labels[index], x + 3, 246);
});
}
document.getElementById('shuffleBtn').addEventListener('click', () => {
data = data.map(() => Math.floor(50 + Math.random() * 50));
drawChart();
});
drawChart();
`
},
{
title: 'Progressive Reveal',
height: 360,
body: `
<div class="sample">
<h1>Progressive Reveal</h1>
<div class="box">
<p><strong>Question:</strong> Why might Source B be biased?</p>
<button class="reveal-btn" type="button">Show Answer</button>
<p class="answer" hidden>The author has a clear purpose and only includes evidence that supports one side.</p>
</div>
<div class="box">
<p><strong>Question:</strong> What should we compare it with?</p>
<button class="reveal-btn" type="button">Show Answer</button>
<p class="answer" hidden>Compare it with another source from a different perspective.</p>
</div>
</div>
`,
script: `
document.querySelectorAll('.reveal-btn').forEach((button) => {
button.addEventListener('click', () => {
const answer = button.nextElementSibling;
answer.hidden = !answer.hidden;
button.textContent = answer.hidden ? 'Show Answer' : 'Hide Answer';
});
});
`
},
{
title: 'Random Question Generator',
height: 430,
body: `
<div class="sample">
<h1>Random Question Generator</h1>
<button id="assignBtn" type="button">Assign 4 Random Questions</button>
<ol class="box" id="questions"></ol>
<p class="status">Each click chooses questions without duplicates.</p>
</div>
`,
script: `
const questionBank = [
'What changed after the new trade route opened?',
'Which source is most reliable? Explain why.',
'Describe one cause of migration.',
'How did geography affect settlement?',
'What evidence supports the claim?',
'Compare two perspectives from the sources.',
'What was one intended consequence?',
'What question would you ask the author?'
];
const list = document.getElementById('questions');
function assign() {
const selected = [...questionBank].sort(() => Math.random() - 0.5).slice(0, 4);
list.innerHTML = selected.map(question => '<li>' + question + '</li>').join('');
}
document.getElementById('assignBtn').addEventListener('click', assign);
assign();
`
},
{
title: 'Text to Speech',
height: 560,
body: `
<div class="sample">
<h1>Text to Speech</h1>
<textarea id="content">Read this short instruction aloud: Compare the two sources and identify one similarity.</textarea>
<label>Language
<select id="languageSelect" aria-label="Language">
<option value="en">English</option>
<option value="zh">Chinese</option>
</select>
</label>
<label>Voice <select id="voiceSelect" aria-label="Voice"></select></label>
<div class="row">
<label>Rate <input id="rate" type="range" min="0.6" max="1.4" step="0.1" value="1"></label>
</div>
<div class="row">
<button id="readBtn" type="button">Read Aloud</button>
<button class="secondary" id="stopBtn" type="button">Stop</button>
</div>
<p class="status" id="status"></p>
</div>
`,
script: `
const status = document.getElementById('status');
const voiceSelect = document.getElementById('voiceSelect');
const languageSelect = document.getElementById('languageSelect');
const content = document.getElementById('content');
const sampleText = {
en: 'Read this short instruction aloud: Compare the two sources and identify one similarity.',
zh: '请朗读这段说明:比较两个资料,并找出一个相似点。'
};
function voiceScore(voice) {
const name = voice.name.toLowerCase();
const lang = voice.lang.toLowerCase();
const selectedLanguage = languageSelect.value;
let score = 0;
if (selectedLanguage === 'en' && lang.startsWith('en-sg')) score += 80;
if (selectedLanguage === 'en' && lang.startsWith('en-gb')) score += 70;
if (selectedLanguage === 'en' && lang.startsWith('en-us')) score += 65;
if (selectedLanguage === 'en' && lang.startsWith('en')) score += 50;
if (selectedLanguage === 'zh' && lang.startsWith('zh-sg')) score += 85;
if (selectedLanguage === 'zh' && lang.startsWith('zh-cn')) score += 80;
if (selectedLanguage === 'zh' && lang.startsWith('zh-hans')) score += 75;
if (selectedLanguage === 'zh' && lang.startsWith('zh-tw')) score += 65;
if (selectedLanguage === 'zh' && lang.startsWith('zh')) score += 55;
if (name.includes('natural')) score += 30;
if (name.includes('online')) score += 20;
if (name.includes('neural')) score += 20;
if (name.includes('microsoft')) score += 12;
if (name.includes('google')) score += 10;
if (name.includes('huihui')) score += 18;
if (name.includes('xiaoxiao')) score += 18;
if (name.includes('xiaoyi')) score += 16;
if (name.includes('yunxi')) score += 16;
if (name.includes('kang kang') || name.includes('kangkang')) score += 12;
if (name.includes('zira')) score += 18;
if (name.includes('mark')) score += 14;
if (name.includes('aria')) score += 18;
if (name.includes('jenny')) score += 18;
if (name.includes('sonia')) score += 16;
if (name.includes('libby')) score += 16;
if (name.includes('guy')) score += 12;
if (name.includes('david')) score += 4;
if (voice.localService) score += 5;
return score;
}
function isLanguageVoice(voice) {
const lang = voice.lang.toLowerCase();
return languageSelect.value === 'zh' ? lang.startsWith('zh') : lang.startsWith('en');
}
function getBestVoice(voices) {
return voices
.filter(isLanguageVoice)
.sort((a, b) => voiceScore(b) - voiceScore(a))[0] || voices[0] || null;
}
function loadVoices() {
if (!('speechSynthesis' in window)) {
voiceSelect.innerHTML = '<option>Text to speech unavailable</option>';
voiceSelect.disabled = true;
return;
}
const voices = speechSynthesis.getVoices();
const bestVoice = getBestVoice(voices);
voiceSelect.innerHTML = '';
if (!voices.length) {
voiceSelect.innerHTML = '<option>Loading system voices...</option>';
status.textContent = 'Voice list is loading. Click Read Aloud if it does not appear.';
return;
}
voices
.filter(isLanguageVoice)
.sort((a, b) => voiceScore(b) - voiceScore(a))
.forEach((voice) => {
const option = document.createElement('option');
option.value = voice.name;
option.textContent = voice.name + ' (' + voice.lang + ')';
if (bestVoice && voice.name === bestVoice.name) option.selected = true;
voiceSelect.appendChild(option);
});
if (!voiceSelect.options.length) {
const option = document.createElement('option');
option.value = '';
option.textContent = 'No ' + (languageSelect.value === 'zh' ? 'Chinese' : 'English') + ' voice installed';
voiceSelect.appendChild(option);
}
status.textContent = bestVoice && isLanguageVoice(bestVoice)
? 'Using the best available installed ' + (languageSelect.value === 'zh' ? 'Chinese' : 'English') + ' voice: ' + bestVoice.name + '.'
: 'No matching installed voice was found. The browser may use its default voice.';
}
loadVoices();
if ('speechSynthesis' in window) {
speechSynthesis.onvoiceschanged = loadVoices;
}
languageSelect.addEventListener('change', () => {
content.value = sampleText[languageSelect.value];
loadVoices();
});
document.getElementById('readBtn').addEventListener('click', () => {
if (!('speechSynthesis' in window)) {
status.textContent = 'Text to speech is not available in this browser.';
return;
}
if (!speechSynthesis.getVoices().length) loadVoices();
speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(document.getElementById('content').value);
const voices = speechSynthesis.getVoices();
const selectedVoice = voices.find(voice => voice.name === voiceSelect.value) || getBestVoice(voices);
if (selectedVoice) utterance.voice = selectedVoice;
utterance.lang = selectedVoice?.lang || (languageSelect.value === 'zh' ? 'zh-CN' : 'en-SG');
utterance.rate = Number(document.getElementById('rate').value);
utterance.onend = () => {
status.textContent = 'Finished reading.';
};
utterance.onerror = () => {
status.textContent = 'The selected system voice could not read this text.';
};
speechSynthesis.speak(utterance);
status.textContent = 'Reading aloud with ' + (selectedVoice?.name || 'the default voice') + '.';
});
document.getElementById('stopBtn').addEventListener('click', () => {
speechSynthesis.cancel();
status.textContent = 'Stopped.';
});
`
}
];
function createSampleDoc(sample) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${sample.title}</title>
<style>${sampleStyles}</style>
</head>
<body>
${sample.body}
<script>${sample.script}<\/script>
</body>
</html>`;
}
document.querySelectorAll('.code-label').forEach((label) => label.remove());
async function copyBlockText(sourceElement, buttonElement, copiedLabel) {
const originalLabel = buttonElement.textContent;
const contentText = sourceElement.innerText.trim().replace(/^"|"$/g, '');
try {
await navigator.clipboard.writeText(contentText);
buttonElement.textContent = copiedLabel;
} catch (error) {
const tempArea = document.createElement('textarea');
tempArea.value = contentText;
document.body.appendChild(tempArea);
tempArea.select();
document.execCommand('copy');
document.body.removeChild(tempArea);
buttonElement.textContent = copiedLabel;
}
setTimeout(() => {
buttonElement.textContent = originalLabel;
}, 1200);
}
document.querySelectorAll('.prompt-text').forEach((promptBlock) => {
const wrap = document.createElement('div');
wrap.className = 'copyable-block';
promptBlock.parentNode.insertBefore(wrap, promptBlock);
wrap.appendChild(promptBlock);
promptBlock.classList.add('has-copy-control');
const copyButton = document.createElement('button');
copyButton.type = 'button';
copyButton.className = 'copy-btn prompt-copy-btn';
copyButton.textContent = 'Copy Prompt';
copyButton.addEventListener('click', () => copyBlockText(promptBlock, copyButton, 'Copied Prompt!'));
wrap.appendChild(copyButton);
});
document.querySelectorAll('.feature pre').forEach((codeBlock) => {
const wrap = document.createElement('div');
wrap.className = 'copyable-block';
codeBlock.parentNode.insertBefore(wrap, codeBlock);
wrap.appendChild(codeBlock);
codeBlock.classList.add('has-copy-control');
const copyButton = document.createElement('button');
copyButton.type = 'button';
copyButton.className = 'copy-btn code-copy-btn';
copyButton.textContent = 'Copy JS Code';
copyButton.addEventListener('click', () => copyBlockText(codeBlock, copyButton, 'Copied JS!'));
wrap.appendChild(copyButton);
});
document.querySelectorAll('.feature .copyable-block').forEach((wrapper) => {
const codeBlock = wrapper.querySelector('pre');
const copyButton = wrapper.querySelector('.code-copy-btn');
if (!codeBlock || !copyButton) return;
const revealButton = document.createElement('button');
revealButton.type = 'button';
revealButton.className = 'copy-btn reveal-code-btn';
revealButton.textContent = 'v Reveal JS Code';
wrapper.appendChild(revealButton);
codeBlock.style.display = 'none';