diff --git a/package.json b/package.json index 6e69562..172754c 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "write-translations": "docusaurus write-translations", "write-heading-ids": "docusaurus write-heading-ids", "typecheck": "tsc", - "test": "node --test scripts/openapi-display.test.mjs scripts/gen-config-ref.test.mjs scripts/sync-catalog.test.mjs", + "test": "node --test scripts/openapi-display.test.mjs scripts/gen-config-ref.test.mjs scripts/sync-catalog.test.mjs src/components/tutorials/snippetText.test.mjs src/components/tutorials/codeGroupTabs.test.mjs", "spellcheck": "cspell \"**/*.md\" \"**/*.mdx\" --no-progress" }, "dependencies": { diff --git a/src/components/tutorials/CodeGroup.tsx b/src/components/tutorials/CodeGroup.tsx new file mode 100644 index 0000000..0b51af2 --- /dev/null +++ b/src/components/tutorials/CodeGroup.tsx @@ -0,0 +1,99 @@ +// The files of one tutorial step, shown as tabs so the page stays short: the reader opens the file +// they need and copies it. Each tab shows one CopyBlock, so every file keeps its own copy button. +// src/theme/MDXComponents/index.tsx registers it as , so tutorial pages use it without +// an import. +import React, {type KeyboardEvent, type ReactNode, useId, useRef, useState} from 'react'; +import clsx from 'clsx'; +import CopyBlock from './CopyBlock'; +import {clampTab, initialTab, nextTab} from './codeGroupTabs.mjs'; + +export type CodeGroupItem = { + /** The tab's label: the file the snippet belongs to, such as `compliance.yaml`. */ + title: string; + /** The file's text: what the tab shows, and what its copy button copies. */ + code: string; + /** Prism language to highlight the file with, such as `sh`, `yaml` or `json`. */ + language?: string; +}; + +export type CodeGroupProps = { + /** The files, in tab order. */ + items: CodeGroupItem[]; + /** Label of the file to open first; the first file when it matches none. */ + defaultTab?: string; + /** Classes added to the group. */ + className?: string; +}; + +export default function CodeGroup({items, defaultTab, className}: CodeGroupProps): ReactNode { + const group = useId(); + const tabs = useRef<(HTMLButtonElement | null)[]>([]); + const [selected, setSelected] = useState(() => initialTab(items, defaultTab)); + if (items.length === 0) { + return null; + } + const active = clampTab(selected, items.length); + + // The tablist moves the selection with the arrow keys, and to either end with Home and End; the + // decision of where a key goes lives in codeGroupTabs.mjs, where `yarn test` covers it. + function onSelectKey(event: KeyboardEvent) { + const moved = nextTab(active, event.key, items.length); + if (moved === undefined) { + return; + } + event.preventDefault(); + setSelected(moved); + tabs.current[moved]?.focus(); + } + + return ( +
+
item.title).join(', ')} + onKeyDown={onSelectKey} + className="flex flex-wrap gap-1 border-b border-[var(--ifm-color-emphasis-300)] bg-[var(--ifm-color-emphasis-100)] px-2 pt-2" + > + {items.map((item, index) => { + const isSelected = index === active; + return ( + + ); + })} +
+
+ {/* No title: the tab above the file already names it. */} + +
+
+ ); +} diff --git a/src/components/tutorials/CopyBlock.tsx b/src/components/tutorials/CopyBlock.tsx new file mode 100644 index 0000000..db4eb6e --- /dev/null +++ b/src/components/tutorials/CopyBlock.tsx @@ -0,0 +1,30 @@ +// One copy-pastable snippet: commands, config or file contents, shown as a code block the reader +// can copy in one click. It is Docusaurus's own code block (so it keeps the site's prism +// github/dracula highlighting and its copy button, made always visible in src/css/custom.css) with +// a title row and text that copies exactly as it is shown. src/theme/MDXComponents/index.tsx +// registers it as , so tutorial pages use it without an import. +import React, {type ReactNode} from 'react'; +import CodeBlock from '@theme/CodeBlock'; +import clsx from 'clsx'; +import {snippetText} from './snippetText.mjs'; + +export type CopyBlockProps = { + /** The snippet. Give this or a plain-text child, not both. */ + code?: string; + /** The snippet as text children, e.g. a template literal that spans several lines. */ + children?: string | Array; + /** Prism language to highlight the snippet with, such as `sh`, `yaml` or `json`. */ + language?: string; + /** Label above the snippet: the file it goes in, or what running it does. */ + title?: string; + /** Classes added to the block. */ + className?: string; +}; + +export default function CopyBlock({code, children, language, title, className}: CopyBlockProps): ReactNode { + return ( + + {snippetText(code, children)} + + ); +} diff --git a/src/components/tutorials/codeGroupTabs.mjs b/src/components/tutorials/codeGroupTabs.mjs new file mode 100644 index 0000000..0f8339f --- /dev/null +++ b/src/components/tutorials/codeGroupTabs.mjs @@ -0,0 +1,50 @@ +// The tab selection decisions of CodeGroup. Plain ESM with JSDoc types, like snippetText.mjs, so +// `yarn test` can cover the lookup, the clamping and the keyboard wrap-around without a browser. + +/** + * The tab to open first: the index of the item titled defaultTab, or 0 when it matches none, so + * the group opens the first file. + * + * @param {{title: string}[]} items The files, in tab order. + * @param {string | undefined} defaultTab The label of the file to open first. + * @returns {number} + */ +export function initialTab(items, defaultTab) { + return Math.max(0, items.findIndex((item) => item.title === defaultTab)); +} + +/** + * The tab the selected index must show, clamped to the last item so items shrinking below the + * selected index, which only happens in a hot reload, cannot crash the group. + * + * @param {number} selected The index selected with clicks or the keyboard. + * @param {number} count The number of items. + * @returns {number} + */ +export function clampTab(selected, count) { + return Math.min(selected, count - 1); +} + +/** + * The tab a key on the tablist moves to, wrapping around at both ends, or undefined for a key the + * tablist does not handle. + * + * @param {number} active The tab currently shown. + * @param {string} key The key pressed. + * @param {number} count The number of tabs. + * @returns {number | undefined} + */ +export function nextTab(active, key, count) { + switch (key) { + case 'ArrowRight': + return (active + 1) % count; + case 'ArrowLeft': + return (active - 1 + count) % count; + case 'Home': + return 0; + case 'End': + return count - 1; + default: + return undefined; + } +} diff --git a/src/components/tutorials/codeGroupTabs.test.mjs b/src/components/tutorials/codeGroupTabs.test.mjs new file mode 100644 index 0000000..135747a --- /dev/null +++ b/src/components/tutorials/codeGroupTabs.test.mjs @@ -0,0 +1,49 @@ +// node --test src/components/tutorials/codeGroupTabs.test.mjs (or `yarn test`) +import assert from 'node:assert/strict'; +import test from 'node:test'; +import {clampTab, initialTab, nextTab} from './codeGroupTabs.mjs'; + +const files = [{title: 'compliance.yaml'}, {title: 'filter.yaml'}, {title: 'run.sh'}]; + +test('defaultTab opens that file, by title', () => { + assert.equal(initialTab(files, 'filter.yaml'), 1); + assert.equal(initialTab(files, 'run.sh'), 2); +}); + +test('a defaultTab that matches no title, or is absent, opens the first file', () => { + assert.equal(initialTab(files, 'missing.yaml'), 0); + assert.equal(initialTab(files, undefined), 0); + assert.equal(initialTab([], 'compliance.yaml'), 0); +}); + +test('the first title wins when two files share it', () => { + assert.equal(initialTab([...files, {title: 'run.sh'}], 'run.sh'), 2); +}); + +test('selection stays put while it is within the items and clamps when they shrink below it', () => { + assert.equal(clampTab(1, 3), 1); + assert.equal(clampTab(2, 3), 2); + assert.equal(clampTab(4, 3), 2); +}); + +test('ArrowRight advances and wraps from the last tab to the first', () => { + assert.equal(nextTab(0, 'ArrowRight', 3), 1); + assert.equal(nextTab(2, 'ArrowRight', 3), 0); +}); + +test('ArrowLeft steps back and wraps from the first tab to the last', () => { + assert.equal(nextTab(1, 'ArrowLeft', 3), 0); + assert.equal(nextTab(0, 'ArrowLeft', 3), 2); +}); + +test('Home and End jump to either end', () => { + assert.equal(nextTab(1, 'Home', 3), 0); + assert.equal(nextTab(1, 'End', 3), 2); + assert.equal(nextTab(0, 'End', 1), 0); +}); + +test('a key the tablist does not handle moves nothing', () => { + assert.equal(nextTab(1, 'Enter', 3), undefined); + assert.equal(nextTab(1, 'Tab', 3), undefined); + assert.equal(nextTab(1, 'ArrowDown', 3), undefined); +}); diff --git a/src/components/tutorials/snippetText.mjs b/src/components/tutorials/snippetText.mjs new file mode 100644 index 0000000..14d280e --- /dev/null +++ b/src/components/tutorials/snippetText.mjs @@ -0,0 +1,21 @@ +// The text a tutorial block shows and copies, shared by CopyBlock and CodeGroup. Plain ESM with +// JSDoc types, like the scripts/ the site builds from, so `yarn test` can cover the trimming and +// dedent it does without a browser. + +/** + * The text of a snippet: the code, or the children joined. Blank lines at the ends are dropped and + * the indentation every line shares is removed, so a snippet written in MDX as an indented template + * literal reads the way its author wrote it, and copies exactly what the reader sees. + * + * @param {string | undefined} code The snippet, when it is given as the code prop. + * @param {string | Array | undefined} children The snippet, when it is given as + * text children. + * @returns {string} + */ +export function snippetText(code, children) { + const raw = code ?? (Array.isArray(children) ? children.join('') : (children ?? '')); + const lines = raw.replace(/^(\s*\n)+/, '').replace(/\s+$/, '').split('\n'); + const indents = lines.filter((line) => line.trim() !== '').map((line) => /^[ \t]*/.exec(line)[0].length); + const indent = indents.length > 0 ? Math.min(...indents) : 0; + return lines.map((line) => line.slice(indent)).join('\n'); +} diff --git a/src/components/tutorials/snippetText.test.mjs b/src/components/tutorials/snippetText.test.mjs new file mode 100644 index 0000000..3f47310 --- /dev/null +++ b/src/components/tutorials/snippetText.test.mjs @@ -0,0 +1,42 @@ +// node --test src/components/tutorials/snippetText.test.mjs (or `yarn test`) +import assert from 'node:assert/strict'; +import test from 'node:test'; +import {snippetText} from './snippetText.mjs'; + +test('the code prop is the text, minus the blank lines at its ends', () => { + assert.equal(snippetText('kubectl get pods\n', undefined), 'kubectl get pods'); + assert.equal(snippetText('\n\napi dashboards export f.json\n\n', undefined), 'api dashboards export f.json'); + assert.equal(snippetText(undefined, ' \n plugins:\n k8s:'), 'plugins:\n k8s:'); +}); + +test('children are joined, so a snippet can be split across expressions', () => { + assert.equal(snippetText(undefined, ['name: k8s\n', 'version: 1\n']), 'name: k8s\nversion: 1'); + assert.equal(snippetText(undefined, ['port: ', 8080]), 'port: 8080'); +}); + +test('the indentation every line shares is dropped and the rest kept, as an indented MDX literal writes it', () => { + const drafted = '\n plugins:\n k8s:\n enabled: true\n '; + assert.equal(snippetText(undefined, drafted), 'plugins:\n k8s:\n enabled: true'); +}); + +test('a snippet that already starts at column zero is left alone', () => { + assert.equal(snippetText('plugins:\n k8s:', undefined), 'plugins:\n k8s:'); +}); + +test('blank lines and shorter-indented lines inside the snippet are kept', () => { + assert.equal(snippetText('a:\n\n b: 1', undefined), 'a:\n\n b: 1'); +}); + +test('tabs count as indentation', () => { + assert.equal(snippetText('\t\tapi digest test\n\t\t --dry-run', undefined), 'api digest test\n --dry-run'); +}); + +test('code wins when the author gives both it and children', () => { + assert.equal(snippetText('from code', ['from children']), 'from code'); +}); + +test('no snippet gives no text', () => { + assert.equal(snippetText(undefined, undefined), ''); + assert.equal(snippetText(undefined, []), ''); + assert.equal(snippetText(' \n \n', undefined), ''); +}); diff --git a/src/css/custom.css b/src/css/custom.css index c566c99..83cd575 100644 --- a/src/css/custom.css +++ b/src/css/custom.css @@ -35,3 +35,20 @@ --ifm-color-primary-lightest: #4fddbf; --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3); } + +/* The tutorial blocks (src/components/tutorials) read the site's Infima variables, so they follow + the light and dark themes on their own. These two rules reach into Docusaurus's code block. */ + +/* A reader is meant to copy these snippets, so their buttons stay visible instead of fading in + only when the block is hovered. !important beats the theme's own hover opacity rules. */ +.ccf-copy-block button.clean-btn { + opacity: 1 !important; +} + +/* Inside a code group, the group's own border, radius and shadow are the block's chrome, so the + file shown drops its own, along with the margin that separates two standalone blocks. */ +.ccf-code-group .ccf-copy-block { + border-radius: 0; + box-shadow: none; + margin-bottom: 0; +} diff --git a/src/theme/MDXComponents/index.tsx b/src/theme/MDXComponents/index.tsx new file mode 100644 index 0000000..4e94a5a --- /dev/null +++ b/src/theme/MDXComponents/index.tsx @@ -0,0 +1,12 @@ +// Registers the tutorial components on every page's MDX scope, so a tutorial page writes +// and without importing them. Docusaurus reads the MDX component scope +// from this module, and the wrapper keeps the theme's own mappings (code, a, ul, admonition...). +import MDXComponents from '@theme-original/MDXComponents'; +import CopyBlock from '@site/src/components/tutorials/CopyBlock'; +import CodeGroup from '@site/src/components/tutorials/CodeGroup'; + +export default { + ...MDXComponents, + CopyBlock, + CodeGroup, +};