The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add frontend skill patterns from FE PR review feedback (#72689)
Nicolò Maria Mezzopera301179ef9b4b
diff --git a/.claude/skills/_shared/react-redux-patterns.md b/.claude/skills/_shared/react-redux-patterns.mdnew file mode 100644index 00000000000..7983b5f762f--- /dev/null+++ b/.claude/skills/_shared/react-redux-patterns.md@@ -0,0 +1,69 @@+# React, Redux, and Data-Layer Patterns++## API access and RTK Query++- **Use RTK Query for server data.** Add typed endpoints under `metabase/api` or `metabase-enterprise/api`; don't add ad-hoc `fetch`, service wrappers, or new thunks for ordinary API access.+- **Keep API files transport-focused.** Endpoint files should cover request/response typing, URLs, params, light response normalization, and cache tags — not feature business logic.+- **Use canonical API types.** Prefer `metabase-types/api`; fix or derive missing types instead of casting endpoint results. Refer to API endpoint implementation in Clojure when building new endpoint connections.+- **Tag caches deliberately.** Use `listTag`, `idTag`, `provide*Tags`, and `invalidateTags(error, tags)` where appropriate.+- **Guard missing query inputs.** Use `skipToken` or `skip` until all required inputs exist. Build query requirements where the query is created, not in a downstream render path.+- **Use lazy queries only for events.** Data needed to render a screen belongs in a regular query hook at the owner component/hook.+- **Handle mutations with `unwrap()`.** Prefer `await trigger(args).unwrap()` in submit handlers; otherwise branch on `result.error` immediately.++## Where data should live++- **Server data:** RTK Query cache, not duplicated Redux state.+- **Form state:** Form library or local component state, not global Redux.+- **Transient UI state:** Component state or narrow context, not store-wide flags.+- **Cross-route/global tasks:** Redux slice with public selectors.+- **Derived values:** Selectors or pure helpers, not stored copies of computed data. Memoized if identity is important.++## Redux state modeling++- **Avoid using Redux**. Most problems can be solved with local component state or RTK Query.+- **Use Redux only when needed.** Reach for Redux only when distant parts of the app need durable shared state.+- **Model async status explicitly.** Use a discriminated union or explicit `status`/`isLoading`/`error`; don't infer loaded or failed state from truthy/falsy `data`.+- **Store canonical state only.** Derive filtered lists, labels, permissions, booleans, and display variants in selectors.+- **Read through selectors.** Name selectors after what they return (`getCurrentTask`, `getHasPendingMutation`), not how they compute it.+- **Add missing public actions/selectors.** Don't reach into another feature's private state shape because an action or selector is missing.+- **Use `createSelector` for derived state.** Keep selectors pure, cheap, and stable by reference when consumers depend on identity.++## React hooks and components++- **`useMemo` computes render values.** Side effects belong in `useEffect`; event-driven changes belong in event handlers or mutation callbacks.+- **Keep effects narrow and idempotent.** Include all dependencies, guard inside the effect, and clean up timers/subscriptions. Complex logic should be split to multiple effects or custom hooks, also consider extracting functional pieces.+- **Hooks can be used to encapsulate complex logic.** For example, a hook can normalize data, handle form's state and validation, or a hook can manage a table's pagination and sorting. If component's logic becomes too complex, consider extracting a hook.+- **Hooks orchestrate behavior.** Custom hooks should return a small typed result object: data, loading/error state, and callbacks when relevant.+- **Don't mirror props/query data into state** unless the consumer can edit that local copy. Keep derived render data as such.+- **Use `useCallback` for stable identity needs, but deliberately.** Wrap callbacks passed to memoized children, dependency arrays, context values, or hooks that require stable identity — not every local handler.+- **Memoize object/array props only when identity matters.** Prefer simpler plain values otherwise.+- **Stories for presentational components**. Create Storybook stories for presentational components to test different states and props. Stories live next to the component.++## Performance++- **Optimize only where identity or scale matters.** Prefer clear code first, then add `memo`, `useMemo`, `useCallback`, selectors, virtualization, or split components when render cost, prop identity, or list size justifies it.+- **Keep context values stable and avoid frequent updates.** Values updated often should be avoided in context consumed by many components, or stored by reference with a stable context value and explicit subscriptions/selectors.+- **Read global state high in the tree.** Let parent components select context/Redux/API state, derive the view model, and pass narrow props top-down. But avoid passing props too deep (reconsider if more thatn 2 levels).+- **Avoid unstable props in hot paths.** Don't pass fresh object/array/function literals to memoized children; memoize them or move them outside render when identity matters.+- **Render large lists deliberately.** Use pagination, windowing/virtualization, stable keys, and row-level memoization for large or frequently updating lists.+- **Consider memoization for leaf components.** If the source of data updates often, but the component doesn't need to re-render, consider memoizing it.++## Loading, error, and empty states++- **Every async operation needs loading UI.** Use `LoadingAndErrorWrapper` or `DelayedLoadingAndErrorWrapper` for full-page/panel loading; use disabled controls and inline progress for local actions.+- **Every async operation needs an error branch.** Use wrappers or feature-specific alerts for query errors; use `getErrorMessage(error, fallback)` plus a toast/form error for mutation failures.+- **Empty is its own state.** Render no-results, empty-list, and permission-limited states intentionally; don't let them look like unfinished loading.+- **Combine multiple query states explicitly.** Example: `isLoading = a.isLoading || b.isLoading`; `error = a.error || b.error`.+- **Distinguish first load from refresh.** Use `isLoading` for first-load blockers and `isFetching` for background refresh indicators.+- **Test all async branches.** Cover loading, error, empty, and success states when adding or changing data access.++## Review checklist++- Server data uses a typed RTK Query endpoint with correct cache tags.+- Query inputs are guarded with `skipToken`/`skip` until ready.+- Global state is justified, minimal, and read through selectors.+- Context values are stable; frequently changing values don't force broad re-renders.+- Leaf components stay dumb and receive narrow props from parent containers.+- Loading, error, empty, and success branches are visible and tested.+- Hooks are pure during render; side effects are confined to effects or event handlers.+- Mutation failures are surfaced to people using the UI.diff --git a/.claude/skills/_shared/typescript-commands.md b/.claude/skills/_shared/typescript-commands.mdindex ad6ac7d59c0..d2372ac7dcb 100644--- a/.claude/skills/_shared/typescript-commands.md+++ b/.claude/skills/_shared/typescript-commands.md@@ -2,8 +2,8 @@- **Lint:** `bun run lint-eslint-pure`- Run ESLint on the codebase-- **Format:** `bun run prettier`- - Format code using Prettier+- **Format:** `bun run format`+ - Format code with oxfmt (`oxfmt --write`); use `bun run lint-format-pure` to check without writing- **Type Check:** `bun run type-check-pure`- Run TypeScript type checkingdiff --git a/.claude/skills/typescript-review/SKILL.md b/.claude/skills/typescript-review/SKILL.mdindex be052434c37..df788003bec 100644--- a/.claude/skills/typescript-review/SKILL.md+++ b/.claude/skills/typescript-review/SKILL.md@@ -1,20 +1,33 @@---name: typescript-reviewdescription: Review TypeScript and JavaScript code changes for compliance with Metabase coding standards, style violations, and code quality issues. Use when reviewing pull requests or diffs containing TypeScript/JavaScript code.-allowed-tools: Read, Grep, Bash, Glob+allowed-tools: Read, Grep, Bash, Glob, Skill---# TypeScript/JavaScript Code Review Skill@./../_shared/typescript-commands.md+@./../_shared/react-redux-patterns.md-## Code Review Guidelines+## Main Focus-Review pull requests with a focus on:+**Primary standard: the [`typescript-write`](../typescript-write/SKILL.md) skill.** Load it first — it defines the authoring rules this review enforces, alongside `frontend/CLAUDE.md` and `docs/developers-guide/frontend.md`.-- Readability and maintainability-- Appropriate test coverage-- Compliance with project coding standards and conventions-- Code quality and best practices-- Type safety and proper TypeScript usage-- React best practices (when applicable)+Adherence to `typescript-write` is the **highest-priority** review dimension: rank any violation of its provisions above all other findings. Treat its **no-`any` hard rule** (no explicit *or* implicit `any` in new code) as **blocking**, and verify it with the LSP rather than by eye.++Review in this priority order:++1. **Violations of [`typescript-write`](../typescript-write/SKILL.md) provisions** — no-`any`, type tightening, type modeling, null/undefined handling, naming, structure, comments. Highest priority; block on the no-`any` rule.+2. Compliance with `frontend/CLAUDE.md`.+3. Readability and maintainability.+4. Appropriate test coverage.++## Blind spots — act as the missing reviewer++These rarely surface in team reviews, so this skill should raise them. They are **additive** — raise them, but rank them below `typescript-write` violations:++- **Accessibility.** Interactive elements need keyboard support, focus management, and accessible names. Flag missing `aria-label`/`aria-labelledby`, non-semantic click targets, modals without focus trap, icon-only buttons without labels, and form inputs without a linked label.+- **Performance.** Flag areas that scale poorly and aren't memoized; inline object/array literals passed to memoized children; effects that fire on every batch of a progressive load; and new dependencies added to hot paths.+- **Security.** Evaluate potential security issues in new code.+- **Bundle size.** Flag new large dependencies, default imports from icon or util libs, and heavy modules imported at route-load time.+- **Analytics.** User-facing flows should emit tracking events. If a PR adds a new flow (button, modal, navigation) without a tracking event, ask whether one is expected.diff --git a/.claude/skills/typescript-write/SKILL.md b/.claude/skills/typescript-write/SKILL.mdindex 8204ff67333..496a2a1fdde 100644--- a/.claude/skills/typescript-write/SKILL.md+++ b/.claude/skills/typescript-write/SKILL.md@@ -7,3 +7,77 @@ description: Write TypeScript and JavaScript code following Metabase coding stan@./../_shared/development-workflow.md@./../_shared/typescript-commands.md+@./../_shared/react-redux-patterns.md++## No `any` — hard rule++- **New code must not introduce `any`, explicit or implicit.** No `any` annotations, no `as any` / `as unknown as`, no untyped parameters or returns that infer `any`, no implicitly-`any` destructures or array/object literals.+- **Untyped third-party / boundary values** must be typed at the boundary (a declared type, `unknown` + type guard, or a small typed wrapper) — never let `any` propagate inward.+- **Mandatory LSP verification.** After writing or editing any TS/TSX, inspect the changed symbols with the TypeScript Language Server (hover to read inferred types; `goToDefinition` to confirm sources) and run the project type-check.++## Type tightening++- **Avoid type casts and loose `unknown`** — fix the signature instead.+- **If a function only needs one field of a wide object, accept that field** — not the wide object. The cast often disappears once the signature is right.+- **Reach for `Partial<T>`, `Pick<T, K>`, `Record<K, V>`, and generics** before reaching for a cast.+- **Prefer making props/components generic** (`<T>`) when a value flows through unchanged and the caller knows the type.+- **Prefer `unknown` over loose typing** and narrow before use — an `unknown` value forces a guard at the point of use.+- **`satisfies` for object literals** that must conform without widening (config objects, lookup maps, discriminated literals) — better than `: T` (widens) or `as T` (unsafe).+- **Avoid non-null assertions (`!`)**. Prefer a guard, early return, or `?.`. Use `!` only when non-nullness is provably true and localized, with a comment.+- **No redundant runtime coercion** — don't wrap already-typed values in `Number()` / `String()` / `Boolean()`.+- **Type guards belong in `frontend/src/metabase-types/guards/`**. Do not redefine them locally.++## Type modeling++- **Reuse existing types; don't re-declare them.** Use canonical IDs and domain entity types from `metabase-types/api` (`FieldId`, `TableId`, `ConcreteTableId`, `SchemaName`, …) and key data structures by them (`new Map<ConcreteTableId, …>()`). Don't duplicate generated/API types — compose or derive (`Pick`, `Omit`, indexed access `SomeType["field"]`, `ReturnType`).+- **Use generics to allow TypeScript to infer correct types** when creating functions and components that need to be reusable and type-safe. Don't hesitate to introduce complex generics if they allow to derive types automatically instead of manual narrowing.+- **Model the actual data contract; keep types narrow.** Optional `field?: T` for a key that may be absent, `field: T | undefined` only when the key is always present but the value may be undefined, `| null` for explicit API nulls. Prefer domain unions over broad `string` / `number` / loose `Record`.+- **Refer to API implementation** when defining or refining types to ensure they match the actual data structure. When considering a type cast, first consider if the type should be refined to match the actual data structure.+- **Discriminated unions for variant state, with exhaustive checks.** Model "one of N shapes" as a union with a literal discriminant rather than a bag of optional fields, and exhaust it with ts-pattern's `.exhaustive()` so adding a variant becomes a compile error:+ ```ts+ import { match } from "ts-pattern";++ const result = match(status)+ .with({ type: "loading" }, () => <Spinner />)+ .with({ type: "error", error: P.select() }, (error) => <Error message={error.message} />)+ .with({ type: "success", data: P.select() }, (data) => <Content data={data} />)+ .exhaustive(); // Compile-time guarantee all cases handled+ ```+- **Derive union types from constants** (`as const` + `typeof`/`keyof`) so the type and the values can't drift.+- **`readonly` / immutability where mutation isn't intended** — component props, shared constants, exported config. Prefer `readonly T[]` / `ReadonlyArray<T>` for inputs you don't mutate.+- **Type async and error states explicitly** (a discriminated union or the data-layer's typed result) — never leave loading/error/empty implicit.++## Null and undefined++- **Narrow at the source**. If a value is optional only in a corner case, don't thread `undefined` through every layer — guard at the producer.+- **Sensible defaults for optional values**. Use `?.` and `??` at the consumer.+- **Lists should be filtered** before being used in a map or other iteration.+- **Avoid non-strict null comparisons** (`X != null`) when `X` can never be `null` — use a strict check or narrow the type. Use `checkNotNull` where necessary.+- **Check actual nullability against API implementation**. Find the API endpoint implementation and check if the field can actually be null.++## Naming++- **Names describe the entity, not the mechanism**. A name must reflect what the value holds.+- **Align sibling concepts**: keep verb conventions consistent across a related API.+- **No names that encode implementation history** rather than current meaning. Suffixes like `Base`, `New`, `Old`, `Initial` need a real semantic distinction, otherwise drop them.+- **Avoid cryptic identifiers** (`v`, `n`, `$n`) for domain values; short names are fine only in tiny conventional contexts (loop index `i`, coordinates `x`/`y`, generic params `T`/`K`/`V`).++## Code structure and organization++- **Prioritize reusability over duplication**. The codebase already has many utility functions — leverage them. If you introduce duplicated logic, extract it to a shared utility.+- **Generic helpers do not belong in feature folders**. Promote to a shared utility.+- **Keep functions small and single-purpose**. A 100+ line function is hard to review — split into focused named helpers, each with one responsibility and a minimal dependency surface. When necessary, cover with unit tests.+- **Extract distinct complex JSX into named components**. Choose same-file vs separate-file by reuse, coupling, testability, and readability.++## Comments++- **No comments by default**. Well-named identifiers carry the `what`.+- **Comments should be concise**. Add a short, concise comment only when the `why` is non-obvious: a workaround, a hidden invariant, a subtle ordering constraint, a clever reduction. Never document the actual implementation, focus on the intent and the why.++## TypeScript Migration++**When touching existing JavaScript files, propose to convert them to TypeScript first**. Create a separate PR for the conversion, then implement the changes.++## Verify before done++- **Run the project type-check** when finished (see the shared TypeScript commands above).diff --git a/docs/developers-guide/frontend.md b/docs/developers-guide/frontend.mdindex 7182c2cbae2..32e8934b54f 100644--- a/docs/developers-guide/frontend.md+++ b/docs/developers-guide/frontend.md@@ -30,10 +30,6 @@ Use Redux global state as little as possible, and wherever possible, prefer locaWe use [RTK Query](https://redux-toolkit.js.org/rtk-query/overview) for data fetching and caching. All API endpoints are defined in `metabase/api`. These should be properly typed, and should not depend on any other application code or contain business logic outside of invalidating tags within the API.-### Entity Loaders--Legacy code uses `metabase/entities` to load data. These entity loaders are deprecated, and wherever possible, use of RTK query apis should be preferred.-## UI LibraryOur UI library in `metabase/ui` is built on top of [`Mantine`](https://mantine.dev/core/package/). You should almost always prefer using mantine components above anything else in the codebase. We have a lot of customization on top of mantine, but no business logic should leak into the `metabase/ui` folder. It should remain purely display-level. All components added to the UI library must have a storybook file to demonstrate usage.@@ -178,9 +174,9 @@ const output = c("{0} and {2} are people's names, and {1} is a place")The first rule of frontend style, is we want to avoid talking about frontend style. Wherever possible, style-level considerations should be encapsulated in lint rules.-### Prettier + Eslint+### oxfmt + ESlint-We use [Prettier](https://prettier.io/) to format our JavaScript code, and it is enforced by CI. We recommend setting your editor to "format on save". You can also format code using `bun run prettier`, and verify it has been formatted correctly using `bun run lint-prettier`.+We use [oxfmt](https://oxc.rs/) to format our JavaScript and TypeScript code, and it is enforced by CI. We recommend setting your editor to "format on save". You can also format code using `bun run format`, and verify it has been formatted correctly using `bun run lint-format-pure`.We use ESLint to enforce additional rules. It is integrated into the Webpack build, or you can manually run `bun run lint-eslint` to check. Nitpicky things like import order, spacing, etc. are all enforced by eslint.diff --git a/frontend/CLAUDE.md b/frontend/CLAUDE.mdindex 616f66972c3..dcca59aa8f9 100644--- a/frontend/CLAUDE.md+++ b/frontend/CLAUDE.md@@ -1,22 +1,33 @@-# Working in /frontend--## Structure--```-frontend/src/-├── metabase/ # Main application components and pages-├── metabase-lib/ # Query building and data modeling utilities-├── metabase-types/ # TypeScript type definitions-└── metabase/ui/ # Design system components--frontend/test/ # Jest unit tests-```+# Working with frontend code++## Where frontend code lives++This is a high-level guide. Use available search tools to discover the current structure. Update the guide if new high-level modules have been added/discovered.++- Main app UI: `frontend/src/metabase`+- Query builder, notebook, and visualization flow: `frontend/src/metabase/query_builder`+- Dashboard runtime and editing: `frontend/src/metabase/dashboard`+- Admin screens: `frontend/src/metabase/admin`+- Shared app components: `frontend/src/metabase/common/components`+- API clients: `frontend/src/metabase/api`+- Query building and data modeling: `frontend/src/metabase-lib`+- Shared TypeScript types: `frontend/src/metabase-types`+- Thin helpers reused across bundles: `frontend/src/metabase-shared`+- Global and ambient type declarations: `frontend/src/types`+- Embedding SDK OSS code: `frontend/src/embedding-sdk-bundle` and `frontend/src/embedding-sdk-shared`+- Enterprise-only features: `enterprise/frontend/src/metabase-enterprise`+- Enterprise embedding code: `enterprise/frontend/src/embedding`, `enterprise/frontend/src/embedding-sdk-ee`, and `enterprise/frontend/src/embedding-sdk-package`+- Custom visualization enterprise code: `enterprise/frontend/src/custom-viz`+- Jest unit tests: colocated next to the files they test+- Jest test support and mocks: `frontend/test`+- Cypress E2E scenarios: `e2e/test/scenarios`+- Cypress component test scenarios: `e2e/test-component/scenarios`## Technology Stack- **Framework**: React 18 with TypeScript- **State**: Redux Toolkit-- **Styling**: CSS Modules (preferred) > Emotion styled-components+- **Styling**: Mantine style props (preferred) > CSS Modules- **UI**: `metabase/ui` components built with Mantine v8- **Package manager**: Bun- **Build**: Rspack (primary), Webpack (legacy)@@ -24,33 +35,27 @@ frontend/test/ # Jest unit tests## Coding Standards-### Component Preferences--- Prefer `metabase/ui`components over `metabase/common/components`-- Use `.tsx` for components, `.ts` for utilities+@../docs/developers-guide/frontend.md-### Styling+Read `docs/developers-guide/frontend.md` before frontend work — it's the detailed guide imported above.-ALWAYS prefer Mantine style props,then CSS modules. DO NOT suggest styled components, they are deprecated.+### Load the right skill first-### TypeScript Migration+Before starting a frontend task, load the matching skill from `.claude/skills/` — the+skills hold the authoritative, detailed rules. The guide above and the notes below are a+summary; when they disagree, follow the skill.-When heavily editing `.js`/`.jsx` files, create a separate PR to convert to TypeScript first, then implement changes.+- Writing / refactoring TypeScript or React → **typescript-write**+- Reviewing a TypeScript/React diff → **typescript-review**+- Writing Cypress E2E specs → **e2e-test-create**, **typescript-write**+- Running / debugging Cypress E2E → **e2e-test**+- Replacing Emotion styled-components with Mantine → **emotion-migrate**+- Adding product analytics events → **analytics-events**### Enterprise FeaturesEnterprise functionality MUST use the plugin system. It is very important to not expose enterprise code in the OSS version.-### Testing Requirements--All PRs should include tests. Prefer Unit tests over E2E tests.--### Localization--All user-facing strings MUST be localized using the ttag library. Localized strings should be complete phrases, do not concatenate a few separately localized strings. You should add context to strings where the meaning of the string might not be obvious in isolation: e.g. "Home" might have different words in some languages depending on whether you're talking about a dwelling or the landing page for a website.-### Scripts-- Use `bun run type-check-pure` to run project-wide type checking.-- Use `bun run lint-eslint-pure` to run project-wide linting.-- Use `bun run test-unit` to run Jest tests.+@../.claude/skills/_shared/typescript-commands.md