# Features

A widget built from the canonical template organizes its code by domain. Each domain is a **feature**: a folder under `src/features/` that holds every layer of that domain. Code that belongs to no domain lives in `src/shared/`.

The template ships one reference feature, `src/features/entities/`, with a minimal example of each layer and one test per layer under `tests/features/entities/`. New features start as a copy of it.

For the full procedure and the reasoning behind each rule, read the template README sections "Arquitectura", "Agregar una feature" and "Quitar una feature".

---

## Structure of a feature

```
src/features/<name>/
├── index.ts        # The only entry point of the feature
├── api/            # Network calls, DTOs (*.dto.ts) and mocks (*.mock.ts)
├── model/          # Domain types and pure functions (mappers)
├── service/        # Optional: orchestrates api/ and model/
├── hooks/          # TanStack Query hooks over api/ (or service/)
└── ui/             # Components of the feature
```

The reference feature:

```
src/features/entities/
├── index.ts
├── api/
│   ├── entityApi.ts           # One function per endpoint, with AbortSignal and USE_MOCKS
│   ├── entity.dto.ts          # Shape of the API response
│   └── entity.mock.ts         # Mock data with the DTO shape
├── model/
│   ├── entity.ts              # Domain types
│   └── entity.mapper.ts       # DTO → domain, pure function
├── hooks/
│   └── useEntities.ts         # Query keys and TanStack Query hooks
└── ui/
    ├── EntityListScreen.tsx   # Block with loading, empty and error states
    └── EntityCreateModal.tsx  # Modal opened as a portal
```

### Layers

| Layer | Contains | May import |
|-------|----------|------------|
| `api/` | One function per endpoint. Receives an optional `AbortSignal`, returns domain types (the DTO never leaves `api/`). Decides between mock data and the network with `USE_MOCKS`. | `@/shared/http/client`, `@/config/widgetConfig`, `model/`, its own `*.dto.ts` and `*.mock.ts` |
| `model/` | Domain types and pure functions (mappers). No React, network, configuration or UI. | Other layers only through `import type` |
| `service/` | Optional. Combines several endpoints or applies rules that do not depend on React. Hooks call it instead of `api/`. | `api/`, `model/` |
| `hooks/` | Query keys and TanStack Query hooks. | `api/` (or `service/`), `model/` |
| `ui/` | Components. Get data from `hooks/` or through props. | `hooks/`, `model/`; types from `api/` with `import type` |

Create `service/` only when an operation combines several endpoints or applies rules of its own. If it would only forward calls to `api/`, leave it out.

---

## The single entry point: `index.ts`

Everything outside the feature (`src/app/`, `src/pages/`, other features) imports it through `@/features/<name>`, never through its internal folders. `index.ts` exposes `hooks/`, `model/` types and `ui/`; from `api/` and `service/` it exposes types only, and it never re-exports the HTTP client.

```ts
export { entityKeys, useCreateEntity, useEntities } from './hooks/useEntities';
export type { CreateEntityData, Entity, EntityFilters } from './model/entity';
export {
  EntityCreateModal,
  type EntityCreatePayload,
  type EntityPortals,
} from './ui/EntityCreateModal';
export { default as EntityListScreen } from './ui/EntityListScreen';
```

Inside the feature, layers import each other with direct relative paths (`../hooks/useEntities`), never through the feature's own `index.ts` (`..`, `../index` or `@/features/<own>`), and without intermediate `..` segments.

---

## 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
```

- `src/app/` and `src/pages/` use a feature only through `@/features/<name>`. `src/pages/` does not import `src/app/`.
- A feature does not reach into another feature's folders; it uses it through its `index.ts`. A feature never imports `src/app/` or `src/pages/`.
- `src/shared/` and `src/config/` never import features, `src/app/` or `src/pages/`.
- The network (`src/shared/http/`) is used only from the `api/` layer of a feature.
- Mocks (`*.mock.ts`) are imported only by `api/`.

The template's ESLint configuration (`eslint.config.js`) enforces this graph, and each error message says what to import instead. See `modyo://docs/widgets/reference-architecture` for the rest of the rules ESLint applies.

---

## Data flow through the layers

`api/` returns domain types. The DTO describes the API response and is translated by the mapper in `model/`:

```ts
// api/entity.dto.ts
export interface ApiEntity {
  id: string;
  name: string;
  created_at: string;
  updated_at?: string;
}
```

```ts
// model/entity.ts
export interface Entity {
  id: string;
  name: string;
  createdAt: string;
  updatedAt?: string;
}

export interface CreateEntityData {
  name: string;
}

export interface EntityFilters {
  search?: string;
}
```

```ts
// model/entity.mapper.ts
import type { ApiEntity } from '../api/entity.dto';

import type { Entity } from './entity';

export function toEntity(dto: ApiEntity): Entity {
  return {
    id: dto.id,
    name: dto.name,
    createdAt: dto.created_at,
    updatedAt: dto.updated_at,
  };
}
```

If the API response already has the domain shape, keep the mapper anyway: it is the single place that changes when the API changes.

How `api/` calls the network and switches to mocks: `modyo://docs/widgets/patterns-api-clients`.
How `hooks/` wraps `api/` with TanStack Query: `modyo://docs/widgets/patterns-tanstack-query`.

---

## Adding a feature

1. **Copy** the reference feature and its tests, using the domain name in kebab-case:

   ```bash
   cp -R src/features/entities src/features/<name>
   cp -R tests/features/entities tests/features/<name>
   ```

2. **Rename** files and identifiers in both copies, preserving case: `Entities` → `<Domains>`, `Entity` → `<Domain>`, `entities` → `<domains>`, `entity` → `<domain>`. This covers `entityApi.ts`, `entity.dto.ts`, `useEntities`, `entityKeys` (its first key, `['entities']`, must be unique in the widget) and the portal name (`'entity-create'`). In the tests, `@/features/entities/...` paths become `@/features/<name>/...`.
3. **Adapt the domain:** the endpoint in `api/`, the DTO and domain type fields, and the mapper that joins them.
4. **Texts:** copy the `entities` block of `src/locales/es.json` and `src/locales/en.json` under the new name; components use `t('<domains>.list.title')` and similar keys.
5. **Use the feature** from `src/pages/` with `import { ... } from '@/features/<name>'`.
6. **Register the modal only if the widget opens it.** The template starts with an empty `availablePortals` in the `DContextProvider` of `src/app/main.tsx`. With the reference feature, registration looks like this:

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

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

   Registering a modal bundles `DModal` and its animation library into `main.js` even if the page never opens it. Calling `openPortal` with a name that is not registered throws an error.
7. Run `npm run lint`, `npm test` and `npm run build`.

### Trimming a small domain

- **Read-only:** remove `createEntity` from `api/`, `useCreateEntity` from `hooks/`, `CreateEntityData` from `model/`, `EntityCreateModal.tsx` (and its registration in `main.tsx`, if any), the create button in `EntityListScreen.tsx` and the creation tests.
- **No filters:** remove `EntityFilters`, the `filters` parameter of `api/` and `hooks/`, and the search input in `EntityListScreen.tsx`.
- **No screen of its own:** if another feature or a page renders the data, delete `ui/` and let `index.ts` export only hooks and types.

---

## Removing a feature

1. Delete `src/features/<name>/` and `tests/features/<name>/`.
2. Remove its imports from `src/pages/` (and from `src/app/main.tsx` if it registered portals).
3. Remove its keys from `src/locales/*.json`.
4. Run `npm run lint` and `npm test`: any import left behind points to a path that no longer exists.

---

## See also

- `modyo://docs/widgets/reference-architecture` — full project structure and the rules ESLint applies
- `modyo://docs/widgets/patterns-api-clients` — HTTP client and mocks in `api/`
- `modyo://docs/widgets/patterns-tanstack-query` — query keys and hooks
- `modyo://docs/widgets/patterns-hooks` — feature hooks, shared hooks and local UI state
