Skip to content
Merged

WIP #102

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
69 changes: 69 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,75 @@ dev server against it — it never touches the repository configured in `.env`.
minted directly (same HMAC scheme as `SessionService`), so specs don't need to drive the login
form except in `e2e/specs/login.spec.ts`, which covers that mechanism itself.

## UI (v3 redesign, in progress)

The redesign uses the Kettu palette (ink surfaces, `brand-500` orange `#f95d11`, Inter). `/brand` is
the live catalog of everything below; it uses the bare layout (no app sidebar/navbar) and needs a
session like any other page. Check it there before inventing a new style.

**Rule: styling is classes, behavior is components.**

- **Styling only → `k-*` classes** from `src/lib/styles/brand.css` (imported by `app.css`):
buttons (`k-btn` + `k-btn-primary|secondary|outline-brand|ghost|danger`, sizes `k-btn-sm|lg`,
`k-btn-icon`), inputs/textarea/native select (`k-input`, `k-label`, `k-help`), checkbox/radio
(`k-checkbox`), badges (`k-badge` + `-brand|ok|warn|danger|info`), `k-kbd`, cards (`k-card`,
`k-card-hover`, `k-panel`), `k-popover`, `k-divider`, navigation (`k-nav-item` with
`aria-current="page"`, `k-nav-heading`), headings (`k-text-gradient`, `k-text-gradient-brand`).
They work on any element (`<a>`, `<button type="submit">`…), so do not wrap them in components.
They live in `@layer components`, so Tailwind utilities can adjust them (`k-input h-9 pl-9`).
- **Anything with behavior, focus or ARIA → `#lib/components/ui`** (import from the index):
`Modal`, `Drawer`, `DropdownMenu` + `MenuItem`, `Select`, `Field`, `Switch`, `Tabs`
(`underline` / `segmented`), `TagInput`, `CommandPalette`, `toast` + `Toaster`. Never hand-roll outside
click, Esc, focus trapping or scroll locking in a page; `ui/overlay.ts` already does it (Esc only
closes the top-most overlay).
- Every form control goes inside `Field` (label, help and error wired with `aria-describedby` /
`aria-invalid`); spread the snippet argument on the control: `<input class="k-input" {...control} />`.
- A submit button in a `Modal` footer lives outside the `<form>`: give the form an `id` and the
button `form="that-id"`. Put `data-autofocus` on the field that should get the initial focus.
- `Select` and `Switch` accept `name` and add a hidden input, but they need JavaScript. Forms that
must work without JS keep a native `<select class="k-input">` / `<input type="checkbox" class="k-checkbox">`.
- Creating something from a list opens a `Modal` instead of navigating; keep the `/new` route for
direct links and no-JS, and post the modal form to that route's actions with local result
handling (see `monitoring/NewMonitorModal.svelte` + `MonitorForm` `variant="modal"`).
- Page pattern (see project settings): `<header>` with `h1.text-2xl` + `text-fg-muted` description
and the primary action on the right; content in `k-card`s; success/error feedback with `toast`,
not inline banners; every destructive action (delete, revoke, rotate, remove access) confirms in
a `Modal` (`role="alertdialog"`), and deleting a top-level entity asks to type its name.
- Floating panels (`DropdownMenu`, `Select`, `TagInput` suggestions) render in `<body>` through
`floating` in `ui/overlay.ts`, so no `overflow` (tables, modal bodies) clips them.
- Alerts: one alert notifies several channels (`mail`, `slack`, `google_chat`, `webhook`), one
message each; targets live in `recipients` (`userIds`/`roleIds`/`emails`, `slackChannels`,
`googleChatSpaces`, `webhookUrls`). Only `mail` is delivered (`DELIVERED_CHANNELS`); the rest are
stored and validated. Create/edit happens in `AlertWizard` (modal); the `/new` and `/[id]` pages
keep the no-JS editor (`AlertEditor`), so new alert fields must be added to both.
- `toast.*` is client-only (module state): call it from event handlers, never during SSR.
- Tokens: `bg-ink-950…500`, `brand-50…900`, text `text-fg|fg-muted|fg-subtle`, status
`ok|warn|danger|info` (always with an icon or text, never as a chart series), chart series
`series-1…5` in that fixed order. Use `bg-snow` for pure white: legacy `app.css` overrides
`.bg-white`, `.bg-white/15|70|80|90`, `.border-white/15|60`, `.text-slate-*`, `.shadow-sm|md|xl`
with `!important`, so avoid those classes in v3 code.
- **App shell (migrated to v3):** `+layout.svelte` renders `AppNavbar` (logo, ⌘K search, docs,
account menu with "Ajustes de GitOps" for cluster admins) and `AppSidebar` as in the `/brand` mock:
context switcher (projects grouped by organization, with search, and one "Ver todos los proyectos"
link for the selected organization), flat sections (Proyecto:
Dashboard + each enabled product + Ajustes; Organización), and `SidebarFooter` (version, GitDB
status, collapse). There is no page footer. A module with several pages shows them as tabs
(`#section-nav`) above the content. The tree lives in `#lib/navigation.ts` (`buildNavigation`) and
feeds the sidebar, the tabs and the search: add new routes there with their permission flag
(`sidebar: false` keeps a category out of the sidebar). The same tree builds the breadcrumbs above the tabs
(org › project › module › page); project pages have no header of their own. The layout mounts `CommandPalette` and
`Toaster` once; do not add another in a page. Collapsed mode is stored in `localStorage`
(`gitops-sidebar-collapsed`); below `md` the sidebar is off-canvas. Auth, bootstrap and `/brand`
keep the bare layout. The sidebar must stay the first `<aside>` in the DOM
(`sidebar-visibility.spec.ts`). Pages inside the shell are still v2 until migrated one by one.
- Logo files are in `static/brand/` (`gitops-logo-dark|light.svg`, `gitops-mark-*.svg`,
`gitops-icon.svg` and PNGs). The navbar uses the new logo; the old `gitops_logo*.png`,
`icono_*.png` and `favicon.png` are still used elsewhere (favicon, auth pages).
- Legacy: `#lib/components/Dropdown.svelte` and the `btn-*` / `field-input` classes are v2; replace
them with the v3 equivalents when a screen is migrated, not piecemeal.
- `e2e/specs/brand-ui.spec.ts` covers keyboard, focus and closing behavior of the UI components;
extend it when you change them.

## Architecture

Business logic lives in `src/modules/<module>/`:
Expand Down
91 changes: 72 additions & 19 deletions e2e/specs/alerts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,50 +31,103 @@ test.describe('project alerts', () => {
'href',
`${alertsUrl}/new`,
);
await openEditor(page, `${alertsUrl}/new`);
await page.waitForLoadState('networkidle');
await page.getByRole('link', { name: 'Crear alerta' }).first().click();
const wizard = page.getByRole('dialog', { name: 'Nueva alerta' });
await expect(wizard).toBeVisible();
// the wizard is a modal: the URL does not change
await expect(page).toHaveURL(new RegExp(`${alertsUrl}$`));

// step 1: event
await page.getByLabel('Nombre', { exact: true }).fill(GUIDED_NAME);
await page.getByLabel('Evento', { exact: true }).selectOption({ label: 'Análisis completado' });
await wizard.getByRole('radio', { name: /^Análisis completado/ }).click();
await wizard.getByRole('button', { name: 'Siguiente' }).click();

// step 2: Servicio es <seeded service> · Vulnerabilidades críticas mayor que 0
const builder = page.getByTestId('condition-builder');
const builder = wizard.getByTestId('condition-builder');
await builder.getByRole('button', { name: 'Añadir condición' }).click();
const first = builder.getByTestId('condition-row').nth(0);
await first.getByLabel('Campo').selectOption({ label: 'Servicio' });
await first.getByLabel('Operador').selectOption({ label: 'es' });
await first.getByLabel('Campo').click();
await page.getByRole('option', { name: 'Servicio', exact: true }).click();
await first.getByLabel('Operador').click();
await page.getByRole('option', { name: 'es', exact: true }).click();
await first.getByRole('radio', { name: 'E2E Seeded Service' }).check();

await builder.getByRole('button', { name: 'Añadir condición' }).click();
const second = builder.getByTestId('condition-row').nth(1);
await second.getByLabel('Campo').selectOption({ label: 'Vulnerabilidades críticas' });
await second.getByLabel('Operador').selectOption({ label: 'mayor que' });
await second.getByLabel('Campo').click();
await page.getByRole('option', { name: 'Vulnerabilidades críticas', exact: true }).click();
await second.getByLabel('Operador').click();
await page.getByRole('option', { name: 'mayor que', exact: true }).click();
await second.getByLabel('Valor').fill('0');

// step 3: recipients and throttle
await page.getByRole('checkbox', { name: 'Project Admin' }).check();
await page.getByLabel('No enviar más de un email cada (minutos)').fill('30');

// step 4: dry run, nothing is sent
await page.getByRole('button', { name: 'Probar alerta' }).click();
const result = page.getByTestId('alert-test-result');
await wizard.getByRole('button', { name: 'Siguiente' }).click();

// step 3: email is on by default; a role from the suggestions plus an external address
const targets = wizard.getByLabel('Destinatarios');
await targets.fill('Project Ad');
await page.getByRole('option', { name: 'Project Admin', exact: true }).click();
await targets.fill('oncall@example.com');
await targets.press('Enter');
await wizard.getByRole('radio', { name: '1 hora' }).click();
await wizard.getByRole('button', { name: 'Siguiente' }).click();

// step 4: name, dry run (nothing is sent) and create
await wizard.getByLabel('Nombre', { exact: true }).fill(GUIDED_NAME);
await wizard.getByRole('button', { name: 'Probar alerta' }).click();
const result = wizard.getByTestId('alert-test-result');
await expect(result).toContainText('El evento de ejemplo cumple las condiciones.');
await expect(result).toContainText(seed.personas.projectAdmin.username);
await expect(result).toContainText('oncall@example.com');
await expect(result).toContainText('no se ha enviado ningún email');

await page.getByRole('button', { name: 'Crear alerta' }).click();
await expect(page).toHaveURL(new RegExp(`${alertsUrl}\\?saved=`));
await wizard.getByRole('button', { name: 'Crear alerta' }).click();
await expect(wizard).toBeHidden();

const row = page.getByTestId('alert-row').filter({ hasText: GUIDED_NAME });
await expect(row).toBeVisible();
await expect(row.getByTestId('alert-summary')).toHaveText(
'Servicio es E2E Seeded Service y Vulnerabilidades críticas mayor que 0',
);
await expect(row).toContainText('Project Admin');
await expect(row).toContainText('Máx. un email cada 30 min');
await expect(row).toContainText('oncall@example.com');
await expect(row).toContainText('Máx. un email cada 60 min');
await expect(row.getByRole('switch')).toHaveAttribute('aria-checked', 'true');
});

test('an alert can notify several channels and is edited in the same wizard', async ({
page,
loginAs,
}) => {
await loginAs('projectAdmin');
await page.goto(alertsUrl);
await page.waitForLoadState('networkidle');
const row = page.getByTestId('alert-row').filter({ hasText: GUIDED_NAME });
await row.getByRole('link', { name: 'Editar' }).click();
const wizard = page.getByRole('dialog', { name: 'Editar alerta' });
await expect(wizard.getByLabel('Nombre', { exact: true })).toHaveValue(GUIDED_NAME);

await wizard.getByRole('button', { name: /Destinos/ }).click();
await wizard.getByRole('checkbox', { name: /^Slack/ }).click();
await wizard.getByRole('checkbox', { name: /^Webhook/ }).click();
// a destination without targets keeps "Next" disabled
await expect(wizard.getByRole('button', { name: 'Siguiente' })).toBeDisabled();
const slack = wizard.getByLabel('Canales de Slack');
await slack.fill('Alertas Prod');
await slack.press('Enter');
await expect(wizard.getByText('Usa nombres de canal de Slack como #alertas.')).toBeVisible();
await slack.fill('alertas-prod');
await slack.press('Enter');
const webhook = wizard.getByLabel('URLs');
await webhook.fill('https://hooks.example.com/gitops');
await webhook.press('Enter');
await wizard.getByRole('button', { name: 'Siguiente' }).click();
await wizard.getByRole('button', { name: 'Guardar cambios' }).click();
await expect(wizard).toBeHidden();

await expect(row).toContainText('#alertas-prod');
await expect(row).toContainText('https://hooks.example.com/gitops');
await expect(row).toContainText('oncall@example.com');
});

test('server validation errors show next to their field', async ({ page, loginAs }) => {
await loginAs('projectAdmin');
await openEditor(page, `${alertsUrl}/new`);
Expand Down
136 changes: 136 additions & 0 deletions e2e/specs/brand-ui.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// Comportamiento de los componentes de #lib/components/ui sobre el catálogo /brand:
// teclado, foco, cierre con Esc y clic fuera, toasts.
import { test, expect } from '../fixtures/auth';

test.beforeEach(async ({ page, loginAs }) => {
await loginAs('orgAdmin');
await page.goto('/brand');
// los componentes solo responden una vez hidratada la página
await expect(page.locator('[data-hydrated="true"]')).toBeAttached({ timeout: 20_000 });
});

test('Modal: abre, enfoca el campo, Esc cierra y devuelve el foco', async ({ page }) => {
const opener = page.getByRole('button', { name: /Formulario/ });
await opener.click();
const dialog = page.getByRole('dialog', { name: 'Nuevo secreto' });
await expect(dialog).toBeVisible();
await expect(dialog.getByLabel('Nombre')).toBeFocused();

await page.keyboard.type('mal-nombre');
await expect(dialog.getByText('Solo mayúsculas')).toBeVisible();
await expect(dialog.getByLabel('Nombre')).toHaveAttribute('aria-invalid', 'true');

await page.keyboard.press('Escape');
await expect(dialog).toBeHidden();
await expect(opener).toBeFocused();
});

test('Modal: el submit del footer envía el formulario y muestra un toast', async ({ page }) => {
await page.getByRole('button', { name: /Formulario/ }).click();
const dialog = page.getByRole('dialog', { name: 'Nuevo secreto' });
await dialog.getByLabel('Nombre').fill('DATABASE_URL');
await dialog.getByPlaceholder('••••••••').fill('postgres://x');
await dialog.getByRole('button', { name: 'Guardar secreto' }).click();
await expect(dialog).toBeHidden();
await expect(page.getByRole('status').filter({ hasText: 'Secreto guardado' })).toBeVisible();
});

test('Modal de confirmación: el botón se habilita al escribir el nombre', async ({ page }) => {
await page.getByRole('button', { name: /Confirmación destructiva/ }).click();
const dialog = page.getByRole('alertdialog', { name: '¿Eliminar el proyecto?' });
const confirm = dialog.getByRole('button', { name: 'Eliminar proyecto' });
await expect(confirm).toBeDisabled();
await expect(dialog.getByRole('textbox')).toBeFocused();
await page.keyboard.type('gitops-cloud');
await expect(confirm).toBeEnabled();
});

test('Drawer: clic en el fondo cierra', async ({ page }) => {
await page.getByRole('button', { name: /Drawer lateral/ }).click();
const drawer = page.getByRole('dialog', { name: 'checkout-api' });
await expect(drawer).toBeVisible();
await page.mouse.click(20, 300);
await expect(drawer).toBeHidden();
});

test('DropdownMenu: flechas recorren los elementos y Esc devuelve el foco', async ({ page }) => {
const trigger = page.getByRole('button', { name: 'Acciones', exact: true });
await trigger.click();
const menu = page.getByRole('menu', { name: 'Acciones del proyecto' });
await expect(menu.getByRole('menuitem', { name: /Editar/ })).toBeFocused();
await page.keyboard.press('ArrowDown');
await expect(menu.getByRole('menuitem', { name: /Duplicar/ })).toBeFocused();
await page.keyboard.press('End');
await expect(menu.getByRole('menuitem', { name: /Eliminar/ })).toBeFocused();
await page.keyboard.press('Escape');
await expect(menu).toBeHidden();
await expect(trigger).toBeFocused();
});

test('DropdownMenu: clic fuera cierra', async ({ page }) => {
await page.getByRole('button', { name: 'Acciones', exact: true }).click();
await expect(page.getByRole('menu', { name: 'Acciones del proyecto' })).toBeVisible();
await page.getByRole('heading', { name: 'Dropdowns' }).click();
await expect(page.getByRole('menu', { name: 'Acciones del proyecto' })).toBeHidden();
});

test('Capas: Esc cierra solo el overlay de arriba', async ({ page }) => {
await page.getByRole('button', { name: /Formulario/ }).click();
const dialog = page.getByRole('dialog', { name: 'Nuevo secreto' });
await expect(dialog).toBeVisible();
// La paleta se abre encima del modal: Esc debe cerrar la paleta y dejar el modal.
await page.keyboard.press('Control+k');
const palette = page.getByRole('dialog', { name: 'Búsqueda' });
await expect(palette).toBeVisible();
await page.keyboard.press('Escape');
await expect(palette).toBeHidden();
await expect(dialog).toBeVisible();
});

test('Select: busca, elige con teclado y actualiza el valor', async ({ page }) => {
const select = page.getByRole('combobox', { name: 'Región' });
await expect(select).toContainText('europe-southwest1');
await select.click();
await page.keyboard.type('iowa');
await page.keyboard.press('Enter');
await expect(select).toContainText('us-central1');
await expect(select).toBeFocused();
});

test('Tabs: las flechas cambian de pestaña y saltan las deshabilitadas', async ({ page }) => {
const resumen = page.getByRole('tab', { name: 'Resumen' });
await resumen.click();
await page.keyboard.press('ArrowLeft');
await expect(page.getByRole('tab', { name: 'Historial' })).toHaveAttribute(
'aria-selected',
'true',
);
await expect(page.getByRole('tab', { name: 'Historial' })).toBeFocused();
await page.keyboard.press('ArrowRight');
await expect(resumen).toHaveAttribute('aria-selected', 'true');
});

test('Switch: cambia aria-checked al pulsarlo', async ({ page }) => {
const sw = page.getByRole('switch', { name: /Registro abierto/ });
await expect(sw).toHaveAttribute('aria-checked', 'false');
await sw.click();
await expect(sw).toHaveAttribute('aria-checked', 'true');
});

test('CommandPalette: Ctrl+K abre, filtra y Enter ejecuta la acción', async ({ page }) => {
await page.keyboard.press('Control+k');
const palette = page.getByRole('dialog', { name: 'Búsqueda' });
await expect(palette).toBeVisible();
await page.keyboard.type('secreto');
await page.keyboard.press('Enter');
await expect(palette).toBeHidden();
await expect(page.getByRole('dialog', { name: 'Nuevo secreto' })).toBeVisible();
});

test('Toaster: muestra el aviso y se puede cerrar', async ({ page }) => {
await page.getByRole('button', { name: 'Error', exact: true }).click();
const alert = page.getByRole('alert').filter({ hasText: 'No se pudo sincronizar' });
await expect(alert).toBeVisible();
await alert.getByRole('button', { name: 'Cerrar aviso' }).click();
await expect(alert).toBeHidden();
});
1 change: 0 additions & 1 deletion e2e/specs/code-report.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ const readOnlyRoutes = [
`${base}/services`,
`${base}/services/${seed.seededServiceSlug}`,
`${base}/settings`,
`${base}/settings/tools`,
];

test.describe('code report — no codereport:*:read grant at all', () => {
Expand Down
Loading
Loading