diff --git a/.atl/.skill-registry.cache.json b/.atl/.skill-registry.cache.json deleted file mode 100644 index c9acc3348..000000000 --- a/.atl/.skill-registry.cache.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "fingerprint": "57a67d9906a0df1266417d5c1d567b607dd3d834" -} diff --git a/.atl/skill-registry.md b/.atl/skill-registry.md deleted file mode 100644 index 67ed9a42e..000000000 --- a/.atl/skill-registry.md +++ /dev/null @@ -1,58 +0,0 @@ -# Skill Registry — ui-kit - - - -Last updated: 2026-10-21 - -## Sources scanned - -- /Users/eclass/.agents/skills -- /Users/eclass/.codex/skills - -## Contract - -**Delegator use only.** This registry is an index, not a summary. Any agent that launches subagents reads it to select relevant skills, then passes exact `SKILL.md` paths for the subagent to read before work. - -`SKILL.md` remains the source of truth. Do not inject generated summaries or compact rules by default; pass paths so subagents load the full runtime contract and preserve author intent. - -## Skills - -| Skill | Trigger / description | Scope | Path | -| --- | --- | --- | --- | -| `branch-pr` | Create Gentle AI pull requests with issue-first checks. Trigger: creating, opening, or preparing PRs for review. | user | `/Users/eclass/.agents/skills/branch-pr/SKILL.md` | -| `chained-pr` | Trigger: PRs over 400 lines, stacked PRs, review slices. Split oversized changes into chained PRs that protect review focus. | user | `/Users/eclass/.agents/skills/chained-pr/SKILL.md` | -| `chakra-sx-migration` | Use when converting React view/component styles from styled-components to Chakra UI `sx` objects in this codebase. Apply it when a file defines styled wrappers that should become `sx...` constants or functions, and update the consuming JSX to use Chakra `Box` with `sx` and semantic `as` tags while preserving nesting, media queries, and project conventions. | user | `/Users/eclass/.codex/skills/chakra-sx-migration/SKILL.md` | -| `cognitive-doc-design` | Design docs that reduce cognitive load. Trigger: writing guides, READMEs, RFCs, onboarding, architecture, or review-facing docs. | user | `/Users/eclass/.agents/skills/cognitive-doc-design/SKILL.md` | -| `comentarios` | Escribe comentarios y JSDoc útiles en español para funciones con lógica no obvia, efectos o invariantes relevantes. | user | `/Users/eclass/.codex/skills/comentarios/SKILL.md` | -| `comment-writer` | Write warm, direct collaboration comments. Trigger: PR feedback, issue replies, reviews, Slack messages, or GitHub comments. | user | `/Users/eclass/.agents/skills/comment-writer/SKILL.md` | -| `contra-revisor` | Trigger: contra-revisor, reviewer feedback, MR observations. Verify review findings and apply only necessary, safe corrections. | user | `/Users/eclass/.codex/skills/contra-revisor/SKILL.md` | -| `e2e-playwright-testing` | End-to-end testing with Playwright for web applications. Use when writing E2E tests, browser automation, form submission testing, or user flow testing. Triggers on "playwright", "e2e test", "browser test", "end-to-end", "form flow testing", or test files in tests/e2e/. | user | `/Users/eclass/.codex/skills/e2e-playwright-testing/SKILL.md` | -| `fill-mr-template` | Completa plantillas de Merge Request o Pull Request en Markdown usando los cambios actuales del repositorio. Usar cuando el usuario pida redactar, crear o completar un MR/PR, especialmente si comparte una plantilla específica que debe respetarse. | user | `/Users/eclass/.codex/skills/fill-mr-template/SKILL.md` | -| `find-skills` | Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill. | user | `/Users/eclass/.agents/skills/find-skills/SKILL.md` | -| `generate-commit-text` | Generate only the commit message text after reviewing the current git changes and the repository's recent commit style. Use when the user asks things like "generame el commit", "dame el mensaje del commit", "redacta el commit", or needs a Conventional Commit style message without executing `git commit`. | user | `/Users/eclass/.codex/skills/generate-commit-text/SKILL.md` | -| `gentle-ai-bench` | Trigger: bench, journey, journeys, driven mode, gentle-ai-bench, journey corpus, j-numbers, bench axis. Author and verify gentle-ai bench journeys; go test ./bench never proves driven execution. | user | `/Users/eclass/.agents/skills/gentle-ai-bench/SKILL.md` | -| `go-testing` | Trigger: Go tests, go test coverage, Bubbletea teatest, golden files. Apply focused Go testing patterns. | user | `/Users/eclass/.agents/skills/go-testing/SKILL.md` | -| `issue-creation` | Create and triage GitHub issues from repository evidence. Trigger: issue creation, bug reports, feature requests, or issue approval. | user | `/Users/eclass/.agents/skills/issue-creation/SKILL.md` | -| `jest` | Jest best practices, patterns, and API guidance for JavaScript/TypeScript testing. Covers mock design, async testing, matchers, timer mocks, snapshots, module mocking, configuration, and CI optimization. Baseline: jest ^30.0.0. Triggers on: jest imports, describe, it, test, expect, jest.fn, jest.mock, jest.spyOn, mentions of "jest", "unit test", "test suite", or "mock". | user | `/Users/eclass/.codex/skills/jest/SKILL.md` | -| `jira-comment-format` | Redacta comentarios de Jira en español para documentar bugs, fixes, comportamientos esperados, hallazgos técnicos, validaciones o seguimiento de tickets. Usar cuando el usuario pida "formato comentario Jira", "comentario de Jira", "déjalo para Jira", "describir bug para Jira" o quiera convertir contexto técnico en un comentario claro para un ticket. | user | `/Users/eclass/.codex/skills/jira-comment-format/SKILL.md` | -| `judgment-day` | Trigger: judgment day, dual review, adversarial review, juzgar. Run explicit blind dual review with at most two scoped fix/re-judgment rounds. | user | `/Users/eclass/.agents/skills/judgment-day/SKILL.md` | -| `manhwa-offline` | Trigger: manhwa URL, manga URL, descargar capítulos, ZIP por capítulos, offline comics. Download ordered images into one ZIP per chapter. | user | `/Users/eclass/.codex/skills/manhwa-offline/SKILL.md` | -| `pokeshort-solver` | Resuelve cadenas compactas de PokeShort cuando el usuario pega JSON con formato {"p":[...],"c":[...]} o pide ordenar Pokémon según condiciones como Gen>, Gen=, Supera>, Supera=, Altura, Peso, Dex, etc. Use when Codex receives compact PokeShort data from a mobile bookmarklet and must return the correct Pokémon order. | user | `/Users/eclass/.codex/skills/pokeshort-solver/SKILL.md` | -| `rdd-defect-workflow` | Trigger: RDD, receipt-driven development, review authority, receipt/lineage, correction/recovery, delivery gate/kill switch, bounded review defects. Guide work. | user | `/Users/eclass/.agents/skills/rdd-defect-workflow/SKILL.md` | -| `requerimiento` | Guide software requirements with a safe, scalable workflow. Use when the user invokes $requerimiento or says a task is feat, feature, fix, bugfix, refactor, hotfix, review follow-up, or asks for a plan before changing code; helps Codex classify the work, define scope, identify break risks, implement narrowly, validate, and document the change. | user | `/Users/eclass/.codex/skills/requerimiento/SKILL.md` | -| `revision-doctor` | Run react-doctor when the user asks for "revision doctor", a React doctor review, or a React health check in the current workspace. Execute the tool, summarize findings, and recommend concrete fixes. | user | `/Users/eclass/.codex/skills/revision-doctor/SKILL.md` | -| `revision-final-front` | Trigger: frontend final review, frontend MR review, revisión final frontend. Review frontend readiness; exclude ordinary edits and implementation requests. | user | `/Users/eclass/.codex/skills/revision-final-front/SKILL.md` | -| `skill-creator` | Trigger: new skills, agent instructions, documenting AI usage patterns. Create LLM-first skills with valid frontmatter. | user | `/Users/eclass/.agents/skills/skill-creator/SKILL.md` | -| `skill-improver` | Trigger: improve skills, audit skills, refactor skills, skill quality. Audit and upgrade existing LLM-first skills. | user | `/Users/eclass/.agents/skills/skill-improver/SKILL.md` | -| `systemic-issue-triage` | Trigger: new issue, bug report, triage, backlog, issue flood, community report, root cause, dead-end, blocked user. Attack issues by root class, never one-by-one; fixes must shrink the system, not grow it. | user | `/Users/eclass/.agents/skills/systemic-issue-triage/SKILL.md` | -| `translation-keys-sync` | Add or update translation keys in repositories that store language catalogs in files like src/spa/*.ts, src/eng/*.ts, src/por/*.ts and matching tests. Use when the user provides new translation rows or asks Codex to add keys to the translation project, especially when Portuguese must remain identical to Spanish instead of being translated. | user | `/Users/eclass/.codex/skills/translation-keys-sync/SKILL.md` | -| `vercel-react-best-practices` | React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements. | user | `/Users/eclass/.codex/skills/react-best-practices/SKILL.md` | -| `web-accessibility` | Routing-first skill for web accessibility remediation and verification. Use when the main job is classifying which accessibility surface is failing — semantics, keyboard/focus, labels/announcements, visual perception/reflow, media alternatives, or routed-app navigation feedback — and turning vague audit, WCAG, axe/Lighthouse, or "make this accessible" requests into one concrete remediation packet. Broad UI critique for hierarchy, polish, and launch readiness belongs here too. Route component API architecture and system governance to `design-system`, and responsive layout strategy to `responsive-design`. | user | `/Users/eclass/.codex/skills/web-accessibility/SKILL.md` | -| `work-unit-commits` | Plan commits as reviewable work units. Trigger: implementation, commit splitting, chained PRs, or keeping tests and docs with code. | user | `/Users/eclass/.agents/skills/work-unit-commits/SKILL.md` | - -## Loading protocol - -1. Match task context and target files against the `Trigger / description` column. -2. Pass only the matching `Path` values to the subagent under `## Skills to load before work`. -3. Instruct the subagent to read those exact `SKILL.md` files before reading, writing, reviewing, testing, or creating artifacts. -4. If no matching skill exists, proceed without project skill injection and report `skill_resolution: none`. diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md new file mode 100644 index 000000000..7cfc50267 --- /dev/null +++ b/.claude/CLAUDE.md @@ -0,0 +1,79 @@ +# CLAUDE.md — ui-kit (librería de componentes eClass) + +Librería `@eclass/ui-kit` en React + TypeScript + Chakra UI 1.8, publicada en npm y consumida +por los fronts de eClass (por ejemplo v8, en React 16.14). Incluye un sitio de documentación +en `src/documentation`. Todo en español: código comentado, JSDoc, títulos de pruebas y commits. +El detalle del proyecto está en `.claude/rules/` (algunas reglas se cargan solo al tocar ciertas +carpetas). + +Antes de cualquier comando: Node 24.22.0 (`.nvmrc`) y npm 11.13.0. Ver `.claude/rules/commands.md`. + +## 1. Piensa antes de codificar + +**No asumas. No ocultes la confusión. Expón las compensaciones.** + +- Declara tus suposiciones. Si tienes dudas, pregunta. +- Si hay varias interpretaciones, preséntalas; no elijas en silencio. +- Si existe un enfoque más simple, dilo. +- Lo que hoy se ve en el componente es la especificación: no "alinees" un componente con otro sin confirmar. + +## 2. Simplicidad primero + +**El código mínimo que resuelve el problema. Nada especulativo.** + +- Sin características ni "flexibilidad" que no se pidieron. +- Sin abstracciones para código de un solo uso. +- Sin manejo de errores para escenarios imposibles. +- Pregúntate: "¿un ingeniero senior diría que esto está sobre-complicado?". Si es sí, simplifica. + +## 3. Cambios quirúrgicos + +**Toca solo lo que debes. Limpia solo tu propio desorden.** + +- No "mejores" código, comentarios ni formato vecinos; respeta el estilo existente. +- No refactorices lo que no está roto. Si ves código muerto ajeno, menciónalo, no lo borres. +- Elimina solo los imports/variables/funciones que TUS cambios dejaron sin uso. +- Cada línea cambiada debe rastrearse a la solicitud del usuario. +- No cambies la API pública (exports de `src/index.ts`, props existentes) sin avisar: los + consumidores se rompen. Ver `.claude/rules/conventions.md`. +- Mejoras grandes: de a una funcionalidad, sin commitear, para que el usuario revise cada paso. +- Nunca hagas squash ni amend de tus cambios sobre commits existentes del usuario. + +## 4. Ejecución dirigida por objetivos + +**Define criterios de éxito. Itera hasta verificar.** + +- "Agregar validación" → escribir pruebas para entradas inválidas y hacerlas pasar. +- "Arreglar el bug" → escribir una prueba que lo reproduzca y hacerla pasar. +- "Refactorizar X" → las pruebas pasan antes y después. +- Para tareas de varios pasos, declara un plan breve: `1. [Paso] → verificar: [comprobación]`. + +## 5. Auto-mejora continua + +Cuando el usuario corrija un enfoque, un error o una suposición: +- Antes de cerrar el tema, pregunta: "¿Agrego esto a CLAUDE.md para no repetir el error?". +- Si acepta, agrega la regla en "Reglas añadidas" (o en el archivo de `.claude/rules/` que + corresponda si es de una carpeta o tema). +- Si una regla quedó obsoleta, elimínala en vez de acumular. + +## 6. Flujo de trabajo + +Clasifica cada pedido antes de editar: + +- **Tarea chica** (se entiende completa y se podría retomar solo mirando el diff): implementar + directo. +- **Tarea grande** (varias partes, decisiones abiertas o no se podría retomar desde el diff): + 1. Entrar en modo plan: explorar, preguntar lo que no esté claro y proponer el plan. + 2. Con el plan aprobado, crear `odd/tasks/.md` (ignorado por git) con objetivo, + alcance, checklist, criterios de aceptación y progreso. Mantenerlo al día en cada paso. + 3. Implementar de a un paso, deteniéndose para que el usuario revise. +- **Todo componente o funcionalidad nueva** lleva sus pruebas y la actualización de su página + en `src/documentation` en el mismo cambio. +- **Al terminar y validar a mano**: el usuario corre `/revisar-desarrollo`, que ajusta la + profundidad de la revisión según el riesgo. +- Al retomar una tarea grande, leer primero su `odd/tasks/.md`. + +## 7. Reglas añadidas + +- Pedir "juntar los commits" significa solo hacer squash de los commits del usuario; los cambios + propios quedan aparte para revisión. diff --git a/.claude/rules/architecture.md b/.claude/rules/architecture.md new file mode 100644 index 000000000..5d41aaf36 --- /dev/null +++ b/.claude/rules/architecture.md @@ -0,0 +1,42 @@ +# Arquitectura + +## Carpetas + +- `src/atoms/`, `src/molecules/`, `src/organisms/`: componentes de la librería según diseño + atómico. Una carpeta por componente (`Label/Label.tsx`); los organismos grandes agrupan dentro + `components/`, `utils/`, `services/` y `types.d.ts` (ver `organisms/CourseList`). +- Cada nivel tiene su barrel `index.ts` (`src/atoms/index.ts`, ...). +- `src/theme/`: tema de Chakra (`extendTheme` con `colors`, `typography`, `utils`, `styles`) y + `vars()`, que devuelve la variable CSS de Chakra (`vars('colors-main-deepSkyBlue')` → + `var(--chakra-colors-main-deepSkyBlue)`). Los colores siguen el sistema de diseño. +- `src/services/`: utilidades sin UI (`uniqueId`). +- `src/test/jest-setup.ts`: configuración global de Jest (ver `.claude/rules/testing/testing.md`). +- `src/documentation/`: sitio de documentación (ver `.claude/rules/documentation/documentation.md`). +- `src/Playground.tsx`: página vacía para probar componentes en local; no se publica. +- `src/main.tsx`: entrada de Vite. Con `VITE_REACT_DEPLOY_DOCUMENTATION=DOCUMENTATION` (en `.env`) + monta la documentación o el Playground; si no, solo importa `src/index.ts`. + +## Imports + +- Alias de `tsconfig.json`: `@/*` → `src/*`, `@atoms`, `@molecules`, `@organisms`, `@theme`, + `@theme/*`, `@icons` (→ `src/atoms/Icons`). En el código existente conviven alias y rutas + relativas; respetar lo que use el archivo. +- `typescript-transform-paths` reescribe los alias en los `.d.ts` generados. + +## API pública + +- `src/index.ts` es la entrada de la librería: lo que no se exporta ahí no existe para el + consumidor. +- Componente nuevo: exportarlo en el barrel de su nivel **y** en `src/index.ts`, en la sección + de su nivel (Átomos, Moléculas, Organismos). Exportar también sus tipos de props si el + consumidor los necesita (`export type { ... }`). +- Quitar o renombrar un export, o una prop, o cambiar su tipo o comportamiento por defecto, es un + cambio incompatible (ver `.claude/rules/git-workflow.md`). + +## Build + +- `npm run build`: `tsc` + `vite build` en modo librería (`dist/eclass-ui-kit.es.js` y `.umd.js`) + + tipos (`tsconfig.types.json`) + copia de los `.d.ts` de `src`. +- `react`, `react-dom`, `@chakra-ui/react`, `@emotion/*` y `framer-motion` son `external`: + no se empaquetan, los pone el consumidor. Cualquier otra dependencia nueva sí entra al bundle + de todos los consumidores: evaluar su peso antes de agregarla. diff --git a/.claude/rules/commands.md b/.claude/rules/commands.md new file mode 100644 index 000000000..9e1604c7a --- /dev/null +++ b/.claude/rules/commands.md @@ -0,0 +1,38 @@ +# Comandos + +## Entorno + +- Node 24.22.0 (`.nvmrc`) y npm 11.13.0 (`packageManager`), los mismos que usa CI. +- Instalar con `npm ci` (CI no regenera el lockfile). Requiere acceso SSH a gitlab.com por los + paquetes de tipos `@types/eclass__*`. + +## Desarrollo + +```bash +npm run dev # Playground (src/Playground.tsx) para probar componentes en local +npm run docu # sitio de documentación en local +npm run build # build de la librería en dist/ (lo corre CI al publicar) +``` + +- `npm run storybook`, que menciona el README, no existe. + +## Tests + +```bash +npx jest +``` + +- `npm run test` corre la suite completa con coverage: en local no usarlo, ni + `--findRelatedTests`, porque es muy pesado para el equipo de desarrollo. La suite completa corre + en CI (GitHub Actions). +- En local, correr solo los `.test.ts(x)` de los archivos tocados, pasando sus rutas, y solo + cuando la tarea lo requiera. + +## Formato, lint y tipos + +- Revisar solo los archivos tocados: + `npx prettier --write ` y `npx eslint `. +- `npm run lint` formatea y corrige todo `src` (prettier + `eslint --fix`); `npm run lint:check` + revisa todo `src` sin corregir (es lo que corre CI). +- Tipos: `npm run ts-compile-check` (`tsc` de todo el proyecto). Lo corre el pre-commit de husky, + así que un error de tipos bloquea el commit. diff --git a/.claude/rules/conventions.md b/.claude/rules/conventions.md new file mode 100644 index 000000000..76c8050c0 --- /dev/null +++ b/.claude/rules/conventions.md @@ -0,0 +1,64 @@ +# Convenciones + +## Código + +- Componentes funcionales en PascalCase con export nombrado (`export function X(...)`); no se usa + `export default` en la librería (solo en las páginas de la documentación, que son lazy). +- Props tipadas con una interfaz `XProps`; exportarla si el consumidor la necesita. Valores por + defecto en la desestructuración (`size = 'md'`). +- Hooks `useX`. Sin componentes de clase. +- Funciones, hooks y componentes nuevos llevan JSDoc en español: qué hacen, y `@param`/`@returns` + cuando no es obvio. En componentes, `@example` con su uso (ver `Label`, `ModalButtons`). +- Pruebas y página de documentación obligatorias en todo lo nuevo (ver + `.claude/rules/testing/testing.md` y `.claude/rules/documentation/documentation.md`). + +## Compatibilidad (la librería corre en el front del consumidor) + +- Solo APIs de React 16.8 y JavaScript ES2019 (ver `.claude/rules/project-overview.md`). +- No cambiar la API pública sin avisar (ver `.claude/rules/architecture.md`): props nuevas siempre + opcionales y con un valor por defecto que mantenga el comportamiento actual. +- Sin estado global ni efectos fuera del componente (nada de `window.x = ...`, listeners sin + limpiar o `localStorage` sin necesidad): el componente vive dentro de la app del consumidor. + +## Textos + +- No hay sistema de traducciones. Los textos visibles que pueda necesitar cambiar el consumidor + se reciben por props con un valor por defecto en español + (`text?.seeMore.see ?? 'Ver más fechas en'`). + +## Estilos + +- Solo Chakra: `Box`/`Flex` + props/`sx`, colores y tokens con `vars('colors-...')` del tema + (`src/theme`), nunca hexadecimales sueltos si el color existe en el tema. +- Responsive con Chakra: + - Pocos atributos: valor por breakpoint en cada atributo, p. ej. `fontSize={{ base: '12px', md: '16px' }}`. + - Muchos cambios: agruparlos en `sx` con `'@media screen and (max-width: 640px)': { ... }`. + - En código nuevo, `useMediaQuery` solo cuando cambia la lógica o qué se renderiza, no para + estilos. El código existente que lo usa para estilos no se migra salvo que se pida. En las + pruebas `useMediaQuery` siempre devuelve `false` (`jest-setup.ts`). + - El punto de quiebre depende del componente; en el repo se usan 900px, 768px, 640px, 577px, + 480px y 425px, entre otros. +- No usar styled-components, `@emotion/styled`, scss ni css nuevos. + +## Rendimiento y accesibilidad (al escribir código) + +Lo esencial de las skills `react-best-practices` y `web-design-guidelines`; la revisión completa +se hace al final con `/revisar-desarrollo`. + +- No definir componentes dentro de otros componentes. +- Derivar valores durante el render en vez de `useEffect` + `setState`. +- Dependencias de efectos primitivas; no objetos ni arrays creados en el render. +- `useMemo`/`useCallback`/`memo` solo para cálculos caros o props de hijos memoizados. +- Condicionales con ternario cuando la condición puede ser `0` o `''` (no `&&`). +- Elementos clicables con `button`/`a` (no `div` con `onClick`); botones solo con ícono con + `aria-label`; imágenes con `alt`; inputs con label asociado. +- HTML recibido por props: sanitizar con `dompurify` antes de parsearlo con `html-react-parser`. + +## Qué NO hacer + +- No editar a mano `CHANGELOG.md` ni la versión de `package.json` (semantic-release). +- No editar `dist/` ni `coverage/` (generados). +- No agregar al repo archivos estáticos (imágenes, videos, audios, PDF): se suben a mano a + Cloudflare y se usan por URL (`https://cdn.eclass.com/...`). Si una tarea necesita uno, o se + detecta uno nuevo en los cambios, avisar al usuario de inmediato para que lo suba y entregue la + URL. Los íconos son componentes SVG en `src/atoms/Icons`. diff --git a/.claude/rules/documentation/documentation.md b/.claude/rules/documentation/documentation.md new file mode 100644 index 000000000..9afa306f6 --- /dev/null +++ b/.claude/rules/documentation/documentation.md @@ -0,0 +1,39 @@ +--- +paths: + - "src/documentation/**" +--- + +# Documentación (sitio de componentes) + +Sitio publicado en GitHub Pages en cada release (`npm run deploy`); en local, `npm run docu`. +Todo componente o funcionalidad nueva actualiza su página en el mismo cambio. + +## Página nueva + +1. Crear `src/documentation/pages//.tsx` (`Atoms`, `Molecules`, `Organisms`, + `Utils`) con un componente `View` exportado con nombre **y** `export default` + (la ruta lo carga con `React.lazy`). +2. Registrarla en `src/documentation/utils/routes.tsx`: + - `React.lazy(async () => await import('../pages//'))` bajo el comentario de + su nivel (`/** ORGANISMS */`, ...). + - Agregar `{ path: '//', label: '', component: }` en el array + `routes`, dentro de la sección de su nivel. El orden del array es el orden del menú. + +## Contenido + +- Importar el componente como lo haría el consumidor: desde `@/index`, `@atoms`, `@molecules` u + `@organisms`, no desde su archivo interno. +- Componentes de la documentación en `@/documentation/components`: + - `MyHeading`: nombre del componente. `MyTitle`: título de cada variante o prop. + - `MyText`: descripción en español (qué es, para qué se creó, cuándo usarlo). + - `Code`: `import` desde `@eclass/ui-kit` y el código de cada ejemplo. + - `ListComponent`: varias variantes en fila. `Notes`, `BoxCopy`: notas y textos copiables. +- Por cada variante o prop relevante: `MyTitle` + `MyText` + el ejemplo renderizado + su `Code`. +- Datos de ejemplo en una constante al final del archivo (ver `pages/Organisms/SimpleCourseBox.tsx`); + imágenes por URL de `https://cdn.eclass.com/...`, nunca archivos en el repo. + +## Al modificar un componente existente + +- Prop nueva o cambio de comportamiento: agregar o actualizar su sección (`MyTitle`, ejemplo y + `Code`) en la página del componente. +- Si el componente no tiene página, avisar al usuario antes de crearla. diff --git a/.claude/rules/git-workflow.md b/.claude/rules/git-workflow.md new file mode 100644 index 000000000..6d3c46cd7 --- /dev/null +++ b/.claude/rules/git-workflow.md @@ -0,0 +1,22 @@ +# Flujo de git + +- Commits con la skill `txt-commit`: `type(scope): resumen`, scope corto en minúsculas (dominio o + componente, p. ej. `modals`, `calendar`, `documentation`), resumen en español de ≤72 + caracteres. commitlint (`config-conventional`) valida el formato. +- Commit normal, con los hooks de husky activos (sin `-n`): + - pre-commit: `npm run ts-compile-check` y luego lint-staged, que ejecuta `npm run lint` + (prettier sobre todo `src` + `eslint --fix`). Puede dejar formateados archivos que no estaban + en el commit: revisar `git status` después de commitear. + - commit-msg: commitlint. +- semantic-release en `main` publica en npm y actualiza `CHANGELOG.md` y la versión + (`.releaserc.json` sin `releaseRules`, preset por defecto): `feat` → minor; `fix`/`perf` → + patch; `refactor`, `docs`, `test`, `chore`, etc. no publican versión. +- Cambio incompatible de la API pública (ver `.claude/rules/architecture.md`): `BREAKING CHANGE: ` en el cuerpo del commit → versión major. El preset por defecto (angular) no + reconoce el `!` del título por sí solo, así que el pie `BREAKING CHANGE:` es obligatorio. Confirmar con el usuario antes, porque obliga + a actualizar a todos los consumidores. +- Ramas: `fix|feat|feature|bugfix/` (las más usadas en el repo). +- Los PR se mergean a `main` con squash en GitHub; el título del PR queda como commit, por eso + debe cumplir el mismo formato. +- CI (GitHub Actions, `.github/workflows/nodejs.yml`) en cada push: `npm run lint:check` + + `npm run test`. En `main` además: build, release y deploy de la documentación a GitHub Pages. diff --git a/.claude/rules/project-overview.md b/.claude/rules/project-overview.md new file mode 100644 index 000000000..92583b734 --- /dev/null +++ b/.claude/rules/project-overview.md @@ -0,0 +1,29 @@ +# Resumen del proyecto + +## Qué es + +- `@eclass/ui-kit`: librería de componentes UI transversales de eClass, basada en el + [sistema de diseño](https://zeroheight.com/15698077d/p/48fae4-eclass-sistema-de-diseo). +- Se publica en npm (`dist/`, formatos ES y UMD + tipos `.d.ts`) y la consumen los fronts de + eClass, por ejemplo v8 (React 16.14). +- El mismo repo genera el sitio de documentación (`src/documentation`), publicado en GitHub Pages. + +## Stack + +- React 17.0.2 en desarrollo, pero `peerDependencies` acepta React `^16.8` a `^19`: todo el + código debe funcionar desde React 16.8 (solo hooks y APIs disponibles en esa versión; nada de + `useId`, `useTransition`, `useSyncExternalStore`, etc.). +- TypeScript 4.9 con `strict: true`. Target ES2019 (sin polyfills: nada de `toSorted`, `at`, etc.). +- UI: Chakra UI 1.8 + Emotion 11 + framer-motion 6 (los cuatro son `peerDependencies` y quedan + fuera del bundle). +- Otras dependencias: `date-fns` 4 (fechas), `html-react-parser` + `dompurify` (HTML recibido por + props), `react-hot-toast` (notificaciones), `react-ripples`. +- `@eclass/api` y `@eclass/sequelize-models` son solo tipos (`@types/eclass__*` por git+ssh). +- Build con Vite 2.9 (modo librería) + `tsc` para los tipos. +- Tests: Jest 27 + ts-jest + Testing Library. + +## Glosario de dominio + +- Átomos, moléculas y organismos: niveles del diseño atómico, uno por carpeta en `src/`. +- Consumidor: el front que instala la librería (v8 u otro). No tiene acceso a lo que no se + exporte desde `src/index.ts`. diff --git a/.claude/rules/testing/testing.md b/.claude/rules/testing/testing.md new file mode 100644 index 000000000..21088d104 --- /dev/null +++ b/.claude/rules/testing/testing.md @@ -0,0 +1,62 @@ +--- +paths: + - "src/**/*.test.ts" + - "src/**/*.test.tsx" +--- + +# Pruebas + +## Reglas generales + +- Obligatorias en todo componente o funcionalidad nueva. Archivo junto al código: + `X.test.ts` / `X.test.tsx`. +- Títulos de `describe`/`test` en español, describiendo el comportamiento esperado. Los títulos + existentes en inglés no se cambian salvo que se pida. +- Probar lo que el componente promete al consumidor: lo que renderiza según sus props, sus + callbacks (`onClick`, `onClose`...) y su accesibilidad (rol, foco, `aria-*`). +- Correr solo las pruebas tocadas con `npx jest ` (ver `.claude/rules/commands.md`). + +## Configuración global (`src/test/jest-setup.ts`) + +Afecta a todas las pruebas; no agregar ahí lógica de una prueba puntual. + +- Extiende `expect` con `@testing-library/jest-dom`. +- Mockea `react-ripples` y `dompurify` (no se valida la sanitización). +- `useMediaQuery` de Chakra siempre devuelve `[false]` (vista mobile). Para probar escritorio, + re-mockearlo en el archivo de prueba (ver `ModalAlert.test.tsx`). +- `css` y `keyframes` de Emotion devuelven `''`: no se pueden validar estilos. + +## Según qué se prueba + +| Qué | Librería | Funciones | +|---|---|---| +| Componente React | `@testing-library/react` (v12) | `render`, `screen`, `waitFor`, `within` | +| Interacción | `@testing-library/user-event` (v14) | `const user = userEvent.setup()`; `await user.click(...)`, `await user.type(...)` | +| Hook | no hay `renderHook` (RTL 12 sin `@testing-library/react-hooks`) | probarlo a través de un componente de prueba que lo use | +| Función / util `.ts` | solo Jest | `describe`, `test`, `expect`, `jest.fn` | + +- Preferir consultas accesibles: `getByRole`, `getByLabelText`, `getByText`; `getByTestId` solo + si no hay otra opción. +- Componentes que usan el tema, portales o modales de Chakra: envolver en `ChakraProvider` + (ver `renderWithChakra` en `ModalAlert.test.tsx`). +- Para estados con interacción (abrir/cerrar, foco al cerrar), usar un componente de prueba con + `useState` que controle el componente (ver `ModalAlertFocusHarness` en `ModalAlert.test.tsx`). + +```tsx +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' + +import { BtnTertiary } from './BtnTertiary' + +describe('BtnTertiary', () => { + const user = userEvent.setup() + + test('llama a onClick al hacer clic', async () => { + const onClick = jest.fn() + render(Texto) + + await user.click(screen.getByRole('button')) + expect(onClick).toHaveBeenCalledTimes(1) + }) +}) +``` diff --git a/.claude/skills/react-best-practices/SKILL.md b/.claude/skills/react-best-practices/SKILL.md new file mode 100644 index 000000000..db7dc2e48 --- /dev/null +++ b/.claude/skills/react-best-practices/SKILL.md @@ -0,0 +1,110 @@ +--- +name: react-best-practices +description: Guía de rendimiento para React adaptada a ui-kit (librería de componentes compatible desde React 16.8, target ES2019, sin Next.js ni SSR), basada en las reglas de Vercel Engineering. Úsala al escribir, revisar o refactorizar componentes y hooks de la librería, o al optimizar re-renders, listeners o tamaño del bundle. +license: MIT +metadata: + author: vercel (adaptada por eClass) + version: "1.0.0" +--- + +# Buenas prácticas de React (ui-kit) + +37 reglas de Vercel Engineering que aplican a una librería de componentes que corre dentro de la +app del consumidor, desde React 16.8. Se quitaron: + +- Las que requieren React 18/19, Next.js/RSC o SSR, y `bundle-barrel-imports` (ui-kit usa + barrels como convención y declara `sideEffects: false` para que el consumidor haga tree-shaking). +- `async-*`: los componentes no hacen peticiones; los datos llegan por props. +- `bundle-dynamic-imports`, `bundle-conditional`, `bundle-preload`, `bundle-defer-third-party`: + la librería se publica como un solo archivo (ES y UMD); dividir en chunks y cargar de forma + diferida es decisión del consumidor. + +Cada regla está en `rules/.md` con explicación y ejemplos incorrecto/correcto. Lee solo +las reglas relevantes para el código que estás tocando. + +## Adaptaciones obligatorias + +- Solo APIs de React 16.8: nada de `useId`, `useTransition`, `useDeferredValue`, + `useSyncExternalStore` ni `useEffectEvent`. En `advanced-event-handler-refs`, usar el patrón con + `useRef`. +- Target ES2019 sin polyfills: en `js-tosorted-immutable`, `js-length-check-first` y + `rerender-split-combined-hooks`, usar `[...arr].sort()` en vez de `toSorted()`. Tampoco `at()`, + `findLast()`, `structuredClone` ni `Object.groupBy`. +- `js-request-idle-callback`: siempre con el respaldo de `setTimeout` que muestra la regla + (Safari no tiene `requestIdleCallback`). +- `client-localstorage-schema`, `js-cache-storage`, `client-passive-event-listeners`: el + componente comparte `window`, `localStorage` y cookies con la app del consumidor. Envolver el + acceso a `localStorage` en `try/catch` (ver `CalendarDropdown/services/parseEvents.ts`), limpiar + los listeners al desmontar (ver `CourseList/utils/useEnterNavigate.ts`) y, en claves nuevas, usar + un prefijo propio para no chocar con las del consumidor. +- `rerender-memo-with-default-value`: aplica también a los valores por defecto de las props de la + librería (no crear objetos o arrays nuevos en la desestructuración si se pasan a hijos + memoizados o a dependencias de efectos). +- `rendering-svg-precision`, `rendering-animate-svg-wrapper`: aplican a los íconos de + `src/atoms/Icons`. +- Nunca recomendar una API que React 16.8 no tiene. Si actualizar React resolvería algo, + mencionarlo aparte como nota, no como hallazgo. + +## Reglas por prioridad + +### 1. Tamaño del bundle (CRÍTICO) — `bundle-` + +- `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces +- Dependencia nueva (no en `external` de `vite.config.ts`): entra al bundle de todos los + consumidores; evaluar su peso o una alternativa con lo que ya existe (Chakra, `date-fns`). + +### 2. Datos en el cliente (MEDIO-ALTO) — `client-` + +- `client-passive-event-listeners` - Use passive listeners for scroll +- `client-localstorage-schema` - Version and minimize localStorage data + +### 3. Re-renders (MEDIO) — `rerender-` + +- `rerender-defer-reads` - Don't subscribe to state only used in callbacks +- `rerender-memo` - Extract expensive work into memoized components +- `rerender-memo-with-default-value` - Hoist default non-primitive props +- `rerender-dependencies` - Use primitive dependencies in effects +- `rerender-derived-state` - Subscribe to derived booleans, not raw values +- `rerender-derived-state-no-effect` - Derive state during render, not effects +- `rerender-functional-setstate` - Use functional setState for stable callbacks +- `rerender-lazy-state-init` - Pass function to useState for expensive values +- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives +- `rerender-split-combined-hooks` - Split hooks with independent dependencies +- `rerender-move-effect-to-event` - Put interaction logic in event handlers +- `rerender-use-ref-transient-values` - Use refs for transient frequent values +- `rerender-no-inline-components` - Don't define components inside components + +### 4. Renderizado (MEDIO) — `rendering-` + +- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element +- `rendering-content-visibility` - Use content-visibility for long lists +- `rendering-hoist-jsx` - Extract static JSX outside components +- `rendering-svg-precision` - Reduce SVG coordinate precision +- `rendering-conditional-render` - Use ternary, not && for conditionals + +### 5. JavaScript (BAJO-MEDIO) — `js-` + +- `js-batch-dom-css` - Group CSS changes via classes or cssText +- `js-index-maps` - Build Map for repeated lookups +- `js-cache-property-access` - Cache object properties in loops +- `js-cache-function-results` - Cache function results in module-level Map +- `js-cache-storage` - Cache localStorage/sessionStorage reads +- `js-combine-iterations` - Combine multiple filter/map into one loop +- `js-length-check-first` - Check array length before expensive comparison +- `js-early-exit` - Return early from functions +- `js-hoist-regexp` - Hoist RegExp creation outside loops +- `js-min-max-loop` - Use loop for min/max instead of sort +- `js-set-map-lookups` - Use Set/Map for O(1) lookups +- `js-tosorted-immutable` - Immutable sort (en ui-kit: `[...arr].sort()`) +- `js-flatmap-filter` - Use flatMap to map and filter in one pass +- `js-request-idle-callback` - Defer non-critical work to browser idle time + +### 6. Patrones avanzados (BAJO) — `advanced-` + +- `advanced-event-handler-refs` - Store event handlers in refs +- `advanced-init-once` - Initialize app once per app load + +## Al reportar una revisión + +Indica la regla (`rules/.md`), el `archivo:línea` y la corrección adaptada a React 16.8 y +ES2019. diff --git a/.claude/skills/react-best-practices/rules/advanced-event-handler-refs.md b/.claude/skills/react-best-practices/rules/advanced-event-handler-refs.md new file mode 100644 index 000000000..97e7ade24 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/advanced-event-handler-refs.md @@ -0,0 +1,55 @@ +--- +title: Store Event Handlers in Refs +impact: LOW +impactDescription: stable subscriptions +tags: advanced, hooks, refs, event-handlers, optimization +--- + +## Store Event Handlers in Refs + +Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes. + +**Incorrect (re-subscribes on every render):** + +```tsx +function useWindowEvent(event: string, handler: (e) => void) { + useEffect(() => { + window.addEventListener(event, handler) + return () => window.removeEventListener(event, handler) + }, [event, handler]) +} +``` + +**Correct (stable subscription):** + +```tsx +function useWindowEvent(event: string, handler: (e) => void) { + const handlerRef = useRef(handler) + useEffect(() => { + handlerRef.current = handler + }, [handler]) + + useEffect(() => { + const listener = (e) => handlerRef.current(e) + window.addEventListener(event, listener) + return () => window.removeEventListener(event, listener) + }, [event]) +} +``` + +**Alternative: use `useEffectEvent` if you're on latest React:** + +```tsx +import { useEffectEvent } from 'react' + +function useWindowEvent(event: string, handler: (e) => void) { + const onEvent = useEffectEvent(handler) + + useEffect(() => { + window.addEventListener(event, onEvent) + return () => window.removeEventListener(event, onEvent) + }, [event]) +} +``` + +`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler. diff --git a/.claude/skills/react-best-practices/rules/advanced-init-once.md b/.claude/skills/react-best-practices/rules/advanced-init-once.md new file mode 100644 index 000000000..73ee38e5e --- /dev/null +++ b/.claude/skills/react-best-practices/rules/advanced-init-once.md @@ -0,0 +1,42 @@ +--- +title: Initialize App Once, Not Per Mount +impact: LOW-MEDIUM +impactDescription: avoids duplicate init in development +tags: initialization, useEffect, app-startup, side-effects +--- + +## Initialize App Once, Not Per Mount + +Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead. + +**Incorrect (runs twice in dev, re-runs on remount):** + +```tsx +function Comp() { + useEffect(() => { + loadFromStorage() + checkAuthToken() + }, []) + + // ... +} +``` + +**Correct (once per app load):** + +```tsx +let didInit = false + +function Comp() { + useEffect(() => { + if (didInit) return + didInit = true + loadFromStorage() + checkAuthToken() + }, []) + + // ... +} +``` + +Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application) diff --git a/.claude/skills/react-best-practices/rules/bundle-analyzable-paths.md b/.claude/skills/react-best-practices/rules/bundle-analyzable-paths.md new file mode 100644 index 000000000..8276f156c --- /dev/null +++ b/.claude/skills/react-best-practices/rules/bundle-analyzable-paths.md @@ -0,0 +1,63 @@ +--- +title: Prefer Statically Analyzable Paths +impact: HIGH +impactDescription: avoids accidental broad bundles and file traces +tags: bundle, nextjs, vite, webpack, rollup, esbuild, path +--- + +## Prefer Statically Analyzable Paths + +Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe. + +Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code. + +When analysis becomes too broad, the cost is real: +- Larger server bundles +- Slower builds +- Worse cold starts +- More memory use + +### Import Paths + +**Incorrect (the bundler cannot tell what may be imported):** + +```ts +const PAGE_MODULES = { + home: './pages/home', + settings: './pages/settings', +} as const + +const Page = await import(PAGE_MODULES[pageName]) +``` + +**Correct (use an explicit map of allowed modules):** + +```ts +const PAGE_MODULES = { + home: () => import('./pages/home'), + settings: () => import('./pages/settings'), +} as const + +const Page = await PAGE_MODULES[pageName]() +``` + +### File-System Paths + +**Incorrect (a 2-value enum still hides the final path from static analysis):** + +```ts +const baseDir = path.join(process.cwd(), 'content/' + contentKind) +``` + +**Correct (make each final path literal at the callsite):** + +```ts +const baseDir = + kind === ContentKind.Blog + ? path.join(process.cwd(), 'content/blog') + : path.join(process.cwd(), 'content/docs') +``` + +In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage. + +Reference: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/) diff --git a/.claude/skills/react-best-practices/rules/client-localstorage-schema.md b/.claude/skills/react-best-practices/rules/client-localstorage-schema.md new file mode 100644 index 000000000..d30a1a7d4 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/client-localstorage-schema.md @@ -0,0 +1,71 @@ +--- +title: Version and Minimize localStorage Data +impact: MEDIUM +impactDescription: prevents schema conflicts, reduces storage size +tags: client, localStorage, storage, versioning, data-minimization +--- + +## Version and Minimize localStorage Data + +Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data. + +**Incorrect:** + +```typescript +// No version, stores everything, no error handling +localStorage.setItem('userConfig', JSON.stringify(fullUserObject)) +const data = localStorage.getItem('userConfig') +``` + +**Correct:** + +```typescript +const VERSION = 'v2' + +function saveConfig(config: { theme: string; language: string }) { + try { + localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config)) + } catch { + // Throws in incognito/private browsing, quota exceeded, or disabled + } +} + +function loadConfig() { + try { + const data = localStorage.getItem(`userConfig:${VERSION}`) + return data ? JSON.parse(data) : null + } catch { + return null + } +} + +// Migration from v1 to v2 +function migrate() { + try { + const v1 = localStorage.getItem('userConfig:v1') + if (v1) { + const old = JSON.parse(v1) + saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang }) + localStorage.removeItem('userConfig:v1') + } + } catch {} +} +``` + +**Store minimal fields from server responses:** + +```typescript +// User object has 20+ fields, only store what UI needs +function cachePrefs(user: FullUser) { + try { + localStorage.setItem('prefs:v1', JSON.stringify({ + theme: user.preferences.theme, + notifications: user.preferences.notifications + })) + } catch {} +} +``` + +**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled. + +**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags. diff --git a/.claude/skills/react-best-practices/rules/client-passive-event-listeners.md b/.claude/skills/react-best-practices/rules/client-passive-event-listeners.md new file mode 100644 index 000000000..ce39a889e --- /dev/null +++ b/.claude/skills/react-best-practices/rules/client-passive-event-listeners.md @@ -0,0 +1,48 @@ +--- +title: Use Passive Event Listeners for Scrolling Performance +impact: MEDIUM +impactDescription: eliminates scroll delay caused by event listeners +tags: client, event-listeners, scrolling, performance, touch, wheel +--- + +## Use Passive Event Listeners for Scrolling Performance + +Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay. + +**Incorrect:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) + const handleWheel = (e: WheelEvent) => console.log(e.deltaY) + + document.addEventListener('touchstart', handleTouch) + document.addEventListener('wheel', handleWheel) + + return () => { + document.removeEventListener('touchstart', handleTouch) + document.removeEventListener('wheel', handleWheel) + } +}, []) +``` + +**Correct:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) + const handleWheel = (e: WheelEvent) => console.log(e.deltaY) + + document.addEventListener('touchstart', handleTouch, { passive: true }) + document.addEventListener('wheel', handleWheel, { passive: true }) + + return () => { + document.removeEventListener('touchstart', handleTouch) + document.removeEventListener('wheel', handleWheel) + } +}, []) +``` + +**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`. + +**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`. diff --git a/.claude/skills/react-best-practices/rules/js-batch-dom-css.md b/.claude/skills/react-best-practices/rules/js-batch-dom-css.md new file mode 100644 index 000000000..a62d84ed8 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-batch-dom-css.md @@ -0,0 +1,107 @@ +--- +title: Avoid Layout Thrashing +impact: MEDIUM +impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks +tags: javascript, dom, css, performance, reflow, layout-thrashing +--- + +## Avoid Layout Thrashing + +Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow. + +**This is OK (browser batches style changes):** +```typescript +function updateElementStyles(element: HTMLElement) { + // Each line invalidates style, but browser batches the recalculation + element.style.width = '100px' + element.style.height = '200px' + element.style.backgroundColor = 'blue' + element.style.border = '1px solid black' +} +``` + +**Incorrect (interleaved reads and writes force reflows):** +```typescript +function layoutThrashing(element: HTMLElement) { + element.style.width = '100px' + const width = element.offsetWidth // Forces reflow + element.style.height = '200px' + const height = element.offsetHeight // Forces another reflow +} +``` + +**Correct (batch writes, then read once):** +```typescript +function updateElementStyles(element: HTMLElement) { + // Batch all writes together + element.style.width = '100px' + element.style.height = '200px' + element.style.backgroundColor = 'blue' + element.style.border = '1px solid black' + + // Read after all writes are done (single reflow) + const { width, height } = element.getBoundingClientRect() +} +``` + +**Correct (batch reads, then writes):** +```typescript +function avoidThrashing(element: HTMLElement) { + // Read phase - all layout queries first + const rect1 = element.getBoundingClientRect() + const offsetWidth = element.offsetWidth + const offsetHeight = element.offsetHeight + + // Write phase - all style changes after + element.style.width = '100px' + element.style.height = '200px' +} +``` + +**Better: use CSS classes** +```css +.highlighted-box { + width: 100px; + height: 200px; + background-color: blue; + border: 1px solid black; +} +``` +```typescript +function updateElementStyles(element: HTMLElement) { + element.classList.add('highlighted-box') + + const { width, height } = element.getBoundingClientRect() +} +``` + +**React example:** +```tsx +// Incorrect: interleaving style changes with layout queries +function Box({ isHighlighted }: { isHighlighted: boolean }) { + const ref = useRef(null) + + useEffect(() => { + if (ref.current && isHighlighted) { + ref.current.style.width = '100px' + const width = ref.current.offsetWidth // Forces layout + ref.current.style.height = '200px' + } + }, [isHighlighted]) + + return
Content
+} + +// Correct: toggle class +function Box({ isHighlighted }: { isHighlighted: boolean }) { + return ( +
+ Content +
+ ) +} +``` + +Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain. + +See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations. diff --git a/.claude/skills/react-best-practices/rules/js-cache-function-results.md b/.claude/skills/react-best-practices/rules/js-cache-function-results.md new file mode 100644 index 000000000..180f8ac8f --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-cache-function-results.md @@ -0,0 +1,80 @@ +--- +title: Cache Repeated Function Calls +impact: MEDIUM +impactDescription: avoid redundant computation +tags: javascript, cache, memoization, performance +--- + +## Cache Repeated Function Calls + +Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render. + +**Incorrect (redundant computation):** + +```typescript +function ProjectList({ projects }: { projects: Project[] }) { + return ( +
+ {projects.map(project => { + // slugify() called 100+ times for same project names + const slug = slugify(project.name) + + return + })} +
+ ) +} +``` + +**Correct (cached results):** + +```typescript +// Module-level cache +const slugifyCache = new Map() + +function cachedSlugify(text: string): string { + if (slugifyCache.has(text)) { + return slugifyCache.get(text)! + } + const result = slugify(text) + slugifyCache.set(text, result) + return result +} + +function ProjectList({ projects }: { projects: Project[] }) { + return ( +
+ {projects.map(project => { + // Computed only once per unique project name + const slug = cachedSlugify(project.name) + + return + })} +
+ ) +} +``` + +**Simpler pattern for single-value functions:** + +```typescript +let isLoggedInCache: boolean | null = null + +function isLoggedIn(): boolean { + if (isLoggedInCache !== null) { + return isLoggedInCache + } + + isLoggedInCache = document.cookie.includes('auth=') + return isLoggedInCache +} + +// Clear cache when auth changes +function onAuthChange() { + isLoggedInCache = null +} +``` + +Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components. + +Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast) diff --git a/.claude/skills/react-best-practices/rules/js-cache-property-access.md b/.claude/skills/react-best-practices/rules/js-cache-property-access.md new file mode 100644 index 000000000..39eec9061 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-cache-property-access.md @@ -0,0 +1,28 @@ +--- +title: Cache Property Access in Loops +impact: LOW-MEDIUM +impactDescription: reduces lookups +tags: javascript, loops, optimization, caching +--- + +## Cache Property Access in Loops + +Cache object property lookups in hot paths. + +**Incorrect (3 lookups × N iterations):** + +```typescript +for (let i = 0; i < arr.length; i++) { + process(obj.config.settings.value) +} +``` + +**Correct (1 lookup total):** + +```typescript +const value = obj.config.settings.value +const len = arr.length +for (let i = 0; i < len; i++) { + process(value) +} +``` diff --git a/.claude/skills/react-best-practices/rules/js-cache-storage.md b/.claude/skills/react-best-practices/rules/js-cache-storage.md new file mode 100644 index 000000000..aa4a30c08 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-cache-storage.md @@ -0,0 +1,70 @@ +--- +title: Cache Storage API Calls +impact: LOW-MEDIUM +impactDescription: reduces expensive I/O +tags: javascript, localStorage, storage, caching, performance +--- + +## Cache Storage API Calls + +`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory. + +**Incorrect (reads storage on every call):** + +```typescript +function getTheme() { + return localStorage.getItem('theme') ?? 'light' +} +// Called 10 times = 10 storage reads +``` + +**Correct (Map cache):** + +```typescript +const storageCache = new Map() + +function getLocalStorage(key: string) { + if (!storageCache.has(key)) { + storageCache.set(key, localStorage.getItem(key)) + } + return storageCache.get(key) +} + +function setLocalStorage(key: string, value: string) { + localStorage.setItem(key, value) + storageCache.set(key, value) // keep cache in sync +} +``` + +Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components. + +**Cookie caching:** + +```typescript +let cookieCache: Record | null = null + +function getCookie(name: string) { + if (!cookieCache) { + cookieCache = Object.fromEntries( + document.cookie.split('; ').map(c => c.split('=')) + ) + } + return cookieCache[name] +} +``` + +**Important (invalidate on external changes):** + +If storage can change externally (another tab, server-set cookies), invalidate cache: + +```typescript +window.addEventListener('storage', (e) => { + if (e.key) storageCache.delete(e.key) +}) + +document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible') { + storageCache.clear() + } +}) +``` diff --git a/.claude/skills/react-best-practices/rules/js-combine-iterations.md b/.claude/skills/react-best-practices/rules/js-combine-iterations.md new file mode 100644 index 000000000..044d017ec --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-combine-iterations.md @@ -0,0 +1,32 @@ +--- +title: Combine Multiple Array Iterations +impact: LOW-MEDIUM +impactDescription: reduces iterations +tags: javascript, arrays, loops, performance +--- + +## Combine Multiple Array Iterations + +Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop. + +**Incorrect (3 iterations):** + +```typescript +const admins = users.filter(u => u.isAdmin) +const testers = users.filter(u => u.isTester) +const inactive = users.filter(u => !u.isActive) +``` + +**Correct (1 iteration):** + +```typescript +const admins: User[] = [] +const testers: User[] = [] +const inactive: User[] = [] + +for (const user of users) { + if (user.isAdmin) admins.push(user) + if (user.isTester) testers.push(user) + if (!user.isActive) inactive.push(user) +} +``` diff --git a/.claude/skills/react-best-practices/rules/js-early-exit.md b/.claude/skills/react-best-practices/rules/js-early-exit.md new file mode 100644 index 000000000..f46cb89c6 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-early-exit.md @@ -0,0 +1,50 @@ +--- +title: Early Return from Functions +impact: LOW-MEDIUM +impactDescription: avoids unnecessary computation +tags: javascript, functions, optimization, early-return +--- + +## Early Return from Functions + +Return early when result is determined to skip unnecessary processing. + +**Incorrect (processes all items even after finding answer):** + +```typescript +function validateUsers(users: User[]) { + let hasError = false + let errorMessage = '' + + for (const user of users) { + if (!user.email) { + hasError = true + errorMessage = 'Email required' + } + if (!user.name) { + hasError = true + errorMessage = 'Name required' + } + // Continues checking all users even after error found + } + + return hasError ? { valid: false, error: errorMessage } : { valid: true } +} +``` + +**Correct (returns immediately on first error):** + +```typescript +function validateUsers(users: User[]) { + for (const user of users) { + if (!user.email) { + return { valid: false, error: 'Email required' } + } + if (!user.name) { + return { valid: false, error: 'Name required' } + } + } + + return { valid: true } +} +``` diff --git a/.claude/skills/react-best-practices/rules/js-flatmap-filter.md b/.claude/skills/react-best-practices/rules/js-flatmap-filter.md new file mode 100644 index 000000000..ee0edf0da --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-flatmap-filter.md @@ -0,0 +1,60 @@ +--- +title: Use flatMap to Map and Filter in One Pass +impact: LOW-MEDIUM +impactDescription: eliminates intermediate array +tags: javascript, arrays, flatMap, filter, performance +--- + +## Use flatMap to Map and Filter in One Pass + +**Impact: LOW-MEDIUM (eliminates intermediate array)** + +Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass. + +**Incorrect (2 iterations, intermediate array):** + +```typescript +const userNames = users + .map(user => user.isActive ? user.name : null) + .filter(Boolean) +``` + +**Correct (1 iteration, no intermediate array):** + +```typescript +const userNames = users.flatMap(user => + user.isActive ? [user.name] : [] +) +``` + +**More examples:** + +```typescript +// Extract valid emails from responses +// Before +const emails = responses + .map(r => r.success ? r.data.email : null) + .filter(Boolean) + +// After +const emails = responses.flatMap(r => + r.success ? [r.data.email] : [] +) + +// Parse and filter valid numbers +// Before +const numbers = strings + .map(s => parseInt(s, 10)) + .filter(n => !isNaN(n)) + +// After +const numbers = strings.flatMap(s => { + const n = parseInt(s, 10) + return isNaN(n) ? [] : [n] +}) +``` + +**When to use:** +- Transforming items while filtering some out +- Conditional mapping where some inputs produce no output +- Parsing/validating where invalid inputs should be skipped diff --git a/.claude/skills/react-best-practices/rules/js-hoist-regexp.md b/.claude/skills/react-best-practices/rules/js-hoist-regexp.md new file mode 100644 index 000000000..dae3fefdc --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-hoist-regexp.md @@ -0,0 +1,45 @@ +--- +title: Hoist RegExp Creation +impact: LOW-MEDIUM +impactDescription: avoids recreation +tags: javascript, regexp, optimization, memoization +--- + +## Hoist RegExp Creation + +Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`. + +**Incorrect (new RegExp every render):** + +```tsx +function Highlighter({ text, query }: Props) { + const regex = new RegExp(`(${query})`, 'gi') + const parts = text.split(regex) + return <>{parts.map((part, i) => ...)} +} +``` + +**Correct (memoize or hoist):** + +```tsx +const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ + +function Highlighter({ text, query }: Props) { + const regex = useMemo( + () => new RegExp(`(${escapeRegex(query)})`, 'gi'), + [query] + ) + const parts = text.split(regex) + return <>{parts.map((part, i) => ...)} +} +``` + +**Warning (global regex has mutable state):** + +Global regex (`/g`) has mutable `lastIndex` state: + +```typescript +const regex = /foo/g +regex.test('foo') // true, lastIndex = 3 +regex.test('foo') // false, lastIndex = 0 +``` diff --git a/.claude/skills/react-best-practices/rules/js-index-maps.md b/.claude/skills/react-best-practices/rules/js-index-maps.md new file mode 100644 index 000000000..9d357a00b --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-index-maps.md @@ -0,0 +1,37 @@ +--- +title: Build Index Maps for Repeated Lookups +impact: LOW-MEDIUM +impactDescription: 1M ops to 2K ops +tags: javascript, map, indexing, optimization, performance +--- + +## Build Index Maps for Repeated Lookups + +Multiple `.find()` calls by the same key should use a Map. + +**Incorrect (O(n) per lookup):** + +```typescript +function processOrders(orders: Order[], users: User[]) { + return orders.map(order => ({ + ...order, + user: users.find(u => u.id === order.userId) + })) +} +``` + +**Correct (O(1) per lookup):** + +```typescript +function processOrders(orders: Order[], users: User[]) { + const userById = new Map(users.map(u => [u.id, u])) + + return orders.map(order => ({ + ...order, + user: userById.get(order.userId) + })) +} +``` + +Build map once (O(n)), then all lookups are O(1). +For 1000 orders × 1000 users: 1M ops → 2K ops. diff --git a/.claude/skills/react-best-practices/rules/js-length-check-first.md b/.claude/skills/react-best-practices/rules/js-length-check-first.md new file mode 100644 index 000000000..8b8957363 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-length-check-first.md @@ -0,0 +1,49 @@ +--- +title: Early Length Check for Array Comparisons +impact: MEDIUM-HIGH +impactDescription: avoids expensive operations when lengths differ +tags: javascript, arrays, performance, optimization, comparison +--- + +## Early Length Check for Array Comparisons + +When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal. + +In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops). + +**Incorrect (always runs expensive comparison):** + +```typescript +function hasChanges(current: string[], original: string[]) { + // Always sorts and joins, even when lengths differ + return current.sort().join() !== original.sort().join() +} +``` + +Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings. + +**Correct (O(1) length check first):** + +```typescript +function hasChanges(current: string[], original: string[]) { + // Early return if lengths differ + if (current.length !== original.length) { + return true + } + // Only sort when lengths match + const currentSorted = current.toSorted() + const originalSorted = original.toSorted() + for (let i = 0; i < currentSorted.length; i++) { + if (currentSorted[i] !== originalSorted[i]) { + return true + } + } + return false +} +``` + +This new approach is more efficient because: +- It avoids the overhead of sorting and joining the arrays when lengths differ +- It avoids consuming memory for the joined strings (especially important for large arrays) +- It avoids mutating the original arrays +- It returns early when a difference is found diff --git a/.claude/skills/react-best-practices/rules/js-min-max-loop.md b/.claude/skills/react-best-practices/rules/js-min-max-loop.md new file mode 100644 index 000000000..4b6656e96 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-min-max-loop.md @@ -0,0 +1,82 @@ +--- +title: Use Loop for Min/Max Instead of Sort +impact: LOW +impactDescription: O(n) instead of O(n log n) +tags: javascript, arrays, performance, sorting, algorithms +--- + +## Use Loop for Min/Max Instead of Sort + +Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower. + +**Incorrect (O(n log n) - sort to find latest):** + +```typescript +interface Project { + id: string + name: string + updatedAt: number +} + +function getLatestProject(projects: Project[]) { + const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt) + return sorted[0] +} +``` + +Sorts the entire array just to find the maximum value. + +**Incorrect (O(n log n) - sort for oldest and newest):** + +```typescript +function getOldestAndNewest(projects: Project[]) { + const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt) + return { oldest: sorted[0], newest: sorted[sorted.length - 1] } +} +``` + +Still sorts unnecessarily when only min/max are needed. + +**Correct (O(n) - single loop):** + +```typescript +function getLatestProject(projects: Project[]) { + if (projects.length === 0) return null + + let latest = projects[0] + + for (let i = 1; i < projects.length; i++) { + if (projects[i].updatedAt > latest.updatedAt) { + latest = projects[i] + } + } + + return latest +} + +function getOldestAndNewest(projects: Project[]) { + if (projects.length === 0) return { oldest: null, newest: null } + + let oldest = projects[0] + let newest = projects[0] + + for (let i = 1; i < projects.length; i++) { + if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i] + if (projects[i].updatedAt > newest.updatedAt) newest = projects[i] + } + + return { oldest, newest } +} +``` + +Single pass through the array, no copying, no sorting. + +**Alternative (Math.min/Math.max for small arrays):** + +```typescript +const numbers = [5, 2, 8, 1, 9] +const min = Math.min(...numbers) +const max = Math.max(...numbers) +``` + +This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability. diff --git a/.claude/skills/react-best-practices/rules/js-request-idle-callback.md b/.claude/skills/react-best-practices/rules/js-request-idle-callback.md new file mode 100644 index 000000000..d81927e5f --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-request-idle-callback.md @@ -0,0 +1,105 @@ +--- +title: Defer Non-Critical Work with requestIdleCallback +impact: MEDIUM +impactDescription: keeps UI responsive during background tasks +tags: javascript, performance, idle, scheduling, analytics +--- + +## Defer Non-Critical Work with requestIdleCallback + +**Impact: MEDIUM (keeps UI responsive during background tasks)** + +Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance. + +**Incorrect (blocks main thread during user interaction):** + +```typescript +function handleSearch(query: string) { + const results = searchItems(query) + setResults(results) + + // These block the main thread immediately + analytics.track('search', { query }) + saveToRecentSearches(query) + prefetchTopResults(results.slice(0, 3)) +} +``` + +**Correct (defers non-critical work to idle time):** + +```typescript +function handleSearch(query: string) { + const results = searchItems(query) + setResults(results) + + // Defer non-critical work to idle periods + requestIdleCallback(() => { + analytics.track('search', { query }) + }) + + requestIdleCallback(() => { + saveToRecentSearches(query) + }) + + requestIdleCallback(() => { + prefetchTopResults(results.slice(0, 3)) + }) +} +``` + +**With timeout for required work:** + +```typescript +// Ensure analytics fires within 2 seconds even if browser stays busy +requestIdleCallback( + () => analytics.track('page_view', { path: location.pathname }), + { timeout: 2000 } +) +``` + +**Chunking large tasks:** + +```typescript +function processLargeDataset(items: Item[]) { + let index = 0 + + function processChunk(deadline: IdleDeadline) { + // Process items while we have idle time (aim for <50ms chunks) + while (index < items.length && deadline.timeRemaining() > 0) { + processItem(items[index]) + index++ + } + + // Schedule next chunk if more items remain + if (index < items.length) { + requestIdleCallback(processChunk) + } + } + + requestIdleCallback(processChunk) +} +``` + +**With fallback for unsupported browsers:** + +```typescript +const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1)) + +scheduleIdleWork(() => { + // Non-critical work +}) +``` + +**When to use:** + +- Analytics and telemetry +- Saving state to localStorage/IndexedDB +- Prefetching resources for likely next actions +- Processing non-urgent data transformations +- Lazy initialization of non-critical features + +**When NOT to use:** + +- User-initiated actions that need immediate feedback +- Rendering updates the user is waiting for +- Time-sensitive operations diff --git a/.claude/skills/react-best-practices/rules/js-set-map-lookups.md b/.claude/skills/react-best-practices/rules/js-set-map-lookups.md new file mode 100644 index 000000000..680a4892e --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-set-map-lookups.md @@ -0,0 +1,24 @@ +--- +title: Use Set/Map for O(1) Lookups +impact: LOW-MEDIUM +impactDescription: O(n) to O(1) +tags: javascript, set, map, data-structures, performance +--- + +## Use Set/Map for O(1) Lookups + +Convert arrays to Set/Map for repeated membership checks. + +**Incorrect (O(n) per check):** + +```typescript +const allowedIds = ['a', 'b', 'c', ...] +items.filter(item => allowedIds.includes(item.id)) +``` + +**Correct (O(1) per check):** + +```typescript +const allowedIds = new Set(['a', 'b', 'c', ...]) +items.filter(item => allowedIds.has(item.id)) +``` diff --git a/.claude/skills/react-best-practices/rules/js-tosorted-immutable.md b/.claude/skills/react-best-practices/rules/js-tosorted-immutable.md new file mode 100644 index 000000000..eae8b3f8a --- /dev/null +++ b/.claude/skills/react-best-practices/rules/js-tosorted-immutable.md @@ -0,0 +1,57 @@ +--- +title: Use toSorted() Instead of sort() for Immutability +impact: MEDIUM-HIGH +impactDescription: prevents mutation bugs in React state +tags: javascript, arrays, immutability, react, state, mutation +--- + +## Use toSorted() Instead of sort() for Immutability + +`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation. + +**Incorrect (mutates original array):** + +```typescript +function UserList({ users }: { users: User[] }) { + // Mutates the users prop array! + const sorted = useMemo( + () => users.sort((a, b) => a.name.localeCompare(b.name)), + [users] + ) + return
{sorted.map(renderUser)}
+} +``` + +**Correct (creates new array):** + +```typescript +function UserList({ users }: { users: User[] }) { + // Creates new sorted array, original unchanged + const sorted = useMemo( + () => users.toSorted((a, b) => a.name.localeCompare(b.name)), + [users] + ) + return
{sorted.map(renderUser)}
+} +``` + +**Why this matters in React:** + +1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only +2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior + +**Browser support (fallback for older browsers):** + +`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator: + +```typescript +// Fallback for older browsers +const sorted = [...items].sort((a, b) => a.value - b.value) +``` + +**Other immutable array methods:** + +- `.toSorted()` - immutable sort +- `.toReversed()` - immutable reverse +- `.toSpliced()` - immutable splice +- `.with()` - immutable element replacement diff --git a/.claude/skills/react-best-practices/rules/rendering-animate-svg-wrapper.md b/.claude/skills/react-best-practices/rules/rendering-animate-svg-wrapper.md new file mode 100644 index 000000000..646744cbe --- /dev/null +++ b/.claude/skills/react-best-practices/rules/rendering-animate-svg-wrapper.md @@ -0,0 +1,47 @@ +--- +title: Animate SVG Wrapper Instead of SVG Element +impact: LOW +impactDescription: enables hardware acceleration +tags: rendering, svg, css, animation, performance +--- + +## Animate SVG Wrapper Instead of SVG Element + +Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `
` and animate the wrapper instead. + +**Incorrect (animating SVG directly - no hardware acceleration):** + +```tsx +function LoadingSpinner() { + return ( + + + + ) +} +``` + +**Correct (animating wrapper div - hardware accelerated):** + +```tsx +function LoadingSpinner() { + return ( +
+ + + +
+ ) +} +``` + +This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations. diff --git a/.claude/skills/react-best-practices/rules/rendering-conditional-render.md b/.claude/skills/react-best-practices/rules/rendering-conditional-render.md new file mode 100644 index 000000000..7e866f585 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/rendering-conditional-render.md @@ -0,0 +1,40 @@ +--- +title: Use Explicit Conditional Rendering +impact: LOW +impactDescription: prevents rendering 0 or NaN +tags: rendering, conditional, jsx, falsy-values +--- + +## Use Explicit Conditional Rendering + +Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render. + +**Incorrect (renders "0" when count is 0):** + +```tsx +function Badge({ count }: { count: number }) { + return ( +
+ {count && {count}} +
+ ) +} + +// When count = 0, renders:
0
+// When count = 5, renders:
5
+``` + +**Correct (renders nothing when count is 0):** + +```tsx +function Badge({ count }: { count: number }) { + return ( +
+ {count > 0 ? {count} : null} +
+ ) +} + +// When count = 0, renders:
+// When count = 5, renders:
5
+``` diff --git a/.claude/skills/react-best-practices/rules/rendering-content-visibility.md b/.claude/skills/react-best-practices/rules/rendering-content-visibility.md new file mode 100644 index 000000000..aa6656362 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/rendering-content-visibility.md @@ -0,0 +1,38 @@ +--- +title: CSS content-visibility for Long Lists +impact: HIGH +impactDescription: faster initial render +tags: rendering, css, content-visibility, long-lists +--- + +## CSS content-visibility for Long Lists + +Apply `content-visibility: auto` to defer off-screen rendering. + +**CSS:** + +```css +.message-item { + content-visibility: auto; + contain-intrinsic-size: 0 80px; +} +``` + +**Example:** + +```tsx +function MessageList({ messages }: { messages: Message[] }) { + return ( +
+ {messages.map(msg => ( +
+ +
{msg.content}
+
+ ))} +
+ ) +} +``` + +For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render). diff --git a/.claude/skills/react-best-practices/rules/rendering-hoist-jsx.md b/.claude/skills/react-best-practices/rules/rendering-hoist-jsx.md new file mode 100644 index 000000000..32d2f3fce --- /dev/null +++ b/.claude/skills/react-best-practices/rules/rendering-hoist-jsx.md @@ -0,0 +1,46 @@ +--- +title: Hoist Static JSX Elements +impact: LOW +impactDescription: avoids re-creation +tags: rendering, jsx, static, optimization +--- + +## Hoist Static JSX Elements + +Extract static JSX outside components to avoid re-creation. + +**Incorrect (recreates element every render):** + +```tsx +function LoadingSkeleton() { + return
+} + +function Container() { + return ( +
+ {loading && } +
+ ) +} +``` + +**Correct (reuses same element):** + +```tsx +const loadingSkeleton = ( +
+) + +function Container() { + return ( +
+ {loading && loadingSkeleton} +
+ ) +} +``` + +This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render. + +**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary. diff --git a/.claude/skills/react-best-practices/rules/rendering-svg-precision.md b/.claude/skills/react-best-practices/rules/rendering-svg-precision.md new file mode 100644 index 000000000..6d7712860 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/rendering-svg-precision.md @@ -0,0 +1,28 @@ +--- +title: Optimize SVG Precision +impact: LOW +impactDescription: reduces file size +tags: rendering, svg, optimization, svgo +--- + +## Optimize SVG Precision + +Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered. + +**Incorrect (excessive precision):** + +```svg + +``` + +**Correct (1 decimal place):** + +```svg + +``` + +**Automate with SVGO:** + +```bash +npx svgo --precision=1 --multipass icon.svg +``` diff --git a/.claude/skills/react-best-practices/rules/rerender-defer-reads.md b/.claude/skills/react-best-practices/rules/rerender-defer-reads.md new file mode 100644 index 000000000..e867c95f0 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/rerender-defer-reads.md @@ -0,0 +1,39 @@ +--- +title: Defer State Reads to Usage Point +impact: MEDIUM +impactDescription: avoids unnecessary subscriptions +tags: rerender, searchParams, localStorage, optimization +--- + +## Defer State Reads to Usage Point + +Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks. + +**Incorrect (subscribes to all searchParams changes):** + +```tsx +function ShareButton({ chatId }: { chatId: string }) { + const searchParams = useSearchParams() + + const handleShare = () => { + const ref = searchParams.get('ref') + shareChat(chatId, { ref }) + } + + return +} +``` + +**Correct (reads on demand, no subscription):** + +```tsx +function ShareButton({ chatId }: { chatId: string }) { + const handleShare = () => { + const params = new URLSearchParams(window.location.search) + const ref = params.get('ref') + shareChat(chatId, { ref }) + } + + return +} +``` diff --git a/.claude/skills/react-best-practices/rules/rerender-dependencies.md b/.claude/skills/react-best-practices/rules/rerender-dependencies.md new file mode 100644 index 000000000..47a4d9268 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/rerender-dependencies.md @@ -0,0 +1,45 @@ +--- +title: Narrow Effect Dependencies +impact: LOW +impactDescription: minimizes effect re-runs +tags: rerender, useEffect, dependencies, optimization +--- + +## Narrow Effect Dependencies + +Specify primitive dependencies instead of objects to minimize effect re-runs. + +**Incorrect (re-runs on any user field change):** + +```tsx +useEffect(() => { + console.log(user.id) +}, [user]) +``` + +**Correct (re-runs only when id changes):** + +```tsx +useEffect(() => { + console.log(user.id) +}, [user.id]) +``` + +**For derived state, compute outside effect:** + +```tsx +// Incorrect: runs on width=767, 766, 765... +useEffect(() => { + if (width < 768) { + enableMobileMode() + } +}, [width]) + +// Correct: runs only on boolean transition +const isMobile = width < 768 +useEffect(() => { + if (isMobile) { + enableMobileMode() + } +}, [isMobile]) +``` diff --git a/.claude/skills/react-best-practices/rules/rerender-derived-state-no-effect.md b/.claude/skills/react-best-practices/rules/rerender-derived-state-no-effect.md new file mode 100644 index 000000000..3d9fe4050 --- /dev/null +++ b/.claude/skills/react-best-practices/rules/rerender-derived-state-no-effect.md @@ -0,0 +1,40 @@ +--- +title: Calculate Derived State During Rendering +impact: MEDIUM +impactDescription: avoids redundant renders and state drift +tags: rerender, derived-state, useEffect, state +--- + +## Calculate Derived State During Rendering + +If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead. + +**Incorrect (redundant state and effect):** + +```tsx +function Form() { + const [firstName, setFirstName] = useState('First') + const [lastName, setLastName] = useState('Last') + const [fullName, setFullName] = useState('') + + useEffect(() => { + setFullName(firstName + ' ' + lastName) + }, [firstName, lastName]) + + return

{fullName}

+} +``` + +**Correct (derive during render):** + +```tsx +function Form() { + const [firstName, setFirstName] = useState('First') + const [lastName, setLastName] = useState('Last') + const fullName = firstName + ' ' + lastName + + return

{fullName}

+} +``` + +References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect) diff --git a/.claude/skills/react-best-practices/rules/rerender-derived-state.md b/.claude/skills/react-best-practices/rules/rerender-derived-state.md new file mode 100644 index 000000000..e5c899f6c --- /dev/null +++ b/.claude/skills/react-best-practices/rules/rerender-derived-state.md @@ -0,0 +1,29 @@ +--- +title: Subscribe to Derived State +impact: MEDIUM +impactDescription: reduces re-render frequency +tags: rerender, derived-state, media-query, optimization +--- + +## Subscribe to Derived State + +Subscribe to derived boolean state instead of continuous values to reduce re-render frequency. + +**Incorrect (re-renders on every pixel change):** + +```tsx +function Sidebar() { + const width = useWindowWidth() // updates continuously + const isMobile = width < 768 + return