Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .claude/skills/editor-conventions/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ description: "Change the email template editor UI, AI assistant or API client. U
# Editor conventions

- Editor UI lives in `src/editor/Main`, not `src/pages` (Next.js would treat `pages` as routes).
- The editor edits one template: `Main` gets `templateId` from `app/templates/[id]/page.tsx` and passes it to every component that calls the API. The list pages live in `src/templates` and `src/sent`; they reuse `notifyError` and `Preview/EmailFrame` from the editor.
- Interactive components need `"use client"`.
- All HTTP calls go through `src/api/main.ts`. Do not call axios from UI files.
- Types belong in `src/api/main.types.ts` and `src/types`. API types are generated from the backend contract: `npm run api:sync`, never edited by hand in `openapi.types.ts`.
Expand Down
6 changes: 3 additions & 3 deletions .claude/skills/run-app/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ The editor needs two processes: this Next.js app on **:3000** and the backend AP
## 1. Reuse what is already running

- Frontend: `next dev` writes its PID, port and URL to `.next/dev/lock`. If it exists and the process is alive, use that server. Starting a second `next dev` only prints the running one's URL.
- Backend: `curl -s localhost:9000/tree` answers JSON when it is up.
- Backend: `curl -s localhost:9000/templates` answers JSON when it is up.

## 2. Start what is missing (in the background)

Expand All @@ -22,12 +22,12 @@ cd ../email-template-editor-nodejs && npm install && npm run dev # :9000
npm run dev # :3000
```

No backend checkout? The UI still loads (tree and elements show errors); for UI-only checks Playwright e2e specs mock the API with `page.route` instead.
No backend checkout? The UI still loads (the templates list and the editor show errors); for UI-only checks Playwright e2e specs mock the API with `page.route` instead.

## 3. Check the change

- **Framework errors** (Next DevTools MCP, `.mcp.json`): `nextjs_index` to find the server, then `nextjs_call` → `get_errors`, `get_logs`, `compile_route`. Faster than `npm run build` while editing.
- **The page itself** (Playwright MCP): open `http://localhost:3000`, take a snapshot or screenshot, click through the flow you changed.
- **The page itself** (Playwright MCP): open `http://localhost:3000` (redirects to `/templates`; the editor is `/templates/<id>`), take a snapshot or screenshot, click through the flow you changed.
- The browser console is forwarded to the `next dev` terminal output.

## 4. Before finishing
Expand Down
7 changes: 6 additions & 1 deletion .claude/skills/testing/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ description: "Write and fix tests for the email template editor. Use when adding

```ts
// Mock every function the component under test (and its children) imports.
// Tree, element, generate and send functions take the template id first: getTree("t1").
vi.mock("@/api/main", () => ({
getTemplate: vi.fn(() =>
Promise.resolve({ id: "t1", name: "Weekly digest", createdAt: "", updatedAt: "" }),
),
getTree: vi.fn(() => Promise.resolve([])),
saveTree: vi.fn(() => Promise.resolve({})),
generate: vi.fn(() => Promise.resolve("")),
Expand All @@ -41,7 +45,8 @@ Run: `npm test`. Coverage: `npm run test:coverage` (HTML report in `coverage/`).
## E2E (Playwright)

- Config: `playwright.config.ts`. Specs: `e2e/`.
- Intercept `/tree` and `/elements` with `page.route` so tests do not need the backend.
- Intercept the backend with `page.route` so tests do not need it. The editor is at `/templates/t1`: mock `GET /templates/t1` with `mockTemplate(page)` from `e2e/backend.ts`, and `**/templates/t1/tree` / `**/templates/t1/elements`. Give backend URLs in full (`API_URL` from `e2e/backend.ts`) when the path could also match a page, e.g. `/templates` or `/templates/t1`.
- Components that use `useRouter()` (`TemplatesPage`, `SendEmailModal`, and so `Main`) need `vi.mock("next/navigation", …)` in unit tests.
- Mock AI providers with `page.route` too (see `e2e/ai-assistant.spec.ts`), and check the key never reaches our backend.
- `e2e/csp.spec.ts` guards the Content-Security-Policy; update it when adding an origin.
- Run: `npm run test:e2e`
Expand Down
31 changes: 21 additions & 10 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ This is a **visual email template editor**. Users build a tree of email elements
```
app/ # Next.js App Router entry
layout.tsx # Root layout (Ant Design reset + global CSS)
page.tsx # Home page → renders <Main />
page.tsx # Home page → redirects to /templates
templates/page.tsx # /templates → <TemplatesPage /> (list of templates)
templates/[id]/page.tsx # /templates/[id] → <Main templateId={id} /> (the editor)
sent/page.tsx # /sent → <SentEmailsPage /> (log of sent emails)
proxy.ts # Per-request nonce Content-Security-Policy + color-scheme client hint (Next 16 "proxy", formerly middleware)


Expand All @@ -42,18 +45,22 @@ src/
errors.ts # errorMessage(): readable message from a failed API call
ai/ # AI assistant (no React): providers, tools, agent loop, keyStore
editor/Main/ # Editor UI (client components)
Main.tsx # Root editor screen
Main.tsx # Editor screen for one template (templateId prop): header, toolbar, workspace
Elements/ # Element list + add/edit modals
TemplateTree/ # Tree view + context-menu actions
AddRootElementForm/ # Form to create the root node
Chat/ # AI assistant panel (left column) + settings (lazy-loaded)
Preview/ # Live email preview (sandboxed iframe) + client-side renderer
Preview/ # Live email preview + client-side renderer; EmailFrame (sandboxed iframe, reused by src/sent)
SendEmailModal/ # "Send email" dialog: recipients + subject → sendEmail()
templates/ # Templates list page: create, rename, delete, open in the editor
sent/ # Sent emails log page with a drawer that shows the sent HTML
security/ # Content-Security-Policy builder
shell/ # App frame: sidebar navigation, header with the System/Light/Dark theme menu (cookie + OS hint, read in app/layout.tsx)
types/ # Shared types (e.g. TemplateTree)
index.css # Global styles
setupTests.ts # Vitest setup (jest-dom, matchMedia/ResizeObserver polyfills)
e2e/ # Playwright specs (backend and AI providers are mocked with page.route)
backend.ts # Backend origin, the sample template t1 and mockTemplate(); mock backend URLs in full
public/ # favicon.ico, robots.txt

.claude/skills/ # Claude skills: best practices, testing, deployment, editor conventions, run-app
Expand All @@ -78,10 +85,11 @@ tsconfig.json # Paths: @/* → ./src/*

- Anything that uses hooks, Ant Design, `window`, or browser APIs must be a **client component**.
- Add `"use client";` at the top of the file.
- Currently marked client: `Main.tsx`, `Elements.tsx`, `TemplateTree.tsx`, `Preview.tsx`, `Chat/ChatPanel.tsx`, `Chat/AiSettingsModal.tsx`, `src/shell/AppShell.tsx`.
- Currently marked client: `Main.tsx`, `Elements.tsx`, `TemplateTree.tsx`, `Preview.tsx`, `Preview/EmailFrame.tsx`, `SendEmailModal/SendEmailModal.tsx`, `Chat/ChatPanel.tsx`, `Chat/AiSettingsModal.tsx`, `src/templates/TemplatesPage.tsx`, `src/templates/TemplateNameModal.tsx`, `src/sent/SentEmailsPage.tsx`, `src/shell/AppShell.tsx`.
- Routes (`app/`) stay server components that render one client page component. Dynamic `params` are a Promise in Next 16: `const { id } = await params`.
- Theme: colors come from antd tokens (`var(--ant-…)` in CSS, `theme.useToken()` in TSX) so they follow the dark theme; do not hard-code light colors.
- Pages are rendered per request (`export const dynamic = "force-dynamic"` in `app/layout.tsx`) because the CSP nonce changes on every request. Do not switch to static export (`output: "export"`).
- New interactive UI under `src/editor/Main/**` should also be client components.
- New interactive UI under `src/editor/Main/**`, `src/templates/` and `src/sent/` should also be client components.

### API client (`src/api/main.ts`)

Expand Down Expand Up @@ -153,7 +161,7 @@ tsconfig.json # Paths: @/* → ./src/*

1. Get the backend's current contract and regenerate the types: `npm run api:sync` (`OPENAPI_URL=http://localhost:9000/openapi.json npm run api:sync` for a local backend or an unmerged backend branch). Commit both `src/api/openapi.json` and `src/api/openapi.types.ts`; a test fails if they disagree.
2. Update the function in `src/api/main.ts`; add or adjust an alias in `src/api/main.types.ts` if a new schema is needed.
3. Run `npm run typecheck`: callers that no longer match the contract fail here. Fix them in `Main.tsx`, `Elements.tsx`, `TemplateTree.tsx` or `src/ai/tools.ts`.
3. Run `npm run typecheck`: callers that no longer match the contract fail here. Fix them in `Main.tsx`, `Elements.tsx`, `TemplateTree.tsx`, `SendEmailModal.tsx`, `src/templates/`, `src/sent/` or `src/ai/tools.ts`.
4. Keep the mock in tests in sync.

### Run locally
Expand Down Expand Up @@ -204,10 +212,13 @@ docker run -p 3000:3000 email-template-editor
## Related

- Backend is a separate service (not in this repo): [email-template-editor-nodejs](https://github.com/LLazyEmail/email-template-editor-nodejs). Frontend expects its REST API:
- Tree: `GET /tree`, `PUT /tree`, `POST /tree/nodes`, `PATCH /tree/nodes/:key`, `DELETE /tree/nodes/:key`
- Elements: `GET /elements`, `POST /elements`, `PATCH /elements/:key`, `DELETE /elements/:key`
- `POST /generate` → `{ url }`
- Keys in paths are URL-encoded. Errors are `{ error: { code, message, details?, requestId } }`.
- Templates: `GET /templates`, `POST /templates` `{ name }`, `GET /templates/:templateId`, `PATCH /templates/:templateId` `{ name }`, `DELETE /templates/:templateId`
- Tree (per template): `GET /templates/:templateId/tree`, `PUT …/tree`, `POST …/tree/nodes`, `PATCH …/tree/nodes/:key`, `DELETE …/tree/nodes/:key`
- Elements (per template): `GET /templates/:templateId/elements`, `POST …/elements`, `PATCH …/elements/:key`, `DELETE …/elements/:key`
- `POST /templates/:templateId/generate` → `{ url }`
- `POST /templates/:templateId/send` `{ to, subject }` → the log entry. Delivery is not configured: the email is only logged (`status: "logged"`); an empty tree is `422 TREE_EMPTY`.
- Sent emails: `GET /sent-emails` (newest first, no HTML), `GET /sent-emails/:id` (with the HTML snapshot)
- Template ids and keys in paths are URL-encoded. An unknown template is `404 NOT_FOUND`. Errors are `{ error: { code, message, details?, requestId } }`.
- **Contract:** the backend's [`openapi.json`](https://github.com/LLazyEmail/email-template-editor-nodejs/blob/main/openapi.json) (OpenAPI 3.1, also served at `GET http://localhost:9000/openapi.json`) is the source of truth. The frontend keeps a copy in `src/api/openapi.json` and generates its types from it (see "Change an API call").
- Product description, charts, and screenshots: `README.md`.

Expand Down
44 changes: 34 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,39 +56,56 @@ The tree, the Elements library and the modals follow the theme too.

### Regenerating the screenshots

Start the backend on `:9000` with the sample `db.json` and run `npm run dev`. Then capture the editor at 1440×900 (device scale 2) with the `theme` cookie set to `light`: the overview, the preview scrolled to the first recipe row, both panels expanded (capture the panels only), and the **edit** modal of `{{recipeCard}}`. Repeat with `theme=dark` for the theme menu open, the panels and the edit modal (`-dark` suffix). Hide the Next.js dev badge before you capture.
Start the backend on `:9000` with the sample `db.json` and run `npm run dev`. Then open the sample template from `/templates` and capture the editor at 1440×900 (device scale 2) with the `theme` cookie set to `light`: the overview, the preview scrolled to the first recipe row, both panels expanded (capture the panels only), and the **edit** modal of `{{recipeCard}}`. Repeat with `theme=dark` for the theme menu open, the panels and the edit modal (`-dark` suffix). Hide the Next.js dev badge before you capture.

## How it works

The app has three pages, reachable from the sidebar:

| Page | What it does |
| ----------------- | ------------------------------------------------------------------------------------------------------- |
| `/templates` | All templates: create, rename, delete, or open one in the editor. `/` redirects here. |
| `/templates/[id]` | The editor for one template: preview, AI assistant, tree and elements, **Generate** and **Send email**. |
| `/sent` | The log of sent emails, newest first, filterable by template; a row opens the email as it was sent. |

Each template has its own tree and its own elements library. **Send email** does not deliver anything yet: the backend renders the template and records it (recipients, subject, HTML) in the sent emails log.

```mermaid
flowchart LR
User[Author] --> UI[Editor UI]
User[Author] --> List[Templates list]
List -->|open| UI[Editor UI]
UI --> Tree[Template tree]
UI --> Lib[Elements library]
UI -->|Generate| API[Backend API]
UI -->|Generate / Send| API[Backend API]
Tree -->|load / save / update| API
Lib -->|CRUD| API
API --> HTML[Generated HTML]
API --> Log[Sent emails log]
```

```mermaid
sequenceDiagram
participant U as User
participant UI as Editor
participant API as Backend
U->>UI: Open app
UI->>API: GET /tree
U->>UI: Open a template from /templates
UI->>API: GET /templates/:id/tree
API-->>UI: Current tree
U->>UI: Add / edit / delete nodes
UI->>API: save / update / add / delete
U->>UI: Generate
UI->>API: POST /generate
UI->>API: POST /templates/:id/generate
API-->>UI: { url } of generated HTML
UI-->>U: Open generated template
U->>UI: Send email (to, subject)
UI->>API: POST /templates/:id/send
API-->>UI: Log entry (status "logged")
```

## Features

- Several templates, each with its own tree and elements, listed on one page
- Send a template to a list of addresses; sent emails are kept in a log you can browse (delivery itself is not connected yet)
- Add a root element and grow a template tree
- Context menu on each node: add, edit, delete
- Live preview of the email next to the AI assistant
Expand All @@ -105,13 +122,17 @@ sequenceDiagram
```mermaid
flowchart TB
subgraph Frontend[This repo]
Page[app/page.tsx]
Page["app/templates/[id]/page.tsx"]
List[src/templates]
Sent[src/sent]
Main[Main.tsx]
Tree[TemplateTree]
Elements[Elements]
Client[src/api/main.ts]
end
Page --> Main
List --> Client
Sent --> Client
Main --> Tree
Main --> Elements
Main --> Client
Expand All @@ -127,7 +148,7 @@ npm install
npm run dev
```

Open [http://localhost:3000](http://localhost:3000).
Open [http://localhost:3000](http://localhost:3000) (it redirects to the templates list).

The frontend expects a backend on port **9000**. Override the base URL with `NEXT_PUBLIC_API_URL`.

Expand Down Expand Up @@ -162,11 +183,14 @@ The assistant sits on the left of the editor, next to the preview. Open **Settin
## Project layout

```
app/ Next.js App Router (layout, page)
app/ Next.js App Router (layout; /templates, /templates/[id], /sent)
src/
api/ Axios client and types
ai/ AI assistant: providers, tools, agent loop, key storage
editor/Main/ Editor UI (tree, elements, forms, AI chat)
editor/Main/ Editor UI (tree, elements, forms, AI chat, send dialog)
templates/ Templates list page
sent/ Sent emails log page
shell/ Sidebar, header and theme
types/ Shared types
AGENTS.md Guide for AI coding agents
docs/AI_AGENT.md Extended agent reference
Expand Down
5 changes: 3 additions & 2 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Main from "../src/editor/Main/Main";
import { redirect } from "next/navigation";

/** The editor opens from the templates list, so the home page is that list. */
export default function HomePage() {
return <Main />;
redirect("/templates");
}
5 changes: 5 additions & 0 deletions app/sent/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import SentEmailsPage from "../../src/sent/SentEmailsPage";

export default function SentRoute() {
return <SentEmailsPage />;
}
7 changes: 7 additions & 0 deletions app/templates/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import Main from "../../../src/editor/Main/Main";

export default async function TemplatePage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
// `key`: opening another template starts the editor (tree, chat, modals) from scratch.
return <Main key={id} templateId={id} />;
}
5 changes: 5 additions & 0 deletions app/templates/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import TemplatesPage from "../../src/templates/TemplatesPage";

export default function TemplatesRoute() {
return <TemplatesPage />;
}
Loading