jereme.net home Writings About Contact
Writings

How to document and test web components without Storybook

TL;DR

  • TSDoc comments in component code describe the documentation and test setups.

  • I generate a Custom Elements Manifest (CEM) from those comments.

  • 11ty reads the CEM and generates a static documentation site from it.

  • This is done generically so it's DRY and easy to repeat.

Why I left Storybook

I started building a component library with Storybook, and it worked until the upkeep outweighed the value. It carries a heavy dependency tree and a lot of features I was never going to use, and getting it to look like my own site meant constantly fighting its opinionated UI. Worse, keeping separate story files alongside the component code created duplicate maintenance—the moment a component changed, its stories started drifting out of sync. When a major version landed and the upgrade broke my setup, I realized I was spending more time maintaining the documentation tool than the components themselves. I’ve written more about why I avoid third-party packages.

I wanted to keep the examples beside the components so I could edit both in one place. A plain static site gave me a faster build and a shorter wait before I could open the docs.

I generated a documentation site from TSDoc comments. Here is an example of my button documentation (opens in a new tab). That entire site is generated from TSDoc comments that build the Custom Element Manifest. This article explains how I did that.

How do I turn a documentation comment into a live playground?

Start in an empty directory. Use a Node version that supports TypeScript config files (opens in a new tab).

  1. Run npm init -y to create package.json.

  2. Run npm pkg set type=module so Node treats the project as an ES module.

  3. Run npm install -D typescript @custom-elements-manifest/analyzer @11ty/eleventy to install the build tools.

Create a src directory and save these two custom elements as src/components.ts. Each @summary names a page. The fenced HTML is what the page runs and shows readers. Set Cherry lives in the picker’s example because it shows how to set the picker’s value from another component.

Use @attr for the attributes readers can set in HTML. Put the method’s comment and @param beside its TypeScript signature. Here, selectFruit() gives someone using the picker in code the same way to select a fruit. For more tags, see the manifest analyzer’s supported JSDoc tags (opens in a new tab) and TSDoc’s @param reference (opens in a new tab).

/**
 * Pick one fruit. This demo starts with Lemon selected.
 *
 * ```html
 * <fruit-picker id="fruit" value="lemon"></fruit-picker>
 * <demo-button data-target="#fruit" data-attribute="value"
 *   data-value="cherry">Set Cherry</demo-button>
 * ```
 *
 * @summary Fruit Picker
 * @attr {string} value - The fruit shown in the picker. Use apple, cherry, or lemon.
 * @fires {CustomEvent} value-change - The user picked a fruit.
 */
export class FruitPicker extends HTMLElement {
  static observedAttributes = ["value"];
  private select = document.createElement("select");

  constructor() {
    super();
    this.select.setAttribute("aria-label", "Pick a fruit");
    for (const name of ["Apple", "Cherry", "Lemon"]) {
      this.select.add(new Option(name, name.toLowerCase()));
    }
    this.attachShadow({ mode: "open" }).append(this.select);
    this.select.addEventListener("change", () => {
      const value = this.select.value;
      this.selectFruit(value);
      this.dispatchEvent(new CustomEvent("value-change", {
        bubbles: true,
        detail: { value },
      }));
    });
  }

  attributeChangedCallback() {
    this.select.value = this.getAttribute("value") ?? "apple";
  }

  /**
   * Select a fruit from code.
   * @param value - The option value, such as "lemon".
   */
  selectFruit(value: string): void {
    this.setAttribute("value", value);
  }
}

/**
 * A button with a text label.
 *
 * ```html
 * <demo-button>Try the button</demo-button>
 * <demo-button disabled>Unavailable</demo-button>
 * ```
 *
 * @summary Button
 * @attr {boolean} disabled - Prevents the button from being activated.
 * @fires {MouseEvent} click - The user activated the button.
 */
export class DemoButton extends HTMLElement {
  static observedAttributes = ["disabled"];
  private button = document.createElement("button");

  constructor() {
    super();
    this.button.type = "button";
    this.button.append(document.createElement("slot"));
    this.attachShadow({ mode: "open" }).append(this.button);
  }

  attributeChangedCallback() {
    this.button.disabled = this.hasAttribute("disabled");
  }
}

customElements.define("fruit-picker", FruitPicker);
customElements.define("demo-button", DemoButton);

How do I generate both pages from the manifest?

From the project root, run npx cem analyze --globs src/components.ts. The analyzer writes custom-elements.json next to package.json. See the CEM analyzer CLI options (opens in a new tab) for the flags you can use.

Open custom-elements.json to see what 11ty will read. Each component declaration has its title in summary, its HTML fence in description, and its event names in events.

The declaration also has attributes and members lists. Find selectFruit in members to see its signature and parameter note.

Save this as eleventy.config.ts. Each declaration with a title and an example gets a page at its tag name. The renderer uses the same HTML for the demo and the code sample. It builds Attributes from the manifest’s attribute list and Methods from documented public methods. The parameter and return types come from the TypeScript signature. The root index links to each page the loop generates.

import { readFileSync } from "node:fs";

type Entry = { name: string; description?: string; type?: { text: string } };
type Member = Entry & {
  kind: string;
  privacy?: string;
  parameters?: Entry[];
  return?: { type?: { text: string } };
};
type Component = {
  tagName?: string;
  summary?: string;
  description?: string;
  events?: { name: string }[];
  attributes?: Entry[];
  members?: Member[];
};

type Config = {
  addPassthroughCopy(path: string): void;
  addTemplate(path: string, content: string, data: object): void;
};

const escapeHtml = (text: string) => text
  .replaceAll("&", "&amp;").replaceAll("<", "&lt;")
  .replaceAll(">", "&gt;").replaceAll('"', "&quot;");

function reference(heading: string, rows: { label: string; description?: string }[]) {
  if (!rows.length) return "";
  const items = rows.map(({ label, description }) =>
    `<dt><code>${escapeHtml(label)}</code></dt><dd>${escapeHtml(description ?? "")}</dd>`
  );
  return `<h2>${heading}</h2><dl>${items.join("")}</dl>`;
}

export default function (config: Config) {
  const { modules }: { modules: { declarations?: Component[] }[] } =
    JSON.parse(readFileSync("custom-elements.json", "utf8"));

  const links: string[] = [];
  config.addPassthroughCopy("assets");
  for (const { tagName, summary, description, events, attributes, members } of
    modules.flatMap(module => module.declarations ?? [])) {
    const fence = description?.match(/^([\s\S]*?)^```html\r?\n([\s\S]*?)^```$/m);
    if (!tagName || !summary || !fence) continue;

    const title = escapeHtml(summary);
    const route = `/${tagName}/`;
    links.push(`- [${summary}](${route})`);
    const markup = fence[2].trim();
    const names = escapeHtml(JSON.stringify(events?.map(event => event.name) ?? []));
    const attributeDocs = (attributes ?? []).map(({ name, type, description }) => ({
      label: type ? `${name}: ${type.text}` : name,
      description,
    }));
    const methodDocs = (members ?? [])
      .filter(member => member.kind === "method" && member.description &&
        (!member.privacy || member.privacy === "public"))
      .map(({ name, description, parameters = [], return: result }) => {
        const args = parameters.map(({ name, type }) =>
          type ? `${name}: ${type.text}` : name
        ).join(", ");
        const returns = result?.type ? `: ${result.type.text}` : "";
        const notes = parameters.map(({ name, description }) =>
          description && `${name}: ${description}`
        );
        return {
          label: `${name}(${args})${returns}`,
          description: [description, ...notes].filter(Boolean).join(" "),
        };
      });

    config.addTemplate(`${tagName}.html`, `<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>${title}</title>
<h1>${title}</h1>
<p>${escapeHtml(fence[1].trim())}</p>
<div id="demo" data-events="${names}">${markup}</div>
<p>Last event: <output id="event" aria-live="polite">none</output></p>
<h2>Example markup</h2>
<pre><code>${escapeHtml(markup)}</code></pre>
${reference("Attributes", attributeDocs)}
${reference("Methods", methodDocs)}
<script type="module" src="/assets/playground.js"></script>
</html>`, { permalink: `${route}index.html`, templateEngineOverride: false });
  }

  config.addTemplate(
    "index.md",
    `# Component examples\n\n${links.join("\n")}\n`,
    { permalink: "/index.html" },
  );
}

How to wire up an interactive documentation playground

Save this as src/playground.ts. Importing components.js registers the custom elements. The handler listens for clicks on example elements with data-target.

When you click Set Cherry, the click from the native button reaches demo-button. The handler reads the button’s data-target, data-attribute, and data-value. In this example, it finds #fruit inside #demo and sets value="cherry". The picker observes that attribute, so its attributeChangedCallback() updates the selection.

11ty puts the manifest’s event names in data-events. The playground uses those names to decide what to log. Set Cherry just changes an attribute, so the picker’s log stays at none. Choosing Apple in the picker emits value-change, and the log shows value-change: apple. On the Button page, the same script logs click.

import "./components.js";

const demo = document.querySelector<HTMLElement>("#demo")!;
const output = document.querySelector<HTMLOutputElement>("#event")!;

for (const action of demo.querySelectorAll<HTMLElement>("[data-target]")) {
  action.addEventListener("click", () => {
    const { target, attribute, value } = action.dataset;
    if (target && attribute && value !== undefined) {
      demo.querySelector(target)?.setAttribute(attribute, value);
    }
  });
}

const names: string[] = JSON.parse(demo.dataset.events ?? "[]");
for (const name of names) {
  demo.addEventListener(name, event => {
    const value = (event as CustomEvent<{ value?: string }>).detail?.value;
    output.textContent = value === undefined ? name : name + ": " + value;
  });
}

After saving the three files and generating the manifest, run these steps from the project root.

  1. Compile the browser files with npx tsc --strict --target ES2022 --module ES2022 --outDir assets src/components.ts src/playground.ts.

  2. Start the site with npx eleventy --config=eleventy.config.ts --serve.

  3. Open the local address 11ty prints. The index links to Fruit Picker and Button.

Check the two demos

  • Open /fruit-picker/. It should start on Lemon. Click Set Cherry and check that the picker changes and the log still says none. Choose Apple and check for value-change: apple. Below the demo, look for value under Attributes and selectFruit(value: string): void under Methods.

  • Open /demo-button/. Click Try the button and check for click in the log. The Unavailable button should stay disabled, as described in the Attributes section.

To try another preset, change the button label and data-value in the picker’s comment. Regenerate the manifest and restart the build. Look for the change in both the live demo and the displayed markup.

Cartoon of a cheerful green book with a red bookmark, white gloves and red sneakers, holding a pencil in each hand
jereme.net home Home About Contact