# Widget Architecture

> For AI: this document describes the structure of a widget project created from the canonical template (`dynamic-framework/dynamic-react-vite-base-template`) at the release tag this MCP pins. Start every new widget with the `widgets-init-project` Prompt, which invokes the `widgets-scaffold` Tool. Do not recreate the template's files by hand.
>
> The template README is the detailed reference for everything below; this document summarizes it for generation.

---

## Project structure

Code is organized by domain: each domain is a feature with all its layers, and code that belongs to no domain lives in `src/shared/`.

```
my-widget/
├── src/
│   ├── app/                       # Startup
│   │   ├── main.tsx               # Mounts the widget; DContextProvider and portal registry
│   │   ├── App.tsx                # QueryProvider, ErrorBoundary, configuration gate, page
│   │   ├── mountTargets.ts        # Finds the containers to mount on
│   │   ├── modyo-preview-entry.ts # Entry used only by the Modyo CLI preview
│   │   └── providers/
│   │       └── QueryProvider.tsx  # TanStack Query client
│   ├── config/
│   │   ├── widgetConfig.ts        # Liquid variables, required variables, context config
│   │   ├── liquidConfig.ts        # Initializes the Liquid parser in development
│   │   ├── liquid.json            # Local values of Liquid variables (development)
│   │   └── i18nConfig.ts          # i18next setup through configureI18n
│   ├── pages/                     # Pages: compose features
│   ├── features/
│   │   └── entities/              # One folder per domain (reference feature)
│   │       ├── index.ts           # The only entry point of the feature
│   │       ├── api/               # Network, DTOs (*.dto.ts) and mocks (*.mock.ts)
│   │       ├── model/             # Domain types and pure functions
│   │       ├── service/           # Optional: orchestrates api/ and model/
│   │       ├── hooks/             # TanStack Query hooks over api/
│   │       └── ui/                # Components of the feature
│   ├── shared/                    # Cross-cutting code, no domain
│   │   ├── http/                  # HTTP client (client.ts)
│   │   ├── ui/                    # Loading, empty and error states; ErrorBoundary
│   │   ├── hooks/                 # Generic hooks
│   │   └── lib/                   # Utilities (liquidParser, errorHandler)
│   ├── locales/                   # Translations (es.json, en.json)
│   ├── styles/                    # The widget's own SCSS (base.scss)
│   └── vite.env.d.ts
├── tests/                         # Mirror of src/, plus boundaries/ and vite-plugins/
│   ├── app/  config/  features/  pages/  shared/
│   ├── boundaries/                # Architecture, dist contents, styles, manifest checks
│   ├── vite-plugins/
│   └── setup.ts
├── .vite/plugins/                 # Build plugins: escapeLiquidInStrings, lucideSubset
├── docs/recipes/                  # Optional modules: router, modyo-content
├── index.html                     # Development page (Modyo never renders it)
├── widget.manifest.json           # Describes the widget outside the code
├── vite.config.ts                 # Vite and Vitest configuration
├── eslint.config.js               # Linting and import graph
├── .stylelintrc                   # Style rules and class prefix
├── .modyo.example                 # Modyo CLI configuration template
└── package.json
```

Everything under `src/` is imported with the `@/` alias (for example `@/shared/ui`). Inside a feature, layers import each other by relative path.

Feature layers, adding and removing features: `modyo://docs/widgets/patterns-features`.

### What the template provides and what you write

| Provided by the template (adapt, do not recreate) | Written for each widget |
|---------------------------------------------------|-------------------------|
| `src/app/*`, `src/config/*`, `src/shared/*` | Features under `src/features/<name>/`, copied from `entities` |
| `vite.config.ts`, `eslint.config.js`, `.stylelintrc`, `tsconfig*.json` | Pages under `src/pages/` that use the features |
| `tests/boundaries/*`, `tests/setup.ts` | Tests under `tests/features/<name>/` and `tests/pages/` |
| `index.html`, `widget.manifest.json`, `.modyo.example` | Keys in `src/locales/es.json` and `src/locales/en.json` |
| | Required variables in `src/config/widgetConfig.ts`, if the widget needs more than the core ones |

---

## Import graph

```
app ──▶ pages ──▶ features/<x>/index.ts
 │        │              │
 └────────┴──────┬───────┘
                 ▼
          shared ◀──▶ config      (no imports of features, app or pages)

Inside a feature:  ui ──▶ hooks ──▶ (service) ──▶ api
                    └────────┴──────────┴─────────▶ model
```

ESLint (`eslint.config.js`) enforces these rules, and each error says what to import instead:

- `src/app/` and `src/pages/` use a feature only through its `index.ts` (`@/features/<name>`), never its internal folders. `src/pages/` does not import `src/app/`.
- `src/shared/` and `src/config/` do not import features, `src/app/` or `src/pages/`. Between them, `src/config/` uses `src/shared/lib/` and `src/shared/http/` reads `src/config/`.
- A feature does not reach into another feature's folders; it uses it through its `index.ts`. It never imports `src/app/` or `src/pages/`.
- Inside a feature: `ui/` uses `hooks/`; `hooks/` uses `api/` (or `service/`); `model/` is pure and receives only `import type` from other layers. `ui/` may import types from `api/` with `import type`.
- Inside a feature, layers import each other by direct relative path (`../hooks/useX`), never through the feature's own `index.ts`.
- The network (`src/shared/http/`) is used only from the `api/` layer of a feature. A feature's `index.ts` exposes `hooks/`, `model/` and `ui/`; from `api/` and `service/` it exposes types only.
- Mocks (`*.mock.ts`) are imported only by `api/`.
- Imports in `src/` are static. Dynamic `import()` is not allowed, with one exception: `src/app/modyo-preview-entry.ts`, which loads the development server for the Modyo CLI preview.
- Visible text in JSX comes from `t('...')`, with its keys in `src/locales/*.json`. Literal text in JSX is an error.
- Keys of `src/config/*.json` are sorted alphabetically (`npx eslint --fix` reorders them).

`tests/boundaries/architecture.test.ts` checks that each rule still applies to its layer's path and that every file in `src/` falls under one of them.

### No code splitting

The build produces a single IIFE `main.js` (`format: 'iife'` in `vite.config.ts`). With that format there are no chunks: `import()` or `React.lazy` would be inlined into the same `main.js`, so they do not reduce the download, and ESLint rejects `import()` in `src/`. The template does not use Module Federation. To keep `main.js` small, import only what the page uses and register only the portals the widget opens (see the template README, "Code Splitting").

---

## Mounting

`src/app/main.tsx` mounts one instance of the widget on each container found by `resolveMountTargets`:

```tsx
const WIDGET_NAME = 'widgetName';

function mount() {
  const targets = resolveMountTargets(document, WIDGET_NAME);

  if (targets.length === 0 && import.meta.env.DEV) {
    console.warn(`No se encontró contenedor para el widget "${WIDGET_NAME}".`);
  }

  targets.forEach((target) => {
    target.setAttribute('data-mounted', '');
    ReactDOM.createRoot(target).render(
      <StrictMode>
        <DContextProvider availablePortals={{}}>
          <App />
        </DContextProvider>
      </StrictMode>,
    );
  });
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', mount, { once: true });
} else {
  mount();
}
```

- **Containers:** every element with `data-widget="<WIDGET_NAME>"` and no `data-mounted` attribute gets its own instance. If there is none, the element with `id="<WIDGET_NAME>"` is used. The development container in `index.html`:

  ```html
  <div id="widgetName" data-widget="widgetName" class="widget-name"></div>
  ```

- **Timing:** if the document is still loading, mounting waits for `DOMContentLoaded`, so `main.js` works whether it is linked in the `<head>` or at the end of the `<body>`.
- **Renaming:** `widgets-scaffold` sets the mount name to the project name in the `WIDGET_NAME` constant of `src/app/main.tsx` and in the `id`/`data-widget` of the container in `index.html`.

### `DContextProvider` and portals

The template starts with `availablePortals={{}}`: no modal is registered. A feature's modal is registered there only when the widget opens it, because registering a modal bundles `DModal` and its animation library into `main.js`. Registration example: `modyo://docs/widgets/patterns-features` (Adding a feature).

`src/app/App.tsx` sets the site language and currency on the Dynamic UI context with `setContext(CONTEXT_CONFIG)`, wraps the page with `QueryProvider` and `ErrorBoundary`, and shows either the page or the list of missing variables.

---

## Required variables

`src/config/widgetConfig.ts` reads the site's Liquid variables with `liquidParser.parse(...)` and declares the ones the widget needs with `requireVariable`:

```ts
export const API_BASE_URL = requireVariable('vars.api-base-url', liquidParser.parse('{{vars.api-base-url}}'));
export const USE_MOCKS = liquidParser.parse('{{vars.use-mocks}}') === 'true';
```

The name goes without braces and the tag is written literally: Modyo replaces every `{{...}}` in the bundle. `tests/config/widgetConfig.test.ts` checks that each name matches its tag.

| Function | What it does |
|----------|--------------|
| `requireVariable(name, value)` | Registers the variable as required and returns its value |
| `isUnresolved(value)` | `true` if the value is empty or still contains the Liquid tag |
| `getMissingVariables()` | Names of the required variables that arrived unresolved; none when `USE_MOCKS` is `true` |

- **Core:** the only required variable is `vars.api-base-url`. Currency variables (`vars.currency-*`) are optional: if any arrives unresolved, the widget does not set the currency and Dynamic UI uses its default format.
- **Configuration gate:** when rendering, `App` calls `getMissingVariables()`. If a required variable is missing, the widget shows which ones instead of the page, rather than failing silently with requests to an empty URL.
- **Mocks:** with `vars.use-mocks` set to `"true"`, no variable is required and the widget works with mock data. This is the default in development, through `src/config/liquid.json`.

Read site variables once in `widgetConfig.ts` and import the constants from there; do not call `liquidParser` across the code. Liquid details: `modyo://docs/widgets/patterns-liquid-environment`.

---

## What the widget publishes

`npm run build` leaves exactly three files in `dist/`, which are the ones `npm run push` uploads:

| File | Content |
|------|---------|
| `main.js` | The widget code (IIFE): React, its dependencies and the Lucide icons it uses |
| `main.css` | Only the widget's own styles (`src/styles/base.scss`) |
| `index.html` | The development page. Modyo does not render it |

The Dynamic UI CSS, the site theme and the fonts are loaded by the site once for the whole page; the widget does not include them. `src/app/main.tsx` imports only `@/styles/base.scss`. `tests/boundaries/distContents.test.ts` builds the widget and fails if `dist/` contains any other file (for example, something in `public/` or an imported image emitted as a separate file).

---

## `widget.manifest.json`

Describes the widget outside the code. `tests/boundaries/widgetManifest.test.ts` keeps it consistent with `package.json`: `name` and `version` must match, and `dynamicUi` must equal the exact pin of `@dynamic-framework/ui-react`. Field rules: template README, "Manifiesto del widget".

---

## Naming

The template uses these conventions; follow them in new code:

| Element | Pattern | Template example |
|---------|---------|------------------|
| Feature folder | domain name in kebab-case | `src/features/entities/` |
| API functions file | `<domain>Api.ts` | `entityApi.ts` |
| DTO file | `<domain>.dto.ts` | `entity.dto.ts` |
| Mock file | `<domain>.mock.ts` | `entity.mock.ts` |
| Domain types file | `<domain>.ts` | `entity.ts` |
| Mapper file | `<domain>.mapper.ts` | `entity.mapper.ts` |
| Component file | `PascalCase.tsx` | `EntityListScreen.tsx` |
| Hook | `use<Purpose>` | `useEntities`, `useDebouncedValue` |
| Constants | `SCREAMING_SNAKE_CASE` | `API_BASE_URL`, `USE_MOCKS` |
| Test files | mirror of `src/` with `.test.ts(x)` | `tests/features/entities/api/entityApi.test.ts` |

---

## Checks before delivering

Run in the widget project:

```bash
npm run lint
npm test
npm run build
```

`npm run stylelint` checks the SCSS. The boundary tests under `tests/boundaries/` run with `npm test`.

---

## See also

- `modyo://docs/widgets/patterns-features` — feature layers, adding and removing features
- `modyo://docs/widgets/patterns-api-clients` — HTTP client and mocks
- `modyo://docs/widgets/patterns-tanstack-query` — provider, query keys and hooks
- `modyo://docs/widgets/patterns-hooks` — feature hooks, shared hooks, UI state
- `modyo://docs/widgets/patterns-liquid-environment` — Liquid variables in development and on the site
- Template README: https://github.com/dynamic-framework/dynamic-react-vite-base-template#readme
