diff --git a/.dockerignore b/.dockerignore index 57e3ace..75fa341 100644 --- a/.dockerignore +++ b/.dockerignore @@ -4,4 +4,3 @@ site/node_modules site/dist site/dist-ssr -site/public/maze-solver.jar diff --git a/Dockerfile b/Dockerfile index 27f813a..b2b3fc6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,12 +1,4 @@ # syntax=docker/dockerfile:1 -FROM maven:3.9-eclipse-temurin-21-alpine AS maze-solver -ARG MAZE_SOLVER_REPO=https://github.com/FRC2713/maze-solver-java.git -ARG MAZE_SOLVER_REF=main -RUN apk add --no-cache git \ - && git clone --depth 1 --branch "${MAZE_SOLVER_REF}" "${MAZE_SOLVER_REPO}" /maze-solver \ - && cd /maze-solver \ - && mvn -B -q -DskipTests package - FROM node:24-bookworm-slim AS builder WORKDIR /app/site COPY site/package.json site/package-lock.json ./ @@ -14,7 +6,6 @@ RUN npm ci WORKDIR /app COPY lessons ./lessons COPY site ./site -COPY --from=maze-solver /maze-solver/target/maze-solver.jar ./site/public/maze-solver.jar WORKDIR /app/site RUN npm run build diff --git a/scripts/smoke-image.sh b/scripts/smoke-image.sh index df5b825..db54f78 100755 --- a/scripts/smoke-image.sh +++ b/scripts/smoke-image.sh @@ -26,7 +26,7 @@ for _attempt in $(seq 1 60); do const health = await fetch("http://127.0.0.1:3000/health").then(r => r.json()); if (health.status !== "ok") process.exit(1); if (process.env.EXPECTED_REV && health.revision !== process.env.EXPECTED_REV) process.exit(1); - for (const p of ["/", "/tools.jar", "/maze-solver.jar"]) { + for (const p of ["/"]) { const r = await fetch("http://127.0.0.1:3000" + p, { method: "HEAD" }); if (!r.ok) { console.error("Missing asset:", p, r.status); process.exit(1); } } diff --git a/site/package-lock.json b/site/package-lock.json index b55490b..398ac83 100644 --- a/site/package-lock.json +++ b/site/package-lock.json @@ -8,7 +8,6 @@ "name": "site", "version": "0.0.0", "dependencies": { - "@codemirror/lang-java": "^6.0.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/theme-one-dark": "^6.1.3", "@radix-ui/react-dialog": "^1.1.18", @@ -76,16 +75,6 @@ "@lezer/common": "^1.1.0" } }, - "node_modules/@codemirror/lang-java": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-java/-/lang-java-6.0.2.tgz", - "integrity": "sha512-m5Nt1mQ/cznJY7tMfQTJchmrjdjQ71IDs+55d1GAa8DGaB8JXWsVCkVT284C3RTASaY43YknrK2X3hPO/J3MOQ==", - "license": "MIT", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@lezer/java": "^1.0.0" - } - }, "node_modules/@codemirror/lang-python": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz", @@ -305,17 +294,6 @@ "@lezer/common": "^1.3.0" } }, - "node_modules/@lezer/java": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@lezer/java/-/java-1.1.3.tgz", - "integrity": "sha512-yHquUfujwg6Yu4Fd1GNHCvidIvJwi/1Xu2DaKl/pfWIA2c1oXkVvawH3NyXhCaFx4OdlYBVX5wvz2f7Aoa/4Xw==", - "license": "MIT", - "dependencies": { - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" - } - }, "node_modules/@lezer/lr": { "version": "1.4.10", "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz", diff --git a/site/package.json b/site/package.json index 562008b..efcef82 100644 --- a/site/package.json +++ b/site/package.json @@ -7,11 +7,9 @@ "dev": "vite", "build": "tsc -b && vite build", "lint": "oxlint", - "preview": "vite preview", - "vendor:maze-solver": "bash scripts/vendor-maze-solver.sh" + "preview": "vite preview" }, "dependencies": { - "@codemirror/lang-java": "^6.0.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/theme-one-dark": "^6.1.3", "@radix-ui/react-dialog": "^1.1.18", diff --git a/site/public/tools.jar b/site/public/tools.jar deleted file mode 100644 index df88aa1..0000000 Binary files a/site/public/tools.jar and /dev/null differ diff --git a/site/scripts/vendor-maze-solver.sh b/site/scripts/vendor-maze-solver.sh deleted file mode 100755 index 4d86c17..0000000 --- a/site/scripts/vendor-maze-solver.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env bash -# Build the FRC2713/maze-solver-java jar and vendor it into public/ so the -# Java playground can load its com.frc2713.mazesolver API locally. -# -# Production doesn't use this script — the Pages workflow builds the jar fresh -# on every deploy (see .github/workflows/deploy-pages.yml). Run this once for -# local `npm run dev`/`npm run build`. Requires a JDK (>= 8, capable of -# --release 8) and Maven on your PATH. -set -euo pipefail - -REPO="${MAZE_SOLVER_REPO:-https://github.com/FRC2713/maze-solver-java}" -REF="${MAZE_SOLVER_REF:-main}" -here="$(cd "$(dirname "$0")/.." && pwd)" - -tmp="$(mktemp -d)" -trap 'rm -rf "$tmp"' EXIT - -echo "Cloning $REPO@$REF ..." -git clone --depth 1 --branch "$REF" "$REPO" "$tmp/lib" -echo "Building jar ..." -( cd "$tmp/lib" && mvn -B -q -DskipTests package ) -cp "$tmp/lib/target/maze-solver.jar" "$here/public/maze-solver.jar" -echo "Vendored public/maze-solver.jar ($(wc -c < "$here/public/maze-solver.jar") bytes)" diff --git a/site/src/components/CodeBlock.tsx b/site/src/components/CodeBlock.tsx index c3aca09..d6b79ba 100644 --- a/site/src/components/CodeBlock.tsx +++ b/site/src/components/CodeBlock.tsx @@ -1,25 +1,21 @@ import { useMemo } from 'react' import CodeMirror, { EditorView } from '@uiw/react-codemirror' -import { java } from '@codemirror/lang-java' import { python } from '@codemirror/lang-python' import { oneDark } from '@codemirror/theme-one-dark' import { editorTheme, usePrefersDark } from '@/lib/editorTheme' // A read-only, syntax-highlighted rendering of a fenced code block in the prose. -// Python and Java blocks get language highlighting + line numbers; other fences -// (e.g. ```text``` output samples) get the same themed surface without either. +// Python blocks get language highlighting + line numbers; other fences (e.g. +// ```text``` output samples) get the same themed surface without either. export function CodeBlock({ code, language }: { code: string; language?: string }) { const dark = usePrefersDark() - const isJava = language === 'java' const isPython = language === 'python' - const isCode = isJava || isPython const extensions = useMemo(() => { const ext = [editorTheme, EditorView.lineWrapping] if (isPython) ext.unshift(python()) - else if (isJava) ext.unshift(java()) return ext - }, [isJava, isPython]) + }, [isPython]) return (
@@ -29,7 +25,7 @@ export function CodeBlock({ code, language }: { code: string; language?: string extensions={extensions} theme={dark ? oneDark : 'light'} basicSetup={{ - lineNumbers: isCode, + lineNumbers: isPython, foldGutter: false, highlightActiveLine: false, highlightActiveLineGutter: false, diff --git a/site/src/components/JavaRunner.tsx b/site/src/components/JavaRunner.tsx index 05ac802..3ef7aab 100644 --- a/site/src/components/JavaRunner.tsx +++ b/site/src/components/JavaRunner.tsx @@ -1,11 +1,8 @@ import { useMemo, useState } from 'react' import CodeMirror, { EditorView } from '@uiw/react-codemirror' -import { java } from '@codemirror/lang-java' import { python } from '@codemirror/lang-python' import { oneDark } from '@codemirror/theme-one-dark' -import { getJavaRuntimeStatus, runJava } from '@/lib/javaRuntime' import { runPython } from '@/lib/pythonRuntime' -import type { RunnableLanguage } from '@/lib/lessons' import { editorTheme, usePrefersDark } from '@/lib/editorTheme' import { Button } from '@/components/ui/button' import { cn } from '@/lib/utils' @@ -13,11 +10,9 @@ import { cn } from '@/lib/utils' export function JavaRunner({ initialCode, storageKey, - language = 'java', }: { initialCode: string storageKey: string - language?: RunnableLanguage }) { const originalCode = initialCode.trimEnd() const [code, setCode] = useState(() => localStorage.getItem(storageKey) ?? originalCode) @@ -26,17 +21,12 @@ export function JavaRunner({ const [running, setRunning] = useState(false) const dark = usePrefersDark() - const extensions = useMemo( - () => [language === 'python' ? python() : java(), editorTheme, EditorView.lineWrapping], - [language], - ) + const extensions = useMemo(() => [python(), editorTheme, EditorView.lineWrapping], []) const handleRun = async () => { - const label = - language === 'python' || getJavaRuntimeStatus() === 'ready' ? 'Running…' : 'Loading Java…' setRunning(true) - setOutput(label) - const result = language === 'python' ? await runPython(code) : await runJava(code) + setOutput('Running…') + const result = await runPython(code) setOk(result.ok) setOutput(result.output || '(no output)') setRunning(false) diff --git a/site/src/components/MazePlayground.tsx b/site/src/components/MazePlayground.tsx index 565763b..d1a0881 100644 --- a/site/src/components/MazePlayground.tsx +++ b/site/src/components/MazePlayground.tsx @@ -1,21 +1,12 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import CodeMirror, { EditorView } from '@uiw/react-codemirror' -import { java } from '@codemirror/lang-java' import { python } from '@codemirror/lang-python' import { oneDark } from '@codemirror/theme-one-dark' -import { getJavaRuntimeStatus, runJava } from '@/lib/javaRuntime' import { runPythonMaze } from '@/lib/pythonRuntime' import type { SolverMode as LessonSolverMode } from '@/lib/lessons' import { editorTheme, usePrefersDark } from '@/lib/editorTheme' import { Button } from '@/components/ui/button' import { cn } from '@/lib/utils' -import { - buildMazeHarness, - mazeGridLiteral, - parseTrail, - retargetErrorLines, - studentLineOffset, -} from '@/lib/mazeHarness' // NOTE: the `maze-generator` npm package is broken — its internal `shuffle` is // written as `for (...; ...; update) return o`, so it returns on the first @@ -81,23 +72,13 @@ const MOVES: Record<'up' | 'down' | 'left' | 'right', { bit: number; dx: number; const cx = (x: number) => PAD + x * CELL + CELL / 2 const cy = (y: number) => PAD + y * CELL + CELL / 2 -// Serialize the maze as a ready-to-paste Java `int[][]` literal, wired into the -// maze-solver library so it runs without any bitmask arithmetic. Each cell is -// the same N/S/E/W bitmask the grid uses, but the library reads it for you. -function serializeToJava(grid: number[][]): string { - const rows = mazeGridLiteral(grid) - return `import com.frc2713.mazesolver.*; - -// The maze as a grid of numbers (each cell an N/S/E/W bitmask). Hand it to a -// GridMaze and you get a robot on the start cell — no bitmask math needed. -int[][] grid = { +// Serialize the maze as a ready-to-paste Python 2D list of bitmasks. +function serializeToPython(grid: number[][]): string { + const rows = grid.map((row) => ` [${row.join(', ')}],`).join('\n') + return `# The maze as a grid of numbers (each cell an UP/DOWN/RIGHT/LEFT bitmask). +grid = [ ${rows} -}; - -Maze maze = new GridMaze(grid); -Robot robot = maze.robot(); -// Now drive it: robot.readWallSensor(Direction.UP), robot.drive(Direction.RIGHT), -// robot.facing(), robot.atGoal(), robot.row(), robot.col().` +]` } // Headings for the wall follower, clockwise: 0=up, 1=right, 2=down, 3=left. @@ -124,112 +105,6 @@ const SOLVER_LABEL: Record = { wall: 'Run wall follower', } -// The editor's starting point for `solver: java`: a right-hand wall follower, -// the same algorithm the maze lessons build up to — written against the -// library's Robot API, using the facing() the robot remembers for itself. -const DEFAULT_JAVA_SOLVE = `// Drive the robot from start (green) to goal (red). Your robot can: -// robot.readWallSensor(Direction.UP/DOWN/LEFT/RIGHT) — is that side a wall? -// robot.drive(Direction.UP/DOWN/LEFT/RIGHT) — move one cell that way -// robot.facing() — the way it last drove -// robot.atGoal(), robot.row(), robot.col() -// -// This starter is the "keep your right hand on the wall" follower. -void solve(Robot robot) { - int maxSteps = 1000; - for (int i = 0; i < maxSteps && !robot.atGoal(); i++) { - // Relative to the way we're facing, try right, straight, left, then - // back — and drive the first opening. drive() updates facing() for us. - Direction ahead = robot.facing(); - Direction[] order = { - ahead.clockwise(), ahead, ahead.counterClockwise(), ahead.opposite() - }; - for (Direction dir : order) { - if (!robot.readWallSensor(dir)) { - robot.drive(dir); - break; - } - } - } -}` - -// The editor's starting point for `solver: astar`. Unlike the reactive wall -// follower, A* is a *planner*: it gets the whole `Maze` (random access to every -// cell via maze.cellAt) plus java.util.* imports, computes the shortest path -// from start (0,0) to the goal (bottom-right), then drives the robot along it. -const DEFAULT_ASTAR_SOLVE = `// A* finds the SHORTEST path, then drives it. You get the whole map: -// maze.rows(), maze.cols() — the grid size -// maze.cellAt(r, c).wall(dir) — is there a wall on that side of (r,c)? -// robot.drive(Direction.UP/DOWN/LEFT/RIGHT) — move the robot one cell -// Start is (0, 0) top-left; the goal is the bottom-right cell. -void solve(Maze maze, Robot robot) { - int rows = maze.rows(), cols = maze.cols(); - int goalR = rows - 1, goalC = cols - 1; - - // Cheapest known cost to reach each cell from the start (g), and the cell we - // arrived from, so we can rebuild the path once we get to the goal. - int[][] g = new int[rows][cols]; - int[][] cameFrom = new int[rows][cols]; - for (int[] row : g) Arrays.fill(row, Integer.MAX_VALUE); - for (int[] row : cameFrom) Arrays.fill(row, -1); - g[0][0] = 0; - - // The frontier: cells still to explore, cheapest estimated total cost first. - // Each entry is {row, col, f} where f = g + heuristic. Pack a cell as r*cols+c. - PriorityQueue frontier = new PriorityQueue<>((a, b) -> a[2] - b[2]); - frontier.add(new int[] { 0, 0, heuristic(0, 0, goalR, goalC) }); - - while (!frontier.isEmpty()) { - int[] cur = frontier.poll(); - int r = cur[0], c = cur[1]; - if (r == goalR && c == goalC) break; // reached the goal — done exploring - - Cell cell = maze.cellAt(r, c); - for (Direction dir : Direction.values()) { - if (cell.wall(dir)) continue; // can't step through a wall - int nr = r, nc = c; - if (dir == Direction.UP) nr--; - else if (dir == Direction.DOWN) nr++; - else if (dir == Direction.LEFT) nc--; - else nc++; - - int tentative = g[r][c] + 1; // every step costs 1 - if (tentative < g[nr][nc]) { // found a cheaper way to this neighbour - g[nr][nc] = tentative; - cameFrom[nr][nc] = r * cols + c; - frontier.add(new int[] { nr, nc, tentative + heuristic(nr, nc, goalR, goalC) }); - } - } - } - - // Walk cameFrom backwards from the goal to the start, then reverse it. - List path = new ArrayList<>(); - for (int cell = goalR * cols + goalC; cell != -1; ) { - int r = cell / cols, c = cell % cols; - path.add(new int[] { r, c }); - cell = cameFrom[r][c]; - } - Collections.reverse(path); - - // Drive the robot cell by cell along the path A* found. - for (int i = 1; i < path.size(); i++) { - robot.drive(step(path.get(i - 1), path.get(i))); - } -} - -// Manhattan distance: cells away if there were no walls. It never over-estimates -// the real distance, which is exactly what lets A* trust it and stay optimal. -int heuristic(int r, int c, int goalR, int goalC) { - return Math.abs(r - goalR) + Math.abs(c - goalC); -} - -// The direction that steps from one cell to its neighbour. -Direction step(int[] from, int[] to) { - if (to[0] < from[0]) return Direction.UP; - if (to[0] > from[0]) return Direction.DOWN; - if (to[1] < from[1]) return Direction.LEFT; - return Direction.RIGHT; -}` - const DEFAULT_PYTHON_SOLVE = `# Drive the robot from start (green) to goal (red). Your robot can: # robot.read_wall_sensor(Direction.UP/DOWN/LEFT/RIGHT) — is that side a wall? # robot.drive(Direction.UP/DOWN/LEFT/RIGHT) — move one cell that way @@ -315,32 +190,20 @@ export function MazePlayground({ solver = null }: { solver?: SolverMode | null } // `solver: java`/`astar` state — the editable Java solver and its run output. // Both modes share the editor; `astar` differs only in its starter code and in // the harness it runs through (it's handed the whole Maze, not just a Robot). - const isJava = solver === 'java' - const isAstar = solver === 'astar' const isPython = solver === 'python' const isPythonAstar = solver === 'python-astar' - const isPythonMode = isPython || isPythonAstar - const isEditable = isJava || isAstar || isPythonMode - const harnessMode = isAstar || isPythonAstar ? 'astar' : 'wall' - const starterCode = isPythonAstar - ? DEFAULT_PYTHON_ASTAR_SOLVE - : isPython - ? DEFAULT_PYTHON_SOLVE - : isAstar - ? DEFAULT_ASTAR_SOLVE - : DEFAULT_JAVA_SOLVE + const isEditable = isPython || isPythonAstar + const harnessMode = isPythonAstar ? 'astar' : 'wall' + const starterCode = isPythonAstar ? DEFAULT_PYTHON_ASTAR_SOLVE : DEFAULT_PYTHON_SOLVE const [code, setCode] = useState(starterCode) - const [javaOutput, setJavaOutput] = useState(null) - const [javaOk, setJavaOk] = useState(true) + const [solverOutput, setSolverOutput] = useState(null) + const [solverOk, setSolverOk] = useState(true) const dark = usePrefersDark() - const editorExtensions = useMemo( - () => [isPythonMode ? python() : java(), editorTheme, EditorView.lineWrapping], - [isPythonMode], - ) + const editorExtensions = useMemo(() => [python(), editorTheme, EditorView.lineWrapping], []) - const copyForJava = () => { - const java = serializeToJava(grid) - navigator.clipboard?.writeText(java).then( + const copyForPython = () => { + const text = serializeToPython(grid) + navigator.clipboard?.writeText(text).then( () => { setCopied(true) setTimeout(() => setCopied(false), 1500) @@ -457,63 +320,34 @@ export function MazePlayground({ solver = null }: { solver?: SolverMode | null } [stopSolver], ) - const runJavaSolver = useCallback(async () => { + const runCodeSolver = useCallback(async () => { stopSolver() setStuck(false) setRobot(START) - setJavaOk(true) - if (isPythonMode) { - setJavaOutput('Running…') - const result = await runPythonMaze(code, grid, harnessMode) - if (!result.ok) { - setJavaOk(false) - setJavaOutput(result.output || '(error)') - return - } - if (!result.trail) { - setJavaOk(false) - setJavaOutput( - 'Ran, but produced no Maze Trail. Make sure solve(robot) moves the robot.', - ) - return - } - setJavaOk(true) - setJavaOutput(result.output || null) - animateTrail(result.trail) - return - } - setJavaOutput(getJavaRuntimeStatus() === 'ready' ? 'Running…' : 'Loading Java…') - const harness = buildMazeHarness(grid, code, harnessMode) - const result = await runJava(harness) + setSolverOk(true) + setSolverOutput('Running…') + const result = await runPythonMaze(code, grid, harnessMode) if (!result.ok) { - const offset = studentLineOffset(grid, harnessMode) - setJavaOk(false) - setJavaOutput(retargetErrorLines(result.output, offset) || '(error)') + setSolverOk(false) + setSolverOutput(result.output || '(error)') return } - const trail = parseTrail(result.output) - if (!trail) { - setJavaOk(false) - setJavaOutput( + if (!result.trail) { + setSolverOk(false) + setSolverOutput( 'Ran, but produced no Maze Trail. Make sure solve(robot) moves the robot.', ) return } - // Show any debug output the student printed, minus the sentinel line. - const debug = result.output - .split('\n') - .filter((l) => !l.startsWith('__TRAIL__ ')) - .join('\n') - .trim() - setJavaOk(true) - setJavaOutput(debug || null) - animateTrail(trail.cells) - }, [grid, code, harnessMode, isPythonMode, stopSolver, animateTrail]) + setSolverOk(true) + setSolverOutput(result.output || null) + animateTrail(result.trail) + }, [grid, code, harnessMode, stopSolver, animateTrail]) const generate = () => { stopSolver() setStuck(false) - setJavaOutput(null) + setSolverOutput(null) setGrid(generateMaze(SIZE)) setRobot(START) } @@ -678,10 +512,10 @@ export function MazePlayground({ solver = null }: { solver?: SolverMode | null } {!isEditable && ( )}
@@ -710,7 +544,7 @@ export function MazePlayground({ solver = null }: { solver?: SolverMode | null } variant="outline" onClick={() => { setCode(starterCode) - setJavaOutput(null) + setSolverOutput(null) }} disabled={running} > @@ -720,20 +554,20 @@ export function MazePlayground({ solver = null }: { solver?: SolverMode | null } type="button" size="sm" variant="outline" - onClick={running ? stopSolver : runJavaSolver} + onClick={running ? stopSolver : runCodeSolver} className="border-primary/40 bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary" > {running ? 'Stop' : '▶ Run in the maze'} - {javaOutput !== null && ( + {solverOutput !== null && (
-                {javaOutput}
+                {solverOutput}
               
)} diff --git a/site/src/lib/javaRuntime.ts b/site/src/lib/javaRuntime.ts deleted file mode 100644 index 1bfe579..0000000 --- a/site/src/lib/javaRuntime.ts +++ /dev/null @@ -1,196 +0,0 @@ -// Runs real Java client-side via CheerpJ (a JVM compiled to WebAssembly), -// loaded lazily from Leaning Tech's CDN on first use under their free -// Community License. This is the only file that knows CheerpJ exists - -// everything else just calls runJava(). -// -// Each run is a real compile-then-execute: the snippet is written into -// CheerpJ's virtual filesystem, compiled with javac (from the OpenJDK 8 -// tools.jar vendored in public/), and the resulting class is executed. javac -// itself is a Java program running inside the same in-browser JVM. -const CHEERPJ_LOADER_URL = 'https://cjrtnc.leaningtech.com/4.3/loader.js' - -// CheerpJ mounts the site's HTTP origin at /app/, so the vendored compiler -// lives under the Vite base path (/ in production). -const TOOLS_JAR = `/app${import.meta.env.BASE_URL}tools.jar` -// FRC2713/maze-solver-java, built into a jar and vendored the same way. Gives -// lesson snippets the com.frc2713.mazesolver API — the Direction enum, the -// Maze/Cell/Robot interfaces, the concrete GridMaze students build with -// `new GridMaze(grid)`, and MazeSolver — so they write solving algorithms -// against it instead of raw bitmasks. The jar is produced by CI on deploy and -// by scripts/vendor-maze-solver.sh locally. -const SOLVER_JAR = `/app${import.meta.env.BASE_URL}maze-solver.jar` -const CLASS_PATH = `${TOOLS_JAR}:${SOLVER_JAR}:/files/` - -// Globals installed by loader.js (a classic script, not an ES module). -declare global { - function cheerpjInit(options?: object): Promise - function cheerpjRunMain(className: string, classPath: string, ...args: string[]): Promise - function cheerpOSAddStringFile(path: string, data: Uint8Array): void -} - -let cheerpjPromise: Promise | null = null -let status: 'idle' | 'loading' | 'ready' = 'idle' - -// Lets the UI show "loading the Java runtime" (a multi-MB download plus a -// slow first compile) only the first time, instead of on every Run click. -export function getJavaRuntimeStatus() { - return status -} - -function injectScriptOnce(src: string): Promise { - return new Promise((resolve, reject) => { - const script = document.createElement('script') - script.src = src - script.onload = () => resolve() - script.onerror = () => reject(new Error(`Failed to load ${src}`)) - document.head.appendChild(script) - }) -} - -// CheerpJ writes System.out and System.err as text into whatever element has -// id="console". We keep a hidden one and read/clear it around each run, which -// is safe because runs are queued (see runQueue below). -let consoleElement: HTMLPreElement | null = null - -function loadCheerpjOnce(): Promise { - if (!cheerpjPromise) { - status = 'loading' - cheerpjPromise = (async () => { - consoleElement = document.createElement('pre') - consoleElement.id = 'console' - consoleElement.style.display = 'none' - document.body.appendChild(consoleElement) - await injectScriptOnce(CHEERPJ_LOADER_URL) - await cheerpjInit({ status: 'none' }) - // Warm-up: the first javac invocation inside the browser JVM is several - // times slower than the ones after it, so absorb that cost here while - // the UI still says "loading" instead of on the student's first Run. - await compileAndRun('class Warmup { public static void main(String[] a) {} }') - status = 'ready' - })() - } - return cheerpjPromise -} - -export interface RunOutcome { - ok: boolean - output: string -} - -// Bare statements are wrapped in a main-method shell so early lessons can run -// `System.out.println("hi");` without meeting class boilerplate (lesson 11 -// reveals the shell). Snippets that declare their own class/enum run as-is. -// The blanket java.util import lets ArrayList/HashMap snippets work before -// imports are taught. -const WRAP_PREFIX = 'import java.util.*;\npublic class Main {\npublic static void main(String[] args) {\n' -const WRAP_SUFFIX = '\n}\n}' -const WRAP_LINE_OFFSET = 3 - -interface PreparedSource { - source: string - mainClass: string - lineOffset: number -} - -function prepareSource(code: string): PreparedSource { - // Ignore `class`/`interface`/`enum` mentions inside line comments when - // deciding whether the snippet is already a full compilation unit. An - // interface-only snippet (lesson 29) must not fall through to the wrap - // path below — a top-level `interface` inside a method body is illegal. - const withoutComments = code.replace(/\/\/[^\n]*/g, '') - const declarations = [...withoutComments.matchAll(/\b(?:class|enum|interface)\s+(\w+)/g)] - if (declarations.length > 0) { - // Run the class that owns main(): the last type declared before the main - // method (snippets can hold several classes, e.g. lesson 21). The public - // class must also match the filename, and in our lessons that is always - // the class with main. A snippet with no main still compiles for feedback. - const mainIndex = withoutComments.search(/\bstatic\s+void\s+main\b/) - const before = declarations.filter((d) => d.index! < mainIndex) - const mainClass = (before.length > 0 ? before[before.length - 1] : declarations[0])[1] - return { source: code, mainClass, lineOffset: 0 } - } - return { - source: WRAP_PREFIX + code + WRAP_SUFFIX, - mainClass: 'Main', - lineOffset: WRAP_LINE_OFFSET, - } -} - -// javac diagnostics point at the wrapped file (/str/Main.java:12); rewrite -// them to the student's own line numbers and drop the trailing "N errors" -// count, keeping the code line + caret which genuinely help. -function simplifyCompileErrors(text: string, lineOffset: number, mainClass: string): string { - const kept: string[] = [] - for (const line of text.split('\n')) { - const diag = new RegExp(`^/str/${mainClass}\\.java:(\\d+):\\s*(.*)$`).exec(line) - if (diag) { - kept.push(`line ${Number(diag[1]) - lineOffset}: ${diag[2]}`) - continue - } - if (/^\d+ errors?$/.test(line.trim())) continue - kept.push(line) - } - return kept.join('\n').trim() -} - -// CheerpJ reports runtime stack frames as "Unknown Source" (no line numbers), -// so the best we can do is keep the exception itself plus the frames in the -// student's own classes and drop JVM-internal ones. -function simplifyRuntimeError(text: string): string { - const kept: string[] = [] - for (const line of text.split('\n')) { - if (/^\s+at\s/.test(line) && !/\(Unknown Source\)|\(\w+\.java/.test(line)) continue - kept.push(line.replace(/\(Unknown Source\)/, '').trimEnd()) - } - return kept.join('\n').trim() -} - -async function compileAndRun(code: string): Promise { - const { source, mainClass, lineOffset } = prepareSource(code) - const out = consoleElement! - out.textContent = '' - cheerpOSAddStringFile(`/str/${mainClass}.java`, new TextEncoder().encode(source)) - const exitCode = await cheerpjRunMain( - 'com.sun.tools.javac.Main', - CLASS_PATH, - `/str/${mainClass}.java`, - '-d', - '/files/', - ) - if (exitCode !== 0) { - return { ok: false, output: simplifyCompileErrors(out.textContent ?? '', lineOffset, mainClass) } - } - out.textContent = '' - await cheerpjRunMain(mainClass, CLASS_PATH) - // Console writes land asynchronously; give the DOM a beat to settle. - await new Promise((resolve) => setTimeout(resolve, 150)) - const output = out.textContent ?? '' - // CheerpJ exits 0 even on an uncaught exception, so detect failure from the - // output itself. "Error:" covers JVM launcher failures (e.g. a snippet whose - // class has no main method). - if (/^Exception in thread |^Error: /m.test(output)) { - return { ok: false, output: simplifyRuntimeError(output) } - } - return { ok: true, output: output.replace(/\n$/, '') } -} - -// The CheerpJ runtime is a single shared instance (loading it twice would mean -// downloading tens of MB again), so concurrent Run clicks across different -// code blocks are queued rather than racing each other's console capture. -let runQueue: Promise = Promise.resolve() - -export function runJava(code: string): Promise { - const run = async (): Promise => { - await loadCheerpjOnce() - return compileAndRun(code) - } - - const result = runQueue.then(run, run) - runQueue = result.catch(() => {}) - return result -} - -// Dev-only hook so lesson snippets can be batch-tested from the console. -if (import.meta.env.DEV && typeof window !== 'undefined') { - ;(window as unknown as { __runJava: typeof runJava }).__runJava = runJava -} diff --git a/site/src/lib/lessons.ts b/site/src/lib/lessons.ts index 28e0316..3c0a47b 100644 --- a/site/src/lib/lessons.ts +++ b/site/src/lib/lessons.ts @@ -121,30 +121,25 @@ export function nextLesson(slug: string): Lesson | undefined { return index === -1 ? undefined : lessons[index + 1] } -export type RunnableLanguage = 'python' | 'java' +export type RunnableLanguage = 'python' export interface RunnableSnippet { language: RunnableLanguage code: string } -// Drives the playground panel: a page's first ```python or ```java fence is -// what gets loaded into it. Pages can still show other code samples in prose; -// only this one is treated as "the" runnable snippet for the page. +// Drives the playground panel: a page's first ```python fence is what gets +// loaded into it. Pages can still show other code samples in prose; only this +// one is treated as "the" runnable snippet for the page. export function firstRunnableSnippet(markdown: string): RunnableSnippet | null { - const match = /```(python|java)\r?\n([\s\S]*?)```/.exec(markdown) + const match = /```python\r?\n([\s\S]*?)```/.exec(markdown) if (!match) return null return { - language: match[1] as RunnableLanguage, - code: match[2].trimEnd(), + language: 'python', + code: match[1].trimEnd(), } } -export function firstJavaSnippet(markdown: string): string | null { - const match = /```java\r?\n([\s\S]*?)```/.exec(markdown) - return match ? match[1].trimEnd() : null -} - // A page can swap the Java playground for the visual block editor with a // ```blocks fence whose body names a preset (see lib/blockPresets.ts). The // fence is a directive, not content, so it never renders in the prose column. @@ -183,11 +178,11 @@ export function hasMaze(markdown: string): boolean { // writes their own reactive solver in real Java, run through the maze round-trip. // The fifth, `astar`, is the same editor but its harness also hands the student // the whole Maze so they can plan a global shortest path (the A* lesson). -export type SolverMode = 'random' | 'naive' | 'wall' | 'java' | 'astar' | 'python' | 'python-astar' +export type SolverMode = 'random' | 'naive' | 'wall' | 'python' | 'python-astar' export function mazeSolver(markdown: string): SolverMode | null { const match = MAZE_FENCE.exec(markdown) if (!match) return null - const m = /solver:\s*(python-astar|python|random|naive|wall|java|astar)/.exec(match[1]) + const m = /solver:\s*(python-astar|python|random|naive|wall)/.exec(match[1]) return m ? (m[1] as SolverMode) : null } diff --git a/site/src/lib/mazeHarness.ts b/site/src/lib/mazeHarness.ts deleted file mode 100644 index b8db150..0000000 --- a/site/src/lib/mazeHarness.ts +++ /dev/null @@ -1,112 +0,0 @@ -// The JS → Java → animated-steps maze round-trip (see docs/maze-roundtrip.md). -// -// A student writes a `solve(Robot)` algorithm in the maze playground. To run it -// we build a full Java compilation unit here: the current maze is interpolated -// in as an `int[][]` literal, the student's method is spliced into the class -// body, and a `main` drives the robot then prints the Maze Trail as a single -// sentinel-tagged line for the JS side to parse and animate back. -// -// `new GridMaze(grid)` resolves against the maze-solver library on the -// classpath (see lib/javaRuntime.ts). Nothing maze-specific is bundled into -// the harness source itself. - -// The maze as a ready-to-embed Java `int[][]` literal body (just the rows, no -// surrounding `int[][] x = {...}`). Each cell is the same N/S/E/W bitmask the JS -// grid uses — a set bit means that side is OPEN — so Java reads it with the -// identical constants. This is the one source of truth for the literal format; -// both the harness and "Copy for Java" build on it. -export function mazeGridLiteral(grid: number[][]): string { - return grid.map((row) => ' {' + row.join(', ') + '}').join(',\n') -} - -// Everything the harness puts *above* the student's spliced-in code. Kept as its -// own string so we can measure its line count and translate compile-error line -// numbers back to what the student sees in their editor. -// -// The `wall` harness hands the student just a `Robot` (a reactive, sense-as-you-go -// algorithm like the wall follower). The `astar` harness also hands them the whole -// `Maze` — random access to every cell via `maze.cellAt(...)` — and imports -// `java.util.*`, because a global planner like A* needs the full map plus -// PriorityQueue/HashMap up front. The trail emission is identical either way. -export type HarnessMode = 'wall' | 'astar' - -function harnessPrefix(grid: number[][], mode: HarnessMode): string { - const imports = - mode === 'astar' - ? 'import java.util.*;\nimport com.frc2713.mazesolver.*;' - : 'import com.frc2713.mazesolver.*;' - const call = mode === 'astar' ? 'new MazeRun().solve(maze, robot);' : 'new MazeRun().solve(robot);' - return `${imports} - -public class MazeRun { - static final int[][] GRID = { -${mazeGridLiteral(grid)} - }; - - public static void main(String[] args) { - Maze maze = new GridMaze(GRID); - Robot robot = maze.robot(); - - ${call} - - // Emit the Maze Trail as one sentinel-tagged JSON line of [row,col] pairs. - int[][] trail = robot.trail(); - StringBuilder sb = new StringBuilder("__TRAIL__ ["); - for (int i = 0; i < trail.length; i++) { - if (i > 0) sb.append(','); - sb.append('[').append(trail[i][0]).append(',').append(trail[i][1]).append(']'); - } - System.out.println(sb.append(']')); - } - - // ===== your algorithm ===== -` -} - -// The harness closes the class after the student's spliced-in code. -const HARNESS_SUFFIX = '\n}\n' - -// How many lines the harness inserts above the student's first line. Compile -// errors come back as "line N: ..." counted in the assembled file; subtracting -// this maps them to the line the student actually typed. The offset depends on -// the mode (the astar prefix has one extra import line), so pass the same mode -// used to build the harness. -export function studentLineOffset(grid: number[][], mode: HarnessMode = 'wall'): number { - return harnessPrefix(grid, mode).split('\n').length - 1 -} - -// Assemble the full compilation unit: harness prefix + student code + close. -export function buildMazeHarness( - grid: number[][], - studentCode: string, - mode: HarnessMode = 'wall', -): string { - return harnessPrefix(grid, mode) + studentCode.trimEnd() + HARNESS_SUFFIX -} - -// Rewrite the "line N:" prefixes in a compile-error message so they point at the -// student's editor lines instead of the assembled harness. Runtime errors have -// no line numbers under CheerpJ, so they pass through untouched. -export function retargetErrorLines(output: string, offset: number): string { - return output.replace(/^line (\d+):/gm, (_m, n) => `line ${Math.max(1, Number(n) - offset)}:`) -} - -export interface TrailResult { - // Cells in [x, y] = [col, row] order (the swap from Java-native [row, col] - // happens here and nowhere else), including the Start cell first. - cells: [number, number][] -} - -// Find the __TRAIL__ sentinel line in captured stdout and parse it. Returns null -// if no sentinel line is present (treat as "algorithm produced no trail"). -export function parseTrail(output: string): TrailResult | null { - const line = output.split('\n').find((l) => l.startsWith('__TRAIL__ ')) - if (!line) return null - try { - const rowCol = JSON.parse(line.slice('__TRAIL__ '.length)) as [number, number][] - // The one conversion point: Java is [row, col]; the robot state is [x, y]. - return { cells: rowCol.map(([row, col]) => [col, row]) } - } catch { - return null - } -} diff --git a/site/src/lib/pythonRuntime.ts b/site/src/lib/pythonRuntime.ts index 992cf3b..0ebfa00 100644 --- a/site/src/lib/pythonRuntime.ts +++ b/site/src/lib/pythonRuntime.ts @@ -1,4 +1,7 @@ -import type { RunOutcome } from './javaRuntime' +export interface RunOutcome { + ok: boolean + output: string +} export interface RunnerResponse { ok: boolean diff --git a/site/src/routes/LessonView.tsx b/site/src/routes/LessonView.tsx index ba81418..f2bf3a0 100644 --- a/site/src/routes/LessonView.tsx +++ b/site/src/routes/LessonView.tsx @@ -142,7 +142,6 @@ export function LessonView() {