538 lines
18 KiB
Markdown
538 lines
18 KiB
Markdown
# Code patterns
|
|
|
|
Reference implementations for each layer. Paths are relative to the project that owns the code: `platforms/<app>/src/` for B2C/B2B logic, `apps/<app>/src/` for admin panels, and `packages/<name>/src/` for shared packages. `@project` is the workspace scope. The `@project/libs/*` APIs shown follow the lib specs: `http` and `isHttpError` in [lib-http.md](lib-http.md), `storage` in [lib-local-storage.md](lib-local-storage.md), `cookie` in [lib-cookie.md](lib-cookie.md). `eventEmitter` stands for the repo's own lib; match its real signature.
|
|
|
|
Type-specific code lives in the playbooks: caches, the page entrypoint, and server-to-client data in [b2c-b2b.md](b2c-b2b.md), routes, guards, and screens in [admin-panels.md](admin-panels.md).
|
|
|
|
This file is the house code for each layer. Which design pattern to use, when, and where it lives is in [design-patterns.md](design-patterns.md).
|
|
|
|
Contents: Island component module · Tokens and Tailwind wiring · Repository · Action (with its event) · Validation, model, and server errors · Mutation with a valid cache · Store · Persisted store · Env
|
|
|
|
## Island component module
|
|
|
|
`atoms/button/variants.ts`
|
|
|
|
```ts
|
|
import { cva } from 'class-variance-authority';
|
|
|
|
export const buttonVariants = cva(
|
|
'inline-flex cursor-pointer items-center justify-center gap-2 rounded-md font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-action-primary disabled:cursor-not-allowed disabled:opacity-50',
|
|
{
|
|
variants: {
|
|
variant: {
|
|
primary: 'bg-action-primary text-on-action hover:bg-action-primary-hover',
|
|
secondary: 'border border-border-subtle bg-surface-card text-text-primary hover:bg-surface-muted',
|
|
danger: 'bg-status-danger text-on-action hover:bg-status-danger-hover',
|
|
},
|
|
size: {
|
|
sm: 'h-8 px-3 text-sm',
|
|
md: 'h-10 px-4 text-sm',
|
|
lg: 'h-11 px-5 text-base',
|
|
},
|
|
},
|
|
defaultVariants: { variant: 'primary', size: 'md' },
|
|
},
|
|
);
|
|
```
|
|
|
|
`atoms/button/types.ts`
|
|
|
|
```ts
|
|
import type { VariantProps } from 'class-variance-authority';
|
|
import type { ComponentPropsWithRef } from 'react';
|
|
import type { buttonVariants } from './variants';
|
|
|
|
export type ButtonProps = ComponentPropsWithRef<'button'> &
|
|
VariantProps<typeof buttonVariants> & {
|
|
isLoading?: boolean;
|
|
};
|
|
```
|
|
|
|
`atoms/button/Button.tsx`
|
|
|
|
```tsx
|
|
import { cn } from '../../tools/cn';
|
|
import { Spinner } from '../spinner';
|
|
import type { ButtonProps } from './types';
|
|
import { buttonVariants } from './variants';
|
|
|
|
export function Button({
|
|
className,
|
|
variant,
|
|
size,
|
|
isLoading = false,
|
|
disabled,
|
|
type = 'button',
|
|
children,
|
|
...props
|
|
}: ButtonProps) {
|
|
return (
|
|
<button
|
|
type={type}
|
|
className={cn(buttonVariants({ variant, size }), className)}
|
|
disabled={disabled || isLoading}
|
|
aria-busy={isLoading || undefined}
|
|
{...props}
|
|
>
|
|
{isLoading && <Spinner size="sm" />}
|
|
{children}
|
|
</button>
|
|
);
|
|
}
|
|
```
|
|
|
|
`atoms/button/index.ts`
|
|
|
|
```ts
|
|
export { Button } from './Button';
|
|
export type { ButtonProps } from './types';
|
|
export { buttonVariants } from './variants';
|
|
```
|
|
|
|
`tools/cn/cn.ts`
|
|
|
|
```ts
|
|
import { clsx, type ClassValue } from 'clsx';
|
|
import { twMerge } from 'tailwind-merge';
|
|
|
|
export function cn(...inputs: ClassValue[]): string {
|
|
return twMerge(clsx(inputs));
|
|
}
|
|
```
|
|
|
|
tailwind-merge doesn't know the theme. If `theme.css` adds a token it can't classify, such as a font size `text-body-sm` (which it reads as a color and drops next to `text-text-primary`), build `cn` with `extendTailwindMerge` and register the token.
|
|
|
|
## Tokens and Tailwind wiring
|
|
|
|
`styles/theme.css`: primitives are plain theme values, semantic tokens point at primitives and switch per theme, and `@theme inline` turns the semantic tokens into utilities (`bg-surface-card`, `text-text-muted`). Components use only the semantic utilities, so they never need `dark:` variants.
|
|
|
|
```css
|
|
@theme {
|
|
--color-neutral-0: #ffffff;
|
|
--color-neutral-50: #f4f6fa;
|
|
--color-neutral-900: #161b23;
|
|
--color-neutral-950: #0f1319;
|
|
--color-blue-500: #3b82f6;
|
|
--color-blue-600: #2563eb;
|
|
}
|
|
|
|
:root {
|
|
--surface-page: var(--color-neutral-50);
|
|
--surface-card: var(--color-neutral-0);
|
|
--action-primary: var(--color-blue-600);
|
|
}
|
|
|
|
.dark {
|
|
--surface-page: var(--color-neutral-950);
|
|
--surface-card: var(--color-neutral-900);
|
|
--action-primary: var(--color-blue-500);
|
|
}
|
|
|
|
@theme inline {
|
|
--color-surface-page: var(--surface-page);
|
|
--color-surface-card: var(--surface-card);
|
|
--color-action-primary: var(--action-primary);
|
|
}
|
|
```
|
|
|
|
This is an excerpt. The real file defines every semantic token the components use, such as `text-primary`, `text-muted`, `border-subtle`, `on-action`, the `status-*` colors, and their hover states.
|
|
|
|
`styles/island.css`
|
|
|
|
```css
|
|
@import './theme.css';
|
|
@import './fonts.css';
|
|
@import './utilities.css';
|
|
@source '../';
|
|
```
|
|
|
|
`apps/<app>/src/styles/app.css`
|
|
|
|
```css
|
|
@import 'tailwindcss' source('../');
|
|
@import '@project/island/styles/island.css';
|
|
@source '../../../../platforms/<app>/src';
|
|
```
|
|
|
|
Tailwind generates only the classes it finds in registered sources. island registers itself in `island.css`; the app registers its own `src/`, its platform, and any integration that renders UI. CSS `@import` resolves package names through package.json `exports`, not TypeScript path aliases, so path-alias workspaces import `island.css` by relative path.
|
|
|
|
## Repository
|
|
|
|
`features/auth/entities/user/types.ts`
|
|
|
|
```ts
|
|
export type UserRole = 'admin' | 'operator';
|
|
|
|
export type User = {
|
|
id: string;
|
|
full_name: string;
|
|
role: UserRole;
|
|
};
|
|
```
|
|
|
|
`features/auth/repositories/auth/types.ts`
|
|
|
|
```ts
|
|
import type { User, UserRole } from '../../entities/user';
|
|
|
|
export type LoginArgs = { phone: string; password: string };
|
|
|
|
export type LoginDto = { mobile: string; password: string };
|
|
|
|
export type LoginResponseDto = { user: User; is_first_login: boolean };
|
|
|
|
export type LoginPayload = {
|
|
user: { id: string; fullName: string; role: UserRole };
|
|
isFirstLogin: boolean;
|
|
};
|
|
```
|
|
|
|
`features/auth/repositories/auth/mappers.ts`
|
|
|
|
```ts
|
|
import type { LoginArgs, LoginDto, LoginPayload, LoginResponseDto } from './types';
|
|
|
|
export function toLoginDto(args: LoginArgs): LoginDto {
|
|
return { mobile: args.phone, password: args.password };
|
|
}
|
|
|
|
export function toLoginPayload(dto: LoginResponseDto): LoginPayload {
|
|
return {
|
|
user: { id: dto.user.id, fullName: dto.user.full_name, role: dto.user.role },
|
|
isFirstLogin: dto.is_first_login,
|
|
};
|
|
}
|
|
```
|
|
|
|
`features/auth/repositories/auth/constants.ts`
|
|
|
|
```ts
|
|
export const AUTH_ENDPOINTS = {
|
|
login: '/auth/login',
|
|
logout: '/auth/logout',
|
|
refresh: '/auth/refresh',
|
|
} as const;
|
|
```
|
|
|
|
`features/auth/http.ts`. Every feature has one; this feature needs nothing special, so it only extends the root. A feature with its own service sets `baseUrl`, headers, timeout, or retry here (see [lib-http.md](lib-http.md#root-and-feature-clients)).
|
|
|
|
```ts
|
|
import { http } from '@project/libs/http';
|
|
|
|
export const authHttp = http.extend({});
|
|
```
|
|
|
|
`features/auth/repositories/auth/auth.ts`. Repositories send requests only through their feature's client and never through the root `http`.
|
|
|
|
```ts
|
|
import { authHttp } from '../../http';
|
|
import { AUTH_ENDPOINTS } from './constants';
|
|
import { toLoginDto, toLoginPayload } from './mappers';
|
|
import type { LoginArgs, LoginPayload, LoginResponseDto } from './types';
|
|
|
|
export const authRepository = {
|
|
async login(args: LoginArgs): Promise<LoginPayload> {
|
|
const response = await authHttp.post<LoginResponseDto>(AUTH_ENDPOINTS.login, toLoginDto(args));
|
|
return toLoginPayload(response);
|
|
},
|
|
};
|
|
```
|
|
|
|
Read methods take an optional last parameter `{ signal?: AbortSignal }` and forward it, so TanStack Query can cancel them (see Mutation with a valid cache).
|
|
|
|
`features/auth/repositories/auth/index.ts` exports no `*Dto`:
|
|
|
|
```ts
|
|
export { authRepository } from './auth';
|
|
export { AUTH_ENDPOINTS } from './constants';
|
|
export type { LoginArgs, LoginPayload } from './types';
|
|
```
|
|
|
|
Query keys sit in the repository's `constants.ts`, start with the domain, and are hierarchical so invalidation is precise. `features/catalog/repositories/products/constants.ts`:
|
|
|
|
```ts
|
|
import type { ListProductsArgs } from './types';
|
|
|
|
export const PRODUCTS_ENDPOINT = '/catalog/products';
|
|
|
|
export const productKeys = {
|
|
all: ['catalog', 'products'] as const,
|
|
lists: () => [...productKeys.all, 'list'] as const,
|
|
list: (args: ListProductsArgs) => [...productKeys.lists(), args] as const,
|
|
details: () => [...productKeys.all, 'detail'] as const,
|
|
detail: (id: string) => [...productKeys.details(), id] as const,
|
|
};
|
|
```
|
|
|
|
## Action
|
|
|
|
`features/auth/constants.ts`. Event names are `<feature>.<action>`.
|
|
|
|
```ts
|
|
export const AUTH_EVENTS = {
|
|
login: 'auth.login',
|
|
logout: 'auth.logout',
|
|
} as const;
|
|
|
|
export const LAST_PHONE_STORAGE_KEY = 'last-phone';
|
|
```
|
|
|
|
`features/auth/actions/login/actions.ts`. The repository throws the normalized `HttpError` when the request fails, so reaching the next line means the response was successful. The caller handles the error.
|
|
|
|
```ts
|
|
import { eventEmitter } from '@project/libs/event-emitter';
|
|
import { storage } from '@project/libs/local-storage';
|
|
import { useAuthStore } from '../../../../stores/auth';
|
|
import { accessRepository } from '../../../access';
|
|
import { AUTH_EVENTS, LAST_PHONE_STORAGE_KEY } from '../../constants';
|
|
import { authRepository, type LoginArgs } from '../../repositories/auth';
|
|
|
|
export async function login(args: LoginArgs, { emit = true }: { emit?: boolean } = {}): Promise<'ok'> {
|
|
const { user, isFirstLogin } = await authRepository.login(args);
|
|
const permissions = await accessRepository.getMyPermissions();
|
|
|
|
useAuthStore.getState().setSession({ user, permissions, isFirstLogin });
|
|
storage.setItem(LAST_PHONE_STORAGE_KEY, args.phone);
|
|
if (emit) eventEmitter.emit(AUTH_EVENTS.login, { userId: user.id });
|
|
|
|
return 'ok';
|
|
}
|
|
```
|
|
|
|
- Every action emits its event as its last step, so a failed step throws before the emit and listeners only hear about completed operations.
|
|
- `{ emit: false }` is for callers that must not trigger listeners, such as an action that runs another action as one of its steps and emits its own event.
|
|
- Code that reacts to an action (analytics, another feature's refresh) subscribes to its event instead of being called from the action. Subscribe once, in an effect of the `AppShell`, and unsubscribe in its cleanup.
|
|
|
|
## Validation, model, and server errors
|
|
|
|
`shared/validations/base-validations.ts`. Messages are i18n keys; the field component translates them. Each message tells the user how to fix the value, for example "Enter an 11-digit mobile number that starts with 09."
|
|
|
|
```ts
|
|
import { MOBILE_REGEX } from '@project/libs/regex';
|
|
import * as v from 'valibot';
|
|
|
|
export const requiredString = (message: string) => v.pipe(v.string(), v.trim(), v.nonEmpty(message));
|
|
|
|
export const mobileNumber = (message: string) =>
|
|
v.pipe(v.string(), v.trim(), v.regex(MOBILE_REGEX, message));
|
|
```
|
|
|
|
`shared/validations/auth-validations.ts`
|
|
|
|
```ts
|
|
import * as v from 'valibot';
|
|
import { mobileNumber, requiredString } from './base-validations';
|
|
|
|
export const loginSchema = v.object({
|
|
phone: mobileNumber('validation:phone.invalid'),
|
|
password: requiredString('validation:password.required'),
|
|
});
|
|
```
|
|
|
|
`shared/validations/types.ts`
|
|
|
|
```ts
|
|
import type * as v from 'valibot';
|
|
import type { loginSchema } from './auth-validations';
|
|
|
|
export type LoginFormValues = v.InferOutput<typeof loginSchema>;
|
|
```
|
|
|
|
`shared/utils/apply-server-errors.ts`: field errors go under their fields (the first one gets focus), errors that match no field go to a form-level alert, and a toast summarizes the failure.
|
|
|
|
```ts
|
|
import { isHttpError } from '@project/libs/http';
|
|
import type { FieldValues, Path, UseFormReturn } from 'react-hook-form';
|
|
import { toast } from 'sonner';
|
|
|
|
export function applyServerErrors<T extends FieldValues>(
|
|
form: UseFormReturn<T>,
|
|
error: unknown,
|
|
fallbackMessage: string,
|
|
): void {
|
|
if (!isHttpError(error)) {
|
|
toast.error(fallbackMessage, { duration: Infinity });
|
|
return;
|
|
}
|
|
|
|
const fieldErrors = Object.entries(error.fieldErrors ?? {});
|
|
fieldErrors.forEach(([field, message], index) => {
|
|
form.setError(field as Path<T>, { type: 'server', message }, { shouldFocus: index === 0 });
|
|
});
|
|
if (fieldErrors.length === 0) {
|
|
form.setError('root.server', { type: 'server', message: error.message });
|
|
}
|
|
toast.error(error.message, { description: error.hint, duration: Infinity });
|
|
}
|
|
```
|
|
|
|
`features/auth/models/login/use-login-page.ts` (admin panel). In a B2C/B2B platform the model is the same, with `useRouter` from `next/navigation`.
|
|
|
|
```ts
|
|
import { valibotResolver } from '@hookform/resolvers/valibot';
|
|
import { useNavigate } from '@tanstack/react-router';
|
|
import { useForm } from 'react-hook-form';
|
|
import { useTranslation } from 'react-i18next';
|
|
import { toast } from 'sonner';
|
|
import { applyServerErrors } from '../../../../shared/utils';
|
|
import { loginSchema, type LoginFormValues } from '../../../../shared/validations';
|
|
import { login } from '../../actions/login';
|
|
|
|
export function useLoginPage() {
|
|
const { t } = useTranslation('auth');
|
|
const navigate = useNavigate();
|
|
const form = useForm<LoginFormValues>({
|
|
resolver: valibotResolver(loginSchema),
|
|
mode: 'onTouched',
|
|
defaultValues: { phone: '', password: '' },
|
|
});
|
|
|
|
const submit = form.handleSubmit(async (values) => {
|
|
try {
|
|
await login(values);
|
|
toast.success(t('login.success'));
|
|
await navigate({ to: '/' });
|
|
} catch (error) {
|
|
applyServerErrors(form, error, t('login.failed'));
|
|
}
|
|
});
|
|
|
|
return { form, submit, isSubmitting: form.formState.isSubmitting };
|
|
}
|
|
```
|
|
|
|
`mode: 'onTouched'` validates a field on its first blur and on every change after that. The submit button is disabled only while `isSubmitting`, never because the form is invalid, so users can click it to find out what is wrong.
|
|
|
|
## Mutation with a valid cache
|
|
|
|
After every create, update, or delete, set the detail, patch the affected lists, then invalidate the lists to reconcile in the background. When patching isn't practical, invalidate every key that can contain the entity (details, lists, counts, dashboards). Never rely on `staleTime` expiring.
|
|
|
|
Use optimistic updates only for quick toggles (active/inactive, favorite), always with a rollback in `onError` and a toast explaining the failure.
|
|
|
|
`features/catalog/models/product-edit/use-product-edit-page.ts`
|
|
|
|
```ts
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
import { useTranslation } from 'react-i18next';
|
|
import { toast } from 'sonner';
|
|
import { productKeys, productsRepository, type ProductsPagePayload } from '../../repositories/products';
|
|
|
|
export function useProductEditPage(productId: string) {
|
|
const { t } = useTranslation('catalog');
|
|
const queryClient = useQueryClient();
|
|
|
|
const product = useQuery({
|
|
queryKey: productKeys.detail(productId),
|
|
queryFn: ({ signal }) => productsRepository.get({ id: productId }, { signal }),
|
|
});
|
|
|
|
const save = useMutation({
|
|
mutationFn: productsRepository.update,
|
|
onSuccess: (updated) => {
|
|
queryClient.setQueryData(productKeys.detail(updated.id), updated);
|
|
queryClient.setQueriesData<ProductsPagePayload>({ queryKey: productKeys.lists() }, (page) =>
|
|
page ? { ...page, items: page.items.map((item) => (item.id === updated.id ? updated : item)) } : page,
|
|
);
|
|
void queryClient.invalidateQueries({ queryKey: productKeys.lists() });
|
|
toast.success(t('product.saved', { name: updated.name }));
|
|
},
|
|
});
|
|
|
|
return { product, save };
|
|
}
|
|
```
|
|
|
|
## Store
|
|
|
|
`stores/auth/types.ts`
|
|
|
|
```ts
|
|
import type { Permission } from '../../features/access';
|
|
import type { LoginPayload } from '../../features/auth';
|
|
|
|
export type Session = {
|
|
user: LoginPayload['user'];
|
|
permissions: Permission[];
|
|
isFirstLogin: boolean;
|
|
};
|
|
|
|
export type AuthState = {
|
|
session: Session | null;
|
|
setSession: (session: Session) => void;
|
|
clearSession: () => void;
|
|
};
|
|
```
|
|
|
|
`stores/auth/auth-store.ts`. Components subscribe to the smallest slice they render, never to the whole store.
|
|
|
|
```ts
|
|
import { create } from 'zustand';
|
|
import { immer } from 'zustand/middleware/immer';
|
|
import type { Permission } from '../../features/access';
|
|
import type { AuthState } from './types';
|
|
|
|
export const useAuthStore = create<AuthState>()(
|
|
immer((set) => ({
|
|
session: null,
|
|
setSession: (session) =>
|
|
set((state) => {
|
|
state.session = session;
|
|
}),
|
|
clearSession: () =>
|
|
set((state) => {
|
|
state.session = null;
|
|
}),
|
|
})),
|
|
);
|
|
|
|
export const useCurrentUser = () => useAuthStore((state) => state.session?.user);
|
|
|
|
export const useHasPermission = (permission: Permission) =>
|
|
useAuthStore((state) => state.session?.permissions.includes(permission) ?? false);
|
|
```
|
|
|
|
B2C/B2B: never write to a store during server render (see b2c-b2b.md).
|
|
|
|
## Persisted store
|
|
|
|
A store that survives a reload keeps its data in local storage through the `storage` adapter, so the key lands under the app's prefix (`shop.session.cart`). `stores/cart/cart-store.ts`:
|
|
|
|
```ts
|
|
import { storage } from '@project/libs/local-storage';
|
|
import { create } from 'zustand';
|
|
import { createJSONStorage, persist } from 'zustand/middleware';
|
|
import { immer } from 'zustand/middleware/immer';
|
|
import type { CartState } from './types';
|
|
|
|
export const useCartStore = create<CartState>()(
|
|
persist(
|
|
immer((set) => ({
|
|
items: [],
|
|
addItem: (item) =>
|
|
set((state) => {
|
|
state.items.push(item);
|
|
}),
|
|
clear: () =>
|
|
set((state) => {
|
|
state.items = [];
|
|
}),
|
|
})),
|
|
{
|
|
name: 'session.cart',
|
|
storage: createJSONStorage(() => storage),
|
|
version: 1,
|
|
partialize: (state) => ({ items: state.items }),
|
|
skipHydration: true,
|
|
},
|
|
),
|
|
);
|
|
```
|
|
|
|
- `name` is the key. `session.` marks it as the logged-in user's data, so logout's `storage.clearByPrefix('session.')` removes it.
|
|
- `partialize` persists only what must survive a reload. Bump `version` and add `migrate` when the shape changes.
|
|
- B2C/B2B keeps `skipHydration: true` and rehydrates after mount, so the server render and the first browser render match. In the platform's `AppShell`: `useEffect(() => { void useCartStore.persist.rehydrate(); }, []);`. Admin panels render only in the browser and can drop `skipHydration`.
|
|
|
|
## Env
|
|
|
|
The app's `env/` files, a project's `setEnv` and `getEnv`, and both bootstraps: [lib-env.md](lib-env.md#usage).
|