diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 561a402..738153a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -187,7 +187,8 @@ chromium`): every approach × language highlights a line on every step, every preset loads, nothing throws, nothing scrolls sideways at 400px or 320px in either language, headings never skip a level, an empty answer says "?" or words rather than a bare dot, space and the arrow keys do what a focused -control expects, and a shared link reopens the same step. What it cannot +control expects, a shared link reopens the same step, and the ⌘K site search +finds and opens a page. What it cannot tell you is whether the page reads well — open it beside another one and look. diff --git a/scripts/audit.mjs b/scripts/audit.mjs index 83ae5d5..bfb133a 100644 --- a/scripts/audit.mjs +++ b/scripts/audit.mjs @@ -20,6 +20,9 @@ // · a toned row in a key/value table is actually coloured (a later CSS // rule once turned every highlighted row grey) // · the home page loads, lists every lesson, and fits at 400px +// · site search: Ctrl+K opens it from a lesson with focus in the field, it +// lists every lesson, "two sum" puts Two Sum first, Enter opens it, Esc +// gives focus back, and the masthead stays one line at 320px // · axe-core finds no WCAG 2 A/AA violation (contrast, labels, keyboard // access) on any page, in the light and the dark theme, at the first // step and partway through @@ -43,6 +46,42 @@ async function accessibility(page, where) { return found.map((x) => `a11y (${where}) ${x}`); } +/* The masthead's search dialog (SiteSearch.astro), driven from a lesson. */ +async function siteSearch(page, base, slugs) { + const found = []; + const open = () => page.$eval('#search-dlg', (d) => d.open); + const first = () => page.$eval('#k-list .k-opt', (a) => a.getAttribute('href')).catch(() => null); + await page.setViewportSize({ width: 1100, height: 800 }); + await page.goto(`${base}/leetcode/${slugs[0]}`); + await page.waitForSelector('#lesson .atab'); + await page.focus('#lesson [data-act="next"]'); + await page.keyboard.press('Control+k'); + if (!(await open())) return ['Ctrl+K did not open the search']; + if (await page.evaluate(() => document.activeElement.getAttribute('role')) !== 'combobox') found.push('Ctrl+K: focus is not in the search field'); + await page.waitForSelector('#k-list .k-opt'); + const listed = await page.$$eval('#k-list .k-opt', (as) => as.map((a) => a.getAttribute('href'))); + found.push(...slugs.filter((s) => !listed.includes(`/leetcode/${s}`)).map((s) => `the empty search does not list /leetcode/${s}`)); + await page.keyboard.type('two sum'); + if (await first() !== '/leetcode/two-sum') found.push(`"two sum" puts ${await first()} first`); + for (const scheme of ['light', 'dark']) { + await page.emulateMedia({ colorScheme: scheme }); + found.push(...await accessibility(page, `search, ${scheme}`)); + } + await page.emulateMedia({ colorScheme: 'light' }); + await page.keyboard.press('Escape'); + if (await open()) found.push('Esc did not close the search'); + else if (await page.evaluate(() => document.activeElement.dataset.act) !== 'next') found.push('closing the search did not give focus back'); + await page.keyboard.press('Control+k'); + await page.keyboard.type('two sum'); + await page.waitForSelector('#k-list .k-opt'); + await page.keyboard.press('Enter'); + await page.waitForURL('**/leetcode/two-sum', { timeout: 5000 }).catch(() => found.push('Enter on "two sum" did not open /leetcode/two-sum')); + await page.setViewportSize({ width: 320, height: 700 }); + const bar = await page.$eval('.masthead', (m) => m.offsetHeight); + if (bar > 60) found.push(`the masthead wraps at 320px (${bar}px tall)`); + return found; +} + async function scrubTo(page, fraction) { await page.evaluate((f) => { const s = document.querySelector('#lesson [data-scrub]'); @@ -301,8 +340,10 @@ async function main() { await page.goto(BASE); a11y.push(...await accessibility(page, scheme)); } + const search = await siteSearch(page, BASE, slugs); report('home page', [ ...errors, + ...search, ...(home.over > 0 ? [`${home.over}px too wide at 400px`] : []), ...missing.map((s) => `no link to /leetcode/${s}`), ...a11y, diff --git a/src/components/Masthead.astro b/src/components/Masthead.astro index 13dc14d..854389c 100644 --- a/src/components/Masthead.astro +++ b/src/components/Masthead.astro @@ -1,6 +1,7 @@ --- import { SITE_NAME, REPO } from '../data/site'; import ThemeToggle from './ThemeToggle.astro'; +import SiteSearch from './SiteSearch.astro'; ---
@@ -10,6 +11,7 @@ import ThemeToggle from './ThemeToggle.astro'; LeetCode GitHub ↗ +
diff --git a/src/components/SiteSearch.astro b/src/components/SiteSearch.astro new file mode 100644 index 0000000..90ed63d --- /dev/null +++ b/src/components/SiteSearch.astro @@ -0,0 +1,158 @@ +--- +/* Site search: a masthead button and ⌘K / Ctrl+K on every page open a dialog + * that finds a problem by name, number, pattern or tag and goes to its + * solution page, or to LeetCode when it has none yet. The index is + * /search.json (src/pages/search.json.ts), fetched on first open. + * + * The dialog is a combobox: focus stays in the field, ↑ ↓ move the active + * result (aria-activedescendant), Enter opens it, Esc closes and focus goes + * back to where it was. Without JavaScript the button stays hidden and the + * home page's own search box does the job. */ +--- + + + +
+ + +
+

+
+

+
+ + diff --git a/src/data/catalog.ts b/src/data/catalog.ts new file mode 100644 index 0000000..4263ccc --- /dev/null +++ b/src/data/catalog.ts @@ -0,0 +1,44 @@ +/* The problem list, as the home page and site search both read it: every + * problem in problems.json, in pattern order and then by difficulty, each with + * the address of its solution page when a lesson covers it. */ +import problems from './problems.json'; + +export interface Problem { + id: number; title: string; slug: string; difficulty: 'Easy' | 'Medium' | 'Hard'; + paid: boolean; acRate: string; tags: string[]; category: string; extra?: boolean; +} + +// A problem gets a solution page when a lesson folder names it: every +// lesson's page.js lists the LeetCode problems it covers. +const pages = import.meta.glob('../lessons/*/page.js', { eager: true, import: 'default' }) as + Record; +export const PAGE: Record = {}; +for (const [path, page] of Object.entries(pages)) { + const slug = path.split('/').at(-2); + for (const { id } of page.links) PAGE[id] = `/leetcode/${slug}`; +} + +// The patterns, in the order they build on each other. Every problem in +// problems.json names one of these as its category. +export const CATEGORIES = [ + 'Arrays & Hashing', 'Two Pointers', 'Sliding Window', 'Stack', 'Binary Search', + 'Linked List', 'Trees', 'Tries', 'Heap', 'Backtracking', 'Graphs', + 'Dynamic Programming', 'Intervals', 'Math & Geometry', 'Bit Manipulation', +]; +const LEVEL = { Easy: 0, Medium: 1, Hard: 2 }; + +export const all = Object.values(problems as Record).flat(); +for (const p of all) { + if (!CATEGORIES.includes(p.category)) throw new Error(`problems.json: ${p.id} has unknown category "${p.category}"`); +} + +export const groups = CATEGORIES.map((name) => ({ + name, + id: name.toLowerCase().replace(/&/g, 'and').replace(/[^a-z0-9]+/g, '-'), + rows: all.filter((p) => p.category === name).sort((a, b) => LEVEL[a.difficulty] - LEVEL[b.difficulty]), +})); + +/** What a search matches against: name, number, pattern and tags. */ +export const haystack = (p: Problem) => [p.id, p.title, p.category, ...p.tags].join(' ').toLowerCase(); + +export const leetcodeUrl = (slug: string) => `https://leetcode.com/problems/${slug}/`; diff --git a/src/pages/index.astro b/src/pages/index.astro index 858013a..cbe7a57 100644 --- a/src/pages/index.astro +++ b/src/pages/index.astro @@ -1,48 +1,11 @@ --- import Base from '../layouts/Base.astro'; import { SITE_NAME } from '../data/site'; -import problems from '../data/problems.json'; import { asOf } from '../data/problems-meta.json'; +import { all, groups, haystack, leetcodeUrl, PAGE as WALKTHROUGH } from '../data/catalog'; -interface Problem { - id: number; title: string; slug: string; difficulty: 'Easy' | 'Medium' | 'Hard'; - paid: boolean; acRate: string; tags: string[]; category: string; extra?: boolean; -} - -// A problem gets a solution page when a lesson folder names it: every -// lesson's page.js lists the LeetCode problems it covers. -const pages = import.meta.glob('../lessons/*/page.js', { eager: true, import: 'default' }) as - Record; -const WALKTHROUGH: Record = {}; -for (const [path, page] of Object.entries(pages)) { - const slug = path.split('/').at(-2); - for (const { id } of page.links) WALKTHROUGH[id] = `/leetcode/${slug}`; -} - -// The patterns, in the order they build on each other. Every problem in -// problems.json names one of these as its category. -const CATEGORIES = [ - 'Arrays & Hashing', 'Two Pointers', 'Sliding Window', 'Stack', 'Binary Search', - 'Linked List', 'Trees', 'Tries', 'Heap', 'Backtracking', 'Graphs', - 'Dynamic Programming', 'Intervals', 'Math & Geometry', 'Bit Manipulation', -]; -const LEVEL = { Easy: 0, Medium: 1, Hard: 2 }; - -const all = Object.values(problems as Record).flat(); const core = all.filter((p) => !p.extra).length; const worked = all.filter((p) => WALKTHROUGH[p.id]).length; -for (const p of all) { - if (!CATEGORIES.includes(p.category)) throw new Error(`problems.json: ${p.id} has unknown category "${p.category}"`); -} - -const id = (name: string) => name.toLowerCase().replace(/&/g, 'and').replace(/[^a-z0-9]+/g, '-'); -const groups = CATEGORIES.map((name) => ({ - name, - id: id(name), - rows: all.filter((p) => p.category === name).sort((a, b) => LEVEL[a.difficulty] - LEVEL[b.difficulty]), -})); -// What the search box matches against: name, number, pattern and tags. -const haystack = (p: Problem) => [p.id, p.title, p.category, ...p.tags].join(' ').toLowerCase(); --- [p.id, p.title, p.category, ...p.tags].join(' ' {!WALKTHROUGH[p.id] && Solution coming soon} {p.extra && Outside the core list} - View on LeetCode ↗ + View on LeetCode ↗ {p.tags.slice(0, 3).join(' · ')} diff --git a/src/pages/search.json.ts b/src/pages/search.json.ts new file mode 100644 index 0000000..ef1480d --- /dev/null +++ b/src/pages/search.json.ts @@ -0,0 +1,18 @@ +/* The site search's index, built with the site: every problem in the home + * page's order. The search dialog fetches it the first time it opens, so no + * page carries the list in its HTML. */ +import { groups, haystack, leetcodeUrl, PAGE } from '../data/catalog'; + +export function GET() { + const rows = groups.flatMap((g) => g.rows.map((p) => ({ + id: p.id, + title: p.title, + difficulty: p.difficulty, + category: p.category, + // a solution page on this site, or the problem on LeetCode + href: PAGE[p.id] ?? leetcodeUrl(p.slug), + page: p.id in PAGE, + text: haystack(p), + }))); + return new Response(JSON.stringify(rows), { headers: { 'content-type': 'application/json' } }); +} diff --git a/src/styles/site.css b/src/styles/site.css index 823174c..e6bb41f 100644 --- a/src/styles/site.css +++ b/src/styles/site.css @@ -26,11 +26,17 @@ /* Keep the sticky bar to one line on a phone: wrapped, it took 84px of a fifth of the screen and never gave it back. */ @media (max-width:560px){ - .masthead .shell{gap:10px;padding-inline:14px} + .masthead .shell{gap:8px;padding-inline:14px} .masthead nav{gap:0} .masthead nav a{font-size:12.5px;padding:5px 7px} .brand{font-size:15px} } +/* Under 375px brand, links, search and theme fit with no room to spare, and a + wider fallback font (before the web fonts load, or on Linux) wraps the bar. + The "LeetCode" link goes where the brand already does, so it steps aside. */ +@media (max-width:374px){ + .masthead nav a[href="/"]{display:none} +} /* ---------- theme switch ---------- */ .theme-btn{ @@ -48,6 +54,61 @@ :root:not([data-theme]) .theme-btn .sun{display:none} } +/* ---------- site search (SiteSearch.astro) ---------- */ +.search-btn{ + display:inline-flex;align-items:center;gap:8px;height:30px;padding:0 8px 0 10px; + border:1px solid var(--line);border-radius:7px;background:var(--surface); + color:var(--ink-2);font:inherit;font-size:13px;cursor:pointer; +} +.search-btn[hidden]{display:none} +.search-btn:hover{border-color:var(--line-2);color:var(--ink)} +.search-btn svg{width:14px;height:14px;flex:none} +.sb-key{ + font-family:"IBM Plex Mono",monospace;font-size:11px;color:var(--ink-3); + border:1px solid var(--line);border-radius:4px;padding:0 5px;line-height:18px; +} +@media (max-width:560px){ + .search-btn{width:30px;padding:0;justify-content:center} + .search-btn .sb-label,.search-btn .sb-key{display:none} +} +@media (pointer:coarse){ .sb-key{display:none} } + +.kdlg{ + width:min(620px,calc(100vw - 32px));max-height:min(560px,calc(100dvh - 96px)); + margin:72px auto auto;padding:0;overflow:hidden; + border:1px solid var(--line-2);border-radius:var(--radius); + background:var(--surface);color:var(--ink);box-shadow:var(--shadow); +} +.kdlg[open]{display:flex;flex-direction:column} +.kdlg::backdrop{background:rgba(15,26,30,.4)} +/* the page behind stays put while the dialog is open */ +html:has(.kdlg[open]){overflow:hidden} +.k-field{display:flex;align-items:center;gap:10px;padding:0 16px;border-bottom:1px solid var(--line);color:var(--ink-3)} +.k-field:focus-within{border-bottom-color:var(--accent)} +.k-field svg{width:16px;height:16px;flex:none} +.k-field input{ + flex:1;min-width:0;border:0;background:none;color:var(--ink); + font:inherit;font-size:16px;padding:15px 0; +} +.k-field input:focus-visible{outline:none} +.k-head{margin:0;padding:10px 16px 2px;font-size:12px;font-weight:600;color:var(--ink-3)} +.k-head[hidden]{display:none} +.k-list{overflow-y:auto;padding:6px;flex:1} +.k-opt{ + display:grid;grid-template-columns:3.4em 1fr auto auto;gap:12px;align-items:center; + padding:9px 10px;border-radius:7px;color:var(--ink);text-decoration:none;font-size:14px; +} +.k-opt[aria-selected="true"]{background:var(--accent-soft)} +.k-num{font-family:"IBM Plex Mono",monospace;font-size:12px;color:var(--ink-3);font-variant-numeric:tabular-nums} +.k-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500} +.k-sub{font-size:12px;color:var(--ink-3);white-space:nowrap} +.k-status{margin:0;padding:9px 16px;border-top:1px solid var(--line);font-size:12px;color:var(--ink-3)} +@media (max-width:560px){ + .kdlg{margin-top:12px;max-height:calc(100dvh - 24px)} + .k-opt{grid-template-columns:3em 1fr auto} + .k-sub{display:none} +} + /* ---------- page head ---------- */ .page-head{padding-block:44px 28px;border-bottom:1px solid var(--line);margin-bottom:34px} .page-head h1{max-width:20ch} @@ -165,4 +226,6 @@ a.ptitle::after{content:"";position:absolute;inset:0;border-radius:inherit} @media (pointer:coarse),(max-width:560px){ .masthead nav a{display:inline-flex;align-items:center;min-height:40px} .theme-btn{width:40px;height:40px} + .search-btn{height:40px;min-width:40px} + .k-opt{min-height:44px} }