Repository navigation
Expand file tree
/
Copy pathexercises.jsx
More file actions
1793 lines (1672 loc) · 80.3 KB
/
Copy pathexercises.jsx
File metadata and controls
1793 lines (1672 loc) · 80.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
/* DBLingo — exercise components.
* Each one calls onResult({ correct: bool, perfect: bool, diff?: string[] }) when checked.
* They expose: { ready: bool } via onState({ ready }) so the parent enables/disables CHECK.
*/
const { useState: useS, useEffect: useE, useRef: useR, useMemo: useM, useCallback: useC } = React;
/* Return a shuffled copy so authored data and answer mappings stay untouched. */
function shuffleForDisplay(items) {
const shuffled = [...items];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
/* ====================================================================
* Common: drag-and-drop engine (pointer events — mouse, touch and pen).
*
* HTML5 drag-and-drop never fires on touch screens, so every draggable
* exercise goes through this hook instead:
* - Touch: the piece lifts (floats, grows, glows) the instant it is pressed.
* - Mouse: the piece lifts after a few pixels of movement.
* - Tap a piece to select it, then tap a slot to place it (no dragging).
* - The page auto-scrolls when a dragged piece nears the viewport edge.
* Drop targets are any element carrying `targetAttrs(key)`; `onPlace(key,
* id, { half, via })` is called when a piece lands on one.
* ==================================================================== */
const DND_SLOP_PX = 4; // mouse movement before a press counts as a drag
const DND_TOUCH_SLOP_PX = 8; // finger jitter tolerated before a tap becomes a drag
const DND_SUPPRESS_CLICK_MS = 400; // ignore the click that trails a drag
const DND_TOUCH_LIFT_PX = 32; // must match the ml-lift-touch keyframe offset
const DND_EDGE_PX = 56; // auto-scroll zone near viewport edges
const DND_MAX_SCROLL_STEP = 20;
/* Creates the imperative pointer engine. It talks to React only through the
* stable setters/refs passed in, so window listeners never see stale state. */
function createDragEngine({ setOver, setDragId, setSelected, onPlaceRef }) {
const scope = 'dnd-' + Math.random().toString(36).slice(2, 9);
let s = null; // active press session
let overNow = null; // { key, half } currently under the piece
let suppressUntil = 0;
function setOverIfChanged(next) {
const sameKey = (overNow && overNow.key) === (next && next.key);
const sameHalf = (overNow && overNow.half) === (next && next.half);
if (sameKey && sameHalf) return;
overNow = next;
setOver(next);
}
function targetAt(x, y) {
const el = document.elementFromPoint(x, y);
const t = el && el.closest('[data-drop-key]');
if (!t || t.getAttribute('data-dnd-scope') !== scope) return null;
const r = t.getBoundingClientRect();
return { key: t.getAttribute('data-drop-key'), half: (y - r.top) < r.height / 2 ? 'top' : 'bot' };
}
function hitTest() {
if (!s) return;
// Centre of the floating piece as the user sees it (raised above the finger on touch).
const cx = s.x - s.offX + s.w / 2;
const cy = s.y - s.offY + s.h / 2 - (s.touch ? DND_TOUCH_LIFT_PX : 0);
const found = s.touch
? (targetAt(cx, cy) || targetAt(s.x, s.y))
: (targetAt(s.x, s.y) || targetAt(cx, cy));
setOverIfChanged(found);
}
function positionGhost() {
if (s && s.ghost) s.ghost.style.transform = `translate3d(${s.x - s.offX}px, ${s.y - s.offY}px, 0)`;
}
function autoScroll() {
if (!s || !s.lifted) return;
const topEdge = (s.topbar ? s.topbar.getBoundingClientRect().bottom : 0) + DND_EDGE_PX;
const bottomEdge = window.innerHeight - DND_EDGE_PX;
let dy = 0;
if (s.y < topEdge) dy = -Math.min(DND_MAX_SCROLL_STEP, Math.ceil((topEdge - s.y) / 3));
else if (s.y > bottomEdge) dy = Math.min(DND_MAX_SCROLL_STEP, Math.ceil((s.y - bottomEdge) / 3));
if (dy) { window.scrollBy(0, dy); hitTest(); }
s.raf = requestAnimationFrame(autoScroll);
}
function lift() {
s.lifted = true;
const ghost = document.createElement('div');
ghost.className = 'ml-drag-ghost' + (s.touch ? ' ml-drag-ghost--touch' : '');
ghost.setAttribute('aria-hidden', 'true');
ghost.style.width = s.w + 'px';
ghost.style.height = s.h + 'px';
ghost.style.setProperty('--ml-lift', DND_TOUCH_LIFT_PX + 'px');
const inner = s.el.cloneNode(true);
inner.removeAttribute('id');
inner.removeAttribute('tabindex');
inner.classList.remove('is-selected', 'is-dragging');
inner.classList.add('ml-drag-ghost__inner');
ghost.appendChild(inner);
document.body.appendChild(ghost);
s.ghost = ghost;
s.topbar = document.querySelector('.ml-topbar');
positionGhost();
document.documentElement.classList.add('ml-dnd-active');
setDragId(s.id);
if (s.touch && navigator.vibrate) { try { navigator.vibrate(10); } catch (e) { /* unsupported */ } }
s.raf = requestAnimationFrame(autoScroll);
hitTest();
}
function end() {
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onCancel);
if (!s) return;
if (s.raf) cancelAnimationFrame(s.raf);
if (s.ghost) s.ghost.remove();
document.documentElement.classList.remove('ml-dnd-active');
s = null;
setOverIfChanged(null);
setDragId(null);
}
function onMove(e) {
if (!s || e.pointerId !== s.pointerId) return;
s.x = e.clientX;
s.y = e.clientY;
if (!s.moved && Math.hypot(s.x - s.sx, s.y - s.sy) > (s.touch ? DND_TOUCH_SLOP_PX : DND_SLOP_PX)) s.moved = true;
if (!s.lifted) {
if (!s.moved) return;
lift();
}
if (e.cancelable) e.preventDefault();
positionGhost();
hitTest();
}
function onUp(e) {
if (!s || e.pointerId !== s.pointerId) return;
const session = s;
if (session.lifted) { session.x = e.clientX; session.y = e.clientY; hitTest(); }
const target = overNow;
end();
// A press that never moved is a tap: the element's onClick handles selection.
if (!session.moved) return;
suppressUntil = performance.now() + DND_SUPPRESS_CLICK_MS;
if (target) {
setSelected(null);
onPlaceRef.current && onPlaceRef.current(target.key, session.id, { half: target.half, via: 'drag' });
}
}
function onCancel(e) {
if (s && e.pointerId === s.pointerId) end();
}
function press(e, id) {
if (s) return;
if (e.pointerType === 'mouse' && e.button !== 0) return;
if (!e.isPrimary) return;
const el = e.currentTarget;
const r = el.getBoundingClientRect();
s = {
id, el,
pointerId: e.pointerId,
touch: e.pointerType !== 'mouse',
x: e.clientX, y: e.clientY, sx: e.clientX, sy: e.clientY,
offX: e.clientX - r.left, offY: e.clientY - r.top,
w: r.width, h: r.height,
lifted: false, moved: false, ghost: null, raf: 0, topbar: null
};
window.addEventListener('pointermove', onMove, { passive: false });
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onCancel);
// Touch users get immediate "picked up" feedback the moment they press.
if (s.touch) lift();
}
return {
scope,
press,
wasDrag: () => performance.now() < suppressUntil,
destroy: end
};
}
/* React hook wrapping the engine. Exercises call it once and spread
* `sourceProps(id)` onto pieces and `targetAttrs(key)` onto drop targets. */
function useDragDrop(onPlace) {
const [selected, setSelected] = useS(null); // tap-selected source id
const [dragId, setDragId] = useS(null); // source id currently floating
const [over, setOver] = useS(null); // { key, half } under the piece
const onPlaceRef = useR(onPlace);
onPlaceRef.current = onPlace;
const engine = useM(
() => createDragEngine({ setOver, setDragId, setSelected, onPlaceRef }),
[]
);
useE(() => () => engine.destroy(), [engine]);
// Escape drops a tap-selection.
useE(() => {
if (!selected) return;
const onKey = (e) => { if (e.key === 'Escape') setSelected(null); };
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [selected]);
const select = useC((id) => setSelected(prev => (prev === id ? null : id)), []);
const clear = useC(() => setSelected(null), []);
return {
scope: engine.scope,
selected,
dragId,
over,
select,
clear,
wasDrag: engine.wasDrag,
/** Spread onto a draggable element. */
sourceProps: (id) => ({
onPointerDown: (e) => engine.press(e, id),
onContextMenu: (e) => e.preventDefault()
}),
/** Spread onto a drop-target element. */
targetAttrs: (key) => ({ 'data-drop-key': key, 'data-dnd-scope': engine.scope }),
/** Place the tap-selected piece on `key`. Returns true when something was placed. */
placeSelected: (key, info) => {
if (!selected) return false;
const id = selected;
setSelected(null);
onPlaceRef.current && onPlaceRef.current(key, id, { ...(info || {}), via: 'tap' });
return true;
}
};
}
/* A token in the bank. Drag it, or tap it to select and then tap a slot. */
function DragToken({ id, kind, label, dnd }) {
const isSelected = dnd.selected === id;
const isDragging = dnd.dragId === id;
return (
<button
type="button"
className={`ml-token ml-token--draggable${isSelected ? ' is-selected' : ''}${isDragging ? ' is-dragging' : ''}`}
data-kind={kind}
{...dnd.sourceProps(id)}
onClick={() => { if (!dnd.wasDrag()) dnd.select(id); }}
aria-pressed={isSelected}
aria-label={`${kind} ${label}${isSelected ? ', selected. Now tap a slot' : ''}`}
>
{label}
</button>
);
}
/* The bank of unused tokens. Placed tokens leave the bank; clearing a slot returns them. */
function TokenBank({ tokens, dnd, kind }) {
return (
<div className="ml-tokenbank" data-has-selection={!!dnd.selected}>
{tokens.length === 0
? <span className="ml-tokenbank__empty">All pieces placed · tap a filled slot to send it back</span>
: tokens.map(t => (
<DragToken key={t.id} id={t.id} kind={kind || t.kind} label={t.label} dnd={dnd} />
))}
</div>
);
}
/* A drop slot. Accepts a dragged token or the tap-selected one; tap a filled slot to clear it. */
function DropSlot({ dropKey, dnd, filledId, filledLabel, filledKind, onClear, placeholder = '____' }) {
const isOver = !!(dnd.over && dnd.over.key === dropKey);
const awaiting = !filledLabel && !!(dnd.selected || dnd.dragId);
function activate() {
if (dnd.wasDrag()) return;
if (dnd.placeSelected(dropKey)) return;
if (filledLabel && onClear) onClear();
}
return (
<span
className="ml-slot"
{...dnd.targetAttrs(dropKey)}
data-over={isOver}
data-filled={!!filledLabel}
data-awaiting={awaiting}
onClick={activate}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); activate(); }
}}
role="button"
tabIndex={0}
aria-label={filledLabel
? `Filled with ${filledLabel}, ${dnd.selected ? 'tap to replace' : 'tap to clear'}`
: (dnd.selected ? 'Empty slot, tap to place the selected piece' : 'Empty slot')}
>
{filledLabel
? <span key={filledId || filledLabel} className="ml-token ml-token--placed" data-kind={filledKind}>{filledLabel}</span>
: <span style={{ padding: '0 6px' }}>{placeholder}</span>}
</span>
);
}
/* ====================================================================
* Exercise: SHAPE — drag JSON values into a document skeleton.
* ==================================================================== */
function ShapeExercise({ level, onResult, onState }) {
const slots = useM(() => level.skeleton.filter(f => f.type === 'slot'), [level]);
const displayBank = useM(() => shuffleForDisplay(level.bank), [level]);
const [filled, setFilled] = useS({}); // { slotName: tokenId }
const [feedback, setFeedback] = useS(null);
const [perfect, setPerfect] = useS(true);
const allFilled = slots.every(s => filled[s.slot]);
const bankById = useM(() => Object.fromEntries(level.bank.map(b => [b.id, b])), [level]);
function placeAt(slotKey, tokenId) {
setFilled(prev => {
const next = { ...prev };
// Remove tokenId from any other slot
for (const k of Object.keys(next)) if (next[k] === tokenId) delete next[k];
next[slotKey] = tokenId;
return next;
});
}
const dnd = useDragDrop((slotKey, tokenId) => placeAt(slotKey, tokenId));
const usedIds = new Set(Object.values(filled));
const availableBank = displayBank.filter(t => !usedIds.has(t.id));
function check() {
let correct = true;
for (const [k, expected] of Object.entries(level.answer)) {
if (filled[k] !== expected) correct = false;
}
if (!correct) setPerfect(false);
setFeedback(correct ? {
state: 'correct',
title: 'Document accepted.',
message: `Inserted into db.users — _id auto-generated.`
} : {
state: 'wrong',
title: 'BSON type mismatch.',
message: 'Strings need quotes. Numbers and booleans do not. Try again.'
});
onResult && onResult({ correct, perfect: correct && perfect });
}
// expose check via state
useE(() => { onState && onState({
ready: allFilled, check,
userState: { filled, bankById },
reset: () => { setFilled({}); setFeedback(null); setPerfect(true); dnd.clear(); }
}); }, [allFilled, filled, perfect]);
return (
<>
<div className="ml-doc-result" style={{ marginBottom: 18 }}>
{/* The skeleton itself acts as the drop targets */}
<div className="ml-code" aria-label="user document">
<span style={{ color: '#6F8390' }}>{'{'}</span>
{level.skeleton.map((f, i) => {
const isLast = i === level.skeleton.length - 1;
return (
<div key={f.key} style={{ marginLeft: 12 }}>
<span style={{ color: '#B6E1FF' }}>{f.key}</span>
<span style={{ color: '#6F8390' }}>: </span>
{f.type === 'oid'
? <span style={{ color: '#FFC76A' }}>{f.value}</span>
: <DropSlot
dropKey={f.slot}
dnd={dnd}
filledId={filled[f.slot]}
filledLabel={filled[f.slot] ? bankById[filled[f.slot]].label : null}
filledKind="value"
onClear={() => setFilled(p => { const n = { ...p }; delete n[f.slot]; return n; })}
placeholder="____"
/>}
{!isLast && <span style={{ color: '#6F8390' }}>,</span>}
</div>
);
})}
<span style={{ color: '#6F8390' }}>{'}'}</span>
</div>
</div>
<div>
<div className="ml-pane__label">Token bank — drag the JSON values, or tap one then tap a slot</div>
<TokenBank tokens={availableBank} dnd={dnd} kind="value" />
</div>
<Feedback {...(feedback || {})} state={feedback?.state} />
</>
);
}
/* ====================================================================
* Exercise: BLOCKS — assemble a snippet by dragging operator/value tokens.
* ==================================================================== */
function BlocksExercise({ level, onResult, onState }) {
const displayBank = useM(() => shuffleForDisplay(level.bank), [level]);
const [filled, setFilled] = useS({}); // slotName → tokenId
const [feedback, setFeedback] = useS(null);
const [perfect, setPerfect] = useS(true);
const slots = useM(() => level.snippet.filter(t => typeof t === 'object' && t.slot).map(t => t.slot), [level]);
const bankById = useM(() => Object.fromEntries(level.bank.map(b => [b.id, b])), [level]);
const allFilled = slots.every(s => filled[s]);
function placeAt(slotKey, tokenId) {
setFilled(prev => {
const next = { ...prev };
for (const k of Object.keys(next)) if (next[k] === tokenId) delete next[k];
next[slotKey] = tokenId;
return next;
});
}
const dnd = useDragDrop((slotKey, tokenId) => placeAt(slotKey, tokenId));
const usedIds = new Set(Object.values(filled));
const availableBank = displayBank.filter(t => !usedIds.has(t.id));
function check() {
let correct = true;
for (const slot of slots) {
const tid = filled[slot];
const tok = tid && bankById[tid];
if (!tok || tok.answer !== slot) correct = false;
}
if (!correct) setPerfect(false);
// Diff for wrong-answer feedback
const correctSnippet = renderSnippet(level.snippet, Object.fromEntries(
slots.map(s => [s, level.bank.find(b => b.answer === s)?.label || '?'])
));
const yourSnippet = renderSnippet(level.snippet, Object.fromEntries(
slots.map(s => [s, filled[s] ? bankById[filled[s]].label : '____'])
));
setFeedback(correct ? {
state: 'correct',
title: 'Query compiles. 1 doc affected.',
message: 'Reads cleanly. Run it!'
} : {
state: 'wrong',
title: 'Almost. Check your operators.',
message: 'Operators start with `$`. Strings need quotes.',
diff: makeDiff(yourSnippet, correctSnippet)
});
onResult && onResult({ correct, perfect: correct && perfect });
}
useE(() => { onState && onState({
ready: allFilled, check,
userState: { filled, bankById },
reset: () => { setFilled({}); setFeedback(null); setPerfect(true); dnd.clear(); }
}); }, [allFilled, filled, perfect]);
return (
<>
<div className="ml-code" style={{ marginBottom: 16 }}>
{renderSnippetReact(level.snippet, filled, bankById, dnd, setFilled)}
</div>
<div className="ml-pane__label">Token bank — drag the missing pieces, or tap one then tap a slot</div>
<TokenBank tokens={availableBank} dnd={dnd} />
<Feedback {...(feedback || {})} state={feedback?.state} />
</>
);
}
function renderSnippetReact(snippet, filled, bankById, dnd, setFilled) {
return snippet.map((piece, i) => {
if (typeof piece === 'string') {
return <React.Fragment key={i}>{piece}</React.Fragment>;
}
const tid = filled[piece.slot];
const tok = tid ? bankById[tid] : null;
return (
<DropSlot
key={i}
dropKey={piece.slot}
dnd={dnd}
filledId={tid}
filledLabel={tok?.label}
filledKind={tok?.kind || 'value'}
onClear={() => setFilled(p => { const n = { ...p }; delete n[piece.slot]; return n; })}
placeholder="____"
/>
);
});
}
function renderSnippet(snippet, filledLabels) {
return snippet.map(p => typeof p === 'string' ? p : (filledLabels[p.slot] ?? '____')).join('');
}
/* ====================================================================
* Exercise: FILL — click a blank, choose from the option list.
* ==================================================================== */
function FillExercise({ level, onResult, onState }) {
const blanks = useM(() => level.snippet.filter(t => typeof t === 'object').map(t => t.blank), [level]);
const displayChoices = useM(() => Object.fromEntries(
Object.entries(level.choices).map(([blank, choice]) => [blank, shuffleForDisplay(choice.options)])
), [level]);
const [filled, setFilled] = useS({});
const [active, setActive] = useS(null);
const [tried, setTried] = useS({}); // blank → set of wrong tokens
const [feedback, setFeedback] = useS(null);
const [perfect, setPerfect] = useS(true);
const allFilled = blanks.every(b => filled[b]);
function choose(blank, value) {
const ans = level.choices[blank].answer;
if (value === ans) {
setFilled(prev => ({ ...prev, [blank]: value }));
setActive(null);
} else {
setTried(prev => ({ ...prev, [blank]: new Set([...(prev[blank] || []), value]) }));
setPerfect(false);
// shake the blank
const el = document.querySelector(`[data-blank="${blank}"]`);
if (el) {
el.setAttribute('data-state', 'wrong');
setTimeout(() => { el.setAttribute('data-state', active === blank ? 'active' : (filled[blank] ? 'filled' : '')); }, 280);
}
}
}
function check() {
const correct = blanks.every(b => filled[b] === level.choices[b].answer);
setFeedback(correct ? {
state: 'correct',
title: 'Compiled.',
message: '1 doc affected. Acknowledged.'
} : {
state: 'wrong',
title: 'Almost.',
message: 'Re-check the highlighted blanks.'
});
onResult && onResult({ correct, perfect: correct && perfect });
}
useE(() => { onState && onState({
ready: allFilled, check,
userState: { filled },
reset: () => { setFilled({}); setTried({}); setActive(null); setFeedback(null); setPerfect(true); }
}); }, [allFilled, filled, perfect]);
// build a flat element list w/ blanks
return (
<>
<div className="ml-code" style={{ marginBottom: 16 }}>
{level.snippet.map((piece, i) => {
if (typeof piece === 'string') return <React.Fragment key={i}>{piece}</React.Fragment>;
const filledVal = filled[piece.blank];
const state = filledVal ? 'filled' : (active === piece.blank ? 'active' : '');
return (
<span
key={i}
className="ml-blank"
data-blank={piece.blank}
data-state={state}
onClick={() => setActive(piece.blank)}
tabIndex={0}
role="button"
aria-label={`blank ${piece.blank}`}
>
{filledVal || '____'}
</span>
);
})}
</div>
{active && (
<div style={{ marginBottom: 16 }}>
<div className="ml-pane__label">Choose for blank · <span style={{ color: 'var(--lg-spring)' }}>{active}</span></div>
<div className="ml-tokenbank">
{displayChoices[active].map(opt => {
const wasTried = (tried[active] || new Set()).has(opt);
return (
<button
key={opt}
className="ml-token"
data-kind={isOperator(opt) ? 'op' : (opt.startsWith('"') ? 'value' : 'value')}
onClick={() => choose(active, opt)}
style={wasTried ? { opacity: 0.45, textDecoration: 'line-through' } : {}}
>
{opt}
</button>
);
})}
</div>
</div>
)}
<Feedback {...(feedback || {})} state={feedback?.state} />
</>
);
}
function isOperator(s) { return typeof s === 'string' && s.startsWith('$'); }
/* ====================================================================
* Exercise: REORDER — drag pipeline stages into the right order.
* ==================================================================== */
function ReorderExercise({ level, onResult, onState }) {
const stageMap = useM(() => Object.fromEntries(level.stages.map(s => [s.id, s])), [level]);
const [order, setOrder] = useS(level.initial);
const [feedback, setFeedback] = useS(null);
const [perfect, setPerfect] = useS(true);
const [lastMoved, setLastMoved] = useS(null);
function moveTo(from, to) {
if (from === to) return;
setOrder(prev => {
const next = [...prev];
const [item] = next.splice(from, 1);
next.splice(to, 0, item);
return next;
});
}
// Drag: insert before/after the hovered stage. Tap: take the tapped stage's position.
const dnd = useDragDrop((targetId, fromId, { half, via }) => {
if (targetId === fromId) return;
const fromIdx = order.indexOf(fromId);
const targetIdx = order.indexOf(targetId);
if (fromIdx < 0 || targetIdx < 0) return;
let toIdx = targetIdx;
if (via === 'drag') {
toIdx = targetIdx + (half === 'bot' ? 1 : 0);
if (fromIdx < toIdx) toIdx--;
}
moveTo(fromIdx, toIdx);
setLastMoved({ id: fromId, n: Date.now() });
});
function check() {
const correct = order.every((id, i) => stageMap[id].correct === i);
if (!correct) setPerfect(false);
setFeedback(correct ? {
state: 'correct',
title: 'Pipeline runs.',
message: 'Stages are in the right order.'
} : {
state: 'wrong',
title: 'That pipeline is out of order.',
message: 'Remember: $match before $group keeps the planner happy.'
});
onResult && onResult({ correct, perfect: correct && perfect });
}
useE(() => { onState && onState({
ready: true, check,
userState: { order, stageMap },
reset: () => { setOrder(level.initial); setFeedback(null); setPerfect(true); dnd.clear(); setLastMoved(null); }
}); }, [order, perfect]);
// keyboard support: focus + arrow keys
function bumpKey(idx, dir) {
const to = idx + dir;
if (to < 0 || to >= order.length) return;
moveTo(idx, to);
}
function activateStage(id) {
if (dnd.wasDrag()) return;
if (dnd.selected && dnd.selected !== id) { dnd.placeSelected(id); return; }
dnd.select(id);
}
// Briefly pulse the stage that just moved so the change is easy to spot.
const listRef = useR(null);
useE(() => {
if (!lastMoved || !listRef.current) return;
const el = listRef.current.querySelector(`[data-stage-id="${CSS.escape(lastMoved.id)}"]`);
if (!el || !el.animate) return;
if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
el.animate([
{ transform: 'scale(1.04)', boxShadow: '0 0 0 3px rgba(0,237,100,0.45)' },
{ transform: 'scale(1)', boxShadow: '0 0 0 0 rgba(0,237,100,0)' }
], { duration: 360, easing: 'cubic-bezier(0.2, 0.6, 0.2, 1)' });
}, [lastMoved]);
return (
<>
<div className="ml-pane__label">
{dnd.selected
? 'Now tap the position to move it to'
: 'Drag stages into order, or tap one stage then tap where it should go'}
</div>
<div className="ml-reorder" ref={listRef} role="list" aria-label="pipeline stages" data-has-selection={!!dnd.selected}>
{order.map((id, idx) => {
const stage = stageMap[id];
const isOver = !!(dnd.over && dnd.over.key === id && dnd.dragId !== id);
const isSelected = dnd.selected === id;
const isDragging = dnd.dragId === id;
return (
<div
key={id}
data-stage-id={id}
className={`ml-stage${isDragging ? ' is-dragging' : ''}${isSelected ? ' is-selected' : ''}${
isOver && dnd.over.half === 'top' ? ' is-over-top' :
isOver && dnd.over.half === 'bot' ? ' is-over-bot' : ''
}`}
{...dnd.sourceProps(id)}
{...dnd.targetAttrs(id)}
tabIndex={0}
role="listitem"
aria-selected={isSelected}
aria-label={`Stage ${idx + 1}: ${stage.code}${isSelected ? ', selected' : ''}`}
onClick={() => activateStage(id)}
onKeyDown={(e) => {
if (e.key === 'ArrowUp') { e.preventDefault(); bumpKey(idx, -1); }
if (e.key === 'ArrowDown') { e.preventDefault(); bumpKey(idx, +1); }
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); activateStage(id); }
}}
>
<div className="ml-stage__num">{idx + 1}</div>
<div className="ml-stage__body">
<code>{stage.code}</code>
<small>{stage.sub}</small>
</div>
<Icon name="Drag" size={14} className="ml-stage__drag" color="var(--ml-text-faint)" />
</div>
);
})}
</div>
<Feedback {...(feedback || {})} state={feedback?.state} />
</>
);
}
/* ====================================================================
* Exercise: INDEX — drop index types onto collection fields.
* ==================================================================== */
function IndexExercise({ level, onResult, onState }) {
const displayBank = useM(() => shuffleForDisplay(level.bank), [level]);
const [drops, setDrops] = useS({}); // fieldName → indexId
const [feedback, setFeedback] = useS(null);
const [perfect, setPerfect] = useS(true);
const bankById = useM(() => Object.fromEntries(level.bank.map(b => [b.id, b])), [level]);
const allFilled = level.fields.every(f => drops[f.name]);
// Each index type is used once, so placing it moves it off any other field.
function place(fieldName, idxId) {
setDrops(prev => {
const next = { ...prev };
for (const k of Object.keys(next)) if (next[k] === idxId) delete next[k];
next[fieldName] = idxId;
return next;
});
}
const dnd = useDragDrop((fieldName, idxId) => place(fieldName, idxId));
const usedIds = new Set(Object.values(drops));
const availableBank = displayBank.filter(b => !usedIds.has(b.id));
function check() {
const correct = level.fields.every(f => drops[f.name] === f.need);
if (!correct) setPerfect(false);
setFeedback(correct ? {
state: 'correct',
title: 'explain() shows IXSCAN.',
message: 'IXSCAN means the query used an index. No more COLLSCANs (full collection scans), so reads got fast.'
} : {
state: 'wrong',
title: 'One of those is a COLLSCAN (full collection scan) waiting to happen.',
message: 'Low-cardinality bool fields rarely pay back the write cost. Combine filter+sort fields into a compound index.'
});
onResult && onResult({ correct, perfect: correct && perfect });
}
useE(() => { onState && onState({
ready: allFilled, check,
userState: { drops, bankById },
reset: () => { setDrops({}); setFeedback(null); setPerfect(true); dnd.clear(); }
}); }, [allFilled, drops, perfect]);
return (
<>
<div className="ml-collection">
<div className="ml-collection__name">db.{level.collection}</div>
{level.fields.map(f => (
<FieldDrop
key={f.name}
field={f}
dnd={dnd}
filledId={drops[f.name]}
label={drops[f.name] ? bankById[drops[f.name]].label : null}
onClear={() => setDrops(p => { const n = { ...p }; delete n[f.name]; return n; })}
/>
))}
</div>
<div style={{ marginTop: 16 }}>
<div className="ml-pane__label">Index types — drag onto each field, or tap an index then tap a row</div>
<TokenBank tokens={availableBank} dnd={dnd} kind="index" />
</div>
<Feedback {...(feedback || {})} state={feedback?.state} />
</>
);
}
/* A collection field row; the whole row is the drop target for an index type. */
function FieldDrop({ field, dnd, filledId, label, onClear }) {
const dropKey = field.name;
const isOver = !!(dnd.over && dnd.over.key === dropKey);
const awaiting = !filledId && !!(dnd.selected || dnd.dragId);
function activate() {
if (dnd.wasDrag()) return;
if (dnd.placeSelected(dropKey)) return;
if (filledId) onClear();
}
return (
<div
className="ml-field-row"
{...dnd.targetAttrs(dropKey)}
data-over={isOver}
data-awaiting={awaiting}
onClick={activate}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); activate(); }
}}
role="button"
tabIndex={0}
aria-label={`${field.name}: ${label
? `${label}, ${dnd.selected ? 'tap to replace' : 'tap to clear'}`
: (dnd.selected ? 'tap to place the selected index' : 'no index yet')}`}
>
<div>
<span className="ml-field-row__name">{field.name}</span>
<span style={{ color: '#6F8390', margin: '0 8px' }}>·</span>
<span className="ml-field-row__type">{field.type}</span>
<div style={{ fontFamily: 'var(--ml-font-sans)', fontSize: 11.5, color: 'var(--ml-text-faint)' }}>
used for {field.used}
</div>
</div>
<div className="ml-field-row__drop" data-over={isOver} data-filled={!!filledId}>
{label
? <span key={filledId} className="ml-field-row__placed">{label}</span>
: 'Drop an index'}
</div>
</div>
);
}
/* ====================================================================
* Live previews per exercise kind — rendered by parent in the right pane.
* ==================================================================== */
function LevelPreview({ level, userState, resultState }) {
if (!resultState?.correct) {
return <div className="ml-empty">Submit a correct answer to run the sandbox and reveal results.</div>;
}
if (!userState) return <div className="ml-empty">Result pending — submit a correct answer to run the sandbox.</div>;
switch (level.kind) {
case 'shape': return <ShapePreview level={level} {...userState} />;
case 'blocks': return <BlocksPreview level={level} {...userState} />;
case 'fill': return <FillPreview level={level} {...userState} />;
case 'reorder': return <ReorderPreview level={level} {...userState} />;
case 'index': return <IndexPreview level={level} {...userState} />;
default: return <div className="ml-empty">No preview.</div>;
}
}
function ShapePreview({ level, filled, bankById }) {
const allFilled = level.skeleton.filter(f => f.type === 'slot').every(f => filled[f.slot]);
if (!allFilled) {
return <div className="ml-empty">Fill the document to see how Mongo will store it.</div>;
}
const correct = Object.entries(level.answer).every(([k, v]) => filled[k] === v);
return <>
<FakeDocs docs={[{
_id: 'ObjectId("64e…")',
...Object.fromEntries(
level.skeleton.filter(f => f.type === 'slot').map(f =>
[f.key, bankById[filled[f.slot]]?.label.replace(/^"|"$/g, '') || '?'])
)
}]} note={correct ? 'acknowledged: true' : 'type warning — numbers should not be strings'} />
</>;
}
function BlocksPreview({ level, filled, bankById }) {
const fl = Object.fromEntries(Object.entries(filled).map(([k, v]) => [k, bankById[v]?.label]));
const completeAll = level.snippet.filter(p => typeof p === 'object').every(p => fl[p.slot]);
if (completeAll) {
const rendered = renderSnippet(level.snippet, fl);
const collection = inferCollectionFromText(rendered, level);
// Stream / change-stream preview
const streamPreview = streamPreviewForLevel(level);
if (streamPreview) {
return <FakeDocs docs={streamPreview.docs} note={streamPreview.note} />;
}
if (/\.insertOne\s*\(/.test(rendered)) {
return <FakeDocs docs={[docFromInsertedSnippet(rendered, collection, level)]} note="acknowledged: true · insertedId: ObjectId(...)" />;
}
const note = rendered.includes('$search')
? `2 ${humanizeCollection(collection)} matched by Atlas Search`
: rendered.includes('$sort') || rendered.includes('$limit')
? `${Math.min(5, inferLimit(rendered) || 3)} ${humanizeCollection(collection)} · sorted and limited`
: `3 ${humanizeCollection(collection)} matched`;
return <FakeDocs docs={sampleDocsForLevel(level, collection, inferLimit(rendered) || 3, { queryText: rendered })} note={note} />;
}
return <div className="ml-empty">Fill the blanks to see the query result.</div>;
}
function FillPreview({ level, filled }) {
const choices = level.choices || {};
const filledValues = filled || {};
const allKnown = Object.keys(choices).length > 0 &&
Object.keys(choices).every(k => filledValues[k] === choices[k].answer);
if (!allKnown) return <div className="ml-empty">Fill all blanks to see the live result.</div>;
const rendered = renderFillSnippet(level, filledValues);
const collection = inferCollectionFromText(rendered, level);
const streamPreview = streamPreviewForLevel(level);
if (streamPreview) {
return <FakeDocs docs={streamPreview.docs} note={streamPreview.note} />;
}
if (/\.updateOne\s*\(/.test(rendered)) {
const field = stripQuotes(choices.field?.answer || 'updatedField');
const val = parsePreviewValue(choices.val?.answer || 'true');
const op = choices.op?.answer || '$set';
const value = op === '$push' || op === '$addToSet' ? [val] : val;
return <FakeDocs docs={[{ _id: '...', [field]: value }]} note="matchedCount: 1 · modifiedCount: 1" highlight={field} />;
}
if (/\.deleteOne\s*\(/.test(rendered)) {
return <FakeDocs docs={[]} note={`deletedCount: 1 · removed one ${singularize(collection)} matching the filter`} />;
}
if (/\.createIndex\s*\(/.test(rendered)) {
const key = rendered.match(/\{\s*([\w.]+)\s*:\s*1\s*\}/)?.[1] || 'field';
const ttl = choices.sec?.answer || 'configured';
return <pre className="mono" style={{ color: '#9DD6B5', margin: 0 }}>
{`✓ index built
ns: app.${collection}
key: { ${key}: 1 }
expireAfterSeconds: ${ttl}
background: true`}
</pre>;
}
if (/\.explain\s*\(/.test(rendered)) {
const indexedFields = extractProjectionFields(rendered).join(', ') || collection;
return (
<div className="ml-explain">
<div className="ml-explain__col">
<h5>Docs examined</h5>
<div className="stat">0</div>
<div className="sub">covered query · index only</div>
</div>
<div className="ml-explain__col">
<h5>Keys examined</h5>
<div className="stat">1</div>
<div className="sub">{`${indexedFields} · 0.4 ms`}</div>
</div>
</div>
);
}
if (rendered.includes('$vectorSearch')) {
return <FakeDocs docs={sampleDocsForLevel(level, collection, 5, { vector: true, queryText: rendered })} note="5 nearest neighbors · cosine similarity" />;
}
if (/Trigger config/.test(rendered)) {
const col = stripQuotes(choices.col?.answer || collection);
const evt = stripQuotes(choices.evt?.answer || 'change');
const fn = stripQuotes(choices.fn?.answer || 'handler');
return <pre className="mono" style={{ color: '#9DD6B5', margin: 0 }}>
{`✓ trigger created
app.${col} · on${capitalize(evt)} → ${fn}()
enabled: true`}
</pre>;
}
return <FakeDocs docs={sampleDocsForLevel(level, collection, 3, { queryText: rendered })} note={`3 ${humanizeCollection(collection)} matched`} />;
}
function ReorderPreview({ level, order, stageMap }) {
const currentOrder = order || [];
const stagesById = stageMap || {};
const inOrder = currentOrder.length > 0 && currentOrder.every((id, i) => stagesById[id]?.correct === i);
if (!inOrder) return <div className="ml-empty">Pipeline isn't in order yet — preview waiting.</div>;
const pipelineText = level.stages.map(s => s.code).join('\n');
const collection = inferCollectionFromText(pipelineText, level);
const solved = <SolvedQuery level={level} />;
// Index-field reorder (ESR): the "result" is the index itself plus a plan summary.
if (isIndexReorder(level)) {
return (
<>
{solved}
<div className="ml-explain">
<div className="ml-explain__col">
<h5>Winning plan</h5>
<div className="stat">IXSCAN</div>
<div className="sub">filter, sort and range all served by one index</div>
<div className="ml-explain__gloss">Index scan: MongoDB walks the index instead of reading every document, and returns rows already sorted.</div>
</div>
</div>
</>
);
}
const streamPreview = streamPreviewForLevel(level);
if (streamPreview) {
return <>{solved}<FakeDocs docs={streamPreview.docs} note={streamPreview.note} /></>;
}