diff --git a/docusaurus.config.js b/docusaurus.config.js index 8b31ebf16..6ce68bf20 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -292,6 +292,16 @@ const config = { label: "โšก Live Code Editor", to: "/LiveEditor/", }, + // Editor + { + label: "๐Ÿ“ Code Editor", + to: "/editor/", + }, + // Playground + { + label: "๐ŸŽฎ Code Playground", + to: "/playground/", + }, // { // label: "๐Ÿ† Coding Challenges", // to: "/challenges/", diff --git a/editor.md b/editor.md new file mode 100644 index 000000000..a4c9d08ae --- /dev/null +++ b/editor.md @@ -0,0 +1,816 @@ +# Monaco Editor Real-Time Linting for CodeHarborHub + +Your template had `[INSERT LANGUAGE]` unfilled, so I built a **modular linter registry** instead of a single-language solution. It ships with: + +| Language | Strategy | Library | +|---|---|---| +| JavaScript | Real parser, exact line/column | `acorn` (lazy-loaded) | +| Python | Pure-TS heuristics: missing `:`, Py2 `print`, `if x = 5`, indentation, brackets | none | +| C, C++, Java, C#, Go | Bracket, string, and comment matching | none | + +Everything runs in the browser and is pure TypeScript, and any other language can be plugged in with `registerLinter()`. + +## Prerequisites / Setup + +```bash +npm install @monaco-editor/react monaco-editor acorn +``` + +Works with Vite, CRA, and Next.js. In Next.js, keep `'use client'` at the top of the component. Folder layout: + +``` +src/ +โ”œโ”€ lib/monaco-lint/ +โ”‚ โ”œโ”€ types.ts +โ”‚ โ”œโ”€ debounce.ts +โ”‚ โ”œโ”€ markers.ts +โ”‚ โ”œโ”€ scanner.ts +โ”‚ โ”œโ”€ linters/ +โ”‚ โ”‚ โ”œโ”€ javascript.ts +โ”‚ โ”‚ โ”œโ”€ bracket.ts +โ”‚ โ”‚ โ””โ”€ python.ts +โ”‚ โ”œโ”€ registry.ts +โ”‚ โ”œโ”€ attachLinter.ts +โ”‚ โ””โ”€ index.ts +โ””โ”€ components/LintedEditor.tsx +``` + +## The Complete Code + +### `lib/monaco-lint/types.ts` + +```ts +// A linter is a PURE function: source code in, issues out. +// It knows nothing about Monaco, so it is easy to unit-test and reuse. + +export type LintSeverity = 'error' | 'warning' | 'info' | 'hint'; + +export interface LintIssue { + message: string; + severity: LintSeverity; + // All positions are 1-based, the same convention Monaco uses. + startLine: number; + startColumn: number; + endLine: number; + endColumn: number; + code?: string; +} + +// Sync or async: async lets you lazy-load parsers or call a Web Worker. +export type Linter = (code: string) => LintIssue[] | Promise; + +export const makeIssue = ( + message: string, + line: number, + col: number, + endCol: number, + severity: LintSeverity = 'error', +): LintIssue => ({ + message, + severity, + startLine: line, + startColumn: col, + endLine: line, + endColumn: endCol, +}); +``` + +### `lib/monaco-lint/debounce.ts` + +```ts +// Minimal debounce with cancel(): waits `wait` ms after the LAST call. +export function debounce(fn: (...args: A) => void, wait: number) { + let timer: ReturnType | undefined; + + const debounced = (...args: A) => { + clearTimeout(timer); + timer = setTimeout(() => fn(...args), wait); + }; + debounced.cancel = () => clearTimeout(timer); + + return debounced; +} +``` + +### `lib/monaco-lint/markers.ts` + +```ts +import type { editor } from 'monaco-editor'; +import type { Monaco } from '@monaco-editor/react'; +import type { LintIssue } from './types'; + +const clamp = (v: number, lo: number, hi: number) => Math.min(Math.max(v, lo), hi); + +// Converts our neutral LintIssue[] into Monaco's IMarkerData[]. +// Positions are clamped to the model so a stale or buggy linter can never crash Monaco. +export function toMarkers( + monaco: Monaco, + model: editor.ITextModel, + issues: LintIssue[], +): editor.IMarkerData[] { + const severity = { + error: monaco.MarkerSeverity.Error, // red squiggle + warning: monaco.MarkerSeverity.Warning, // yellow squiggle + info: monaco.MarkerSeverity.Info, + hint: monaco.MarkerSeverity.Hint, + }; + const lastLine = model.getLineCount(); + + return issues.map((i) => { + const startLineNumber = clamp(i.startLine, 1, lastLine); + const endLineNumber = clamp(i.endLine, startLineNumber, lastLine); + const startColumn = clamp(i.startColumn, 1, model.getLineMaxColumn(startLineNumber)); + let endColumn = clamp(i.endColumn, 1, model.getLineMaxColumn(endLineNumber)); + + // Zero-width ranges are invisible, so widen them by one character. + if (endLineNumber === startLineNumber && endColumn <= startColumn) { + endColumn = Math.min(startColumn + 1, model.getLineMaxColumn(startLineNumber)); + } + + return { + severity: severity[i.severity], + message: i.message, + startLineNumber, + startColumn, + endLineNumber, + endColumn, + source: 'CHH Lint', + code: i.code, + }; + }); +} +``` + +### `lib/monaco-lint/scanner.ts` + +```ts +import { makeIssue, type LintIssue } from './types'; + +// One tiny scanner powers the C-family AND Python linters. +// It walks the source once and tracks: +// - strings (incl. unterminated ones), comments +// - bracket matching with a stack +// It also returns a "cleaned" copy of the source (strings and comments masked) +// so the Python linter can run safe regex checks without false positives. + +export interface ScanConfig { + lineComments: string[]; + blockComments: [open: string, close: string][]; + quotes: string[]; // every string delimiter + multilineQuotes?: string[]; // delimiters allowed to span lines (e.g. Go's `) + rawQuotes?: string[]; // delimiters with NO backslash escapes + tripleQuotes?: boolean; // Python / Java text blocks: """ ... """ + digitSeparators?: boolean; // C++14: 1'000'000 is not a char literal +} + +export interface ScanResult { + issues: LintIssue[]; + cleanLines: string[]; // same line count & columns as the input + isContinuation: boolean[]; // [lineNumber] -> line starts inside ( ) or a multi-line string +} + +const OPEN = new Map([['(', ')'], ['[', ']'], ['{', '}']]); +const CLOSE = new Set([')', ']', '}']); + +export function scan(code: string, cfg: ScanConfig): ScanResult { + const issues: LintIssue[] = []; + const stack: { char: string; line: number; col: number }[] = []; + const clean = code.split(''); + const isContinuation: boolean[] = []; + isContinuation[1] = false; + + let i = 0; + let line = 1; + let col = 1; + let inMultiline = false; + + // Moves one character forward while keeping line/column counters accurate. + const advance = () => { + if (code[i] === '\n') { + line++; + col = 1; + isContinuation[line] = stack.length > 0 || inMultiline; + } else { + col++; + } + i++; + }; + + // Overwrites a range in the "clean" copy (newlines are preserved for alignment). + const mask = (from: number, to: number, fill: string) => { + for (let k = from; k < to; k++) { + if (clean[k] !== '\n' && clean[k] !== '\r') clean[k] = fill; + } + }; + + while (i < code.length) { + const ch = code[i]; + + // 1) Line comments: skip to end of line. + if (cfg.lineComments.some((t) => code.startsWith(t, i))) { + const start = i; + while (i < code.length && code[i] !== '\n') advance(); + mask(start, i, ' '); + continue; + } + + // 2) Block comments: skip to the closing token. + const block = cfg.blockComments.find(([open]) => code.startsWith(open, i)); + if (block) { + const [open, close] = block; + const start = i, sl = line, sc = col; + for (let k = 0; k < open.length; k++) advance(); + let closed = false; + while (i < code.length) { + if (code.startsWith(close, i)) { + for (let k = 0; k < close.length; k++) advance(); + closed = true; + break; + } + advance(); + } + mask(start, i, ' '); + if (!closed) issues.push(makeIssue('Unterminated comment', sl, sc, sc + open.length)); + continue; + } + + // 3) C++14 digit separators (1'000) must not start a char literal. + if ( + ch === "'" && cfg.digitSeparators && + /[0-9a-fA-F]/.test(code[i - 1] ?? '') && /[0-9a-fA-F]/.test(code[i + 1] ?? '') + ) { + advance(); + continue; + } + + // 4) Strings. + if (cfg.quotes.includes(ch)) { + const triple = !!cfg.tripleQuotes && code.startsWith(ch.repeat(3), i); + const delim = triple ? ch.repeat(3) : ch; + const multi = triple || !!cfg.multilineQuotes?.includes(ch); + const raw = !!cfg.rawQuotes?.includes(ch); + const start = i, sl = line, sc = col; + + for (let k = 0; k < delim.length; k++) advance(); + inMultiline = multi; + + let closed = false; + while (i < code.length) { + if (!raw && code[i] === '\\') { // escape: skip the next char too + advance(); + if (i < code.length) advance(); + continue; + } + if (code.startsWith(delim, i)) { + for (let k = 0; k < delim.length; k++) advance(); + closed = true; + break; + } + if (code[i] === '\n' && !multi) break; // single-line string hit end of line + advance(); + } + inMultiline = false; + + mask(start, i, '_'); // hide the string's contents + if (closed) { clean[start] = '"'; clean[i - 1] = '"'; } + else { + issues.push( + makeIssue( + triple ? 'Unterminated triple-quoted string' : `Unterminated string literal (missing closing ${ch})`, + sl, sc, sc + delim.length, + ), + ); + } + continue; + } + + // 5) Brackets. + if (OPEN.has(ch)) { + stack.push({ char: ch, line, col }); + } else if (CLOSE.has(ch)) { + const top = stack.pop(); + if (!top) { + issues.push(makeIssue(`Unexpected '${ch}': no matching opening bracket`, line, col, col + 1)); + } else if (OPEN.get(top.char) !== ch) { + issues.push( + makeIssue( + `Mismatched '${ch}': expected '${OPEN.get(top.char)}' to close '${top.char}' from line ${top.line}`, + line, col, col + 1, + ), + ); + } + } + advance(); + } + + // Anything left on the stack was never closed. + for (const open of stack) { + issues.push(makeIssue(`Unclosed '${open.char}'`, open.line, open.col, open.col + 1)); + } + + return { issues, cleanLines: clean.join('').split('\n'), isContinuation }; +} +``` + +### `lib/monaco-lint/linters/bracket.ts` + +```ts +import { scan, type ScanConfig } from '../scanner'; +import type { Linter } from '../types'; + +// Factory: turns a ScanConfig into a Linter that reports bracket/string/comment problems. +export const createBracketLinter = + (cfg: ScanConfig): Linter => + (code) => + scan(code, cfg).issues; + +const C_LIKE: ScanConfig = { + lineComments: ['//'], + blockComments: [['/*', '*/']], + quotes: ['"', "'"], +}; + +export const cLinter = createBracketLinter(C_LIKE); +export const cppLinter = createBracketLinter({ ...C_LIKE, digitSeparators: true }); +export const csharpLinter = createBracketLinter(C_LIKE); +export const javaLinter = createBracketLinter({ ...C_LIKE, tripleQuotes: true }); // text blocks +export const goLinter = createBracketLinter({ + ...C_LIKE, + quotes: ['"', "'", '`'], + multilineQuotes: ['`'], // Go raw strings can span lines + rawQuotes: ['`'], // ...and have no escapes +}); +``` + +### `lib/monaco-lint/linters/javascript.ts` + +```ts +import { makeIssue, type Linter } from '../types'; + +// acorn throws a SyntaxError carrying `loc` ({ line (1-based), column (0-based) }) and `pos`. +type AcornError = SyntaxError & { loc?: { line: number; column: number }; pos?: number }; + +export const javascriptLinter: Linter = async (code) => { + // Dynamic import: acorn is only downloaded the first time JS is linted. + const { parse } = await import('acorn'); + + try { + parse(code, { + ecmaVersion: 'latest', + sourceType: 'module', // modern JS: import/export, top-level await + locations: true, + allowHashBang: true, + }); + return []; + } catch (e) { + const err = e as AcornError; + if (!err.loc) throw e; // not a syntax error, so let attachLinter log it + + // Highlight the whole offending token instead of a single character. + const token = /^[\w$]+|^\S/.exec(code.slice(err.pos ?? 0))?.[0] ?? ' '; + const col = err.loc.column + 1; // acorn: 0-based -> Monaco: 1-based + + return [ + makeIssue( + err.message.replace(/\s*\(\d+:\d+\)$/, ''), // drop acorn's "(line:col)" suffix + err.loc.line, col, col + token.length, + ), + ]; + } +}; +``` + +### `lib/monaco-lint/linters/python.ts` + +```ts +import { scan, type ScanConfig } from '../scanner'; +import { makeIssue, type LintIssue, type Linter } from '../types'; + +const PY_SCAN: ScanConfig = { + lineComments: ['#'], + blockComments: [], + quotes: ['"', "'"], + tripleQuotes: true, +}; + +const BLOCK_START = /^(?:async\s+)?(?:if|elif|else|for|while|def|class|try|except|finally|with)\b/; +const CONDITION = /^(?:if|elif|while)\b/; +const PY2_PRINT = /^print\s+(?![=(.\[,)\]:])\S/; + +// Tabs count up to the next multiple of 8, like CPython does. +const indentWidth = (ws: string) => { + let w = 0; + for (const c of ws) w = c === '\t' ? (Math.floor(w / 8) + 1) * 8 : w + 1; + return w; +}; + +// Finds the first ':' and the first stray '=' that sit OUTSIDE any brackets. +function analyze(text: string) { + let depth = 0, colon = -1, assign = -1; + for (let k = 0; k < text.length; k++) { + const c = text[k]; + if ('([{'.includes(c)) depth++; + else if (')]}'.includes(c)) depth = Math.max(0, depth - 1); + else if (depth === 0) { + if (c === ':' && text[k + 1] !== '=' && colon === -1) colon = k; + else if ( + c === '=' && assign === -1 && colon === -1 && text[k + 1] !== '=' && + !'=!<>:+-*/%&|^@~'.includes(text[k - 1] ?? ' ') // skip ==, !=, <=, +=, :=, ... + ) assign = k; + } + } + return { colon, assign }; +} + +export const pythonLinter: Linter = (code) => { + const { issues: scanIssues, cleanLines, isContinuation } = scan(code, PY_SCAN); + const issues: LintIssue[] = []; + + // 1) Group physical lines into LOGICAL lines (brackets, \ and docstrings continue a line). + const logical: { startLine: number; lines: string[] }[] = []; + let backslash = false; + cleanLines.forEach((text, idx) => { + const lineNo = idx + 1; + const cont = lineNo > 1 && (isContinuation[lineNo] || backslash); + if (cont && logical.length) logical[logical.length - 1].lines.push(text); + else if (text.trim() !== '') logical.push({ startLine: lineNo, lines: [text] }); + backslash = text.trimEnd().endsWith('\\'); + }); + + // 2) Check each logical line. + const indents = [0]; + let prev: { opensBlock: boolean; line: number; endCol: number } | null = null; + + for (const lg of logical) { + const joined = lg.lines.join('\n'); + const ws = /^[ \t]*/.exec(lg.lines[0])![0]; + const stmt = joined.slice(ws.length); + const firstCol = ws.length + 1; + const firstWord = /^\S+/.exec(stmt)?.[0] ?? ' '; + const indent = indentWidth(ws); + const top = indents[indents.length - 1]; + + // Indentation rules + if (/ \t|\t /.test(ws)) { + issues.push(makeIssue('Mixed tabs and spaces in indentation', lg.startLine, 1, ws.length + 1, 'warning')); + } + if (prev?.opensBlock) { + if (indent > top) indents.push(indent); + else issues.push(makeIssue('Expected an indented block', lg.startLine, firstCol, firstCol + firstWord.length)); + } else if (indent > top) { + issues.push(makeIssue('Unexpected indent', lg.startLine, 1, ws.length + 1)); + indents.push(indent); // avoid a cascade of follow-up errors + } else if (indent < top) { + while (indents.length > 1 && indents[indents.length - 1] > indent) indents.pop(); + if (indents[indents.length - 1] !== indent) { + issues.push( + makeIssue('Unindent does not match any outer indentation level', lg.startLine, 1, ws.length + 1), + ); + indents.push(indent); + } + } + + // Statement rules + const { colon, assign } = analyze(joined); + const isHeader = BLOCK_START.test(stmt); + + // Maps an index in `joined` back to a real line/column. + const toPos = (idx: number) => { + let l = 0, off = 0; + while (l < lg.lines.length - 1 && idx > off + lg.lines[l].length) { + off += lg.lines[l].length + 1; + l++; + } + return { line: lg.startLine + l, col: idx - off + 1 }; + }; + + // Last non-blank physical line, used to place the "missing colon" marker. + let lastIdx = lg.lines.length - 1; + while (lastIdx > 0 && lg.lines[lastIdx].trim() === '') lastIdx--; + const lastLine = lg.startLine + lastIdx; + const endCol = lg.lines[lastIdx].trimEnd().length; + + if (isHeader && colon === -1) { + issues.push(makeIssue("Expected ':' at the end of this statement", lastLine, endCol, endCol + 1)); + } else if (isHeader && CONDITION.test(stmt) && assign !== -1 && assign < colon) { + const p = toPos(assign); + issues.push(makeIssue("Invalid syntax: use '==' to compare, '=' is assignment", p.line, p.col, p.col + 1)); + } + + if (PY2_PRINT.test(stmt)) { + issues.push( + makeIssue( + "Missing parentheses in call to 'print'. Did you mean print(...)?", + lg.startLine, firstCol, firstCol + lg.lines[0].trimEnd().length - ws.length, + ), + ); + } + + prev = { + // A header missing its colon still "opens" a block, which avoids cascading errors. + opensBlock: joined.trimEnd().endsWith(':') || (isHeader && colon === -1), + line: lastLine, + endCol, + }; + } + + // A header on the very last line has no body yet. That is normal while typing, so warn only. + if (prev?.opensBlock) { + issues.push(makeIssue('Expected an indented block after this statement', prev.line, 1, prev.endCol + 1, 'warning')); + } + + return [...scanIssues, ...issues]; +}; +``` + +### `lib/monaco-lint/registry.ts` + +```ts +import type { Linter } from './types'; +import { cLinter, cppLinter, csharpLinter, goLinter, javaLinter } from './linters/bracket'; +import { javascriptLinter } from './linters/javascript'; +import { pythonLinter } from './linters/python'; + +// Keys are Monaco language ids. A Map avoids prototype-key surprises. +const LINTERS = new Map([ + ['javascript', javascriptLinter], + ['python', pythonLinter], + ['c', cLinter], + ['cpp', cppLinter], + ['java', javaLinter], + ['csharp', csharpLinter], + ['go', goLinter], +]); + +export const getLinter = (languageId: string) => LINTERS.get(languageId); + +// Plug in your own (e.g. Pyodide, Skulpt, a Web Worker, tree-sitter...). +export const registerLinter = (languageId: string, linter: Linter) => { + LINTERS.set(languageId, linter); +}; +``` + +### `lib/monaco-lint/attachLinter.ts` + +```ts +import type { editor, IDisposable } from 'monaco-editor'; +import type { Monaco } from '@monaco-editor/react'; +import { debounce } from './debounce'; +import { toMarkers } from './markers'; +import { getLinter } from './registry'; +import type { LintIssue, Linter } from './types'; + +export interface AttachLinterOptions { + delay?: number; // debounce in ms (default 300) + owner?: string; // marker owner id + resolveLinter?: (languageId: string) => Linter | undefined; + onIssues?: (issues: LintIssue[]) => void; // e.g. to power a "Problems" panel +} + +// Framework-agnostic: wires a linter to ONE Monaco editor and returns a disposable. +export function attachLinter( + ed: editor.IStandaloneCodeEditor, + monaco: Monaco, + { delay = 300, owner = 'chh-lint', resolveLinter = getLinter, onIssues }: AttachLinterOptions = {}, +): IDisposable { + let runId = 0; // increments on every run, so slow async linters can't overwrite newer results + + const run = async () => { + const model = ed.getModel(); + if (!model) return; + + const myRun = ++runId; + const version = model.getVersionId(); + const linter = resolveLinter(model.getLanguageId()); // read at lint time, so language switches just work + + // No linter for this language: clear old squiggles. + if (!linter) { + monaco.editor.setModelMarkers(model, owner, []); + onIssues?.([]); + return; + } + + let issues: LintIssue[]; + try { + issues = await linter(model.getValue()); + } catch (err) { + // A crashing linter must never break typing: log it and show no markers. + console.warn('[CHH Lint] linter failed:', err); + issues = []; + } + + // Drop stale results (newer run started, model disposed, or text changed meanwhile). + if (myRun !== runId || model.isDisposed() || model.getVersionId() !== version) return; + + monaco.editor.setModelMarkers(model, owner, toMarkers(monaco, model, issues)); + onIssues?.(issues); + }; + + const debouncedRun = debounce(run, delay); + + const subscriptions = [ + ed.onDidChangeModelContent(() => debouncedRun()), // typing: debounced + ed.onDidChangeModel(() => run()), // new file/model: lint immediately + ed.onDidChangeModelLanguage(() => run()), // language switched: lint immediately + ]; + + run(); // initial pass + + return { + dispose() { + debouncedRun.cancel(); + runId++; // invalidate in-flight async runs + subscriptions.forEach((s) => s.dispose()); + const model = ed.getModel(); + if (model && !model.isDisposed()) monaco.editor.setModelMarkers(model, owner, []); + }, + }; +} +``` + +### `lib/monaco-lint/index.ts` + +```ts +export * from './types'; +export { attachLinter } from './attachLinter'; +export type { AttachLinterOptions } from './attachLinter'; +export { getLinter, registerLinter } from './registry'; +export { toMarkers } from './markers'; +``` + +### `components/LintedEditor.tsx` + +```tsx +'use client'; // required in Next.js App Router + +import { useEffect, useRef, useState } from 'react'; +import Editor, { type OnMount } from '@monaco-editor/react'; +import type { editor, IDisposable } from 'monaco-editor'; +import { attachLinter, type LintIssue } from '../lib/monaco-lint'; + +interface Props { + language: string; // Monaco language id: python | javascript | cpp | java ... + value: string; + onChange: (value: string) => void; + height?: string; +} + +export default function LintedEditor({ language, value, onChange, height = '60vh' }: Props) { + const editorRef = useRef(null); + const lintRef = useRef(null); + const [issues, setIssues] = useState([]); + + // Runs once when Monaco is ready: attach the debounced linter (300ms). + const handleMount: OnMount = (ed, monaco) => { + editorRef.current = ed; + lintRef.current?.dispose(); + lintRef.current = attachLinter(ed, monaco, { delay: 300, onIssues: setIssues }); + }; + + // Clean up listeners and markers when the component unmounts. + useEffect(() => () => lintRef.current?.dispose(), []); + + // Click a problem to jump to it. + const jumpTo = (i: LintIssue) => { + const ed = editorRef.current; + if (!ed) return; + ed.revealLineInCenter(i.startLine); + ed.setPosition({ lineNumber: i.startLine, column: i.startColumn }); + ed.focus(); + }; + + const errors = issues.filter((i) => i.severity === 'error').length; + const warnings = issues.filter((i) => i.severity === 'warning').length; + + return ( +
+ onChange(v ?? '')} + onMount={handleMount} + options={{ + minimap: { enabled: false }, + fontSize: 14, + automaticLayout: true, + glyphMargin: true, + scrollBeyondLastLine: false, + }} + /> + + {/* Mini "Problems" panel */} +
+ + โœ– {errors} error{errors !== 1 && 's'} ยท โš  {warnings} warning{warnings !== 1 && 's'} + + {issues.map((i, idx) => ( +
jumpTo(i)} style={{ cursor: 'pointer', padding: '2px 0' }}> + + {i.severity === 'error' ? 'โ—' : 'โ–ฒ'} + {' '} + [{i.startLine}:{i.startColumn}] {i.message} +
+ ))} +
+
+ ); +} +``` + +### `App.tsx` (demo) + +```tsx +import { useState } from 'react'; +import LintedEditor from './components/LintedEditor'; + +const SAMPLES: Record = { + python: `def greet(name) + print "Hello", name + +if x = 5: + pass +`, + javascript: `const x = ; +console.log(x); +`, + cpp: `int main() { + printf("Hi); + return 0; +`, +}; + +export default function App() { + const [language, setLanguage] = useState('python'); + const [code, setCode] = useState(SAMPLES.python); + + const switchLanguage = (lang: string) => { + setLanguage(lang); + setCode(SAMPLES[lang]); + }; + + return ( +
+

CodeHarborHub ยท Live Linting Playground

+ + +
+ ); +} +``` + +### Optional: add your own language in 5 lines + +```ts +import { registerLinter, type Linter } from './lib/monaco-lint'; + +const jsonLinter: Linter = (code) => { + try { JSON.parse(code); return []; } + catch (e) { + // JSON.parse messages vary by browser, so highlight line 1 as a simple fallback. + return [{ message: (e as Error).message, severity: 'error', startLine: 1, startColumn: 1, endLine: 1, endColumn: 2 }]; + } +}; +registerLinter('json', jsonLinter); +``` + +## Example Output / Usage + +After you stop typing for 300 ms, squiggles appear and the Problems bar updates. + +**Python sample** + +| Position | Severity | Message | +|---|---|---| +| 1:15 | ๐Ÿ”ด Error | Expected ':' at the end of this statement | +| 2:5 | ๐Ÿ”ด Error | Missing parentheses in call to 'print'. Did you mean print(...)? | +| 4:6 | ๐Ÿ”ด Error | Invalid syntax: use '==' to compare, '=' is assignment | + +**JavaScript sample** (`const x = ;`) + +| Position | Severity | Message | +|---|---|---| +| 1:11 | ๐Ÿ”ด Error | Unexpected token | + +**C++ sample** + +| Position | Severity | Message | +|---|---|---| +| 2:12 | ๐Ÿ”ด Error | Unterminated string literal (missing closing ") | +| 2:11 | ๐Ÿ”ด Error | Unclosed '(' | +| 1:12 | ๐Ÿ”ด Error | Unclosed '{' | + +A tab/space mix in Python indentation shows as a ๐ŸŸก **warning**. + +## Notes for Learners + +- **JS/TS duplicate squiggles:** Monaco already has a built-in JS/TS language service. To show only CHH Lint messages for JavaScript, disable its syntax validation with `monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({ noSyntaxValidation: true })` in `beforeMount`. +- **Limits of the heuristic linters:** The Python and C-family linters are lightweight checkers, not full compilers. They catch the common beginner mistakes and avoid false positives on strings and comments, but they won't catch every error. For exact CPython errors, register an async linter that runs `compile()` in Pyodide (free, open source) inside a Web Worker. `attachLinter` already supports async linters and ignores stale results. +- **Performance:** The 300 ms debounce, stale-run guard, and lazy-loaded `acorn` keep typing smooth. + +If you'd like, I can extend this with an ESLint-style rule engine for JS (e.g., `no-unused-vars` warnings via `acorn-walk`), a Pyodide Web Worker linter, or Jest/Vitest tests for the linters. \ No newline at end of file diff --git a/renovate.json b/renovate.json index 3161e7870..2b2606c1a 100644 --- a/renovate.json +++ b/renovate.json @@ -19,6 +19,6 @@ "prHourlyLimit": 24, "prConcurrentLimit": 10, "labels": ["dependencies"], - "reviewers": ["Ajay-Dhangar"], - "assignees": ["Ajay-Dhangar"] + "reviewers": ["ajay-dhangar"], + "assignees": ["ajay-dhangar"] } diff --git a/tutorials/html/17-modern-html/details-summary.mdx b/tutorials/html/17-modern-html/details-summary.mdx index e69de29bb..2a687b1a5 100644 --- a/tutorials/html/17-modern-html/details-summary.mdx +++ b/tutorials/html/17-modern-html/details-summary.mdx @@ -0,0 +1,507 @@ +--- +id: html-modern-details-summary +title: "Details and Summary in Practice" +sidebar_label: "Details and Summary" +sidebar_position: 5 +slug: /html/modern-html/details-summary +description: "Go beyond the basics of details and summary: forms inside collapsed sections, deep links into nested details, structuring summaries, optional open and close animation, loading heavy content late, tracking toggles responsibly, and when another pattern fits better. Includes a form-in-details lab, a deep-link lab, and a true-or-false quiz." +keywords: + - details summary + - details element accordion + - details form validation + - details deep link + - nested details + - details animation details-content + - disclosure widget + - learn HTML + - CodeHarborHub HTML +tags: [html, web-development, beginner, modern-html, details, summary, accordion, forms, frontend] +--- + +import {useState} from 'react'; + +export function FormInDetailsLab() { + const [autoOpen, setAutoOpen] = useState(false); + const [msg, setMsg] = useState(""); + const [round, setRound] = useState(0); + const onInvalid = function (e) { + const d = e.target.closest("details"); + const hidden = d !== null && !d.open; + if (autoOpen && d) d.open = true; + setMsg(hidden && !autoOpen + ? "A field is invalid, but it is inside a closed section. The visitor may see nothing happen, and the form will not send." + : (hidden ? "A field inside a closed section was invalid, so the section was opened for the visitor." : "A visible field is invalid. The browser shows its message.")); + }; + return ( +
+ +
+

+ {" "} + +

+
+ Delivery details (phone is required) +

+ {" "} + +

+
+
+ + +
+
+

{msg}

+

+ Press Send with the phone field empty and the section closed. Then tick the box, reset, and try again. How browsers handle an invalid field inside a closed section differs, which is why the extra line of script is worth adding. +

+
+ ); +} + +export function revealAncestors(target) { + const opened = []; + let el = target.closest("details"); + while (el) { + if (!el.open) { + el.open = true; + const s = el.querySelector(":scope > summary"); + opened.push(s ? s.textContent.trim() : el.id); + } + el = el.parentElement ? el.parentElement.closest("details") : null; + } + return opened; +} + +export function DeepLinkLab() { + const [msg, setMsg] = useState(""); + const jump = function (id) { + const t = document.getElementById(id); + if (!t) return; + const opened = revealAncestors(t); + const s = t.matches("details") ? t.querySelector(":scope > summary") : null; + if (s) s.focus(); + else t.scrollIntoView({block: "nearest"}); + setMsg(opened.length === 0 ? "Everything on the way was already open." : "Opened: " + opened.join(" > ")); + }; + const closeAll = function () { + Array.from(document.querySelectorAll("#dl-root details")).forEach(function (d) { d.open = false; }); + setMsg("Everything is closed."); + }; + return ( +
+
+ + + +
+
+
+ Help centre +
+ Payments +

We accept cards and bank transfers.

+
+
+ Refunds +

Refunds go back to the original payment method.

+
+ Late refunds +

If a refund takes longer than ten working days, contact support.

+
+
+
+
+

{msg}

+

+ The same idea is used to open the right sections when a visitor follows a link such as the address of a question in an FAQ. +

+
+ ); +} + +export const tfItems = [ + {text: "A link placed inside a summary is a good way to make the heading clickable.", answer: false, why: "Links and buttons inside a summary fight with the toggle. Keep the summary to text, and put links in the content."}, + {text: "Content inside a closed details element is still in the page source, and its form fields still belong to the form.", answer: true, why: "Closed does not mean removed. The content is in the HTML, and its fields are submitted and validated."}, + {text: "A details element closes by itself when the visitor clicks somewhere else on the page.", answer: false, why: "It does not. That behaviour belongs to a popover. A details element stays open until the visitor closes it."}, + {text: "You may nest one details element inside another.", answer: true, why: "Nesting is allowed. Keep the depth small, so the page stays easy to scan."}, + {text: "Following a link to an item inside a closed details always opens it, with no code from you.", answer: false, why: "Behaviour varies between browsers. A few lines of script that open the ancestors make it reliable."}, + {text: "Animating the opening of a details element is an optional enhancement.", answer: true, why: "It is a nice touch where supported, and the element works fine without it."} +]; + +export function DetailsQuiz() { + const [answers, setAnswers] = useState({}); + const answered = Object.keys(answers).length; + const correct = tfItems.filter(function (it, i) { return answers[i] === it.answer; }).length; + const set = function (i, v) { + setAnswers(function (prev) { const n = Object.assign({}, prev); n[i] = v; return n; }); + }; + return ( +
+

True or false?

+ {tfItems.map(function (it, i) { + const a = answers[i]; + const right = a === it.answer; + return ( +
+

{it.text}

+ + +
+ {a !== undefined && ( +

+ {right ? "Correct. " : "Not quite. "}{it.why} +

+ )} +
+
+ ); + })} +

{answered === 0 ? "" : "Score so far: " + correct + " of " + answered + " answered."}

+
+ ); +} + +The earlier lesson on [the Details element](/tutorials/html/semantic-html/details) showed how `details` and `summary` make an expandable section with no JavaScript, how `open` works, how `name` builds an exclusive accordion, and how to style the marker. This lesson is about what happens in **real pages**: forms inside collapsed sections, links that point into them, nesting, animation, and knowing when something else fits better. + +## What You Will Learn + +- Why a required field inside a closed section can quietly block a form +- How to open the right sections for a deep link +- How to structure a good summary +- How to add an optional animation +- How to load heavy content only when needed +- When not to use `details` + + +
+ +## The Big Idea + +`details` is the simplest way to hide and reveal content, and it works without any script. Real pages add small needs on top: "show the error", "open the section I linked to", "do not load that video yet". A few lines of script cover those, and the element keeps doing the heavy lifting. + + + + + +<> + + + + + + + + +<> + + + + + + + + +<> + + + + + + + +```html title="index.html" +
+ + + +
+ Delivery details + + +
+ + +
+``` + +```js title="script.js" +// 1. Open a section when a field inside it is invalid. +// The invalid event does not bubble, so listen in the capture phase. +document.getElementById("order").addEventListener("invalid", (event) => { + const section = event.target.closest("details"); + if (section) section.open = true; +}, true); + +// 2. Open every section around a link target. +function revealFromHash() { + let id; + try { id = decodeURIComponent(location.hash.slice(1)); } catch (e) { return; } + const target = id ? document.getElementById(id) : null; + if (!target) return; + let el = target.closest("details"); + while (el) { + el.open = true; + el = el.parentElement ? el.parentElement.closest("details") : null; + } + target.scrollIntoView(); +} +window.addEventListener("hashchange", revealFromHash); +revealFromHash(); +``` + +
+
+ +## Pattern 1: Forms Inside a Collapsed Section + +Content in a closed `details` is **still in the page, and still part of the form.** Its fields are sent when the form is submitted, and checked when the browser validates the form. + +That causes a classic trap. If a `required` field sits inside a closed section and is empty, the browser cannot show a message next to a field that is not displayed. Depending on the browser and version, the visitor may see an error in the Console, a section that quietly opens, or nothing at all. The form simply **does not send**, and they cannot tell why. + +Try it in the first tab: press Send with the section closed, then turn on the checkbox, reset, and try again. + +The fix is a few lines: + +```js +form.addEventListener("invalid", (event) => { + const section = event.target.closest("details"); + if (section) section.open = true; +}, true); +``` + +- The `invalid` event fires on each field that fails validation, but it **does not bubble**, so you listen in the capture phase (the final `true`). +- Opening the section lets the browser focus the field and show its message. +- It is just as important to validate on the server, as covered in [Secure Forms](/tutorials/html/security/secure-forms). + +A simpler rule also helps: **do not hide required fields.** Keep optional fields in a collapsed section, and required ones in the open. + +## Pattern 2: Deep Links and Nested Sections + +A common request is "link to that exact question in our FAQ". The link is easy: give the `details` an `id`, and link to `#that-id`. But the visitor may arrive with the section closed, or with a closed section around it. + +Some browsers open a closed section when the address points inside it, and some do not, or only in certain cases. To be consistent, open the ancestors yourself, as in the code above. The **Deep Link Lab** does the same for a nested help centre: jump to "Late refunds" and watch every section on the way open. + +Notes on nesting: + +- **It is allowed,** but keep it shallow. Two levels are usually plenty. +- **Give the sections that you link to an `id`,** and keep ids stable. Changing one breaks old links. +- **Move focus to the summary** of the target, so keyboard and screen reader users land in the right place. + +## Pattern 3: A Good Summary + +The `summary` is the visitor's only clue to what is inside, so it needs to work on its own. + +- **Write it as a clear label or a question,** such as "Can I return an item?", not "More". +- **Keep it short,** so it does not wrap into a block of text. +- **Use text and simple inline elements.** A heading can go inside a summary, but screen reader support for headings inside a summary varies, so test it if you rely on headings for navigation. +- **Do not put links or buttons inside a summary.** They compete with the toggle, and the result is confusing for everyone. +- **Make it easy to tap.** Give the summary generous padding, so it is a comfortable target on a phone. + +## Pattern 4: An Optional Animation + +By default, a section jumps open. In browsers that support newer CSS, you can animate the height: + +```css +:root { + interpolate-size: allow-keywords; +} + +details::details-content { + block-size: 0; + overflow: clip; + transition: block-size 0.25s ease, content-visibility 0.25s allow-discrete; +} + +details[open]::details-content { + block-size: auto; +} + +@media (prefers-reduced-motion: reduce) { + details::details-content { + transition: none; + } +} +``` + +This is a **progressive enhancement**: where the features are not supported, the section simply jumps open, as before. Always include the reduced-motion rule, and check the support of `::details-content` and `interpolate-size` on MDN before relying on it. + +## Pattern 5: Load Heavy Content Late + +Content in a closed `details` is not displayed, so you can save work by keeping heavy things out of the first load. For a video, a map, or other embed: + +```html +
+ Watch the video + +
+``` + +With `loading="lazy"`, the browser usually waits until the frame is near view, so a closed section does not pay for it. The same goes for lazy images. Check this in the Network panel for your browser, because behaviour can vary. If a third party is involved, see [iFrame Security](/tutorials/html/security/iframe-security) for `sandbox` and privacy points. + +## Pattern 6: Accordions + +You can build an exclusive accordion by giving several `details` the same `name`, as the earlier lesson explained. A few extra points from practice: + +- **Open at most one** at the start, and consider opening none on small screens, to keep the page short. +- **Do not hide essential information** such as prices, warnings, or errors. +- **Browsers without `name` support** just let several stay open, which is fine. + +## Tracking Toggles (Carefully) + +The `toggle` event fires after a section opens or closes. Some sites use it to learn which FAQ questions are read most. + +```js +document.querySelectorAll("details").forEach((d) => { + d.addEventListener("toggle", () => { + if (d.open) console.log("opened:", d.id); + }); +}); +``` + +If you send this data anywhere, record **aggregate** counts, avoid personal data, and follow the privacy rules and consent requirements that apply where you operate. This is not legal advice. + +## When Not to Use details + +| You need | A better fit | +| :-- | :-- | +| A menu or card that opens above the page and closes when you click away | [Popover](./popover) | +| A pop-up that blocks the page until answered | [Dialog](./dialog) | +| A set of views where exactly one is always showing | Tabs, with the tab roles and keyboard handling | +| Site navigation with sub-menus | A button with `aria-expanded` that controls a list, which gives you full control of closing and keyboard use | +| Important content everyone must see | Plain content, in the open | + +## Checking Your Setup + +1. Submit a form that has an empty required field **inside a closed section.** Can the visitor tell what is wrong? +2. Link to a question **inside a nested section,** and follow the link in a new tab. +3. Use the **keyboard:** Tab to a summary, then press Enter or Space. +4. Test with a **screen reader** if you can, and listen to the summary text and the open or closed state. +5. Check the **Network** panel to see whether a closed section loads its heavy content. +6. Turn on **reduced motion** in your system settings, and check that the animation stops. +7. Look at the page in **right-to-left** text and at 200% zoom. + +## Best Practices + +1. **Keep required fields out of closed sections,** or open the section on `invalid`. +2. **Give linkable sections an `id`,** and open their ancestors for deep links. +3. **Write clear, short summaries,** and keep links and buttons out of them. +4. **Keep nesting shallow.** +5. **Use `loading="lazy"`** for heavy embeds inside closed sections. +6. **Animate only as an enhancement,** with a reduced-motion rule. +7. **Do not hide essential information.** +8. **Choose a popover, dialog, or button** when `details` does not fit. +9. **Track toggles only in aggregate,** and respect privacy. +10. **Validate on the server.** + +## Quick Checklist + +- [ ] Required fields are visible, or their section opens on `invalid` +- [ ] Linkable sections have stable `id`s, and ancestors open for deep links +- [ ] Each summary is a short, clear label with no links or buttons inside +- [ ] Nesting is no more than two levels +- [ ] Heavy embeds inside are lazy +- [ ] Any animation respects `prefers-reduced-motion` +- [ ] Nothing essential is hidden +- [ ] I tested with the keyboard and at 200% zoom + +## Security and Privacy Notes + +- **Hidden is not secret.** Content in a closed `details` is in the page source and in the form. Never put private data or secrets there. See [HTML Security Basics](/tutorials/html/security/html-security-basics). +- **Build summaries and content safely.** If visitor text is shown inside a section, set it with `textContent`, not `innerHTML`. See [XSS Basics](/tutorials/html/security/xss-basics). +- **Third-party embeds in a section still carry risk.** Use `sandbox`, `referrerpolicy`, and a trusted source. See [iFrame Security](/tutorials/html/security/iframe-security). +- **Toggle tracking is behaviour data.** Collect as little as you need, and tell visitors what you collect. + +## Global Audience Notes + +- **Translated labels are longer.** Let summaries wrap, and do not fix their width. +- **Right-to-left languages** move the marker to the other side. Use logical properties, such as `padding-inline-start`, and test. +- **Touch targets matter on phones,** where many visitors browse. Make summaries comfortable to tap. +- **Slow connections** benefit from lazy loading and from keeping long text collapsed until wanted. +- **Write clear, plain questions,** especially for FAQs read in a second language. + +## Common Mistakes to Avoid + +1. **Hiding a required field** in a closed section, and leaving visitors guessing. +2. **Putting links or buttons inside a summary.** +3. **Expecting a deep link to open** the right section in every browser. +4. **Nesting five levels deep.** +5. **Writing vague summaries** such as "More" or "Click here". +6. **Hiding essential information.** +7. **Loading a heavy embed** in a closed section without `loading="lazy"`. +8. **Animating without a reduced-motion rule.** +9. **Using `details` for a menu,** and expecting it to close on outside clicks. +10. **Putting secrets in hidden sections.** + +## Practice Time + +1. In the first tab, press Send with the phone empty and the section closed. What happens? Then tick the checkbox, reset, and try again. +2. In the Deep Link Lab, click "Jump to Late refunds". Which sections open? +3. Click "Close everything", then "Jump to Payments". What is different? +4. Complete the True or False quiz. +5. Add a required field inside a `details` on a test page, and add the `invalid` listener. +6. Write a `details` for a video embed with `loading="lazy"`, and check the Network panel. +7. Rewrite three vague summaries from a page of yours as clear questions. +8. Bonus: add the animation, then test it with reduced motion turned on. + +## Quick Recap + +Click a question to check your answer. + +
+1. Why can a closed details element break a form? + +Its fields are still part of the form. A required field that is empty and hidden cannot show its message, so the form may refuse to send without the visitor seeing why. + +
+ +
+2. How do you fix it? + +Listen for the `invalid` event in the capture phase, and open the closest `details` of the failing field. Better still, keep required fields visible. + +
+ +
+3. How do you make deep links reliable? + +Give the target an `id`, and with a small script open every `details` around it, then scroll or focus to the target. + +
+ +
+4. What belongs in a summary? + +A short, clear label or question. Do not put links or buttons in it. + +
+ +
+5. How can you avoid loading heavy content in a closed section? + +Use `loading="lazy"` on images and frames inside it, and check the Network panel. + +
+ +
+6. When is `details` not the right choice? + +For menus that close on outside clicks, pop-ups that block the page, tabs, and important content. Use a popover, dialog, tabs, or plain content. + +
+ +## Key Takeaways + +- **A closed `details` still belongs to the page and the form.** +- **Open the section on `invalid`,** or keep required fields visible. +- **Open ancestors for deep links,** and give linkable sections stable `id`s. +- **Short, clear summaries,** with no links or buttons inside. +- **Animation and lazy loading** are optional improvements. +- **Pick the right tool:** popover, dialog, tabs, or a plain element when `details` does not fit. +- **Hidden is not secret.** + +Next up: [Popover](./popover), where you will learn how the `popover` attribute opens menus, cards, and tooltips with no JavaScript, and closes them when the visitor clicks away. \ No newline at end of file diff --git a/tutorials/html/17-modern-html/inert.mdx b/tutorials/html/17-modern-html/inert.mdx index e69de29bb..9e58a4729 100644 --- a/tutorials/html/17-modern-html/inert.mdx +++ b/tutorials/html/17-modern-html/inert.mdx @@ -0,0 +1,503 @@ +--- +id: html-modern-inert +title: "The inert Attribute" +sidebar_label: "inert" +sidebar_position: 7 +slug: /html/modern-html/inert +description: "Learn the inert attribute: one attribute that makes part of a page unreachable by mouse, keyboard, and screen reader. Covers what inert changes, how it differs from disabled, hidden, and aria-hidden, patterns such as off-canvas menus and saving states, fallbacks, accessibility, and security notes. Includes a focus lab, an off-canvas menu lab, and a which-tool quiz." +keywords: + - inert attribute + - HTML inert + - inert vs aria-hidden + - inert vs disabled + - off-canvas menu focus + - element.inert + - keyboard focus trap + - learn HTML + - CodeHarborHub HTML +tags: [html, web-development, beginner, modern-html, inert, accessibility, focus, frontend] +--- + +import {useState, useEffect, useRef} from 'react'; + +export function probeFocus(root) { + const items = Array.from(root.querySelectorAll("[data-probe]")); + const results = items.map(function (el) { + el.focus(); + return {label: el.getAttribute("data-probe"), reached: document.activeElement === el}; + }); + if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); + return results; +} + +export function ProbeList(props) { + if (props.results === null) return null; + return ( +
    + {props.results.map(function (r) { + return ( +
  • + {r.label}: {r.reached ? "accepted keyboard focus" : "refused keyboard focus"} +
  • + ); + })} +
+ ); +} + +export function FocusLab() { + const areaRef = useRef(null); + const [mode, setMode] = useState("normal"); + const [clicks, setClicks] = useState(0); + const [probe, setProbe] = useState(null); + const [supported, setSupported] = useState(null); + useEffect(function () { + setSupported(typeof HTMLElement !== "undefined" && "inert" in HTMLElement.prototype); + }, []); + useEffect(function () { + const el = areaRef.current; + if (!el) return; + if ("inert" in el) el.inert = mode === "inert"; + if (mode === "aria") el.setAttribute("aria-hidden", "true"); + else el.removeAttribute("aria-hidden"); + setProbe(null); + }, [mode]); + const notes = { + normal: "Nothing is switched off. Every control accepts focus.", + inert: "The whole area refuses focus and clicks, and is hidden from screen readers.", + aria: "Screen readers are told to skip the area, but the keyboard can still land inside it. That mismatch is the trap." + }; + return ( +
+ {supported === false && ( +

This browser does not support inert, so the inert option will have no effect here. That is what a visitor with an older browser would get.

+ )} +
+ Switch the area + {[["normal", "Normal"], ["inert", "inert"], ["aria", "aria-hidden=\"true\" only"]].map(function (o) { + return ; + })} +
+
+

Shop area

+

+ {" "} + Help +

+

+ {" "} + +

+ +
+

Clicks received by the Buy button: {clicks} (try clicking it in each mode)

+ + +

{notes[mode]}

+

+ The test calls focus() on each control and checks whether the browser accepted it, which is the same thing the Tab key does. Nothing is stored or sent. +

+
+ ); +} + +export function MenuLab() { + const menuRef = useRef(null); + const [open, setOpen] = useState(false); + const [useInert, setUseInert] = useState(false); + const [probe, setProbe] = useState(null); + useEffect(function () { + const el = menuRef.current; + if (el && "inert" in el) el.inert = useInert && !open; + setProbe(null); + }, [open, useInert]); + return ( +
+ + +
+ +

Page content

+
+

The menu is {open ? "open and visible." : "closed and off screen."}

+ + +

+ With the menu closed and the box unticked, the links are invisible but still accept focus, so a keyboard user would tab into links they cannot see. Tick the box and test again. +

+
+ ); +} + +export const toolOptions = ["inert", "disabled", "hidden", "aria-hidden", "native dialog (showModal)"]; + +export const toolItems = [ + {job: "Stop one text field from being edited, and keep it out of the form submission", answer: "disabled"}, + {job: "Make a whole sidebar unreachable while it is off screen, for mouse, keyboard, and screen reader", answer: "inert"}, + {job: "Remove a section from the page completely, including the space it takes up", answer: "hidden"}, + {job: "Block the entire page behind a pop-up that needs an answer first", answer: "native dialog (showModal)"}, + {job: "Freeze a large form section while it saves, without changing every field", answer: "inert"}, + {job: "Hide a purely decorative icon, which cannot be focused, from screen readers", answer: "aria-hidden"} +]; + +export function ToolMatcher() { + const [picked, setPicked] = useState({}); + const [checked, setChecked] = useState(false); + const correct = toolItems.filter(function (it, i) { return picked[i] === it.answer; }).length; + return ( +
+

Pick the right tool for each job.

+ {toolItems.map(function (it, i) { + const ok = picked[i] === it.answer; + return ( +

+ +
+ + {checked && {ok ? "Correct" : "Not quite"}} +

+ ); + })} + +

{checked ? correct + " of " + toolItems.length + " correct." : ""}

+
+ ); +} + +Sometimes part of a page should be **out of reach**: a menu that has slid off screen, a section that is saving, the page behind a pop-up. Before `inert`, you switched these off by hand, with `tabindex="-1"` on every link, `aria-hidden` on containers, `pointer-events: none` in CSS, and a lot of luck. The **`inert` attribute** does the whole job with one word. + +## What You Will Learn + +- What `inert` changes, and what it leaves alone +- How it differs from `disabled`, `hidden`, and `aria-hidden` +- Patterns that use it: off-canvas menus, saving states, carousels, and overlays +- How to set it from JavaScript, and what to do without support +- Accessibility and security notes + + +
+ +## The Big Idea + +Putting `inert` on an element says: "**this part of the page is not available right now.**" The element and everything inside it stop taking part in the page, for **every** kind of visitor: mouse, touch, keyboard, and screen reader. + + + + + +<> + + + + + + + + +<> + + + + + + + + +<> + + + + + + + +```html title="index.html" + +
+ + Help + +
+ + + + +``` + +```js title="script.js" +const toggle = document.getElementById("toggle"); +const menu = document.getElementById("menu"); + +toggle.addEventListener("click", () => { + const opening = menu.inert; // inert now means "closed" + menu.inert = !opening; // reflects the attribute + toggle.setAttribute("aria-expanded", String(opening)); +}); +``` + +```css title="styles.css" +/* inert changes behaviour, not looks, so show it yourself */ +[inert] { + opacity: 0.5; +} +``` + +
+
+ +## What inert Does + +For an inert element and **all of its descendants**: + +| Part of the experience | What happens | +| :-- | :-- | +| **Pointer** | Clicks and taps do nothing, because the element is skipped when the browser works out what was pressed | +| **Keyboard** | Nothing inside can take focus, so Tab skips it | +| **Screen readers** | The content is removed from the accessibility tree, as if it were hidden | +| **Text selection** | Text cannot be selected | +| **Find in page** | Text inside is generally not found | +| **Looks** | **Nothing changes.** It still shows, exactly as before | + +That last row matters: `inert` is about **behaviour**, not appearance. If a section is switched off, show that with your own CSS, such as lower opacity, and say so in text. + +Open the **Focus Lab** and try the buttons in each mode. In the plain mode, every control accepts focus. In the `inert` mode, every control refuses it, and clicking the Buy button does nothing. + +## inert, disabled, hidden, and aria-hidden + +These four are easy to mix up: + +| Tool | Where it works | Looks | Focus and clicks | Screen reader | Form data | +| :-- | :-- | :-- | :-- | :-- | :-- | +| `inert` | Any element, with its whole subtree | Unchanged | Blocked | Hidden | Not what it is for | +| `disabled` | Form controls (and `fieldset`) | Usually greyed out | Blocked | Announced as unavailable | The control is **left out** of the submission | +| `hidden` | Any element | Not displayed, no space used | Not reachable | Hidden | Not rendered | +| `aria-hidden="true"` | Any element | Unchanged | **Not blocked** | Hidden | Unchanged | + +### The aria-hidden trap + +`aria-hidden="true"` only tells **screen readers** to ignore something. A keyboard user can still Tab into it. So a link inside an `aria-hidden` area can take focus, while a screen reader says nothing about it. That is a real accessibility failure. + +Switch the Focus Lab to `aria-hidden="true" only` and run the focus test: every control still accepts focus. `inert` fixes both problems at once. Keep `aria-hidden` for things that **cannot** be focused, such as a purely decorative icon. + +:::info +`inert` is about interaction, not form data. If you need a control left out of a submission, use `disabled` on that control. Do not depend on `inert` for that. +::: + +## Pattern 1: Off-Canvas Menus + +A menu that slides off screen with CSS is **invisible, but not gone.** Its links are still in the tab order, so a keyboard user tabs into links they cannot see, and a screen reader reads a menu that looks closed. + +The fix: set `inert` while the menu is closed, and remove it when the menu opens, as in the code above. Open the **Off-Canvas Menu Lab**, leave the box unticked, and run the focus test on the closed menu. Then tick the box and run it again. + +## Pattern 2: A Section That Is Saving + +When a large part of a form is saving, you want it frozen so no one edits it half-way. Instead of disabling every field, make the whole section inert and tell people what is going on: + +```html +

+
...many fields...
+``` + +```js +details.inert = true; +status.textContent = "Saving your changes..."; +// ...when done... +details.inert = false; +status.textContent = "Saved."; +``` + +Notice that the status message sits **outside** the inert area. An inert area is hidden from screen readers, so anything you want announced must live somewhere else. + +## Pattern 3: Slides and Hidden Panels + +In a carousel, the slides that are off screen are still in the page. Make every slide except the current one `inert`, so Tab does not wander into slides nobody can see. The same idea fits stacked panels, such as the earlier steps of a wizard that you keep in the page but not in view. + +If you do not need to keep an area in the layout at all, `hidden` is simpler. + +## Pattern 4: Behind a Custom Overlay + +A native `dialog` opened with `showModal()` already makes the rest of the page behave as if it were inert, as the [Dialog lesson](./dialog) explains. If you cannot use a `dialog` and build your own overlay, set `inert` on the page regions behind it (not on the overlay itself), and remove it when the overlay closes. Use the native dialog whenever you can, because it also handles focus and the Escape key. + +## Setting inert From JavaScript + +`inert` is a boolean attribute, and it has a matching JavaScript property that stays in sync: + +```js +panel.inert = true; // adds the attribute +panel.inert = false; // removes it +console.log(panel.inert); +``` + +A few rules to remember: + +- **It is inherited and cannot be undone below.** If a parent is inert, a child cannot opt out, even with `inert="false"`. Remove it from the parent. +- **Move focus first.** If the element that currently has focus becomes inert, focus is lost and falls back to the page. Move focus somewhere sensible before you switch a region off, for example to the control that opened it. +- **Explain the state.** Use text, a live region outside the inert area, and your own styling. + +## Support and Fallbacks + +`inert` works in current versions of the major browsers, but older versions ignore it. Check its Baseline label on MDN. In a browser without support: + +- the area simply **stays interactive**, +- and nothing breaks, but you lose the protection. + +For a low-stakes case, such as an off-screen menu, that is acceptable, and you can detect support if you want a backup: + +```js +if (!("inert" in HTMLElement.prototype)) { + // optional: add tabindex="-1" to focusable children while the area is off +} +``` + +For high-stakes cases, such as blocking the page behind a pop-up, prefer the native `dialog`, or a maintained polyfill. + +## Accessibility Notes + +- **Do not make visible, important content inert** without a clear reason and a visible explanation. People who use screen readers cannot reach it, and nobody can select or copy its text. +- **Tell visitors why.** A greyed-out area with no explanation is confusing. Add a visible message such as "Saving...", in a live region **outside** the inert area. +- **Manage focus on purpose** when you add or remove `inert`, as above. +- **Do not use `inert` to hide content** from screen readers when it should be hidden from everyone. Use `hidden`. +- **Test it:** press Tab through the page, click the area, and look at the browser's accessibility panel, if it has one, to confirm the area is gone from the tree. + +## Checking Your Setup + +1. Press **Tab** repeatedly. Does focus ever land on something you cannot see? +2. **Click** inside the area you switched off. Does anything respond? +3. In DevTools, open the **Accessibility** panel and check that the inert area is not listed. +4. Switch the state on and off, and watch where **focus** goes. +5. Test with a **screen reader** if you can, and listen for your status message. +6. Look for `aria-hidden` on containers that hold links or buttons. They are the likely bugs. +7. Test in a **second browser**, and think about what happens without support. + +## Best Practices + +1. **Use `inert`** for areas that are temporarily unavailable. +2. **Prefer it to `aria-hidden`** on anything that can take focus. +3. **Use `disabled`** for individual form controls, and `hidden` to remove things entirely. +4. **Show the state** with CSS and text. +5. **Put announcements outside** the inert area. +6. **Move focus** before inerting the region that has it. +7. **Use a native `dialog`** for modal pop-ups. +8. **Plan for browsers without support.** +9. **Keep the area small and temporary.** +10. **Test with the keyboard and a screen reader.** + +## Quick Checklist + +- [ ] Off-screen menus, slides, and panels are inert while out of view +- [ ] No focusable controls sit inside `aria-hidden` areas +- [ ] An inert area has a visible explanation and a status message outside it +- [ ] Focus is moved before a region is made inert +- [ ] I used `disabled` for single controls, and `hidden` to remove content +- [ ] Modal pop-ups use a native `dialog` +- [ ] The page still works where `inert` is not supported +- [ ] I tested with Tab, the mouse, and a screen reader + +## Security and Privacy Notes + +- **`inert` is not security.** It is a client-side setting that any visitor can remove in DevTools. Never use it to protect information or actions. The server must decide who may do what. +- **Inert content is still in the page.** It is in the source, and it may still be sent in a form. Do not hide private data in an inert area. +- **Do not rely on it to prevent double submissions** or double payments. Disable buttons, and make the server ignore repeats. See [Secure Forms](/tutorials/html/security/secure-forms). +- **Inert does not stop scripts.** A script can still read or change an inert area. + +## Global Audience Notes + +- **Keyboard and screen reader use is common** among many visitors, including people who cannot use a mouse. Hidden-but-focusable content hurts them the most. +- **Explain states in plain, translatable text.** "Saving..." and "Unavailable" are easier to translate than icons alone. +- **Slow connections make saving states long.** A clear message and a way to tell when it ends are especially helpful. +- **Older and low-cost devices** may lack support. Keep the page usable without it. + +## Common Mistakes to Avoid + +1. **Hiding a menu with CSS only,** so its links still take focus. +2. **Using `aria-hidden`** on areas with links or buttons. +3. **Making important content inert** with no explanation. +4. **Putting the status message inside** the inert area. +5. **Forgetting to move focus** before switching the area off. +6. **Expecting `inert` to change how the area looks.** +7. **Using `inert` instead of `disabled`** to keep a field out of a submission. +8. **Trying to un-inert a child** of an inert parent. +9. **Building a custom pop-up** when a native `dialog` would do. +10. **Treating `inert` as protection.** + +## Practice Time + +1. In the Focus Lab, run the focus test in all three modes. Which controls accept focus each time? +2. In `inert` mode, click the Buy button several times. What is the counter? +3. Switch to `aria-hidden` only, and press the Buy button again. What is the difference? +4. In the Menu Lab, with the menu closed and the box unticked, run the test. What does it say about invisible links? +5. Tick the box and test again. +6. Complete the **Which Tool?** quiz. +7. Add `inert` to an off-screen menu on a test page, and check it with the Tab key. +8. Bonus: write the three lines of script that freeze a form section while it saves, and announce the change. + +## Quick Recap + +Click a question to check your answer. + +
+1. What does `inert` do? + +It makes an element and all its descendants unavailable: no clicks, no keyboard focus, no screen reader access, and no text selection. It does not change how the element looks. + +
+ +
+2. How is `inert` different from `aria-hidden`? + +`aria-hidden` only hides content from screen readers, so keyboard users can still focus it. `inert` blocks pointer, keyboard, and screen reader access together. + +
+ +
+3. How is `inert` different from `disabled`? + +`disabled` applies to form controls, greys them out, and leaves them out of form submission. `inert` applies to any element and its whole subtree, and changes behaviour only. + +
+ +
+4. Why set `inert` on a closed off-canvas menu? + +A menu hidden only by CSS still takes keyboard focus and is read by screen readers. `inert` removes it from both. + +
+ +
+5. What should you do before making a region inert? + +Move focus out of it, if it holds the focused element, and prepare a visible explanation and a status message outside the region. + +
+ +
+6. Is `inert` a security feature? + +No. It is a client-side setting that visitors can remove, so the server must always enforce permissions. + +
+ +## Key Takeaways + +- **`inert` switches off an area for pointer, keyboard, and screen reader,** with one attribute. +- **It changes behaviour, not looks.** Show the state yourself. +- **Prefer it to `aria-hidden`** whenever the content can take focus. +- **Use `disabled` for single controls and `hidden` to remove content.** +- **Great for off-canvas menus, saving states, and carousels.** +- **Move focus first, and announce outside the area.** +- **Never treat it as security.** + +Next up: [template](./template), where you will learn how to keep reusable chunks of HTML in your page without showing them, and copy them when you need them. \ No newline at end of file diff --git a/tutorials/html/17-modern-html/lazy-loading.mdx b/tutorials/html/17-modern-html/lazy-loading.mdx index e69de29bb..1c9132c05 100644 --- a/tutorials/html/17-modern-html/lazy-loading.mdx +++ b/tutorials/html/17-modern-html/lazy-loading.mdx @@ -0,0 +1,381 @@ +--- +id: html-modern-lazy-loading +title: "Native Lazy Loading in Modern HTML" +sidebar_label: "Lazy Loading" +sidebar_position: 11 +slug: /html/modern-html/lazy-loading +description: "Learn native lazy loading as part of modern HTML: the loading attribute on images and iframes, what it can and cannot do, why you should never lazy-load your main image, how to avoid layout shift, and how to check your markup. Includes a live markup checker and a lazy or eager matcher." +keywords: + - lazy loading + - loading lazy + - loading eager + - lazy load images + - lazy load iframe + - LCP + - layout shift + - fetchpriority + - learn HTML + - CodeHarborHub HTML +tags: [html, web-development, beginner, modern-html, lazy-loading, performance, images, iframe, frontend] +--- + +import {useState} from 'react'; +import BrowserOnly from '@docusaurus/BrowserOnly'; + +export const lazyPresets = { + good: 'Mountain at sunrise\nLake\n', + bad: 'Mountain at sunrise\n\n\nHills' +}; + +export function checkLazy(html) { + if (typeof DOMParser === "undefined") return []; + // DOMParser builds an inert document: nothing loads and no script runs. + const doc = new DOMParser().parseFromString(html, "text/html"); + const items = Array.from(doc.querySelectorAll("img, iframe")); + const out = []; + items.forEach(function (el, i) { + const tag = el.tagName.toLowerCase(); + const name = tag + " " + (i + 1); + const loading = el.getAttribute("loading"); + if (loading !== null && loading !== "lazy" && loading !== "eager") { + out.push({level: "error", text: name + ': loading="' + loading + '" is not a valid value. Use lazy or eager.'}); + } + if (tag === "img" && !el.hasAttribute("alt")) { + out.push({level: "error", text: name + " has no alt attribute."}); + } + if (!el.hasAttribute("width") || !el.hasAttribute("height")) { + out.push({level: "warn", text: name + " has no width and height, so the page can jump when it loads."}); + } + if (tag === "iframe" && !el.hasAttribute("title")) { + out.push({level: "error", text: name + " has no title."}); + } + if (i === 0 && tag === "img" && loading === "lazy") { + out.push({level: "error", text: name + " is the first image and is lazy-loaded. If it is visible on arrival, it will load later than it should."}); + } + if (i > 0 && loading !== "lazy") { + out.push({level: "info", text: name + " is not lazy. If it is below the first screen, add loading=\"lazy\"."}); + } + }); + if (items.length === 0) out.push({level: "info", text: "No images or iframes found."}); + else if (out.filter(function (o) { return o.level !== "info"; }).length === 0) out.push({level: "ok", text: "No problems found in these " + items.length + " element(s)."}); + return out; +} + +export function LazyChecker() { + const [code, setCode] = useState(lazyPresets.bad); + const results = checkLazy(code); + const mark = {error: "Error", warn: "Warning", info: "Tip", ok: "OK"}; + return ( +
+
+ + +
+ +