Skip to content

AI Code Generation — Local-first component library with Storybook

Created:
Updated:

In the previous post in this series — AI Code Generation — From prompt to XM Cloud component matrix — I focused on requirements, not code. Starting from a manually curated component matrix or Figma design system, I used coding agents to produce one Sitecore-ready requirement markdown file per component under something like ai/prompts/component_specs/Accordion.md.

This post is about what happens next: how I take those requirement files and let coding agents generate a local-first component library with Storybook, staying close to the specs while keeping humans firmly in charge.

For this phase I usually work inside a Next.js + TypeScript repo (often the same one that will later host the XM Cloud head) and lean on:

Going “local‑first” with this setup has helped me in two very practical ways on real projects:

At a high level, the flow I use looks like this:

Component requirements

React components

Component library / Storybook

Mock data / Storybook

The input to this post is only the requirement files from the previous one; Storybook and code show up here for the first time.

From here, the rest of the series builds on this library:


Starting point: requirement files, not spreadsheets

By now, the component matrix work is done. For each component you have a markdown file that looks roughly like this (shortened here for space):

# Requirements

## Name
Accordion

## Description
Expandable FAQ container used to present grouped questions and answers. Authors can supply an optional intro with subtitle, then curate individual accordion items that reveal detailed answers on click. Component supports lazy loading and can reveal additional items with a “Load more” control.

## Fields

### Title
- **Field Type**: Single-Line Text
- **Required**: Yes
...

### Accordion Items
- **Field Type**: Treelist (Accordion Item)
- **Required**: Yes
- **Repeating**: Yes
...

#### Accordion Item Fields:
- **Question**: Single-Line Text - Title displayed on the accordion trigger.
- **Answer**: Rich Text - Content revealed when the panel expands; supports lists and inline links.
- **Anchor ID**: Single-Line Text - Optional anchor for deep-linking directly to the FAQ entry.

## Example Reference
* **URL**: https://www.cws.com/en/workwear/products
* **Element**: `<div class="paragraph paragraph--type--faq lazy-load workwear lazy-inst-1">`

## Notes
- Component lazy-loads content to improve performance; ensure important FAQs appear in the first three slots.
...

My goal for this post is to treat that folder of requirement files as the only input and have agents:


Give the code repo its own AGENTS.md

Just like the requirements workspace had its own AGENTS.md, I give the code repo a dedicated one. This keeps agents aligned on tech stack, structure, and what they are allowed to generate.

Here is a trimmed‑down version of what I use for a Next.js + Storybook component library that will later be wired into XM Cloud:

# AGENTS.md — Local-first component library for XM Cloud

## Project scope
- Next.js + TypeScript component library built Storybook-first.
- Components will later be wired into Sitecore XM Cloud (BYOC).
- Input: requirement markdown files under `ai/prompts/component_specs/`.

## Preferred models
- Primary: OpenAI ChatGPT-5 Codex for coding tasks.
- Secondary: Claude Sonnet 4 for analysis-heavy refactors and reviews.
- Budget: Google CLI with Gemini 2.5 (expect more manual review and corrections).

## Tech stack
- Next.js App Router (e.g., `src/app`).
- React + TypeScript with strict type checking.
- Storybook for component development.
- Styling: CSS Modules or Sass Modules (as configured in this repo).

## File structure
- Components live under `src/components/<ComponentName>/`.
- Each component folder usually contains:
  - `<ComponentName>.tsx` — implementation.
  - `<ComponentName>.stories.tsx` — Storybook stories.
  - `<ComponentName>.props.ts` — typed props / Sitecore mapping (optional).
  - `<ComponentName>.module.(css|scss)` — styling.

## Conventions
- Component names are PascalCase (e.g., `Accordion`, `IndustryCard`).
- Props map 1:1 to fields defined in requirement files.
- Components should be pure and data-agnostic: no direct HTTP calls or CMS access.

## What you should generate
- New components and stories based on existing requirement files.
- Supporting types and mock data as needed.
- Do NOT change project configuration or CI scripts unless explicitly asked.

I reference this file from my prompts so agents understand that the requirements repo and the code repo have different roles.


Batch task: generate components from all spec files

Once the repo is agent‑friendly, I set up a batch prompt that tells a coding agent how to transform every requirements file in ai/prompts/component_specs/ into a component folder under src/components/.

Here is a version of that task, adapted to the way I usually run this phase.

# Component generation from requirement files

## Overview

You are an AI coding agent working inside a Next.js + TypeScript project.

Your goal is to read all component requirement markdown files and, for each one, generate a Storybook-ready React component package using the project’s conventions.

Preferred models:
- OpenAI ChatGPT-5 Codex for code generation.
- Claude Sonnet 4 if Codex is unavailable.
- Google CLI with Gemini 2.5 only if necessary and with extra human review.

## Input files

- **Requirements directory**: `ai/prompts/component_specs/` (all `.md` files).
- **Component template prompt**: `ai/prompts/create_component.md` (describes file structure and naming).

## Component name extraction

For each requirements file:

1. **Filename**: start from the filename without `.md` (e.g., `Accordion.md``Accordion`).  
2. **Content**: if the filename is generic, read the `## Name` section inside the file.  
3. **Sanitize**: convert the result to PascalCase for the component name (e.g., `industry-card``IndustryCard`).

## Processing strategy

- Scan `ai/prompts/component_specs/` and build a list of all `.md` files.  
- Validate that each file can be read and parsed; build a processing queue.  
- Process components in batches (for example 5–8 per batch) to keep context manageable.  
- For each batch:
  - Read `ai/prompts/create_component.md` once.  
  - For each spec in the batch:
    - Extract the component name.  
    - Read the requirements content.  
    - Generate or update the component files (`.tsx`, `.stories.tsx`, styles, props) under `src/components/<ComponentName>/`.  
  - Report which components succeeded or failed.

## Output requirements

For every requirement file, generate a component package that:

- Lives under `src/components/<ComponentName>/`.  
- Includes at least:
  - `<ComponentName>.tsx` — React component with strictly typed props that map to fields in the requirements file.  
  - `<ComponentName>.stories.tsx` — Storybook stories showcasing default and key variant states using realistic mock data.  
  - `<ComponentName>.module.(css|scss)` — styling consistent with the repo.  
- Uses existing utilities, design tokens, and shared primitives when available (do not reinvent button or typography primitives).  
- Does **not** make any direct calls to Sitecore XM Cloud or Experience Edge; props should be passed in from the outside.

## Logging

Maintain a markdown log at `ai/prompts/component_generation_log.md` with:

```md
# Component generation log

## Summary
- Total specs found: [count]
- Successfully generated: [count]
- Failed: [count]
- Skipped: [count]

## Detailed results
| Component Name | Status | Notes |
|----------------|--------|-------|
| Accordion      | ✓ Success | - |
| IndustryCard   | ✓ Success | - |
| BrokenSpec     | ✗ Failed | Missing required fields section |

Pre-execution checks

Before you start, verify that:


I generally paste this prompt into the agent, attach or reference the `AGENTS.md`, `create_component.md`, and a handful of requirement files, then let it generate a first batch while I review the output.

---

## Single-component prompt: Accordion as a Storybook-first build

For components that deserve more attention—or when the batch output needs refinement—I use a **single‑component prompt**. Here is a version tailored to the Accordion requirements and a Storybook‑first approach.

```md
You are working inside a Next.js + TypeScript repo that will later be wired into Sitecore XM Cloud.

I need you to build a new component “Storybook-first” based on an existing requirement document.

## Inputs

- Requirement file: `ai/prompts/component_specs/Accordion.md`  
  - This file defines fields, example values, and behavior for the Accordion component.  
- Project conventions: see `AGENTS.md` in the repo root.  
- Target location: `src/components/Accordion/`.

## Goals

Implement a fully-typed, accessible Accordion component and its Storybook stories, using the requirement file as the single source of truth.

## Files to create or update

- `src/components/Accordion/Accordion.tsx`  
  - React component that maps props 1:1 to the fields in the requirements file (titles, intro text, items, load-more toggle, background theme, etc.).  
  - No direct CMS calls; all data comes from props.  

- `src/components/Accordion/Accordion.module.(css|scss)`  
  - Styling that matches the look and feel implied by the Example Reference and Notes.  
  - Use the project’s preferred styling approach (CSS Modules or Sass Modules) and design tokens where available.  

- `src/components/Accordion/Accordion.props.ts` (optional)  
  - TypeScript interfaces for props and item types, named consistently with Sitecore field concepts (e.g., `AccordionProps`, `AccordionItem`).  

- `src/components/Accordion/Accordion.stories.tsx`  
  - Storybook stories showing:
    - A default FAQ list with 3–5 items.  
    - A variant with “Load more” enabled and more than 3 items.  
    - An edge-case variant with minimal content.  

## Implementation notes

- Map each Sitecore field in the requirements document to a prop.  
  - For example, `Load More Enabled` becomes a boolean prop that controls whether extra items are hidden behind a “load more” button.  
- For repeating items, create a typed array of item objects (`AccordionItem[]`).  
- Ensure accessibility:
  - Use semantic markup for accordions (e.g., buttons with `aria-expanded`, `aria-controls`, and appropriate heading levels).  
  - Support keyboard navigation (Enter/Space to toggle, arrow keys if appropriate for your design system).  
- Implement the “only one panel open at a time” behavior described in the Notes.  
- Reflect the `Background Theme` field in CSS classes (e.g., `accordion--light-grey`).  

## Storybook specifics

- Stories must import the component from `src/components/Accordion/Accordion`.  
- Use realistic mock data based on the Example Reference and field guidelines.  
- Give the story a clear `title` in the Storybook tree (e.g., `Components/Accordion`).  
- Avoid live CMS calls or network requests in stories; use local mock data only.

## Out of scope

- Do NOT register this component in XM Cloud or modify any Sitecore configuration.  
- Do NOT create Playwright tests in this task; focus on the component and stories only.

I keep the prompt close to the requirements language so it is easy to verify that every field and behavior made it into the component and its stories.


Storybook-first, local-first workflow

Once a few components like Accordion are in place, the rest of the library tends to follow the same pattern:

Some habits that have helped:

Tests (Playwright or otherwise) still matter, but I tend to cover them in the BYOC/Integration steps rather than at this first implementation pass.


How this feeds into XM Cloud and beyond

By the end of this step you have:

The next post in this theme—AI Code Generation — Promoting Storybook components into XM Cloud (BYOC)—picks up from here:

Later, the Flutter head post shows how the same requirements and content contracts can be reused in a Flutter-based head, keeping multi-channel experiences aligned without making the Storybook/Next.js library an afterthought.


Additional resources


Previous Post
AI-Powered Stack — From Blank Page to Signed SOW
Next Post
AI Code Generation — Promoting Storybook components into XM Cloud (BYOC)