# Dynamic Context — Widget Generation Guide

> ⚠️ **First action for any widget work: invoke the `widgets-init-project` MCP Prompt.**
> It instructs the agent to invoke the `widgets-scaffold` Tool, which clones the
> canonical template at the version this MCP is validated against (the template,
> Dynamic UI and validator versions are fixed together; values are deliberately
> not duplicated here).
> Generating the project from memory diverges from that set of versions. The
> clone is the only path to reproducible builds.
>
> For existing widget projects, check `package.json` against the template's
> pinned versions before suggesting changes: if `@dynamic-framework/ui-react`
> differs from the version the template pins, the project is on a different
> stack and patterns from this knowledge base may not apply.

> **For AI:** This is the single entry point. Read this file first, then follow links as needed.
> **Do not read all documentation at once.** Load selectively based on the widget you're building.

---

## Stack

| Dependency | Purpose |
|------------|---------|
| React | UI |
| TypeScript | Type safety |
| `@dynamic-framework/ui-react` (Dynamic UI) | Component library |
| `@tanstack/react-query` | Remote data and cache |
| Axios | HTTP client |
| i18next / react-i18next | Internationalization |
| liquidjs | Liquid variables in development |
| Vite | Build and development server |
| Vitest | Tests |

**Versions are pinned in the template's `package.json`, and and the Dynamic UI and template versions are fixed by the MCP. Do not change them.** The template has no global UI store: UI state lives in components (`modyo://docs/widgets/patterns-hooks`).

---

## Modyo Platform

This module covers generating the **widget project** (React + Dynamic UI). For Modyo platform context (widget UUIDs vs IDs, CSP nonce, widget lifecycle in sites, editing published widgets):

| Document | When to read |
|----------|--------------|
| `modyo://docs/widgets/platform-development` | Widget development practices on Modyo sites |
| `modyo://docs/widgets/platform-workflows` | Creating and assigning widgets |
| `modyo://docs/widgets/platform-editing-published` | Safely editing published widgets |

---

## Critical Rules (Read Before Coding)

These rules prevent the most common errors. Full reference → `modyo://docs/widgets/reference-quick-reference`

### Props and handlers

| Rule | Template example |
|------|------------------|
| Button text goes in the `text` prop | `text={t('common.save')}` |
| Inputs pass the **value** to `onChange`, not an event | `onChange={setSearchQuery}` (see below) |
| Semantic color goes in the `color` prop | `<DAlert color="danger">` |
| Icons are Lucide names in PascalCase | `iconStart="Search"`, `icon="Book"` |
| A portal opens with its name and a payload object | `openPortal('entity-create', { onCreate: createEntity })` |

```tsx
  const [searchQuery, setSearchQuery] = useState('');
```

```tsx
          <DInput
            iconStart="Search"
            placeholder={t('common.searchPlaceholder')}
            value={searchQuery}
            onChange={setSearchQuery}
          />
```

### Visible text

All visible text comes from `t('...')`, with keys in `src/locales/es.json` and `src/locales/en.json`. ESLint rejects literal text in JSX.

```tsx
      <h1 className="fw-semibold text-center">{t('title')}</h1>
```

### Imports

- Outside a feature, import it only through `@/features/<name>`.
- The HTTP client is used only from a feature's `api/` layer.
- No dynamic `import()` or `React.lazy` in `src/`: the build is a single `main.js`.

Full import graph → `modyo://docs/widgets/reference-architecture`

### Modal registration

The template mounts `DContextProvider` in `src/app/main.tsx` with `availablePortals={{}}`. Register a modal there only if the widget opens it:

```tsx
import { EntityCreateModal, type EntityPortals } from '@/features/entities';

<DContextProvider<EntityPortals> availablePortals={{ 'entity-create': EntityCreateModal }}>
```

Portals render outside the `QueryProvider`: pass actions in the `openPortal` payload instead of calling TanStack Query hooks inside the modal (`modyo://docs/widgets/patterns-tanstack-query`).

---

## Base Template (MANDATORY First Step)

The canonical template lives at `https://github.com/dynamic-framework/dynamic-react-vite-base-template`. To start a project from the MCP, the operator invokes the `widgets-init-project` Prompt, whose only effect is that the agent runs the **`widgets-scaffold`** Tool.

**Before ANY code generation**, `widgets-scaffold` initializes the project deterministically:

1. Clones the template at its pinned release tag (`git clone --depth 1 --branch <tag>`) into `./<name>/` under the given `targetDir`. Never from the default branch.
2. Removes `.git/` (detaches the template history).
3. Renames the widget to the project name: `name` and `version` (`0.1.0`) in `package.json`, `widget.manifest.json` and the root of `package-lock.json`; the mount name (`WIDGET_NAME` in `src/app/main.tsx`, `id`/`data-widget` in `index.html`, the `data-widget` in `tests/app/main.test.ts`); the CSS class prefix (`index.html`, `src/styles/base.scss`, `.stylelintrc`); and `MODYO_WIDGET_NAME` in `.modyo.example` and `.env.example`. If an expected literal is missing (the template changed), it fails before the initial commit and leaves the directory in place.
4. Re-initializes git (`git init`) and creates the initial commit `chore: scaffold from dynamic-react-vite-base-template <tag>` with the operator's git identity (without `user.name`/`user.email`, the repo is left initialized without a commit — `gitInit: "initialized_no_commit"`). The commit happens before `npm ci`, capturing the renamed scaffold (`node_modules/` is excluded by the template's `.gitignore`).
5. Runs `npm ci` (if it fails, the project remains usable with a manual `npm ci`).

The Tool fails closed — touching nothing — if the target directory already exists or if the target is anywhere inside an existing widget project (its root or any subdirectory: the guard walks up the ancestors looking for `@dynamic-framework/ui-react` in the dependencies). It also fails closed if any `package.json` in that chain exists but cannot be read or parsed — it could belong to the enclosing widget. Never nest widgets or reinterpret the name as a feature of an existing widget.

The only post-clone step left is the Modyo CLI configuration: the operator copies `.modyo.example` to `.modyo` and fills in the account, token and site (template README, Quick start). The agent never writes or reads `.modyo`.

**Two-step flow:** (1) scaffold through the Tool; (2) the operator provides the widget's functional description in the next turn. Do not generate widget code before receiving it.

---

## Architecture

Every widget follows the template structure: code organized by domain, one folder per feature. Details → `modyo://docs/widgets/reference-architecture`

```
my-widget/
├── src/
│   ├── app/            # main.tsx, App.tsx, mountTargets.ts, providers/, modyo-preview-entry.ts
│   ├── config/         # widgetConfig.ts, liquidConfig.ts, liquid.json, i18nConfig.ts
│   ├── pages/          # Pages: compose features
│   ├── features/
│   │   └── <name>/     # index.ts, api/, model/, service/ (optional), hooks/, ui/
│   ├── shared/         # http/, ui/, hooks/, lib/
│   ├── locales/        # es.json, en.json
│   └── styles/         # base.scss
├── tests/              # Mirror of src/, plus boundaries/ and vite-plugins/
├── docs/recipes/       # Optional modules
├── index.html
└── widget.manifest.json
```

The template's reference feature is `src/features/entities/`. New features start as a copy of it → `modyo://docs/widgets/patterns-features`

---

## Generation Workflow

| Step | Action | Reference |
|------|--------|-----------|
| 1 | Scaffold through the `widgets-scaffold` Tool | Base Template section above (entry point: Prompt `widgets-init-project`) |
| 2 | Create one feature per domain by copying `src/features/entities` | `modyo://docs/widgets/patterns-features` |
| 3 | Adapt `api/` (endpoints, DTO, mocks) and `model/` (types, mapper) | `modyo://docs/widgets/patterns-api-clients` |
| 4 | Adapt query keys and hooks in `hooks/` | `modyo://docs/widgets/patterns-tanstack-query` |
| 5 | Build the feature's `ui/` and compose it from `src/pages/` | `modyo://docs/widgets/components-_index` |
| 6 | Add translations (es.json + en.json) | `modyo://docs/widgets/patterns-i18n` |
| 7 | Declare required site variables in `widgetConfig.ts` | `modyo://docs/widgets/patterns-liquid-environment` |
| 8 | Run `npm run lint`, `npm test`, `npm run build` and the validator | See Validator section below |

---

## Component Reference

**Start here:** `modyo://docs/widgets/components-_index` — full catalog with props and examples.

### By Category

| Category | File | Key Components |
|----------|------|----------------|
| Inputs | `modyo://docs/widgets/components-inputs` | DInput, DInputCurrency, DInputSwitch ⚠️ |
| Inputs (Advanced) | `modyo://docs/widgets/components-inputs-advanced` | DInputMask, DInputCounter, DBoxFile |
| Selects | `modyo://docs/widgets/components-selects` | DSelect, DInputSelect ⚠️ |
| Buttons | `modyo://docs/widgets/components-buttons` | DButton, DButtonGroup |
| Feedback | `modyo://docs/widgets/components-feedback` | DAlert, DBadge, DToast, DSpinner |
| Layout | `modyo://docs/widgets/components-layout` | DCard, DBox, DCollapse |
| Navigation | `modyo://docs/widgets/components-navigation` | DTabs, DStepper, DPaginator |
| Modals and Offcanvas | `modyo://docs/widgets/components-overlay` | DModal, DOffcanvas (portals) ⚠️ |
| Overlay (Widgets) | `modyo://docs/widgets/components-overlay-widgets` | DPopover, DTooltip |
| Icons | `modyo://docs/widgets/components-icons` | DIcon (Lucide PascalCase) ⚠️ |
| Other | `modyo://docs/widgets/components-other` | DAvatar, DListGroup, DCurrencyText |
| Hooks | `modyo://docs/widgets/components-hooks` | useDPortalContext, useFormatCurrency |

**⚠️ = Critical patterns that cause errors if misunderstood. Read the marked sections before using.**

### Selective Loading by Widget Type

| Widget Type | Load These Component Files |
|-------------|---------------------------|
| **Form** | inputs.md, selects.md, buttons.md, date-time.md |
| **List/Dashboard** | layout.md, feedback.md, icons.md, other.md |
| **Wizard** | navigation.md, inputs.md, selects.md, buttons.md |
| **Modal/Dialog** | hooks.md, overlay.md, buttons.md |

---

## Catalog Discovery

The MCP exposes the Dynamic UI component catalog and pattern stories as **versioned MCP Resources**, sourced from the official Storybook manifests of the Dynamic UI version the MCP is validated against. They complement the curated documentation above with live data — story snippet code, prop types, MDX content.

| URI | Shape | Use when |
|-----|-------|----------|
| `modyo://widgets/catalog/components` | Lightweight list (id, name, key, description, storyCount) | Discovering what's available |
| `modyo://widgets/catalog/components/{componentName}` | Full detail (stories with snippet code, props with TS types, JSDoc) | Need exact API surface or a working snippet |
| `modyo://widgets/catalog/patterns` | Lightweight pattern list (id, name, title) | Discovering composed UI examples |
| `modyo://widgets/catalog/patterns/{patternId}` | Full MDX content of a pattern story | Adapting an official pattern to a new widget |

Full guide — Tools vs Resources, when to use each, output shapes, error handling: `modyo://docs/widgets/_meta-catalog-discovery`.

### Pattern Discovery (required)

> ⚠️ **Before generating widget UI**, you must consult `modyo://widgets/catalog/patterns` to identify official patterns matching the request domain. If a pattern matches, read its full content from `modyo://widgets/catalog/patterns/{patternId}` and use it as the structural and visual basis. Adapting to the request's specifics is expected; ignoring an applicable pattern produces visually generic output that fails to reflect Dynamic Framework conventions.
>
> If no pattern matches, state this explicitly and proceed using only components from `modyo://widgets/catalog/components`.

---

## Patterns Reference

| Pattern | File | Description |
|---------|------|-------------|
| Features | `modyo://docs/widgets/patterns-features` | Feature layers, single entry point, import graph, adding and removing a feature |
| API Clients | `modyo://docs/widgets/patterns-api-clients` | Shared HTTP client, `api/` functions, mocks with `USE_MOCKS` |
| TanStack Query | `modyo://docs/widgets/patterns-tanstack-query` | Query keys, queries and mutations of a feature |
| Hooks | `modyo://docs/widgets/patterns-hooks` | Feature hooks, shared hooks, local UI state |
| i18n | `modyo://docs/widgets/patterns-i18n` | Internationalization with Liquid template support |
| Liquid Environment | `modyo://docs/widgets/patterns-liquid-environment` | Mock/API toggle, environment config |
| Data States | `modyo://docs/widgets/patterns-data-states` | Loading/Error/Empty/Success handling |
| Testing | `modyo://docs/widgets/patterns-testing` | Vitest setup, hook testing |
| Utilities | `modyo://docs/widgets/patterns-utilities` | errorHandler, liquidParser, formatters |

---

## Reference Documents

| Document | File | When to Read |
|----------|------|--------------|
| Quick Reference | `modyo://docs/widgets/reference-quick-reference` | Before coding (color, variant, size, boolean props, `onChange`) |
| Architecture | `modyo://docs/widgets/reference-architecture` | Project structure, import graph, mounting, required variables, build output |
| UI Patterns | `modyo://docs/widgets/reference-ui-patterns` | Forms, lists, master-detail, summary cards, modals |
| Validator Rules | `modyo://docs/widgets/reference-validator-rules` | When `widgets-validate` reports errors |
| Troubleshooting | `modyo://docs/widgets/reference-troubleshooting` | Build/runtime errors |
| Theming | `modyo://docs/widgets/reference-theming` | Client branding customization |
| Accessibility | `modyo://docs/widgets/reference-accessibility` | A11y guidelines |
| Generation Workflow | `modyo://docs/widgets/reference-generation-workflow` | Detailed step-by-step process |
| Quick Reference | `modyo://docs/widgets/reference-quick-reference` | Icon lookup, prop cheat sheet |

---

## Validator

Run after generating a widget. The validator ships as the NPM package `@modyo/widget-validator`; you can invoke it three ways:

**1. MCP tool (preferred when the Modyo MCP server is active):**

| Tool | Input | Notes |
|------|-------|-------|
| `widgets-validate` | `projectPath` (filesystem path) **or** `projectFiles` (array of `{path, content}`) | Exactly one of the two. Returns a `ValidationReport` (`score`, `passing`, `errors`, `warnings`). |

**2. CLI via `npx` (no MCP dependency):**

```bash
npx @modyo/widget-validator@<version> /path/to/my-widget
```

Use the `version` field of a `widgets-validate` report; without a version, `npx` runs the latest published release. The CLI skips the `stack-alignment` check.

**3. Automated on every `Write`/`Edit` (Claude Code only):** see `modyo://docs/widgets/_meta-integration-claude-code` for the `PostToolUse` hook snippet.

**The widget passes when `passing` is `true`: no errors.** Warnings do not block, and the score is not a criterion (`stack-alignment` can set `passing: false` with a score of 100). Fix errors, re-run. Rule details → `modyo://docs/widgets/reference-validator-rules`. Known quirks → `modyo://docs/widgets/_meta-validator-quirks`.

---

## Deploy (outside the MCP)

The generation flow ends at validation plus a served smoke test (`npm run dev`). Deployment is NOT an MCP operation: it runs through CI from the widget's own git repository — the scaffold initializes a git repository (and creates an initial commit when git has a user identity configured) so the project is ready for that path. A manual push is the developer's explicit `modyo-cli push` in their own shell, never the agent.

Credentials (`MODYO_ACCOUNT_URL`, `MODYO_TOKEN`, `MODYO_SITE_HOST`) live in the repo's CI secrets or the developer's local `.modyo` (or `.env`) file — the MCP process never reads them, and the token never enters the chat.

Full guide: `modyo://docs/widgets/_meta-publishing` — deploy path (CI from the repo), manual `modyo-cli push`, credentials policy.

---

## Quality Checklist

Before submitting a widget:

- [ ] `npm run lint`, `npm test` and `npm run build` pass
- [ ] `widgets-validate` reports `passing: true` (no errors)
- [ ] `npm run dev` runs without errors, with mock data (`use-mocks` in `src/config/liquid.json`)
- [ ] All features work (no placeholders)
- [ ] Every visible text comes from `t('...')`, with keys in es.json and en.json
- [ ] Only the modals the widget opens are registered in `availablePortals`
- [ ] Every site variable the widget needs is declared with `requireVariable` in `widgetConfig.ts`

---

## External Links

- **Storybook:** https://react.dynamicframework.dev/
- **Lucide Icons:** https://lucide.dev/icons/
- **Dynamic UI Repo:** https://github.com/dynamic-framework/dynamic-ui
- **Base Template Repo:** https://github.com/dynamic-framework/dynamic-react-vite-base-template

