From 026afe1ed58295504f019ff1d8ed130d4a913c31 Mon Sep 17 00:00:00 2001 From: devmtnaing Date: Mon, 28 Sep 2026 15:27:06 +0630 Subject: [PATCH] Code review: escape typed input, keep widget focus, bound verify runs - longest-substring: narration and widget lines escape the string the reader typed; a shared ?s=ab link injected markup and garbled step 6 - esc() moves to kit.js, the one escaper lessons import; valid-palindrome drops its own copy - the stepper puts focus back on a redrawn widget chip or cell, which 44 widgets dropped to on a keyboard pick - home page: a rate-limited replaceState in Safari no longer throws - run.py: each approach x language times out after 20 minutes and removes its container; rust:1-slim pinned to rust:1.98-slim, the version the badges quote - audit: wait out the 150ms address debounce before checking for a query, and stop playback only if the space test started it --- .../references/lesson-kit.md | 8 +++- .github/workflows/verify.yml | 4 +- CONTRIBUTING.md | 2 +- scripts/audit.mjs | 4 +- scripts/verify/run.py | 24 ++++++++--- src/lessons/3sum/lesson.js | 2 +- src/lessons/basic-calculator/lesson.js | 2 +- .../best-time-to-buy-and-sell-stock/lesson.js | 2 +- .../binary-tree-maximum-path-sum/lesson.js | 2 +- src/lessons/climbing-stairs/lesson.js | 2 +- src/lessons/coin-change/lesson.js | 2 +- src/lessons/course-schedule/lesson.js | 2 +- src/lessons/diameter-of-binary-tree/lesson.js | 2 +- .../find-median-from-data-stream/lesson.js | 2 +- .../implement-trie-prefix-tree/lesson.js | 2 +- src/lessons/invert-binary-tree/lesson.js | 2 +- .../kth-largest-element-in-an-array/lesson.js | 2 +- .../largest-rectangle-in-histogram/lesson.js | 2 +- src/lessons/linked-list-cycle/lesson.js | 2 +- .../lesson.js | 2 +- .../lesson.js | 43 ++++++++++--------- .../lesson.js | 2 +- src/lessons/lru-cache/lesson.js | 2 +- src/lessons/majority-element/lesson.js | 2 +- .../maximum-depth-of-binary-tree/lesson.js | 2 +- src/lessons/maximum-subarray/lesson.js | 2 +- .../median-of-two-sorted-arrays/lesson.js | 2 +- src/lessons/merge-intervals/lesson.js | 6 +-- src/lessons/merge-k-sorted-lists/lesson.js | 2 +- src/lessons/merge-two-sorted-lists/lesson.js | 2 +- .../minimum-window-substring/lesson.js | 2 +- src/lessons/move-zeroes/lesson.js | 2 +- src/lessons/n-queens/lesson.js | 2 +- src/lessons/number-of-islands/lesson.js | 2 +- src/lessons/permutations/lesson.js | 2 +- .../product-of-array-except-self/lesson.js | 2 +- src/lessons/reverse-linked-list/lesson.js | 2 +- .../reverse-nodes-in-k-group/lesson.js | 2 +- src/lessons/rotate-image/lesson.js | 2 +- .../search-in-rotated-sorted-array/lesson.js | 2 +- .../lesson.js | 2 +- src/lessons/single-number/lesson.js | 2 +- src/lessons/sliding-window-maximum/lesson.js | 2 +- src/lessons/trapping-rain-water/lesson.js | 2 +- src/lessons/two-sum/lesson.js | 2 +- src/lessons/valid-anagram/lesson.js | 2 +- src/lessons/valid-palindrome/lesson.js | 41 ++++++++---------- src/lessons/valid-parentheses/lesson.js | 2 +- src/lessons/word-ladder/lesson.js | 2 +- src/lessons/word-search-ii/lesson.js | 2 +- src/lib/kit.js | 4 ++ src/lib/stage.js | 2 +- src/lib/stepper.js | 28 ++++++++++-- src/pages/index.astro | 4 +- 54 files changed, 151 insertions(+), 103 deletions(-) diff --git a/.claude/skills/leetcode-solution-page/references/lesson-kit.md b/.claude/skills/leetcode-solution-page/references/lesson-kit.md index 0a3d84e..f43fad9 100644 --- a/.claude/skills/leetcode-solution-page/references/lesson-kit.md +++ b/.claude/skills/leetcode-solution-page/references/lesson-kit.md @@ -119,7 +119,13 @@ worked". A control shows a list back as `1, 2, 3` by itself; give it a string — `?approach=heap&step=7&lang=python&nums=1,2,3` — so a mode's `id` and a control's `key` are part of every link a reader shares. Keep them short and stable once published, and make `parse(format(v))` give back `v` -for every control, so a shared link reopens the same input. The part 1 widget uses `presetChips(sets, active)` for its chips +for every control, so a shared link reopens the same input. A link is input +anyone can write, and narration, notes and widget lines are HTML: a value from +a control that allows `<`, `>` or `&` goes through `esc()` (kit.js) before it is +spliced into one (stage.js shapes and the hover tip escape on their own). A +widget redraws on every pick; the stepper puts focus back on the redrawn chip +or cell with the same `data-*` attributes, so give each clickable one a stable +`data-*` key (`data-set`, `data-i`). The part 1 widget uses `presetChips(sets, active)` for its chips (the active one is `aria-pressed`, which lesson.css draws as selected; a widget's own toggle chips should set it too) and `widgetLabel(text)` for the note beside its heading. Anything a lesson draws uses a class from `lesson.css`, `kit.css` diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 284ac6b..bad4504 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -14,7 +14,7 @@ # Actions tab to verify all of them. # # The runner is pinned to ubuntu-24.04 (ubuntu-latest moves to 26.04, which -# may not carry a prebuilt Ruby 3.1), and Node 24, Ruby 3.1 and Python 3.12 are pinned to the versions the badges were +# may not carry a prebuilt Ruby 3.1), and Node 24, Ruby 3.1, Python 3.12 and Rust 1.98 are pinned to the versions the badges were # measured with: a stack depth a badge quotes ("overflows Ruby 3.1's default # stack past 7,687 deep") only holds for that runtime. Change them together # with the badges. @@ -154,6 +154,6 @@ jobs: with: ruby-version: '3.1' - name: Pull the Go and Rust images run.py uses - run: docker pull -q golang:1.23-alpine && docker pull -q rust:1-slim + run: docker pull -q golang:1.23-alpine && docker pull -q rust:1.98-slim - name: Every listing, five languages, then the walkthroughs run: python3 scripts/verify/run.py "${{ matrix.slug }}" --strict diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 99ac188..cf947fb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,7 +29,7 @@ code they can trust. So three rules are firm: - Node 20+, Python 3.10+, Ruby 3 - Docker, for Go and Rust. The verifier runs them in `golang:1.23-alpine` and - `rust:1-slim`, and reports them as *skipped*, not passed, when Docker isn't + `rust:1.98-slim`, and reports them as *skipped*, not passed, when Docker isn't running. ## Building a page, step by step diff --git a/scripts/audit.mjs b/scripts/audit.mjs index 40b8449..83ae5d5 100644 --- a/scripts/audit.mjs +++ b/scripts/audit.mjs @@ -173,6 +173,7 @@ async function keysAndLink(page, url) { const found = []; await page.goto(url); await page.waitForSelector('#lesson .atab'); + await page.waitForTimeout(300); // the address is written after a 150ms debounce if (new URL(page.url()).search) found.push(`an untouched page has a query: ${new URL(page.url()).search}`); const count = () => page.$eval('#lesson [data-count]', (e) => e.textContent.trim()); const playLabel = () => page.$eval('#lesson [data-act="play"]', (e) => e.textContent.trim()); @@ -181,7 +182,8 @@ async function keysAndLink(page, url) { await page.keyboard.press(' '); if (!(await count()).startsWith('2 /') || (await playLabel()) !== 'Play') { found.push(`space on a focused Next: step ${await count()}, play button "${await playLabel()}" (want step 2, not playing)`); - await page.click('#lesson [data-act="play"]').catch(() => {}); + // stop playback if space started it; clicking a stopped Play would start it + if ((await playLabel()) !== 'Play') await page.click('#lesson [data-act="play"]').catch(() => {}); } if ((await page.$$('#lesson .atab')).length > 1) { await page.focus('#lesson .atab[aria-selected="true"]'); diff --git a/scripts/verify/run.py b/scripts/verify/run.py index d66643f..d980eed 100644 --- a/scripts/verify/run.py +++ b/scripts/verify/run.py @@ -26,7 +26,7 @@ lesson's lesson.js — the text a reader copies, not a draft. 3. Runs each approach x language and compares line by line. Ruby, Python and JavaScript run locally; Go and Rust run in Docker (golang:1.23-alpine, - rust:1-slim), so Docker must be running. + rust:1.98-slim), so Docker must be running. 4. Runs the walkthrough check (steps.mjs) over the same corpus. A language that could not run is reported as SKIPPED, never as passing. @@ -37,9 +37,12 @@ HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.abspath(os.path.join(HERE, '..', '..')) EXT = {'ruby': 'rb', 'python': 'py', 'javascript': 'js', 'go': 'go', 'rust': 'rs'} +# One approach x language, compile included. A listing that never finishes +# fails here instead of holding the CI job to its 40-minute limit. +TIMEOUT = 20 * 60 -def command(lang, work, big_stack=False): +def command(lang, work, big_stack=False, name=None): if lang == 'ruby': return ['ruby', f'{work}/main.rb'] if lang == 'python': @@ -47,11 +50,11 @@ def command(lang, work, big_stack=False): if lang == 'javascript': return ['node'] + (['--stack-size=16000'] if big_stack else []) + [f'{work}/main.cjs'] if lang == 'go': # the build cache outlives the container, so the standard library compiles once - return ['docker', 'run', '--rm', '-i', '-v', f'{work}:/w', '-v', 'leetcode-go-build:/root/.cache/go-build', + return ['docker', 'run', '--rm', '-i', '--name', name, '-v', f'{work}:/w', '-v', 'leetcode-go-build:/root/.cache/go-build', '-w', '/w', 'golang:1.23-alpine', 'sh', '-c', 'go build -o m main.go && ./m'] if lang == 'rust': - return ['docker', 'run', '--rm', '-i', '-v', f'{work}:/w', '-w', '/w', 'rust:1-slim', + return ['docker', 'run', '--rm', '-i', '--name', name, '-v', f'{work}:/w', '-w', '/w', 'rust:1.98-slim', 'sh', '-c', 'rustc -O -o m main.rs 2>&1 >/dev/null | grep -E "^error" ; ./m'] @@ -123,8 +126,17 @@ def run_one(mode, lang, todo, cases): main_name = 'main.cjs' if lang == 'javascript' else 'main.' + ext with open(f'{work}/{main_name}', 'w') as f: f.write(S.DRIVERS[lang].replace('{SOL}', solution)) - r = subprocess.run(command(lang, work, big_stack), input=cases, capture_output=True, text=True, env=env, - preexec_fn=raise_stack if big_stack and lang in ('ruby', 'javascript') else None) + # named, so a container that outlives the timeout can be removed: killing + # the docker client alone leaves it running + name = f'verify-{os.getpid()}-{mode}-{lang}' + try: + r = subprocess.run(command(lang, work, big_stack, name), input=cases, capture_output=True, text=True, + env=env, timeout=TIMEOUT, + preexec_fn=raise_stack if big_stack and lang in ('ruby', 'javascript') else None) + except subprocess.TimeoutExpired: + if lang in ('go', 'rust'): + subprocess.run(['docker', 'rm', '-f', name], capture_output=True) + return True, f'FAIL {mode}/{lang}: still running after {TIMEOUT // 60} minutes' got = r.stdout.split('\n') bad = [i for i, (_, e) in enumerate(todo) if i >= len(got) or got[i] != e] if not bad: diff --git a/src/lessons/3sum/lesson.js b/src/lessons/3sum/lesson.js index 332481e..c763d58 100644 --- a/src/lessons/3sum/lesson.js +++ b/src/lessons/3sum/lesson.js @@ -631,7 +631,7 @@ mountLesson({ // from -3..3, 5,000 of 3–30 from -10..10, and five at n = 3000 — against an // oracle that counts values and checks pairs of distinct values. Triplets // are compared in sorted order. The brute force skips the five at n = 3000. - // Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: { brute: 'ran here · 20,008 cases, not the five at n = 3000', pointers: 'ran here · 20,013 cases' }, python: { brute: 'ran here · 20,008 cases, not the five at n = 3000', pointers: 'ran here · 20,013 cases' }, diff --git a/src/lessons/basic-calculator/lesson.js b/src/lessons/basic-calculator/lesson.js index 530f58c..f20509d 100644 --- a/src/lessons/basic-calculator/lesson.js +++ b/src/lessons/basic-calculator/lesson.js @@ -616,7 +616,7 @@ mountLesson({ // (149,999 nested brackets, nested unary minus, 50,000 numbers, a random // expression, numbers near 2³¹ − 1, 75,000 "(1)") — against an oracle that // keeps a stack of bracket signs. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim); the recursive listing ran with a + // (golang:1.23-alpine, rust:1.98-slim); the recursive listing ran with a // larger stack in Ruby, Node and Rust. Default-stack limits were measured // cold, one nested expression per process (Rust: a release build, 8 MB main // thread). diff --git a/src/lessons/best-time-to-buy-and-sell-stock/lesson.js b/src/lessons/best-time-to-buy-and-sell-stock/lesson.js index 82c0175..962cc98 100644 --- a/src/lessons/best-time-to-buy-and-sell-stock/lesson.js +++ b/src/lessons/best-time-to-buy-and-sell-stock/lesson.js @@ -635,7 +635,7 @@ mountLesson({ code: CODE, // How each language was actually checked, printed as the part 3 badges. // The corpus: 4 examples, 15,000 short price lists over 0..6, 5,000 up to 10⁴, three of 3,000 — against all-pairs search; the one-pass versions also ran four at n = 10⁵. - // Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,007 cases', python: 'ran here · 20,007 cases', diff --git a/src/lessons/binary-tree-maximum-path-sum/lesson.js b/src/lessons/binary-tree-maximum-path-sum/lesson.js index 57fa57e..b744b6b 100644 --- a/src/lessons/binary-tree-maximum-path-sum/lesson.js +++ b/src/lessons/binary-tree-maximum-path-sum/lesson.js @@ -532,7 +532,7 @@ mountLesson({ // non-recursive oracle. Trying every node as the top skips those six. Ruby // and Node ran with a larger stack (BIG_STACK); their default-stack limits // were measured cold, one chain per process. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim) on their default stacks. + // (golang:1.23-alpine, rust:1.98-slim) on their default stacks. verification: { ruby: { every: 'ran here · 20,007 cases, not the six at 3 × 10⁴; overflows Ruby 3.1\'s default stack past 8,731 deep', once: 'ran here · overflows Ruby 3.1\'s default stack past 8,186 deep' }, python: { every: 'ran here · 20,007 cases, not the six at 3 × 10⁴', once: 'ran here · 20,013 cases, 3 × 10⁴ calls deep' }, diff --git a/src/lessons/climbing-stairs/lesson.js b/src/lessons/climbing-stairs/lesson.js index aa5d537..539b241 100644 --- a/src/lessons/climbing-stairs/lesson.js +++ b/src/lessons/climbing-stairs/lesson.js @@ -579,7 +579,7 @@ mountLesson({ // with binomials (itself checked by enumerating every climb up to 20). // Plain recursion ran on n = 1..35 in every language, and on n = 45, timed // on an Apple M5 Pro — right answer each time, and the time is the point. - // Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: { naive: 'ran here · n = 1–35, and 45 in 63 s', memo: 'ran here · every n, 1–45', dp: 'ran here · every n, 1–45' }, python: { naive: 'ran here · n = 1–35, and 45 in 72 s', memo: 'ran here · every n, 1–45', dp: 'ran here · every n, 1–45' }, diff --git a/src/lessons/coin-change/lesson.js b/src/lessons/coin-change/lesson.js index 9c0f8ca..a02c66d 100644 --- a/src/lessons/coin-change/lesson.js +++ b/src/lessons/coin-change/lesson.js @@ -525,7 +525,7 @@ mountLesson({ // from 1..10 with amounts 0..12, 5,000 of up to 12 coins with amounts up to // 500, and five at amount = 10⁴ — against a breadth-first search over the // amounts. The plain recursion runs only the 15,131 cases with amount ≤ 12. - // Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: { recurse: 'ran here · 15,131 cases, amount ≤ 12 only', table: 'ran here · 20,014 cases' }, python: { recurse: 'ran here · 15,131 cases, amount ≤ 12 only', table: 'ran here · 20,014 cases' }, diff --git a/src/lessons/course-schedule/lesson.js b/src/lessons/course-schedule/lesson.js index bac5506..7355e15 100644 --- a/src/lessons/course-schedule/lesson.js +++ b/src/lessons/course-schedule/lesson.js @@ -699,7 +699,7 @@ mountLesson({ // chain closed into a cycle, random DAG and random graph with 5,000 pairs, // a 2,000-cycle, one course needed by all) — against an oracle that peels // off free courses until none are left. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim), every language on its default stack. + // (golang:1.23-alpine, rust:1.98-slim), every language on its default stack. verification: { ruby: 'ran here · 20,016 cases', python: 'ran here · 20,016 cases', diff --git a/src/lessons/diameter-of-binary-tree/lesson.js b/src/lessons/diameter-of-binary-tree/lesson.js index 2f8419e..877cbab 100644 --- a/src/lessons/diameter-of-binary-tree/lesson.js +++ b/src/lessons/diameter-of-binary-tree/lesson.js @@ -662,7 +662,7 @@ mountLesson({ // all-right and zigzag chains, a random tree, a complete tree, a deep chain // that forks) — against an oracle that treats the tree as a graph and finds // the longest shortest path (all pairs, or double BFS when big). Go and Rust - // ran in Docker (golang:1.23-alpine, rust:1-slim). + // ran in Docker (golang:1.23-alpine, rust:1.98-slim). // Measured cold, one 10⁴ chain per process: Ruby 3.1's default stack // overflows past 7,705 nodes (brute) and 8,732 (DFS); Node 24's past 6,219 // and 7,773. Both pass all 20,009 cases with a larger stack diff --git a/src/lessons/find-median-from-data-stream/lesson.js b/src/lessons/find-median-from-data-stream/lesson.js index 3ae84f8..b151d59 100644 --- a/src/lessons/find-median-from-data-stream/lesson.js +++ b/src/lessons/find-median-from-data-stream/lesson.js @@ -633,7 +633,7 @@ mountLesson({ // The corpus: the example, 6 edges, 15,000 random runs of up to 20 calls // over -5..5, 5,000 of up to 500 over ±10⁵, and six of 5 × 10⁴ calls — // against a Fenwick tree over every value. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim). + // (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,013 cases', python: 'ran here · 20,013 cases', diff --git a/src/lessons/implement-trie-prefix-tree/lesson.js b/src/lessons/implement-trie-prefix-tree/lesson.js index 39dcc0f..59d5996 100644 --- a/src/lessons/implement-trie-prefix-tree/lesson.js +++ b/src/lessons/implement-trie-prefix-tree/lesson.js @@ -660,7 +660,7 @@ mountLesson({ // over two or three letters, 5,000 of up to 300 calls, and four of 3 × 10⁴ // calls (2,000-letter words, random words, 20,000 prefix queries that miss // 10,000 words) — against a sorted-list oracle. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim). + // (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,011 cases', python: 'ran here · 20,011 cases', diff --git a/src/lessons/invert-binary-tree/lesson.js b/src/lessons/invert-binary-tree/lesson.js index 664d99e..04a30d0 100644 --- a/src/lessons/invert-binary-tree/lesson.js +++ b/src/lessons/invert-binary-tree/lesson.js @@ -563,7 +563,7 @@ mountLesson({ // over -3..3, 5,000 of up to 100 nodes over -100..100, and three 100-node // chains (all-left, all-right, zigzag) — against a reference that builds a // new mirrored tree rather than swapping in place. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim). + // (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,010 cases', python: 'ran here · 20,010 cases', diff --git a/src/lessons/kth-largest-element-in-an-array/lesson.js b/src/lessons/kth-largest-element-in-an-array/lesson.js index 53634ba..b4b7b37 100644 --- a/src/lessons/kth-largest-element-in-an-array/lesson.js +++ b/src/lessons/kth-largest-element-in-an-array/lesson.js @@ -462,7 +462,7 @@ mountLesson({ // The corpus: the 2 examples, 5 edges, 15,000 random arrays of 1–9 values // from -3..3 with any valid k, 5,000 of up to 300 across ±10⁴, and five at // n = 10⁵ — against an oracle that counts values and walks down from the - // largest. Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // largest. Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,012 cases', python: 'ran here · 20,012 cases', diff --git a/src/lessons/largest-rectangle-in-histogram/lesson.js b/src/lessons/largest-rectangle-in-histogram/lesson.js index 447c85b..da031dd 100644 --- a/src/lessons/largest-rectangle-in-histogram/lesson.js +++ b/src/lessons/largest-rectangle-in-histogram/lesson.js @@ -420,7 +420,7 @@ mountLesson({ // 12 bars from 0..5, 5,000 of up to 300 across the full range, and five of // 10⁵ bars — against a nearest-lower-by-jumping oracle. Growing around each // bar skips the five at 10⁵. Go and Rust ran in Docker (golang:1.23-alpine, - // rust:1-slim). + // rust:1.98-slim). verification: { ruby: { extend: 'ran here · 20,008 cases, not the five at n = 10⁵', stack: 'ran here · 20,013 cases' }, python: { extend: 'ran here · 20,008 cases, not the five at n = 10⁵', stack: 'ran here · 20,013 cases' }, diff --git a/src/lessons/linked-list-cycle/lesson.js b/src/lessons/linked-list-cycle/lesson.js index 84b0e7e..160f919 100644 --- a/src/lessons/linked-list-cycle/lesson.js +++ b/src/lessons/linked-list-cycle/lesson.js @@ -601,7 +601,7 @@ mountLesson({ // empty list and repeated values), 15,000 lists up to 8 nodes with every pos, // 4,990 up to 200 nodes over the full value range, and four at the 10⁴-node // constraint — each checked against the pos it was built from. Go and Rust - // ran in Docker (golang:1.23-alpine, rust:1-slim); the Rust harness builds + // ran in Docker (golang:1.23-alpine, rust:1.98-slim); the Rust harness builds // the Rc list the caveat describes. verification: { ruby: 'ran here · 20,001 cases up to n = 10⁴', diff --git a/src/lessons/longest-increasing-path-in-a-matrix/lesson.js b/src/lessons/longest-increasing-path-in-a-matrix/lesson.js index ed46cc3..103a293 100644 --- a/src/lessons/longest-increasing-path-in-a-matrix/lesson.js +++ b/src/lessons/longest-increasing-path-in-a-matrix/lesson.js @@ -746,7 +746,7 @@ mountLesson({ // reversed, a walled snake 20,099 calls deep, r + c, all equal, a // checkerboard, random values to 2³¹ − 1) — against an oracle that sorts // the cells by value. Go and Rust ran in Docker (golang:1.23-alpine, - // rust:1-slim) on their default stacks. The memo DFS limits were measured + // rust:1.98-slim) on their default stacks. The memo DFS limits were measured // cold, one walled snake per process, on each default stack. verification: { ruby: { memo: 'ran here · overflows Ruby 3.1\'s default stack past 2,846 calls deep', peel: 'ran here · 20,016 cases' }, diff --git a/src/lessons/longest-substring-without-repeating-characters/lesson.js b/src/lessons/longest-substring-without-repeating-characters/lesson.js index f8441ad..c9f8183 100644 --- a/src/lessons/longest-substring-without-repeating-characters/lesson.js +++ b/src/lessons/longest-substring-without-repeating-characters/lesson.js @@ -10,7 +10,7 @@ import { mountLesson } from '../../lib/stepper.js'; import { pick, onLangChange } from '../../lib/i18n.js'; import { cells, kv, readout, slots, stagePanel } from '../../lib/stage.js'; -import { t, exampleTitle, LANGUAGES, k, c, stageRow, stageGap, presetChips, widgetLabel } from '../../lib/kit.js'; +import { t, esc, exampleTitle, LANGUAGES, k, c, stageRow, stageGap, presetChips, widgetLabel } from '../../lib/kit.js'; const MAX_LEN = 12; @@ -26,6 +26,9 @@ function parseS(text) { // A space is a character like any other; draw it so it can be seen. const vis = (ch) => (ch === ' ' ? '␣' : ch); const quote = (str) => `"${str}"`; +// The same, escaped, for narration and widget text, which are HTML: s may hold < > &. +const visH = (ch) => esc(vis(ch)); +const quoteH = (str) => esc(quote(str)); /* ---------------- step generators ---------------- */ @@ -50,15 +53,15 @@ function buildBrute({ s }) { while (j < n && !seen.includes(s[j])) { seen.push(s[j]); steps.push(snap({ i, j, seen: [...seen], line: 'take', tag: t('new', 'အသစ်'), - note: t(`'${vis(s[j])}' is not in seen: take it. The run is ${quote(s.slice(i, j + 1))}, length ${j - i + 1}.`, - `'${vis(s[j])}' သည် seen ထဲ မရှိ — ယူသည်။ run သည် ${quote(s.slice(i, j + 1))}၊ အရှည် ${j - i + 1}။`) })); + note: t(`'${visH(s[j])}' is not in seen: take it. The run is ${quoteH(s.slice(i, j + 1))}, length ${j - i + 1}.`, + `'${visH(s[j])}' သည် seen ထဲ မရှိ — ယူသည်။ run သည် ${quoteH(s.slice(i, j + 1))}၊ အရှည် ${j - i + 1}။`) })); j += 1; } const stop = j < n; steps.push(snap({ i, j, seen: [...seen], repeat: stop ? s.indexOf(s[j], i) : null, line: 'test', tag: stop ? t('repeat', 'ထပ်') : t('end', 'အဆုံး'), note: stop - ? t(`'${vis(s[j])}' at index ${j} is already in the run, at index ${s.indexOf(s[j], i)}. Stop.`, - `index ${j} ရှိ '${vis(s[j])}' သည် run ထဲ index ${s.indexOf(s[j], i)} တွင် ရှိပြီးသား။ ရပ်သည်။`) + ? t(`'${visH(s[j])}' at index ${j} is already in the run, at index ${s.indexOf(s[j], i)}. Stop.`, + `index ${j} ရှိ '${visH(s[j])}' သည် run ထဲ index ${s.indexOf(s[j], i)} တွင် ရှိပြီးသား။ ရပ်သည်။`) : t('The end of the string. Stop.', 'string ၏ အဆုံး။ ရပ်သည်။') })); const was = best; best = Math.max(best, j - i); @@ -89,29 +92,29 @@ function buildWindow({ s }) { for (let right = 0; right < n; right++) { const ch = s[right]; steps.push(snap({ right, line: 'read', tag: t(`'${vis(ch)}'`, `'${vis(ch)}'`), - note: t(`right = ${right}: '${vis(ch)}' comes in.`, `right = ${right} — '${vis(ch)}' ဝင်လာသည်။`) })); + note: t(`right = ${right}: '${visH(ch)}' comes in.`, `right = ${right} — '${visH(ch)}' ဝင်လာသည်။`) })); if (ch in last) { const prev = last[ch]; if (prev >= left) { const was = left; left = prev + 1; steps.push(snap({ right, prev, jumped: [was, left], line: 'jump', tag: t('jump', 'ခုန်'), - note: t(`'${vis(ch)}' is already in the window, at index ${prev}. Move left from ${was} to ${left}, just past it — in one move, not one at a time.`, - `'${vis(ch)}' သည် window ထဲ index ${prev} တွင် ရှိပြီးသား။ left ကို ${was} မှ ${left} သို့ — ၎င်း၏ နောက်သို့ — တစ်ကြိမ်တည်း ရွှေ့သည်၊ တစ်ခုချင်း မဟုတ်ပါ။`) })); + note: t(`'${visH(ch)}' is already in the window, at index ${prev}. Move left from ${was} to ${left}, just past it — in one move, not one at a time.`, + `'${visH(ch)}' သည် window ထဲ index ${prev} တွင် ရှိပြီးသား။ left ကို ${was} မှ ${left} သို့ — ၎င်း၏ နောက်သို့ — တစ်ကြိမ်တည်း ရွှေ့သည်၊ တစ်ခုချင်း မဟုတ်ပါ။`) })); } else { steps.push(snap({ right, prev, stale: true, line: 'jump', tag: t('stale', 'ဟောင်း'), - note: t(`'${vis(ch)}' was last seen at index ${prev}, but that is left of left (${left}) — outside the window. Ignore it; moving left back would let a repeat in.`, - `'${vis(ch)}' ကို နောက်ဆုံး index ${prev} တွင် တွေ့ခဲ့သော်လည်း ၎င်းသည် left (${left}) ၏ ဘယ်ဘက် — window အပြင်ဘက်။ လျစ်လျူရှုသည် — left ကို နောက်ပြန်ရွှေ့လျှင် ထပ်နေသော character ဝင်လာမည်။`) })); + note: t(`'${visH(ch)}' was last seen at index ${prev}, but that is left of left (${left}) — outside the window. Ignore it; moving left back would let a repeat in.`, + `'${visH(ch)}' ကို နောက်ဆုံး index ${prev} တွင် တွေ့ခဲ့သော်လည်း ၎င်းသည် left (${left}) ၏ ဘယ်ဘက် — window အပြင်ဘက်။ လျစ်လျူရှုသည် — left ကို နောက်ပြန်ရွှေ့လျှင် ထပ်နေသော character ဝင်လာမည်။`) })); } } last[ch] = right; steps.push(snap({ right, stored: ch, line: 'store', tag: t('remember', 'မှတ်'), - note: t(`Remember '${vis(ch)}' → ${right}.`, `'${vis(ch)}' → ${right} ကို မှတ်သည်။`) })); + note: t(`Remember '${visH(ch)}' → ${right}.`, `'${visH(ch)}' → ${right} ကို မှတ်သည်။`) })); const was = best; best = Math.max(best, right - left + 1); steps.push(snap({ right, improved: best > was, line: 'best', tag: t(`best ${best}`, `best ${best}`), - note: t(`The window ${quote(s.slice(left, right + 1))} has length ${right - left + 1}${best > was ? `: best = ${best}` : `, not more than ${best}`}.`, - `window ${quote(s.slice(left, right + 1))} ၏ အရှည် ${right - left + 1}${best > was ? ` — best = ${best}` : ` — ${best} ထက် မပို`}။`) })); + note: t(`The window ${quoteH(s.slice(left, right + 1))} has length ${right - left + 1}${best > was ? `: best = ${best}` : `, not more than ${best}`}.`, + `window ${quoteH(s.slice(left, right + 1))} ၏ အရှည် ${right - left + 1}${best > was ? ` — best = ${best}` : ` — ${best} ထက် မပို`}။`) })); } steps.push(snap({ line: 'ret', finished: true, tag: t(`return ${best}`, `${best} ပြန်`), note: t(`Return ${best}. Each character came in once, and left only ever moved forward.`, @@ -418,18 +421,18 @@ function mountRunWidget(host) { const inRun = x >= from && x <= to; const cls = x === dupAt || x === firstAt ? 'cut' : inRun ? 'kept' : ''; const ends = x === from || x === to; - return `
${vis(ch)}${x}
`; + return `
${visH(ch)}${x}
`; }).join(''); widgetLabel(pick(t(`click the ${state.next === 'from' ? 'start' : 'end'}`, `${state.next === 'from' ? 'အစ' : 'အဆုံး'} ကို နှိပ်ပါ`))); q('[data-line]').innerHTML = pick(dupAt >= 0 - ? t(`${quote(run)} repeats '${vis(str[dupAt])}' (indices ${firstAt} and ${dupAt}), so it does not count. A substring cannot skip the second copy — skipping makes a subsequence.`, - `${quote(run)} တွင် '${vis(str[dupAt])}' ထပ်သည် (index ${firstAt} နှင့် ${dupAt}) — မရေတွက်ပါ။ substring သည် ဒုတိယ copy ကို ကျော်၍ မရ — ကျော်လျှင် subsequence ဖြစ်သွားသည်။`) - : t(`${quote(run)} is ${run.length} characters in a row, none repeated. The longest in this string is ${longestIn(str)}.`, - `${quote(run)} သည် ဆက်တိုက် character ${run.length} လုံး၊ တစ်လုံးမျှ မထပ်ပါ။ ဤ string ၏ အရှည်ဆုံးမှာ ${longestIn(str)}။`)); + ? t(`${quoteH(run)} repeats '${visH(str[dupAt])}' (indices ${firstAt} and ${dupAt}), so it does not count. A substring cannot skip the second copy — skipping makes a subsequence.`, + `${quoteH(run)} တွင် '${visH(str[dupAt])}' ထပ်သည် (index ${firstAt} နှင့် ${dupAt}) — မရေတွက်ပါ။ substring သည် ဒုတိယ copy ကို ကျော်၍ မရ — ကျော်လျှင် subsequence ဖြစ်သွားသည်။`) + : t(`${quoteH(run)} is ${run.length} characters in a row, none repeated. The longest in this string is ${longestIn(str)}.`, + `${quoteH(run)} သည် ဆက်တိုက် character ${run.length} လုံး၊ တစ်လုံးမျှ မထပ်ပါ။ ဤ string ၏ အရှည်ဆုံးမှာ ${longestIn(str)}။`)); - q('[data-expr]').innerHTML = `s[${from}..${to}] = ${quote([...run].map(vis).join(''))} · ${new Set(run).size} distinct of ${run.length}`; + q('[data-expr]').innerHTML = `s[${from}..${to}] = ${quoteH([...run].map(vis).join(''))} · ${new Set(run).size} distinct of ${run.length}`; q('[data-total]').innerHTML = dupAt >= 0 ? `✗${pick(t('repeats', 'ထပ်နေ'))}` : `${run.length}${pick(t('length', 'အရှည်'))}`; @@ -542,7 +545,7 @@ mountLesson({ // characters from "abc", 5,000 of up to 40 from a dozen characters with a // space, and five at n = 5 × 10⁴ — against an oracle that shrinks a counted // window. Both approaches ran on every case. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim). + // (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,015 cases', python: 'ran here · 20,015 cases', diff --git a/src/lessons/lowest-common-ancestor-of-a-binary-tree/lesson.js b/src/lessons/lowest-common-ancestor-of-a-binary-tree/lesson.js index ac43458..9803cd7 100644 --- a/src/lessons/lowest-common-ancestor-of-a-binary-tree/lesson.js +++ b/src/lessons/lowest-common-ancestor-of-a-binary-tree/lesson.js @@ -598,7 +598,7 @@ mountLesson({ // measured cold here, Ruby 3.1 overflows past 7,687 levels, Node 24 past // 6,906, and Rust's 8 MB main thread aborts at 10⁵ (fine at 5 × 10⁴). // Python (recursion limit raised in the listing) and Go ran a 10⁵ chain. - // Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: { parents: 'ran here · 20,013 cases', recurse: 'ran here · overflows Ruby 3.1\'s default stack past 7,687 deep' }, python: { parents: 'ran here · 20,013 cases', recurse: 'ran here · 20,011 cases, and a 10⁵-deep chain' }, diff --git a/src/lessons/lru-cache/lesson.js b/src/lessons/lru-cache/lesson.js index 28c3392..73e8750 100644 --- a/src/lessons/lru-cache/lesson.js +++ b/src/lessons/lru-cache/lesson.js @@ -872,7 +872,7 @@ mountLesson({ // The corpus: the example, 6 edges, 15,000 random runs of up to 20 calls // over a handful of keys, 5,000 of up to 500 calls, and three of 2 × 10⁵ // calls at capacity 3,000 and 1 — against an OrderedDict oracle. Go and - // Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,010 cases', python: 'ran here · 20,010 cases', diff --git a/src/lessons/majority-element/lesson.js b/src/lessons/majority-element/lesson.js index a8ae594..9e4c340 100644 --- a/src/lessons/majority-element/lesson.js +++ b/src/lessons/majority-element/lesson.js @@ -490,7 +490,7 @@ mountLesson({ // n = 5×10⁴ (random, few distinct values, all equal, and two with the // tightest majority, ⌊n/2⌋ + 1 copies) — every array built to have a // majority, against an oracle that sorts and takes the middle. Go and Rust - // ran in Docker (golang:1.23-alpine, rust:1-slim). + // ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,011 cases', python: 'ran here · 20,011 cases', diff --git a/src/lessons/maximum-depth-of-binary-tree/lesson.js b/src/lessons/maximum-depth-of-binary-tree/lesson.js index 3a147b7..6b57918 100644 --- a/src/lessons/maximum-depth-of-binary-tree/lesson.js +++ b/src/lessons/maximum-depth-of-binary-tree/lesson.js @@ -530,7 +530,7 @@ mountLesson({ // 5,000 of up to 300, and four at the 10⁴-node constraint (all-left, // all-right, zigzag chains and one random tree) — against an iterative // reference with an explicit stack. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim). Recursive Ruby is correct on all of + // (golang:1.23-alpine, rust:1.98-slim). Recursive Ruby is correct on all of // them with a larger VM stack (RUBY_THREAD_VM_STACK_SIZE=8MB), but on Ruby // 3.1's default stack it overflows on the three 10⁴-deep chains; measured, // it survives chains up to 8,733 nodes. Recursive JavaScript passed the diff --git a/src/lessons/maximum-subarray/lesson.js b/src/lessons/maximum-subarray/lesson.js index 263a0a0..f31632c 100644 --- a/src/lessons/maximum-subarray/lesson.js +++ b/src/lessons/maximum-subarray/lesson.js @@ -472,7 +472,7 @@ mountLesson({ // from -5..5, 5,000 of 1–60 across ±10⁴, and five at n = 10⁵ — against an // oracle taking the best difference of prefix sums. The brute force skips // the five at n = 10⁵. Go and Rust ran in Docker (golang:1.23-alpine, - // rust:1-slim). + // rust:1.98-slim). verification: { ruby: { brute: 'ran here · 20,008 cases, not the five at n = 10⁵', kadane: 'ran here · 20,013 cases' }, python: { brute: 'ran here · 20,008 cases, not the five at n = 10⁵', kadane: 'ran here · 20,013 cases' }, diff --git a/src/lessons/median-of-two-sorted-arrays/lesson.js b/src/lessons/median-of-two-sorted-arrays/lesson.js index 240dfd7..9f1a90e 100644 --- a/src/lessons/median-of-two-sorted-arrays/lesson.js +++ b/src/lessons/median-of-two-sorted-arrays/lesson.js @@ -509,7 +509,7 @@ mountLesson({ // The corpus: the 2 examples, 8 edges, 15,000 random pairs of up to 6 // values from -5..5, 5,000 of up to 1,000 each, and four at the limits — // against sort-and-read-the-middle. Each driver prints five decimals. Go - // and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,014 cases', python: 'ran here · 20,014 cases', diff --git a/src/lessons/merge-intervals/lesson.js b/src/lessons/merge-intervals/lesson.js index 579a69c..b02b3a2 100644 --- a/src/lessons/merge-intervals/lesson.js +++ b/src/lessons/merge-intervals/lesson.js @@ -7,10 +7,10 @@ * the last merged one — anything earlier ended before the last one started — * so the sweep compares with one interval, not all of them. */ -import { mountLesson, esc } from '../../lib/stepper.js'; +import { mountLesson } from '../../lib/stepper.js'; import { pick, onLangChange } from '../../lib/i18n.js'; import { cells, readout, slots, stagePanel } from '../../lib/stage.js'; -import { t, exampleTitle, LANGUAGES, k, c, stageGap, presetChips, widgetLabel, stageEmpty } from '../../lib/kit.js'; +import { t, esc, exampleTitle, LANGUAGES, k, c, stageGap, presetChips, widgetLabel, stageEmpty } from '../../lib/kit.js'; const MAX_LEN = 8; const TOP = 20; @@ -565,7 +565,7 @@ mountLesson({ // intervals inside 0..10, 5,000 of 1–40 inside 0..100, and five at // n = 10⁴ — against an oracle that paints a doubled number line. Merged // intervals are compared in sorted order. The brute force skips the five at - // n = 10⁴. Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // n = 10⁴. Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: { brute: 'ran here · 20,010 cases, not the five at n = 10⁴', sweep: 'ran here · 20,015 cases' }, python: { brute: 'ran here · 20,010 cases, not the five at n = 10⁴', sweep: 'ran here · 20,015 cases' }, diff --git a/src/lessons/merge-k-sorted-lists/lesson.js b/src/lessons/merge-k-sorted-lists/lesson.js index fdf373d..79f9c75 100644 --- a/src/lessons/merge-k-sorted-lists/lesson.js +++ b/src/lessons/merge-k-sorted-lists/lesson.js @@ -585,7 +585,7 @@ mountLesson({ // short lists, 5,000 of up to 60 lists up to 20 long, and five of 10⁴ // nodes — against concatenate-and-sort. Merging one at a time skips the // three with 10⁴ lists. Go and Rust ran in Docker (golang:1.23-alpine, - // rust:1-slim). + // rust:1.98-slim). verification: { ruby: { one: 'ran here · 20,011 cases, not the three with 10⁴ lists', halves: 'ran here · 20,014 cases' }, python: { one: 'ran here · 20,011 cases, not the three with 10⁴ lists', halves: 'ran here · 20,014 cases' }, diff --git a/src/lessons/merge-two-sorted-lists/lesson.js b/src/lessons/merge-two-sorted-lists/lesson.js index af90a8f..81e5379 100644 --- a/src/lessons/merge-two-sorted-lists/lesson.js +++ b/src/lessons/merge-two-sorted-lists/lesson.js @@ -651,7 +651,7 @@ mountLesson({ // lists up to 6 long over -3..3 (so ties are everywhere), 5,000 pairs up to // the 50-node constraint over -100..100, and two disjoint 50-node pairs — // checked against concatenate-and-sort. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim). + // (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,008 cases vs sort', python: 'ran here · 20,008 cases vs sort', diff --git a/src/lessons/minimum-window-substring/lesson.js b/src/lessons/minimum-window-substring/lesson.js index fd266da..6b755c7 100644 --- a/src/lessons/minimum-window-substring/lesson.js +++ b/src/lessons/minimum-window-substring/lesson.js @@ -572,7 +572,7 @@ mountLesson({ // letters, 5,000 over ten letters of both cases up to 300 long, and five // with 10⁵-letter strings — against an oracle that binary-searches the // window's length. The brute force skips the five at 10⁵. Go and Rust ran - // in Docker (golang:1.23-alpine, rust:1-slim). + // in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: { brute: 'ran here · 20,010 cases, not the five at m = 10⁵', window: 'ran here · 20,015 cases' }, python: { brute: 'ran here · 20,010 cases, not the five at m = 10⁵', window: 'ran here · 20,015 cases' }, diff --git a/src/lessons/move-zeroes/lesson.js b/src/lessons/move-zeroes/lesson.js index 28d76ce..9ecd9ad 100644 --- a/src/lessons/move-zeroes/lesson.js +++ b/src/lessons/move-zeroes/lesson.js @@ -598,7 +598,7 @@ mountLesson({ }, // How each language was actually checked, printed as the part 3 badges. // The corpus: 5 edges, 15,000 short arrays heavy in zeros, 5,000 up to 80 values over the full 32-bit range, two at n = 10⁴ — against filter-and-append. - // Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,007 cases', python: 'ran here · 20,007 cases', diff --git a/src/lessons/n-queens/lesson.js b/src/lessons/n-queens/lesson.js index 19f02e8..b4e0cd0 100644 --- a/src/lessons/n-queens/lesson.js +++ b/src/lessons/n-queens/lesson.js @@ -600,7 +600,7 @@ mountLesson({ // The constraint allows n = 1 to 9, so the corpus is all nine, checked // against an oracle that filters every permutation of the columns. Each // driver sorts the boards, since any order is accepted. Go and Rust ran in - // Docker (golang:1.23-alpine, rust:1-slim). + // Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · every n from 1 to 9', python: 'ran here · every n from 1 to 9', diff --git a/src/lessons/number-of-islands/lesson.js b/src/lessons/number-of-islands/lesson.js index e9d9045..54bc9b7 100644 --- a/src/lessons/number-of-islands/lesson.js +++ b/src/lessons/number-of-islands/lesson.js @@ -637,7 +637,7 @@ mountLesson({ // The corpus: the 2 examples, 6 edges, 15,000 random grids up to 6 × 8, // 5,000 up to 40 × 40, and five at 300 × 300 (all land, a checkerboard, // three random densities) — against a union-find oracle. Go and Rust ran in - // Docker (golang:1.23-alpine, rust:1-slim). The DFS stack limits were + // Docker (golang:1.23-alpine, rust:1.98-slim). The DFS stack limits were // measured cold, one snake-shaped island per process, on each default stack. verification: { ruby: { dfs: 'ran here · overflows Ruby 3.1\'s default stack past 8,729 cells deep', bfs: 'ran here · 20,013 cases' }, diff --git a/src/lessons/permutations/lesson.js b/src/lessons/permutations/lesson.js index 5100b3e..d165749 100644 --- a/src/lessons/permutations/lesson.js +++ b/src/lessons/permutations/lesson.js @@ -544,7 +544,7 @@ mountLesson({ // values from -10..10, weighted toward length 6 — against // itertools.permutations. Each driver sorts the answer and prints its // length first, since any order is accepted. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim). + // (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,005 cases', python: 'ran here · 20,005 cases', diff --git a/src/lessons/product-of-array-except-self/lesson.js b/src/lessons/product-of-array-except-self/lesson.js index 82e6aca..7208735 100644 --- a/src/lessons/product-of-array-except-self/lesson.js +++ b/src/lessons/product-of-array-except-self/lesson.js @@ -542,7 +542,7 @@ mountLesson({ // every one with each prefix and suffix product inside 32 bits — against an // oracle multiplying Python integers. The brute force skips the five at // n = 10⁵ (10¹⁰ multiplications each). Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim). + // (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: { brute: 'ran here · 20,008 cases, not the five at n = 10⁵', sweep: 'ran here · 20,013 cases' }, python: { brute: 'ran here · 20,008 cases, not the five at n = 10⁵', sweep: 'ran here · 20,013 cases' }, diff --git a/src/lessons/reverse-linked-list/lesson.js b/src/lessons/reverse-linked-list/lesson.js index 8a59fba..e5e8239 100644 --- a/src/lessons/reverse-linked-list/lesson.js +++ b/src/lessons/reverse-linked-list/lesson.js @@ -706,7 +706,7 @@ mountLesson({ // long ones (5,000, 5,000 and 999 nodes) — checked against Python's list // reversal. The 5,000-node cases are what forced the recursion limit into the // recursive Python listing: without it, it raises RecursionError. Go and Rust - // ran in Docker (golang:1.23-alpine, rust:1-slim). + // ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 19,998 cases up to n = 5,000', python: 'ran here · 19,998 cases up to n = 5,000', diff --git a/src/lessons/reverse-nodes-in-k-group/lesson.js b/src/lessons/reverse-nodes-in-k-group/lesson.js index e89dc83..44fecfe 100644 --- a/src/lessons/reverse-nodes-in-k-group/lesson.js +++ b/src/lessons/reverse-nodes-in-k-group/lesson.js @@ -525,7 +525,7 @@ mountLesson({ // nodes with every k, 5,000 of up to 300, and five of 5,000 nodes with k = // 1, 2, 70, 4,999 and 5,000 — against chunk-and-reverse in a Python list. // Every language ran on its default stack. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim). + // (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,013 cases', python: 'ran here · 20,013 cases', diff --git a/src/lessons/rotate-image/lesson.js b/src/lessons/rotate-image/lesson.js index 14db0b0..d6ec3f8 100644 --- a/src/lessons/rotate-image/lesson.js +++ b/src/lessons/rotate-image/lesson.js @@ -435,7 +435,7 @@ mountLesson({ // and 5,000 up to 20 × 20 across ±1000 — against an oracle that reads each // new row off a column, bottom to top. Each driver prints the matrix it // passed in, so a rotation that did not reach the caller fails. Go and Rust - // ran in Docker (golang:1.23-alpine, rust:1-slim). + // ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,005 cases', python: 'ran here · 20,005 cases', diff --git a/src/lessons/search-in-rotated-sorted-array/lesson.js b/src/lessons/search-in-rotated-sorted-array/lesson.js index 58473d5..2099a39 100644 --- a/src/lessons/search-in-rotated-sorted-array/lesson.js +++ b/src/lessons/search-in-rotated-sorted-array/lesson.js @@ -471,7 +471,7 @@ mountLesson({ // The corpus: the 3 examples, 6 edges, 15,000 random rotated arrays of 1–9 // distinct values with targets often absent, 5,000 of up to 200 across // ±10⁴, and five at n = 5000 — against a value → index dictionary. Go and - // Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,014 cases', python: 'ran here · 20,014 cases', diff --git a/src/lessons/serialize-and-deserialize-binary-tree/lesson.js b/src/lessons/serialize-and-deserialize-binary-tree/lesson.js index f65d3e8..6f91ab1 100644 --- a/src/lessons/serialize-and-deserialize-binary-tree/lesson.js +++ b/src/lessons/serialize-and-deserialize-binary-tree/lesson.js @@ -752,7 +752,7 @@ mountLesson({ // a random tree, a complete tree, a chain of -1000s). Each driver // serializes with one codec, deserializes with another, and checks the // rebuilt tree prints as the input. Go and Rust ran in Docker - // (golang:1.23-alpine, rust:1-slim) on their default stacks. The preorder + // (golang:1.23-alpine, rust:1.98-slim) on their default stacks. The preorder // limits were measured cold, one left chain per process. verification: { ruby: { preorder: 'ran here · overflows Ruby 3.1\'s default stack past an 8,185-node chain', level: 'ran here · 20,014 round trips' }, diff --git a/src/lessons/single-number/lesson.js b/src/lessons/single-number/lesson.js index 4215abc..c75d253 100644 --- a/src/lessons/single-number/lesson.js +++ b/src/lessons/single-number/lesson.js @@ -537,7 +537,7 @@ mountLesson({ // listing in part 3. The corpus: the 3 examples, 4 edges, 15,000 arrays of // up to 13 values drawn from -4..4, 5,000 of up to 41 values over the full // ±3 × 10⁴ range, and three at n = 29,999 — checked against a Counter in - // Python. Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Python. Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,010 cases vs a Counter', python: 'ran here · 20,010 cases vs a Counter', diff --git a/src/lessons/sliding-window-maximum/lesson.js b/src/lessons/sliding-window-maximum/lesson.js index dc8f02a..74aff04 100644 --- a/src/lessons/sliding-window-maximum/lesson.js +++ b/src/lessons/sliding-window-maximum/lesson.js @@ -453,7 +453,7 @@ mountLesson({ // values from -3..3, 5,000 of up to 300 across the full range, and five of // 10⁵ values — against a block prefix/suffix-maximum oracle. The brute force // skips the five at 10⁵. Go and Rust ran in Docker (golang:1.23-alpine, - // rust:1-slim). + // rust:1.98-slim). verification: { ruby: { brute: 'ran here · 20,008 cases, not the five at n = 10⁵', deque: 'ran here · 20,013 cases' }, python: { brute: 'ran here · 20,008 cases, not the five at n = 10⁵', deque: 'ran here · 20,013 cases' }, diff --git a/src/lessons/trapping-rain-water/lesson.js b/src/lessons/trapping-rain-water/lesson.js index 2a60fdc..a50db25 100644 --- a/src/lessons/trapping-rain-water/lesson.js +++ b/src/lessons/trapping-rain-water/lesson.js @@ -468,7 +468,7 @@ mountLesson({ // The corpus: the 2 examples, 6 edges, 15,000 random landscapes of up to 12 // bars from 0..5, 5,000 of up to 300 across the full range, and four of // 2 × 10⁴ bars — the largest answer 1,999,800,000 — against a stack - // oracle. Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // oracle. Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,012 cases', python: 'ran here · 20,012 cases', diff --git a/src/lessons/two-sum/lesson.js b/src/lessons/two-sum/lesson.js index 12946ca..c38478a 100644 --- a/src/lessons/two-sum/lesson.js +++ b/src/lessons/two-sum/lesson.js @@ -453,7 +453,7 @@ mountLesson({ }, // How each language was actually checked, printed as the part 3 badges. // The corpus: 3 examples, 15,000 small arrays with one pair, 5,000 up to ±10⁹, and one at n = 10⁴ — each against all-pairs search. - // Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,004 cases', python: 'ran here · 20,004 cases', diff --git a/src/lessons/valid-anagram/lesson.js b/src/lessons/valid-anagram/lesson.js index 6c9ec5d..3d9c31d 100644 --- a/src/lessons/valid-anagram/lesson.js +++ b/src/lessons/valid-anagram/lesson.js @@ -637,7 +637,7 @@ mountLesson({ }, // How each language was actually checked, printed as the part 3 badges. // The corpus: 6 edges, 15,000 strings over "abc", 5,000 permutations (half with one letter changed), three at 5 × 10⁴ — against a Counter. - // Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,009 cases', python: 'ran here · 20,009 cases', diff --git a/src/lessons/valid-palindrome/lesson.js b/src/lessons/valid-palindrome/lesson.js index a6f97e5..e35c537 100644 --- a/src/lessons/valid-palindrome/lesson.js +++ b/src/lessons/valid-palindrome/lesson.js @@ -5,7 +5,7 @@ * same question by *skipping* the characters the filter would have removed — * same O(n) time, but the only state that survives a step is two integers. */ -import { t, plural, exampleTitle, LANGUAGES, k, c, verdictAnswer, stageRow, presetChips, widgetLabel } from '../../lib/kit.js'; +import { t, esc, plural, exampleTitle, LANGUAGES, k, c, verdictAnswer, stageRow, presetChips, widgetLabel } from '../../lib/kit.js'; import { mountLesson } from '../../lib/stepper.js'; import { pick, onLangChange } from '../../lib/i18n.js'; import { cells, readout, stagePanel } from '../../lib/stage.js'; @@ -19,10 +19,7 @@ const isAlnum = (ch) => /[a-z0-9]/i.test(ch); * problem most needs the reader to actually see. */ const show = (ch) => (ch === ' ' ? '␣' : ch); -/* Narration is HTML, and `s` comes from a text box the reader controls. */ -const e = (x) => String(x).replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c])); - -const named = (ch) => (ch === ' ' ? t('a space', 'space တစ်ခု') : t(`'${e(ch)}'`, `'${e(ch)}'`)); +const named = (ch) => (ch === ' ' ? t('a space', 'space တစ်ခု') : t(`'${esc(ch)}'`, `'${esc(ch)}'`)); /* ---------------- step generators ---------------- */ @@ -60,10 +57,10 @@ function buildClean({ s }) { const pos = cleaned.length - 1; steps.push({ line: 'keep', i, cleaned: cleaned.slice(), keepAt: pos, tag: t('keep', 'ထည့်'), note: pos === 0 - ? t(`s[${i}] = '${e(ch)}' is alphanumeric, so it is lowercased to '${e(ch.toLowerCase())}' and appended. Lowercasing here is what lets the comparison at the end be a plain equality.`, - `s[${i}] = '${e(ch)}' သည် alphanumeric ဖြစ်သဖြင့် '${e(ch.toLowerCase())}' အဖြစ် အသေးပြောင်းပြီး ထည့်သည်။ ဤနေရာတွင် အသေးပြောင်းထားခြင်းကြောင့် နောက်ဆုံး နှိုင်းယှဉ်မှုကို ရိုးရိုး ညီမျှခြင်းဖြင့် လုပ်နိုင်သည်။`) - : t(`s[${i}] = '${e(ch)}' survives, lowercased to '${e(ch.toLowerCase())}' at position ${pos} of cleaned.`, - `s[${i}] = '${e(ch)}' ကျန်ရစ်သည် — '${e(ch.toLowerCase())}' အဖြစ် အသေးပြောင်းပြီး cleaned ၏ နေရာ ${pos} တွင် ထားသည်။`) }); + ? t(`s[${i}] = '${esc(ch)}' is alphanumeric, so it is lowercased to '${esc(ch.toLowerCase())}' and appended. Lowercasing here is what lets the comparison at the end be a plain equality.`, + `s[${i}] = '${esc(ch)}' သည် alphanumeric ဖြစ်သဖြင့် '${esc(ch.toLowerCase())}' အဖြစ် အသေးပြောင်းပြီး ထည့်သည်။ ဤနေရာတွင် အသေးပြောင်းထားခြင်းကြောင့် နောက်ဆုံး နှိုင်းယှဉ်မှုကို ရိုးရိုး ညီမျှခြင်းဖြင့် လုပ်နိုင်သည်။`) + : t(`s[${i}] = '${esc(ch)}' survives, lowercased to '${esc(ch.toLowerCase())}' at position ${pos} of cleaned.`, + `s[${i}] = '${esc(ch)}' ကျန်ရစ်သည် — '${esc(ch.toLowerCase())}' အဖြစ် အသေးပြောင်းပြီး cleaned ၏ နေရာ ${pos} တွင် ထားသည်။`) }); } const reversed = cleaned.slice().reverse(); @@ -89,8 +86,8 @@ function buildClean({ s }) { 'string ဗလာကို မည်သည့်ဘက်မှ ဖတ်ဖတ် အတူတူ ဖြစ်သဖြင့် အဖြေမှာ true။') : t(`Every position agrees, so the answer is true. Cost: ${n} characters read and ${2 * len} characters of scratch allocated.`, `နေရာတိုင်း ကိုက်ညီသဖြင့် အဖြေမှာ true။ ကုန်ကျမှု — စာလုံး ${n} လုံး ဖတ်ပြီး ယာယီ စာလုံး ${2 * len} လုံးစာ memory ယူခဲ့သည်။`)) - : t(`Position ${diff} differs — '${e(cleaned[diff])}' against '${e(reversed[diff])}' — so the answer is false. Both copies were built in full before a single comparison happened.`, - `နေရာ ${diff} တွင် မတူပါ — '${e(cleaned[diff])}' နှင့် '${e(reversed[diff])}' — ထို့ကြောင့် အဖြေမှာ false။ နှိုင်းယှဉ်မှု တစ်ခုမျှ မလုပ်ရသေးမီ copy နှစ်ခုလုံးကို အပြည့် တည်ဆောက်ခဲ့ရသည်။`) }); + : t(`Position ${diff} differs — '${esc(cleaned[diff])}' against '${esc(reversed[diff])}' — so the answer is false. Both copies were built in full before a single comparison happened.`, + `နေရာ ${diff} တွင် မတူပါ — '${esc(cleaned[diff])}' နှင့် '${esc(reversed[diff])}' — ထို့ကြောင့် အဖြေမှာ false။ နှိုင်းယှဉ်မှု တစ်ခုမျှ မလုပ်ရသေးမီ copy နှစ်ခုလုံးကို အပြည့် တည်ဆောက်ခဲ့ရသည်။`) }); return steps; } @@ -163,10 +160,10 @@ function buildTwoPointer({ s }) { ? t(`Skipping has left left and right on the same character, index ${left}. The code still runs the comparison, and it is trivially true.`, `ကျော်လိုက်ရာမှ left နှင့် right တို့ index ${left} ရှိ စာလုံးတစ်လုံးတည်းပေါ် ရောက်နေသည်။ code က နှိုင်းယှဉ်မှုကို လုပ်ဆဲဖြစ်ပြီး မှန်သည်မှာ သေချာသည်။`) : match - ? t(`s[${left}] = '${e(a)}' against s[${right}] = '${e(b)}'. Lowercased both read '${e(la)}', so this pair holds.`, - `s[${left}] = '${e(a)}' နှင့် s[${right}] = '${e(b)}'။ အသေးပြောင်းလိုက်လျှင် နှစ်ခုလုံး '${e(la)}' ဖြစ်သဖြင့် ဤအတွဲ ကိုက်သည်။`) - : t(`s[${left}] = '${e(a)}' against s[${right}] = '${e(b)}'. Lowercased that is '${e(la)}' against '${e(lb)}'.`, - `s[${left}] = '${e(a)}' နှင့် s[${right}] = '${e(b)}'။ အသေးပြောင်းလိုက်လျှင် '${e(la)}' နှင့် '${e(lb)}' ဖြစ်သည်။`) })); + ? t(`s[${left}] = '${esc(a)}' against s[${right}] = '${esc(b)}'. Lowercased both read '${esc(la)}', so this pair holds.`, + `s[${left}] = '${esc(a)}' နှင့် s[${right}] = '${esc(b)}'။ အသေးပြောင်းလိုက်လျှင် နှစ်ခုလုံး '${esc(la)}' ဖြစ်သဖြင့် ဤအတွဲ ကိုက်သည်။`) + : t(`s[${left}] = '${esc(a)}' against s[${right}] = '${esc(b)}'. Lowercased that is '${esc(la)}' against '${esc(lb)}'.`, + `s[${left}] = '${esc(a)}' နှင့် s[${right}] = '${esc(b)}'။ အသေးပြောင်းလိုက်လျှင် '${esc(la)}' နှင့် '${esc(lb)}' ဖြစ်သည်။`) })); if (!match) { const gap = right - left - 1; @@ -528,7 +525,7 @@ function mountFilterWidget(host) { q('[data-arr]').innerHTML = s.map((ch, i) => { const on = pairs && (i === a || i === b); - return `
${e(show(ch))}${i}
`; + return `
${esc(show(ch))}${i}
`; }).join(''); widgetLabel(pick(t(`${s.length} characters, ${m} count`, `စာလုံး ${s.length} လုံး၊ ${m} လုံး အရေးပါ`))); @@ -543,16 +540,16 @@ function mountFilterWidget(host) { } else { const x = s[a], y = s[b], eq = x.toLowerCase() === y.toLowerCase(); line = eq - ? t(`Pair ${k}: s[${a}] = '${e(x)}' and s[${b}] = '${e(y)}'. ${x === y ? 'Equal.' : 'Equal once both are lowercased.'} Everything between them that is not lit was never part of the question.`, - `အတွဲ ${k} — s[${a}] = '${e(x)}' နှင့် s[${b}] = '${e(y)}'။ ${x === y ? 'တူသည်။' : 'နှစ်ခုလုံး အသေးပြောင်းလိုက်လျှင် တူသည်။'} ကြားရှိ မလင်းသော စာလုံးများသည် မေးခွန်း၏ အစိတ်အပိုင်း မဟုတ်ခဲ့ပါ။`) - : t(`Pair ${k}: s[${a}] = '${e(x)}' against s[${b}] = '${e(y)}'. Different even after lowercasing — that one pair makes the answer false.`, - `အတွဲ ${k} — s[${a}] = '${e(x)}' နှင့် s[${b}] = '${e(y)}'။ အသေးပြောင်းပြီးသည့်တိုင် မတူပါ — ထိုအတွဲ တစ်ခုတည်းကြောင့် အဖြေ false ဖြစ်သည်။`); + ? t(`Pair ${k}: s[${a}] = '${esc(x)}' and s[${b}] = '${esc(y)}'. ${x === y ? 'Equal.' : 'Equal once both are lowercased.'} Everything between them that is not lit was never part of the question.`, + `အတွဲ ${k} — s[${a}] = '${esc(x)}' နှင့် s[${b}] = '${esc(y)}'။ ${x === y ? 'တူသည်။' : 'နှစ်ခုလုံး အသေးပြောင်းလိုက်လျှင် တူသည်။'} ကြားရှိ မလင်းသော စာလုံးများသည် မေးခွန်း၏ အစိတ်အပိုင်း မဟုတ်ခဲ့ပါ။`) + : t(`Pair ${k}: s[${a}] = '${esc(x)}' against s[${b}] = '${esc(y)}'. Different even after lowercasing — that one pair makes the answer false.`, + `အတွဲ ${k} — s[${a}] = '${esc(x)}' နှင့် s[${b}] = '${esc(y)}'။ အသေးပြောင်းပြီးသည့်တိုင် မတူပါ — ထိုအတွဲ တစ်ခုတည်းကြောင့် အဖြေ false ဖြစ်သည်။`); } q('[data-line]').innerHTML = pick(line); // the ledger is a formula, as on x-sum: the string the question is really about const filtered = kept.map((i) => s[i].toLowerCase()).join(''); - q('[data-expr]').innerHTML = `"${e(filtered)}" ${filtered === [...filtered].reverse().join('') ? '=' : '≠'} "${e([...filtered].reverse().join(''))}"`; + q('[data-expr]').innerHTML = `"${esc(filtered)}" ${filtered === [...filtered].reverse().join('') ? '=' : '≠'} "${esc([...filtered].reverse().join(''))}"`; q('[data-total]').innerHTML = `${good}/${pairs}${pick(t('pairs match', 'အတွဲ ကိုက်'))}`; } @@ -670,7 +667,7 @@ mountLesson({ // 12,000 short strings over "aAbB01 .,:!_`", 6,000 noisy palindromes (half // perturbed), 2,000 random printable-ASCII strings, and three at 2 × 10⁵ — // checked against a separate pointer-peeling reference. Go and Rust ran in - // Docker (golang:1.23-alpine, rust:1-slim). + // Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,016 cases vs a reference', python: 'ran here · 20,016 cases vs a reference', diff --git a/src/lessons/valid-parentheses/lesson.js b/src/lessons/valid-parentheses/lesson.js index 05fa8af..64317dc 100644 --- a/src/lessons/valid-parentheses/lesson.js +++ b/src/lessons/valid-parentheses/lesson.js @@ -636,7 +636,7 @@ mountLesson({ // 12,000 random strings of length 1–10, 8,000 valid strings (half with one // character flipped), and six at n = 10⁴ — checked against a separate // recursive-descent parser. verify/valid-parentheses/spec.py rebuilds it. - // Go and Rust ran in Docker (golang:1.23-alpine, rust:1-slim). + // Go and Rust ran in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,020 cases vs a parser', python: 'ran here · 20,020 cases vs a parser', diff --git a/src/lessons/word-ladder/lesson.js b/src/lessons/word-ladder/lesson.js index 157d81e..c630373 100644 --- a/src/lessons/word-ladder/lesson.js +++ b/src/lessons/word-ladder/lesson.js @@ -674,7 +674,7 @@ mountLesson({ // 4-letter words over "abc", 5,000 of 3 to 6 letters over "abcd" with up to // 300 words, and six with 10-letter words, five of them 5,000 words long — // against an oracle that groups words by pattern ("h*t"). Go and Rust ran - // in Docker (golang:1.23-alpine, rust:1-slim). + // in Docker (golang:1.23-alpine, rust:1.98-slim). verification: { ruby: 'ran here · 20,015 cases', python: 'ran here · 20,015 cases', diff --git a/src/lessons/word-search-ii/lesson.js b/src/lessons/word-search-ii/lesson.js index bcca3fb..f73f3d5 100644 --- a/src/lessons/word-search-ii/lesson.js +++ b/src/lessons/word-search-ii/lesson.js @@ -700,7 +700,7 @@ mountLesson({ // over two or three letters, 5,000 up to 8 × 8, and five at 12 × 12 — against // a bitmask search per word. One search per word skips the two inputs with // thousands of words. Go and Rust ran in Docker (golang:1.23-alpine, - // rust:1-slim). + // rust:1.98-slim). verification: { ruby: { each: 'ran here · 20,011 cases, not the two with thousands of words', trie: 'ran here · 20,013 cases' }, python: { each: 'ran here · 20,011 cases, not the two with thousands of words', trie: 'ran here · 20,013 cases' }, diff --git a/src/lib/kit.js b/src/lib/kit.js index b899df8..004ebba 100644 --- a/src/lib/kit.js +++ b/src/lib/kit.js @@ -10,6 +10,10 @@ import { pick } from './i18n.js'; /** A reader-facing sentence in both languages; `pick()` chooses the side. */ export const t = (en, my) => ({ en, my }); +/** Text made safe to splice into HTML. Narration, notes and widget lines are + * HTML, so anything the reader typed goes through this first. */ +export const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[ch])); + /** "1 node", "3 nodes". English only — Burmese needs no plural. */ export const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`; diff --git a/src/lib/stage.js b/src/lib/stage.js index 57d28fe..630e169 100644 --- a/src/lib/stage.js +++ b/src/lib/stage.js @@ -9,7 +9,7 @@ * tone {index: 'up'|'down'|'warn'|'done'} — per-cell colour */ -import { esc } from './stepper.js'; +import { esc } from './kit.js'; import { pick } from './i18n.js'; const tones = (t) => (t ? ` t-${t}` : ''); diff --git a/src/lib/stepper.js b/src/lib/stepper.js index c58a93a..62e0a3b 100644 --- a/src/lib/stepper.js +++ b/src/lib/stepper.js @@ -36,9 +36,9 @@ */ import { pick, onLangChange } from './i18n.js'; +import { esc } from './kit.js'; const $ = (sel, el = document) => el.querySelector(sel); -const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); const nameOf = (k) => (typeof k === 'string' ? k : k?.en ?? ''); /* A tab's selection attributes. Only the selected tab sits in the Tab order; @@ -568,7 +568,7 @@ export function mountLesson(cfg) { } if (cfg.widget) { const host = document.getElementById('q-widget'); - if (host) cfg.widget(host); + if (host) { cfg.widget(host); keepFocus(host); } } // Narration is generated per step and the chrome is rendered by this file, so @@ -579,6 +579,29 @@ export function mountLesson(cfg) { return { rebuild, go, stop, state }; } +/* A widget redraws its chips and cells on every pick, which throws away the + * element that had focus and drops a keyboard reader back to the top of the + * page. Registered after the widget's own handlers, so it runs after them: if + * focus fell out of the widget, it goes to the redrawn element with the same + * data-* attributes. A widget that already refocuses is left alone. */ +function keepFocus(host) { + let key = null; + const before = () => { + const el = document.activeElement; + const attrs = el && el !== host && host.contains(el) + ? el.getAttributeNames().filter((n) => n.startsWith('data-')) : []; + key = attrs.length + ? el.localName + attrs.map((n) => `[${n}="${CSS.escape(el.getAttribute(n))}"]`).join('') : null; + }; + const after = () => { + if (key && !host.contains(document.activeElement)) host.querySelector(key)?.focus(); + }; + for (const type of ['click', 'keydown']) { + host.addEventListener(type, before, true); + host.addEventListener(type, after); + } +} + /* A function that wraps known identifiers in a rendered listing line, never * inside a tag and never in the middle of a longer identifier, so the reader * can hover one and see its value at the current step. Built once per listing. */ @@ -713,4 +736,3 @@ function renderSolutions(cfg, state) { }; } -export { esc }; diff --git a/src/pages/index.astro b/src/pages/index.astro index 40ce256..858013a 100644 --- a/src/pages/index.astro +++ b/src/pages/index.astro @@ -205,7 +205,9 @@ const haystack = (p: Problem) => [p.id, p.title, p.category, ...p.tags].join(' ' if (d.value) next.set('d', d.value); if (solved.checked) next.set('solved', '1'); const url = `${location.pathname}${next.size ? `?${next}` : ''}${cat ? `#${cat}` : ''}`; - history.replaceState(null, '', url); + // Safari throws once a page calls replaceState too often (a held key in + // the search box); the filter has already applied, so only the URL lags. + try { history.replaceState(null, '', url); } catch { /* rate-limited */ } } form.addEventListener('input', apply);