diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2284399..7635762 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,5 +27,7 @@ jobs: working-directory: site - name: Validate Hawk app contract run: node scripts/deploy-check.mjs --contract >/dev/null + - name: Test server progress store + run: node --test server/test_progress.mjs - name: Test Python runner run: python3 -m unittest discover -t . -s runner -p "test_*.py" -v diff --git a/.gitignore b/.gitignore index 41c33c8..5c35259 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ __pycache__/ *.pyc +.data/ diff --git a/.hawk/app.json b/.hawk/app.json index 1693419..a92f11e 100644 --- a/.hawk/app.json +++ b/.hawk/app.json @@ -5,13 +5,14 @@ "port": 3000, "health": "/health", "database": null, - "data_dir": null, + "data_dir": "/data", "required_env": [ "APP_URL" ], "optional_env": [ "PORT", "HOST", + "DATA_DIR", "RUNNER_URL", "HAWK_SUITE_ISSUER", "HAWK_SUITE_TRUST_PROXY", diff --git a/Dockerfile b/Dockerfile index b2b3fc6..9e1306b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -16,9 +16,12 @@ ENV APP_REVISION=${APP_REVISION} LABEL org.opencontainers.image.revision=${APP_REVISION} ENV NODE_ENV=production PORT=3000 HOST=0.0.0.0 RUN groupadd --system --gid 1001 nodejs \ - && useradd --system --uid 1001 --gid nodejs hawklearn + && useradd --system --uid 1001 --gid nodejs hawklearn \ + && mkdir -p /data \ + && chown hawklearn:nodejs /data COPY --from=builder --chown=hawklearn:nodejs /app/site/dist ./site/dist COPY --chown=hawklearn:nodejs server.mjs ./server.mjs +COPY --chown=hawklearn:nodejs server ./server COPY --chown=hawklearn:nodejs .hawk ./.hawk COPY --chown=hawklearn:nodejs scripts/deploy-check.mjs ./scripts/deploy-check.mjs USER hawklearn diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 1422a3b..57d9530 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -7,7 +7,10 @@ services: - "3000:3000" environment: APP_URL: http://localhost:3000 + DATA_DIR: /data RUNNER_URL: http://hawk-learn-runner:4000 + volumes: + - hawk_learn_data:/data networks: - default - learn_runner @@ -34,3 +37,6 @@ services: networks: learn_runner: internal: true + +volumes: + hawk_learn_data: diff --git a/docs/screenshots/pr-30/after-index.png b/docs/screenshots/pr-30/after-index.png new file mode 100644 index 0000000..e620f84 Binary files /dev/null and b/docs/screenshots/pr-30/after-index.png differ diff --git a/docs/screenshots/pr-30/after-lesson1.png b/docs/screenshots/pr-30/after-lesson1.png new file mode 100644 index 0000000..ab5127d Binary files /dev/null and b/docs/screenshots/pr-30/after-lesson1.png differ diff --git a/docs/screenshots/pr-30/after-lesson2.png b/docs/screenshots/pr-30/after-lesson2.png new file mode 100644 index 0000000..a934f33 Binary files /dev/null and b/docs/screenshots/pr-30/after-lesson2.png differ diff --git a/docs/screenshots/pr-30/after-lesson3.png b/docs/screenshots/pr-30/after-lesson3.png new file mode 100644 index 0000000..9fd3fac Binary files /dev/null and b/docs/screenshots/pr-30/after-lesson3.png differ diff --git a/docs/screenshots/pr-30/after-lesson4.png b/docs/screenshots/pr-30/after-lesson4.png new file mode 100644 index 0000000..911578d Binary files /dev/null and b/docs/screenshots/pr-30/after-lesson4.png differ diff --git a/docs/screenshots/pr-30/before-index.png b/docs/screenshots/pr-30/before-index.png new file mode 100644 index 0000000..0afc513 Binary files /dev/null and b/docs/screenshots/pr-30/before-index.png differ diff --git a/docs/screenshots/pr-30/before-lesson1.png b/docs/screenshots/pr-30/before-lesson1.png new file mode 100644 index 0000000..5568ba7 Binary files /dev/null and b/docs/screenshots/pr-30/before-lesson1.png differ diff --git a/docs/screenshots/pr-30/before-lesson2.png b/docs/screenshots/pr-30/before-lesson2.png new file mode 100644 index 0000000..8a2006b Binary files /dev/null and b/docs/screenshots/pr-30/before-lesson2.png differ diff --git a/docs/screenshots/pr-30/before-lesson3.png b/docs/screenshots/pr-30/before-lesson3.png new file mode 100644 index 0000000..34d6619 Binary files /dev/null and b/docs/screenshots/pr-30/before-lesson3.png differ diff --git a/docs/screenshots/pr-30/before-lesson4.png b/docs/screenshots/pr-30/before-lesson4.png new file mode 100644 index 0000000..bb47883 Binary files /dev/null and b/docs/screenshots/pr-30/before-lesson4.png differ diff --git a/lessons/01-flowcharts/README.md b/lessons/01-flowcharts/README.md index 2abd87b..baa741c 100644 --- a/lessons/01-flowcharts/README.md +++ b/lessons/01-flowcharts/README.md @@ -1,85 +1,81 @@ --- title: "Programs are step-by-step" -goal: "See a program as a flowchart of blocks and watch the computer evaluate it one step at a time." +goal: "Follow a robot flowchart from START to END and watch the computer run one instruction at a time." order: 10 section: "Programming with Blocks" --- # One step at a time -Before we write a single line of code, let's get the big idea out of the way: -**a program is a list of steps, and the computer does them one at a time, in -order.** It never does two things at once by accident, and it never skips -ahead. It finishes one step, then moves to the next. +Before we write a single line of Python, let's get the big idea out of the way: +**a program is a list of instructions, and the computer runs them one at a time, +in order.** It never skips ahead, and it never runs two steps at once by +accident. It finishes one box, updates its memory, and follows the arrow to the +next box. -A good way to picture this is a **flowchart** — boxes joined by arrows. Each box -does one small thing, and the arrows show what feeds into what. The computer -follows the arrows. +A **flowchart** shows that exact journey from **START** to **END**: -The block editor here is exactly that: a little flowchart that does -math. Read it from top to bottom, the same way you read code: +- Each **box** is one instruction — like storing a number or doing math. +- Each **arrow** shows which step runs next. +- **Robot Memory** at the bottom shows the named values the robot is remembering + right now. -- The **number** blocks hold values. -- The **+** and **×** blocks each take *two* inputs (the arrows coming in from - the blocks above them) and produce *one* output. -- The **result** block at the bottom shows the final answer. +The flowchart here calculates an FRC robot's **autonomous score**: `3` coral at +`4` points each, plus a `3`-point bonus for leaving the starting zone. -Press **▶ Run step by step** and watch. The computer can't multiply until it -knows what `3 + 4` is, so it works out the inner block first, then feeds that -answer forward. That order — inputs before the things that use them — is the -whole game. +Press **▶ Run** (or click **⏭ Step** to advance one instruction at a time) and +watch **Robot Memory** update as each box lights up. You can also click +**Peek at Python** to see the exact same steps written as real Python code. ```blocks preset: sequence ``` -# Blocks carry values +# Order matters because steps share memory -So this flowchart computes `(3 + 4) × 2`. Notice the computer had to figure out -`3 + 4 = 7` *before* it could do `7 × 2 = 14`. It literally cannot do the -multiply first — one of its inputs doesn't exist yet. **Every block has to wait -for its inputs to be ready.** +Notice how `points` changed twice during the run: -That waiting is why order matters, and it's the same reason the lines of a real -program run top to bottom: later steps often depend on what earlier steps -produced. +1. First, `points = coral × 4` stored `12` in Robot Memory. +2. Next, `points = points + 3` read that `12`, added `3`, and updated `points` + to `15`. -Now make it your own. The number blocks in the editor are **editable** this -time — click into one and change its value. Before you press Run, try to predict -the new answer in your head. Then run it and check whether the value flowing -into the result block matches what you expected. +If you tried to add the bonus *before* calculating `coral × 4`, `points` +wouldn't even exist yet! **Later steps depend on what earlier steps stored in +memory** — that's why top-to-bottom order is the foundation of every program. + +Now experiment. The `coral` and `leave_bonus` boxes are **editable** — click a +number to change it, predict the new score in your head, then **Step** through +to check your prediction. Some things to try: -- Set the two top numbers so their sum is `10`. What does the result become? -- Can you make the result equal `0`? (Hint: what times anything is zero?) -- Make the result a **negative** number. +- Score `5` coral with a `3`-point leave bonus. What does `points` reach? +- What if the robot didn't leave the starting zone (`leave_bonus = 0`)? +- What if `coral = 0` and `leave_bonus = 0`? ```blocks preset: edit-values ``` -# Build your own math machine - -Time to build a flowchart from scratch. This canvas starts with two number -blocks and a result block, and a toolbar for adding more. - -**How to work the editor:** - -- Click a toolbar button — **number**, **+**, **−**, or **×** — to drop a new - block onto the canvas. Drag blocks around to arrange them. -- **Connect blocks by dragging** from the little dot on the bottom of one block - to a dot on the top of another. An operation block has *two* dots on top - because it needs two inputs; the result block has one. -- Press **▶ Run step by step** to watch your machine evaluate. **Reset** clears - the shown values so you can run it again. - -A block shows `?` when it doesn't have all of its inputs wired up yet — that's -the computer telling you a step is missing. - -Your challenge: build a machine that computes **`(8 − 3) × 4`** and check that -the result block lands on `20`. You'll need a subtract block feeding into a -multiply block, just like the very first example — except now *you* decide the -order the computer works in. +# Build your own scoring flowchart + +Time to build a flowchart yourself. Suppose our robot took `8` shots +(`attempts`) and dropped `3` of them (`dropped`), and each scored coral is worth +`4` points. + +**How to build:** +- **Drag a block** from the palette into the drop slot (or click its **`+`** + button to insert it). +- Use the **↑ / ↓** arrows on any block you added to change the order, or the + **trash icon** to remove it. +- Press **▶ Run** or **⏭ Step** to trace your program. **Clear run** resets only + the animation (your blocks stay safe); **Start over** resets the whole canvas. + +Your challenge: assemble the steps so the robot computes +**`(attempts − dropped) × 4`** and outputs `score`. Try putting the multiply +block *before* the subtract block once just to see what happens when a step +reads a variable that hasn't been calculated yet — then put them in the right +order and click **✓ Check** to test your flowchart against three match +scenarios! ```blocks preset: build diff --git a/lessons/02-conditionals/README.md b/lessons/02-conditionals/README.md index 4485103..85ab887 100644 --- a/lessons/02-conditionals/README.md +++ b/lessons/02-conditionals/README.md @@ -1,86 +1,72 @@ --- title: "Making decisions" -goal: "Use a condition to make a program choose between two paths." +goal: "Use a condition diamond to make a program choose one path and skip the other." order: 20 section: "Programming with Blocks" --- -# When programs choose +# When a robot has to choose -So far our flowcharts always did the exact same steps in the exact same order. -Real programs need to **make decisions**: do one thing when the weather is cold, -another when it's warm; show "pass" when a score is high enough, "fail" when it -isn't. +So far our flowcharts ran every single box from **START** to **END**. Real +robots have to **make decisions** based on sensors: slow down when the battery +is low, shoot when the target is in range, or stop when an arm hits its limit +switch. -In a flowchart, a decision is a **diamond**. It takes two numbers, `a` and `b`, -and asks a yes/no question about them — `a > b?` here (the question can also -use `<`, `=`, or `≠`). Then the program follows **exactly one of the two -arrows leaving it**: the `true` arrow when the answer is yes, the `false` -arrow when it's no. Never both, never neither. +In a flowchart, a decision is a **diamond** (`IF ... ?`). It asks a yes/no +question about the robot's memory — here, `battery < 10 ?` — and then follows +**exactly one** of its two outgoing arrows: -Each arrow leads to an **answer** block — the step that runs on that path. An -answer block has two inputs: `when` (wired from one of the diamond's arrows) -and `value` (what to produce if its path is the one taken). The branch the -program doesn't take simply **never runs**. +- Follow **YES** when the condition is **True**. +- Follow **NO** when the condition is **False**. -The flowchart in the editor finds **the larger of two numbers**. The diamond -asks `a > b?` — that's `true` here (`7 > 4`) — so the program follows the -`true` arrow down to the answer wired to `a`, and `7` flows on to the result. +The other branch **grays out and is completely skipped** — none of the steps on +that side ever run. After the taken branch finishes, both paths come back +together and continue to **OUTPUT** and **END**. -Press **▶ Run step by step**. Watch the diamond answer `true` and the program -head down the `true` arrow — while the other branch **grays out and gets -skipped**. Those blocks never run. This fork is exactly what Python writes as -`if / else`, and you'll type it yourself in [lesson {n}](#/lesson/09-if-statements). +Press **▶ Run** or **⏭ Step** on this **Battery Brownout Limiter**. With +`battery = 12`, watch the robot check `12 < 10` (False), follow the **NO** +arrow to set `mode = "FULL POWER"` and `max_speed = 100`, and skip the entire +**YES** branch. Click **Peek at Python** to see how this maps directly to +`if / else` (which you'll write yourself in +[lesson {n}](#/lesson/09-if-statements)). ```blocks preset: cond-demo ``` -# The road not taken +# Testing the boundary -The key idea: a decision **takes exactly one path, every time.** The other -branch isn't "a value you don't use" — it's code that **never runs**. Watch it -gray out during a run: the computer doesn't even look at it. +A decision **takes exactly one path, every time.** Every step inside the untaken +branch is skipped — the computer doesn't even touch it. -The numbers are editable now. Try these and run each time: +Now both the `battery` voltage and the `IF` condition are editable. Try these +and **Step** through each one: -- Make `a` **smaller** than `b`. Which arrow does the program follow now? - `a > b` is `false`, so it takes the `false` branch — and the answer wired to - `b` is the one that runs while the other side gets skipped. -- Make `a` and `b` **equal**. Is `a > b` true or false when they're the same? - (This is a classic bug source — "greater than" is not the same as "greater - than or equal to.") - -The result always ends up being whichever number is bigger, no matter which one -you put where. That's the whole point: the program adapts to its inputs instead -of doing one fixed thing. +- Set `battery` to **`9`**. Now `9 < 10` is **YES (True)** — watch the **YES** + branch run (`mode = "LOW POWER"`, `max_speed = 40`) while the **NO** branch + grays out. +- Set `battery` to **`10`** — right on the boundary! Is `10 < 10` True or False? + (This is one of the most common bugs in robotics code: `<` means *strictly + less than*, while `≤` includes the boundary itself.) +- Try switching `<` to `≤` in the diamond and run `battery = 10` again. ```blocks preset: cond-edit ``` -# Build a decision - -Your turn. Build a flowchart that outputs **the smaller of two numbers** and -check it against a few inputs. - -**How:** you have a toolbar with number blocks, four decision diamonds -(`if >`, `if <`, `if =`, `if ≠`), and an **answer** block. Drag from a block's -output dot to an input dot on another block to wire things up. - -A diamond needs `a` and `b` wired into its top. Each answer block needs two -wires: `when` (from one of the diamond's `true`/`false` arrows) and `value` -(the number that path should produce). Wire both answers into the result. +# Build a shooter range check -Two ways to get the *smaller* number — see if you can find both: +Your turn. Our robot has a distance sensor measuring how many meters away the +target is (`distance`). -- Use `if <`: ask `a < b`, wire the `true` arrow's answer to `a` and the - `false` arrow's answer to `b`. -- Or use `if >` and swap which number each answer is wired to. +**Your challenge:** +- If `distance < 3`, the robot should set `action = "SHOOT"`. +- Otherwise (`NO`), the robot should set `action = "DRIVE CLOSER"`. -Both work, because a decision is really just "which path do I take?" — and -each path carries its own answer. Run it with different numbers to convince -yourself it always picks the smaller one. +**How:** drag a block from the palette into the **YES** drop slot and another +into the **NO** drop slot (or click **`+`**). Then click **✓ Check** — it will +automatically test your flowchart with `distance = 2`, the boundary `distance = 3`, +and `distance = 5`! ```blocks preset: cond-build diff --git a/lessons/03-loops/README.md b/lessons/03-loops/README.md index 3890fe5..ac73ecf 100644 --- a/lessons/03-loops/README.md +++ b/lessons/03-loops/README.md @@ -1,71 +1,70 @@ --- title: "Doing things over and over" -goal: "Use a loop to repeat a step many times without copying it out by hand." +goal: "Use a loop with a loop-back arrow to repeat instructions without copying them by hand." order: 30 section: "Programming with Blocks" --- # Repeating without copying -Imagine you want to add `3` to a number five times. You *could* drag out five -separate `+` blocks and chain them together. But what if it were five hundred -times? Copying a block out by hand stops working fast. +If you slam an FRC drive motor straight from `0%` to `100%` speed in one +instant, the wheels slip and the battery voltage drops. Instead, robot code +**ramps** the speed up smoothly in small steps: `+20%`, `+20%`, `+20%`, `+20%`, +`+20%`. -Programs solve this with a **loop**: one block with its own logic built in, -that runs that logic over and over. The **repeat** block in the editor takes -just one thing from outside — **times**, how many passes to run — and it -carries its own **start** value and **by** step right on the block, editable -whenever you like. +You *could* paste five identical `speed = speed + 20` boxes in a row — until you +need to ramp in 50 steps! Programs solve this with a **loop**: -This one starts at `0` and adds `3`, five times over. Press **▶ Run step by -step** and watch the block's value climb — `0`, `3`, `6`, `9`, `12`, `15`. -Each pass runs the *same* internal logic again, using the result so far. +1. The **REPEAT** header tracks which pass you're on (`Pass 1 / 5`, `Pass 2 / 5`, + …). +2. The computer runs the step(s) **inside** the loop body. +3. At the bottom of the body, it follows the curved **loop-back arrow** up to the + top to repeat again. +4. Once all passes finish, it exits through the **DONE** arrow. + +Press **▶ Run** or **⏭ Step** and watch the loop-back arrow light up on each +pass while `speed` in **Robot Memory** climbs: `0 → 20 → 40 → 60 → 80 → 100`. +Click **Peek at Python** to see how this becomes a `for` loop in Python. ```blocks preset: loop-demo ``` -# A loop keeps a running total - -Notice what the repeat block is really doing: it remembers a value (its -**start**), and each pass updates that value using its **by** step. That -"value so far" is the heart of every loop — it's how five identical passes add -up to something. +# Loops update memory on every pass -This one starts at `1` and *multiplies* by `2`, four times. Before you run it, -predict the sequence in your head — `1`, then… Run it and watch: `1`, `2`, -`4`, `8`, `16`. Repeated multiplying grows *fast*; that's the same reason -folding a piece of paper in half again and again gets thick so quickly. +The reason a loop can accomplish something different on each pass — even though +it runs the *exact same box* — is that the box reads and updates a variable in +**Robot Memory** every time around. -Now experiment. The **times** input is editable, and so are the block's own -**start** and **by** fields: +Here, `power` starts at `1` and **doubles** (`power = power × 2`) on each pass, +four times: `1 → 2 → 4 → 8 → 16`. -- Change **times** and watch how many passes the loop takes. -- Set **start** to `10` and **by** to `10` — what running total do you get - after a few passes? -- What happens with **times** set to `0`? A loop that repeats zero times just - hands back its **start** value, untouched. +Experiment with the editable numbers and step through: +- Change the repeat count to **`5`** or **`6`** — watch how fast repeated + doubling grows! +- Change the repeat count to **`0`**. What happens? A loop that runs zero times + skips its body completely and jumps straight to the **DONE** arrow, leaving + `power` untouched at `1`. +- Change the multiplier from `2` to `3` and predict the result before running. ```blocks preset: loop-edit ``` -# Build a loop - -Build a repeat block that computes **2 to the 5th power** — that's `2` -multiplied by itself, ending on `32`. +# Build a flywheel spin-up loop -**How:** the toolbar has number blocks, a **repeat +**, and a **repeat ×**. -Drop one in, wire a number into its **times** input, then set its **start** -and **by** fields directly on the block. Send its output to the result block. +Your turn. Build a loop that starts with `power = 1` and ends at **`32`** (which +is 2⁵: `1 → 2 → 4 → 8 → 16 → 32`). -Think about which pieces you need: to keep multiplying by `2`, what should -**start** be so the very first multiply gives you `2`? How many **times** do -you repeat to land on `32`? Run it step by step and check the climb: `2`, `4`, -`8`, `16`, `32`. +**How:** +- Drag the right step from the palette **inside the REPEAT loop body** (or click + **`+`**). +- Set the **REPEAT** count to the right number of passes. +- Press **▶ Run** or **⏭ Step** to watch each pass climb toward `32`, then click + **✓ Check** to verify! -Once that works, try a **repeat +** that counts to `100` — there's more than -one combination of **start**, **times**, and **by** that gets there. +Once that passes, try swapping in `power = power + 10` and adjusting the repeat +count to see how easy it is to change what a loop does. ```blocks preset: loop-build diff --git a/lessons/04-functions/README.md b/lessons/04-functions/README.md index 55c76d9..b753bb1 100644 --- a/lessons/04-functions/README.md +++ b/lessons/04-functions/README.md @@ -1,69 +1,74 @@ --- title: "Reusable blocks" -goal: "Package a flowchart into a named block you can reuse instead of rebuilding it." +goal: "Package a flowchart into a named function you can call from anywhere instead of rebuilding it." order: 40 section: "Programming with Blocks" --- -# A block with a flowchart inside +# Jumping into a reusable flowchart -Look at the top of the block editor. There's a block called **double**, -and it has its own little flowchart *inside* it: an input `n`, a `× 2`, and an -output. That's a **function** — a small program you've wrapped up and given a -name. +Look to the right of **Main Program**: there is a separate mini-flowchart called +**`double(n)`**. That's a **function** — a small routine you write once, give a +name, and call whenever you need it. -Down in your program, you don't see those inner blocks anymore. You just see one -tidy **double** block. Feed it a number and it hands back that number times two. -Here we give it `5`, and out comes `10`. +- **`n`** is its **parameter** (the input handed in when you call it). +- Inside, it calculates `result = n × 2` in its own local memory. +- At the bottom, **`RETURN result`** hands the answer back to wherever it was + called from. -Press **▶ Run step by step**. The `double` block lights up and produces `10` — -without you ever having to place the `× 2` yourself. The messy details are -hidden inside; you just *use* the block. +Press **⏭ Step** (or **▶ Run**) and watch closely! When **Main Program** reaches +`boosted = double(speed)`: + +1. Execution **pauses** in Main Program and **jumps over to `double(n)`**. +2. `n` receives `5` (the value of `speed`). +3. `double` runs `result = 5 × 2 = 10` (watch **`double()` Local Memory** at the + bottom!) and returns `10`. +4. Execution **jumps back** to Main Program and stores `10` in `boosted`. + +Check the **Call Stack** at the bottom while it's inside `double` — that's how +the computer remembers where to return! ```blocks preset: fn-demo ``` -# Define once, use many times +# Define once, call as many times as you need -Here's why functions are worth the trouble: **you build the flowchart once, then -reuse it as many times as you like.** +Here is why functions are so useful in robot code: **you define the routine +once, then call it as many times as you want with different inputs — and if you +ever need to change how it works, you only change it in one place.** -This program feeds `3` into a `double` block, and then feeds *that* result into -**another** `double` block. Same block, used twice. `3` becomes `6`, and `6` -becomes `12`. +This program calls `boost_speed(speed)` **twice in a row**. Watch the +**`boost_speed(n)`** card on the right as you step through: -Press **▶ Run step by step** and watch the value pass through both copies. Each -`double` block runs the exact same inner flowchart — you defined it a single -time, but you can drop it in wherever you need it. Imagine the double block -secretly held fifty inner blocks; you'd still just wire up one tidy "double" and -move on. +- On the **1st call**, `n` becomes `3` and `boost_speed` returns `6`. +- On the **2nd call**, the *exact same* flowchart runs again, except now `n` is + `6` and `boost_speed` returns `12`. -Change the starting number and run again. Whatever you put in, it comes out -multiplied by four — because doubling twice is the same as ×4. +Now try editing the **`2`** *inside* the `boost_speed` function on the right +(for example, change it to `3`) and run again. Notice that changing the function +**once** automatically updates **both** calls in Main Program (`3 → 9 → 27`)! ```blocks preset: fn-chain ``` -# Build with reusable blocks +# Build a match scoring pipeline -Now you have **two** reusable blocks in the toolbar: **add 1** (which does -`n + 1`) and **double** (which does `n × 2`). You can see both inner flowcharts -at the top of the panel. +Now you have **two** reusable FRC scoring functions defined on the right: +- **`add_leave_bonus(pts)`** — adds `1` bonus point and returns the new score. +- **`coop_double(pts)`** — doubles the score and returns it. -Your challenge: starting from the number `4`, build a program whose result is -**exactly `10`**, using the `add 1` and `double` blocks. +**Your challenge:** starting from `score = 4`, drag function calls into **Main +Program** so that the final match score is **`10`** (and `14` when `score = 6`). -**Order matters** — and this is the whole lesson. `4` fed through *add 1 then -double* gives `(4 + 1) × 2 = 10`. But *double then add 1* gives -`4 × 2 + 1 = 9`. Same two blocks, different order, different answer — just like -[the very first lesson](#/lesson/01-flowcharts), where the computer had to do the inner step before the -outer one. +**Order matters!** +- `add_leave_bonus` *then* `coop_double`: `(4 + 1) × 2 = 10` +- `coop_double` *then* `add_leave_bonus`: `(4 × 2) + 1 = 9` -Wire a block's output into the next block's `n` input to chain them, then send -the last block into the result. Run it step by step and confirm you land on -`10`. Then see what *double then add 1* gives you instead. +Use the **↑ / ↓** arrows on the blocks you add to test both orders, step through +to watch the values jump into each function on the right, and click **✓ Check** +to verify your solution against all three match scores! ```blocks preset: fn-build diff --git a/scripts/deploy-check.mjs b/scripts/deploy-check.mjs index ab61cb4..000dc41 100644 --- a/scripts/deploy-check.mjs +++ b/scripts/deploy-check.mjs @@ -35,6 +35,9 @@ if (process.argv.includes("--contract")) { const port = Number(process.env.PORT); if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(); } + if (process.env.DATA_DIR !== undefined && !process.env.DATA_DIR.trim()) { + throw new Error(); + } console.log(JSON.stringify({ status: "ok", contract: contract.schema })); } catch { // Parse errors can contain credentials. Report names, never values. diff --git a/server.mjs b/server.mjs index 1231082..777f26c 100644 --- a/server.mjs +++ b/server.mjs @@ -2,9 +2,13 @@ import { createReadStream, statSync } from 'node:fs' import http from 'node:http' import path from 'node:path' import { fileURLToPath } from 'node:url' +import { openProgressDb } from './server/progress-db.mjs' const rootDir = path.dirname(fileURLToPath(import.meta.url)) const distDir = path.resolve(process.env.DIST_DIR || path.join(rootDir, 'site', 'dist')) +const dataDir = path.resolve( + process.env.DATA_DIR || (process.env.NODE_ENV === 'production' ? '/data' : path.join(rootDir, '.data')), +) const host = process.env.HOST || '0.0.0.0' const port = Number(process.env.PORT || 3000) const revision = process.env.APP_REVISION || 'development' @@ -12,6 +16,10 @@ const runnerUrl = (process.env.RUNNER_URL || '').replace(/\/+$/, '') const trustProxy = process.env.HAWK_SUITE_TRUST_PROXY === 'true' const expectedTeamId = process.env.HAWK_SUITE_TEAM_ID || '' +const progressDb = openProgressDb(path.join(dataDir, 'progress.db')) + +const LESSON_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,99}$/ + const MAX_BODY_BYTES = 64 * 1024 const RATE_LIMIT_BURST = 5 const RATE_LIMIT_REFILL_PER_SEC = 0.5 // 30 runs/minute per user @@ -125,13 +133,87 @@ function readJsonBody(req) { }) } +function resolveUser(req) { + if (!trustProxy) { + return { + userKey: 'local-dev', + slackUserId: 'local-dev', + slackTeamId: 'local', + slackName: 'Local Developer', + } + } + const slackUserId = String(req.headers['x-hawk-slack-user'] || '').trim() + const slackTeamId = String(req.headers['x-hawk-slack-team'] || '').trim() + if (!slackUserId) return null + if (expectedTeamId && slackTeamId !== expectedTeamId) return null + const slackName = + String( + req.headers['x-hawk-slack-name'] || + req.headers['x-hawk-user-name'] || + req.headers['x-hawk-slack-display-name'] || + '', + ).trim() || slackUserId + return { + userKey: `${slackTeamId}:${slackUserId}`, + slackUserId, + slackTeamId, + slackName, + } +} + function resolveUserKey(req) { - if (!trustProxy) return 'local-dev' - const user = String(req.headers['x-hawk-slack-user'] || '').trim() - const team = String(req.headers['x-hawk-slack-team'] || '').trim() - if (!user) return null - if (expectedTeamId && team !== expectedTeamId) return null - return `${team}:${user}` + return resolveUser(req)?.userKey ?? null +} + +async function handleProgressApi(req, res, method) { + const user = resolveUser(req) + if (!user) { + sendJson(res, 401, { error: 'Sign in with Hawk Suite to track progress.' }) + return + } + + if (method === 'GET') { + progressDb.upsertUser(user) + const completed = progressDb.getCompletedLessons(user.userKey) + sendJson(res, 200, { + user: { id: user.slackUserId, name: user.slackName }, + completed, + }) + return + } + + if (method === 'POST') { + let body + try { + body = await readJsonBody(req) + } catch (err) { + sendJson(res, err.status || 400, { error: err.message || 'Bad request' }) + return + } + + if ( + !body || + typeof body !== 'object' || + typeof body.lessonSlug !== 'string' || + !LESSON_SLUG_RE.test(body.lessonSlug) || + typeof body.completed !== 'boolean' + ) { + sendJson(res, 400, { + error: 'Fields `lessonSlug` (valid slug) and `completed` (boolean) are required.', + }) + return + } + + const completed = progressDb.setLessonCompleted(user, body.lessonSlug, body.completed) + sendJson(res, 200, { + user: { id: user.slackUserId, name: user.slackName }, + completed, + }) + return + } + + res.writeHead(405, { Allow: 'GET, POST', 'Content-Type': 'text/plain; charset=utf-8' }) + res.end('Method Not Allowed') } async function handleRunApi(req, res, isMaze) { @@ -243,6 +325,11 @@ const server = http.createServer((req, res) => { return } + if (pathname === '/api/progress') { + void handleProgressApi(req, res, method) + return + } + if (pathname === '/api/run' || pathname === '/api/run/maze') { if (method !== 'POST') { res.writeHead(405, { Allow: 'POST', 'Content-Type': 'text/plain; charset=utf-8' }) @@ -314,6 +401,9 @@ server.listen(port, host, () => { for (const signal of ['SIGINT', 'SIGTERM']) { process.on(signal, () => { - server.close(() => process.exit(0)) + server.close(() => { + progressDb.close() + process.exit(0) + }) }) } diff --git a/server/progress-db.mjs b/server/progress-db.mjs new file mode 100644 index 0000000..7700669 --- /dev/null +++ b/server/progress-db.mjs @@ -0,0 +1,86 @@ +import { mkdirSync } from 'node:fs' +import path from 'node:path' +import { DatabaseSync } from 'node:sqlite' + +export function openProgressDb(dbPath) { + if (dbPath !== ':memory:') { + mkdirSync(path.dirname(dbPath), { recursive: true }) + } + + const db = new DatabaseSync(dbPath) + db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA foreign_keys = ON; + PRAGMA busy_timeout = 5000; + + CREATE TABLE IF NOT EXISTS users ( + user_key TEXT PRIMARY KEY, + slack_user_id TEXT NOT NULL, + slack_team_id TEXT NOT NULL, + slack_name TEXT NOT NULL, + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS lesson_completions ( + user_key TEXT NOT NULL REFERENCES users(user_key) ON DELETE CASCADE, + lesson_slug TEXT NOT NULL, + completed_at TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (user_key, lesson_slug) + ); + `) + + const upsertUserStmt = db.prepare(` + INSERT INTO users (user_key, slack_user_id, slack_team_id, slack_name, updated_at) + VALUES (?, ?, ?, ?, datetime('now')) + ON CONFLICT(user_key) DO UPDATE SET + slack_name = excluded.slack_name, + updated_at = datetime('now') + `) + + const listCompletedStmt = db.prepare(` + SELECT lesson_slug, completed_at + FROM lesson_completions + WHERE user_key = ? + ORDER BY completed_at ASC + `) + + const markCompleteStmt = db.prepare(` + INSERT INTO lesson_completions (user_key, lesson_slug, completed_at) + VALUES (?, ?, datetime('now')) + ON CONFLICT(user_key, lesson_slug) DO NOTHING + `) + + const unmarkCompleteStmt = db.prepare(` + DELETE FROM lesson_completions + WHERE user_key = ? AND lesson_slug = ? + `) + + return { + upsertUser({ userKey, slackUserId, slackTeamId, slackName }) { + upsertUserStmt.run(userKey, slackUserId, slackTeamId, slackName) + }, + + getCompletedLessons(userKey) { + const rows = listCompletedStmt.all(userKey) + const completed = {} + for (const row of rows) { + completed[row.lesson_slug] = row.completed_at + } + return completed + }, + + setLessonCompleted(user, lessonSlug, completed) { + upsertUserStmt.run(user.userKey, user.slackUserId, user.slackTeamId, user.slackName) + if (completed) { + markCompleteStmt.run(user.userKey, lessonSlug) + } else { + unmarkCompleteStmt.run(user.userKey, lessonSlug) + } + return this.getCompletedLessons(user.userKey) + }, + + close() { + db.close() + }, + } +} diff --git a/server/test_progress.mjs b/server/test_progress.mjs new file mode 100644 index 0000000..231c105 --- /dev/null +++ b/server/test_progress.mjs @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import test from 'node:test' +import { openProgressDb } from './progress-db.mjs' + +test('records and toggles lesson completions per user', () => { + const db = openProgressDb(':memory:') + try { + const alice = { + userKey: 'T2713:U001', + slackUserId: 'U001', + slackTeamId: 'T2713', + slackName: 'Alice', + } + const bob = { + userKey: 'T2713:U002', + slackUserId: 'U002', + slackTeamId: 'T2713', + slackName: 'Bob', + } + + assert.deepEqual(db.getCompletedLessons(alice.userKey), {}) + + const afterFirst = db.setLessonCompleted(alice, '01-flowcharts', true) + assert.ok(afterFirst['01-flowcharts']) + assert.deepEqual(db.getCompletedLessons(bob.userKey), {}) + + // Marking the same lesson complete twice keeps the original timestamp. + const firstTs = afterFirst['01-flowcharts'] + const afterDup = db.setLessonCompleted(alice, '01-flowcharts', true) + assert.equal(afterDup['01-flowcharts'], firstTs) + + // Completing a second lesson and unmarking the first. + db.setLessonCompleted(alice, '02-conditionals', true) + const afterUnmark = db.setLessonCompleted(alice, '01-flowcharts', false) + assert.equal(afterUnmark['01-flowcharts'], undefined) + assert.ok(afterUnmark['02-conditionals']) + } finally { + db.close() + } +}) + +test('persists completions across reopen on disk', () => { + const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'hawk-learn-progress-')) + const dbPath = path.join(tmpDir, 'progress.db') + const user = { + userKey: 'T2713:U009', + slackUserId: 'U009', + slackTeamId: 'T2713', + slackName: 'Maya', + } + + try { + const db1 = openProgressDb(dbPath) + db1.setLessonCompleted(user, '06-hello-world', true) + db1.close() + + const db2 = openProgressDb(dbPath) + const completed = db2.getCompletedLessons(user.userKey) + assert.ok(completed['06-hello-world']) + db2.close() + } finally { + rmSync(tmpDir, { recursive: true, force: true }) + } +}) diff --git a/site/src/App.tsx b/site/src/App.tsx index ad5364f..4afdd1b 100644 --- a/site/src/App.tsx +++ b/site/src/App.tsx @@ -1,28 +1,48 @@ import { HashRouter, Route, Routes } from 'react-router-dom' import { AppSidebar } from './components/AppSidebar' import { SidebarInset, SidebarProvider, SidebarTrigger } from '@/components/ui/sidebar' +import { ProgressProvider, useProgress } from '@/lib/progress' import { LessonIndex } from './routes/LessonIndex' import { LessonView } from './routes/LessonView' +function HeaderProgress() { + const { user, completedCount, totalLessons, loading } = useProgress() + if (loading || !user) return null + return ( +
+ + {completedCount} / {totalLessons} completed + + · + + {user.name} + +
+ ) +} + function App() { return ( - - - -
- - - FRC 2713 Software Training - -
- - } /> - } /> - } /> - -
-
+ + + + +
+ + + FRC 2713 Software Training + + +
+ + } /> + } /> + } /> + +
+
+
) } diff --git a/site/src/components/AppSidebar.tsx b/site/src/components/AppSidebar.tsx index 712e5c9..dc3a939 100644 --- a/site/src/components/AppSidebar.tsx +++ b/site/src/components/AppSidebar.tsx @@ -1,3 +1,4 @@ +import { Check } from 'lucide-react' import { NavLink, useLocation } from 'react-router-dom' import { Sidebar, @@ -12,9 +13,11 @@ import { SidebarRail, } from '@/components/ui/sidebar' import { lessons, lessonSections } from '@/lib/lessons' +import { useProgress } from '@/lib/progress' export function AppSidebar() { const { pathname } = useLocation() + const { isCompleted, user } = useProgress() return ( @@ -33,31 +36,48 @@ export function AppSidebar() { - {lessonSections.map((section) => ( - - {section.title} - - - {section.lessons.map((lesson) => { - const to = `/lesson/${lesson.slug}` - const active = pathname === to || pathname.startsWith(`${to}/`) - return ( - - - - - {lessons.indexOf(lesson) + 1} - - {lesson.title} - - - - ) - })} - - - - ))} + {lessonSections.map((section) => { + const doneInSection = section.lessons.filter((l) => isCompleted(l.slug)).length + return ( + + + {section.title} + {user && ( + + {doneInSection}/{section.lessons.length} + + )} + + + + {section.lessons.map((lesson) => { + const to = `/lesson/${lesson.slug}` + const active = pathname === to || pathname.startsWith(`${to}/`) + const done = isCompleted(lesson.slug) + return ( + + + + + {lessons.indexOf(lesson) + 1} + + {lesson.title} + {done && ( + + )} + + + + ) + })} + + + + ) + })} diff --git a/site/src/components/FlowchartPlayground.css b/site/src/components/FlowchartPlayground.css new file mode 100644 index 0000000..bc7d1be --- /dev/null +++ b/site/src/components/FlowchartPlayground.css @@ -0,0 +1,901 @@ +.fc-shell { + border: 1px solid var(--border); + border-radius: 12px; + background: var(--bg); + overflow: hidden; + display: flex; + flex-direction: column; +} + +.fc-header { + padding: 12px 16px; + border-bottom: 1px solid var(--border); + background: var(--code-bg); +} + +.fc-title { + font-size: 15px; + font-weight: 600; + color: var(--text-h); +} + +.fc-subtitle { + font-size: 13px; + color: var(--text); + margin-top: 2px; +} + +.fc-controls { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding: 10px 14px; + border-bottom: 1px solid var(--border); +} + +.fc-controls-spacer { + flex: 1 1 auto; +} + +.fc-palette { + padding: 10px 14px; + border-bottom: 1px solid var(--border); + background: var(--code-bg); +} + +.fc-palette-label { + font-size: 12px; + font-weight: 500; + color: var(--text); + margin-bottom: 8px; +} + +.fc-palette-items { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.fc-palette-chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 5px 8px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--bg); + font-family: var(--mono); + font-size: 13px; + color: var(--text-h); + cursor: grab; + user-select: none; + transition: border-color 140ms ease, box-shadow 140ms ease; +} + +.fc-palette-chip:hover { + border-color: var(--accent); +} + +.fc-palette-chip:active { + cursor: grabbing; +} + +.fc-palette-add { + display: inline-flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + border-radius: 6px; + border: 1px solid var(--border); + background: var(--accent-bg); + color: var(--accent); + cursor: pointer; +} + +.fc-palette-add:hover:not(:disabled) { + background: var(--accent); + color: #fff; +} + +.fc-palette-branch-btns { + display: inline-flex; + gap: 4px; +} + +.fc-palette-add-text { + width: auto; + padding: 0 7px; + font-family: var(--sans); + font-size: 11px; + font-weight: 700; +} + +.fc-workspace { + padding: 18px 14px; + background: radial-gradient(var(--border) 1px, transparent 1px); + background-size: 18px 18px; +} + +.fc-workspace-split { + display: grid; + grid-template-columns: minmax(0, 1.1fr) minmax(0, 0.9fr); + gap: 16px; + align-items: start; +} + +@media (max-width: 720px) { + .fc-workspace-split { + grid-template-columns: 1fr; + } +} + +.fc-canvas, +.fc-column, +.fc-item { + display: flex; + flex-direction: column; + align-items: center; + width: 100%; +} + +.fc-pane-label { + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--text); + margin-bottom: 10px; +} + +.fc-pill { + padding: 5px 18px; + border-radius: 999px; + font-size: 12px; + font-weight: 700; + letter-spacing: 0.06em; + border: 2px solid var(--border); + background: var(--bg); + color: var(--text-h); + transition: box-shadow 180ms ease, border-color 180ms ease, transform 180ms ease; +} + +.fc-pill-sm { + padding: 4px 12px; + font-size: 11px; +} + +.fc-pill-start { + border-color: var(--ok); + color: var(--ok); +} + +.fc-pill-end { + border-color: var(--accent); + color: var(--accent); +} + +.fc-arrow { + display: flex; + flex-direction: column; + align-items: center; + color: var(--text); + margin: 1px 0; + position: relative; +} + +.fc-arrow-active { + color: var(--accent); +} + +.fc-arrow-label { + font-size: 10px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--text); + margin-bottom: 1px; +} + +.fc-node { + position: relative; + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; + padding: 9px 14px; + min-width: 190px; + max-width: 100%; + border-radius: 10px; + border: 2px solid var(--border); + background: var(--bg); + color: var(--text-h); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06); + transition: border-color 180ms ease, box-shadow 180ms ease, opacity 180ms ease; +} + +.fc-node-call { + border-style: double; + border-width: 3px; +} + +.fc-node-output { + flex-direction: row; + flex-wrap: wrap; + justify-content: center; + gap: 8px; + border-radius: 10px; + border-color: var(--accent-border); + background: var(--accent-bg); +} + +.fc-node-main { + display: flex; + align-items: center; + flex-wrap: wrap; + justify-content: center; + gap: 6px; + font-family: var(--mono); + font-size: 14px; +} + +.fc-var { + font-weight: 700; + color: var(--text-h); +} + +.fc-eq { + color: var(--text); +} + +.fc-expr, +.fc-expr-inline { + display: inline-flex; + align-items: center; + gap: 5px; + font-family: var(--mono); + font-size: 14px; +} + +.fc-note { + font-family: var(--sans); + font-size: 11px; + color: var(--text); +} + +.fc-tag { + font-family: var(--sans); + font-size: 10px; + font-weight: 700; + letter-spacing: 0.05em; + padding: 1px 6px; + border-radius: 5px; + background: var(--accent-bg); + color: var(--accent); +} + +.fc-num-input { + width: 58px; + padding: 2px 6px; + border-radius: 6px; + border: 1.5px solid var(--accent-border); + background: var(--code-bg); + color: var(--text-h); + font-family: var(--mono); + font-size: 13px; + font-weight: 600; + text-align: center; +} + +.fc-select { + padding: 2px 4px; + border-radius: 6px; + border: 1.5px solid var(--accent-border); + background: var(--code-bg); + color: var(--text-h); + font-family: var(--mono); + font-size: 13px; + font-weight: 700; +} + +.fc-node-actions { + display: flex; + gap: 4px; + margin-top: 2px; +} + +.fc-node-actions button { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + border-radius: 6px; + border: 1px solid var(--border); + background: var(--code-bg); + color: var(--text); + cursor: pointer; +} + +.fc-node-actions button:hover:not(:disabled) { + border-color: var(--accent); + color: var(--accent); +} + +.fc-node-actions .fc-btn-remove:hover:not(:disabled) { + border-color: var(--err); + color: var(--err); +} + +/* Active, Error & Skipped states */ +.fc-active { + border-color: var(--accent) !important; + box-shadow: 0 0 0 4px var(--accent-bg), 0 4px 14px rgba(186, 12, 47, 0.22); +} + +.fc-node-error { + border-color: var(--err) !important; + background: rgba(138, 18, 36, 0.08); + box-shadow: 0 0 0 4px rgba(138, 18, 36, 0.22); +} + +.fc-output-val { + font-family: var(--mono); + font-size: 13px; + font-weight: 700; + padding: 1px 7px; + border-radius: 999px; + background: var(--ok); + color: #fff; +} + +.fc-mem-output { + border-color: var(--ok); + color: var(--ok); + font-weight: 700; +} + +.fc-skipped { + opacity: 0.36; + filter: grayscale(0.7); +} + +/* IF decision diamond + fork/merge connectors + branches */ +.fc-if-block { + display: flex; + flex-direction: column; + align-items: center; + width: 100%; +} + +.fc-diamond-wrap { + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 210px; + max-width: 100%; + padding: 12px 28px; + transition: filter 180ms ease; +} + +.fc-diamond-svg { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + pointer-events: none; +} + +.fc-diamond-poly { + fill: var(--bg); + stroke: var(--accent-border); + stroke-width: 2.2; + vector-effect: non-scaling-stroke; + transition: stroke 180ms ease, stroke-width 180ms ease; +} + +.fc-diamond-active { + filter: drop-shadow(0 0 6px var(--accent-border)); +} + +.fc-diamond-active .fc-diamond-poly { + stroke: var(--accent); + stroke-width: 3; +} + +.fc-diamond-error { + filter: drop-shadow(0 0 6px rgba(138, 18, 36, 0.5)); +} + +.fc-diamond-error .fc-diamond-poly { + stroke: var(--err); + stroke-width: 3; +} + +.fc-diamond-content { + position: relative; + z-index: 1; + display: flex; + align-items: center; + gap: 8px; +} + +.fc-fork-svg, +.fc-merge-svg { + width: 100%; + height: 22px; + display: block; +} + +.fc-connector { + stroke: var(--border); + stroke-width: 2.2; + vector-effect: non-scaling-stroke; + transition: stroke 180ms ease, opacity 180ms ease; +} + +.fc-connector-active { + stroke: var(--accent); + stroke-width: 2.8; +} + +.fc-connector-skipped { + opacity: 0.3; +} + +.fc-diamond-badge { + font-size: 10px; + font-weight: 800; + color: var(--accent); + letter-spacing: 0.06em; +} + +.fc-diamond-expr { + display: inline-flex; + align-items: center; + gap: 6px; + font-family: var(--mono); + font-size: 14px; + font-weight: 600; + color: var(--text-h); +} + +.fc-cmp { + color: var(--accent); + font-weight: 700; +} + +.fc-branches { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; + width: 100%; +} + +.fc-branch .fc-node { + min-width: 0; + width: 100%; + padding: 8px 10px; +} + +.fc-branch { + display: flex; + flex-direction: column; + align-items: center; + padding: 10px 8px; + border-radius: 10px; + border: 1.5px dashed var(--border); + background: var(--bg); + transition: opacity 180ms ease, border-color 180ms ease; +} + +.fc-branch-skipped { + opacity: 0.38; + filter: grayscale(0.7); +} + +.fc-branch-header { + display: flex; + align-items: center; + gap: 6px; +} + +.fc-branch-header-active { + transform: scale(1.06); +} + +.fc-pill-yes { + font-size: 11px; + font-weight: 700; + padding: 2px 8px; + border-radius: 999px; + background: rgba(26, 127, 55, 0.14); + color: var(--ok); +} + +.fc-pill-no { + font-size: 11px; + font-weight: 700; + padding: 2px 8px; + border-radius: 999px; + background: var(--code-bg); + color: var(--text); +} + +.fc-skipped-tag { + font-size: 10px; + font-weight: 600; + color: var(--text); + text-transform: uppercase; +} + +.fc-branch-body { + width: 100%; + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; +} + +/* REPEAT loop frame */ +.fc-repeat-block { + display: flex; + flex-direction: column; + align-items: center; + width: 100%; +} + +.fc-repeat-header { + display: flex; + align-items: center; + flex-wrap: wrap; + justify-content: center; + gap: 8px; + padding: 8px 14px; + border: 2px solid var(--accent-border); + border-radius: 10px; + background: var(--bg); + font-size: 14px; + font-weight: 600; + color: var(--text-h); +} + +.fc-repeat-count { + font-family: var(--mono); + font-weight: 700; + color: var(--accent); +} + +.fc-pass-badge { + font-size: 11px; + font-weight: 700; + padding: 2px 8px; + border-radius: 999px; + background: var(--accent); + color: #fff; +} + +.fc-repeat-inner { + display: flex; + align-items: stretch; + justify-content: center; + gap: 6px; + width: 100%; + margin-top: 2px; +} + +.fc-repeat-body { + flex: 1 1 auto; + display: flex; + flex-direction: column; + align-items: center; + padding: 6px 10px 12px; + border: 1.5px dashed var(--accent-border); + border-radius: 10px; + background: var(--bg); +} + +.fc-loopback { + width: 42px; + flex-shrink: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + color: var(--text); + position: relative; +} + +.fc-loopback svg { + width: 38px; + height: 100%; + min-height: 76px; +} + +.fc-loopback-active { + color: var(--accent); + filter: drop-shadow(0 0 6px var(--accent-bg)); +} + +.fc-loopback-label { + font-size: 10px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.fc-repeat-exit { + display: flex; + justify-content: center; +} + +/* Dropzone */ +.fc-dropzone { + width: 100%; + min-height: 44px; + padding: 8px 12px; + border: 2px dashed var(--border); + border-radius: 10px; + background: var(--code-bg); + color: var(--text); + font-size: 12px; + font-weight: 500; + display: flex; + align-items: center; + justify-content: center; + text-align: center; + transition: border-color 140ms ease, background 140ms ease; +} + +.fc-dropzone-over { + border-color: var(--accent); + background: var(--accent-bg); + color: var(--accent); +} + +/* Side-by-side Function cards */ +.fc-functions-col { + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + width: 100%; +} + +.fc-fn-card { + width: 100%; + padding: 12px; + border: 2px solid var(--border); + border-radius: 12px; + background: var(--bg); + transition: border-color 180ms ease, box-shadow 180ms ease; +} + +.fc-fn-active { + border-color: var(--accent); + box-shadow: 0 0 0 4px var(--accent-bg); +} + +.fc-fn-header { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + font-family: var(--mono); + font-size: 13px; + color: var(--text-h); +} + +.fc-param-pill { + margin-left: auto; + font-size: 11px; + font-weight: 700; + padding: 2px 8px; + border-radius: 999px; + background: var(--accent); + color: #fff; +} + +.fc-fn-desc { + margin: 4px 0 10px; + font-size: 12px; + color: var(--text); +} + +.fc-fn-flow { + display: flex; + flex-direction: column; + align-items: center; +} + +/* Narrator & Memory bars */ +.fc-narrator { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 14px; + border-top: 1px solid var(--border); + background: var(--code-bg); + font-size: 13px; + color: var(--text-h); +} + +.fc-narrator-err { + color: var(--err); +} + +.fc-step-badge { + flex-shrink: 0; + font-size: 11px; + font-weight: 700; + padding: 2px 8px; + border-radius: 999px; + background: var(--accent-bg); + color: var(--accent); + font-variant-numeric: tabular-nums; +} + +.fc-memory-bar { + display: flex; + flex-direction: column; + gap: 6px; + padding: 10px 14px; + border-top: 1px solid var(--border); + background: var(--bg); + font-size: 13px; +} + +.fc-memory-section { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; +} + +.fc-memory-label { + font-size: 12px; + font-weight: 600; + color: var(--text); +} + +.fc-memory-empty { + font-size: 12px; + color: var(--text); + font-style: italic; +} + +.fc-memory-chips { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.fc-mem-chip { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 2px 8px; + border-radius: 6px; + border: 1px solid var(--border); + background: var(--code-bg); + font-family: var(--mono); + font-size: 12px; + transition: border-color 160ms ease, background 160ms ease; +} + +.fc-mem-changed { + border-color: var(--accent); + background: var(--accent-bg); +} + +.fc-mem-k { + font-weight: 700; + color: var(--text-h); +} + +.fc-mem-eq { + color: var(--text); +} + +.fc-mem-v { + color: var(--accent); + font-weight: 600; +} + +.fc-stack-text { + font-family: var(--mono); + font-size: 12px; + color: var(--text-h); +} + +/* Synced Python preview */ +.fc-python-panel { + border-top: 1px solid var(--border); + background: var(--code-bg); +} + +.fc-python-header { + padding: 6px 14px; + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--text); + border-bottom: 1px solid var(--border); +} + +.fc-python-code { + margin: 0; + padding: 8px 0; + font-family: var(--mono); + font-size: 13px; + overflow-x: auto; +} + +.fc-python-line { + display: flex; + gap: 12px; + padding: 2px 14px; + color: var(--text-h); +} + +.fc-python-line-active { + background: var(--accent-bg); + box-shadow: inset 3px 0 0 var(--accent); +} + +.fc-python-ln { + width: 20px; + text-align: right; + color: var(--text); + user-select: none; +} + +/* Challenge check results */ +.fc-checks { + padding: 12px 14px; + border-top: 1px solid var(--border); + background: var(--code-bg); +} + +.fc-checks-pass { + background: rgba(26, 127, 55, 0.09); +} + +.fc-checks-title { + font-size: 13px; + font-weight: 600; + color: var(--text-h); + margin-bottom: 6px; +} + +.fc-checks-list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 5px; + font-size: 13px; +} + +.fc-checks-list li { + display: flex; + align-items: center; + gap: 6px; +} + +.fc-check-ok { + color: var(--ok); +} + +.fc-check-fail { + color: var(--err); +} + +.fc-check-detail { + font-family: var(--mono); + font-size: 12px; +} diff --git a/site/src/components/FlowchartPlayground.tsx b/site/src/components/FlowchartPlayground.tsx new file mode 100644 index 0000000..f74637e --- /dev/null +++ b/site/src/components/FlowchartPlayground.tsx @@ -0,0 +1,1084 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { + ArrowDown, + ArrowUp, + Check, + CheckCircle2, + Code2, + GripVertical, + Pause, + Play, + Plus, + RotateCcw, + SkipBack, + SkipForward, + Trash2, + XCircle, +} from 'lucide-react' +import { + compileTrace, + formatCmpSymbol, + formatExpr, + formatOperand, + formatOpSymbol, + formatValue, + generatePythonLines, + MAX_REPEAT_TIMES, + runChallengeChecks, + type ChallengeCheckResult, + type CmpOp, + type FlowchartProgram, + type FlowNode, + type FunctionDef, + type IfNode, + type RepeatNode, + type SetNode, + type TraceStep, +} from '@/lib/flowchartEngine' +import { getFlowchartPreset, type PaletteItem } from '@/lib/flowchartPresets' +import { Button } from '@/components/ui/button' +import './FlowchartPlayground.css' + +type SlotTarget = + | { kind: 'main' } + | { kind: 'if-yes'; nodeId: string } + | { kind: 'if-no'; nodeId: string } + | { kind: 'repeat-body'; nodeId: string } + | { kind: 'fn-body'; fnName: string } + +// Controlled numeric input that keeps raw text while typing so clearing the +// field doesn't snap to 0 mid-edit. +function DraftNumberInput({ + value, + onChange, + disabled, + min, + max, + ariaLabel, +}: { + value: number + onChange: (n: number) => void + disabled?: boolean + min?: number + max?: number + ariaLabel: string +}) { + const [draft, setDraft] = useState(String(value)) + const [focused, setFocused] = useState(false) + + useEffect(() => { + if (!focused) setDraft(String(value)) + }, [value, focused]) + + const commit = (raw: string) => { + const trimmed = raw.trim() + if (trimmed === '' || trimmed === '-') { + setDraft(String(value)) + return + } + const parsed = Number(trimmed) + if (!Number.isFinite(parsed)) { + setDraft(String(value)) + return + } + let clamped = parsed + if (min !== undefined) clamped = Math.max(min, clamped) + if (max !== undefined) clamped = Math.min(max, clamped) + onChange(clamped) + setDraft(String(clamped)) + } + + return ( + setFocused(true)} + onBlur={() => { + setFocused(false) + commit(draft) + }} + onChange={(e) => { + const next = e.target.value + setDraft(next) + const parsed = Number(next) + if (next.trim() !== '' && next.trim() !== '-' && Number.isFinite(parsed)) { + if ((min === undefined || parsed >= min) && (max === undefined || parsed <= max)) { + onChange(parsed) + } + } + }} + className="fc-num-input" + /> + ) +} + +function FlowArrow({ active, skipped, label }: { active?: boolean; skipped?: boolean; label?: string }) { + return ( +
+ {label && {label}} + +
+ ) +} + +function mapNodes(nodes: FlowNode[], fn: (n: FlowNode) => FlowNode): FlowNode[] { + return nodes.map((n) => { + const updated = fn(n) + if (updated.kind === 'if') { + return { + ...updated, + yes: mapNodes(updated.yes, fn), + no: mapNodes(updated.no, fn), + } + } + if (updated.kind === 'repeat') { + return { + ...updated, + body: mapNodes(updated.body, fn), + } + } + return updated + }) +} + +function updateSlotList( + nodes: FlowNode[], + slot: SlotTarget, + updater: (list: FlowNode[]) => FlowNode[], +): FlowNode[] { + if (slot.kind === 'main') return updater(nodes) + return nodes.map((n) => { + if (slot.kind === 'if-yes' && n.kind === 'if' && n.id === slot.nodeId) { + return { ...n, yes: updater(n.yes) } + } + if (slot.kind === 'if-no' && n.kind === 'if' && n.id === slot.nodeId) { + return { ...n, no: updater(n.no) } + } + if (slot.kind === 'repeat-body' && n.kind === 'repeat' && n.id === slot.nodeId) { + return { ...n, body: updater(n.body) } + } + if (n.kind === 'if') { + return { + ...n, + yes: updateSlotList(n.yes, slot, updater), + no: updateSlotList(n.no, slot, updater), + } + } + if (n.kind === 'repeat') { + return { ...n, body: updateSlotList(n.body, slot, updater) } + } + return n + }) +} + +const CMP_OPTIONS: CmpOp[] = ['<', '>', '<=', '>=', '==', '!='] + +export function FlowchartPlayground({ preset }: { preset: string }) { + const config = useMemo(() => getFlowchartPreset(preset), [preset]) + const [program, setProgram] = useState(() => structuredClone(config.program)) + const [stepIndex, setStepIndex] = useState(-1) + const [playing, setPlaying] = useState(false) + const [fast, setFast] = useState(false) + const [showPython, setShowPython] = useState(false) + const [confirmStartOver, setConfirmStartOver] = useState(false) + const [checkResults, setCheckResults] = useState(null) + const [dragOverSlot, setDragOverSlot] = useState(null) + const nextId = useRef(1) + + // Reset state cleanly if preset changes. + useEffect(() => { + setProgram(structuredClone(config.program)) + setStepIndex(-1) + setPlaying(false) + setConfirmStartOver(false) + setCheckResults(null) + }, [config]) + + const trace = useMemo(() => compileTrace(program), [program]) + const pythonLines = useMemo(() => generatePythonLines(program), [program]) + const currentStep: TraceStep | null = + stepIndex >= 0 && stepIndex < trace.steps.length ? trace.steps[stepIndex] : null + + // Auto-advance timer when playing. + useEffect(() => { + if (!playing) return + const delay = fast ? 380 : 800 + const timer = window.setTimeout(() => { + setStepIndex((curr) => { + if (curr + 1 >= trace.steps.length) { + setPlaying(false) + return curr + } + return curr + 1 + }) + }, delay) + return () => window.clearTimeout(timer) + }, [playing, stepIndex, fast, trace.steps.length]) + + const clearRun = useCallback(() => { + setPlaying(false) + setStepIndex(-1) + }, []) + + const handlePlayPause = () => { + if (playing) { + setPlaying(false) + return + } + if (stepIndex < 0 || stepIndex >= trace.steps.length - 1) { + setStepIndex(0) + } + setPlaying(true) + } + + const handleStep = () => { + setPlaying(false) + setStepIndex((curr) => { + if (curr < 0) return 0 + if (curr + 1 >= trace.steps.length) return curr + return curr + 1 + }) + } + + const handleStepBack = () => { + setPlaying(false) + setStepIndex((curr) => (curr > 0 ? curr - 1 : curr)) + } + + const mutateProgram = (updater: (prev: FlowchartProgram) => FlowchartProgram) => { + clearRun() + setCheckResults(null) + setConfirmStartOver(false) + setProgram(updater) + } + + const insertFromPalette = (item: PaletteItem, slot: SlotTarget) => { + const id = `usr-${nextId.current++}` + const node = item.makeNode(id) + mutateProgram((prev) => ({ + ...prev, + main: updateSlotList(prev.main, slot, (list) => { + if (slot.kind === 'main') { + // Insert right before the final output node so it feeds into the output. + const outIdx = list.findIndex((n) => n.kind === 'output') + if (outIdx !== -1) { + return [...list.slice(0, outIdx), node, ...list.slice(outIdx)] + } + } + return [...list, node] + }), + })) + } + + const removeNode = (slot: SlotTarget, nodeId: string) => { + mutateProgram((prev) => ({ + ...prev, + main: updateSlotList(prev.main, slot, (list) => list.filter((n) => n.id !== nodeId)), + })) + } + + const moveNode = (slot: SlotTarget, nodeId: string, dir: -1 | 1) => { + mutateProgram((prev) => ({ + ...prev, + main: updateSlotList(prev.main, slot, (list) => { + const idx = list.findIndex((n) => n.id === nodeId) + if (idx === -1) return list + const targetIdx = idx + dir + if (targetIdx < 0 || targetIdx >= list.length) return list + // Keep removable nodes from moving past fixed inputs or the output node. + if (!list[targetIdx].removable) return list + const copy = [...list] + const [moved] = copy.splice(idx, 1) + copy.splice(targetIdx, 0, moved) + return copy + }), + })) + } + + const updateSetLiteral = (nodeId: string, val: number) => { + const patch = (n: FlowNode): FlowNode => { + if (n.id !== nodeId || n.kind !== 'set') return n + if (n.expr.kind === 'operand' && n.expr.operand.kind === 'num') { + return { ...n, expr: { kind: 'operand', operand: { kind: 'num', value: val } } } + } + if (n.expr.kind === 'binary' && n.expr.right.kind === 'num') { + return { ...n, expr: { ...n.expr, right: { kind: 'num', value: val } } } + } + return n + } + mutateProgram((prev) => ({ + main: mapNodes(prev.main, patch), + functions: prev.functions.map((fn) => ({ ...fn, body: mapNodes(fn.body, patch) })), + })) + } + + const updateIfCondition = (nodeId: string, cmp: CmpOp, rightVal: number) => { + mutateProgram((prev) => ({ + ...prev, + main: mapNodes(prev.main, (n) => { + if (n.id !== nodeId || n.kind !== 'if') return n + return { ...n, cmp, right: { kind: 'num', value: rightVal } } + }), + })) + } + + const updateRepeatTimes = (nodeId: string, times: number) => { + mutateProgram((prev) => ({ + ...prev, + main: mapNodes(prev.main, (n) => { + if (n.id !== nodeId || n.kind !== 'repeat') return n + return { ...n, times: { kind: 'num', value: times } } + }), + })) + } + + const handleCheck = () => { + if (!config.checks) return + clearRun() + setCheckResults(runChallengeChecks(program, config.checks)) + } + + const handleStartOver = () => { + if (!confirmStartOver) { + setConfirmStartOver(true) + return + } + setProgram(structuredClone(config.program)) + clearRun() + setCheckResults(null) + setConfirmStartOver(false) + } + + // Default click-to-add target for palette buttons. + const defaultClickSlot = useMemo(() => { + if (config.targetSlots?.includes('body')) { + const rep = program.main.find((n) => n.kind === 'repeat') + if (rep) return { kind: 'repeat-body', nodeId: rep.id } + } + if (config.targetSlots?.includes('yes')) { + const cond = program.main.find((n) => n.kind === 'if') + if (cond && cond.kind === 'if') { + if (cond.yes.length === 0) return { kind: 'if-yes', nodeId: cond.id } + return { kind: 'if-no', nodeId: cond.id } + } + } + return { kind: 'main' } + }, [config.targetSlots, program.main]) + + const skippedSet = useMemo(() => new Set(currentStep?.skippedNodeIds ?? []), [currentStep]) + const activeNodeId = currentStep?.nodeId ?? null + + const slotKey = (slot: SlotTarget) => { + if (slot.kind === 'main') return 'main' + if (slot.kind === 'fn-body') return `fn-body:${slot.fnName}` + return `${slot.kind}:${slot.nodeId}` + } + + const renderDropZone = (slot: SlotTarget, prompt: string) => { + if (!config.palette) return null + const key = slotKey(slot) + const isOver = dragOverSlot === key + return ( +
{ + e.preventDefault() + setDragOverSlot(key) + }} + onDragLeave={() => setDragOverSlot((curr) => (curr === key ? null : curr))} + onDrop={(e) => { + e.preventDefault() + setDragOverSlot(null) + const itemId = e.dataTransfer.getData('text/plain') + const item = config.palette?.find((p) => p.id === itemId) + if (item) insertFromPalette(item, slot) + }} + > + {prompt} +
+ ) + } + + const renderSetNode = (node: SetNode, slot: SlotTarget, list: FlowNode[], index: number) => { + const isActive = activeNodeId === node.id + const isError = isActive && Boolean(currentStep?.isError) + const isSkipped = skippedSet.has(node.id) + const isCall = node.expr.kind === 'call' + const canMoveUp = Boolean(node.removable && index > 0 && list[index - 1]?.removable) + const canMoveDown = Boolean( + node.removable && index < list.length - 1 && list[index + 1]?.removable, + ) + + return ( +
+
+ {isCall && CALL} + {node.target} + = + {node.editable && node.expr.kind === 'operand' && node.expr.operand.kind === 'num' ? ( + updateSetLiteral(node.id, v)} + disabled={playing} + ariaLabel={`Value for ${node.target}`} + /> + ) : node.editable && node.expr.kind === 'binary' && node.expr.right.kind === 'num' ? ( + + {formatOperand(node.expr.left)} + {formatOpSymbol(node.expr.op)} + updateSetLiteral(node.id, v)} + disabled={playing} + ariaLabel={`Step value for ${node.target}`} + /> + + ) : ( + {formatExpr(node.expr)} + )} +
+ {node.note &&
{node.note}
} + {node.removable && ( +
+ {canMoveUp && ( + + )} + {canMoveDown && ( + + )} + +
+ )} +
+ ) + } + + const renderIfNode = (node: IfNode) => { + const isActive = activeNodeId === node.id + const isError = isActive && Boolean(currentStep?.isError) + const isSkipped = skippedSet.has(node.id) + const yesSkipped = + node.yes.length > 0 + ? node.yes.every((n) => skippedSet.has(n.id)) + : currentStep?.nodeId === node.id && currentStep.activeBranch === 'no' + const noSkipped = + node.no.length > 0 + ? node.no.every((n) => skippedSet.has(n.id)) + : currentStep?.nodeId === node.id && currentStep.activeBranch === 'yes' + const yesTaken = currentStep?.nodeId === node.id && currentStep.activeBranch === 'yes' + const noTaken = currentStep?.nodeId === node.id && currentStep.activeBranch === 'no' + + return ( +
+
+ +
+
IF
+
+ {formatOperand(node.left)} + {node.editableCond && node.right.kind === 'num' ? ( + <> + + updateIfCondition(node.id, node.cmp, v)} + disabled={playing} + ariaLabel="Comparison threshold" + /> + + ) : ( + <> + {formatCmpSymbol(node.cmp)} + {formatOperand(node.right)} + + )} + ? +
+
+
+ + + +
+
+
+ YES + {yesSkipped && skipped} +
+ +
+ {renderFlowList(node.yes, { kind: 'if-yes', nodeId: node.id })} + {node.editableBranches && + renderDropZone( + { kind: 'if-yes', nodeId: node.id }, + node.yes.length === 0 ? 'Drop YES step here' : '+ Drop another YES step', + )} +
+
+ +
+
+ NO + {noSkipped && skipped} +
+ +
+ {renderFlowList(node.no, { kind: 'if-no', nodeId: node.id })} + {node.editableBranches && + renderDropZone( + { kind: 'if-no', nodeId: node.id }, + node.no.length === 0 ? 'Drop NO step here' : '+ Drop another NO step', + )} +
+
+
+ + +
+ ) + } + + const renderRepeatNode = (node: RepeatNode) => { + const isActive = activeNodeId === node.id + const isError = isActive && Boolean(currentStep?.isError) + const isSkipped = skippedSet.has(node.id) + const progress = currentStep?.loopProgress?.[node.id] + const loopBackActive = isActive && currentStep?.activeLoopPhase === 'back' + const loopExitActive = isActive && currentStep?.activeLoopPhase === 'exit' + const bodySkipped = node.body.length > 0 && node.body.every((n) => skippedSet.has(n.id)) + + return ( +
+
+ REPEAT + {node.editableTimes && node.times.kind === 'num' ? ( + updateRepeatTimes(node.id, v)} + disabled={playing} + ariaLabel="Number of loop passes" + /> + ) : ( + {formatOperand(node.times)} + )} + times + {progress && ( + + {progress.total === 0 ? '0 passes' : `Pass ${progress.pass} / ${progress.total}`} + + )} +
+ +
+
+ + {renderFlowList(node.body, { kind: 'repeat-body', nodeId: node.id })} + {node.editableBody && + renderDropZone( + { kind: 'repeat-body', nodeId: node.id }, + node.body.length === 0 ? 'Drop step to repeat here' : '+ Drop another step', + )} +
+ +
+ + repeat +
+
+ +
+ +
+
+ ) + } + + const renderFlowList = (nodes: FlowNode[], slot: SlotTarget) => { + const outIdx = slot.kind === 'main' ? nodes.findIndex((n) => n.kind === 'output') : -1 + + return ( +
+ {nodes.map((node, i) => { + const isSkipped = skippedSet.has(node.id) + const showMainDropBefore = + slot.kind === 'main' && config.targetSlots?.includes('main') && i === outIdx + + return ( +
+ {showMainDropBefore && ( + <> + {renderDropZone({ kind: 'main' }, 'Drop step here (or click a block above)')} + + + )} + {node.kind === 'set' && renderSetNode(node, slot, nodes, i)} + {node.kind === 'if' && renderIfNode(node)} + {node.kind === 'repeat' && renderRepeatNode(node)} + {node.kind === 'output' && ( +
+ OUTPUT + {formatOperand(node.operand)} + {currentStep && currentStep.outputs.length > 0 && ( + + = {formatValue(currentStep.outputs[currentStep.outputs.length - 1])} + + )} + {node.label && ({node.label})} +
+ )} + {i < nodes.length - 1 && node.kind !== 'repeat' && ( + + )} +
+ ) + })} +
+ ) + } + + const renderFunctionCard = (fn: FunctionDef) => { + const isFnActive = currentStep?.scope === fn.name + const startActive = activeNodeId === `__fn_start_${fn.name}__` + const retActive = activeNodeId === `__fn_return_${fn.name}__` + const paramVal = isFnActive ? currentStep?.fnMemory?.[fn.param] : undefined + + return ( +
+
+ FUNCTION + + {fn.name}({fn.param}) + + {isFnActive && paramVal !== undefined && ( + + {fn.param} = {formatValue(paramVal)} + + )} +
+

{fn.description}

+
+
+ IN: {fn.param} + {isFnActive && paramVal !== undefined ? ` = ${formatValue(paramVal)}` : ''} +
+ + {renderFlowList(fn.body, { kind: 'fn-body', fnName: fn.name })} + +
+ RETURN {fn.returnVar} + {retActive && currentStep?.returnValue !== undefined + ? ` (${formatValue(currentStep.returnValue)})` + : ''} +
+
+
+ ) + } + + const memoryEntries = Object.entries(currentStep?.memory ?? {}) + const hasFunctions = program.functions.length > 0 + const allChecksPassed = checkResults !== null && checkResults.every((r) => r.passed) + + return ( +
+
+
+
{config.title}
+
{config.subtitle}
+
+
+ + {/* Controls bar */} +
+ + + + + +
+ + {config.checks && ( + + )} + {config.palette && ( + + )} +
+ + {/* Palette for build presets */} + {config.palette && ( +
+
+ {config.targetSlots?.includes('yes') && config.targetSlots?.includes('no') + ? 'Drag a block into YES or NO (or click + YES / + NO):' + : 'Drag a block into the flowchart (or click + to add):'} +
+
+ {config.palette.map((item) => { + const condNode = + config.targetSlots?.includes('yes') && config.targetSlots?.includes('no') + ? program.main.find((n) => n.kind === 'if') + : undefined + return ( +
{ + e.dataTransfer.setData('text/plain', item.id) + e.dataTransfer.effectAllowed = 'copy' + }} + className="fc-palette-chip" + title={item.hint} + > + + {item.label} + {condNode ? ( +
+ + +
+ ) : ( + + )} +
+ ) + })} +
+
+ )} + + {/* Main flowchart + optional side-by-side function definitions */} +
+
+ {hasFunctions &&
Main Program
} +
+ START +
+ + {renderFlowList(program.main, { kind: 'main' })} + +
+ END +
+
+ + {hasFunctions && ( +
+
Reusable Functions
+ {program.functions.map(renderFunctionCard)} +
+ )} +
+ + {/* Live execution narrator */} +
+ + {currentStep ? `Step ${currentStep.stepNumber} / ${trace.steps.length}` : 'Ready'} + + + {currentStep + ? currentStep.narration + : 'Press Run or Step to watch the computer follow the arrows.'} + +
+ + {/* Live Robot Memory + Local Function Memory + Output */} +
+
+ Robot Memory: + {memoryEntries.length === 0 ? ( + (empty until a step runs) + ) : ( +
+ {memoryEntries.map(([k, v]) => ( + + {k} + = + {formatValue(v)} + + ))} +
+ )} +
+ {currentStep?.fnMemory && currentStep.scope !== 'main' && ( +
+ {currentStep.scope}() Local Memory: +
+ {Object.entries(currentStep.fnMemory).map(([k, v]) => ( + + {k} + = + {formatValue(v)} + + ))} +
+
+ )} + {currentStep && currentStep.outputs.length > 0 && ( +
+ Output: +
+ {currentStep.outputs.map((val, i) => ( + + {formatValue(val)} + + ))} +
+
+ )} + {hasFunctions && currentStep && currentStep.callStack.length > 1 && ( +
+ Call Stack: + {currentStep.callStack.join(' → ')} +
+ )} +
+ + {/* Optional synced Python preview */} + {showPython && ( +
+
Same program in Python
+
+            {pythonLines.map((line) => {
+              const isLineActive = Boolean(activeNodeId && line.nodeId === activeNodeId)
+              return (
+                
+ {line.lineNumber} + {line.text || ' '} +
+ ) + })} +
+
+ )} + + {/* Automated challenge check results */} + {checkResults && ( +
+
+ {allChecksPassed + ? 'All test cases passed!' + : 'Some test cases need a tweak:'} +
+
    + {checkResults.map((r) => ( +
  • + {r.passed ? ( + + ) : ( + + )} + + {r.label} + {!r.passed && ( + + {' '} + — {r.error ? r.error : `got ${formatValue(r.actual)}`} + + )} + +
  • + ))} +
+
+ )} +
+ ) +} diff --git a/site/src/components/LessonCard.tsx b/site/src/components/LessonCard.tsx index 1f51c01..923f158 100644 --- a/site/src/components/LessonCard.tsx +++ b/site/src/components/LessonCard.tsx @@ -1,18 +1,41 @@ +import { Check } from 'lucide-react' import { Link } from 'react-router-dom' import type { Lesson } from '@/lib/lessons' import { Card } from '@/components/ui/card' +import { cn } from '@/lib/utils' -export function LessonCard({ lesson, index }: { lesson: Lesson; index: number }) { +export function LessonCard({ + lesson, + index, + completed = false, +}: { + lesson: Lesson + index: number + completed?: boolean +}) { return ( - - {index + 1} + + {completed ? : index + 1} -
+

{lesson.title}

{lesson.goal}

+ {completed && ( + + Done + + )} ) diff --git a/site/src/lib/flowchartEngine.ts b/site/src/lib/flowchartEngine.ts new file mode 100644 index 0000000..a2cbcb4 --- /dev/null +++ b/site/src/lib/flowchartEngine.ts @@ -0,0 +1,519 @@ +export type Value = number | string + +export type Operand = + | { kind: 'num'; value: number } + | { kind: 'str'; value: string } + | { kind: 'var'; name: string } + +export type BinOp = '+' | '-' | '*' +export type CmpOp = '<' | '>' | '<=' | '>=' | '==' | '!=' + +export type Expr = + | { kind: 'operand'; operand: Operand } + | { kind: 'binary'; left: Operand; op: BinOp; right: Operand } + | { kind: 'call'; fnName: string; arg: Operand } + +export interface SetNode { + id: string + kind: 'set' + target: string + expr: Expr + note?: string + editable?: boolean + removable?: boolean +} + +export interface IfNode { + id: string + kind: 'if' + left: Operand + cmp: CmpOp + right: Operand + yes: FlowNode[] + no: FlowNode[] + editableCond?: boolean + editableBranches?: boolean + removable?: boolean +} + +export interface RepeatNode { + id: string + kind: 'repeat' + times: Operand + body: FlowNode[] + editableTimes?: boolean + editableBody?: boolean + removable?: boolean +} + +export interface OutputNode { + id: string + kind: 'output' + operand: Operand + label?: string + removable?: boolean +} + +export type FlowNode = SetNode | IfNode | RepeatNode | OutputNode + +export interface FunctionDef { + name: string + param: string + description: string + body: FlowNode[] + returnVar: string + editableBody?: boolean +} + +export interface FlowchartProgram { + main: FlowNode[] + functions: FunctionDef[] +} + +export interface TraceStep { + stepNumber: number + nodeId: string + scope: 'main' | string + isError?: boolean + activeBranch?: 'yes' | 'no' + activeLoopPhase?: 'check' | 'back' | 'exit' + skippedNodeIds: string[] + memory: Record + fnMemory?: Record + changedVar?: string + callStack: string[] + loopProgress?: Record + outputs: Value[] + narration: string + returnValue?: Value +} + +export interface TraceResult { + steps: TraceStep[] + finalMemory: Record + finalOutputs: Value[] + error?: string +} + +export interface ChallengeCase { + label: string + overrides: Record + expectedOutput: Value +} + +export interface ChallengeCheckResult { + label: string + passed: boolean + expected: Value + actual: Value | undefined + error?: string +} + +const MAX_TRACE_STEPS = 120 +export const MAX_REPEAT_TIMES = 20 + +export function formatValue(v: Value | undefined): string { + if (v === undefined) return '?' + if (typeof v === 'string') return `"${v}"` + return Number.isInteger(v) ? String(v) : String(Number(v.toFixed(2))) +} + +export function formatOperand(op: Operand): string { + if (op.kind === 'num') return String(op.value) + if (op.kind === 'str') return `"${op.value}"` + return op.name +} + +export function formatOpSymbol(op: BinOp): string { + if (op === '*') return '×' + if (op === '-') return '−' + return '+' +} + +export function formatCmpSymbol(cmp: CmpOp): string { + if (cmp === '==') return '=' + if (cmp === '!=') return '≠' + if (cmp === '<=') return '≤' + if (cmp === '>=') return '≥' + return cmp +} + +export function formatExpr(expr: Expr): string { + if (expr.kind === 'operand') return formatOperand(expr.operand) + if (expr.kind === 'binary') { + return `${formatOperand(expr.left)} ${formatOpSymbol(expr.op)} ${formatOperand(expr.right)}` + } + return `${expr.fnName}(${formatOperand(expr.arg)})` +} + +function collectIds(nodes: FlowNode[]): string[] { + const out: string[] = [] + for (const n of nodes) { + out.push(n.id) + if (n.kind === 'if') { + out.push(...collectIds(n.yes), ...collectIds(n.no)) + } else if (n.kind === 'repeat') { + out.push(...collectIds(n.body)) + } + } + return out +} + +function evalOperand(op: Operand, mem: Record): Value { + if (op.kind === 'num') return op.value + if (op.kind === 'str') return op.value + if (Object.prototype.hasOwnProperty.call(mem, op.name)) { + return mem[op.name] + } + throw new Error(`Variable "${op.name}" hasn't been set yet.`) +} + +function toNumber(v: Value, context: string): number { + if (typeof v === 'number' && Number.isFinite(v)) return v + throw new Error(`Expected a number for ${context}, got ${formatValue(v)}.`) +} + +function evalCmp(left: Value, cmp: CmpOp, right: Value): boolean { + switch (cmp) { + case '<': + return toNumber(left, 'comparison') < toNumber(right, 'comparison') + case '>': + return toNumber(left, 'comparison') > toNumber(right, 'comparison') + case '<=': + return toNumber(left, 'comparison') <= toNumber(right, 'comparison') + case '>=': + return toNumber(left, 'comparison') >= toNumber(right, 'comparison') + case '==': + return left === right + case '!=': + return left !== right + } +} + +export function applyInputOverrides( + program: FlowchartProgram, + overrides: Record, +): FlowchartProgram { + const clone: FlowchartProgram = structuredClone(program) + for (const node of clone.main) { + if ( + node.kind === 'set' && + node.expr.kind === 'operand' && + Object.prototype.hasOwnProperty.call(overrides, node.target) + ) { + const val = overrides[node.target] + node.expr.operand = + typeof val === 'number' ? { kind: 'num', value: val } : { kind: 'str', value: val } + } + } + return clone +} + +export function compileTrace(program: FlowchartProgram): TraceResult { + const steps: TraceStep[] = [] + const memory: Record = {} + const outputs: Value[] = [] + const skipped = new Set() + const loopProgress: Record = {} + const fnMap = new Map(program.functions.map((f) => [f.name, f])) + + const pushStep = (partial: Omit & { fnMemory?: Record }) => { + if (steps.length >= MAX_TRACE_STEPS) { + throw new Error(`Stopped after ${MAX_TRACE_STEPS} steps to keep the trace manageable.`) + } + steps.push({ + stepNumber: steps.length + 1, + skippedNodeIds: [...skipped], + memory: { ...memory }, + outputs: [...outputs], + loopProgress: structuredClone(loopProgress), + ...partial, + }) + } + + pushStep({ + nodeId: '__start__', + scope: 'main', + callStack: ['main'], + narration: 'Program starts at START and follows the arrows from top to bottom.', + }) + + class RecordedError extends Error { + constructor(message: string) { + super(message) + } + } + + const runNodes = ( + nodes: FlowNode[], + scope: 'main' | string, + scopeMem: Record, + callStack: string[], + ) => { + for (const node of nodes) { + try { + if (node.kind === 'set') { + if (node.expr.kind === 'call') { + const fn = fnMap.get(node.expr.fnName) + if (!fn) throw new Error(`Unknown function "${node.expr.fnName}".`) + const argVal = evalOperand(node.expr.arg, scopeMem) + pushStep({ + nodeId: node.id, + scope, + callStack: [...callStack], + fnMemory: scope === 'main' ? undefined : { ...scopeMem }, + narration: `Calling ${fn.name}(${formatValue(argVal)}) — jumping into the reusable "${fn.name}" flowchart.`, + }) + + const localMem: Record = { [fn.param]: argVal } + const nextStack = [...callStack, `${fn.name}(${fn.param}=${formatValue(argVal)})`] + pushStep({ + nodeId: `__fn_start_${fn.name}__`, + scope: fn.name, + callStack: nextStack, + fnMemory: { ...localMem }, + changedVar: fn.param, + narration: `Inside ${fn.name}: parameter ${fn.param} receives ${formatValue(argVal)}.`, + }) + + runNodes(fn.body, fn.name, localMem, nextStack) + + const retVal = evalOperand({ kind: 'var', name: fn.returnVar }, localMem) + pushStep({ + nodeId: `__fn_return_${fn.name}__`, + scope: fn.name, + callStack: nextStack, + fnMemory: { ...localMem }, + returnValue: retVal, + narration: `${fn.name} finishes and hands back ${formatValue(retVal)} to the caller.`, + }) + + scopeMem[node.target] = retVal + pushStep({ + nodeId: node.id, + scope, + callStack: [...callStack], + fnMemory: scope === 'main' ? undefined : { ...scopeMem }, + changedVar: node.target, + returnValue: retVal, + narration: `Back in ${scope}: stored ${formatValue(retVal)} into ${node.target}.`, + }) + continue + } + + let val: Value + let detail: string + if (node.expr.kind === 'operand') { + val = evalOperand(node.expr.operand, scopeMem) + detail = `${node.target} = ${formatValue(val)}` + } else { + const l = toNumber(evalOperand(node.expr.left, scopeMem), 'math') + const r = toNumber(evalOperand(node.expr.right, scopeMem), 'math') + if (node.expr.op === '+') val = l + r + else if (node.expr.op === '-') val = l - r + else val = l * r + detail = `${formatValue(l)} ${formatOpSymbol(node.expr.op)} ${formatValue(r)} = ${formatValue(val)} → stored in ${node.target}` + } + scopeMem[node.target] = val + pushStep({ + nodeId: node.id, + scope, + callStack: [...callStack], + fnMemory: scope === 'main' ? undefined : { ...scopeMem }, + changedVar: node.target, + narration: detail, + }) + } else if (node.kind === 'if') { + const l = evalOperand(node.left, scopeMem) + const r = evalOperand(node.right, scopeMem) + const result = evalCmp(l, node.cmp, r) + const taken = result ? node.yes : node.no + const untaken = result ? node.no : node.yes + for (const sid of collectIds(untaken)) skipped.add(sid) + + pushStep({ + nodeId: node.id, + scope, + activeBranch: result ? 'yes' : 'no', + callStack: [...callStack], + fnMemory: scope === 'main' ? undefined : { ...scopeMem }, + narration: `Check: ${formatValue(l)} ${formatCmpSymbol(node.cmp)} ${formatValue(r)} is ${result ? 'YES (True)' : 'NO (False)'} → taking the ${result ? 'YES' : 'NO'} arrow and skipping the other branch.`, + }) + + runNodes(taken, scope, scopeMem, callStack) + } else if (node.kind === 'repeat') { + const rawTimes = toNumber(evalOperand(node.times, scopeMem), 'repeat count') + const times = Math.trunc(rawTimes) + if (times < 0 || times > MAX_REPEAT_TIMES) { + throw new Error(`Repeat count must be between 0 and ${MAX_REPEAT_TIMES} (got ${rawTimes}).`) + } + if (times === 0) { + for (const sid of collectIds(node.body)) skipped.add(sid) + loopProgress[node.id] = { pass: 0, total: 0 } + pushStep({ + nodeId: node.id, + scope, + activeLoopPhase: 'exit', + callStack: [...callStack], + fnMemory: scope === 'main' ? undefined : { ...scopeMem }, + narration: `Repeat count is 0 → skipping the loop body and taking the DONE arrow.`, + }) + continue + } + + for (let pass = 1; pass <= times; pass++) { + loopProgress[node.id] = { pass, total: times } + pushStep({ + nodeId: node.id, + scope, + activeLoopPhase: 'check', + callStack: [...callStack], + fnMemory: scope === 'main' ? undefined : { ...scopeMem }, + narration: `Loop pass ${pass} of ${times}: entering the loop body.`, + }) + runNodes(node.body, scope, scopeMem, callStack) + if (pass < times) { + pushStep({ + nodeId: node.id, + scope, + activeLoopPhase: 'back', + callStack: [...callStack], + fnMemory: scope === 'main' ? undefined : { ...scopeMem }, + narration: `End of pass ${pass} of ${times}: following the loop-back arrow to repeat.`, + }) + } + } + + pushStep({ + nodeId: node.id, + scope, + activeLoopPhase: 'exit', + callStack: [...callStack], + fnMemory: scope === 'main' ? undefined : { ...scopeMem }, + narration: `Completed all ${times} ${times === 1 ? 'pass' : 'passes'} → exiting via the DONE arrow.`, + }) + } else if (node.kind === 'output') { + const val = evalOperand(node.operand, scopeMem) + outputs.push(val) + pushStep({ + nodeId: node.id, + scope, + callStack: [...callStack], + fnMemory: scope === 'main' ? undefined : { ...scopeMem }, + narration: `${node.label ?? 'Output'}: ${formatValue(val)}`, + }) + } + } catch (err) { + if (err instanceof RecordedError) throw err + const message = err instanceof Error ? err.message : 'Could not evaluate step.' + pushStep({ + nodeId: node.id, + scope, + isError: true, + callStack: [...callStack], + fnMemory: scope === 'main' ? undefined : { ...scopeMem }, + narration: `Error at this step: ${message}`, + }) + throw new RecordedError(message) + } + } + } + + try { + runNodes(program.main, 'main', memory, ['main']) + pushStep({ + nodeId: '__end__', + scope: 'main', + callStack: ['main'], + narration: + outputs.length > 0 + ? `Reached END! Final output: ${formatValue(outputs[outputs.length - 1])}.` + : 'Reached END! Program finished.', + }) + return { steps, finalMemory: memory, finalOutputs: outputs } + } catch (err) { + return { + steps, + finalMemory: memory, + finalOutputs: outputs, + error: err instanceof Error ? err.message : 'Could not evaluate flowchart.', + } + } +} + +export interface PythonLine { + lineNumber: number + text: string + nodeId?: string +} + +function pyOperand(op: Operand): string { + if (op.kind === 'num') return String(op.value) + if (op.kind === 'str') return `"${op.value}"` + return op.name +} + +function pyExpr(expr: Expr): string { + if (expr.kind === 'operand') return pyOperand(expr.operand) + if (expr.kind === 'binary') return `${pyOperand(expr.left)} ${expr.op} ${pyOperand(expr.right)}` + return `${expr.fnName}(${pyOperand(expr.arg)})` +} + +export function generatePythonLines(program: FlowchartProgram): PythonLine[] { + const lines: PythonLine[] = [] + const push = (text: string, nodeId?: string) => { + lines.push({ lineNumber: lines.length + 1, text, nodeId }) + } + + const emitNodes = (nodes: FlowNode[], indent: string) => { + if (nodes.length === 0) { + push(`${indent}pass`) + return + } + for (const node of nodes) { + if (node.kind === 'set') { + push(`${indent}${node.target} = ${pyExpr(node.expr)}`, node.id) + } else if (node.kind === 'if') { + push(`${indent}if ${pyOperand(node.left)} ${node.cmp} ${pyOperand(node.right)}:`, node.id) + emitNodes(node.yes, `${indent} `) + if (node.no.length > 0) { + push(`${indent}else:`) + emitNodes(node.no, `${indent} `) + } + } else if (node.kind === 'repeat') { + push(`${indent}for _ in range(${pyOperand(node.times)}):`, node.id) + emitNodes(node.body, `${indent} `) + } else if (node.kind === 'output') { + push(`${indent}print(${pyOperand(node.operand)})`, node.id) + } + } + } + + for (const fn of program.functions) { + push(`def ${fn.name}(${fn.param}):`, `__fn_start_${fn.name}__`) + emitNodes(fn.body, ' ') + push(` return ${fn.returnVar}`, `__fn_return_${fn.name}__`) + push('') + } + + emitNodes(program.main, '') + return lines +} + +export function runChallengeChecks( + program: FlowchartProgram, + cases: ChallengeCase[], +): ChallengeCheckResult[] { + return cases.map((c) => { + const overridden = applyInputOverrides(program, c.overrides) + const trace = compileTrace(overridden) + const actual = trace.finalOutputs[trace.finalOutputs.length - 1] + return { + label: c.label, + passed: !trace.error && actual === c.expectedOutput, + expected: c.expectedOutput, + actual, + error: trace.error, + } + }) +} diff --git a/site/src/lib/flowchartPresets.ts b/site/src/lib/flowchartPresets.ts new file mode 100644 index 0000000..409ebf6 --- /dev/null +++ b/site/src/lib/flowchartPresets.ts @@ -0,0 +1,827 @@ +import type { ChallengeCase, FlowchartProgram, FlowNode } from './flowchartEngine' + +export interface PaletteItem { + id: string + label: string + hint: string + makeNode: (id: string) => FlowNode +} + +export interface FlowchartPreset { + id: string + title: string + subtitle: string + program: FlowchartProgram + palette?: PaletteItem[] + targetSlots?: ('main' | 'yes' | 'no' | 'body')[] + challengePrompt?: string + checks?: ChallengeCase[] +} + +const PRESETS: Record = { + // ── Lesson 1: Programs are step-by-step (Autonomous Coral Scoring) ────────── + sequence: { + id: 'sequence', + title: 'Autonomous Score Calculator', + subtitle: 'Watch the robot calculate its autonomous score one step at a time.', + program: { + functions: [], + main: [ + { + id: 's1', + kind: 'set', + target: 'coral', + expr: { kind: 'operand', operand: { kind: 'num', value: 3 } }, + note: 'coral scored in auto', + }, + { + id: 's2', + kind: 'set', + target: 'points', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'coral' }, + op: '*', + right: { kind: 'num', value: 4 }, + }, + note: '4 points per coral', + }, + { + id: 's3', + kind: 'set', + target: 'points', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'points' }, + op: '+', + right: { kind: 'num', value: 3 }, + }, + note: '+3 leave-zone bonus', + }, + { + id: 's4', + kind: 'output', + operand: { kind: 'var', name: 'points' }, + label: 'Total auto points', + }, + ], + }, + }, + + 'edit-values': { + id: 'edit-values', + title: 'Experiment with Inputs', + subtitle: 'Change the starting numbers, predict the score, then step through.', + program: { + functions: [], + main: [ + { + id: 'e1', + kind: 'set', + target: 'coral', + expr: { kind: 'operand', operand: { kind: 'num', value: 3 } }, + note: 'coral scored', + editable: true, + }, + { + id: 'e2', + kind: 'set', + target: 'leave_bonus', + expr: { kind: 'operand', operand: { kind: 'num', value: 3 } }, + note: '0 if robot stayed put', + editable: true, + }, + { + id: 'e3', + kind: 'set', + target: 'points', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'coral' }, + op: '*', + right: { kind: 'num', value: 4 }, + }, + note: '4 points each', + }, + { + id: 'e4', + kind: 'set', + target: 'points', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'points' }, + op: '+', + right: { kind: 'var', name: 'leave_bonus' }, + }, + note: 'add leave bonus', + }, + { + id: 'e5', + kind: 'output', + operand: { kind: 'var', name: 'points' }, + label: 'Total auto points', + }, + ], + }, + }, + + build: { + id: 'build', + title: 'Build: Net Coral Score', + subtitle: 'Drag steps into order so the robot subtracts dropped coral before multiplying by 4.', + challengePrompt: + 'Build a flowchart that computes (attempts − dropped) × 4 and outputs score. Order matters!', + targetSlots: ['main'], + program: { + functions: [], + main: [ + { + id: 'b-attempts', + kind: 'set', + target: 'attempts', + expr: { kind: 'operand', operand: { kind: 'num', value: 8 } }, + note: 'shots taken', + editable: true, + }, + { + id: 'b-dropped', + kind: 'set', + target: 'dropped', + expr: { kind: 'operand', operand: { kind: 'num', value: 3 } }, + note: 'missed shots', + editable: true, + }, + { + id: 'b-out', + kind: 'output', + operand: { kind: 'var', name: 'score' }, + label: 'Final score', + }, + ], + }, + palette: [ + { + id: 'p-sub', + label: 'scored = attempts − dropped', + hint: 'Find how many actually went in', + makeNode: (id) => ({ + id, + kind: 'set', + target: 'scored', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'attempts' }, + op: '-', + right: { kind: 'var', name: 'dropped' }, + }, + removable: true, + }), + }, + { + id: 'p-mul', + label: 'score = scored × 4', + hint: '4 points per scored coral', + makeNode: (id) => ({ + id, + kind: 'set', + target: 'score', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'scored' }, + op: '*', + right: { kind: 'num', value: 4 }, + }, + removable: true, + }), + }, + { + id: 'p-bonus', + label: 'score = score + 3', + hint: 'Optional bonus step', + makeNode: (id) => ({ + id, + kind: 'set', + target: 'score', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'score' }, + op: '+', + right: { kind: 'num', value: 3 }, + }, + removable: true, + }), + }, + ], + checks: [ + { label: '8 attempts, 3 dropped → 20', overrides: { attempts: 8, dropped: 3 }, expectedOutput: 20 }, + { label: '5 attempts, 1 dropped → 16', overrides: { attempts: 5, dropped: 1 }, expectedOutput: 16 }, + { label: '4 attempts, 4 dropped → 0', overrides: { attempts: 4, dropped: 4 }, expectedOutput: 0 }, + ], + }, + + // ── Lesson 2: Making decisions (Battery Brownout Limiter) ────────────────── + 'cond-demo': { + id: 'cond-demo', + title: 'Battery Brownout Limiter', + subtitle: 'Watch the robot take ONE branch and completely skip the other.', + program: { + functions: [], + main: [ + { + id: 'cd-bat', + kind: 'set', + target: 'battery', + expr: { kind: 'operand', operand: { kind: 'num', value: 12 } }, + note: 'volts', + }, + { + id: 'cd-if', + kind: 'if', + left: { kind: 'var', name: 'battery' }, + cmp: '<', + right: { kind: 'num', value: 10 }, + yes: [ + { + id: 'cd-y1', + kind: 'set', + target: 'mode', + expr: { kind: 'operand', operand: { kind: 'str', value: 'LOW POWER' } }, + }, + { + id: 'cd-y2', + kind: 'set', + target: 'max_speed', + expr: { kind: 'operand', operand: { kind: 'num', value: 40 } }, + note: 'protect the battery', + }, + ], + no: [ + { + id: 'cd-n1', + kind: 'set', + target: 'mode', + expr: { kind: 'operand', operand: { kind: 'str', value: 'FULL POWER' } }, + }, + { + id: 'cd-n2', + kind: 'set', + target: 'max_speed', + expr: { kind: 'operand', operand: { kind: 'num', value: 100 } }, + note: 'all systems go', + }, + ], + }, + { + id: 'cd-out', + kind: 'output', + operand: { kind: 'var', name: 'max_speed' }, + label: 'Motor speed %', + }, + ], + }, + }, + + 'cond-edit': { + id: 'cond-edit', + title: 'Test the Boundary', + subtitle: 'Change the battery voltage (try 9, 10, and 12) and watch which path runs.', + program: { + functions: [], + main: [ + { + id: 'ce-bat', + kind: 'set', + target: 'battery', + expr: { kind: 'operand', operand: { kind: 'num', value: 12 } }, + note: 'volts', + editable: true, + }, + { + id: 'ce-if', + kind: 'if', + left: { kind: 'var', name: 'battery' }, + cmp: '<', + right: { kind: 'num', value: 10 }, + editableCond: true, + yes: [ + { + id: 'ce-y1', + kind: 'set', + target: 'mode', + expr: { kind: 'operand', operand: { kind: 'str', value: 'LOW POWER' } }, + }, + { + id: 'ce-y2', + kind: 'set', + target: 'max_speed', + expr: { kind: 'operand', operand: { kind: 'num', value: 40 } }, + }, + ], + no: [ + { + id: 'ce-n1', + kind: 'set', + target: 'mode', + expr: { kind: 'operand', operand: { kind: 'str', value: 'FULL POWER' } }, + }, + { + id: 'ce-n2', + kind: 'set', + target: 'max_speed', + expr: { kind: 'operand', operand: { kind: 'num', value: 100 } }, + }, + ], + }, + { + id: 'ce-out', + kind: 'output', + operand: { kind: 'var', name: 'max_speed' }, + label: 'Motor speed %', + }, + ], + }, + }, + + 'cond-build': { + id: 'cond-build', + title: 'Build: Shooter Range Check', + subtitle: 'Drag the right action into the YES and NO branches.', + challengePrompt: + 'If distance < 3 meters, set action to "SHOOT". Otherwise, set action to "DRIVE CLOSER".', + targetSlots: ['yes', 'no'], + program: { + functions: [], + main: [ + { + id: 'cb-dist', + kind: 'set', + target: 'distance', + expr: { kind: 'operand', operand: { kind: 'num', value: 2 } }, + note: 'meters to target', + editable: true, + }, + { + id: 'cb-if', + kind: 'if', + left: { kind: 'var', name: 'distance' }, + cmp: '<', + right: { kind: 'num', value: 3 }, + editableCond: true, + editableBranches: true, + yes: [], + no: [], + }, + { + id: 'cb-out', + kind: 'output', + operand: { kind: 'var', name: 'action' }, + label: 'Robot command', + }, + ], + }, + palette: [ + { + id: 'p-shoot', + label: 'action = "SHOOT"', + hint: 'Fire when close enough', + makeNode: (id) => ({ + id, + kind: 'set', + target: 'action', + expr: { kind: 'operand', operand: { kind: 'str', value: 'SHOOT' } }, + removable: true, + }), + }, + { + id: 'p-drive', + label: 'action = "DRIVE CLOSER"', + hint: 'Move toward the target', + makeNode: (id) => ({ + id, + kind: 'set', + target: 'action', + expr: { kind: 'operand', operand: { kind: 'str', value: 'DRIVE CLOSER' } }, + removable: true, + }), + }, + { + id: 'p-stop', + label: 'action = "STOP"', + hint: 'Halt the drivetrain', + makeNode: (id) => ({ + id, + kind: 'set', + target: 'action', + expr: { kind: 'operand', operand: { kind: 'str', value: 'STOP' } }, + removable: true, + }), + }, + ], + checks: [ + { label: 'distance = 2 (< 3) → "SHOOT"', overrides: { distance: 2 }, expectedOutput: 'SHOOT' }, + { label: 'distance = 3 (edge case!) → "DRIVE CLOSER"', overrides: { distance: 3 }, expectedOutput: 'DRIVE CLOSER' }, + { label: 'distance = 5 → "DRIVE CLOSER"', overrides: { distance: 5 }, expectedOutput: 'DRIVE CLOSER' }, + ], + }, + + // ── Lesson 3: Doing things over and over (Motor Ramp-Up Loop) ────────────── + 'loop-demo': { + id: 'loop-demo', + title: 'Smooth Motor Ramp-Up', + subtitle: 'Watch the loop-back arrow run the same step 5 times to ramp speed smoothly.', + program: { + functions: [], + main: [ + { + id: 'ld-s', + kind: 'set', + target: 'speed', + expr: { kind: 'operand', operand: { kind: 'num', value: 0 } }, + note: 'start from rest', + }, + { + id: 'ld-loop', + kind: 'repeat', + times: { kind: 'num', value: 5 }, + body: [ + { + id: 'ld-inc', + kind: 'set', + target: 'speed', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'speed' }, + op: '+', + right: { kind: 'num', value: 20 }, + }, + note: 'nudge motor +20%', + }, + ], + }, + { + id: 'ld-out', + kind: 'output', + operand: { kind: 'var', name: 'speed' }, + label: 'Final motor speed %', + }, + ], + }, + }, + + 'loop-edit': { + id: 'loop-edit', + title: 'Power Doubling & Zero Passes', + subtitle: 'Change start, repeat count (try 0!), or multiplier and watch every pass.', + program: { + functions: [], + main: [ + { + id: 'le-s', + kind: 'set', + target: 'power', + expr: { kind: 'operand', operand: { kind: 'num', value: 1 } }, + note: 'starting value', + editable: true, + }, + { + id: 'le-loop', + kind: 'repeat', + times: { kind: 'num', value: 4 }, + editableTimes: true, + body: [ + { + id: 'le-mul', + kind: 'set', + target: 'power', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'power' }, + op: '*', + right: { kind: 'num', value: 2 }, + }, + note: 'double each pass', + editable: true, + }, + ], + }, + { + id: 'le-out', + kind: 'output', + operand: { kind: 'var', name: 'power' }, + label: 'Final power', + }, + ], + }, + }, + + 'loop-build': { + id: 'loop-build', + title: 'Build: Flywheel Spin-Up', + subtitle: 'Drop a step INSIDE the loop body and set the repeat count to hit 32.', + challengePrompt: + 'Starting from power = 1, repeat doubling power so the robot lands on 32 (2⁵).', + targetSlots: ['body'], + program: { + functions: [], + main: [ + { + id: 'lb-s', + kind: 'set', + target: 'power', + expr: { kind: 'operand', operand: { kind: 'num', value: 1 } }, + note: 'starting value', + editable: true, + }, + { + id: 'lb-loop', + kind: 'repeat', + times: { kind: 'num', value: 3 }, + editableTimes: true, + editableBody: true, + body: [], + }, + { + id: 'lb-out', + kind: 'output', + operand: { kind: 'var', name: 'power' }, + label: 'Final power', + }, + ], + }, + palette: [ + { + id: 'p-dbl', + label: 'power = power × 2', + hint: 'Double power each pass', + makeNode: (id) => ({ + id, + kind: 'set', + target: 'power', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'power' }, + op: '*', + right: { kind: 'num', value: 2 }, + }, + removable: true, + }), + }, + { + id: 'p-add10', + label: 'power = power + 10', + hint: 'Add 10 each pass', + makeNode: (id) => ({ + id, + kind: 'set', + target: 'power', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'power' }, + op: '+', + right: { kind: 'num', value: 10 }, + }, + removable: true, + }), + }, + { + id: 'p-add1', + label: 'power = power + 1', + hint: 'Add 1 each pass', + makeNode: (id) => ({ + id, + kind: 'set', + target: 'power', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'power' }, + op: '+', + right: { kind: 'num', value: 1 }, + }, + removable: true, + }), + }, + ], + checks: [ + { label: 'Starts at 1 → ends at 32', overrides: { power: 1 }, expectedOutput: 32 }, + { label: 'Starts at 2 → ends at 64', overrides: { power: 2 }, expectedOutput: 64 }, + ], + }, + + // ── Lesson 4: Reusable blocks (Functions) ────────────────────────────────── + 'fn-demo': { + id: 'fn-demo', + title: 'Calling a Reusable Routine', + subtitle: 'Watch execution jump into the function on the right, run its steps, and return.', + program: { + functions: [ + { + name: 'double', + param: 'n', + description: 'Multiplies any input by 2 and returns it.', + returnVar: 'result', + body: [ + { + id: 'fd-fn-1', + kind: 'set', + target: 'result', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'n' }, + op: '*', + right: { kind: 'num', value: 2 }, + }, + }, + ], + }, + ], + main: [ + { + id: 'fd-1', + kind: 'set', + target: 'speed', + expr: { kind: 'operand', operand: { kind: 'num', value: 5 } }, + note: 'base speed', + }, + { + id: 'fd-2', + kind: 'set', + target: 'boosted', + expr: { kind: 'call', fnName: 'double', arg: { kind: 'var', name: 'speed' } }, + note: 'call reusable routine', + }, + { + id: 'fd-3', + kind: 'output', + operand: { kind: 'var', name: 'boosted' }, + label: 'Boosted speed', + }, + ], + }, + }, + + 'fn-chain': { + id: 'fn-chain', + title: 'Define Once, Call Twice', + subtitle: 'Same function, two inputs — edit the multiplier inside boost_speed once and watch both calls update!', + program: { + functions: [ + { + name: 'boost_speed', + param: 'n', + description: 'Scales a motor speed by the factor below and returns it.', + returnVar: 'result', + editableBody: true, + body: [ + { + id: 'fc-fn-1', + kind: 'set', + target: 'result', + editable: true, + expr: { + kind: 'binary', + left: { kind: 'var', name: 'n' }, + op: '*', + right: { kind: 'num', value: 2 }, + }, + }, + ], + }, + ], + main: [ + { + id: 'fc-1', + kind: 'set', + target: 'speed', + expr: { kind: 'operand', operand: { kind: 'num', value: 3 } }, + editable: true, + }, + { + id: 'fc-2', + kind: 'set', + target: 'speed', + expr: { kind: 'call', fnName: 'boost_speed', arg: { kind: 'var', name: 'speed' } }, + note: '1st call', + }, + { + id: 'fc-3', + kind: 'set', + target: 'speed', + expr: { kind: 'call', fnName: 'boost_speed', arg: { kind: 'var', name: 'speed' } }, + note: '2nd call', + }, + { + id: 'fc-4', + kind: 'output', + operand: { kind: 'var', name: 'speed' }, + label: 'Final speed', + }, + ], + }, + }, + + 'fn-build': { + id: 'fn-build', + title: 'Build: Match Scoring Pipeline', + subtitle: 'Drag the reusable robot scoring functions into order so score = 4 lands on 10.', + challengePrompt: + 'Apply add_leave_bonus (+1) before coop_double (×2) so (score + 1) × 2 gives 10 when score = 4.', + targetSlots: ['main'], + program: { + functions: [ + { + name: 'add_leave_bonus', + param: 'pts', + description: 'Adds 1 bonus point and returns the new score.', + returnVar: 'result', + body: [ + { + id: 'fb-fn-a1', + kind: 'set', + target: 'result', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'pts' }, + op: '+', + right: { kind: 'num', value: 1 }, + }, + }, + ], + }, + { + name: 'coop_double', + param: 'pts', + description: 'Doubles the match score and returns it.', + returnVar: 'result', + body: [ + { + id: 'fb-fn-d1', + kind: 'set', + target: 'result', + expr: { + kind: 'binary', + left: { kind: 'var', name: 'pts' }, + op: '*', + right: { kind: 'num', value: 2 }, + }, + }, + ], + }, + ], + main: [ + { + id: 'fb-1', + kind: 'set', + target: 'score', + expr: { kind: 'operand', operand: { kind: 'num', value: 4 } }, + note: 'base match score', + editable: true, + }, + { + id: 'fb-out', + kind: 'output', + operand: { kind: 'var', name: 'score' }, + label: 'Final match score', + }, + ], + }, + palette: [ + { + id: 'p-call-add', + label: 'score = add_leave_bonus(score)', + hint: 'Adds 1 bonus point to score', + makeNode: (id) => ({ + id, + kind: 'set', + target: 'score', + expr: { kind: 'call', fnName: 'add_leave_bonus', arg: { kind: 'var', name: 'score' } }, + removable: true, + }), + }, + { + id: 'p-call-dbl', + label: 'score = coop_double(score)', + hint: 'Doubles score', + makeNode: (id) => ({ + id, + kind: 'set', + target: 'score', + expr: { kind: 'call', fnName: 'coop_double', arg: { kind: 'var', name: 'score' } }, + removable: true, + }), + }, + ], + checks: [ + { label: 'score = 4 → 10', overrides: { score: 4 }, expectedOutput: 10 }, + { label: 'score = 6 → 14', overrides: { score: 6 }, expectedOutput: 14 }, + { label: 'score = 0 → 2', overrides: { score: 0 }, expectedOutput: 2 }, + ], + }, +} + +export function isFlowchartPreset(preset: string): boolean { + return Object.prototype.hasOwnProperty.call(PRESETS, preset) +} + +export function getFlowchartPreset(preset: string): FlowchartPreset { + return PRESETS[preset] ?? PRESETS.sequence +} diff --git a/site/src/lib/progress.tsx b/site/src/lib/progress.tsx new file mode 100644 index 0000000..444d8ea --- /dev/null +++ b/site/src/lib/progress.tsx @@ -0,0 +1,120 @@ +import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react' +import type { ReactNode } from 'react' +import { lessons } from '@/lib/lessons' + +export interface ProgressUser { + id: string + name: string +} + +interface ProgressPayload { + user: ProgressUser + completed: Record +} + +interface ProgressContextValue { + user: ProgressUser | null + completed: Record + loading: boolean + savingSlug: string | null + isCompleted: (slug: string) => boolean + setCompleted: (slug: string, done: boolean) => Promise + completedCount: number + totalLessons: number +} + +const ProgressContext = createContext(null) + +const KNOWN_SLUGS = new Set(lessons.map((l) => l.slug)) + +export function ProgressProvider({ children }: { children: ReactNode }) { + const [user, setUser] = useState(null) + const [completed, setCompletedMap] = useState>({}) + const [loading, setLoading] = useState(true) + const [savingSlug, setSavingSlug] = useState(null) + + useEffect(() => { + let cancelled = false + fetch('/api/progress') + .then(async (res) => { + if (!res.ok) return null + const ct = res.headers.get('content-type') || '' + if (!ct.includes('application/json')) return null + return (await res.json()) as ProgressPayload + }) + .then((data) => { + if (cancelled || !data) return + setUser(data.user) + setCompletedMap(data.completed ?? {}) + }) + .catch(() => {}) + .finally(() => { + if (!cancelled) setLoading(false) + }) + return () => { + cancelled = true + } + }, []) + + const isCompleted = useCallback((slug: string) => Boolean(completed[slug]), [completed]) + + const setCompleted = useCallback(async (slug: string, done: boolean): Promise => { + setSavingSlug(slug) + let previous: Record = {} + setCompletedMap((curr) => { + previous = curr + const next = { ...curr } + if (done) next[slug] = new Date().toISOString() + else delete next[slug] + return next + }) + + try { + const res = await fetch('/api/progress', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ lessonSlug: slug, completed: done }), + }) + if (!res.ok) { + setCompletedMap(previous) + return false + } + const data = (await res.json()) as ProgressPayload + setUser(data.user) + setCompletedMap(data.completed ?? {}) + return true + } catch { + setCompletedMap(previous) + return false + } finally { + setSavingSlug((curr) => (curr === slug ? null : curr)) + } + }, []) + + const completedCount = useMemo( + () => Object.keys(completed).filter((slug) => KNOWN_SLUGS.has(slug)).length, + [completed], + ) + + const value = useMemo( + () => ({ + user, + completed, + loading, + savingSlug, + isCompleted, + setCompleted, + completedCount, + totalLessons: lessons.length, + }), + [user, completed, loading, savingSlug, isCompleted, setCompleted, completedCount], + ) + + return {children} +} + +export function useProgress(): ProgressContextValue { + const ctx = useContext(ProgressContext) + if (!ctx) throw new Error('useProgress must be used within ProgressProvider') + return ctx +} diff --git a/site/src/routes/LessonIndex.tsx b/site/src/routes/LessonIndex.tsx index e94f1ef..f4076b0 100644 --- a/site/src/routes/LessonIndex.tsx +++ b/site/src/routes/LessonIndex.tsx @@ -1,7 +1,10 @@ import { lessons, lessonSections } from '@/lib/lessons' +import { useProgress } from '@/lib/progress' import { LessonCard } from '@/components/LessonCard' export function LessonIndex() { + const { isCompleted, completedCount, totalLessons, user } = useProgress() + return (
@@ -10,20 +13,44 @@ export function LessonIndex() { Learn the fundamentals of programming, one short lesson at a time. Every lesson is hands-on — build and run things right in the browser.

+ {user && ( +

+ Progress:{' '} + + {completedCount} of {totalLessons} + {' '} + lessons completed +

+ )}
- {lessonSections.map((section) => ( -
-

- {section.title} -

-
- {section.lessons.map((lesson) => ( - - ))} -
-
- ))} + {lessonSections.map((section) => { + const doneInSection = section.lessons.filter((l) => isCompleted(l.slug)).length + return ( +
+
+

+ {section.title} +

+ {user && ( + + {doneInSection} / {section.lessons.length} + + )} +
+
+ {section.lessons.map((lesson) => ( + + ))} +
+
+ ) + })}
) diff --git a/site/src/routes/LessonView.tsx b/site/src/routes/LessonView.tsx index f2bf3a0..5e1799e 100644 --- a/site/src/routes/LessonView.tsx +++ b/site/src/routes/LessonView.tsx @@ -1,4 +1,5 @@ import type { ReactNode } from 'react' +import { Check, Circle } from 'lucide-react' import { Link, Navigate, useNavigate, useParams } from 'react-router-dom' import ReactMarkdown from 'react-markdown' import type { Components } from 'react-markdown' @@ -13,13 +14,17 @@ import { nextLesson, stripBlocksFence, } from '@/lib/lessons' +import { useProgress } from '@/lib/progress' import { JavaRunner } from '@/components/JavaRunner' import { CodeBlock } from '@/components/CodeBlock' import { BlockPlayground } from '@/components/BlockPlayground' +import { FlowchartPlayground } from '@/components/FlowchartPlayground' import { MazePlayground } from '@/components/MazePlayground' import { StatePlayground } from '@/components/StatePlayground' +import { isFlowchartPreset } from '@/lib/flowchartPresets' import { isStatePreset } from '@/lib/statePresets' import { PageNav } from '@/components/PageNav' +import { Button } from '@/components/ui/button' // Fenced code blocks in the prose render read-only through CodeMirror (same // syntax highlighting + line numbers as the playground); the runnable copy of @@ -79,10 +84,17 @@ const PROSE_CLASSES = [ export function LessonView() { const { slug, page } = useParams() const navigate = useNavigate() + const { isCompleted, setCompleted, savingSlug, user } = useProgress() const lesson = getLesson(slug ?? '') if (!lesson) return + const completed = isCompleted(lesson.slug) + const saving = savingSlug === lesson.slug + const toggleCompleted = () => { + void setCompleted(lesson.slug, !completed) + } + const pageCount = lesson.pages.length const requested = page ? Number(page) - 1 : 0 const pageIndex = Number.isFinite(requested) @@ -104,9 +116,37 @@ export function LessonView() { return (
- - ← All lessons - +
+ + ← All lessons + + {user && ( + + )} +

Goal: {lesson.goal}

@@ -132,6 +172,11 @@ export function LessonView() {

▶ State machine

+ ) : preset && isFlowchartPreset(preset) ? ( + <> +

▶ Interactive Flowchart

+ + ) : preset ? ( <>

▶ Block editor

@@ -156,6 +201,20 @@ export function LessonView() { onNext={() => goTo(pageIndex + 1)} onJump={goTo} /> + {onLastPage && user && !completed && ( +
+
Finished this lesson?
+ +
+ )} {onLastPage && (next ? (