diff --git a/src/app/courses/page.tsx b/src/app/courses/page.tsx index 0546b9f0..054cd7b9 100644 --- a/src/app/courses/page.tsx +++ b/src/app/courses/page.tsx @@ -8,7 +8,6 @@ import { CoursesHero } from "@/components/courses/CoursesHero"; import { CATALOG, TOPICS, - formatDuration, getTrackOutline, getTrackStats, } from "@/components/courses/catalog"; @@ -39,7 +38,6 @@ export default function CoursesPage() { // Lessons lead on every card — they are ours and one click away, where // enrolling leaves the site. Every figure below is counted, not typed. const items: CatalogItem[] = CATALOG.map((course) => { - const stats = getTrackStats(course.track); return { track: course.track, title: course.title, @@ -49,14 +47,12 @@ export default function CoursesPage() { topicLabel: TOPICS.find((topic) => topic.id === course.topic)?.label ?? "", enrol: course.enrol, href: TRACK_ROUTES[course.track].href, - stats, - duration: formatDuration(stats.minutes), outline: getTrackOutline(course.track), cover: , }; }); - const totalChapters = items.reduce((sum, item) => sum + item.stats.chapters, 0); + const totalChapters = CATALOG.reduce((sum, course) => sum + getTrackStats(course.track).chapters, 0); const totalEnrolments = CATALOG.reduce((sum, course) => sum + course.enrol.length, 0); // Suggested to newcomers by the courses' own tags, not by a hand-picked list. const startHere = CATALOG.filter((course) => diff --git a/src/app/learn/financial-literacy/page.tsx b/src/app/learn/financial-literacy/page.tsx index 898b1918..d51a56d8 100644 --- a/src/app/learn/financial-literacy/page.tsx +++ b/src/app/learn/financial-literacy/page.tsx @@ -24,7 +24,7 @@ export default function LearnFinancialLiteracyPage() { } /> diff --git a/src/app/learn/github/page.tsx b/src/app/learn/github/page.tsx index fa03426f..0a24452a 100644 --- a/src/app/learn/github/page.tsx +++ b/src/app/learn/github/page.tsx @@ -24,7 +24,7 @@ export default function LearnGithubPage() { } /> diff --git a/src/app/learn/health-in-tech/page.tsx b/src/app/learn/health-in-tech/page.tsx index 05933970..166a8e1e 100644 --- a/src/app/learn/health-in-tech/page.tsx +++ b/src/app/learn/health-in-tech/page.tsx @@ -24,7 +24,7 @@ export default function LearnHealthInTechPage() { } /> diff --git a/src/app/learn/html-css/page.tsx b/src/app/learn/html-css/page.tsx index 4ae9fe11..19b9dd96 100644 --- a/src/app/learn/html-css/page.tsx +++ b/src/app/learn/html-css/page.tsx @@ -24,7 +24,7 @@ export default function LearnHtmlCssPage() { } /> diff --git a/src/app/learn/python/page.tsx b/src/app/learn/python/page.tsx index e6b4c3dc..17de7b3a 100644 --- a/src/app/learn/python/page.tsx +++ b/src/app/learn/python/page.tsx @@ -24,7 +24,7 @@ export default function LearnPythonPage() { } /> diff --git a/src/app/learn/roblox/page.tsx b/src/app/learn/roblox/page.tsx index 42d93a53..39422afb 100644 --- a/src/app/learn/roblox/page.tsx +++ b/src/app/learn/roblox/page.tsx @@ -24,7 +24,7 @@ export default function LearnRobloxPage() { } /> diff --git a/src/app/playground/opengraph-image.tsx b/src/app/playground/opengraph-image.tsx index 38604409..0c592e6d 100644 --- a/src/app/playground/opengraph-image.tsx +++ b/src/app/playground/opengraph-image.tsx @@ -1,6 +1,6 @@ import { OG_CONTENT_TYPE, OG_SIZE, ogImage } from "@/lib/og-image"; -export const alt = "CodeWithPurpose code playground: run Python in your browser"; +export const alt = "CodeWithPurpose code playground: run Python and build ML models in your browser"; export const size = OG_SIZE; export const contentType = OG_CONTENT_TYPE; diff --git a/src/app/playground/page.tsx b/src/app/playground/page.tsx index c1b1ce25..b103a0d0 100644 --- a/src/app/playground/page.tsx +++ b/src/app/playground/page.tsx @@ -5,10 +5,10 @@ import { Reveal } from "@/components/Reveal"; import BlurText from "@/components/reactbits/BlurText"; import { PlaygroundIsland } from "@/components/playground/PlaygroundIsland"; import { PYODIDE_VERSION } from "@/components/playground/protocol"; -import { LEARN_ML_HREF, LEARN_PYTHON_HREF } from "@/lib/links"; +import { LEARN_ML_HREF, LEARN_PYTHON_HREF, PROJECTS_HREF } from "@/lib/links"; const DESCRIPTION = - "Write and run real Python, NumPy, pandas, scikit-learn and matplotlib in your browser. Free, no sign-up, and your code never leaves your device."; + "Write and run real Python, NumPy, pandas, scikit-learn and matplotlib in your browser, or drag blocks together to train a machine-learning model. Free, no sign-up, and your code never leaves your device."; export const metadata: Metadata = { title: "Code Playground", @@ -37,12 +37,12 @@ const HOW_IT_WORKS = [ body: "There is no server and no account. Your code is saved in this browser only, and Share packs it into the link itself, after the #, which browsers never send to a server.", }, { - title: "Libraries load when you import them", - body: "The first Run downloads Python (about 10 MB). Importing numpy, pandas, scikit-learn or matplotlib fetches that library the first time; after that your browser keeps a copy.", + title: "The ML builder writes real code", + body: "Each block you drag in becomes a commented section of ordinary scikit-learn code, shown beside the pipeline. Open it in the editor whenever you want to change it by hand.", }, { - title: "A few honest limits", - body: "Runs stop after 30 seconds. input() reads from an answer box you fill in before running, because the page can't pause Python mid-run. There's no internet access or access to files on your computer from inside Python.", + title: "Good to know", + body: "The first Run downloads Python (about 10 MB), and big libraries load the first time you import them; after that your browser keeps a copy. Runs stop after 30 seconds, input() reads from an answer box you fill in first, and Python here has no internet access.", }, ] as const; @@ -62,10 +62,21 @@ export default function PlaygroundPage() { className="home-display mt-3 text-[2rem] leading-[1.05] tracking-[-0.02em] md:text-[2.75rem] lg:text-[3.25rem]" />

- Pick a starter or write your own, then press Run. Python, NumPy, pandas, - scikit-learn and matplotlib all work, for free, with no sign-up, and your + Pick a starter or write your own, then press Run. Or open the ML builder + and drag blocks together to train a real model. Free, no sign-up, and your code never leaves this page.

+

+ Building a web page instead?{" "} + + Open the HTML & CSS editor + + , or pick a guided{" "} + + project + + . +

diff --git a/src/app/playground/web/page.tsx b/src/app/playground/web/page.tsx new file mode 100644 index 00000000..16c9efc8 --- /dev/null +++ b/src/app/playground/web/page.tsx @@ -0,0 +1,92 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { PageShell } from "@/components/PageShell"; +import { WebPlaygroundIsland } from "@/components/webplay/WebPlaygroundIsland"; +import { LEARN_HTML_CSS_HREF, PLAYGROUND_HREF } from "@/lib/links"; + +const DESCRIPTION = + "Write HTML, CSS and JavaScript and watch the page update as you type. Free, no sign-up, and your code stays in your browser."; + +export const metadata: Metadata = { + title: "Web Playground", + description: DESCRIPTION, + alternates: { canonical: "/playground/web/" }, + openGraph: { + title: "Web Playground | CodeWithPurpose", + description: DESCRIPTION, + url: "/playground/web/", + type: "website", + }, + twitter: { + card: "summary_large_image", + title: "Web Playground | CodeWithPurpose", + description: DESCRIPTION, + }, +}; + +const NOTES = [ + { + title: "It updates as you type", + body: "Pause for a moment and the preview redraws. Switch between the HTML, CSS and JS tabs; they all feed the same page.", + }, + { + title: "Nothing leaves your browser", + body: "Your code is saved in this browser only. Share puts it in the link itself, after the #, which browsers never send to a server.", + }, + { + title: "The preview is walled off", + body: "It runs in a sandboxed frame with no network access, so external images, fonts and scripts won't load. Inline code and data: URLs work.", + }, +] as const; + +export default function WebPlaygroundPage() { + return ( + +
+
+

+ Web playground +

+

+ Build a web page, live +

+

+ Pick a starter or clear it out and write your own. Change one thing, watch the preview, + and keep going. +

+ +
+ +
+
+
+ +
+
+

+ Good to know +

+
+ {NOTES.map((item) => ( +
+

{item.title}

+

{item.body}

+
+ ))} +
+

+ New to all this? The{" "} + + HTML and CSS track + {" "} + starts from what a web page is. Prefer Python? Try the{" "} + + Python playground + + . +

+
+
+
+ ); +} diff --git a/src/app/projects/[slug]/opengraph-image.tsx b/src/app/projects/[slug]/opengraph-image.tsx new file mode 100644 index 00000000..6415de36 --- /dev/null +++ b/src/app/projects/[slug]/opengraph-image.tsx @@ -0,0 +1,19 @@ +import { OG_CONTENT_TYPE, OG_SIZE, ogImage } from "@/lib/og-image"; +import { PROJECTS, getProject, trackLabel } from "@/lib/projects"; + +export const alt = "A guided project from CodeWithPurpose"; +export const size = OG_SIZE; +export const contentType = OG_CONTENT_TYPE; + +export function generateStaticParams() { + return PROJECTS.map((project) => ({ slug: project.slug })); +} + +export default async function Image({ params }: { params: Promise<{ slug: string }> }) { + const { slug } = await params; + const project = getProject(slug); + return ogImage({ + eyebrow: project ? `${trackLabel(project.track)} project` : "Projects", + title: project?.title ?? "Guided build projects", + }); +} diff --git a/src/app/projects/[slug]/page.tsx b/src/app/projects/[slug]/page.tsx new file mode 100644 index 00000000..3241f2a1 --- /dev/null +++ b/src/app/projects/[slug]/page.tsx @@ -0,0 +1,233 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { ChevronDown, Lightbulb } from "lucide-react"; +import { PageShell } from "@/components/PageShell"; +import { InlineCode } from "@/components/projects/InlineCode"; +import { CodeFiles, PlaygroundButton } from "@/components/projects/ProjectCode"; +import { TrackIcon } from "@/components/projects/TrackIcon"; +import { chapterHref, getChapter, getTrack } from "@/lib/learn-nav"; +import { PROJECTS_HREF } from "@/lib/links"; +import { PROJECTS, getProject, trackLabel, type Project } from "@/lib/projects"; + +export function generateStaticParams() { + return PROJECTS.map((project) => ({ slug: project.slug })); +} + +export async function generateMetadata({ + params, +}: { + params: Promise<{ slug: string }>; +}): Promise { + const { slug } = await params; + const project = getProject(slug); + if (!project) return { title: "Projects" }; + const title = `${project.title} project`; + const url = `${PROJECTS_HREF}${slug}/`; + return { + title, + description: project.pitch, + alternates: { canonical: url }, + openGraph: { title: `${title} | CodeWithPurpose`, description: project.pitch, url, type: "article" }, + twitter: { card: "summary_large_image", title: `${title} | CodeWithPurpose`, description: project.pitch }, + }; +} + +/** Resolve chapter links at build time; a renamed slug fails loudly here. */ +function resolveChapters(project: Project) { + return project.chapters.map(({ track, slug }) => { + const chapter = getChapter(track, slug); + if (!chapter) throw new Error(`Project "${project.slug}" links to a missing chapter: ${track}/${slug}`); + return { href: chapterHref(track, slug), title: chapter.title, course: getTrack(track).title }; + }); +} + +const SECTION_TITLE = "home-display text-[1.5rem] leading-[1.15] md:text-[1.875rem]"; + +export default async function ProjectPage({ params }: { params: Promise<{ slug: string }> }) { + const { slug } = await params; + const project = getProject(slug); + if (!project) notFound(); + + const chapters = resolveChapters(project); + const index = PROJECTS.indexOf(project); + const next = PROJECTS[(index + 1) % PROJECTS.length]; + const isWeb = project.starter.kind === "web"; + + return ( + +
+
+ +
+
+

+ Steps +

+
    + {project.steps.map((step, stepIndex) => ( +
  1. + +
    +

    + Step {stepIndex + 1}: + {step.title} +

    +

    + +

    + {step.hint && ( +
    + + +

    + +

    +
    + )} +
    +
  2. + ))} +
+
+ +
+
+
+

+ Starter code +

+

+ {isWeb + ? "It already shows something on the page. The TODO comments mark where to start." + : "It already runs. The TODO comments mark where to start."} +

+
+ +
+
+ +
+
+ +
+

+ Example solution +

+

+ One way to finish it. Have a go first; yours doesn't need to match. +

+
+ + Reveal the solution + Hide the solution + +
+ +
+ +
+
+
+
+ +
+
+

+ Stretch goal +

+

+ +

+
+
+

+ Chapters that help +

+ +
+
+ + +
+
+ ); +} diff --git a/src/app/projects/[slug]/twitter-image.tsx b/src/app/projects/[slug]/twitter-image.tsx new file mode 100644 index 00000000..789b5eed --- /dev/null +++ b/src/app/projects/[slug]/twitter-image.tsx @@ -0,0 +1 @@ +export { default, alt, size, contentType, generateStaticParams } from "./opengraph-image"; diff --git a/src/app/projects/opengraph-image.tsx b/src/app/projects/opengraph-image.tsx new file mode 100644 index 00000000..d10484bd --- /dev/null +++ b/src/app/projects/opengraph-image.tsx @@ -0,0 +1,9 @@ +import { OG_CONTENT_TYPE, OG_SIZE, ogImage } from "@/lib/og-image"; + +export const alt = "CodeWithPurpose projects: guided builds you can finish in your browser"; +export const size = OG_SIZE; +export const contentType = OG_CONTENT_TYPE; + +export default function Image() { + return ogImage({ eyebrow: "Projects", title: "Build something real, one step at a time" }); +} diff --git a/src/app/projects/page.tsx b/src/app/projects/page.tsx new file mode 100644 index 00000000..fa999b63 --- /dev/null +++ b/src/app/projects/page.tsx @@ -0,0 +1,105 @@ +import type { Metadata } from "next"; +import { PageShell } from "@/components/PageShell"; +import { ProjectFilter, type ProjectCardItem } from "@/components/projects/ProjectFilter"; +import { COURSES_HREF, PLAYGROUND_HREF, PROJECTS_HREF } from "@/lib/links"; +import { PROJECTS, PROJECT_TRACKS, trackLabel } from "@/lib/projects"; + +const DESCRIPTION = + "Free, beginner-friendly build projects in Python, HTML and CSS, and machine learning. Follow short steps, peek at hints, and run everything in your browser."; + +export const metadata: Metadata = { + title: "Projects", + description: DESCRIPTION, + alternates: { canonical: PROJECTS_HREF }, + openGraph: { + title: "Projects | CodeWithPurpose", + description: DESCRIPTION, + url: PROJECTS_HREF, + type: "website", + }, + twitter: { + card: "summary_large_image", + title: "Projects | CodeWithPurpose", + description: DESCRIPTION, + }, +}; + +const HOW_IT_GOES = [ + { title: "Pick one that sounds fun", body: "Each project is small enough to finish and starts from code that already runs." }, + { title: "Follow the steps", body: "Short steps, each with a hint tucked away for when you get stuck." }, + { title: "Check, then stretch", body: "Compare with an example solution, then try the stretch goal to make it yours." }, +] as const; + +export default function ProjectsPage() { + // Only what a card draws crosses into the client filter, not the code. + const items: ProjectCardItem[] = PROJECTS.map((project) => ({ + slug: project.slug, + href: `${PROJECTS_HREF}${project.slug}/`, + track: project.track, + trackLabel: trackLabel(project.track), + title: project.title, + pitch: project.pitch, + skills: project.skills, + })); + + return ( + +
+
+ +
+
+

+ All projects +

+ + +
+

+ Want to brush up first? Every project links to the course chapters that help, and the + playground is always open if you'd rather just tinker. +

+ +
+
+
+
+ ); +} diff --git a/src/app/projects/twitter-image.tsx b/src/app/projects/twitter-image.tsx new file mode 100644 index 00000000..76d56364 --- /dev/null +++ b/src/app/projects/twitter-image.tsx @@ -0,0 +1 @@ +export { default, alt, size, contentType } from "./opengraph-image"; diff --git a/src/app/resources/ai-coding/page.tsx b/src/app/resources/ai-coding/page.tsx index 424f4505..3a5e2290 100644 --- a/src/app/resources/ai-coding/page.tsx +++ b/src/app/resources/ai-coding/page.tsx @@ -1,21 +1,19 @@ import type { Metadata } from "next"; +import type { ReactNode } from "react"; import Link from "next/link"; -import { ArrowUpRight } from "lucide-react"; +import { ArrowRight, ArrowUpRight, Check, Code2, Globe, MessageCircle, X } from "lucide-react"; import { PageHero, PageSection } from "@/components/PageHero"; import { PageShell } from "@/components/PageShell"; -import { Reveal } from "@/components/Reveal"; -import BlurText from "@/components/reactbits/BlurText"; -import GlareHover from "@/components/reactbits/GlareHover"; -import Magnet from "@/components/reactbits/Magnet"; -import { CopyPromptButton } from "@/components/resources/CopyPromptButton"; +import { PromptBuilder } from "@/components/resources/PromptBuilder"; import { - AI_TOOLS, + DONTS, + DOS, GLOSSARY, - PROMPT_TEMPLATES, - SAFETY_RULES, - WORKFLOW_STEPS, + START_STEPS, + TOOL_GROUPS, + type ToolGroup, } from "@/components/resources/ai-coding-content"; -import { DISCORD_HREF, JOIN_HREF, LEARN_VIBECODING_HREF, PLAYGROUND_HREF } from "@/lib/links"; +import { DISCORD_HREF, LEARN_VIBECODING_HREF, PLAYGROUND_HREF } from "@/lib/links"; const TITLE = "AI-Coding Resources"; const DESCRIPTION = @@ -40,26 +38,33 @@ export const metadata: Metadata = { const EYEBROW = "text-[11px] uppercase tracking-[0.16em] text-[#397554]"; const H2 = "home-serif text-[1.75rem] leading-[1.1] md:text-[2.25rem]"; -const LEAD = "mt-4 max-w-2xl text-[15px] leading-[1.6] text-[var(--home-ink-soft)] md:text-base"; +const LEAD = "mt-3 max-w-xl text-[15px] leading-[1.6] text-[var(--home-ink-soft)] md:text-base"; +const DIVIDER = "scroll-mt-24 border-t-[0.5px] border-[var(--home-hairline)]"; -function SectionIntro({ eyebrow, title, lead, id }: { eyebrow: string; title: string; lead: string; id: string }) { +const GROUP_ICONS: Record = { + chat: MessageCircle, + editor: Code2, + browser: Globe, +}; + +function SectionIntro({ eyebrow, title, lead, id }: { eyebrow: string; title: string; lead?: string; id: string }) { return ( - +

{eyebrow}

{title}

-

{lead}

- + {lead &&

{lead}

} +
); } -function ExternalLink({ href, children, className = "" }: { href: string; children: React.ReactNode; className?: string }) { +function ExternalLink({ href, children, className = "" }: { href: string; children: ReactNode; className?: string }) { return ( - + {children} ); } @@ -69,189 +74,207 @@ export default function AiCodingResourcesPage() { - - Start the Vibe Coding course - - - Try code in your browser + + Start here + + + Build a prompt - {/* Pick a tool */} - - -
    - {AI_TOOLS.map((tool, i) => ( -
  • - -
    + +
      + {START_STEPS.map((step, i) => { + const internal = step.cta.href.startsWith("/"); + const cta = ( + <> + {step.cta.label} +
-

- Listed in no particular order. CodeWithPurpose isn’t affiliated with any of these companies. -

+ + ); + })} +
- {/* Prompts */} - + {/* Prompt builder */} + -
    - {PROMPT_TEMPLATES.map((item, i) => ( -
  • - - -
    -
    -

    {item.title}

    -

    {item.why}

    -
    -
    - -
    -
    -
    -                    {item.prompt}
    -                  
    -
    -
    -
  • - ))} -
+
+ +
- {/* Workflow */} - -
- -
    - {WORKFLOW_STEPS.map((step, i) => ( -
  1. - + {/* Tools */} + + +
    + {TOOL_GROUPS.map((group) => { + const Icon = GROUP_ICONS[group.id]; + const headingId = `tools-${group.id}`; + return ( +
    +
    -

    - Step {i + 1}: - {step.title} +

    + {group.title}

    -

    {step.body}

    +

    {group.blurb}

    - -
  2. - ))} -
+
+
    + {group.tools.map((tool) => ( +
  • +

    {tool.name}

    +

    {tool.description}

    +
    + Visit site + {tool.student && ( + + {tool.student.label} + + )} +
    +
  • + ))} +
+ + ); + })}
+

+ Listed in no particular order. CodeWithPurpose isn’t affiliated with any of these companies. +

{/* Safety */} - + -
    - {SAFETY_RULES.map((rule, i) => ( -
  • - -

    {rule.title}

    -

    {rule.body}

    -
    -
  • - ))} -
+
+
+

+

+
    + {DOS.map((item) => ( +
  • +
  • + ))} +
+
+
+

+

+
    + {DONTS.map((item) => ( +
  • +
  • + ))} +
+
+
{/* Glossary */} - - - -
- {GLOSSARY.map((entry) => ( -
-
{entry.term}
-
{entry.definition}
-
- ))} -
-
+ + +
+ {GLOSSARY.map((entry) => ( +
+
{entry.term}
+
{entry.definition}
+
+ ))} +
- {/* Closing CTA */} -
-
- -

- Our free Vibe Coding course walks you through building real projects with AI, one step at a - time. Questions along the way? Ask the community. + {/* Next steps */} + +

+

+ Ready to build something? +

+

+ Our free Vibe Coding course walks you through building real projects with AI, one step at a time. + Or try some code right now in the playground.

-
- - - Start the Vibe Coding course - - - - Join our Discord - (opens in a new tab) - - - Join Us +
+ + Start the Vibe Coding course + + + Open the playground
+

+ Questions along the way?{" "} + + Ask in our Discord + (opens in a new tab) + +

-
+
); } diff --git a/src/app/sitemap.ts b/src/app/sitemap.ts index e61cb48d..a3cb2fe2 100644 --- a/src/app/sitemap.ts +++ b/src/app/sitemap.ts @@ -1,6 +1,7 @@ import type { MetadataRoute } from "next"; import { SITE_URL } from "@/lib/links"; import { posts } from "@/lib/posts"; +import { PROJECTS } from "@/lib/projects"; /** Absolute URL with a trailing slash, matching how the site serves pages * (`trailingSlash: true`) so canonicals and the sitemap agree. */ @@ -25,6 +26,7 @@ export default function sitemap(): MetadataRoute.Sitemap { "/media", "/resources/ai-coding", "/playground", + "/projects", "/learn/ml", "/learn/vibecoding", "/learn/python", @@ -48,5 +50,12 @@ export default function sitemap(): MetadataRoute.Sitemap { priority: 0.6, })); - return [...staticRoutes, ...postRoutes]; + const projectRoutes = PROJECTS.map((project) => ({ + url: abs(`/projects/${project.slug}`), + lastModified: new Date(), + changeFrequency: "monthly" as const, + priority: 0.6, + })); + + return [...staticRoutes, ...projectRoutes, ...postRoutes]; } diff --git a/src/components/SiteFooter.tsx b/src/components/SiteFooter.tsx index 6c68920a..c12f60cf 100644 --- a/src/components/SiteFooter.tsx +++ b/src/components/SiteFooter.tsx @@ -15,6 +15,7 @@ import { JOIN_HREF, MEDIA_HREF, PLAYGROUND_HREF, + PROJECTS_HREF, X_HREF, } from "@/lib/links"; @@ -76,6 +77,11 @@ export function SiteFooter() { Courses +
  • + + Projects + +
  • diff --git a/src/components/SiteHeader.tsx b/src/components/SiteHeader.tsx index 56d0af5b..f9236b26 100644 --- a/src/components/SiteHeader.tsx +++ b/src/components/SiteHeader.tsx @@ -12,7 +12,7 @@ const PRIMARY_NAV_LINKS = NAV_LINKS.filter(({ label }) => ["Courses", "About Us", "Stories", "Join Us"].includes(label), ); const MORE_NAV_LINKS = NAV_LINKS.filter(({ label }) => - ["AI Resources", "Code Playground", "Media", "Contact"].includes(label), + ["Projects", "Code Playground", "AI Resources", "Media", "Contact"].includes(label), ); function LogInButton({ onNavigate }: { onNavigate?: () => void }) { diff --git a/src/components/computer-vision/BoundingBoxesAndIouLesson.tsx b/src/components/computer-vision/BoundingBoxesAndIouLesson.tsx index 61808d02..6a624950 100644 --- a/src/components/computer-vision/BoundingBoxesAndIouLesson.tsx +++ b/src/components/computer-vision/BoundingBoxesAndIouLesson.tsx @@ -1,6 +1,8 @@ import { TakeawayCard } from "@/components/learn/primitives/Cards"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; import { IouDragger } from "@/components/computer-vision/IouDragger"; +import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; export function BoundingBoxesAndIouLesson() { return ( @@ -40,6 +42,16 @@ export function BoundingBoxesAndIouLesson() { all score 0. Everything a detector actually produces lands somewhere in between, and the interactive below lets you watch that number move.

    +
    + +
    @@ -59,13 +71,42 @@ export function BoundingBoxesAndIouLesson() { picture changes continuously. The verdict does not — it flips the instant the number crosses the line.

    +

    + Here is IoU as a function, with a 100-by-100 prediction slid further and further right + of the true box. +

    + = 0.5 else "miss" + print(f"shifted {shift:3} px: IoU {score:.2f} ({verdict} at 0.5)")`} + /> +

    + A 25-pixel slide still scores 0.60, a hit. At 50 pixels it is 0.33, the miss from the + exercise above. Change the threshold to 0.75 and the 25-pixel box becomes a miss + without moving. +

    0.5 is the threshold you will see quoted most often, but it is a convention, not a property of geometry. A benchmark can and does choose differently — some standard - evaluations report accuracy at 0.75, a noticeably stricter bar, and some report a whole + evaluations report results at 0.75, a noticeably stricter bar, and some report a whole curve of scores across every threshold from 0.5 to 0.95 rather than commit to one.

    diff --git a/src/components/computer-vision/ColourAndChannelsLesson.tsx b/src/components/computer-vision/ColourAndChannelsLesson.tsx index 97300d95..8ee9989a 100644 --- a/src/components/computer-vision/ColourAndChannelsLesson.tsx +++ b/src/components/computer-vision/ColourAndChannelsLesson.tsx @@ -1,7 +1,8 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards"; -import { InlineCode } from "@/components/learn/primitives/CodeBlock"; +import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; export function ColourAndChannelsLesson() { return ( @@ -27,7 +28,7 @@ export function ColourAndChannelsLesson() { channel until you ask a specific question about a specific image.

    - + combined @@ -41,9 +42,9 @@ export function ColourAndChannelsLesson() { G = 206 - + + B = 235 - B = 235
    @@ -59,9 +60,11 @@ export function ColourAndChannelsLesson() { 0.299R + 0.587G + 0.114B, not a plain average of the three.

    - Green gets nearly five times the weight of blue because human vision is - far more sensitive to green light — your eye has more receptors tuned to that part of - the spectrum than to red or blue. A grayscale conversion that used equal weights would + Green gets about five times the weight of blue because human brightness + perception peaks in the green part of the spectrum: the cones that respond to red and to + green both respond strongly there, while blue-sensitive cones are comparatively few and + contribute little to how bright something looks. A grayscale conversion that used equal + weights would produce a technically valid image that looked wrong to every person who looked at it, because it would not match how brightness actually registers for a human observer.

    @@ -71,6 +74,16 @@ export function ColourAndChannelsLesson() { convert to the same grey. The weighting is tuned to human perception, not to the raw light hitting the sensor. +
    + +
    @@ -137,12 +150,51 @@ export function ColourAndChannelsLesson() { one. It is a common bug, not a hypothetical: forgetting one{" "} cv2.cvtColor(img, cv2.COLOR_BGR2RGB) call is enough to cause it. +

    + A two-pixel image, a sky and a leaf, pulled apart into channels, turned grey, and then + read in the wrong channel order. +

    + +

    + The weighted grey for the sky is 188, as in the exercise above. Reversed, the sky + becomes 235, 206, 135, a pale orange, while the leaf barely changes, because its red + and blue were close to begin with. +

    - Click through the matrix above and one pair dominates. Cats, dogs and foxes are each - confused with something else once or twice out of fifty — noise, essentially. Wolves and + Click through the matrix above and one pair dominates. Cats, dogs and foxes each lose + only three or four photos out of fifty, scattered one or two at a time across the other + classes — noise, essentially. Wolves and coyotes are a different story: 19 wolves called coyotes, 21 coyotes called wolves, out of 50 of each. That is 40 of the 54 total errors in the entire matrix, from one pair of classes out of five.

    That number changes what you would do next. Improving every class’s accuracy by a - point each is 5 points of work for a few points of overall gain. Fixing the wolf/coyote + point each is five separate pieces of work for one point of overall gain. Fixing the wolf/coyote confusion alone — better ear and muzzle features, more training photos of exactly this pair side by side — recovers up to 40 of the 54 errors on its own, which would push - accuracy from 78.4% into the low-to-mid 90s. The matrix tells you where to spend + accuracy from 78.4% to as high as 94.4%. The matrix tells you where to spend the next month, and the single number never could.

    @@ -72,6 +74,40 @@ export function ConfusionMatrixForVisionLesson() { confusion is almost always a small number of visually or semantically similar classes, not a uniform smear. +

    + Try it on real images: a deliberately weak digit classifier, then the off-diagonal + cells sorted by count. +

    + +

    + Overall it scores 84.4%. The biggest single error is 21 eights called ones, then 16 + threes called nines. Change the 60 training images to 300 and see which confusions + survive. +

    +
    + +
    + + Strictly, the textbook definition of convolution flips the kernel before sliding it. + Image libraries and neural networks almost always skip the flip — the operation they + run is technically called cross-correlation — and for symmetric kernels like blur and + sharpen the two give identical results. + Edge detection, sharpening, blurring and the very first layer of a neural network’s convolution are all this same slide-multiply-sum procedure. What changes between all of diff --git a/src/components/computer-vision/ConvolutionalNeuralNetworksLesson.tsx b/src/components/computer-vision/ConvolutionalNeuralNetworksLesson.tsx index f25b2dff..4738b7aa 100644 --- a/src/components/computer-vision/ConvolutionalNeuralNetworksLesson.tsx +++ b/src/components/computer-vision/ConvolutionalNeuralNetworksLesson.tsx @@ -2,6 +2,7 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { TakeawayCard } from "@/components/learn/primitives/Cards"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; import { LayerStepper } from "@/components/computer-vision/LayerStepper"; +import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; export function ConvolutionalNeuralNetworksLesson() { return ( @@ -51,7 +52,7 @@ export function ConvolutionalNeuralNetworksLesson() { simply what a network with a 3×3 window and one layer of depth is capable of noticing, and so edges are what it converges on.

    - + This is not a claim you have to take on faith. Feature visualisation techniques let you render exactly what pattern makes each first-layer kernel fire most strongly, and across published networks the result looks the same: a bank of oriented edges and colour @@ -92,10 +93,34 @@ export function ConvolutionalNeuralNetworksLesson() { The second is reach. A single 3×3 kernel in the first layer only ever looks at nine pixels. Stack five layers of 3×3 kernels and the fifth layer’s output at any position is influenced by roughly an 11×11 patch of the original image — its{" "} - receptive field. Stack thirty and that patch can cover most of the - photo. Depth is how a network built from small, local operations ends up seeing + receptive field. Each 3×3 layer adds two pixels to the width, so n + layers see a patch 2n + 1 pixels across. Real networks also shrink the grid between + layers with pooling or larger strides, which makes the patch grow much faster, so by + thirty layers it can cover most of the photo. Depth is how a network built from small, local operations ends up seeing something global.

    +

    + You can check the 2n + 1 rule by following a single pixel through a stack of 3-by-3 + layers. +

    + +

    + Each layer adds two pixels: 3, 5, 7, 9, then 11 after five layers. +

    Depth is not free. More layers means more parameters to learn, more computation for every photo you show it, and a model that needs far more labelled diff --git a/src/components/computer-vision/DatasetBiasLesson.tsx b/src/components/computer-vision/DatasetBiasLesson.tsx index 0e7242d9..60c302cc 100644 --- a/src/components/computer-vision/DatasetBiasLesson.tsx +++ b/src/components/computer-vision/DatasetBiasLesson.tsx @@ -1,5 +1,6 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards"; +import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; export function DatasetBiasLesson() { @@ -45,9 +46,9 @@ export function DatasetBiasLesson() {

    This is not hypothetical. Joy Buolamwini and Timnit Gebru’s 2018 “Gender - Shades” study tested three commercial facial-analysis systems and found error rates - on darker-skinned women running as high as 34%, against under 1% for lighter-skinned men - on the same systems. The gap was not a mysterious algorithmic quirk — it traced directly + Shades” study tested three commercial systems that classify the gender of a face and + found error rates on darker-skinned women running as high as 34%, against under 1% for + lighter-skinned men on the same systems. The gap was not a mysterious algorithmic quirk — it traced directly back to benchmark and training datasets that were overwhelmingly lighter-skinned and male.

    @@ -86,6 +87,29 @@ export function DatasetBiasLesson() { blended average. It is unglamorous and it is the only method that reliably surfaces a gap an overall score is mathematically built to hide.

    +

    + A generated test set where one group makes up about 4% of the photos and the model is + much worse on it. One overall number, then the same results grouped. +

    + error_rate + +results = pd.DataFrame({"group": group, "correct": correct}) +print(f"overall accuracy: {results.correct.mean():.1%}") +print(results.groupby("group").correct.agg(["mean", "count"]).round(3))`} + /> +

    + Overall accuracy is 96.4%. Grouped, it is 97.1% for the well-represented photos and + 79.1% for the rest. +

    pick a cutoff, and call anything above it an edge.
    That single decision — a threshold — is what turns a field of slopes into a clean line drawing.

    +

    + Here it is on a tiny wall with a darker doorway, plus a little sensor noise. Each + pixel is compared with its right neighbour and the one below. +

    + threshold).astype(int)) # 1 marks an edge`} + /> +

    + Inside the wall and the doorway the slope stays under 20; along the door frame it + jumps past 75. A threshold of 40 keeps just the frame. Drop it to 5 and the noise + starts drawing lines of its own. +

    - The previous chapter’s Gender Shades findings apply directly here, and soberly: that + The Gender Shades findings from the dataset bias chapter apply here, and soberly: that research measured commercial facial-analysis error rates as high as 34% for darker-skinned - women against under 1% for lighter-skinned men, on systems already deployed commercially. + women against under 1% for lighter-skinned men, on systems already sold commercially. + Gender Shades tested gender classification rather than identity matching, but the U.S. + government’s own testing of face recognition algorithms in 2019 also found error + rates that varied across demographic groups for many of the systems it evaluated. A wrongful match from a recognition system is not an abstract inconvenience — it can mean being stopped, questioned, or investigated for something you did not do.

    @@ -71,19 +74,19 @@ export function FaceDetectionAndPrivacyLesson() {

    - None of this stayed theoretical. Several cities and police departments in the United - States have restricted or banned police use of facial recognition outright, after - documented wrongful arrests traced back to recognition errors. A number of large - companies paused or ended sales of facial recognition to law enforcement following the - same evidence. + None of this stayed theoretical. Several U.S. cities have restricted or banned police + use of facial recognition outright, and documented wrongful arrests traced back to false + matches have since strengthened the case for limits. In 2020, amid public scrutiny that + included independent audits of uneven error rates, a number of large companies paused or + ended sales of facial recognition to police.

    @@ -97,8 +100,8 @@ export function FaceDetectionAndPrivacyLesson() { items={[ "Face detection answers 'is there a face here'; face recognition additionally matches that face against a known identity — two different technical steps routinely described as one.", "Unlocking your own phone is recognition you consented to, for a database of one; a public camera matching strangers against a database they never joined is the same technology under an opposite consent situation.", - "Documented research found facial-recognition error rates far higher for darker-skinned women than for lighter-skinned men, meaning the harm of a wrongful match falls unevenly.", - "Real, documented wrongful arrests led multiple cities and companies to restrict or end police use of facial recognition.", + "Documented research found facial-analysis error rates far higher for darker-skinned women than for lighter-skinned men, so the harm of a wrong answer falls unevenly.", + "Multiple cities and companies have restricted or ended police use of facial recognition, and documented wrongful arrests from false matches have strengthened the case for limits.", "The EU's GDPR and AI Act specifically single out biometric identification for stricter rules — this is already shaped policy, not a hypothetical concern.", ]} /> diff --git a/src/components/computer-vision/FeatureDetectorsLesson.tsx b/src/components/computer-vision/FeatureDetectorsLesson.tsx index a167759a..30e18c77 100644 --- a/src/components/computer-vision/FeatureDetectorsLesson.tsx +++ b/src/components/computer-vision/FeatureDetectorsLesson.tsx @@ -1,5 +1,6 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards"; +import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; export function FeatureDetectorsLesson() { @@ -43,7 +44,14 @@ export function FeatureDetectorsLesson() { not the sharpness of the angle, is what a corner detector is actually testing for, and it is exactly what makes a corner locatable again in a second photo.

    +

    + An edge sits in between. Slide the window across an edge and the view changes sharply; + slide it along the edge and it barely changes at all. That makes an edge locatable in one + direction and ambiguous in the other, which is why detectors prefer corners, where no + direction is ambiguous. +

    ), }, + { + title: "Edge", + tone: "neutral", + children: ( +

    + Shift across the edge and the pixels change; shift along it and they do not. You + can pin down one direction, never both. +

    + ), + }, { title: "Corner", tone: "positive", @@ -67,6 +85,35 @@ export function FeatureDetectorsLesson() { }, ]} /> +

    + Here is that test as arithmetic, on a bright square. The score adds up how brightness + changes across and down a small window, and is only large when it changes in both + directions at once. +

    + +

    + The flat patch scores 0, the edge scores below 0, and the corner scores 1.74. This is + the idea behind the Harris corner detector. +

    A live video feed at 30 frames per second hands the model a new frame every 33 - milliseconds, whether or not it has finished with the last one. A large, highly accurate - model that takes 200 milliseconds per frame is not a slower version of a usable system — - it is unusable at that frame rate, full stop, regardless of how it scored offline. + milliseconds, whether or not it has finished with the last one. Take a large, highly + accurate model that needs 200 milliseconds per frame, running on a single worker. That + worker cannot keep up with the frame rate, regardless of how the model scored offline: + it has to skip five frames in every six, and whatever happens in those gaps goes unseen. +

    +

    + Two numbers are tangled together here. Throughput is how many frames + per second the system can get through; latency is how long any one + frame waits for its answer. Running six or seven copies of the model side by side, each + taking every sixth or seventh frame, can bring throughput back up to 30 frames per + second, at the cost of that much more hardware. It does nothing for latency. Every + answer still arrives at least 200 milliseconds after its frame, which for a robot arm + or a car can already be too late. +

    +

    + A three-second simulation of a 30 fps feed and a 200 ms model, with one worker and + then seven. +

    + arrives: # every worker is busy, so this frame is skipped + continue + free_at[w] = arrives + inference + processed += 1 + print(f"{workers} worker(s): {processed} of {frames} frames processed, " + f"each answer {inference} ms after its frame")`} + /> +

    + One worker processes 15 of the 90 frames. Seven process all 90. Either way, every + answer arrives 200 ms after its frame.

    This is a genuine trade-off against accuracy, not an implementation footnote to solve - later. A smaller, faster, slightly less accurate model that keeps up with 33 milliseconds - per frame is often the only real option; a bigger model that cannot keep up does not get - partial credit for its offline score. + later. A smaller, faster, slightly less accurate model that fits inside 33 milliseconds + per frame on the hardware you actually have is often the only real option; a bigger model + that cannot keep up does not get partial credit for its offline score.

    33ms per frame at 30fps. 16.7ms at 60fps. If inference plus preprocessing plus any - post-processing does not fit inside that number, the system falls behind the incoming - feed — it does not just run a little slower, it starts processing frames that are already - stale. + post-processing does not fit inside that number on one worker, that worker falls behind + the incoming feed — it does not just run a little slower, it starts processing frames + that are already stale. More workers can share the frames out, but none of them makes a + single answer arrive sooner.
    @@ -108,7 +147,7 @@ export function FromPrototypeToProductionLesson() { items={[ "A benchmark score is a fact about a static test set measured once; it is not a promise about a continuous, real-time production camera feed.", "Deployed cameras drift from what the model trained on through scratched lenses, seasonal white-balance shifts, and newer sensor generations, and the decline is usually gradual, not dramatic.", - "At 30 frames per second a model has roughly 33 milliseconds per frame; a 200-millisecond model is unusable at that rate regardless of its offline accuracy.", + "At 30 frames per second a single worker has roughly 33 milliseconds per frame; a 200-millisecond model on one worker can only keep up by skipping most frames. Parallel workers can restore throughput, but each answer still arrives 200 milliseconds late.", "Choosing a smaller, faster, slightly less accurate model to fit the latency budget is a genuine engineering trade-off, not a footnote to accept reluctantly.", "Production traffic has no automatic ground truth, so monitoring means watching proxy signals — confidence-score drift, spikes in low-confidence predictions, user corrections — rather than a clean accuracy number.", ]} diff --git a/src/components/computer-vision/ImageClassificationLesson.tsx b/src/components/computer-vision/ImageClassificationLesson.tsx index 00947b46..138574d6 100644 --- a/src/components/computer-vision/ImageClassificationLesson.tsx +++ b/src/components/computer-vision/ImageClassificationLesson.tsx @@ -1,5 +1,6 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards"; +import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; export function ImageClassificationLesson() { @@ -22,7 +23,7 @@ export function ImageClassificationLesson() {

    That narrowness is the whole design, not a limitation someone forgot to - fix. Detection and segmentation, two chapters ahead, exist specifically to + fix. Detection and segmentation, later in this track, exist specifically to answer the questions classification refuses to.

    @@ -52,13 +53,13 @@ export function ImageClassificationLesson() { title="What a confident wrong answer looks like" >

    - A well-known example: a model trained to tell huskies from wolves reported 97% - confidence on a photo of a wolf standing in a grassy field — correctly, this time, - identifying it as a wolf, but for the wrong reason entirely. In earlier tests the same - model had called wolves “husky” whenever the photo had snow in the - background, because most of its husky training photos happened to have snow in them - and most of its wolf photos did not. The model had learned to detect snow, not dogs, - and reported startling confidence while doing it. + A well-known demonstration from research on explaining classifiers: a model was + trained to tell huskies from wolves on photos where the wolves were nearly always + pictured against snow. It then labelled a husky standing in snow as a wolf. When the + researchers asked which parts of the image drove the decision, the answer was mostly + the snow, not the animal. The model had learned to detect snow, not wolves, and on + most of its test photos that shortcut happened to give the right answer — which is + exactly why nobody would have noticed from the accuracy alone.

    A confidence score describes how sure the model is, not how right it @@ -86,6 +87,39 @@ export function ImageClassificationLesson() { fine-grained categories — breeds of dog, species of bird — where the correct answer and the model’s honest second guess are easy to confuse.

    +

    + Four photos, six classes, and a model’s probabilities for each. Rank the guesses + and score them both ways. +

    + +

    + Only the first photo’s best guess is right, so top-1 accuracy is 25%. Every + correct answer is somewhere in the top three, so top-3 accuracy is 100%. Same model, + same probabilities. +

    - Right if the true label is anywhere in the model’s five best guesses. Always - the higher number, and quietly a lower bar. + Right if the true label is anywhere in the model’s five best guesses. Never + lower than top-1, and quietly a lower bar.

    ), }, diff --git a/src/components/computer-vision/ImagePreprocessingLesson.tsx b/src/components/computer-vision/ImagePreprocessingLesson.tsx index d0fde7dd..a83f0510 100644 --- a/src/components/computer-vision/ImagePreprocessingLesson.tsx +++ b/src/components/computer-vision/ImagePreprocessingLesson.tsx @@ -2,6 +2,7 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { TakeawayCard } from "@/components/learn/primitives/Cards"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; import { AugmentationPreview } from "@/components/computer-vision/AugmentationPreview"; +import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; export function ImagePreprocessingLesson() { return ( @@ -69,7 +70,9 @@ export function ImagePreprocessingLesson() { Normalising fixes the scale rather than the content: divide every pixel by 255 to land in the 0–1 range, or subtract the dataset’s mean and divide by its standard deviation so brightness differences between photos stop swamping the differences that actually - matter — edges, shapes, colour. + matter — edges, shapes, colour. If you use a dataset mean and standard deviation, + compute them from the training photos only, and reuse those same two numbers on every + validation, test and live image.

    @@ -101,6 +104,45 @@ export function ImagePreprocessingLesson() { place. + + First, an augmentation must not change the right answer. Rotate a handwritten 6 by 180 + degrees and it becomes a 9 that is still labelled 6; flip a photo of text left to right + and it stops being text. Pick only the transformations your real inputs could plausibly + go through. Second, augment the training set only. Validation and test photos should look + like the real inputs the model will meet, so they get resized and normalised, never + randomly rotated or relit. + +

    + Both halves of that in one run. Normalising uses numbers from the training photos only, + and then a 6 from the test set is rotated by 180 degrees. +

    + the model says {guess}")`} + /> +

    + The model reads the 6 correctly, and calls the rotated one a 9. If that rotation were + used as augmentation, the training set would be full of 9s labelled 6. +

    +
    diff --git a/src/components/computer-vision/ImageSegmentationLesson.tsx b/src/components/computer-vision/ImageSegmentationLesson.tsx index c4ce3aff..44a56be7 100644 --- a/src/components/computer-vision/ImageSegmentationLesson.tsx +++ b/src/components/computer-vision/ImageSegmentationLesson.tsx @@ -1,4 +1,5 @@ import { TakeawayCard } from "@/components/learn/primitives/Cards"; +import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; export function ImageSegmentationLesson() { @@ -63,6 +64,37 @@ export function ImageSegmentationLesson() { .

    +

    + A small semantic mask with two round dogs. First, how much of a box around one of them + is not dog; then, counting the dogs by finding connected blobs. +

    + +

    + 32 of the 81 pixels in the box are background. The blob count finds two dogs, but only + while they do not touch. Move them together and the same mask reports one. +

    diff --git a/src/components/computer-vision/ImagesAsNumbersLesson.tsx b/src/components/computer-vision/ImagesAsNumbersLesson.tsx index 0233857d..c7b69ec8 100644 --- a/src/components/computer-vision/ImagesAsNumbersLesson.tsx +++ b/src/components/computer-vision/ImagesAsNumbersLesson.tsx @@ -2,6 +2,7 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { TakeawayCard } from "@/components/learn/primitives/Cards"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; import { PixelZoom } from "@/components/computer-vision/PixelZoom"; +import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; export function ImagesAsNumbersLesson() { return ( @@ -35,7 +36,7 @@ export function ImagesAsNumbersLesson() { Click any square in the grid above and the value it shows is the entire content of that pixel — one integer, from 0 to 255, for a grayscale image. Nothing else is stored there. 0 is black, 255 is white, and everything between is a shade of grey with - no unit finer than a whole number: 255 possible steps and not one more. + no unit finer than a whole number: 256 possible values and not one more.

    A colour pixel is not one number, it is three — one each for red, green and blue, @@ -68,6 +69,36 @@ export function ImagesAsNumbersLesson() { times the numbers to store and four times the numbers a model has to process, for roughly twice the visible detail. +

    + Build a small face from nothing but numbers, then halve its resolution by averaging + each 2-by-2 block into one pixel. +

    + ", image.size, "numbers") +print(image) + +# Halve the resolution: average every 2-by-2 block into one pixel. +small = image.reshape(6, 2, 6, 2).mean(axis=(1, 3)).astype(np.uint8) +print(small.shape, "->", small.size, "numbers") +print(small) + +# Doubling width and height quadruples the count. +for width, height in [(500, 375), (1000, 750)]: + print(f"{width}x{height}: {width * height:,} pixels")`} + /> +

    + 144 numbers become 36, and the eyes and mouth smear into two greys. Change the 200 or + the 30 and rerun to see that the picture is nothing but those values. +

    - Average precision sidesteps the choice: instead of one threshold, take - the precision value at every point along the sweep and average them. It is a way of + Average precision sidesteps the choice: instead of one threshold, walk + down the sorted list and note the precision each time another real object is caught. + Add those up and divide by the number of real objects in the scene — so an object the + detector never found contributes zero. In the panel above that is (1 + 1 + 1 + 0.8 + + 0.83 + 0.75) / 8 ≈ 0.67. It is a way of scoring the whole trade-off curve with one number instead of committing to a threshold nobody agreed on in advance. Mean average precision then averages that score again, across every object class the detector was tested on — one AP for “pedestrian”, one for “bicycle”, one for “traffic light”, meaned into the single number that gets reported.

    +

    + The panel’s ten detections, walked down by hand. +

    + +

    + It prints the same 0.67. Flip one of the last two detections to True and see how much + a single late hit is worth. +

    @@ -82,7 +112,7 @@ export function MeanAveragePrecisionLesson() {

    It also treats every miss as equally costly, which is never true in practice. A detector that misses a parked car and one that misses a pedestrian stepping into the road produce - the same one-point deduction to AP, and only one of those two failures matters at + the same deduction from AP, and only one of those two failures matters at highway speed. A single mAP number is a fair summary of overall detection quality and a poor guide to which failures you can actually tolerate.

    diff --git a/src/components/computer-vision/NonMaxSuppressionLesson.tsx b/src/components/computer-vision/NonMaxSuppressionLesson.tsx index 8b1e6a2f..815b7ff1 100644 --- a/src/components/computer-vision/NonMaxSuppressionLesson.tsx +++ b/src/components/computer-vision/NonMaxSuppressionLesson.tsx @@ -1,6 +1,7 @@ import { TakeawayCard } from "@/components/learn/primitives/Cards"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; import { NmsThreshold } from "@/components/computer-vision/NmsThreshold"; +import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; export function NonMaxSuppressionLesson() { return ( @@ -48,6 +49,11 @@ export function NonMaxSuppressionLesson() { It is one dog, described twice. Suppressing the extra box loses nothing; keeping it would double-count the same animal in the final result.

    +

    + In practice this runs separately for each class. A box labelled “dog” never + suppresses a box labelled “person”, however much they overlap — someone + holding a puppy is two objects, not one described twice. +

    @@ -67,7 +73,43 @@ export function NonMaxSuppressionLesson() { survive, because none of them overlap each other by quite enough to trip the threshold, and your final output still reports several dogs where there is one.{" "} There is no threshold that is safe for every photo; it is tuned against - a validation set, the same way the IoU threshold in the last lesson was. + a validation set that looks like the scenes you expect. Crowded scenes, where real + objects genuinely overlap, usually want a higher threshold than sparse ones. +

    +

    + The six boxes from the interactive, run through the algorithm at three thresholds. All + of them are labelled dog, so every box is compared with every kept box. +

    + +

    + At 0.5 it keeps a and f, one box per dog. At 0.1 the second dog’s box f is + swallowed by a, and at 0.9 all six survive.

    diff --git a/src/components/computer-vision/ObjectDetectionLesson.tsx b/src/components/computer-vision/ObjectDetectionLesson.tsx index 1932130c..8d05fc01 100644 --- a/src/components/computer-vision/ObjectDetectionLesson.tsx +++ b/src/components/computer-vision/ObjectDetectionLesson.tsx @@ -54,9 +54,8 @@ export function ObjectDetectionLesson() { The next idea is to run the classifier again and again, on every possible rectangle the image could contain — every position, every width, every height. A modest 224×224 photo has tens of thousands of plausible box positions at just a handful of sizes; check every - size at every position and you are into the millions. That is a combinatorial explosion, - not a plan, and it is exactly the problem the next two lessons exist to avoid solving the - brute-force way. + size at every position and you are into the hundreds of millions. That is a combinatorial + explosion, not a plan, and it is why real detectors take a different route.

    diff --git a/src/components/computer-vision/OverfittingInVisionLesson.tsx b/src/components/computer-vision/OverfittingInVisionLesson.tsx index 90997eea..63caad92 100644 --- a/src/components/computer-vision/OverfittingInVisionLesson.tsx +++ b/src/components/computer-vision/OverfittingInVisionLesson.tsx @@ -88,8 +88,9 @@ export function OverfittingInVisionLesson() { being a defence against the actual signal in the photo.

    - “More augmentation is always better” is false in exactly the way “more - training data is always better” usually is not. Past the point where validation + More real training data rarely hurts. More augmentation can, because every extra unit + of strength moves the images further from anything the model will really see. Past the + point where validation accuracy peaks, every additional unit of augmentation strength is pure cost. Find that peak on validation data specifically — not on training accuracy, which will look fine right up until the augmentation is destroying the images. diff --git a/src/components/computer-vision/PixelsToPredictionsLesson.tsx b/src/components/computer-vision/PixelsToPredictionsLesson.tsx index 51f41c68..71c876bc 100644 --- a/src/components/computer-vision/PixelsToPredictionsLesson.tsx +++ b/src/components/computer-vision/PixelsToPredictionsLesson.tsx @@ -65,6 +65,38 @@ export function PixelsToPredictionsLesson() { +

    + The same failure shows up on real handwriting. This model gives every pixel of an + 8-by-8 digit its own weight, then is tested on digits nudged one or two pixels to the + right. +

    + +

    + It reads 95% of the digits as drawn, 40% after a one-pixel shift, and 9% after two. + Nothing about the digits changed except where they sit. +

    A convolution kernel, from the earlier chapter on filters, fixes exactly this failure. Instead of one independent weight per pixel position, a kernel is a small set of diff --git a/src/components/computer-vision/ThresholdCurve.tsx b/src/components/computer-vision/ThresholdCurve.tsx index 82bae3df..b91597e8 100644 --- a/src/components/computer-vision/ThresholdCurve.tsx +++ b/src/components/computer-vision/ThresholdCurve.tsx @@ -51,8 +51,18 @@ const CURVE: readonly CurvePoint[] = Array.from({ length: DETECTIONS.length + 1 }; }); +/** + * Standard (non-interpolated) average precision: the precision at each rank + * where a correct detection is added, summed and divided by the number of + * real objects. Objects that were never detected contribute zero, so the two + * missed objects pull AP down — averaging precision over every cut-off, + * correct or not, would ignore them. + */ const AVERAGE_PRECISION = - CURVE.slice(1).reduce((sum, point) => sum + (point.precision ?? 0), 0) / DETECTIONS.length; + CURVE.slice(1).reduce( + (sum, point, index) => (DETECTIONS[index].correct ? sum + (point.precision ?? 0) : sum), + 0, + ) / TOTAL_GROUND_TRUTH; /** The recall ceiling: even flagging every detection never recovers the two * ground-truth objects nothing was ever proposed for. */ diff --git a/src/components/computer-vision/TransferLearningLesson.tsx b/src/components/computer-vision/TransferLearningLesson.tsx index a9109a0b..591c6cd1 100644 --- a/src/components/computer-vision/TransferLearningLesson.tsx +++ b/src/components/computer-vision/TransferLearningLesson.tsx @@ -69,6 +69,14 @@ export function TransferLearningLesson() { up to the last, doing the seeing; the head is the final layer, doing the naming. Transfer learning keeps the body and swaps the head. +

    + Freezing everything is the cautious end of a dial. With a few thousand photos rather + than a few hundred, a common next step is fine-tuning: once the new + head has trained, unfreeze the last few layers of the body as well and keep training + with a small learning rate, so the later, more specific features can adjust to your + images without wiping out what the early layers already know. With very little data, + leave the body frozen; there is not enough to adjust it without overfitting. +

    - A car moving at highway speed covers roughly 30 metres every second. Convert that to + A car moving at highway speed — about 110 km/h — covers roughly 30 metres every + second. Convert that to something more concrete: a vision pipeline that takes 200 milliseconds to decide “object ahead, brake” has already let the car travel about 6 metres before the decision even exists, before the brakes have engaged at all. @@ -39,10 +40,10 @@ export function VisionInSelfDrivingCarsLesson() { it is measuring the same thing your eyes measure: visible light bouncing off surfaces.

    - That is why no production self-driving system trusts a camera by itself. Radar keeps + That is why most self-driving systems do not trust a camera by itself. Radar keeps working in rain, fog and darkness that would blind a camera, and measures distance and closing speed directly and precisely — but it is weak at telling you what kind of object - it found, a plastic bag and a small dog can look similar to it. Lidar gives precise 3D + it found, and a stationary car and an overhead sign can be hard for it to tell apart. Lidar gives precise 3D distance to every surface it hits regardless of lighting, at real hardware cost, and can struggle with dark or reflective surfaces that absorb or scatter its laser pulses.

    @@ -118,8 +119,8 @@ export function VisionInSelfDrivingCarsLesson() { +

    + You can look at that wall of numbers yourself. scikit-learn ships with a set of small + handwritten digits; here is the first one. +

    + +

    + The array is the image. The picture underneath is drawn from those same 64 numbers, + and nothing in them says “zero”. +

    diff --git a/src/components/courses/CourseCatalog.tsx b/src/components/courses/CourseCatalog.tsx index d8b61460..d6847b6a 100644 --- a/src/components/courses/CourseCatalog.tsx +++ b/src/components/courses/CourseCatalog.tsx @@ -1,9 +1,8 @@ "use client"; import { useMemo, useState, type ReactNode } from "react"; -import CountUp from "@/components/reactbits/CountUp"; import { CourseEntryProvider, CourseLink } from "@/components/courses/CourseEntry"; -import type { Enrolment, OutlineChapter, TopicId, TrackStats } from "@/components/courses/catalog"; +import type { Enrolment, OutlineChapter, TopicId } from "@/components/courses/catalog"; import { summarise, useProgressMap, type TrackProgress } from "@/components/learn/space/progress"; import type { LearnTrackId } from "@/lib/learn-types"; @@ -16,8 +15,6 @@ export interface CatalogItem { topicLabel: string; enrol: Enrolment[]; href: string; - stats: TrackStats; - duration: string; outline: OutlineChapter[]; cover: ReactNode; } @@ -78,12 +75,12 @@ export function CourseCatalog({ return ( {/* ---- Continue / start row ---------------------------------------- */} -
    +

    {hasProgress ? "Continue learning" : "Good places to start"}

    -

    +

    {hasProgress ? "Saved on this device" : "Free, interactive, and saved as you go"}

    @@ -164,7 +161,7 @@ export function CourseCatalog({ function ProgressBar({ value, className = "" }: { value: number; className?: string }) { return ( -
    diff --git a/src/components/courses/CourseEntry.tsx b/src/components/courses/CourseEntry.tsx index 660021c4..2905ed7f 100644 --- a/src/components/courses/CourseEntry.tsx +++ b/src/components/courses/CourseEntry.tsx @@ -9,8 +9,8 @@ import { flushSync } from "react-dom"; /** * The step from the catalogue into a course. * - * Clicking a course grows a moss panel out of the card until it fills the - * screen, then navigates. The learning space's bar is the same moss, so the + * Clicking a course grows a mint panel out of the card until it fills the + * screen, then navigates. The learning space's bar is the same mint, so the * panel hands straight over to it. About half a second, start to finish. * * It is an enhancement on an ordinary link: modified clicks (new tab, new @@ -137,7 +137,7 @@ export function CourseEntryProvider({ children }: { children: React.ReactNode }) {active && ( -

    Entering course

    +

    Entering course

    {active.title}

    {/* Only shows if the next page is slow to arrive. */} +

    {DAYS_REMOVED} days out of {TOTAL_DAYS.toString()} trading days — a tiny fraction of the - whole period — account for the entire gap between these two numbers. + whole period — account for the entire gap between these two numbers. The daily returns + here are simulated to resemble a broad index fund, not taken from real market history.

    ); diff --git a/src/components/financial-literacy/NeedsVsWantsLesson.tsx b/src/components/financial-literacy/NeedsVsWantsLesson.tsx index b6aeb711..146d55e2 100644 --- a/src/components/financial-literacy/NeedsVsWantsLesson.tsx +++ b/src/components/financial-literacy/NeedsVsWantsLesson.tsx @@ -23,7 +23,7 @@ export function NeedsVsWantsLesson() {

    That test is stricter than it feels. A {formatCurrency(6)}-a-day coffee habit adds up - to about {formatCurrency(165)} a month — real money, and a real routine — but it fails + to about {formatCurrency(180)} a month — real money, and a real routine — but it fails the test cleanly. Skip it for a week and nothing breaks except your morning habit. The question was never how much you want something. It was always what happens if you don't get it. diff --git a/src/components/financial-literacy/OpportunityCostChart.tsx b/src/components/financial-literacy/OpportunityCostChart.tsx index 96a8fa0d..16b3ae72 100644 --- a/src/components/financial-literacy/OpportunityCostChart.tsx +++ b/src/components/financial-literacy/OpportunityCostChart.tsx @@ -50,7 +50,7 @@ export function OpportunityCostChart() { id={priceId} type="range" min={200} - max={10000} + max={40000} step={100} value={price} onChange={(event) => setPrice(Number(event.target.value))} diff --git a/src/components/financial-literacy/RetirementAccountsLesson.tsx b/src/components/financial-literacy/RetirementAccountsLesson.tsx index 2e892c85..6af64e11 100644 --- a/src/components/financial-literacy/RetirementAccountsLesson.tsx +++ b/src/components/financial-literacy/RetirementAccountsLesson.tsx @@ -18,8 +18,8 @@ export function RetirementAccountsLesson() { individually) are both containers, not investments. Inside either one, you still choose stocks, bonds, or funds — the same building blocks from two chapters ago. What the container adds is a tax rule: a traditional account reduces your taxable income now and - taxes withdrawals in retirement; a Roth account is taxed now and withdrawals are entirely - tax-free later. + taxes withdrawals in retirement; a Roth account is taxed now and qualified withdrawals in + retirement are entirely tax-free.

    Nothing about that mechanism is uniquely American, even though the names are. Whatever @@ -37,8 +37,9 @@ export function RetirementAccountsLesson() { traditional account and the full $100 goes in — no tax paid now — but withdrawals in retirement get taxed as ordinary income at whatever rate applies then. Contribute it to a Roth account instead and you pay the 22% first, - landing about $78 in the account, but every dollar it grows into later comes out - completely untaxed. + landing about $78 in the account, but every dollar it grows into comes out completely + untaxed in retirement, as long as the account's rules for qualified withdrawals are + met.

    If your tax rate is identical at contribution and at withdrawal, the two options land in @@ -66,8 +67,8 @@ export function RetirementAccountsLesson() { tone: "neutral", children: (

    - Contribution is taxed now, so less of it lands in the account. Withdrawals in - retirement are entirely tax-free. Favours a tax rate later that is the same or + Contribution is taxed now, so less of it lands in the account. Qualified + withdrawals in retirement are entirely tax-free. Favours a tax rate later that is the same or higher than now.

    ), diff --git a/src/components/financial-literacy/RiskAndDiversificationLesson.tsx b/src/components/financial-literacy/RiskAndDiversificationLesson.tsx index a69ab81c..9c72d357 100644 --- a/src/components/financial-literacy/RiskAndDiversificationLesson.tsx +++ b/src/components/financial-literacy/RiskAndDiversificationLesson.tsx @@ -116,9 +116,9 @@ export function RiskAndDiversificationLesson() {

    Systematic risk — also called market risk — is the part that hits - nearly everything at once: a recession, a spike in interest rates, a war, a pandemic. In - 2008, broad stock indices fell by roughly half across nearly every industry and nearly - every country simultaneously. Owning twenty companies instead of one did nothing to + nearly everything at once: a recession, a spike in interest rates, a war, a pandemic. In the + 2007–2009 financial crisis, broad stock indices fell by roughly half from peak to trough, + across nearly every industry and nearly every country at once. Owning twenty companies instead of one did nothing to soften that, because the source of the risk was never any individual company to begin with.

    diff --git a/src/components/financial-literacy/StatementSimulator.tsx b/src/components/financial-literacy/StatementSimulator.tsx index f758ce0c..81749dfe 100644 --- a/src/components/financial-literacy/StatementSimulator.tsx +++ b/src/components/financial-literacy/StatementSimulator.tsx @@ -101,7 +101,7 @@ export function StatementSimulator() {

    {choice === "full" - ? `Paid in full before the due date, so the ${formatPercent(APR, 2)} APR never applies — this purchase ends up costing exactly its sticker price.` + ? `Paid in full before the due date, so the ${formatPercent(APR, 2)} APR never applies — these purchases end up costing exactly their sticker prices.` : `Paying only the ${formatCurrency(MIN_PAYMENT)} minimum leaves ${formatCurrency(remaining)} carrying over, and ${formatPercent(APR, 2)} APR adds ${formatCurrency(interest)} in interest before next month's statement even opens.`}

    diff --git a/src/components/financial-literacy/TaxesTheBasicsLesson.tsx b/src/components/financial-literacy/TaxesTheBasicsLesson.tsx index beb06b87..1fef2b42 100644 --- a/src/components/financial-literacy/TaxesTheBasicsLesson.tsx +++ b/src/components/financial-literacy/TaxesTheBasicsLesson.tsx @@ -18,12 +18,15 @@ export function TaxesTheBasicsLesson() {

    The US uses a marginal tax system: income is sliced into bands, and each - band is taxed only at its own rate. Someone earning $60,000 doesn't pay one rate on - the full amount — the first slice is taxed at 10%, the next slice at 12%, and so on, only + band is taxed only at its own rate. Someone with $60,000 of taxable income — what's + left after deductions like the standard deduction — doesn't pay one rate on the + full amount — the first slice is taxed at 10%, the next slice at 12%, and so on, only up to wherever their income actually stops.

    - Run the actual numbers for that $60,000. The first $11,600 is taxed at 10%, which is + Run the actual numbers for that $60,000, using the 2024 single-filer brackets (the + thresholds are adjusted for inflation every year, so check the current ones). The first + $11,600 is taxed at 10%, which is $1,160. The next $35,550, up to $47,150, is taxed at 12%, which is $4,266. The remaining $12,850, up to the full $60,000, is taxed at 22%, which is $2,827. Add the three slices together — $1,160 plus $4,266 plus $2,827 — and the total tax bill is $8,253, not the @@ -34,16 +37,18 @@ export function TaxesTheBasicsLesson() {

    Your marginal rate is the rate on your next dollar earned. Your{" "} - effective rate is total tax divided by total income — a blend of every + effective rate is total tax divided by income — a blend of every bracket you passed through on the way up. The effective rate is always lower than the marginal rate, often by a wide margin, because the earlier, lower-taxed slices are still part of the average.

    - For the $60,000 example above, that's $8,253 in tax divided by $60,000 in income — - an effective rate of about 13.8%, even though the marginal rate sitting on the last - dollar earned is 22%. Nobody actually pays 22% of their income in this scenario; they pay - 13.8% of it, and the 22% only describes what the next dollar would face. + For the $60,000 example above, that's $8,253 in tax divided by $60,000 of taxable + income — an effective rate of about 13.8% on taxable income, even though the marginal + rate sitting on the last dollar earned is 22%. Measured against total income it is lower + still: if this person took the 2024 standard deduction of $14,600, they earned $74,600, + and $8,253 is about 11.1% of that. Either way, nobody pays 22% of their income here; the + 22% only describes what the next dollar would face.

    @@ -99,6 +104,11 @@ export function TaxesTheBasicsLesson() { some benefit with its own separate income cutoff out of reach, which is a real consideration, but a completely different mechanism from the tax bracket itself.

    + + Set the slider above to $45,000, then to $50,000. Only the $2,850 that crossed $47,150 + moves into the 22% bracket; the tax on that slice rises from 12% to 22%, an extra $285. + The other $47,150 is taxed exactly as before, which is why take-home pay still goes up. + Some tax credits and government benefits do phase out above certain income thresholds, and that can offset a raise's value. That's a separate, real @@ -144,7 +154,7 @@ export function TaxesTheBasicsLesson() {

    - There is a second, quieter mechanic working against you: because the minimum is a{" "} - percentage of the balance, it shrinks along with the balance. A balance that - starts at {formatCurrency(1000)} might carry a minimum near {formatCurrency(35)}. Once - interest has eaten away at the progress and the balance is down to {formatCurrency(700)}, - the minimum recalculates too — smaller, at the same percentage — which is part of why the - final stretch of a minimum-only payoff takes so much longer than the first stretch. + There is a second, quieter mechanic working against you on larger balances: because the + minimum is a percentage of the balance, it shrinks along with the balance. At + 2%, a {formatCurrency(5000)} balance carries a {formatCurrency(100)} minimum; by the time + it's down to {formatCurrency(3000)}, the minimum has recalculated to{" "} + {formatCurrency(60)}. Every step of progress makes the next required payment smaller, + which is exactly why a minimum-only payoff drags on. +

    +

    + On the {formatCurrency(1000)} balance in the chart below, the{" "} + {formatCurrency(25)} floor is what sets the minimum instead (2% of{" "} + {formatCurrency(1000)} is only {formatCurrency(20)}). Work out the first month:{" "} + {formatPercent(22.99, 2)} ÷ 12 is about {formatPercent(1.92, 2)}, so roughly{" "} + {formatCurrency(19.16, 2)} of interest accrues. Of the {formatCurrency(25)} payment, only + about {formatCurrency(5.84, 2)} actually reduces what you owe.

    diff --git a/src/components/financial-literacy/WhatACreditScoreActuallyMeasuresLesson.tsx b/src/components/financial-literacy/WhatACreditScoreActuallyMeasuresLesson.tsx index cd2c1d96..3f88847f 100644 --- a/src/components/financial-literacy/WhatACreditScoreActuallyMeasuresLesson.tsx +++ b/src/components/financial-literacy/WhatACreditScoreActuallyMeasuresLesson.tsx @@ -116,7 +116,8 @@ export function WhatACreditScoreActuallyMeasuresLesson() {

    Two beliefs about credit scores are common, confidently repeated, and wrong. Both lead people to either waste money or avoid a useful habit out of caution that - isn't earned. + isn't earned — and the second one clears up once you know what actually does + count as a hard pull.

    A handful of other files get special treatment on GitHub, all of them optional and all of - them ordinary files in the repository — most can live at the root or in a{" "} - .github/ directory to keep the root tidy. + them ordinary files in the repository. LICENSE belongs at the root; most of the others can + live there or in a .github/ directory to keep the root tidy.

    This surprises people and it is worth being blunt about. Code on GitHub with no licence file is not open source. Copyright applies by default, and the default is that - nobody may copy, modify, or use it. Making a repository public grants permission to view - it, and only because you agreed to GitHub's terms. + nobody may copy, modify, or use it. Making a repository public lets people view and fork it + on GitHub, because you agreed to GitHub's terms — and nothing more.

    A licence is how you grant the rest. There is no need to write one — pick a standard one, @@ -141,8 +141,8 @@ git switch --detach v1.2.0 # look at the code as it was at that release

    A release is a GitHub feature built on top of a tag. It adds release - notes, downloadable binaries, and a pre-release flag. Every release has a tag; most tags are - not releases. + notes, downloadable binaries, and a pre-release flag. Every release has a tag; not every tag is + a release.

    Network — a visualisation of every fork and branch that is the fastest way to see whether a fork went somewhere the original did not.{" "} Security holds Dependabot alerts for known-vulnerable dependencies, secret - scanning, and code scanning. On a public repository most of it is free and off by default. + scanning, and code scanning. On a public repository these are free; secret scanning is on by default, and Dependabot + alerts are worth switching on.

    - The simplest model that supports review, and by a wide margin the most common on GitHub. One + The simplest model that supports review, and a very common one on GitHub. One permanent branch — main, always deployable — and short-lived branches off it.

    ;`} develop branch, in particular, is pure overhead when main is deployed the moment something merges.

    - - It was adopted almost universally on the strength of one very clear illustration, by an - enormous number of teams who ship continuously and have no supported old versions. If you + + It was adopted widely on the strength of one very clear illustration, including by many + teams who ship continuously and have no supported old versions. If you are using it, be able to say which of its branches solves a problem you actually have. If the answer is none, you are paying for machinery in exchange for nothing. diff --git a/src/components/github/IgnoringFilesLesson.tsx b/src/components/github/IgnoringFilesLesson.tsx index 90227c99..bbd90fc1 100644 --- a/src/components/github/IgnoringFilesLesson.tsx +++ b/src/components/github/IgnoringFilesLesson.tsx @@ -23,13 +23,26 @@ export function IgnoringFilesLesson() {

    Three rules do almost all the work, and the third one surprises everybody. @@ -174,7 +187,7 @@ RESEND_API_KEY=`}

    - Check first — you may already have it. macOS ships a Git, and most Linux distributions - install one by default. + Check first — you may already have it. macOS offers to install Apple's Git the first + time you type the command, and many Linux distributions include one.

    @@ -111,8 +111,8 @@ git config --global core.editor nano`} Press Esc, then type{" "} :wq and press Enter to save and quit, or :q! to - quit without saving. This is one of the most-searched programming questions of - all time. + quit without saving. Being stuck here is a famously common first experience, so do + not feel bad about it. diff --git a/src/components/github/IssuesAndTrackingLesson.tsx b/src/components/github/IssuesAndTrackingLesson.tsx index 4897601e..a76790dd 100644 --- a/src/components/github/IssuesAndTrackingLesson.tsx +++ b/src/components/github/IssuesAndTrackingLesson.tsx @@ -197,8 +197,8 @@ body: {" "} can set{" "} blank_issues_enabled: false{" "} - and add links to Discussions, the docs, or a chat. Most projects find that half their issue - volume was questions, and pointing those somewhere better helps both sides. + and add links to Discussions, the docs, or a chat. On many projects a large share of issues turn + out to be questions, and pointing those somewhere better helps both sides. diff --git a/src/components/github/MergeConflictsLesson.tsx b/src/components/github/MergeConflictsLesson.tsx index 9d718629..7e3a68d5 100644 --- a/src/components/github/MergeConflictsLesson.tsx +++ b/src/components/github/MergeConflictsLesson.tsx @@ -205,8 +205,8 @@ git cherry-pick --abort # a conflicted cherry-pick`} {" "} switches on "reuse recorded resolution". Git records how you resolved each conflict and replays that resolution automatically when it sees the same one again — which - happens constantly if you rebase a long-lived branch repeatedly. It is off by default and - almost everybody who turns it on keeps it on. + happens constantly if you rebase a long-lived branch repeatedly. It is off by default, so + you have to switch it on yourself. diff --git a/src/components/github/MergingAPullRequestLesson.tsx b/src/components/github/MergingAPullRequestLesson.tsx index 2e7edf14..3e866ed4 100644 --- a/src/components/github/MergingAPullRequestLesson.tsx +++ b/src/components/github/MergingAPullRequestLesson.tsx @@ -68,8 +68,9 @@ export function MergingAPullRequestLesson() { commits are not merged; they stay on the branch, which is usually then deleted.

    - This is the most popular option on GitHub by a wide margin, and the reason is worth stating - plainly: every commit on main builds and passes. Bisect becomes reliable, + Many teams default to this option, and the reason is worth stating plainly: when the build + and the tests are required checks that gate every change to main,{" "} + every commit on main has passed them. Bisect becomes reliable, reverting is one commit with no flags, and the log reads as a list of features rather than a list of afternoons.

    @@ -130,7 +131,7 @@ rows and aborted the download. Fixes #482.`} And afterwards: delete the branch. GitHub offers a button and a setting to do it automatically, and the commits are safely in main either way. If you need it back, the - Restore branch button on the pull request works for months. + Restore branch button on the pull request brings it back.

    Whether that is good depends on your taste. Some teams want a clean straight line; others - want the record that these three commits were one piece of work reviewed together. Git + want the record that these commits were one piece of work reviewed together. Git lets you insist on the record:

    - M is a merge commit, and it is the only kind of commit with two parents. + M is a merge commit, and it is the only kind of commit with more than one + parent. It contains the combined result, it records that these two lines of development joined here, and Git writes its message for you.

    @@ -231,7 +232,7 @@ git branch -d fix/login # safe delete: refuses if the work is NOT merged`} "Stand on main and merge the branch to publish work; stand on the branch and merge main to catch up.", "A fast-forward happens when the target has not moved: no commit is created, the label slides.", "--no-ff forces a merge commit anyway; --ff-only refuses to merge unless it can fast-forward.", - "A three-way merge builds a merge commit — the only commit with two parents.", + "A three-way merge builds a merge commit — the only kind of commit with more than one parent.", "The merge base is the most recent shared commit, and it is what lets Git tell an addition from a deletion.", "A line changed on one side is taken silently. A line changed on both sides is a conflict.", "git merge --abort undoes a merge in progress completely.", diff --git a/src/components/github/OpeningAPullRequestLesson.tsx b/src/components/github/OpeningAPullRequestLesson.tsx index c2e7fdcc..4e9e283b 100644 --- a/src/components/github/OpeningAPullRequestLesson.tsx +++ b/src/components/github/OpeningAPullRequestLesson.tsx @@ -206,7 +206,7 @@ gh pr ready # mark it ready when it is`} }, { label: "The commit tested never existed", - text: "The tested commit is a temporary merge that is not on any branch. This is why a pull request can go red without you pushing anything.", + text: "The tested commit is a temporary merge that is not on any branch. Re-running an old run tests that same merge again. But when main moves, GitHub builds a fresh merge, and the new check run on it can go red without you pushing anything.", }, { label: "Required vs optional", @@ -249,7 +249,7 @@ gh pr view --web # open the failing run's logs`} "The description is read by more people than the diff. Say why, and say what you are unsure about.", "A draft pull request cannot be merged and does not request reviewers — good from day one of the work.", "The merge button is gated by required checks, no outstanding changes requested, and enough approvals.", - "Checks run against a temporary merge with the base, not your branch, so a pull request can go red with no push.", + "Checks run against a temporary merge with the base, not your branch, so when main moves, a fresh check run can go red with no push from you.", "Small pull requests get reviewed. Large ones get approved.", ]} /> diff --git a/src/components/github/ReadingHistoryLesson.tsx b/src/components/github/ReadingHistoryLesson.tsx index 8038c221..c07536bb 100644 --- a/src/components/github/ReadingHistoryLesson.tsx +++ b/src/components/github/ReadingHistoryLesson.tsx @@ -108,7 +108,7 @@ git log -S "loadUser"`} { label: "git diff", text: "Working tree against the index. What you have changed and NOT staged. Silent if everything is staged." }, { label: "--staged", text: "Index against HEAD. Exactly what your next commit will contain. Read this before every commit." }, { label: "HEAD", text: "Working tree against the last commit. Everything you have done since, staged or not." }, - { label: "a..b", text: "Any two commits, branches, or tags. git diff main..fix/login shows what the branch adds." }, + { label: "a..b", text: "Any two commits, branches, or tags, compared tip to tip. git diff main..fix/login is the same as git diff main fix/login." }, ]} /> diff --git a/src/components/github/RebaseAndHistoryLesson.tsx b/src/components/github/RebaseAndHistoryLesson.tsx index be02f8bd..7f6735b4 100644 --- a/src/components/github/RebaseAndHistoryLesson.tsx +++ b/src/components/github/RebaseAndHistoryLesson.tsx @@ -20,7 +20,7 @@ export function RebaseAndHistoryLesson() {

    A rebase takes each of your commits in turn, computes the change it made, and applies that change on top of a different commit. The result is a new commit with the same message, the - same author, the same content — and a different hash, because the parent is different and + same author, the same change — and a different hash, because the parent is different and the hash covers the parent.

    @@ -112,7 +112,8 @@ git rebase main lineTones={{ 0: "ok", 1: "ok", 2: "err", 3: "err" }} />

    - Every commit is now duplicated. If they merge, both copies land and the diff applies twice. + Every commit is now duplicated. If they merge, both copies end up in the history side by + side, and anything they built on the originals is tangled up with your rewritten ones. Untangling this is unpleasant and it is always somebody else's afternoon, not yours.

    diff --git a/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx b/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx index 7ec14861..a0d9de90 100644 --- a/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx +++ b/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx @@ -180,8 +180,8 @@ Untracked files: variant="terminal" code={`# Same information, one line per file, once you know the letters git status --short -# M src/auth/redirect.ts staged modification -# M src/lib/users.ts modified, not staged +# M src/auth/redirect.ts left column: staged +# M src/lib/users.ts right column: modified, not staged # ?? notes.md untracked`} /> @@ -205,12 +205,13 @@ git status --short code={`git add report.md # index now matches disk # ... you keep typing ... git status --short -# M report.md staged: the version from the git add -# M report.md not staged: everything you typed since`} +# MM report.md +# left M: a staged version, from the git add +# right M: newer edits on disk, not staged`} />

    - The same file appears twice, because there are two different versions of it. The - fix is to git add again before committing. This is not a bug and it is not + The file carries two letters, one per column, because there are two different versions of + it — and in the full git status it is listed under both headings. The fix is to git add again before committing. This is not a bug and it is not a trap — it is exactly the behaviour that makes staging useful — but it is the most common source of "I committed it and the change is not there".

    @@ -220,6 +221,25 @@ git status --short every commit catches the half-staged file, the stray debug print, and the accidentally pasted password — in that order of frequency.
    +

    + Try it yourself. Make a throwaway repository and watch one file move + through the three places. The comments show the expected output from the status and diff commands. +

    + notes.txt +git status --short # ?? notes.txt untracked +git add notes.txt +git status --short # A notes.txt staged as a new file +echo "two" >> notes.txt +git status --short # AM notes.txt staged, then changed again +git diff --staged # shows only the line "one" +git add notes.txt +git commit -m "Add notes" +git status --short # (nothing: all three places agree)`} + /> - Almost every leaked credential on GitHub arrived by way of{" "} + A very common way credentials leak onto GitHub is{" "} git add . catching a file the author had forgotten existed. Running{" "} git status first takes @@ -61,7 +61,7 @@ git restore --staged . # unstage everything, keeping every edit`}

    This looks like arbitrary pedantry and it is not. Git itself writes messages in the - imperative when it generates them — "Merge branch feature into main", "Revert - Add the caching layer". Your messages sit in the same list, and matching the mood makes + imperative when it generates them — Merge branch 'feature',{" "} + Revert "Add the caching layer". Your messages sit in the same list, and matching the mood makes the log read as one document rather than a pile of styles.

    diff --git a/src/components/github/UndoingThingsLesson.tsx b/src/components/github/UndoingThingsLesson.tsx index c6b8ea03..46a03f07 100644 --- a/src/components/github/UndoingThingsLesson.tsx +++ b/src/components/github/UndoingThingsLesson.tsx @@ -2,6 +2,7 @@ import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/Le import { Callout } from "@/components/learn/primitives/Callout"; import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { CompareGrid, LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; import { StepList } from "@/components/learn/primitives/StepList"; import { UndoChooser } from "@/components/github/UndoChooser"; @@ -19,9 +20,8 @@ export function UndoingThingsLesson() { title="Name what you regret before picking a command" >

    - This chapter exists because the top search result for "git undo" is a Stack - Overflow answer with eleven commands and forty thousand upvotes, and running the wrong one - of them destroys work. + This chapter exists because searching for "git undo" turns up long answers + listing many commands side by side, and running the wrong one of them destroys work.

    The reliable method is to stop and say out loud what you want to lose. There are only six @@ -32,13 +32,13 @@ export function UndoingThingsLesson() {

    - git restore overwrites a file in your working tree with the version from - the last commit. Whatever you had typed is gone — not in the index, not in a commit, not in + git restore overwrites a file in your working tree with the version in + the index — which is the last commit, unless you had staged a newer version. Whatever you had typed is gone — not in the index, not in a commit, not in the reflog. Gone.

    @@ -191,7 +191,7 @@ git revert HEAD # undo the very last commit, safely`} + + You pushed a commit to main yesterday, two teammates have pulled it since, and today + you find it broke the login page. Which of restore, reset and revert do you reach + for, and why not the other two? + + } + detailTag="Answer" + detail={ + <> + git revert on that commit, then push. It adds a new commit that + undoes the change, so nobody's history is rewritten. Reset would move main + backwards under your teammates and force them to untangle it. Restore only touches + files in your working tree; it cannot undo a commit that is already shared. + + } + openLabel="Show the answer" + closeLabel="Hide the answer" + /> +

    One file per branch, each containing one commit hash and a newline. Forty-one bytes. That diff --git a/src/components/github/WhyVersionControlLesson.tsx b/src/components/github/WhyVersionControlLesson.tsx index 41989e5e..b0cee3a2 100644 --- a/src/components/github/WhyVersionControlLesson.tsx +++ b/src/components/github/WhyVersionControlLesson.tsx @@ -57,8 +57,8 @@ site-final-USE-THIS-ONE (copy)/`} />

    Git answers all four, and the price is learning a handful of ideas that are - strange the first time. It is worth it — this is the tool every professional developer on - earth uses, every day, and it has been the standard for twenty years. + strange the first time. It is worth it — this is the tool nearly every software team uses, + every day, and it has been around since 2005.

    diff --git a/src/components/health-in-tech/AiAssistedDiagnosisLesson.tsx b/src/components/health-in-tech/AiAssistedDiagnosisLesson.tsx index ead1feda..0c930499 100644 --- a/src/components/health-in-tech/AiAssistedDiagnosisLesson.tsx +++ b/src/components/health-in-tech/AiAssistedDiagnosisLesson.tsx @@ -27,8 +27,8 @@ export function AiAssistedDiagnosisLesson() { actual deployed shape almost everywhere one of these tools is in clinical use today. A model that is wrong in a way a busy clinician would catch is an acceptable cost of doing business; a model that is wrong with nobody checking is a different kind of product - entirely, and regulators have been explicit that the second one is not what gets - approved for anything but the narrowest, lowest-stakes uses. + entirely, and regulators have so far authorised that second kind only for a handful of + narrow, tightly scoped screening tasks.

    @@ -46,10 +46,12 @@ export function AiAssistedDiagnosisLesson() {

    Two systems can share the exact same underlying number and behave completely differently - once a hospital deploys them, because the number itself commits to nothing. A model that - says 0.61 has not said “probably positive” or “probably + once a hospital deploys them, because the number itself commits to nothing. A well-calibrated + model that says 0.61 has not said “probably positive” or “probably negative” — it has said “more likely than not, by not very much,” and it is entirely up to the people deploying it to decide how much weight that deserves. + (Many models' raw scores aren't even calibrated probabilities, which is one + more reason the score alone commits to nothing.)

    @@ -147,6 +149,12 @@ Positive predictive value: 90 / 1,080 ≈ 8%`} catch more true cases at a low prevalence still returns mostly false alarms — it just returns a different mix of them.

    + + Run the same 90%-sensitive, 90%-specific test on 10,000 people where prevalence is 10%. + That's 1,000 sick people, so 900 true positives; and 9,000 healthy people, so 900 + false positives. Of 1,800 flags, 900 are real — a positive predictive value of 50%, a + coin flip, from a test whose spec sheet never changed. + @@ -87,9 +87,8 @@ export function BiasAndErrorInMedicalAiLesson() { title="What a sensor or a dataset can quietly leave out" >

    - A proxy variable standing in for illness is one mechanism. Two more, both well - documented and both simpler than anything involving a learned model, so learn them - by name. + A proxy variable standing in for illness is one mechanism. Two more are both well + documented, and both are simpler than anything involving a learned model.

    Data: a short daily symptom check — breathlessness, swelling, - weight — plus whatever vitals a home blood-pressure cuff already reports.{" "} - Where it lives: the vitals come from a consumer wearable, - wellness-grade under Part 3's distinction, not medical-grade; the symptom - answers are typed in by hand. Who sees it: the patient sees their + weight — plus whatever a home blood-pressure cuff already reports.{" "} + Where it lives: the blood pressure and weight come from a cuff and a + scale the patient already owns at home. Owning the device is not what decides how far + to trust it — the specific model's validation, clearance and intended use do. A + validated home cuff used as directed can give readings a clinician acts on; an + unvalidated one only gives a trend to watch. So the app records which device each + reading came from, and the care team decides which ones count. The symptom answers + are typed in by hand. Who sees it: the patient sees their own trend; a nurse on the discharging team sees flagged entries only, not the full daily log; nobody else does without the patient's consent.{" "} AI and the human: a model flags an entry as worth a nurse's attention; it never contacts emergency services or changes medication on its own — a nurse decides what happens next, every time.{" "} Who gets left out: a patient without a smartphone or reliable data - plan, handled here with a weekly automated phone call covering the same three - questions, read out loud instead of tapped in. + plan, handled here with a daily automated phone call covering the same three + questions, read out loud and answered on the keypad instead of tapped in. } footnote="Notice that every answer above is a specific fact, not a description of how good the idea sounds. That's what makes it checkable against the list below." @@ -136,7 +140,7 @@ export function CapstoneMappingAHealthTechIdeaLesson() { title="What this track was actually teaching you to notice" >

    - Twenty-four chapters ago, this track opened with a claim: health tech is not four + Twenty-four chapters ago, this track opened with a claim: health tech is not six separate topics, it is one connected system, and every part of it changes shape the moment it touches an actual patient. The exercise you just ran is the proof of that claim, not a summary of it. You didn't just sketch an app — you touched every diff --git a/src/components/health-in-tech/CybersecurityInHealthcareLesson.tsx b/src/components/health-in-tech/CybersecurityInHealthcareLesson.tsx index b1581deb..91d59ced 100644 --- a/src/components/health-in-tech/CybersecurityInHealthcareLesson.tsx +++ b/src/components/health-in-tech/CybersecurityInHealthcareLesson.tsx @@ -21,9 +21,8 @@ export function CybersecurityInHealthcareLesson() { Ransomware works by locking an organisation out of its own systems until it pays. That threat only has teeth if the organisation cannot simply wait it out — and a hospital, unlike almost any other kind of business, cannot pause patient care for a - week while IT rebuilds servers from backup. Attackers know this. It is exactly why - healthcare gets targeted disproportionately relative to how much money actually flows - through it. + week while IT rebuilds servers from backup. Attackers know this, and it is exactly why + healthcare is such an attractive target.

    The way in is rarely a sophisticated exploit. It is a phishing email, and clinical @@ -45,11 +44,13 @@ export function CybersecurityInHealthcareLesson() {

    Patch a laptop and the update finishes in minutes. Patch an MRI machine, and a hospital often cannot do it at all. Medical imaging and monitoring equipment routinely - runs for fifteen to twenty years, frequently on an operating system its vendor stopped - supporting long ago, because changing the software of a certified medical device can - trigger a fresh regulatory review before it is allowed back into service. Updating it - is not the routine, low-stakes patch it would be on an ordinary office computer — it is - closer to re-certifying the device from scratch. + stays in service for well over a decade, frequently on an operating system that stopped + getting security updates long ago. The hospital usually isn't allowed to patch it + on its own: the device maker controls the software, has to test every change against + the device's validated, cleared configuration before releasing it, and may stop + supporting older models entirely. US regulators have said routine security patches + generally don't need a fresh review — but a fix nobody ships is a fix the hospital + never gets.

    The result is a building full of machines nobody can safely update, sitting on the @@ -147,7 +148,7 @@ export function CybersecurityInHealthcareLesson() { items={[ "Hospitals are a disproportionate ransomware target because they cannot pause patient care to wait out an attack the way most businesses can.", "Attackers targeting healthcare aim at urgency, not carelessness — clinical staff working under time pressure are primed to act fast on anything marked urgent, which is exactly the instinct phishing depends on.", - "Legacy imaging and monitoring equipment often can't be patched at all, because changing a certified medical device's software can trigger a fresh regulatory review, leaving networks full of machines nobody can safely update.", + "Legacy imaging and monitoring equipment often can't be patched by the hospital at all — the device maker controls and validates every software change, and may stop supporting older models — leaving networks full of machines nobody can safely update.", "Staff training, network segmentation, and offline tested backups stop most of these attacks before they start, and none of the three are exotic or expensive relative to a single ransom payment.", "The real cost of hospital downtime isn't a dollar figure — it's a diverted ambulance and a delayed diagnosis, neither of which gets undone once the systems come back online.", ]} diff --git a/src/components/health-in-tech/DigitalDivideChart.tsx b/src/components/health-in-tech/DigitalDivideChart.tsx index 6a93d626..65c55f4c 100644 --- a/src/components/health-in-tech/DigitalDivideChart.tsx +++ b/src/components/health-in-tech/DigitalDivideChart.tsx @@ -57,7 +57,8 @@ export function DigitalDivideChart() { return (

    - Share of households with both broadband and a personal device + Share of households with both broadband and a personal device — illustrative, simulated + figures
    diff --git a/src/components/health-in-tech/DrugDiscoveryAndAiLesson.tsx b/src/components/health-in-tech/DrugDiscoveryAndAiLesson.tsx index 56da6189..4716bd3b 100644 --- a/src/components/health-in-tech/DrugDiscoveryAndAiLesson.tsx +++ b/src/components/health-in-tech/DrugDiscoveryAndAiLesson.tsx @@ -72,16 +72,15 @@ export function DrugDiscoveryAndAiLesson() {

    Both are real, and both are also two of the narrowest stages in the pipeline above — which is exactly why the improvement doesn't show up as a shorter overall timeline - yet. Be precise about which tool did which job before crediting AI with the whole - pipeline. + yet. Before crediting AI with a whole new drug, ask which stage it actually sped up.

    - DeepMind's AlphaFold is a well-known example of AI in this space, and - be exact about what it did, because the popular version of the story - credits it with more than it delivered. Predicting the three-dimensional shape a protein + DeepMind's AlphaFold is a well-known example of AI in this space, and it is + worth being exact about what it did, because the popular version of the story credits + it with more than it delivered. Predicting the three-dimensional shape a protein folds into, from nothing but the sequence of amino acids that make it up, was an open problem biologists had chased for decades. Solving it well enough to compete with a physical lab measurement was a scientific breakthrough, and the resulting @@ -101,8 +100,8 @@ export function DrugDiscoveryAndAiLesson() { children: (

    Given a protein's sequence, predicting the shape it physically folds into — - to an accuracy that rivals a lab measurement, for the vast majority of proteins - ever catalogued. + often to an accuracy that rivals a lab measurement, with a confidence score + attached to show where a prediction is less reliable.

    ), }, diff --git a/src/components/health-in-tech/HealthAppsAndPatientEngagementLesson.tsx b/src/components/health-in-tech/HealthAppsAndPatientEngagementLesson.tsx index 1de5d294..f1f6e321 100644 --- a/src/components/health-in-tech/HealthAppsAndPatientEngagementLesson.tsx +++ b/src/components/health-in-tech/HealthAppsAndPatientEngagementLesson.tsx @@ -25,9 +25,9 @@ export function HealthAppsAndPatientEngagementLesson() { store with good reviews.

    - The numbers are blunt. Something close to a quarter of people who download a health - app never open it a second time at all, and by the two-week mark most of the people - who did have already stopped. By three months, ongoing daily use is the exception + The pattern is blunt. A sizeable share of people who download a health app never open + it a second time at all, and within the first couple of weeks most of the rest have + drifted away. By three months, ongoing daily use is the exception rather than the rule for anything that stands alone — a wellness app someone downloaded on their own after a symptom worried them at 2 a.m., say, with nobody and nothing else pulling them back to it. @@ -164,7 +164,7 @@ export function HealthAppsAndPatientEngagementLesson() {

    - FHIR is not the first attempt at this. It is the fourth major generation of a - standard published by the same organisation, HL7, and it only makes sense once you + FHIR is not the first attempt at this. It is the newest in a line of standards from + the same organisation, HL7, and it only makes sense once you have seen what it replaced — a format that is, remarkably, still running underneath most of American healthcare today.

    @@ -40,7 +40,7 @@ export function HealthDataStandardsLesson() { >

    Before FHIR, the standard almost every hospital system spoke was{" "} - HL7 version 2, first published in 1987. Its job was narrower than + HL7 version 2, dating back to the late 1980s. Its job was narrower than FHIR's: get a lab result, an admission notice, or an order from one hospital system to another in real time, without a courier walking a printout down a hallway. For that job it worked, and it is the reason a message typed at a nurse's station @@ -58,12 +58,14 @@ PV1|1|I|MED^204^1||||1234^SMITH^ROBERT|||MED`} code and each field inside it separated by a pipe: MSH is the message header, PID is patient identity, PV1{" "} is the visit. There is no field name anywhere in the message — position is the only - thing telling a receiving system that the fourth pipe-separated value in{" "} - PID is a birth date. Miscount a pipe and you have silently + thing telling a receiving system that the seventh field in{" "} + PID, 19910604, is a birth date. Count + it yourself: after PID, each pipe starts the next field, empty + ones included. Miscount a pipe and you have silently shifted every field after it.

    - That positional format was fast to parse and cheap to implement in 1987, which is + That positional format was fast to parse and cheap to implement in the late 1980s, which is exactly why it spread. What it did not solve is the problem from the last chapter: v2 lets a message get from one system to another, but it never forced two hospitals to fill those positions with the same codes. Each @@ -103,7 +105,12 @@ PV1|1|I|MED^204^1||||1234^SMITH^ROBERT|||MED`} }, "subject": { "reference": "Patient/482" }, "recordedDate": "2026-03-14", - "clinicalStatus": "active" + "clinicalStatus": { + "coding": [{ + "system": "http://terminology.hl7.org/CodeSystem/condition-clinical", + "code": "active" + }] + } }`} />

    Reading each field in plain English:

    @@ -113,7 +120,7 @@ PV1|1|I|MED^204^1||||1234^SMITH^ROBERT|||MED`} { label: "code", text: "The diagnosis itself, tagged to a specific, universally recognised code — no ambiguity about which condition this is." }, { label: "subject", text: "Which patient this belongs to, referenced by a stable internal ID." }, { label: "recordedDate", text: "One fixed date format, always year-month-day, no matter which country or vendor wrote it." }, - { label: "clinicalStatus", text: "Whether the condition is still active, resolved, or in remission — a field neither of the last chapter's two systems even named the same way." }, + { label: "clinicalStatus", text: "Whether the condition is still active, resolved, or in remission — itself a code from a shared list, and a field neither of the last chapter's two systems even named the same way." }, ]} />

    @@ -206,13 +213,14 @@ PV1|1|I|MED^204^1||||1234^SMITH^ROBERT|||MED`} "display": "Hemoglobin A1c/Hemoglobin.total in Blood" }] }, + "status": "final", "subject": { "reference": "Patient/482" }, "valueQuantity": { "value": 7.2, "unit": "%" } }`} />

    - 4548-4 means the exact same test at every hospital on earth - that uses LOINC, which is nearly all of them. A receiving system does not need to know + 4548-4 means the exact same test at every hospital and lab that + uses LOINC, which is widely adopted. A receiving system does not need to know which lab drew the blood to know what was measured — it just needs to recognise one code, once. That is the practical benefit of a shared terminology: the envelope carries the data, the terminology makes the data legible to a stranger. @@ -248,7 +256,7 @@ PV1|1|I|MED^204^1||||1234^SMITH^ROBERT|||MED`}

    - Melanin absorbs green light more strongly than lighter, less pigmented skin does, + Darker, more melanin-rich skin absorbs more green light than lighter skin does, which means less light reaches the blood vessels and less of it returns to the photodiode — a weaker signal sitting under the same amount of motion and ambient noise. A tattoo directly over the sensor compounds the same problem: ink absorbs light too, regardless of skin tone underneath it, and can degrade the reading further - still. Neither effect is a hypothetical edge case — it is a real accuracy gap that - contributed to a 2021 FDA safety communication warning that pulse oximeter readings - can be less accurate on patients with darker skin pigmentation. + still. Neither effect is a hypothetical edge case. The same light-absorption problem in pulse + oximeters, which use red and infrared light rather than green, led to a 2021 FDA + safety communication warning that their readings can be less accurate on patients with + darker skin pigmentation.

    Manufacturers have responded by adding more LEDs at different wavelengths and more diff --git a/src/components/health-in-tech/InteroperabilityLesson.tsx b/src/components/health-in-tech/InteroperabilityLesson.tsx index 16c8d587..4fd5d9e5 100644 --- a/src/components/health-in-tech/InteroperabilityLesson.tsx +++ b/src/components/health-in-tech/InteroperabilityLesson.tsx @@ -143,8 +143,8 @@ export function InteroperabilityLesson() {

    That shared standard already exists and has a name — FHIR. The next chapter walks - through what it actually looks like as data, and why it took decades to catch on even - after it existed. + through what it actually looks like as data, and why shared standards took decades to + catch on even after they existed.
    diff --git a/src/components/health-in-tech/InteroperabilityRecords.tsx b/src/components/health-in-tech/InteroperabilityRecords.tsx index 703393c2..f5aa5a92 100644 --- a/src/components/health-in-tech/InteroperabilityRecords.tsx +++ b/src/components/health-in-tech/InteroperabilityRecords.tsx @@ -73,7 +73,7 @@ export function InteroperabilityRecords() {

    - Both records below describe one real patient's one real diagnosis. Nothing about + Both mock records below describe one patient's single diagnosis. Nothing about the medicine is different — only how each system happened to write it down.

    diff --git a/src/components/health-in-tech/PrivacyAndHipaaBasicsLesson.tsx b/src/components/health-in-tech/PrivacyAndHipaaBasicsLesson.tsx index 96acd29d..a2bc2be2 100644 --- a/src/components/health-in-tech/PrivacyAndHipaaBasicsLesson.tsx +++ b/src/components/health-in-tech/PrivacyAndHipaaBasicsLesson.tsx @@ -81,10 +81,12 @@ export function PrivacyAndHipaaBasicsLesson() {

    An emergency room doctor at a hospital you have never visited before can request your records from your regular clinic in the middle of treating you, without a new consent - form, because that request falls inside treatment. The one blanket document you sign — - the Notice of Privacy Practices, usually on a clipboard at a first visit — is what - covers all three going forward. Anything outside TPO, like selling PHI to a - marketer, needs the patient's specific authorisation instead. + form, because that request falls inside treatment. The document usually handed to you on + a clipboard at a first visit — the Notice of Privacy Practices — is not + what grants that permission; the law already does. The notice explains how the practice + uses your information, and the signature it asks for typically just confirms you + received it. Anything outside TPO, like selling PHI to a marketer, needs the + patient's specific authorisation instead.

    @@ -190,7 +192,7 @@ export function PrivacyAndHipaaBasicsLesson() { items={[ "HIPAA protects Protected Health Information handled by covered entities and their business associates — not every piece of health-adjacent data everywhere.", "PHI is defined by eighteen specific identifiers attached to health data, including a catch-all for any other unique identifying code — strip all eighteen and the legal category can disappear.", - "Treatment, payment, and healthcare operations need no fresh authorisation each time; one signed notice at the first visit covers all three going forward.", + "Treatment, payment, and healthcare operations need no fresh authorisation each time — the law permits them directly, and the Notice of Privacy Practices just tells you how they're used.", "A business associate can only touch PHI under a signed agreement obligating it to safeguard the data and report its own breaches — sharing without one is a compliance failure regardless of actual security.", "De-identified data is a legal category, not a guarantee of anonymity — ZIP code, birth date, and sex alone re-identify most Americans once cross-referenced against an outside dataset.", ]} diff --git a/src/components/health-in-tech/RegulationAndOversightLesson.tsx b/src/components/health-in-tech/RegulationAndOversightLesson.tsx index e362d79c..e3a3074c 100644 --- a/src/components/health-in-tech/RegulationAndOversightLesson.tsx +++ b/src/components/health-in-tech/RegulationAndOversightLesson.tsx @@ -56,8 +56,8 @@ export function RegulationAndOversightLesson() { tone: "neutral", children: ( <> -

    Bandages, tongue depressors, most step-counting wellness trackers.

    -

    General controls only. No premarket review required at all.

    +

    Bandages, tongue depressors, manual stethoscopes.

    +

    General controls only. Most are exempt from premarket review.

    ), }, @@ -171,11 +171,13 @@ export function RegulationAndOversightLesson() { deployed — what regulators call an adaptive algorithm. The version reviewed on approval day and the version actually running in a hospital eighteen months later can behave differently, and neither the original clearance nor a patient trusting the - device particularly knows how differently. Regulators have started publishing draft - frameworks for exactly this problem, mostly built around requiring a company to - pre-specify the boundaries an algorithm is allowed to drift within rather than - freezing it entirely — but there is no settled, universally adopted answer yet. It is - one of the open questions in this entire field. + device particularly knows how differently. The FDA's answer so far is a{" "} + predetermined change control plan: the company specifies up front which + kinds of updates it intends to make and exactly how it will test each one, and that plan + is reviewed along with the device. That handles planned, bounded changes. A model that + keeps learning on its own in the field is a harder case, and there is no settled, + universally adopted answer for it yet. It is one of the open questions in this entire + field.

    @@ -202,7 +204,7 @@ export function RegulationAndOversightLesson() { diff --git a/src/components/health-in-tech/RemotePatientMonitoringLesson.tsx b/src/components/health-in-tech/RemotePatientMonitoringLesson.tsx index 80370d44..9b05586d 100644 --- a/src/components/health-in-tech/RemotePatientMonitoringLesson.tsx +++ b/src/components/health-in-tech/RemotePatientMonitoringLesson.tsx @@ -46,7 +46,8 @@ export function RemotePatientMonitoringLesson() { Below is a simplified version of what a remote-monitoring dashboard shows: one patient's heart rate, updating hour by hour over a single day. Click through the readings and watch what happens when one crosses the threshold a care team set in - advance. + advance — then notice what the chart can't tell you on its own: whether that spike + is a real problem or a patient who just climbed the stairs.

    @@ -161,8 +162,11 @@ export function RemotePatientMonitoringLesson() {

    That 16-day threshold on 99454 is the number that quietly runs the whole programme. A patient who wears the device for nine days out of thirty generates - real data and real staff attention, and the practice still cannot bill for that - patient's monitoring that month at all. Reimbursement is not a footnote here — it + real data and real staff attention, and still falls short of the code that pays for a + full month of device monitoring. Billing rules like these are revised regularly — + newer codes have been added for shorter stretches of transmission — so the exact + thresholds are worth checking against current Medicare guidance, but the pressure they + create stays the same. Reimbursement is not a footnote here — it is the reason a monitoring programme that cannot keep patients transmitting reliably eventually gets shut down regardless of how well the alerts themselves work.

    @@ -197,7 +201,7 @@ export function RemotePatientMonitoringLesson() { "Remote patient monitoring turns one data point per scheduled visit into a continuous stream generated during an ordinary day at home.", "A warning sign that appears between visits is invisible to a system that only checks in on a schedule, which is the entire case for monitoring continuously.", "The device is the easy part — the harder problem is staffing an alert queue that someone is actually watching at 3am, not just during business hours.", - "Reimbursement isn't a footnote: Medicare's own billing code only pays for a month where the patient transmitted readings on at least 16 of 30 days.", + "Reimbursement isn't a footnote: Medicare's main device code for remote monitoring pays for a month only when the patient transmitted readings on at least 16 of 30 days.", "A device that goes silent is not the same as a stable patient, and a workflow that treats silence as good news has built the wrong assumption into its core.", ]} /> diff --git a/src/components/health-in-tech/TheDigitalDivideInHealthcareLesson.tsx b/src/components/health-in-tech/TheDigitalDivideInHealthcareLesson.tsx index 80ca9ef9..ef8e8f00 100644 --- a/src/components/health-in-tech/TheDigitalDivideInHealthcareLesson.tsx +++ b/src/components/health-in-tech/TheDigitalDivideInHealthcareLesson.tsx @@ -36,8 +36,10 @@ export function TheDigitalDivideInHealthcareLesson() {

    - The gap is not evenly spread. Compare access across a few different groups below — the - difference between the best-connected and least-connected group is not a rounding error, + The gap is not evenly spread. Compare access across a few different groups in the + illustrative chart below — the figures are simulated to show the shape of the gap, not + taken from a specific survey — and notice that the difference between the + best-connected and least-connected group is not a rounding error, it is the difference between a product that works for someone and one that quietly does not.

    @@ -102,6 +104,12 @@ export function TheDigitalDivideInHealthcareLesson() { "Onboarding that assumes zero prior comfort with video calls, not a help page a struggling patient has to go find on their own.", ]} /> + + Pick one health app or patient portal you have used. List everything it quietly + assumes about the person using it — a smartphone, a data plan, a reading level, a + language, steady hands, an email address. Then choose one item on your list and + describe what that person would need instead. +
    -

    Roughly two out of three people who followed up on an alert did not - actually have the condition.

    +

    Roughly two out of three people who followed up on an alert showed no + sign of the condition on the confirmation patch.

    ), }, @@ -162,7 +164,7 @@ export function TheLimitsOfConsumerHealthDataLesson() { }, { label: "Most of those follow-ups find nothing, at a real cost in money and time", - detail: "The false alarm rate from the last section compounds here: most flagged readings were never the condition to begin with.", + detail: "The confirmation gap from the last section compounds here: most flagged readings don't turn out to be the condition.", }, ]} /> @@ -192,10 +194,27 @@ export function TheLimitsOfConsumerHealthDataLesson() {

    + + It can tell you something changed, and when it started — a real, useful trend. + It cannot tell you why: a cold, poor sleep, stress, alcohol or harder training can + all move it, and so can the sensor sitting differently on your wrist. The honest + next step is to watch whether it settles, and to book an appointment if it persists + or comes with symptoms. + + } + openLabel="Show the answer" + closeLabel="Hide the answer" + /> + +const BASELINE: readonly number[] = Array.from({ length: READING_COUNT }, () => Math.round(normalish(random, 76, 6, { min: 58, max: 104 })), ); +/** + * A short afternoon episode layered on top of the random baseline, so the + * stream actually crosses the alert threshold (the baseline alone never does) + * and then settles back down. Keyed by reading index. + */ +const EPISODE: Readonly> = { 11: 10, 12: 24, 13: 21, 14: 8 }; +const READINGS: readonly number[] = BASELINE.map((bpm, i) => bpm + (EPISODE[i] ?? 0)); + const VIEW_WIDTH = 600; const VIEW_HEIGHT = 220; const PAD_LEFT = 40; diff --git a/src/components/health-in-tech/WearableSignalToggle.tsx b/src/components/health-in-tech/WearableSignalToggle.tsx index ea1b26fb..0ddfb14d 100644 --- a/src/components/health-in-tech/WearableSignalToggle.tsx +++ b/src/components/health-in-tech/WearableSignalToggle.tsx @@ -15,9 +15,10 @@ const random = mulberry32(20260401); const BASE_SIGNAL: readonly number[] = Array.from({ length: SAMPLE_COUNT }, (_, i) => { // Two stacked sine terms approximate a pulse: a slow rise-and-fall dressed - // with a sharper secondary bump, roughly like a real PPG waveform. + // with a sharper secondary bump at twice the frequency, so every one of the + // four beats repeats the same shape, roughly like a real PPG waveform. const t = (i / SAMPLE_COUNT) * Math.PI * 2 * 4; - return Math.sin(t) * 0.6 + Math.sin(t * 2.3) * 0.25; + return Math.sin(t) * 0.6 + Math.sin(t * 2 + 0.8) * 0.25; }); const RAW_SIGNAL: readonly number[] = BASE_SIGNAL.map((v) => v + (random() - 0.5) * 0.9); diff --git a/src/components/health-in-tech/WhatIsHealthTechLesson.tsx b/src/components/health-in-tech/WhatIsHealthTechLesson.tsx index 1c7930c0..d81c65a8 100644 --- a/src/components/health-in-tech/WhatIsHealthTechLesson.tsx +++ b/src/components/health-in-tech/WhatIsHealthTechLesson.tsx @@ -77,9 +77,10 @@ export function WhatIsHealthTechLesson() { touched health tech before you sat in the waiting room.

    - Checked your step count or resting heart rate on a phone or watch? Roughly a third of - adults in the US now own a wearable that tracks something health-adjacent, and a - meaningful share of those readings get shown to an actual clinician at some point. + Checked your step count or resting heart rate on a phone or watch? Wearables that track + something health-adjacent are now an everyday purchase, and some of those readings end + up in front of an actual clinician — shown at an appointment, or fed into a monitoring + programme.

    Had a video call with a doctor instead of driving to a clinic? Telehealth visits @@ -160,8 +161,8 @@ export function WhatIsHealthTechLesson() {

    Skip a stage and the others stop making sense. Bias in a diagnosis model (Part 4) is only dangerous because that model's output reaches a real patient through an - app or a doctor's screen (Part 5) built on a record that was supposed to be - protected the whole way through (Part 2). Treat health tech as one system and every + app or a doctor's screen (Part 5), built on a record (Part 2) that was supposed to + be protected the whole way through (Part 6). Treat health tech as one system and every later chapter has somewhere to attach to.

    diff --git a/src/components/health-in-tech/WhatMedicalAiIsActuallyDoingTodayLesson.tsx b/src/components/health-in-tech/WhatMedicalAiIsActuallyDoingTodayLesson.tsx index d3c8f489..75b09ee3 100644 --- a/src/components/health-in-tech/WhatMedicalAiIsActuallyDoingTodayLesson.tsx +++ b/src/components/health-in-tech/WhatMedicalAiIsActuallyDoingTodayLesson.tsx @@ -127,8 +127,12 @@ export function WhatMedicalAiIsActuallyDoingTodayLesson() {

    Fully autonomous diagnosis — a model that receives your symptoms and - returns a confident, unsupervised verdict with no clinician in the loop — is essentially - not deployed anywhere serious today, for reasons the next chapter covers directly. + returns a confident, unsupervised verdict with no clinician in the loop — is barely + deployed today. The rare exceptions are tightly scoped screening tasks: the best-known + is an FDA-authorised system that checks retinal photos for diabetic eye disease without + a specialist reading the image, and even its output is a decision about whether to + refer the patient to an eye specialist, not a treatment plan. The next chapter covers + why the boundary sits there.

    Predicting rare, highly individual outcomes from limited data, the kind @@ -148,7 +152,7 @@ export function WhatMedicalAiIsActuallyDoingTodayLesson() { "Medical AI's real advantage is exposure at scale — millions of training examples against one career's worth of cases — not a deeper kind of reasoning.", "Imaging review, triage worklists, and narrowing drug candidates are three places it is deployed today, always with a clinician reviewing the output.", "The highest-volume use isn't diagnostic at all — it's turning conversations into notes, notes into billing codes, and calendars into fuller schedules.", - "Fully autonomous diagnosis with no clinician in the loop is essentially not deployed anywhere serious, despite the headlines it generates.", + "Fully autonomous diagnosis with no clinician in the loop is barely deployed outside a few tightly scoped screening tasks, despite the headlines it generates.", "A model that looks brilliant on data resembling its training set can quietly get worse on data that doesn't — the subject the next few chapters take on directly.", ]} /> diff --git a/src/components/health-in-tech/WhyHealthcareIsDifferentLesson.tsx b/src/components/health-in-tech/WhyHealthcareIsDifferentLesson.tsx index cbf4bd29..1028b20e 100644 --- a/src/components/health-in-tech/WhyHealthcareIsDifferentLesson.tsx +++ b/src/components/health-in-tech/WhyHealthcareIsDifferentLesson.tsx @@ -223,7 +223,7 @@ export function WhyHealthcareIsDifferentLesson() { items={[ "A shopping-app bug costs a transaction and is fully recoverable — refund it, patch it, move on.", "A health-app bug can drop an allergy or miscalculate a dose, and neither failure has an undo button.", - "The patient, the provider who buys the software, and the payer who settles the bill want three different things, and none of them is guaranteed to be the same as what's best for the patient.", + "The patient, the provider who buys the software, and the payer who settles the bill want three different things, and the one choosing the software is rarely the one living with the outcome.", "Procurement here runs eighteen months to three years, not a sprint, because integration, security review, and clinical validation all have to clear before a patient is exposed to it.", "\"Move fast and break things\" assumes bugs are cheap and reversible, and cheap to notice — healthcare breaks all three assumptions at once.", ]} diff --git a/src/components/html-css/AccessibilityBasicsLesson.tsx b/src/components/html-css/AccessibilityBasicsLesson.tsx index 22b6a994..4b1766d4 100644 --- a/src/components/html-css/AccessibilityBasicsLesson.tsx +++ b/src/components/html-css/AccessibilityBasicsLesson.tsx @@ -43,7 +43,7 @@ export function AccessibilityBasicsLesson() { {" "} with two keyboard handlers is a worse{" "} <button>. Bad - ARIA is measurably worse than no ARIA. + ARIA is worse than no ARIA, because it announces things that are not true.

    These are the ARIA attributes most likely to appear on a static site: @@ -172,7 +172,7 @@ export function AccessibilityBasicsLesson() { Removing focus outlines because they look untidy makes a site unusable for anybody navigating by keyboard — there is no longer any way to tell where you are. Style the - outline instead. Chapter 21 does it once, for everything, in four lines with{" "} + outline instead. Chapter 21 does it once, for everything, in a single rule with{" "} :focus-visible.

    @@ -213,7 +213,7 @@ export function AccessibilityBasicsLesson() { "Read the page with CSS off. That is roughly the screen reader experience", ]} /> - + Lighthouse and axe are useful and will find missing alt attributes, contrast failures, and unlabelled inputs in seconds. They cannot tell whether your alt text is{" "} good, whether your heading order makes sense, or whether the tab order is logical. @@ -240,7 +240,7 @@ export function AccessibilityBasicsLesson() { "outline: none makes a site unusable by keyboard. Style the outline; never delete it.", "opacity: 0 keeps things focusable, and positive tabindex scrambles the whole page order.", "Alt text describes what the image communicates; functional images describe the action; decorative ones get alt=\"\".", - "Lighthouse catches roughly a third of the problems automatically. Use the keyboard yourself for the rest.", + "Lighthouse catches only some of the problems automatically. Use the keyboard yourself for the rest.", "Almost all of it helps people who are not disabled too — it is one site that works in more conditions.", ]} /> diff --git a/src/components/html-css/ColourAndTypographyLesson.tsx b/src/components/html-css/ColourAndTypographyLesson.tsx index 67da81c6..e5d3fb44 100644 --- a/src/components/html-css/ColourAndTypographyLesson.tsx +++ b/src/components/html-css/ColourAndTypographyLesson.tsx @@ -2,6 +2,7 @@ import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/Le import { Callout } from "@/components/learn/primitives/Callout"; import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { ChecklistCard, CompareGrid, LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards"; +import { WebPlayground } from "@/components/webplay/WebPlayground"; export function ColourAndTypographyLesson() { return ( @@ -17,14 +18,16 @@ export function ColourAndTypographyLesson() { title="Four ways to write a colour, and when each helps" >

    - They all produce the same pixels. The difference is which one you can read and adjust. + Hex, rgb, and hsl can describe exactly the same colour; keywords only cover about 140 named + ones, so the keyword below is the nearest match rather than the same green. The real + difference is which one you can read and adjust.

    without a unit. A unitless value is a multiplier that each element applies to its own font size. A value with a unit computes once and then inherits that fixed pixel value to every child, so a large heading inherits a line height meant for - 14-pixel text and its lines overlap. + 16-pixel text and its lines overlap.

    - A full-width paragraph on a 27-inch monitor is around 200 characters. Which is why an + A full-width paragraph on a large monitor can run past 200 characters a line. Which is why an unstyled page feels hard to read even though nothing is wrong with it.

    +

    + Try it: set line-height to 1, then back + to 1.6. Change max-width to 30ch, then + change the font size and watch the measure follow. +

    + +

    Why line length matters

    +

    + Long lines make your eyes travel a long way back to the start of the + next one, and it is easy to land on the wrong line. Short lines break + the rhythm of reading. Somewhere in between is comfortable. +

    +

    + Spacing between lines matters just as much: too tight and the lines + blur together, too loose and they stop feeling like one paragraph. +

    +`} + initialCss={`:root { + --ink: hsl(150 34% 18%); + --accent: hsl(150 34% 37%); +} + +body { + font-family: Georgia, "Times New Roman", serif; + color: var(--ink); + padding: 8px; +} + +.prose { + max-width: 65ch; + font-size: 1rem; + line-height: 1.6; +} + +h1 { + color: var(--accent); + font-size: 1.5rem; + line-height: 1.2; +}`} + />

    With an element selected, the Styles panel on the right lists every rule that matched it — - in cascade order, most specific first, with the file and line number each came from. + in cascade order, with the winning rules at the top and the file and line number each came + from.

    - Three things in that list explain most of the panel's behaviour. + Four things in that list explain most of the panel's behaviour.

    diff --git a/src/components/html-css/DisplayAndFlowLesson.tsx b/src/components/html-css/DisplayAndFlowLesson.tsx index 9a87bcb4..a75e0448 100644 --- a/src/components/html-css/DisplayAndFlowLesson.tsx +++ b/src/components/html-css/DisplayAndFlowLesson.tsx @@ -98,7 +98,7 @@ ul ol li form figure blockquote table hr`}

    An img is inline, so it sits on the text baseline — and the baseline leaves room for descenders, the tails of{" "} - g and y. That space is the four-pixel gap under an image inside a + g and y. That space is the few-pixel gap under an image inside a container. Two fixes:{" "} img {"{ display: block; }"}{" "} or{" "} diff --git a/src/components/html-css/DocumentStructureLesson.tsx b/src/components/html-css/DocumentStructureLesson.tsx index d2b59d52..3a3c1146 100644 --- a/src/components/html-css/DocumentStructureLesson.tsx +++ b/src/components/html-css/DocumentStructureLesson.tsx @@ -8,7 +8,7 @@ export function DocumentStructureLesson() { return (
    - Every page on the internet starts with the same eight lines, and each one is doing a job you + Every page on the internet starts with the same dozen lines, and each one is doing a job you can name. Then see the same markup as a tree, because that is what the browser turns it into and what CSS selects from. @@ -99,7 +99,7 @@ export function DocumentStructureLesson() { }, { label: "viewport", - text: "Without this, a phone renders your page at 980 pixels wide and zooms out, so everything is tiny and no CSS media query ever fires. Chapter 19 explains how to make the layout respond.", + text: "Without this, a phone renders your page at 980 pixels wide and zooms out, so everything is tiny and your small-screen media queries never fire. Chapter 19 explains how to make the layout respond.", }, { label: "title", @@ -176,7 +176,7 @@ export function DocumentStructureLesson() { "html has exactly two children: head, which is about the page, and body, which is the page.", "lang on html tells screen readers how to pronounce your words.", "charset utf-8 goes first, before anything the browser has to decode.", - "The viewport meta tag is what makes a phone render your page at its real width — without it no media query fires.", + "The viewport meta tag is what makes a phone render your page at its real width — without it your small-screen media queries never fire.", "title is the tab, the bookmark, and the search headline. Specific first, site name second.", "The browser turns your markup into a tree called the DOM. Your indentation is ignored.", "Parent, child, descendant, sibling, ancestor — these are CSS selector vocabulary, not jargon.", diff --git a/src/components/html-css/DomTree.tsx b/src/components/html-css/DomTree.tsx index 61578639..b3b49543 100644 --- a/src/components/html-css/DomTree.tsx +++ b/src/components/html-css/DomTree.tsx @@ -31,7 +31,7 @@ const NODES: readonly Node[] = [ { id: "head", depth: 1, source: "", label: "head", kind: "element", note: "Information about the page. Nothing here is drawn — it is the first child of html, and a sibling of body." }, { id: "title", depth: 2, source: "My site", label: "title", kind: "element", note: "A child of head, a grandchild of html. Shown in the browser tab, not on the page." }, { id: "body", depth: 1, source: "", label: "body", kind: "element", note: "Everything visible. A child of html and a SIBLING of head — the two share a parent, which is what sibling means." }, - { id: "h1", depth: 2, source: "

    Hello

    ", label: "h1", kind: "element", note: "A child of body. In CSS, `body h1` and `body > h1` both match it here — but only because it is a direct child." }, + { id: "h1", depth: 2, source: "

    Hello

    ", label: "h1", kind: "element", note: "A child of body. In CSS, `body h1` matches it, and so does `body > h1` — the second only because h1 is a direct child of body." }, { id: "p", depth: 2, source: "

    Some text

    ", label: "p", kind: "element", note: "A sibling of h1. Note it has a child of its own, which is what makes this a tree rather than a list." }, { id: "em", depth: 3, source: " text", label: "em", kind: "element", note: "A child of p, a DESCENDANT of body, and not a child of body. `body > em` matches nothing; `body em` matches this. That distinction is a whole CSS chapter." }, ]; diff --git a/src/components/html-css/ElementsAndTagsLesson.tsx b/src/components/html-css/ElementsAndTagsLesson.tsx index e50cc0b8..577cfdee 100644 --- a/src/components/html-css/ElementsAndTagsLesson.tsx +++ b/src/components/html-css/ElementsAndTagsLesson.tsx @@ -3,6 +3,7 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { CompareGrid, LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards"; import { ElementAnatomy } from "@/components/html-css/ElementAnatomy"; +import { WebPlayground } from "@/components/webplay/WebPlayground"; export function ElementsAndTagsLesson() { return ( @@ -91,7 +92,7 @@ export function ElementsAndTagsLesson() { `} />

    - There are about fourteen in total and those six are all you will use. Note that{" "} + There are thirteen in total and those six are the ones you will use most. Note that{" "} <link> is void — it points at a stylesheet — while{" "} <a>, the one people call a link, wraps content and definitely closes. @@ -121,8 +122,8 @@ export function ElementsAndTagsLesson() { {" "} and{" "} </br>. - There is no content to wrap and nothing to close. Browsers ignore the stray closing - tag, so it looks like it works. + There is no content to wrap and nothing to close. Browsers patch over both — the + stray closing tag is dropped or reinterpreted — so it looks like it works.

    ), }, @@ -163,6 +164,26 @@ export function ElementsAndTagsLesson() {
  • First
  • Second
  • +`} + /> +

    + Try it: change the h2 to an h1, wrap a + word in <em>, and add a third list item. Then delete one closing tag + and see what the browser decides you meant. +

    + +

    A post

    +

    + Some text with a link in it, + and one important word. +

    +
      +
    • First
    • +
    • Second
    • +
    `} /> diff --git a/src/components/html-css/FlexboxLesson.tsx b/src/components/html-css/FlexboxLesson.tsx index 278c518f..ca8e7ed9 100644 --- a/src/components/html-css/FlexboxLesson.tsx +++ b/src/components/html-css/FlexboxLesson.tsx @@ -2,7 +2,9 @@ import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/Le import { Callout } from "@/components/learn/primitives/Callout"; import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { CompareGrid, LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; import { FlexPlayground } from "@/components/html-css/FlexPlayground"; +import { WebPlayground } from "@/components/webplay/WebPlayground"; export function FlexboxLesson() { return ( @@ -94,6 +96,15 @@ flex-direction: column-reverse; /* bottom to top */`} main axis is whatever flex-direction says. Toggle direction in the widget above and watch them swap. + @@ -120,6 +131,33 @@ flex-direction: column-reverse; /* bottom to top */`} } /*
    Logo
    */`} /> +

    + Try it: change space-between to center, + then space-evenly. Then add flex-direction: column and + notice that justify-content now works top to bottom. +

    + + Logo + Lessons + About +`} + initialCss={`.header { + display: flex; + justify-content: space-between; + align-items: center; + min-height: 160px; + padding: 0 16px; + background: #dbefdb; + font-family: system-ui, sans-serif; +} + +.header a { + color: #1e3c2c; +}`} + />
    diff --git a/src/components/html-css/FormsAndInputsLesson.tsx b/src/components/html-css/FormsAndInputsLesson.tsx index d4f56c3a..425a1c3c 100644 --- a/src/components/html-css/FormsAndInputsLesson.tsx +++ b/src/components/html-css/FormsAndInputsLesson.tsx @@ -160,7 +160,7 @@ export function FormsAndInputsLesson() { <button> with no type is{" "} type="submit". - So a "Add another" button submits the form and reloads the page, which looks like + So an "Add another" button submits the form and reloads the page, which looks like the form randomly resetting itself. Always write{" "} type="button"{" "} on anything that is not the submit. diff --git a/src/components/html-css/HowCssAttachesLesson.tsx b/src/components/html-css/HowCssAttachesLesson.tsx index 647c75f0..c101db1f 100644 --- a/src/components/html-css/HowCssAttachesLesson.tsx +++ b/src/components/html-css/HowCssAttachesLesson.tsx @@ -163,8 +163,9 @@ h1 { />

    Note that the CSS file contains no HTML, no <style> tags, nothing - but rules. Putting a style tag inside a .css file is a common first-day mistake and it - breaks the whole file — everything after it is treated as invalid. + but rules. Putting a style tag inside a .css file is a common first-day mistake: the browser reads + the tag as part of the next selector, decides that rule is invalid, and throws it away — + and developer tools may report a stylesheet parsing error.

    Because these defaults differ slightly between browsers, most projects start with a{" "} reset — a few rules that normalise them. A minimal one is three - declarations and covers most of the pain: + rules and covers most of the pain:

    - Normalize.css and larger resets exist and are fine. For a hand-written site, those nine - lines cover nearly everything they would, and you can read all of them — which matters more + Normalize.css and larger resets exist and are fine. For a hand-written site, those three + rules cover most of what you need, and you can read all of them — which matters more at this stage than completeness.
    diff --git a/src/components/html-css/LinksAndImagesLesson.tsx b/src/components/html-css/LinksAndImagesLesson.tsx index 412c014f..9382dffe 100644 --- a/src/components/html-css/LinksAndImagesLesson.tsx +++ b/src/components/html-css/LinksAndImagesLesson.tsx @@ -38,7 +38,7 @@ export function LinksAndImagesLesson() {

    Those are the image's real pixel dimensions and they are not a display size. The - browser uses the ratio to reserve the right shape, then your CSS scales it. This - is the modern advice and it reverses guidance from about 2015. Older tutorials say the - opposite because browsers used to handle images differently. + browser uses the ratio to reserve the right shape, then your CSS scales it. Some + older tutorials say to leave the dimensions off; that advice dates from before browsers + used them this way, and it no longer applies.

    - Without those two lines an 4000-pixel photo blows out your layout on a phone and produces + Without those two lines a 4,000-pixel photo blows out your layout on a phone and produces horizontal scrolling. Three more image rules matter:

    Not because divs are banned, but because nothing so far has needed one — every region had - an element that described it. Divs will turn up in the next chapter, if a layout - needs a wrapper with no meaning. Notice how far you get before that happens. + an element that described it. A div turns up in the next section, where a group needs + a wrapper with no meaning. Notice how far you get before that happens. diff --git a/src/components/html-css/PublishingYourSiteLesson.tsx b/src/components/html-css/PublishingYourSiteLesson.tsx index a3c1bf99..a50d09b1 100644 --- a/src/components/html-css/PublishingYourSiteLesson.tsx +++ b/src/components/html-css/PublishingYourSiteLesson.tsx @@ -123,14 +123,14 @@ export function PublishingYourSiteLesson() { themselves. That matters because it used to be an annual chore with a fee.

    - A custom domain costs roughly £10 a year from any registrar and points at your host with + A custom domain is a small yearly fee from any registrar, and it points at your host with one DNS record. Chapter 1 explains why the change takes a while to appear everywhere.

    Two bugs account for nearly every "it worked on my laptop" report, and both are @@ -146,7 +146,7 @@ export function PublishingYourSiteLesson() { macOS and Windows treat{" "} Photo.JPG and{" "} photo.jpg as the - same file. Every Linux web server does not. So a mis-cased path works perfectly + same file. Most Linux web servers do not. So a mis-cased path works perfectly locally and 404s the instant you publish.

    ), @@ -203,7 +203,7 @@ export function PublishingYourSiteLesson() { steps={[ { label: "Open the published URL, not localhost", - detail: "In a private window, so nothing is served from your cache. Click every link, load every image, submit the form. This is where a mis-cased path shows up.", + detail: "In a private window, which avoids your normal profile's cookies and cache. Click every link, load every image, submit the form. This is where a mis-cased path shows up.", }, { label: "Open it on an actual phone", @@ -211,7 +211,7 @@ export function PublishingYourSiteLesson() { }, { label: "Run Lighthouse on the live URL", - detail: "The devtools tab audits performance, accessibility, best practices, and SEO in one click. Read the accessibility and SEO sections in particular; they point to specific fixes.", + detail: "The devtools tab audits performance, accessibility, best practices, and SEO in one click. Read the accessibility and SEO sections in particular; they point to specific fixes.", }, ]} /> @@ -232,11 +232,13 @@ export function PublishingYourSiteLesson() { />
    @@ -198,7 +222,7 @@ p:not(.intro) { } /* every p WITHOUT that class */`} /> means direct child. Confusing them is the top cause of a selector matching nothing.", - "Long descendant chains are fragile, slow, and hard to override. Two levels is plenty; a class is usually better.", + "Long descendant chains break when an ancestor in the list moves, and their high specificity makes them hard to override. Two levels is plenty; a class is usually better.", "Pseudo-classes match a state: :hover, :focus-visible, :nth-child(), :not().", - ":hover does not exist on touch devices, so never hide anything important behind it.", + "Touch screens have no real hover, so never hide anything important behind :hover.", "Never remove a focus outline without replacing it — it is how keyboard users know where they are.", "Pseudo-elements use :: and need a content property; their text is decoration and is not reliably announced or searchable.", ]} diff --git a/src/components/html-css/StylingThePageLesson.tsx b/src/components/html-css/StylingThePageLesson.tsx index ca97882b..9a202c27 100644 --- a/src/components/html-css/StylingThePageLesson.tsx +++ b/src/components/html-css/StylingThePageLesson.tsx @@ -13,7 +13,7 @@ export function StylingThePageLesson() { markup changes at all. - +

    The order of these five passes matters more than any individual rule in them. Each one settles decisions the next one depends on. @@ -110,7 +110,7 @@ input, textarea, select, button { { label: "Overridable", text: "Redeclare any of these inside a media query or a class and everything using it changes." }, ]} /> - + Because every colour is read through a token, switching the whole page means redeclaring the tokens. No rule elsewhere in the file changes at all. @@ -123,9 +123,15 @@ input, textarea, select, button { --surface: hsl(150 18% 10%); --raised: hsl(150 14% 14%); --line: hsl(150 10% 22%); + --accent-ink: hsl(150 40% 70%); /* links must stay readable on dark */ } }`} /> +

    + One token moves in the opposite direction: --accent-ink is the link + colour, and a dark green that reads well on a pale page disappears on a dark one, so it + flips to a light green. Check every token you use for text, not just the obvious ones. +

    diff --git a/src/components/html-css/TextAndHeadingsLesson.tsx b/src/components/html-css/TextAndHeadingsLesson.tsx index 15f40cae..b640d9a8 100644 --- a/src/components/html-css/TextAndHeadingsLesson.tsx +++ b/src/components/html-css/TextAndHeadingsLesson.tsx @@ -93,8 +93,8 @@ export function TextAndHeadingsLesson() { title="A paragraph is a block, and whitespace is not" >

    - HTML collapses whitespace on the first page you build: - any run of spaces, tabs, and newlines becomes a single space. + HTML collapses whitespace, and it surprises almost everyone on their first page: any run + of spaces, tabs, and newlines becomes a single space.

    element for paragraphs.`} "HTML collapses all whitespace to a single space. Blank lines and repeated spaces do nothing.", "Spacing comes from block elements and CSS margin, never from
    or pressing Enter.", "strong is importance, em is stress emphasis; b and i are conventional appearance with no added meaning.", - "blockquote, code, time, abbr and cite all say something a span would not.", + "blockquote, q, code, time, abbr and s all say something a span would not.", "Write < > & as entities. With utf-8 everything else can be typed directly.", "Comments are ignored by the browser and fully visible in view source.", ]} diff --git a/src/components/html-css/TheBoxModelLesson.tsx b/src/components/html-css/TheBoxModelLesson.tsx index c157e24c..110e17ab 100644 --- a/src/components/html-css/TheBoxModelLesson.tsx +++ b/src/components/html-css/TheBoxModelLesson.tsx @@ -2,13 +2,15 @@ import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/Le import { Callout } from "@/components/learn/primitives/Callout"; import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { CompareGrid, LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; import { BoxModelExplorer } from "@/components/html-css/BoxModelExplorer"; +import { WebPlayground } from "@/components/webplay/WebPlayground"; export function TheBoxModelLesson() { return (
    - Set an element to 300 pixels wide, add padding, and measure it: it is 340. That one behaviour + Set an element to 300 pixels wide, add 20 pixels of padding, and measure it: it is 340. That one behaviour has confused every person who has ever learned CSS, and one line of code fixes it permanently. @@ -128,6 +130,33 @@ Actual space on screen: }, ]} /> +

    + Try it: both boxes below say width: 240px. Change the + padding to 40px and watch which one grows, then add + box-sizing: border-box to the first. +

    + content-box
    +
    border-box
    `} + initialCss={`.box { + width: 240px; + padding: 20px; + border: 4px solid #3e7f5c; + margin-bottom: 12px; + background: #dbefdb; + font-family: system-ui, sans-serif; +} + +.content { + box-sizing: content-box; /* the default */ +} + +.border { + box-sizing: border-box; +}`} + />

    There is no downside and essentially every real project starts with it. It is not the default only because changing a default would have broken a large part of the existing web @@ -140,6 +169,15 @@ Actual space on screen: *::before, *::after are in the selector too. +

    The escaping-child case is the one that produces a genuine bug report. Anything that - establishes a new formatting context stops it — padding, a border, or the modern one-liner: + separates the two margins stops it — padding or a border on the parent — or the modern + one-liner, which gives the parent its own formatting context:

    !important.

    +
    @@ -255,7 +265,7 @@ nav ul li a 0-0-4 "One ID beats any number of classes; one class beats any number of element names.", "An inline style attribute outranks all three columns.", "Inheritance is not the cascade: it passes text properties down to elements no rule targeted.", - "Text properties inherit; box properties do not. Form controls inherit nothing until you write font: inherit.", + "Text properties inherit; box properties do not. Form controls do not inherit your font until you write font: inherit.", "A rule always beats an inherited value, which is why links ignore body's colour.", "!important buys a fix now and an escalation later. Devtools shows you which rule actually won.", ]} diff --git a/src/components/html-css/WhatIsAWebsiteLesson.tsx b/src/components/html-css/WhatIsAWebsiteLesson.tsx index 2433eae1..470754c5 100644 --- a/src/components/html-css/WhatIsAWebsiteLesson.tsx +++ b/src/components/html-css/WhatIsAWebsiteLesson.tsx @@ -8,7 +8,7 @@ export function WhatIsAWebsiteLesson() { return (
    - Between pressing Enter and seeing a page, six things happen, and none of them are magic. + Between pressing Enter and seeing a page, seven things happen, and none of them are magic. Follow one request from your keyboard to a server on another continent and back, and see exactly which step you will be writing. @@ -159,7 +159,7 @@ Content-Length: 187

    - Step through that and notice how little of it is yours. You write the file in step five. + Step through that and notice how little of it is yours. The file the server sends in step five is the one you wrote. Everything before it is infrastructure you will never touch, and everything after it is the browser interpreting what you wrote.

    diff --git a/src/components/html-css/YourFirstPageLesson.tsx b/src/components/html-css/YourFirstPageLesson.tsx index b0c4f226..6706d4d6 100644 --- a/src/components/html-css/YourFirstPageLesson.tsx +++ b/src/components/html-css/YourFirstPageLesson.tsx @@ -8,7 +8,7 @@ export function YourFirstPageLesson() { return (
    - You need a text editor and a browser, both of which you already have. Write six lines, save + You need a text editor and a browser, both of which you already have. Write eleven lines, save the file, double-click it, and you are a web developer — then learn the two habits that stop the next hundred files from being painful. @@ -174,7 +174,7 @@ my-site/ marker="check" items={[ "A folder for the site — Desktop is fine, and one folder per project from the start", - "index.html inside it, with the ten lines above", + "index.html inside it, with the eleven lines above", "The editor and the browser side by side, not overlapping. Half the screen each", "Live Server installed, or Ctrl/Cmd + R ready in the browser", "File extensions visible in your file manager", @@ -199,7 +199,7 @@ my-site/ "Word processors save formatting, not plain text. TextEdit needs Format → Make Plain Text.", "The .html extension is what makes a text file a web page. Turn on file extensions in Windows so you can see it.", "Double-clicking opens the file over file:// with no server. That is a real and normal way to build.", - "file:// pages cannot be shared and block a few features; a local server like Live Server removes both limits.", + "file:// pages cannot be shared and block a few features. A local server like Live Server lifts the feature limit; only publishing makes a page shareable.", "index.html is served when somebody asks for a folder, which is why URLs are shorter than paths.", "Lowercase, hyphenated filenames. Servers are case-sensitive and your laptop is not — that mismatch is a deploy-day bug.", "Save, refresh, look. If nothing changed: did you save, is it the same file, is it cached?", diff --git a/src/components/learn/shell/LearnChapterHeader.tsx b/src/components/learn/shell/LearnChapterHeader.tsx index b0697f09..2c784411 100644 --- a/src/components/learn/shell/LearnChapterHeader.tsx +++ b/src/components/learn/shell/LearnChapterHeader.tsx @@ -2,19 +2,12 @@ import Link from "next/link"; import type { LearnChapter, LearnTrackId } from "@/lib/learn-types"; import { chapterHref, - getPosition, getPositionLabel, getPrerequisites, getTrack, } from "@/lib/learn-nav"; import { ChapterDoneBadge } from "@/components/learn/reader/ChapterDoneBadge"; -const LEVEL_LABEL: Record = { - beginner: "Beginner", - intermediate: "Intermediate", - advanced: "Advanced", -}; - interface LearnChapterHeaderProps { track: LearnTrackId; chapter: LearnChapter; @@ -23,7 +16,6 @@ interface LearnChapterHeaderProps { export function LearnChapterHeader({ track, chapter }: LearnChapterHeaderProps) { const trackMeta = getTrack(track); const prerequisites = getPrerequisites(track, chapter.slug); - const position = getPosition(track, chapter.slug); return (
    @@ -44,20 +36,9 @@ export function LearnChapterHeader({ track, chapter }: LearnChapterHeaderProps)

    - - {LEVEL_LABEL[chapter.level]} - - {/* Track-wide position; the eyebrow above gives the within-part one. */} - {position && position.partTotal > 1 && ( - - Chapter {position.indexInTrack} of {position.total} - - )} - {chapter.minutes} min read {chapter.lastReviewed && ( <> - {/* Tooling and pricing chapters go stale fast, so say when they were last checked rather than letting readers guess. */} diff --git a/src/components/learn/shell/LessonGate.tsx b/src/components/learn/shell/LessonGate.tsx index d05fd8fe..d27b5e95 100644 --- a/src/components/learn/shell/LessonGate.tsx +++ b/src/components/learn/shell/LessonGate.tsx @@ -82,12 +82,12 @@ export function LessonGate({ track, slug, prev, children }: LessonGateProps) {

    - Finish the previous chapter first + One chapter at a time

    - Chapters unlock in order. Pass the quick check on{" "} - {prev.title}, and this one opens - up. + Finish the quick check at the end of{" "} + {prev.title}, and this chapter + opens up.

    ReactNode; }) { const course = getCatalogCourse(track); - const stats = getTrackStats(track); const parts = getPartsWithChapters(track); - const duration = formatDuration(stats.minutes); // Numbered across the whole course, the order LessonGate unlocks them in. const numberOf = new Map( parts.flatMap((group) => group.chapters).map((chapter, index) => [chapter.slug, index + 1]), @@ -50,11 +45,10 @@ export function CourseHome({ return ( <> -
    -
    @@ -235,6 +237,49 @@ export function PrecisionRecallLesson() { lopsidedness. Take the extreme case — precision 1.0, recall 0.0. A normal average reports 0.5. F1 reports 0.

    + +
    + +
    +

    + Now with a thousand made-up transactions and a model’s confidence score for + each. Choose a threshold, count the four boxes, and build precision, recall and F1 + from them by hand. +

    + = threshold + +tn, fp, fn, tp = confusion_matrix(fraud, flagged).ravel() +print(f"TP {tp} FP {fp} FN {fn} TN {tn}") + +precision = tp / (tp + fp) +recall = tp / (tp + fn) +f1 = 2 * precision * recall / (precision + recall) +print(f"precision {precision:.2f} recall {recall:.2f} F1 {f1:.2f}") +print(f"sklearn agrees: {precision_score(fraud, flagged):.2f}, {recall_score(fraud, flagged):.2f}")`} + /> +

    + At 0.5 it finds 87 of the 102 frauds (recall 0.85) while 142 legitimate transactions + get flagged too (precision 0.38). Set the threshold to 0.3 and recall reaches 0.99 + as precision drops to 0.15; at 0.7 precision rises to 0.89 and recall falls to 0.48. +

    diff --git a/src/components/ml/RandomForestsLesson.tsx b/src/components/ml/RandomForestsLesson.tsx index 204af2d9..7bf43fe1 100644 --- a/src/components/ml/RandomForestsLesson.tsx +++ b/src/components/ml/RandomForestsLesson.tsx @@ -1,5 +1,6 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { TakeawayCard } from "@/components/learn/primitives/Cards"; +import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; import { ForestVote } from "@/components/ml/ForestVote"; @@ -92,10 +93,41 @@ export function RandomForestsLesson() { builds a forest of two.

    - Notice where the gain stops. Between 32 and 120 trees the score moves by half a point. - More trees never makes a forest worse — the average just gets less noisy — but the - returns flatten early. Practitioners pick a few hundred and stop thinking about it, - because the parameter that matters is how the trees are made, not how many. + Notice where the gain stops. Between 32 and 120 trees the score only wobbles within a + point: 82% at 32, 81% at 50, back to 82.5% at 120. Adding trees does not make a forest + systematically worse. The vote just gets less noisy, and on a test set this small a + single flat or two changing sides moves the score up or down a little. But the returns + flatten early. Practitioners pick a few hundred and stop thinking about it, because the + parameter that matters is how the trees are made, not how many. +

    +

    + Try it on a different dataset. One unrestricted tree first, then forests of increasing + size. +

    + +

    + The single tree scores 72.8%. A forest of one tree does worse, 60.6%, because that + lone tree was trained on a bootstrap sample with a limited choice of features at each + split. By 25 trees the forest reaches 80.6%, and after that the score only wobbles: + 80.0% at 100 and 79.4% at 200.

    @@ -135,7 +167,7 @@ export function RandomForestsLesson() { "Feature subsetting limits each split to a random handful of features, which is what stops one strong feature dominating every root.", "Here the forest reached 82.5% against 72.5% for one unrestricted tree and 76.0% for the best pruned one.", "120 trees drew a clean diagonal boundary that no individual member could express.", - "Returns flatten fast — most of the gain arrives by about 30 trees, and more trees never hurt.", + "Returns flatten fast. Most of the gain arrives by about 30 trees; after that the score only wobbles by a point or so, with no trend downwards.", "You lose readability entirely. Feature importances tell you what mattered overall, never why one particular prediction came out as it did.", ]} /> diff --git a/src/components/ml/RegularisationLesson.tsx b/src/components/ml/RegularisationLesson.tsx index a4eb4d5a..4a9ad46b 100644 --- a/src/components/ml/RegularisationLesson.tsx +++ b/src/components/ml/RegularisationLesson.tsx @@ -1,5 +1,5 @@ import { Callout } from "@/components/learn/primitives/Callout"; -import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; +import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock"; import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards"; import { StepList } from "@/components/learn/primitives/StepList"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; @@ -95,6 +95,35 @@ export function RegularisationLesson() { }, ]} /> +

    + Fit both penalties to forty rows and eight columns, where only the first three columns + carry any real signal. +

    + +

    + Ridge shrinks every coefficient and sets none of them to exactly zero; the one that + prints as 0. is merely tiny, as the count confirms. Lasso keeps + the three real columns, sets four of the five noise columns to exactly zero, and leaves + one at 0.2. Raise either alpha and both get stricter. +

    There is a compromise between the two — elastic net, which penalises with a blend of both sums at once — for when you want some sparsity without betting @@ -166,10 +195,10 @@ export function RegularisationLesson() { /> A penalty on raw coefficient size only makes sense if the coefficients are comparable - in the first place. A rent measured in minutes of walk time and a rent measured in - square metres are not on the same scale, so an unscaled penalty punishes whichever - column happened to be measured in small units, for no reason connected to how much it - actually matters. Standardise every predictor before fitting, exactly as the widget + in the first place. A predictor measured in minutes of walk time and one measured in + square metres are not on the same scale. A column whose numbers are small needs a large + coefficient to have the same effect, so an unscaled penalty punishes that column hardest, + for no reason connected to how much it actually matters. Standardise every predictor before fitting, exactly as the widget above does, and fit that standardiser on the training rows only. diff --git a/src/components/ml/TrainTestSplitLesson.tsx b/src/components/ml/TrainTestSplitLesson.tsx index 683e4945..2831586e 100644 --- a/src/components/ml/TrainTestSplitLesson.tsx +++ b/src/components/ml/TrainTestSplitLesson.tsx @@ -1,5 +1,6 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { TakeawayCard } from "@/components/learn/primitives/Cards"; +import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; import { SplitLottery } from "@/components/ml/SplitLottery"; @@ -80,6 +81,40 @@ export function TrainTestSplitLesson() { and it is the model flattering itself. Never quote a training score as though it were a measure of how good your model is.

    +

    + Both effects show up on a real dataset that ships with scikit-learn: 569 breast + tumours, each described by 30 measurements. An unrestricted decision tree is graded on + what it studied, then on the drawer, and then the drawer is redrawn ten times. +

    + +

    + The tree scores 100% on its own training rows and 88% on the drawer. With a 5% drawer + the ten scores run from 79% to 100%; change test_size to 0.3 + and they tighten to between 89% and 95%. +

    +

    + Here is the voting rule from the top of the page again, except this time nobody writes + it. The model gets ten example people, their ages, and whether each one could vote, + and has to find the rule itself. +

    + +

    + It prints age <= 17.50: close to the real rule, and found + only because the examples happened to include a 17-year-old and an 18-year-old. Delete + the 17 from both lists and run it again, and the cut moves. That is the trade in + miniature: the learned rule is only as good as the examples it saw. +

    diff --git a/src/components/playground/MLBuilder.tsx b/src/components/playground/MLBuilder.tsx new file mode 100644 index 00000000..7e4e4d68 --- /dev/null +++ b/src/components/playground/MLBuilder.tsx @@ -0,0 +1,967 @@ +"use client"; + +import { useId, useMemo, useRef, useState, type DragEvent, type PointerEvent as ReactPointerEvent } from "react"; +import { + ArrowDown, + ArrowUp, + Check, + CircleAlert, + Code2, + GripVertical, + Lightbulb, + Play, + Plus, + RotateCcw, + Square, + Trash2, +} from "lucide-react"; +import { cn } from "@/lib/utils"; +import { FigureGallery, OutputConsole, StatusPill, isBusy } from "./OutputConsole"; +import { + BLOCK_INFO, + BLOCK_ORDER, + C_VALUES, + DATASETS, + MODELS, + TEST_SIZES, + TREE_COUNTS, + generateCode, + makeBlock, + parsePipeline, + starterPipeline, + validate, + type Block, + type BlockSettings, + type BlockType, + type DatasetId, + type ModelKind, +} from "./ml-pipeline"; +import { usePythonRunner } from "./usePythonRunner"; + +const ML_STORAGE_KEY = "cwp-playground-ml"; + +function loadPipeline(): Block[] { + try { + const raw = window.localStorage.getItem(ML_STORAGE_KEY); + if (raw) { + const parsed = parsePipeline(JSON.parse(raw)); + if (parsed) return parsed; + } + } catch { + // Blocked or corrupt storage: start from the example pipeline. + } + return starterPipeline(); +} + +function savePipeline(blocks: Block[]) { + try { + window.localStorage.setItem( + ML_STORAGE_KEY, + JSON.stringify(blocks.map(({ type, settings }) => ({ type, settings }))), + ); + } catch { + // Persistence is a convenience only. + } +} + +type DragSource = { kind: "palette"; type: BlockType } | { kind: "pipeline"; uid: string }; + +interface DragState { + source: DragSource; + /** Insertion index in the pipeline, or null while outside it. */ + over: number | null; +} + +const LEAF = "#3e7f5c"; + +const SMALL_BTN = + "inline-flex size-9 shrink-0 items-center justify-center rounded-md text-[var(--home-ink-quiet)] transition-colors hover:bg-[#dbefdb] hover:text-[var(--home-moss)] focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[var(--home-fern)] disabled:pointer-events-none disabled:opacity-30"; + +const FIELD = + "min-h-9 w-full cursor-pointer rounded-md border border-[var(--home-hairline-strong)] bg-[var(--home-white)] px-2.5 text-[0.875rem] text-[var(--home-ink)] focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[var(--home-fern)]"; + +const LABEL = "text-[0.75rem] font-medium text-[var(--home-ink-quiet)]"; + +/** + * Drag blocks into an ordered pipeline; the Python for it is written live + * beside it and runs in the same Pyodide worker as the editor. + * + * Dragging works three ways, and none of them is required: + * - a mouse uses native HTML5 drag and drop; + * - touch and pen use pointer events on the grip, since mobile browsers' + * native drag is patchy; + * - the keyboard (and anyone who prefers it) uses the Add, Move up, Move down + * and Remove buttons, which do the same things. + */ +export function MLBuilder({ onOpenInEditor }: { onOpenInEditor: (code: string) => void }) { + const [blocks, setBlocks] = useState(loadPipeline); + const [drag, setDrag] = useState(null); + const [active, setActive] = useState(null); + const [announcement, setAnnouncement] = useState(""); + const listRef = useRef(null); + const ghostRef = useRef(null); + const pointerDrag = useRef<{ source: DragSource; over: number | null } | null>(null); + const runner = usePythonRunner(); + const ids = useId(); + + const generated = useMemo(() => generateCode(blocks), [blocks]); + const issues = useMemo(() => validate(blocks), [blocks]); + const errors = issues.filter((issue) => issue.level === "error"); + const tips = issues.filter((issue) => issue.level === "tip"); + const busy = runner.isRunning || isBusy(runner.status); + const canRun = errors.length === 0 && !busy && !runner.isBlocked; + const used = new Set(blocks.map((block) => block.type)); + + const commit = (next: Block[], message?: string) => { + setBlocks(next); + savePipeline(next); + if (message) setAnnouncement(message); + }; + + const insertAt = (type: BlockType, index: number) => { + if (used.has(type)) return; + const next = blocks.slice(); + const at = Math.max(0, Math.min(index, next.length)); + next.splice(at, 0, makeBlock(type)); + commit(next, `Added ${BLOCK_INFO[type].title} at step ${at + 1}.`); + }; + + /** Where a new block of this type most naturally goes: after the last block + * that normally comes before it. Keeps button-adding in a sensible order. */ + const naturalIndex = (type: BlockType) => { + const rank = BLOCK_ORDER.indexOf(type); + let index = 0; + blocks.forEach((block, i) => { + if (BLOCK_ORDER.indexOf(block.type) < rank) index = i + 1; + }); + return index; + }; + + const moveTo = (uid: string, insertion: number) => { + const from = blocks.findIndex((block) => block.uid === uid); + if (from === -1) return; + let to = insertion; + if (to > from) to -= 1; + if (to === from) return; + const next = blocks.slice(); + const [moved] = next.splice(from, 1); + next.splice(to, 0, moved); + commit(next, `Moved ${BLOCK_INFO[moved.type].title} to step ${to + 1}.`); + }; + + const remove = (uid: string) => { + const block = blocks.find((b) => b.uid === uid); + if (!block) return; + commit( + blocks.filter((b) => b.uid !== uid), + `Removed ${BLOCK_INFO[block.type].title}. It's back in the blocks list.`, + ); + if (active === uid) setActive(null); + }; + + const updateSettings = (uid: string, patch: Partial) => { + commit( + blocks.map((block) => + block.uid === uid ? ({ ...block, settings: { ...block.settings, ...patch } } as Block) : block, + ), + ); + }; + + const dropSource = (source: DragSource, index: number) => { + if (source.kind === "palette") insertAt(source.type, index); + else moveTo(source.uid, index); + }; + + /** The insertion index for a point, or null when it is outside the list. */ + const indexAt = (x: number, y: number): number | null => { + const list = listRef.current; + if (!list) return null; + const box = list.getBoundingClientRect(); + const margin = 24; + if (x < box.left - margin || x > box.right + margin || y < box.top - margin || y > box.bottom + margin) { + return null; + } + const items = Array.from(list.querySelectorAll("[data-block-uid]")); + for (let i = 0; i < items.length; i += 1) { + const rect = items[i].getBoundingClientRect(); + if (y < rect.top + rect.height / 2) return i; + } + return items.length; + }; + + const setOver = (source: DragSource, over: number | null) => { + setDrag((prev) => + prev && prev.over === over && sameSource(prev.source, source) ? prev : { source, over }, + ); + }; + + /* --- native HTML5 drag and drop (mouse) --- */ + + const onNativeDragStart = (event: DragEvent, source: DragSource, image?: HTMLElement | null) => { + if (pointerDrag.current) { + // A touch drag is already under way on the same element. + event.preventDefault(); + return; + } + event.dataTransfer.effectAllowed = source.kind === "palette" ? "copy" : "move"; + event.dataTransfer.setData("text/plain", source.kind === "palette" ? source.type : source.uid); + if (image) { + const rect = image.getBoundingClientRect(); + event.dataTransfer.setDragImage(image, event.clientX - rect.left, event.clientY - rect.top); + } + setDrag({ source, over: null }); + }; + + const onListDragOver = (event: DragEvent) => { + if (!drag) return; + event.preventDefault(); + event.dataTransfer.dropEffect = drag.source.kind === "palette" ? "copy" : "move"; + setOver(drag.source, indexAt(event.clientX, event.clientY) ?? blocks.length); + }; + + const onListDrop = (event: DragEvent) => { + event.preventDefault(); + if (!drag) return; + const index = indexAt(event.clientX, event.clientY) ?? drag.over ?? blocks.length; + dropSource(drag.source, index); + setDrag(null); + }; + + const onListDragLeave = (event: DragEvent) => { + if (!drag) return; + const next = event.relatedTarget as Node | null; + if (next && event.currentTarget.contains(next)) return; + setOver(drag.source, null); + }; + + /* --- pointer events (touch and pen) --- */ + + const moveGhost = (x: number, y: number) => { + const ghost = ghostRef.current; + if (ghost) ghost.style.transform = `translate(${x + 12}px, ${y - 20}px)`; + }; + + const onGripPointerDown = (event: ReactPointerEvent, source: DragSource, label: string) => { + if (event.pointerType === "mouse" || event.button !== 0) return; + event.preventDefault(); + try { + // Keeps move and up events coming to the grip even when the finger + // leaves it. + event.currentTarget.setPointerCapture(event.pointerId); + } catch { + // An already-released pointer: the drag still works while over the grip. + } + pointerDrag.current = { source, over: null }; + const ghost = ghostRef.current; + if (ghost) { + ghost.textContent = label; + ghost.hidden = false; + } + moveGhost(event.clientX, event.clientY); + setDrag({ source, over: null }); + }; + + const onGripPointerMove = (event: ReactPointerEvent) => { + const current = pointerDrag.current; + if (!current) return; + moveGhost(event.clientX, event.clientY); + // Nudge the page when the finger nears an edge, since the grip has + // touch-action: none and the page can't be scrolled by hand mid-drag. + if (event.clientY < 56) window.scrollBy(0, -12); + else if (event.clientY > window.innerHeight - 56) window.scrollBy(0, 12); + const over = indexAt(event.clientX, event.clientY); + current.over = over; + setOver(current.source, over); + }; + + const endPointerDrag = (commitDrop: boolean) => { + const current = pointerDrag.current; + pointerDrag.current = null; + const ghost = ghostRef.current; + if (ghost) ghost.hidden = true; + setDrag(null); + if (commitDrop && current && current.over !== null) dropSource(current.source, current.over); + }; + + const gripHandlers = (source: DragSource, label: string) => ({ + onPointerDown: (event: ReactPointerEvent) => onGripPointerDown(event, source, label), + onPointerMove: onGripPointerMove, + onPointerUp: () => endPointerDrag(true), + onPointerCancel: () => endPointerDrag(false), + }); + + const run = () => { + if (!canRun) return; + runner.run(generated.code); + }; + + const issueFor = (uid: string) => errors.find((issue) => issue.uid === uid) ?? tips.find((issue) => issue.uid === uid); + const generalIssues = issues.filter((issue) => issue.uid === null); + const activeSection = generated.sections.find((section) => section.uid === active && active !== null); + const codeLines = generated.code.replace(/\n$/, "").split("\n"); + + const liveText = + runner.status === "done" + ? `${runner.statusText} ${runner.figures.length > 0 ? "A chart was drawn." : ""}` + : runner.status === "error" && runner.error + ? `${runner.statusText} ${runner.error.message}` + : runner.status === "idle" + ? "" + : runner.statusText; + + return ( +
    + {/* Left: palette and pipeline */} +
    +
    +
    +

    + Blocks +

    +
    + + +
    +
    +

    + Drag a block into your pipeline, or press its + button. +

    +
      + {BLOCK_ORDER.map((type) => { + const info = BLOCK_INFO[type]; + const inUse = used.has(type); + return ( +
    • +
      onNativeDragStart(event, { kind: "palette", type })} + onDragEnd={() => setDrag(null)} + title={info.why} + className={cn( + "flex min-h-10 items-center rounded-full border text-[0.875rem] font-medium transition-colors", + inUse + ? "border-transparent bg-[var(--home-grey-400)] text-[var(--home-ink-quiet)]" + : "cursor-grab border-[#bfdcc3] bg-[#dbefdb] text-[var(--home-moss)] hover:border-[#3e7f5c] active:cursor-grabbing", + )} + > + {inUse ? ( + + + ) : ( + <> + + {info.title} + + + )} +
      +
    • + ); + })} +
    +
    + +
    +

    + Your pipeline +

    +

    + Steps run from top to bottom. Drag the grip or use the arrows to reorder. +

    +
      + {blocks.length === 0 && ( +
    1. + Drop a Load dataset block here to begin. +
    2. + )} + {blocks.map((block, index) => { + const issue = issueFor(block.uid); + const isSource = drag?.source.kind === "pipeline" && drag.source.uid === block.uid; + const info = BLOCK_INFO[block.type]; + return ( +
    3. setActive(block.uid)} + onMouseLeave={() => setActive((current) => (current === block.uid ? null : current))} + onFocus={() => setActive(block.uid)} + className={cn( + "relative rounded-xl border bg-[var(--home-white)] shadow-[var(--home-shadow-sm)] transition-[border-color,opacity]", + issue?.level === "error" + ? "border-[#e0a46b]" + : active === block.uid + ? "border-[#3e7f5c]" + : "border-[var(--home-hairline-strong)]", + isSource && "opacity-45", + )} + > + {drag?.over === index && ( +
    4. + ); + })} +
    +

    + Each step has Move up, Move down and Remove buttons. Add steps with the plus buttons in the blocks list. +

    + {generalIssues.length > 0 && ( +
      + {generalIssues.map((issue) => ( +
    • + {issue.level === "error" ? ( +
    • + ))} +
    + )} +
    +
    + + {/* Right: generated code and results */} +
    +
    +
    +

    + pipeline.py + Live +

    +
    + + + +
    +
    +
    +
    +              {codeLines.map((line, index) => {
    +                const number = index + 1;
    +                const highlighted =
    +                  activeSection !== undefined && number >= activeSection.startLine && number <= activeSection.endLine;
    +                const comment = /^\s*#/.test(line);
    +                return (
    +                  
    + + + {line || " "} + +
    + ); + })} +
    +
    +
    + + {errors.length > 0 && ( +

    +

    + )} + {runner.isBlocked && ( +

    + Python is busy with the editor's code. Run this when it finishes. +

    + )} + +
    +
    + +

    + Results +

    + +
    + +
    + + {runner.figures.length > 0 && ( +
    + +
    + )} +
    +
    + + {/* Follows the finger during a touch drag. Positioned by the handlers. */} + + ); +} + +function sameSource(a: DragSource, b: DragSource) { + if (a.kind === "palette" && b.kind === "palette") return a.type === b.type; + if (a.kind === "pipeline" && b.kind === "pipeline") return a.uid === b.uid; + return false; +} + +function BlockFields({ + block, + ids, + onChange, +}: { + block: Block; + ids: string; + onChange: (patch: Record) => void; +}) { + switch (block.type) { + case "load": + return ( +
    + + +

    {DATASETS[block.settings.dataset].blurb}

    +
    + ); + case "split": + return ( +
    +
    + + +
    + onChange({ stratify })} + label="Keep the class mix the same in both sets" + /> +
    + ); + case "scale": + return ( +
    + + +
    + ); + case "model": { + const s = block.settings; + return ( +
    +
    + + +

    {MODELS[s.kind].short}

    +
    + {s.kind === "knn" && ( + onChange({ k })} /> + )} + {(s.kind === "tree" || s.kind === "forest") && ( + onChange({ maxDepth })} + /> + )} + {s.kind === "forest" && ( +
    + + +
    + )} + {s.kind === "logistic" && ( +
    + + +
    + )} +
    + ); + } + case "train": + return ( +
    + onChange({ showTrainScore })} + label="Also show accuracy on the training examples" + /> +
    + ); + case "evaluate": + return ( +
    + onChange({ report })} + label="Add a report for each class" + /> +
    + ); + case "plot": + return ( +
    + + +
    + ); + } +} + +function Slider({ + id, + label, + min, + max, + value, + onChange, +}: { + id: string; + label: string; + min: number; + max: number; + value: number; + onChange: (value: number) => void; +}) { + return ( +
    +
    + + + {value} + +
    + onChange(Number(event.target.value))} + className="mt-1 h-8 w-full cursor-pointer" + style={{ accentColor: LEAF }} + /> +
    + ); +} + +function Toggle({ + id, + checked, + onChange, + label, +}: { + id: string; + checked: boolean; + onChange: (checked: boolean) => void; + label: string; +}) { + return ( + + ); +} diff --git a/src/components/playground/Playground.tsx b/src/components/playground/Playground.tsx index 1dae48fa..3c5cd201 100644 --- a/src/components/playground/Playground.tsx +++ b/src/components/playground/Playground.tsx @@ -1,20 +1,38 @@ "use client"; -import { useEffect, useId, useRef, useState } from "react"; +import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react"; import Image from "next/image"; -import { Check, Copy, Link2, Play, RotateCcw, Square, Undo2 } from "lucide-react"; -import { TypeLine } from "@/components/koda/TypeLine"; +import { + Blocks, + Check, + CircleAlert, + CircleCheck, + CircleStop, + Code2, + Copy, + Link2, + LoaderCircle, + Play, + RotateCcw, + Square, + Undo2, +} from "lucide-react"; +import { cn } from "@/lib/utils"; import { CodeEditor } from "./CodeEditor"; import { DEFAULT_EXAMPLE, EXAMPLES, exampleById, type Example } from "./examples"; +import { MLBuilder } from "./MLBuilder"; import { FigureGallery, OutputConsole, StatusPill, isBusy } from "./OutputConsole"; import { codeFromHash, encodeCode, STORAGE_KEY } from "./share"; -import { usePythonRunner, type RunState } from "./usePythonRunner"; +import { usePythonRunner, type RunState, type RunStatus } from "./usePythonRunner"; interface Saved { code: string; exampleId: string | null; } +type Mode = "code" | "ml"; +const MODE_KEY = "cwp-playground-mode"; + /** Where the editor starts: a shared link wins, then the student's own last * session, then the Hello starter. Client-only (this component is loaded * with ssr: false), so reading location and storage here is safe. */ @@ -35,6 +53,19 @@ function initialCode(): Saved { return { code: DEFAULT_EXAMPLE.code, exampleId: DEFAULT_EXAMPLE.id }; } +/** A shared #code= link always opens the editor; #ml opens the builder; + * otherwise the tab the student last used. */ +function initialMode(): Mode { + const hash = window.location.hash; + if (codeFromHash(hash) !== null) return "code"; + if (hash === "#ml") return "ml"; + try { + return window.localStorage.getItem(MODE_KEY) === "ml" ? "ml" : "code"; + } catch { + return "code"; + } +} + function save(value: Saved) { try { window.localStorage.setItem(STORAGE_KEY, JSON.stringify(value)); @@ -46,7 +77,7 @@ function save(value: Saved) { /** Drop a consumed `#code=` once the student edits, so a reload brings back * their edits (from storage) rather than the original shared snippet. */ function clearShareHash() { - if (window.location.hash.startsWith("#code=")) { + if (window.location.hash.startsWith("#code=") || window.location.hash === "#ml") { window.history.replaceState(null, "", window.location.pathname + window.location.search); } } @@ -78,10 +109,57 @@ function kodaLine(run: RunState, example: Example | null): string { } } +/** A short, fixed-width label for the toolbar. The full sentence lives in + * the output header and the live region. */ +const BADGE: Record = { + idle: "Ready", + booting: "Loading Python", + packages: "Loading libraries", + running: "Running", + done: "Done", + error: "Error", + stopped: "Stopped", + unavailable: "Offline", +}; + +function StatusBadge({ status }: { status: RunStatus }) { + const busy = isBusy(status); + const Icon = busy + ? LoaderCircle + : status === "done" + ? CircleCheck + : status === "error" || status === "unavailable" + ? CircleAlert + : status === "stopped" + ? CircleStop + : CircleCheck; + return ( + + ); +} + const TOOL_BTN = - "home-btn home-btn-outline !min-h-10 !px-3 !text-[0.875rem] disabled:cursor-not-allowed disabled:opacity-50"; + "inline-flex min-h-10 items-center justify-center gap-1.5 rounded-lg border border-[var(--home-hairline-strong)] bg-[var(--home-white)] px-3 text-[0.875rem] font-medium text-[var(--home-ink)] transition-colors hover:border-[#3e7f5c] hover:bg-[#f3faf3] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--home-fern)] disabled:cursor-not-allowed disabled:opacity-50"; + +const PANE_SHADOW = "shadow-[0_1px_0_rgba(21,18,12,0.04),0_18px_40px_-24px_rgba(21,18,12,0.55)]"; export function Playground() { + const [mode, setModeState] = useState(initialMode); const [saved, setSaved] = useState(initialCode); const { code, exampleId } = saved; const [stdin, setStdin] = useState(""); @@ -90,8 +168,11 @@ export function Playground() { const [undo, setUndo] = useState(null); const [flash, setFlash] = useState<"copied" | "shared" | null>(null); const flashTimer = useRef(undefined); + const rootRef = useRef(null); + const tabRefs = useRef>({ code: null, ml: null }); const runner = usePythonRunner(); const ids = useId(); + const editorId = `${ids}-editor`; const editorHintId = `${ids}-editor-hint`; const statusId = `${ids}-status`; @@ -108,12 +189,22 @@ export function Playground() { const shared = codeFromHash(window.location.hash); if (shared === null) return; setSaved({ code: shared, exampleId: null }); + setModeState("code"); setNotice("Loaded the code from this link. It came in the link itself; nothing was downloaded."); }; window.addEventListener("hashchange", onHash); return () => window.removeEventListener("hashchange", onHash); }, []); + const setMode = (next: Mode) => { + setModeState(next); + try { + window.localStorage.setItem(MODE_KEY, next); + } catch { + // Remembering the tab is a convenience only. + } + }; + const update = (next: Saved) => { setSaved(next); save(next); @@ -135,16 +226,30 @@ export function Playground() { runner.run(code, answers); }; - const loadExample = (next: Example, message: string) => { + const replaceCode = (next: Saved, message: string) => { if (code !== next.code) setUndo({ code, exampleId }); clearShareHash(); - update({ code: next.code, exampleId: next.id }); + update(next); if (runner.isRunning) runner.stop(); runner.clear(); setRanCode(null); setNotice(message); }; + const loadExample = (next: Example, message: string) => { + replaceCode({ code: next.code, exampleId: next.id }, message); + }; + + const openFromBuilder = (generated: string) => { + replaceCode( + { code: generated, exampleId: null }, + "Here's your pipeline as plain Python. Change anything you like, then press Run.", + ); + setMode("code"); + rootRef.current?.scrollIntoView({ block: "start", behavior: "smooth" }); + tabRefs.current.code?.focus({ preventScroll: true }); + }; + const restoreUndo = () => { if (!undo) return; update(undo); @@ -180,8 +285,18 @@ export function Playground() { } }; + const onTabKey = (event: KeyboardEvent) => { + if (event.key !== "ArrowLeft" && event.key !== "ArrowRight" && event.key !== "Home" && event.key !== "End") return; + event.preventDefault(); + const next: Mode = + event.key === "Home" ? "code" : event.key === "End" ? "ml" : mode === "code" ? "ml" : "code"; + setMode(next); + tabRefs.current[next]?.focus(); + }; + const errorLine = runner.error && ranCode === code ? runner.error.line : null; const line = notice ?? kodaLine(runner, example); + const hasOutput = runner.output.length > 0 || runner.error !== null || runner.figures.length > 0; const liveText = runner.status === "done" ? `${runner.statusText} ${runner.figures.length > 0 ? `${runner.figures.length} figure${runner.figures.length === 1 ? "" : "s"} drawn.` : ""}` @@ -191,38 +306,96 @@ export function Playground() { ? "" : runner.statusText; + const tabs: { mode: Mode; label: string; hint: string; Icon: typeof Code2 }[] = [ + { mode: "code", label: "Code editor", hint: "Write and run Python", Icon: Code2 }, + { mode: "ml", label: "ML builder", hint: "Drag blocks to train a model", Icon: Blocks }, + ]; + return ( -
    - {/* Toolbar */} -
    -
    - - -
    +
    + {/* Mode switch */} +
    + {tabs.map((tab) => { + const selected = mode === tab.mode; + return ( + + ); + })} +
    -
    + {/* Code editor */} + - - {/* Koda */} -
    - -

    - Koda: - - {undo && notice && ( +

    + + - )} -

    -
    - - {/* Workspace */} -
    -
    -
    -
    - - main.py - Python - - - Tab indents · Esc then Tab leaves · Ctrl/⌘ + Enter runs - -
    -
    +
    - {wantsInput && ( -
    - -

    - Your code asks for input. Type each answer on its own line before you press Run; each input() call takes the next line. -

    -