390 lines
37 KiB
Markdown
390 lines
37 KiB
Markdown
# Design patterns
|
|
|
|
How to pick and apply the GoF patterns from refactoring.guru and the JavaScript and React patterns from patterns.dev in this architecture. You already know the patterns, so this file gives only the decisions for this codebase: the signal that calls for each pattern, where it lives, its TypeScript shape, and when not to use it. Rendering and loading patterns are in [rendering-patterns.md](rendering-patterns.md), and code smells and refactoring techniques are in [refactoring.md](refactoring.md). Names match the source pages under refactoring.guru/design-patterns/ and patterns.dev/vanilla/ or patterns.dev/react/.
|
|
|
|
Contents: How to choose · Patterns the architecture already uses · Adding a pattern · React and JavaScript patterns · Other GoF patterns · Not used here
|
|
|
|
## How to choose
|
|
|
|
1. **Start from a problem you have now, never from a pattern.** Name the signal, then use the smallest pattern that removes it:
|
|
- The same `switch` on a type in several places → Strategy as a `Record` map.
|
|
- The same object built in several places with small differences → a factory function.
|
|
- Several booleans that describe one flow (`isUploading`, `isProcessing`, `hasFailed`) → State as a discriminated union.
|
|
- A vendor SDK's types and calls spreading through the code → Adapter in an integration.
|
|
- A back-end field name reaching a component → Adapter in the repository's `mappers.ts`.
|
|
- One feature must react to another feature's completed operation → Observer through the action's event.
|
|
- Parts of one page that must stay in step → Mediator in the page model.
|
|
- The pieces of one widget passing the same state to each other through props → Compound component.
|
|
|
|
Without a signal, write the direct code.
|
|
2. **Reuse the pattern the architecture already has for the job** (next section). A second event bus, HTTP wrapper, store library, or cache layer is a design error.
|
|
3. **Shape it with functions, closures, modules, and object literals.** Use a class only in a stateful lib whose spec already has one: `HttpClient`, `InterceptorManager`, `CookieAdapter`, or `LocalStorageAdapter`. Compose instead of inheriting. Error classes such as `HttpError` extend `Error`, and island's error-boundary primitive (`packages/island/src/primitives/error-boundary/ErrorBoundary.tsx`) extends React's `Component`, because React has no hook for catching render errors. Nothing else inherits, and no component inherits from another component.
|
|
4. **Keep a pattern inside its layer.** No pattern justifies an upward or cross-product import, or a break in the feature's layer order ([project-structure.md](project-structure.md#feature-anatomy)). When two layers must meet, wire them one level up: the AppShell subscribes, and the bootstrap configures.
|
|
5. **On the server, module scope holds only startup configuration and immutable helpers built from a fixed set, such as one `Intl` formatter per supported locale and time zone.** A singleton, a flyweight pool, or a memoized value in module scope serves every request, so it never holds back-end data, rendered output, or per-request or per-user data, even when every user would see the same value ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
|
|
6. **Wait for the third case before you extract an abstraction.** Two similar blocks can stay duplicated; the third one shows what really varies. island is the exception: a second style becomes a variant at once ([refactoring.md](refactoring.md)).
|
|
7. **Make the role visible in the name**, following the repo's conventions. Factories are camelCase `create*` functions (`createHttpClient`; `makeQueryClient` keeps the name from TanStack's docs). Key factories are camelCase objects (`productKeys`). Constant maps are UPPER_SNAKE_CASE (`AUTH_EVENTS`). A class or type that wraps a browser or vendor API ends in `Adapter` (`CookieAdapter`, `AnalyticsAdapter`), and its instance takes the domain name (`cookie`, `analytics`). A strategy map is a constant map named `<SUBJECT>_<ROLE>` (`ORDER_STATUS_BADGES`). A state machine lives in `<flow>-flow.ts` and exports `<Flow>State`, `<Flow>Event`, `<flow>Reducer`, and `INITIAL_<FLOW>_STATE`, with dotted event types that name what happened (`file.selected`).
|
|
8. **Record a new, non-obvious pattern** in the PR description: the signal, the pattern, and the simpler option you rejected.
|
|
|
|
## Patterns the architecture already uses
|
|
|
|
Reuse these before you add anything.
|
|
|
|
| Pattern | Where it lives | Rule |
|
|
|---|---|---|
|
|
| Module | Every module's `index.ts`; `server.ts` for server-only code | Every module. Re-export the public API by name and keep the rest private: never `export *`, never import another module's internal file, and never re-export `server.ts` from `index.ts` ([project-structure.md](project-structure.md#exports-and-tree-shaking)) |
|
|
| Singleton | The root `http`, `cookie`, `storage`, `eventEmitter`, zustand stores, and the browser `QueryClient` from `getQueryClient()` | For a service the whole app shares: a module instance that the bootstrap configures (`export const cookie = new CookieAdapter()`), never a class with `getInstance`. On the server one instance serves every request, so per-request objects come from a function (a new `QueryClient` per `getQueryClient()` call, a per-request i18next instance), and nothing writes to a store during server render ([b2c-b2b.md](b2c-b2b.md#state-and-auth)) |
|
|
| Factory functions | `createHttpClient`, `createClientEnv`, `createServerEnv`, `makeQueryClient`, and key factories such as `productKeys` | When several callers build the same kind of object from different inputs: a function that returns a new object or closure. Query keys always come from the repository's key factory ([code-patterns.md](code-patterns.md#repository)). Don't add a factory for an object built in one place |
|
|
| Adapter | `CookieAdapter` over `document.cookie`; each repository's `mappers.ts`; each integration over its vendor API; the json-ld lib over the schema.org vocabulary | At a boundary whose shape you don't own. Translate once, at the edge, so no `*Dto`, vendor type, cookie string syntax, or schema.org shape crosses it. Don't adapt two of your own modules to each other; change one of them |
|
|
| Facade | The `http` client over `fetch`, `XMLHttpRequest`, retry, refresh, and abort; feature actions over repositories, stores, storage, and events | When callers would repeat the same sequence of calls into several parts: one function, or one object with a few verbs. Callers never reach past it: no `fetch` outside the HTTP lib, and no model that repeats an action's steps |
|
|
| Proxy | Features' `caches/` (React `cache()`); `LocalStorageAdapter`; route guards; lazy widgets; the pwa lib's service worker | A cache dedupes calls within one request and never outlives it. The service worker stands in front of the network only for JS, CSS, fonts, and the icon sprite ([lib-pwa.md](lib-pwa.md)). `LocalStorageAdapter` keeps the `Storage` interface while it namespaces keys and absorbs blocked storage, so it works as a Proxy; keep the name its spec gives it. A guard lets a route through only when its check passes. When lazy loading pays off is in rendering-patterns.md |
|
|
| Decorator | zustand middleware: `immer` and `persist` | When a store needs cross-cutting behavior: wrap the creator and keep its shape, as in `persist(immer(...))` ([code-patterns.md](code-patterns.md#persisted-store)). No TypeScript decorator syntax, and no higher-order components that wrap components (see HOC below) |
|
|
| Chain of Responsibility | HTTP request and response interceptors; Next.js `proxy.ts`; nested error boundaries | For steps that every request or error passes through. Interceptors run root first and carry only cross-cutting concerns ([lib-http.md](lib-http.md#interceptors)). `proxy.ts` either answers (a redirect) or passes the request on, after it refreshes an expired session. An error stops at the nearest error boundary: part, then page, then app ([error-handling.md](error-handling.md#boundaries)). Never put business logic in a link |
|
|
| Observer | Action events through `eventEmitter`; zustand selectors; the TanStack Query cache and the queries that observe it | When code must react to a change that its source shouldn't know about. Events fire only after an operation completes. A listener subscribes once in an AppShell effect and unsubscribes in its cleanup, and a component subscribes to the smallest slice. The emitter only broadcasts, so coordination stays in actions and models |
|
|
| Mediator | The page model, between its part models | When parts of one page must stay in step. Parts never import or call each other: the page model owns what they share (the current step, the final submit) and passes it down as props. Don't add a context or a store for one page's parts. Run the page model in the smallest client component that contains the coordinated parts, never in the template or the page, which stay Server Components ([b2c-b2b.md](b2c-b2b.md#rendering)). State that must survive a reload or a shared link goes in the URL |
|
|
| Command | `useMutation` around a repository call or a feature action | When the UI triggers an operation and shows its progress. The mutation holds the operation; the UI calls `mutate` and reads `isPending` and `error`, and an error toast's retry calls it again when running it twice is safe ([error-handling.md](error-handling.md#actions)). Feature actions are client-side operations, not Next.js Server Actions. No hand-made command objects with `execute` and `undo`; undo is a back-end operation offered in the toast. A multi-step flow with its own states runs the request from its State reducer's model instead; don't wrap the same call in `useMutation` as well. A form whose submit runs a feature action awaits it inside `form.handleSubmit` and uses `formState.isSubmitting` as its pending state ([code-patterns.md](code-patterns.md#validation-model-and-server-errors)); don't wrap the action in `useMutation` as well. A form that saves through one repository call keeps the model's `useMutation` ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)) and awaits `mutateAsync` inside `form.handleSubmit`, catching the error for `applyServerErrors`, so `isSubmitting` and `isPending` agree |
|
|
| State | Multi-step flows: wizards, imports, bulk actions | When a flow has steps that carry different data: a state union, an event union, and a pure reducer in the model's folder (example below). Never a set of booleans |
|
|
| Strategy | Function-valued options such as the HTTP lib's `mapErrorBody` and `shouldRefresh`; sort comparators; the mobile or desktop template that the page picks on the server | When one contract has interchangeable implementations: pass a function, or pick an entry from a `Record` map (example below). Choose once, at the top: the page picks the template, and no component branches on viewport size. Don't add a strategy for behavior that never varies |
|
|
| Composite | Navigation menus, sidebar groups, and category trees | When a tree mixes leaves and groups: one node type (`children?: MenuNode[]`) and one recursive component. Filter the tree before rendering, so a group with no visible items disappears, and key nodes by id, never by index |
|
|
| Bridge | Semantic tokens over primitive tokens in island `theme.css` | For every component and theme. Components use semantic tokens only, and each theme maps them to primitives, so components and themes vary independently and a new theme touches only `theme.css` ([code-patterns.md](code-patterns.md#tokens-and-tailwind-wiring)). Never add a theme prop, `dark:` classes, or theme-specific variants to a component |
|
|
| Flyweight | The icon sprite, where every `<use>` points at one `<symbol>`; `Intl` formatters shared per locale and time zone in `packages/tools` | When many uses share heavy, immutable data: share that part and pass the rest per use (size and color for an icon, the value for a formatter). Date formatters always set `timeZone` explicitly to the one the server chose, never the runtime default ([b2c-b2b.md](b2c-b2b.md#hydration-and-navigation)). On the server, build a pool only from a fixed set such as the app's locales and supported time zones, never from user input, and never store formatted output |
|
|
| Memento | Persisted stores (`partialize`, `version`, `migrate`); react-hook-form `defaultValues` and `reset` | When state must be restored later. Snapshot only what must survive, and migrate old snapshots ([code-patterns.md](code-patterns.md#persisted-store)). After a successful save, `reset` the form with the saved values, so dirty tracking and the unsaved-changes warning start from the saved data. Never snapshot server data or loading flags |
|
|
| Iterator | `useInfiniteQuery` for feeds; an async generator in a repository | When code walks a paged collection without caring how the pages load. Infinite queries serve feeds only. Use an async generator over pages only when a flow must visit every page and the back end has no bulk endpoint |
|
|
| Container/Presentational with Hooks | Models with presentational pages, templates, and organisms; on the server, async server components that read caches | For every page and part. The model holds the data and handlers, and the page calls it and renders a template that only takes props. On the server, the container is an async server component that reads caches and passes `*Payload` props ([b2c-b2b.md](b2c-b2b.md#data-flow)). Components never call repositories or actions directly |
|
|
| Provider | The AppShell's providers; compound component contexts | For app-wide services, such as the query client and i18next, and for the parts of one compound component. Render `<Context value>` and read it with `use(Context)` or `useContext` (React 19). Keep app-wide providers in the AppShell, and keep shared state out of context (see Provider below) |
|
|
| Compound | `DataTable` and other complex island organisms | When a widget's parts share state and the caller arranges them: the parts share state through context and are also exported by name (example below). A component with one fixed layout takes props instead |
|
|
| Render props | Slots for `DataTable` cells, empty states, and toolbars | When the caller varies part of an organism: a `ReactNode` slot by default, and a render function (`cell: (row: TRow) => ReactNode`) only when the slot needs the organism's data. Never use one to share logic; write a hook |
|
|
|
|
## Adding a pattern
|
|
|
|
Where a new implementation goes:
|
|
|
|
| Pattern | Home | Shape |
|
|
|---|---|---|
|
|
| Strategy map | The owning module's `constants.ts`. Other features import it through that feature's `index.ts`. Use `shared/constants/` only when neither its keys nor its values come from a feature, because `shared/` never imports from `features/` | A constant map named `<SUBJECT>_<ROLE>`, typed with `satisfies Record<Union, Entry>`. Styles that vary by a prop are cva variants instead |
|
|
| State machine | The page or part model's folder, such as `models/product-import/product-import-flow.ts` | The state union, the event union, and a pure reducer. The model runs it with `useReducer`. When the flow must outlive the page, move the flow file into the store's folder (`stores/<domain>/<flow>-flow.ts`), have the store's action call the reducer, and have the model read the state through a selector. A store never imports from `models/` |
|
|
| Adapter for a vendor SDK | `packages/integrations/src/<name>/` | An object literal or functions typed by the integration's own `types.ts`, with no vendor type in its public API |
|
|
| Adapter for an API shape | The repository's `mappers.ts` | `to<Name>Dto(args)` and `to<Name>Payload(dto)` ([code-patterns.md](code-patterns.md#repository)) |
|
|
| Facade over several repositories or side effects | An action in the feature that owns the operation: `actions/<action-name>/actions.ts` | One async function with the `{ emit }` option that emits its event last ([code-patterns.md](code-patterns.md#action)) |
|
|
| Observer listener | An effect of the AppShell | Subscribe once, and return the unsubscribe function as the effect's cleanup |
|
|
| Factory | Beside what it builds: in the module's main file when the module exists to build that thing (`createHttpClient` in `http.ts`), otherwise its own `create-<thing>.ts` in the owning module | `create<Thing>(options): Thing`, returning an object literal or a closure |
|
|
| Exhaustive check | `assertNever` in `packages/tools/src/assert-never/` | `assertNever(value: never): never` throws. Call it in the `default` of every `switch` over a union |
|
|
| Generic hook with no feature data, such as `useDebouncedValue` | `packages/tools/src/use-debounced-value/use-debounced-value.ts` when more than one project needs it; otherwise beside its only user, such as an organism's `hooks/` | A `use-<name>.ts` hook that takes plain values and imports only React. A hook that reads a store, a query, or a `*Payload` belongs in the owning feature's `models/` or beside its store |
|
|
|
|
The examples use feature paths relative to `platforms/<platform>/src/`, as code-patterns.md does.
|
|
|
|
**Strategy.** An order's status picks its badge in the order list, the order header, and the timeline. One map replaces the three switches, and `satisfies` makes a new status fail type-check until it has an entry.
|
|
|
|
`features/orders/constants.ts`
|
|
|
|
```ts
|
|
import type { BadgeProps } from '@project/island/atoms/badge';
|
|
import type { OrderStatus } from './entities/order';
|
|
|
|
export const ORDER_STATUS_BADGES = {
|
|
pending: { variant: 'warning', labelKey: 'orders:status.pending' },
|
|
paid: { variant: 'info', labelKey: 'orders:status.paid' },
|
|
shipped: { variant: 'info', labelKey: 'orders:status.shipped' },
|
|
delivered: { variant: 'success', labelKey: 'orders:status.delivered' },
|
|
cancelled: { variant: 'danger', labelKey: 'orders:status.cancelled' },
|
|
} as const satisfies Record<OrderStatus, { variant: NonNullable<BadgeProps['variant']>; labelKey: string }>;
|
|
```
|
|
|
|
A component reads `const badge = ORDER_STATUS_BADGES[order.status]` and renders `<Badge variant={badge.variant}>{t(badge.labelKey)}</Badge>`.
|
|
|
|
**State.** A product import goes `idle → validating → uploading → processing → done | failed`. The flow file holds the states, the events, and a pure reducer. An event that doesn't fit the current state returns the state unchanged.
|
|
|
|
`features/catalog/models/product-import/product-import-flow.ts`
|
|
|
|
```ts
|
|
import { assertNever } from '@project/tools/assert-never';
|
|
import type { ProductImportReportPayload } from '../../repositories/product-imports';
|
|
|
|
export type ProductImportState =
|
|
| { status: 'idle' }
|
|
| { status: 'validating'; file: File }
|
|
| { status: 'uploading'; file: File; percent: number }
|
|
| { status: 'processing'; file: File }
|
|
| { status: 'done'; report: ProductImportReportPayload }
|
|
| { status: 'failed'; error: unknown };
|
|
|
|
export type ProductImportEvent =
|
|
| { type: 'file.selected'; file: File }
|
|
| { type: 'file.validated' }
|
|
| { type: 'upload.progressed'; percent: number }
|
|
| { type: 'import.succeeded'; report: ProductImportReportPayload }
|
|
| { type: 'import.failed'; error: unknown }
|
|
| { type: 'import.cancelled' };
|
|
|
|
export const INITIAL_PRODUCT_IMPORT_STATE: ProductImportState = { status: 'idle' };
|
|
|
|
export function isProductImportBusy(state: ProductImportState): boolean {
|
|
return state.status === 'validating' || state.status === 'uploading' || state.status === 'processing';
|
|
}
|
|
|
|
export function productImportReducer(state: ProductImportState, event: ProductImportEvent): ProductImportState {
|
|
switch (event.type) {
|
|
case 'file.selected':
|
|
return isProductImportBusy(state) ? state : { status: 'validating', file: event.file };
|
|
case 'file.validated':
|
|
return state.status === 'validating' ? { status: 'uploading', file: state.file, percent: 0 } : state;
|
|
case 'upload.progressed':
|
|
if (state.status !== 'uploading') return state;
|
|
return event.percent < 100 ? { ...state, percent: event.percent } : { status: 'processing', file: state.file };
|
|
case 'import.succeeded':
|
|
return state.status === 'uploading' || state.status === 'processing'
|
|
? { status: 'done', report: event.report }
|
|
: state;
|
|
case 'import.failed':
|
|
return isProductImportBusy(state) ? { status: 'failed', error: event.error } : state;
|
|
case 'import.cancelled':
|
|
return INITIAL_PRODUCT_IMPORT_STATE;
|
|
default:
|
|
return assertNever(event);
|
|
}
|
|
}
|
|
```
|
|
|
|
`features/catalog/models/product-import/use-product-import-page.ts`. The progress comes from the feature client's `upload()` through the repository ([lib-http.md](lib-http.md#files)). The server answers with the report after it processes the file, so the flow enters `processing` when the upload reaches 100%.
|
|
|
|
```ts
|
|
import { useReducer, useRef } from 'react';
|
|
import * as v from 'valibot';
|
|
import { productImportFileSchema } from '../../../../shared/validations';
|
|
import { productImportsRepository } from '../../repositories/product-imports';
|
|
import { INITIAL_PRODUCT_IMPORT_STATE, productImportReducer } from './product-import-flow';
|
|
|
|
export function useProductImportPage() {
|
|
const [state, dispatch] = useReducer(productImportReducer, INITIAL_PRODUCT_IMPORT_STATE);
|
|
const controllerRef = useRef<AbortController | null>(null);
|
|
|
|
async function start(file: File) {
|
|
if (controllerRef.current) return;
|
|
const controller = new AbortController();
|
|
controllerRef.current = controller;
|
|
dispatch({ type: 'file.selected', file });
|
|
try {
|
|
await v.parseAsync(productImportFileSchema, file);
|
|
if (controller.signal.aborted) return;
|
|
dispatch({ type: 'file.validated' });
|
|
const report = await productImportsRepository.upload(
|
|
{ file },
|
|
{
|
|
signal: controller.signal,
|
|
onProgress: ({ percent }) => dispatch({ type: 'upload.progressed', percent }),
|
|
},
|
|
);
|
|
if (controller.signal.aborted) return;
|
|
dispatch({ type: 'import.succeeded', report });
|
|
} catch (error) {
|
|
if (!controller.signal.aborted) dispatch({ type: 'import.failed', error });
|
|
} finally {
|
|
if (controllerRef.current === controller) controllerRef.current = null;
|
|
}
|
|
}
|
|
|
|
function cancel() {
|
|
controllerRef.current?.abort();
|
|
controllerRef.current = null;
|
|
dispatch({ type: 'import.cancelled' });
|
|
}
|
|
|
|
return { state, start, cancel };
|
|
}
|
|
```
|
|
|
|
- The controller is the in-flight guard: it exists from the first step, so a second `start` (a double click) returns at once. `cancel` aborts it and clears the ref, so a cancel during validation never starts the upload, and a new file can start right away.
|
|
- An aborted run dispatches nothing, so the `ABORTED` error is never shown and a late event from the old run can't touch the new one.
|
|
- After `import.succeeded`, the model also shows a toast and invalidates the product lists ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)). Both are left out here.
|
|
- The template switches on `state.status`, with `assertNever` in the `default`.
|
|
|
|
**Observer with Adapter.** The analytics integration adapts a tag manager's `dataLayer`, which needs no npm dependency. Integrations can't import features, so the AppShell wires the auth feature's event to the integration.
|
|
|
|
`packages/integrations/src/analytics/types.ts`
|
|
|
|
```ts
|
|
export type AnalyticsEvent = { name: 'login' | 'logout' | 'purchase'; params?: Record<string, string | number> };
|
|
|
|
export type AnalyticsAdapter = { track: (event: AnalyticsEvent) => void };
|
|
|
|
declare global {
|
|
interface Window {
|
|
dataLayer?: Record<string, unknown>[];
|
|
}
|
|
}
|
|
```
|
|
|
|
`packages/integrations/src/analytics/analytics.ts`. The rest of the code calls `analytics.track`, so a change of vendor touches only this file.
|
|
|
|
```ts
|
|
import type { AnalyticsAdapter } from './types';
|
|
|
|
export const analytics: AnalyticsAdapter = {
|
|
track(event) {
|
|
if (typeof window === 'undefined') return;
|
|
(window.dataLayer ??= []).push({ event: event.name, ...event.params });
|
|
},
|
|
};
|
|
```
|
|
|
|
`platforms/<platform>/src/app/app-shell/AppShell.tsx`, reduced to the subscription.
|
|
|
|
```tsx
|
|
'use client';
|
|
|
|
import { analytics } from '@project/integrations/analytics';
|
|
import { eventEmitter } from '@project/libs/event-emitter';
|
|
import { useEffect } from 'react';
|
|
import { AUTH_EVENTS } from '../../features/auth';
|
|
import type { AppShellProps } from './types';
|
|
|
|
export function AppShell({ children }: AppShellProps) {
|
|
useEffect(() => {
|
|
const unsubscribe = eventEmitter.on(AUTH_EVENTS.login, () => analytics.track({ name: 'login' }));
|
|
return unsubscribe;
|
|
}, []);
|
|
|
|
return children;
|
|
}
|
|
```
|
|
|
|
This assumes that `on` returns an unsubscribe function. Match the repo's real event-emitter signature, for example by calling its `off` in the cleanup. Loading the tag manager's script is a loading decision, covered in rendering-patterns.md.
|
|
|
|
**Compound component.** island's `Tabs` organism: the root owns the state, the parts read it from a context, and every part is exported by name.
|
|
|
|
`packages/island/src/organisms/tabs/hooks/use-tabs-context.ts`, private to the organism:
|
|
|
|
```ts
|
|
import { createContext, useContext } from 'react';
|
|
import type { TabsContextValue } from '../types';
|
|
|
|
export const TabsContext = createContext<TabsContextValue | null>(null);
|
|
|
|
export function useTabsContext(): TabsContextValue {
|
|
const context = useContext(TabsContext);
|
|
if (!context) throw new Error('Tabs parts must be rendered inside <Tabs>.');
|
|
return context;
|
|
}
|
|
```
|
|
|
|
`packages/island/src/organisms/tabs/Tabs.tsx`. Memoize the context value, so a root re-render that keeps the same tab doesn't re-render parts that sit behind a `memo` boundary. Skip `useMemo` when the repo enables the React Compiler.
|
|
|
|
```tsx
|
|
'use client';
|
|
|
|
import { useId, useMemo, useState } from 'react';
|
|
import { TabsList } from './components/tabs-list';
|
|
import { TabsPanel } from './components/tabs-panel';
|
|
import { TabsTrigger } from './components/tabs-trigger';
|
|
import { TabsContext } from './hooks/use-tabs-context';
|
|
import type { TabsProps } from './types';
|
|
|
|
function TabsRoot({ defaultValue, children }: TabsProps) {
|
|
const [activeValue, setActiveValue] = useState(defaultValue);
|
|
const baseId = useId();
|
|
const context = useMemo(() => ({ activeValue, select: setActiveValue, baseId }), [activeValue, baseId]);
|
|
return <TabsContext value={context}>{children}</TabsContext>;
|
|
}
|
|
|
|
export const Tabs = Object.assign(TabsRoot, { List: TabsList, Trigger: TabsTrigger, Panel: TabsPanel });
|
|
```
|
|
|
|
`packages/island/src/organisms/tabs/components/tabs-trigger/TabsTrigger.tsx`. `TabsPanel` reads the same context. It renders its children the first time its tab is selected, then keeps them mounted inside `<Activity mode="hidden">` while another tab is active, so switching tabs never remounts a visited panel. A panel whose content must be in the server HTML, such as product details for search engines, takes `forceMount` and is hidden with the `hidden` attribute instead. `TabsList` only renders `role="tablist"`. Arrow-key movement between tabs is left out to keep the example short.
|
|
|
|
```tsx
|
|
'use client';
|
|
|
|
import { useTabsContext } from '../../hooks/use-tabs-context';
|
|
import type { TabsTriggerProps } from './types';
|
|
import { tabsTriggerVariants } from './variants';
|
|
|
|
export function TabsTrigger({ value, children }: TabsTriggerProps) {
|
|
const { activeValue, select, baseId } = useTabsContext();
|
|
const isSelected = activeValue === value;
|
|
return (
|
|
<button
|
|
type="button"
|
|
role="tab"
|
|
id={`${baseId}-tab-${value}`}
|
|
aria-selected={isSelected}
|
|
aria-controls={`${baseId}-panel-${value}`}
|
|
className={tabsTriggerVariants({ isSelected })}
|
|
onClick={() => select(value)}
|
|
>
|
|
{children}
|
|
</button>
|
|
);
|
|
}
|
|
```
|
|
|
|
`packages/island/src/organisms/tabs/index.ts`
|
|
|
|
```ts
|
|
export { Tabs } from './Tabs';
|
|
export { TabsList, type TabsListProps } from './components/tabs-list';
|
|
export { TabsPanel, type TabsPanelProps } from './components/tabs-panel';
|
|
export { TabsTrigger, type TabsTriggerProps } from './components/tabs-trigger';
|
|
export type { TabsProps } from './types';
|
|
```
|
|
|
|
Pitfall: a Server Component can't reach a part through the root. island modules are ES modules, so on the server each export of a `'use client'` file is only a client reference. `Tabs.List` is `undefined` there, so the render fails, and the error message depends on the bundler. So Server Components compose the named parts, and `Tabs.List` stays for client components. The panels' content can stay server-rendered, and panels that search engines must read take `forceMount`:
|
|
|
|
`apps/<app>/src/app/(shop)/product/[id]/templates/product-desktop/ProductDesktop.tsx`, excerpt:
|
|
|
|
```tsx
|
|
<Tabs defaultValue="details">
|
|
<TabsList>
|
|
<TabsTrigger value="details">{t('catalog:product.tabs.details')}</TabsTrigger>
|
|
<TabsTrigger value="shipping">{t('catalog:product.tabs.shipping')}</TabsTrigger>
|
|
</TabsList>
|
|
<TabsPanel value="details" forceMount>
|
|
<ProductSpecs product={product} />
|
|
</TabsPanel>
|
|
<TabsPanel value="shipping" forceMount>
|
|
<ShippingInfo product={product} />
|
|
</TabsPanel>
|
|
</Tabs>
|
|
```
|
|
|
|
## React and JavaScript patterns
|
|
|
|
Decisions for the patterns.dev design patterns that the table above leaves open:
|
|
|
|
- **HOC**: not used for new code. Put cross-cutting behavior in a hook or a wrapper component, such as an error boundary. React's own `memo` and `lazy` are fine, and so is Next.js's `catchError`, which builds the `PartBoundary` ([error-handling.md](error-handling.md#boundaries)). `ref` is a regular prop in React 19, so new components skip `forwardRef` too.
|
|
- **Render props versus slots**: a Server Component can't pass a plain function to a client component, so it passes only `ReactNode` slots. An organism that needs render functions, such as a `DataTable` with custom cells, is rendered from a client component that defines them.
|
|
- **Provider**: context carries services and one compound component's state, never app data. Shared client state goes to a zustand store read through selectors, server state to the query cache, and form state to react-hook-form; never mirror any of them into a context. Split large contexts. The one store-in-context case is a store that must start from server data ([b2c-b2b.md](b2c-b2b.md#state-and-auth)).
|
|
- **Hooks added in React 19**: `useActionState`, `useFormStatus`, and `useOptimistic` are built for React's actions. Forms here run on react-hook-form with the model's `submit`, and optimistic toggles go through the query cache with a rollback ([code-patterns.md](code-patterns.md#mutation-with-a-valid-cache)), so don't add a second pending or optimistic state for the same data. `use()` reads a streamed promise inside `<Suspense>` ([b2c-b2b.md](b2c-b2b.md#data-flow)).
|
|
- **Mixin**: not used. Share behavior with functions, hooks, and composition, and never copy methods onto a class or a prototype.
|
|
- **Proxy object** (JavaScript `Proxy` and `Reflect`): not used in app code, because it hides behavior from readers and from the type checker. immer uses it inside zustand's `set`, so never keep a draft after `set` returns. For guarded configuration, write explicit functions, like a project's `getEnv` that throws before `setEnv` has run.
|
|
- **Prototype** (the prototype chain): only the custom prototypes lib (`packages/libs/src/custom-prototypes/`) extends built-ins. It adds each method with `Object.defineProperty` (non-enumerable), skips a name that already exists so it never overwrites a native or third-party method, declares the methods in a `declare global` block, and is listed in `sideEffects` ([project-structure.md](project-structure.md#exports-and-tree-shaking)). Import it at the top of each bootstrap. Everywhere else, write plain functions.
|
|
- **Mediator/Middleware**: patterns.dev joins two rows of the table: Mediator (the page model) and Chain of Responsibility (interceptors and `proxy.ts`). Don't add a central hub that components send messages through.
|
|
- **Server push**, such as a live order status or the progress of an import's `processing` step: poll first, with the part model's `useQuery` and a `refetchInterval` that stops when the status is final. Push is a lib change with its own spec and approval: SSE is a streaming method in the HTTP lib, as for AI UI below, so it shares the one refresh and abort, and a WebSocket client is a new lib in `packages/libs`. Never a raw `EventSource` or `WebSocket` in a model. The part model subscribes in an effect and writes each message to the query cache with `setQueryData`, never to a store.
|
|
- **AI UI Patterns**: only when the product has a chat or assistant page. The conversation is a part model's state, with each message a union by status (`streaming`, `done`, `failed`). Streamed replies need a streaming method in the HTTP lib, which is a lib change ([lib-http.md](lib-http.md)), never `fetch` in a model. The AI SDK is outside the stack, so state the reason and get approval before adding it.
|
|
- **React Stack Patterns**: a survey of tool choices, not a design pattern. The stack is fixed in [SKILL.md](../SKILL.md#2-stack), and any other pick needs a stated reason and approval.
|
|
|
|
## Other GoF patterns
|
|
|
|
The GoF patterns that the architecture doesn't already use:
|
|
|
|
- **Factory Method**: not used in its class form, because nothing here inherits. When a caller needs one of several implementations by key, use a factory function (table above) or a `Record` from key to implementation in the owning module's `constants.ts`. A map of components inside a client component bundles every entry, so heavy entries map to lazy components; a map in a Server Component ships only the client entries it renders (rendering-patterns.md).
|
|
- **Abstract Factory**: rarely needed, because matching families are already chosen once, higher up: the theme through tokens (Bridge) and the device through the template. Don't build a context that swaps whole component kits; a second brand is a theme in `theme.css`. A real need for different component sets, such as white-label apps, is decided in the plan first.
|
|
- **Builder**: rarely needed. When a value has many optional parts, such as metadata from `configs/seo.ts` or JSON-LD built from a `*Payload` (the json-ld lib's `build*` functions and the platform's `app/json-ld/`, [lib-json-ld.md](lib-json-ld.md)), write a pure function that takes an options object with defaults and returns the finished value. No chained, mutable builder classes; valibot's `pipe` already composes schemas step by step.
|
|
- **Prototype**: copying is an immutable update: spread for a shallow copy, `structuredClone` for a deep copy of plain data, and immer drafts inside stores. `http.extend` isn't a Prototype: it delegates to the root live instead of copying it, so settings made later in bootstrap still apply ([lib-http.md](lib-http.md#api)). Never `structuredClone` an object that holds functions or class instances; it throws on functions and drops prototypes.
|
|
- **Template Method**: not used in its class form. Its component form already exists: island templates and organisms such as `PageHeader` fix the layout and take the varying parts as slots. For logic, write a function that owns the sequence and takes the varying steps as callbacks, such as `runImport({ validate, upload, dispatch })`, and move it to `shared/utils/` only when a third feature needs the same sequence.
|
|
- **Visitor**: rarely needed in app code. To run type-specific logic over mixed nodes, such as CMS content blocks or filter expressions, switch exhaustively over the discriminated union with `assertNever`, or use a `Record` from `type` to handler. A new operation is a new function, and a new node type fails type-check at every switch. No `accept` and `visit` double dispatch.
|
|
|
|
## Not used here
|
|
|
|
Keep these out of designs, and flag each one in review with its alternative. A merge blocks only for the reasons in [SKILL.md](../SKILL.md#7-review-stance), which include the server-side cache and boundary cases below.
|
|
|
|
- **`getInstance` singleton classes.** Export a module instance. On the server, create per-request objects with a function such as `getQueryClient()`.
|
|
- **Module-scope per-request or per-user state on the server**, such as a `Map` of users, a memoized promise of back-end data, or a store written during render. Use a feature cache (React `cache()`), the per-request `QueryClient`, or props ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
|
|
- **A service locator or DI container.** The bootstrap is the composition root: it passes settings to libs with `configure` and values to projects with `setEnv`, and each module imports what it uses by name.
|
|
- **Base classes** such as `BaseRepository` or `BaseService`. A repository is an object literal. Shared request behavior lives in the feature client and its interceptors ([lib-http.md](lib-http.md#root-and-feature-clients)), and shared logic lives in small functions.
|
|
- **Inheritance between components.** Compose with `children`, slots, cva variants, and compound parts.
|
|
- **HOCs and mixins in new code.** Use a hook or a wrapper component.
|
|
- **Events for request and response flows**, such as emitting `cart.totalRequested` and waiting for a reply event. Call the action or repository and await it; events only fan out after an operation completes.
|
|
- **A second event bus, cache layer, or state library**, such as RxJS subjects, a hand-made fetch cache, a service worker that stores pages or data, Redux, or a context used as a store. Use the event emitter, the query cache (or `cache()` within one server request), the pwa lib's worker for JS, CSS, fonts, and the icon sprite only, and zustand.
|
|
- **A pattern for a future that isn't planned.** Write the direct code, and extract the pattern when the third case arrives (refactoring.md).
|
|
- **A pattern that needs an upward or cross-product import, or `export *`**, such as an integration that imports a feature to listen to it. Wire it one level up, in the AppShell or the bootstrap, and re-export by name.
|
|
- **A pattern library without approval**, such as XState or InversifyJS. Use the in-stack alternative first: a discriminated union and a pure reducer in `useReducer` or a zustand store instead of XState, and the bootstrap's `configure` and `setEnv` instead of InversifyJS. Any dependency outside [the stack](../SKILL.md#2-stack) needs a stated reason and approval.
|