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
26 changes: 22 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ The kit's body, link, code and table styles skip anything inside a `not-prose`
element, so a box that draws its own table, list or heading keeps its own
layout.

A table sits in a `docs-kit-table` box that `getDocsKitMDXComponents` draws
around it, so the box's width, not the screen's, decides the layout. A table of
up to five columns has fixed columns: the first takes 45% of a two-column table
and 30% of a three-column one, so tables on a page share their lines. Where the
box is narrower than 35rem, each row stacks as an entry. A site that registers
its own `table` component must keep that box (`<div className="docs-kit-table
relative my-6 overflow-auto prose-no-margin">`) or its tables never stack.
A heading that is only a name in code, such as a member on a reference page,
draws as plain monospace text with no chip.

### Configure the MDX source

In `source.config.ts`, import from `@withmarfa/docs-kit/config`, not from `/mdx`: the config entry reaches Fumadocs's Node-only plugins, and `/mdx` stays free of them so a page can load it in the browser. Use `codeOptions` for code highlighting and
Expand Down Expand Up @@ -214,8 +224,9 @@ sections are reachable another way:

- **A page outside the docs layout** (`DocsHomeHeader`, such as a landing page
or the 404 page) gets one menu button. It opens a panel under the bar with the
sections, then the icon links and the appearance control. The panel closes on
navigation, on Escape and on the button, and moves focus into itself and back.
sections, then the icon links and the appearance control at its foot. The panel
closes on navigation, on Escape and on the button, and moves focus into itself
and back.
- **A page in the docs layout** (`DocsHeader`) lists the sections at the top of
the phone drawer, and of the desktop sidebar below 1024px, when you pass the
`sidebar` slot and turn off Fumadocs's own tabs, whose dropdown lists only the
Expand All @@ -227,6 +238,11 @@ sections are reachable another way:

Without `sidebar`, the drawer shows Fumadocs's tab dropdown as before.

On a phone the drawer is the same pattern as the landing menu: it fills the
screen under the bar, the bar's menu button turns into the close control where
it was, the current section is bold and the current page keeps its pill, and the
icon links and appearance control sit at the foot.

`baseOptions` puts the drawer's icon links in the order of the phone menu: the
`githubUrl` first, then the `links` you pass.

Expand Down Expand Up @@ -442,8 +458,10 @@ export const Route = createFileRoute('/api/search')({
the same index can serve a tool as well as the search box.

The route answers the search box with one row per page, then at most three
matches under it, each on a single line around the first match. `searchDocs`
keeps the full snippets.
matches under it, each on a single line around the first match, ending in an
ellipsis where it is cut. A breadcrumb starts at the section, not at the site's
name. `searchDocs` keeps the full snippets. Below 768px the box's Escape chip
reads "Close", since a phone has no Escape key.

To show those rows, pass the kit's `SearchDialog` to Fumadocs's `RootProvider`.
`links` lists pages before anything is typed (`[name, url]`, as Fumadocs's own
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@withmarfa/docs-kit",
"version": "0.0.1-alpha.4",
"version": "0.0.1-alpha.5",
"description": "The shared look and plumbing of WithMarfa's documentation sites: Fumadocs layout, components, styles, agent surfaces and search.",
"license": "Apache-2.0",
"type": "module",
Expand Down
72 changes: 72 additions & 0 deletions src/components/code.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// @vitest-environment jsdom
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getDocsKitMDXComponents } from './mdx-components';

declare global {
var IS_REACT_ACT_ENVIRONMENT: boolean;
}
globalThis.IS_REACT_ACT_ENVIRONMENT = true;

const { pre: Pre, Terminal } = getDocsKitMDXComponents() as Record<string, React.ComponentType<any>>;

const block = (text: string) => (
<Pre className="shiki">
<code>
<span className="line">{text}</span>
</code>
</Pre>
);

let container: HTMLDivElement;
let root: Root;
let written: string[];

beforeEach(() => {
written = [];
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText: (text: string) => (written.push(text), Promise.resolve()) },
});
container = document.createElement('div');
document.body.append(container);
root = createRoot(container);
});

afterEach(() => {
act(() => root.unmount());
container.remove();
vi.restoreAllMocks();
});

const copy = () => container.querySelector<HTMLButtonElement>('button')!;

describe('the copy button of a code block', () => {
it('shows two squares, the icon the page\'s Copy Markdown button uses, never a clipboard', () => {
act(() => root.render(<Pre title="Example">{block('example whoami').props.children}</Pre>));
expect(copy().querySelector('svg')?.getAttribute('class')).toContain('lucide-copy');
expect(copy().textContent).toBe('Copy text');
});

it('copies the block\'s text and shows a check afterwards', async () => {
act(() => root.render(block('example whoami')));
await act(async () => copy().click());
expect(written).toEqual(['example whoami']);
expect(copy().querySelector('svg')?.getAttribute('class')).toContain('lucide-check');
expect(copy().textContent).toBe('Copied text');
});

it('copies a terminal\'s command and leaves its output out', async () => {
act(() =>
root.render(
<Terminal>
{block('example whoami')}
{block('owner')}
</Terminal>,
),
);
await act(async () => copy().click());
expect(written).toEqual(['example whoami']);
});
});
44 changes: 41 additions & 3 deletions src/components/code.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { CodeBlock, Pre } from 'fumadocs-ui/components/codeblock';
import { buttonVariants } from 'fumadocs-ui/components/ui/button';
import { useCopyButton } from 'fumadocs-ui/utils/use-copy-button';
import { Check, Copy } from 'lucide-react';
import {
Children,
createContext,
createElement,
isValidElement,
useRef,
useState,
type ComponentProps,
type ReactElement,
Expand Down Expand Up @@ -54,18 +58,52 @@ function Status({ code }: { code: string }) {
);
}

/**
* Copy, with the two-squares icon the page's Copy Markdown button uses;
* Fumadocs draws a clipboard. It reads the block's first `pre`, as Fumadocs
* does, so a terminal's output is left out, and writes `.nd-copy-ignore`
* spans as line breaks.
*/
function CopyCode() {
const button = useRef<HTMLButtonElement>(null);
const [checked, onClick] = useCopyButton(() => {
const pre = button.current?.closest('figure')?.getElementsByTagName('pre').item(0);
if (!pre) return;
const clone = pre.cloneNode(true) as HTMLElement;
clone.querySelectorAll('.nd-copy-ignore').forEach((node) => node.replaceWith('\n'));
return navigator.clipboard.writeText(clone.textContent ?? '');
});
return (
<button
ref={button}
type="button"
data-checked={checked || undefined}
aria-live="polite"
className={buttonVariants({
size: 'icon-xs',
className: 'hover:text-fd-accent-foreground data-checked:text-fd-accent-foreground',
})}
onClick={onClick}
>
{checked ? <Check /> : <Copy />}
<span className="sr-only">{checked ? 'Copied text' : 'Copy text'}</span>
</button>
);
}

/**
* The header's right-hand side: an optional note or status chip, then Copy.
* Fumadocs calls this where it draws its Copy button, so the extras sit
* in the same row without a header of our own.
* in the same row without a header of our own. It also stands in for the
* button itself, which it draws when Fumadocs would have drawn its own.
*/
function actions(note: string | undefined, status: string | undefined) {
return function Actions({ className, children }: ComponentProps<'div'>) {
return (
<>
{note ? <span className="docs-kit-code-note">{note}</span> : null}
{status ? <Status code={status} /> : null}
<div className={cn('empty:hidden', className)}>{children}</div>
<div className={cn('empty:hidden', className)}>{children ? <CopyCode /> : null}</div>
</>
);
};
Expand Down Expand Up @@ -115,7 +153,7 @@ function CodeBlockCard({
<CodeBlock
{...block}
title={header ? title || NO_TITLE : undefined}
Actions={header ? actions(note, status) : undefined}
Actions={actions(header ? note : undefined, header ? status : undefined)}
>
{children}
</CodeBlock>
Expand Down
39 changes: 28 additions & 11 deletions src/components/docs-header.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = true;

// The sidebar's state, trigger and drawer as Fumadocs draws them: the trigger
// is a button named for the state, and the open drawer holds a close button of
// its own that controls the same drawer.
// its own that controls the same drawer, which the stylesheet hides.
let setOpen: (open: boolean) => void = () => {};
let isOpen = false;
vi.mock('fumadocs-ui/layouts/notebook', () => ({
Expand Down Expand Up @@ -38,6 +38,8 @@ vi.mock('@tanstack/react-router', () => ({ useRouterState: () => '/' }));

const { DocsHeader } = await import('./docs-header');

let withCurrent = false;

function Page() {
const [open, set] = useState(false);
isOpen = open;
Expand All @@ -49,6 +51,11 @@ function Page() {
<aside id="nd-sidebar-mobile">
<button type="button" aria-label="Close Sidebar" aria-controls="nd-sidebar-mobile" onClick={() => set(false)} />
<a href="/next">Next</a>
{withCurrent ? (
<a href="/current" data-active="true">
Current
</a>
) : null}
</aside>
) : null}
</>
Expand All @@ -74,31 +81,41 @@ const toggle = () => container.querySelector<HTMLButtonElement>('header [aria-co
const drawerClose = () => container.querySelector<HTMLButtonElement>('#nd-sidebar-mobile button')!;

describe('the menu button on a phone', () => {
it('is the only control for the sidebar while the drawer is shut', () => {
it('is the control for the sidebar while the drawer is shut', () => {
expect(toggle().getAttribute('aria-label')).toBe('Open Sidebar');
expect(toggle().hasAttribute('inert')).toBe(false);
});

it('leaves the accessibility tree and the tab order while the drawer is open, so one Close Sidebar remains', () => {
it('stays live and rises above the drawer when it opens, so it closes the drawer from where it opened it', () => {
expect(container.querySelector('header')!.className).not.toContain('max-md:z-[45]');
act(() => toggle().click());
expect(toggle().hasAttribute('inert')).toBe(false);
expect(toggle().getAttribute('aria-label')).toBe('Close Sidebar');
expect(container.querySelector('header')!.className).toContain('max-md:z-[45]');
act(() => toggle().click());
expect(toggle().hasAttribute('inert')).toBe(true);
const live = [...container.querySelectorAll<HTMLElement>('[aria-controls="nd-sidebar-mobile"]')].filter(
(element) => !element.closest('[inert]'),
);
expect(live).toEqual([drawerClose()]);
expect(container.querySelector('#nd-sidebar-mobile')).toBeNull();
});

it('hands focus to the drawer when it opens', async () => {
it('hands focus to the first link of the drawer when it opens', async () => {
toggle().focus();
act(() => toggle().click());
await act(() => new Promise((resolve) => requestAnimationFrame(resolve)));
expect(document.activeElement).toBe(drawerClose());
expect(document.activeElement).toBe(container.querySelector('#nd-sidebar-mobile a'));
});

it('hands focus to the current page when the drawer marks one', async () => {
withCurrent = true;
act(() => root.render(<Page />));
act(() => toggle().click());
await act(() => new Promise((resolve) => requestAnimationFrame(resolve)));
expect(document.activeElement?.textContent).toBe('Current');
withCurrent = false;
});

it('takes focus back when the drawer closes with focus inside it', () => {
act(() => toggle().click());
drawerClose().focus();
act(() => drawerClose().click());
expect(toggle().hasAttribute('inert')).toBe(false);
expect(document.activeElement).toBe(toggle());
});

Expand Down
28 changes: 18 additions & 10 deletions src/components/docs-header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ export function DocsHeader({ site, ...props }: ComponentProps<'header'> & { site
{...props}
className={cn(
'sticky top-(--fd-docs-row-1) z-10 bg-fd-background/80 backdrop-blur-sm [grid-area:header] layout:[--fd-header-height:--spacing(14)]',
// The open drawer starts under the bar and the bar stays, as on a landing page, so it rises above the drawer
// and its overlay (z-40) but stays under the search dialog (z-50), which opens from the bar's own button.
open && 'max-md:z-[45]',
props.className,
)}
>
Expand All @@ -62,9 +65,9 @@ export function DocsHeader({ site, ...props }: ComponentProps<'header'> & { site
actions={
<DocsActions site={site}>
{sidebar ? (
// The open drawer covers this button and has a close button of its own, which is the one control to
// announce, so `inert` takes this one out of the accessibility tree and the tab order.
<sidebar.trigger ref={toggle} inert={open} className={cn(iconButton, 'md:hidden')}>
// The drawer opens under the bar, so this button stays where it is and closes it. The drawer's own
// close button is hidden by `styles.css`, which leaves one control to announce.
<sidebar.trigger ref={toggle} className={cn(iconButton, 'md:hidden')}>
{open ? <X strokeWidth={1.75} /> : <Menu strokeWidth={1.75} />}
</sidebar.trigger>
) : null}
Expand All @@ -75,12 +78,12 @@ export function DocsHeader({ site, ...props }: ComponentProps<'header'> & { site
);
}

const DRAWER_CLOSE = '#nd-sidebar-mobile [aria-controls="nd-sidebar-mobile"]';
const DRAWER = '#nd-sidebar-mobile';

// Focus follows the drawer: into it when it opens, which `inert` would
// otherwise drop to the page's start, and back to the menu button when it
// closes with focus still inside it or lost. The drawer mounts a frame after
// `open` changes, so the close button is looked up then. Escape closes it:
// Focus follows the drawer, as it does in the landing menu: into it when it
// opens, to the current page or else the first link, and back to the menu
// button when it closes with focus still inside it or lost. The drawer mounts a
// frame after `open` changes, so the link is looked up then. Escape closes it:
// Fumadocs 16.15 has no handler, and a later one that also closes it is harmless.
function useDrawerFocus(open: boolean, toggle: RefObject<HTMLButtonElement | null>, close: () => void) {
const opened = useRef(false);
Expand All @@ -89,7 +92,12 @@ function useDrawerFocus(open: boolean, toggle: RefObject<HTMLButtonElement | nul
useEffect(() => {
if (open) {
opened.current = true;
const frame = requestAnimationFrame(() => document.querySelector<HTMLElement>(DRAWER_CLOSE)?.focus());
const frame = requestAnimationFrame(() =>
(
document.querySelector<HTMLElement>(`${DRAWER} a[aria-current], ${DRAWER} a[data-active="true"]`) ??
document.querySelector<HTMLElement>(`${DRAWER} a`)
)?.focus(),
);
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape' && !event.defaultPrevented) closeRef.current();
};
Expand All @@ -102,7 +110,7 @@ function useDrawerFocus(open: boolean, toggle: RefObject<HTMLButtonElement | nul
if (opened.current) {
opened.current = false;
const active = document.activeElement;
if (!active || active === document.body || active.closest('#nd-sidebar-mobile')) toggle.current?.focus();
if (!active || active === document.body || active.closest(DRAWER)) toggle.current?.focus();
}
}, [open, toggle]);
}
Expand Down
29 changes: 29 additions & 0 deletions src/components/error-page.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { ErrorPage } from './error-page';

describe('ErrorPage', () => {
const html = renderToStaticMarkup(
<ErrorPage message="Nothing is here." primaryHref="/" primaryLabel="Go home" secondaryHref="/search" secondaryLabel="Search" />,
);
const links = [...html.matchAll(/<a href="([^"]*)" class="([^"]*)">([^<]*)<\/a>/g)];

it('puts the primary action first', () => {
expect(links.map((m) => [m[1], m[3]])).toEqual([
['/', 'Go home'],
['/search', 'Search'],
]);
});

it('makes both buttons the size and weight of a site\'s main buttons', () => {
for (const link of links) {
expect(link[2]).toContain('h-10');
expect(link[2]).toContain('font-medium');
expect(link[2]).toContain('text-sm');
}
});

it('draws no second button without a label for it', () => {
expect(renderToStaticMarkup(<ErrorPage message="x" primaryHref="/" primaryLabel="Go home" />).match(/<a /g)).toHaveLength(1);
});
});
Loading