Awesome_IA_Rules / frontend
Cursor rule1 starsChanged 3 days agoMITView on GitHub
React, TypeScript, and SSR frontend architecture, custom hooks, AsyncState, WCAG 2.1 AA accessibility, BEM/SCSS, and testing
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 4,144 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository8 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .cursor/rules/backend/go-backend.mdcCursor rule
- .cursor/rules/backend/java-quarkus-backend.mdcCursor rule
- .cursor/rules/backend/node-bff-backend.mdcCursor rule
- .cursor/rules/core/01-core-engineering.mdcCursor rule
- .cursor/rules/core/02-spec-driven-development.mdcCursor rule
- .cursor/rules/core/03-code-review.mdcCursor rule
The file
Show its rules and text
We split this node-react-frontend.mdc into the rules it gives an agent
16 rules. About 0 are common, 3 are distinctive, and 13 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 52
Shared Promotion: If a component or hook is needed by 2+ features, promote it to app/shared/ with comprehensive tests and generic types.
- Very specific: line 59
150-Line Limit: Keep components under 150 lines.
- Distinctive: line 60
One Component Per File: Never declare multiple stateful components in the same file.
- Distinctive: line 63
Every functional component must follow this exact 6-step internal ordering:
- Very specific: line 126
Effect Cleanup: Avoid manual useEffect data fetching whenever TanStack Query applies.
- Very specific: line 133
Keep server route handlers (getServerSideProps / Server Components / Loaders) thin: verify authentication from the server request context, …
- Very specific: line 134
Never access window, document, or localStorage during render without an SSR guard or useEffect, and never render non-deterministic values …
- Very specific: line 136
Never use dangerouslySetInnerHTML with unsanitized content.
- Distinctive: line 138
Never instantiate inline object/array literals or anonymous closures as props to memoized children.
- Very specific: line 139
Use code-splitting (React.lazy / dynamic imports) at feature and route boundaries.
- Very specific: line 146
Semantic HTML First: Use <main>, <nav>, <section>, <article>, <button type="button">, and <dialog> instead of generic <div> or <span> …
- Very specific: line 147
Keyboard & Focus Management: Ensure all interactive elements are reachable via Tab, operable via Enter/Space/Escape, have visible …
- Very specific: line 151
Full Class Names (No
&__Concatenation): Write complete BEM class names (.order-summary__title) instead of nested &__title concatenation … - Very specific: line 152
Contextual Breakpoints: Place responsive media queries/mixins (@include mobile-only, @include tablet-up) directly inside the class rule …
- Very specific: line 158
AAA + Builder Pattern: Follow Arrange, Act, Assert (single Act per test) using fluent Builders (new …
- Very specific: line 164
Test successful fetch, select transformation, disabled state when params are invalid, and error state handling.
≈ “Common” is an estimate: at least 1 in 5 of the 6,668 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
---
description: "React, TypeScript, and SSR frontend architecture, custom hooks, AsyncState, WCAG 2.1 AA accessibility, BEM/SCSS, and testing"
globs: "{app,web,client,frontend,src}/**/*.{ts,tsx,scss,css}"
alwaysApply: false
---
# Frontend Engineering Standards (React, TypeScript & SSR)
> **Scope**: All Frontend TypeScript/React, SSR, and stylesheet files (`{app,web,client,frontend,src}/**/*.{ts,tsx,scss,css}`).
> **Mandate**: Build accessible (WCAG 2.1 AA), high-performance, type-safe, feature-isolated web applications with strict separation between declarative UI Views and custom Hooks.
---
## 1. Feature-Based Architecture
Organize the frontend into self-contained business features under `app/features/` (or `src/features/`). Enforce strict boundaries: **`Pages / Routes (SSR) → Feature View → Custom Hooks → Sub-Components`**.
```text
app/
├── features/ # Self-contained business features
│ └── {feature-name}/
│ ├── components/ # Feature-scoped sub-components
│ │ └── {SubComponent}/
│ │ ├── hooks/ # Component-specific logic hooks
│ │ ├── {SubComponent}.tsx
│ │ ├── {SubComponent}.types.ts
│ │ ├── {SubComponent}.spec.tsx
│ │ └── index.ts
│ ├── hooks/ # Feature-level data fetching & domain logic hooks
│ │ └── use{Feature}Data/
│ │ ├── use{Feature}Data.ts
│ │ ├── use{Feature}Data.types.ts
│ │ ├── use{Feature}Data.spec.tsx
│ │ └── index.ts
│ ├── services/ # Typed BFF/API client functions
│ ├── view/ # Main Feature View (entry UI for pages/MFE)
│ │ ├── {Feature}View.tsx
│ │ ├── {Feature}View.types.ts
│ │ ├── {Feature}View.styles.scss
│ │ └── index.ts
│ └── index.ts # Feature Public API (export only View & public types)
├── pages/ # Routing & SSR layer (Next.js / Remix / Custom SSR)
├── shared/ # Truly global UI primitives, hooks, and utilities
│ ├── components/ # e.g., AsyncState, ErrorBoundary, QueryClientWrapper
│ └── hooks/
└── styles/ # Design tokens, breakpoints, global resets
```
### Feature Isolation Rules
- **No Cross-Feature Internal Imports**: Feature A must **never** import internal components or hooks from `features/feature-b/components/*`.
- **Public API Only**: Pages and host containers import exclusively from the feature's public entrypoint (`features/{feature-name}/view` or `features/{feature-name}`).
- **Shared Promotion**: If a component or hook is needed by 2+ features, promote it to `app/shared/` with comprehensive tests and generic types.
---
## 2. Component & Hook Design Standards
### Size & Single Responsibility
- **150-Line Limit**: Keep components under **150 lines**. Extract stateful orchestration, data transformations, and side effects into custom hooks (`hooks/use*.ts`).
- **One Component Per File**: Never declare multiple stateful components in the same file.
### Canonical Component Organization Order
Every functional component must follow this exact 6-step internal ordering:
```tsx
export const OrderSummaryView: FC<OrderSummaryViewProps> = (props) => {
// 1. Destructure props (with defaults)
const { orderId, isCompact = false, onOrderCancel } = props;
// 2. Custom hooks (server state, i18n, feature logic)
const { data, isLoading, isError, refetch } = useOrderSummaryData({ orderId });
// 3. Derived state (useMemo)
const formattedTotal = useMemo(() => formatCurrency(data?.total), [data?.total]);
// 4. Event handlers (useCallback)
const handleCancelClick = useCallback(() => {
onOrderCancel?.(orderId);
}, [onOrderCancel, orderId]);
// 5. Declarative AsyncState / Conditional early returns (Loading / Error / Empty)
return (
<AsyncState
isLoading={isLoading}
isError={isError}
isEmpty={!data}
skeleton={<OrderSummarySkeleton />}
onRetry={refetch}
>
{/* 6. Main render */}
<section className="order-summary" aria-labelledby="order-summary-title">
<h2 id="order-summary-title" className="order-summary__title">
{data?.title}
</h2>
<span className="order-summary__total">{formattedTotal}</span>
{!isCompact && (
<button
type="button"
className="order-summary__cancel-button"
onClick={handleCancelClick}
>
Cancel Order
</button>
)}
</section>
</AsyncState>
);
};
```
### Server State & Data Fetching (TanStack Query / React Query)
- **Scalable `select` Pattern**: Expose a generic `select?: (data: TDomain) => TSelected` parameter in data-fetching hooks so consumer components subscribe only to the slice of data they render, minimizing re-renders:
```typescript
export const useFetchOrder = <TData = OrderData>({
orderId,
select,
}: UseFetchOrderParams<TData>) => {
return useQuery<OrderData, Error, TData>({
queryKey: orderKeys.byId(orderId),
queryFn: ({ signal }) => getOrderById(orderId, { signal }),
enabled: Boolean(orderId),
select,
});
};
```
- **Effect Cleanup**: Avoid manual `useEffect` data fetching whenever TanStack Query applies. When `useEffect` is required for subscriptions or DOM events, **always** return a cleanup function (`AbortController.abort()`, `isCancelled = true`, `removeEventListener`) to prevent memory leaks and state updates on unmounted components.
---
## 3. SSR, Security & Performance
- **SSR & Hydration Safety**:
- Keep server route handlers (`getServerSideProps` / Server Components / Loaders) thin: verify authentication from the server request context, validate route params, and pass only minimal, sanitized props to the client.
- Never access `window`, `document`, or `localStorage` during render without an SSR guard or `useEffect`, and never render non-deterministic values (`Date.now()`, `Math.random()`) that cause SSR/CSR hydration mismatches.
- **XSS Prevention**:
- Never use `dangerouslySetInnerHTML` with unsanitized content. When rendering rich text is unavoidable, sanitize with **DOMPurify** (`RETURN_TRUSTED_TYPE: true`).
- **Performance**:
- Never instantiate inline object/array literals or anonymous closures as props to memoized children.
- Use code-splitting (`React.lazy` / dynamic imports) at feature and route boundaries.
---
## 4. Accessibility (WCAG 2.1 AA) & Styling (SCSS / BEM)
### Accessibility (a11y)
- **Semantic HTML First**: Use `<main>`, `<nav>`, `<section>`, `<article>`, `<button type="button">`, and `<dialog>` instead of generic `<div>` or `<span>` elements with click handlers.
- **Keyboard & Focus Management**: Ensure all interactive elements are reachable via `Tab`, operable via `Enter`/`Space`/`Escape`, have visible `:focus-visible` outlines, and trap/restore focus properly in modals/drawers.
- **ARIA & Contrast**: Provide `aria-label` or `aria-labelledby` for icon/control elements, `aria-invalid` + `aria-describedby` (`role="alert"`) for form validation errors, and maintain a minimum `4.5:1` text contrast ratio.
### Searchable BEM & Contextual Responsive Styling
- **Full Class Names (No `&__` Concatenation)**: Write complete BEM class names (`.order-summary__title`) instead of nested `&__title` concatenation so every class name is 100% greppable with `Ctrl+F` / `ripgrep`. Use `&` **only** for pseudo-classes (`&:hover`, `&:focus-visible`) and modifiers (`&--compact`).
- **Contextual Breakpoints**: Place responsive media queries/mixins (`@include mobile-only`, `@include tablet-up`) directly inside the class rule they modify, never in a detached block at the bottom of the file. Use design-system CSS custom properties (`var(--color-surface-primary)`) instead of hardcoded hex values.
---
## 5. Frontend Testing (`*.spec.tsx`)
- **AAA + Builder Pattern**: Follow **Arrange, Act, Assert** (single Act per test) using fluent **Builders** (`new OrderDataBuilder().withPendingStatus().build()`) for all mock data.
- **Component Tests (React Testing Library)**:
- Query the DOM the way a user interacts with it (`screen.getByRole`, `screen.getByLabelText`, `screen.getByText`); use `data-testid` only as a last resort.
- Explicitly test all 4 visual states: **Loading (skeleton)**, **Success**, **Empty**, and **Error (with retry interaction)**.
- **Hook Tests (`renderHook`)**:
- Wrap React Query hooks in a clean `TestQueryClientWrapper` (with `retry: false`).
- Test successful fetch, `select` transformation, disabled state when params are invalid, and error state handling.
- **Coverage Target**: `>= 90%` across feature components, custom hooks, and shared utilities.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

