Skip to main content

logicaffeine_web/ui/pages/
learn.rs

1//! The Learn Logic page: a roadmap through the curriculum, one lesson at a time.
2//!
3//! The curriculum (`assets/curriculum`, via [`ContentEngine::shared`]) is laid out as a route: four
4//! eras, a stop for each module, a stop for each lesson. A lesson is a short teaching, two examples
5//! and one question. Answering it right, or asking to see the answer after a try, lets the learner
6//! move on; "More examples" and "More practice" are there for anyone who wants them. The rules live
7//! in [`crate::learn_state`]; this file renders them and records progress to [`UserProgress`].
8//!
9//! # Layout
10//!
11//! - **Hero**: the page title and how many lessons are done
12//! - **Lesson**: the open lesson, its examples and its question
13//! - **Roadmap**: every era, module and lesson; beside the lesson on wide screens, after it on phones
14//!
15//! # Route
16//!
17//! Accessed via [`Route::Learn`](crate::ui::router::Route::Learn). `/learn#<module-id>` opens that
18//! module's first lesson not yet done.
19
20use crate::content::{ContentBlock, ContentEngine, ExerciseConfig, LessonExample, LessonQuestion};
21use crate::generator::{AnswerType, Challenge, Generator};
22use crate::grader::{check_answer, check_readings};
23use crate::learn_state::{Journey, LessonQuiz, PracticeSession, QuizState};
24use crate::progress::UserProgress;
25use crate::struggle::StruggleDetector;
26use crate::ui::components::footer::Footer;
27use crate::ui::components::icon::{Icon, IconSize, IconVariant};
28use crate::ui::components::learn_roadmap::LearnRoadmap;
29use crate::ui::components::lexicon_gate::LexiconGate;
30use crate::ui::components::main_nav::{ActivePage, MainNav};
31use crate::ui::components::symbol_pad::SymbolPad;
32use crate::ui::inline_markup::inline_markup_html;
33use crate::ui::seo::{
34    breadcrumb_schema, course_schema, organization_schema, pages as seo_pages, BreadcrumbItem,
35    JsonLdMultiple, PageHead,
36};
37use dioxus::prelude::*;
38#[cfg(all(feature = "split", target_arch = "wasm32"))]
39use dioxus::wasm_split;
40use rand::rngs::StdRng;
41use rand::SeedableRng;
42
43const LEARN_STYLE: &str = r#"
44.learn-page {
45    min-height: 100vh;
46    color: var(--text-primary);
47    background:
48        radial-gradient(900px 480px at 85% -160px, rgba(var(--accent-secondary-rgb), 0.12), transparent 60%),
49        linear-gradient(180deg, var(--bg-gradient-start), var(--bg-gradient-mid) 55%, var(--bg-gradient-end));
50    font-family: var(--font-sans);
51}
52
53/* Hero */
54.learn-hero {
55    max-width: 1180px;
56    margin: 0 auto;
57    padding: 40px 16px 28px;
58}
59
60.learn-hero h1 {
61    font-size: var(--font-display-md);
62    font-weight: 800;
63    letter-spacing: -0.02em;
64    line-height: 1.1;
65    margin: 0 0 12px;
66}
67
68.learn-intro {
69    max-width: 60ch;
70    margin: 0;
71    font-size: var(--font-body-lg);
72    line-height: 1.6;
73    color: var(--text-secondary);
74}
75
76.learn-progress {
77    display: flex;
78    align-items: center;
79    gap: var(--spacing-md);
80    max-width: 420px;
81    margin: 20px 0 0;
82    font-size: var(--font-body-sm);
83    color: var(--text-tertiary);
84}
85
86.learn-progress-bar {
87    flex: 1;
88    height: 4px;
89    border-radius: 2px;
90    background: rgba(255, 255, 255, 0.08);
91    overflow: hidden;
92}
93
94.learn-progress-fill {
95    height: 100%;
96    background: var(--accent-secondary);
97    border-radius: 2px;
98}
99
100/* Layout: the lesson first; on wide screens the roadmap sits to its left. */
101.learn-layout {
102    max-width: 1180px;
103    margin: 0 auto;
104    padding: 0 16px 80px;
105    display: grid;
106    grid-template-columns: minmax(0, 1fr);
107    gap: 48px;
108}
109
110.learn-main {
111    min-width: 0;
112    max-width: 720px;
113}
114
115.learn-to-roadmap {
116    display: inline-flex;
117    align-items: center;
118    min-height: 44px;
119    margin-top: var(--spacing-xl);
120    padding: 0 14px;
121    border: 1px solid rgba(255, 255, 255, 0.14);
122    border-radius: var(--radius-full);
123    background: none;
124    color: var(--text-secondary);
125    font: inherit;
126    font-size: var(--font-body-sm);
127    cursor: pointer;
128}
129
130@media (min-width: 1024px) {
131    .learn-hero {
132        padding: 56px 24px 36px;
133    }
134    .learn-layout {
135        grid-template-columns: 300px minmax(0, 1fr);
136        grid-template-areas: "roadmap lesson";
137        align-items: start;
138        padding: 0 24px 96px;
139    }
140    .learn-main {
141        grid-area: lesson;
142    }
143    .learn-roadmap {
144        grid-area: roadmap;
145        position: sticky;
146        top: 112px;
147        max-height: calc(100vh - 128px);
148        overflow-y: auto;
149        padding-right: var(--spacing-sm);
150    }
151    .learn-to-roadmap {
152        display: none;
153    }
154}
155
156/* A lesson */
157/* Clear of the sticky site nav when a link or the roadmap scrolls a lesson into view. */
158.lesson {
159    scroll-margin-top: 112px;
160}
161
162.lesson-crumb {
163    margin: 0 0 6px;
164    font-size: var(--font-caption-md);
165    color: var(--text-tertiary);
166}
167
168.lesson-title {
169    margin: 0 0 20px;
170    font-size: var(--font-heading-lg);
171    font-weight: 800;
172    line-height: 1.25;
173    letter-spacing: -0.01em;
174}
175
176.lesson-number {
177    margin-right: 0.4em;
178    font-variant-numeric: tabular-nums;
179    color: var(--accent-primary);
180}
181
182.lesson-teaching p {
183    max-width: 65ch;
184    margin: 0 0 14px;
185    font-size: var(--font-body-lg);
186    line-height: 1.7;
187    color: var(--text-secondary);
188}
189
190.lesson-teaching strong {
191    color: var(--text-primary);
192}
193
194.lesson-definition {
195    margin: 0 0 14px;
196    padding: 2px 0 2px 14px;
197    border-left: 2px solid rgba(var(--accent-secondary-rgb), 0.55);
198}
199
200.lesson-definition p {
201    margin: 0;
202}
203
204.lesson-definition .lesson-term {
205    color: var(--text-primary);
206    font-weight: 700;
207}
208
209.lesson-table {
210    margin: 4px 0 18px;
211}
212
213.lesson-table-title {
214    margin: 0 0 8px;
215    font-weight: 700;
216    color: var(--text-primary);
217}
218
219.lesson-table-row {
220    display: grid;
221    grid-template-columns: minmax(0, 11em) minmax(0, 1fr);
222    gap: 4px 16px;
223    padding: 8px 0;
224    border-top: 1px solid rgba(255, 255, 255, 0.07);
225}
226
227.lesson-table-key {
228    font-family: var(--font-mono);
229    color: var(--accent-primary);
230    overflow-wrap: anywhere;
231}
232
233.lesson-table-name {
234    color: var(--text-primary);
235    font-weight: 600;
236}
237
238.lesson-table-meaning {
239    grid-column: 2;
240    color: var(--text-secondary);
241    font-size: var(--font-body-sm);
242    line-height: 1.5;
243}
244
245.lesson-heading {
246    margin: 32px 0 12px;
247    font-size: var(--font-heading-sm);
248    font-weight: 700;
249}
250
251.lesson-example {
252    margin: 0 0 16px;
253    padding: 4px 0 4px 16px;
254    border-left: 2px solid rgba(var(--accent-primary-rgb), 0.4);
255}
256
257.lesson-example-sentence,
258.lesson-example-title {
259    margin: 0 0 8px;
260    font-size: var(--font-body-lg);
261    color: var(--text-primary);
262}
263
264.lesson-example-title {
265    font-weight: 600;
266}
267
268.lesson-formula {
269    display: block;
270    font-family: var(--font-mono);
271    font-size: 17px;
272    line-height: 1.55;
273    color: var(--accent-primary);
274    white-space: pre-wrap;
275    overflow-wrap: anywhere;
276}
277
278.lesson-example-lines {
279    margin: 0;
280    padding-left: 1.1em;
281    color: var(--text-secondary);
282    line-height: 1.6;
283}
284
285.lesson-example-conclusion {
286    margin: 6px 0 0;
287    color: var(--text-primary);
288    font-weight: 600;
289    line-height: 1.5;
290}
291
292.lesson-example-note {
293    max-width: 62ch;
294    margin: 8px 0 0;
295    font-size: var(--font-body-sm);
296    line-height: 1.55;
297    color: var(--text-tertiary);
298}
299
300.lesson-toggle {
301    display: inline-flex;
302    align-items: center;
303    gap: 8px;
304    min-height: 44px;
305    padding: 0 16px;
306    border: 1px solid rgba(255, 255, 255, 0.14);
307    border-radius: var(--radius-full);
308    background: none;
309    color: var(--text-secondary);
310    font: inherit;
311    font-size: var(--font-body-sm);
312    cursor: pointer;
313}
314
315/* A chevron marks the toggles that open and close something; Skip is a plain button. */
316.lesson-toggle[aria-expanded]::after {
317    content: "";
318    width: 7px;
319    height: 7px;
320    border-right: 2px solid currentColor;
321    border-bottom: 2px solid currentColor;
322    transform: rotate(45deg) translateY(-2px);
323}
324
325.lesson-toggle[aria-expanded="true"]::after {
326    transform: rotate(-135deg) translateY(-1px);
327}
328
329.lesson-toggle:hover {
330    color: var(--text-primary);
331    border-color: rgba(255, 255, 255, 0.26);
332}
333
334.lesson-extra {
335    margin-top: 16px;
336}
337
338/* The question: the one block that asks something of the learner. */
339.lesson-question {
340    margin-top: 36px;
341    padding: 20px 16px;
342    border-radius: var(--radius-lg);
343    background: rgba(var(--accent-secondary-rgb), 0.06);
344    border: 1px solid rgba(var(--accent-secondary-rgb), 0.24);
345}
346
347.lesson-question .lesson-heading {
348    margin-top: 0;
349}
350
351.lesson-question-prompt {
352    margin: 0 0 6px;
353    color: var(--text-secondary);
354    line-height: 1.55;
355}
356
357.lesson-question-sentence {
358    margin: 0 0 14px;
359    font-size: 20px;
360    font-weight: 600;
361    line-height: 1.4;
362    color: var(--text-primary);
363}
364
365.lesson-answer-row {
366    display: flex;
367    flex-wrap: wrap;
368    gap: var(--spacing-sm);
369}
370
371.lesson-input {
372    flex: 1 1 220px;
373    min-width: 0;
374    height: 48px;
375    padding: 0 14px;
376    border: 1px solid rgba(255, 255, 255, 0.18);
377    border-radius: var(--radius-md);
378    background: rgba(255, 255, 255, 0.05);
379    color: var(--text-primary);
380    font-family: var(--font-mono);
381    font-size: 17px;
382}
383
384.lesson-input:focus {
385    outline: 2px solid var(--accent-primary);
386    outline-offset: 1px;
387}
388
389.lesson-input.correct {
390    border-color: var(--color-success);
391}
392
393.lesson-input.wrong {
394    border-color: var(--color-error);
395}
396
397.lesson-check,
398.lesson-next {
399    min-height: 48px;
400    padding: 0 22px;
401    border: none;
402    border-radius: var(--radius-md);
403    background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
404    color: var(--bg-gradient-start);
405    font: inherit;
406    font-weight: 700;
407    cursor: pointer;
408}
409
410.lesson-check:disabled {
411    opacity: 0.5;
412    cursor: default;
413}
414
415.lesson-check:focus-visible,
416.lesson-next:focus-visible,
417.lesson-toggle:focus-visible,
418.lesson-option:focus-visible,
419.lesson-show-answer:focus-visible,
420.learn-to-roadmap:focus-visible {
421    outline: 2px solid var(--accent-primary);
422    outline-offset: 2px;
423}
424
425.lesson-options {
426    display: grid;
427    gap: var(--spacing-sm);
428}
429
430.lesson-option {
431    min-height: 48px;
432    padding: 12px 16px;
433    border: 1px solid rgba(255, 255, 255, 0.14);
434    border-radius: var(--radius-md);
435    background: rgba(255, 255, 255, 0.03);
436    color: var(--text-secondary);
437    font: inherit;
438    text-align: left;
439    line-height: 1.45;
440    cursor: pointer;
441}
442
443.lesson-option:hover:not(:disabled) {
444    border-color: rgba(var(--accent-primary-rgb), 0.5);
445    color: var(--text-primary);
446}
447
448.lesson-option:disabled {
449    cursor: default;
450}
451
452.lesson-option.wrong {
453    border-color: var(--color-error);
454    color: var(--color-error);
455}
456
457.lesson-option.correct {
458    border-color: var(--color-success);
459    color: var(--color-success);
460}
461
462.lesson-verdict {
463    margin: 14px 0 0;
464    font-weight: 600;
465}
466
467.lesson-verdict.correct {
468    color: var(--color-success);
469}
470
471.lesson-verdict.wrong {
472    color: var(--color-error);
473}
474
475.lesson-hint {
476    display: grid;
477    grid-template-columns: auto minmax(0, 1fr);
478    gap: 10px;
479    align-items: start;
480    margin-top: 12px;
481    padding: 12px 14px;
482    border-left: 3px solid var(--accent-secondary);
483    border-radius: 0 var(--radius-md) var(--radius-md) 0;
484    background: rgba(var(--accent-secondary-rgb), 0.08);
485    color: var(--text-secondary);
486    line-height: 1.6;
487}
488
489.lesson-hint p {
490    margin: 0;
491}
492
493.lesson-hint p + p {
494    margin-top: 6px;
495}
496
497.lesson-show-answer {
498    min-height: 44px;
499    margin-top: 12px;
500    padding: 0 16px;
501    border: 1px solid rgba(255, 255, 255, 0.18);
502    border-radius: var(--radius-md);
503    background: none;
504    color: var(--text-secondary);
505    font: inherit;
506    cursor: pointer;
507}
508
509.lesson-answer {
510    margin-top: 16px;
511    padding-top: 14px;
512    border-top: 1px solid rgba(255, 255, 255, 0.08);
513}
514
515.lesson-answer-label {
516    margin: 0 0 6px;
517    font-size: var(--font-caption-md);
518    color: var(--text-tertiary);
519}
520
521.lesson-answer-option {
522    margin: 0;
523    color: var(--text-primary);
524    font-weight: 600;
525}
526
527.lesson-explanation {
528    margin: 10px 0 0;
529    color: var(--text-secondary);
530    line-height: 1.6;
531}
532
533.lesson-next {
534    margin-top: 16px;
535}
536
537.lesson-practice {
538    margin-top: 28px;
539}
540
541/* Practice */
542.practice {
543    margin-top: 16px;
544}
545
546.practice-progress {
547    margin: 0 0 10px;
548    font-size: var(--font-caption-md);
549    color: var(--text-tertiary);
550}
551
552.practice-card {
553    padding: 18px 16px;
554    border-radius: var(--radius-lg);
555    border: 1px solid rgba(255, 255, 255, 0.1);
556    background: rgba(255, 255, 255, 0.02);
557}
558
559.practice-prompt {
560    margin: 0 0 6px;
561    color: var(--text-tertiary);
562    font-size: var(--font-body-sm);
563}
564
565.practice-sentence {
566    margin: 0 0 14px;
567    font-size: var(--font-body-lg);
568    font-weight: 600;
569    line-height: 1.45;
570}
571
572.practice-options {
573    display: grid;
574    gap: var(--spacing-sm);
575}
576
577.practice-readings {
578    display: grid;
579    gap: var(--spacing-sm);
580}
581
582.practice-readings label {
583    font-size: var(--font-caption-md);
584    color: var(--text-tertiary);
585}
586
587.practice-actions {
588    display: flex;
589    flex-wrap: wrap;
590    gap: var(--spacing-sm);
591    margin-top: 14px;
592}
593
594.practice-key {
595    display: block;
596    margin: 6px 0;
597    font-family: var(--font-mono);
598    color: var(--accent-primary);
599    white-space: pre-wrap;
600    overflow-wrap: anywhere;
601}
602
603@media (min-width: 640px) {
604    .lesson-question {
605        padding: 24px;
606    }
607    .practice-card {
608        padding: 20px 22px;
609    }
610}
611
612@media (prefers-reduced-motion: reduce) {
613    .learn-page * {
614        transition: none !important;
615        animation: none !important;
616    }
617}
618"#;
619
620// ---------------------------------------------------------------------------------------
621// Browser glue: scrolling and the URL fragment. `<body>` is the scroll container site-wide,
622// so nothing here reads or writes `window.scrollY`.
623// ---------------------------------------------------------------------------------------
624
625/// Bring the element with `id` to the top of the page (under the nav), waiting for it to exist.
626fn scroll_to(id: &'static str) {
627    #[cfg(target_arch = "wasm32")]
628    wasm_bindgen_futures::spawn_local(async move {
629        for _ in 0..30 {
630            gloo_timers::future::TimeoutFuture::new(16).await;
631            let Some(window) = web_sys::window() else {
632                return;
633            };
634            let Some(element) = window.document().and_then(|d| d.get_element_by_id(id)) else {
635                continue;
636            };
637            let reduced = window
638                .match_media("(prefers-reduced-motion: reduce)")
639                .ok()
640                .flatten()
641                .is_some_and(|m| m.matches());
642            let options = web_sys::ScrollIntoViewOptions::new();
643            options.set_behavior(if reduced {
644                web_sys::ScrollBehavior::Instant
645            } else {
646                web_sys::ScrollBehavior::Smooth
647            });
648            options.set_block(web_sys::ScrollLogicalPosition::Start);
649            element.scroll_into_view_with_scroll_into_view_options(&options);
650            return;
651        }
652    });
653    #[cfg(not(target_arch = "wasm32"))]
654    let _ = id;
655}
656
657/// Record the open lesson's module in the address bar without adding a history entry.
658fn set_fragment(module: &str) {
659    #[cfg(target_arch = "wasm32")]
660    if let Some(history) = web_sys::window().and_then(|w| w.history().ok()) {
661        let _ = history.replace_state_with_url(
662            &wasm_bindgen::JsValue::NULL,
663            "",
664            Some(&format!("#{module}")),
665        );
666    }
667    #[cfg(not(target_arch = "wasm32"))]
668    let _ = module;
669}
670
671fn new_seed() -> u64 {
672    #[cfg(target_arch = "wasm32")]
673    {
674        js_sys::Date::now() as u64
675    }
676    #[cfg(not(target_arch = "wasm32"))]
677    {
678        42
679    }
680}
681
682/// Every lesson id, in roadmap order.
683fn lesson_order() -> Vec<String> {
684    ContentEngine::shared()
685        .lessons()
686        .iter()
687        .map(|l| l.section.id.clone())
688        .collect()
689}
690
691/// Change where the learner stands on the roadmap, and save it.
692fn steer(mut progress: Signal<UserProgress>, change: impl FnOnce(&mut Journey)) {
693    let mut journey = {
694        let p = progress.peek();
695        Journey::new(
696            lesson_order(),
697            p.lessons.iter().cloned(),
698            p.open_lesson.as_deref(),
699        )
700    };
701    change(&mut journey);
702    let mut p = progress.write();
703    p.lessons = journey.done_ids().map(str::to_string).collect();
704    p.open_lesson = journey.open().map(str::to_string);
705    p.save();
706}
707
708/// The module a lesson belongs to.
709fn module_of(lesson: &str) -> Option<String> {
710    ContentEngine::shared()
711        .lesson(lesson)
712        .map(|l| l.module.meta.id.clone())
713}
714
715// ---------------------------------------------------------------------------------------
716// The page
717// ---------------------------------------------------------------------------------------
718
719#[component(lazy)]
720pub fn Learn(module: String) -> Element {
721    let progress = use_context_provider(|| Signal::new(UserProgress::load()));
722
723    // `/learn#<module-id>` opens that module at its first lesson not done, unless the lesson
724    // already open belongs to it; on arrival and on any later link to one.
725    use_effect(use_reactive!(|module| {
726        let Some(found) = ContentEngine::shared()
727            .eras()
728            .iter()
729            .flat_map(|e| e.modules.iter())
730            .find(|m| m.meta.id == module)
731        else {
732            return;
733        };
734        let ids: Vec<&str> = found.sections.iter().map(|s| s.id.as_str()).collect();
735        steer(progress, |journey| {
736            if !journey.open().is_some_and(|open| ids.contains(&open)) {
737                journey.open_first_unfinished(&ids);
738            }
739        });
740        scroll_to("lesson");
741    }));
742
743    let journey = {
744        let p = progress.read();
745        Journey::new(
746            lesson_order(),
747            p.lessons.iter().cloned(),
748            p.open_lesson.as_deref(),
749        )
750    };
751    let open = journey.open().map(str::to_string);
752    let done: Vec<String> = journey.done_ids().map(str::to_string).collect();
753    let (finished, total) = (journey.done_count(), journey.len());
754    let percent = if total == 0 {
755        0
756    } else {
757        finished * 100 / total
758    };
759    let count = if journey.is_finished() {
760        format!("All {total} lessons done")
761    } else {
762        format!("{finished} of {total} lessons done")
763    };
764
765    let breadcrumbs = vec![
766        BreadcrumbItem {
767            name: "Home",
768            path: "/",
769        },
770        BreadcrumbItem {
771            name: "Learn",
772            path: "/learn",
773        },
774    ];
775    let schemas = vec![
776        organization_schema(),
777        course_schema(),
778        breadcrumb_schema(&breadcrumbs),
779    ];
780
781    rsx! {
782        PageHead {
783            title: seo_pages::LEARN.title,
784            description: seo_pages::LEARN.description,
785            canonical_path: seo_pages::LEARN.canonical_path,
786        }
787        style { "{LEARN_STYLE}" }
788        JsonLdMultiple { schemas }
789
790        div { class: "learn-page",
791            MainNav { active: ActivePage::Learn, subtitle: Some("Master formal reasoning") }
792
793            header { class: "learn-hero",
794                h1 { "Learn Logic" }
795                p { class: "learn-intro",
796                    "Learn to read and write formal logic, one short lesson at a time. Each lesson shows two examples and asks one question. Answer it to move on."
797                }
798                p { class: "learn-progress",
799                    span { "{count}" }
800                    span { class: "learn-progress-bar", aria_hidden: "true",
801                        span { class: "learn-progress-fill", style: "width: {percent}%" }
802                    }
803                }
804            }
805
806            div { class: "learn-layout",
807                main { class: "learn-main",
808                    if let Some(id) = open.clone() {
809                        LessonPanel {
810                            key: "{id}",
811                            lesson: id.clone(),
812                            done: journey.is_done(&id),
813                            on_next: move |_| {
814                                steer(progress, |journey| {
815                                    journey.finish();
816                                    journey.advance();
817                                });
818                                if let Some(module) = progress.peek().open_lesson.as_deref().and_then(module_of) {
819                                    set_fragment(&module);
820                                }
821                                scroll_to("lesson");
822                            },
823                        }
824                    }
825                    button {
826                        class: "learn-to-roadmap",
827                        r#type: "button",
828                        onclick: move |_| scroll_to("roadmap"),
829                        "See the whole roadmap"
830                    }
831                }
832                LearnRoadmap {
833                    open,
834                    done,
835                    on_open: move |id: String| {
836                        steer(progress, |journey| {
837                            journey.open_lesson(&id);
838                        });
839                        if let Some(module) = module_of(&id) {
840                            set_fragment(&module);
841                        }
842                        scroll_to("lesson");
843                    },
844                }
845            }
846
847            Footer {}
848        }
849    }
850}
851
852// ---------------------------------------------------------------------------------------
853// One lesson: its teaching, two examples, the question, and the extras behind their toggles
854// ---------------------------------------------------------------------------------------
855
856/// A lesson as the page draws it. `on_next` moves the learner on once its question is settled.
857#[component]
858pub fn LessonPanel(lesson: String, done: bool, on_next: EventHandler<()>) -> Element {
859    let mut more_examples = use_signal(|| false);
860    let mut more_practice = use_signal(|| false);
861    let engine = ContentEngine::shared();
862    let Some(here) = engine.lesson(&lesson) else {
863        return rsx! { p { class: "lesson-missing", "This lesson is not on the roadmap." } };
864    };
865    let (section, module) = (here.section, here.module);
866    let position = module
867        .sections
868        .iter()
869        .position(|s| s.id == section.id)
870        .unwrap_or(0)
871        + 1;
872    let last = engine
873        .lessons()
874        .last()
875        .is_some_and(|l| l.section.id == section.id);
876    let practice = module
877        .exercises
878        .iter()
879        .filter(|e| e.section.as_deref() == Some(section.id.as_str()))
880        .count();
881    let extra = section.examples.get(2..).unwrap_or_default();
882    let finished = if done { ", done" } else { "" };
883
884    rsx! {
885        article { class: "lesson", id: "lesson", "data-lesson": "{section.id}", aria_labelledby: "lesson-title",
886            p { class: "lesson-crumb", "{module.meta.title}, lesson {position} of {module.sections.len()}{finished}" }
887            h2 { class: "lesson-title", id: "lesson-title",
888                span { class: "lesson-number", "{section.id}" }
889                "{section.title}"
890            }
891
892            div { class: "lesson-teaching",
893                for (i, block) in section.content.iter().enumerate() {
894                    {teaching_block(i, block)}
895                }
896            }
897
898            section { class: "lesson-examples", aria_labelledby: "lesson-examples-title",
899                h3 { class: "lesson-heading", id: "lesson-examples-title", "Examples" }
900                for (i, example) in section.examples.iter().take(2).enumerate() {
901                    {example_view(i, example)}
902                }
903                if !extra.is_empty() {
904                    button {
905                        class: "lesson-toggle lesson-more-examples",
906                        r#type: "button",
907                        aria_expanded: "{more_examples}",
908                        aria_controls: "lesson-extra-examples",
909                        onclick: move |_| more_examples.toggle(),
910                        "More examples ({extra.len()})"
911                    }
912                    div { class: "lesson-extra", id: "lesson-extra-examples", hidden: !more_examples(),
913                        if more_examples() {
914                            for (i, example) in extra.iter().enumerate() {
915                                {example_view(i + 2, example)}
916                            }
917                        }
918                    }
919                }
920            }
921
922            LessonQuestionView { lesson: section.id.clone(), last, on_next }
923
924            if practice > 0 {
925                div { class: "lesson-practice",
926                    button {
927                        class: "lesson-toggle lesson-more-practice",
928                        r#type: "button",
929                        aria_expanded: "{more_practice}",
930                        aria_controls: "lesson-practice",
931                        onclick: move |_| more_practice.toggle(),
932                        "More practice ({practice})"
933                    }
934                    div { id: "lesson-practice", hidden: !more_practice(),
935                        if more_practice() {
936                            LexiconGate {
937                                PracticeArea { lesson: section.id.clone() }
938                            }
939                        }
940                    }
941                }
942            }
943        }
944    }
945}
946
947/// One block of a lesson's teaching.
948fn teaching_block(i: usize, block: &'static ContentBlock) -> Element {
949    match block {
950        ContentBlock::Paragraph { text } => rsx! {
951            p { key: "{i}", class: "lesson-paragraph", dangerous_inner_html: inline_markup_html(text) }
952        },
953        ContentBlock::Definition { term, definition } => rsx! {
954            div { key: "{i}", class: "lesson-definition",
955                p { span { class: "lesson-term", "{term}" } }
956                p { "{definition}" }
957            }
958        },
959        ContentBlock::Symbols { title, symbols } => rsx! {
960            div { key: "{i}", class: "lesson-table",
961                p { class: "lesson-table-title", "{title}" }
962                for (j, row) in symbols.iter().enumerate() {
963                    div { key: "{j}", class: "lesson-table-row",
964                        span { class: "lesson-table-key", "{row.symbol}" }
965                        span { class: "lesson-table-name", "{row.name}" }
966                        span { class: "lesson-table-meaning", "{row.meaning}" }
967                    }
968                }
969            }
970        },
971    }
972}
973
974/// One example: a sentence and the formula LOGOS prints for it, or a worked case.
975fn example_view(i: usize, example: &'static LessonExample) -> Element {
976    match example {
977        LessonExample::Formula {
978            sentence,
979            formula,
980            note,
981        } => rsx! {
982            div { key: "{i}", class: "lesson-example",
983                p { class: "lesson-example-sentence", "{sentence}" }
984                code { class: "lesson-formula", "{formula}" }
985                if let Some(note) = note {
986                    p { class: "lesson-example-note", "{note}" }
987                }
988            }
989        },
990        LessonExample::Worked {
991            title,
992            lines,
993            conclusion,
994            note,
995        } => rsx! {
996            div { key: "{i}", class: "lesson-example worked",
997                p { class: "lesson-example-title", "{title}" }
998                ul { class: "lesson-example-lines",
999                    for (j, line) in lines.iter().enumerate() {
1000                        li { key: "{j}", "{line}" }
1001                    }
1002                }
1003                if let Some(conclusion) = conclusion {
1004                    p { class: "lesson-example-conclusion", "{conclusion}" }
1005                }
1006                if let Some(note) = note {
1007                    p { class: "lesson-example-note", "{note}" }
1008                }
1009            }
1010        },
1011    }
1012}
1013
1014// ---------------------------------------------------------------------------------------
1015// The lesson's question
1016// ---------------------------------------------------------------------------------------
1017
1018#[component]
1019fn LessonQuestionView(lesson: String, last: bool, on_next: EventHandler<()>) -> Element {
1020    let mut quiz = use_signal(LessonQuiz::default);
1021    let mut answer = use_signal(String::new);
1022    let mut tried = use_signal(Vec::<usize>::new);
1023    let mut verdict = use_signal(|| None::<String>);
1024    let mut struggle = use_signal(StruggleDetector::default);
1025    let Some(question) = ContentEngine::shared()
1026        .lesson(&lesson)
1027        .and_then(|l| l.section.question.as_ref())
1028    else {
1029        return rsx! {};
1030    };
1031
1032    let mut grade = move |correct: bool, why: Option<String>| {
1033        quiz.write().answer(correct);
1034        if correct {
1035            struggle.write().record_correct_attempt();
1036            verdict.set(None);
1037        } else {
1038            struggle.write().record_wrong_attempt();
1039            verdict.set(why);
1040        }
1041    };
1042
1043    let state = quiz.read().state();
1044    let settled = quiz.read().is_settled();
1045    let wrong = quiz.read().wrong_attempts();
1046    let (hint, explanation, kind) = match question {
1047        LessonQuestion::Translate {
1048            hint, explanation, ..
1049        } => (hint, explanation, "typed"),
1050        LessonQuestion::Choice {
1051            hint, explanation, ..
1052        } => (hint, explanation, "choice"),
1053    };
1054
1055    rsx! {
1056        section { class: "lesson-question", "data-kind": kind, aria_labelledby: "lesson-question-title",
1057            h3 { class: "lesson-heading", id: "lesson-question-title", "Your turn" }
1058            match question {
1059                LessonQuestion::Translate { sentence, answer: key, .. } => {
1060                    let key = key.clone();
1061                    let check = move || {
1062                        if quiz.peek().is_settled() {
1063                            return;
1064                        }
1065                        let given = answer.peek().clone();
1066                        if given.trim().is_empty() {
1067                            verdict.set(Some("Write a formula first.".to_string()));
1068                            return;
1069                        }
1070                        let result = check_answer(&given, &key);
1071                        grade(result.correct, Some(result.feedback));
1072                    };
1073                    let field = match state {
1074                        QuizState::Correct => "lesson-input correct",
1075                        QuizState::Answering if wrong > 0 => "lesson-input wrong",
1076                        _ => "lesson-input",
1077                    };
1078                    rsx! {
1079                        p { class: "lesson-question-prompt", "Write this sentence in logic." }
1080                        p { class: "lesson-question-sentence", "{sentence}" }
1081                        div { class: "lesson-answer-row",
1082                            input {
1083                                id: "lesson-answer",
1084                                class: "{field}",
1085                                r#type: "text",
1086                                aria_label: "Your formula",
1087                                autocomplete: "off",
1088                                autocapitalize: "off",
1089                                spellcheck: "false",
1090                                placeholder: "Type, or tap the symbols below",
1091                                readonly: settled,
1092                                value: "{answer}",
1093                                oninput: move |e: Event<FormData>| {
1094                                    answer.set(e.value());
1095                                    struggle.write().record_activity();
1096                                },
1097                                onkeydown: {
1098                                    let mut check = check.clone();
1099                                    move |e: Event<KeyboardData>| {
1100                                        if e.key() == Key::Enter {
1101                                            e.prevent_default();
1102                                            check();
1103                                        }
1104                                    }
1105                                },
1106                            }
1107                            button {
1108                                class: "lesson-check",
1109                                r#type: "button",
1110                                disabled: settled,
1111                                onclick: {
1112                                    let mut check = check.clone();
1113                                    move |_| check()
1114                                },
1115                                "Check"
1116                            }
1117                        }
1118                        if !settled {
1119                            SymbolPad { target: "lesson-answer".to_string(), on_input: move |text: String| answer.set(text) }
1120                        }
1121                    }
1122                }
1123                LessonQuestion::Choice { prompt, options, correct, .. } => {
1124                    let right = *correct;
1125                    rsx! {
1126                        p { class: "lesson-question-prompt", "{prompt}" }
1127                        div { class: "lesson-options", role: "group", aria_label: "Options",
1128                            for (i, option) in options.iter().enumerate() {
1129                                {
1130                                    let missed = tried.read().contains(&i) && i != right;
1131                                    let class = if missed {
1132                                        "lesson-option wrong"
1133                                    } else if settled && i == right {
1134                                        "lesson-option correct"
1135                                    } else {
1136                                        "lesson-option"
1137                                    };
1138                                    rsx! {
1139                                        button {
1140                                            key: "{i}",
1141                                            class: "{class}",
1142                                            r#type: "button",
1143                                            disabled: settled || missed,
1144                                            onclick: move |_| {
1145                                                if quiz.peek().is_settled() {
1146                                                    return;
1147                                                }
1148                                                tried.write().push(i);
1149                                                grade(i == right, Some("Not quite.".to_string()));
1150                                            },
1151                                            "{option}"
1152                                        }
1153                                    }
1154                                }
1155                            }
1156                        }
1157                    }
1158                }
1159            }
1160
1161            div { class: "lesson-feedback", role: "status", aria_live: "polite",
1162                if state == QuizState::Correct {
1163                    p { class: "lesson-verdict correct", "Correct." }
1164                } else if let Some(why) = verdict() {
1165                    p { class: "lesson-verdict wrong", "{why}" }
1166                }
1167                if state == QuizState::Answering && struggle.read().should_show_hints() {
1168                    SocraticHint { hint: hint.clone() }
1169                }
1170            }
1171
1172            if quiz.read().can_show_answer() {
1173                button {
1174                    class: "lesson-show-answer",
1175                    r#type: "button",
1176                    onclick: move |_| {
1177                        quiz.write().show_answer();
1178                    },
1179                    "Show the answer"
1180                }
1181            }
1182
1183            if settled {
1184                div { class: "lesson-answer",
1185                    p { class: "lesson-answer-label", "The answer" }
1186                    match question {
1187                        LessonQuestion::Translate { answer: key, .. } => rsx! { code { class: "lesson-formula", "{key}" } },
1188                        LessonQuestion::Choice { options, correct, .. } => rsx! {
1189                            p { class: "lesson-answer-option", "{options[*correct]}" }
1190                        },
1191                    }
1192                    p { class: "lesson-explanation", "{explanation}" }
1193                }
1194                button {
1195                    class: "lesson-next",
1196                    r#type: "button",
1197                    onclick: move |_| on_next.call(()),
1198                    if last { "Finish the roadmap" } else { "Next lesson" }
1199                }
1200            }
1201        }
1202    }
1203}
1204
1205/// The hint a learner gets once the struggle detector sees them stuck: a question that points the
1206/// way without giving the answer.
1207#[component]
1208fn SocraticHint(hint: String) -> Element {
1209    rsx! {
1210        div { class: "lesson-hint",
1211            span { class: "lesson-hint-mark", aria_hidden: "true",
1212                Icon { variant: IconVariant::Owl, size: IconSize::Medium, color: "var(--accent-secondary)" }
1213            }
1214            p { "{hint}" }
1215        }
1216    }
1217}
1218
1219// ---------------------------------------------------------------------------------------
1220// More practice: the lesson's exercises, one at a time (behind the word bank)
1221// ---------------------------------------------------------------------------------------
1222
1223/// The exercises that practise `lesson`, in the order they play.
1224fn practice_set(lesson: &str) -> Vec<&'static ExerciseConfig> {
1225    ContentEngine::shared()
1226        .lesson(lesson)
1227        .map(|l| {
1228            l.module
1229                .exercises
1230                .iter()
1231                .filter(|e| e.section.as_deref() == Some(lesson))
1232                .collect()
1233        })
1234        .unwrap_or_default()
1235}
1236
1237#[component]
1238fn PracticeArea(lesson: String) -> Element {
1239    let set = practice_set(&lesson);
1240    let fallback = use_signal(UserProgress::new);
1241    let progress = try_consume_context::<Signal<UserProgress>>().unwrap_or(fallback);
1242    let total = set.len();
1243    let practice = use_signal(|| {
1244        let p = progress.peek();
1245        let solved = set
1246            .iter()
1247            .enumerate()
1248            .filter(|(_, e)| {
1249                p.get_exercise_progress(&e.id)
1250                    .is_some_and(|x| x.correct_count > 0)
1251            })
1252            .map(|(i, _)| i);
1253        PracticeSession::new(total, solved.collect::<Vec<_>>())
1254    });
1255    let seed = use_hook(new_seed);
1256
1257    let session = practice.read();
1258    let Some(index) = session.current() else {
1259        return rsx! { p { class: "practice-progress", "No practice questions for this lesson yet." } };
1260    };
1261    let completed = session.completed_count();
1262    rsx! {
1263        div { class: "practice",
1264            p { class: "practice-progress", "Question {index + 1} of {total}. {completed} answered right." }
1265            // A keyed list of one: a new visit remounts the card, so it opens with a blank answer.
1266            for visit in std::iter::once(session.visit()) {
1267                PracticeCard { key: "{visit}", lesson: lesson.clone(), index, practice, progress, seed }
1268            }
1269        }
1270    }
1271}
1272
1273fn generate(exercise: &ExerciseConfig, seed: u64, index: usize) -> Option<Challenge> {
1274    let mut rng = StdRng::seed_from_u64(seed.wrapping_add((index as u64).wrapping_mul(1000)));
1275    Generator::new().generate(exercise, &mut rng)
1276}
1277
1278/// Which of a practice question's aids are showing.
1279#[derive(Debug, Clone, Copy, PartialEq, Default)]
1280struct Reveal {
1281    hint: bool,
1282    answer: bool,
1283}
1284
1285#[component]
1286fn PracticeCard(
1287    lesson: String,
1288    index: usize,
1289    mut practice: Signal<PracticeSession>,
1290    mut progress: Signal<UserProgress>,
1291    seed: u64,
1292) -> Element {
1293    let config = practice_set(&lesson).get(index).copied();
1294    let challenge = use_hook(|| config.and_then(|config| generate(config, seed, index)));
1295    let mut answer = use_signal(String::new);
1296    let readings_count = match challenge.as_ref().map(|c| &c.answer) {
1297        Some(AnswerType::Ambiguity { readings }) => readings.len(),
1298        _ => 0,
1299    };
1300    let mut readings = use_signal(|| vec![String::new(); readings_count]);
1301    let mut reading_focus = use_signal(|| 0usize);
1302    let mut selected = use_signal(|| None::<usize>);
1303    let mut feedback = use_signal(|| None::<(bool, String)>);
1304    let mut reveal = use_signal(Reveal::default);
1305    let mut struggle = use_signal(StruggleDetector::default);
1306
1307    let (Some(config), Some(challenge)) = (config, challenge) else {
1308        return rsx! {
1309            div { class: "practice-card",
1310                p { "This question could not be made." }
1311                button { class: "lesson-toggle practice-skip", r#type: "button", onclick: move |_| practice.write().advance(), "Skip" }
1312            }
1313        };
1314    };
1315    let exercise_id: &'static str = config.id.as_str();
1316
1317    let is_correct = {
1318        let challenge = challenge.clone();
1319        move || -> (bool, String) {
1320            match &challenge.answer {
1321                AnswerType::FreeForm { golden_logic } => {
1322                    let given = answer.peek().clone();
1323                    if given.trim().is_empty() {
1324                        return (false, "Write a formula first.".to_string());
1325                    }
1326                    let result = check_answer(&given, golden_logic);
1327                    (result.correct, result.feedback)
1328                }
1329                AnswerType::MultipleChoice { correct_index, .. } => (
1330                    *selected.peek() == Some(*correct_index),
1331                    "Not quite.".to_string(),
1332                ),
1333                AnswerType::Ambiguity { readings: expected } => {
1334                    let grade = check_readings(&readings.peek(), expected);
1335                    (
1336                        grade.all_correct(),
1337                        format!("{} of {} readings right.", grade.matched, grade.total),
1338                    )
1339                }
1340            }
1341        }
1342    };
1343    let check = move || {
1344        let (correct, why) = is_correct();
1345        practice.write().answer(correct);
1346        progress.write().record_attempt(exercise_id, correct);
1347        if correct {
1348            struggle.write().record_correct_attempt();
1349            feedback.set(Some((true, "Correct.".to_string())));
1350        } else {
1351            struggle.write().record_wrong_attempt();
1352            feedback.set(Some((false, why)));
1353        }
1354    };
1355    let solved = practice.read().solved_current();
1356    let shown = reveal();
1357    let field = match feedback() {
1358        Some((true, _)) => "lesson-input correct",
1359        Some((false, _)) => "lesson-input wrong",
1360        None => "lesson-input",
1361    };
1362
1363    rsx! {
1364        div { class: "practice-card",
1365            if challenge.prompt.trim() != challenge.sentence.trim() {
1366                p { class: "practice-prompt", "{challenge.prompt}" }
1367            }
1368            p { class: "practice-sentence", "{challenge.sentence}" }
1369
1370            match &challenge.answer {
1371                AnswerType::FreeForm { .. } => rsx! {
1372                    div { class: "lesson-answer-row",
1373                        input {
1374                            id: "practice-answer",
1375                            class: "{field}",
1376                            r#type: "text",
1377                            aria_label: "Your formula",
1378                            autocomplete: "off",
1379                            autocapitalize: "off",
1380                            spellcheck: "false",
1381                            value: "{answer}",
1382                            oninput: move |e: Event<FormData>| {
1383                                answer.set(e.value());
1384                                struggle.write().record_activity();
1385                            },
1386                            onkeydown: {
1387                                let mut check = check.clone();
1388                                move |e: Event<KeyboardData>| {
1389                                    if e.key() == Key::Enter {
1390                                        e.prevent_default();
1391                                        check();
1392                                    }
1393                                }
1394                            },
1395                        }
1396                        button { class: "lesson-check", r#type: "button", onclick: { let mut check = check.clone(); move |_| check() }, "Check" }
1397                    }
1398                    SymbolPad { target: "practice-answer".to_string(), on_input: move |text: String| answer.set(text) }
1399                },
1400                AnswerType::MultipleChoice { options, correct_index } => {
1401                    let right = *correct_index;
1402                    let answered = feedback().is_some();
1403                    rsx! {
1404                        div { class: "practice-options", role: "group", aria_label: "Options",
1405                            for (i, option) in options.iter().enumerate() {
1406                                {
1407                                    let chosen = selected() == Some(i);
1408                                    let class = match (answered && chosen, i == right) {
1409                                        (true, true) => "lesson-option correct",
1410                                        (true, false) => "lesson-option wrong",
1411                                        _ => "lesson-option",
1412                                    };
1413                                    let mut check = check.clone();
1414                                    rsx! {
1415                                        button {
1416                                            key: "{i}",
1417                                            class: "{class}",
1418                                            r#type: "button",
1419                                            aria_pressed: "{chosen}",
1420                                            onclick: move |_| {
1421                                                selected.set(Some(i));
1422                                                check();
1423                                            },
1424                                            "{option}"
1425                                        }
1426                                    }
1427                                }
1428                            }
1429                        }
1430                    }
1431                },
1432                AnswerType::Ambiguity { readings: expected } => {
1433                    let n = expected.len();
1434                    let target = format!("practice-reading-{}", reading_focus());
1435                    rsx! {
1436                        div { class: "practice-readings", "data-answer-kind": "readings",
1437                            p { class: "practice-prompt", "Give all {n} readings, in any order." }
1438                            for i in 0..n {
1439                                label { key: "{i}", r#for: "practice-reading-{i}", "Reading {i + 1}" }
1440                                input {
1441                                    id: "practice-reading-{i}",
1442                                    class: "{field}",
1443                                    r#type: "text",
1444                                    "data-reading": "{i}",
1445                                    autocomplete: "off",
1446                                    autocapitalize: "off",
1447                                    spellcheck: "false",
1448                                    value: "{readings.read().get(i).cloned().unwrap_or_default()}",
1449                                    onfocus: move |_| reading_focus.set(i),
1450                                    oninput: move |e: Event<FormData>| {
1451                                        if let Some(slot) = readings.write().get_mut(i) {
1452                                            *slot = e.value();
1453                                        }
1454                                        struggle.write().record_activity();
1455                                    },
1456                                }
1457                            }
1458                        }
1459                        SymbolPad {
1460                            target,
1461                            on_input: move |text: String| {
1462                                let at = *reading_focus.peek();
1463                                if let Some(slot) = readings.write().get_mut(at) {
1464                                    *slot = text;
1465                                }
1466                            },
1467                        }
1468                        div { class: "practice-actions",
1469                            button { class: "lesson-check", r#type: "button", onclick: { let mut check = check.clone(); move |_| check() }, "Check" }
1470                        }
1471                    }
1472                },
1473            }
1474
1475            div { role: "status", aria_live: "polite",
1476                if let Some((correct, message)) = feedback() {
1477                    p { class: if correct { "lesson-verdict correct" } else { "lesson-verdict wrong" }, "{message}" }
1478                    if !correct && struggle.read().should_show_hints() {
1479                        if let Some(hint) = challenge.hint.clone() {
1480                            SocraticHint { hint }
1481                        }
1482                    }
1483                }
1484            }
1485
1486            div { class: "practice-actions",
1487                if challenge.hint.is_some() && feedback().is_none() {
1488                    button {
1489                        class: "lesson-toggle practice-hint",
1490                        r#type: "button",
1491                        aria_expanded: "{shown.hint}",
1492                        onclick: move |_| reveal.write().hint ^= true,
1493                        "Hint"
1494                    }
1495                }
1496                button {
1497                    class: "lesson-toggle practice-show",
1498                    r#type: "button",
1499                    aria_expanded: "{shown.answer}",
1500                    onclick: move |_| {
1501                        if !reveal.peek().answer {
1502                            practice.write().reveal_answer();
1503                        }
1504                        reveal.write().answer ^= true;
1505                    },
1506                    "Show the answer"
1507                }
1508                if solved {
1509                    button { class: "lesson-check practice-next", r#type: "button", onclick: move |_| practice.write().advance(), "Next question" }
1510                } else {
1511                    button { class: "lesson-toggle practice-skip", r#type: "button", onclick: move |_| practice.write().advance(), "Skip" }
1512                }
1513            }
1514
1515            if shown.hint && feedback().is_none() {
1516                if let Some(hint) = challenge.hint.clone() {
1517                    SocraticHint { hint }
1518                }
1519            }
1520            if shown.answer {
1521                div { class: "lesson-answer",
1522                    p { class: "lesson-answer-label", "The answer" }
1523                    match &challenge.answer {
1524                        AnswerType::FreeForm { golden_logic } => rsx! { code { class: "practice-key", "{golden_logic}" } },
1525                        AnswerType::MultipleChoice { options, correct_index } => rsx! {
1526                            p { class: "lesson-answer-option practice-key-option", "{options[*correct_index]}" }
1527                        },
1528                        AnswerType::Ambiguity { readings: expected } => rsx! {
1529                            for (i, reading) in expected.iter().enumerate() {
1530                                code { key: "{i}", class: "practice-key", "{reading}" }
1531                            }
1532                        },
1533                    }
1534                    if let Some(explanation) = challenge.explanation.as_ref() {
1535                        p { class: "lesson-explanation", "{explanation}" }
1536                    }
1537                }
1538            }
1539        }
1540    }
1541}