diff --git a/_projects/lessons/java/notebooks/2025-09-21-2.2.ipynb b/_projects/lessons/java/notebooks/2025-09-21-2.2.ipynb index 49a48aa5df..d9478b78ec 100644 --- a/_projects/lessons/java/notebooks/2025-09-21-2.2.ipynb +++ b/_projects/lessons/java/notebooks/2025-09-21-2.2.ipynb @@ -1,7 +1,8 @@ { "cells": [ { - "cell_type": "markdown", + "cell_type": "raw", + "id": "93cacbcd", "metadata": { "vscode": { "languageId": "raw" @@ -10,15 +11,17 @@ "source": [ "---\n", "layout: post\n", + "assignment: true\n", "courses: { csa: {week: 2} }\n", "categories: [Java, Boolean-Expressions]\n", "lesson_language: Java\n", "lesson_topic: Boolean-Expressions\n", - "lesson_part: interactive\n", + "lesson_source: APCSA\n", "lesson_type: lesson\n", - "toc: true\n", "codemirror: true\n", - "title: Boolean Expressions\n", + "toc: true\n", + "title: 2.02 Boolean Expressions\n", + "description: Write yes or no questions in Java with the relational operators ==, !=, <, >, <=, and >=.\n", "menu: nav/csa_units/csaunit2.html\n", "permalink: /csa/unit_02/2_2\n", "---" @@ -28,224 +31,487 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# 2.2 Boolean Expressions\n", + "## 1. LxD Cycle Process\n", + "\n", + "**Empathize:** Students read `=` and `==` as the same symbol and are surprised when the compiler rejects one or the program silently does the wrong thing. They also treat comparison results as something that only lives inside an `if`.\n", + "\n", + "**Define:**\n", + "- **POV:** CSA students need to see a comparison as a value, not only as a condition, because the AP exam asks them to store, print and combine Boolean results.\n", + "- **Learning Goal:** Students will evaluate relational expressions by hand, store results in `boolean` variables, and find the difference between assignment and comparison.\n", + "\n", + "**Ideate:**\n", + "- **HMW Question:** How might we make the result of a comparison visible as a value, so students stop thinking it only exists inside an `if`?\n", + "- **Activity:** A live comparison lab where changing operands updates the printed `true` or `false`, followed by a true-or-false drill and a bug hunt.\n", + "\n", + "**Prototype & Test:** The comparison lab runs before any `if` statement appears, so students meet `boolean` as a data type first and as a condition second.\n", + "\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Lesson Plan\n", + "\n", + "**Learning Objective:** Evaluate Boolean expressions that use relational operators in program code.\n", + "\n", + "**Success Criteria:** You can predict whether a relational expression is `true` or `false`, store the result in a `boolean` variable, and explain why `=` and `==` are not interchangeable.\n", "\n", - "A **Boolean expression** evaluates to `true` or `false` \u2014 nothing else. The College Board puts it simply: \"An expression involving relational operators evaluates to a Boolean value\" (College Board, 2025, p. 61).\n", + "### Tech Talk & Introduction (5 minutes)\n", + "\n", + "A Boolean expression is a question with only two possible answers. Java answers it with `true` or `false`, and that value can be stored just like a number.\n", + "\n", + "- The relational operators are `==`, `!=`, `<`, `>`, `<=` and `>=`.\n", + "- `=` assigns a value. `==` asks whether two values are equal. Mixing them up is the most common bug in this topic.\n", + "- The result of a comparison is a `boolean`, so `boolean passed = score >= 60;` is legal and often clearer than repeating the comparison." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Reference Guide\n", + "\n", + "### Key Ideas\n", + "\n", + "- A **Boolean expression** evaluates to exactly one of two values: `true` or `false`.\n", + "- **Relational operators** compare two values: `==` `!=` `<` `>` `<=` `>=`.\n", + "- `==` asks \"are these equal?\" while `=` assigns a value. Mixing them up is the most common bug in this unit.\n", + "- Arithmetic runs first, then the comparison: `x + 1 > 5` adds before it compares.\n", + "- Relational operators work on numbers (`int`, `double`) and `char`. Use `.equals` for Strings (more in 2.6).\n", + "- A Boolean value can be stored in a `boolean` variable: `boolean isAdult = age >= 18;`\n", + "\n", + "### The Six Relational Operators\n", + "\n", + "| Operator | Question it asks | Example (x = 7) | Value |\n", + "| --- | --- | --- | --- |\n", + "| `==` | equal to? | `x == 7` | `true` |\n", + "| `!=` | not equal to? | `x != 7` | `false` |\n", + "| `<` | less than? | `x < 10` | `true` |\n", + "| `>` | greater than? | `x > 10` | `false` |\n", + "| `<=` | less than or equal? | `x <= 7` | `true` |\n", + "| `>=` | greater than or equal? | `x >= 8` | `false` |\n", + "\n", + "- Integer division still applies: `10 / 4 == 2` is `true` because `10 / 4` is `2`.\n", + "- `%` gives the remainder: `x % 2 == 0` is the standard test for \"is x even?\"." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Code Examples\n", "\n", - "| Operator | Meaning |\n", - "|---|---|\n", - "| `==` | equal to |\n", - "| `!=` | not equal to |\n", - "| `<` | less than |\n", - "| `>` | greater than |\n", - "| `<=` | less than or equal to |\n", - "| `>=` | greater than or equal to |\n", + "### A. Simple: Booleans in Code\n", "\n", - "Run it yourself below." + "Run this program. Then change `temperature` to `100`, `72`, and `-5` and predict each line before you press Run." ] }, { "cell_type": "code", "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, + "id": "ce5ccd87", + "metadata": {}, "outputs": [], "source": [ - "// CODE_RUNNER: Boolean Expressions - Try It\n", - "public class Main {\n", + "// CODE_RUNNER: Boolean demo: store comparisons in boolean variables and print them.\n", + "public class BooleanDemo {\n", " public static void main(String[] args) {\n", - " int score = 85;\n", + " int temperature = 85;\n", + " int limit = 90;\n", + "\n", + " boolean isHot = temperature > limit;\n", + " boolean isFreezing = temperature <= 32;\n", + " boolean isEven = temperature % 2 == 0;\n", "\n", - " System.out.println(score == 85); // true\n", - " System.out.println(score != 100); // true\n", - " System.out.println(score > 90); // false\n", - " System.out.println(score <= 85); // true\n", + " System.out.println(\"temperature > limit: \" + isHot);\n", + " System.out.println(\"temperature <= 32: \" + isFreezing);\n", + " System.out.println(\"temperature % 2 == 0: \" + isEven);\n", + " System.out.println(\"temperature != limit: \" + (temperature != limit));\n", + " System.out.println(\"temperature + 5 >= limit: \" + (temperature + 5 >= limit));\n", " }\n", "}\n", - "Main.main(null);" + "BooleanDemo.main(null);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Raise your hand:\n", - "1. If `score` was 90, what would `score > 90` print?\n", - "2. Is `score != 85` `true` or `false` right now?" + "## 5. Hacks & Practice Tasks\n", + "\n", + "### Prepare your submission IPYNB\n", + "\n", + "1. Create a new notebook in your portfolio homework area: `_notebooks/homework`.\n", + "2. Add one markdown cell at the top with the frontmatter:\n", + "\n", + "~~~raw\n", + "---\n", + "layout: post\n", + "title: CSA Unit 2.02 Boolean Expressions HW\n", + "categories: [Java, Boolean-Expressions]\n", + "lesson_language: Java\n", + "lesson_topic: Boolean-Expressions HW\n", + "lesson_source: APCSA\n", + "lesson_type: lesson\n", + "permalink: /csa/unit_02/2_2_hw\n", + "author: yourGithubID\n", + "---\n", + "~~~\n", + "\n", + "3. Add code cells for the Popcorn Hack and the Homework Hack. Ensure all code runs and output is visible.\n", + "4. Include a markdown cell before each code section explaining the concept.\n", + "\n", + "### Submission Safety Rules (Read First)\n", + "\n", + "[IMPORTANT]\n", + "To avoid grading errors, follow these rules exactly:\n", + "\n", + "- Write your prediction before you run each code section\n", + "- Execute every code cell and leave the output visible\n", + "- Show your work for any hand-traced prediction\n", + "- Do not just copy code; explain what each line does\n", + "- Label each question clearly" ] }, { "cell_type": "markdown", + "id": "47638e7a", "metadata": {}, "source": [ - "## Where else do you see this?\n", - "Every API you build \u2014 Spring on the CSA side, any backend on the CSP side \u2014 has to decide what to send back before it responds: *Does this exist? Is this value allowed?* Each check is a Boolean expression built from the exact operators above, and the `true`/`false` result decides the response." + "\n", + "\n", + "### Activity 1: Live Comparison Lab\n", + "\n", + "Move the sliders. Every `println` line re-evaluates instantly. Try to make every line print `true`, then every line print `false`.\n", + "\n", + "
\n", + "
\n", + "
Comparison Lab
\n", + "
Change x and y and watch each Boolean expression update.
\n", + "
\n", + "
\n", + "\n", + "
\n", + "
\n", + "" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], + "cell_type": "markdown", + "id": "f98f38cd", + "metadata": {}, "source": [ - "if (item == null) {\n", - " return notFound(); // equality operator: does it exist?\n", - "}\n", - "if (quantity > maxAllowed) {\n", - " return badRequest(); // relational operator: is it valid?\n", - "}" + "### Activity 2: True or False?\n", + "\n", + "Given the three variables below, sort every expression into the TRUE or FALSE bucket. Watch out for integer division.\n", + "\n", + "
\n", + "
int a = 10;
\n", + "
int b = 4;
\n", + "
double c = 2.5;
\n", + "
\n", + "\n", + "
\n", + "
\n", + "
Sort the Expressions
\n", + "
Ten expressions. Evaluate each one in your head first.
\n", + "
\n", + "
\n", + "

Click an item, then click a bucket. Or drag it. Click an item inside a bucket to send it back.

\n", + "
\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
\n", + "
\n", + "
TRUE
\n", + "
FALSE
\n", + "
\n", + "
\n", + "
" ] }, { "cell_type": "markdown", + "id": "543f9a5e", "metadata": {}, "source": [ - "### Popcorn Hack 1\n", - "Predict what each line prints, then run it to check." + "### Activity 3: Spot the Bug\n", + "\n", + "
\n", + "
\n", + "
Bug Hunt
\n", + "
Three quick questions. Each one is a classic AP exam trap.
\n", + "
\n", + "
\n", + "
\n", + "
Question 1
\n", + "

Which line will NOT compile?

\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "
\n", + "
\n", + "
Question 2
\n", + "

What is the value of 7 / 2 == 3.5?

\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "
\n", + "
\n", + "
Question 3
\n", + "

Which expression is true exactly when n is a multiple of 5?

\n", + "\n", + "
\n", + " \n", + " \n", + " \n", + "
\n", + "
\n", + "
\n", + "
" + ] + }, + { + "cell_type": "markdown", + "id": "f9c31162", + "metadata": {}, + "source": [ + "### Popcorn Hack (In-Class)\n", + "This program has two bugs. One stops it from compiling, the other prints the wrong answer. Fix both so it prints `Bonus unlocked: true` and `Exact score: false`." ] }, { "cell_type": "code", "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, + "id": "06bf4296", + "metadata": {}, "outputs": [], "source": [ - "// CODE_RUNNER: Popcorn Hack 1 - Predict the Output\n", - "public class Main {\n", + "// CODE_RUNNER: Popcorn hack: fix the two bugs so both lines print the expected values.\n", + "public class BonusCheck {\n", " public static void main(String[] args) {\n", - " int temp = 72;\n", - " System.out.println(temp >= 70);\n", - " System.out.println(temp == 72.0);\n", - " System.out.println(temp < 32);\n", + " int score = 120;\n", + " int target = 100;\n", + "\n", + " // Bug 1: this line does not compile\n", + " boolean bonus = score => target;\n", + "\n", + " // Bug 2: this should ask whether score is EXACTLY equal to target\n", + " boolean exact = score != target;\n", + "\n", + " System.out.println(\"Bonus unlocked: \" + bonus);\n", + " System.out.println(\"Exact score: \" + exact);\n", " }\n", "}\n", - "Main.main(null);" + "BonusCheck.main(null);" ] }, { "cell_type": "markdown", + "id": "f568d456", "metadata": {}, "source": [ - "### Popcorn Hack 2\n", - "Find and fix the 2 errors in this Boolean expression, then run it until it works." + "### Homework Hack\n", + "Short and specific.\n", + "\n", + "1. Complete the runner below: write the four Boolean expressions described in the comments and print them.\n", + "2. Answer the two quick checks under it." ] }, { "cell_type": "code", "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, + "id": "cbdc1279", + "metadata": {}, "outputs": [], "source": [ - "// CODE_RUNNER: Popcorn Hack 2 - Fix the Bug\n", - "public class Main {\n", + "// CODE_RUNNER: Homework: replace each false with a Boolean expression so the expected values print.\n", + "public class SpeedCheck {\n", " public static void main(String[] args) {\n", - " int number = 4;\n", - " boolean isEven = number % 2 = 0;\n", - " System.out.println(isEven)\n", + " int speed = 68;\n", + " int limit = 65;\n", + " int age = 17;\n", + "\n", + " // 1. true when the driver is over the limit\n", + " boolean speeding = false; // TODO\n", + "\n", + " // 2. true when the driver is going exactly the limit\n", + " boolean exactLimit = false; // TODO\n", + "\n", + " // 3. true when the driver is at least 18\n", + " boolean adult = false; // TODO\n", + "\n", + " // 4. true when speed is an odd number (use %)\n", + " boolean oddSpeed = false; // TODO\n", + "\n", + " System.out.println(\"speeding: \" + speeding); // expected: true\n", + " System.out.println(\"exactLimit: \" + exactLimit); // expected: false\n", + " System.out.println(\"adult: \" + adult); // expected: false\n", + " System.out.println(\"oddSpeed: \" + oddSpeed); // expected: false\n", " }\n", "}\n", - "Main.main(null);" + "SpeedCheck.main(null);" ] }, { "cell_type": "markdown", + "id": "f31257d0", "metadata": {}, "source": [ - "
Show fixed code\n", - "
int number = 4;\n",
-    "boolean isEven = number % 2 == 0;\n",
-    "System.out.println(isEven);
\n", - "
" + "
\n", + "
\n", + "
Homework Quick Checks
\n", + "
Type the value Java produces. Answers are true or false.
\n", + "
\n", + "
\n", + "
\n", + "
Question 1
\n", + "

What does this print?

\n", + "
\n", + "
int n = 15;
\n", + "
System.out.println(n % 5 == 0);
\n", + "
\n", + "
\n", + " \n", + "
\n", + "
\n", + "
\n", + "
Question 2
\n", + "

What does this print?

\n", + "
\n", + "
int a = 9;
\n", + "
int b = 2;
\n", + "
System.out.println(a / b == 4.5);
\n", + "
\n", + "
\n", + " \n", + "
\n", + "
\n", + "
\n", + "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### Try It Yourself\n", - "Change `false` below to a Boolean expression using `age` and a relational operator, so `canJoinClub` is only `true` when `age` is 13 or older. Run it, then edit `age` to test 12, 13, and 100." + "## 6. Grading Plan (1 Point Total)\n", + "\n", + "### Classroom Rubric\n", + "\n", + "- **0.2 points: Popcorn completion**\n", + " Student fixed both bugs so the program compiles and prints `Bonus unlocked: true` and `Exact score: false`.\n", + "\n", + "- **0.8 points: Homework completion**\n", + " - **0.5 Four expressions:** The four Boolean expressions described in the runner comments are written correctly and printed.\n", + " - **0.2 Quick checks:** Both quick check questions answered with the reasoning shown.\n", + " - **0.1 Notebook quality:** Every code cell executed with output visible, and a markdown cell before each code section explaining the concept.\n", + "\n", + "### Quick Validation Checklist\n", + "\n", + "- Present: all four expressions print a `true` or `false` value\n", + "- Present: both Popcorn bugs fixed, with a comment naming each one\n", + "- Absent: `=` used where `==` was intended\n", + "- Test: output reads `Bonus unlocked: true` and `Exact score: false`\n", + "\n", + "---" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], + "cell_type": "markdown", + "metadata": {}, "source": [ - "// CODE_RUNNER: Try It Yourself - Age Check\n", - "public class Main {\n", - " public static void main(String[] args) {\n", - " int age = 16;\n", + "## 7. Lesson Revisions & Feedback Evidence\n", "\n", - " boolean canJoinClub = false; // TODO: use age and a relational operator\n", + "**Feedback Received:** Team review of the Unit 2 set found that these lessons did not follow the section format used by the Unit 1 lessons, and that they ended without the assignment submission form every other CSA lesson provides.\n", "\n", - " System.out.println(canJoinClub);\n", - " }\n", - "}\n", - "Main.main(null);" + "**Revision Made:** The lesson was reorganised into the shared CSA lesson format, so it now opens with the LxD cycle and lesson plan, states its reference material before the code, and groups the activities, Popcorn Hack and Homework Hack under one practice section. The duplicate lesson heading was removed, and the page now renders the standard Submit Assignment form at the end.\n", + "\n", + "**Design Decision Kept:** The comparison lab runs before any `if` statement appears, so students meet `boolean` as a data type first and as a condition second.\n", + "\n", + "**Open Item:** Record peer feedback from the team teach delivery here once the lesson has been taught.\n", + "\n", + "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "
Show one possible answer\n", - "
boolean canJoinClub = age >= 13;
\n", - "
" + "## 8. Summary\n", + "\n", + "- Boolean expressions are `true` or `false`; relational operators build them.\n", + "- `==` compares, `=` assigns.\n", + "- Arithmetic (including integer division and `%`) happens before the comparison.\n", + "- `x % k == 0` tests divisibility; `x % 2 == 0` tests even.\n", + "- Next lesson: using Boolean expressions to make decisions with `if`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## AP Exam Practice\n", - "Try these on your own before checking the answer.\n", + "## 9. References\n", "\n", - "**1.** What does `12 != 12` evaluate to?\n", - "A) `true` B) `false` C) `0` D) Compile-time error\n", + "### College Board Course and Exam Description\n", "\n", - "
Show answerB \u2014 != is false when both sides are equal.
\n", + "Topic 2.2, *Boolean Expressions*, is required content on the AP Computer Science A Exam. The objective quoted in section 2 of this lesson is the College Board's own wording for this topic, and the activities, Popcorn Hack and Homework Hack are all written against it.\n", "\n", - "**2.**\n", - "
int x = 5, y = 10;\n",
-    "System.out.println(x <= y);
\n", - "What is printed?\n", - "A) `5` B) `10` C) `true` D) `false`\n", + "### Outside Academic Reference\n", "\n", - "
Show answerC \u2014 5 is less than 10, so the relational expression evaluates to true.
\n", + "The relational operators and the `boolean` type behave exactly as the language specification defines them: a numeric comparison produces a value of type `boolean`, which is why it can be assigned to a variable.\n", "\n", - "**3.** Which correctly tests two `int` values, `a` and `b`, for equality?\n", - "A) `a = b` B) `a == b` C) `a.equals(b)` D) `a != b`\n", + "### Reference List\n", "\n", - "
Show answerB \u2014 == compares primitive values directly; a.equals(b) is for objects, not primitives.
" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## References\n", - "- College Board. (2025). *AP Computer Science A course and exam description*. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description.pdf\n", - "- Oracle. (n.d.). *Equality, relational, and conditional operators*. The Java Tutorials. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html" + "College Board. (2025). *AP Computer Science A: Course and exam description*. https://apcentral.collegeboard.org/courses/ap-computer-science-a\n", + "\n", + "Gosling, J., Joy, B., Steele, G., Bracha, G., Buckley, A., Smith, D., & Bierman, G. (2023). *The Java language specification: Java SE 21 edition*. Oracle America. https://docs.oracle.com/javase/specs/jls/se21/html/" ] } ], @@ -259,11 +525,11 @@ "codemirror_mode": "java", "file_extension": ".jshell", "mimetype": "text/x-java-source", - "name": "Java", + "name": "java", "pygments_lexer": "java", "version": "17.0.12+0" } }, "nbformat": 4, - "nbformat_minor": 2 -} + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/_sass/open-coding/_main.scss b/_sass/open-coding/_main.scss index 73d8e86c34..f996044492 100644 --- a/_sass/open-coding/_main.scss +++ b/_sass/open-coding/_main.scss @@ -25,6 +25,7 @@ @import "platformer-game"; @import "quiz"; @import "rps_lesson"; +@import "csa-unit2-interactive"; @import "search"; @import "stack-clicker"; @import "theme/user-preferences"; diff --git a/_sass/open-coding/csa-unit2-interactive.scss b/_sass/open-coding/csa-unit2-interactive.scss new file mode 100644 index 0000000000..02e2cc402a --- /dev/null +++ b/_sass/open-coding/csa-unit2-interactive.scss @@ -0,0 +1,953 @@ +// AP CSA Unit 2 (Selection and Iteration) - Interactive Lesson Styles +// Follows the frq-interactive.scss card patterns and the project theme +// variables/mixins. Widgets are wired up by assets/js/csa-lessons/unit2-interactives.js + +@import "mixins/buttons"; +@import "mixins/panel"; +@import "mixins/container"; +@import "mixins/variables"; + +// =========================== +// Animations +// =========================== +@keyframes u2SlideDown { + from { opacity: 0; transform: translateY(-8px); } + to { opacity: 1; transform: translateY(0); } +} + +@keyframes u2Shake { + 0%, 100% { transform: translateX(0); } + 20%, 60% { transform: translateX(-4px); } + 40%, 80% { transform: translateX(4px); } +} + +@keyframes u2Pop { + 0% { transform: scale(1); } + 50% { transform: scale(1.08); } + 100% { transform: scale(1); } +} + +// =========================== +// Shared patterns +// =========================== +@mixin u2-feedback { + display: none; + margin-top: $spacing-sm; + padding: $spacing-sm; + border-radius: $radius-xs; + @include responsive-text($text-md); + line-height: 1.5; + color: var(--pref-text-color); + + code { + background: var(--pref-bg-color); + padding: 2px 6px; + border-radius: 3px; + color: var(--pref-text-color); + } + + &--correct { + display: block; + background: rgba($green, 0.12); + border-left: 4px solid $green; + animation: u2SlideDown $transition-slow ease; + } + + &--incorrect { + display: block; + background: rgba($red, 0.12); + border-left: 4px solid $red; + animation: u2Shake 0.4s ease; + } + + &--info { + display: block; + background: rgba($teal, 0.12); + border-left: 4px solid $teal; + animation: u2SlideDown $transition-slow ease; + } +} + +@mixin u2-option-btn { + @include base-button; + display: block; + width: 100%; + text-align: left; + padding: $spacing-sm $spacing-md; + border-radius: $radius-sm; + border-width: 2px; + line-height: 1.4; + transition: all $transition-base; + + code { + font-family: $mono-font; + background: transparent; + padding: 0; + color: inherit; + } + + &--correct { + border-color: $green !important; + background: rgba($green, 0.12) !important; + } + + &--incorrect { + border-color: $red !important; + background: rgba($red, 0.12) !important; + } + + &--disabled { + pointer-events: none; + opacity: 0.55; + } +} + +// =========================== +// Card shell used by every widget +// =========================== +.u2-card { + @include main-container; + max-width: 880px; + border-radius: $radius-lg; + overflow: hidden; + border: 1px solid var(--ui-border); + position: relative; + + &__header { + background: var(--pref-accent-color); + padding: $spacing-md $spacing-lg; + display: flex; + align-items: center; + justify-content: space-between; + gap: $spacing-sm; + flex-wrap: wrap; + } + + &__title { + margin: 0; + color: var(--pref-bg-color); + font-weight: 700; + @include responsive-text($text-xl); + } + + &__subtitle { + margin: 4px 0 0; + color: var(--pref-bg-color); + opacity: 0.85; + @include responsive-text($text-md); + flex-basis: 100%; + } + + &__badge { + display: none; + background: var(--pref-bg-color); + color: $green; + border-radius: 999px; + padding: 4px 12px; + font-weight: 700; + @include responsive-text($text-sm); + white-space: nowrap; + } + + &--done &__badge { + display: inline-block; + animation: u2Pop 0.4s ease; + } + + &__body { + background: var(--pref-bg-color); + padding: $spacing-lg; + } + + &__prompt { + color: var(--pref-text-color); + @include responsive-text($text-md); + line-height: 1.6; + margin: 0 0 $spacing-sm; + + code { + font-family: $mono-font; + background: var(--panel-mid); + padding: 2px 6px; + border-radius: 3px; + color: var(--pref-text-color); + } + } + + &__hint { + color: var(--text-muted); + @include responsive-text($text-sm); + margin: $spacing-xxs 0 0; + font-style: italic; + } +} + +// =========================== +// Buttons +// =========================== +.u2-btn { + @include text-button; + font-weight: 600; + padding: $spacing-xxs $spacing-md; + gap: 6px; + + &--primary { + background: var(--pref-accent-color); + border-color: var(--pref-accent-color); + color: var(--pref-bg-color); + } + + &--success { + background: $green; + border-color: $green; + color: var(--pref-bg-color); + } + + &--warn { + background: $orange; + border-color: $orange; + color: var(--pref-bg-color); + } + + &--ghost { + background: var(--panel-mid); + border-color: var(--ui-border); + color: var(--pref-text-color); + } + + &:disabled { + opacity: 0.4; + cursor: not-allowed; + transform: none; + } +} + +.u2-controls { + @include inline-container(flex, $spacing-xs); + flex-wrap: wrap; + margin-top: $spacing-md; +} + +.u2-feedback { @include u2-feedback; } + +// =========================== +// Code display with line highlighting +// =========================== +.u2-code { + background: var(--panel-mid); + border: 1px solid var(--ui-border); + border-radius: $radius-sm; + padding: $spacing-xs 0; + margin: 0 0 $spacing-sm; + font-family: $mono-font; + @include responsive-text($text-md); + line-height: 1.6; + overflow-x: auto; + counter-reset: u2line; + + &__line { + display: flex; + white-space: pre; + padding: 1px $spacing-sm 1px 0; + color: var(--pref-text-color); + border-left: 4px solid transparent; + transition: background $transition-fast, border-color $transition-fast; + + &::before { + counter-increment: u2line; + content: counter(u2line); + display: inline-block; + width: 2.2em; + margin-right: $spacing-xs; + text-align: right; + color: var(--text-muted); + user-select: none; + flex-shrink: 0; + } + + &--active { + background: rgba($warn, 0.18); + border-left-color: $warn; + } + + &--taken { + background: rgba($green, 0.14); + border-left-color: $green; + } + + &--skipped { + opacity: 0.45; + } + } +} + +// =========================== +// Output console +// =========================== +.u2-console { + background: var(--bg-0); + color: var(--pref-text-color); + border: 1px solid var(--ui-border); + border-left: 3px solid $green; + border-radius: $radius-sm; + padding: $spacing-xs $spacing-sm; + font-family: $mono-font; + @include responsive-text($text-md); + white-space: pre-wrap; + min-height: 48px; + max-height: 220px; + overflow-y: auto; + + &__label { + color: var(--text-muted); + @include responsive-text($text-xs); + text-transform: uppercase; + letter-spacing: 1px; + margin: 0 0 4px; + font-family: var(--pref-font-family); + } + + &__empty { + color: var(--text-muted); + font-style: italic; + } +} + +// =========================== +// 1. Multiple choice (predict the output, quick checks) +// =========================== +.u2-mcq { + &__q { + margin-bottom: $spacing-lg; + padding-bottom: $spacing-md; + border-bottom: 1px dashed var(--ui-border); + + &:last-child { + border-bottom: none; + margin-bottom: 0; + padding-bottom: 0; + } + } + + &__number { + color: var(--pref-accent-color); + font-weight: 700; + @include responsive-text($text-sm); + text-transform: uppercase; + letter-spacing: 1px; + margin-bottom: $spacing-xxs; + } + + &__options { + display: flex; + flex-direction: column; + gap: $spacing-xxs; + } + + &__option { @include u2-option-btn; } + + &__feedback { @include u2-feedback; } +} + +// =========================== +// 2. Short answer (fill in) +// =========================== +.u2-fill { + &__row { + @include inline-container(flex, $spacing-xs); + flex-wrap: wrap; + } + + &__input { + @include base-button; + cursor: text; + padding: $spacing-xxs $spacing-sm; + border-radius: $radius-xs; + font-family: $mono-font; + min-width: 140px; + flex: 1 1 200px; + + &--correct { border-color: $green !important; } + &--incorrect { border-color: $red !important; } + } + + &__feedback { @include u2-feedback; } +} + +// =========================== +// 3. Ordering (Parsons style) +// =========================== +.u2-order { + &__list { + display: flex; + flex-direction: column; + gap: $spacing-xxs; + margin-bottom: $spacing-sm; + } + + &__item { + display: flex; + align-items: center; + gap: $spacing-xs; + background: var(--panel-mid); + border: 2px solid var(--ui-border); + border-radius: $radius-sm; + padding: $spacing-xxs $spacing-sm; + cursor: grab; + user-select: none; + color: var(--pref-text-color); + transition: border-color $transition-base, background $transition-base; + + &:hover { border-color: var(--pref-accent-color); } + &.dragging { opacity: 0.4; cursor: grabbing; } + &.drag-over { border-color: var(--pref-accent-color); border-style: dashed; } + + &--correct { border-color: $green; background: rgba($green, 0.1); } + &--incorrect { border-color: $red; background: rgba($red, 0.1); } + } + + &__handle { + color: var(--text-muted); + font-weight: 700; + flex-shrink: 0; + } + + &__code { + font-family: $mono-font; + @include responsive-text($text-md); + white-space: pre; + flex: 1; + overflow-x: auto; + } + + &__moves { + display: flex; + gap: 4px; + flex-shrink: 0; + + button { + @include base-button; + padding: 2px 8px; + border-radius: $radius-xxs; + line-height: 1; + font-size: 12px; + } + } + + &__feedback { @include u2-feedback; } +} + +// =========================== +// 4. Sorting into buckets (classification) +// =========================== +.u2-sort { + &__pool { + display: flex; + flex-wrap: wrap; + gap: $spacing-xxs; + min-height: 44px; + padding: $spacing-xs; + background: var(--panel-mid); + border: 2px dashed var(--ui-border); + border-radius: $radius-sm; + margin-bottom: $spacing-md; + } + + &__item { + @include base-button; + padding: 6px $spacing-sm; + border-radius: $radius-xs; + border-width: 2px; + @include responsive-text($text-md); + cursor: grab; + user-select: none; + + code { font-family: $mono-font; color: inherit; background: transparent; padding: 0; } + + &--selected { + border-color: var(--pref-accent-color); + background: var(--panel-mid); + box-shadow: 0 0 0 2px var(--pref-accent-color); + } + + &--correct { border-color: $green !important; background: rgba($green, 0.12) !important; } + &--incorrect { border-color: $red !important; background: rgba($red, 0.12) !important; } + &.dragging { opacity: 0.4; } + } + + &__buckets { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: $spacing-sm; + } + + &__bucket { + background: var(--panel-mid); + border: 2px solid var(--ui-border); + border-radius: $radius-sm; + padding: $spacing-xs; + min-height: 90px; + display: flex; + flex-direction: column; + gap: $spacing-xxs; + cursor: pointer; + transition: border-color $transition-base; + + &:hover, &.drag-over { border-color: var(--pref-accent-color); } + } + + &__bucket-title { + color: var(--pref-accent-color); + font-weight: 700; + @include responsive-text($text-md); + text-align: center; + margin-bottom: 4px; + } + + &__help { + color: var(--text-muted); + @include responsive-text($text-sm); + margin: 0 0 $spacing-xxs; + } + + &__feedback { @include u2-feedback; } +} + +// =========================== +// 5. Step-by-step trace (code + variables + output) +// =========================== +.u2-trace { + &__params { + @include inline-container(flex, $spacing-sm); + flex-wrap: wrap; + margin-bottom: $spacing-sm; + + label { + color: var(--pref-text-color); + font-family: $mono-font; + @include responsive-text($text-md); + display: inline-flex; + align-items: center; + gap: 6px; + } + + input, select { + @include base-button; + cursor: text; + padding: 4px $spacing-xxs; + border-radius: $radius-xxs; + width: 80px; + font-family: $mono-font; + } + + select { cursor: pointer; width: auto; } + } + + &__layout { + display: grid; + grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); + gap: $spacing-md; + + @media (max-width: $breakpoint-mobile) { grid-template-columns: 1fr; } + } + + &__state { + display: flex; + flex-direction: column; + gap: $spacing-sm; + } + + &__vars { + width: 100%; + border-collapse: collapse; + font-family: $mono-font; + @include responsive-text($text-md); + + th, td { + border: 1px solid var(--ui-border); + padding: 4px $spacing-xxs; + text-align: left; + color: var(--pref-text-color); + } + + th { + background: var(--panel-mid); + color: var(--text-muted); + font-weight: 600; + @include responsive-text($text-xs); + text-transform: uppercase; + letter-spacing: 1px; + } + + td.changed { + background: rgba($warn, 0.2); + font-weight: 700; + } + } + + &__extra { + margin-top: 2px; + } + + &__note { + margin-top: $spacing-sm; + padding: $spacing-sm; + background: var(--panel-mid); + border-radius: $radius-sm; + border-left: 3px solid var(--pref-accent-color); + color: var(--text-muted); + @include responsive-text($text-md); + line-height: 1.5; + min-height: 40px; + + strong { color: var(--pref-accent-color); } + code { + background: var(--pref-bg-color); + padding: 2px 6px; + border-radius: 3px; + color: var(--pref-text-color); + font-family: $mono-font; + } + } + + &__counter { + color: var(--text-muted); + @include responsive-text($text-sm); + font-family: $mono-font; + margin-left: auto; + } + + // Letter/cell strips used by string and grid traces + &__cells { + display: flex; + flex-wrap: wrap; + gap: 4px; + } + + &__cell { + width: 30px; + height: 30px; + display: inline-flex; + align-items: center; + justify-content: center; + border: 1px solid var(--ui-border); + border-radius: $radius-xxs; + background: var(--panel-mid); + color: var(--pref-text-color); + font-family: $mono-font; + @include responsive-text($text-md); + transition: all $transition-fast; + + &--active { + background: var(--pref-accent-color); + color: var(--pref-bg-color); + border-color: var(--pref-accent-color); + transform: scale(1.1); + } + + &--hit { background: rgba($green, 0.35); border-color: $green; } + &--done { background: rgba($green, 0.2); border-color: $green; } + &--dim { opacity: 0.35; } + } + + &__grid { + display: grid; + gap: 4px; + width: max-content; + } +} + +// =========================== +// 6. Truth table builder +// =========================== +.u2-truth { + &__table { + width: 100%; + border-collapse: collapse; + font-family: $mono-font; + @include responsive-text($text-md); + margin-bottom: $spacing-sm; + + th, td { + border: 1px solid var(--ui-border); + padding: 6px $spacing-xxs; + text-align: center; + color: var(--pref-text-color); + } + + th { + background: var(--panel-mid); + @include responsive-text($text-sm); + } + + th.expr { color: var(--pref-accent-color); } + } + + &__given { color: var(--text-muted); } + + &__cell { + cursor: pointer; + user-select: none; + min-width: 48px; + transition: background $transition-fast; + + &:hover { background: var(--panel-mid); } + &--t { color: $green; font-weight: 700; } + &--f { color: $orange; font-weight: 700; } + &--correct { background: rgba($green, 0.18) !important; } + &--incorrect { background: rgba($red, 0.18) !important; } + } + + &__feedback { @include u2-feedback; } +} + +// =========================== +// 7. Live sandbox (inputs drive the code path) +// =========================== +.u2-live { + &__inputs { + display: flex; + flex-wrap: wrap; + gap: $spacing-md; + margin-bottom: $spacing-sm; + } + + &__field { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 150px; + + label { + color: var(--pref-text-color); + font-family: $mono-font; + @include responsive-text($text-md); + } + + input[type="number"], input[type="text"], select { + @include base-button; + cursor: text; + padding: 4px $spacing-xxs; + border-radius: $radius-xxs; + font-family: $mono-font; + } + + select { cursor: pointer; } + input[type="range"] { accent-color: var(--pref-accent-color); width: 180px; } + input[type="checkbox"] { accent-color: var(--pref-accent-color); width: 18px; height: 18px; } + } + + &__value { + color: var(--pref-accent-color); + font-weight: 700; + } + + &__layout { + display: grid; + grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); + gap: $spacing-md; + + @media (max-width: $breakpoint-mobile) { grid-template-columns: 1fr; } + } + + &__explain { + margin-top: $spacing-sm; + color: var(--text-muted); + @include responsive-text($text-md); + line-height: 1.5; + + strong { color: var(--pref-accent-color); } + code { + background: var(--panel-mid); + padding: 2px 6px; + border-radius: 3px; + color: var(--pref-text-color); + font-family: $mono-font; + } + } +} + +// =========================== +// 8. Flowchart walkthrough +// =========================== +.u2-flow { + &__layout { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + gap: $spacing-md; + + @media (max-width: $breakpoint-mobile) { grid-template-columns: 1fr; } + } + + &__chart { + display: flex; + flex-direction: column; + align-items: center; + gap: 0; + } + + &__node { + width: 100%; + max-width: 320px; + padding: $spacing-xs $spacing-sm; + border: 2px solid var(--ui-border); + background: var(--panel-mid); + color: var(--pref-text-color); + text-align: center; + @include responsive-text($text-md); + transition: all $transition-base; + box-sizing: border-box; + + &--start, &--end { border-radius: 999px; } + &--process { border-radius: $radius-xs; } + &--decision { + border-radius: $radius-xs; + border-style: dashed; + color: var(--pref-accent-color); + font-weight: 600; + } + &--active { + border-color: $warn; + background: rgba($warn, 0.18); + transform: scale(1.03); + box-shadow: $shadow-md; + } + &--visited { border-color: $green; } + } + + &__arrow { + color: var(--text-muted); + line-height: 1; + padding: 2px 0; + @include responsive-text($text-lg); + } + + &__jump { + color: var(--text-muted); + @include responsive-text($text-xs); + font-style: italic; + } + + &__panel { + display: flex; + flex-direction: column; + gap: $spacing-sm; + } + + &__question { + color: var(--pref-text-color); + @include responsive-text($text-md); + padding: $spacing-sm; + background: var(--panel-mid); + border-radius: $radius-sm; + border-left: 3px solid var(--pref-accent-color); + min-height: 40px; + } + + &__log { + background: var(--panel-mid); + border: 1px solid var(--ui-border); + border-radius: $radius-sm; + padding: $spacing-xs $spacing-sm; + max-height: 240px; + overflow-y: auto; + color: var(--text-muted); + @include responsive-text($text-sm); + font-family: $mono-font; + + div { padding: 1px 0; } + strong { color: var(--pref-text-color); } + } +} + +// =========================== +// 9. Execution counter (informal run-time analysis) +// =========================== +.u2-count { + &__row { + @include inline-container(flex, $spacing-xs); + flex-wrap: wrap; + margin-top: $spacing-sm; + } + + &__input { + @include base-button; + cursor: text; + padding: $spacing-xxs $spacing-sm; + border-radius: $radius-xs; + font-family: $mono-font; + width: 140px; + + &--correct { border-color: $green !important; } + &--incorrect { border-color: $red !important; } + } + + &__display { + display: flex; + gap: $spacing-md; + align-items: stretch; + margin-top: $spacing-sm; + flex-wrap: wrap; + } + + &__meter { + min-width: 150px; + text-align: center; + background: var(--panel-mid); + border: 2px solid var(--pref-accent-color); + border-radius: $radius-sm; + padding: $spacing-sm; + + .count-value { + color: var(--pref-text-color); + font-family: $mono-font; + font-size: 34px; + font-weight: 700; + line-height: 1; + } + + .count-label { + color: var(--text-muted); + @include responsive-text($text-xs); + text-transform: uppercase; + letter-spacing: 1px; + margin-top: 6px; + } + } + + &__console { flex: 1 1 200px; } + + &__feedback { @include u2-feedback; } +} + +// =========================== +// 10. Quiz scoreboard +// =========================== +.u2-quiz { + &__score { + text-align: center; + padding: $spacing-md; + background: var(--panel-mid); + border-radius: $radius-md; + margin-top: $spacing-md; + + .score-label { color: var(--text-muted); @include responsive-text($text-md); margin-bottom: 4px; } + .score-value { color: var(--pref-text-color); font-size: 30px; font-weight: 700; } + .score-sub { color: var(--text-muted); @include responsive-text($text-sm); margin-top: 4px; } + + .score-bar { + margin-top: $spacing-xs; + height: 8px; + background: var(--ui-border); + border-radius: $radius-xxs; + overflow: hidden; + + .score-fill { + height: 100%; + background: var(--pref-accent-color); + border-radius: $radius-xxs; + transition: width 0.5s ease; + } + } + } +} diff --git a/assets/js/csa-lessons/unit2-interactives.js b/assets/js/csa-lessons/unit2-interactives.js new file mode 100644 index 0000000000..622d87f471 --- /dev/null +++ b/assets/js/csa-lessons/unit2-interactives.js @@ -0,0 +1,1032 @@ +/** + * AP CSA Unit 2 Interactives (Selection and Iteration) + * + * Dependency-free widgets used by the Unit 2 lesson notebooks. Styles live in + * _sass/open-coding/csa-unit2-interactive.scss (class prefix: u2-). + * + * Declarative widgets are written as plain HTML in a lesson and wired up on load: + * .u2-mcq multiple choice (options carry data-correct / data-feedback) + * .u2-fill short answer (inputs carry data-answer, answers separated by |) + * .u2-order put code lines in order (Parsons style) + * .u2-sort drag or click items into labeled buckets + * .u2-quiz scoreboard wrapper around .u2-mcq__q and .u2-fill__q blocks + * + * Programmatic widgets are built by calling a U2 function with a config: + * U2.trace(id, cfg) step through code with a variable table and console + * U2.truth(id, cfg) fill in a truth table and check it + * U2.live(id, cfg) inputs drive which branch of the code runs + * U2.flow(id, cfg) walk through a flowchart by answering its decisions + * U2.count(id, cfg) predict, then count, statement executions + */ +(function (window, document) { + 'use strict'; + + var MAX_TRACE_STEPS = 400; + var PLAY_INTERVAL_MS = 900; + + // --------------------------------------------------------------------------- + // Small DOM helpers + // --------------------------------------------------------------------------- + function qs(selector, root) { return (root || document).querySelector(selector); } + function qsa(selector, root) { return Array.prototype.slice.call((root || document).querySelectorAll(selector)); } + + function el(tag, attrs, children) { + var node = document.createElement(tag); + if (attrs) { + Object.keys(attrs).forEach(function (key) { + if (key === 'class') node.className = attrs[key]; + else if (key === 'html') node.innerHTML = attrs[key]; + else if (key === 'text') node.textContent = attrs[key]; + else if (key.indexOf('on') === 0) node.addEventListener(key.slice(2), attrs[key]); + else node.setAttribute(key, attrs[key]); + }); + } + (children || []).forEach(function (child) { + if (child === null || child === undefined) return; + node.appendChild(typeof child === 'string' ? document.createTextNode(child) : child); + }); + return node; + } + + function escapeHtml(text) { + return String(text) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); + } + + function shuffle(array) { + var copy = array.slice(); + for (var i = copy.length - 1; i > 0; i--) { + var j = Math.floor(Math.random() * (i + 1)); + var tmp = copy[i]; copy[i] = copy[j]; copy[j] = tmp; + } + return copy; + } + + function button(label, kind, onClick) { + return el('button', { type: 'button', class: 'u2-btn u2-btn--' + (kind || 'ghost'), text: label, onclick: onClick }); + } + + // Feedback boxes keep their base class and swap a --correct/--incorrect/--info modifier. + function setFeedback(box, kind, html) { + if (!box) return; + if (!box.dataset.u2base) box.dataset.u2base = box.classList[0] || 'u2-feedback'; + var base = box.dataset.u2base; + box.className = kind ? base + ' ' + base + '--' + kind : base; + box.innerHTML = html || ''; + } + + function findOrCreateFeedback(container, className) { + var box = qs('.' + className, container) || qs('.u2-feedback', container); + if (!box) { + box = el('div', { class: className }); + container.appendChild(box); + } + return box; + } + + // --------------------------------------------------------------------------- + // Completion badge (persisted per page + widget id in localStorage) + // --------------------------------------------------------------------------- + function storageKey(card) { + return 'u2done:' + window.location.pathname + '#' + card.id; + } + + function ensureBadge(card) { + var header = qs('.u2-card__header', card); + if (!header) return null; + var badge = qs('.u2-card__badge', header); + if (!badge) { + badge = el('span', { class: 'u2-card__badge', text: 'Completed' }); + header.appendChild(badge); + } + return badge; + } + + function markDone(card) { + if (!card) return; + card.classList.add('u2-card--done'); + ensureBadge(card); + if (card.id) { + try { window.localStorage.setItem(storageKey(card), '1'); } catch (err) { /* storage unavailable */ } + } + } + + function restoreDone(card) { + if (!card || !card.id) return; + try { + if (window.localStorage.getItem(storageKey(card)) === '1') { + card.classList.add('u2-card--done'); + ensureBadge(card); + } + } catch (err) { /* storage unavailable */ } + } + + function announce(card, detail) { + card.dispatchEvent(new CustomEvent('u2:answered', { bubbles: true, detail: detail })); + } + + // --------------------------------------------------------------------------- + // Code rendering shared by trace / live / count + // --------------------------------------------------------------------------- + function renderCode(lines) { + var block = el('div', { class: 'u2-code' }); + lines.forEach(function (line) { + block.appendChild(el('div', { class: 'u2-code__line', text: line === '' ? ' ' : line })); + }); + return block; + } + + function highlightLines(block, active, taken, skipped) { + qsa('.u2-code__line', block).forEach(function (lineEl, index) { + lineEl.classList.toggle('u2-code__line--active', (active || []).indexOf(index) !== -1); + lineEl.classList.toggle('u2-code__line--taken', (taken || []).indexOf(index) !== -1); + lineEl.classList.toggle('u2-code__line--skipped', (skipped || []).indexOf(index) !== -1); + }); + } + + function renderConsole(label) { + var wrap = el('div'); + wrap.appendChild(el('div', { class: 'u2-console__label', text: label || 'Output' })); + var box = el('div', { class: 'u2-console' }); + wrap.appendChild(box); + wrap.box = box; + return wrap; + } + + function setConsole(box, text) { + if (text === '' || text === null || text === undefined) { + box.innerHTML = '(no output yet)'; + } else { + box.textContent = text; + } + } + + function formatValue(value) { + if (typeof value === 'string') return value; + if (typeof value === 'boolean') return value ? 'true' : 'false'; + if (value === null || value === undefined) return 'null'; + if (typeof value === 'number' && !Number.isInteger(value)) return String(Math.round(value * 1000) / 1000); + return String(value); + } + + // --------------------------------------------------------------------------- + // 1. Multiple choice + // --------------------------------------------------------------------------- + function initMcq(card) { + var groups = qsa('.u2-mcq__q', card); + if (!groups.length) groups = [card]; + var solved = 0; + + groups.forEach(function (group) { + var options = qsa('.u2-mcq__option', group); + if (!options.length) return; + var feedback = findOrCreateFeedback(qs('.u2-mcq__options', group) ? qs('.u2-mcq__options', group).parentNode : group, 'u2-mcq__feedback'); + var done = false; + var attempts = 0; + + options.forEach(function (option) { + option.setAttribute('type', 'button'); + option.addEventListener('click', function () { + if (done) return; + var correct = option.dataset.correct === 'true'; + options.forEach(function (other) { other.classList.remove('u2-mcq__option--incorrect'); }); + if (correct) { + done = true; + solved += 1; + option.classList.add('u2-mcq__option--correct'); + options.forEach(function (other) { if (other !== option) other.classList.add('u2-mcq__option--disabled'); }); + setFeedback(feedback, 'correct', option.dataset.feedback || 'Correct.'); + announce(card, { widget: 'mcq', correct: true, firstTry: attempts === 0 }); + if (solved === groups.length) markDone(card); + } else { + attempts += 1; + option.classList.add('u2-mcq__option--incorrect'); + setFeedback(feedback, 'incorrect', option.dataset.feedback || 'Not quite. Try again.'); + announce(card, { widget: 'mcq', correct: false, firstTry: false }); + } + }); + }); + }); + } + + // --------------------------------------------------------------------------- + // 2. Short answer + // --------------------------------------------------------------------------- + function normalizeAnswer(text) { + return String(text).trim().toLowerCase().replace(/\s+/g, ' '); + } + + function answerMatches(given, expected) { + var normalizedGiven = normalizeAnswer(given); + var compactGiven = normalizedGiven.replace(/\s+/g, ''); + return expected.split('|').some(function (candidate) { + var normalizedCandidate = normalizeAnswer(candidate); + if (normalizedGiven === normalizedCandidate) return true; + if (compactGiven !== '' && compactGiven === normalizedCandidate.replace(/\s+/g, '')) return true; + var a = parseFloat(normalizedGiven); + var b = parseFloat(normalizedCandidate); + return !isNaN(a) && !isNaN(b) && /^-?\d+(\.\d+)?$/.test(normalizedGiven) && a === b; + }); + } + + function initFill(card) { + var groups = qsa('.u2-fill__q', card); + if (!groups.length) groups = [card]; + var solved = 0; + + groups.forEach(function (group) { + var input = qs('.u2-fill__input', group); + if (!input) return; + var row = input.parentNode; + var check = qs('.u2-fill__check', group); + if (!check) { + check = button('Check', 'primary'); + row.appendChild(check); + } + var feedback = findOrCreateFeedback(group, 'u2-fill__feedback'); + var done = false; + var attempts = 0; + + function evaluate() { + if (done) return; + var expected = input.dataset.answer || ''; + if (answerMatches(input.value, expected)) { + done = true; + solved += 1; + input.classList.remove('u2-fill__input--incorrect'); + input.classList.add('u2-fill__input--correct'); + input.disabled = true; + setFeedback(feedback, 'correct', input.dataset.feedback || 'Correct.'); + announce(card, { widget: 'fill', correct: true, firstTry: attempts === 0 }); + if (solved === groups.length) markDone(card); + } else { + attempts += 1; + input.classList.add('u2-fill__input--incorrect'); + setFeedback(feedback, 'incorrect', input.dataset.hint || 'Not quite. Check the code again and retry.'); + announce(card, { widget: 'fill', correct: false, firstTry: false }); + } + } + + check.addEventListener('click', evaluate); + input.addEventListener('keydown', function (event) { + if (event.key === 'Enter') { event.preventDefault(); evaluate(); } + }); + }); + } + + // --------------------------------------------------------------------------- + // 3. Ordering (Parsons style) + // --------------------------------------------------------------------------- + function initOrder(card) { + var list = qs('.u2-order__list', card); + if (!list) return; + var items = qsa('.u2-order__item', list); + if (items.length < 2) return; + var feedback = findOrCreateFeedback(card.querySelector('.u2-card__body') || card, 'u2-order__feedback'); + var dragged = null; + + // Lines that share a data-group may appear in any order among themselves + // (for example two variable declarations), so compare by group when one is set. + function slotKey(item) { return item.dataset.group || ('pos' + item.dataset.pos); } + items.forEach(function (item, index) { + if (item.dataset.pos === undefined) item.dataset.pos = String(index); + }); + var expectedKeys = items.slice().sort(function (a, b) { return Number(a.dataset.pos) - Number(b.dataset.pos); }).map(slotKey); + + items.forEach(function (item) { + if (!qs('.u2-order__code', item)) { + var text = item.textContent.replace(/^\n/, '').replace(/\s+$/, ''); + item.textContent = ''; + item.appendChild(el('span', { class: 'u2-order__code', text: text })); + } + item.insertBefore(el('span', { class: 'u2-order__handle', text: '☰', 'aria-hidden': 'true' }), item.firstChild); + var moves = el('span', { class: 'u2-order__moves' }); + moves.appendChild(el('button', { type: 'button', text: '▲', title: 'Move up', 'aria-label': 'Move up', onclick: function () { moveItem(item, -1); } })); + moves.appendChild(el('button', { type: 'button', text: '▼', title: 'Move down', 'aria-label': 'Move down', onclick: function () { moveItem(item, 1); } })); + item.appendChild(moves); + item.setAttribute('draggable', 'true'); + + item.addEventListener('dragstart', function () { dragged = item; item.classList.add('dragging'); }); + item.addEventListener('dragend', function () { item.classList.remove('dragging'); qsa('.drag-over', list).forEach(function (n) { n.classList.remove('drag-over'); }); }); + item.addEventListener('dragover', function (event) { event.preventDefault(); if (dragged && dragged !== item) item.classList.add('drag-over'); }); + item.addEventListener('dragleave', function () { item.classList.remove('drag-over'); }); + item.addEventListener('drop', function (event) { + event.preventDefault(); + item.classList.remove('drag-over'); + if (!dragged || dragged === item) return; + var siblings = qsa('.u2-order__item', list); + var from = siblings.indexOf(dragged); + var to = siblings.indexOf(item); + list.insertBefore(dragged, from < to ? item.nextSibling : item); + clearMarks(); + }); + }); + + function moveItem(item, direction) { + var siblings = qsa('.u2-order__item', list); + var index = siblings.indexOf(item); + var target = index + direction; + if (target < 0 || target >= siblings.length) return; + list.insertBefore(item, direction < 0 ? siblings[target] : siblings[target].nextSibling); + clearMarks(); + } + + function clearMarks() { + qsa('.u2-order__item', list).forEach(function (item) { + item.classList.remove('u2-order__item--correct', 'u2-order__item--incorrect'); + }); + setFeedback(feedback, null, ''); + } + + function scramble() { + var current = qsa('.u2-order__item', list); + var order = shuffle(current); + var isSorted = order.every(function (item, index) { return Number(item.dataset.pos) === index; }); + if (isSorted) order.reverse(); + order.forEach(function (item) { list.appendChild(item); }); + clearMarks(); + } + + function check() { + var current = qsa('.u2-order__item', list); + var wrong = 0; + current.forEach(function (item, index) { + var ok = slotKey(item) === expectedKeys[index]; + item.classList.toggle('u2-order__item--correct', ok); + item.classList.toggle('u2-order__item--incorrect', !ok); + if (!ok) wrong += 1; + }); + if (wrong === 0) { + setFeedback(feedback, 'correct', card.dataset.success || 'Correct order. The program reads top to bottom exactly as Java will run it.'); + announce(card, { widget: 'order', correct: true }); + markDone(card); + } else { + setFeedback(feedback, 'incorrect', '' + wrong + ' line' + (wrong === 1 ? ' is' : 's are') + ' out of place. Red lines need to move. ' + (card.dataset.hint || 'Think about what must happen first.')); + announce(card, { widget: 'order', correct: false }); + } + } + + var controls = el('div', { class: 'u2-controls' }, [ + button('Check order', 'success', check), + button('Shuffle again', 'warn', scramble) + ]); + list.parentNode.insertBefore(controls, list.nextSibling); + scramble(); + } + + // --------------------------------------------------------------------------- + // 4. Sort into buckets + // --------------------------------------------------------------------------- + function initSort(card) { + var pool = qs('.u2-sort__pool', card); + var buckets = qsa('.u2-sort__bucket', card); + if (!pool || !buckets.length) return; + var items = qsa('.u2-sort__item', card); + var selected = null; + var dragged = null; + + function clearMarks() { + items.forEach(function (item) { item.classList.remove('u2-sort__item--correct', 'u2-sort__item--incorrect'); }); + setFeedback(feedback, null, ''); + } + + function select(item) { + if (selected === item) { item.classList.remove('u2-sort__item--selected'); selected = null; return; } + if (selected) selected.classList.remove('u2-sort__item--selected'); + selected = item; + item.classList.add('u2-sort__item--selected'); + } + + function place(item, target) { + target.appendChild(item); + item.classList.remove('u2-sort__item--selected'); + if (selected === item) selected = null; + clearMarks(); + } + + items.forEach(function (item) { + item.setAttribute('type', 'button'); + item.setAttribute('draggable', 'true'); + item.addEventListener('click', function () { + if (item.parentNode !== pool) { place(item, pool); return; } + select(item); + }); + item.addEventListener('dragstart', function () { dragged = item; item.classList.add('dragging'); }); + item.addEventListener('dragend', function () { item.classList.remove('dragging'); dragged = null; }); + }); + + buckets.concat([pool]).forEach(function (zone) { + zone.addEventListener('click', function (event) { + if (event.target.classList.contains('u2-sort__item')) return; + if (selected && zone !== pool) place(selected, zone); + }); + zone.addEventListener('dragover', function (event) { event.preventDefault(); zone.classList.add('drag-over'); }); + zone.addEventListener('dragleave', function () { zone.classList.remove('drag-over'); }); + zone.addEventListener('drop', function (event) { + event.preventDefault(); + zone.classList.remove('drag-over'); + if (dragged) place(dragged, zone); + }); + }); + + function check() { + var wrong = 0; + var unplaced = 0; + items.forEach(function (item) { + var zone = item.parentNode; + if (zone === pool) { unplaced += 1; return; } + var ok = zone.dataset.bucket === item.dataset.bucket; + item.classList.toggle('u2-sort__item--correct', ok); + item.classList.toggle('u2-sort__item--incorrect', !ok); + if (!ok) wrong += 1; + }); + if (unplaced > 0) { + setFeedback(feedback, 'info', '' + unplaced + ' item' + (unplaced === 1 ? '' : 's') + ' still in the pool. Place everything before checking.'); + } else if (wrong === 0) { + setFeedback(feedback, 'correct', card.dataset.success || 'All sorted correctly.'); + announce(card, { widget: 'sort', correct: true }); + markDone(card); + } else { + setFeedback(feedback, 'incorrect', '' + wrong + ' item' + (wrong === 1 ? ' is' : 's are') + ' in the wrong bucket. Click a red item to send it back to the pool and try again.'); + announce(card, { widget: 'sort', correct: false }); + } + } + + function reset() { + shuffle(items).forEach(function (item) { pool.appendChild(item); item.classList.remove('u2-sort__item--selected'); }); + selected = null; + clearMarks(); + } + + var controls = el('div', { class: 'u2-controls' }, [ + button('Check buckets', 'success', check), + button('Reset', 'warn', reset) + ]); + (qs('.u2-card__body', card) || card).appendChild(controls); + var feedback = findOrCreateFeedback(qs('.u2-card__body', card) || card, 'u2-sort__feedback'); + reset(); + } + + // --------------------------------------------------------------------------- + // 5. Step-by-step trace + // cfg = { code: [...lines], params: [{name,label,value,min,max,step,options}], + // run: function* (params, io) { yield {line, vars, note} }, + // extra: function (vars) -> html string (optional) } + // --------------------------------------------------------------------------- + function traceWidget(id, cfg) { + var card = document.getElementById(id); + if (!card) return; + var body = qs('.u2-card__body', card) || card; + var steps = []; + var index = 0; + var timer = null; + var paramInputs = {}; + + var paramsBar = el('div', { class: 'u2-trace__params' }); + (cfg.params || []).forEach(function (param) { + var input; + if (param.options) { + input = el('select'); + param.options.forEach(function (option) { + input.appendChild(el('option', { value: String(option), text: String(option) })); + }); + input.value = String(param.value); + } else { + input = el('input', { type: param.type || 'number', value: String(param.value) }); + if (param.min !== undefined) input.min = param.min; + if (param.max !== undefined) input.max = param.max; + if (param.step !== undefined) input.step = param.step; + if (param.maxlength !== undefined) input.maxLength = param.maxlength; + } + input.addEventListener('change', rebuild); + paramInputs[param.name] = { input: input, spec: param }; + paramsBar.appendChild(el('label', {}, [(param.label || param.name) + ' = ', input])); + }); + if (cfg.params && cfg.params.length) body.appendChild(paramsBar); + + var code = renderCode(cfg.code); + var vars = el('table', { class: 'u2-trace__vars' }); + var extra = el('div', { class: 'u2-trace__extra' }); + var consoleWrap = renderConsole('Console'); + var state = el('div', { class: 'u2-trace__state' }, [extra, vars, consoleWrap]); + body.appendChild(el('div', { class: 'u2-trace__layout' }, [code, state])); + var note = el('div', { class: 'u2-trace__note' }); + body.appendChild(note); + + var backBtn = button('Back', 'ghost', function () { stop(); go(index - 1); }); + var nextBtn = button('Next step', 'primary', function () { stop(); go(index + 1); }); + var playBtn = button('Play', 'success', function () { timer ? stop() : play(); }); + var resetBtn = button('Reset', 'warn', function () { stop(); go(0); }); + var counter = el('span', { class: 'u2-trace__counter' }); + body.appendChild(el('div', { class: 'u2-controls' }, [backBtn, nextBtn, playBtn, resetBtn, counter])); + + function readParams() { + var values = {}; + Object.keys(paramInputs).forEach(function (name) { + var entry = paramInputs[name]; + var raw = entry.input.value; + if (entry.spec.type === 'text' || entry.spec.options) values[name] = raw; + else { + var num = Number(raw); + if (isNaN(num)) num = Number(entry.spec.value); + if (entry.spec.min !== undefined) num = Math.max(entry.spec.min, num); + if (entry.spec.max !== undefined) num = Math.min(entry.spec.max, num); + num = Math.round(num); + entry.input.value = String(num); + values[name] = num; + } + }); + return values; + } + + function compute() { + var io = { + buffer: [], + print: function (text) { this.buffer.push(String(text)); }, + println: function (text) { this.buffer.push((text === undefined ? '' : String(text)) + '\n'); } + }; + steps = []; + var iterator = cfg.run(readParams(), io); + var result = iterator.next(); + while (!result.done && steps.length < MAX_TRACE_STEPS) { + var step = result.value || {}; + var snapshot = {}; + Object.keys(step.vars || {}).forEach(function (key) { snapshot[key] = step.vars[key]; }); + steps.push({ line: step.line, vars: snapshot, note: step.note || '', out: io.buffer.join('') }); + result = iterator.next(); + } + if (!steps.length) steps.push({ line: -1, vars: {}, note: '', out: '' }); + } + + function render() { + var step = steps[index]; + var previous = index > 0 ? steps[index - 1] : null; + highlightLines(code, step.line >= 0 ? [step.line] : []); + + vars.innerHTML = ''; + // Keys starting with __ carry data for cfg.extra and stay out of the table. + var keys = Object.keys(step.vars).filter(function (key) { return key.indexOf('__') !== 0; }); + if (keys.length) { + var head = el('tr', {}, [el('th', { text: 'Variable' }), el('th', { text: 'Value' })]); + vars.appendChild(head); + keys.forEach(function (key) { + var changed = previous && String(previous.vars[key]) !== String(step.vars[key]); + vars.appendChild(el('tr', {}, [ + el('td', { text: key }), + el('td', { text: formatValue(step.vars[key]), class: changed ? 'changed' : '' }) + ])); + }); + } + extra.innerHTML = cfg.extra ? (cfg.extra(step.vars, index, step) || '') : ''; + setConsole(consoleWrap.box, step.out); + note.innerHTML = step.note || (index === 0 ? 'Press Next step to begin.' : ''); + counter.textContent = 'Step ' + (index + 1) + ' / ' + steps.length; + backBtn.disabled = index === 0; + nextBtn.disabled = index >= steps.length - 1; + if (index >= steps.length - 1) { + stop(); + if (steps.length > 1) markDone(card); + } + } + + function go(target) { + index = Math.max(0, Math.min(steps.length - 1, target)); + render(); + } + + function play() { + if (index >= steps.length - 1) go(0); + playBtn.textContent = 'Pause'; + timer = window.setInterval(function () { + if (index >= steps.length - 1) { stop(); return; } + go(index + 1); + }, PLAY_INTERVAL_MS); + } + + function stop() { + if (timer) window.clearInterval(timer); + timer = null; + playBtn.textContent = 'Play'; + } + + function rebuild() { + stop(); + compute(); + go(0); + } + + rebuild(); + } + + // --------------------------------------------------------------------------- + // 6. Truth table + // cfg = { vars: ['a','b'], cols: [{label, fn: function(values) -> boolean}] } + // --------------------------------------------------------------------------- + function truthWidget(id, cfg) { + var card = document.getElementById(id); + if (!card) return; + var body = qs('.u2-card__body', card) || card; + var rows = []; + var total = 1 << cfg.vars.length; + for (var r = 0; r < total; r++) { + var values = {}; + cfg.vars.forEach(function (name, i) { + values[name] = ((r >> (cfg.vars.length - 1 - i)) & 1) === 0; // true rows first + }); + rows.push(values); + } + + var table = el('table', { class: 'u2-truth__table' }); + var head = el('tr'); + cfg.vars.forEach(function (name) { head.appendChild(el('th', { text: name })); }); + cfg.cols.forEach(function (col) { head.appendChild(el('th', { class: 'expr', text: col.label })); }); + table.appendChild(head); + + var cells = []; + rows.forEach(function (values) { + var tr = el('tr'); + cfg.vars.forEach(function (name) { + tr.appendChild(el('td', { class: 'u2-truth__given', text: values[name] ? 'true' : 'false' })); + }); + cfg.cols.forEach(function (col) { + var cell = el('td', { class: 'u2-truth__cell', text: '?', title: 'Click to cycle true / false' }); + cell.dataset.state = ''; + cell.expected = !!col.fn(values); + cell.addEventListener('click', function () { + var next = cell.dataset.state === '' ? 't' : (cell.dataset.state === 't' ? 'f' : ''); + setCell(cell, next); + cell.classList.remove('u2-truth__cell--correct', 'u2-truth__cell--incorrect'); + setFeedback(feedback, null, ''); + }); + cells.push(cell); + tr.appendChild(cell); + }); + table.appendChild(tr); + }); + body.appendChild(table); + + function setCell(cell, state) { + cell.dataset.state = state; + cell.classList.toggle('u2-truth__cell--t', state === 't'); + cell.classList.toggle('u2-truth__cell--f', state === 'f'); + cell.textContent = state === 't' ? 'true' : (state === 'f' ? 'false' : '?'); + } + + var feedback = el('div', { class: 'u2-truth__feedback' }); + + function check() { + var wrong = 0; + var blank = 0; + cells.forEach(function (cell) { + if (cell.dataset.state === '') { blank += 1; cell.classList.remove('u2-truth__cell--correct', 'u2-truth__cell--incorrect'); return; } + var ok = (cell.dataset.state === 't') === cell.expected; + cell.classList.toggle('u2-truth__cell--correct', ok); + cell.classList.toggle('u2-truth__cell--incorrect', !ok); + if (!ok) wrong += 1; + }); + if (blank > 0) { + setFeedback(feedback, 'info', '' + blank + ' cell' + (blank === 1 ? '' : 's') + ' still blank. Click a cell to set it to true or false.'); + } else if (wrong === 0) { + setFeedback(feedback, 'correct', cfg.success || 'Every row is right.'); + announce(card, { widget: 'truth', correct: true }); + markDone(card); + } else { + setFeedback(feedback, 'incorrect', '' + wrong + ' cell' + (wrong === 1 ? ' is' : 's are') + ' wrong. ' + (cfg.hint || 'Evaluate each expression one row at a time.')); + announce(card, { widget: 'truth', correct: false }); + } + } + + function reveal() { + cells.forEach(function (cell) { + setCell(cell, cell.expected ? 't' : 'f'); + cell.classList.remove('u2-truth__cell--correct', 'u2-truth__cell--incorrect'); + }); + setFeedback(feedback, 'info', 'Answers shown. Read each row and make sure you can explain it.'); + } + + function reset() { + cells.forEach(function (cell) { + setCell(cell, ''); + cell.classList.remove('u2-truth__cell--correct', 'u2-truth__cell--incorrect'); + }); + setFeedback(feedback, null, ''); + } + + body.appendChild(el('div', { class: 'u2-controls' }, [ + button('Check table', 'success', check), + button('Reset', 'warn', reset), + button('Show answers', 'ghost', reveal) + ])); + body.appendChild(feedback); + } + + // --------------------------------------------------------------------------- + // 7. Live sandbox + // cfg = { inputs: [{name,label,type,min,max,step,value,options}], code: [...], + // evaluate: function(values) -> { lines: [..], skipped: [..], output: string|array, explain: html } } + // --------------------------------------------------------------------------- + function liveWidget(id, cfg) { + var card = document.getElementById(id); + if (!card) return; + var body = qs('.u2-card__body', card) || card; + var inputs = {}; + var inputsBar = el('div', { class: 'u2-live__inputs' }); + var interactions = 0; + + (cfg.inputs || []).forEach(function (spec) { + var input; + var valueLabel = null; + if (spec.type === 'select') { + input = el('select'); + spec.options.forEach(function (option) { input.appendChild(el('option', { value: String(option), text: String(option) })); }); + input.value = String(spec.value); + } else if (spec.type === 'checkbox') { + input = el('input', { type: 'checkbox' }); + input.checked = !!spec.value; + } else { + input = el('input', { type: spec.type || 'number', value: String(spec.value) }); + if (spec.min !== undefined) input.min = spec.min; + if (spec.max !== undefined) input.max = spec.max; + if (spec.step !== undefined) input.step = spec.step; + if (spec.maxlength !== undefined) input.maxLength = spec.maxlength; + if (spec.type === 'range') valueLabel = el('span', { class: 'u2-live__value', text: String(spec.value) }); + } + inputs[spec.name] = { input: input, spec: spec, valueLabel: valueLabel }; + var label = el('label', {}, [spec.label || spec.name, valueLabel ? ' = ' : '', valueLabel]); + inputsBar.appendChild(el('div', { class: 'u2-live__field' }, [label, input])); + input.addEventListener('input', function () { interactions += 1; update(); }); + input.addEventListener('change', function () { interactions += 1; update(); }); + }); + body.appendChild(inputsBar); + + var code = renderCode(cfg.code); + var consoleWrap = renderConsole('Output'); + body.appendChild(el('div', { class: 'u2-live__layout' }, [code, consoleWrap])); + var explain = el('div', { class: 'u2-live__explain' }); + body.appendChild(explain); + + function readValues() { + var values = {}; + Object.keys(inputs).forEach(function (name) { + var entry = inputs[name]; + var input = entry.input; + if (entry.spec.type === 'checkbox') values[name] = input.checked; + else if (entry.spec.type === 'select' || entry.spec.type === 'text') values[name] = input.value; + else { + var num = Number(input.value); + if (isNaN(num) || input.value === '') num = Number(entry.spec.value); + values[name] = entry.spec.decimals ? num : Math.round(num); + if (entry.valueLabel) entry.valueLabel.textContent = formatValue(values[name]); + } + }); + return values; + } + + function update() { + var result = cfg.evaluate(readValues()) || {}; + highlightLines(code, result.lines || [], [], result.skipped || []); + var output = Array.isArray(result.output) ? result.output.join('\n') : (result.output || ''); + setConsole(consoleWrap.box, output); + explain.innerHTML = result.explain || ''; + if (interactions >= (cfg.doneAfter || 3)) markDone(card); + } + + update(); + } + + // --------------------------------------------------------------------------- + // 8. Flowchart walkthrough + // cfg = { nodes: [{id, type:'start'|'process'|'decision'|'end', text, next, yes, no}], maxSteps } + // --------------------------------------------------------------------------- + function flowWidget(id, cfg) { + var card = document.getElementById(id); + if (!card) return; + var body = qs('.u2-card__body', card) || card; + var nodesById = {}; + var nodeEls = {}; + var chart = el('div', { class: 'u2-flow__chart' }); + + cfg.nodes.forEach(function (node) { nodesById[node.id] = node; }); + + function nodeText(nodeId) { + return nodesById[nodeId] ? '"' + nodesById[nodeId].text + '"' : '?'; + } + + cfg.nodes.forEach(function (node, i) { + var nodeEl = el('div', { class: 'u2-flow__node u2-flow__node--' + node.type, text: node.text }); + nodeEls[node.id] = nodeEl; + chart.appendChild(nodeEl); + if (node.type === 'end') return; + var following = cfg.nodes[i + 1]; + var followingId = following ? following.id : null; + var jumps = []; + if (node.type === 'decision') { + if (node.yes !== followingId) jumps.push('Yes → ' + nodeText(node.yes)); + if (node.no !== followingId) jumps.push('No → ' + nodeText(node.no)); + } else if (node.next !== followingId) { + jumps.push('then → ' + nodeText(node.next)); + } + chart.appendChild(el('div', { class: 'u2-flow__arrow', text: '↓' })); + if (jumps.length) chart.appendChild(el('div', { class: 'u2-flow__jump', text: jumps.join(' ') })); + }); + + var question = el('div', { class: 'u2-flow__question' }); + var log = el('div', { class: 'u2-flow__log' }); + var controls = el('div', { class: 'u2-controls' }); + var panel = el('div', { class: 'u2-flow__panel' }, [question, controls, log]); + body.appendChild(el('div', { class: 'u2-flow__layout' }, [chart, panel])); + + var current = null; + var stepCount = 0; + var visited = []; + + function setCurrent(nodeId) { + Object.keys(nodeEls).forEach(function (key) { nodeEls[key].classList.remove('u2-flow__node--active'); }); + current = nodesById[nodeId]; + stepCount += 1; + nodeEls[nodeId].classList.add('u2-flow__node--active'); + nodeEls[nodeId].classList.add('u2-flow__node--visited'); + var entry = el('div', { html: '' + stepCount + '. ' + escapeHtml(current.text) }); + log.appendChild(entry); + log.scrollTop = log.scrollHeight; + renderControls(); + } + + function renderControls() { + controls.innerHTML = ''; + if (!current) { + question.textContent = 'Press Start to walk through the flowchart.'; + controls.appendChild(button('Start', 'primary', function () { reset(); setCurrent(cfg.nodes[0].id); })); + return; + } + if (current.type === 'end') { + question.innerHTML = 'Finished in ' + stepCount + ' steps. ' + (cfg.finish || ''); + controls.appendChild(button('Run again', 'warn', function () { reset(); setCurrent(cfg.nodes[0].id); })); + markDone(card); + return; + } + if (stepCount > (cfg.maxSteps || 40)) { + question.innerHTML = 'This is looping a lot. ' + (cfg.loopWarning || 'Is there a way out of the loop? Try a different answer.'); + } else if (current.type === 'decision') { + question.innerHTML = 'Decision: ' + escapeHtml(current.text); + } else { + question.innerHTML = escapeHtml(current.text); + } + if (current.type === 'decision') { + controls.appendChild(button('Yes', 'success', function () { logAnswer('Yes'); setCurrent(current.yes); })); + controls.appendChild(button('No', 'warn', function () { logAnswer('No'); setCurrent(current.no); })); + } else { + controls.appendChild(button('Next', 'primary', function () { setCurrent(current.next); })); + } + controls.appendChild(button('Reset', 'ghost', reset)); + } + + function logAnswer(answer) { + var last = log.lastElementChild; + if (last) last.innerHTML += ' → ' + answer + ''; + } + + function reset() { + current = null; + stepCount = 0; + log.innerHTML = ''; + Object.keys(nodeEls).forEach(function (key) { nodeEls[key].classList.remove('u2-flow__node--active', 'u2-flow__node--visited'); }); + renderControls(); + } + + reset(); + } + + // --------------------------------------------------------------------------- + // 9. Execution counter + // cfg = { code: [...], question, answer, explain, run: function(io) -> count } + // --------------------------------------------------------------------------- + function countWidget(id, cfg) { + var card = document.getElementById(id); + if (!card) return; + var body = qs('.u2-card__body', card) || card; + body.appendChild(renderCode(cfg.code)); + if (cfg.question) body.appendChild(el('p', { class: 'u2-card__prompt', html: cfg.question })); + + var input = el('input', { class: 'u2-count__input', type: 'number', placeholder: 'your guess' }); + var feedback = el('div', { class: 'u2-count__feedback' }); + var meter = el('div', { class: 'u2-count__meter' }, [ + el('div', { class: 'count-value', text: '0' }), + el('div', { class: 'count-label', text: cfg.label || 'executions' }) + ]); + var consoleWrap = renderConsole('Output'); + consoleWrap.classList.add('u2-count__console'); + setConsole(consoleWrap.box, ''); + var counted = false; + var attempts = 0; + + function check() { + var guess = Number(input.value); + if (input.value === '' || isNaN(guess)) { setFeedback(feedback, 'info', 'Type a number first.'); return; } + if (guess === cfg.answer) { + input.classList.remove('u2-count__input--incorrect'); + input.classList.add('u2-count__input--correct'); + setFeedback(feedback, 'correct', 'Correct: ' + cfg.answer + '. ' + (cfg.explain || '')); + announce(card, { widget: 'count', correct: true, firstTry: attempts === 0 }); + markDone(card); + } else { + attempts += 1; + input.classList.add('u2-count__input--incorrect'); + setFeedback(feedback, 'incorrect', 'Not ' + guess + '. ' + (guess > cfg.answer ? 'Too high.' : 'Too low.') + ' Press Run and count to watch it happen, then explain why.'); + announce(card, { widget: 'count', correct: false, firstTry: false }); + } + } + + function runAndCount() { + if (counted) return; + counted = true; + var io = { buffer: [], print: function (t) { this.buffer.push(String(t)); }, println: function (t) { this.buffer.push((t === undefined ? '' : String(t)) + '\n'); } }; + var total = cfg.run ? cfg.run(io) : cfg.answer; + var valueEl = qs('.count-value', meter); + var shown = 0; + var stepSize = Math.max(1, Math.ceil(total / 40)); + var timer = window.setInterval(function () { + shown = Math.min(total, shown + stepSize); + valueEl.textContent = String(shown); + if (shown >= total) { + window.clearInterval(timer); + counted = false; + setConsole(consoleWrap.box, io.buffer.join('')); + if (!input.classList.contains('u2-count__input--correct')) { + setFeedback(feedback, 'info', 'It ran ' + total + ' times. ' + (cfg.explain || '')); + } + } + }, 40); + } + + input.addEventListener('keydown', function (event) { if (event.key === 'Enter') { event.preventDefault(); check(); } }); + body.appendChild(el('div', { class: 'u2-count__row' }, [input, button('Check', 'primary', check), button('Run and count', 'success', runAndCount)])); + body.appendChild(el('div', { class: 'u2-count__display' }, [meter, consoleWrap])); + body.appendChild(feedback); + } + + // --------------------------------------------------------------------------- + // 10. Quiz scoreboard + // --------------------------------------------------------------------------- + function initQuiz(card) { + var questions = qsa('.u2-mcq__q, .u2-fill__q', card); + if (!questions.length) return; + var score = qs('.u2-quiz__score', card); + if (!score) { + score = el('div', { class: 'u2-quiz__score' }); + (qs('.u2-card__body', card) || card).appendChild(score); + } + var correct = 0; + var firstTry = 0; + + function render() { + var pct = Math.round((correct / questions.length) * 100); + score.innerHTML = + '
Score
' + + '
' + correct + ' / ' + questions.length + '
' + + '
' + firstTry + ' correct on the first try
' + + '
'; + } + + card.addEventListener('u2:answered', function (event) { + if (!event.detail || !event.detail.correct) return; + correct += 1; + if (event.detail.firstTry) firstTry += 1; + render(); + if (correct >= questions.length) markDone(card); + }); + render(); + } + + // --------------------------------------------------------------------------- + // Bootstrap declarative widgets + // --------------------------------------------------------------------------- + function init(root) { + var scope = root || document; + qsa('.u2-mcq', scope).forEach(function (card) { if (!card.dataset.u2ready) { card.dataset.u2ready = '1'; initMcq(card); } }); + qsa('.u2-fill', scope).forEach(function (card) { if (!card.dataset.u2ready) { card.dataset.u2ready = '1'; initFill(card); } }); + qsa('.u2-order', scope).forEach(function (card) { if (!card.dataset.u2ready) { card.dataset.u2ready = '1'; initOrder(card); } }); + qsa('.u2-sort', scope).forEach(function (card) { if (!card.dataset.u2ready) { card.dataset.u2ready = '1'; initSort(card); } }); + qsa('.u2-quiz', scope).forEach(function (card) { if (!card.dataset.u2quiz) { card.dataset.u2quiz = '1'; initQuiz(card); } }); + qsa('.u2-card', scope).forEach(restoreDone); + } + + var U2 = window.U2 || {}; + U2.init = init; + U2.trace = function (id, cfg) { onReady(function () { traceWidget(id, cfg); restoreDone(document.getElementById(id)); }); }; + U2.truth = function (id, cfg) { onReady(function () { truthWidget(id, cfg); restoreDone(document.getElementById(id)); }); }; + U2.live = function (id, cfg) { onReady(function () { liveWidget(id, cfg); restoreDone(document.getElementById(id)); }); }; + U2.flow = function (id, cfg) { onReady(function () { flowWidget(id, cfg); restoreDone(document.getElementById(id)); }); }; + U2.count = function (id, cfg) { onReady(function () { countWidget(id, cfg); restoreDone(document.getElementById(id)); }); }; + window.U2 = U2; + + function onReady(fn) { + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn); + else fn(); + } + + onReady(function () { init(document); }); +})(window, document);