Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
41 changes: 41 additions & 0 deletions scripts/audit.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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]');
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions src/components/Masthead.astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
---
import { SITE_NAME, REPO } from '../data/site';
import ThemeToggle from './ThemeToggle.astro';
import SiteSearch from './SiteSearch.astro';

---
<header class="masthead">
Expand All @@ -10,6 +11,7 @@ import ThemeToggle from './ThemeToggle.astro';
<a href="/">LeetCode</a>
<a href={REPO} target="_blank" rel="noopener">GitHub ↗</a>
</nav>
<SiteSearch />
<ThemeToggle />
</div>
</header>
158 changes: 158 additions & 0 deletions src/components/SiteSearch.astro
Original file line number Diff line number Diff line change
@@ -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. */
---
<button class="search-btn" id="search-btn" type="button" aria-haspopup="dialog"
aria-keyshortcuts="Meta+K Control+K" hidden>
<svg viewBox="0 0 16 16" aria-hidden="true"><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M10.5 10.5 14 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
<span class="sb-label">Search</span>
<kbd class="sb-key" data-key aria-hidden="true"></kbd>
</button>

<dialog class="kdlg" id="search-dlg" aria-label="Search problems">
<div class="k-field">
<svg viewBox="0 0 16 16" aria-hidden="true"><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.5"/><path d="M10.5 10.5 14 14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
<input type="text" role="combobox" enterkeyhint="go" aria-expanded="true" aria-controls="k-list" aria-autocomplete="list"
aria-label="Search problems" placeholder="Search by name, number or pattern"
autocomplete="off" spellcheck="false">
</div>
<p class="k-head" data-head></p>
<div class="k-list" id="k-list" role="listbox" aria-label="Problems"></div>
<p class="k-status" data-status aria-live="polite"></p>
</dialog>

<script>
interface Row { id: number; title: string; difficulty: string; category: string; href: string; page: boolean; text: string }

const btn = document.getElementById('search-btn') as HTMLButtonElement;
const dlg = document.getElementById('search-dlg') as HTMLDialogElement;
const field = dlg.querySelector('input')!;
const list = dlg.querySelector<HTMLElement>('[role="listbox"]')!;
const head = dlg.querySelector<HTMLElement>('[data-head]')!;
const status = dlg.querySelector<HTMLElement>('[data-status]')!;

const mac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
btn.querySelector('[data-key]')!.textContent = mac ? '⌘K' : 'Ctrl K';
btn.hidden = false;

let rows: Row[] | null = null;
let loading: Promise<void> | null = null;
const load = () => (loading ??= fetch('/search.json')
.then((r) => r.json())
.then((data: Row[]) => { rows = data; })
.catch(() => { loading = null; }));

let shown: Row[] = [];
let active = 0;
let opener: HTMLElement | null = null;

/* An empty field lists the solution pages. Otherwise every term must match;
* an exact number comes first, then titles that start with what was typed,
* then problems with a page, each group in the home page's order. */
function find(q: string): Row[] {
if (!rows) return [];
const typed = q.trim().toLowerCase();
const terms = typed.split(/\s+/).filter(Boolean);
if (!terms.length) return rows.filter((r) => r.page);
const rank = (r: Row) => (String(r.id) === typed ? 0 : r.title.toLowerCase().startsWith(typed) ? 2 : 4) + (r.page ? 0 : 1);
return rows
.filter((r) => terms.every((t) => r.text.includes(t)))
.map((r, i) => ({ r, i, k: rank(r) }))
.sort((a, b) => a.k - b.k || a.i - b.i)
.map((x) => x.r);
}

function option(r: Row, i: number) {
const a = document.createElement('a');
a.className = 'k-opt';
a.id = `k-opt-${i}`;
a.href = r.href;
a.setAttribute('role', 'option');
a.tabIndex = -1;
if (!r.page) { a.target = '_blank'; a.rel = 'noopener'; }
const part = (cls: string, text: string) => {
const s = document.createElement('span');
s.className = cls;
s.textContent = text;
a.append(s);
};
part('k-num', String(r.id));
part('k-title', r.title);
part('k-sub', r.page ? r.category : 'LeetCode ↗');
part(`diff ${r.difficulty.toLowerCase()}`, r.difficulty);
return a;
}

function update() {
shown = find(field.value);
active = 0;
list.replaceChildren(...shown.map(option));
const typed = field.value.trim();
head.textContent = typed ? '' : 'Problems with a solution page';
head.hidden = !!typed;
status.textContent = !rows
? (loading ? 'Loading…' : 'Could not load the problem list.')
: shown.length
? `${shown.length} ${shown.length === 1 ? 'problem' : 'problems'} · ↑ ↓ to move, Enter to open, Esc to close`
: 'No problems match.';
mark();
}

// `scroll` is off for the pointer: the list must not move under it
function mark(scroll = true) {
list.querySelectorAll('[aria-selected]').forEach((el) => el.removeAttribute('aria-selected'));
const el = shown.length ? document.getElementById(`k-opt-${active}`) : null;
if (el) { el.setAttribute('aria-selected', 'true'); if (scroll) el.scrollIntoView({ block: 'nearest' }); }
if (el) field.setAttribute('aria-activedescendant', el.id);
else field.removeAttribute('aria-activedescendant');
}

function open() {
if (dlg.open) return;
opener = document.activeElement as HTMLElement | null;
field.value = '';
dlg.showModal();
field.focus();
const ready = load();
update();
if (!rows) ready.then(update);
}
dlg.addEventListener('close', () => { opener?.focus?.(); opener = null; });
// a click on the backdrop lands on the dialog itself
dlg.addEventListener('click', (e) => { if (e.target === dlg) dlg.close(); });

btn.addEventListener('click', open);
btn.addEventListener('pointerenter', load, { once: true });
field.addEventListener('input', update);
field.addEventListener('keydown', (e) => {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault();
if (shown.length) { active = (active + (e.key === 'ArrowDown' ? 1 : -1) + shown.length) % shown.length; mark(); }
} else if (e.key === 'Enter') {
e.preventDefault();
const el = document.getElementById(`k-opt-${active}`);
if (!el) return;
if (el.getAttribute('target') === '_blank') dlg.close();
el.click();
}
});
list.addEventListener('pointermove', (e) => {
const el = (e.target as Element).closest<HTMLElement>('.k-opt');
const i = el ? Number(el.id.slice(6)) : -1;
if (i >= 0 && i !== active) { active = i; mark(false); }
});

// ⌘K / Ctrl+K anywhere, over the browser's own use of it, and again to close.
document.addEventListener('keydown', (e) => {
if (e.key?.toLowerCase() !== 'k' || !(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return;
e.preventDefault();
if (dlg.open) dlg.close(); else open();
});
</script>
44 changes: 44 additions & 0 deletions src/data/catalog.ts
Original file line number Diff line number Diff line change
@@ -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<string, { links: { id: number }[] }>;
export const PAGE: Record<number, string> = {};
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<string, Problem[]>).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}/`;
41 changes: 2 additions & 39 deletions src/pages/index.astro
Original file line number Diff line number Diff line change
@@ -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<string, { links: { id: number }[] }>;
const WALKTHROUGH: Record<number, string> = {};
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<string, Problem[]>).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();
---
<Base
title={`LeetCode · ${SITE_NAME}`}
Expand Down Expand Up @@ -117,7 +80,7 @@ const haystack = (p: Problem) => [p.id, p.title, p.category, ...p.tags].join(' '
<span class="psub">
{!WALKTHROUGH[p.id] && <span class="soon">Solution coming soon</span>}
{p.extra && <span>Outside the core list</span>}
<a class="lc" href={`https://leetcode.com/problems/${p.slug}/`} target="_blank" rel="noopener">View on LeetCode ↗</a>
<a class="lc" href={leetcodeUrl(p.slug)} target="_blank" rel="noopener">View on LeetCode ↗</a>
</span>
</div>
<span class="ptags">{p.tags.slice(0, 3).join(' · ')}</span>
Expand Down
18 changes: 18 additions & 0 deletions src/pages/search.json.ts
Original file line number Diff line number Diff line change
@@ -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' } });
}
Loading
Loading