From 22688d352611b9b90ab504e436861bab4d777437 Mon Sep 17 00:00:00 2001 From: devmtnaing Date: Wed, 7 Oct 2026 20:43:02 +0630 Subject: [PATCH 1/4] Merge the AI Engineer course into the site, one design for both MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The site now has two sections under one shell: /leetcode (the problem list moved here from /) and /ai-engineer, a self-study path built from the markdown course in course/. The home page is a hub for both. - Design: the AI Engineer look becomes the design system. tokens.css holds the palette, fonts (Sora, Plus Jakarta Sans, JetBrains Mono) and two accents chosen by : teal for LeetCode, indigo for the AI section and hub. Every text colour still clears AA in both themes. - Shell: a dark sidebar, a 56px sticky top bar with search and the theme switch, and a progress rail on AI pages. Icons only under 1024px, a bottom tab bar under 720px. Lesson offsets keep the 56px bar. - AI Engineer: static track, module and lesson-step pages; quizzes, checklists, flashcards and the profile are Preact islands. Progress, XP and streak live in src/lib/progress.ts for the whole site. - Search: ⌘K also finds AI Engineer modules. - Audit: serves /x.html before /x/ like Cloudflare, checks the problem list at /leetcode, and checks the hub and a sample of AI pages for errors, overflow at 320 and 400px, and AA in both themes. npm run check and npm run audit pass (46 lessons). --- .../references/lesson-kit.md | 6 +- CONTRIBUTING.md | 6 +- README.md | 23 +- astro.config.mjs | 5 +- course/00-setup/README.md | 52 + course/README.md | 86 ++ course/math/README.md | 127 +++ course/notes/README.md | 42 + course/notes/glossary.md | 6 + course/projects/README.md | 171 ++++ .../track-1-ai-application-engineer/README.md | 223 +++++ course/track-2-ml-systems-engineer/README.md | 281 ++++++ course/track-3-research-engineer/README.md | 199 ++++ course/track-3-research-engineer/papers.md | 126 +++ package-lock.json | 886 +++++++++++++++++- package.json | 5 +- public/_redirects | 6 +- public/favicon.svg | 1 + scripts/audit.mjs | 60 +- src/components/AppSidebar.astro | 96 ++ src/components/Icon.astro | 6 + src/components/Logo.astro | 11 + src/components/Masthead.astro | 17 - src/components/SiteFooter.astro | 2 +- src/components/SiteSearch.astro | 17 +- src/components/ai/Onboard.tsx | 59 ++ src/components/ai/Practice.tsx | 124 +++ src/components/ai/Profile.tsx | 112 +++ src/components/ai/Rail.tsx | 132 +++ src/components/ai/Review.tsx | 22 + src/components/ai/Session.tsx | 478 ++++++++++ src/components/ai/Stepper.astro | 29 + src/components/ai/TrackTabs.astro | 20 + src/components/ai/ui.tsx | 37 + src/layouts/AiLayout.astro | 24 + src/layouts/Base.astro | 49 +- src/layouts/Walkthrough.astro | 6 +- src/lessons/basic-calculator/style.css | 2 +- src/lessons/course-schedule/style.css | 2 +- .../implement-trie-prefix-tree/style.css | 2 +- .../largest-rectangle-in-histogram/style.css | 2 +- src/lessons/merge-intervals/style.css | 4 +- src/lessons/merge-k-sorted-lists/style.css | 2 +- src/lessons/trapping-rain-water/style.css | 2 +- src/lessons/word-ladder/style.css | 4 +- src/lessons/x-sum/style.css | 14 +- src/lib/ai/course.ts | 244 +++++ src/lib/ai/decorate.ts | 59 ++ src/lib/ai/flashcards.ts | 101 ++ src/lib/ai/quizzes.ts | 699 ++++++++++++++ src/lib/icons.ts | 36 + src/lib/progress.ts | 143 +++ src/lib/stage.js | 4 +- src/pages/404.astro | 2 +- src/pages/ai-engineer/[track].astro | 55 ++ src/pages/ai-engineer/[track]/[module].astro | 30 + .../ai-engineer/[track]/[module]/[unit].astro | 32 + src/pages/ai-engineer/index.astro | 40 + src/pages/ai-engineer/papers.astro | 55 ++ src/pages/ai-engineer/practice.astro | 12 + src/pages/ai-engineer/projects.astro | 41 + src/pages/ai-engineer/review.astro | 9 + src/pages/index.astro | 231 +---- src/pages/leetcode/index.astro | 190 ++++ src/pages/profile.astro | 16 + src/pages/search.json.ts | 19 +- src/styles/ai.css | 310 ++++++ src/styles/app.css | 97 ++ src/styles/base.css | 16 +- src/styles/kit.css | 34 +- src/styles/lesson.css | 72 +- src/styles/site.css | 63 +- src/styles/tokens.css | 133 ++- tsconfig.json | 15 +- 74 files changed, 5908 insertions(+), 436 deletions(-) create mode 100644 course/00-setup/README.md create mode 100644 course/README.md create mode 100644 course/math/README.md create mode 100644 course/notes/README.md create mode 100644 course/notes/glossary.md create mode 100644 course/projects/README.md create mode 100644 course/track-1-ai-application-engineer/README.md create mode 100644 course/track-2-ml-systems-engineer/README.md create mode 100644 course/track-3-research-engineer/README.md create mode 100644 course/track-3-research-engineer/papers.md create mode 100644 public/favicon.svg create mode 100644 src/components/AppSidebar.astro create mode 100644 src/components/Icon.astro create mode 100644 src/components/Logo.astro delete mode 100644 src/components/Masthead.astro create mode 100644 src/components/ai/Onboard.tsx create mode 100644 src/components/ai/Practice.tsx create mode 100644 src/components/ai/Profile.tsx create mode 100644 src/components/ai/Rail.tsx create mode 100644 src/components/ai/Review.tsx create mode 100644 src/components/ai/Session.tsx create mode 100644 src/components/ai/Stepper.astro create mode 100644 src/components/ai/TrackTabs.astro create mode 100644 src/components/ai/ui.tsx create mode 100644 src/layouts/AiLayout.astro create mode 100644 src/lib/ai/course.ts create mode 100644 src/lib/ai/decorate.ts create mode 100644 src/lib/ai/flashcards.ts create mode 100644 src/lib/ai/quizzes.ts create mode 100644 src/lib/icons.ts create mode 100644 src/lib/progress.ts create mode 100644 src/pages/ai-engineer/[track].astro create mode 100644 src/pages/ai-engineer/[track]/[module].astro create mode 100644 src/pages/ai-engineer/[track]/[module]/[unit].astro create mode 100644 src/pages/ai-engineer/index.astro create mode 100644 src/pages/ai-engineer/papers.astro create mode 100644 src/pages/ai-engineer/practice.astro create mode 100644 src/pages/ai-engineer/projects.astro create mode 100644 src/pages/ai-engineer/review.astro create mode 100644 src/pages/leetcode/index.astro create mode 100644 src/pages/profile.astro create mode 100644 src/styles/ai.css create mode 100644 src/styles/app.css diff --git a/.claude/skills/leetcode-solution-page/references/lesson-kit.md b/.claude/skills/leetcode-solution-page/references/lesson-kit.md index c1aec08..7e7043f 100644 --- a/.claude/skills/leetcode-solution-page/references/lesson-kit.md +++ b/.claude/skills/leetcode-solution-page/references/lesson-kit.md @@ -65,7 +65,7 @@ right. not a row), transport with the narration under it, then the stage and ✓ the answer beside "The code, live" with hoverable variables and any `caveats` note under it. Don't add boxes inside the player. The transport and - narration stay under the masthead while the reader scrolls the stage and + narration stay under the top bar while the reader scrolls the stage and code, and the strip wraps onto more rows on a narrow screen. ✓ Under the player, the `playHint` line from `page.js`: the keys (`←` `→` step · `space` play/pause), what the reader can edit "above" and any limits ("up to 12 @@ -86,12 +86,12 @@ reader should meet first. ## The folder a lesson writes Everything for a lesson is one folder; `src/pages/leetcode/[slug].astro` -renders every folder that has a `page.js`, and the home page lists problems +renders every folder that has a `page.js`, and the problem list (`/leetcode`) lists problems only: a problem whose id is in some lesson's `links` gets its title linked (the whole row opens the page), the rest say "Solution coming soon", and every row has a "View on LeetCode ↗" link. Problems are grouped by the `category` each has in `src/data/problems.json`; a problem added there needs one of the -categories listed in `src/pages/index.astro`. There is no page file and no index entry to add. +categories listed in `src/pages/leetcode/index.astro`. There is no page file and no index entry to add. ``` src/lessons//page.js the static prose, as Walkthrough props diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 926e028..57caaeb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,7 +1,7 @@ # Contributing a solution page The most useful contribution is a new solution page for a problem on the list -that doesn't have one yet: any row on the home page marked *Solution coming +that doesn't have one yet: any row on the problem list (`/leetcode`) marked *Solution coming soon*. Fixes to existing pages, including better Burmese, are just as welcome. Before you start, open a page or two to see what one looks like: @@ -35,7 +35,7 @@ code they can trust. So three rules are firm: ## Building a page, step by step A page is one folder, `src/lessons//`. The route finds it and -the home page links it automatically, so there is nothing else to register. +the problem list links it automatically, so there is nothing else to register. ``` src/lessons//statement.html LeetCode's statement, verbatim @@ -137,7 +137,7 @@ Every prop is required, and `npm run check` names any that are missing: `title`, `summary`, `eyebrow`, `lede`, `links`, `constraints`, `part1Sub`, `widgetTitle`, `traps`, `part2Sub`, `notes`, `cost`, `part3Sub`, `playHint`. `links` carries the LeetCode problem id, and that id is what links the -problem's row on the home page to your page. `playHint` is the line under the +problem's row on the problem list to your page. `playHint` is the line under the player in 2·2: the keys, what the reader can edit above it and within what limits, and what rebuilds. diff --git a/README.md b/README.md index b666491..f0b587b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ # LeetCode solution pages -**Live: [learn.devmtnaing.com](https://learn.devmtnaing.com).** Open any problem and step through its solution. +**Live: [learn.devmtnaing.com](https://learn.devmtnaing.com).** Two sections share one site, one design and one progress record: + +- **[LeetCode](https://learn.devmtnaing.com/leetcode)**: open any problem and step through its solution. +- **[AI Engineer](https://learn.devmtnaing.com/ai-engineer)**: a self-study path from backend engineer to AI research engineer, built from the markdown course in [`course/`](course/README.md), with quizzes, flashcards, XP and streaks. [![Lowest Common Ancestor, step 4 of 7: the tree with the call stack beside it and the Ruby line that is running highlighted](docs/screenshots/walkthrough.png)](https://learn.devmtnaing.com/leetcode/lowest-common-ancestor-of-a-binary-tree) @@ -32,7 +35,7 @@ theme. The screenshots below are all in the dark one. **The problem list.** 47 problems grouped by pattern, with search, a difficulty filter and ⌘K from any page. -[![The home page: patterns down the side, problems with difficulty and acceptance rate](docs/screenshots/home.png)](https://learn.devmtnaing.com) +[![The home page: patterns down the side, problems with difficulty and acceptance rate](docs/screenshots/home.png)](https://learn.devmtnaing.com/leetcode) **In Burmese.** Trapping Rain Water with two pointers, finished. @@ -49,7 +52,7 @@ npm run audit # every built page in a real browser (after npm run build) npm run refresh-problems # re-read titles, tags and acceptance rates from LeetCode ``` -The home page lists 45 interview problems, 15 each of easy, medium and hard, +The problem list has 45 interview problems, 15 each of easy, medium and hard, chosen where three of LeetCode's own study plans agree ([how](docs/problem-list.md)), plus 2 from outside that list, grouped by pattern (Arrays & Hashing, Two Pointers, Trees, …). Every one of them has a @@ -59,11 +62,18 @@ solution page. To add a problem or fix a page, see ## What is in the repo ``` -src/pages/index.astro the problem list +src/pages/index.astro the hub: both sections +src/pages/leetcode/index.astro the problem list src/pages/leetcode/[slug].astro renders every lesson folder src/lessons// one folder per solution page +src/pages/ai-engineer/ the AI Engineer path, module guides and lesson steps +src/pages/profile.astro progress across both sections +course/ the AI Engineer course as markdown (the pages read it at build) +src/lib/ai/ course parser, quizzes, flashcards, progress painter +src/components/ai/ Preact islands: lesson steps, practice, profile, rail +src/lib/progress.ts progress, XP and streak for the whole site (localStorage) src/lib/ the shared kit: stepper, stage shapes, trees, i18n -src/styles/ tokens, site chrome, the lesson page, the stage +src/styles/ tokens (one design, a teal and an indigo accent), app shell, lessons, AI section scripts/check-lessons.mjs structure and format check scripts/audit.mjs drives every built page in Chromium scripts/refresh-problems.mjs refreshes src/data/problems.json from LeetCode @@ -73,7 +83,8 @@ docs/ how the problem list was chosen; translation not wrangler.jsonc Cloudflare: serve dist/ at learn.devmtnaing.com ``` -The site is fully static: every page is prerendered and served as a file, so +The site is fully static: every page is prerendered and served as a file (the +AI Engineer's interactive steps are small Preact islands on those pages), so there's no backend. A solution page is a folder of data and one step generator per approach. The kit supplies the transport, code panel, language switching and layout. Every lesson has a spec in `verify/`, so `npm run verify -- diff --git a/astro.config.mjs b/astro.config.mjs index 23ae92c..ceb9816 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -1,8 +1,10 @@ // @ts-check import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; // The site is fully static: every page is prerendered at build time and served // from a CDN. Nothing here runs per-request, which is why there is no adapter. +// Preact renders the few interactive islands of the AI Engineer section. export default defineConfig({ site: 'https://learn.devmtnaing.com', // Pages build as /leetcode/two-sum.html and are linked without a slash, so @@ -10,6 +12,5 @@ export default defineConfig({ // /leetcode/two-sum/ on every click. build: { format: 'file' }, trailingSlash: 'never', - // The problem list used to live here, before it became the home page. - redirects: { '/leetcode': '/' }, + integrations: [preact()], }); diff --git a/course/00-setup/README.md b/course/00-setup/README.md new file mode 100644 index 0000000..52a572d --- /dev/null +++ b/course/00-setup/README.md @@ -0,0 +1,52 @@ +# 00 · Setup (week 0) + +Get the tooling out of the way so it doesn't slow you down later. + +## 1. Python for ML (coming from Ruby) + +You already know Python from backend work. ML Python is a different style: array-oriented, notebook-heavy and full of shapes. + +**Learn** +- *Core:* [NumPy: the absolute basics for beginners](https://numpy.org/doc/stable/user/absolute_beginners.html) +- *Core:* [NumPy broadcasting](https://numpy.org/doc/stable/user/basics.broadcasting.html). Broadcasting bugs are the most common silent ML bug. +- *Core:* [PyTorch: Learn the Basics](https://pytorch.org/tutorials/beginner/basics/intro.html) +- *Optional:* [Python Data Science Handbook](https://jakevdp.github.io/PythonDataScienceHandbook/) by Jake VanderPlas (free online), chapters on NumPy and Pandas. + +**Build** +- Write matrix multiplication with three nested Python loops, then with NumPy. Time both at 512×512. +- Implement `softmax` in NumPy for a batch of vectors (shape `[batch, classes]`). Make it numerically stable by subtracting the max. + +## 2. Environment + +- **Package manager:** [`uv`](https://docs.astral.sh/uv/) (fast, handles Python versions and venvs). One project per folder under `projects/`. +- **Notebooks:** Jupyter or VS Code notebooks for exploration. Move code into `.py` files once it works. +- **Experiment tracking:** a free [Weights & Biases](https://wandb.ai/) account. You'll use it from Track 2. +- **Hugging Face account:** for models, datasets and hosting demos. +- **Model API keys:** Anthropic (and optionally one other provider) for Track 1. Set a monthly spend limit. + +## 3. GPU access + +Your Mac is fine for Track 1 and the early Track 2 work (small models, `mps` backend). Later you'll need NVIDIA GPUs. + +| Option | Good for | Notes | +|---|---|---| +| [Google Colab](https://colab.research.google.com/) | Early exercises | Free tier has a T4; Pro is cheap. | +| [Kaggle Notebooks](https://www.kaggle.com/code) | Free GPU hours | Weekly quota. | +| [Modal](https://modal.com/) | Python-native serverless GPUs | A good fit for a backend engineer; pay per second. | +| RunPod / Lambda / Vast.ai | Hourly A100/H100 rentals | For GPT-2 reproduction and inference benchmarks. | +| AWS (g5/g6/p4/p5 instances) | Production-style benchmarks | You know AWS already. Watch the costs. | + +**Budget guide:** expect roughly USD 0–20/month in Track 1 and 20–150/month in Track 2. A GPT-2 (124M) reproduction costs about USD 10–30 on rented GPUs. + +## 4. Notes system + +- Use `notes/` in this repo: one markdown file per week (template in `notes/README.md`). +- Keep a running `notes/glossary.md`. When you meet a new term, write a one-line definition in your own words. +- Consider Anki for spaced repetition of formulas and definitions (softmax, cross-entropy, attention, Adam update rule). + +## Checkpoint + +- [ ] `uv` project created, NumPy and PyTorch import, a tensor runs on `mps` (Mac) or `cuda` (Colab) +- [ ] Hugging Face, W&B and API accounts ready +- [ ] Stable softmax implemented and tested against `torch.softmax` +- [ ] First weekly note written diff --git a/course/README.md b/course/README.md new file mode 100644 index 0000000..2b78cb8 --- /dev/null +++ b/course/README.md @@ -0,0 +1,86 @@ +# From Backend Engineer to AI Research Engineer + +A self-study curriculum in three tracks. Each track is a career step you can be hired at, and each one builds the understanding the next track needs. + +``` + Track 1 Track 2 Track 3 + AI Application Engineer ──► ML / AI Systems Engineer ──────► Research Engineer + (use models well) (train, tune, serve models) (understand & improve models) + ~3.5–4 months ~7–9 months ~8–12 months, then ongoing + + ════════════════════ Math track runs alongside all three (math/) ═════════════════════ +``` + +**Who this is for:** an experienced backend engineer (Rails, Python, Kafka, AWS, performance work) with no formal ML background who wants real depth rather than only API-level skill. + +**Pace assumption:** 12–15 hours/week. Studying full-time roughly halves the timeline. + +--- + +## Layout + +| Folder | What's inside | +|---|---| +| [`00-setup/`](00-setup/README.md) | Python/ML tooling, GPU access, how to take notes. Do this first (1 week). | +| [`math/`](math/README.md) | The math track in three levels, matched to the three tracks. | +| [`track-1-ai-application-engineer/`](track-1-ai-application-engineer/README.md) | LLM APIs, prompting, RAG, agents, MCP, evals, production concerns, agent frameworks (LangGraph) & durable workflows (Temporal). | +| [`track-2-ml-systems-engineer/`](track-2-ml-systems-engineer/README.md) | Neural nets from scratch, deep learning, transformers, fine-tuning, GPUs, inference, distributed training, Kubernetes & GPU infrastructure. | +| [`track-3-research-engineer/`](track-3-research-engineer/README.md) | Deeper theory, RL and post-training, interpretability, reading and reproducing papers, doing research. | +| [`track-3-research-engineer/papers.md`](track-3-research-engineer/papers.md) | A reading list of core papers, ordered. | +| [`projects/`](projects/README.md) | Every capstone project in one place, plus a write-up template. | +| [`notes/`](notes/README.md) | Your learning log. One file per week. | +| The site | [learn.devmtnaing.com/ai-engineer](https://learn.devmtnaing.com/ai-engineer) is built from these files (`src/pages/ai-engineer/`): path, quizzes, flashcards, XP and streaks. | + +--- + +## Timeline at a glance + +| Month | Track work | Math alongside | You can apply for | +|---|---|---|---| +| 0 | Setup | – | – | +| 1–4 | **Track 1**: modules 1.1–1.8 + capstone (AI Factory Ops Agent v1) | Level 1 (vectors, similarity, softmax, basic probability) | AI Engineer (Agents & Applications), AI Product Engineer, backend roles on AI teams | +| 5–7 | **Track 2**: modules 2.1–2.5 (from scratch → fine-tuning) | Level 2 (linear algebra, calculus, probability, optimization) | – | +| 8–12 | **Track 2**: modules 2.6–2.10 (GPUs, inference, distributed, platform, Kubernetes) + capstones, Ops Agent v2 | Level 2 finish | **ML Platform / ML Infrastructure / Inference Engineer** | +| 13–18 | **Track 3**: modules 3.1–3.5 | Level 3 (deeper probability, optimization, information theory) | – | +| 19–24+ | **Track 3**: modules 3.6–3.7, paper reproductions, original work | Level 3 ongoing | **Research Engineer** (lab, applied research team, or fellowship such as MATS or Anthropic Fellows) | + +You don't have to finish everything before moving on. Get a job at the Track 1 or Track 2 level and keep going while employed. That's the normal route. + +--- + +## How each module works + +Every module has the same four parts: + +1. **Why it matters**: one or two lines. +2. **Learn**: *core* resources (do these) and *optional* ones (go deeper if you're curious). +3. **Build**: hands-on exercises. Not optional; this is where the learning happens. +4. **Checkpoint**: what you should be able to do or explain before moving on. If you can't do it, go back. + +## Rules that make this work + +1. **Implement before you import.** Before using a library for something (attention, LoRA, BM25, Adam), write a small version yourself in NumPy or PyTorch. It can be slow and ugly. +2. **Write up everything you build.** A README with what you tried, what failed, numbers and plots. Publish the good ones on devmtnaing.com. Write-ups are how you'll show depth to hiring managers. +3. **Measure, don't guess.** Every project needs a number: eval score, loss, tokens/sec, p95 latency, $ per 1M tokens. You already do this with APIs and databases; keep doing it. +4. **Learn the math when the code needs it.** Don't spend three months on math before touching a model. The `math/` track tells you which math to learn at which stage. +5. **Weekly rhythm:** about 60% building, 30% studying, 10% writing. Log the week in `notes/`. +6. **Explain it out loud.** If you can't explain a concept to a junior engineer on a whiteboard, you don't understand it yet. That was true for Kafka, and it's true for backprop. + +--- + +## Progress + +Tick these off as you go. The detailed checklists are in each track's README. + +- [ ] 00 Setup complete +- [ ] Track 1 modules complete +- [ ] Track 1 capstone published +- [ ] Math Level 1 +- [ ] Track 2 modules 2.1–2.5 +- [ ] Track 2 modules 2.6–2.10 +- [ ] Track 2 capstones published (at least 2 of 4) +- [ ] Math Level 2 +- [ ] Track 3 modules 3.1–3.5 +- [ ] Track 3 paper reproduction published +- [ ] Track 3 original study published +- [ ] Math Level 3 diff --git a/course/math/README.md b/course/math/README.md new file mode 100644 index 0000000..486a6be --- /dev/null +++ b/course/math/README.md @@ -0,0 +1,127 @@ +# Math Track + +The math runs **alongside** the three tracks, not before them. Each level covers what its matching track needs. + +**Method:** learn the intuition (videos), work through the formal material (book), then **implement it in NumPy**. If you can code it and check it against a library, you understand it. + +| Level | Pairs with | Rough effort | +|---|---|---| +| Level 1: Intuition | Track 1 | 2–3 hrs/week for 6–8 weeks | +| Level 2: Working math for deep learning | Track 2 | 3–4 hrs/week for 4–6 months | +| Level 3: Research math | Track 3 | Ongoing | + +--- + +## Level 1: Intuition (with Track 1) + +Enough to understand embeddings, similarity search and why sampling settings change model outputs. + +**Topics** +- Vectors, dot product, vector length (norm), cosine similarity +- Matrices as functions that transform vectors; matrix-vector multiply +- Exponentials and logs; why we work in log-space +- Softmax and temperature +- Basic probability: distributions, sampling, expected value +- Basic statistics for evals: mean, variance, standard error, confidence intervals + +**Learn** +- *Core:* 3Blue1Brown, [Essence of Linear Algebra](https://www.3blue1brown.com/topics/linear-algebra), chapters 1–4 and 9 +- *Core:* 3Blue1Brown, [Neural Networks](https://www.3blue1brown.com/topics/neural-networks) series. Watch all of it, including the transformer and attention chapters; it previews Track 2. +- *Core:* Khan Academy, [Statistics and Probability](https://www.khanacademy.org/math/statistics-probability): the sections on probability, random variables and confidence intervals +- *Optional:* [Seeing Theory](https://seeing-theory.brown.edu/), visual probability + +**Build (NumPy)** +- [ ] Cosine similarity between one query vector and 10,000 document vectors, without loops +- [ ] Softmax with a temperature parameter. Plot the output distribution at T = 0.1, 1, 2. +- [ ] Sample 10,000 tokens from a softmax distribution and check the empirical frequencies match +- [ ] Given eval scores from 50 test cases for two prompts, compute the mean and a 95% confidence interval. Is prompt B really better? + +**Checkpoint:** explain to a colleague why temperature 0 is (nearly) deterministic, and why cosine similarity is used for embeddings rather than Euclidean distance. + +--- + +## Level 2: Working math for deep learning (with Track 2) + +The math behind backpropagation, loss functions and optimizers. + +### 2a. Linear algebra +- Matrix multiplication as many dot products; the rule shapes must follow: `[m,k] @ [k,n] → [m,n]` +- Transpose, identity, inverse (conceptually) +- Linear transformations, basis, rank +- Eigenvalues/eigenvectors and SVD (intuition, and why low-rank matters, which is the idea behind LoRA) +- Tensors as multi-dimensional arrays; batch dimensions; `einsum` + +### 2b. Calculus +- Derivatives as rates of change; partial derivatives +- **The chain rule.** This is backpropagation. +- Gradients (the vector of partial derivatives) and what "direction of steepest ascent" means +- Jacobians (enough to follow shapes through a network) +- Computational graphs + +### 2c. Probability & information theory +- Random variables, PMF/PDF, expectation, variance +- Bernoulli, categorical and Gaussian distributions +- Conditional probability, Bayes' rule +- Maximum likelihood estimation. Why minimizing cross-entropy equals maximizing likelihood. +- Entropy, cross-entropy, KL divergence +- Perplexity (the exponentiated cross-entropy you'll see in LLM papers) + +### 2d. Optimization +- Gradient descent, learning rate, why too-large rates diverge +- Stochastic and mini-batch gradient descent +- Momentum, RMSProp, **Adam / AdamW** +- Learning-rate warmup and cosine decay +- Convex vs non-convex (intuition) + +**Learn** +- *Core:* Deisenroth, Faisal & Ong, [*Mathematics for Machine Learning*](https://mml-book.github.io/) (free PDF), chapters 2 (linear algebra), 5 (vector calculus), 6 (probability), 7 (optimization). Use it as a reference; don't read it cover to cover. +- *Core:* 3Blue1Brown, [Essence of Calculus](https://www.3blue1brown.com/topics/calculus), chapters 1–4 +- *Core:* Karpathy's [micrograd video](https://www.youtube.com/watch?v=VMj-3S1tku0), the best explanation of the chain rule as code +- *Core:* Parr & Howard, [The Matrix Calculus You Need for Deep Learning](https://explained.ai/matrix-calculus/) +- *Optional:* Gilbert Strang, [MIT 18.06 Linear Algebra](https://ocw.mit.edu/courses/18-06-linear-algebra-spring-2010/) (classic lectures) +- *Optional:* Sebastian Ruder, [An overview of gradient descent optimization algorithms](https://www.ruder.io/optimizing-gradient-descent/) +- *Optional:* Christopher Olah, [Visual Information Theory](https://colah.github.io/posts/2015-09-Visual-Information/) + +**Build (NumPy, then check against PyTorch)** +- [ ] Linear regression trained with gradient descent: derive the gradient by hand, implement it, plot loss over steps +- [ ] Logistic regression on a 2D toy dataset with a hand-derived cross-entropy gradient +- [ ] Numerical gradient checking: compare your analytic gradient with `(f(x+h) - f(x-h)) / 2h` +- [ ] Implement SGD, momentum and Adam from their update equations, then race them on the same problem +- [ ] SVD on a small matrix; reconstruct it at rank 1, 2, 5 and plot the error (this is the LoRA idea) +- [ ] Compute entropy, cross-entropy and KL divergence between two categorical distributions; check KL ≥ 0 +- [ ] Rewrite three matrix operations using `np.einsum` + +**Checkpoint:** on a whiteboard, derive the gradient of softmax + cross-entropy with respect to the logits (it comes out as `p - y`), and explain why Adam usually beats plain SGD on transformers. + +--- + +## Level 3: Research math (with Track 3) + +Enough to read most ML papers without getting stuck on the notation, and to reason about why methods work. + +**Topics** +- **Probability, more rigorously:** joint, marginal and conditional distributions; multivariate Gaussians; law of large numbers; central limit theorem; Monte Carlo estimation +- **Statistics:** hypothesis testing, bootstrap, multiple comparisons, effect sizes. You need these to make honest claims in experiments. +- **Bayesian thinking:** priors, posteriors, variational inference and the ELBO (used in VAEs and diffusion) +- **Optimization theory:** convexity, Lagrange multipliers, constrained optimization (used in RL and alignment derivations, e.g. the DPO derivation) +- **Information theory:** mutual information, KL properties (forward vs reverse KL) +- **Linear algebra depth:** eigendecomposition, matrix norms, conditioning, low-rank structure +- **RL math:** Markov decision processes, Bellman equations, policy gradient theorem +- *Optional:* random matrix theory and high-dimensional geometry (why initialization scales matter); stochastic differential equations (diffusion models) + +**Learn** +- *Core:* Joe Blitzstein, [Stat 110: Probability](https://stat110.net/) (Harvard; lectures and book free) +- *Core:* Boyd & Vandenberghe, [*Convex Optimization*](https://web.stanford.edu/~boyd/cvxbook/) (free PDF), chapters 1–5 +- *Core:* Kevin Murphy, [*Probabilistic Machine Learning: An Introduction*](https://probml.github.io/pml-book/book1.html) (free PDF), as your reference text +- *Core:* Sutton & Barto, [*Reinforcement Learning: An Introduction*](http://incompleteideas.net/book/the-book-2nd.html) (free PDF), chapters 1–6 and 13 +- *Optional:* Kevin Murphy, [*Probabilistic Machine Learning: Advanced Topics*](https://probml.github.io/pml-book/book2.html) +- *Optional:* David MacKay, [*Information Theory, Inference, and Learning Algorithms*](https://www.inference.org.uk/mackay/itila/) (free) + +**Build** +- [ ] Bootstrap confidence intervals for an eval metric; compare with the analytic standard error +- [ ] Monte Carlo estimate of an expectation; plot the error against sample count (shrinks as 1/√n) +- [ ] Derive and implement REINFORCE (policy gradient) on a simple bandit problem +- [ ] Follow the DPO paper's derivation line by line from the RLHF objective to the DPO loss, writing each step in your notes +- [ ] Measure forward vs reverse KL between a bimodal distribution and a single Gaussian fit; explain the "mode-covering vs mode-seeking" behavior + +**Checkpoint:** pick a recent ML paper, read the method section, and rewrite its key equation in your own notation with every symbol defined. diff --git a/course/notes/README.md b/course/notes/README.md new file mode 100644 index 0000000..e010495 --- /dev/null +++ b/course/notes/README.md @@ -0,0 +1,42 @@ +# Notes + +Your learning log. + +``` +notes/ +├── README.md ← this file +├── glossary.md ← one-line definitions in your own words +├── 2026-W41.md ← one file per week (ISO week number) +├── 2026-W42.md +└── papers/ ← one summary per paper (template in track-3-research-engineer/papers.md) +``` + +## Weekly log template + +Copy into `notes/-W.md`: + +```markdown +# Week · + +**Track / module:** +**Hours:** build: _ study: _ write: _ + +## What I built + +## What I learned (explain it as if to a junior engineer) + +## What confused me / still don't get + +## Numbers +(loss, eval scores, tokens/sec, cost, anything measured) + +## Next week +- [ ] +- [ ] +``` + +## Monthly review (first weekend of each month) + +- Am I on pace with the timeline in the top-level README? If not, cut scope rather than skip building. +- Which checkpoint can I *not* yet pass? Go back to that first. +- What did I publish this month? (Aim for at least one write-up per month.) diff --git a/course/notes/glossary.md b/course/notes/glossary.md new file mode 100644 index 0000000..b63ab02 --- /dev/null +++ b/course/notes/glossary.md @@ -0,0 +1,6 @@ +# Glossary + +One line per term, in your own words. Alphabetical. + +| Term | Meaning | +|---|---| diff --git a/course/projects/README.md b/course/projects/README.md new file mode 100644 index 0000000..956018f --- /dev/null +++ b/course/projects/README.md @@ -0,0 +1,171 @@ +# Projects + +All capstones in one place. Each project goes in its own folder here (e.g. `projects/01-ai-factory-ops-agent/`) with its own `uv` environment and a `README.md` write-up using the template at the bottom. + +These are your portfolio. Hiring managers will read the write-ups, so make them clear and honest, and include numbers. + +| # | Project | Track | Shows | +|---|---|---|---| +| 1 | AI Factory Ops Agent | 1 (v2 after Track 2) | Multi-agent design, RAG, MCP, durable workflows, human-in-the-loop, agent security, evals | +| A | Reproduce GPT-2 (124M) | 2 | Deep understanding of transformers & training | +| B | Domain fine-tune that beats a prompted model | 2 | Fine-tuning, data curation, evaluation | +| C | LLM inference benchmark on AWS | 2 | Inference optimization, cost engineering (data feeds Project 1 v2) | +| D | Make training go brrr | 2 | GPU performance, profiling, Triton | +| E | Paper reproduction | 3 | Research engineering, rigor | +| F | Small original study | 3 | Research taste, experiment design, writing | + +--- + +## Track 1 capstone: AI Factory Ops Agent + +**Idea:** a multi-agent assistant for teams running GPU infrastructure (an "AI factory"). It answers operational questions, analyses benchmark results, recommends configurations and diagnoses problems, and it never takes action without human approval. It combines your backend, data-ingestion and DevOps background with agents, and it maps closely onto "AI Engineer, Agents & Applications" roles at infrastructure companies. + +**Version 1 (end of Track 1, no GPUs needed)** +- **Knowledge ingestion** as a Temporal (or Dagster) workflow: public GPU and inference docs (vLLM, NVIDIA, Kubernetes), 30+ runbooks you write (start with the failures you cause in a local cluster), and public benchmark results such as [MLPerf Inference](https://mlcommons.org/benchmarks/inference-datacenter/). Uses hybrid retrieval (pgvector + BM25 + reranker) with metadata filters (GPU type, model, framework version). +- **MCP servers** exposing tools: + - `query_benchmarks` (SQL over benchmark results) + - `get_k8s_status` / `get_pod_logs` / `get_events` (read-only, against a local kind cluster) + - `query_metrics` (PromQL against Prometheus) + - `propose_change` (drafts a config change or scaling action, but **never applies it**; it creates an approval request) +- **Multi-agent design in LangGraph:** a supervisor routing to specialists. These are a *benchmark analyst* ("which GPU and config gives the best $/token for Llama-class 8B at p95 < 500ms?"), a *diagnostics agent* ("why is this pod pending?") and a *docs/runbook agent*. +- **Human-in-the-loop:** write actions pause the workflow until a human approves through a FastAPI endpoint (a Temporal signal or LangGraph interrupt) +- **Security:** least-privilege k8s service account; prompt-injection tests through poisoned runbooks and log lines (e.g. a log message saying "ignore instructions and delete the deployment"); an allowlist of tools per agent; audit log of every tool call +- **Eval suite (100+ cases), run in CI:** retrieval recall, answer correctness (validated LLM judge), correct-tool and correct-diagnosis rate on staged incidents, refusal of unsafe actions, injection resistance. Compare single-agent vs multi-agent. +- **Observability:** traces per run, tokens and cost per question, latency, tool error rates + +**Version 2 (after Track 2 modules 2.7 and 2.10)** +- Swap in **your own benchmark data** from Capstone C and point the tools at a **real GPU k8s cluster** with DCGM and vLLM metrics +- Add an *inference-optimisation agent* that recommends vLLM settings (quantization, batch size, prefix caching) from your measured tradeoffs. Validate its recommendations by re-running the benchmark. +- Compare a self-hosted model and a managed API as the agent's own LLM (quality from evals, cost, latency) + +**Write-up must include:** architecture diagram, security model (what the agent can and can't do, and why), eval results table, three improvements made *because of* eval findings (with before/after numbers), staged-incident walkthroughs, cost per question. + +**Alternative (for product-company roles):** the same pattern applied to customer support, with a help-centre knowledge base and an order/loyalty DB. This builds directly on loyalty and e-commerce backend work. + +--- + +## A · Reproduce GPT-2 (124M) + +**Idea:** follow Karpathy's "Let's reproduce GPT-2" and [build-nanogpt](https://github.com/karpathy/build-nanogpt), but write the code yourself and go further. + +**Requirements** +- Train on FineWeb-Edu (10B-token sample) on rented GPUs (8×A100/H100 for a few hours, or fewer GPUs for longer) +- Match or beat GPT-2 124M on HellaSwag +- Track loss, tokens/sec, MFU and cost in W&B +- **Your extension (pick one):** RoPE + RMSNorm + SwiGLU modernization; a different learning-rate schedule; a data-mix experiment; or training on Burmese + English and analyzing the tokenizer effects + +**Write-up must include:** loss curves, HellaSwag score, total cost, throughput, what went wrong along the way, and the results of your extension. + +--- + +## B · Domain fine-tune that beats a prompted model + +**Idea:** show you know when and how fine-tuning pays off. + +**Requirements** +- Pick a narrow task with clear evaluation (e.g. support-ticket triage plus a structured response, loyalty-transaction anomaly explanations, or Burmese ↔ English customer messages) +- Build a dataset of 1–5k examples (real public data + synthetic, with a documented curation process) +- QLoRA-fine-tune a small open model (1–8B), optionally followed by DPO +- Compare against: the base model, the base model + few-shot prompt, and a frontier model + prompt, on a held-out eval set with confidence intervals +- Compare cost and latency per 1k requests for each option + +**Write-up must include:** data pipeline, training config, eval table with CIs, cost comparison, and an honest conclusion (including if fine-tuning *didn't* win). + +--- + +## C · LLM inference benchmark on AWS + +**Idea:** the clearest way to show your systems background. Treat it like the API performance work you've done before, applied to GPUs. + +**Requirements** +- Serve an open model (e.g. 8B) with vLLM (and optionally SGLang) on AWS GPU instances, ideally on EKS (module 2.10) +- Store every run's results in Postgres with a consistent schema, since your ops agent will query them +- Write a load generator (async Python) that simulates realistic traffic with varied prompt and output lengths +- Measure **TTFT, inter-token latency, p50/p95/p99, throughput and $ per 1M output tokens** across: + - precision: bf16 vs FP8 vs AWQ INT4 + - max batch size / concurrency + - prefix caching on/off (with a shared-system-prompt workload) + - speculative decoding on/off + - one GPU type vs another +- Compare with the price of a hosted API for the same model + +**Write-up must include:** a latency–throughput tradeoff chart, a cost table, and a recommendation along the lines of "for a workload like X, use config Y". This is the kind of document an infrastructure team would want to read. + +--- + +## D · Make training go brrr + +**Idea:** take your own GPT training loop and make it as fast as you can, explaining each gain. + +**Requirements** +- Baseline: fp32, eager mode, naive attention +- Apply step by step, measuring tokens/sec and MFU after each: bf16 autocast → FlashAttention (`scaled_dot_product_attention`) → `torch.compile` → fused AdamW → better batch size and gradient accumulation → one custom Triton kernel (e.g. fused RMSNorm or fused cross-entropy) +- Profile with the PyTorch profiler and include traces + +**Write-up must include:** a waterfall chart of the speedup from each step, roofline reasoning for why each step helped, and your Triton kernel benchmark. + +--- + +## E · Paper reproduction + +**Idea:** reproduce the central claim of one paper at small scale. + +**Good candidates** (pick one that interests you): +- DPO vs PPO-based RLHF on a small model +- Chinchilla-style scaling-law fit on your GPT +- μP learning-rate transfer +- Toy Models of Superposition +- Grokking on modular arithmetic plus the mechanistic analysis +- Speculative decoding speedup vs draft-model size +- A recent arXiv paper with no public code (most valuable, since it adds something new) + +**Requirements:** state the claim, design the smallest test, run multiple seeds, report error bars, and say clearly what did and didn't reproduce. + +--- + +## F · Small original study + +**Idea:** ask a question nobody has quite answered, and answer it carefully. + +**How to find a question** +- Something that surprised you in an earlier project ("why did my Burmese tokenizer make X worse?") +- A "what happens if…" from a paper's limitations section +- An eval gap: something models do badly that nobody measures well +- An interpretability question about a behavior you saw + +**Requirements:** a clear hypothesis, baselines, ablations, multiple seeds, a 4–8 page write-up in paper format (intro, related work, method, results, limitations). Share it publicly (blog, arXiv, workshop or Alignment Forum) and ask for feedback. + +--- + +## Write-up template + +Copy into each project's `README.md`: + +```markdown +# + +**TL;DR:** one sentence: what I did and the headline number. + +## Goal +What question does this project answer? + +## Setup +Data, model, hardware, cost. Link to code and configs. + +## Approach +What I built, with a diagram if helpful. + +## Results +| Variant | Metric 1 | Metric 2 | Cost | +|---|---|---|---| + +Plots here. + +## What went wrong / what I learned +The honest part. Usually the most interesting section. + +## Limitations & next steps + +## Reproduce +Exact commands. +``` diff --git a/course/track-1-ai-application-engineer/README.md b/course/track-1-ai-application-engineer/README.md new file mode 100644 index 0000000..9ab71ca --- /dev/null +++ b/course/track-1-ai-application-engineer/README.md @@ -0,0 +1,223 @@ +# Track 1 · AI Application Engineer + +**Goal:** build reliable, measurable products on top of LLMs: APIs, prompting, retrieval, agents, tools/MCP, evals and production concerns. + +**Duration:** ~3.5–4 months at 12–15 hrs/week. You have a head start from your MCP and support-automation work. + +**Math alongside:** [Level 1](../math/README.md#level-1-intuition-with-track-1) + +**Why this comes first:** you get a working mental model of what LLMs can and can't do, and a hireable skill set quickly. The evals habit from module 1.6 is what separates engineers with real depth in this area from those without it. + +| # | Module | Weeks | +|---|---|---| +| 1.1 | How LLMs work (a user's mental model) | 1 | +| 1.2 | Working with model APIs | 1 | +| 1.3 | Prompt & context engineering | 1 | +| 1.4 | Embeddings, search & RAG | 2 | +| 1.5 | Tool use, agents & MCP | 2 | +| 1.6 | Evals ★ | 2 | +| 1.7 | Production: observability, security, cost | 1 | +| 1.8 | Agent frameworks & workflow orchestration | 2 | +| ⚑ | Capstone: AI Factory Ops Agent | 3–4 | + +--- + +## 1.1 How LLMs work (a user's mental model) + +**Why:** every later decision (prompt structure, context size, temperature, when to fine-tune) depends on this picture. + +**Concepts:** tokens and tokenization; next-token prediction; logits → softmax → sampling (temperature, top-p); context windows; pretraining vs instruction tuning vs RLHF; why models hallucinate; reasoning/"thinking" models; what an embedding is. + +**Learn** +- *Core:* Andrej Karpathy, [Intro to Large Language Models](https://www.youtube.com/watch?v=zjkBMFhNj_g) (1 hr) +- *Core:* Andrej Karpathy, [Deep Dive into LLMs like ChatGPT](https://www.youtube.com/watch?v=7xTGNNLPyMI) (3.5 hrs, full pipeline from data to RL) +- *Core:* 3Blue1Brown, [Transformers / attention chapters](https://www.3blue1brown.com/topics/neural-networks) (chapters 5–7) +- *Core:* Jay Alammar, [The Illustrated Transformer](https://jalammar.github.io/illustrated-transformer/) +- *Optional:* [OpenAI Tokenizer playground](https://platform.openai.com/tokenizer), or the tokenizer section of Karpathy's tokenizer video (Track 2) + +**Build** +- [ ] Tokenize the same paragraph in English and Burmese with a tokenizer library. Compare token counts and explain what that means for cost and context length. +- [ ] Call a model with the same prompt at temperature 0, 0.7 and 1.2, 10 times each. Record how much the outputs vary. + +**Checkpoint:** explain, without notes, what happens from "user sends prompt" to "token appears on screen", and why a model can state something false with confidence. + +--- + +## 1.2 Working with model APIs + +**Why:** this is your bread and butter, and it's mostly backend engineering you already know: HTTP, streaming, retries, rate limits, cost. + +**Concepts:** messages and roles; system prompts; streaming (SSE); structured outputs/JSON; tool use (function calling); vision/PDF inputs; prompt caching; batch APIs; token counting; rate limits and retries with backoff; model selection by cost, latency and quality. + +**Learn** +- *Core:* [Claude API documentation](https://platform.claude.com/docs): getting started, messages, streaming, tool use, prompt caching +- *Core:* [Anthropic courses](https://github.com/anthropics/courses) on GitHub: API fundamentals and tool use +- *Optional:* the OpenAI API docs, to see the shared patterns across providers + +**Build** +- [ ] A Python CLI chat with streaming, conversation history and a running token and cost counter +- [ ] Extract structured data (name, amount, date, merchant) from 20 messy receipt texts into validated Pydantic models. Measure the accuracy. +- [ ] Add prompt caching to a long-system-prompt call and measure latency and cost before and after +- [ ] Wrap API calls with retry/backoff and a timeout, and compare two models on latency and price for the same task + +**Checkpoint:** you can pick a model for a task and justify it with numbers (quality, p50/p95 latency, cost per 1k requests). + +--- + +## 1.3 Prompt & context engineering + +**Why:** what's in the context window decides the output. Most quality gains come from better context, not cleverer wording. + +**Concepts:** clear instructions; role and system prompts; few-shot examples; XML/markdown structuring; chain of thought vs extended thinking; prompt chaining; long-context placement (put documents first, instructions after); context engineering (choosing which information goes in at all); prompt versioning. + +**Learn** +- *Core:* Anthropic, [Prompt engineering interactive tutorial](https://github.com/anthropics/prompt-eng-interactive-tutorial) +- *Core:* [Prompt engineering overview](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview) (Claude docs) +- *Core:* Anthropic, [Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) +- *Optional:* [Prompt Engineering Guide](https://www.promptingguide.ai/) (broad survey) + +**Build** +- [ ] Take one real task from your past work (e.g. classifying support tickets) and write three prompt versions. Score each on 30 labeled examples. Keep the prompts in git. +- [ ] Split a complex single prompt into a 2–3 step chain and compare quality and cost + +**Checkpoint:** you have a habit of changing one thing, running it on a test set and comparing numbers. If you're judging prompts by eye, you're not there yet. + +--- + +## 1.4 Embeddings, search & RAG + +**Why:** most business AI apps are "LLM + your company's data". Retrieval quality usually limits answer quality. + +**Concepts:** embeddings and vector similarity; chunking strategies; vector indexes (HNSW, IVF) at a conceptual level; keyword search (BM25) and **hybrid search**; reranking; metadata filtering; query rewriting; contextual retrieval; retrieval metrics (recall@k, MRR, nDCG); when RAG is the wrong tool. + +**Learn** +- *Core:* Anthropic, [Introducing Contextual Retrieval](https://www.anthropic.com/news/contextual-retrieval) +- *Core:* Eugene Yan, [Patterns for Building LLM-based Systems & Products](https://eugeneyan.com/writing/llm-patterns/) +- *Core:* [pgvector](https://github.com/pgvector/pgvector) README. You know Postgres, so start there before reaching for a dedicated vector database. +- *Core:* [Sentence Transformers documentation](https://www.sbert.net/) +- *Optional:* Chip Huyen, [*AI Engineering*](https://www.oreilly.com/library/view/ai-engineering/9781098166298/) (O'Reilly, 2025), the RAG chapter. It's the best single book for this whole track. +- *Optional:* Jo Kristian Bergum's writing on hybrid search and why BM25 is a strong baseline + +**Build** +- [ ] **Implement first:** BM25 from scratch in Python (~50 lines), then cosine top-k search over embeddings in NumPy +- [ ] RAG over a real document set (e.g. a product's public docs or help center) using Postgres + pgvector +- [ ] Create 50 question → relevant-chunk pairs, then measure recall@5 for vector-only, BM25-only and hybrid search, with and without a reranker. Put the results in a table. +- [ ] Try two chunk sizes and contextual retrieval; report what changed and why + +**Checkpoint:** when a RAG answer is wrong, you can tell whether retrieval failed (wrong chunks) or generation failed (right chunks, bad answer), because you measure them separately. + +--- + +## 1.5 Tool use, agents & MCP + +**Why:** agents (LLMs calling tools in a loop) are where a lot of hiring is right now, and your MCP experience is a real advantage. + +**Concepts:** tool definitions and schemas; the agent loop (model → tool call → result → model); workflows vs agents (prompt chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer); MCP servers, clients and transports; sub-agents; memory; human-in-the-loop; failure modes (loops, wrong tool, compounding errors); designing tools for agents to use. + +**Learn** +- *Core:* Anthropic, [Building effective agents](https://www.anthropic.com/engineering/building-effective-agents) +- *Core:* Anthropic, [Writing effective tools for agents](https://www.anthropic.com/engineering/writing-tools-for-agents) +- *Core:* [Model Context Protocol docs and spec](https://modelcontextprotocol.io/) +- *Core:* [Claude Agent SDK docs](https://code.claude.com/docs/en/agent-sdk/overview) +- *Optional:* Anthropic, [How we built our multi-agent research system](https://www.anthropic.com/engineering/multi-agent-research-system) +- *Optional:* Lilian Weng, [LLM Powered Autonomous Agents](https://lilianweng.github.io/posts/2023-06-23-agent/) + +**Build** +- [ ] **Implement first:** an agent loop from scratch with the raw API (no framework): tools, max-steps guard, logging of every step +- [ ] An MCP server in Python exposing 3–4 tools over a real data source (e.g. a Postgres DB of orders and customers, much like your loyalty-platform work) +- [ ] The same task built as a fixed workflow and as an autonomous agent. Compare success rate, cost and latency over 30 runs. + +**Checkpoint:** you can explain when *not* to use an agent, and you have numbers showing where your agent fails. + +--- + +## 1.6 Evals ★ (most important module) + +**Why:** you can't improve what you don't measure. Evals are what tell you whether a change was an improvement, and they're the base of everything in Tracks 2 and 3. + +**Concepts:** error analysis (reading traces and labeling failure categories); code-based assertions; LLM-as-judge and how to validate the judge against human labels; reference-based vs reference-free metrics; golden datasets; regression testing in CI; online vs offline evals; statistical significance with small test sets; benchmark contamination. + +**Learn** +- *Core:* Hamel Husain, [Your AI Product Needs Evals](https://hamel.dev/blog/posts/evals/) +- *Core:* Hamel Husain, [Using LLM-as-a-Judge](https://hamel.dev/blog/posts/llm-judge/) +- *Core:* Hamel Husain & Shreya Shankar, [LLM Evals FAQ](https://hamel.dev/blog/posts/evals-faq/) +- *Core:* Anthropic, [Define success criteria and build evaluations](https://platform.claude.com/docs/en/test-and-evaluate/develop-tests) +- *Core:* [Inspect](https://inspect.aisi.org.uk/), an open-source eval framework from the UK AI Security Institute +- *Optional:* Eugene Yan, [Evaluating the Effectiveness of LLM-Evaluators](https://eugeneyan.com/writing/llm-evaluators/) +- *Optional:* Anthropic, [A statistical approach to model evaluations](https://www.anthropic.com/research/statistical-approach-to-model-evals) + +**Build** +- [ ] Take your RAG app from 1.4 and do error analysis: read 50 traces, write a short note on each failure and group them into categories. Count them. +- [ ] Write code-based checks for the failure categories you can detect automatically +- [ ] Build an LLM judge for one subjective criterion and measure its agreement with your own labels (target over 85%) +- [ ] Run the eval suite in CI (GitHub Actions) and fail the build if the score drops +- [ ] Re-run your 1.3 prompt comparison with confidence intervals. Was the "winner" really better? + +**Checkpoint:** for any AI feature, you can design an eval plan in 30 minutes covering the dataset, metrics, judge validation and pass threshold. + +--- + +## 1.7 Production: observability, security, cost + +**Why:** this is where your 12 years of backend work count most. Many AI engineers can't run a reliable service; you can. + +**Concepts:** tracing LLM calls (inputs, outputs, tokens, latency); prompt and model versioning; caching (exact and semantic); fallbacks and model routing; rate limiting and queueing; cost attribution per feature or user; **prompt injection** and data exfiltration; PII handling; guardrails; streaming UX; feedback collection. + +**Learn** +- *Core:* [OWASP Top 10 for LLM Applications](https://genai.owasp.org/llm-top-10/) +- *Core:* Simon Willison's [prompt injection series](https://simonwillison.net/tags/prompt-injection/), especially "the lethal trifecta" +- *Core:* [OpenTelemetry semantic conventions for GenAI](https://opentelemetry.io/docs/specs/semconv/gen-ai/) +- *Optional:* an open-source LLM observability tool such as [Langfuse](https://langfuse.com/docs) (self-hostable) +- *Optional:* Simon Willison's [blog](https://simonwillison.net/), a reliable way to keep up with the field + +**Build** +- [ ] Add tracing to your agent or RAG app: every call logged with prompt version, tokens, latency and cost +- [ ] Red-team your own app: try 10 prompt injections (including through retrieved documents). Fix what you can and document what you can't. +- [ ] Add a cost dashboard and a per-user rate limit + +**Checkpoint:** you can explain why "LLM + private data + untrusted input + ability to send data out" is dangerous, and how you'd design around it. + +--- + +## 1.8 Agent frameworks & workflow orchestration + +**Why:** you built agents from scratch in 1.5 so you understand what's underneath. Most job ads still list frameworks by name (LangGraph, LlamaIndex, AutoGen) and durable workflow engines (Temporal, Dagster, Prefect, Airflow). Now learn them, and judge them against your from-scratch version. + +**Concepts:** agents as graphs (nodes, edges, shared state, conditional routing); checkpointing and resuming; human-in-the-loop interrupts; multi-agent patterns (supervisor, hierarchical, handoffs, swarm); framework abstractions and what they hide; **durable execution** (workflows that survive crashes and restarts, retries, timeouts, long-running human approvals); activities vs workflows; event-driven triggers; serving agents behind FastAPI with streaming. + +**Learn** +- *Core:* [LangGraph documentation](https://docs.langchain.com/oss/python/langgraph/overview): quickstart, persistence, human-in-the-loop, multi-agent +- *Core:* [Temporal documentation](https://docs.temporal.io/) and the free [Temporal 101 (Python)](https://learn.temporal.io/courses/temporal_101/python/) course. Coming from Kafka, durable execution will make sense quickly. +- *Core:* [FastAPI tutorial](https://fastapi.tiangolo.com/tutorial/), the user guide sections on async, dependencies and background tasks +- *Optional:* [LlamaIndex documentation](https://docs.llamaindex.ai/), strongest for RAG-heavy and document-ingestion pipelines +- *Optional:* [Microsoft AutoGen](https://microsoft.github.io/autogen/), conversation-based multi-agent +- *Optional:* [Pydantic AI](https://ai.pydantic.dev/), a lightweight typed agent framework +- *Optional:* [Dagster](https://docs.dagster.io/), asset-based data orchestration, good for knowledge-ingestion pipelines + +**Build** +- [ ] Rebuild your 1.5 from-scratch agent in LangGraph, with a human-approval interrupt before any write action and checkpointing so a run can resume. Compare lines of code, debuggability and behavior with your raw version. +- [ ] A supervisor + 2 specialist agents in LangGraph (e.g. a "retrieval" agent and an "analysis" agent). Run your 1.6 evals on single-agent vs multi-agent and compare quality, cost and latency. +- [ ] Rewrite the 1.4 ingestion pipeline as a Temporal workflow (fetch → chunk → embed → upsert) and kill the worker mid-run to watch it resume +- [ ] A long-running Temporal workflow that waits hours or days for a human approval signal before the agent acts +- [ ] Serve the agent through FastAPI with SSE streaming and request tracing + +**Checkpoint:** you can explain when a framework helps and when it gets in the way, and when you need a durable workflow engine rather than a simple job queue. Back both answers with something you built. + +--- + +## ⚑ Track 1 Capstone + +See [`projects/README.md`](../projects/README.md#track-1-capstone-ai-factory-ops-agent) for the full spec. + +**AI Factory Ops Agent.** A multi-agent system for GPU-infrastructure operations. It ingests benchmark results, runbooks and docs; answers questions like "why is this inference workload slow?"; recommends configurations; and queries Kubernetes and Prometheus through MCP tools, with human approval before any action. It also includes evals in CI, injection defences and a public write-up with numbers. It covers nearly every requirement of AI Engineer (Agents) roles at infrastructure companies, and you upgrade it in Track 2 with your own benchmark data. + +## Track 1 complete when + +- [ ] All module checkpoints passed +- [ ] Capstone published with a write-up containing at least one results table +- [ ] Resume updated: AI work at the top, outcomes with numbers +- [ ] Math Level 1 complete +- [ ] You can do a 45-minute interview walkthrough: "design a RAG system for X and tell me how you'd know it's working" +- [ ] You can answer: "design a multi-agent system that acts on production infrastructure safely". Cover the architecture, human-in-the-loop, permissions, evals and failure handling. + +**Roles you can target now:** AI Engineer, Senior AI Engineer (Agents & Applications), Applied AI Engineer, AI Product Engineer, Backend Engineer (AI platform). diff --git a/course/track-2-ml-systems-engineer/README.md b/course/track-2-ml-systems-engineer/README.md new file mode 100644 index 0000000..6190d1a --- /dev/null +++ b/course/track-2-ml-systems-engineer/README.md @@ -0,0 +1,281 @@ +# Track 2 · ML / AI Systems Engineer + +**Goal:** understand neural networks from first principles, then train, fine-tune, optimize and serve them efficiently. This is where your backend, infrastructure and performance experience pays off most. + +**Duration:** ~7–9 months at 12–15 hrs/week. + +**Math alongside:** [Level 2](../math/README.md#level-2-working-math-for-deep-learning-with-track-2) + +**Why this comes second:** Track 1 showed you what models do. Track 2 shows you how they work and how to make them faster and cheaper. Systems skills (inference, GPU efficiency, distributed training) are scarce, well paid and hard to automate. + +| # | Module | Weeks | Part | +|---|---|---|---| +| 2.1 | PyTorch fluency | 2 | A · Foundations | +| 2.2 | Neural networks from scratch | 4 | A · Foundations | +| 2.3 | Deep learning fundamentals | 4 | A · Foundations | +| 2.4 | Transformers & LLMs from scratch ★ | 4 | A · Foundations | +| 2.5 | Fine-tuning & post-training | 3 | B · Working with real models | +| 2.6 | GPUs & performance ★ | 4 | C · Systems | +| 2.7 | Inference & serving ★ | 3 | C · Systems | +| 2.8 | Distributed training | 3 | C · Systems | +| 2.9 | ML platform & MLOps | 2 | C · Systems | +| 2.10 | Kubernetes & GPU infrastructure | 3 | C · Systems | +| ⚑ | Capstones (pick at least 2 of 4) | ongoing | | + +--- + +## Part A: Foundations + +### 2.1 PyTorch fluency + +**Why:** PyTorch is the language of the field. You need to be fluent with tensors, as you are with ActiveRecord. + +**Concepts:** tensors, dtypes, devices; broadcasting; indexing and reshaping (`view`, `reshape`, `permute`, `transpose`, contiguity); autograd; `nn.Module`; `Dataset`/`DataLoader`; the training loop (forward, loss, backward, step, zero_grad); saving and loading; `einsum`. + +**Learn** +- *Core:* [PyTorch tutorials: Learn the Basics](https://pytorch.org/tutorials/beginner/basics/intro.html), then [Introduction to PyTorch – YouTube series](https://pytorch.org/tutorials/beginner/introyt/introyt_index.html) +- *Core:* Sasha Rush, [Tensor Puzzles](https://github.com/srush/Tensor-Puzzles). Solving these makes you fluent with broadcasting. +- *Optional:* [Zero to Mastery: Learn PyTorch](https://www.learnpytorch.io/) + +**Build** +- [ ] Complete Tensor Puzzles +- [ ] Train an MLP on MNIST with a hand-written training loop (no Lightning or Trainer). Log loss and accuracy to W&B. + +**Checkpoint:** you can predict the output shape of any line of tensor code before running it. + +--- + +### 2.2 Neural networks from scratch + +**Why:** this is the most important foundation in the whole curriculum. Once you've built backprop yourself, the rest of deep learning stops being mysterious. + +**Learn** +- *Core:* Andrej Karpathy, [Neural Networks: Zero to Hero](https://karpathy.ai/zero-to-hero.html). Do these lectures in this module: + 1. The spelled-out intro to neural networks and backpropagation: building **micrograd** + 2. **makemore** Part 1: bigram language model + 3. makemore Part 2: MLP + 4. makemore Part 3: activations, gradients, BatchNorm + 5. makemore Part 4: becoming a backprop ninja (manual backprop through everything) + 6. makemore Part 5: building a WaveNet +- *Core:* Michael Nielsen, [Neural Networks and Deep Learning](http://neuralnetworksanddeeplearning.com/), chapters 1–3 (free online book) + +**How to do Karpathy's lectures properly:** watch a section, pause, **type the code yourself** (never copy-paste), then close the video and rebuild it from memory the next day. Expect 3–4× the video length. + +**Build** +- [ ] micrograd rebuilt from memory, with unit tests comparing gradients to PyTorch +- [ ] makemore through Part 5, with your own notes on every "aha" moment +- [ ] Backprop ninja exercise (Part 4) fully completed. It's hard, and it's worth it. + +**Checkpoint:** you can implement a 2-layer MLP with manual backprop in NumPy (no autograd), train it, and get the same loss curve as the PyTorch version. + +--- + +### 2.3 Deep learning fundamentals + +**Why:** you need to know *why* training works or fails so you can debug real runs. + +**Concepts:** loss landscapes; weight initialization (Xavier/He); activation functions; normalization (BatchNorm, LayerNorm, RMSNorm); residual connections; regularization (dropout, weight decay, data augmentation); overfitting vs underfitting; learning-rate schedules; CNNs at a conceptual level; embeddings; vanishing and exploding gradients; mixed precision at a conceptual level. + +**Learn** +- *Core:* Simon Prince, [*Understanding Deep Learning*](https://udlbook.github.io/udlbook/) (free PDF + notebooks), chapters 1–11. The clearest modern deep learning textbook, with excellent figures. +- *Core:* Andrej Karpathy, [A Recipe for Training Neural Networks](https://karpathy.github.io/2019/04/25/recipe/). Re-read it every few months. +- *Core:* [Stanford CS231n](https://cs231n.stanford.edu/) course notes on optimization, backprop, neural networks parts 1–3 and CNNs. Do assignment 1 or 2. +- *Optional:* fast.ai, [Practical Deep Learning for Coders](https://course.fast.ai/), a top-down complement if you want more applied practice +- *Optional:* [Dive into Deep Learning (d2l.ai)](https://d2l.ai/), an interactive textbook with code +- *Optional:* Google, [Deep Learning Tuning Playbook](https://github.com/google-research/tuning_playbook) + +**Build** +- [ ] Do the UDL notebooks for chapters 6–9 +- [ ] Ablation study on CIFAR-10 with a small CNN: no normalization vs BatchNorm, no residuals vs residuals, three learning rates. Plot everything in W&B and write up the results. +- [ ] Deliberately break training (bad init, LR too high, a missing `zero_grad`) and record what each failure looks like in the loss curve + +**Checkpoint:** shown a bad loss curve, you can give the three most likely causes. + +--- + +### 2.4 Transformers & LLMs from scratch ★ + +**Why:** the transformer is the core architecture of modern AI. Building one end to end takes you from someone who uses LLMs to someone who understands them. + +**Concepts:** tokenization (BPE); token and positional embeddings (learned, RoPE); self-attention (Q, K, V); causal masking; multi-head attention; MLP blocks; pre-norm residual stream; the language-modeling loss; sampling; KV cache; scaling (params, data, compute); modern variants (RMSNorm, SwiGLU, GQA, MoE). + +**Learn** +- *Core:* Karpathy Zero to Hero, the rest of the series: + 1. **Let's build GPT: from scratch, in code, spelled out** + 2. **Let's build the GPT Tokenizer** + 3. **Let's reproduce GPT-2 (124M)**, plus the [build-nanogpt repo](https://github.com/karpathy/build-nanogpt) +- *Core:* Sebastian Raschka, [*Build a Large Language Model (From Scratch)*](https://github.com/rasbt/LLMs-from-scratch) (book + free code repo) +- *Core:* Vaswani et al., [Attention Is All You Need](https://arxiv.org/abs/1706.03762). Read it *after* building GPT, when it will make sense. +- *Core:* Harvard NLP, [The Annotated Transformer](https://nlp.seas.harvard.edu/annotated-transformer/) +- *Optional:* [Hugging Face LLM Course](https://huggingface.co/learn/llm-course), chapters 1–4 for the HF ecosystem +- *Optional:* [Stanford CS224n](https://web.stanford.edu/class/cs224n/) lectures on transformers and pretraining +- *Optional:* Sebastian Raschka's [blog](https://magazine.sebastianraschka.com/), with architecture comparisons of new open models + +**Build** +- [ ] Your own GPT (character-level, then BPE) trained on a dataset you like, e.g. Burmese text +- [ ] BPE tokenizer from scratch; compare its compression on English vs Burmese with GPT-4's tokenizer +- [ ] Add a KV cache to your GPT's generation and measure the speedup at sequence lengths 128, 512, 1024 +- [ ] Swap in RoPE, RMSNorm and SwiGLU one at a time and compare validation loss +- [ ] **Capstone A** (see projects): reproduce GPT-2 124M + +**Checkpoint:** on a blank page, write a transformer block in PyTorch from memory and explain every tensor shape. + +--- + +## Part B: Working with real models + +### 2.5 Fine-tuning & post-training + +**Why:** most companies won't pretrain, but many will fine-tune. Knowing *when* to fine-tune (rather than prompt or use RAG) and how to do it is a core skill. + +**Concepts:** pretraining → SFT → preference tuning (RLHF, DPO) → RL with verifiable rewards; full fine-tuning vs **LoRA/QLoRA** (and why low-rank works); chat templates; dataset curation and formatting; catastrophic forgetting; overfitting on small data; evaluating fine-tuned models; distillation; synthetic data. + +**Learn** +- *Core:* [Hugging Face LLM Course](https://huggingface.co/learn/llm-course), chapters on fine-tuning +- *Core:* [TRL documentation](https://huggingface.co/docs/trl) (SFTTrainer, DPOTrainer) and [PEFT documentation](https://huggingface.co/docs/peft) +- *Core:* Papers: [LoRA](https://arxiv.org/abs/2106.09685), [QLoRA](https://arxiv.org/abs/2305.14314), [DPO](https://arxiv.org/abs/2305.18290) +- *Core:* Nathan Lambert, [*RLHF Book*](https://rlhfbook.com/) (free online), chapters on the overall pipeline, SFT and DPO +- *Optional:* [Unsloth](https://docs.unsloth.ai/), fast single-GPU fine-tuning +- *Optional:* [InstructGPT paper](https://arxiv.org/abs/2203.02155), the original RLHF pipeline + +**Build** +- [ ] **Implement first:** a LoRA layer from scratch (wrap `nn.Linear` with A·B low-rank matrices) and fine-tune your own GPT with it +- [ ] Use QLoRA to fine-tune a small open model (1–8B) on a narrow task from your domain (e.g. support-ticket classification and response). Compare with the base model and with a prompted frontier model on your eval set. +- [ ] Run a small DPO pass on preference pairs and measure the change +- [ ] **Capstone B** (see projects) + +**Checkpoint:** you can argue in a design review whether a problem needs prompting, RAG, fine-tuning or a combination, and back it up with your own experiment results. + +--- + +## Part C: Systems (your differentiator) + +### 2.6 GPUs & performance ★ + +**Why:** this matches your API and database optimization background. Same mindset (profile, find the bottleneck, fix it), different hardware. + +**Concepts:** GPU architecture (SMs, warps, threads, memory hierarchy: HBM, L2, shared memory, registers); **compute-bound vs memory-bound vs overhead-bound**; the roofline model; arithmetic intensity; FLOPs and MFU (model FLOPs utilization); mixed precision (fp16, bf16, fp8); kernel fusion; `torch.compile`; the PyTorch profiler; FlashAttention (why tiling beats materializing the attention matrix); writing kernels in Triton; CUDA basics. + +**Learn** +- *Core:* Horace He, [Making Deep Learning Go Brrrr From First Principles](https://horace.io/brrr_intro.html). Read it first. +- *Core:* [GPU MODE lectures](https://github.com/gpu-mode/lectures) (YouTube + code), the community for this skill +- *Core:* [Triton tutorials](https://triton-lang.org/main/getting-started/tutorials/index.html): vector add, fused softmax, matmul +- *Core:* [PyTorch Profiler recipe](https://pytorch.org/tutorials/recipes/recipes/profiler_recipe.html) and [`torch.compile` intro](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) +- *Core:* FlashAttention [paper](https://arxiv.org/abs/2205.14135); read for the IO-aware idea +- *Optional:* Hwu, Kirk & El Hajj, *Programming Massively Parallel Processors* (4th ed.), the CUDA textbook. GPU MODE runs a reading group on it. +- *Optional:* Sasha Rush, [GPU Puzzles](https://github.com/srush/GPU-Puzzles) and [Triton Puzzles](https://github.com/srush/Triton-Puzzles) +- *Optional:* [MIT 6.5940 TinyML and Efficient Deep Learning](https://efficientml.ai/) (Song Han), on pruning, quantization and efficient architectures + +**Build** +- [ ] Profile your GPT training loop: find the top 5 time consumers and make three improvements (bf16, `torch.compile`, fused AdamW, better batch size). Report tokens/sec and MFU before and after. +- [ ] Complete GPU Puzzles +- [ ] Write a fused softmax and a matmul in Triton and benchmark them against PyTorch +- [ ] Compute the arithmetic intensity of a matmul vs a layernorm and place both on a roofline plot for your GPU +- [ ] **Capstone D** (see projects) + +**Checkpoint:** given a slow training or inference job, you can say whether it's compute-, memory- or overhead-bound, and what you'd try first. + +--- + +### 2.7 Inference & serving ★ + +**Why:** inference is where most of the money goes in production AI. Making it cheaper and faster is directly valuable to any company running models, and it's close to the systems work you already do. + +**Concepts:** prefill vs decode phases; KV cache memory math; batching (static, dynamic, **continuous**); **PagedAttention**; prefix caching; time to first token (TTFT), inter-token latency, throughput; **quantization** (INT8, INT4, FP8; weight-only vs activations; GPTQ, AWQ); **speculative decoding**; tensor parallelism for inference; serving engines; autoscaling GPU workloads; cost per million tokens. + +**Learn** +- *Core:* [vLLM documentation](https://docs.vllm.ai/) and the [PagedAttention paper](https://arxiv.org/abs/2309.06180) +- *Core:* [SGLang documentation](https://docs.sglang.ai/) (RadixAttention, structured generation) +- *Core:* Papers: [GPTQ](https://arxiv.org/abs/2210.17323), [AWQ](https://arxiv.org/abs/2306.00978), [Speculative Decoding](https://arxiv.org/abs/2211.17192) +- *Core:* [Hugging Face: Quantization overview](https://huggingface.co/docs/transformers/main/en/quantization/overview) +- *Optional:* Lilian Weng, [Large Transformer Model Inference Optimization](https://lilianweng.github.io/posts/2023-01-10-inference-optimization/) +- *Optional:* [llama.cpp](https://github.com/ggml-org/llama.cpp), CPU/Mac inference and the GGUF quantization formats + +**Build** +- [ ] **Implement first:** continuous batching for your own GPT (a simple scheduler that adds and removes sequences each step) and compare throughput with static batching +- [ ] Write the KV cache memory formula and verify it against real GPU memory use +- [ ] INT8 weight quantization of your GPT from scratch; measure size, speed and loss change +- [ ] **Capstone C** (see projects): inference benchmark on AWS + +**Checkpoint:** you can size a deployment: given a model, traffic and latency SLO, estimate the GPUs needed and the monthly cost, then check the estimate against a benchmark. + +--- + +### 2.8 Distributed training + +**Why:** large models don't fit on one GPU. Even if you never train a frontier model, you'll fine-tune across several GPUs and need to read papers that assume this knowledge. + +**Concepts:** data parallelism (DDP); all-reduce and other collectives (NCCL); gradient accumulation; activation checkpointing; **ZeRO stages / FSDP**; tensor parallelism; pipeline parallelism; sequence/context parallelism; expert parallelism (MoE); memory math (params + gradients + optimizer states + activations); interconnects (NVLink, InfiniBand); fault tolerance and checkpointing. + +**Learn** +- *Core:* Hugging Face, [The Ultra-Scale Playbook: Training LLMs on GPU Clusters](https://huggingface.co/spaces/nanotron/ultrascale-playbook) +- *Core:* Google DeepMind, [How to Scale Your Model](https://jax-ml.github.io/scaling-book/). It's TPU/JAX-flavored, but the math applies everywhere. +- *Core:* [PyTorch DDP tutorial](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html) and [FSDP tutorial](https://pytorch.org/tutorials/intermediate/FSDP_tutorial.html) +- *Core:* Stas Bekman, [Machine Learning Engineering](https://github.com/stas00/ml-engineering) (open book): debugging, hardware, network, training at scale +- *Optional:* [ZeRO paper](https://arxiv.org/abs/1910.02054), [Megatron-LM paper](https://arxiv.org/abs/1909.08053) + +**Build** +- [ ] Memory calculator script: given params, precision, optimizer and parallelism strategy, output GB per GPU. Check it against a real run. +- [ ] Train your GPT with DDP on 2+ GPUs (rented for a few hours), then FSDP. Measure scaling efficiency. +- [ ] Implement data-parallel all-reduce manually with `torch.distributed` primitives + +**Checkpoint:** you can explain what ZeRO stages 1, 2 and 3 shard, and pick a parallelism strategy for a given model size and GPU count. + +--- + +### 2.9 ML platform & MLOps + +**Why:** this module puts your backend and DevOps background together with ML. Many "ML Platform Engineer" jobs are mostly this. + +**Concepts:** experiment tracking; dataset versioning; reproducibility (seeds, configs, environments); training pipelines and orchestration; model registries; eval harnesses as a service; CI/CD for models; GPU cluster scheduling (Kubernetes, Slurm); monitoring (data drift, quality regressions); feature stores at a conceptual level; data quality pipelines. + +**Learn** +- *Core:* Chip Huyen, *Designing Machine Learning Systems* (O'Reilly, 2022) +- *Core:* Goku Mohandas, [Made With ML](https://madewithml.com/) (MLOps course) +- *Core:* EleutherAI, [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness), the standard benchmark runner +- *Optional:* [Full Stack Deep Learning](https://fullstackdeeplearning.com/) course materials +- *Optional:* [Ray](https://docs.ray.io/) docs (Ray Train, Ray Serve), common in ML platforms + +**Build** +- [ ] Turn your fine-tuning project into a reproducible pipeline: config file → data prep → train → eval → register model, all one command, with W&B tracking +- [ ] Run lm-evaluation-harness on your fine-tuned model vs the base model on 3 benchmarks + +**Checkpoint:** anyone could clone your repo and reproduce your best model and its eval numbers. + +--- + +### 2.10 Kubernetes & GPU infrastructure + +**Why:** most production model serving, and most "AI factory" platforms, run on Kubernetes with GPU scheduling. Agents that diagnose or operate infrastructure (as in the Track 1 capstone) need someone who understands what they're touching. Your AWS, auto-scaling and DevOps background carries over directly. + +**Concepts:** pods, deployments, services, ingress, ConfigMaps/Secrets; resource requests and limits; **GPU scheduling** (NVIDIA device plugin, GPU Operator, node selectors and taints, MIG and time-slicing); model serving on k8s (vLLM deployments, KServe, LLM-aware routing); autoscaling (HPA, KEDA on queue depth or tokens/sec, cold-start costs of large model weights); batch and training job scheduling (Kueue, Slurm, gang scheduling); observability (Prometheus, Grafana, **DCGM exporter** for GPU metrics such as utilization, memory, temperature and XID errors); RBAC and least-privilege service accounts (critical when agents call the k8s API); common failure modes (OOMKilled, pending pods with no GPU, image pull of 20GB+ weights, NCCL timeouts). + +**Learn** +- *Core:* [Kubernetes basics tutorial](https://kubernetes.io/docs/tutorials/kubernetes-basics/), then [kind](https://kind.sigs.k8s.io/) for a local cluster +- *Core:* [NVIDIA GPU Operator docs](https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/latest/index.html) and [DCGM exporter](https://github.com/NVIDIA/dcgm-exporter) +- *Core:* [vLLM on Kubernetes](https://docs.vllm.ai/en/latest/deployment/k8s.html) and the [vLLM production stack](https://docs.vllm.ai/projects/production-stack/en/latest/) +- *Core:* [Prometheus overview](https://prometheus.io/docs/introduction/overview/) and [Grafana getting started](https://grafana.com/docs/grafana/latest/getting-started/) +- *Core:* [Kubernetes RBAC good practices](https://kubernetes.io/docs/concepts/security/rbac-good-practices/) +- *Optional:* [KServe](https://kserve.github.io/website/), [KEDA](https://keda.sh/), [Kueue](https://kueue.sigs.k8s.io/), [llm-d](https://llm-d.ai/) (distributed LLM inference on k8s) +- *Optional:* [Slurm overview](https://slurm.schedmd.com/overview.html), still the default scheduler on many GPU training clusters +- *Optional:* Kelsey Hightower, [Kubernetes The Hard Way](https://github.com/kelseyhightower/kubernetes-the-hard-way), to understand the control plane + +**Build** +- [ ] Local kind cluster: deploy your FastAPI agent service from 1.8 with Prometheus + Grafana, and break it on purpose (OOM, bad config, crash loop). Write a runbook for each failure; these runbooks feed your ops agent. +- [ ] Rent a small GPU k8s cluster (EKS with one or two GPU nodes, or a managed GPU cloud) and install the GPU Operator and DCGM exporter. Deploy vLLM and build a Grafana dashboard of GPU utilization, KV-cache usage, TTFT and throughput. +- [ ] Autoscale vLLM replicas with KEDA on a custom metric (queue length or running requests) and measure scale-up time, including model-weight loading +- [ ] Create a read-only, namespace-scoped service account for your ops agent and prove it can't delete or modify anything +- [ ] Upgrade the Track 1 capstone: point its MCP tools at this real cluster and your own Capstone C benchmark data + +**Checkpoint:** given "the inference service p95 latency doubled since yesterday", you can work through k8s events, pod status, DCGM GPU metrics and vLLM metrics to the cause. You can also explain which of those steps an agent could safely do for you. + +--- + +## Track 2 complete when + +- [ ] All module checkpoints passed +- [ ] At least 2 of 4 Track 2 capstones published with write-ups +- [ ] Math Level 2 complete +- [ ] You can do these interview whiteboards: "implement attention", "estimate the memory to fine-tune a 7B model", "why is decode memory-bound?", "design an inference platform for X req/s on Kubernetes, including GPU scheduling and autoscaling" + +**Roles you can target now:** ML Platform Engineer, ML Infrastructure Engineer, Inference / Model Serving Engineer, ML Engineer (LLMs), AI Infrastructure Engineer. diff --git a/course/track-3-research-engineer/README.md b/course/track-3-research-engineer/README.md new file mode 100644 index 0000000..6533e4d --- /dev/null +++ b/course/track-3-research-engineer/README.md @@ -0,0 +1,199 @@ +# Track 3 · Research Engineer + +**Goal:** understand *why* models work, run rigorous experiments, read and reproduce papers, and add new findings. A research engineer is the strong engineer on a research team. They turn ideas into experiments that run at scale and produce trustworthy results. + +**Duration:** ~8–12 months to be credible, then ongoing for the rest of your career. + +**Math alongside:** [Level 3](../math/README.md#level-3-research-math-with-track-3) + +**Why this comes last:** research needs everything before it. Track 1 gives you evals and product sense, Track 2 gives you training and systems skill. Track 3 adds theory, rigor and taste. + +**A realistic note:** research engineer roles at frontier labs are very competitive. Your systems background is valued there, because many research teams are short on people who can make experiments run fast and reliably. Common routes in are fellowships (MATS, Anthropic Fellows), open-source contributions (EleutherAI, Hugging Face), and publishing strong reproductions and small studies. + +| # | Module | Weeks | +|---|---|---| +| 3.1 | Classical ML & learning theory | 4 | +| 3.2 | Training dynamics & scaling | 4 | +| 3.3 | Reading & reproducing papers ★ | ongoing, 3 to start | +| 3.4 | Reinforcement learning | 5 | +| 3.5 | Post-training & alignment | 4 | +| 3.6 | Interpretability | 5 | +| 3.7 | Doing research ★ | ongoing | +| ⚑ | Capstones | ongoing | + +--- + +### 3.1 Classical ML & learning theory + +**Why:** papers assume this vocabulary: bias–variance, generalization, regularization as a prior, kernels, probabilistic models. + +**Concepts:** supervised learning framing; bias–variance tradeoff; generalization and overfitting; cross-validation; linear/logistic regression as probabilistic models; regularization as a prior (MAP); SVMs and kernels (conceptually); decision trees and ensembles; PCA; k-means and EM; Gaussian mixtures; VAEs (as a bridge to deep generative models). + +**Learn** +- *Core:* [Stanford CS229](https://cs229.stanford.edu/) lecture notes (Andrew Ng's main notes); lectures on YouTube +- *Core:* Christopher Bishop & Hugh Bishop, [*Deep Learning: Foundations and Concepts*](https://www.bishopbook.com/) (2024), a rigorous modern textbook (free to read online) +- *Optional:* Kevin Murphy, [*Probabilistic Machine Learning: An Introduction*](https://probml.github.io/pml-book/book1.html) +- *Optional:* Goodfellow, Bengio & Courville, [*Deep Learning*](https://www.deeplearningbook.org/), dated but still the classic for part II theory + +**Build** +- [ ] Implement PCA (via SVD) and k-means from scratch; apply them to your GPT's token embeddings and visualize them +- [ ] Implement EM for a Gaussian mixture model +- [ ] Reproduce the classic double-descent curve on a small problem + +**Checkpoint:** you can explain why deep networks generalize despite having more parameters than data points, and why that's still partly an open question. + +--- + +### 3.2 Training dynamics & scaling + +**Why:** most research results are about how training behaves: what scales, what is stable, what transfers from small to large models. + +**Concepts:** scaling laws (Kaplan; Chinchilla compute-optimal); emergent abilities and the debate about them; hyperparameter transfer (μP); loss spikes and training instabilities; grokking; optimizer research (AdamW, Lion, Shampoo, Muon); data quality and data mixing; learning-rate schedules (cosine, WSD); in-context learning. + +**Learn** +- *Core:* Papers: [Kaplan scaling laws](https://arxiv.org/abs/2001.08361), [Chinchilla](https://arxiv.org/abs/2203.15556), [μP / Tensor Programs V](https://arxiv.org/abs/2203.03466) +- *Core:* [Stanford CS336: Language Modeling from Scratch](https://cs336.stanford.edu/). **Do all the assignments.** It's the best course for this track: tokenizers, transformers, systems, scaling laws, data, alignment. +- *Core:* Simon Prince, *Understanding Deep Learning*, chapters 20 ("Why does deep learning work?") and the remaining chapters you skipped +- *Optional:* [Grokking paper](https://arxiv.org/abs/2201.02177) and Neel Nanda's [mechanistic analysis of grokking](https://arxiv.org/abs/2301.05217) +- *Optional:* Keller Jordan's [modded-nanogpt speedrun](https://github.com/KellerJordan/modded-nanogpt), a public record of training improvements; read the changelog + +**Build** +- [ ] Train 5–7 sizes of your GPT at fixed compute budgets and fit your own scaling law. Plot it on log–log axes. +- [ ] Implement μP for your GPT and show the optimal learning rate transfers across widths +- [ ] Take one modded-nanogpt record change, reproduce its effect at small scale and write up why it helps + +**Checkpoint:** given a compute budget, you can estimate a compute-optimal model size and token count, and explain the assumptions behind the estimate. + +--- + +### 3.3 Reading & reproducing papers ★ + +**Why:** reproducing a paper is the standard way to show research-engineering ability. It's also how you'll learn most of what remains. + +**Method** +1. **Three-pass reading** (Keshav, [How to Read a Paper](https://web.stanford.edu/class/ee384m/Handouts/HowtoReadPaper.pdf)): skim (5 min) → understand the main idea (1 hr) → reconstruct it in detail (several hours). +2. For each paper, write a one-page summary in `notes/papers/`: problem, key idea, method in your own notation, results, what you doubt, what you'd try next. +3. Reproduce the **smallest experiment that tests the main claim**. Don't reproduce the whole paper. +4. Report both what reproduced and what didn't. Failed reproductions are informative too. + +**Learn** +- *Core:* the ordered reading list in [`papers.md`](papers.md) +- *Core:* John Schulman, [An Opinionated Guide to ML Research](http://joschu.net/blog/opinionated-guide-ml-research.html) +- *Core:* [arXiv](https://arxiv.org/) cs.LG / cs.CL; follow through [alphaXiv](https://www.alphaxiv.org/) or [Hugging Face Daily Papers](https://huggingface.co/papers) +- *Optional:* [Distill.pub](https://distill.pub/) archive, a model of clear explanation +- *Optional:* Lilian Weng's [blog](https://lilianweng.github.io/), long, well-cited surveys + +**Build** +- [ ] Summaries for the first 15 papers in `papers.md` +- [ ] **Capstone E** (see projects): a full paper reproduction with write-up + +**Checkpoint:** you can read a new paper in a day, write down its central claim and the weakest part of its evidence, and design a small experiment to test it. + +--- + +### 3.4 Reinforcement learning + +**Why:** RL is the foundation of RLHF, reasoning models and agent training. Recent progress in reasoning models comes largely from RL with verifiable rewards. + +**Concepts:** MDPs; returns, value functions, Bellman equations; dynamic programming; Monte Carlo and TD learning; Q-learning and DQN; policy gradients (REINFORCE); baselines and advantage estimation (GAE); actor-critic; **PPO**; exploration; reward hacking; offline RL (conceptually). + +**Learn** +- *Core:* Sutton & Barto, [*Reinforcement Learning: An Introduction*](http://incompleteideas.net/book/the-book-2nd.html), chapters 1–6 and 13 +- *Core:* OpenAI, [Spinning Up in Deep RL](https://spinningup.openai.com/) +- *Core:* [Berkeley CS285 Deep RL](https://rail.eecs.berkeley.edu/deeprlcourse/) (Sergey Levine), lectures and homework +- *Core:* [PPO paper](https://arxiv.org/abs/1707.06347) +- *Optional:* [Hugging Face Deep RL Course](https://huggingface.co/learn/deep-rl-course) +- *Optional:* Costa Huang et al., [The 37 Implementation Details of PPO](https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/) + +**Build** +- [ ] Tabular Q-learning on a gridworld +- [ ] REINFORCE with a baseline on CartPole, from scratch +- [ ] PPO from scratch (single file, following the 37-details post); match published CartPole and one Atari or MuJoCo curve + +**Checkpoint:** you can derive the policy gradient theorem and explain why PPO clips the ratio. + +--- + +### 3.5 Post-training & alignment + +**Why:** post-training is what turns a base model into a useful assistant, and it's where much of current lab research happens. + +**Concepts:** instruction tuning; reward modeling; RLHF with PPO; DPO and variants; **RL with verifiable rewards (RLVR)** and GRPO; reasoning models and test-time compute; Constitutional AI / RLAIF; reward hacking and overoptimization; sycophancy; evaluating alignment; scalable oversight; safety evaluations. + +**Learn** +- *Core:* Nathan Lambert, [*RLHF Book*](https://rlhfbook.com/), all of it +- *Core:* Papers: [InstructGPT](https://arxiv.org/abs/2203.02155), [Constitutional AI](https://arxiv.org/abs/2212.08073), [DPO](https://arxiv.org/abs/2305.18290), [DeepSeekMath (GRPO)](https://arxiv.org/abs/2402.03300), [DeepSeek-R1](https://arxiv.org/abs/2501.12948), [Scaling Laws for Reward Model Overoptimization](https://arxiv.org/abs/2210.10760) +- *Core:* CS336 alignment and RL assignment +- *Optional:* Anthropic's [research page](https://www.anthropic.com/research) on alignment and safety +- *Optional:* [TRL GRPOTrainer docs](https://huggingface.co/docs/trl/main/en/grpo_trainer) + +**Build** +- [ ] Train a small reward model on a preference dataset and measure its accuracy +- [ ] GRPO from scratch on a small model (≤1.5B) for a verifiable task (e.g. arithmetic or GSM8K-style math). Plot reward, response length and accuracy over training. +- [ ] Deliberately cause reward hacking with a flawed reward function and document what the model learns to exploit + +**Checkpoint:** you can explain the RLHF → DPO → GRPO progression: what problem each one solves and what new problem it introduces. + +--- + +### 3.6 Interpretability + +**Why:** this is the science of what's going on inside the network. It suits people who like debugging systems, and it has a well-developed path for newcomers. + +**Concepts:** the residual stream view; attention heads and circuits (induction heads); superposition and polysemanticity; probing; activation patching and causal interventions; logit lens; sparse autoencoders (SAEs) and dictionary learning; transcoders and attribution graphs; steering vectors. + +**Learn** +- *Core:* [ARENA curriculum](https://www.arena.education/), chapter 1 (Transformer interpretability). Free and hands-on; the standard on-ramp. +- *Core:* Anthropic, [A Mathematical Framework for Transformer Circuits](https://transformer-circuits.pub/2021/framework/index.html) and [In-context Learning and Induction Heads](https://transformer-circuits.pub/2022/in-context-learning-and-induction-heads/index.html) +- *Core:* Anthropic, [Toy Models of Superposition](https://transformer-circuits.pub/2022/toy_model/index.html) and [Towards Monosemanticity](https://transformer-circuits.pub/2023/monosemantic-features) +- *Core:* [TransformerLens](https://github.com/TransformerLensOrg/TransformerLens) library +- *Optional:* the rest of [transformer-circuits.pub](https://transformer-circuits.pub/), including Scaling Monosemanticity and the circuit-tracing work +- *Optional:* Neel Nanda's guides on getting started in mechanistic interpretability (linked from his [website](https://www.neelnanda.io/)) + +**Build** +- [ ] ARENA chapter 1 exercises +- [ ] Find induction heads in your own small GPT +- [ ] Train a sparse autoencoder on one layer of a small model and label 20 features by hand +- [ ] Build a steering vector that reliably changes one behavior, and measure the side effects + +**Checkpoint:** you can take a small model behavior and form and test a causal hypothesis about which components produce it. + +--- + +### 3.7 Doing research ★ + +**Why:** the final skill is producing knowledge that is trustworthy, not just running code. + +**Concepts:** choosing problems (important × tractable × suited to you); hypotheses before experiments; baselines first; ablations; seeds and variance across runs; avoiding test-set leakage; negative results; fast iteration loops; good experiment infrastructure (you're well placed here); clear writing and figures. + +**Learn** +- *Core:* John Schulman, [An Opinionated Guide to ML Research](http://joschu.net/blog/opinionated-guide-ml-research.html), read again now +- *Core:* Richard Hamming, [You and Your Research](https://www.cs.virginia.edu/~robins/YouAndYourResearch.html) (talk transcript) +- *Core:* Andrej Karpathy, [A Recipe for Training Neural Networks](https://karpathy.github.io/2019/04/25/recipe/), read again with research eyes +- *Optional:* Richard Sutton, [The Bitter Lesson](http://www.incompleteideas.net/IncIdeas/BitterLesson.html) + +**Communities & programs** +- [EleutherAI](https://www.eleuther.ai/), an open research community with active Discord projects you can join +- [MATS](https://www.matsprogram.org/), a mentored AI alignment/safety research program +- [Anthropic Fellows Program](https://alignment.anthropic.com/), funded research with Anthropic mentors (check the Anthropic site for current calls) +- [GPU MODE](https://github.com/gpu-mode) for systems-flavored research +- Open-source: contribute to vLLM, TRL, TransformerLens, lm-evaluation-harness or nanoGPT-style projects + +**Build** +- [ ] **Capstone F** (see projects): a small original study, written as a short paper or blog post +- [ ] At least one merged contribution to a major open-source ML repo +- [ ] Share your work publicly (blog, LessWrong/Alignment Forum, arXiv or a workshop) + +**Checkpoint:** a researcher reads your write-up and trusts the conclusions, because the baselines, ablations, seeds and error bars are there. + +--- + +## Track 3 complete when + +- [ ] Modules 3.1–3.6 checkpoints passed +- [ ] 30+ paper summaries in `notes/papers/` +- [ ] Capstone E (reproduction) and Capstone F (original study) published +- [ ] One merged open-source contribution +- [ ] Math Level 3 core done + +**Roles you can target now:** Research Engineer, Member of Technical Staff (research-adjacent), Applied Research Scientist, AI research fellowships. diff --git a/course/track-3-research-engineer/papers.md b/course/track-3-research-engineer/papers.md new file mode 100644 index 0000000..a9a13d9 --- /dev/null +++ b/course/track-3-research-engineer/papers.md @@ -0,0 +1,126 @@ +# Core Paper Reading List + +Read in order within each section. You can start the first sections during Track 2; you'll get more from them after building the thing yourself. + +For each paper, write a one-page summary in `notes/papers/.md` (template at the bottom). Mark ⭐ papers for a full three-pass read; skim the rest. + +Tick `[x]` when the summary is written. + +--- + +## 1. Foundations of deep learning (read during Track 2, Part A) + +- [ ] ⭐ He et al., 2015: **Deep Residual Learning (ResNet)**: +- [ ] Ioffe & Szegedy, 2015: **Batch Normalization**: +- [ ] Ba et al., 2016: **Layer Normalization**: +- [ ] ⭐ Kingma & Ba, 2014: **Adam**: +- [ ] Loshchilov & Hutter, 2017: **Decoupled Weight Decay (AdamW)**: +- [ ] Mikolov et al., 2013: **word2vec**: +- [ ] Bahdanau et al., 2014: **Neural Machine Translation by Jointly Learning to Align and Translate** (the origin of attention): + +## 2. Transformers & language models (Track 2, module 2.4) + +- [ ] ⭐ Vaswani et al., 2017: **Attention Is All You Need**: +- [ ] Devlin et al., 2018: **BERT**: +- [ ] ⭐ Radford et al., 2019: **GPT-2: Language Models are Unsupervised Multitask Learners**: +- [ ] ⭐ Brown et al., 2020: **GPT-3: Language Models are Few-Shot Learners**: +- [ ] Su et al., 2021: **RoFormer (RoPE)**: +- [ ] Shazeer, 2020: **GLU Variants Improve Transformer (SwiGLU)**: +- [ ] Ainslie et al., 2023: **GQA: Grouped-Query Attention**: +- [ ] Touvron et al., 2023: **LLaMA**: +- [ ] Dosovitskiy et al., 2020: **An Image is Worth 16x16 Words (ViT)**: +- [ ] Radford et al., 2021: **CLIP**: + +## 3. Applications: RAG, reasoning, agents (Track 1 background) + +- [ ] Lewis et al., 2020: **Retrieval-Augmented Generation**: +- [ ] Wei et al., 2022: **Chain-of-Thought Prompting**: +- [ ] Yao et al., 2022: **ReAct**: +- [ ] Schick et al., 2023: **Toolformer**: + +## 4. Systems & efficiency (Track 2, Part C) + +- [ ] ⭐ Dao et al., 2022: **FlashAttention**: +- [ ] ⭐ Kwon et al., 2023: **PagedAttention / vLLM**: +- [ ] Leviathan et al., 2022: **Speculative Decoding**: +- [ ] Frantar et al., 2022: **GPTQ**: +- [ ] Lin et al., 2023: **AWQ**: +- [ ] Rajbhandari et al., 2019: **ZeRO**: +- [ ] Shoeybi et al., 2019: **Megatron-LM**: +- [ ] Fedus et al., 2021: **Switch Transformers (MoE)**: +- [ ] Jiang et al., 2024: **Mixtral of Experts**: + +## 5. Fine-tuning & post-training (Track 2 module 2.5 → Track 3 module 3.5) + +- [ ] ⭐ Hu et al., 2021: **LoRA**: +- [ ] Dettmers et al., 2023: **QLoRA**: +- [ ] ⭐ Ouyang et al., 2022: **InstructGPT (RLHF)**: +- [ ] ⭐ Schulman et al., 2017: **PPO**: +- [ ] ⭐ Rafailov et al., 2023: **DPO**: +- [ ] Bai et al., 2022: **Constitutional AI**: +- [ ] Gao et al., 2022: **Scaling Laws for Reward Model Overoptimization**: +- [ ] Lightman et al., 2023: **Let's Verify Step by Step**: +- [ ] ⭐ Shao et al., 2024: **DeepSeekMath (GRPO)**: +- [ ] ⭐ DeepSeek-AI, 2025: **DeepSeek-R1**: +- [ ] Snell et al., 2024: **Scaling LLM Test-Time Compute Optimally**: + +## 6. Scaling & training dynamics (Track 3 module 3.2) + +- [ ] ⭐ Kaplan et al., 2020: **Scaling Laws for Neural Language Models**: +- [ ] ⭐ Hoffmann et al., 2022: **Training Compute-Optimal LLMs (Chinchilla)**: +- [ ] Yang et al., 2022: **Tensor Programs V (μP)**: +- [ ] Nakkiran et al., 2019: **Deep Double Descent**: +- [ ] Frankle & Carbin, 2018: **The Lottery Ticket Hypothesis**: +- [ ] Power et al., 2022: **Grokking**: +- [ ] Keller Jordan, 2024: **Muon optimizer** (blog): + +## 7. Frontier open-model technical reports (read the architecture & training sections) + +- [ ] Llama Team, 2024: **The Llama 3 Herd of Models**: +- [ ] DeepSeek-AI, 2024: **DeepSeek-V3 Technical Report**: +- [ ] *Add the newest open-model reports here as they come out (Qwen, DeepSeek, OLMo, Gemma, etc.)* + +## 8. Interpretability (Track 3 module 3.6) + +- [ ] ⭐ Elhage et al., 2021: **A Mathematical Framework for Transformer Circuits**: +- [ ] Olsson et al., 2022: **In-context Learning and Induction Heads**: +- [ ] ⭐ Elhage et al., 2022: **Toy Models of Superposition**: +- [ ] Bricken et al., 2023: **Towards Monosemanticity**: +- [ ] Nanda et al., 2023: **Progress Measures for Grokking via Mechanistic Interpretability**: + +## 9. Beyond transformers (optional, for breadth) + +- [ ] Ho et al., 2020: **DDPM (diffusion models)**: +- [ ] Gu & Dao, 2023: **Mamba (state-space models)**: + +--- + +## Paper summary template + +Copy into `notes/papers/.md`: + +```markdown +# (<Authors>, <Year>) + +Link: +Read on: Passes done: 1 / 2 / 3 + +## Problem +What were they trying to solve, and why did it matter then? + +## Key idea (one sentence) + +## Method (in my own notation) +Key equations with every symbol defined. + +## Results +Main numbers. What is the baseline? How big is the gain? + +## What I doubt +Weakest evidence, missing ablations, possible confounders. + +## What I'd try next / small reproduction idea + +## Connections +Which other papers or modules does this relate to? +``` diff --git a/package-lock.json b/package-lock.json index 9df075b..f647a34 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,10 @@ "version": "0.1.0", "license": "MIT", "dependencies": { - "astro": "^7.3.3" + "@astrojs/preact": "^6.0.6", + "astro": "^7.3.3", + "marked": "^18.1.0", + "preact": "^10.29.8" }, "devDependencies": { "axe-core": "^4.13.0", @@ -238,6 +241,42 @@ "satteri": "^0.10.3" } }, + "node_modules/@astrojs/preact": { + "version": "6.0.6", + "resolved": "https://registry.npmjs.org/@astrojs/preact/-/preact-6.0.6.tgz", + "integrity": "sha512-Z8GGzW0DAUdy+EtQ+otGtzDLMuYXUueRN5MM8UF4yB8OUaxnVIHF5er1dNCGKoxlnM/8Y2B8+ub+YadofKSSJA==", + "license": "MIT", + "dependencies": { + "@astrojs/internal-helpers": "0.12.0", + "@preact/preset-vite": "^2.10.6", + "@preact/signals": "^2.11.2", + "devalue": "^5.9.4", + "preact-render-to-string": "^6.7.0", + "vite": "^8.3.0" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "preact": "^10.6.5" + } + }, + "node_modules/@astrojs/preact/node_modules/@astrojs/internal-helpers": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@astrojs/internal-helpers/-/internal-helpers-0.12.0.tgz", + "integrity": "sha512-pKPuwCDtO0L7zgmt1JGd9X4Aes1+0SX3IEBSqBNPHsScYdPMlfmed3Y7DTbXyF7E+8ylnb563o/0OzGQPOFehw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.4", + "@types/mdast": "^4.0.4", + "picomatch": "^4.0.4", + "retext-smartypants": "^6.2.0", + "shiki": "^4.0.2", + "smol-toml": "^1.8.0", + "unified": "^11.0.5", + "yaml": "^2.9.1" + } + }, "node_modules/@astrojs/prism": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@astrojs/prism/-/prism-4.0.2.tgz", @@ -265,6 +304,188 @@ "node": "18.20.8 || ^20.3.0 || >=22.0.0" } }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.8", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", + "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.8", + "@babel/types": "^7.29.8", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/generator/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@babel/helper-annotate-as-pure": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.7.tgz", + "integrity": "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/helper-string-parser": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", @@ -283,6 +504,28 @@ "node": ">=6.9.0" } }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.10.tgz", + "integrity": "sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg==", + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8" + }, + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/parser": { "version": "7.29.9", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", @@ -298,6 +541,87 @@ "node": ">=6.0.0" } }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz", + "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==", + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.29.7.tgz", + "integrity": "sha512-WsZulLVBUHXVj2cUcPVx6UE21TpalB6bHbSFErKT0Ib++ax24jjXe73FqlWvdylFOjiuPHYi6VCcgRad1ItN+A==", + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.29.7", + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-plugin-utils": "^7.29.7", + "@babel/plugin-syntax-jsx": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-development": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.29.7.tgz", + "integrity": "sha512-Xfy3UVMF04+ypnFbkhvfqtmvwfe92qwQdbGZVonhE+6v35GzlofmOnA1szaZqzb9xYWr0nl1e5EMmzi0DNON1g==", + "license": "MIT", + "dependencies": { + "@babel/plugin-transform-react-jsx": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.10.tgz", + "integrity": "sha512-B3lYAs2nkKskbgQ1nfy8Ma9ao9Q1rntTAQHrzzyDuj+TSO+X3le6PfWwqDvodsb+OumE10eMFfuMCTQSQ5iuIQ==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.8", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.9", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.8", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/types": { "version": "7.29.8", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", @@ -1578,11 +1902,50 @@ "url": "https://opencollective.com/libvips" } }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/gen-mapping/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, "license": "MIT", "engines": { "node": ">=6.0.0" @@ -1670,6 +2033,129 @@ "dev": true, "license": "MIT" }, + "node_modules/@preact/preset-vite": { + "version": "2.10.6", + "resolved": "https://registry.npmjs.org/@preact/preset-vite/-/preset-vite-2.10.6.tgz", + "integrity": "sha512-ZZ5RIT2ZVXg8UxRA8VZpoT8CdpDG7RFIqOT4bELqNBp85+HKvQBbgmh3gsoW1UOQXx26TLe+ZRNKI7q281Kckw==", + "license": "MIT", + "dependencies": { + "@babel/plugin-transform-react-jsx": "^7.27.1", + "@babel/plugin-transform-react-jsx-development": "^7.27.1", + "@prefresh/vite": "^2.4.11", + "@rollup/pluginutils": "^5.0.0", + "babel-plugin-transform-hook-names": "^1.0.2", + "debug": "^4.4.3", + "magic-string": "^0.30.21", + "picocolors": "^1.1.1", + "vite-prerender-plugin": "^0.5.8", + "zimmerframe": "^1.1.4" + }, + "peerDependencies": { + "@babel/core": "7.x", + "vite": "2.x || 3.x || 4.x || 5.x || 6.x || 7.x || 8.x" + } + }, + "node_modules/@preact/preset-vite/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/@preact/signals": { + "version": "2.11.3", + "resolved": "https://registry.npmjs.org/@preact/signals/-/signals-2.11.3.tgz", + "integrity": "sha512-mttwFM98G/JiriTgMwU+UWygL6sfVmYEiNcPSKkUnv4PxPpZhmP2ugGC4qi360+ZIHyQ8NY05bfJT3b4RUIGlw==", + "license": "MIT", + "dependencies": { + "@preact/signals-core": "^1.14.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + }, + "peerDependencies": { + "preact": ">= 10.25.0 || >=11.0.0-0" + } + }, + "node_modules/@preact/signals-core": { + "version": "1.14.4", + "resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.4.tgz", + "integrity": "sha512-HNB6HYeYKhQbJ1aKl+YRjrS4+QWHLKX6qKoUsfS/m0vqzsVaEBiZiaKbG/e+NKk2ch5ALQr/ihWaMHxiCuuWHA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/@prefresh/babel-plugin": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/@prefresh/babel-plugin/-/babel-plugin-0.5.4.tgz", + "integrity": "sha512-GSwqHGVem7AjnOKAkmLNbAExqZZFddf9S3ySOwowGEsJR8vwNKJ7Z/262fov5wra8LkDVSmFw3CjMGRdLoCmRA==", + "license": "MIT", + "peerDependencies": { + "@babel/core": "^7.0.0 || ^8.0.0" + } + }, + "node_modules/@prefresh/core": { + "version": "1.5.11", + "resolved": "https://registry.npmjs.org/@prefresh/core/-/core-1.5.11.tgz", + "integrity": "sha512-Ml00PP8jeHaADxfQqxUs4+M5JS+T5J26UnvPVfsrmlpGw2I3e9XtM0DMeuzkmvg+Tn7VdHSMpLBrDPG0iHoDqQ==", + "license": "MIT", + "peerDependencies": { + "preact": "^10.0.0 || ^11.0.0-0" + } + }, + "node_modules/@prefresh/utils": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@prefresh/utils/-/utils-1.2.1.tgz", + "integrity": "sha512-vq/sIuN5nYfYzvyayXI4C2QkprfNaHUQ9ZX+3xLD8nL3rWyzpxOm1+K7RtMbhd+66QcaISViK7amjnheQ/4WZw==", + "license": "MIT" + }, + "node_modules/@prefresh/vite": { + "version": "2.4.12", + "resolved": "https://registry.npmjs.org/@prefresh/vite/-/vite-2.4.12.tgz", + "integrity": "sha512-FY1fzXpUjiuosznMV0YM7XAOPZjB5FIdWS0W24+XnlxYkt9hNAwwsiKYn+cuTEoMtD/ZVazS5QVssBr9YhpCQA==", + "license": "MIT", + "dependencies": { + "@babel/core": "^7.22.1", + "@prefresh/babel-plugin": "^0.5.2", + "@prefresh/core": "^1.5.0", + "@prefresh/utils": "^1.2.0", + "@rollup/pluginutils": "^4.2.1" + }, + "peerDependencies": { + "preact": "^10.4.0 || ^11.0.0-0", + "vite": ">=2.0.0" + } + }, + "node_modules/@prefresh/vite/node_modules/@rollup/pluginutils": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.2.1.tgz", + "integrity": "sha512-iKnFXr7NkdZAIHiIWE+BX5ULi/ucVFYWD6TbAV+rZctiRTY2PL6tsIKhoIOaoskiWAkgu+VsbXgUVDNLHf+InQ==", + "license": "MIT", + "dependencies": { + "estree-walker": "^2.0.1", + "picomatch": "^2.2.2" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/@prefresh/vite/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/@rolldown/binding-android-arm-eabi": { "version": "1.2.9", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.9.tgz", @@ -1916,6 +2402,28 @@ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", "license": "MIT" }, + "node_modules/@rollup/pluginutils": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz", + "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, "node_modules/@shikijs/core": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.4.3.tgz", @@ -2255,6 +2763,15 @@ "node": ">= 0.4" } }, + "node_modules/babel-plugin-transform-hook-names": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-hook-names/-/babel-plugin-transform-hook-names-1.0.2.tgz", + "integrity": "sha512-5gafyjyyBTTdX/tQQ0hRgu4AhNHG/hqWi0ZZmg2xvs2FgRkJXzDNKBZCyoYqgFkovfDrgM8OoKg8karoUvWeCw==", + "license": "MIT", + "peerDependencies": { + "@babel/core": "^7.12.10" + } + }, "node_modules/bail": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz", @@ -2265,6 +2782,18 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.27", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz", + "integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==", + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/blake3-wasm": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz", @@ -2278,6 +2807,59 @@ "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", "license": "ISC" }, + "node_modules/browserslist": { + "version": "4.29.3", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz", + "integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.26", + "caniuse-lite": "^1.0.30001813", + "electron-to-chromium": "^1.5.439", + "node-releases": "^2.0.57", + "update-browserslist-db": "^1.3.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001815", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001815.tgz", + "integrity": "sha512-uDybUEyfgbyJJ93J1vikTylBX31AkdVYeVPeffMQpf8XN7hSfr0oZOn4VFOIMNvtU5+rHvC5Udg2TgtJKHm23Q==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, "node_modules/ccount": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", @@ -2375,6 +2957,12 @@ "node": ">= 18" } }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "license": "MIT" + }, "node_modules/cookie": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/cookie/-/cookie-2.0.1.tgz", @@ -2477,6 +3065,23 @@ "integrity": "sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==", "license": "CC0-1.0" }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, "node_modules/defu": { "version": "6.1.7", "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", @@ -2599,6 +3204,12 @@ "node": ">=4" } }, + "node_modules/electron-to-chromium": { + "version": "1.5.449", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.449.tgz", + "integrity": "sha512-dKeYk/3SFQz+nXi5whp3OuJzeWABEG4zCtkWJ9+Vby1E1iFM2y0gElRtQvNXRPJTsj8WAF4HMP7hvP790QtJ9g==", + "license": "ISC" + }, "node_modules/entities": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", @@ -2668,6 +3279,21 @@ "@esbuild/win32-x64": "0.28.2" } }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, "node_modules/eventemitter3": { "version": "5.0.4", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", @@ -2774,6 +3400,15 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/get-tsconfig": { "version": "5.0.0-beta.4", "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-5.0.0-beta.4.tgz", @@ -2848,6 +3483,15 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, "node_modules/html-escaper": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz", @@ -2906,6 +3550,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, "node_modules/js-yaml": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", @@ -2928,6 +3578,30 @@ "js-yaml": "bin/js-yaml.js" } }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/jsonc-parser": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", @@ -2944,6 +3618,12 @@ "node": ">=6" } }, + "node_modules/kolorist": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/kolorist/-/kolorist-1.8.0.tgz", + "integrity": "sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==", + "license": "MIT" + }, "node_modules/lightningcss": { "version": "1.33.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", @@ -3222,6 +3902,18 @@ "source-map-js": "^1.2.1" } }, + "node_modules/marked": { + "version": "18.1.0", + "resolved": "https://registry.npmjs.org/marked/-/marked-18.1.0.tgz", + "integrity": "sha512-PamYXWWWg2nboG3oX5Ffzpy3EFZROqZJK9hSlMmUnekp7TxPs5DcT95vwd46m73/exfKCRVMtgXoPMI4FEJL6w==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + }, "node_modules/mdast-util-to-hast": { "version": "13.2.1", "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", @@ -3375,6 +4067,12 @@ "node": ">=10" } }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, "node_modules/nanoid": { "version": "3.3.19", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", @@ -3421,12 +4119,59 @@ "integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==", "license": "MIT" }, + "node_modules/node-html-parser": { + "version": "6.1.13", + "resolved": "https://registry.npmjs.org/node-html-parser/-/node-html-parser-6.1.13.tgz", + "integrity": "sha512-qIsTMOY4C/dAa5Q5vsobRpOOvPfC4pB61UVW2uSwZNUp0QU/jCekTal1vMmbO0DgdHeLUJpv/ARmDqErVxA3Sg==", + "license": "MIT", + "dependencies": { + "css-select": "^5.1.0", + "he": "1.2.0" + } + }, + "node_modules/node-html-parser/node_modules/css-select": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz", + "integrity": "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.1.0", + "domhandler": "^5.0.2", + "domutils": "^3.0.1", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/node-html-parser/node_modules/css-what": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz", + "integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, "node_modules/node-mock-http": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/node-mock-http/-/node-mock-http-1.0.5.tgz", "integrity": "sha512-KQyt/wLjG3TAc7DOUhpqWzgd4ERxR80JOlTK5VE5R1S12IaPVN5qkj4klBce9HPG1Njuup4Sb5bljaT34lIyjw==", "license": "MIT" }, + "node_modules/node-releases": { + "version": "2.0.57", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.57.tgz", + "integrity": "sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -3639,6 +4384,33 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/preact": { + "version": "10.29.8", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.8.tgz", + "integrity": "sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + }, + "peerDependencies": { + "preact-render-to-string": ">=5" + }, + "peerDependenciesMeta": { + "preact-render-to-string": { + "optional": true + } + } + }, + "node_modules/preact-render-to-string": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-6.8.0.tgz", + "integrity": "sha512-2qiMrReQz+MZ5+/bT27kbVnFE7QNCC2fku/Tnc2H5bFUS3I3ASbRy0q72XLZ+2p2KyDE5xMfvSEtkmVo6TRNyA==", + "license": "MIT", + "peerDependencies": { + "preact": ">=10 || >= 11.0.0-0" + } + }, "node_modules/prismjs": { "version": "1.30.0", "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz", @@ -3881,6 +4653,15 @@ "node": ">=20" } }, + "node_modules/simple-code-frame": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/simple-code-frame/-/simple-code-frame-1.3.0.tgz", + "integrity": "sha512-MB4pQmETUBlNs62BBeRjIFGeuy/x6gGKh7+eRUemn1rCFhqo7K+4slPqsyizCbcbYLnaYqaoZ2FWsZ/jN06D8w==", + "license": "MIT", + "dependencies": { + "kolorist": "^1.6.0" + } + }, "node_modules/sisteransi": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", @@ -3899,6 +4680,15 @@ "url": "https://github.com/sponsors/cyyynthia" } }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", @@ -3918,6 +4708,15 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/stack-trace": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-1.0.0.tgz", + "integrity": "sha512-H6D7134xi6qONvh7ZHKgviXf+rd3vhGBSvebPZCaUkd8zvQ+7PtDw6CljPTe4cXWNf2IKZGNqw6VJXSb9IgBpA==", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/stringify-entities": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", @@ -4268,6 +5067,36 @@ } } }, + "node_modules/update-browserslist-db": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz", + "integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, "node_modules/verkit": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/verkit/-/verkit-0.4.1.tgz", @@ -4385,6 +5214,32 @@ } } }, + "node_modules/vite-prerender-plugin": { + "version": "0.5.14", + "resolved": "https://registry.npmjs.org/vite-prerender-plugin/-/vite-prerender-plugin-0.5.14.tgz", + "integrity": "sha512-X2w9AS1OhwEUec9HSryGAmEnEQJGhW6eFoiCVJv8BfOTVpM8SOjk75cEw/IC28APDHZudeIRbP8Sp7wfABq+Aw==", + "license": "MIT", + "dependencies": { + "kolorist": "^1.8.0", + "magic-string": "0.x >= 0.26.0", + "node-html-parser": "^6.1.12", + "simple-code-frame": "^1.3.0", + "source-map": "^0.7.4", + "stack-trace": "^1.0.0-pre2" + }, + "peerDependencies": { + "vite": "5.x || 6.x || 7.x || 8.x" + } + }, + "node_modules/vite-prerender-plugin/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, "node_modules/vitefu": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-1.1.3.tgz", @@ -4973,6 +5828,27 @@ "integrity": "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==", "license": "MIT" }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "license": "ISC" + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, "node_modules/yargs-parser": { "version": "22.0.0", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", @@ -5033,6 +5909,12 @@ "url": "https://opencollective.com/express" } }, + "node_modules/zimmerframe": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.5.tgz", + "integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==", + "license": "MIT" + }, "node_modules/zod": { "version": "4.6.5", "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", diff --git a/package.json b/package.json index b5736cd..abfa50f 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,10 @@ "serve": "wrangler dev" }, "dependencies": { - "astro": "^7.3.3" + "@astrojs/preact": "^6.0.6", + "astro": "^7.3.3", + "marked": "^18.1.0", + "preact": "^10.29.8" }, "description": "Interactive, verified LeetCode solution pages — step through the algorithm, copy code that was run in five languages.", "license": "MIT", diff --git a/public/_redirects b/public/_redirects index 3a2a70f..5143350 100644 --- a/public/_redirects +++ b/public/_redirects @@ -1,4 +1,2 @@ -# Served by Cloudflare before any file. The problem list moved to the home -# page; a real 301 here, where the static build can only write a meta refresh. -/leetcode / 301 -/leetcode/ / 301 +# Served by Cloudflare before any file. Nothing to redirect right now: the +# problem list lives at /leetcode again and the home page is the hub. diff --git a/public/favicon.svg b/public/favicon.svg new file mode 100644 index 0000000..1688ac2 --- /dev/null +++ b/public/favicon.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><defs><linearGradient id="g" x1="0" y1="0" x2="40" y2="40"><stop stop-color="#7B6DFF"/><stop offset="1" stop-color="#0FA3A3"/></linearGradient></defs><rect width="40" height="40" rx="11" fill="url(#g)"/><path d="M12 27 20 15 28 25" stroke="#fff" stroke-width="2.2" fill="none" stroke-linecap="round"/><circle cx="12" cy="27" r="3.2" fill="#fff"/><circle cx="20" cy="15" r="3.2" fill="#fff"/><circle cx="28" cy="25" r="3.2" fill="#fff"/><circle cx="31" cy="9" r="3.4" fill="#fff"/></svg> diff --git a/scripts/audit.mjs b/scripts/audit.mjs index bfb133a..7d50c1d 100644 --- a/scripts/audit.mjs +++ b/scripts/audit.mjs @@ -46,7 +46,7 @@ async function accessibility(page, where) { return found.map((x) => `a11y (${where}) ${x}`); } -/* The masthead's search dialog (SiteSearch.astro), driven from a lesson. */ +/* The top bar's search dialog (SiteSearch.astro), driven from a lesson. */ async function siteSearch(page, base, slugs) { const found = []; const open = () => page.$eval('#search-dlg', (d) => d.open); @@ -77,8 +77,8 @@ async function siteSearch(page, base, slugs) { await page.keyboard.press('Enter'); await page.waitForURL('**/leetcode/two-sum', { timeout: 5000 }).catch(() => found.push('Enter on "two sum" did not open /leetcode/two-sum')); await page.setViewportSize({ width: 320, height: 700 }); - const bar = await page.$eval('.masthead', (m) => m.offsetHeight); - if (bar > 60) found.push(`the masthead wraps at 320px (${bar}px tall)`); + const bar = await page.$eval('.app-top', (m) => m.offsetHeight); + if (bar > 60) found.push(`the top bar wraps at 320px (${bar}px tall)`); return found; } @@ -98,16 +98,18 @@ if (!existsSync(resolve(ROOT, 'dist/index.html'))) { process.exit(1); } -/* dist/ served as a static site: /x resolves to /x.html or /x/index.html. Its own - * server rather than `astro preview`, which runs one instance per project. */ +/* dist/ served as a static site: /x resolves to /x.html, else /x/index.html, the + * order Cloudflare uses (/leetcode is leetcode.html beside the leetcode/ folder of + * lessons). Its own server rather than `astro preview`, which runs one instance + * per project. */ const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.json': 'application/json', '.png': 'image/png', '.woff2': 'font/woff2', '.ico': 'image/x-icon', '.xml': 'application/xml' }; function serve() { const server = createServer((req, res) => { let file = join(DIST, decodeURIComponent(new URL(req.url, 'http://x').pathname)); if (!file.startsWith(DIST)) { res.writeHead(403).end(); return; } - if (existsSync(file) && statSync(file).isDirectory()) file = join(file, 'index.html'); - else if (!existsSync(file) && existsSync(`${file}.html`)) file = `${file}.html`; // build.format 'file' + if (existsSync(`${file}.html`) && !(existsSync(file) && statSync(file).isFile())) file = `${file}.html`; // build.format 'file' + else if (existsSync(file) && statSync(file).isDirectory()) file = join(file, 'index.html'); if (!existsSync(file)) { res.writeHead(404).end('not found'); return; } res.writeHead(200, { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream' }); res.end(readFileSync(file)); @@ -327,7 +329,7 @@ async function main() { const errors = []; page.on('pageerror', (e) => errors.push(`page error: ${e.message}`)); await page.setViewportSize({ width: 400, height: 850 }); - await page.goto(BASE); + await page.goto(`${BASE}/leetcode`); const home = await page.evaluate(() => ({ over: document.documentElement.scrollWidth - window.innerWidth, links: [...document.querySelectorAll('a.ptitle')].map((a) => a.getAttribute('href')), @@ -337,17 +339,55 @@ async function main() { for (const scheme of ['light', 'dark']) { await page.setViewportSize({ width: 1300, height: 900 }); await page.emulateMedia({ colorScheme: scheme }); - await page.goto(BASE); + await page.goto(`${BASE}/leetcode`); a11y.push(...await accessibility(page, scheme)); } const search = await siteSearch(page, BASE, slugs); - report('home page', [ + report('problem list', [ ...errors, ...search, ...(home.over > 0 ? [`${home.over}px too wide at 400px`] : []), ...missing.map((s) => `no link to /leetcode/${s}`), ...a11y, ]); + + // The hub and a sample of AI Engineer pages: no errors, nothing too wide, + // AA in both themes. Lesson steps render client-side, so wait for them. + const others = [ + ['/', 'h1'], + ['/ai-engineer', '.track-tabs'], + ['/ai-engineer/track-2', '.timeline'], + ['/ai-engineer/track-2/2-7', '.guide-hero'], + ['/ai-engineer/track-1/1-1/concepts', '.session-body h1'], + ['/ai-engineer/track-1/1-4/learn', '.check'], + ['/ai-engineer/track-2/2-7/quiz', '.option'], + ['/ai-engineer/practice', '.grid-cards'], + ['/ai-engineer/papers', '.check'], + ['/ai-engineer/projects', 'details'], + ['/profile', '.seg'], + ]; + for (const [path, ready] of others) { + const found = []; + const onError = (e) => found.push(`page error: ${e.message}`); + page.on('pageerror', onError); + for (const width of [400, 320]) { + await page.setViewportSize({ width, height: 850 }); + await page.emulateMedia({ colorScheme: 'light' }); + await page.goto(`${BASE}${path}`); + await page.waitForSelector(ready, { timeout: 5000 }).catch(() => found.push(`${ready} never appeared`)); + const over = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + if (over > 0) found.push(`${over}px too wide at ${width}px`); + } + for (const scheme of ['light', 'dark']) { + await page.setViewportSize({ width: 1500, height: 900 }); + await page.emulateMedia({ colorScheme: scheme }); + await page.goto(`${BASE}${path}`); + await page.waitForSelector(ready, { timeout: 5000 }).catch(() => {}); + found.push(...await accessibility(page, scheme)); + } + page.off('pageerror', onError); + report(path, [...new Set(found)]); + } } await browser.close(); diff --git a/src/components/AppSidebar.astro b/src/components/AppSidebar.astro new file mode 100644 index 0000000..1f78a11 --- /dev/null +++ b/src/components/AppSidebar.astro @@ -0,0 +1,96 @@ +--- +/* The dark sidebar on every page. On a phone it becomes a bottom tab bar + * holding only the links marked .tab; between 720px and 1024px it shows + * icons only. The daily goal at its foot is filled in from progress.ts. */ +import Icon from './Icon.astro'; +import Logo from './Logo.astro'; +import { REPO, SITE_NAME } from '../data/site'; +import type { IconName } from '../lib/icons'; + +const path = Astro.url.pathname.replace(/(index)?\.html$/, '').replace(/\/$/, '') || '/'; +const aiSub = path.startsWith('/ai-engineer') ? (path.split('/')[2] ?? '') : null; + +type Item = { href: string; label: string; icon: IconName; active: boolean; tab?: string; accent?: 'teal' | 'indigo' }; +const groups: { label?: string; items: Item[] }[] = [ + { items: [{ href: '/', label: 'Home', icon: 'home', active: path === '/', tab: 'Home' }] }, + { + label: 'LeetCode', + items: [{ href: '/leetcode', label: 'Problems', icon: 'code', active: path.startsWith('/leetcode'), tab: 'LeetCode', accent: 'teal' }], + }, + { + label: 'AI Engineer', + items: [ + { href: '/ai-engineer', label: 'Path', icon: 'route', active: aiSub !== null && !['practice', 'papers', 'projects'].includes(aiSub), tab: 'AI path', accent: 'indigo' }, + { href: '/ai-engineer/practice', label: 'Practice', icon: 'refresh', active: aiSub === 'practice', tab: 'Practice', accent: 'indigo' }, + { href: '/ai-engineer/papers', label: 'Papers', icon: 'file', active: aiSub === 'papers', accent: 'indigo' }, + { href: '/ai-engineer/projects', label: 'Projects', icon: 'hammer', active: aiSub === 'projects', accent: 'indigo' }, + ], + }, + { label: 'You', items: [{ href: '/profile', label: 'Profile', icon: 'user', active: path === '/profile', tab: 'Profile' }] }, +]; +--- +<nav class="app-side" aria-label="Main"> + <a class="app-brand" href="/"> + <Logo size={34} /> + <span class="app-brand-text"><b>{SITE_NAME}</b><small>devmtnaing.com</small></span> + </a> + {groups.map((g) => ( + <> + {g.label && <div class="app-label">{g.label}</div>} + {g.items.map((it) => ( + <a + class:list={['app-nav', it.accent && `acc-${it.accent}`, it.tab && 'tab']} + href={it.href} + aria-current={it.active ? 'page' : undefined} + title={it.label} + > + <Icon name={it.icon} /> + <span class="app-nav-text">{it.label}</span> + {it.tab && <span class="app-tab-text">{it.tab}</span>} + </a> + ))} + </> + ))} + <a class="app-nav" href={REPO} target="_blank" rel="noopener" title="Source on GitHub"> + <Icon name="github" /> + <span class="app-nav-text">GitHub ↗</span> + </a> + <div class="app-spacer"></div> + <a class="app-goal" href="/profile" data-goal> + <span class="app-goal-row"><b>Daily goal</b><small data-goal-streak></small></span> + <small data-goal-text>0 / 30 XP</small> + <span class="app-meter"><i data-goal-bar style="width:0%"></i></span> + </a> + <button class="app-collapse" type="button" data-collapse aria-label="Collapse the sidebar"> + <Icon name="panel" size={18} /> + <span class="app-nav-text">Collapse</span> + </button> +</nav> + +<script> + import { get, subscribe, streak, xpToday } from '../lib/progress'; + + const goal = () => { + const p = get(); + const xp = xpToday(p); + const s = streak(p); + const text = document.querySelector('[data-goal-text]'); + const bar = document.querySelector<HTMLElement>('[data-goal-bar]'); + const st = document.querySelector('[data-goal-streak]'); + if (text) text.textContent = `${xp} / ${p.dailyGoal} XP today`; + if (bar) bar.style.width = `${Math.min((xp / p.dailyGoal) * 100, 100)}%`; + if (st) st.textContent = s ? `${s}-day streak` : ''; + }; + goal(); + subscribe(goal); + + document.querySelector('[data-collapse]')?.addEventListener('click', () => { + const root = document.documentElement; + const on = root.dataset.nav !== 'collapsed'; + if (on) root.dataset.nav = 'collapsed'; + else delete root.dataset.nav; + try { + localStorage.setItem('learn-nav', on ? 'collapsed' : ''); + } catch {} + }); +</script> diff --git a/src/components/Icon.astro b/src/components/Icon.astro new file mode 100644 index 0000000..99191dd --- /dev/null +++ b/src/components/Icon.astro @@ -0,0 +1,6 @@ +--- +import { ICONS, type IconName } from '../lib/icons'; +interface Props { name: IconName; size?: number; class?: string; fill?: string } +const { name, size = 20, class: cls, fill = 'none' } = Astro.props; +--- +<svg class={cls} width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d={ICONS[name]} /></svg> diff --git a/src/components/Logo.astro b/src/components/Logo.astro new file mode 100644 index 0000000..8f3ba11 --- /dev/null +++ b/src/components/Logo.astro @@ -0,0 +1,11 @@ +--- +interface Props { size?: number } +const { size = 36 } = Astro.props; +--- +<svg width={size} height={size} viewBox="0 0 40 40" aria-hidden="true"> + <defs><linearGradient id="logo-g" x1="0" y1="0" x2="40" y2="40"><stop stop-color="#7B6DFF" /><stop offset="1" stop-color="#0FA3A3" /></linearGradient></defs> + <rect width="40" height="40" rx="11" fill="url(#logo-g)" /> + <path d="M12 27 20 15 28 25" stroke="#fff" stroke-width="2.2" fill="none" stroke-linecap="round" /> + <circle cx="12" cy="27" r="3.2" fill="#fff" /><circle cx="20" cy="15" r="3.2" fill="#fff" /><circle cx="28" cy="25" r="3.2" fill="#fff" /> + <circle cx="31" cy="9" r="3.4" fill="#fff" /> +</svg> diff --git a/src/components/Masthead.astro b/src/components/Masthead.astro deleted file mode 100644 index 854389c..0000000 --- a/src/components/Masthead.astro +++ /dev/null @@ -1,17 +0,0 @@ ---- -import { SITE_NAME, REPO } from '../data/site'; -import ThemeToggle from './ThemeToggle.astro'; -import SiteSearch from './SiteSearch.astro'; - ---- -<header class="masthead"> - <div class="shell"> - <a class="brand" href="/"><span class="dot"></span>{SITE_NAME}</a> - <nav> - <a href="/">LeetCode</a> - <a href={REPO} target="_blank" rel="noopener">GitHub ↗</a> - </nav> - <SiteSearch /> - <ThemeToggle /> - </div> -</header> diff --git a/src/components/SiteFooter.astro b/src/components/SiteFooter.astro index 73d252c..6e4cf3a 100644 --- a/src/components/SiteFooter.astro +++ b/src/components/SiteFooter.astro @@ -3,7 +3,7 @@ import { SITE_NAME, REPO } from '../data/site'; --- <footer class="site-foot"> <div class="shell"> - <span>Written and verified by hand. Every solution here was compiled and run before it went up.</span> + <span>Written and checked by hand. Every LeetCode solution here was compiled and run before it went up.</span> <span>The source is public on <a class="foot-link" href={REPO} target="_blank" rel="noopener">GitHub ↗</a>. Found a bug, a wrong answer or a confusing step? <a class="foot-link" href={`${REPO}/issues/new/choose`} target="_blank" rel="noopener">Report it there ↗</a></span> <a class="sep" href="/">{SITE_NAME}</a> </div> diff --git a/src/components/SiteSearch.astro b/src/components/SiteSearch.astro index 90ed63d..bd5cee3 100644 --- a/src/components/SiteSearch.astro +++ b/src/components/SiteSearch.astro @@ -16,20 +16,20 @@ <kbd class="sb-key" data-key aria-hidden="true"></kbd> </button> -<dialog class="kdlg" id="search-dlg" aria-label="Search problems"> +<dialog class="kdlg" id="search-dlg" aria-label="Search the site"> <div class="k-field"> <svg viewBox="0 0 16 16" aria-hidden="true"><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M10.5 10.5 14 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg> <input type="text" role="combobox" enterkeyhint="go" aria-expanded="true" aria-controls="k-list" aria-autocomplete="list" - aria-label="Search problems" placeholder="Search by name, number or pattern" + aria-label="Search problems and modules" placeholder="Search problems and AI Engineer modules" autocomplete="off" spellcheck="false"> </div> <p class="k-head" data-head></p> - <div class="k-list" id="k-list" role="listbox" aria-label="Problems"></div> + <div class="k-list" id="k-list" role="listbox" aria-label="Results"></div> <p class="k-status" data-status aria-live="polite"></p> </dialog> <script> - interface Row { id: number; title: string; difficulty: string; category: string; href: string; page: boolean; text: string } + interface Row { id: number | string; title: string; difficulty: string; category: string; href: string; page: boolean; text: string; kind?: 'module' } const btn = document.getElementById('search-btn') as HTMLButtonElement; const dlg = document.getElementById('search-dlg') as HTMLDialogElement; @@ -60,7 +60,7 @@ if (!rows) return []; const typed = q.trim().toLowerCase(); const terms = typed.split(/\s+/).filter(Boolean); - if (!terms.length) return rows.filter((r) => r.page); + if (!terms.length) return rows.filter((r) => r.page && r.kind !== 'module'); const rank = (r: Row) => (String(r.id) === typed ? 0 : r.title.toLowerCase().startsWith(typed) ? 2 : 4) + (r.page ? 0 : 1); return rows .filter((r) => terms.every((t) => r.text.includes(t))) @@ -86,7 +86,8 @@ part('k-num', String(r.id)); part('k-title', r.title); part('k-sub', r.page ? r.category : 'LeetCode ↗'); - part(`diff ${r.difficulty.toLowerCase()}`, r.difficulty); + if (r.kind === 'module') part('diff ai', 'AI'); + else part(`diff ${r.difficulty.toLowerCase()}`, r.difficulty); return a; } @@ -100,8 +101,8 @@ status.textContent = !rows ? (loading ? 'Loading…' : 'Could not load the problem list.') : shown.length - ? `${shown.length} ${shown.length === 1 ? 'problem' : 'problems'} · ↑ ↓ to move, Enter to open, Esc to close` - : 'No problems match.'; + ? `${shown.length} ${shown.length === 1 ? 'result' : 'results'} · ↑ ↓ to move, Enter to open, Esc to close` + : 'Nothing matches.'; mark(); } diff --git a/src/components/ai/Onboard.tsx b/src/components/ai/Onboard.tsx new file mode 100644 index 0000000..6892fb5 --- /dev/null +++ b/src/components/ai/Onboard.tsx @@ -0,0 +1,59 @@ +/** "Where are you starting?" on the AI Engineer overview, until it has been answered once. */ +import { useState } from 'preact/hooks' +import type { IconName } from '../../lib/icons' +import { update } from '../../lib/progress' +import { Icon, useProgress } from './ui' + +const STARTS: { id: string; url: string; color: string; icon: IconName; t: string; s: string }[] = [ + { id: 'setup', url: '/ai-engineer/setup', color: 'slate', icon: 'code', t: 'Set up first', s: 'Python, PyTorch, GPU access and notes (week 0)' }, + { id: 't1', url: '/ai-engineer/track-1', color: 'teal', icon: 'bulb', t: 'New to building with LLMs', s: 'Start with Track 1: AI Application Engineer' }, + { id: 't2', url: '/ai-engineer/track-2', color: 'indigo', icon: 'bolt', t: 'I already ship LLM apps', s: 'Jump to Track 2: ML / AI Systems Engineer' }, + { id: 't3', url: '/ai-engineer/track-3', color: 'rose', icon: 'sparkle', t: 'I already train models', s: 'Jump to Track 3: Research Engineer' }, +] + +export default function Onboard() { + const p = useProgress() + const [goal, setGoal] = useState(p.dailyGoal) + if (p.aiOnboarded) return null + return ( + <section class="card onb-card" aria-labelledby="onb-h"> + <div class="kicker">Welcome</div> + <h2 id="onb-h" style={{ fontSize: '22px', margin: '6px 0 4px' }}> + Where are you starting? + </h2> + <p class="page-sub" style={{ margin: 0 }}> + Pick a daily goal, then a starting point. You can change both later on your profile. + </p> + <div class="seg" role="group" aria-label="Daily goal" style={{ marginTop: '14px' }}> + {[ + [10, 'Casual'], + [30, 'Regular'], + [50, 'Serious'], + [100, 'Intense'], + ].map(([xp, l]) => ( + <button key={xp} class={goal === xp ? 'on' : ''} aria-pressed={goal === xp} onClick={() => setGoal(xp as number)}> + {l} · {xp} XP/day + </button> + ))} + </div> + <div class="choices"> + {STARTS.map((s) => ( + <a + key={s.id} + href={s.url} + class={`choice tc-${s.color}`} + onClick={() => update((x) => ({ ...x, aiOnboarded: true, aiTrack: s.id, dailyGoal: goal }))} + > + <span class="e"> + <Icon name={s.icon} /> + </span> + <span> + <b>{s.t}</b> + <small>{s.s}</small> + </span> + </a> + ))} + </div> + </section> + ) +} diff --git a/src/components/ai/Practice.tsx b/src/components/ai/Practice.tsx new file mode 100644 index 0000000..88b1be0 --- /dev/null +++ b/src/components/ai/Practice.tsx @@ -0,0 +1,124 @@ +/** Flashcards (Leitner boxes) and the entry to the mixed quiz review. */ +import { useState } from 'preact/hooks' +import { cards as allCards, type Card } from '../../lib/ai/flashcards' +import { quizzes } from '../../lib/ai/quizzes' +import { reviewCard, today, type Progress } from '../../lib/progress' +import { Icon, shuffle, startedModules, useProgress } from './ui' + +export const reviewPool = (p: Progress) => + Object.entries(quizzes) + .filter(([mid]) => p.done[`${mid}/quiz`]) + .flatMap(([, qs]) => qs) + +function FlashSession({ deck, titles, done }: { deck: Card[]; titles: Record<string, string>; done: () => void }) { + const [i, setI] = useState(0) + const [flip, setFlip] = useState(false) + const card = deck[i] + const answer = (knew: boolean) => { + reviewCard(card.id, knew) + setFlip(false) + if (i + 1 >= deck.length) done() + else setI(i + 1) + } + return ( + <div class="card" style={{ padding: '20px' }}> + <div class="row"> + <div class="bar"> + <i style={{ width: `${(i / deck.length) * 100}%` }} /> + </div> + <small style={{ fontWeight: 700, color: 'var(--muted)', fontFamily: 'var(--mono)' }}> + {i + 1} / {deck.length} + </small> + </div> + <div class="flash"> + <div + class={`flash-in ${flip ? 'flip' : ''}`} + onClick={() => setFlip((f) => !f)} + role="button" + tabIndex={0} + aria-label={flip ? 'Show the term' : 'Reveal the meaning'} + onKeyDown={(e) => (e.key === ' ' || e.key === 'Enter') && (e.preventDefault(), setFlip((f) => !f))} + > + <div class="face front" aria-hidden={flip}> + <b>{card.front}</b> + <span class="hint">tap to reveal</span> + </div> + <div class="face back" aria-hidden={!flip}> + {card.back} + <span class="hint">{titles[card.module]}</span> + </div> + </div> + </div> + <div style={{ display: 'flex', gap: '12px', justifyContent: 'center', marginTop: '22px' }}> + {flip ? ( + <> + <button class="btn ghost" onClick={() => answer(false)}> + Again + </button> + <button class="btn" onClick={() => answer(true)}> + Got it + </button> + </> + ) : ( + <button class="btn" onClick={() => setFlip(true)}> + Reveal + </button> + )} + </div> + </div> + ) +} + +export default function Practice({ titles }: { titles: Record<string, string> }) { + const p = useProgress() + const [deck, setDeck] = useState<Card[] | null>(null) + const started = startedModules(p) + const unlocked = allCards.filter((c) => started.has(c.module)) + const t = today() + const due = unlocked.filter((c) => !p.cards[c.id] || p.cards[c.id].due <= t) + const pool = reviewPool(p) + if (deck) return <FlashSession deck={deck} titles={titles} done={() => setDeck(null)} /> + return ( + <div class="stack"> + <div class="grid-cards"> + <div class="card row" style={{ padding: '18px' }}> + <span class="chip-icon" style={{ background: 'var(--accent-soft)', color: 'var(--accent)' }}> + <Icon name="refresh" /> + </span> + <span class="grow"> + <b>Flashcards</b> + <small> + {due.length} due · {unlocked.length} of {allCards.length} unlocked + </small> + </span> + <button class="btn sm" disabled={!due.length} onClick={() => setDeck(shuffle(due).slice(0, 20))}> + Review + </button> + </div> + <div class="card row" style={{ padding: '18px' }}> + <span class="chip-icon" style={{ background: 'var(--ok-soft)', color: 'var(--ok)' }}> + <Icon name="help" /> + </span> + <span class="grow"> + <b>Mixed quiz review</b> + <small>{pool.length ? `8 random questions from ${pool.length} in finished quizzes` : 'Finish a module quiz to unlock'}</small> + </span> + {pool.length ? ( + <a class="btn sm" href="/ai-engineer/review"> + Start + </a> + ) : ( + <button class="btn sm" disabled> + Start + </button> + )} + </div> + </div> + {unlocked.length === 0 && ( + <p class="page-sub" style={{ marginTop: '8px' }}> + Start your first module on the <a href="/ai-engineer">path</a> to unlock cards. + </p> + )} + </div> + ) +} diff --git a/src/components/ai/Profile.tsx b/src/components/ai/Profile.tsx new file mode 100644 index 0000000..8ea9a7f --- /dev/null +++ b/src/components/ai/Profile.tsx @@ -0,0 +1,112 @@ +/** Site-wide progress: stats, the AI Engineer tracks, daily goal, and moving data between browsers. */ +import { useRef, useState } from 'preact/hooks' +import { crownCount, exportProgress, importProgress, resetProgress, streak, totalXp, update } from '../../lib/progress' +import { Icon, useProgress } from './ui' + +export type TrackSummary = { id: string; url: string; short: string; title: string; color: string; units: string[]; modules: string[] } + +export default function Profile({ tracks }: { tracks: TrackSummary[] }) { + const p = useProgress() + const file = useRef<HTMLInputElement>(null) + const [msg, setMsg] = useState('') + const download = () => { + const a = document.createElement('a') + a.href = URL.createObjectURL(new Blob([exportProgress()], { type: 'application/json' })) + a.download = `learn-progress-${new Date().toISOString().slice(0, 10)}.json` + a.click() + } + const onFile = async (f?: File) => { + if (!f) return + try { + importProgress(await f.text()) + setMsg('Progress imported.') + } catch (e) { + setMsg(`Import failed: ${(e as Error).message}`) + } + } + return ( + <> + <div class="grid-cards" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))' }}> + {[ + { icon: 'flame' as const, color: 'var(--streak)', n: streak(p), l: 'day streak' }, + { icon: 'bolt' as const, color: 'var(--xp)', n: totalXp(p), l: 'total XP' }, + { icon: 'crown' as const, color: 'var(--accent)', n: crownCount(p), l: 'modules crowned' }, + ].map((s) => ( + <div class="card row" key={s.l}> + <span class="chip-icon" style={{ background: `color-mix(in srgb, ${s.color} 16%, transparent)`, color: s.color }}> + <Icon name={s.icon} /> + </span> + <span class="grow"> + <b style={{ fontFamily: 'var(--display)', fontSize: '22px' }}>{s.n}</b> + <small>{s.l}</small> + </span> + </div> + ))} + </div> + + <div class="section-title">AI Engineer</div> + <div class="grid-cards"> + {tracks.map((t) => { + const pct = t.units.length ? Math.round((t.units.filter((u) => p.done[u]).length / t.units.length) * 100) : 0 + return ( + <a key={t.id} href={t.url} class={`card tc-${t.color}`} style={{ borderTop: '4px solid var(--c)' }}> + <div class="row"> + <span class="grow"> + <b> + {t.short}: {t.title} + </b> + <small> + {t.modules.filter((m) => p.crowns[m]).length} / {t.modules.length} modules crowned + </small> + </span> + <b>{pct}%</b> + </div> + <div class="meter" style={{ marginTop: '12px' }}> + <i style={{ width: `${pct}%` }} /> + </div> + </a> + ) + })} + </div> + + <div class="section-title">LeetCode</div> + <p class="page-sub">Problem progress isn't tracked yet. It arrives with sign-in, and will share this XP and streak.</p> + + <div class="section-title">Daily goal</div> + <div class="seg" role="group" aria-label="Daily goal"> + {[10, 30, 50, 100].map((g) => ( + <button key={g} class={p.dailyGoal === g ? 'on' : ''} aria-pressed={p.dailyGoal === g} onClick={() => update((s) => ({ ...s, dailyGoal: g }))}> + {g} XP + </button> + ))} + </div> + + <div class="section-title">Your data</div> + <p class="page-sub" style={{ marginBottom: '12px' }}> + Progress is saved in this browser only. Export it to back it up or move it to another device. Files exported from the standalone AI Engineer site import too. + </p> + <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}> + <button class="btn ghost sm" onClick={download}> + <Icon name="download" size={16} /> Export + </button> + <button class="btn ghost sm" onClick={() => file.current?.click()}> + <Icon name="upload" size={16} /> Import + </button> + <input ref={file} type="file" accept="application/json" hidden onChange={(e) => onFile((e.target as HTMLInputElement).files?.[0])} /> + <button + class="btn red sm" + onClick={() => { + if (confirm('Reset all progress? This cannot be undone. Export first if unsure.')) resetProgress() + }} + > + Reset + </button> + </div> + {msg && ( + <p class="page-sub" role="status" style={{ marginTop: '10px' }}> + {msg} + </p> + )} + </> + ) +} diff --git a/src/components/ai/Rail.tsx b/src/components/ai/Rail.tsx new file mode 100644 index 0000000..70723a8 --- /dev/null +++ b/src/components/ai/Rail.tsx @@ -0,0 +1,132 @@ +/** The right-hand progress rail, and the compact strip that replaces it on narrower screens. */ +import { cards } from '../../lib/ai/flashcards' +import type { UnitRef } from '../../lib/ai/course' +import { crownCount, streak, today, totalXp, xpToday, type Progress } from '../../lib/progress' +import { Icon, startedModules, useProgress } from './ui' + +export function nextUnit(p: Progress, units: UnitRef[]): UnitRef | null { + const inTrack = units.filter((u) => u.track === p.aiTrack) + return inTrack.find((u) => !p.done[u.id]) ?? units.find((u) => !p.done[u.id]) ?? null +} + +export function dueCount(p: Progress) { + const started = startedModules(p) + const t = today() + return cards.filter((c) => started.has(c.module) && (!p.cards[c.id] || p.cards[c.id].due <= t)).length +} + +function Week({ p }: { p: Progress }) { + const days = Array.from({ length: 7 }, (_, i) => { + const d = new Date() + d.setDate(d.getDate() - (6 - i)) + return { key: today(d), label: d.toLocaleDateString('en', { weekday: 'narrow' }), xp: p.xpByDay[today(d)] || 0 } + }) + const max = Math.max(p.dailyGoal, ...days.map((d) => d.xp)) + return ( + <div class="week" aria-label="XP over the last 7 days"> + {days.map((d, i) => ( + <div key={d.key} class={i === 6 ? 'today' : ''} title={`${d.xp} XP`}> + <i style={{ height: `${Math.max((d.xp / max) * 70, 4)}px` }} /> + <span>{d.label}</span> + </div> + ))} + </div> + ) +} + +export default function Rail({ units }: { units: UnitRef[] }) { + const p = useProgress() + const next = nextUnit(p, units) + const due = dueCount(p) + const xp = xpToday(p) + return ( + <div class="stack" style={{ gap: '14px' }}> + <div class="card"> + <div class="panel-title"> + <span class="kicker">Today</span> + <span class="kicker"> + {xp}/{p.dailyGoal} XP + </span> + </div> + <div class="stat-tiles"> + <div class="tile"> + <span class="ic" style={{ background: 'color-mix(in srgb, var(--streak) 16%, transparent)', color: 'var(--streak)' }}> + <Icon name="flame" size={16} /> + </span> + <b>{streak(p)}</b> + <small>day streak</small> + </div> + <div class="tile"> + <span class="ic" style={{ background: 'color-mix(in srgb, var(--xp) 18%, transparent)', color: 'var(--xp)' }}> + <Icon name="bolt" size={16} /> + </span> + <b>{totalXp(p)}</b> + <small>total XP</small> + </div> + <div class="tile"> + <span class="ic" style={{ background: 'var(--accent-soft)', color: 'var(--accent)' }}> + <Icon name="crown" size={16} /> + </span> + <b>{crownCount(p)}</b> + <small>crowns</small> + </div> + </div> + <div class="meter" style={{ marginTop: '14px' }}> + <i style={{ width: `${Math.min((xp / p.dailyGoal) * 100, 100)}%`, background: xp >= p.dailyGoal ? 'var(--ok)' : 'var(--accent)' }} /> + </div> + </div> + {next && ( + <a href={next.url} class={`card row upnext tc-${next.color}`}> + <span class="chip-icon"> + <Icon name="play" fill="currentColor" size={16} /> + </span> + <span class="grow"> + <span class="kicker">Up next · {next.label}</span> + <b>{next.moduleTitle}</b> + <small> + {next.trackShort} · {next.moduleLabel} + </small> + </span> + <Icon name="chevron" /> + </a> + )} + <a href="/ai-engineer/practice" class="card row"> + <span class="chip-icon" style={{ background: 'var(--accent-soft)', color: 'var(--accent)' }}> + <Icon name="refresh" /> + </span> + <span class="grow"> + <b>Review cards</b> + <small>{due} due now</small> + </span> + <Icon name="chevron" /> + </a> + <div class="card"> + <div class="panel-title"> + <span class="kicker">This week</span> + <span class="kicker">goal {p.dailyGoal}/day</span> + </div> + <Week p={p} /> + </div> + </div> + ) +} + +export function StatStrip() { + const p = useProgress() + return ( + <div class="stat-strip"> + <span class="s" style={{ color: 'var(--streak)' }}> + <Icon name="flame" size={16} /> <span style={{ color: 'var(--ink)' }}>{streak(p)}</span> + </span> + <span class="s" style={{ color: 'var(--xp)' }}> + <Icon name="bolt" size={16} /> <span style={{ color: 'var(--ink)' }}>{totalXp(p)}</span> + </span> + <span class="s" style={{ color: 'var(--accent)' }}> + <Icon name="crown" size={16} /> <span style={{ color: 'var(--ink)' }}>{crownCount(p)}</span> + </span> + <span class="s"> + {xpToday(p)}/{p.dailyGoal} <small>XP today</small> + </span> + </div> + ) +} diff --git a/src/components/ai/Review.tsx b/src/components/ai/Review.tsx new file mode 100644 index 0000000..54b01ff --- /dev/null +++ b/src/components/ai/Review.tsx @@ -0,0 +1,22 @@ +/** Eight random questions from quizzes already finished. */ +import { useMemo, useState } from 'preact/hooks' +import { get, totalXp } from '../../lib/progress' +import { reviewPool } from './Practice' +import { DoneScreen, Quiz } from './Session' +import { shuffle, useProgress } from './ui' + +export default function Review() { + const p = useProgress() + const [startXp] = useState(() => totalXp(get())) + const [result, setResult] = useState<string | null>(null) + const questions = useMemo(() => shuffle(reviewPool(get())).slice(0, 8), []) + const back = () => { + location.href = '/ai-engineer/practice' + } + if (!questions.length) { + back() + return null + } + if (result) return <DoneScreen title="Review complete" sub={result} xp={totalXp(p) - startXp} onContinue={back} /> + return <Quiz questions={questions} title="Mixed review" exit={back} onComplete={(c, t) => setResult(`${c} of ${t} right on the first try.`)} /> +} diff --git a/src/components/ai/Session.tsx b/src/components/ai/Session.tsx new file mode 100644 index 0000000..b6fcf10 --- /dev/null +++ b/src/components/ai/Session.tsx @@ -0,0 +1,478 @@ +/** A full-screen lesson step: concepts, a resource or build checklist, a quiz, or the checkpoint. */ +import type { ComponentChildren } from 'preact' +import { useEffect, useMemo, useRef, useState } from 'preact/hooks' +import type { Question } from '../../lib/ai/quizzes' +import type { BuildItem, Resource, UnitKind } from '../../lib/ai/course' +import { addXp, markDone, toggleChecked, totalXp, update, get } from '../../lib/progress' +import { Icon, shuffle, useProgress, XP } from './ui' + +export type SessionModule = { + id: string + label: string + title: string + why: string + concepts: string[] + notes?: string + guideHtml: string + resources: Resource[] + build: BuildItem[] + checkpoint: string +} +export type SessionProps = { + unitId: string + kind: UnitKind + module: SessionModule + track: { id: string; short: string; subtitle: string } + questions?: Question[] + backUrl: string + guideUrl: string +} + +// ───────── shared frame ───────── + +function useEnter(fn: () => void, enabled = true) { + const ref = useRef(fn) + useEffect(() => { + ref.current = fn + }) + useEffect(() => { + if (!enabled) return + const h = (e: KeyboardEvent) => { + if (e.key === 'Enter' && !(e.target instanceof HTMLButtonElement) && !(e.target instanceof HTMLAnchorElement)) { + e.preventDefault() + ref.current() + } + } + window.addEventListener('keydown', h) + return () => window.removeEventListener('keydown', h) + }, [enabled]) +} + +function Frame({ progress, hearts, onClose, children, footer }: { progress: number; hearts?: number; onClose: () => void; children: ComponentChildren; footer: ComponentChildren }) { + return ( + <div class="session"> + <div class="session-top"> + <button class="close" onClick={onClose} aria-label="Close and go back to the path"> + <Icon name="x" size={26} /> + </button> + <div class="bar" role="progressbar" aria-label="Progress" aria-valuenow={Math.round(progress * 100)} aria-valuemin={0} aria-valuemax={100}> + <i style={{ width: `${Math.max(progress * 100, 2)}%` }} /> + </div> + {hearts !== undefined && ( + <span class="hearts" aria-label={`${hearts} hearts left`}> + <Icon name="heart" fill="currentColor" size={20} /> {hearts} + </span> + )} + </div> + <main class="session-body">{children}</main> + {footer} + </div> + ) +} + +function Footer({ tone, msg, children, hints = true }: { tone?: 'ok' | 'bad'; msg?: ComponentChildren; children: ComponentChildren; hints?: boolean }) { + return ( + <div class={`footer ${tone ?? ''}`}> + <div class="footer-in"> + {msg ? ( + <div class="msg" role="status"> + {msg} + </div> + ) : hints ? ( + <div class="kbd"> + <kbd>Enter</kbd> continue · <kbd>1–4</kbd> choose + </div> + ) : ( + <span /> + )} + <div style={{ display: 'flex', gap: '10px' }}>{children}</div> + </div> + </div> + ) +} + +export function DoneScreen({ title, sub, xp, crown, onContinue }: { title: string; sub?: string; xp: number; crown?: boolean; onContinue: () => void }) { + useEnter(onContinue) + return ( + <Frame + progress={1} + onClose={onContinue} + footer={ + <Footer> + <button class="btn track" onClick={onContinue}> + Continue + </button> + </Footer> + } + > + <div class="done-screen"> + <div class="big" style={crown ? { background: 'color-mix(in srgb, var(--xp) 18%, transparent)', color: 'var(--xp)' } : undefined}> + <Icon name={crown ? 'crown' : 'trophy'} size={60} /> + </div> + <h1>{title}</h1> + {sub && <p class="lead">{sub}</p>} + <div class="xp-pills"> + <div class="xp-pill"> + <small>XP earned</small> + <b> + <span style={{ color: 'var(--xp)', display: 'inline-flex' }}> + <Icon name="bolt" size={20} /> + </span>{' '} + +{xp} + </b> + </div> + {crown && ( + <div class="xp-pill"> + <small>Crown</small> + <b style={{ color: 'var(--xp)' }}> + <Icon name="crown" size={22} /> + </b> + </div> + )} + </div> + </div> + </Frame> + ) +} + +// ───────── unit types ───────── + +type UnitProps = { s: SessionProps; exit: () => void; finish: (title: string, sub?: string, crown?: boolean) => void } + +function Concepts({ s, exit, finish }: UnitProps) { + const m = s.module + const go = () => { + markDone(s.unitId, XP.concepts) + finish('Concepts unlocked', 'Next: work through the resources.') + } + useEnter(go) + const fallback = !m.why && m.concepts.length === 0 + return ( + <Frame + progress={0.5} + onClose={exit} + footer={ + <Footer> + <button class="btn track" onClick={go}> + Continue + </button> + </Footer> + } + > + <span class="pill"> + <Icon name="sparkle" size={14} /> {s.track.short} · {m.label} + </span> + <h1>{m.title}</h1> + {m.why && ( + <> + <div class="section-title">Why it matters</div> + <p class="lead" style={{ marginTop: 0 }} dangerouslySetInnerHTML={{ __html: m.why }} /> + </> + )} + {!m.why && !fallback && <p class="lead">{s.track.subtitle}</p>} + {m.concepts.length > 0 && ( + <> + <div class="section-title">Key concepts</div> + <div class="concepts"> + {m.concepts.map((c, i) => ( + <span key={i} class="concept" dangerouslySetInnerHTML={{ __html: c }} /> + ))} + </div> + </> + )} + {m.notes && <ul class="prose" dangerouslySetInnerHTML={{ __html: m.notes }} />} + {fallback && <div class="prose" dangerouslySetInnerHTML={{ __html: m.guideHtml }} />} + </Frame> + ) +} + +function Checklist({ s, exit, finish }: UnitProps) { + const p = useProgress() + const [showOpt, setShowOpt] = useState(false) + const m = s.module + const isRes = s.kind === 'resources' + const required = isRes ? m.resources.filter((r) => r.core) : m.build + const optional = isRes ? m.resources.filter((r) => !r.core) : [] + const req = required.length ? required : optional + const doneN = req.filter((r) => p.checked[r.id]).length + const complete = doneN === req.length + const already = !!p.done[s.unitId] + + const go = () => { + if (complete) { + markDone(s.unitId, XP.unitBonus) + if (!already) return finish(isRes ? 'Resources complete!' : 'Builds complete!') + } + exit() + } + useEnter(go) + + // The row toggles on click; the box is the real checkbox (keyboard and screen + // readers), so the resource links inside the row are not nested in a control. + const item = (r: { id: string; html: string; core?: boolean; sub?: string[] }, xp: number) => ( + <div + key={r.id} + class={`check ${p.checked[r.id] ? 'on' : ''}`} + onClick={(e) => { + if ((e.target as HTMLElement).closest('a')) return + toggleChecked(r.id, xp) + }} + > + <button class="box" type="button" role="checkbox" aria-checked={!!p.checked[r.id]} aria-labelledby={`t-${r.id}`}> + {p.checked[r.id] && <Icon name="check" size={16} />} + </button> + <span> + {isRes && <span class="tag">{r.core ? 'Core' : 'Optional'}</span>} + <span id={`t-${r.id}`} dangerouslySetInnerHTML={{ __html: r.html }} /> + {r.sub && r.sub.length > 0 && ( + <ol> + {r.sub.map((x, i) => ( + <li key={i} dangerouslySetInnerHTML={{ __html: x }} /> + ))} + </ol> + )} + </span> + </div> + ) + + return ( + <Frame + progress={req.length ? doneN / req.length : 1} + onClose={exit} + footer={ + <Footer + msg={ + <span style={{ fontWeight: 600, color: 'var(--muted)', fontFamily: 'var(--mono)', fontSize: '13px' }}> + {doneN} / {req.length} {isRes ? 'core resources' : 'builds'} done + </span> + } + > + <button class={complete ? 'btn track' : 'btn ghost'} onClick={go}> + {complete ? (already ? 'Done' : 'Complete') : 'Save & exit'} + </button> + </Footer> + } + > + <span class="pill"> + <Icon name={isRes ? 'bookOpen' : 'code'} size={14} /> {isRes ? 'Learn' : 'Build'} · {m.label} + </span> + <h1>{m.title}</h1> + <p class="lead" style={{ color: 'var(--muted)', fontSize: '15px' }}> + {isRes + ? 'Work through the core resources. Tick each one when finished. Links open in a new tab.' + : 'Hands-on work. This is where the learning happens. Tick each build when it runs and you have written notes on it.'} + </p> + <div class="checklist">{req.map((r) => item(r, isRes ? XP.coreResource : XP.build))}</div> + {required.length > 0 && optional.length > 0 && ( + <> + <button class="optional-toggle" onClick={() => setShowOpt((v) => !v)} aria-expanded={showOpt}> + <Icon name="chevron" size={16} /> {showOpt ? 'Hide' : 'Show'} {optional.length} optional resources + </button> + {showOpt && <div class="checklist">{optional.map((r) => item(r, XP.optionalResource))}</div>} + </> + )} + </Frame> + ) +} + +type QItem = { q: Question; order: number[]; first: boolean } + +export function Quiz({ questions, title, exit, onComplete }: { questions: Question[]; title: string; exit: () => void; onComplete: (correctFirst: number, total: number) => void }) { + const initial = useMemo<QItem[]>(() => shuffle(questions).map((q) => ({ q, order: shuffle(q.o.map((_, i) => i)), first: true })), [questions]) + const [queue, setQueue] = useState(initial) + const [idx, setIdx] = useState(0) + const [sel, setSel] = useState<number | null>(null) + const [status, setStatus] = useState<'ask' | 'right' | 'wrong'>('ask') + const [hearts, setHearts] = useState(3) + const [correctFirst, setCorrectFirst] = useState(0) + const [solved, setSolved] = useState(0) + const [failed, setFailed] = useState(false) + const item = queue[idx] + const total = initial.length + + const check = () => { + if (sel === null || status !== 'ask') return + if (item.order[sel] === item.q.a) { + setStatus('right') + setSolved((n) => n + 1) + if (item.first) { + setCorrectFirst((n) => n + 1) + addXp(XP.quizCorrect) + } + } else { + setStatus('wrong') + setHearts((h) => h - 1) + setQueue((q) => [...q, { ...item, first: false, order: shuffle(item.q.o.map((_, i) => i)) }]) + } + } + const next = () => { + if (status === 'wrong' && hearts <= 0) return setFailed(true) + if (idx + 1 >= queue.length) return onComplete(correctFirst, total) + setIdx(idx + 1) + setSel(null) + setStatus('ask') + } + useEnter(status === 'ask' ? check : next, !failed) + useEffect(() => { + const h = (e: KeyboardEvent) => { + const n = Number(e.key) + if (status === 'ask' && n >= 1 && n <= (item?.order.length ?? 0)) setSel(n - 1) + } + window.addEventListener('keydown', h) + return () => window.removeEventListener('keydown', h) + }, [status, item]) + + if (failed) + return ( + <Frame + progress={solved / total} + hearts={0} + onClose={exit} + footer={ + <Footer hints={false}> + <button class="btn ghost" onClick={exit}> + Back to path + </button> + </Footer> + } + > + <div class="done-screen"> + <div class="big" style={{ background: 'var(--bad-soft)', color: 'var(--bad)' }}> + <Icon name="heart" size={60} /> + </div> + <h1>Out of hearts</h1> + <p class="lead">Re-read the concepts and the guide for this module, then try again. Every miss shows you a gap worth knowing about.</p> + </div> + </Frame> + ) + + const correctIdx = item.order.indexOf(item.q.a) + return ( + <Frame + progress={solved / total} + hearts={hearts} + onClose={exit} + footer={ + status === 'ask' ? ( + <Footer> + <button class="btn track" disabled={sel === null} onClick={check}> + Check + </button> + </Footer> + ) : ( + <Footer + tone={status === 'right' ? 'ok' : 'bad'} + msg={ + <> + <b>{status === 'right' ? 'Correct!' : `Answer: ${item.q.o[item.q.a]}`}</b> + <span>{item.q.why}</span> + </> + } + > + <button class={status === 'right' ? 'btn ok' : 'btn red'} onClick={next}> + Continue + </button> + </Footer> + ) + } + > + <span class="pill"> + <Icon name="help" size={14} /> {title} + {!item.first && ' · retry'} + </span> + <h1 style={{ fontSize: '22px', lineHeight: 1.35 }}>{item.q.q}</h1> + <div class="options" role="radiogroup" aria-label="Answers"> + {item.order.map((oi, i) => { + const cls = ['option', status === 'ask' && sel === i && 'sel', status !== 'ask' && i === correctIdx && 'right', status === 'wrong' && sel === i && 'wrong'].filter(Boolean).join(' ') + return ( + <button key={i} class={cls} disabled={status !== 'ask'} onClick={() => setSel(i)} role="radio" aria-checked={sel === i}> + <span class="k">{i + 1}</span> + {item.q.o[oi]} + </button> + ) + })} + </div> + </Frame> + ) +} + +function Checkpoint({ s, exit, finish }: UnitProps) { + const p = useProgress() + const m = s.module + const openBuilds = m.build.filter((b) => !p.checked[b.id]).length + const yes = () => { + update((x) => ({ ...x, crowns: { ...x.crowns, [m.id]: true } })) + markDone(s.unitId, XP.checkpoint) + finish(`${m.title} mastered`, 'You earned a crown for this module.', true) + } + return ( + <Frame + progress={0.9} + onClose={exit} + footer={ + <Footer hints={false}> + <a class="btn ghost" href={s.guideUrl}> + Not yet + </a> + <button class="btn track" onClick={yes}> + Yes, I can + </button> + </Footer> + } + > + <span class="pill"> + <Icon name="trophy" size={14} /> Checkpoint · {m.label} + </span> + <h1>{m.title}</h1> + <div class="section-title">Can you do this without notes?</div> + <div class="card" style={{ fontSize: '18px', lineHeight: 1.6, fontWeight: 500, padding: '22px 24px', borderLeft: '4px solid var(--c)', maxWidth: '80ch' }} dangerouslySetInnerHTML={{ __html: m.checkpoint }} /> + {openBuilds > 0 && ( + <p class="lead" style={{ fontSize: '14.5px', color: 'var(--muted)', marginTop: '16px' }}> + {openBuilds} build {openBuilds === 1 ? 'exercise is' : 'exercises are'} still unticked for this module. Be honest with yourself: the checkpoint is what makes the next module easier. + </p> + )} + </Frame> + ) +} + +// ───────── entry ───────── + +export default function Session(s: SessionProps) { + const [startXp] = useState(() => totalXp(get())) + const p = useProgress() + const [finished, setFinished] = useState<null | { title: string; sub?: string; crown?: boolean }>(null) + const exit = () => { + location.href = s.backUrl + } + const finish = (title: string, sub?: string, crown?: boolean) => setFinished({ title, sub, crown }) + + useEffect(() => { + // opening a track's lesson makes it the track "up next" follows + update((x) => (x.aiTrack === s.track.id ? x : { ...x, aiTrack: s.track.id })) + }, [s.track.id]) + + if (finished) return <DoneScreen {...finished} xp={totalXp(p) - startXp} onContinue={exit} /> + + switch (s.kind) { + case 'concepts': + return <Concepts s={s} exit={exit} finish={finish} /> + case 'resources': + case 'build': + return <Checklist s={s} exit={exit} finish={finish} /> + case 'quiz': + return ( + <Quiz + questions={s.questions ?? []} + title={`Quiz · ${s.module.label}`} + exit={exit} + onComplete={(c, t) => { + update((x) => ({ ...x, quizBest: { ...x.quizBest, [s.module.id]: Math.max(x.quizBest[s.module.id] || 0, c / t) } })) + markDone(s.unitId, c === t ? XP.unitBonus : 0) + finish(c === t ? 'Perfect quiz!' : 'Quiz complete', `${c} of ${t} right on the first try.`) + }} + /> + ) + case 'checkpoint': + return <Checkpoint s={s} exit={exit} finish={finish} /> + } +} diff --git a/src/components/ai/Stepper.astro b/src/components/ai/Stepper.astro new file mode 100644 index 0000000..81e92f6 --- /dev/null +++ b/src/components/ai/Stepper.astro @@ -0,0 +1,29 @@ +--- +/* The five steps of one module. Static links; decorate.ts marks progress. */ +import Icon from '../Icon.astro'; +import { UNIT_LABEL, unitKinds, unitUrl, type Module, type Track, type UnitKind } from '../../lib/ai/course'; +import type { IconName } from '../../lib/icons'; + +interface Props { track: Track; module: Module } +const { track, module: m } = Astro.props; +const KIND_ICON: Record<UnitKind, IconName> = { concepts: 'bulb', resources: 'bookOpen', build: 'code', quiz: 'help', checkpoint: 'trophy' }; +--- +<div class="stepper"> + {unitKinds(m).map((k) => ( + <a + class:list={['step', k === 'checkpoint' && 'trophy']} + href={unitUrl(track, m, k)} + data-unit={`${m.id}/${k}`} + data-label={`${m.title}: ${UNIT_LABEL[k]}`} + data-kind-label={UNIT_LABEL[k]} + data-mod-label={m.label} + aria-label={`${m.title}: ${UNIT_LABEL[k]}`} + > + <span class="step-dot"> + <Icon name={KIND_ICON[k]} class="ic-kind" /> + {k !== 'checkpoint' && <Icon name="check" class="ic-done" />} + </span> + <span class="step-label">{UNIT_LABEL[k]}</span> + </a> + ))} +</div> diff --git a/src/components/ai/TrackTabs.astro b/src/components/ai/TrackTabs.astro new file mode 100644 index 0000000..b7b8b2e --- /dev/null +++ b/src/components/ai/TrackTabs.astro @@ -0,0 +1,20 @@ +--- +/* The five tracks as cards; the current one is highlighted. Progress filled in by decorate.ts. */ +import { tracks, trackUrl, units } from '../../lib/ai/course'; +interface Props { current?: string } +const { current } = Astro.props; +--- +<nav class="track-tabs" aria-label="Tracks"> + {tracks.map((t) => { + const ids = units.filter((u) => u.track === t.id).map((u) => u.id).join(','); + const mods = t.modules.map((m) => m.id).join(','); + return ( + <a class:list={['track-tab', `tc-${t.color}`, t.id === current && 'on']} href={trackUrl(t)} aria-current={t.id === current ? 'page' : undefined}> + <span class="kicker">{t.short}</span> + <b>{t.title}</b> + <div class="meter"><i data-meter-of={ids} style="width:0%"></i></div> + <small><span data-pct-of={ids}>0%</span> · <span data-crowns-of={mods}>0/{t.modules.length}</span> modules</small> + </a> + ); + })} +</nav> diff --git a/src/components/ai/ui.tsx b/src/components/ai/ui.tsx new file mode 100644 index 0000000..6c28191 --- /dev/null +++ b/src/components/ai/ui.tsx @@ -0,0 +1,37 @@ +/** Small pieces every AI Engineer island shares. */ +import { useEffect, useState } from 'preact/hooks' +import { ICONS, type IconName } from '../../lib/icons' +import { get, subscribe, type Progress } from '../../lib/progress' + +export function useProgress(): Progress { + const [p, setP] = useState<Progress>(get) + useEffect(() => subscribe(() => setP(get())), []) + return p +} + +export function Icon({ name, size = 20, class: cls, fill = 'none' }: { name: IconName; size?: number; class?: string; fill?: string }) { + return ( + <svg class={cls} width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke="currentColor" stroke-width={2} stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> + <path d={ICONS[name]} /> + </svg> + ) +} + +export const XP = { concepts: 5, coreResource: 10, optionalResource: 5, build: 25, unitBonus: 10, quizCorrect: 5, checkpoint: 50, paper: 15, project: 100 } + +export function shuffle<T>(xs: T[]): T[] { + const a = [...xs] + for (let i = a.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)) + ;[a[i], a[j]] = [a[j], a[i]] + } + return a +} + +/** A module counts as started once any of its units is done or any of its checklist items is ticked. */ +export function startedModules(p: Progress): Set<string> { + const s = new Set<string>() + for (const k of Object.keys(p.done)) s.add(k.split('/')[0]) + for (const k of Object.keys(p.checked)) if (!k.startsWith('paper:') && !k.startsWith('project:')) s.add(k.split(':')[0]) + return s +} diff --git a/src/layouts/AiLayout.astro b/src/layouts/AiLayout.astro new file mode 100644 index 0000000..8366dd4 --- /dev/null +++ b/src/layouts/AiLayout.astro @@ -0,0 +1,24 @@ +--- +/* Every AI Engineer page except the full-screen lesson steps: the app shell, + * the indigo accent, the progress rail (or the stat strip on narrower + * screens) and the script that paints progress onto the static markup. */ +import Base from './Base.astro'; +import Rail, { StatStrip } from '../components/ai/Rail'; +import { units } from '../lib/ai/course'; +import { SITE_NAME } from '../data/site'; +import '../styles/ai.css'; + +interface Props { title: string; description: string; where?: string; section?: 'ai' | 'hub' } +const { title, description, where = 'AI Engineer', section = 'ai' } = Astro.props; +--- +<Base section={section} where={where} title={`${title} · ${SITE_NAME}`} description={description}> + <div class="ai-page"> + <StatStrip client:only="preact" /> + <slot /> + </div> + <Rail slot="rail" units={units} client:only="preact" /> +</Base> + +<script> + import '../lib/ai/decorate'; +</script> diff --git a/src/layouts/Base.astro b/src/layouts/Base.astro index 7084a18..bb22006 100644 --- a/src/layouts/Base.astro +++ b/src/layouts/Base.astro @@ -2,20 +2,30 @@ import '../styles/tokens.css'; import '../styles/base.css'; import '../styles/site.css'; -import Masthead from '../components/Masthead.astro'; +import '../styles/app.css'; +import AppSidebar from '../components/AppSidebar.astro'; import SiteFooter from '../components/SiteFooter.astro'; +import SiteSearch from '../components/SiteSearch.astro'; +import ThemeToggle from '../components/ThemeToggle.astro'; interface Props { title: string; description: string; + /** Picks the accent: LeetCode pages are teal, the hub and AI Engineer indigo. */ + section?: 'hub' | 'leetcode' | 'ai'; + /** Shown at the left of the top bar. */ + where?: string; + /** A focused page (a lesson session) with no sidebar, top bar or footer. */ + bare?: boolean; } -const { title, description } = Astro.props; +const { title, description, section = 'hub', where, bare = false } = Astro.props; // Pages build as .html files (astro.config.mjs) but are served without the // extension, so the canonical address drops it: /leetcode/two-sum, not .html. const canonical = new URL(Astro.url.pathname.replace(/(index)?\.html$/, ''), Astro.site); +const hasRail = Astro.slots.has('rail'); --- <!doctype html> -<html lang="en"> +<html lang="en" data-section={section}> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> @@ -25,21 +35,36 @@ const canonical = new URL(Astro.url.pathname.replace(/(index)?\.html$/, ''), Ast <meta property="og:title" content={title} /> <meta property="og:description" content={description} /> <meta property="og:type" content="website" /> - <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'><text y='52' font-size='52'>📐</text></svg>" /> + <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> - <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Archivo:wght@600;700&family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;450;500;600&family=Noto+Sans+Myanmar:wght@400;500;600&display=swap" /> - <!-- Blocking on purpose: a stored theme has to land on <html> before the - first paint, or every visit starts with a flash of the wrong one. --> + <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&family=Noto+Sans+Myanmar:wght@400;500;600&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Sora:wght@600;700&display=swap" /> + <!-- Blocking on purpose: a stored theme and sidebar state have to land on + <html> before the first paint, or every visit starts with a flash. --> <script is:inline> try { var t = localStorage.getItem('learn-theme'); if (t === 'dark' || t === 'light') document.documentElement.setAttribute('data-theme', t); + if (localStorage.getItem('learn-nav') === 'collapsed') document.documentElement.setAttribute('data-nav', 'collapsed'); } catch (e) {} </script> </head> -<body> - <Masthead /> - <main><slot /></main> - <SiteFooter /> -</body> +{bare ? ( + <body class="bare"><slot /></body> +) : ( + <body> + <div class:list={['app', hasRail && 'has-rail']}> + <AppSidebar /> + <div class="app-main"> + <header class="app-top"> + <span class="app-where">{where}</span> + <SiteSearch /> + <ThemeToggle /> + </header> + <main><slot /></main> + <SiteFooter /> + </div> + {hasRail && <aside class="app-rail" aria-label="Your progress"><slot name="rail" /></aside>} + </div> + </body> +)} </html> diff --git a/src/layouts/Walkthrough.astro b/src/layouts/Walkthrough.astro index 907b557..7e1013c 100644 --- a/src/layouts/Walkthrough.astro +++ b/src/layouts/Walkthrough.astro @@ -56,10 +56,10 @@ const my = (v?: T) => (v == null || typeof v === 'string' ? undefined : v.my); const plain = (v: T) => en(v).replace(/<[^>]+>/g, ''); const lcUrl = (slug: string) => `https://leetcode.com/problems/${slug}/`; --- -<Base title={`${plain(p.title)} · ${SITE_NAME}`} description={p.summary}> +<Base section="leetcode" where="LeetCode" title={`${plain(p.title)} · ${SITE_NAME}`} description={p.summary}> <div class="shell"> <nav class="crumbs" aria-label="Breadcrumb"> - <a href="/">LeetCode</a><span>/</span> + <a href="/leetcode">LeetCode</a><span>/</span> <span>{plain(p.title)}</span> </nav> </div> @@ -201,7 +201,7 @@ const lcUrl = (slug: string) => `https://leetcode.com/problems/${slug}/`; <div class="shell"> <nav class="pager" aria-label="Lesson navigation"> - <a class="up" href="/"><span class="dir">Back to</span><span>All problems</span></a> + <a class="up" href="/leetcode"><span class="dir">Back to</span><span>All problems</span></a> </nav> </div> </Base> diff --git a/src/lessons/basic-calculator/style.css b/src/lessons/basic-calculator/style.css index a90ab3e..b1f3292 100644 --- a/src/lessons/basic-calculator/style.css +++ b/src/lessons/basic-calculator/style.css @@ -6,6 +6,6 @@ .bc-w{flex-wrap:wrap;gap:4px;margin-bottom:12px} .bc-w .cell{width:auto;min-width:30px;padding:0 6px;height:46px} .bc-w .cell.neg{background:var(--down-soft);border-color:var(--down);color:var(--ink)} -.bc-w .cell.op{cursor:pointer;font:inherit;font-family:"IBM Plex Mono",monospace;font-size:16px;background:var(--surface);border:1px solid var(--line-2);color:var(--ink)} +.bc-w .cell.op{cursor:pointer;font:inherit;font-family:var(--mono);font-size:16px;background:var(--surface);border:1px solid var(--line-2);color:var(--ink)} .bc-w .cell.op:hover{border-color:var(--accent)} .bc-w .cell.op:focus-visible{outline:2px solid var(--accent)} diff --git a/src/lessons/course-schedule/style.css b/src/lessons/course-schedule/style.css index 236eedd..b95d9ae 100644 --- a/src/lessons/course-schedule/style.css +++ b/src/lessons/course-schedule/style.css @@ -11,7 +11,7 @@ .g-head.hot{fill:var(--amber)} .g-head.bad{fill:var(--down)} .g-node circle{fill:var(--surface);stroke:var(--line-2);stroke-width:1.5} -.g-node text{fill:var(--ink);font-family:"IBM Plex Mono",monospace;font-size:13px;font-weight:500} +.g-node text{fill:var(--ink);font-family:var(--mono);font-size:13px;font-weight:500} .g-node.on circle{fill:var(--amber-soft);stroke:var(--amber)} .g-node.done circle{fill:var(--up-soft);stroke:var(--up)} .g-node.queued circle{fill:var(--accent-soft);stroke:var(--accent)} diff --git a/src/lessons/implement-trie-prefix-tree/style.css b/src/lessons/implement-trie-prefix-tree/style.css index 6579b42..a038619 100644 --- a/src/lessons/implement-trie-prefix-tree/style.css +++ b/src/lessons/implement-trie-prefix-tree/style.css @@ -1,5 +1,5 @@ /* Implement Trie: the trie itself is stage.js's trieOutline(), styled in kit.css. The part 1 widget's prefix field: */ -.tw-input{font-family:"IBM Plex Mono",monospace;font-size:14px;width:7.5em;padding:6px 9px;border-radius:7px; +.tw-input{font-family:var(--mono);font-size:14px;width:7.5em;padding:6px 9px;border-radius:7px; border:1px solid var(--line-2);background:var(--surface);color:var(--ink)} .tw-input:focus-visible{outline:2px solid var(--accent);outline-offset:1px} diff --git a/src/lessons/largest-rectangle-in-histogram/style.css b/src/lessons/largest-rectangle-in-histogram/style.css index 74d924a..880b063 100644 --- a/src/lessons/largest-rectangle-in-histogram/style.css +++ b/src/lessons/largest-rectangle-in-histogram/style.css @@ -8,4 +8,4 @@ .hg-u.bar{background:var(--ink-3)} .hg-u.in{background:var(--accent)} .hg-u.me{box-shadow:inset 0 0 0 2px var(--amber)} -.hg-lab{font-family:"IBM Plex Mono",monospace;font-size:10px;color:var(--ink-3);margin-top:3px} +.hg-lab{font-family:var(--mono);font-size:10px;color:var(--ink-3);margin-top:3px} diff --git a/src/lessons/merge-intervals/style.css b/src/lessons/merge-intervals/style.css index 20498f3..d3bd4f3 100644 --- a/src/lessons/merge-intervals/style.css +++ b/src/lessons/merge-intervals/style.css @@ -5,7 +5,7 @@ inline styles. */ .tl{display:flex;flex-direction:column;gap:5px;overflow-x:auto;padding-bottom:2px} .tl-row{display:flex;align-items:center;gap:8px} -.tl-lab{flex:none;min-width:4.6em;text-align:right;font-family:"IBM Plex Mono",monospace;font-size:11.5px;color:var(--ink-2)} +.tl-lab{flex:none;min-width:4.6em;text-align:right;font-family:var(--mono);font-size:11.5px;color:var(--ink-2)} .tl-cells{display:flex} .tl-c{display:block;flex:none;width:6px;height:14px} .tl-c.on{background:var(--line-2)} @@ -21,5 +21,5 @@ .tl-row.clear .tl-c.on{background:var(--accent);opacity:.55} .tl-row.cur .tl-lab{color:var(--amber);font-weight:600} /* the axis: a number under every fifth point */ -.tl-axis .tl-c{height:auto;position:relative;overflow:visible;white-space:nowrap;font-family:"IBM Plex Mono",monospace;font-size:9.5px;color:var(--ink-3)} +.tl-axis .tl-c{height:auto;position:relative;overflow:visible;white-space:nowrap;font-family:var(--mono);font-size:9.5px;color:var(--ink-3)} .tl-sep{height:1px;background:var(--line);margin:2px 0} diff --git a/src/lessons/merge-k-sorted-lists/style.css b/src/lessons/merge-k-sorted-lists/style.css index bf7b151..b6bef4a 100644 --- a/src/lessons/merge-k-sorted-lists/style.css +++ b/src/lessons/merge-k-sorted-lists/style.css @@ -8,7 +8,7 @@ .mk-fill{display:block;height:12px;border-radius:3px;flex:none} .mk-bar.one .mk-fill{background:var(--amber)} .mk-bar.two .mk-fill{background:var(--accent)} -.mk-n{font-family:"IBM Plex Mono",monospace;font-size:11.5px;color:var(--ink-2)} +.mk-n{font-family:var(--mono);font-size:11.5px;color:var(--ink-2)} .mk-w1{width:6px} .mk-w2{width:12px} .mk-w3{width:18px} diff --git a/src/lessons/trapping-rain-water/style.css b/src/lessons/trapping-rain-water/style.css index 879d25e..8d758e5 100644 --- a/src/lessons/trapping-rain-water/style.css +++ b/src/lessons/trapping-rain-water/style.css @@ -5,7 +5,7 @@ .land .u{display:block;width:20px;height:13px;border-radius:2px;margin-top:1px} .land .u.rock{background:var(--ink-3)} .land .u.water{background:var(--accent-soft);box-shadow:inset 0 0 0 1px var(--accent)} -.land .lab{font-family:"IBM Plex Mono",monospace;font-size:10px;color:var(--ink-3);margin-top:3px} +.land .lab{font-family:var(--mono);font-size:10px;color:var(--ink-3);margin-top:3px} .land .col.cur{outline:2px solid var(--amber);outline-offset:0} .land .col[role="button"]{cursor:pointer} .land .col[role="button"]:focus-visible{outline:2px solid var(--accent)} diff --git a/src/lessons/word-ladder/style.css b/src/lessons/word-ladder/style.css index 3fdd3a7..5b1a4d5 100644 --- a/src/lessons/word-ladder/style.css +++ b/src/lessons/word-ladder/style.css @@ -3,6 +3,6 @@ .wl .cell.set{background:var(--accent-soft);border-color:var(--accent);color:var(--ink)} .wl-w{margin-bottom:10px} .wl-w .q-arr{align-items:center;margin-bottom:6px} -.wl-lv{font-family:"IBM Plex Mono",monospace;font-size:11px;color:var(--ink-3);width:18px;flex:none} +.wl-lv{font-family:var(--mono);font-size:11px;color:var(--ink-3);width:18px;flex:none} .wl-list{flex-wrap:wrap;gap:6px} -.wl-lab{font-family:"IBM Plex Mono",monospace;font-size:11px;color:var(--ink-3);margin-right:4px} +.wl-lab{font-family:var(--mono);font-size:11px;color:var(--ink-3);margin-right:4px} diff --git a/src/lessons/x-sum/style.css b/src/lessons/x-sum/style.css index a6c4d29..a9316f1 100644 --- a/src/lessons/x-sum/style.css +++ b/src/lessons/x-sum/style.css @@ -5,14 +5,14 @@ .shelf-top{background:var(--accent-soft);border-color:var(--accent)} .shelf-rest{background:var(--sunk);border-style:dashed} .shelf-head{display:flex;justify-content:space-between;align-items:baseline;gap:8px;margin-bottom:9px} -.shelf-name{font-family:"IBM Plex Mono",monospace;font-size:11.5px;letter-spacing:.12em;font-weight:600} +.shelf-name{font-family:var(--mono);font-size:11.5px;letter-spacing:.12em;font-weight:600} .shelf-top .shelf-name{color:var(--accent)} .shelf-rest .shelf-name{color:var(--ink-3)} .shelf-note{font-size:11.5px;color:var(--ink-3)} .cards{display:flex;flex-wrap:wrap;gap:7px;min-height:52px;align-items:flex-start} .kard{ display:flex;flex-direction:column;align-items:center;gap:1px;padding:6px 11px;border-radius:7px; - background:var(--surface);border:1px solid var(--line-2);font-family:"IBM Plex Mono",monospace; + background:var(--surface);border:1px solid var(--line-2);font-family:var(--mono); font-variant-numeric:tabular-nums; } .kard .face{font-size:17px;font-weight:600;color:var(--ink);letter-spacing:.01em} @@ -29,7 +29,7 @@ .barrier{ display:flex;align-items:center;gap:10px;margin-block:9px; - font-family:"IBM Plex Mono",monospace;font-size:11px;color:var(--ink-3); + font-family:var(--mono);font-size:11px;color:var(--ink-3); } .barrier::before,.barrier::after{content:"";height:1px;background:var(--line-2);flex:1} .barrier.broken{color:var(--amber);font-weight:500} @@ -43,15 +43,15 @@ .bf-step.pending, .bf-step.pending *{color:var(--ink-3)} .bf-step.active{background:var(--surface);border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-soft)} .bf-step h5{margin-bottom:9px;color:var(--ink-2)} -.bf-step h5 .n{font-family:"IBM Plex Mono",monospace;color:var(--accent);margin-right:6px} +.bf-step h5 .n{font-family:var(--mono);color:var(--accent);margin-right:6px} .bars{display:flex;flex-direction:column;gap:5px} -.bar-row{display:grid;grid-template-columns:34px 1fr 30px;align-items:center;gap:8px;font-family:"IBM Plex Mono",monospace;font-size:12.5px;font-variant-numeric:tabular-nums} +.bar-row{display:grid;grid-template-columns:34px 1fr 30px;align-items:center;gap:8px;font-family:var(--mono);font-size:12.5px;font-variant-numeric:tabular-nums} .bar-track{background:var(--surface);border:1px solid var(--line);border-radius:4px;height:15px;overflow:hidden} .bar-fill{height:100%;background:var(--accent);opacity:.8} .bar-row.cut .bar-fill{background:var(--ink-3);opacity:.45} .rank{display:flex;flex-wrap:wrap;align-items:center;gap:7px} .cutline{ - font-family:"IBM Plex Mono",monospace;font-size:10.5px;letter-spacing:.06em;color:var(--down); + font-family:var(--mono);font-size:10.5px;letter-spacing:.06em;color:var(--down); border-left:2px dashed var(--down);padding-left:7px;align-self:stretch;display:flex;align-items:center; } .kard.dropped{border-style:dashed;background:transparent} @@ -71,7 +71,7 @@ .heap-row{display:flex;flex-wrap:wrap;gap:6px;justify-content:center} .hcard{ display:flex;flex-direction:column;align-items:center;gap:1px;padding:5px 10px;border-radius:7px; - background:var(--surface);border:1px solid var(--line-2);font-family:"IBM Plex Mono",monospace; + background:var(--surface);border:1px solid var(--line-2);font-family:var(--mono); font-variant-numeric:tabular-nums;position:relative; } .hcard .face{font-size:16px;font-weight:600;color:var(--ink)} diff --git a/src/lib/ai/course.ts b/src/lib/ai/course.ts new file mode 100644 index 0000000..1c3168d --- /dev/null +++ b/src/lib/ai/course.ts @@ -0,0 +1,244 @@ +/* The AI Engineer course, read from the markdown in /course at build time. + * The markdown is the source of truth: edit a track's README and the pages + * follow on the next build. Only Astro pages import this module; islands get + * the slices they need as props, so the markdown never ships to the browser. */ +import { marked } from 'marked' +import { quizzes } from './quizzes' + +const files = import.meta.glob('/course/**/*.md', { query: '?raw', import: 'default', eager: true }) as Record<string, string> +const read = (p: string) => { + const s = files[`/course/${p}`] + if (s == null) throw new Error(`course file missing: ${p}`) + return s +} + +export type Resource = { id: string; core: boolean; html: string; sub: string[] } +export type BuildItem = { id: string; html: string } +export type Module = { + id: string + key: string + slug: string + label: string + title: string + star: boolean + weeks: string | null + why: string + concepts: string[] + resources: Resource[] + build: BuildItem[] + checkpoint: string + notes?: string + guideHtml: string +} +export type Track = { id: string; slug: string; title: string; short: string; subtitle: string; color: string; modules: Module[] } +export type Paper = { id: string; star: boolean; title: string; by: string; url: string | null } +export type PaperSection = { title: string; papers: Paper[] } +export type Project = { id: string; title: string; template: boolean; html: string } +export type UnitKind = 'concepts' | 'resources' | 'build' | 'quiz' | 'checkpoint' + +const hash = (s: string) => { + let h = 5381 + for (const c of s) h = ((h << 5) + h + c.codePointAt(0)!) >>> 0 + return h.toString(36) +} +const linkOut = (html: string) => html.replace(/<a href="(https?:)/g, '<a target="_blank" rel="noopener" href="$1') +const inline = (md: string) => linkOut(marked.parseInline(md.trim()) as string) +// Task-list boxes in the guides are decoration (progress is ticked in the Build +// step), so they become plain markers instead of unlabelled, disabled inputs. +const block = (md: string) => + linkOut(marked.parse(md) as string).replace(/<input (checked="" )?disabled="" type="checkbox">\s*/g, (_, on) => `<span class="task" aria-hidden="true">${on ? '☑' : '☐'}</span> `) + +const TRACKS = [ + { id: 'setup', slug: 'setup', file: '00-setup/README.md', title: 'Setup', short: 'Setup', subtitle: 'Tools, GPUs and notes. Week 0.', color: 'slate', heading: /^## (?!Checkpoint)(\d+)\. (.+)$/ }, + { id: 't1', slug: 'track-1', file: 'track-1-ai-application-engineer/README.md', title: 'AI Application Engineer', short: 'Track 1', subtitle: 'Use models well: APIs, RAG, agents, MCP, evals.', color: 'teal', heading: /^## (1\.\d+) (.+)$/ }, + { id: 't2', slug: 'track-2', file: 'track-2-ml-systems-engineer/README.md', title: 'ML / AI Systems Engineer', short: 'Track 2', subtitle: 'Train, tune, optimise and serve models.', color: 'indigo', heading: /^### (2\.\d+) (.+)$/ }, + { id: 't3', slug: 'track-3', file: 'track-3-research-engineer/README.md', title: 'Research Engineer', short: 'Track 3', subtitle: 'Understand and improve models.', color: 'rose', heading: /^### (3\.\d+) (.+)$/ }, + { id: 'math', slug: 'math', file: 'math/README.md', title: 'Math Track', short: 'Math', subtitle: 'Runs alongside all three tracks.', color: 'amber', heading: /^## Level (\d): (.+)$/ }, +] + +function weeksTable(md: string) { + const weeks: Record<string, string> = {} + for (const m of md.matchAll(/^\| (\d+\.\d+) \| [^|]+\| (\d[\d–-]*) \|/gm)) weeks[m[1]] = m[2] + return weeks +} + +function parseBody(lines: string[], moduleId: string) { + // checklist ids carry the module id, so "has this module been started?" is a prefix test + const id = (s: string) => `${moduleId}:${hash(s)}` + const mod = { why: '', concepts: [] as string[], resources: [] as Resource[], build: [] as BuildItem[], checkpoint: '', notes: undefined as string | undefined } + let section = '' + let last: Resource | null = null + for (const raw of lines) { + const line = raw.trimEnd() + const t = line.trim() + if (!t || t === '---') continue + let m: RegExpMatchArray | null + if ((m = t.match(/^\*\*Why[^*]*\*\*:?\s*(.*)$/))) { + mod.why = inline(m[1]) + section = 'why' + } else if ((m = t.match(/^\*\*Concepts:\*\*\s*(.*)$/))) { + mod.concepts.push(...m[1].split(/;\s*/).map((s) => s.replace(/\.$/, '').trim()).filter(Boolean).map(inline)) + section = 'concepts' + } else if ((m = t.match(/^\*\*Checkpoint:\*\*\s*(.*)$/))) { + mod.checkpoint = inline(m[1]) + section = 'checkpoint' + } else if (/^\*\*(Learn|Topics|Build|Method|Communities & programs)\*\*/.test(t)) { + section = t.match(/^\*\*([^*]+)\*\*/)![1].toLowerCase() + } else if (/^#{3,4} /.test(t)) { + section = 'topics' // math sub-sections like "### 2a. Linear algebra" + } else if ((m = t.match(/^- \[[ x]\] (.+)$/))) { + mod.build.push({ id: id(m[1]), html: inline(m[1]) }) + } else if ((m = t.match(/^- \*(Core|Optional):\*\s*(.+)$/))) { + last = { id: id(m[2]), core: m[1] === 'Core', html: inline(m[2]), sub: [] } + mod.resources.push(last) + } else if (last && /^\s+\d+\. /.test(line)) { + last.sub.push(inline(t.replace(/^\d+\.\s*/, ''))) + } else if ((m = t.match(/^- (.+)$/))) { + if (section === 'topics' || section === 'concepts') mod.concepts.push(inline(m[1])) + else if (section === 'build') mod.build.push({ id: id(m[1]), html: inline(m[1]) }) + else if (section === 'communities & programs') mod.resources.push({ id: id(m[1]), core: false, html: inline(m[1]), sub: [] }) + else if (section === 'method' || section === '') mod.notes = (mod.notes || '') + `<li>${inline(m[1])}</li>` + } else if ((m = t.match(/^\d+\. (.+)$/)) && section === 'method') { + mod.notes = (mod.notes || '') + `<li>${inline(m[1])}</li>` + } else if (section === 'why' && !t.startsWith('*') && !t.startsWith('|')) { + mod.why += ' ' + inline(t) + } + } + mod.why = mod.why.trim().replace(/^([a-z])/, (c) => c.toUpperCase()) + return mod +} + +function parseTrack(cfg: (typeof TRACKS)[number]): Track { + const md = read(cfg.file) + const weeks = weeksTable(md) + const raw: { key: string; title: string; star: boolean; lines: string[] }[] = [] + let cur: (typeof raw)[number] | null = null + let stop = false + for (const line of md.split('\n')) { + const m = line.match(cfg.heading) + if (m) { + cur = { key: m[1], title: m[2].replace(/★/g, '').replace(/\(.*?\)\s*$/, '').trim(), star: line.includes('★'), lines: [] } + raw.push(cur) + stop = false + continue + } + if (/^## /.test(line) && cur) { + if (cfg.id === 'setup' && /^## Checkpoint/.test(line)) { + cur = { key: 'ck', title: 'Setup checkpoint', star: false, lines: [] } + raw.push(cur) + continue + } + stop = true // a level-2 heading that isn't a module ends the module + } + if (cur && !stop) cur.lines.push(line) + } + return { + id: cfg.id, + slug: cfg.slug, + title: cfg.title, + short: cfg.short, + subtitle: cfg.subtitle, + color: cfg.color, + modules: raw.map((r) => { + const id = `${cfg.id}-${r.key}` + const slug = cfg.id === 'math' ? `level-${r.key}` : cfg.id === 'setup' ? (r.key === 'ck' ? 'checkpoint' : `step-${r.key}`) : r.key.replace('.', '-') // no dots in URLs: '2.7' would read as a file extension + const label = cfg.id === 'math' ? `Level ${r.key}` : cfg.id === 'setup' ? (r.key === 'ck' ? 'Checkpoint' : `Step ${r.key}`) : r.key + return { + id, + key: r.key, + slug, + label, + title: r.title, + star: r.star, + weeks: weeks[r.key] ?? null, + ...parseBody(r.lines, id), + guideHtml: block(r.lines.join('\n').replace(/^---\s*$/gm, '')), + } + }), + } +} + +function parsePapers(): PaperSection[] { + const sections: PaperSection[] = [] + let cur: PaperSection | null = null + for (const line of read('track-3-research-engineer/papers.md').split('\n')) { + let m: RegExpMatchArray | null + if ((m = line.match(/^## (\d+)\. (.+)$/))) { + cur = { title: m[2], papers: [] } + sections.push(cur) + continue + } + if (line.startsWith('## ')) cur = null + if (cur && (m = line.match(/^- \[[ x]\] (.+)$/))) { + const text = m[1] + if (text.startsWith('*')) continue + const title = text.match(/\*\*(.+?)\*\*/)?.[1] ?? text + cur.papers.push({ + id: `paper:${hash(title)}`, + star: text.includes('⭐'), + title, + by: text.split(':')[0].replace('⭐', '').trim(), + url: text.match(/<(https?:[^>]+)>/)?.[1] ?? null, + }) + } + } + return sections +} + +function parseProjects(): Project[] { + const [body, template = ''] = read('projects/README.md').split(/^## Write-up template\s*$/m) + const parts: Project[] = body + .split(/^## /m) + .slice(1) + .map((p) => { + const [first, ...rest] = p.split('\n') + return { id: `project:${hash(first)}`, title: first.trim(), template: false, html: block(rest.join('\n').replace(/^---\s*$/gm, '')) } + }) + if (template) parts.push({ id: 'project:template', title: 'Write-up template', template: true, html: block(template) }) + return parts +} + +export const tracks: Track[] = TRACKS.map(parseTrack) +export const papers = parsePapers() +export const projects = parseProjects() + +// ───────── units: the five steps of every module ───────── + +export const UNIT_LABEL: Record<UnitKind, string> = { concepts: 'Concepts', resources: 'Learn', build: 'Build', quiz: 'Quiz', checkpoint: 'Checkpoint' } +export const UNIT_SLUG: Record<UnitKind, string> = { concepts: 'concepts', resources: 'learn', build: 'build', quiz: 'quiz', checkpoint: 'checkpoint' } + +export const BASE = '/ai-engineer' +export const trackUrl = (t: Track) => `${BASE}/${t.slug}` +export const moduleUrl = (t: Track, m: Module) => `${BASE}/${t.slug}/${m.slug}` +export const unitUrl = (t: Track, m: Module, k: UnitKind) => `${moduleUrl(t, m)}/${UNIT_SLUG[k]}` + +export function unitKinds(m: Module): UnitKind[] { + const k: UnitKind[] = ['concepts'] + if (m.resources.length) k.push('resources') + if (m.build.length) k.push('build') + if (quizzes[m.id]?.length) k.push('quiz') + if (m.checkpoint) k.push('checkpoint') + return k +} + +/** What the browser needs to know about one unit: enough for progress, "up next" and links. */ +export type UnitRef = { id: string; kind: UnitKind; label: string; url: string; module: string; moduleTitle: string; moduleLabel: string; track: string; trackShort: string; color: string } + +export const units: UnitRef[] = tracks.flatMap((t) => + t.modules.flatMap((m) => + unitKinds(m).map((k) => ({ + id: `${m.id}/${k}`, + kind: k, + label: UNIT_LABEL[k], + url: unitUrl(t, m, k), + module: m.id, + moduleTitle: m.title, + moduleLabel: m.label, + track: t.id, + trackShort: t.short, + color: t.color, + })), + ), +) + +export const trackColor = (trackId: string) => tracks.find((t) => t.id === trackId)?.color ?? 'indigo' diff --git a/src/lib/ai/decorate.ts b/src/lib/ai/decorate.ts new file mode 100644 index 0000000..90fb2d2 --- /dev/null +++ b/src/lib/ai/decorate.ts @@ -0,0 +1,59 @@ +/* Paints saved progress onto the prerendered AI Engineer pages. The pages are + * static, so they ship with every step looking "not started"; this marks the + * done ones, the current one, crowns and percentages, and points the + * Continue button at the next step. Markup contract: + * + * [data-unit="t1-1.4/quiz"] a step (its href is the step's page) + * [data-mod="t1-1.4"] a module card (gets crowned/started/current) + * [data-pct-of="id,id,…"] text set to the % of those units done + * [data-meter-of="id,id,…"] width set to that % + * [data-crowns-of="mod,mod,…"] text set to "n/total" + * [data-continue] link pointed at the first unfinished step + * [data-ai-track="t1"] visiting the page makes it the current track */ +import { get, subscribe, update } from '../progress' + +function paint() { + const p = get() + const steps = [...document.querySelectorAll<HTMLElement>('[data-unit]')] + // pages listing several tracks continue in the track you were last in + const inTrack = steps.filter((s) => s.dataset.unit!.startsWith(`${p.aiTrack}-`)) + const current = (inTrack.length ? inTrack : steps).find((s) => !p.done[s.dataset.unit!]) ?? steps.find((s) => !p.done[s.dataset.unit!]) + steps.forEach((s, i) => { + const done = !!p.done[s.dataset.unit!] + s.classList.toggle('done', done) + s.classList.toggle('current', s === current) + const prev = steps[i - 1] + s.classList.toggle('linked', !!prev && prev.parentElement === s.parentElement && !!p.done[prev.dataset.unit!]) + s.setAttribute('aria-label', `${s.dataset.label}${done ? ' (done)' : s === current ? ' (next)' : ''}`) + }) + const curMod = current?.dataset.unit?.split('/')[0] + document.querySelectorAll<HTMLElement>('[data-mod]').forEach((m) => { + const id = m.dataset.mod! + m.classList.toggle('crowned', !!p.crowns[id]) + m.classList.toggle('current', id === curMod) + m.classList.toggle('started', Object.keys(p.done).some((k) => k.startsWith(id + '/')) || Object.keys(p.checked).some((k) => k.startsWith(id + ':'))) + }) + const pct = (ids: string) => { + const list = ids.split(',').filter(Boolean) + return list.length ? Math.round((list.filter((u) => p.done[u]).length / list.length) * 100) : 0 + } + document.querySelectorAll<HTMLElement>('[data-pct-of]').forEach((e) => (e.textContent = `${pct(e.dataset.pctOf!)}%`)) + document.querySelectorAll<HTMLElement>('[data-meter-of]').forEach((e) => (e.style.width = `${pct(e.dataset.meterOf!)}%`)) + document.querySelectorAll<HTMLElement>('[data-crowns-of]').forEach((e) => { + const mods = e.dataset.crownsOf!.split(',').filter(Boolean) + e.textContent = `${mods.filter((m) => p.crowns[m]).length}/${mods.length}` + }) + document.querySelectorAll<HTMLAnchorElement>('[data-continue]').forEach((a) => { + if (!current) return void (a.hidden = true) + a.hidden = false + a.href = (current as HTMLAnchorElement).href + const label = a.querySelector('[data-continue-label]') + if (label) label.textContent = `${current.dataset.modLabel} ${current.dataset.kindLabel}` + }) +} + +paint() +subscribe(paint) + +const track = document.querySelector<HTMLElement>('[data-ai-track]')?.dataset.aiTrack +if (track && get().aiTrack !== track) update((p) => ({ ...p, aiTrack: track })) diff --git a/src/lib/ai/flashcards.ts b/src/lib/ai/flashcards.ts new file mode 100644 index 0000000..ae093a5 --- /dev/null +++ b/src/lib/ai/flashcards.ts @@ -0,0 +1,101 @@ +// Spaced-repetition cards. `module` controls when a card unlocks: it joins your review +// deck once you've started that module. +export type Card = { id: string; module: string; front: string; back: string } + +const c = (module: string, front: string, back: string): Card => ({ id: `${module}:${front}`, module, front, back }) + +export const cards: Card[] = [ + c('t1-1.1', 'Token', 'The unit a model reads and writes: a word piece produced by the tokenizer (BPE). Cost and context limits are counted in tokens.'), + c('t1-1.1', 'Logits', 'Raw, unnormalised scores the model outputs for every token in the vocabulary before softmax.'), + c('t1-1.1', 'Temperature', 'Divides the logits before softmax. Low = sharper, more deterministic; high = flatter, more random.'), + c('t1-1.1', 'Top-p (nucleus) sampling', 'Sample only from the smallest set of tokens whose probabilities add up to p.'), + c('t1-1.1', 'Context window', 'The maximum number of tokens (input + output) the model can attend to in one call.'), + c('t1-1.2', 'Prompt caching', 'Reusing the provider-side processed prefix of a prompt across calls, cutting cost and latency for repeated context.'), + c('t1-1.2', 'Tool use / function calling', 'The model emits a structured request to call a function you define; your code runs it and returns the result.'), + c('t1-1.3', 'Few-shot prompting', 'Including worked input→output examples in the prompt to show the model the task format.'), + c('t1-1.3', 'Context engineering', 'Deciding which information enters the context window, in what form and order, so the model can do the task.'), + c('t1-1.4', 'Embedding', 'A dense vector representing meaning; similar texts end up close together (high cosine similarity).'), + c('t1-1.4', 'BM25', 'A classic keyword ranking function based on term frequency and inverse document frequency, with length normalisation.'), + c('t1-1.4', 'Hybrid search', 'Combining keyword (BM25) and vector retrieval, often merged with reciprocal rank fusion.'), + c('t1-1.4', 'Reranker', 'A slower, more accurate model (often a cross-encoder) that reorders a shortlist of retrieved candidates.'), + c('t1-1.4', 'HNSW', 'Hierarchical Navigable Small World: a graph-based approximate nearest-neighbour index used by vector stores like pgvector.'), + c('t1-1.4', 'recall@k', 'The fraction of queries where at least one relevant item appears in the top k results.'), + c('t1-1.5', 'Agent loop', 'Model → tool call → tool result → model … until the model produces a final answer or hits the step limit.'), + c('t1-1.5', 'MCP', 'Model Context Protocol: an open standard for exposing tools, resources and prompts to AI clients through servers.'), + c('t1-1.5', 'Orchestrator–workers', 'A pattern where a lead model breaks a task down and delegates subtasks to worker models, then combines the results.'), + c('t1-1.6', 'Error analysis', 'Reading real traces, noting failures and grouping them into categories to decide what to measure and fix.'), + c('t1-1.6', 'LLM-as-judge', 'Using a model to grade outputs against a rubric. It must be validated against human labels.'), + c('t1-1.7', 'Prompt injection', 'Untrusted text (from a user, document, web page or tool output) containing instructions that hijack the model.'), + c('t1-1.7', 'Lethal trifecta', 'Private data access + untrusted content + an exfiltration channel. Together they let injections steal data.'), + c('t1-1.8', 'Durable execution', 'Workflow state is persisted (e.g. Temporal), so long multi-step processes survive crashes and resume.'), + c('t1-1.8', 'Human-in-the-loop interrupt', 'Pausing an agent graph or workflow until a person approves, edits or rejects a proposed action.'), + + c('t2-2.1', 'Broadcasting', 'Automatic expansion of size-1 dimensions so tensors of different shapes can be combined elementwise.'), + c('t2-2.1', 'Autograd', 'PyTorch records operations on tensors and computes gradients automatically with .backward().'), + c('t2-2.2', 'Backpropagation', 'Computing gradients by applying the chain rule backwards through the computation graph.'), + c('t2-2.2', 'Chain rule', 'd/dx f(g(x)) = f′(g(x)) · g′(x). Upstream gradient × local gradient.'), + c('t2-2.3', 'Overfitting', 'Low training loss but high validation loss: the model memorises instead of generalising.'), + c('t2-2.3', 'Residual connection', 'y = x + f(x). It gives gradients a direct path and makes deep nets trainable.'), + c('t2-2.3', 'LayerNorm / RMSNorm', 'Normalise each token\'s activation vector. RMSNorm skips mean-centring and is cheaper.'), + c('t2-2.3', 'Weight decay', 'Shrinking weights towards zero each step (decoupled in AdamW) to regularise.'), + c('t2-2.4', 'Self-attention', 'softmax(QKᵀ/√d)·V. Each token mixes information from other tokens, weighted by relevance.'), + c('t2-2.4', 'Causal mask', 'Sets attention scores to future positions to −∞ so tokens only attend to the past.'), + c('t2-2.4', 'KV cache', 'Stored keys and values of previous tokens, so each decode step only computes the new token.'), + c('t2-2.4', 'RoPE', 'Rotary positional embeddings: encode position by rotating Q and K vectors, so attention depends on relative position.'), + c('t2-2.4', 'BPE', 'Byte Pair Encoding: build a vocabulary by repeatedly merging the most frequent adjacent symbol pairs.'), + c('t2-2.4', 'Perplexity', 'exp(average cross-entropy per token). Lower means the model is less "surprised" by the text.'), + c('t2-2.5', 'LoRA', 'Freeze W; train a low-rank update ΔW = B·A (rank r ≪ d). Few trainable parameters, mergeable after training.'), + c('t2-2.5', 'QLoRA', 'LoRA on top of a 4-bit (NF4) quantised frozen base model, so large models fine-tune on one GPU.'), + c('t2-2.5', 'DPO', 'Direct Preference Optimization: train on chosen/rejected pairs with a closed-form loss, with no reward model or RL loop.'), + c('t2-2.5', 'SFT', 'Supervised fine-tuning on input→ideal output pairs (instruction data).'), + c('t2-2.6', 'Arithmetic intensity', 'FLOPs per byte of memory moved. Low = memory-bound; high = compute-bound.'), + c('t2-2.6', 'Roofline model', 'Achievable performance = min(peak compute, bandwidth × arithmetic intensity).'), + c('t2-2.6', 'MFU', 'Model FLOPs utilisation: achieved model FLOPs/sec ÷ hardware peak.'), + c('t2-2.6', 'Kernel fusion', 'Combining several ops into one GPU kernel so intermediate results never leave on-chip memory.'), + c('t2-2.6', 'bf16', '16-bit float with fp32\'s exponent range (8 bits) but less precision. Standard for training without loss scaling.'), + c('t2-2.7', 'Prefill vs decode', 'Prefill processes the prompt in parallel (compute-heavy); decode generates one token at a time (memory-bound).'), + c('t2-2.7', 'TTFT', 'Time to first token: latency until the first output token. Dominated by queueing + prefill.'), + c('t2-2.7', 'Continuous batching', 'Scheduling at the iteration level: sequences join and leave the running batch every step.'), + c('t2-2.7', 'PagedAttention', 'Store the KV cache in fixed-size blocks (like OS pages) to avoid fragmentation and allow sharing.'), + c('t2-2.7', 'Speculative decoding', 'A draft model proposes k tokens; the target model verifies them in one pass, giving the same output distribution faster.'), + c('t2-2.7', 'AWQ / GPTQ', 'Post-training weight quantisation methods (often 4-bit) that keep accuracy by protecting important weights or correcting errors.'), + c('t2-2.8', 'All-reduce', 'A collective operation where every GPU ends up with the sum (or mean) of all GPUs\' tensors. Used to sync gradients.'), + c('t2-2.8', 'ZeRO / FSDP', 'Shard optimizer states (stage 1), gradients (2) and parameters (3) across data-parallel GPUs.'), + c('t2-2.8', 'Tensor parallelism', 'Split individual weight matrices across GPUs; needs fast interconnect (NVLink).'), + c('t2-2.8', 'Pipeline parallelism', 'Split layers into stages on different GPUs, with micro-batches flowing through to reduce idle "bubbles".'), + c('t2-2.8', 'Activation checkpointing', 'Drop activations in the forward pass and recompute them during backward, trading compute for memory.'), + c('t2-2.10', 'DCGM exporter', 'NVIDIA tool exposing GPU metrics (utilisation, memory, temperature, XID errors) to Prometheus.'), + c('t2-2.10', 'KEDA', 'Kubernetes event-driven autoscaling: scale workloads on external metrics such as queue length.'), + c('t2-2.10', 'Taints & tolerations', 'Taints repel pods from nodes (e.g. GPU nodes); only pods with matching tolerations can schedule there.'), + + c('t3-3.1', 'Bias–variance tradeoff', 'Error = bias² + variance + noise. Simple models underfit (bias); complex ones overfit (variance).'), + c('t3-3.1', 'MAP estimation', 'Maximise likelihood × prior. A Gaussian prior gives L2 regularisation.'), + c('t3-3.1', 'Double descent', 'Test error rises near the interpolation threshold, then falls again as models grow even larger.'), + c('t3-3.2', 'Chinchilla scaling', 'Compute-optimal: scale parameters and tokens together, roughly 20 tokens per parameter.'), + c('t3-3.2', 'μP', 'A parametrisation under which optimal hyperparameters transfer from small to large widths.'), + c('t3-3.2', 'Grokking', 'Delayed generalisation: test accuracy jumps long after training accuracy reached 100%.'), + c('t3-3.4', 'Policy gradient', '∇J(θ) = E[∇log π_θ(a|s) · A(s,a)]. Push up the probability of actions with positive advantage.'), + c('t3-3.4', 'Advantage', 'A(s,a) = Q(s,a) − V(s): how much better an action is than average in that state.'), + c('t3-3.4', 'PPO', 'Policy optimisation with a clipped probability ratio that keeps updates small and stable.'), + c('t3-3.5', 'GRPO', 'Group Relative Policy Optimization: sample a group of answers per prompt and use within-group normalised rewards as advantages. No value model.'), + c('t3-3.5', 'Reward hacking', 'The policy exploits flaws in the reward signal instead of achieving the intended goal.'), + c('t3-3.5', 'RLVR', 'RL with verifiable rewards: rewards come from automatic checkers (unit tests, math answers).'), + c('t3-3.6', 'Residual stream', 'The running vector each layer reads from and writes to. A shared communication channel inside the transformer.'), + c('t3-3.6', 'Induction head', 'An attention head that completes patterns: after "A B … A", it predicts "B".'), + c('t3-3.6', 'Superposition', 'Representing more features than dimensions using nearly orthogonal directions, which causes polysemantic neurons.'), + c('t3-3.6', 'Activation patching', 'Replace an activation with its value from another input to test whether that component causally matters.'), + + c('math-1', 'Dot product', 'a·b = Σ aᵢbᵢ = ‖a‖‖b‖cos θ. It measures alignment.'), + c('math-1', 'Softmax', 'softmax(x)ᵢ = e^{xᵢ} / Σⱼ e^{xⱼ}. Turns logits into a probability distribution.'), + c('math-1', 'Standard error', 'σ/√n: the uncertainty of a sample mean.'), + c('math-2', 'Cross-entropy', 'H(p,q) = −Σ p log q. As a loss with one-hot targets: −log q(correct class).'), + c('math-2', 'KL divergence', 'KL(P‖Q) = Σ P log(P/Q) ≥ 0. Asymmetric "extra bits" from using Q in place of P.'), + c('math-2', 'Entropy', 'H(P) = −Σ P log P. The average uncertainty or surprise of a distribution.'), + c('math-2', 'MLE', 'Maximum likelihood estimation: pick parameters that make the observed data most probable.'), + c('math-2', 'Jacobian', 'The matrix of all partial derivatives of a vector function. Its shape follows [outputs × inputs].'), + c('math-2', 'SVD', 'M = UΣVᵀ. Truncating to the top r singular values gives the best rank-r approximation.'), + c('math-2', 'Adam update', 'm ← β₁m + (1−β₁)g; v ← β₂v + (1−β₂)g²; θ ← θ − η·m̂/(√v̂ + ε)'), + c('math-3', 'Bootstrap', 'Resample the data with replacement many times to estimate a statistic\'s sampling distribution.'), + c('math-3', 'Bellman equation', 'V(s) = E[r + γV(s′)]. The value of a state is the immediate reward plus the discounted future value.'), + c('math-3', 'ELBO', 'Evidence lower bound: E_q[log p(x,z)] − E_q[log q(z)] ≤ log p(x). Maximised in variational inference.'), +] diff --git a/src/lib/ai/quizzes.ts b/src/lib/ai/quizzes.ts new file mode 100644 index 0000000..061e55d --- /dev/null +++ b/src/lib/ai/quizzes.ts @@ -0,0 +1,699 @@ +// Concept-check questions per module, keyed by module id from content.json. +// `a` is the index of the correct option. +export type Question = { q: string; o: string[]; a: number; why: string } + +export const quizzes: Record<string, Question[]> = { + // ───────────── Track 1 ───────────── + 't1-1.1': [ + { + q: 'What does an LLM actually compute at each generation step?', + o: ['The full answer in one pass', 'A probability distribution over the next token', 'A database lookup of similar text', 'A fixed rule chosen by the system prompt'], + a: 1, + why: 'The model outputs logits over its vocabulary; softmax turns them into probabilities and one token is sampled. Repeat until done.', + }, + { + q: 'Lowering temperature towards 0 makes outputs…', + o: ['More random', 'More deterministic, favouring the top token', 'Longer', 'Cheaper per token'], + a: 1, + why: 'Temperature divides the logits before softmax. Small T sharpens the distribution so the most likely token dominates.', + }, + { + q: 'Why does the same sentence often cost more tokens in Burmese than in English?', + o: ['Burmese models are bigger', 'Tokenizers are trained mostly on English, so other scripts split into more, smaller pieces', 'APIs charge extra for Unicode', 'Burmese needs a separate system prompt'], + a: 1, + why: 'BPE vocabularies reflect their training data. Under-represented scripts get fragmented, which raises cost and uses up context.', + }, + { + q: 'Which stage turns a raw base model into a helpful assistant?', + o: ['Pretraining on more web text', 'Tokenization', 'Post-training (instruction tuning, RLHF/RL)', 'Increasing the context window'], + a: 2, + why: 'Pretraining gives knowledge and fluency; post-training teaches the assistant format, helpfulness and refusals.', + }, + ], + 't1-1.2': [ + { + q: 'You send the same 20k-token system prompt on every request. What cuts cost and latency the most?', + o: ['Raise max_tokens', 'Prompt caching', 'Use temperature 0', 'Stream the response'], + a: 1, + why: 'Caching lets the provider reuse the processed prefix, so repeated input tokens are much cheaper and faster.', + }, + { + q: 'Streaming mainly improves…', + o: ['Total cost', 'Perceived latency (time to first token shown)', 'Answer accuracy', 'Rate limits'], + a: 1, + why: 'Total generation time is similar, but users see output immediately instead of waiting for the full response.', + }, + { + q: 'In tool use (function calling), who executes the tool?', + o: ['The model provider', 'Your application code', 'The tokenizer', 'Nobody, it is simulated'], + a: 1, + why: 'The model emits a structured tool-call request; your code runs it and sends the result back as the next message.', + }, + { + q: 'Best way to handle a 429 rate-limit response?', + o: ['Retry immediately in a tight loop', 'Retry with exponential backoff and jitter', 'Switch to a bigger model', 'Drop the request silently'], + a: 1, + why: 'Same as any backend API: back off, add jitter to avoid thundering herds, and cap retries.', + }, + ], + 't1-1.3': [ + { + q: 'With a long document plus a question, where should the question usually go?', + o: ['Before the document', 'After the document', 'In the temperature setting', 'It does not matter at all'], + a: 1, + why: 'Putting long material first and the instructions/question at the end tends to give better results with long contexts.', + }, + { + q: 'Prompt A scores 82% and prompt B 85% on 30 examples. What should you conclude?', + o: ['B is clearly better; ship it', 'The difference may be noise; check confidence intervals or use more examples', 'A is better because it is shorter', 'Neither works'], + a: 1, + why: 'One example is about 3.3 points here. With n=30 the standard error is large, so a 3-point gap is easily noise.', + }, + { + q: '"Context engineering" mainly means…', + o: ['Finding magic wording', 'Deciding what information goes into the context window, and in what form', 'Maximising context length', 'Fine-tuning the model'], + a: 1, + why: 'The model can only use what is in context. Choosing, trimming and structuring that information matters most.', + }, + { + q: 'Why split one complex prompt into a chain of smaller steps?', + o: ['It always costs less', 'Each step is simpler, easier to test and easier to debug', 'Models cannot handle long prompts', 'To avoid tool use'], + a: 1, + why: 'Chains trade some latency and cost for reliability and observability, much like splitting a big function.', + }, + ], + 't1-1.4': [ + { + q: 'Your RAG bot gives a wrong answer. What should you check first?', + o: ['Switch to a bigger model', 'Whether the right chunks were retrieved', 'Increase temperature', 'Add more documents'], + a: 1, + why: 'Separate retrieval failures from generation failures. If the right chunk was never retrieved, the model could not have answered.', + }, + { + q: 'Why combine BM25 with vector search (hybrid search)?', + o: ['BM25 is newer', 'Keyword search catches exact terms (IDs, error codes, names) that embeddings can miss', 'It removes the need for chunking', 'Vector search cannot rank'], + a: 1, + why: 'Embeddings capture meaning; BM25 nails exact lexical matches. Together they usually beat either alone.', + }, + { + q: 'What does recall@5 measure?', + o: ['Answer fluency', 'Share of queries where a relevant chunk appears in the top 5 results', 'Latency of the top 5 calls', 'Number of chunks per document'], + a: 1, + why: 'It is a retrieval metric: did the right evidence make it into what the model sees?', + }, + { + q: 'What does a reranker do?', + o: ['Re-embeds the whole corpus', 'Rescores a shortlist of candidates with a more accurate (slower) model', 'Rewrites the user query', 'Deletes duplicate chunks'], + a: 1, + why: 'Fast retrieval fetches about 50–100 candidates; a cross-encoder reranker orders them more precisely before the top-k go to the LLM.', + }, + ], + 't1-1.5': [ + { + q: 'The steps are known and fixed (fetch → classify → reply). What should you build?', + o: ['An autonomous multi-agent system', 'A workflow (prompt chain or router)', 'A fine-tuned model', 'A swarm'], + a: 1, + why: 'Use agents only when the path cannot be known in advance. Workflows are cheaper, faster and more predictable.', + }, + { + q: 'What problem does MCP solve?', + o: ['Model training speed', 'A standard way to connect tools and data sources to any compatible AI client', 'GPU scheduling', 'Prompt caching'], + a: 1, + why: 'Model Context Protocol standardises tool and resource servers, so one integration works across clients.', + }, + { + q: 'Which guard is essential in a from-scratch agent loop?', + o: ['A maximum step count', 'A higher temperature', 'Removing the system prompt', 'Disabling logging'], + a: 0, + why: 'Agents can loop forever. Cap the steps, log every tool call, and fail cleanly.', + }, + { + q: 'A common reason agents fail on multi-step tasks is…', + o: ['Errors compound across steps', 'Tools run too fast', 'Too few tokens in the vocabulary', 'JSON is unsupported'], + a: 0, + why: '95% per-step reliability over 10 steps is only about 60% end to end. Well-designed tools and checks matter.', + }, + ], + 't1-1.6': [ + { + q: 'The best first step in building evals for an existing AI feature is…', + o: ['Pick a public benchmark', 'Read real traces and write down failure categories (error analysis)', 'Build an LLM judge', 'Buy an eval platform'], + a: 1, + why: 'Error analysis tells you what actually breaks. Metrics designed before looking at data often measure the wrong thing.', + }, + { + q: 'Before trusting an LLM-as-judge you should…', + o: ['Use the biggest model', 'Measure its agreement with human labels on a sample', 'Set temperature to 1', 'Hide the rubric from it'], + a: 1, + why: 'A judge is itself a model that can be wrong. Validate it like any classifier.', + }, + { + q: 'Which failure is best caught with a code-based assertion rather than a judge?', + o: ['Tone is too formal', 'Output is not valid JSON or is missing a required field', 'Answer is unhelpful', 'Explanation is unclear'], + a: 1, + why: 'Deterministic checks are cheap, fast and exact. Save judges for subjective criteria.', + }, + { + q: 'Why run evals in CI?', + o: ['To make builds slower', 'To catch quality regressions from prompt or model changes before they ship', 'Because judges need GPUs', 'To train the model'], + a: 1, + why: 'Prompts and model versions are code. Regression tests stop silent quality drops.', + }, + ], + 't1-1.7': [ + { + q: 'Which combination makes prompt injection most dangerous ("the lethal trifecta")?', + o: ['Long prompts, high temperature, streaming', 'Access to private data + exposure to untrusted content + ability to send data out', 'Many users, many tools, many models', 'Caching, batching, retries'], + a: 1, + why: 'If all three are present, injected instructions can steal data. Remove at least one of the three.', + }, + { + q: 'Where can an injection arrive from in a RAG agent?', + o: ['Only the user message', 'Retrieved documents, tool outputs, web pages and logs too', 'Only the system prompt', 'Nowhere if you use JSON mode'], + a: 1, + why: 'Any text the model reads is a possible attack channel, especially retrieved or third-party content.', + }, + { + q: 'What is the most useful thing to log per LLM call?', + o: ['Only errors', 'Prompt version, model, inputs/outputs, tokens, latency and cost', 'Only token count', 'Nothing, for privacy'], + a: 1, + why: 'Traces make debugging and cost attribution possible. Redact PII where needed rather than logging nothing.', + }, + ], + 't1-1.8': [ + { + q: 'What does durable execution (e.g. Temporal) give you over a simple job queue?', + o: ['Faster model inference', 'Workflow state survives crashes, so long-running multi-step work resumes where it stopped', 'Free GPUs', 'Automatic prompt tuning'], + a: 1, + why: 'Workflow history is persisted; workers can die and the workflow continues. This suits approvals that wait for days.', + }, + { + q: 'In LangGraph, an agent is modelled as…', + o: ['A single prompt', 'A graph of nodes sharing state, with conditional edges', 'A Kafka topic', 'A vector index'], + a: 1, + why: 'Nodes do work (LLM calls, tools), edges route on state, and checkpointing lets runs pause and resume.', + }, + { + q: 'What is the main benefit of human-in-the-loop interrupts for infra agents?', + o: ['Lower token cost', 'Risky actions (deletes, scaling, config changes) need explicit approval before they run', 'Better embeddings', 'Faster responses'], + a: 1, + why: 'Agents propose; humans approve. It limits the damage from mistakes and injections.', + }, + { + q: 'When is a framework a bad fit?', + o: ['When you need persistence', 'When its abstractions hide behaviour you need to control or debug', 'When you have multiple agents', 'When using Python'], + a: 1, + why: 'You built from scratch first so you can tell when a framework helps and when it gets in the way.', + }, + ], + + // ───────────── Track 2 ───────────── + 't2-2.1': [ + { + q: 'A @ B where A is [32, 64] and B is [64, 10] gives shape…', + o: ['[32, 10]', '[64, 64]', '[10, 32]', 'Error'], + a: 0, + why: '[m,k] @ [k,n] → [m,n]. The inner dimensions must match.', + }, + { + q: 'Forgetting optimizer.zero_grad() in a training loop causes…', + o: ['A crash', 'Gradients to accumulate across steps', 'Weights to reset', 'Nothing'], + a: 1, + why: 'PyTorch adds into .grad by default, so stale gradients pile up and updates get too large.', + }, + { + q: 'Adding x of shape [8, 1] to y of shape [1, 5] gives…', + o: ['Error', '[8, 5] via broadcasting', '[8, 1]', '[1, 5]'], + a: 1, + why: 'Size-1 dimensions stretch to match. Very handy, and a common source of silent bugs.', + }, + { + q: 'What does loss.backward() do?', + o: ['Updates the weights', 'Computes gradients of the loss with respect to all parameters that require grad', 'Resets the model', 'Evaluates on the test set'], + a: 1, + why: 'Autograd walks the computation graph backwards (chain rule). optimizer.step() then applies the update.', + }, + ], + 't2-2.2': [ + { + q: 'Backpropagation is essentially…', + o: ['Random search', 'The chain rule applied backwards through a computation graph', 'Matrix inversion', 'A sorting algorithm'], + a: 1, + why: 'Each node multiplies the upstream gradient by its local derivative. micrograd shows this in about 100 lines.', + }, + { + q: 'For L = a·b, what is ∂L/∂a?', + o: ['a', 'b', '1', 'a + b'], + a: 1, + why: 'The local derivative of a product with respect to one input is the other input.', + }, + { + q: 'If a value feeds into two downstream nodes, its gradient is…', + o: ['The max of the two', 'The sum of the gradients from both paths', 'The first one only', 'Zero'], + a: 1, + why: 'Gradients from multiple uses accumulate (+=). This is why micrograd uses += in backward.', + }, + { + q: 'The initial loss of a 27-class model is much higher than −ln(1/27) ≈ 3.3. This suggests…', + o: ['A great initialisation', 'Overconfident initial logits; scale down the output layer weights', 'Not enough data', 'The learning rate is too low'], + a: 1, + why: 'At init the model should be uniformly unsure. A high initial loss wastes early training steps squashing logits.', + }, + ], + 't2-2.3': [ + { + q: 'Training loss falls but validation loss rises. What is happening?', + o: ['Underfitting', 'Overfitting', 'Learning rate too low', 'A data loader bug, always'], + a: 1, + why: 'The model is memorising the training set. Add regularisation or data, stop earlier, or use a smaller model.', + }, + { + q: 'The loss suddenly goes to NaN early in training. Most likely cause?', + o: ['Learning rate too high or numerical instability', 'Too much data', 'Too many layers of dropout', 'The model is too small'], + a: 0, + why: 'Exploding updates overflow. Lower the LR, add warmup, clip gradients, and check fp16/bf16 settings.', + }, + { + q: 'Why do residual connections help deep networks train?', + o: ['They reduce parameters', 'They give gradients a direct path backwards, easing vanishing gradients', 'They replace normalisation', 'They speed up inference only'], + a: 1, + why: 'x + f(x) lets the identity carry signal and gradients through many layers.', + }, + { + q: 'Which normalisation do most modern LLMs use?', + o: ['BatchNorm', 'LayerNorm / RMSNorm', 'No normalisation', 'GroupNorm'], + a: 1, + why: 'Normalising per token (not per batch) suits variable-length sequences. RMSNorm is the cheaper variant.', + }, + ], + 't2-2.4': [ + { + q: 'In self-attention, scores are computed from…', + o: ['V · Vᵀ', 'Q · Kᵀ, scaled by √d and softmaxed, then used to weight V', 'K + V', 'Embeddings only'], + a: 1, + why: 'Queries ask, keys advertise, values carry content: softmax(QKᵀ/√d)·V.', + }, + { + q: 'What does the causal mask do in a GPT?', + o: ['Hides padding only', 'Prevents a token attending to future tokens', 'Drops random heads', 'Masks the loss'], + a: 1, + why: 'Next-token prediction must not peek ahead, so future positions get −∞ before the softmax.', + }, + { + q: 'Why does a KV cache speed up generation?', + o: ['It compresses weights', 'Past tokens’ keys and values are stored, so each new step only processes the new token', 'It skips attention', 'It batches users'], + a: 1, + why: 'Without a cache every step recomputes attention inputs for the whole prefix. With one, each step adds one row.', + }, + { + q: 'Why divide attention scores by √d_k?', + o: ['To save memory', 'To keep dot products from growing with dimension and saturating the softmax', 'To normalise V', 'It is optional decoration'], + a: 1, + why: 'Dot products of random d-dimensional vectors have variance about d. Scaling keeps the softmax in a useful range.', + }, + ], + 't2-2.5': [ + { + q: 'LoRA fine-tunes a layer by…', + o: ['Updating all weights', 'Freezing W and learning a low-rank update B·A added to it', 'Pruning neurons', 'Quantising to INT4'], + a: 1, + why: 'Only the small A and B matrices train, which cuts optimizer memory massively. They can be merged back after training.', + }, + { + q: 'QLoRA adds what on top of LoRA?', + o: ['A reward model', 'A 4-bit quantised frozen base model, so big models fit on one GPU', 'More layers', 'Distillation'], + a: 1, + why: 'The base model is stored in 4-bit NF4, while LoRA adapters train in higher precision.', + }, + { + q: 'DPO trains on…', + o: ['Unlabelled text', 'Preference pairs (chosen vs rejected) without a separate reward model or RL loop', 'Images', 'Only the system prompt'], + a: 1, + why: 'DPO rewrites the RLHF objective as a classification-style loss directly on preference pairs.', + }, + { + q: 'When is fine-tuning usually not the first choice?', + o: ['When the model lacks up-to-date or private facts (use RAG)', 'When you need a consistent output format', 'When you need lower latency with a smaller model', 'When a narrow task needs a specialised style'], + a: 0, + why: 'Fine-tuning teaches behaviour and format well. Knowledge that changes belongs in retrieval.', + }, + ], + 't2-2.6': [ + { + q: 'An elementwise op (e.g. GELU) on a large tensor is typically…', + o: ['Compute-bound', 'Memory-bandwidth-bound', 'Network-bound', 'Disk-bound'], + a: 1, + why: 'It does very few FLOPs per byte moved (low arithmetic intensity), so HBM bandwidth is the limit.', + }, + { + q: 'Why does FlashAttention speed attention up?', + o: ['It approximates attention', 'It tiles the computation in fast on-chip SRAM and never writes the full N×N matrix to HBM', 'It uses INT4', 'It skips the softmax'], + a: 1, + why: 'It is exact attention that is IO-aware. Avoiding HBM reads and writes is the win.', + }, + { + q: 'Kernel fusion helps mainly because…', + o: ['It adds more FLOPs', 'Intermediate results stay on-chip instead of round-tripping through memory', 'It increases batch size', 'It reduces parameters'], + a: 1, + why: 'Every separate kernel reads from and writes to HBM. Fusing removes those trips. torch.compile does much of this for you.', + }, + { + q: 'MFU (model FLOPs utilisation) is…', + o: ['GPU memory used', 'Achieved model FLOPs/sec divided by the hardware’s peak FLOPs/sec', 'Fraction of time the GPU is on', 'Tokens per dollar'], + a: 1, + why: 'It is the honest measure of how well training uses the hardware. 40–60% is good for LLM training.', + }, + ], + 't2-2.7': [ + { + q: 'LLM decode (one token at a time) is usually limited by…', + o: ['Compute', 'Memory bandwidth (reading weights and the KV cache each step)', 'Disk', 'CPU'], + a: 1, + why: 'Each step does little math per weight loaded. Batching many requests raises arithmetic intensity.', + }, + { + q: 'Continuous batching improves throughput by…', + o: ['Waiting for a full batch before starting', 'Adding and removing sequences from the running batch at every step', 'Using bigger GPUs', 'Shortening prompts'], + a: 1, + why: 'Finished sequences free slots immediately and new requests join, so the GPU stays busy.', + }, + { + q: 'What problem does PagedAttention solve?', + o: ['Slow tokenization', 'KV-cache memory fragmentation and over-reservation', 'Training instability', 'Prompt injection'], + a: 1, + why: 'It allocates the KV cache in fixed-size blocks like OS virtual-memory pages, which allows far bigger batches.', + }, + { + q: 'Speculative decoding works by…', + o: ['Skipping tokens', 'A small draft model proposes several tokens; the big model verifies them in one pass', 'Lowering precision', 'Caching answers'], + a: 1, + why: 'Verification is parallel. Accepted drafts give multiple tokens per big-model step, with the same output distribution.', + }, + { + q: 'Prefix caching is most useful when…', + o: ['Every prompt is unique', 'Many requests share a long common prefix (a system prompt or document)', 'Outputs are very long', 'Batch size is 1'], + a: 1, + why: 'The KV cache for the shared prefix is computed once and reused, cutting prefill time and TTFT.', + }, + ], + 't2-2.8': [ + { + q: 'Plain data parallelism (DDP) replicates…', + o: ['Only the data', 'The full model on every GPU, then all-reduces gradients', 'Half the layers per GPU', 'Nothing'], + a: 1, + why: 'Each GPU runs a different mini-batch on a full copy of the model; gradients are averaged with all-reduce.', + }, + { + q: 'ZeRO stage 3 / FSDP shards…', + o: ['Only optimizer states', 'Optimizer states, gradients and parameters across GPUs', 'Only the data', 'Only activations'], + a: 1, + why: 'Stage 1 shards optimizer states, stage 2 adds gradients, stage 3 adds parameters too.', + }, + { + q: 'Roughly how much memory does mixed-precision Adam training need per parameter, before activations?', + o: ['2 bytes', '~16 bytes', '~4 bytes', '~64 bytes'], + a: 1, + why: 'bf16 weights (2) + bf16 grads (2) + fp32 master weights (4) + Adam m and v (4+4) ≈ 16 bytes. A 7B model needs ~112 GB.', + }, + { + q: 'Activation checkpointing trades…', + o: ['Accuracy for speed', 'Extra compute (recomputing the forward pass) for less activation memory', 'Bandwidth for disk', 'Parameters for data'], + a: 1, + why: 'Activations are dropped in the forward pass and recomputed during backward.', + }, + ], + 't2-2.9': [ + { + q: 'The most important property of an ML training pipeline is…', + o: ['It uses the newest framework', 'Reproducibility: same config + data + code gives the same model and eval numbers', 'It runs on Kubernetes', 'It has a UI'], + a: 1, + why: 'Without reproducibility you cannot trust comparisons or debug regressions.', + }, + { + q: 'What is a model registry for?', + o: ['Storing raw data', 'Versioning trained models with their metadata, metrics and lineage for promotion and rollback', 'Training faster', 'Serving embeddings'], + a: 1, + why: 'It is like an artifact repository: what model is in prod, how it was trained, and how to roll back.', + }, + { + q: 'Data drift means…', + o: ['The training job moved servers', 'The production input distribution has shifted away from the training data', 'The model weights changed', 'Disk is full'], + a: 1, + why: 'Model quality degrades silently when inputs change. Monitor input statistics and eval quality over time.', + }, + ], + 't2-2.10': [ + { + q: 'A vLLM pod is stuck in Pending on a GPU cluster. A likely cause?', + o: ['The prompt is too long', 'No node has a free GPU matching its resource request, taints or selector', 'Temperature too high', 'The KV cache is full'], + a: 1, + why: 'Check `kubectl describe pod` events: insufficient nvidia.com/gpu, untolerated taints, or node selectors.', + }, + { + q: 'Which tool exposes GPU utilisation, memory and XID errors to Prometheus?', + o: ['KEDA', 'DCGM exporter', 'Kueue', 'Helm'], + a: 1, + why: 'NVIDIA DCGM exporter publishes GPU telemetry as Prometheus metrics.', + }, + { + q: 'Why autoscale LLM servers on queue depth or running requests rather than CPU?', + o: ['CPU metrics are unavailable', 'GPU inference load is not reflected in CPU usage; request backlog tracks real demand', 'It is cheaper to store', 'HPA cannot read CPU'], + a: 1, + why: 'KEDA or custom metrics on queue length, or vLLM’s running/waiting requests, reflect actual saturation.', + }, + { + q: 'How should your ops agent access the Kubernetes API?', + o: ['Cluster-admin for convenience', 'A least-privilege, namespace-scoped read-only service account; writes go through human approval', 'The developer’s kubeconfig', 'No auth inside the cluster'], + a: 1, + why: 'Assume the agent can be manipulated. Limit what it can do, and audit it.', + }, + ], + + // ───────────── Track 3 ───────────── + 't3-3.1': [ + { + q: 'The bias–variance tradeoff says that, roughly, more model complexity…', + o: ['Always lowers test error', 'Lowers bias but can raise variance', 'Raises bias', 'Has no effect'], + a: 1, + why: 'Classic U-shaped test error. Deep learning complicates it (double descent), but the vocabulary still matters.', + }, + { + q: 'L2 regularisation corresponds to which prior on the weights (MAP view)?', + o: ['Uniform', 'Gaussian', 'Laplace', 'Bernoulli'], + a: 1, + why: 'A Gaussian prior gives an L2 penalty; a Laplace prior gives L1 (sparsity).', + }, + { + q: 'PCA finds…', + o: ['Clusters', 'Orthogonal directions of maximum variance (via SVD of centred data)', 'Decision boundaries', 'Nearest neighbours'], + a: 1, + why: 'The top singular vectors of centred data are the principal components.', + }, + ], + 't3-3.2': [ + { + q: 'Chinchilla’s main finding was that for a fixed compute budget…', + o: ['Bigger models are always better', 'Parameters and training tokens should scale roughly equally (~20 tokens per parameter)', 'Data does not matter', 'Small models win'], + a: 1, + why: 'Earlier models like GPT-3 were undertrained. Compute-optimal training uses far more tokens per parameter.', + }, + { + q: 'Scaling laws typically appear as straight lines on…', + o: ['Linear axes', 'Log–log axes (power laws)', 'Polar plots', 'Histograms'], + a: 1, + why: 'Loss ≈ A·N^(−α) + E, a power law, which is linear in log-log space.', + }, + { + q: 'μP (maximal update parametrisation) mainly lets you…', + o: ['Skip training', 'Tune hyperparameters on a small model and transfer them to a large one', 'Quantise models', 'Remove normalisation'], + a: 1, + why: 'With μP the optimal learning rate stays stable as width grows, which saves expensive sweeps at scale.', + }, + ], + 't3-3.3': [ + { + q: 'What is the first pass of Keshav’s three-pass method?', + o: ['Re-derive every equation', 'A 5–10 minute skim: title, abstract, intro, headings, conclusion', 'Run the code', 'Email the authors'], + a: 1, + why: 'Decide whether the paper is worth more time before investing hours.', + }, + { + q: 'When reproducing a paper you should first reproduce…', + o: ['Every table at full scale', 'The smallest experiment that tests the central claim', 'Only the figures', 'The related work'], + a: 1, + why: 'A small, faithful test of the main claim gives most of the signal for a fraction of the cost.', + }, + { + q: 'A result that does not reproduce is…', + o: ['Worthless; hide it', 'Useful information to report honestly with your setup', 'Proof the paper is fraudulent', 'A sign to change seeds until it works'], + a: 1, + why: 'Negative results with clear methodology are valuable. Seed-hacking until it works is not science.', + }, + ], + 't3-3.4': [ + { + q: 'The policy gradient (REINFORCE) increases the probability of actions in proportion to…', + o: ['Their frequency', 'The return (or advantage) that followed them', 'Their entropy', 'Random noise'], + a: 1, + why: '∇J = E[∇log π(a|s) · R]. Subtracting a baseline gives the advantage and reduces variance.', + }, + { + q: 'Why does PPO clip the probability ratio?', + o: ['To speed up sampling', 'To prevent overly large policy updates from a single batch', 'To remove the value function', 'To discretise actions'], + a: 1, + why: 'Clipping keeps the new policy close to the old one, a cheap stand-in for a trust region.', + }, + { + q: 'Q-learning is…', + o: ['On-policy', 'Off-policy: it learns the greedy policy’s value while behaving differently', 'Supervised learning', 'Only for continuous actions'], + a: 1, + why: 'The target uses max over next actions regardless of the exploratory action actually taken.', + }, + ], + 't3-3.5': [ + { + q: 'GRPO differs from PPO mainly by…', + o: ['Using images', 'Dropping the learned value model and using group-relative rewards over several samples as the baseline', 'Removing the KL penalty forever', 'Training only the embeddings'], + a: 1, + why: 'Sample several answers per prompt, normalise rewards within the group, and use that as the advantage. This saves memory.', + }, + { + q: 'Reward hacking means…', + o: ['Stealing reward models', 'The policy exploits flaws in the reward signal and scores well without doing the intended task', 'Faster convergence', 'Using too small a learning rate'], + a: 1, + why: 'Optimising a proxy too hard diverges from the true goal (Goodhart). The overoptimisation scaling-law paper measures this.', + }, + { + q: 'RLVR (RL with verifiable rewards) is well suited to…', + o: ['Poetry style', 'Math and code, where answers can be checked automatically', 'Image generation', 'Open-ended chat'], + a: 1, + why: 'Automatic verifiers give clean reward signals, which is behind recent reasoning-model gains.', + }, + ], + 't3-3.6': [ + { + q: 'An induction head implements roughly…', + o: ['Sorting', 'If token A was followed by B earlier, then after seeing A again, predict B', 'Counting tokens', 'Translation'], + a: 1, + why: 'A two-head circuit (previous-token head + induction head) underlies much in-context copying.', + }, + { + q: 'Superposition is the idea that…', + o: ['Models use quantum hardware', 'Networks represent more features than they have dimensions, using nearly orthogonal directions', 'Layers are redundant', 'Attention is linear'], + a: 1, + why: 'Sparse features can share dimensions, which makes individual neurons polysemantic.', + }, + { + q: 'Sparse autoencoders are used in interpretability to…', + o: ['Compress models for deployment', 'Decompose activations into a larger set of sparse, more interpretable features', 'Speed up training', 'Generate data'], + a: 1, + why: 'Dictionary learning undoes superposition so that features map more cleanly to concepts.', + }, + { + q: 'Activation patching tests…', + o: ['Memory usage', 'Whether a component causally matters, by swapping its activation from another input and measuring the change', 'Training speed', 'Tokenizer quality'], + a: 1, + why: 'It is an intervention, not just a correlation. That is the core move of causal interpretability.', + }, + ], + 't3-3.7': [ + { + q: 'Before running a new idea you should first have…', + o: ['A press release', 'A strong, well-tuned baseline', 'Ten GPUs', 'The final figure designed'], + a: 1, + why: 'Many "improvements" disappear against a properly tuned baseline.', + }, + { + q: 'Your method beats the baseline on one seed by 0.3%. You should…', + o: ['Publish', 'Run several seeds and report the variance before claiming anything', 'Try new seeds until the gap grows', 'Drop the baseline'], + a: 1, + why: 'Seed-to-seed noise is often larger than small claimed gains. Report error bars.', + }, + { + q: 'What is an ablation?', + o: ['Deleting the dataset', 'Removing or changing one component to measure its contribution', 'A type of optimizer', 'Hyperparameter search'], + a: 1, + why: 'Ablations show which parts of a method actually matter.', + }, + ], + + // ───────────── Math ───────────── + 'math-1': [ + { + q: 'Cosine similarity between two vectors depends on…', + o: ['Their lengths only', 'The angle between them, not their lengths', 'Their sum', 'Their dimension count'], + a: 1, + why: 'cos θ = a·b / (‖a‖‖b‖). Normalising removes the effect of magnitude.', + }, + { + q: 'softmax([2, 2, 2]) equals…', + o: ['[2, 2, 2]', '[1/3, 1/3, 1/3]', '[1, 0, 0]', '[0.5, 0.5, 0.5]'], + a: 1, + why: 'Equal logits give a uniform distribution.', + }, + { + q: 'Why subtract max(x) before computing softmax?', + o: ['It changes the result', 'Numerical stability: prevents exp() overflow without changing the output', 'It makes it faster', 'To get negative probabilities'], + a: 1, + why: 'softmax(x) = softmax(x − c) for any constant c, and exp of large numbers overflows.', + }, + { + q: 'The standard error of a mean from n samples shrinks like…', + o: ['1/n', '1/√n', 'n', 'log n'], + a: 1, + why: 'SE = σ/√n. Four times the data halves the uncertainty.', + }, + ], + 'math-2': [ + { + q: 'The gradient of softmax + cross-entropy with respect to the logits is…', + o: ['y − p', 'p − y', 'p · y', 'log p'], + a: 1, + why: 'Predicted probabilities minus the one-hot target. Simple, and it explains why this pairing is used everywhere.', + }, + { + q: 'Minimising cross-entropy loss is equivalent to…', + o: ['Minimising variance', 'Maximising the likelihood of the data', 'Maximising entropy', 'Minimising weights'], + a: 1, + why: 'The negative log-likelihood of a categorical model is exactly the cross-entropy against the labels.', + }, + { + q: 'KL(P‖Q) is…', + o: ['Symmetric', 'Always ≥ 0, and 0 only when P = Q', 'Always ≤ 0', 'A distance metric'], + a: 1, + why: 'KL is non-negative but asymmetric, so it is not a true metric. Forward and reverse KL behave differently.', + }, + { + q: 'Adam differs from SGD mainly by…', + o: ['Using no learning rate', 'Per-parameter adaptive step sizes from running averages of gradients and squared gradients', 'Computing second derivatives exactly', 'Ignoring gradients'], + a: 1, + why: 'm (momentum) and v (squared-gradient scale) give each parameter its own effective step size.', + }, + { + q: 'A matrix of rank r can be written exactly as…', + o: ['A sum of r rank-1 outer products', 'A diagonal matrix', 'Its transpose', 'r scalars'], + a: 0, + why: 'SVD: M = Σᵢ σᵢ uᵢ vᵢᵀ. Truncating gives the best low-rank approximation, which is the idea behind LoRA.', + }, + ], + 'math-3': [ + { + q: 'The bootstrap estimates uncertainty by…', + o: ['Collecting new data', 'Resampling the observed data with replacement and recomputing the statistic', 'Assuming normality only', 'Using the median'], + a: 1, + why: 'The spread of the resampled statistics approximates its sampling distribution.', + }, + { + q: 'Fitting a single Gaussian Q to a bimodal P with reverse KL(Q‖P) tends to…', + o: ['Cover both modes', 'Lock onto one mode (mode-seeking)', 'Produce a uniform distribution', 'Diverge'], + a: 1, + why: 'Reverse KL heavily penalises Q putting mass where P has none. Forward KL is mode-covering.', + }, + { + q: 'Monte Carlo estimation error decreases as…', + o: ['1/n', '1/√n', 'e^(−n)', 'It does not decrease'], + a: 1, + why: 'It is the same √n law as the standard error.', + }, + ], +} diff --git a/src/lib/icons.ts b/src/lib/icons.ts new file mode 100644 index 0000000..b52946f --- /dev/null +++ b/src/lib/icons.ts @@ -0,0 +1,36 @@ +// Stroke icons (lucide-style paths) shared by the Astro chrome and the Preact islands. +export const ICONS = { + route: 'M6 19a2 2 0 1 0 0-4 2 2 0 0 0 0 4ZM18 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4ZM6 15V9a4 4 0 0 1 4-4h2M18 9v6a4 4 0 0 1-4 4h-2', + dumbbell: 'M6.5 6.5l11 11M21 21l-1-1M3 3l1 1M18 22l4-4M2 6l4-4M3 10l7-7M14 21l7-7', + file: 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M16 13H8M16 17H8M10 9H8', + hammer: 'M15 12l-8.5 8.5a2.12 2.12 0 0 1-3-3L12 9M17.64 15L22 10.64M20.91 11.7l-1.25-1.25c-.6-.6-.93-1.4-.93-2.25V6.5l-3.5-3.5H9l2 2v1.5c0 .85-.34 1.66-.93 2.25L9 9.5', + user: 'M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z', + flame: 'M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.07-2.14 0-5.5 3-7 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.15.43-2.29 1-3a2.5 2.5 0 0 0 2.5 2.5Z', + bolt: 'M13 2 3 14h9l-1 8 10-12h-9l1-8Z', + crown: 'M2 4l3 12h14l3-12-6 7-4-7-4 7-6-7zM5 20h14', + target: 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20ZM12 18a6 6 0 1 0 0-12 6 6 0 0 0 0 12ZM12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z', + refresh: 'M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8M21 3v5h-5M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16M8 16H3v5', + play: 'M6 3l14 9-14 9V3z', + star: 'M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z', + trophy: 'M6 9H4.5a2.5 2.5 0 0 1 0-5H6M18 9h1.5a2.5 2.5 0 0 0 0-5H18M4 22h16M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22M18 2H6v7a6 6 0 0 0 12 0V2Z', + check: 'M20 6 9 17l-5-5', + x: 'M18 6 6 18M6 6l12 12', + heart: 'M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z', + book: 'M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20', + bookOpen: 'M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2zM22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z', + bulb: 'M9 18h6M10 22h4M15.09 14c.18-.98.65-1.74 1.41-2.5A4.65 4.65 0 0 0 18 8 6 6 0 0 0 6 8c0 1 .23 2.23 1.5 3.5A4.61 4.61 0 0 1 8.91 14', + code: 'M16 18l6-6-6-6M8 6l-6 6 6 6', + help: 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20ZM9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3M12 17h.01', + chevron: 'M9 18l6-6-6-6', + back: 'M15 18l-6-6 6-6', + ext: 'M15 3h6v6M10 14 21 3M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6', + panel: 'M3 5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2zM9 3v18', + sparkle: 'M12 3l1.9 5.8L20 10l-6.1 1.2L12 17l-1.9-5.8L4 10l6.1-1.2L12 3z', + download: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3', + upload: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12', + home: 'M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z', + grid: 'M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z', + github: 'M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.4 5.4 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65S8.93 17.38 9 18v4M9 18c-4.51 2-5-2-7-2', +} + +export type IconName = keyof typeof ICONS diff --git a/src/lib/progress.ts b/src/lib/progress.ts new file mode 100644 index 0000000..a487aa0 --- /dev/null +++ b/src/lib/progress.ts @@ -0,0 +1,143 @@ +// Progress for the whole site, kept in localStorage. Every section reads and +// writes it through here, so XP, streak and daily goal are shared. A signed-in +// sync to the server will replace load/save below; nothing else needs to change. +// +// Item ids are namespaced by their section: AI Engineer units look like +// "t2-2.7/quiz", papers "paper:<id>", projects "project:<id>". + +export type CardState = { box: number; due: string } +export type Progress = { + dailyGoal: number + /** Whether the AI Engineer "where are you starting?" question was answered. */ + aiOnboarded: boolean + aiTrack: string + xpByDay: Record<string, number> + done: Record<string, true> + checked: Record<string, true> + crowns: Record<string, true> + quizBest: Record<string, number> + cards: Record<string, CardState> +} + +const KEY = 'learn-progress-v1' +const EMPTY: Progress = { + dailyGoal: 30, + aiOnboarded: false, + aiTrack: 't1', + xpByDay: {}, + done: {}, + checked: {}, + crowns: {}, + quizBest: {}, + cards: {}, +} + +function load(): Progress { + try { + const s = localStorage.getItem(KEY) + if (s) return { ...EMPTY, ...JSON.parse(s) } + } catch { + /* storage unavailable: run in memory */ + } + return { ...EMPTY } +} + +let state: Progress | null = null +const listeners = new Set<() => void>() + +export function get(): Progress { + if (!state) state = load() + return state +} + +export function subscribe(fn: () => void) { + listeners.add(fn) + return () => { + listeners.delete(fn) + } +} + +export function update(fn: (p: Progress) => Progress) { + state = fn(get()) + try { + localStorage.setItem(KEY, JSON.stringify(state)) + } catch { + /* ignore */ + } + listeners.forEach((l) => l()) +} + +// another tab changed it +if (typeof window !== 'undefined') + window.addEventListener('storage', (e) => { + if (e.key !== KEY) return + state = load() + listeners.forEach((l) => l()) + }) + +export const today = (d = new Date()) => d.toLocaleDateString('en-CA') + +export function addXp(n: number) { + if (n <= 0) return + const t = today() + update((p) => ({ ...p, xpByDay: { ...p.xpByDay, [t]: (p.xpByDay[t] || 0) + n } })) +} + +export const totalXp = (p: Progress) => Object.values(p.xpByDay).reduce((a, b) => a + b, 0) +export const xpToday = (p: Progress) => p.xpByDay[today()] || 0 +export const crownCount = (p: Progress) => Object.keys(p.crowns).length + +export function streak(p: Progress) { + let n = 0 + const d = new Date() + if (!p.xpByDay[today(d)]) d.setDate(d.getDate() - 1) + while (p.xpByDay[today(d)]) { + n++ + d.setDate(d.getDate() - 1) + } + return n +} + +export function toggleChecked(id: string, xp: number) { + const on = !get().checked[id] + update((p) => { + const checked = { ...p.checked } + if (on) checked[id] = true + else delete checked[id] + return { ...p, checked } + }) + if (on) addXp(xp) + return on +} + +export function markDone(unitId: string, xp = 0) { + const first = !get().done[unitId] + update((p) => ({ ...p, done: { ...p.done, [unitId]: true } })) + if (first) addXp(xp) +} + +export const exportProgress = () => JSON.stringify(get(), null, 2) + +export function importProgress(json: string) { + const parsed = JSON.parse(json) + if (typeof parsed !== 'object' || !parsed || !parsed.xpByDay) throw new Error('Not a progress file') + // files exported by the first standalone AI Engineer site used these names + if ('startTrack' in parsed && !('aiTrack' in parsed)) parsed.aiTrack = parsed.startTrack + if ('onboarded' in parsed && !('aiOnboarded' in parsed)) parsed.aiOnboarded = parsed.onboarded + update(() => ({ ...EMPTY, ...parsed })) +} + +export const resetProgress = () => update(() => ({ ...EMPTY })) + +// Leitner boxes: review intervals in days per box. +const INTERVALS = [0, 1, 3, 7, 16, 35] +export function reviewCard(id: string, knew: boolean) { + update((p) => { + const cur = p.cards[id] || { box: 0, due: today() } + const box = knew ? Math.min(cur.box + 1, INTERVALS.length - 1) : 1 + const d = new Date() + d.setDate(d.getDate() + INTERVALS[box]) + return { ...p, cards: { ...p.cards, [id]: { box, due: today(d) } } } + }) + addXp(knew ? 2 : 1) +} diff --git a/src/lib/stage.js b/src/lib/stage.js index 630e169..5040300 100644 --- a/src/lib/stage.js +++ b/src/lib/stage.js @@ -155,10 +155,10 @@ export function tree(root, o = {}) { return `<g> <circle cx="${x(n)}" cy="${y(n)}" r="17" fill="${fill}" stroke="${stroke}" stroke-width="1.5"/> <text x="${x(n)}" y="${y(n) + 4.5}" text-anchor="middle" fill="${ink}" - font-family="IBM Plex Mono, monospace" font-size="13">${esc(n.value)}</text> + font-family="JetBrains Mono, monospace" font-size="13">${esc(n.value)}</text> ${badges[n.key] != null ? `<text x="${x(n) + 23}" y="${y(n) - 10}" fill="var(--accent)" - font-family="IBM Plex Mono, monospace" font-size="11">${esc(badges[n.key])}</text>` + font-family="JetBrains Mono, monospace" font-size="11">${esc(badges[n.key])}</text>` : ''} </g>`; }) diff --git a/src/pages/404.astro b/src/pages/404.astro index 473c97b..3aad90c 100644 --- a/src/pages/404.astro +++ b/src/pages/404.astro @@ -7,7 +7,7 @@ import { SITE_NAME } from '../data/site'; <div class="shell"> <div class="page-head"> <h1>Not found</h1> - <p class="lede">There is no page at this address. The problem list is on the <a href="/">home page</a>.</p> + <p class="lede">There is no page at this address. Try the <a href="/">home page</a>, the <a href="/leetcode">LeetCode problems</a> or the <a href="/ai-engineer">AI Engineer path</a>.</p> </div> </div> </Base> diff --git a/src/pages/ai-engineer/[track].astro b/src/pages/ai-engineer/[track].astro new file mode 100644 index 0000000..15b62ad --- /dev/null +++ b/src/pages/ai-engineer/[track].astro @@ -0,0 +1,55 @@ +--- +import AiLayout from '../../layouts/AiLayout.astro'; +import TrackTabs from '../../components/ai/TrackTabs.astro'; +import Stepper from '../../components/ai/Stepper.astro'; +import Icon from '../../components/Icon.astro'; +import { moduleUrl, tracks, unitUrl, unitKinds, type Track } from '../../lib/ai/course'; + +export function getStaticPaths() { + return tracks.map((t) => ({ params: { track: t.slug }, props: { track: t } })); +} +const { track } = Astro.props as { track: Track }; +const first = track.modules[0]; +--- +<AiLayout title={`${track.short}: ${track.title}`} description={`${track.title}: ${track.subtitle}`}> + <TrackTabs current={track.id} /> + <div class={`track-hero tc-${track.color}`} data-ai-track={track.id}> + <div> + <div class="kicker" style="color:var(--ct)">{track.short} · {track.modules.length} modules</div> + <h1>{track.title}</h1> + <p>{track.subtitle}</p> + </div> + <a class="btn track" href={unitUrl(track, first, unitKinds(first)[0])} data-continue> + <Icon name="play" size={14} fill="currentColor" /> Continue: <span data-continue-label>{first.label} Concepts</span> + </a> + </div> + <ol class={`timeline tc-${track.color}`}> + {track.modules.map((m) => { + const meta = [m.weeks && `${m.weeks} wk${m.weeks === '1' ? '' : 's'}`, m.resources.length && `${m.resources.length} resources`, m.build.length && `${m.build.length} builds`].filter(Boolean).join(' · '); + const blurb = m.why || m.concepts.slice(0, 6).join(' · '); + return ( + <li class="mod" id={m.slug} data-mod={m.id}> + <div class="spine-dot" aria-hidden="true"> + <span class="ic-kind">{m.key === 'ck' ? '✓' : m.key}</span> + </div> + <article class="mod-card" aria-labelledby={`h-${m.slug}`}> + <div class="mod-head"> + <div style="min-width:0"> + <div class="kicker"> + {m.label}{meta && ` · ${meta}`} + {m.star && <span class="badge">★ key</span>} + </div> + <h2 id={`h-${m.slug}`}><a href={moduleUrl(track, m)} style="color:inherit;text-decoration:none">{m.title}</a></h2> + {blurb && <p class="mod-why" set:html={blurb} />} + </div> + <div class="mod-actions"> + <a href={moduleUrl(track, m)} class="btn ghost sm"><Icon name="book" size={15} /> Guide</a> + </div> + </div> + <Stepper track={track} module={m} /> + </article> + </li> + ); + })} + </ol> +</AiLayout> diff --git a/src/pages/ai-engineer/[track]/[module].astro b/src/pages/ai-engineer/[track]/[module].astro new file mode 100644 index 0000000..15c8864 --- /dev/null +++ b/src/pages/ai-engineer/[track]/[module].astro @@ -0,0 +1,30 @@ +--- +import AiLayout from '../../../layouts/AiLayout.astro'; +import Stepper from '../../../components/ai/Stepper.astro'; +import Icon from '../../../components/Icon.astro'; +import { moduleUrl, tracks, trackUrl, type Module, type Track } from '../../../lib/ai/course'; + +export function getStaticPaths() { + return tracks.flatMap((t) => + t.modules.map((m, i) => ({ params: { track: t.slug, module: m.slug }, props: { track: t, module: m, prev: t.modules[i - 1], next: t.modules[i + 1] } })), + ); +} +const { track, module: m, prev, next } = Astro.props as { track: Track; module: Module; prev?: Module; next?: Module }; +--- +<AiLayout title={`${m.label} ${m.title}`} description={`${track.title}, ${m.label}: ${m.title}`}> + <a href={trackUrl(track)} class="optional-toggle" style="margin-top:0"><Icon name="back" size={16} /> {track.short}: {track.title}</a> + <div class={`tc-${track.color}`} data-ai-track={track.id}> + <div class="guide-hero"> + <div class="kicker">{track.short} · {m.label}{m.weeks && ` · ${m.weeks} wk${m.weeks === '1' ? '' : 's'}`}</div> + <h1>{m.title}</h1> + </div> + <div class="card" style="padding:4px 18px 16px;margin-bottom:26px" data-mod={m.id}> + <Stepper track={track} module={m} /> + </div> + <div class="prose" set:html={m.guideHtml} /> + <nav class="pager" aria-label="Modules" style="margin-top:32px"> + {prev ? <a class="up" href={moduleUrl(track, prev)}><span class="dir">Previous</span><span>{prev.label} {prev.title}</span></a> : <span />} + {next && <a href={moduleUrl(track, next)}><span class="dir">Next →</span><span>{next.label} {next.title}</span></a>} + </nav> + </div> +</AiLayout> diff --git a/src/pages/ai-engineer/[track]/[module]/[unit].astro b/src/pages/ai-engineer/[track]/[module]/[unit].astro new file mode 100644 index 0000000..b297150 --- /dev/null +++ b/src/pages/ai-engineer/[track]/[module]/[unit].astro @@ -0,0 +1,32 @@ +--- +/* One lesson step, full screen. Built for every step of every module. */ +import Base from '../../../../layouts/Base.astro'; +import Session from '../../../../components/ai/Session'; +import { moduleUrl, tracks, trackUrl, unitKinds, UNIT_LABEL, UNIT_SLUG, type Module, type Track, type UnitKind } from '../../../../lib/ai/course'; +import { quizzes } from '../../../../lib/ai/quizzes'; +import { SITE_NAME } from '../../../../data/site'; +import '../../../../styles/ai.css'; + +export function getStaticPaths() { + return tracks.flatMap((t) => + t.modules.flatMap((m) => unitKinds(m).map((k) => ({ params: { track: t.slug, module: m.slug, unit: UNIT_SLUG[k] }, props: { track: t, module: m, kind: k } }))), + ); +} +const { track, module: m, kind } = Astro.props as { track: Track; module: Module; kind: UnitKind }; +const label = UNIT_LABEL[kind]; +--- +<Base bare section="ai" title={`${label} · ${m.title} · ${SITE_NAME}`} description={`${track.title}, ${m.label} ${m.title}: ${label}`}> + <div class={`tc-${track.color}`}> + <Session + client:only="preact" + unitId={`${m.id}/${kind}`} + kind={kind} + module={{ id: m.id, label: m.label, title: m.title, why: m.why, concepts: m.concepts, notes: m.notes, guideHtml: kind === 'concepts' ? m.guideHtml : '', resources: m.resources, build: m.build, checkpoint: m.checkpoint }} + track={{ id: track.id, short: track.short, subtitle: track.subtitle }} + questions={kind === 'quiz' ? quizzes[m.id] : undefined} + backUrl={`${trackUrl(track)}#${m.slug}`} + guideUrl={moduleUrl(track, m)} + /> + <noscript><main class="session-body"><h1>{m.title}</h1><p class="lead">This step needs JavaScript. The full module text is on the <a href={moduleUrl(track, m)}>guide page</a>.</p></main></noscript> + </div> +</Base> diff --git a/src/pages/ai-engineer/index.astro b/src/pages/ai-engineer/index.astro new file mode 100644 index 0000000..d115498 --- /dev/null +++ b/src/pages/ai-engineer/index.astro @@ -0,0 +1,40 @@ +--- +import AiLayout from '../../layouts/AiLayout.astro'; +import TrackTabs from '../../components/ai/TrackTabs.astro'; +import Onboard from '../../components/ai/Onboard'; +import Icon from '../../components/Icon.astro'; +import { tracks, trackUrl, units } from '../../lib/ai/course'; + +const weeks = tracks.map((t) => t.modules.reduce((a, m) => a + (Number(m.weeks?.split(/[–-]/).at(-1)) || 0), 0)); +--- +<AiLayout title="AI Engineer" description="A self-study path from backend engineer to AI research engineer: three tracks, a math track, quizzes, flashcards and portfolio projects."> + <div class="kicker">AI Engineer</div> + <h1 class="page-h">From backend engineer to research engineer</h1> + <p class="page-sub"> + Three tracks, each one a job you can be hired for, with math running alongside. Every module has five steps: + concepts, resources, hands-on builds, a quiz and a checkpoint that earns a crown. + </p> + <Onboard client:only="preact" /> + <div class="track-hero"> + <div><div class="kicker">Pick up where you left off</div></div> + <a class="btn" href={units[0].url} data-continue hidden><Icon name="play" size={14} fill="currentColor" /> Continue: <span data-continue-label></span></a> + </div> + <TrackTabs /> + <div class="section-title">The tracks</div> + <div class="grid-cards"> + {tracks.map((t, i) => ( + <a class={`card tc-${t.color}`} href={trackUrl(t)} style="border-top:4px solid var(--c)"> + <div class="kicker" style="color:var(--ct)">{t.short}{weeks[i] ? ` · ~${weeks[i]} weeks` : ''}</div> + <h2 style="font-size:19px;margin:6px 0">{t.title}</h2> + <p class="page-sub" style="margin:0 0 10px">{t.subtitle}</p> + <ol style="margin:0;padding-left:18px;color:var(--ink-2);font-size:14px;line-height:1.7"> + {t.modules.map((m) => <li>{m.title}</li>)} + </ol> + </a> + ))} + </div> + {/* the steps, hidden, so decorate.ts can find the first unfinished one for Continue */} + <div hidden> + {units.map((u) => <a href={u.url} data-unit={u.id} data-label={u.label} data-kind-label={u.label} data-mod-label={u.moduleLabel}></a>)} + </div> +</AiLayout> diff --git a/src/pages/ai-engineer/papers.astro b/src/pages/ai-engineer/papers.astro new file mode 100644 index 0000000..e2ccb61 --- /dev/null +++ b/src/pages/ai-engineer/papers.astro @@ -0,0 +1,55 @@ +--- +import AiLayout from '../../layouts/AiLayout.astro'; +import Icon from '../../components/Icon.astro'; +import { papers } from '../../lib/ai/course'; +const total = papers.reduce((a, s) => a + s.papers.length, 0); +--- +<AiLayout title="Papers" description="The core machine learning papers, in reading order." where="AI Engineer · Papers"> + <div class="kicker">Papers</div> + <h1 class="page-h">Reading list</h1> + <p class="page-sub"> + <span data-papers-read>0</span> / {total} summarised · ★ = full three-pass read. Tick a paper once you've written its one-page summary. + </p> + {papers.map((s) => ( + <section> + <h2 class="section-title">{s.title}</h2> + <div class="checklist tc-rose" style="margin-top:0"> + {s.papers.map((x) => ( + <div class="check" data-check={x.id} data-xp="15"> + <button class="box" type="button" role="checkbox" aria-checked="false" aria-label={`Summarised: ${x.title}`}><Icon name="check" size={16} /></button> + <span style="flex:1"> + {x.star && <span style="color:var(--xp)">★ </span>}<b>{x.title}</b> + <span class="paper-meta">{x.by}</span> + </span> + {x.url && <a href={x.url} target="_blank" rel="noopener" aria-label={`Open ${x.title}`} style="color:var(--muted)"><Icon name="ext" size={18} /></a>} + </div> + ))} + </div> + </section> + ))} +</AiLayout> + +<script> + import { get, subscribe, toggleChecked } from '../../lib/progress'; + const rows = [...document.querySelectorAll<HTMLElement>('[data-check]')]; + const paint = () => { + const p = get(); + let n = 0; + for (const r of rows) { + const on = !!p.checked[r.dataset.check!]; + if (on) n++; + r.classList.toggle('on', on); + r.querySelector('[role=checkbox]')?.setAttribute('aria-checked', String(on)); + } + const c = document.querySelector('[data-papers-read]'); + if (c) c.textContent = String(n); + }; + // the whole row toggles (the box is the keyboard target); the paper link opens normally + for (const r of rows) + r.addEventListener('click', (e) => { + if ((e.target as HTMLElement).closest('a')) return; + toggleChecked(r.dataset.check!, Number(r.dataset.xp)); + }); + paint(); + subscribe(paint); +</script> diff --git a/src/pages/ai-engineer/practice.astro b/src/pages/ai-engineer/practice.astro new file mode 100644 index 0000000..19032af --- /dev/null +++ b/src/pages/ai-engineer/practice.astro @@ -0,0 +1,12 @@ +--- +import AiLayout from '../../layouts/AiLayout.astro'; +import Practice from '../../components/ai/Practice'; +import { tracks } from '../../lib/ai/course'; +const titles = Object.fromEntries(tracks.flatMap((t) => t.modules.map((m) => [m.id, m.title]))); +--- +<AiLayout title="Practice" description="Spaced-repetition flashcards and mixed quiz review for the AI Engineer course." where="AI Engineer · Practice"> + <div class="kicker">Practice</div> + <h1 class="page-h">Keep it fresh</h1> + <p class="page-sub">Spaced repetition keeps the vocabulary fresh. Cards unlock as you start each module.</p> + <Practice client:only="preact" titles={titles} /> +</AiLayout> diff --git a/src/pages/ai-engineer/projects.astro b/src/pages/ai-engineer/projects.astro new file mode 100644 index 0000000..b50bd4b --- /dev/null +++ b/src/pages/ai-engineer/projects.astro @@ -0,0 +1,41 @@ +--- +import AiLayout from '../../layouts/AiLayout.astro'; +import { projects } from '../../lib/ai/course'; +--- +<AiLayout title="Projects" description="Portfolio capstone projects for the AI Engineer course." where="AI Engineer · Projects"> + <div class="kicker">Projects</div> + <h1 class="page-h">Portfolio</h1> + <p class="page-sub">The capstones are your portfolio. Mark one published once its write-up is public.</p> + <div class="stack"> + {projects.map((x, i) => ( + <details class="card" open={i === 0} data-project={x.template ? undefined : x.id}> + <summary><span>{x.title}</span>{!x.template && <span class="badge tc-teal" data-published hidden>published</span>}</summary> + <div class="prose" set:html={x.html} /> + {!x.template && ( + <div style="padding:0 22px 18px"> + <button class="btn sm" type="button" data-publish aria-pressed="false">Mark as published (+100 XP)</button> + </div> + )} + </details> + ))} + </div> +</AiLayout> + +<script> + import { get, subscribe, toggleChecked } from '../../lib/progress'; + const cards = [...document.querySelectorAll<HTMLElement>('[data-project]')]; + const paint = () => { + const p = get(); + for (const c of cards) { + const on = !!p.checked[c.dataset.project!]; + const btn = c.querySelector<HTMLButtonElement>('[data-publish]')!; + btn.textContent = on ? 'Mark as not published' : 'Mark as published (+100 XP)'; + btn.classList.toggle('ghost', on); + btn.setAttribute('aria-pressed', String(on)); + c.querySelector<HTMLElement>('[data-published]')!.hidden = !on; + } + }; + for (const c of cards) c.querySelector('[data-publish]')?.addEventListener('click', () => toggleChecked(c.dataset.project!, 100)); + paint(); + subscribe(paint); +</script> diff --git a/src/pages/ai-engineer/review.astro b/src/pages/ai-engineer/review.astro new file mode 100644 index 0000000..f04bc85 --- /dev/null +++ b/src/pages/ai-engineer/review.astro @@ -0,0 +1,9 @@ +--- +import Base from '../../layouts/Base.astro'; +import Review from '../../components/ai/Review'; +import { SITE_NAME } from '../../data/site'; +import '../../styles/ai.css'; +--- +<Base bare section="ai" title={`Mixed review · ${SITE_NAME}`} description="Eight random questions from the quizzes you have finished."> + <div class="tc-indigo"><Review client:only="preact" /></div> +</Base> diff --git a/src/pages/index.astro b/src/pages/index.astro index 4d14fb4..937add6 100644 --- a/src/pages/index.astro +++ b/src/pages/index.astro @@ -1,188 +1,51 @@ --- -import Base from '../layouts/Base.astro'; -import { SITE_NAME } from '../data/site'; -import { asOf } from '../data/problems-meta.json'; -import { all, groups, haystack, leetcodeUrl, PAGE as WALKTHROUGH } from '../data/catalog'; - -const worked = all.filter((p) => WALKTHROUGH[p.id]).length; +/* The hub: the two sections of the site, and where to pick up. */ +import AiLayout from '../layouts/AiLayout.astro'; +import Icon from '../components/Icon.astro'; +import { all, PAGE } from '../data/catalog'; +import { tracks, units } from '../lib/ai/course'; +import { quizzes } from '../lib/ai/quizzes'; + +const walkthroughs = all.filter((p) => PAGE[p.id]).length; +const modules = tracks.reduce((a, t) => a + t.modules.length, 0); +const questions = Object.values(quizzes).reduce((a, q) => a + q.length, 0); --- -<Base - title={`LeetCode · ${SITE_NAME}`} - description="LeetCode interview problems grouped by pattern, with step-by-step walkthroughs and tested code in five languages." -> - <div class="shell"> - <div class="page-head"> - <h1>LeetCode</h1> - <p class="lede"> - Interview problems, grouped by pattern. Open one to step through the solution, - with code in Ruby, Python, JavaScript, Go and Rust. - </p> - </div> - - <div class="plist"> - <aside class="cats"> - <nav aria-label="Patterns"> - <a class="cat" href="#top" data-cat="" aria-current="true"> - <span>All problems</span><span class="cat-n">{all.length}</span> - </a> - {groups.map((g) => ( - <a class="cat" href={`#${g.id}`} data-cat={g.id}> - <span>{g.name}</span><span class="cat-n">{g.rows.length}</span> - </a> - ))} - </nav> - </aside> - - <div class="plist-main" id="top"> - <form class="filters" role="search" data-filters hidden> - <label class="search"> - <svg viewBox="0 0 16 16" aria-hidden="true"><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M10.5 10.5 14 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg> - <input type="search" name="q" placeholder="Search by name, number or pattern" aria-label="Search problems" autocomplete="off" spellcheck="false"> - </label> - <select name="d" aria-label="Difficulty"> - <option value="">All difficulties</option> - <option value="easy">Easy</option> - <option value="medium">Medium</option> - <option value="hard">Hard</option> - </select> - <label class="only"> - <input type="checkbox" name="solved" value="1"> - <span>With a solution</span> - </label> - </form> - <p class="plist-count" aria-live="polite" data-summary> - {all.length} problems · {worked} with an interactive solution - </p> - - {groups.map((g) => ( - <section class="cat-sec" id={g.id} data-sec={g.id}> - <header> - <h2>{g.name}</h2> - <span data-sec-count>{g.rows.length} {g.rows.length === 1 ? 'problem' : 'problems'}</span> - </header> - <ul class="prows"> - {g.rows.map((p) => ( - <li - class={WALKTHROUGH[p.id] ? 'prow has-page' : 'prow'} - data-d={p.difficulty.toLowerCase()} - data-text={haystack(p)} - data-solved={WALKTHROUGH[p.id] ? '1' : undefined} - > - <span class="pnum">{p.id}</span> - <div class="pmain"> - {WALKTHROUGH[p.id] - ? <a class="ptitle" href={WALKTHROUGH[p.id]}>{p.title}</a> - : <span class="ptitle">{p.title}</span>} - <span class="psub"> - {!WALKTHROUGH[p.id] && <span class="soon">Solution coming soon</span>} - {p.extra && <span>Outside the core list</span>} - <a class="lc" href={leetcodeUrl(p.slug)} target="_blank" rel="noopener">View on LeetCode ↗</a> - </span> - </div> - <span class="ptags">{p.tags.slice(0, 3).join(' · ')}</span> - <span class={`diff ${p.difficulty.toLowerCase()}`}>{p.difficulty}</span> - <span class="prate" title={`Acceptance rate on LeetCode, as of ${asOf}`}>{p.acRate}</span> - </li> - ))} - </ul> - </section> - ))} - - <p class="plist-empty" data-empty hidden> - No problems match. <button type="button" data-clear>Clear the filters</button> - </p> - <p class="plist-foot">Difficulty, tags and acceptance rates from LeetCode, as of {asOf}.</p> +<AiLayout section="hub" where="Home" title="Home" description="LeetCode walkthroughs you can step through, and a self-study path from backend engineer to AI research engineer."> + <div class="kicker">learn.devmtnaing.com</div> + <h1 class="page-h">Practise the interview. Then go deeper.</h1> + <p class="page-sub"> + LeetCode problems you can step through one state change at a time, and a self-study path from backend engineer + to AI research engineer. XP, streaks and your daily goal count across both. + </p> + <div class="hub-sections"> + <a class="hub-card tc-teal" href="/leetcode"> + <div class="kicker" style="color:var(--ct)">LeetCode</div> + <h2>Interview problems</h2> + <p>Grouped by pattern. Each walkthrough quotes the problem, steps through the algorithm and ends with tested code in Ruby, Python, JavaScript, Go and Rust.</p> + <div class="hub-stats"> + <span><b>{all.length}</b>problems</span> + <span><b>{walkthroughs}</b>walkthroughs</span> + <span><b>5</b>languages</span> + </div> + <span class="go">Browse problems <Icon name="chevron" size={16} /></span> + </a> + <a class="hub-card tc-indigo" href="/ai-engineer"> + <div class="kicker" style="color:var(--ct)">AI Engineer</div> + <h2>Backend → research engineer</h2> + <p>Three tracks, each a job you can be hired for: AI application, ML systems, research. Concepts, resources, builds, quizzes and checkpoints.</p> + <div class="hub-stats"> + <span><b>{modules}</b>modules</span> + <span><b>{questions}</b>quiz questions</span> + <span><b>{units.length}</b>steps</span> </div> - </div> + <span class="go">Open the path <Icon name="chevron" size={16} /></span> + </a> </div> -</Base> - -<script> - // Search, difficulty and pattern filters. Everything is in the markup - // already, so without JavaScript the full list shows and the pattern links - // scroll to their section; this only hides rows. State lives in the URL - // (?q=&d=&solved=1#pattern) so a filtered list can be shared. - const form = document.querySelector<HTMLFormElement>('[data-filters]')!; - const q = form.elements.namedItem('q') as HTMLInputElement; - const d = form.elements.namedItem('d') as HTMLSelectElement; - const solved = form.elements.namedItem('solved') as HTMLInputElement; - const cats = [...document.querySelectorAll<HTMLAnchorElement>('.cat')]; - const secs = [...document.querySelectorAll<HTMLElement>('[data-sec]')]; - const summary = document.querySelector('[data-summary]')!; - const empty = document.querySelector<HTMLElement>('[data-empty]')!; - let cat = ''; - - const params = new URLSearchParams(location.search); - q.value = params.get('q') ?? ''; - d.value = params.get('d') ?? ''; - solved.checked = params.get('solved') === '1'; - const fromHash = location.hash.slice(1); - if (secs.some((s) => s.dataset.sec === fromHash)) cat = fromHash; - form.hidden = false; - - const plural = (n: number) => `${n} ${n === 1 ? 'problem' : 'problems'}`; - - function apply() { - const terms = q.value.toLowerCase().split(/\s+/).filter(Boolean); - const counts: Record<string, number> = {}; - let shown = 0, shownSolved = 0; - for (const sec of secs) { - let n = 0; - for (const row of sec.querySelectorAll<HTMLElement>('.prow')) { - const hit = (!d.value || row.dataset.d === d.value) - && (!solved.checked || row.dataset.solved) - && terms.every((t) => row.dataset.text!.includes(t)); - row.hidden = !hit; - if (hit) { n++; if (row.dataset.solved) shownSolved++; } - } - counts[sec.dataset.sec!] = n; - const inCat = !cat || sec.dataset.sec === cat; - sec.hidden = !inCat || n === 0; - sec.querySelector('[data-sec-count]')!.textContent = plural(n); - if (inCat) shown += n; - } - // Sidebar counts follow the search and difficulty, not the chosen pattern. - let total = 0; - for (const a of cats) { - const id = a.dataset.cat!; - const n = id ? counts[id] : 0; - total += n; - if (id) { - a.querySelector('.cat-n')!.textContent = String(n); - a.classList.toggle('none', n === 0); - } - a.setAttribute('aria-current', String(id === cat)); - } - cats[0].querySelector('.cat-n')!.textContent = String(total); - summary.textContent = shown - ? `${plural(shown)} · ${shownSolved} with an interactive solution` - : 'No problems match'; - empty.hidden = shown > 0; - - const next = new URLSearchParams(); - if (q.value) next.set('q', q.value); - if (d.value) next.set('d', d.value); - if (solved.checked) next.set('solved', '1'); - const url = `${location.pathname}${next.size ? `?${next}` : ''}${cat ? `#${cat}` : ''}`; - // Safari throws once a page calls replaceState too often (a held key in - // the search box); the filter has already applied, so only the URL lags. - try { history.replaceState(null, '', url); } catch { /* rate-limited */ } - } - - form.addEventListener('input', apply); - form.addEventListener('submit', (e) => e.preventDefault()); - for (const a of cats) { - a.addEventListener('click', (e) => { - e.preventDefault(); - cat = a.dataset.cat!; - apply(); - document.getElementById('top')!.scrollIntoView({ block: 'start' }); - }); - } - document.querySelector('[data-clear]')!.addEventListener('click', () => { - q.value = ''; d.value = ''; solved.checked = false; cat = ''; - apply(); - q.focus(); - }); - apply(); -</script> + <div class="track-hero" style="margin-top:28px"> + <div><div class="kicker">AI Engineer · pick up where you left off</div></div> + <a class="btn" href={units[0].url} data-continue hidden><Icon name="play" size={14} fill="currentColor" /> Continue: <span data-continue-label></span></a> + </div> + <div hidden> + {units.map((u) => <a href={u.url} data-unit={u.id} data-label={u.label} data-kind-label={u.label} data-mod-label={u.moduleLabel}></a>)} + </div> +</AiLayout> diff --git a/src/pages/leetcode/index.astro b/src/pages/leetcode/index.astro new file mode 100644 index 0000000..9edc331 --- /dev/null +++ b/src/pages/leetcode/index.astro @@ -0,0 +1,190 @@ +--- +import Base from '../../layouts/Base.astro'; +import { SITE_NAME } from '../../data/site'; +import { asOf } from '../../data/problems-meta.json'; +import { all, groups, haystack, leetcodeUrl, PAGE as WALKTHROUGH } from '../../data/catalog'; + +const worked = all.filter((p) => WALKTHROUGH[p.id]).length; +--- +<Base + section="leetcode" + where="LeetCode" + title={`LeetCode · ${SITE_NAME}`} + description="LeetCode interview problems grouped by pattern, with step-by-step walkthroughs and tested code in five languages." +> + <div class="shell"> + <div class="page-head"> + <h1>LeetCode</h1> + <p class="lede"> + Interview problems, grouped by pattern. Open one to step through the solution, + with code in Ruby, Python, JavaScript, Go and Rust. + </p> + </div> + + <div class="plist"> + <aside class="cats"> + <nav aria-label="Patterns"> + <a class="cat" href="#top" data-cat="" aria-current="true"> + <span>All problems</span><span class="cat-n">{all.length}</span> + </a> + {groups.map((g) => ( + <a class="cat" href={`#${g.id}`} data-cat={g.id}> + <span>{g.name}</span><span class="cat-n">{g.rows.length}</span> + </a> + ))} + </nav> + </aside> + + <div class="plist-main" id="top"> + <form class="filters" role="search" data-filters hidden> + <label class="search"> + <svg viewBox="0 0 16 16" aria-hidden="true"><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M10.5 10.5 14 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg> + <input type="search" name="q" placeholder="Search by name, number or pattern" aria-label="Search problems" autocomplete="off" spellcheck="false"> + </label> + <select name="d" aria-label="Difficulty"> + <option value="">All difficulties</option> + <option value="easy">Easy</option> + <option value="medium">Medium</option> + <option value="hard">Hard</option> + </select> + <label class="only"> + <input type="checkbox" name="solved" value="1"> + <span>With a solution</span> + </label> + </form> + <p class="plist-count" aria-live="polite" data-summary> + {all.length} problems · {worked} with an interactive solution + </p> + + {groups.map((g) => ( + <section class="cat-sec" id={g.id} data-sec={g.id}> + <header> + <h2>{g.name}</h2> + <span data-sec-count>{g.rows.length} {g.rows.length === 1 ? 'problem' : 'problems'}</span> + </header> + <ul class="prows"> + {g.rows.map((p) => ( + <li + class={WALKTHROUGH[p.id] ? 'prow has-page' : 'prow'} + data-d={p.difficulty.toLowerCase()} + data-text={haystack(p)} + data-solved={WALKTHROUGH[p.id] ? '1' : undefined} + > + <span class="pnum">{p.id}</span> + <div class="pmain"> + {WALKTHROUGH[p.id] + ? <a class="ptitle" href={WALKTHROUGH[p.id]}>{p.title}</a> + : <span class="ptitle">{p.title}</span>} + <span class="psub"> + {!WALKTHROUGH[p.id] && <span class="soon">Solution coming soon</span>} + {p.extra && <span>Outside the core list</span>} + <a class="lc" href={leetcodeUrl(p.slug)} target="_blank" rel="noopener">View on LeetCode ↗</a> + </span> + </div> + <span class="ptags">{p.tags.slice(0, 3).join(' · ')}</span> + <span class={`diff ${p.difficulty.toLowerCase()}`}>{p.difficulty}</span> + <span class="prate" title={`Acceptance rate on LeetCode, as of ${asOf}`}>{p.acRate}</span> + </li> + ))} + </ul> + </section> + ))} + + <p class="plist-empty" data-empty hidden> + No problems match. <button type="button" data-clear>Clear the filters</button> + </p> + <p class="plist-foot">Difficulty, tags and acceptance rates from LeetCode, as of {asOf}.</p> + </div> + </div> + </div> +</Base> + +<script> + // Search, difficulty and pattern filters. Everything is in the markup + // already, so without JavaScript the full list shows and the pattern links + // scroll to their section; this only hides rows. State lives in the URL + // (?q=&d=&solved=1#pattern) so a filtered list can be shared. + const form = document.querySelector<HTMLFormElement>('[data-filters]')!; + const q = form.elements.namedItem('q') as HTMLInputElement; + const d = form.elements.namedItem('d') as HTMLSelectElement; + const solved = form.elements.namedItem('solved') as HTMLInputElement; + const cats = [...document.querySelectorAll<HTMLAnchorElement>('.cat')]; + const secs = [...document.querySelectorAll<HTMLElement>('[data-sec]')]; + const summary = document.querySelector('[data-summary]')!; + const empty = document.querySelector<HTMLElement>('[data-empty]')!; + let cat = ''; + + const params = new URLSearchParams(location.search); + q.value = params.get('q') ?? ''; + d.value = params.get('d') ?? ''; + solved.checked = params.get('solved') === '1'; + const fromHash = location.hash.slice(1); + if (secs.some((s) => s.dataset.sec === fromHash)) cat = fromHash; + form.hidden = false; + + const plural = (n: number) => `${n} ${n === 1 ? 'problem' : 'problems'}`; + + function apply() { + const terms = q.value.toLowerCase().split(/\s+/).filter(Boolean); + const counts: Record<string, number> = {}; + let shown = 0, shownSolved = 0; + for (const sec of secs) { + let n = 0; + for (const row of sec.querySelectorAll<HTMLElement>('.prow')) { + const hit = (!d.value || row.dataset.d === d.value) + && (!solved.checked || row.dataset.solved) + && terms.every((t) => row.dataset.text!.includes(t)); + row.hidden = !hit; + if (hit) { n++; if (row.dataset.solved) shownSolved++; } + } + counts[sec.dataset.sec!] = n; + const inCat = !cat || sec.dataset.sec === cat; + sec.hidden = !inCat || n === 0; + sec.querySelector('[data-sec-count]')!.textContent = plural(n); + if (inCat) shown += n; + } + // Sidebar counts follow the search and difficulty, not the chosen pattern. + let total = 0; + for (const a of cats) { + const id = a.dataset.cat!; + const n = id ? counts[id] : 0; + total += n; + if (id) { + a.querySelector('.cat-n')!.textContent = String(n); + a.classList.toggle('none', n === 0); + } + a.setAttribute('aria-current', String(id === cat)); + } + cats[0].querySelector('.cat-n')!.textContent = String(total); + summary.textContent = shown + ? `${plural(shown)} · ${shownSolved} with an interactive solution` + : 'No problems match'; + empty.hidden = shown > 0; + + const next = new URLSearchParams(); + if (q.value) next.set('q', q.value); + if (d.value) next.set('d', d.value); + if (solved.checked) next.set('solved', '1'); + const url = `${location.pathname}${next.size ? `?${next}` : ''}${cat ? `#${cat}` : ''}`; + // Safari throws once a page calls replaceState too often (a held key in + // the search box); the filter has already applied, so only the URL lags. + try { history.replaceState(null, '', url); } catch { /* rate-limited */ } + } + + form.addEventListener('input', apply); + form.addEventListener('submit', (e) => e.preventDefault()); + for (const a of cats) { + a.addEventListener('click', (e) => { + e.preventDefault(); + cat = a.dataset.cat!; + apply(); + document.getElementById('top')!.scrollIntoView({ block: 'start' }); + }); + } + document.querySelector('[data-clear]')!.addEventListener('click', () => { + q.value = ''; d.value = ''; solved.checked = false; cat = ''; + apply(); + q.focus(); + }); + apply(); +</script> diff --git a/src/pages/profile.astro b/src/pages/profile.astro new file mode 100644 index 0000000..392c0c9 --- /dev/null +++ b/src/pages/profile.astro @@ -0,0 +1,16 @@ +--- +import AiLayout from '../layouts/AiLayout.astro'; +import Profile from '../components/ai/Profile'; +import { tracks, trackUrl, units } from '../lib/ai/course'; +const summary = tracks.map((t) => ({ + id: t.id, url: trackUrl(t), short: t.short, title: t.title, color: t.color, + units: units.filter((u) => u.track === t.id).map((u) => u.id), + modules: t.modules.map((m) => m.id), +})); +--- +<AiLayout section="hub" title="Profile" description="Your progress across the site." where="Profile"> + <div class="kicker">Profile</div> + <h1 class="page-h">Your progress</h1> + <p class="page-sub">XP and streaks count across the whole site.</p> + <Profile client:only="preact" tracks={summary} /> +</AiLayout> diff --git a/src/pages/search.json.ts b/src/pages/search.json.ts index ef1480d..1ec1fee 100644 --- a/src/pages/search.json.ts +++ b/src/pages/search.json.ts @@ -1,7 +1,8 @@ -/* The site search's index, built with the site: every problem in the home - * page's order. The search dialog fetches it the first time it opens, so no - * page carries the list in its HTML. */ +/* The site search's index, built with the site: every problem in the problem + * list's order, then every AI Engineer module. The search dialog fetches it + * the first time it opens, so no page carries the list in its HTML. */ import { groups, haystack, leetcodeUrl, PAGE } from '../data/catalog'; +import { moduleUrl, tracks } from '../lib/ai/course'; export function GET() { const rows = groups.flatMap((g) => g.rows.map((p) => ({ @@ -14,5 +15,15 @@ export function GET() { page: p.id in PAGE, text: haystack(p), }))); - return new Response(JSON.stringify(rows), { headers: { 'content-type': 'application/json' } }); + const modules = tracks.flatMap((t) => t.modules.map((m) => ({ + id: m.label, + title: m.title, + difficulty: '', + category: `AI Engineer · ${t.short}`, + href: moduleUrl(t, m), + page: true, + kind: 'module', + text: [m.label, m.title, t.short, t.title, 'ai engineer', ...m.concepts.map((c) => c.replace(/<[^>]+>/g, ''))].join(' ').toLowerCase(), + }))); + return new Response(JSON.stringify([...rows, ...modules]), { headers: { 'content-type': 'application/json' } }); } diff --git a/src/styles/ai.css b/src/styles/ai.css new file mode 100644 index 0000000..0a672c8 --- /dev/null +++ b/src/styles/ai.css @@ -0,0 +1,310 @@ +/* The AI Engineer section: path, module cards, lesson sessions, practice. + Colours come from tokens.css; the names below are the section's own + shorthands for them. Track colours: --c solid, --ce edge, --cs soft tint, + --ct text on the tint (AA on --cs, --surface and --ground). */ +:root{ + --bg:var(--ground); + --bg-2:var(--sunk); + --card:var(--surface); + --muted:var(--ink-3); + --accent-ink:var(--accent); + --xp:#E8960F; + --streak:#E8592C; + --ok:var(--up); + --ok-edge:#105A3D; + --ok-soft:var(--up-soft); + --bad:var(--down); + --bad-edge:#7E2A1F; + --bad-soft:var(--down-soft); + --radius:18px; +} +.tc-slate{--c:#5F6B85;--ce:#46506A;--cs:#E9ECF3;--ct:#3D465C} +.tc-teal{--c:#0B7077;--ce:#08545A;--cs:#DCF1F0;--ct:#08545A} +.tc-indigo{--c:#5141E0;--ce:#3A2DB8;--cs:#ECEBFF;--ct:#3A2DB8} +.tc-rose{--c:#C2346A;--ce:#962550;--cs:#FDE8EF;--ct:#962550} +.tc-amber{--c:#B4650A;--ce:#8A4C06;--cs:#FDF0DC;--ct:#7F4605} +@media (prefers-color-scheme: dark){ + :root:not([data-theme="light"]){--xp:#F5B03C;--streak:#F2784F;--ok-edge:#2E8F62;--bad-edge:#B0533F} + :root:not([data-theme="light"]) .tc-slate{--c:#8792AE;--ce:#5F6B85;--cs:#232838;--ct:#B5BDD2} + :root:not([data-theme="light"]) .tc-teal{--c:#4FC0C9;--ce:#2A8F97;--cs:#103539;--ct:#6FD3DA} + :root:not([data-theme="light"]) .tc-indigo{--c:#A39AFF;--ce:#6E61E6;--cs:#25204F;--ct:#BDB6FF} + :root:not([data-theme="light"]) .tc-rose{--c:#F27AA3;--ce:#C2346A;--cs:#3A1726;--ct:#F7A6C2} + :root:not([data-theme="light"]) .tc-amber{--c:#F0A93E;--ce:#B4650A;--cs:#3A2A10;--ct:#F7C46E} +} +:root[data-theme="dark"]{--xp:#F5B03C;--streak:#F2784F;--ok-edge:#2E8F62;--bad-edge:#B0533F} +:root[data-theme="dark"] .tc-slate{--c:#8792AE;--ce:#5F6B85;--cs:#232838;--ct:#B5BDD2} +:root[data-theme="dark"] .tc-teal{--c:#4FC0C9;--ce:#2A8F97;--cs:#103539;--ct:#6FD3DA} +:root[data-theme="dark"] .tc-indigo{--c:#A39AFF;--ce:#6E61E6;--cs:#25204F;--ct:#BDB6FF} +:root[data-theme="dark"] .tc-rose{--c:#F27AA3;--ce:#C2346A;--cs:#3A1726;--ct:#F7A6C2} +:root[data-theme="dark"] .tc-amber{--c:#F0A93E;--ce:#B4650A;--cs:#3A2A10;--ct:#F7C46E} + +.ai-page{padding:28px clamp(16px,3vw,40px) 72px} +.kicker{font-family:var(--mono);font-size:11px;font-weight:600;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)} +/* ───────── generic ───────── */ +.card { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); padding: 16px 18px; } +a.card { text-decoration: none; display: block; transition: border-color 0.15s, transform 0.15s; } +a.card:hover { border-color: color-mix(in srgb, var(--accent) 40%, var(--line)); } +a.card.row, .card.row { display: flex; } +.row { display: flex; align-items: center; gap: 12px; } +.row .grow, .grow { flex: 1; min-width: 0; } +.row b { display: block; font-weight: 700; } +.row small { color: var(--muted); font-size: 12.5px; font-weight: 500; } +.chip-icon { width: 38px; height: 38px; border-radius: 11px; display: grid; place-items: center; flex: none; } +.meter { height: 8px; background: var(--bg-2); border-radius: 99px; overflow: hidden; } +.meter > i { display: block; height: 100%; border-radius: 99px; background: var(--c, var(--accent)); transition: width 0.4s; } +.page-top { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; flex-wrap: wrap; margin-bottom: 22px; } +.page-h { font-size: clamp(24px, 2.4vw, 32px); font-weight: 700; margin: 6px 0 6px; } +.page-sub { color: var(--muted); font-weight: 500; margin: 0 0 22px; max-width: 72ch; line-height: 1.55; } +.section-title { font-family: var(--mono); font-size: 11.5px; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); margin: 28px 0 12px; } +.stack { display: flex; flex-direction: column; gap: 12px; } +.grid-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(320px, 100%), 1fr)); gap: 14px; } + +/* buttons: chunky with a bottom edge */ +.btn { + border: 0; border-radius: 12px; padding: 12px 20px; font-weight: 700; font-size: 14.5px; + background: var(--accent); color: var(--on-accent); box-shadow: 0 4px 0 var(--accent-edge); + transition: transform 0.06s, box-shadow 0.06s, filter 0.15s; text-decoration: none; + display: inline-flex; align-items: center; justify-content: center; gap: 8px; white-space: nowrap; +} +.btn:hover { filter: brightness(1.06); } +.btn:active { transform: translateY(3px); box-shadow: 0 1px 0 var(--accent-edge); } +.btn:disabled { background: var(--bg-2); color: var(--muted); box-shadow: 0 4px 0 var(--line); cursor: default; filter: none; } +.btn.ghost { background: var(--card); color: var(--ink); box-shadow: 0 0 0 1.5px var(--line), 0 4px 0 var(--line); } +.btn.track { background: var(--c); box-shadow: 0 4px 0 var(--ce); } +.btn.ok { background: var(--ok); box-shadow: 0 4px 0 var(--ok-edge); } +.btn.red { background: var(--bad); box-shadow: 0 4px 0 var(--bad-edge); } +.btn.sm { padding: 8px 14px; font-size: 13px; border-radius: 10px; } +.seg { display: inline-flex; background: var(--bg-2); border-radius: 12px; padding: 4px; gap: 2px; flex-wrap: wrap; } +.seg button { border: 0; background: none; padding: 7px 14px; border-radius: 9px; font-weight: 600; font-size: 13px; color: var(--muted); } +.seg button.on { background: var(--card); color: var(--ink); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); } + +/* ───────── track picker ───────── */ +.track-tabs { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 12px; margin-bottom: 30px; } +.track-tab { + text-align: left; background: var(--card); border: 1.5px solid var(--line); border-radius: 16px; padding: 14px 14px 12px; + display: flex; flex-direction: column; gap: 4px; position: relative; overflow: hidden; box-shadow: var(--shadow); +} +.track-tab::before { content: ''; position: absolute; inset: 0 0 auto; height: 4px; background: var(--c); } +.track-tab b { font-family: var(--display); font-size: 14.5px; font-weight: 600; line-height: 1.25; min-height: 2.5em; } +.track-tab small { font-family: var(--mono); font-size: 11px; color: var(--muted); } +.track-tab .meter { margin: 6px 0 2px; height: 6px; } +.track-tab .kicker { color: var(--ct); } +.track-tab:hover { border-color: var(--c); } +.track-tab.on { border-color: var(--c); background: var(--cs); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c) 18%, transparent); } + +/* ───────── path: timeline of module cards ───────── */ +.track-hero { display: flex; gap: 20px; align-items: flex-end; justify-content: space-between; flex-wrap: wrap; margin-bottom: 20px; } +.track-hero h1 { font-size: clamp(24px, 2.6vw, 34px); font-weight: 700; margin-top: 4px; } +.track-hero p { margin: 6px 0 0; color: var(--muted); font-weight: 500; } +.timeline { list-style: none; margin: 0; padding: 0; position: relative; } +.timeline::before { content: ''; position: absolute; left: 22px; top: 24px; bottom: 24px; width: 2px; background: repeating-linear-gradient(to bottom, var(--line) 0 6px, transparent 6px 12px); } +.mod { display: grid; grid-template-columns: 46px minmax(0, 1fr); gap: 18px; margin-bottom: 16px; position: relative; } +.spine-dot { + width: 46px; height: 46px; border-radius: 14px; display: grid; place-items: center; position: relative; z-index: 1; + background: var(--card); border: 1.5px solid var(--line); font-family: var(--mono); font-size: 12px; font-weight: 700; color: var(--muted); margin-top: 18px; +} +.mod.started .spine-dot { border-color: var(--c); color: var(--ct); background: var(--cs); } +.mod.crowned .spine-dot { background: var(--c); border-color: var(--c); color: var(--on-accent); box-shadow: 0 3px 0 var(--ce); } +.mod-card { background: var(--card); border: 1.5px solid var(--line); border-radius: 20px; padding: 20px 22px 18px; box-shadow: var(--shadow); } +.mod.current .mod-card { border-color: var(--c); box-shadow: 0 0 0 4px color-mix(in srgb, var(--c) 14%, transparent), var(--shadow); } +.mod-head { display: flex; gap: 16px; align-items: flex-start; justify-content: space-between; } +.mod-head h2 { font-size: clamp(17px, 1.5vw, 20px); font-weight: 600; margin: 4px 0 6px; } +.mod-why { margin: 0; color: var(--muted); font-size: 14px; line-height: 1.5; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; max-width: 90ch; } +.mod-why a { color: inherit; } +.mod-actions { display: flex; gap: 8px; flex: none; } +.badge { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 99px; background: var(--cs); color: var(--ct); font-family: var(--mono); font-size: 10.5px; font-weight: 600; letter-spacing: 0.04em; vertical-align: 1px; margin-left: 6px; } +.stepper { display: flex; margin-top: 18px; padding-top: 16px; border-top: 1px dashed var(--line); } +.step { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: center; gap: 8px; background: none; border: 0; padding: 0; position: relative; } +.step + .step::before { content: ''; position: absolute; top: 21px; right: 50%; width: 100%; height: 3px; background: var(--bg-2); z-index: 0; border-radius: 3px; } +.step.linked::before { background: var(--c) !important; } +.step-dot { + width: 44px; height: 44px; border-radius: 50%; display: grid; place-items: center; position: relative; z-index: 1; + background: var(--bg-2); color: var(--muted); border: 2px solid transparent; transition: transform 0.12s; +} +.step:hover .step-dot { transform: translateY(-2px); } +.step.done .step-dot { background: var(--c); color: var(--on-accent); box-shadow: 0 3px 0 var(--ce); } +.step.current .step-dot { background: var(--card); color: var(--c); border-color: var(--c); box-shadow: 0 0 0 5px var(--cs); animation: pulse 2s ease-in-out infinite; } +.step.trophy.done .step-dot { background: var(--xp); box-shadow: 0 3px 0 #c47f0c; } +.step-label { font-size: 12px; font-weight: 600; color: var(--muted); } +.step.current .step-label { color: var(--ct); font-weight: 700; } +@keyframes pulse { 50% { box-shadow: 0 0 0 9px var(--cs); } } + +/* ───────── rail ───────── */ +.panel-title { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; } +.stat-tiles { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; } +.tile { background: var(--bg-2); border-radius: 14px; padding: 10px; display: flex; flex-direction: column; gap: 2px; } +.tile .ic { width: 26px; height: 26px; border-radius: 8px; display: grid; place-items: center; margin-bottom: 4px; } +.tile b { font-family: var(--display); font-size: 20px; font-weight: 700; } +.tile small { color: var(--muted); font-size: 11.5px; font-weight: 600; } +.week { display: grid; grid-template-columns: repeat(7, 1fr); gap: 8px; align-items: end; height: 92px; margin-top: 6px; } +.week div { display: flex; flex-direction: column; align-items: center; gap: 6px; height: 100%; justify-content: flex-end; } +.week i { width: 100%; max-width: 26px; border-radius: 7px 7px 4px 4px; background: color-mix(in srgb, var(--accent) 35%, var(--bg-2)); min-height: 4px; } +.week .today i { background: var(--accent); } +.week span { font-family: var(--mono); font-size: 10.5px; color: var(--muted); } +.upnext { background: linear-gradient(135deg, var(--c), var(--ce)); border: 0; color: var(--on-accent); } +.upnext small, .upnext .kicker { color: inherit; opacity: .85; } +.upnext .chip-icon { background: color-mix(in srgb, var(--on-accent) 18%, transparent); } +.stat-strip { display: none; gap: 10px; flex-wrap: wrap; margin-bottom: 20px; } +.stat-strip .s { display: flex; align-items: center; gap: 6px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 7px 12px; font-weight: 700; font-size: 14px; } +.stat-strip .s small { color: var(--muted); font-weight: 500; } + +/* ───────── session ───────── */ +.session { min-height: 100vh; display: flex; flex-direction: column; background: radial-gradient(1200px 500px at 50% -200px, var(--cs, var(--accent-soft)), transparent 70%), var(--bg); } +.session-top { width: 100%; max-width: 1120px; margin: 0 auto; display: flex; align-items: center; gap: 16px; padding: 22px 24px 8px; } +.close { background: none; border: 0; color: var(--muted); padding: 4px; border-radius: 8px; } +.close:hover { color: var(--ink); } +.bar { flex: 1; height: 12px; background: var(--bg-2); border-radius: 99px; overflow: hidden; } +.bar > i { display: block; height: 100%; background: var(--c, var(--accent)); border-radius: 99px; transition: width 0.35s; } +.hearts { display: flex; align-items: center; gap: 4px; color: var(--bad); font-weight: 800; font-family: var(--mono); } +.session-body { flex: 1; width: 100%; max-width: 1120px; margin: 0 auto; padding: 28px 24px 150px; } +.session-body h1 { font-size: clamp(24px, 2.6vw, 32px); font-weight: 700; margin-bottom: 8px; } +.pill { display: inline-flex; align-items: center; gap: 6px; background: var(--cs, var(--accent-soft)); color: var(--ct, var(--accent-ink)); font-family: var(--mono); font-weight: 600; font-size: 11.5px; letter-spacing: 0.04em; padding: 5px 12px; border-radius: 99px; margin-bottom: 14px; text-transform: uppercase; } +.lead { font-size: 17px; line-height: 1.6; font-weight: 500; max-width: 75ch; } +.concepts { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(240px, 100%), 1fr)); gap: 10px; } +.concept { background: var(--card); border: 1.5px solid var(--line); border-left: 4px solid var(--c, var(--accent)); border-radius: 12px; padding: 10px 14px; font-weight: 600; font-size: 14px; line-height: 1.4; } +.checklist { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(380px, 100%), 1fr)); gap: 10px; margin-top: 16px; } +.check { + display: flex; gap: 12px; align-items: flex-start; text-align: left; width: 100%; + background: var(--card); border: 1.5px solid var(--line); border-radius: 14px; padding: 14px; font-weight: 500; font-size: 14.5px; line-height: 1.5; box-shadow: 0 2px 0 var(--line); +} +.check:hover { border-color: color-mix(in srgb, var(--c, var(--accent)) 50%, var(--line)); } +.check.on { border-color: var(--c, var(--ok)); background: var(--cs, var(--ok-soft)); } +.box { width: 24px; height: 24px; border-radius: 7px; border: 2px solid var(--line); display: grid; place-items: center; flex: none; margin-top: 1px; color: var(--on-accent); background: var(--card); } +.check.on .box { background: var(--c, var(--ok)); border-color: var(--c, var(--ok)); color: var(--on-accent); } +.check .tag { font-family: var(--mono); font-size: 10px; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); display: block; margin-bottom: 3px; } +.check a { color: var(--accent); font-weight: 700; text-decoration-thickness: 1.5px; text-underline-offset: 2px; } +.check ol { margin: 6px 0 0; padding-left: 20px; font-size: 13.5px; color: var(--muted); } +.optional-toggle { margin-top: 18px; background: none; border: 0; font-weight: 700; color: var(--muted); display: inline-flex; align-items: center; gap: 6px; padding: 6px 0; text-decoration: none; } +.optional-toggle:hover { color: var(--ink); } + +.options { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(320px, 100%), 1fr)); gap: 10px; margin-top: 22px; } +.option { + display: flex; gap: 14px; align-items: center; text-align: left; width: 100%; + background: var(--card); border: 1.5px solid var(--line); border-radius: 14px; padding: 16px; font-weight: 600; font-size: 15px; box-shadow: 0 3px 0 var(--line); +} +.option:hover:not(:disabled) { border-color: var(--accent); } +.option .k { width: 28px; height: 28px; border-radius: 8px; background: var(--bg-2); display: grid; place-items: center; font-family: var(--mono); font-size: 12px; font-weight: 700; color: var(--muted); flex: none; } +.option.sel { border-color: var(--accent); background: var(--accent-soft); box-shadow: 0 3px 0 var(--accent); } +.option.sel .k { background: var(--accent); color: var(--on-accent); } +.option.right { border-color: var(--ok); background: var(--ok-soft); box-shadow: 0 3px 0 var(--ok); } +.option.right .k { background: var(--ok); color: var(--on-accent); } +.option.wrong { border-color: var(--bad); background: var(--bad-soft); box-shadow: 0 3px 0 var(--bad); } +.option.wrong .k { background: var(--bad); color: var(--on-accent); } +.option:disabled { cursor: default; } + +.footer { position: fixed; left: 0; right: 0; bottom: 0; border-top: 1px solid var(--line); background: color-mix(in srgb, var(--bg) 88%, transparent); backdrop-filter: blur(10px); } +.footer.ok { background: var(--ok-soft); border-color: color-mix(in srgb, var(--ok) 35%, transparent); } +.footer.bad { background: var(--bad-soft); border-color: color-mix(in srgb, var(--bad) 35%, transparent); } +.footer-in { max-width: 1120px; margin: 0 auto; padding: 18px 24px; display: flex; align-items: center; justify-content: space-between; gap: 16px; } +.footer .msg { max-width: 70ch; } +.footer .msg b { display: block; font-family: var(--display); font-size: 18px; font-weight: 700; } +.footer.ok .msg b { color: var(--ok); } +.footer.bad .msg b { color: var(--bad); } +.footer .msg span { font-weight: 500; font-size: 14px; } +.kbd { font-size: 12px; color: var(--muted); font-weight: 500; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.kbd kbd { font-family: var(--mono); font-size: 11px; border: 1px solid var(--line); border-bottom-width: 3px; border-radius: 6px; padding: 1px 6px; background: var(--card); } + +.done-screen { text-align: center; padding-top: 48px; } +.done-screen .big { width: 120px; height: 120px; border-radius: 34px; margin: 0 auto 20px; display: grid; place-items: center; background: var(--cs, var(--accent-soft)); color: var(--c, var(--accent)); } +.done-screen .lead { margin: 8px auto 0; color: var(--muted); } +.xp-pills { display: flex; gap: 12px; justify-content: center; margin-top: 26px; flex-wrap: wrap; } +.xp-pill { border: 1.5px solid var(--line); border-radius: 16px; min-width: 140px; background: var(--card); padding: 12px 16px; box-shadow: var(--shadow); } +.xp-pill small { display: block; font-family: var(--mono); font-size: 10.5px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); } +.xp-pill b { display: flex; justify-content: center; align-items: center; gap: 6px; font-family: var(--display); font-size: 24px; margin-top: 4px; } + +/* ───────── pages ───────── */ +.prose { line-height: 1.7; font-size: 15.5px; max-width: 90ch; } +.prose a { color: var(--accent); font-weight: 600; } +.prose h2, .prose h3 { margin: 26px 0 10px; font-weight: 600; } +.prose strong { font-weight: 700; } +.prose table { border-collapse: collapse; width: 100%; font-size: 14px; display: block; overflow-x: auto; } +.prose th, .prose td { border: 1px solid var(--line); padding: 7px 10px; text-align: left; } +.prose th { background: var(--bg-2); } +.prose pre { background: var(--bg-2); border: 1px solid var(--line); padding: 14px; border-radius: 12px; overflow-x: auto; font-size: 13px; } +.prose pre code { background: none; padding: 0; } +.prose ul, .prose ol { padding-left: 22px; } +.prose input[type='checkbox'] { accent-color: var(--accent); } +.guide-hero { border-radius: 22px; padding: 26px 28px; background: linear-gradient(135deg, var(--c), var(--ce)); color: var(--on-accent); margin: 10px 0 26px; } +.guide-hero .kicker { color: inherit; opacity: .85; } +.guide-hero h1 { font-size: clamp(24px, 2.6vw, 34px); margin-top: 6px; } +details.card { padding: 0; } +details.card summary { list-style: none; padding: 18px 20px; font-family: var(--display); font-weight: 600; font-size: 16px; display: flex; justify-content: space-between; align-items: center; gap: 10px; cursor: pointer; } +details.card summary::-webkit-details-marker { display: none; } +details.card[open] summary { border-bottom: 1px solid var(--line); } +details.card .prose { padding: 6px 22px 18px; max-width: none; } +.paper-meta { color: var(--muted); font-size: 12.5px; font-weight: 500; display: block; margin-top: 2px; } + +.flash { perspective: 1200px; margin: 24px auto 0; max-width: 560px; height: 300px; } +.flash-in { position: relative; width: 100%; height: 100%; transition: transform 0.5s; transform-style: preserve-3d; cursor: pointer; } +.flash-in.flip { transform: rotateY(180deg); } +.face { position: absolute; inset: 0; backface-visibility: hidden; border-radius: 22px; display: grid; place-items: center; padding: 28px; text-align: center; background: var(--card); border: 1.5px solid var(--line); box-shadow: var(--shadow), 0 5px 0 var(--line); } +.face.front { background: linear-gradient(135deg, var(--accent-soft), var(--card)); } +.face.front b { font-family: var(--display); font-size: 30px; font-weight: 700; } +.face.back { transform: rotateY(180deg); font-size: 17px; font-weight: 500; line-height: 1.55; } +.face .hint { position: absolute; bottom: 14px; font-family: var(--mono); font-size: 11px; color: var(--muted); } + +.choice { display: flex; gap: 14px; align-items: center; text-align: left; width: 100%; background: var(--card); border: 1.5px solid var(--line); border-radius: 16px; padding: 14px 16px; margin-top: 10px; box-shadow: 0 3px 0 var(--line); } +.choice:hover { border-color: var(--c, var(--accent)); } +.choice .e { width: 40px; height: 40px; border-radius: 12px; display: grid; place-items: center; background: var(--cs, var(--accent-soft)); color: var(--c, var(--accent)); flex: none; } +.choice b { display: block; font-weight: 700; } +.choice small { color: var(--muted); font-weight: 500; } +.steps { display: flex; gap: 8px; margin-bottom: 32px; } +.steps i { flex: 1; height: 5px; border-radius: 9px; background: var(--bg-2); } +.steps i.on { background: var(--accent); } + + +/* ───────── onboarding card ───────── */ +.onb-card{border:1.5px solid var(--accent);background:linear-gradient(135deg,var(--accent-soft),var(--card));margin-bottom:24px} +.choices{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(240px,100%),1fr));gap:10px;margin-top:12px} +.choices .choice{margin-top:0} + +/* ───────── hub ───────── */ +.hub-sections{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(340px,100%),1fr));gap:16px} +.hub-card{position:relative;overflow:hidden;border-radius:22px;padding:24px;text-decoration:none;display:flex;flex-direction:column;gap:10px;min-height:220px; + background:var(--card);border:1.5px solid var(--line);box-shadow:var(--shadow)} +.hub-card::after{content:"";position:absolute;right:-60px;top:-60px;width:220px;height:220px;border-radius:50%;background:var(--cs);opacity:.9} +.hub-card > *{position:relative;z-index:1} +.hub-card:hover{border-color:var(--c)} +.hub-card h2{font-size:26px;font-weight:700} +.hub-card p{margin:0;color:var(--muted);line-height:1.55;max-width:52ch} +.hub-card .go{margin-top:auto;display:inline-flex;gap:6px;align-items:center;font-weight:700;color:var(--ct)} +.hub-stats{display:flex;gap:18px;flex-wrap:wrap;font-family:var(--mono);font-size:12px;color:var(--muted)} +.hub-stats b{color:var(--ink);font-family:var(--display);font-size:20px;display:block} + +@media (max-width:1439px){ .stat-strip{display:flex} } +@media (max-width:1200px){ .track-tabs{grid-template-columns:repeat(auto-fill,minmax(170px,1fr))} } +@media (max-width:719px){ + .ai-page{padding:18px 16px 40px} + .track-tabs{display:flex;overflow-x:auto;scroll-snap-type:x mandatory;margin:0 -16px 24px;padding:2px 16px 6px;scrollbar-width:none} + .track-tab{min-width:160px;scroll-snap-align:start} + .timeline::before{left:15px} + .mod{grid-template-columns:32px minmax(0,1fr);gap:10px} + .spine-dot{width:32px;height:32px;border-radius:10px;font-size:10px} + .mod-card{padding:16px} + .mod-head{flex-direction:column} + .step-dot{width:38px;height:38px} + .step + .step::before{top:18px} + .step-label{font-size:10.5px} + .checklist,.options,.concepts{grid-template-columns:1fr} + .session-body{padding:18px 16px 170px} + .footer-in{padding:14px 16px} + .kbd{display:none} + .hub-sections{grid-template-columns:1fr} +} + +/* links styled as cards or choices keep their own colour */ +a.choice{text-decoration:none;color:inherit} +/* a step shows its kind icon until done, then a tick (the checkpoint keeps its trophy) */ +.step{text-decoration:none;color:inherit} +.step .ic-done{display:none} +.step.done:not(.trophy) .ic-done{display:block} +.step.done:not(.trophy) .ic-kind{display:none} +.track-tab{text-decoration:none;color:inherit} +div.check{cursor:pointer} +button.box{padding:0;cursor:pointer} +/* cards and choices that are links keep the text colour, not the link colour */ +a.card,a.hub-card,a.choice,a.track-tab,a.step{color:var(--ink)} +a.card.upnext{color:var(--on-accent)} +.ai-page .prose a,.session .prose a{color:var(--accent)} +.prose li:has(> .task){list-style:none;margin-left:-20px} +.prose .task{color:var(--muted);font-size:1.05em} diff --git a/src/styles/app.css b/src/styles/app.css new file mode 100644 index 0000000..8960a1a --- /dev/null +++ b/src/styles/app.css @@ -0,0 +1,97 @@ +/* The app shell shared by every section: a dark sidebar, the page column + (a sticky 56px top bar, the page, the footer) and, on pages that have one, + a progress rail on the right. Lesson CSS offsets its sticky parts by the + 56px bar, so keep that height. + + ≥1440px sidebar · page · rail + <1440px the rail is hidden; pages show a compact stat strip instead + <1024px the sidebar shrinks to icons + <720px the sidebar becomes a bottom tab bar */ +.app{display:grid;grid-template-columns:248px minmax(0,1fr);min-height:100vh} +.app.has-rail{grid-template-columns:248px minmax(0,1fr) 340px} +:root[data-nav="collapsed"] .app{grid-template-columns:76px minmax(0,1fr)} +:root[data-nav="collapsed"] .app.has-rail{grid-template-columns:76px minmax(0,1fr) 340px} +.app-main{min-width:0;display:flex;flex-direction:column} + +/* ---------- sidebar ---------- */ +.app-side{ + background:var(--side-bg);color:var(--side-ink); + display:flex;flex-direction:column;gap:2px;padding:18px 12px 14px; + position:sticky;top:0;height:100vh;overflow-y:auto;scrollbar-width:none;z-index:30; +} +.app-brand{display:flex;gap:11px;align-items:center;padding:2px 8px 16px;text-decoration:none;color:#fff} +.app-brand b{display:block;font-family:var(--display);font-size:17px;font-weight:700;line-height:1.1;letter-spacing:-.02em} +.app-brand small{font-family:var(--mono);font-size:10.5px;color:var(--side-dim)} +.app-label{font-family:var(--mono);font-size:10.5px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:var(--side-dim);padding:14px 12px 6px} +.app-nav{ + display:flex;align-items:center;gap:12px;padding:9px 12px;border-radius:10px; + text-decoration:none;font-weight:600;font-size:14px;color:var(--side-ink);position:relative; +} +.app-nav svg{flex:none} +.app-nav:hover{background:var(--side-hover);color:#fff} +.app-nav[aria-current="page"]{background:linear-gradient(90deg,rgba(123,109,255,.24),rgba(123,109,255,.06));color:#fff} +.app-nav.acc-teal[aria-current="page"]{background:linear-gradient(90deg,rgba(79,192,201,.22),rgba(79,192,201,.05))} +.app-nav[aria-current="page"]::before{ + content:"";position:absolute;left:-12px;top:7px;bottom:7px;width:3px;border-radius:3px; + background:#7B6DFF;box-shadow:0 0 12px #7B6DFF; +} +.app-nav.acc-teal[aria-current="page"]::before{background:#4FC0C9;box-shadow:0 0 12px #4FC0C9} +.app-tab-text{display:none} +.app-spacer{flex:1;min-height:12px} +.app-goal{display:block;border:1px solid var(--side-line);border-radius:12px;padding:11px 12px;margin-bottom:6px;text-decoration:none;color:var(--side-ink)} +.app-goal:hover{border-color:#3a3860} +.app-goal-row{display:flex;justify-content:space-between;align-items:baseline;gap:8px} +.app-goal b{color:#fff;font-size:13px} +.app-goal small{font-family:var(--mono);font-size:10.5px;color:var(--side-dim)} +.app-meter{display:block;height:6px;border-radius:9px;background:#26243F;overflow:hidden;margin-top:8px} +.app-meter i{display:block;height:100%;background:#7B6DFF;border-radius:9px;transition:width .4s} +.app-collapse{display:flex;align-items:center;gap:10px;background:none;border:0;padding:9px 12px;color:var(--side-dim);font:inherit;font-weight:600;font-size:13px;border-radius:10px;cursor:pointer} +.app-collapse:hover{color:#fff;background:var(--side-hover)} +.app-side a:focus-visible,.app-side button:focus-visible{outline:2px solid #7B6DFF;outline-offset:2px} + +:root[data-nav="collapsed"] .app-brand-text, +:root[data-nav="collapsed"] .app-nav-text, +:root[data-nav="collapsed"] .app-label, +:root[data-nav="collapsed"] .app-goal{display:none} +:root[data-nav="collapsed"] .app-nav, +:root[data-nav="collapsed"] .app-collapse, +:root[data-nav="collapsed"] .app-brand{justify-content:center;padding-inline:0} + +/* ---------- top bar ---------- */ +.app-top{ + position:sticky;top:0;z-index:20;height:56px;display:flex;align-items:center;gap:10px; + padding-inline:clamp(16px,3vw,40px); + background:color-mix(in srgb,var(--ground) 86%,transparent);backdrop-filter:blur(10px); + border-bottom:1px solid var(--line); +} +.app-where{flex:1;min-width:0;font-family:var(--mono);font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:var(--ink-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} + +/* ---------- rail ---------- */ +.app-rail{padding:24px 24px 32px 0;position:sticky;top:0;align-self:start;max-height:100vh;overflow-y:auto;scrollbar-width:thin} + +/* ---------- bare pages (lesson sessions) ---------- */ +body.bare{min-height:100vh} + +/* ---------- responsive ---------- */ +@media (max-width:1439px){ + .app.has-rail{grid-template-columns:248px minmax(0,1fr)} + :root[data-nav="collapsed"] .app.has-rail{grid-template-columns:76px minmax(0,1fr)} + .app-rail{display:none} +} +@media (max-width:1023px){ + .app,.app.has-rail,:root[data-nav="collapsed"] .app,:root[data-nav="collapsed"] .app.has-rail{grid-template-columns:72px minmax(0,1fr)} + .app-brand-text,.app-nav-text,.app-label,.app-goal,.app-collapse{display:none} + .app-nav,.app-brand{justify-content:center;padding-inline:0} +} +@media (max-width:719px){ + .app,.app.has-rail,:root[data-nav="collapsed"] .app,:root[data-nav="collapsed"] .app.has-rail{display:block} + .app-main{min-height:100vh;padding-bottom:64px} + .app-side{ + position:fixed;inset:auto 0 0 0;height:auto;flex-direction:row;justify-content:space-around;gap:0; + padding:6px 4px calc(6px + env(safe-area-inset-bottom));overflow:visible;border-top:1px solid var(--side-line); + } + .app-side > :not(.tab){display:none} + .app-nav.tab{flex:1;flex-direction:column;gap:3px;padding:6px 2px;font-size:10.5px;border-radius:10px} + .app-nav.tab .app-tab-text{display:block} + .app-nav[aria-current="page"]::before{left:25%;right:25%;top:-6px;bottom:auto;width:auto;height:3px} +} diff --git a/src/styles/base.css b/src/styles/base.css index 5c55d00..ebf9dfb 100644 --- a/src/styles/base.css +++ b/src/styles/base.css @@ -1,6 +1,6 @@ /* Reset, body type, headings. Loaded on every page including the ones with no interactive stage. */ -/* Clear the sticky masthead so an anchor jump doesn't land underneath it. +/* Clear the sticky top bar (app.css) so an anchor jump doesn't land underneath it. Also covers keyboard focus scrolling, which a :target offset would not. */ html{scroll-padding-top:76px} @media (max-width:560px){html{scroll-padding-top:96px}} @@ -13,30 +13,30 @@ body{ margin:0; background:var(--ground); color:var(--ink); - font-family:"IBM Plex Sans",-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; + font-family:var(--font); font-size:15px; line-height:1.55; -webkit-font-smoothing:antialiased; } -.wrap{max-width:1140px;margin:0 auto;padding-inline:20px;padding-block:32px 56px} +.wrap{max-width:1240px;margin:0 auto;padding-inline:clamp(16px,3vw,40px);padding-block:32px 56px} /* .as-h2 and .as-h3 give a deeper heading the look of a shallower one, so the outline can nest properly without the page changing how it looks. */ -h1,h2,h3,.as-h2,.as-h3{font-family:Archivo,"IBM Plex Sans",sans-serif;font-weight:700;text-wrap:balance;margin:0} +h1,h2,h3,.as-h2,.as-h3{font-family:var(--display);font-weight:700;text-wrap:balance;margin:0} h1{font-size:clamp(28px,4.6vw,42px);letter-spacing:-.022em;line-height:1.05} h2,.as-h2{font-size:19px;letter-spacing:-.01em} h3,.as-h3{font-size:14px;letter-spacing:-.005em;font-weight:600} p{margin:0} /* Read by a screen reader, not shown. */ .vh{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0} -code,.mono{font-family:"IBM Plex Mono",ui-monospace,SFMono-Regular,Menlo,monospace;font-variant-numeric:tabular-nums} +code,.mono{font-family:var(--mono);font-variant-numeric:tabular-nums} .eyebrow{ - font-family:"IBM Plex Mono",monospace;font-size:11.5px;letter-spacing:.14em; + font-family:var(--mono);font-size:11.5px;letter-spacing:.14em; text-transform:uppercase;color:var(--accent);font-weight:500; } -/* The shell is a column so a short page still pins its footer to the bottom. */ -body{min-height:100vh;display:flex;flex-direction:column} +/* The page column (app.css) is a flex column, so a short page still pins its + footer to the bottom. */ main{flex:1} a:focus-visible,button:focus-visible,input:focus-visible,summary:focus-visible{ outline:2px solid var(--accent);outline-offset:2px;border-radius:4px; diff --git a/src/styles/kit.css b/src/styles/kit.css index 74356b9..09faf9c 100644 --- a/src/styles/kit.css +++ b/src/styles/kit.css @@ -9,7 +9,7 @@ /* ---------- stage shapes ---------- */ .st-box{display:flex;flex-direction:column;gap:7px;min-width:0} .st-label{ - font-family:"IBM Plex Mono",monospace;font-size:10.5px;letter-spacing:.1em; + font-family:var(--mono);font-size:10.5px;letter-spacing:.1em; text-transform:uppercase;color:var(--ink-3);font-weight:600; } .st-panels{display:flex;flex-wrap:wrap;gap:20px 26px;align-items:flex-start} @@ -23,12 +23,12 @@ border-radius:7px;flex:0 0 auto; } .st-cell.on{background:var(--accent-soft);border-color:var(--accent)} -.st-val{font-family:"IBM Plex Mono",monospace;font-size:15px;color:var(--ink);font-variant-numeric:tabular-nums} +.st-val{font-family:var(--mono);font-size:15px;color:var(--ink);font-variant-numeric:tabular-nums} .st-cell.on .st-val{color:var(--accent);font-weight:600} -.st-idx{font-family:"IBM Plex Mono",monospace;font-size:10px;color:var(--ink-3);margin-top:2px} +.st-idx{font-family:var(--mono);font-size:10px;color:var(--ink-3);margin-top:2px} .st-mark{ position:absolute;top:100%;margin-top:3px;white-space:nowrap; - font-family:"IBM Plex Mono",monospace;font-size:10.5px;color:var(--accent);font-weight:600; + font-family:var(--mono);font-size:10.5px;color:var(--accent);font-weight:600; } .t-up{background:var(--up-soft);border-color:var(--up)} .t-up .st-val{color:var(--up)} @@ -43,7 +43,7 @@ /* key/value */ .st-kv{border:1px solid var(--line);border-radius:7px;overflow:hidden;min-width:150px} .st-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:18px;padding:5px 11px; - font-family:"IBM Plex Mono",monospace;font-size:12.5px;border-top:1px solid var(--line);background:var(--sunk)} + font-family:var(--mono);font-size:12.5px;border-top:1px solid var(--line);background:var(--sunk)} .st-row:first-child{border-top:0} .st-row.head{background:var(--surface);color:var(--ink-3);font-size:10.5px;letter-spacing:.08em;text-transform:uppercase} .st-row.on{background:var(--accent-soft)} @@ -64,7 +64,7 @@ .st-slot{ display:flex;align-items:center;justify-content:space-between;gap:10px; background:var(--sunk);border:1px solid var(--line);border-radius:6px;padding:6px 11px; - font-family:"IBM Plex Mono",monospace;font-size:14px;color:var(--ink); + font-family:var(--mono);font-size:14px;color:var(--ink); } .st-slot.on{background:var(--accent-soft);border-color:var(--accent);color:var(--accent);font-weight:600} .st-top{font-size:10px;letter-spacing:.08em;text-transform:uppercase;color:var(--accent)} @@ -78,8 +78,8 @@ .st-node.on{background:var(--accent-soft);border-color:var(--accent)} .st-node.on .st-val{color:var(--accent);font-weight:600} .st-arrow{color:var(--ink-3);font-size:14px} -.st-arrow.cyc{color:var(--amber);font-family:"IBM Plex Mono",monospace;font-size:11.5px;font-weight:600} -.st-null{font-family:"IBM Plex Mono",monospace;font-size:12px;color:var(--ink-3)} +.st-arrow.cyc{color:var(--amber);font-family:var(--mono);font-size:11.5px;font-weight:600} +.st-null{font-family:var(--mono);font-size:12px;color:var(--ink-3)} /* tree */ .st-tree{overflow-x:auto} @@ -88,7 +88,7 @@ /* bars */ .st-bars{display:flex;align-items:flex-end;gap:5px;overflow-x:auto;padding-bottom:20px;margin-bottom:-14px;min-height:var(--bar-h)} .st-bar{position:relative;display:flex;flex-direction:column;align-items:center;gap:3px;flex:0 0 auto;min-width:34px;justify-content:flex-end} -.st-barval{font-family:"IBM Plex Mono",monospace;font-size:11px;color:var(--ink-2);font-variant-numeric:tabular-nums} +.st-barval{font-family:var(--mono);font-size:11px;color:var(--ink-2);font-variant-numeric:tabular-nums} .st-fill{width:100%;background:var(--line-2);border-radius:4px 4px 0 0;display:block} .st-bar.on .st-fill{background:var(--accent)} .st-bar.on .st-barval{color:var(--accent);font-weight:600} @@ -98,7 +98,7 @@ /* scalar readouts */ .st-reads{display:flex;flex-wrap:wrap;gap:7px} .st-read{ - font-family:"IBM Plex Mono",monospace;font-size:13px;background:var(--sunk); + font-family:var(--mono);font-size:13px;background:var(--sunk); border:1px solid var(--line);border-radius:7px;padding:5px 11px;color:var(--ink);font-variant-numeric:tabular-nums; } .st-read b{color:var(--ink-3);font-weight:500;margin-right:7px} @@ -117,7 +117,7 @@ /* Stage data stays in the Latin monospace face in both languages. */ :root[data-ui="my"] .st-cell,:root[data-ui="my"] .st-kv,:root[data-ui="my"] .st-node, :root[data-ui="my"] .st-read,:root[data-ui="my"] .st-slot,:root[data-ui="my"] .st-barval{ - font-family:"IBM Plex Mono",ui-monospace,Menlo,monospace; + font-family:var(--mono); } @@ -125,7 +125,7 @@ .strip .cell,.q-arr .cell{position:relative} .cell .ptr{ position:absolute;top:100%;margin-top:4px;white-space:nowrap; - font-family:"IBM Plex Mono",monospace;font-size:10.5px;font-weight:600;color:var(--accent); + font-family:var(--mono);font-size:10.5px;font-weight:600;color:var(--accent); } .player .strip:has(.ptr),.strip.has-ptr{padding-bottom:24px} .cell.done{background:transparent;border-style:dotted} @@ -156,10 +156,10 @@ A lesson sets only its cell size. */ .rows.grid{gap:6px} .rows.grid .row{flex-wrap:nowrap} -.row-label{font-family:"IBM Plex Mono",monospace;font-size:12px;color:var(--ink-3);min-width:42px} +.row-label{font-family:var(--mono);font-size:12px;color:var(--ink-3);min-width:42px} /* The same, as rows of the part 1 widget. */ -.q-row-label{font-family:"IBM Plex Mono",monospace;font-size:11px;color:var(--ink-3);align-self:center;min-width:38px} -.q-empty{font-family:"IBM Plex Mono",monospace;align-self:center;color:var(--ink-3)} +.q-row-label{font-family:var(--mono);font-size:11px;color:var(--ink-3);align-self:center;min-width:38px} +.q-empty{font-family:var(--mono);align-self:center;color:var(--ink-3)} /* The widget cell the reader has picked. */ .q-arr .cell.picked{outline:2px solid var(--accent);outline-offset:2px} @@ -176,13 +176,13 @@ .approach ol{margin:4px 0 0;padding-left:22px;display:flex;flex-direction:column;gap:3px} .approach li::marker{color:var(--accent);font-weight:600} .approach .mono{color:var(--ink)} -.approach-label{display:inline-block;min-width:52px;margin-right:8px;font-family:"IBM Plex Mono",monospace; +.approach-label{display:inline-block;min-width:52px;margin-right:8px;font-family:var(--mono); font-size:10.5px;letter-spacing:.09em;text-transform:uppercase;color:var(--ink-3);font-weight:600} :root[data-ui="my"] .approach{line-height:1.85;overflow-wrap:break-word} /* A trie as an outline, one row per node indented by depth: trieOutline() in stage.js (Implement Trie, Word Search II). */ -.trie{display:flex;flex-direction:column;gap:3px;font-family:"IBM Plex Mono",monospace;font-size:13px} +.trie{display:flex;flex-direction:column;gap:3px;font-family:var(--mono);font-size:13px} .tr-row{display:flex;align-items:center;gap:8px;min-height:26px} .tr-row.d1{margin-left:14px}.tr-row.d2{margin-left:28px}.tr-row.d3{margin-left:42px} .tr-row.d4{margin-left:56px}.tr-row.d5{margin-left:70px}.tr-row.d6{margin-left:84px} diff --git a/src/styles/lesson.css b/src/styles/lesson.css index ae75253..5c8ad01 100644 --- a/src/styles/lesson.css +++ b/src/styles/lesson.css @@ -10,7 +10,7 @@ .field{display:flex;flex-direction:column;gap:5px;min-width:0} .field label{font-size:11px;letter-spacing:.09em;text-transform:uppercase;color:var(--ink-3);font-weight:600} input[type=text],input[type=number]{ - font-family:"IBM Plex Mono",monospace;font-size:14px;font-variant-numeric:tabular-nums; + font-family:var(--mono);font-size:14px;font-variant-numeric:tabular-nums; background:var(--sunk);color:var(--ink);border:1px solid var(--line);border-radius:7px; padding:7px 10px; } @@ -19,7 +19,7 @@ input[type=number]{width:72px} input:focus-visible,button:focus-visible,select:focus-visible{outline:2px solid var(--accent);outline-offset:2px} .presets{display:flex;flex-wrap:wrap;gap:7px} .chip{ - font-family:"IBM Plex Mono",monospace;font-size:12px;cursor:pointer; + font-family:var(--mono);font-size:12px;cursor:pointer; background:transparent;color:var(--ink-2);border:1px solid var(--line-2);border-radius:999px;padding:5px 11px; } .chip:hover{border-color:var(--accent);color:var(--accent)} @@ -34,7 +34,7 @@ input.bad{border-color:var(--down);box-shadow:0 0 0 1px var(--down)} /* ---------- array strip ---------- */ .strip-head{display:flex;flex-wrap:wrap;gap:10px;justify-content:space-between;align-items:baseline;margin-bottom:12px} .strip-head .op{ - font-family:"IBM Plex Mono",monospace;font-size:13px;color:var(--amber);font-weight:500; + font-family:var(--mono);font-size:13px;color:var(--amber);font-weight:500; background:var(--amber-soft);border-radius:6px;padding:3px 9px; } .strip{display:flex;gap:6px;overflow-x:auto;padding-block:6px} @@ -42,7 +42,7 @@ input.bad{border-color:var(--down);box-shadow:0 0 0 1px var(--down)} flex:0 0 auto;width:42px;height:50px;border-radius:8px;display:flex;flex-direction:column; align-items:center;justify-content:center;gap:1px; background:var(--sunk);border:1px solid var(--line);color:var(--ink-3); - font-family:"IBM Plex Mono",monospace;font-size:16px;font-weight:500; + font-family:var(--mono);font-size:16px;font-weight:500; } .cell .idx{font-size:9.5px;color:var(--ink-3)} .cell.inwin{background:var(--amber-soft);border-color:var(--amber);color:var(--ink)} @@ -57,12 +57,10 @@ input.bad{border-color:var(--down);box-shadow:0 0 0 1px var(--down)} border-radius:7px;padding:6px 12px;font-size:13px;font-family:inherit;font-weight:500; } .btn:hover{border-color:var(--accent);color:var(--accent)} -.btn.primary{background:var(--accent);border-color:var(--accent);color:#fff} -:root:not([data-theme="light"]) .btn.primary{color:#07191B} -@media (prefers-color-scheme: light){:root:not([data-theme="dark"]) .btn.primary{color:#fff}} +.btn.primary{background:var(--accent);border-color:var(--accent);color:var(--on-accent)} .btn.primary:hover{opacity:.88;color:inherit} .btn[disabled]{opacity:.4;cursor:not-allowed} -.counter{font-family:"IBM Plex Mono",monospace;font-size:12.5px;color:var(--ink-3);font-variant-numeric:tabular-nums} +.counter{font-family:var(--mono);font-size:12.5px;color:var(--ink-3);font-variant-numeric:tabular-nums} input[type=range]{accent-color:var(--accent);flex:1 1 180px;min-width:120px} .narration{ @@ -71,7 +69,7 @@ input[type=range]{accent-color:var(--accent);flex:1 1 180px;min-width:120px} border-radius:0 var(--radius) var(--radius) 0;padding:12px 15px;min-height:52px; } .narration .tag{ - flex:0 0 auto;font-family:"IBM Plex Mono",monospace;font-size:10.5px;letter-spacing:.09em; + flex:0 0 auto;font-family:var(--mono);font-size:10.5px;letter-spacing:.09em; text-transform:uppercase;font-weight:600;color:var(--accent);background:var(--accent-soft); border-radius:5px;padding:3px 7px;margin-top:2px; } @@ -88,7 +86,7 @@ input[type=range]{accent-color:var(--accent);flex:1 1 180px;min-width:120px} padding:16px;box-shadow:var(--shadow); } .panel-head{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:baseline;gap:6px 10px;margin-bottom:12px} -.panel-head .note{min-width:0;font-size:12px;color:var(--ink-3);font-family:"IBM Plex Mono",monospace} +.panel-head .note{min-width:0;font-size:12px;color:var(--ink-3);font-family:var(--mono)} .empty{font-size:12.5px;color:var(--ink-3);font-style:italic;padding:6px 2px} @@ -96,24 +94,24 @@ input[type=range]{accent-color:var(--accent);flex:1 1 180px;min-width:120px} display:flex;flex-wrap:wrap;align-items:baseline;gap:8px 14px;margin-top:14px;padding-top:13px; border-top:1px solid var(--line); } -.ledger .expr{font-family:"IBM Plex Mono",monospace;font-size:13px;color:var(--ink-2);word-break:break-word} +.ledger .expr{font-family:var(--mono);font-size:13px;color:var(--ink-2);word-break:break-word} .ledger .total{ - font-family:Archivo,sans-serif;font-size:30px;font-weight:700;color:var(--accent); + font-family:var(--display);font-size:30px;font-weight:700;color:var(--accent); font-variant-numeric:tabular-nums;line-height:1;margin-left:auto; } -.ledger .total small{font-family:"IBM Plex Mono",monospace;font-size:11px;color:var(--ink-3);font-weight:400;display:block;text-align:right;letter-spacing:.08em} +.ledger .total small{font-family:var(--mono);font-size:11px;color:var(--ink-3);font-weight:400;display:block;text-align:right;letter-spacing:.08em} /* code */ .code{ position:relative;background:var(--sunk);border-radius:8px;padding:12px 4px 12px 0; overflow:auto;max-height:clamp(300px,58vh,520px);overscroll-behavior:contain; - font-family:"IBM Plex Mono",monospace;font-size:12.3px;line-height:1.75; + font-family:var(--mono);font-size:12.3px;line-height:1.75; scroll-behavior:smooth; } @media (prefers-reduced-motion: reduce){.code{scroll-behavior:auto}} .code .ln{display:block;padding-inline:14px 12px;border-left:3px solid transparent;white-space:pre;color:var(--ink-2)} .code .ln.hot{background:var(--accent-soft);border-left-color:var(--accent);color:var(--ink)} -.code-sub{font-size:11.5px;color:var(--ink-3);margin-top:10px;font-family:"IBM Plex Mono",monospace} +.code-sub{font-size:11.5px;color:var(--ink-3);margin-top:10px;font-family:var(--mono)} .wrap a{color:var(--accent);text-underline-offset:2px} /* full source */ @@ -124,7 +122,7 @@ input[type=range]{accent-color:var(--accent);flex:1 1 180px;min-width:120px} pre.full{ margin:0;background:var(--sunk);border-radius:8px;padding:14px 16px; overflow:auto;max-height:clamp(320px,52vh,540px);overscroll-behavior:contain; - font-family:"IBM Plex Mono",monospace;font-size:12.5px;line-height:1.7;color:var(--ink); + font-family:var(--mono);font-size:12.5px;line-height:1.7;color:var(--ink); } pre.full:focus-visible{outline:2px solid var(--accent);outline-offset:2px} .copy{font-size:12px;padding:5px 11px} @@ -133,7 +131,7 @@ pre.full:focus-visible{outline:2px solid var(--accent);outline-offset:2px} /* answer */ .answer-row{display:flex;flex-wrap:wrap;gap:7px;align-items:center} .slot{ - font-family:"IBM Plex Mono",monospace;font-variant-numeric:tabular-nums;font-size:15px;font-weight:500; + font-family:var(--mono);font-variant-numeric:tabular-nums;font-size:15px;font-weight:500; min-width:44px;text-align:center;padding:7px 10px;border-radius:7px; background:var(--sunk);border:1px dashed var(--line-2);color:var(--ink-3); } @@ -156,7 +154,7 @@ td.mono{font-variant-numeric:tabular-nums} /* Under the player in 2·2: the keys and what the reader can edit. */ .play-hint{margin:10px 2px 0;font-size:12.5px;line-height:1.7;color:var(--ink-3)} -.wrap kbd{font-family:"IBM Plex Mono",monospace;font-size:11px;background:var(--sunk);border:1px solid var(--line-2);border-bottom-width:2px;border-radius:4px;padding:1px 5px;color:var(--ink-2)} +.wrap kbd{font-family:var(--mono);font-size:11px;background:var(--sunk);border:1px solid var(--line-2);border-bottom-width:2px;border-radius:4px;padding:1px 5px;color:var(--ink-2)} @media (max-width:520px){ .ledger .total{margin-left:0} @@ -171,7 +169,7 @@ td.mono{font-variant-numeric:tabular-nums} .q-statement{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:18px;box-shadow:var(--shadow)} .constraints{display:flex;flex-wrap:wrap;gap:6px;margin-top:13px} .constraints span{ - font-family:"IBM Plex Mono",monospace;font-size:11.5px;color:var(--ink-3); + font-family:var(--mono);font-size:11.5px;color:var(--ink-3); background:var(--sunk);border:1px solid var(--line);border-radius:6px;padding:4px 9px; } .constraints b{color:var(--accent);font-weight:600;margin-right:4px} @@ -189,7 +187,7 @@ td.mono{font-variant-numeric:tabular-nums} .q-grid .q-arr{flex-wrap:nowrap;margin-bottom:6px} .q-slider{display:flex;flex-wrap:wrap;align-items:center;gap:10px;margin-bottom:14px} .q-slider label{font-size:11px;letter-spacing:.09em;text-transform:uppercase;color:var(--ink-3);font-weight:600} -.q-slider output{font-family:"IBM Plex Mono",monospace;font-size:17px;font-weight:600;color:var(--accent);min-width:20px} +.q-slider output{font-family:var(--mono);font-size:17px;font-weight:600;color:var(--accent);min-width:20px} .q-presets{display:flex;flex-wrap:wrap;gap:6px;flex-basis:100%} .q-tie{font-size:12.5px;color:var(--amber);margin-top:10px;min-height:19px;line-height:1.45} .q-play .ledger{margin-top:12px} @@ -197,7 +195,7 @@ td.mono{font-variant-numeric:tabular-nums} /* ---------- language tabs ---------- */ .lang-bar{display:flex;flex-wrap:wrap;gap:4px;background:var(--sunk);border:1px solid var(--line);border-radius:9px;padding:4px;margin-bottom:14px} .lang{ - font-family:"IBM Plex Sans",sans-serif;font-size:13px;font-weight:500;cursor:pointer; + font-family:var(--font);font-size:13px;font-weight:500;cursor:pointer; background:transparent;border:0;color:var(--ink-2);padding:7px 15px;border-radius:6px; } .lang:hover{color:var(--accent)} @@ -228,12 +226,12 @@ td.mono{font-variant-numeric:tabular-nums} .lang-bar .lang{flex:0 0 auto;padding-inline:10px} } .tagpill{ - font-family:"IBM Plex Mono",monospace;font-size:10.5px;font-weight:500;color:var(--accent); + font-family:var(--mono);font-size:10.5px;font-weight:500;color:var(--accent); background:var(--accent-soft);border-radius:5px;padding:2px 7px;margin-left:8px; vertical-align:middle;letter-spacing:.04em; } /* A long badge wraps inside its pill rather than pushing the page sideways on a phone. */ -.verify{display:inline-block;max-width:100%;font-family:"IBM Plex Mono",monospace;font-size:11px;padding:3px 8px;border-radius:5px;line-height:1.5} +.verify{display:inline-block;max-width:100%;font-family:var(--mono);font-size:11px;padding:3px 8px;border-radius:5px;line-height:1.5} .verify.ok{color:var(--up);background:var(--up-soft)} .verify.warn{color:var(--amber);background:var(--amber-soft)} @@ -244,9 +242,9 @@ td.mono{font-variant-numeric:tabular-nums} background:var(--sunk);border:1px solid var(--line);border-radius:7px;padding:7px 10px; } .plink:hover{border-color:var(--accent);color:var(--ink)} -.pnum{font-family:"IBM Plex Mono",monospace;font-size:12px;font-weight:600;color:var(--accent)} +.pnum{font-family:var(--mono);font-size:12px;font-weight:600;color:var(--accent)} .pdiff{ - margin-left:auto;font-family:"IBM Plex Mono",monospace;font-size:10.5px;letter-spacing:.05em; + margin-left:auto;font-family:var(--mono);font-size:10.5px;letter-spacing:.05em; padding:2px 7px;border-radius:5px;text-transform:uppercase; } .pdiff.easy{color:var(--up);background:var(--up-soft)} @@ -288,7 +286,7 @@ td.mono{font-variant-numeric:tabular-nums} .jump a:not(.lc) + a.lc{position:relative;margin-left:9px} .jump a:not(.lc) + a.lc::before{content:"";position:absolute;left:-9px;top:50%;height:16px;margin-top:-8px;border-left:1px solid var(--line-2)} .jump b{ - font-family:"IBM Plex Mono",monospace;font-size:11px;color:var(--accent);background:var(--accent-soft); + font-family:var(--mono);font-size:11px;color:var(--accent);background:var(--accent-soft); width:18px;height:18px;border-radius:50%;display:flex;align-items:center;justify-content:center; } .part{ @@ -296,7 +294,7 @@ td.mono{font-variant-numeric:tabular-nums} margin:42px 0 20px;padding-top:18px;border-top:2px solid var(--line-2);scroll-margin-top:14px; } .part-n{ - font-family:Archivo,sans-serif;font-size:32px;font-weight:700;color:var(--accent); + font-family:var(--display);font-size:32px;font-weight:700;color:var(--accent); line-height:.9;letter-spacing:-.03em;min-width:32px; } .part h2{font-size:clamp(20px,2.6vw,25px);letter-spacing:-.015em} @@ -306,7 +304,7 @@ td.mono{font-variant-numeric:tabular-nums} /* ---------- statement, disclosures, approach picker ---------- */ .q-head{display:flex;justify-content:space-between;align-items:baseline;gap:10px;margin-bottom:11px} -.q-src{font-family:"IBM Plex Mono",monospace;font-size:11px;color:var(--ink-3);letter-spacing:.04em} +.q-src{font-family:var(--mono);font-size:11px;color:var(--ink-3);letter-spacing:.04em} .q-statement .statement{display:flex;flex-direction:column;gap:10px;font-size:14px;color:var(--ink-2);line-height:1.6} .q-statement .statement b{color:var(--ink);font-weight:600} .q-statement .statement ol{margin:0;padding-left:22px;display:flex;flex-direction:column;gap:7px} @@ -323,7 +321,7 @@ td.mono{font-variant-numeric:tabular-nums} } .disclose summary::-webkit-details-marker{display:none} .disclose summary::before{ - content:"+";font-family:"IBM Plex Mono",monospace;font-size:14px;color:var(--accent); + content:"+";font-family:var(--mono);font-size:14px;color:var(--accent); background:var(--accent-soft);width:19px;height:19px;border-radius:5px; display:flex;align-items:center;justify-content:center;flex:0 0 auto; } @@ -346,14 +344,14 @@ td.mono{font-variant-numeric:tabular-nums} .lang-opt[aria-pressed="true"]{background:var(--surface);color:var(--ink);font-weight:600;box-shadow:0 1px 2px rgba(0,0,0,.12)} [lang="my"], :root[data-ui="my"] body{ font-family:"Noto Sans Myanmar","Padauk","Myanmar Text","Myanmar MN", - "IBM Plex Sans",-apple-system,sans-serif; + "Plus Jakarta Sans",-apple-system,sans-serif; } /* Burmese stacks tall: give it room, and never let the script be squeezed */ :root[data-ui="my"] body{line-height:1.85;font-size:15px} :root[data-ui="my"] h1,:root[data-ui="my"] h2,:root[data-ui="my"] h3, :root[data-ui="my"] .as-h2,:root[data-ui="my"] .as-h3, :root[data-ui="my"] .atab-name,:root[data-ui="my"] .part h2{ - font-family:"Noto Sans Myanmar","Padauk",Archivo,sans-serif;line-height:1.5;letter-spacing:0; + font-family:"Noto Sans Myanmar","Padauk",var(--display);line-height:1.5;letter-spacing:0; } :root[data-ui="my"] h1{font-size:clamp(25px,4vw,36px)} :root[data-ui="my"] .lede,:root[data-ui="my"] .statement, @@ -376,9 +374,9 @@ td.mono{font-variant-numeric:tabular-nums} :root[data-ui="my"] .cell,:root[data-ui="my"] .slot,:root[data-ui="my"] .counter, :root[data-ui="my"] .tagpill,:root[data-ui="my"] .verify,:root[data-ui="my"] .q-src, :root[data-ui="my"] input,:root[data-ui="my"] .chip,:root[data-ui="my"] .total{ - font-family:"IBM Plex Mono",ui-monospace,Menlo,monospace;line-height:1.6; + font-family:var(--mono);line-height:1.6; } -:root[data-ui="my"] .lang{font-family:"IBM Plex Sans",sans-serif} +:root[data-ui="my"] .lang{font-family:var(--font)} /* ---------- hoverable variables ---------- */ .code .var{ @@ -391,7 +389,7 @@ td.mono{font-variant-numeric:tabular-nums} position:absolute;z-index:50;max-width:min(420px,88vw); background:var(--surface);border:1px solid var(--accent);border-radius:8px; padding:8px 11px;box-shadow:0 8px 24px -10px rgba(0,0,0,.45); - font-family:"IBM Plex Mono",monospace;font-size:12px;line-height:1.5; + font-family:var(--mono);font-size:12px;line-height:1.5; display:flex;flex-direction:column;gap:2px;pointer-events:none; } .tip-name{color:var(--accent);font-weight:600;font-size:12.5px} @@ -404,7 +402,7 @@ td.mono{font-variant-numeric:tabular-nums} .subsec{margin-top:30px} .subsec:first-child{margin-top:6px} .subsec-head{display:flex;align-items:baseline;gap:10px;margin-bottom:12px} -.subsec-n{font-family:"IBM Plex Mono",monospace;font-size:12px;font-weight:600;color:var(--accent); +.subsec-n{font-family:var(--mono);font-size:12px;font-weight:600;color:var(--accent); background:var(--accent-soft);border-radius:6px;padding:2px 7px} .subsec-head h3{font-size:18px;letter-spacing:-.01em;margin:0} @@ -419,9 +417,9 @@ td.mono{font-variant-numeric:tabular-nums} .atab:hover .atab-name{color:var(--accent)} .atab[aria-selected="true"]{background:var(--surface);color:var(--ink);box-shadow:inset 0 3px 0 var(--accent)} .atab[aria-selected="true"]::after{content:"";position:absolute;left:0;right:0;bottom:-1px;height:2px;background:var(--surface)} -.atab-name{font-family:Archivo,sans-serif;font-weight:600;font-size:16px;letter-spacing:-.01em;color:var(--ink)} +.atab-name{font-family:var(--display);font-weight:600;font-size:16px;letter-spacing:-.01em;color:var(--ink)} .atab-desc{font-size:12.5px;line-height:1.45} -.atab-cost{font-family:"IBM Plex Mono",monospace;font-size:11.5px;color:var(--ink-3);margin-top:3px} +.atab-cost{font-family:var(--mono);font-size:11.5px;color:var(--ink-3);margin-top:3px} .atab[aria-selected="true"] .atab-cost{color:var(--accent)} .atab-panel{ background:var(--surface);border:1px solid var(--line);border-radius:0 0 var(--radius) var(--radius); diff --git a/src/styles/site.css b/src/styles/site.css index e6bb41f..05ad447 100644 --- a/src/styles/site.css +++ b/src/styles/site.css @@ -1,42 +1,11 @@ -/* Chrome around the lessons: masthead, the problem list, pager, footer. +/* Chrome around the lessons: search, theme switch, the problem list, pager, footer. Reads every colour from tokens.css so the shell and the walkthrough inside it are demonstrably the same design. */ /* ---------- shell ---------- */ -.shell{max-width:1140px;margin:0 auto;padding-inline:20px} -.masthead{ - border-bottom:1px solid var(--line);background:var(--surface); - position:sticky;top:0;z-index:40; -} -.masthead .shell{ - display:flex;align-items:center;gap:20px;min-height:56px;flex-wrap:wrap; -} -.brand{ - display:inline-flex;align-items:baseline;gap:8px;text-decoration:none;color:var(--ink); - font-family:Archivo,"IBM Plex Sans",sans-serif;font-weight:700;letter-spacing:-.02em;font-size:16px; -} -.brand .dot{width:8px;height:8px;border-radius:2px;background:var(--accent);align-self:center} -.masthead nav{display:flex;gap:2px;margin-inline-start:auto;flex-wrap:wrap} -.masthead nav a{ - color:var(--ink-2);text-decoration:none;font-size:13.5px;font-weight:500; - padding:6px 10px;border-radius:7px; -} -.masthead nav a:hover{background:var(--sunk);color:var(--ink)} - -/* Keep the sticky bar to one line on a phone: wrapped, it took 84px of a - fifth of the screen and never gave it back. */ -@media (max-width:560px){ - .masthead .shell{gap:8px;padding-inline:14px} - .masthead nav{gap:0} - .masthead nav a{font-size:12.5px;padding:5px 7px} - .brand{font-size:15px} -} -/* Under 375px brand, links, search and theme fit with no room to spare, and a - wider fallback font (before the web fonts load, or on Linux) wraps the bar. - The "LeetCode" link goes where the brand already does, so it steps aside. */ -@media (max-width:374px){ - .masthead nav a[href="/"]{display:none} -} +/* Pages sit inside the app shell (app.css); .shell only sets the gutter, so + lists and heads use the full width beside the sidebar. */ +.shell{padding-inline:clamp(16px,3vw,40px)} /* ---------- theme switch ---------- */ .theme-btn{ @@ -64,7 +33,7 @@ .search-btn:hover{border-color:var(--line-2);color:var(--ink)} .search-btn svg{width:14px;height:14px;flex:none} .sb-key{ - font-family:"IBM Plex Mono",monospace;font-size:11px;color:var(--ink-3); + font-family:var(--mono);font-size:11px;color:var(--ink-3); border:1px solid var(--line);border-radius:4px;padding:0 5px;line-height:18px; } @media (max-width:560px){ @@ -99,7 +68,7 @@ html:has(.kdlg[open]){overflow:hidden} padding:9px 10px;border-radius:7px;color:var(--ink);text-decoration:none;font-size:14px; } .k-opt[aria-selected="true"]{background:var(--accent-soft)} -.k-num{font-family:"IBM Plex Mono",monospace;font-size:12px;color:var(--ink-3);font-variant-numeric:tabular-nums} +.k-num{font-family:var(--mono);font-size:12px;color:var(--ink-3);font-variant-numeric:tabular-nums} .k-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500} .k-sub{font-size:12px;color:var(--ink-3);white-space:nowrap} .k-status{margin:0;padding:9px 16px;border-top:1px solid var(--line);font-size:12px;color:var(--ink-3)} @@ -129,7 +98,7 @@ html:has(.kdlg[open]){overflow:hidden} .cat:hover{background:var(--sunk);color:var(--ink)} .cat[aria-current="true"]{background:var(--accent-soft);color:var(--accent);font-weight:600} .cat:first-child{margin-bottom:6px} -.cat-n{font-family:"IBM Plex Mono",monospace;font-size:11px;color:var(--ink-3);font-variant-numeric:tabular-nums} +.cat-n{font-family:var(--mono);font-size:11px;color:var(--ink-3);font-variant-numeric:tabular-nums} .cat[aria-current="true"] .cat-n{color:var(--accent)} .cat.none{opacity:.45} @@ -151,15 +120,15 @@ html:has(.kdlg[open]){overflow:hidden} .cat-sec{margin-bottom:34px} .cat-sec header{display:flex;align-items:baseline;justify-content:space-between;gap:12px; padding-bottom:8px;margin-bottom:10px;border-bottom:1px solid var(--line)} -.cat-sec h2{font-family:"IBM Plex Mono",monospace;font-size:12px;letter-spacing:.1em;text-transform:uppercase;color:var(--ink-2);margin:0} -.cat-sec header span{font-family:"IBM Plex Mono",monospace;font-size:11.5px;color:var(--ink-3)} +.cat-sec h2{font-family:var(--mono);font-size:12px;letter-spacing:.1em;text-transform:uppercase;color:var(--ink-2);margin:0} +.cat-sec header span{font-family:var(--mono);font-size:11.5px;color:var(--ink-3)} .prows{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px} .prow{position:relative;display:grid;grid-template-columns:3.2em minmax(0,1fr) auto 4.6em 3.6em;gap:14px;align-items:center; background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:11px 16px} .prow.has-page{cursor:pointer} .prow.has-page:hover{border-color:var(--accent)} .prow:has(.ptitle:focus-visible){outline:2px solid var(--accent);outline-offset:1px} -.pnum{font-family:"IBM Plex Mono",monospace;font-size:12.5px;color:var(--ink-3);font-variant-numeric:tabular-nums} +.pnum{font-family:var(--mono);font-size:12.5px;color:var(--ink-3);font-variant-numeric:tabular-nums} .pmain{min-width:0} .ptitle{display:block;font-weight:600;font-size:14.5px;color:var(--ink);text-decoration:none} a.ptitle{outline:none} @@ -172,9 +141,9 @@ a.ptitle::after{content:"";position:absolute;inset:0;border-radius:inherit} .psub .soon{font-style:italic} .psub a.lc{position:relative;z-index:1;color:var(--ink-3);text-decoration:none;font-weight:500} .psub a.lc:hover{color:var(--accent);text-decoration:underline} -.ptags{font-family:"IBM Plex Mono",monospace;font-size:11.5px;color:var(--ink-3);text-align:right;white-space:nowrap} +.ptags{font-family:var(--mono);font-size:11.5px;color:var(--ink-3);text-align:right;white-space:nowrap} .prow .diff{justify-self:center} -.prate{font-family:"IBM Plex Mono",monospace;font-size:12px;color:var(--ink-2);text-align:right;font-variant-numeric:tabular-nums} +.prate{font-family:var(--mono);font-size:12px;color:var(--ink-2);text-align:right;font-variant-numeric:tabular-nums} .plist-foot{font-size:12.5px;color:var(--ink-3);margin-top:8px} .plist-empty{color:var(--ink-2);font-size:14px;padding:24px 0} .plist-empty button{font:inherit;color:var(--accent);background:none;border:0;padding:0;cursor:pointer;text-decoration:underline} @@ -196,12 +165,13 @@ a.ptitle::after{content:"";position:absolute;inset:0;border-radius:inherit} } .diff{ - font-family:"IBM Plex Mono",monospace;font-size:10.5px;letter-spacing:.06em;text-transform:uppercase; + font-family:var(--mono);font-size:10.5px;letter-spacing:.06em;text-transform:uppercase; font-weight:600;padding:2px 8px;border-radius:999px;white-space:nowrap; } .diff.easy{background:var(--up-soft);color:var(--up)} .diff.medium{background:var(--amber-soft);color:var(--amber)} .diff.hard{background:var(--down-soft);color:var(--down)} +.diff.ai{background:var(--indigo-soft);color:var(--indigo)} /* ---------- pager ---------- */ .pager{display:flex;gap:12px;justify-content:space-between;border-top:1px solid var(--line);padding-top:20px;margin-top:8px;margin-bottom:64px;flex-wrap:wrap} @@ -210,7 +180,7 @@ a.ptitle::after{content:"";position:absolute;inset:0;border-radius:inherit} border:1px solid var(--line);border-radius:var(--radius);padding:11px 15px;background:var(--surface);min-width:0; } .pager a:hover{border-color:var(--accent);color:var(--accent)} -.pager .dir{font-family:"IBM Plex Mono",monospace;font-size:10.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--ink-3)} +.pager .dir{font-family:var(--mono);font-size:10.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--ink-3)} .pager .up .dir::before{content:"\2190\00a0"} /* ---------- footer ---------- */ @@ -221,10 +191,9 @@ a.ptitle::after{content:"";position:absolute;inset:0;border-radius:inherit} .site-foot .foot-link{color:var(--accent);text-decoration:underline;text-underline-offset:2px} .site-foot .sep{margin-inline-start:auto} -/* On a touch screen the masthead's links and theme button grow to 40px, still +/* On a touch screen the theme and search buttons grow to 40px, still inside its 56px bar. */ @media (pointer:coarse),(max-width:560px){ - .masthead nav a{display:inline-flex;align-items:center;min-height:40px} .theme-btn{width:40px;height:40px} .search-btn{height:40px;min-width:40px} .k-opt{min-height:44px} diff --git a/src/styles/tokens.css b/src/styles/tokens.css index b3170ab..6fc47e8 100644 --- a/src/styles/tokens.css +++ b/src/styles/tokens.css @@ -1,70 +1,115 @@ -/* Palette and shape, in all three theme states: system, forced light, - forced dark. Every other stylesheet reads colour only through these. - Text colours clear WCAG AA (4.5:1) on every background they sit on — +/* Palette, type and shape, in all three theme states: system, forced light, + forced dark. Every other stylesheet reads colour and fonts only through + these. Text colours clear WCAG AA (4.5:1) on every background they sit on: ground, surface, sunk and the soft tints; npm run audit checks it. - color-scheme follows the theme so native parts — scrollbars, range - tracks, number spinners — are drawn dark on the dark theme too. */ + color-scheme follows the theme so native parts (scrollbars, range tracks, + number spinners) are drawn dark on the dark theme too. + + One design system, two accents: <html data-section> picks the accent. + LeetCode pages are teal, the AI Engineer course and the hub are indigo. */ :root{ color-scheme:light; - --ground:#EEF2F2; + --font:"Plus Jakarta Sans",-apple-system,BlinkMacSystemFont,"Segoe UI","Noto Sans Myanmar",sans-serif; + --display:Sora,"Plus Jakarta Sans",-apple-system,sans-serif; + --mono:"JetBrains Mono",ui-monospace,SFMono-Regular,Menlo,monospace; + + --ground:#F3F4F9; --surface:#FFFFFF; - --sunk:#E3E9EA; - --ink:#0F1A1E; - --ink-2:#4B5D64; - --ink-3:#5B696E; - --line:#CCD7D9; - --line-2:#B4C3C6; - --accent:#0C727B; - --accent-soft:#D8EDEE; + --sunk:#EAECF5; + --ink:#161427; + --ink-2:#4A4966; + --ink-3:#5C5B77; + --line:#E1E2EE; + --line-2:#C9CADB; --amber:#945908; - --amber-soft:#F6E7CD; + --amber-soft:#F8ECD6; --up:#197551; - --up-soft:#D6EDE2; + --up-soft:#DCF1E7; --down:#A63A2B; - --down-soft:#F6DED9; - --shadow:0 1px 2px rgba(15,26,30,.07), 0 10px 24px -16px rgba(15,26,30,.35); - --radius:10px; + --down-soft:#F9E2DE; + --shadow:0 1px 2px rgba(22,20,39,.05), 0 10px 24px -16px rgba(22,20,39,.3); + --radius:12px; + + /* the two accents; --accent is whichever one this section uses */ + --indigo:#5141E0; + --indigo-edge:#3A2DB8; + --indigo-soft:#ECEBFF; + --teal:#0B7077; + --teal-edge:#08545A; + --teal-soft:#DCF1F0; + --accent:var(--indigo); + --accent-edge:var(--indigo-edge); + --accent-soft:var(--indigo-soft); + /* text drawn on a solid accent fill */ + --on-accent:#FFFFFF; + + /* the sidebar is dark in both themes */ + --side-bg:#15132A; + --side-ink:#B9B8D3; + --side-dim:#9391B5; + --side-line:#26243F; + --side-hover:#1F1D38; +} +:root[data-section="leetcode"]{ + --accent:var(--teal); + --accent-edge:var(--teal-edge); + --accent-soft:var(--teal-soft); } @media (prefers-color-scheme: dark){ :root:not([data-theme="light"]){ color-scheme:dark; - --ground:#0C1315; - --surface:#141E21; - --sunk:#0F1A1D; - --ink:#E7EFF0; - --ink-2:#A2B5BB; - --ink-3:#8C9CA2; - --line:#26363A; - --line-2:#33474C; - --accent:#4FC0C9; - --accent-soft:#103539; + --ground:#0F0E1A; + --surface:#17162A; + --sunk:#121124; + --ink:#ECEBF7; + --ink-2:#B0AFCB; + --ink-3:#9897B6; + --line:#2A2945; + --line-2:#37365A; --amber:#DFA94C; - --amber-soft:#332815; + --amber-soft:#33281550; --up:#4FC08A; --up-soft:#11312450; - --down:#E07C64; + --down:#E8806A; --down-soft:#3A1E1750; --shadow:0 1px 2px rgba(0,0,0,.4), 0 10px 24px -16px rgba(0,0,0,.8); + --indigo:#A39AFF; + --indigo-edge:#6E61E6; + --indigo-soft:#25204F; + --teal:#4FC0C9; + --teal-edge:#2A8F97; + --teal-soft:#103539; + --on-accent:#0F0E1A; + --side-bg:#0A0913; + --side-line:#1D1C31; + --side-hover:#17162A; } } :root[data-theme="dark"]{ color-scheme:dark; - --ground:#0C1315; - --surface:#141E21; - --sunk:#0F1A1D; - --ink:#E7EFF0; - --ink-2:#A2B5BB; - --ink-3:#8C9CA2; - --line:#26363A; - --line-2:#33474C; - --accent:#4FC0C9; - --accent-soft:#103539; + --ground:#0F0E1A; + --surface:#17162A; + --sunk:#121124; + --ink:#ECEBF7; + --ink-2:#B0AFCB; + --ink-3:#9897B6; + --line:#2A2945; + --line-2:#37365A; --amber:#DFA94C; - --amber-soft:#332815; + --amber-soft:#33281550; --up:#4FC08A; --up-soft:#11312450; - --down:#E07C64; + --down:#E8806A; --down-soft:#3A1E1750; --shadow:0 1px 2px rgba(0,0,0,.4), 0 10px 24px -16px rgba(0,0,0,.8); + --indigo:#A39AFF; + --indigo-edge:#6E61E6; + --indigo-soft:#25204F; + --teal:#4FC0C9; + --teal-edge:#2A8F97; + --teal-soft:#103539; + --on-accent:#0F0E1A; + --side-bg:#0A0913; + --side-line:#1D1C31; + --side-hover:#17162A; } - diff --git a/tsconfig.json b/tsconfig.json index 8bf91d3..3832a3d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,5 +1,14 @@ { "extends": "astro/tsconfigs/strict", - "include": [".astro/types.d.ts", "**/*"], - "exclude": ["dist"] -} + "include": [ + ".astro/types.d.ts", + "**/*" + ], + "exclude": [ + "dist" + ], + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "preact" + } +} \ No newline at end of file From b6c47e1fb01070aa0544ce5861b9d82a208d0191 Mon Sep 17 00:00:00 2001 From: devmtnaing <bobo.b90@gmail.com> Date: Wed, 7 Oct 2026 23:25:27 +0630 Subject: [PATCH 2/4] Section rail and per-section menus; hub jumps back into each section One shared sidebar listed every section's pages, so a LeetCode link sat in the AI Engineer menu and each new course would have made it longer. - A section rail (icons, always visible) switches between Home, LeetCode, AI Engineer and Profile. On a phone it is the bottom tab bar. - A section sidebar shows only the current section's menu, defined in src/data/sections.ts: patterns for LeetCode; tracks with progress, practice, papers and projects for AI Engineer. The hub and profile have none. Under 1024px the menu becomes a strip of links under the top bar. - The hub's "Jump back in" shows a card per section you have used, most recent first: the last LeetCode problem opened, the next AI Engineer step. progress.ts records the last thing opened per section. - The hub and profile progress rail shows site-wide stats only. npm run check and npm run audit pass. --- src/components/AppRail.astro | 46 ++++++++ src/components/AppSidebar.astro | 96 ----------------- src/components/SectionNav.astro | 69 ++++++++++++ src/components/ai/JumpBackIn.tsx | 66 ++++++++++++ src/components/ai/Rail.tsx | 7 +- src/components/ai/Session.tsx | 3 +- src/data/sections.ts | 78 ++++++++++++++ src/layouts/AiLayout.astro | 2 +- src/layouts/Base.astro | 12 ++- src/layouts/Walkthrough.astro | 5 + src/lib/progress.ts | 10 ++ src/pages/ai-engineer/[track].astro | 2 - src/pages/index.astro | 10 +- src/styles/ai.css | 6 ++ src/styles/app.css | 160 +++++++++++++++++----------- 15 files changed, 400 insertions(+), 172 deletions(-) create mode 100644 src/components/AppRail.astro delete mode 100644 src/components/AppSidebar.astro create mode 100644 src/components/SectionNav.astro create mode 100644 src/components/ai/JumpBackIn.tsx create mode 100644 src/data/sections.ts diff --git a/src/components/AppRail.astro b/src/components/AppRail.astro new file mode 100644 index 0000000..027e91a --- /dev/null +++ b/src/components/AppRail.astro @@ -0,0 +1,46 @@ +--- +/* The section rail: one icon per section, always on screen, so moving between + * courses is one click from anywhere. On a phone it is the bottom tab bar. */ +import Icon from './Icon.astro'; +import Logo from './Logo.astro'; +import { REPO, SITE_NAME } from '../data/site'; +import { SECTIONS } from '../data/sections'; + +interface Props { section: string; hasNav: boolean } +const { section, hasNav } = Astro.props; +const path = Astro.url.pathname.replace(/(index)?\.html$/, '').replace(/\/$/, '') || '/'; +--- +<nav class="app-rail-nav" aria-label="Sections"> + <a class="rail-brand" href="/" aria-label={`${SITE_NAME}: home`}><Logo size={36} /></a> + <a class="rail-item tab" href="/" aria-current={path === '/' ? 'page' : undefined} data-tip="Home" aria-label="Home"> + <Icon name="home" /><span class="rail-label">Home</span> + </a> + <span class="rail-sep" aria-hidden="true"></span> + {SECTIONS.map((s) => ( + <a class:list={['rail-item tab', `acc-${s.accent}`]} href={s.href} aria-current={section === s.id ? 'true' : undefined} data-tip={s.label} aria-label={s.label}> + <Icon name={s.icon} /><span class="rail-label">{s.id === 'ai' ? 'AI' : s.label}</span> + </a> + ))} + <span class="rail-spacer"></span> + <a class="rail-item tab" href="/profile" aria-current={path === '/profile' ? 'page' : undefined} data-tip="Profile" aria-label="Profile"> + <Icon name="user" /><span class="rail-label">Profile</span> + </a> + <a class="rail-item" href={REPO} target="_blank" rel="noopener" data-tip="Source on GitHub" aria-label="Source on GitHub"> + <Icon name="github" /> + </a> + {hasNav && ( + <button class="rail-item" type="button" data-collapse data-tip="Hide the section menu" aria-label="Show or hide the section menu" aria-controls="section-nav"> + <Icon name="panel" /> + </button> + )} +</nav> + +<script> + document.querySelector('[data-collapse]')?.addEventListener('click', () => { + const root = document.documentElement; + const on = root.dataset.nav !== 'collapsed'; + if (on) root.dataset.nav = 'collapsed'; + else delete root.dataset.nav; + try { localStorage.setItem('learn-nav', on ? 'collapsed' : ''); } catch {} + }); +</script> diff --git a/src/components/AppSidebar.astro b/src/components/AppSidebar.astro deleted file mode 100644 index 1f78a11..0000000 --- a/src/components/AppSidebar.astro +++ /dev/null @@ -1,96 +0,0 @@ ---- -/* The dark sidebar on every page. On a phone it becomes a bottom tab bar - * holding only the links marked .tab; between 720px and 1024px it shows - * icons only. The daily goal at its foot is filled in from progress.ts. */ -import Icon from './Icon.astro'; -import Logo from './Logo.astro'; -import { REPO, SITE_NAME } from '../data/site'; -import type { IconName } from '../lib/icons'; - -const path = Astro.url.pathname.replace(/(index)?\.html$/, '').replace(/\/$/, '') || '/'; -const aiSub = path.startsWith('/ai-engineer') ? (path.split('/')[2] ?? '') : null; - -type Item = { href: string; label: string; icon: IconName; active: boolean; tab?: string; accent?: 'teal' | 'indigo' }; -const groups: { label?: string; items: Item[] }[] = [ - { items: [{ href: '/', label: 'Home', icon: 'home', active: path === '/', tab: 'Home' }] }, - { - label: 'LeetCode', - items: [{ href: '/leetcode', label: 'Problems', icon: 'code', active: path.startsWith('/leetcode'), tab: 'LeetCode', accent: 'teal' }], - }, - { - label: 'AI Engineer', - items: [ - { href: '/ai-engineer', label: 'Path', icon: 'route', active: aiSub !== null && !['practice', 'papers', 'projects'].includes(aiSub), tab: 'AI path', accent: 'indigo' }, - { href: '/ai-engineer/practice', label: 'Practice', icon: 'refresh', active: aiSub === 'practice', tab: 'Practice', accent: 'indigo' }, - { href: '/ai-engineer/papers', label: 'Papers', icon: 'file', active: aiSub === 'papers', accent: 'indigo' }, - { href: '/ai-engineer/projects', label: 'Projects', icon: 'hammer', active: aiSub === 'projects', accent: 'indigo' }, - ], - }, - { label: 'You', items: [{ href: '/profile', label: 'Profile', icon: 'user', active: path === '/profile', tab: 'Profile' }] }, -]; ---- -<nav class="app-side" aria-label="Main"> - <a class="app-brand" href="/"> - <Logo size={34} /> - <span class="app-brand-text"><b>{SITE_NAME}</b><small>devmtnaing.com</small></span> - </a> - {groups.map((g) => ( - <> - {g.label && <div class="app-label">{g.label}</div>} - {g.items.map((it) => ( - <a - class:list={['app-nav', it.accent && `acc-${it.accent}`, it.tab && 'tab']} - href={it.href} - aria-current={it.active ? 'page' : undefined} - title={it.label} - > - <Icon name={it.icon} /> - <span class="app-nav-text">{it.label}</span> - {it.tab && <span class="app-tab-text">{it.tab}</span>} - </a> - ))} - </> - ))} - <a class="app-nav" href={REPO} target="_blank" rel="noopener" title="Source on GitHub"> - <Icon name="github" /> - <span class="app-nav-text">GitHub ↗</span> - </a> - <div class="app-spacer"></div> - <a class="app-goal" href="/profile" data-goal> - <span class="app-goal-row"><b>Daily goal</b><small data-goal-streak></small></span> - <small data-goal-text>0 / 30 XP</small> - <span class="app-meter"><i data-goal-bar style="width:0%"></i></span> - </a> - <button class="app-collapse" type="button" data-collapse aria-label="Collapse the sidebar"> - <Icon name="panel" size={18} /> - <span class="app-nav-text">Collapse</span> - </button> -</nav> - -<script> - import { get, subscribe, streak, xpToday } from '../lib/progress'; - - const goal = () => { - const p = get(); - const xp = xpToday(p); - const s = streak(p); - const text = document.querySelector('[data-goal-text]'); - const bar = document.querySelector<HTMLElement>('[data-goal-bar]'); - const st = document.querySelector('[data-goal-streak]'); - if (text) text.textContent = `${xp} / ${p.dailyGoal} XP today`; - if (bar) bar.style.width = `${Math.min((xp / p.dailyGoal) * 100, 100)}%`; - if (st) st.textContent = s ? `${s}-day streak` : ''; - }; - goal(); - subscribe(goal); - - document.querySelector('[data-collapse]')?.addEventListener('click', () => { - const root = document.documentElement; - const on = root.dataset.nav !== 'collapsed'; - if (on) root.dataset.nav = 'collapsed'; - else delete root.dataset.nav; - try { - localStorage.setItem('learn-nav', on ? 'collapsed' : ''); - } catch {} - }); -</script> diff --git a/src/components/SectionNav.astro b/src/components/SectionNav.astro new file mode 100644 index 0000000..37163bd --- /dev/null +++ b/src/components/SectionNav.astro @@ -0,0 +1,69 @@ +--- +/* The current section's own menu. As a sidebar (≥1024px) it has the section + * header, the menu and the daily goal; as a strip (narrower screens) it is the + * same links in one scrolling row at the top of the page. */ +import Icon from './Icon.astro'; +import type { Section } from '../data/sections'; + +interface Props { section: Section; variant?: 'sidebar' | 'strip' } +const { section: s, variant = 'sidebar' } = Astro.props; +const path = Astro.url.pathname.replace(/(index)?\.html$/, '').replace(/\/$/, '') || '/'; +const active = (href: string, prefix?: boolean) => !href.includes('#') && (path === href || (!!prefix && path.startsWith(href + '/'))); +const items = s.groups.flatMap((g) => g.items); +--- +{variant === 'sidebar' ? ( + <nav class={`section-nav acc-${s.accent}`} id="section-nav" aria-label={`${s.label} menu`}> + <a class="sn-head" href={s.href}> + <span class="sn-icon"><Icon name={s.icon} size={18} /></span> + <span><b>{s.label}</b><small>{s.tagline}</small></span> + </a> + {s.groups.map((g) => ( + <div class="sn-group"> + {g.label && <div class="sn-label">{g.label}</div>} + {g.items.map((it) => ( + <a class:list={['sn-item', it.color && `tc-${it.color}`]} href={it.href} aria-current={active(it.href, it.prefix) ? 'page' : undefined}> + {it.icon ? <Icon name={it.icon} size={17} /> : it.color ? <span class="sn-dot" aria-hidden="true"></span> : null} + <span class="sn-text"> + {it.kicker && <small>{it.kicker}</small>} + <span>{it.label}</span> + {it.meterOf && <span class="sn-meter" aria-hidden="true"><i data-meter-of={it.meterOf} style="width:0%"></i></span>} + </span> + {it.count != null && <span class="sn-count">{it.count}</span>} + </a> + ))} + </div> + ))} + <span class="sn-spacer"></span> + <a class="app-goal" href="/profile"> + <span class="app-goal-row"><b>Daily goal</b><small data-goal-streak></small></span> + <small data-goal-text>0 / 30 XP today</small> + <span class="app-meter"><i data-goal-bar style="width:0%"></i></span> + </a> + </nav> +) : ( + <nav class={`section-strip acc-${s.accent}`} aria-label={`${s.label} menu`}> + <a class="ss-item ss-head" href={s.href}><Icon name={s.icon} size={15} /> {s.label}</a> + {items.filter((it) => !it.href.includes('#')).map((it) => ( + <a class="ss-item" href={it.href} aria-current={active(it.href, it.prefix) ? 'page' : undefined}>{it.kicker ?? it.label}</a> + ))} + </nav> +)} + +<script> + import { get, subscribe, streak, xpToday } from '../lib/progress'; + const goal = () => { + const p = get(); + const xp = xpToday(p); + const s = streak(p); + document.querySelectorAll('[data-goal-text]').forEach((e) => (e.textContent = `${xp} / ${p.dailyGoal} XP today`)); + document.querySelectorAll<HTMLElement>('[data-goal-bar]').forEach((e) => (e.style.width = `${Math.min((xp / p.dailyGoal) * 100, 100)}%`)); + document.querySelectorAll('[data-goal-streak]').forEach((e) => (e.textContent = s ? `${s}-day streak` : '')); + }; + goal(); + subscribe(goal); + + // on narrow screens, show the current page's link in the strip + const strip = document.querySelector<HTMLElement>('.section-strip'); + const cur = strip?.querySelector<HTMLElement>('[aria-current]'); + if (strip && cur) strip.scrollLeft = cur.offsetLeft - (strip.clientWidth - cur.clientWidth) / 2; +</script> diff --git a/src/components/ai/JumpBackIn.tsx b/src/components/ai/JumpBackIn.tsx new file mode 100644 index 0000000..a83ae0f --- /dev/null +++ b/src/components/ai/JumpBackIn.tsx @@ -0,0 +1,66 @@ +/** The hub's "jump back in": one card per section you have used, most recent first. */ +import type { UnitRef } from '../../lib/ai/course' +import { nextUnit } from './Rail' +import { Icon, useProgress } from './ui' + +type Card = { key: string; color: string; kicker: string; title: string; sub: string; href: string; cta: string; other: { href: string; label: string }; at: number } + +export default function JumpBackIn({ units }: { units: UnitRef[] }) { + const p = useProgress() + const cards: Card[] = [] + const lc = p.recent.leetcode + if (lc) + cards.push({ + key: 'leetcode', + color: 'teal', + kicker: 'LeetCode · last opened', + title: lc.title, + sub: lc.sub, + href: lc.url, + cta: 'Open problem', + other: { href: '/leetcode', label: 'All problems' }, + at: lc.at, + }) + const aiUsed = p.recent.ai || Object.keys(p.done).length > 0 + const next = aiUsed ? nextUnit(p, units) : null + if (next) + cards.push({ + key: 'ai', + color: next.color, + kicker: 'AI Engineer · up next', + title: next.moduleTitle, + sub: `${next.trackShort} · ${next.moduleLabel} · ${next.label}`, + href: next.url, + cta: 'Continue', + other: { href: '/ai-engineer', label: 'Overview' }, + at: p.recent.ai?.at ?? 0, + }) + if (!cards.length) return null + cards.sort((a, b) => b.at - a.at) + return ( + <section aria-labelledby="jbi-h" style={{ marginBottom: '28px' }}> + <h2 id="jbi-h" class="section-title" style={{ marginTop: 0 }}> + Jump back in + </h2> + <div class="grid-cards"> + {cards.map((c) => ( + <div key={c.key} class={`card jbi tc-${c.color}`}> + <div class="kicker" style={{ color: 'var(--ct)' }}> + {c.kicker} + </div> + <b class="jbi-title">{c.title}</b> + <small class="jbi-sub">{c.sub}</small> + <div class="row" style={{ marginTop: '12px', gap: '10px' }}> + <a class="btn track sm" href={c.href}> + <Icon name="play" size={13} fill="currentColor" /> {c.cta} + </a> + <a class="jbi-other" href={c.other.href}> + {c.other.label} + </a> + </div> + </div> + ))} + </div> + </section> + ) +} diff --git a/src/components/ai/Rail.tsx b/src/components/ai/Rail.tsx index 70723a8..8df28b2 100644 --- a/src/components/ai/Rail.tsx +++ b/src/components/ai/Rail.tsx @@ -34,9 +34,10 @@ function Week({ p }: { p: Progress }) { ) } -export default function Rail({ units }: { units: UnitRef[] }) { +/** `site` (hub, profile) shows only site-wide stats; `ai` adds what's next in the course. */ +export default function Rail({ units, mode = 'ai' }: { units: UnitRef[]; mode?: 'ai' | 'site' }) { const p = useProgress() - const next = nextUnit(p, units) + const next = mode === 'ai' ? nextUnit(p, units) : null const due = dueCount(p) const xp = xpToday(p) return ( @@ -90,6 +91,7 @@ export default function Rail({ units }: { units: UnitRef[] }) { <Icon name="chevron" /> </a> )} + {mode === 'ai' && ( <a href="/ai-engineer/practice" class="card row"> <span class="chip-icon" style={{ background: 'var(--accent-soft)', color: 'var(--accent)' }}> <Icon name="refresh" /> @@ -100,6 +102,7 @@ export default function Rail({ units }: { units: UnitRef[] }) { </span> <Icon name="chevron" /> </a> + )} <div class="card"> <div class="panel-title"> <span class="kicker">This week</span> diff --git a/src/components/ai/Session.tsx b/src/components/ai/Session.tsx index b6fcf10..a8dda1a 100644 --- a/src/components/ai/Session.tsx +++ b/src/components/ai/Session.tsx @@ -3,7 +3,7 @@ import type { ComponentChildren } from 'preact' import { useEffect, useMemo, useRef, useState } from 'preact/hooks' import type { Question } from '../../lib/ai/quizzes' import type { BuildItem, Resource, UnitKind } from '../../lib/ai/course' -import { addXp, markDone, toggleChecked, totalXp, update, get } from '../../lib/progress' +import { addXp, markDone, toggleChecked, totalXp, touch, update, get } from '../../lib/progress' import { Icon, shuffle, useProgress, XP } from './ui' export type SessionModule = { @@ -449,6 +449,7 @@ export default function Session(s: SessionProps) { useEffect(() => { // opening a track's lesson makes it the track "up next" follows update((x) => (x.aiTrack === s.track.id ? x : { ...x, aiTrack: s.track.id })) + touch('ai', { url: location.pathname, title: s.module.title, sub: `${s.track.short} · ${s.module.label}` }) }, [s.track.id]) if (finished) return <DoneScreen {...finished} xp={totalXp(p) - startXp} onContinue={exit} /> diff --git a/src/data/sections.ts b/src/data/sections.ts new file mode 100644 index 0000000..a3fcf41 --- /dev/null +++ b/src/data/sections.ts @@ -0,0 +1,78 @@ +/* The site's sections and each one's own navigation. The section rail lists + * the sections; the section sidebar shows only the current one's nav, so a + * new course adds one entry here instead of lengthening a shared menu. */ +import type { IconName } from '../lib/icons'; +import { all, groups } from './catalog'; +import { tracks, trackUrl, units } from '../lib/ai/course'; + +export type SectionId = 'leetcode' | 'ai'; +export type NavItem = { + href: string; + label: string; + /** small text before the label, e.g. "Track 1" */ + kicker?: string; + icon?: IconName; + count?: number; + /** track colour for the dot and progress meter */ + color?: string; + /** unit ids whose share done fills the meter (painted by the AI section's script) */ + meterOf?: string; + /** match this path and everything under it, not only the exact path */ + prefix?: boolean; +}; +export type Section = { + id: SectionId; + label: string; + tagline: string; + href: string; + icon: IconName; + accent: 'teal' | 'indigo'; + groups: { label?: string; items: NavItem[] }[]; +}; + +export const SECTIONS: Section[] = [ + { + id: 'leetcode', + label: 'LeetCode', + tagline: 'Step through solutions', + href: '/leetcode', + icon: 'code', + accent: 'teal', + groups: [ + { items: [{ href: '/leetcode', label: 'All problems', icon: 'grid', count: all.length }] }, + { label: 'Patterns', items: groups.map((g) => ({ href: `/leetcode#${g.id}`, label: g.name, count: g.rows.length })) }, + ], + }, + { + id: 'ai', + label: 'AI Engineer', + tagline: 'Backend → research', + href: '/ai-engineer', + icon: 'sparkle', + accent: 'indigo', + groups: [ + { items: [{ href: '/ai-engineer', label: 'Overview', icon: 'route' }] }, + { + label: 'Tracks', + items: tracks.map((t) => ({ + href: trackUrl(t), + label: t.title, + kicker: t.short, + color: t.color, + prefix: true, + meterOf: units.filter((u) => u.track === t.id).map((u) => u.id).join(','), + })), + }, + { + label: 'Practice', + items: [ + { href: '/ai-engineer/practice', label: 'Flashcards & review', icon: 'refresh' }, + { href: '/ai-engineer/papers', label: 'Papers', icon: 'file' }, + { href: '/ai-engineer/projects', label: 'Projects', icon: 'hammer' }, + ], + }, + ], + }, +]; + +export const sectionOf = (id: string) => SECTIONS.find((s) => s.id === id); diff --git a/src/layouts/AiLayout.astro b/src/layouts/AiLayout.astro index 8366dd4..0572912 100644 --- a/src/layouts/AiLayout.astro +++ b/src/layouts/AiLayout.astro @@ -16,7 +16,7 @@ const { title, description, where = 'AI Engineer', section = 'ai' } = Astro.prop <StatStrip client:only="preact" /> <slot /> </div> - <Rail slot="rail" units={units} client:only="preact" /> + <Rail slot="rail" units={units} mode={section === 'ai' ? 'ai' : 'site'} client:only="preact" /> </Base> <script> diff --git a/src/layouts/Base.astro b/src/layouts/Base.astro index bb22006..fbe2c35 100644 --- a/src/layouts/Base.astro +++ b/src/layouts/Base.astro @@ -3,7 +3,9 @@ import '../styles/tokens.css'; import '../styles/base.css'; import '../styles/site.css'; import '../styles/app.css'; -import AppSidebar from '../components/AppSidebar.astro'; +import AppRail from '../components/AppRail.astro'; +import SectionNav from '../components/SectionNav.astro'; +import { sectionOf } from '../data/sections'; import SiteFooter from '../components/SiteFooter.astro'; import SiteSearch from '../components/SiteSearch.astro'; import ThemeToggle from '../components/ThemeToggle.astro'; @@ -23,6 +25,8 @@ const { title, description, section = 'hub', where, bare = false } = Astro.props // extension, so the canonical address drops it: /leetcode/two-sum, not .html. const canonical = new URL(Astro.url.pathname.replace(/(index)?\.html$/, ''), Astro.site); const hasRail = Astro.slots.has('rail'); +// the hub and the profile belong to no section, so they have no section menu +const current = sectionOf(section); --- <!doctype html> <html lang="en" data-section={section}> @@ -52,14 +56,16 @@ const hasRail = Astro.slots.has('rail'); <body class="bare"><slot /></body> ) : ( <body> - <div class:list={['app', hasRail && 'has-rail']}> - <AppSidebar /> + <div class:list={['app', current && 'has-nav', hasRail && 'has-rail']}> + <AppRail section={section} hasNav={!!current} /> + {current && <SectionNav section={current} />} <div class="app-main"> <header class="app-top"> <span class="app-where">{where}</span> <SiteSearch /> <ThemeToggle /> </header> + {current && <SectionNav section={current} variant="strip" />} <main><slot /></main> <SiteFooter /> </div> diff --git a/src/layouts/Walkthrough.astro b/src/layouts/Walkthrough.astro index 7e1013c..e5a5e3f 100644 --- a/src/layouts/Walkthrough.astro +++ b/src/layouts/Walkthrough.astro @@ -208,5 +208,10 @@ const lcUrl = (slug: string) => `https://leetcode.com/problems/${slug}/`; <script> import { initLangSwitch } from '../lib/i18n.js'; + import { touch } from '../lib/progress'; initLangSwitch(); + // the hub's "jump back in" offers the last problem opened + const title = document.querySelector('.wrap h1')?.textContent?.trim(); + const sub = document.querySelector('.wrap header .eyebrow')?.textContent?.replace(/\s+/g, ' ').trim(); + if (title) touch('leetcode', { url: location.pathname, title, sub: sub ?? 'LeetCode' }); </script> diff --git a/src/lib/progress.ts b/src/lib/progress.ts index a487aa0..099c03e 100644 --- a/src/lib/progress.ts +++ b/src/lib/progress.ts @@ -6,6 +6,8 @@ // "t2-2.7/quiz", papers "paper:<id>", projects "project:<id>". export type CardState = { box: number; due: string } +/** The last thing opened in a section, for "jump back in" on the hub. */ +export type Recent = { url: string; title: string; sub: string; at: number } export type Progress = { dailyGoal: number /** Whether the AI Engineer "where are you starting?" question was answered. */ @@ -17,6 +19,8 @@ export type Progress = { crowns: Record<string, true> quizBest: Record<string, number> cards: Record<string, CardState> + /** keyed by section id: 'leetcode', 'ai' */ + recent: Record<string, Recent> } const KEY = 'learn-progress-v1' @@ -30,6 +34,7 @@ const EMPTY: Progress = { crowns: {}, quizBest: {}, cards: {}, + recent: {}, } function load(): Progress { @@ -116,6 +121,11 @@ export function markDone(unitId: string, xp = 0) { if (first) addXp(xp) } +/** Remember the last thing opened in a section. */ +export function touch(section: string, item: Omit<Recent, 'at'>) { + update((p) => ({ ...p, recent: { ...p.recent, [section]: { ...item, at: Date.now() } } })) +} + export const exportProgress = () => JSON.stringify(get(), null, 2) export function importProgress(json: string) { diff --git a/src/pages/ai-engineer/[track].astro b/src/pages/ai-engineer/[track].astro index 15b62ad..ce6b3d5 100644 --- a/src/pages/ai-engineer/[track].astro +++ b/src/pages/ai-engineer/[track].astro @@ -1,6 +1,5 @@ --- import AiLayout from '../../layouts/AiLayout.astro'; -import TrackTabs from '../../components/ai/TrackTabs.astro'; import Stepper from '../../components/ai/Stepper.astro'; import Icon from '../../components/Icon.astro'; import { moduleUrl, tracks, unitUrl, unitKinds, type Track } from '../../lib/ai/course'; @@ -12,7 +11,6 @@ const { track } = Astro.props as { track: Track }; const first = track.modules[0]; --- <AiLayout title={`${track.short}: ${track.title}`} description={`${track.title}: ${track.subtitle}`}> - <TrackTabs current={track.id} /> <div class={`track-hero tc-${track.color}`} data-ai-track={track.id}> <div> <div class="kicker" style="color:var(--ct)">{track.short} · {track.modules.length} modules</div> diff --git a/src/pages/index.astro b/src/pages/index.astro index 937add6..593ebba 100644 --- a/src/pages/index.astro +++ b/src/pages/index.astro @@ -2,6 +2,7 @@ /* The hub: the two sections of the site, and where to pick up. */ import AiLayout from '../layouts/AiLayout.astro'; import Icon from '../components/Icon.astro'; +import JumpBackIn from '../components/ai/JumpBackIn'; import { all, PAGE } from '../data/catalog'; import { tracks, units } from '../lib/ai/course'; import { quizzes } from '../lib/ai/quizzes'; @@ -17,6 +18,8 @@ const questions = Object.values(quizzes).reduce((a, q) => a + q.length, 0); LeetCode problems you can step through one state change at a time, and a self-study path from backend engineer to AI research engineer. XP, streaks and your daily goal count across both. </p> + <JumpBackIn client:only="preact" units={units} /> + <h2 class="section-title">Sections</h2> <div class="hub-sections"> <a class="hub-card tc-teal" href="/leetcode"> <div class="kicker" style="color:var(--ct)">LeetCode</div> @@ -41,11 +44,4 @@ const questions = Object.values(quizzes).reduce((a, q) => a + q.length, 0); <span class="go">Open the path <Icon name="chevron" size={16} /></span> </a> </div> - <div class="track-hero" style="margin-top:28px"> - <div><div class="kicker">AI Engineer · pick up where you left off</div></div> - <a class="btn" href={units[0].url} data-continue hidden><Icon name="play" size={14} fill="currentColor" /> Continue: <span data-continue-label></span></a> - </div> - <div hidden> - {units.map((u) => <a href={u.url} data-unit={u.id} data-label={u.label} data-kind-label={u.label} data-mod-label={u.moduleLabel}></a>)} - </div> </AiLayout> diff --git a/src/styles/ai.css b/src/styles/ai.css index 0a672c8..617f840 100644 --- a/src/styles/ai.css +++ b/src/styles/ai.css @@ -308,3 +308,9 @@ a.card.upnext{color:var(--on-accent)} .ai-page .prose a,.session .prose a{color:var(--accent)} .prose li:has(> .task){list-style:none;margin-left:-20px} .prose .task{color:var(--muted);font-size:1.05em} + +/* ───────── hub: jump back in ───────── */ +.jbi{border-left:4px solid var(--c);display:flex;flex-direction:column;gap:2px} +.jbi-title{font-family:var(--display);font-size:18px;font-weight:600;margin-top:6px} +.jbi-sub{color:var(--muted);font-size:13px} +.jbi-other{color:var(--ink-2);font-weight:600;font-size:13px} diff --git a/src/styles/app.css b/src/styles/app.css index 8960a1a..f7db953 100644 --- a/src/styles/app.css +++ b/src/styles/app.css @@ -1,61 +1,97 @@ -/* The app shell shared by every section: a dark sidebar, the page column - (a sticky 56px top bar, the page, the footer) and, on pages that have one, - a progress rail on the right. Lesson CSS offsets its sticky parts by the - 56px bar, so keep that height. +/* The app shell shared by every section: + section rail · section sidebar · page column · progress rail + The section rail (icons) is always there, so switching courses is one + click. The section sidebar shows only the current section's menu; the hub + and the profile have none. The page column is a sticky 56px top bar, the + page and the footer; lesson CSS offsets its sticky parts by that 56px. - ≥1440px sidebar · page · rail - <1440px the rail is hidden; pages show a compact stat strip instead - <1024px the sidebar shrinks to icons - <720px the sidebar becomes a bottom tab bar */ -.app{display:grid;grid-template-columns:248px minmax(0,1fr);min-height:100vh} -.app.has-rail{grid-template-columns:248px minmax(0,1fr) 340px} -:root[data-nav="collapsed"] .app{grid-template-columns:76px minmax(0,1fr)} -:root[data-nav="collapsed"] .app.has-rail{grid-template-columns:76px minmax(0,1fr) 340px} + ≥1440px all four columns (the progress rail only on pages that have one) + <1440px the progress rail is hidden; AI pages show a stat strip instead + <1024px the section sidebar becomes a strip of links under the top bar + <720px the section rail becomes a bottom tab bar */ +.app{display:grid;grid-template-columns:68px minmax(0,1fr);min-height:100vh} +.app.has-nav{grid-template-columns:68px 244px minmax(0,1fr)} +.app.has-rail{grid-template-columns:68px minmax(0,1fr) 340px} +.app.has-nav.has-rail{grid-template-columns:68px 244px minmax(0,1fr) 340px} +:root[data-nav="collapsed"] .app.has-nav{grid-template-columns:68px minmax(0,1fr)} +:root[data-nav="collapsed"] .app.has-nav.has-rail{grid-template-columns:68px minmax(0,1fr) 340px} +:root[data-nav="collapsed"] .section-nav{display:none} .app-main{min-width:0;display:flex;flex-direction:column} -/* ---------- sidebar ---------- */ -.app-side{ - background:var(--side-bg);color:var(--side-ink); - display:flex;flex-direction:column;gap:2px;padding:18px 12px 14px; - position:sticky;top:0;height:100vh;overflow-y:auto;scrollbar-width:none;z-index:30; +/* ---------- section rail ---------- */ +.app-rail-nav{ + background:#0B0A16;display:flex;flex-direction:column;align-items:center;gap:6px;padding:14px 0; + position:sticky;top:0;height:100vh;z-index:31; +} +.rail-brand{display:grid;place-items:center;margin-bottom:8px;border-radius:11px} +.rail-sep{width:28px;height:1px;background:var(--side-line);margin:4px 0} +.rail-spacer{flex:1} +.rail-item{ + width:44px;height:44px;border-radius:12px;display:grid;place-items:center;position:relative; + color:var(--side-dim);background:none;border:0;cursor:pointer;text-decoration:none;font:inherit;padding:0; } -.app-brand{display:flex;gap:11px;align-items:center;padding:2px 8px 16px;text-decoration:none;color:#fff} -.app-brand b{display:block;font-family:var(--display);font-size:17px;font-weight:700;line-height:1.1;letter-spacing:-.02em} -.app-brand small{font-family:var(--mono);font-size:10.5px;color:var(--side-dim)} -.app-label{font-family:var(--mono);font-size:10.5px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:var(--side-dim);padding:14px 12px 6px} -.app-nav{ - display:flex;align-items:center;gap:12px;padding:9px 12px;border-radius:10px; - text-decoration:none;font-weight:600;font-size:14px;color:var(--side-ink);position:relative; +.rail-item:hover{color:#fff;background:var(--side-hover)} +.rail-item[aria-current]{color:#fff;background:#2A2650} +.rail-item.acc-teal[aria-current]{background:#123A3F;color:#7FE0E7} +.rail-item.acc-indigo[aria-current]{background:#2A2650;color:#C2BBFF} +.rail-item[aria-current]::before{content:"";position:absolute;left:-12px;top:10px;bottom:10px;width:3px;border-radius:0 3px 3px 0;background:currentColor} +.rail-label{display:none} +/* a label beside the icon on hover or keyboard focus */ +.rail-item[data-tip]:hover::after,.rail-item[data-tip]:focus-visible::after{ + content:attr(data-tip);position:absolute;left:54px;top:50%;transform:translateY(-50%);white-space:nowrap; + background:#0B0A16;color:#fff;font-size:12.5px;font-weight:600;padding:5px 10px;border-radius:8px; + box-shadow:0 4px 14px rgba(0,0,0,.35);pointer-events:none;z-index:50; } -.app-nav svg{flex:none} -.app-nav:hover{background:var(--side-hover);color:#fff} -.app-nav[aria-current="page"]{background:linear-gradient(90deg,rgba(123,109,255,.24),rgba(123,109,255,.06));color:#fff} -.app-nav.acc-teal[aria-current="page"]{background:linear-gradient(90deg,rgba(79,192,201,.22),rgba(79,192,201,.05))} -.app-nav[aria-current="page"]::before{ - content:"";position:absolute;left:-12px;top:7px;bottom:7px;width:3px;border-radius:3px; - background:#7B6DFF;box-shadow:0 0 12px #7B6DFF; +.app-rail-nav a:focus-visible,.app-rail-nav button:focus-visible{outline:2px solid #7B6DFF;outline-offset:2px} +:root[data-nav="collapsed"] [data-collapse]{color:#C2BBFF} + +/* ---------- section sidebar ---------- */ +.section-nav{ + background:var(--side-bg);color:var(--side-ink);border-right:1px solid var(--side-line); + display:flex;flex-direction:column;gap:2px;padding:16px 12px 14px; + position:sticky;top:0;height:100vh;overflow-y:auto;scrollbar-width:none;z-index:30; } -.app-nav.acc-teal[aria-current="page"]::before{background:#4FC0C9;box-shadow:0 0 12px #4FC0C9} -.app-tab-text{display:none} -.app-spacer{flex:1;min-height:12px} -.app-goal{display:block;border:1px solid var(--side-line);border-radius:12px;padding:11px 12px;margin-bottom:6px;text-decoration:none;color:var(--side-ink)} -.app-goal:hover{border-color:#3a3860} +.sn-head{display:flex;gap:11px;align-items:center;padding:4px 8px 14px;text-decoration:none;color:#fff} +.sn-head b{display:block;font-family:var(--display);font-size:16px;font-weight:700;line-height:1.15;letter-spacing:-.01em} +.sn-head small{font-size:11.5px;color:var(--side-dim)} +.sn-icon{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;flex:none} +.acc-teal .sn-icon{background:#123A3F;color:#7FE0E7} +.acc-indigo .sn-icon{background:#2A2650;color:#C2BBFF} +.sn-group{display:flex;flex-direction:column;gap:1px;margin-bottom:6px} +.sn-label{font-family:var(--mono);font-size:10.5px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:var(--side-dim);padding:12px 10px 6px} +.sn-item{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:9px;text-decoration:none;color:var(--side-ink);font-size:13.5px;font-weight:500;position:relative} +.sn-item svg{flex:none;opacity:.85} +.sn-item:hover{background:var(--side-hover);color:#fff} +.sn-item[aria-current]{background:var(--side-hover);color:#fff;font-weight:600} +.acc-teal .sn-item[aria-current]{box-shadow:inset 3px 0 0 #4FC0C9} +.acc-indigo .sn-item[aria-current]{box-shadow:inset 3px 0 0 #7B6DFF} +.sn-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px} +.sn-text > span:first-of-type{overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.sn-text small{font-family:var(--mono);font-size:10px;letter-spacing:.06em;text-transform:uppercase;color:var(--side-dim)} +.sn-count{font-family:var(--mono);font-size:10.5px;color:var(--side-dim)} +.sn-dot{width:10px;height:10px;border-radius:3px;background:var(--c);flex:none;align-self:flex-start;margin-top:4px} +.sn-meter{display:block;height:4px;border-radius:4px;background:#26243F;overflow:hidden;margin-top:5px} +.sn-meter i{display:block;height:100%;background:var(--c);border-radius:4px;transition:width .4s} +.sn-spacer{flex:1;min-height:12px} +.section-nav a:focus-visible{outline:2px solid #7B6DFF;outline-offset:2px} + +.app-goal{display:block;border:1px solid var(--side-line);border-radius:12px;padding:11px 12px;text-decoration:none;color:var(--side-ink)} +.app-goal:hover{border-color:#3A3860} .app-goal-row{display:flex;justify-content:space-between;align-items:baseline;gap:8px} .app-goal b{color:#fff;font-size:13px} .app-goal small{font-family:var(--mono);font-size:10.5px;color:var(--side-dim)} .app-meter{display:block;height:6px;border-radius:9px;background:#26243F;overflow:hidden;margin-top:8px} .app-meter i{display:block;height:100%;background:#7B6DFF;border-radius:9px;transition:width .4s} -.app-collapse{display:flex;align-items:center;gap:10px;background:none;border:0;padding:9px 12px;color:var(--side-dim);font:inherit;font-weight:600;font-size:13px;border-radius:10px;cursor:pointer} -.app-collapse:hover{color:#fff;background:var(--side-hover)} -.app-side a:focus-visible,.app-side button:focus-visible{outline:2px solid #7B6DFF;outline-offset:2px} -:root[data-nav="collapsed"] .app-brand-text, -:root[data-nav="collapsed"] .app-nav-text, -:root[data-nav="collapsed"] .app-label, -:root[data-nav="collapsed"] .app-goal{display:none} -:root[data-nav="collapsed"] .app-nav, -:root[data-nav="collapsed"] .app-collapse, -:root[data-nav="collapsed"] .app-brand{justify-content:center;padding-inline:0} +/* ---------- section strip (narrow screens) ---------- */ +.section-strip{ + display:none;position:relative;gap:6px;overflow-x:auto;scrollbar-width:none;padding:10px clamp(16px,3vw,40px); + border-bottom:1px solid var(--line);background:var(--surface); +} +.section-strip::-webkit-scrollbar{display:none} +.ss-item{flex:none;padding:6px 12px;border-radius:999px;border:1px solid var(--line);font-size:13px;font-weight:600;color:var(--ink-2);text-decoration:none;white-space:nowrap;display:inline-flex;align-items:center;gap:6px} +.ss-item[aria-current]{background:var(--accent-soft);border-color:var(--accent);color:var(--accent)} +.ss-head{border-color:transparent;color:var(--ink);padding-left:0} /* ---------- top bar ---------- */ .app-top{ @@ -66,32 +102,36 @@ } .app-where{flex:1;min-width:0;font-family:var(--mono);font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:var(--ink-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} -/* ---------- rail ---------- */ +/* ---------- progress rail ---------- */ .app-rail{padding:24px 24px 32px 0;position:sticky;top:0;align-self:start;max-height:100vh;overflow-y:auto;scrollbar-width:thin} -/* ---------- bare pages (lesson sessions) ---------- */ +/* ---------- bare pages (lesson steps) ---------- */ body.bare{min-height:100vh} /* ---------- responsive ---------- */ @media (max-width:1439px){ - .app.has-rail{grid-template-columns:248px minmax(0,1fr)} - :root[data-nav="collapsed"] .app.has-rail{grid-template-columns:76px minmax(0,1fr)} + .app.has-rail{grid-template-columns:68px minmax(0,1fr)} + .app.has-nav.has-rail{grid-template-columns:68px 244px minmax(0,1fr)} + :root[data-nav="collapsed"] .app.has-nav.has-rail{grid-template-columns:68px minmax(0,1fr)} .app-rail{display:none} } @media (max-width:1023px){ - .app,.app.has-rail,:root[data-nav="collapsed"] .app,:root[data-nav="collapsed"] .app.has-rail{grid-template-columns:72px minmax(0,1fr)} - .app-brand-text,.app-nav-text,.app-label,.app-goal,.app-collapse{display:none} - .app-nav,.app-brand{justify-content:center;padding-inline:0} + .app,.app.has-nav,.app.has-rail,.app.has-nav.has-rail, + :root[data-nav="collapsed"] .app.has-nav,:root[data-nav="collapsed"] .app.has-nav.has-rail{grid-template-columns:68px minmax(0,1fr)} + .section-nav,[data-collapse]{display:none} + .section-strip{display:flex} } @media (max-width:719px){ - .app,.app.has-rail,:root[data-nav="collapsed"] .app,:root[data-nav="collapsed"] .app.has-rail{display:block} + .app,.app.has-nav,.app.has-rail,.app.has-nav.has-rail, + :root[data-nav="collapsed"] .app.has-nav,:root[data-nav="collapsed"] .app.has-nav.has-rail{display:block} .app-main{min-height:100vh;padding-bottom:64px} - .app-side{ + .app-rail-nav{ position:fixed;inset:auto 0 0 0;height:auto;flex-direction:row;justify-content:space-around;gap:0; - padding:6px 4px calc(6px + env(safe-area-inset-bottom));overflow:visible;border-top:1px solid var(--side-line); + padding:6px 4px calc(6px + env(safe-area-inset-bottom));border-top:1px solid var(--side-line); } - .app-side > :not(.tab){display:none} - .app-nav.tab{flex:1;flex-direction:column;gap:3px;padding:6px 2px;font-size:10.5px;border-radius:10px} - .app-nav.tab .app-tab-text{display:block} - .app-nav[aria-current="page"]::before{left:25%;right:25%;top:-6px;bottom:auto;width:auto;height:3px} + .app-rail-nav > :not(.tab){display:none} + .rail-item.tab{flex:1;width:auto;height:auto;display:flex;flex-direction:column;align-items:center;gap:3px;padding:6px 2px;font-size:10.5px;font-weight:600} + .rail-item.tab .rail-label{display:block} + .rail-item[aria-current]::before{left:30%;right:30%;top:-6px;bottom:auto;width:auto;height:3px;border-radius:0 0 3px 3px} + .rail-item[data-tip]::after{display:none} } From 1370e31ca0a8e668f8e1cc60902c2e49fb381ee4 Mon Sep 17 00:00:00 2001 From: devmtnaing <bobo.b90@gmail.com> Date: Thu, 8 Oct 2026 10:19:41 +0630 Subject: [PATCH 3/4] Per-section XP, study pace in hours, scoped search, simpler problem list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Layout: the progress rail sits under the top bar, beside the page, and the footer runs under both, so neither is cut short. - XP is recorded per section. Each section shows its own streak and XP; the hub and profile show the total and each section. The daily goal counts every section. LeetCode lessons get "Mark as solved" (+20 XP), ticked on the problem list. Older saves migrate (their XP was all AI). - Study pace in hours a week (3, 6, 12, 25) replaces the XP goal choice. It sets the daily goal, and every AI Engineer time estimate is scaled from the course's ~13.5 h/week to your pace. - The AI Engineer plan is asked once (pace, then where to start) and then shown as "Your plan" with a link to change it in the profile. - ⌘K search stays in its section: problems on LeetCode pages, modules on AI Engineer pages, both on the hub and profile. - Problem list: no in-page pattern sidebar (the section menu has the patterns and highlights the one being read), no in-page search (⌘K) and no "With a solution" filter; a difficulty filter stays. npm run check and npm run audit pass. --- src/components/SectionNav.astro | 8 +- src/components/SiteSearch.astro | 15 +- src/components/ai/JumpBackIn.tsx | 2 +- src/components/ai/Onboard.tsx | 124 ++++++++----- src/components/ai/Plan.tsx | 26 +++ src/components/ai/Profile.tsx | 88 +++++---- src/components/ai/Rail.tsx | 158 +++++++++++------ src/layouts/Base.astro | 6 +- src/layouts/Walkthrough.astro | 20 ++- src/lib/ai/course.ts | 5 + src/lib/ai/decorate.ts | 9 +- src/lib/progress.ts | 117 ++++++++---- src/pages/ai-engineer/[track].astro | 8 +- src/pages/ai-engineer/[track]/[module].astro | 4 +- src/pages/ai-engineer/index.astro | 29 +-- src/pages/leetcode/index.astro | 177 +++++++------------ src/pages/profile.astro | 8 +- src/styles/ai.css | 31 ++++ src/styles/app.css | 23 ++- src/styles/site.css | 59 +++---- 20 files changed, 554 insertions(+), 363 deletions(-) create mode 100644 src/components/ai/Plan.tsx diff --git a/src/components/SectionNav.astro b/src/components/SectionNav.astro index 37163bd..d2f84a8 100644 --- a/src/components/SectionNav.astro +++ b/src/components/SectionNav.astro @@ -50,13 +50,15 @@ const items = s.groups.flatMap((g) => g.items); )} <script> - import { get, subscribe, streak, xpToday } from '../lib/progress'; + import { dailyGoal, get, PACES, subscribe, streak, xpToday } from '../lib/progress'; + // the daily goal counts XP from every section; the pace sets its size const goal = () => { const p = get(); const xp = xpToday(p); const s = streak(p); - document.querySelectorAll('[data-goal-text]').forEach((e) => (e.textContent = `${xp} / ${p.dailyGoal} XP today`)); - document.querySelectorAll<HTMLElement>('[data-goal-bar]').forEach((e) => (e.style.width = `${Math.min((xp / p.dailyGoal) * 100, 100)}%`)); + const g = dailyGoal(p); + document.querySelectorAll('[data-goal-text]').forEach((e) => (e.textContent = `${xp} / ${g} XP today · ${PACES[p.pace].label}`)); + document.querySelectorAll<HTMLElement>('[data-goal-bar]').forEach((e) => (e.style.width = `${Math.min((xp / g) * 100, 100)}%`)); document.querySelectorAll('[data-goal-streak]').forEach((e) => (e.textContent = s ? `${s}-day streak` : '')); }; goal(); diff --git a/src/components/SiteSearch.astro b/src/components/SiteSearch.astro index bd5cee3..b856289 100644 --- a/src/components/SiteSearch.astro +++ b/src/components/SiteSearch.astro @@ -42,11 +42,19 @@ btn.querySelector('[data-key]')!.textContent = mac ? '⌘K' : 'Ctrl K'; btn.hidden = false; + // Search stays inside the section you're in: LeetCode finds problems, AI + // Engineer finds modules, the hub and profile find both. + const section = document.documentElement.dataset.section; + const inScope = (r: Row) => (section === 'leetcode' ? r.kind !== 'module' : section === 'ai' ? r.kind === 'module' : true); + field.placeholder = section === 'leetcode' ? 'Search problems by name, number or pattern' + : section === 'ai' ? 'Search AI Engineer modules and concepts' : 'Search problems and AI Engineer modules'; + field.setAttribute('aria-label', field.placeholder); + let rows: Row[] | null = null; let loading: Promise<void> | null = null; const load = () => (loading ??= fetch('/search.json') .then((r) => r.json()) - .then((data: Row[]) => { rows = data; }) + .then((data: Row[]) => { rows = data.filter(inScope); }) .catch(() => { loading = null; })); let shown: Row[] = []; @@ -60,7 +68,8 @@ if (!rows) return []; const typed = q.trim().toLowerCase(); const terms = typed.split(/\s+/).filter(Boolean); - if (!terms.length) return rows.filter((r) => r.page && r.kind !== 'module'); + // an empty field lists the pages: every solution, or every module + if (!terms.length) return section === 'ai' ? rows : rows.filter((r) => r.page && r.kind !== 'module'); const rank = (r: Row) => (String(r.id) === typed ? 0 : r.title.toLowerCase().startsWith(typed) ? 2 : 4) + (r.page ? 0 : 1); return rows .filter((r) => terms.every((t) => r.text.includes(t))) @@ -96,7 +105,7 @@ active = 0; list.replaceChildren(...shown.map(option)); const typed = field.value.trim(); - head.textContent = typed ? '' : 'Problems with a solution page'; + head.textContent = typed ? '' : section === 'ai' ? 'AI Engineer modules' : 'Problems with a solution page'; head.hidden = !!typed; status.textContent = !rows ? (loading ? 'Loading…' : 'Could not load the problem list.') diff --git a/src/components/ai/JumpBackIn.tsx b/src/components/ai/JumpBackIn.tsx index a83ae0f..8aad022 100644 --- a/src/components/ai/JumpBackIn.tsx +++ b/src/components/ai/JumpBackIn.tsx @@ -21,7 +21,7 @@ export default function JumpBackIn({ units }: { units: UnitRef[] }) { other: { href: '/leetcode', label: 'All problems' }, at: lc.at, }) - const aiUsed = p.recent.ai || Object.keys(p.done).length > 0 + const aiUsed = p.recent.ai || p.aiOnboarded || Object.keys(p.done).length > 0 const next = aiUsed ? nextUnit(p, units) : null if (next) cards.push({ diff --git a/src/components/ai/Onboard.tsx b/src/components/ai/Onboard.tsx index 6892fb5..1742158 100644 --- a/src/components/ai/Onboard.tsx +++ b/src/components/ai/Onboard.tsx @@ -1,59 +1,89 @@ -/** "Where are you starting?" on the AI Engineer overview, until it has been answered once. */ +/** The AI Engineer plan: asked once (pace, then where to start), then shown as a summary. */ import { useState } from 'preact/hooks' import type { IconName } from '../../lib/icons' -import { update } from '../../lib/progress' +import { formatWeeks, PACES, update, weeksAtPace } from '../../lib/progress' +import { PacePicker } from './Plan' import { Icon, useProgress } from './ui' -const STARTS: { id: string; url: string; color: string; icon: IconName; t: string; s: string }[] = [ - { id: 'setup', url: '/ai-engineer/setup', color: 'slate', icon: 'code', t: 'Set up first', s: 'Python, PyTorch, GPU access and notes (week 0)' }, - { id: 't1', url: '/ai-engineer/track-1', color: 'teal', icon: 'bulb', t: 'New to building with LLMs', s: 'Start with Track 1: AI Application Engineer' }, - { id: 't2', url: '/ai-engineer/track-2', color: 'indigo', icon: 'bolt', t: 'I already ship LLM apps', s: 'Jump to Track 2: ML / AI Systems Engineer' }, - { id: 't3', url: '/ai-engineer/track-3', color: 'rose', icon: 'sparkle', t: 'I already train models', s: 'Jump to Track 3: Research Engineer' }, +export type TrackPlan = { id: string; url: string; short: string; title: string; color: string; weeks: number } + +const STARTS: { id: string; icon: IconName; t: string; s: string }[] = [ + { id: 'setup', icon: 'code', t: 'Set up first', s: 'Python, PyTorch, GPU access and notes (week 0)' }, + { id: 't1', icon: 'bulb', t: 'New to building with LLMs', s: 'Start with Track 1: AI Application Engineer' }, + { id: 't2', icon: 'bolt', t: 'I already ship LLM apps', s: 'Jump to Track 2: ML / AI Systems Engineer' }, + { id: 't3', icon: 'sparkle', t: 'I already train models', s: 'Jump to Track 3: Research Engineer' }, ] -export default function Onboard() { +export default function Onboard({ tracks }: { tracks: TrackPlan[] }) { const p = useProgress() - const [goal, setGoal] = useState(p.dailyGoal) - if (p.aiOnboarded) return null + const [step, setStep] = useState<1 | 2>(1) + const track = tracks.find((t) => t.id === p.aiTrack) ?? tracks[1] + + if (p.aiOnboarded) { + const all = tracks.filter((t) => t.id !== 'math' && t.id !== 'setup').reduce((a, t) => a + t.weeks, 0) + return ( + <section class={`card plan-card tc-${track.color}`} aria-label="Your plan"> + <div class="plan-main"> + <div class="kicker">Your plan</div> + <b class="plan-title"> + {PACES[p.pace].label} · {PACES[p.pace].hours} h a week + </b> + <small> + You're on {track.short}: {track.title}, {formatWeeks(weeksAtPace(track.weeks, p.pace))} at this pace. All three tracks: {formatWeeks(weeksAtPace(all, p.pace))}. Estimates on every page follow your pace. + </small> + </div> + <a class="btn ghost sm" href="/profile#plan"> + Change plan + </a> + </section> + ) + } + return ( <section class="card onb-card" aria-labelledby="onb-h"> - <div class="kicker">Welcome</div> - <h2 id="onb-h" style={{ fontSize: '22px', margin: '6px 0 4px' }}> - Where are you starting? - </h2> - <p class="page-sub" style={{ margin: 0 }}> - Pick a daily goal, then a starting point. You can change both later on your profile. - </p> - <div class="seg" role="group" aria-label="Daily goal" style={{ marginTop: '14px' }}> - {[ - [10, 'Casual'], - [30, 'Regular'], - [50, 'Serious'], - [100, 'Intense'], - ].map(([xp, l]) => ( - <button key={xp} class={goal === xp ? 'on' : ''} aria-pressed={goal === xp} onClick={() => setGoal(xp as number)}> - {l} · {xp} XP/day - </button> - ))} - </div> - <div class="choices"> - {STARTS.map((s) => ( - <a - key={s.id} - href={s.url} - class={`choice tc-${s.color}`} - onClick={() => update((x) => ({ ...x, aiOnboarded: true, aiTrack: s.id, dailyGoal: goal }))} - > - <span class="e"> - <Icon name={s.icon} /> - </span> - <span> - <b>{s.t}</b> - <small>{s.s}</small> - </span> - </a> - ))} - </div> + <div class="kicker">Set up your plan · step {step} of 2</div> + {step === 1 ? ( + <> + <h2 id="onb-h" class="onb-h"> + How much time can you study? + </h2> + <p class="page-sub" style={{ margin: 0 }}> + The course is written for about 13 hours a week. Pick yours and every estimate adjusts. You can change it any time in your profile. + </p> + <PacePicker value={p.pace} onPick={() => setStep(2)} /> + </> + ) : ( + <> + <h2 id="onb-h" class="onb-h"> + Where are you starting? + </h2> + <p class="page-sub" style={{ margin: 0 }}> + {PACES[p.pace].label}, {PACES[p.pace].hours} h a week.{' '} + <button type="button" class="linkish" onClick={() => setStep(1)}> + Change + </button> + </p> + <div class="choices"> + {STARTS.map((s) => { + const t = tracks.find((x) => x.id === s.id)! + return ( + <a key={s.id} href={t.url} class={`choice tc-${t.color}`} onClick={() => update((x) => ({ ...x, aiOnboarded: true, aiTrack: s.id }))}> + <span class="e"> + <Icon name={s.icon} /> + </span> + <span> + <b>{s.t}</b> + <small> + {s.s} + {t.weeks ? ` · ${formatWeeks(weeksAtPace(t.weeks, p.pace))}` : ''} + </small> + </span> + </a> + ) + })} + </div> + </> + )} </section> ) } diff --git a/src/components/ai/Plan.tsx b/src/components/ai/Plan.tsx new file mode 100644 index 0000000..7ee903b --- /dev/null +++ b/src/components/ai/Plan.tsx @@ -0,0 +1,26 @@ +/** Choosing a study pace, shown in hours a week. Shared by onboarding and the profile. */ +import { PACES, update, type Pace } from '../../lib/progress' + +export function PacePicker({ value, onPick }: { value: Pace; onPick?: (p: Pace) => void }) { + return ( + <div class="pace-grid" role="radiogroup" aria-label="Study pace"> + {(Object.keys(PACES) as Pace[]).map((k) => ( + <button + key={k} + type="button" + role="radio" + aria-checked={value === k} + class={`pace ${value === k ? 'on' : ''}`} + onClick={() => { + update((p) => ({ ...p, pace: k })) + onPick?.(k) + }} + > + <b>{PACES[k].label}</b> + <span class="pace-h">{PACES[k].hours} h / week</span> + <small>{k === 'intense' ? 'about full-time' : `about ${Math.round((PACES[k].hours * 60) / 7)} min a day`}</small> + </button> + ))} + </div> + ) +} diff --git a/src/components/ai/Profile.tsx b/src/components/ai/Profile.tsx index 8ea9a7f..3e87eb2 100644 --- a/src/components/ai/Profile.tsx +++ b/src/components/ai/Profile.tsx @@ -1,11 +1,28 @@ -/** Site-wide progress: stats, the AI Engineer tracks, daily goal, and moving data between browsers. */ +/** Site-wide progress: totals, each section, the study plan, and moving data between browsers. */ import { useRef, useState } from 'preact/hooks' -import { crownCount, exportProgress, importProgress, resetProgress, streak, totalXp, update } from '../../lib/progress' +import { + crownCount, exportProgress, formatWeeks, importProgress, PACES, resetProgress, solvedCount, streak, totalXp, update, weeksAtPace, +} from '../../lib/progress' +import { PacePicker } from './Plan' import { Icon, useProgress } from './ui' -export type TrackSummary = { id: string; url: string; short: string; title: string; color: string; units: string[]; modules: string[] } +export type TrackSummary = { id: string; url: string; short: string; title: string; color: string; units: string[]; modules: string[]; weeks: number } -export default function Profile({ tracks }: { tracks: TrackSummary[] }) { +function Stat({ icon, color, n, l }: { icon: 'flame' | 'bolt' | 'crown' | 'check'; color: string; n: number; l: string }) { + return ( + <div class="card row"> + <span class="chip-icon" style={{ background: `color-mix(in srgb, ${color} 16%, transparent)`, color }}> + <Icon name={icon} /> + </span> + <span class="grow"> + <b style={{ fontFamily: 'var(--display)', fontSize: '22px' }}>{n}</b> + <small>{l}</small> + </span> + </div> + ) +} + +export default function Profile({ tracks, problems }: { tracks: TrackSummary[]; problems: number }) { const p = useProgress() const file = useRef<HTMLInputElement>(null) const [msg, setMsg] = useState('') @@ -26,25 +43,27 @@ export default function Profile({ tracks }: { tracks: TrackSummary[] }) { } return ( <> - <div class="grid-cards" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))' }}> - {[ - { icon: 'flame' as const, color: 'var(--streak)', n: streak(p), l: 'day streak' }, - { icon: 'bolt' as const, color: 'var(--xp)', n: totalXp(p), l: 'total XP' }, - { icon: 'crown' as const, color: 'var(--accent)', n: crownCount(p), l: 'modules crowned' }, - ].map((s) => ( - <div class="card row" key={s.l}> - <span class="chip-icon" style={{ background: `color-mix(in srgb, ${s.color} 16%, transparent)`, color: s.color }}> - <Icon name={s.icon} /> - </span> - <span class="grow"> - <b style={{ fontFamily: 'var(--display)', fontSize: '22px' }}>{s.n}</b> - <small>{s.l}</small> - </span> - </div> - ))} + <h2 class="section-title" style={{ marginTop: 0 }}> + All sections + </h2> + <div class="grid-cards" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(min(200px, 100%), 1fr))' }}> + <Stat icon="flame" color="var(--streak)" n={streak(p)} l="day streak, any section" /> + <Stat icon="bolt" color="var(--xp)" n={totalXp(p)} l="total XP" /> </div> - <div class="section-title">AI Engineer</div> + <h2 class="section-title">LeetCode</h2> + <div class="grid-cards" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(min(200px, 100%), 1fr))' }}> + <Stat icon="check" color="var(--teal)" n={solvedCount(p)} l={`of ${problems} problems solved`} /> + <Stat icon="flame" color="var(--streak)" n={streak(p, 'leetcode')} l="day streak" /> + <Stat icon="bolt" color="var(--xp)" n={totalXp(p, 'leetcode')} l="XP" /> + </div> + + <h2 class="section-title">AI Engineer</h2> + <div class="grid-cards" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(min(200px, 100%), 1fr))', marginBottom: '12px' }}> + <Stat icon="crown" color="var(--indigo)" n={crownCount(p)} l="modules crowned" /> + <Stat icon="flame" color="var(--streak)" n={streak(p, 'ai')} l="day streak" /> + <Stat icon="bolt" color="var(--xp)" n={totalXp(p, 'ai')} l="XP" /> + </div> <div class="grid-cards"> {tracks.map((t) => { const pct = t.units.length ? Math.round((t.units.filter((u) => p.done[u]).length / t.units.length) * 100) : 0 @@ -57,6 +76,7 @@ export default function Profile({ tracks }: { tracks: TrackSummary[] }) { </b> <small> {t.modules.filter((m) => p.crowns[m]).length} / {t.modules.length} modules crowned + {t.weeks ? ` · ${formatWeeks(weeksAtPace(t.weeks, p.pace))} at your pace` : ''} </small> </span> <b>{pct}%</b> @@ -69,21 +89,27 @@ export default function Profile({ tracks }: { tracks: TrackSummary[] }) { })} </div> - <div class="section-title">LeetCode</div> - <p class="page-sub">Problem progress isn't tracked yet. It arrives with sign-in, and will share this XP and streak.</p> - - <div class="section-title">Daily goal</div> - <div class="seg" role="group" aria-label="Daily goal"> - {[10, 30, 50, 100].map((g) => ( - <button key={g} class={p.dailyGoal === g ? 'on' : ''} aria-pressed={p.dailyGoal === g} onClick={() => update((s) => ({ ...s, dailyGoal: g }))}> - {g} XP + <h2 class="section-title" id="plan"> + Study plan + </h2> + <p class="page-sub" style={{ marginBottom: 0 }}> + How many hours a week you can study. It sets your daily goal ({PACES[p.pace].xp} XP at {PACES[p.pace].label}) and every time estimate in the AI Engineer course. + </p> + <PacePicker value={p.pace} /> + <p class="page-sub" style={{ margin: '16px 0 8px' }}> + Current AI Engineer track ("up next" follows it; opening a lesson in another track switches it): + </p> + <div class="seg" role="radiogroup" aria-label="Current track"> + {tracks.map((t) => ( + <button key={t.id} role="radio" aria-checked={p.aiTrack === t.id} class={p.aiTrack === t.id ? 'on' : ''} onClick={() => update((x) => ({ ...x, aiTrack: t.id, aiOnboarded: true }))}> + {t.short} </button> ))} </div> - <div class="section-title">Your data</div> + <h2 class="section-title">Your data</h2> <p class="page-sub" style={{ marginBottom: '12px' }}> - Progress is saved in this browser only. Export it to back it up or move it to another device. Files exported from the standalone AI Engineer site import too. + Progress is saved in this browser only, until sign-in arrives. Export it to back it up or move it to another device. Files exported from the standalone AI Engineer site import too. </p> <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}> <button class="btn ghost sm" onClick={download}> diff --git a/src/components/ai/Rail.tsx b/src/components/ai/Rail.tsx index 8df28b2..ea7b734 100644 --- a/src/components/ai/Rail.tsx +++ b/src/components/ai/Rail.tsx @@ -1,7 +1,7 @@ /** The right-hand progress rail, and the compact strip that replaces it on narrower screens. */ import { cards } from '../../lib/ai/flashcards' import type { UnitRef } from '../../lib/ai/course' -import { crownCount, streak, today, totalXp, xpToday, type Progress } from '../../lib/progress' +import { crownCount, dailyGoal, dayXp, PACES, solvedCount, streak, today, totalXp, xpToday, type Progress, type SectionId } from '../../lib/progress' import { Icon, startedModules, useProgress } from './ui' export function nextUnit(p: Progress, units: UnitRef[]): UnitRef | null { @@ -15,18 +15,27 @@ export function dueCount(p: Progress) { return cards.filter((c) => started.has(c.module) && (!p.cards[c.id] || p.cards[c.id].due <= t)).length } +const SECTION_COLOR: Record<SectionId, string> = { leetcode: 'var(--teal)', ai: 'var(--indigo)' } + +/** Seven days of XP, stacked by section. */ function Week({ p }: { p: Progress }) { const days = Array.from({ length: 7 }, (_, i) => { const d = new Date() d.setDate(d.getDate() - (6 - i)) - return { key: today(d), label: d.toLocaleDateString('en', { weekday: 'narrow' }), xp: p.xpByDay[today(d)] || 0 } + const key = today(d) + return { key, label: d.toLocaleDateString('en', { weekday: 'narrow' }), lc: dayXp(p, key, 'leetcode'), ai: dayXp(p, key, 'ai') } }) - const max = Math.max(p.dailyGoal, ...days.map((d) => d.xp)) + const max = Math.max(dailyGoal(p), ...days.map((d) => d.lc + d.ai)) + const h = (n: number) => (n / max) * 70 return ( <div class="week" aria-label="XP over the last 7 days"> {days.map((d, i) => ( - <div key={d.key} class={i === 6 ? 'today' : ''} title={`${d.xp} XP`}> - <i style={{ height: `${Math.max((d.xp / max) * 70, 4)}px` }} /> + <div key={d.key} class={i === 6 ? 'today' : ''} title={`${d.lc + d.ai} XP (LeetCode ${d.lc}, AI Engineer ${d.ai})`}> + <span class="stack-bar"> + {d.ai > 0 && <i style={{ height: `${h(d.ai)}px`, background: SECTION_COLOR.ai }} />} + {d.lc > 0 && <i style={{ height: `${h(d.lc)}px`, background: SECTION_COLOR.leetcode }} />} + {d.ai + d.lc === 0 && <i class="empty" />} + </span> <span>{d.label}</span> </div> ))} @@ -34,46 +43,97 @@ function Week({ p }: { p: Progress }) { ) } -/** `site` (hub, profile) shows only site-wide stats; `ai` adds what's next in the course. */ +function Tile({ icon, color, n, label }: { icon: 'flame' | 'bolt' | 'crown' | 'check'; color: string; n: number; label: string }) { + return ( + <div class="tile"> + <span class="ic" style={{ background: `color-mix(in srgb, ${color} 16%, transparent)`, color }}> + <Icon name={icon} size={16} /> + </span> + <b>{n}</b> + <small>{label}</small> + </div> + ) +} + +function Goal({ p }: { p: Progress }) { + const xp = xpToday(p) + const g = dailyGoal(p) + return ( + <div class="card"> + <div class="panel-title"> + <span class="kicker">Daily goal · {PACES[p.pace].label}</span> + <span class="kicker"> + {xp}/{g} XP + </span> + </div> + <div class="meter"> + <i style={{ width: `${Math.min((xp / g) * 100, 100)}%`, background: xp >= g ? 'var(--ok)' : 'var(--accent)' }} /> + </div> + <small class="rail-note"> + {xp >= g ? 'Done for today. ' : ''}Counts XP from every section. <a href="/profile#plan">Change pace</a> + </small> + </div> + ) +} + +/** `ai` shows the course's own stats and what's next; `site` (hub, profile) shows everything, by section. */ export default function Rail({ units, mode = 'ai' }: { units: UnitRef[]; mode?: 'ai' | 'site' }) { const p = useProgress() - const next = mode === 'ai' ? nextUnit(p, units) : null + if (mode === 'site') + return ( + <div class="stack" style={{ gap: '14px' }}> + <div class="card"> + <div class="panel-title"> + <span class="kicker">All sections</span> + </div> + <div class="stat-tiles"> + <Tile icon="flame" color="var(--streak)" n={streak(p)} label="day streak" /> + <Tile icon="bolt" color="var(--xp)" n={totalXp(p)} label="total XP" /> + <Tile icon="check" color="var(--ok)" n={xpToday(p)} label="XP today" /> + </div> + <div class="by-section"> + <a href="/leetcode" class="bs-row"> + <i style={{ background: SECTION_COLOR.leetcode }} /> + <b>LeetCode</b> + <small> + {totalXp(p, 'leetcode')} XP · {streak(p, 'leetcode')}-day streak · {solvedCount(p)} solved + </small> + </a> + <a href="/ai-engineer" class="bs-row"> + <i style={{ background: SECTION_COLOR.ai }} /> + <b>AI Engineer</b> + <small> + {totalXp(p, 'ai')} XP · {streak(p, 'ai')}-day streak · {crownCount(p)} crowns + </small> + </a> + </div> + </div> + <Goal p={p} /> + <div class="card"> + <div class="panel-title"> + <span class="kicker">This week</span> + <span class="kicker legend"> + <i style={{ background: SECTION_COLOR.leetcode }} /> LeetCode <i style={{ background: SECTION_COLOR.ai }} /> AI + </span> + </div> + <Week p={p} /> + </div> + </div> + ) + + const next = nextUnit(p, units) const due = dueCount(p) - const xp = xpToday(p) return ( <div class="stack" style={{ gap: '14px' }}> <div class="card"> <div class="panel-title"> - <span class="kicker">Today</span> - <span class="kicker"> - {xp}/{p.dailyGoal} XP - </span> + <span class="kicker">AI Engineer</span> + <span class="kicker">{xpToday(p, 'ai')} XP today</span> </div> <div class="stat-tiles"> - <div class="tile"> - <span class="ic" style={{ background: 'color-mix(in srgb, var(--streak) 16%, transparent)', color: 'var(--streak)' }}> - <Icon name="flame" size={16} /> - </span> - <b>{streak(p)}</b> - <small>day streak</small> - </div> - <div class="tile"> - <span class="ic" style={{ background: 'color-mix(in srgb, var(--xp) 18%, transparent)', color: 'var(--xp)' }}> - <Icon name="bolt" size={16} /> - </span> - <b>{totalXp(p)}</b> - <small>total XP</small> - </div> - <div class="tile"> - <span class="ic" style={{ background: 'var(--accent-soft)', color: 'var(--accent)' }}> - <Icon name="crown" size={16} /> - </span> - <b>{crownCount(p)}</b> - <small>crowns</small> - </div> - </div> - <div class="meter" style={{ marginTop: '14px' }}> - <i style={{ width: `${Math.min((xp / p.dailyGoal) * 100, 100)}%`, background: xp >= p.dailyGoal ? 'var(--ok)' : 'var(--accent)' }} /> + <Tile icon="flame" color="var(--streak)" n={streak(p, 'ai')} label="day streak" /> + <Tile icon="bolt" color="var(--xp)" n={totalXp(p, 'ai')} label="XP" /> + <Tile icon="crown" color="var(--accent)" n={crownCount(p)} label="crowns" /> </div> </div> {next && ( @@ -91,7 +151,6 @@ export default function Rail({ units, mode = 'ai' }: { units: UnitRef[]; mode?: <Icon name="chevron" /> </a> )} - {mode === 'ai' && ( <a href="/ai-engineer/practice" class="card row"> <span class="chip-icon" style={{ background: 'var(--accent-soft)', color: 'var(--accent)' }}> <Icon name="refresh" /> @@ -102,14 +161,7 @@ export default function Rail({ units, mode = 'ai' }: { units: UnitRef[]; mode?: </span> <Icon name="chevron" /> </a> - )} - <div class="card"> - <div class="panel-title"> - <span class="kicker">This week</span> - <span class="kicker">goal {p.dailyGoal}/day</span> - </div> - <Week p={p} /> - </div> + <Goal p={p} /> </div> ) } @@ -118,18 +170,18 @@ export function StatStrip() { const p = useProgress() return ( <div class="stat-strip"> - <span class="s" style={{ color: 'var(--streak)' }}> - <Icon name="flame" size={16} /> <span style={{ color: 'var(--ink)' }}>{streak(p)}</span> + <span class="s" style={{ color: 'var(--streak)' }} title="AI Engineer day streak"> + <Icon name="flame" size={16} /> <span style={{ color: 'var(--ink)' }}>{streak(p, 'ai')}</span> </span> - <span class="s" style={{ color: 'var(--xp)' }}> - <Icon name="bolt" size={16} /> <span style={{ color: 'var(--ink)' }}>{totalXp(p)}</span> + <span class="s" style={{ color: 'var(--xp)' }} title="AI Engineer XP"> + <Icon name="bolt" size={16} /> <span style={{ color: 'var(--ink)' }}>{totalXp(p, 'ai')}</span> </span> - <span class="s" style={{ color: 'var(--accent)' }}> + <span class="s" style={{ color: 'var(--accent)' }} title="Modules crowned"> <Icon name="crown" size={16} /> <span style={{ color: 'var(--ink)' }}>{crownCount(p)}</span> </span> - <span class="s"> - {xpToday(p)}/{p.dailyGoal} <small>XP today</small> - </span> + <a class="s" href="/profile#plan" title="Daily goal (all sections)"> + {xpToday(p)}/{dailyGoal(p)} <small>XP today</small> + </a> </div> ) } diff --git a/src/layouts/Base.astro b/src/layouts/Base.astro index fbe2c35..b0b824d 100644 --- a/src/layouts/Base.astro +++ b/src/layouts/Base.astro @@ -66,10 +66,12 @@ const current = sectionOf(section); <ThemeToggle /> </header> {current && <SectionNav section={current} variant="strip" />} - <main><slot /></main> + <div class="app-body"> + <main><slot /></main> + {hasRail && <aside class="app-rail" aria-label="Your progress"><slot name="rail" /></aside>} + </div> <SiteFooter /> </div> - {hasRail && <aside class="app-rail" aria-label="Your progress"><slot name="rail" /></aside>} </div> </body> )} diff --git a/src/layouts/Walkthrough.astro b/src/layouts/Walkthrough.astro index e5a5e3f..da79b6b 100644 --- a/src/layouts/Walkthrough.astro +++ b/src/layouts/Walkthrough.astro @@ -202,16 +202,34 @@ const lcUrl = (slug: string) => `https://leetcode.com/problems/${slug}/`; <div class="shell"> <nav class="pager" aria-label="Lesson navigation"> <a class="up" href="/leetcode"><span class="dir">Back to</span><span>All problems</span></a> + <button class="solve-btn" type="button" data-solve={p.slug} aria-pressed="false" hidden> + <span class="dir">Your progress</span><span data-solve-label>Mark as solved</span> + </button> </nav> </div> </Base> <script> import { initLangSwitch } from '../lib/i18n.js'; - import { touch } from '../lib/progress'; + import { get, subscribe, toggleChecked, touch } from '../lib/progress'; initLangSwitch(); // the hub's "jump back in" offers the last problem opened const title = document.querySelector('.wrap h1')?.textContent?.trim(); const sub = document.querySelector('.wrap header .eyebrow')?.textContent?.replace(/\s+/g, ' ').trim(); if (title) touch('leetcode', { url: location.pathname, title, sub: sub ?? 'LeetCode' }); + + // "Mark as solved": a tick on the problem list and LeetCode XP + const solve = document.querySelector<HTMLButtonElement>('[data-solve]'); + if (solve) { + const id = `leetcode:${solve.dataset.solve}`; + const paint = () => { + const on = !!get().checked[id]; + solve.setAttribute('aria-pressed', String(on)); + solve.querySelector('[data-solve-label]')!.textContent = on ? 'Solved ✓' : 'Mark as solved (+20 XP)'; + }; + solve.hidden = false; + solve.addEventListener('click', () => toggleChecked(id, 20, 'leetcode')); + paint(); + subscribe(paint); + } </script> diff --git a/src/lib/ai/course.ts b/src/lib/ai/course.ts index 1c3168d..b8323f3 100644 --- a/src/lib/ai/course.ts +++ b/src/lib/ai/course.ts @@ -242,3 +242,8 @@ export const units: UnitRef[] = tracks.flatMap((t) => ) export const trackColor = (trackId: string) => tracks.find((t) => t.id === trackId)?.color ?? 'indigo' + +/** Weeks a track takes at the course's own pace (~13.5 h/week): its modules' estimates, upper end of a range. */ +export const trackWeeks = (t: Track) => t.modules.reduce((a, m) => a + (Number(m.weeks?.split(/[–-]/).at(-1)) || 0), 0) +/** Upper end of a module's estimate, in course weeks, or 0 when it has none. */ +export const moduleWeeks = (m: Module) => Number(m.weeks?.split(/[–-]/).at(-1)) || 0 diff --git a/src/lib/ai/decorate.ts b/src/lib/ai/decorate.ts index 90fb2d2..359d25f 100644 --- a/src/lib/ai/decorate.ts +++ b/src/lib/ai/decorate.ts @@ -9,8 +9,9 @@ * [data-meter-of="id,id,…"] width set to that % * [data-crowns-of="mod,mod,…"] text set to "n/total" * [data-continue] link pointed at the first unfinished step - * [data-ai-track="t1"] visiting the page makes it the current track */ -import { get, subscribe, update } from '../progress' + * [data-ai-track="t1"] visiting the page makes it the current track + * [data-course-weeks="4"] text set to that estimate at your study pace */ +import { formatWeeks, get, subscribe, update, weeksAtPace } from '../progress' function paint() { const p = get() @@ -43,6 +44,10 @@ function paint() { const mods = e.dataset.crownsOf!.split(',').filter(Boolean) e.textContent = `${mods.filter((m) => p.crowns[m]).length}/${mods.length}` }) + document.querySelectorAll<HTMLElement>('[data-course-weeks]').forEach((e) => { + e.textContent = formatWeeks(weeksAtPace(Number(e.dataset.courseWeeks), p.pace)) + e.title = `At your pace. The course itself plans ${e.dataset.courseWeeks} week(s) at ~13.5 h a week.` + }) document.querySelectorAll<HTMLAnchorElement>('[data-continue]').forEach((a) => { if (!current) return void (a.hidden = true) a.hidden = false diff --git a/src/lib/progress.ts b/src/lib/progress.ts index 099c03e..0dd8de2 100644 --- a/src/lib/progress.ts +++ b/src/lib/progress.ts @@ -1,34 +1,50 @@ // Progress for the whole site, kept in localStorage. Every section reads and -// writes it through here, so XP, streak and daily goal are shared. A signed-in -// sync to the server will replace load/save below; nothing else needs to change. +// writes it through here. XP is recorded per section, so each section can show +// its own streak and total while the hub and the daily goal count all of it. +// A signed-in sync to the server will replace load/save below; nothing else +// needs to change. // // Item ids are namespaced by their section: AI Engineer units look like -// "t2-2.7/quiz", papers "paper:<id>", projects "project:<id>". +// "t2-2.7/quiz", papers "paper:<id>", projects "project:<id>", LeetCode +// problems marked solved "leetcode:<slug>". + +export type SectionId = 'leetcode' | 'ai' +export const SECTION_LABEL: Record<SectionId, string> = { leetcode: 'LeetCode', ai: 'AI Engineer' } + +/** How much time you plan to study. The course is written for ~13.5 hours a week. */ +export type Pace = 'casual' | 'regular' | 'serious' | 'intense' +export const PACES: Record<Pace, { label: string; hours: number; xp: number }> = { + casual: { label: 'Casual', hours: 3, xp: 10 }, + regular: { label: 'Regular', hours: 6, xp: 30 }, + serious: { label: 'Serious', hours: 12, xp: 50 }, + intense: { label: 'Intense', hours: 25, xp: 100 }, +} +export const COURSE_HOURS_PER_WEEK = 13.5 export type CardState = { box: number; due: string } /** The last thing opened in a section, for "jump back in" on the hub. */ export type Recent = { url: string; title: string; sub: string; at: number } export type Progress = { - dailyGoal: number - /** Whether the AI Engineer "where are you starting?" question was answered. */ + pace: Pace + /** Whether the AI Engineer plan (pace and starting track) has been chosen. */ aiOnboarded: boolean aiTrack: string - xpByDay: Record<string, number> + /** XP earned, per section, per day (YYYY-MM-DD). */ + xp: Partial<Record<SectionId, Record<string, number>>> done: Record<string, true> checked: Record<string, true> crowns: Record<string, true> quizBest: Record<string, number> cards: Record<string, CardState> - /** keyed by section id: 'leetcode', 'ai' */ - recent: Record<string, Recent> + recent: Partial<Record<SectionId, Recent>> } const KEY = 'learn-progress-v1' const EMPTY: Progress = { - dailyGoal: 30, + pace: 'regular', aiOnboarded: false, aiTrack: 't1', - xpByDay: {}, + xp: {}, done: {}, checked: {}, crowns: {}, @@ -37,10 +53,26 @@ const EMPTY: Progress = { recent: {}, } +const paceFromGoal = (goal: number): Pace => (goal <= 10 ? 'casual' : goal <= 30 ? 'regular' : goal <= 50 ? 'serious' : 'intense') + +/** Older saves and exports: one XP-per-day map (all AI Engineer), a daily XP goal, other key names. */ +function migrate(raw: Record<string, unknown>): Progress { + const r = { ...raw } as Record<string, any> + if (r.xpByDay && !r.xp) r.xp = { ai: r.xpByDay } + if (typeof r.dailyGoal === 'number' && !r.pace) r.pace = paceFromGoal(r.dailyGoal) + if ('startTrack' in r && !('aiTrack' in r)) r.aiTrack = r.startTrack + if ('onboarded' in r && !('aiOnboarded' in r)) r.aiOnboarded = r.onboarded + delete r.xpByDay + delete r.dailyGoal + delete r.startTrack + delete r.onboarded + return { ...EMPTY, ...r } +} + function load(): Progress { try { const s = localStorage.getItem(KEY) - if (s) return { ...EMPTY, ...JSON.parse(s) } + if (s) return migrate(JSON.parse(s)) } catch { /* storage unavailable: run in memory */ } @@ -82,28 +114,56 @@ if (typeof window !== 'undefined') export const today = (d = new Date()) => d.toLocaleDateString('en-CA') -export function addXp(n: number) { +// ───────── XP, streaks, goal ───────── + +export function addXp(n: number, section: SectionId = 'ai') { if (n <= 0) return const t = today() - update((p) => ({ ...p, xpByDay: { ...p.xpByDay, [t]: (p.xpByDay[t] || 0) + n } })) + update((p) => { + const days = { ...(p.xp[section] ?? {}) } + days[t] = (days[t] || 0) + n + return { ...p, xp: { ...p.xp, [section]: days } } + }) } -export const totalXp = (p: Progress) => Object.values(p.xpByDay).reduce((a, b) => a + b, 0) -export const xpToday = (p: Progress) => p.xpByDay[today()] || 0 -export const crownCount = (p: Progress) => Object.keys(p.crowns).length +/** XP on one day, for one section or (no section) all of them. */ +export function dayXp(p: Progress, day: string, section?: SectionId) { + const maps = section ? [p.xp[section] ?? {}] : Object.values(p.xp) + return maps.reduce((a, m) => a + (m?.[day] || 0), 0) +} +export function totalXp(p: Progress, section?: SectionId) { + const maps = section ? [p.xp[section] ?? {}] : Object.values(p.xp) + return maps.reduce((a, m) => a + Object.values(m ?? {}).reduce((x, y) => x + y, 0), 0) +} +export const xpToday = (p: Progress, section?: SectionId) => dayXp(p, today(), section) -export function streak(p: Progress) { +/** Days in a row with any XP (in that section, or anywhere), counting today if it has some. */ +export function streak(p: Progress, section?: SectionId) { let n = 0 const d = new Date() - if (!p.xpByDay[today(d)]) d.setDate(d.getDate() - 1) - while (p.xpByDay[today(d)]) { + if (!dayXp(p, today(d), section)) d.setDate(d.getDate() - 1) + while (dayXp(p, today(d), section)) { n++ d.setDate(d.getDate() - 1) } return n } -export function toggleChecked(id: string, xp: number) { +export const dailyGoal = (p: Progress) => PACES[p.pace].xp +export const crownCount = (p: Progress) => Object.keys(p.crowns).length +export const solvedCount = (p: Progress) => Object.keys(p.checked).filter((k) => k.startsWith('leetcode:')).length + +/** Weeks to finish work written for COURSE_HOURS_PER_WEEK, at the chosen pace. */ +export const weeksAtPace = (courseWeeks: number, pace: Pace) => (courseWeeks * COURSE_HOURS_PER_WEEK) / PACES[pace].hours +export function formatWeeks(w: number) { + if (w < 0.75) return `~${Math.max(1, Math.round(w * 7))} days` + const r = w < 10 ? Math.round(w * 2) / 2 : Math.round(w) + return `~${r} wk${r === 1 ? '' : 's'}` +} + +// ───────── items ───────── + +export function toggleChecked(id: string, xp: number, section: SectionId = 'ai') { const on = !get().checked[id] update((p) => { const checked = { ...p.checked } @@ -111,18 +171,18 @@ export function toggleChecked(id: string, xp: number) { else delete checked[id] return { ...p, checked } }) - if (on) addXp(xp) + if (on) addXp(xp, section) return on } -export function markDone(unitId: string, xp = 0) { +export function markDone(unitId: string, xp = 0, section: SectionId = 'ai') { const first = !get().done[unitId] update((p) => ({ ...p, done: { ...p.done, [unitId]: true } })) - if (first) addXp(xp) + if (first) addXp(xp, section) } /** Remember the last thing opened in a section. */ -export function touch(section: string, item: Omit<Recent, 'at'>) { +export function touch(section: SectionId, item: Omit<Recent, 'at'>) { update((p) => ({ ...p, recent: { ...p.recent, [section]: { ...item, at: Date.now() } } })) } @@ -130,11 +190,8 @@ export const exportProgress = () => JSON.stringify(get(), null, 2) export function importProgress(json: string) { const parsed = JSON.parse(json) - if (typeof parsed !== 'object' || !parsed || !parsed.xpByDay) throw new Error('Not a progress file') - // files exported by the first standalone AI Engineer site used these names - if ('startTrack' in parsed && !('aiTrack' in parsed)) parsed.aiTrack = parsed.startTrack - if ('onboarded' in parsed && !('aiOnboarded' in parsed)) parsed.aiOnboarded = parsed.onboarded - update(() => ({ ...EMPTY, ...parsed })) + if (typeof parsed !== 'object' || !parsed || !(parsed.xp || parsed.xpByDay)) throw new Error('Not a progress file') + update(() => migrate(parsed)) } export const resetProgress = () => update(() => ({ ...EMPTY })) @@ -149,5 +206,5 @@ export function reviewCard(id: string, knew: boolean) { d.setDate(d.getDate() + INTERVALS[box]) return { ...p, cards: { ...p.cards, [id]: { box, due: today(d) } } } }) - addXp(knew ? 2 : 1) + addXp(knew ? 2 : 1, 'ai') } diff --git a/src/pages/ai-engineer/[track].astro b/src/pages/ai-engineer/[track].astro index ce6b3d5..161dc9e 100644 --- a/src/pages/ai-engineer/[track].astro +++ b/src/pages/ai-engineer/[track].astro @@ -2,7 +2,7 @@ import AiLayout from '../../layouts/AiLayout.astro'; import Stepper from '../../components/ai/Stepper.astro'; import Icon from '../../components/Icon.astro'; -import { moduleUrl, tracks, unitUrl, unitKinds, type Track } from '../../lib/ai/course'; +import { moduleUrl, moduleWeeks, tracks, trackWeeks, unitUrl, unitKinds, type Track } from '../../lib/ai/course'; export function getStaticPaths() { return tracks.map((t) => ({ params: { track: t.slug }, props: { track: t } })); @@ -13,7 +13,7 @@ const first = track.modules[0]; <AiLayout title={`${track.short}: ${track.title}`} description={`${track.title}: ${track.subtitle}`}> <div class={`track-hero tc-${track.color}`} data-ai-track={track.id}> <div> - <div class="kicker" style="color:var(--ct)">{track.short} · {track.modules.length} modules</div> + <div class="kicker" style="color:var(--ct)">{track.short} · {track.modules.length} modules{trackWeeks(track) > 0 && <> · <span data-course-weeks={trackWeeks(track)}>{trackWeeks(track)} wks</span> at your pace</>}</div> <h1>{track.title}</h1> <p>{track.subtitle}</p> </div> @@ -23,7 +23,7 @@ const first = track.modules[0]; </div> <ol class={`timeline tc-${track.color}`}> {track.modules.map((m) => { - const meta = [m.weeks && `${m.weeks} wk${m.weeks === '1' ? '' : 's'}`, m.resources.length && `${m.resources.length} resources`, m.build.length && `${m.build.length} builds`].filter(Boolean).join(' · '); + const meta = [m.resources.length && `${m.resources.length} resources`, m.build.length && `${m.build.length} builds`].filter(Boolean).join(' · '); const blurb = m.why || m.concepts.slice(0, 6).join(' · '); return ( <li class="mod" id={m.slug} data-mod={m.id}> @@ -34,7 +34,7 @@ const first = track.modules[0]; <div class="mod-head"> <div style="min-width:0"> <div class="kicker"> - {m.label}{meta && ` · ${meta}`} + {m.label}{moduleWeeks(m) > 0 && <> · <span data-course-weeks={moduleWeeks(m)}>{m.weeks} wks</span></>}{meta && ` · ${meta}`} {m.star && <span class="badge">★ key</span>} </div> <h2 id={`h-${m.slug}`}><a href={moduleUrl(track, m)} style="color:inherit;text-decoration:none">{m.title}</a></h2> diff --git a/src/pages/ai-engineer/[track]/[module].astro b/src/pages/ai-engineer/[track]/[module].astro index 15c8864..94d19e9 100644 --- a/src/pages/ai-engineer/[track]/[module].astro +++ b/src/pages/ai-engineer/[track]/[module].astro @@ -2,7 +2,7 @@ import AiLayout from '../../../layouts/AiLayout.astro'; import Stepper from '../../../components/ai/Stepper.astro'; import Icon from '../../../components/Icon.astro'; -import { moduleUrl, tracks, trackUrl, type Module, type Track } from '../../../lib/ai/course'; +import { moduleUrl, moduleWeeks, tracks, trackUrl, type Module, type Track } from '../../../lib/ai/course'; export function getStaticPaths() { return tracks.flatMap((t) => @@ -15,7 +15,7 @@ const { track, module: m, prev, next } = Astro.props as { track: Track; module: <a href={trackUrl(track)} class="optional-toggle" style="margin-top:0"><Icon name="back" size={16} /> {track.short}: {track.title}</a> <div class={`tc-${track.color}`} data-ai-track={track.id}> <div class="guide-hero"> - <div class="kicker">{track.short} · {m.label}{m.weeks && ` · ${m.weeks} wk${m.weeks === '1' ? '' : 's'}`}</div> + <div class="kicker">{track.short} · {m.label}{moduleWeeks(m) > 0 && <> · <span data-course-weeks={moduleWeeks(m)}>{m.weeks} wks</span> at your pace</>}</div> <h1>{m.title}</h1> </div> <div class="card" style="padding:4px 18px 16px;margin-bottom:26px" data-mod={m.id}> diff --git a/src/pages/ai-engineer/index.astro b/src/pages/ai-engineer/index.astro index d115498..86a84e3 100644 --- a/src/pages/ai-engineer/index.astro +++ b/src/pages/ai-engineer/index.astro @@ -3,29 +3,30 @@ import AiLayout from '../../layouts/AiLayout.astro'; import TrackTabs from '../../components/ai/TrackTabs.astro'; import Onboard from '../../components/ai/Onboard'; import Icon from '../../components/Icon.astro'; -import { tracks, trackUrl, units } from '../../lib/ai/course'; +import { tracks, trackUrl, trackWeeks, units } from '../../lib/ai/course'; -const weeks = tracks.map((t) => t.modules.reduce((a, m) => a + (Number(m.weeks?.split(/[–-]/).at(-1)) || 0), 0)); +const plans = tracks.map((t) => ({ id: t.id, url: trackUrl(t), short: t.short, title: t.title, color: t.color, weeks: trackWeeks(t) })); --- <AiLayout title="AI Engineer" description="A self-study path from backend engineer to AI research engineer: three tracks, a math track, quizzes, flashcards and portfolio projects."> - <div class="kicker">AI Engineer</div> - <h1 class="page-h">From backend engineer to research engineer</h1> + <div class="track-hero" style="margin-bottom:14px"> + <div> + <div class="kicker">AI Engineer</div> + <h1 class="page-h">From backend engineer to research engineer</h1> + </div> + <a class="btn" href={units[0].url} data-continue hidden><Icon name="play" size={14} fill="currentColor" /> Continue: <span data-continue-label></span></a> + </div> <p class="page-sub"> Three tracks, each one a job you can be hired for, with math running alongside. Every module has five steps: concepts, resources, hands-on builds, a quiz and a checkpoint that earns a crown. </p> - <Onboard client:only="preact" /> - <div class="track-hero"> - <div><div class="kicker">Pick up where you left off</div></div> - <a class="btn" href={units[0].url} data-continue hidden><Icon name="play" size={14} fill="currentColor" /> Continue: <span data-continue-label></span></a> - </div> + <Onboard client:only="preact" tracks={plans} /> <TrackTabs /> - <div class="section-title">The tracks</div> + <h2 class="section-title">What each track covers</h2> <div class="grid-cards"> - {tracks.map((t, i) => ( + {tracks.map((t) => ( <a class={`card tc-${t.color}`} href={trackUrl(t)} style="border-top:4px solid var(--c)"> - <div class="kicker" style="color:var(--ct)">{t.short}{weeks[i] ? ` · ~${weeks[i]} weeks` : ''}</div> - <h2 style="font-size:19px;margin:6px 0">{t.title}</h2> + <div class="kicker" style="color:var(--ct)">{t.short}{trackWeeks(t) > 0 && <> · <span data-course-weeks={trackWeeks(t)}>{trackWeeks(t)} wks</span> at your pace</>}</div> + <h3 style="font-size:19px;margin:6px 0">{t.title}</h3> <p class="page-sub" style="margin:0 0 10px">{t.subtitle}</p> <ol style="margin:0;padding-left:18px;color:var(--ink-2);font-size:14px;line-height:1.7"> {t.modules.map((m) => <li>{m.title}</li>)} @@ -33,7 +34,7 @@ const weeks = tracks.map((t) => t.modules.reduce((a, m) => a + (Number(m.weeks?. </a> ))} </div> - {/* the steps, hidden, so decorate.ts can find the first unfinished one for Continue */} + {/* the steps, hidden, so the progress script can find the first unfinished one for Continue */} <div hidden> {units.map((u) => <a href={u.url} data-unit={u.id} data-label={u.label} data-kind-label={u.label} data-mod-label={u.moduleLabel}></a>)} </div> diff --git a/src/pages/leetcode/index.astro b/src/pages/leetcode/index.astro index 9edc331..775642a 100644 --- a/src/pages/leetcode/index.astro +++ b/src/pages/leetcode/index.astro @@ -2,9 +2,7 @@ import Base from '../../layouts/Base.astro'; import { SITE_NAME } from '../../data/site'; import { asOf } from '../../data/problems-meta.json'; -import { all, groups, haystack, leetcodeUrl, PAGE as WALKTHROUGH } from '../../data/catalog'; - -const worked = all.filter((p) => WALKTHROUGH[p.id]).length; +import { all, groups, leetcodeUrl, PAGE as WALKTHROUGH } from '../../data/catalog'; --- <Base section="leetcode" @@ -21,40 +19,17 @@ const worked = all.filter((p) => WALKTHROUGH[p.id]).length; </p> </div> - <div class="plist"> - <aside class="cats"> - <nav aria-label="Patterns"> - <a class="cat" href="#top" data-cat="" aria-current="true"> - <span>All problems</span><span class="cat-n">{all.length}</span> - </a> - {groups.map((g) => ( - <a class="cat" href={`#${g.id}`} data-cat={g.id}> - <span>{g.name}</span><span class="cat-n">{g.rows.length}</span> - </a> - ))} - </nav> - </aside> - - <div class="plist-main" id="top"> - <form class="filters" role="search" data-filters hidden> - <label class="search"> - <svg viewBox="0 0 16 16" aria-hidden="true"><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M10.5 10.5 14 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg> - <input type="search" name="q" placeholder="Search by name, number or pattern" aria-label="Search problems" autocomplete="off" spellcheck="false"> - </label> - <select name="d" aria-label="Difficulty"> - <option value="">All difficulties</option> - <option value="easy">Easy</option> - <option value="medium">Medium</option> - <option value="hard">Hard</option> - </select> - <label class="only"> - <input type="checkbox" name="solved" value="1"> - <span>With a solution</span> - </label> - </form> - <p class="plist-count" aria-live="polite" data-summary> - {all.length} problems · {worked} with an interactive solution - </p> + <div class="plist-main" id="top"> + <div class="filters" role="group" aria-label="Difficulty" data-filters hidden> + <div class="seg-d"> + <button type="button" data-d="" aria-pressed="true">All</button> + <button type="button" data-d="easy" aria-pressed="false">Easy</button> + <button type="button" data-d="medium" aria-pressed="false">Medium</button> + <button type="button" data-d="hard" aria-pressed="false">Hard</button> + </div> + <span class="plist-count" aria-live="polite" data-summary>{all.length} problems</span> + <span class="plist-solved" data-solved-count hidden></span> + </div> {groups.map((g) => ( <section class="cat-sec" id={g.id} data-sec={g.id}> @@ -67,10 +42,9 @@ const worked = all.filter((p) => WALKTHROUGH[p.id]).length; <li class={WALKTHROUGH[p.id] ? 'prow has-page' : 'prow'} data-d={p.difficulty.toLowerCase()} - data-text={haystack(p)} - data-solved={WALKTHROUGH[p.id] ? '1' : undefined} + data-slug={p.slug} > - <span class="pnum">{p.id}</span> + <span class="pnum"><span class="ptick" aria-hidden="true">✓</span><span class="pid">{p.id}</span></span> <div class="pmain"> {WALKTHROUGH[p.id] ? <a class="ptitle" href={WALKTHROUGH[p.id]}>{p.title}</a> @@ -90,101 +64,70 @@ const worked = all.filter((p) => WALKTHROUGH[p.id]).length; </section> ))} - <p class="plist-empty" data-empty hidden> - No problems match. <button type="button" data-clear>Clear the filters</button> - </p> <p class="plist-foot">Difficulty, tags and acceptance rates from LeetCode, as of {asOf}.</p> - </div> </div> </div> </Base> <script> - // Search, difficulty and pattern filters. Everything is in the markup - // already, so without JavaScript the full list shows and the pattern links - // scroll to their section; this only hides rows. State lives in the URL - // (?q=&d=&solved=1#pattern) so a filtered list can be shared. - const form = document.querySelector<HTMLFormElement>('[data-filters]')!; - const q = form.elements.namedItem('q') as HTMLInputElement; - const d = form.elements.namedItem('d') as HTMLSelectElement; - const solved = form.elements.namedItem('solved') as HTMLInputElement; - const cats = [...document.querySelectorAll<HTMLAnchorElement>('.cat')]; + // The difficulty filter, the pattern highlight in the section menu, and the + // ticks on problems marked solved. Everything is in the markup already, so + // without JavaScript the full list shows and the pattern links still jump. + // ⌘K is the search. The difficulty lives in the URL (?d=) so it can be shared. + import { get, subscribe } from '../../lib/progress'; + + const bar = document.querySelector<HTMLElement>('[data-filters]')!; + const buttons = [...bar.querySelectorAll<HTMLButtonElement>('[data-d]')]; const secs = [...document.querySelectorAll<HTMLElement>('[data-sec]')]; const summary = document.querySelector('[data-summary]')!; - const empty = document.querySelector<HTMLElement>('[data-empty]')!; - let cat = ''; - - const params = new URLSearchParams(location.search); - q.value = params.get('q') ?? ''; - d.value = params.get('d') ?? ''; - solved.checked = params.get('solved') === '1'; - const fromHash = location.hash.slice(1); - if (secs.some((s) => s.dataset.sec === fromHash)) cat = fromHash; - form.hidden = false; - const plural = (n: number) => `${n} ${n === 1 ? 'problem' : 'problems'}`; + let d = new URLSearchParams(location.search).get('d') ?? ''; + bar.hidden = false; function apply() { - const terms = q.value.toLowerCase().split(/\s+/).filter(Boolean); - const counts: Record<string, number> = {}; - let shown = 0, shownSolved = 0; + let shown = 0; for (const sec of secs) { let n = 0; for (const row of sec.querySelectorAll<HTMLElement>('.prow')) { - const hit = (!d.value || row.dataset.d === d.value) - && (!solved.checked || row.dataset.solved) - && terms.every((t) => row.dataset.text!.includes(t)); - row.hidden = !hit; - if (hit) { n++; if (row.dataset.solved) shownSolved++; } + row.hidden = !!d && row.dataset.d !== d; + if (!row.hidden) n++; } - counts[sec.dataset.sec!] = n; - const inCat = !cat || sec.dataset.sec === cat; - sec.hidden = !inCat || n === 0; + sec.hidden = n === 0; sec.querySelector('[data-sec-count]')!.textContent = plural(n); - if (inCat) shown += n; - } - // Sidebar counts follow the search and difficulty, not the chosen pattern. - let total = 0; - for (const a of cats) { - const id = a.dataset.cat!; - const n = id ? counts[id] : 0; - total += n; - if (id) { - a.querySelector('.cat-n')!.textContent = String(n); - a.classList.toggle('none', n === 0); - } - a.setAttribute('aria-current', String(id === cat)); + shown += n; } - cats[0].querySelector('.cat-n')!.textContent = String(total); - summary.textContent = shown - ? `${plural(shown)} · ${shownSolved} with an interactive solution` - : 'No problems match'; - empty.hidden = shown > 0; - - const next = new URLSearchParams(); - if (q.value) next.set('q', q.value); - if (d.value) next.set('d', d.value); - if (solved.checked) next.set('solved', '1'); - const url = `${location.pathname}${next.size ? `?${next}` : ''}${cat ? `#${cat}` : ''}`; - // Safari throws once a page calls replaceState too often (a held key in - // the search box); the filter has already applied, so only the URL lags. + for (const b of buttons) b.setAttribute('aria-pressed', String(b.dataset.d === d)); + summary.textContent = plural(shown); + const url = `${location.pathname}${d ? `?d=${d}` : ''}${location.hash}`; try { history.replaceState(null, '', url); } catch { /* rate-limited */ } } - - form.addEventListener('input', apply); - form.addEventListener('submit', (e) => e.preventDefault()); - for (const a of cats) { - a.addEventListener('click', (e) => { - e.preventDefault(); - cat = a.dataset.cat!; - apply(); - document.getElementById('top')!.scrollIntoView({ block: 'start' }); - }); - } - document.querySelector('[data-clear]')!.addEventListener('click', () => { - q.value = ''; d.value = ''; solved.checked = false; cat = ''; - apply(); - q.focus(); - }); + for (const b of buttons) b.addEventListener('click', () => { d = b.dataset.d!; apply(); }); apply(); + + // solved ticks + const solved = () => { + const p = get(); + let n = 0; + for (const row of document.querySelectorAll<HTMLElement>('.prow[data-slug]')) { + const on = !!p.checked[`leetcode:${row.dataset.slug}`]; + row.classList.toggle('solved', on); + if (on) n++; + } + const c = document.querySelector<HTMLElement>('[data-solved-count]')!; + c.hidden = !n; + c.textContent = `${n} solved`; + }; + solved(); + subscribe(solved); + + // highlight the pattern being read in the section menu + const links = new Map([...document.querySelectorAll<HTMLAnchorElement>('.section-nav a[href^="/leetcode#"]')].map((a) => [a.hash.slice(1), a])); + const spy = new IntersectionObserver((entries) => { + for (const e of entries) { + if (!e.isIntersecting) continue; + links.forEach((a) => a.removeAttribute('aria-current')); + links.get((e.target as HTMLElement).dataset.sec!)?.setAttribute('aria-current', 'location'); + } + }, { rootMargin: '-80px 0px -70% 0px' }); + secs.forEach((s) => spy.observe(s)); </script> diff --git a/src/pages/profile.astro b/src/pages/profile.astro index 392c0c9..029faff 100644 --- a/src/pages/profile.astro +++ b/src/pages/profile.astro @@ -1,16 +1,18 @@ --- import AiLayout from '../layouts/AiLayout.astro'; import Profile from '../components/ai/Profile'; -import { tracks, trackUrl, units } from '../lib/ai/course'; +import { tracks, trackUrl, trackWeeks, units } from '../lib/ai/course'; +import { all } from '../data/catalog'; const summary = tracks.map((t) => ({ id: t.id, url: trackUrl(t), short: t.short, title: t.title, color: t.color, units: units.filter((u) => u.track === t.id).map((u) => u.id), modules: t.modules.map((m) => m.id), + weeks: trackWeeks(t), })); --- <AiLayout section="hub" title="Profile" description="Your progress across the site." where="Profile"> <div class="kicker">Profile</div> <h1 class="page-h">Your progress</h1> - <p class="page-sub">XP and streaks count across the whole site.</p> - <Profile client:only="preact" tracks={summary} /> + <p class="page-sub">Your streaks and XP, overall and for each section, and the study plan that sets your daily goal.</p> + <Profile client:only="preact" tracks={summary} problems={all.length} /> </AiLayout> diff --git a/src/styles/ai.css b/src/styles/ai.css index 617f840..9395144 100644 --- a/src/styles/ai.css +++ b/src/styles/ai.css @@ -314,3 +314,34 @@ a.card.upnext{color:var(--on-accent)} .jbi-title{font-family:var(--display);font-size:18px;font-weight:600;margin-top:6px} .jbi-sub{color:var(--muted);font-size:13px} .jbi-other{color:var(--ink-2);font-weight:600;font-size:13px} + +/* ───────── rail: sections, goal, stacked week ───────── */ +.week .stack-bar{flex:1;width:100%;max-width:26px;display:flex;flex-direction:column-reverse;justify-content:flex-start;align-items:stretch;gap:2px} +.week .stack-bar i{width:100%;max-width:none;border-radius:4px;min-height:3px} +.week .stack-bar i.empty{height:4px;background:var(--bg-2)} +.week .today span:last-child{color:var(--ink);font-weight:700} +.by-section{display:flex;flex-direction:column;gap:6px;margin-top:14px} +.bs-row{display:grid;grid-template-columns:10px 1fr;column-gap:10px;align-items:center;padding:8px 10px;border-radius:10px;background:var(--bg-2);text-decoration:none;color:var(--ink)} +.bs-row i{width:10px;height:10px;border-radius:3px;grid-row:span 2} +.bs-row b{font-size:13.5px} +.bs-row small{color:var(--muted);font-size:12px} +.rail-note{display:block;margin-top:10px;color:var(--muted);font-size:12px;line-height:1.5} +.rail-note a{color:var(--accent);font-weight:600} +.legend{display:inline-flex;align-items:center;gap:5px} +.legend i{width:8px;height:8px;border-radius:2px;display:inline-block} +a.s{text-decoration:none;color:var(--ink)} + +/* ───────── study plan ───────── */ +.onb-h{font-size:22px;margin:6px 0 4px} +.pace-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(170px,100%),1fr));gap:10px;margin-top:14px} +.pace{display:flex;flex-direction:column;gap:2px;text-align:left;background:var(--card);border:1.5px solid var(--line);border-radius:14px;padding:12px 14px;box-shadow:0 3px 0 var(--line);font:inherit;color:var(--ink);cursor:pointer} +.pace:hover{border-color:var(--accent)} +.pace.on{border-color:var(--accent);background:var(--accent-soft);box-shadow:0 3px 0 var(--accent)} +.pace b{font-size:15px} +.pace .pace-h{font-family:var(--display);font-size:20px;font-weight:700} +.pace small{color:var(--muted);font-size:12px} +.plan-card{display:flex;align-items:center;gap:16px;border-left:4px solid var(--c);margin-bottom:24px;flex-wrap:wrap} +.plan-main{flex:1;min-width:240px;display:flex;flex-direction:column;gap:2px} +.plan-title{font-family:var(--display);font-size:18px;margin-top:4px} +.plan-main small{color:var(--muted);line-height:1.5} +.linkish{background:none;border:0;padding:0;font:inherit;color:var(--accent);font-weight:600;cursor:pointer;text-decoration:underline} diff --git a/src/styles/app.css b/src/styles/app.css index f7db953..af7645b 100644 --- a/src/styles/app.css +++ b/src/styles/app.css @@ -5,18 +5,21 @@ and the profile have none. The page column is a sticky 56px top bar, the page and the footer; lesson CSS offsets its sticky parts by that 56px. - ≥1440px all four columns (the progress rail only on pages that have one) + ≥1440px all of it (the progress rail only on pages that have one; it sits + under the top bar, and the footer runs under page and rail) <1440px the progress rail is hidden; AI pages show a stat strip instead <1024px the section sidebar becomes a strip of links under the top bar <720px the section rail becomes a bottom tab bar */ .app{display:grid;grid-template-columns:68px minmax(0,1fr);min-height:100vh} .app.has-nav{grid-template-columns:68px 244px minmax(0,1fr)} -.app.has-rail{grid-template-columns:68px minmax(0,1fr) 340px} -.app.has-nav.has-rail{grid-template-columns:68px 244px minmax(0,1fr) 340px} :root[data-nav="collapsed"] .app.has-nav{grid-template-columns:68px minmax(0,1fr)} -:root[data-nav="collapsed"] .app.has-nav.has-rail{grid-template-columns:68px minmax(0,1fr) 340px} :root[data-nav="collapsed"] .section-nav{display:none} +/* the page column: top bar, then the page beside the progress rail, then the + footer under both, so the bar and footer run the full width */ .app-main{min-width:0;display:flex;flex-direction:column} +.app-body{flex:1;display:grid;grid-template-columns:minmax(0,1fr)} +.app.has-rail .app-body{grid-template-columns:minmax(0,1fr) 340px} +.app-body > main{min-width:0} /* ---------- section rail ---------- */ .app-rail-nav{ @@ -103,27 +106,23 @@ .app-where{flex:1;min-width:0;font-family:var(--mono);font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:var(--ink-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} /* ---------- progress rail ---------- */ -.app-rail{padding:24px 24px 32px 0;position:sticky;top:0;align-self:start;max-height:100vh;overflow-y:auto;scrollbar-width:thin} +.app-rail{padding:28px 24px 32px 0;position:sticky;top:56px;align-self:start;max-height:calc(100vh - 56px);overflow-y:auto;scrollbar-width:thin} /* ---------- bare pages (lesson steps) ---------- */ body.bare{min-height:100vh} /* ---------- responsive ---------- */ @media (max-width:1439px){ - .app.has-rail{grid-template-columns:68px minmax(0,1fr)} - .app.has-nav.has-rail{grid-template-columns:68px 244px minmax(0,1fr)} - :root[data-nav="collapsed"] .app.has-nav.has-rail{grid-template-columns:68px minmax(0,1fr)} + .app.has-rail .app-body{grid-template-columns:minmax(0,1fr)} .app-rail{display:none} } @media (max-width:1023px){ - .app,.app.has-nav,.app.has-rail,.app.has-nav.has-rail, - :root[data-nav="collapsed"] .app.has-nav,:root[data-nav="collapsed"] .app.has-nav.has-rail{grid-template-columns:68px minmax(0,1fr)} + .app,.app.has-nav,:root[data-nav="collapsed"] .app.has-nav{grid-template-columns:68px minmax(0,1fr)} .section-nav,[data-collapse]{display:none} .section-strip{display:flex} } @media (max-width:719px){ - .app,.app.has-nav,.app.has-rail,.app.has-nav.has-rail, - :root[data-nav="collapsed"] .app.has-nav,:root[data-nav="collapsed"] .app.has-nav.has-rail{display:block} + .app,.app.has-nav,:root[data-nav="collapsed"] .app.has-nav{display:block} .app-main{min-height:100vh;padding-bottom:64px} .app-rail-nav{ position:fixed;inset:auto 0 0 0;height:auto;flex-direction:row;justify-content:space-around;gap:0; diff --git a/src/styles/site.css b/src/styles/site.css index 05ad447..0723fac 100644 --- a/src/styles/site.css +++ b/src/styles/site.css @@ -87,35 +87,19 @@ html:has(.kdlg[open]){overflow:hidden} .crumbs a:hover{color:var(--accent)} /* ---------- the problem list ---------- */ -/* A pattern sidebar beside the list; on a narrow screen it becomes a row of - chips above it. */ -.plist{display:grid;grid-template-columns:210px minmax(0,1fr);gap:28px;align-items:start;padding-bottom:56px} -.cats{position:sticky;top:calc(56px + 18px);max-height:calc(100vh - 56px - 36px);overflow-y:auto; - background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:8px} -.cats nav{display:flex;flex-direction:column;gap:1px} -.cat{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:7px 10px;border-radius:7px; - color:var(--ink-2);text-decoration:none;font-size:13.5px} -.cat:hover{background:var(--sunk);color:var(--ink)} -.cat[aria-current="true"]{background:var(--accent-soft);color:var(--accent);font-weight:600} -.cat:first-child{margin-bottom:6px} -.cat-n{font-family:var(--mono);font-size:11px;color:var(--ink-3);font-variant-numeric:tabular-nums} -.cat[aria-current="true"] .cat-n{color:var(--accent)} -.cat.none{opacity:.45} - -.plist-main{min-width:0;scroll-margin-top:calc(56px + 18px)} -.filters{display:flex;flex-wrap:wrap;gap:10px;margin-bottom:10px} -.filters .search{flex:1 1 260px;display:flex;align-items:center;gap:8px;padding:0 12px; - background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);color:var(--ink-3)} -.filters .search:focus-within{border-color:var(--accent)} -.filters .search svg{width:15px;height:15px;flex:none} -.filters input[type=search]{flex:1;min-width:0;border:0;background:none;color:var(--ink);font:inherit;font-size:14px;padding:10px 0;outline:none} -.filters select{font:inherit;font-size:13.5px;color:var(--ink);background:var(--surface);border:1px solid var(--line); - border-radius:var(--radius);padding:9px 12px;cursor:pointer} -.filters select:focus-visible,.filters .only:focus-within{outline:2px solid var(--accent);outline-offset:1px} -.filters .only{display:flex;align-items:center;gap:7px;font-size:13.5px;color:var(--ink-2);cursor:pointer; - background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:0 12px} -.filters .only input{accent-color:var(--accent);margin:0} -.plist-count{font-size:12.5px;color:var(--ink-3);margin:0 0 22px} +/* Patterns are in the section menu (which highlights the one being read) and + ⌘K is the search, so the page is just the list and a difficulty filter. */ +.plist-main{min-width:0;padding-bottom:56px} +.filters{display:flex;flex-wrap:wrap;align-items:center;gap:10px 16px;margin-bottom:22px} +.seg-d{display:inline-flex;background:var(--sunk);border-radius:10px;padding:3px;gap:2px} +.seg-d button{font:inherit;font-size:13px;font-weight:600;color:var(--ink-2);background:none;border:0;border-radius:8px;padding:6px 14px;cursor:pointer} +.seg-d button[aria-pressed="true"]{background:var(--surface);color:var(--ink);box-shadow:0 1px 3px rgba(0,0,0,.1)} +.plist-count,.plist-solved{font-family:var(--mono);font-size:12px;color:var(--ink-3)} +.plist-solved{color:var(--up)} +.cat-sec{scroll-margin-top:76px} +.ptick{display:none;color:var(--up);font-weight:700;margin-right:4px} +.prow.solved .ptick{display:inline} +.prow.solved{border-color:color-mix(in srgb,var(--up) 40%,var(--line))} .cat-sec{margin-bottom:34px} .cat-sec header{display:flex;align-items:baseline;justify-content:space-between;gap:12px; @@ -145,23 +129,15 @@ a.ptitle::after{content:"";position:absolute;inset:0;border-radius:inherit} .prow .diff{justify-self:center} .prate{font-family:var(--mono);font-size:12px;color:var(--ink-2);text-align:right;font-variant-numeric:tabular-nums} .plist-foot{font-size:12.5px;color:var(--ink-3);margin-top:8px} -.plist-empty{color:var(--ink-2);font-size:14px;padding:24px 0} -.plist-empty button{font:inherit;color:var(--accent);background:none;border:0;padding:0;cursor:pointer;text-decoration:underline} @media (max-width:980px){ .ptags{display:none} .prow{grid-template-columns:3.2em minmax(0,1fr) 4.6em 3.6em} } @media (max-width:760px){ - .plist{grid-template-columns:minmax(0,1fr);gap:16px} - .cats{position:static;max-height:none;overflow:visible;background:none;border:0;padding:0} - .cats nav{flex-direction:row;gap:6px;overflow-x:auto;scrollbar-width:none} - .cats nav::-webkit-scrollbar{display:none} - .cat{flex:none;border:1px solid var(--line);background:var(--surface);border-radius:999px;padding:5px 11px;font-size:12.5px} - .cat:first-child{margin-bottom:0} - .cat.none{display:none} .prow{grid-template-columns:minmax(0,1fr) auto;gap:10px;padding:10px 12px} .prow .pnum,.prow .prate{display:none} + .prow.solved .ptitle::after{content:" ✓";color:var(--up)} } .diff{ @@ -182,6 +158,13 @@ a.ptitle::after{content:"";position:absolute;inset:0;border-radius:inherit} .pager a:hover{border-color:var(--accent);color:var(--accent)} .pager .dir{font-family:var(--mono);font-size:10.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--ink-3)} .pager .up .dir::before{content:"\2190\00a0"} +.solve-btn{ + display:flex;flex-direction:column;align-items:flex-end;gap:3px;font:inherit;cursor:pointer; + border:1px solid var(--line);border-radius:var(--radius);padding:11px 15px;background:var(--surface);color:var(--ink); +} +.solve-btn:hover{border-color:var(--up)} +.solve-btn[aria-pressed="true"]{background:var(--up-soft);border-color:var(--up);color:var(--up);font-weight:600} +.solve-btn .dir{font-family:var(--mono);font-size:10.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--ink-3)} /* ---------- footer ---------- */ .site-foot{border-top:1px solid var(--line);margin-top:auto;padding-block:26px 40px;color:var(--ink-3);font-size:12.5px} From ba2464beb3b70560b5c198521876f2c1df7a63c9 Mon Sep 17 00:00:00 2001 From: devmtnaing <bobo.b90@gmail.com> Date: Thu, 8 Oct 2026 10:43:32 +0630 Subject: [PATCH 4/4] Track 3 is "AI Research Engineer"; Mark as solved at the top; shorter footer - Track 3 and the course's end goal are named AI Research Engineer everywhere: course markdown, track title, hub, overview, onboarding. - LeetCode lessons have "Mark as solved" beside the language switch at the top as well as at the foot; both stay in step. - The footer drops its first line. npm run check and npm run audit pass. --- course/README.md | 4 ++-- course/track-3-research-engineer/README.md | 8 ++++---- src/components/SiteFooter.astro | 1 - src/components/ai/Onboard.tsx | 2 +- src/data/sections.ts | 2 +- src/layouts/Walkthrough.astro | 22 ++++++++++++++-------- src/lib/ai/course.ts | 2 +- src/pages/ai-engineer/index.astro | 2 +- src/pages/index.astro | 2 +- src/styles/site.css | 11 +++++++++++ 10 files changed, 36 insertions(+), 20 deletions(-) diff --git a/course/README.md b/course/README.md index 2b78cb8..0d03156 100644 --- a/course/README.md +++ b/course/README.md @@ -4,7 +4,7 @@ A self-study curriculum in three tracks. Each track is a career step you can be ``` Track 1 Track 2 Track 3 - AI Application Engineer ──► ML / AI Systems Engineer ──────► Research Engineer + AI Application Engineer ──► ML / AI Systems Engineer ──────► AI Research Engineer (use models well) (train, tune, serve models) (understand & improve models) ~3.5–4 months ~7–9 months ~8–12 months, then ongoing @@ -42,7 +42,7 @@ A self-study curriculum in three tracks. Each track is a career step you can be | 5–7 | **Track 2**: modules 2.1–2.5 (from scratch → fine-tuning) | Level 2 (linear algebra, calculus, probability, optimization) | – | | 8–12 | **Track 2**: modules 2.6–2.10 (GPUs, inference, distributed, platform, Kubernetes) + capstones, Ops Agent v2 | Level 2 finish | **ML Platform / ML Infrastructure / Inference Engineer** | | 13–18 | **Track 3**: modules 3.1–3.5 | Level 3 (deeper probability, optimization, information theory) | – | -| 19–24+ | **Track 3**: modules 3.6–3.7, paper reproductions, original work | Level 3 ongoing | **Research Engineer** (lab, applied research team, or fellowship such as MATS or Anthropic Fellows) | +| 19–24+ | **Track 3**: modules 3.6–3.7, paper reproductions, original work | Level 3 ongoing | **AI Research Engineer** (lab, applied research team, or fellowship such as MATS or Anthropic Fellows) | You don't have to finish everything before moving on. Get a job at the Track 1 or Track 2 level and keep going while employed. That's the normal route. diff --git a/course/track-3-research-engineer/README.md b/course/track-3-research-engineer/README.md index 6533e4d..7e461f2 100644 --- a/course/track-3-research-engineer/README.md +++ b/course/track-3-research-engineer/README.md @@ -1,6 +1,6 @@ -# Track 3 · Research Engineer +# Track 3 · AI Research Engineer -**Goal:** understand *why* models work, run rigorous experiments, read and reproduce papers, and add new findings. A research engineer is the strong engineer on a research team. They turn ideas into experiments that run at scale and produce trustworthy results. +**Goal:** understand *why* models work, run rigorous experiments, read and reproduce papers, and add new findings. An AI research engineer is the strong engineer on a research team. They turn ideas into experiments that run at scale and produce trustworthy results. **Duration:** ~8–12 months to be credible, then ongoing for the rest of your career. @@ -8,7 +8,7 @@ **Why this comes last:** research needs everything before it. Track 1 gives you evals and product sense, Track 2 gives you training and systems skill. Track 3 adds theory, rigor and taste. -**A realistic note:** research engineer roles at frontier labs are very competitive. Your systems background is valued there, because many research teams are short on people who can make experiments run fast and reliably. Common routes in are fellowships (MATS, Anthropic Fellows), open-source contributions (EleutherAI, Hugging Face), and publishing strong reproductions and small studies. +**A realistic note:** AI research engineer roles at frontier labs are very competitive. Your systems background is valued there, because many research teams are short on people who can make experiments run fast and reliably. Common routes in are fellowships (MATS, Anthropic Fellows), open-source contributions (EleutherAI, Hugging Face), and publishing strong reproductions and small studies. | # | Module | Weeks | |---|---|---| @@ -196,4 +196,4 @@ - [ ] One merged open-source contribution - [ ] Math Level 3 core done -**Roles you can target now:** Research Engineer, Member of Technical Staff (research-adjacent), Applied Research Scientist, AI research fellowships. +**Roles you can target now:** AI Research Engineer, Member of Technical Staff (research-adjacent), Applied Research Scientist, AI research fellowships. diff --git a/src/components/SiteFooter.astro b/src/components/SiteFooter.astro index 6e4cf3a..72063d6 100644 --- a/src/components/SiteFooter.astro +++ b/src/components/SiteFooter.astro @@ -3,7 +3,6 @@ import { SITE_NAME, REPO } from '../data/site'; --- <footer class="site-foot"> <div class="shell"> - <span>Written and checked by hand. Every LeetCode solution here was compiled and run before it went up.</span> <span>The source is public on <a class="foot-link" href={REPO} target="_blank" rel="noopener">GitHub ↗</a>. Found a bug, a wrong answer or a confusing step? <a class="foot-link" href={`${REPO}/issues/new/choose`} target="_blank" rel="noopener">Report it there ↗</a></span> <a class="sep" href="/">{SITE_NAME}</a> </div> diff --git a/src/components/ai/Onboard.tsx b/src/components/ai/Onboard.tsx index 1742158..905280a 100644 --- a/src/components/ai/Onboard.tsx +++ b/src/components/ai/Onboard.tsx @@ -11,7 +11,7 @@ const STARTS: { id: string; icon: IconName; t: string; s: string }[] = [ { id: 'setup', icon: 'code', t: 'Set up first', s: 'Python, PyTorch, GPU access and notes (week 0)' }, { id: 't1', icon: 'bulb', t: 'New to building with LLMs', s: 'Start with Track 1: AI Application Engineer' }, { id: 't2', icon: 'bolt', t: 'I already ship LLM apps', s: 'Jump to Track 2: ML / AI Systems Engineer' }, - { id: 't3', icon: 'sparkle', t: 'I already train models', s: 'Jump to Track 3: Research Engineer' }, + { id: 't3', icon: 'sparkle', t: 'I already train models', s: 'Jump to Track 3: AI Research Engineer' }, ] export default function Onboard({ tracks }: { tracks: TrackPlan[] }) { diff --git a/src/data/sections.ts b/src/data/sections.ts index a3fcf41..46433ba 100644 --- a/src/data/sections.ts +++ b/src/data/sections.ts @@ -46,7 +46,7 @@ export const SECTIONS: Section[] = [ { id: 'ai', label: 'AI Engineer', - tagline: 'Backend → research', + tagline: 'Backend → AI research', href: '/ai-engineer', icon: 'sparkle', accent: 'indigo', diff --git a/src/layouts/Walkthrough.astro b/src/layouts/Walkthrough.astro index da79b6b..600d42a 100644 --- a/src/layouts/Walkthrough.astro +++ b/src/layouts/Walkthrough.astro @@ -69,6 +69,9 @@ const lcUrl = (slug: string) => `https://leetcode.com/problems/${slug}/`; <header> <div class="top-row"> <span class="eyebrow" data-i18n={my(p.eyebrow)} set:html={en(p.eyebrow)} /> + <button class="solve-top" type="button" data-solve={p.slug} aria-pressed="false" hidden> + <span aria-hidden="true">✓</span> <span data-solve-label>Mark as solved</span> + </button> <div class="lang-switch" role="group" aria-label="Page language"> <button class="lang-opt" data-lang-opt="en" aria-pressed="true">English</button> <button class="lang-opt" data-lang-opt="my" aria-pressed="false" lang="my">မြန်မာ</button> @@ -218,17 +221,20 @@ const lcUrl = (slug: string) => `https://leetcode.com/problems/${slug}/`; const sub = document.querySelector('.wrap header .eyebrow')?.textContent?.replace(/\s+/g, ' ').trim(); if (title) touch('leetcode', { url: location.pathname, title, sub: sub ?? 'LeetCode' }); - // "Mark as solved": a tick on the problem list and LeetCode XP - const solve = document.querySelector<HTMLButtonElement>('[data-solve]'); - if (solve) { - const id = `leetcode:${solve.dataset.solve}`; + // "Mark as solved", at the top and at the foot of the page: a tick on the + // problem list and LeetCode XP + const solves = [...document.querySelectorAll<HTMLButtonElement>('[data-solve]')]; + if (solves.length) { + const id = `leetcode:${solves[0].dataset.solve}`; const paint = () => { const on = !!get().checked[id]; - solve.setAttribute('aria-pressed', String(on)); - solve.querySelector('[data-solve-label]')!.textContent = on ? 'Solved ✓' : 'Mark as solved (+20 XP)'; + for (const b of solves) { + b.setAttribute('aria-pressed', String(on)); + b.querySelector('[data-solve-label]')!.textContent = on ? 'Solved' : b.classList.contains('solve-top') ? 'Mark as solved' : 'Mark as solved (+20 XP)'; + b.hidden = false; + } }; - solve.hidden = false; - solve.addEventListener('click', () => toggleChecked(id, 20, 'leetcode')); + for (const b of solves) b.addEventListener('click', () => toggleChecked(id, 20, 'leetcode')); paint(); subscribe(paint); } diff --git a/src/lib/ai/course.ts b/src/lib/ai/course.ts index b8323f3..c2e5468 100644 --- a/src/lib/ai/course.ts +++ b/src/lib/ai/course.ts @@ -52,7 +52,7 @@ const TRACKS = [ { id: 'setup', slug: 'setup', file: '00-setup/README.md', title: 'Setup', short: 'Setup', subtitle: 'Tools, GPUs and notes. Week 0.', color: 'slate', heading: /^## (?!Checkpoint)(\d+)\. (.+)$/ }, { id: 't1', slug: 'track-1', file: 'track-1-ai-application-engineer/README.md', title: 'AI Application Engineer', short: 'Track 1', subtitle: 'Use models well: APIs, RAG, agents, MCP, evals.', color: 'teal', heading: /^## (1\.\d+) (.+)$/ }, { id: 't2', slug: 'track-2', file: 'track-2-ml-systems-engineer/README.md', title: 'ML / AI Systems Engineer', short: 'Track 2', subtitle: 'Train, tune, optimise and serve models.', color: 'indigo', heading: /^### (2\.\d+) (.+)$/ }, - { id: 't3', slug: 'track-3', file: 'track-3-research-engineer/README.md', title: 'Research Engineer', short: 'Track 3', subtitle: 'Understand and improve models.', color: 'rose', heading: /^### (3\.\d+) (.+)$/ }, + { id: 't3', slug: 'track-3', file: 'track-3-research-engineer/README.md', title: 'AI Research Engineer', short: 'Track 3', subtitle: 'Understand and improve models.', color: 'rose', heading: /^### (3\.\d+) (.+)$/ }, { id: 'math', slug: 'math', file: 'math/README.md', title: 'Math Track', short: 'Math', subtitle: 'Runs alongside all three tracks.', color: 'amber', heading: /^## Level (\d): (.+)$/ }, ] diff --git a/src/pages/ai-engineer/index.astro b/src/pages/ai-engineer/index.astro index 86a84e3..867bc76 100644 --- a/src/pages/ai-engineer/index.astro +++ b/src/pages/ai-engineer/index.astro @@ -11,7 +11,7 @@ const plans = tracks.map((t) => ({ id: t.id, url: trackUrl(t), short: t.short, t <div class="track-hero" style="margin-bottom:14px"> <div> <div class="kicker">AI Engineer</div> - <h1 class="page-h">From backend engineer to research engineer</h1> + <h1 class="page-h">From backend engineer to AI research engineer</h1> </div> <a class="btn" href={units[0].url} data-continue hidden><Icon name="play" size={14} fill="currentColor" /> Continue: <span data-continue-label></span></a> </div> diff --git a/src/pages/index.astro b/src/pages/index.astro index 593ebba..daa2ab1 100644 --- a/src/pages/index.astro +++ b/src/pages/index.astro @@ -34,7 +34,7 @@ const questions = Object.values(quizzes).reduce((a, q) => a + q.length, 0); </a> <a class="hub-card tc-indigo" href="/ai-engineer"> <div class="kicker" style="color:var(--ct)">AI Engineer</div> - <h2>Backend → research engineer</h2> + <h2>Backend → AI research engineer</h2> <p>Three tracks, each a job you can be hired for: AI application, ML systems, research. Concepts, resources, builds, quizzes and checkpoints.</p> <div class="hub-stats"> <span><b>{modules}</b>modules</span> diff --git a/src/styles/site.css b/src/styles/site.css index 0723fac..3f08aa3 100644 --- a/src/styles/site.css +++ b/src/styles/site.css @@ -181,3 +181,14 @@ a.ptitle::after{content:"";position:absolute;inset:0;border-radius:inherit} .search-btn{height:40px;min-width:40px} .k-opt{min-height:44px} } + +/* "Mark as solved" beside the language switch at the top of a lesson */ +.solve-top{ + margin-left:auto;display:inline-flex;align-items:center;gap:6px;font:inherit;font-size:13px;font-weight:600;cursor:pointer; + border:1px solid var(--line);border-radius:999px;padding:6px 14px;background:var(--surface);color:var(--ink-2); +} +.solve-top > span:first-child{color:var(--ink-3)} +.solve-top:hover{border-color:var(--up);color:var(--up)} +.solve-top[aria-pressed="true"]{background:var(--up-soft);border-color:var(--up);color:var(--up)} +.solve-top[aria-pressed="true"] > span:first-child{color:var(--up)} +.solve-top + .lang-switch{margin-left:0}