321 lines
22 KiB
Markdown
321 lines
22 KiB
Markdown
# Admin panel playbook
|
||
|
||
Back-office panels where staff manage a B2C/B2B site, often eight hours a day, repeating the same task hundreds of times. Treat them as production software, not throwaway CRUD screens: every screen should let operators finish faster, with fewer mistakes and less fatigue than a spreadsheet. UX is the primary deliverable.
|
||
|
||
Contents: Access levels · Business domains and endpoints · Help system · Screens and routing · UX rules (copy, data and cache, file uploads, surfaces and color, cursors, feedback, stability, responsiveness, loading and progress, lists, errors, lazy loading, forms, keyboard, performance) · Example: route, guard, and screen · Testing · Definition of Done
|
||
|
||
## Access levels
|
||
|
||
Pages, actions, and sidebar items are all permission-aware. The back end is the authority; front-end checks are UX, never security.
|
||
|
||
- Permissions arrive with the session (the login action fetches them) and live in the auth store. They are a typed union in `features/access/entities/permission/types.ts`, for example `'catalog.products.read' | 'catalog.products.update'`.
|
||
- Pages: every route in `navigation/navigation.ts` runs a guard in `beforeLoad`. Signed-out users go to login with a return URL. Users without the permission go to a "no access" screen that explains why and links back. Never render a blank page.
|
||
- Actions: wrap buttons and menu items in `PermissionGuard`, or use `useHasPermission`. Hide actions the role can never use. When the role has the action but it's unavailable right now (for example, the order is locked), disable it with a tooltip that says why.
|
||
- Sidebar: each item in `navigation/constants.ts` carries its permission, a navigation hook filters the items, and a group with no visible items disappears.
|
||
- A 403 from the API means permissions changed mid-session. Tell the user what they tried and why it failed, then refresh the permissions.
|
||
|
||
## Business domains and endpoints
|
||
|
||
- One DDD feature per business domain: catalog, orders, customers, finance. A domain may call its own service or base URL. Set it in the feature's `http.ts` from the app's env, `export const catalogHttp = http.extend({ baseUrl: () => clientEnv.VITE_CATALOG_API_URL })`, so every domain shares the root client's auth refresh, interceptors, and error normalization, and only one refresh runs at a time across domains. A domain may also set its own headers, timeout, and retry there, never auth settings (see [lib-http.md](lib-http.md#root-and-feature-clients)).
|
||
- Each domain's mappers convert that service's DTO conventions to `*Payload`, and every domain surfaces the same normalized error shape.
|
||
- Query keys start with the domain (`['catalog', 'products', ...]`) so invalidation stays precise.
|
||
- Features import other features only through their `index.ts`. A screen that spans domains composes several models; features don't reach into each other.
|
||
|
||
## Help system
|
||
|
||
Operators should never have to guess what a page, action, or flow does.
|
||
|
||
- Every screen shows a one-sentence description under its title: what the page is for and when changes take effect.
|
||
- Every action with non-obvious consequences (bulk operations, imports, status transitions, permission changes, anything irreversible or asynchronous) has an info icon beside it. The help says what the flow does, what it affects, how long it takes, and what happens if it fails. Example: "Publishing this catalog makes all 340 active products visible on the storefront within about 2 minutes. Products missing a price will be skipped and listed in a report."
|
||
- Business flows with states, such as the order lifecycle or refund approval, get a help panel that describes each state and the allowed transitions.
|
||
- Fields that need explanation get help text under the field.
|
||
- Help text lives in i18n resources under a `help` namespace, keyed by screen, action, or flow ID, so it is translatable and reviewable. The info-icon popover and the help panel are island components. A script in `tools/` can check that every route and flagged action has a help entry.
|
||
|
||
## Screens and routing
|
||
|
||
- Routes are code-based in `navigation/navigation.ts`. Each route runs its guard in `beforeLoad`, validates its search params with a valibot schema in `validateSearch`, and lazy-loads its screen with `lazyRouteComponent`, using a skeleton of the page layout as `pendingComponent`.
|
||
- `screen/<page-name>/page.tsx` is a thin entry: it calls the page's model hook and renders the template. Each screen level may keep its own `organisms/` and `templates/`.
|
||
- A part that loads or changes on its own (a filters panel, a stats card, a table) calls its own part model and sits in its own `<Suspense>` with a same-size skeleton and its own error boundary. What the parts share, such as the selected row or the current step, lives in the page model and reaches the parts as props.
|
||
- The shell (sidebar, header, breadcrumbs) stays mounted across navigation; only the outlet changes.
|
||
|
||
Every screen has the same anatomy, so operators never hunt for navigation:
|
||
|
||
1. A title that names the page and its object ("Edit Category", "Product: Blue Ceramic Mug"), matched by the document title ("Edit Category · Admin").
|
||
2. Breadcrumbs with every ancestor linked: Dashboard / Catalog / Categories / Edit Category.
|
||
3. A back button ("Back to Categories") that goes to the logical parent, not `history.back()`, so it also works from a direct link.
|
||
4. Primary actions in the header on desktop and in a sticky bottom bar on mobile.
|
||
5. Info icons for complex actions and flows.
|
||
|
||
```tsx
|
||
<PageHeader
|
||
breadcrumbs={[
|
||
{ label: t('nav:dashboard'), to: '/' },
|
||
{ label: t('nav:catalog'), to: '/catalog' },
|
||
{ label: t('nav:categories'), to: '/catalog/categories' },
|
||
{ label: t('category.edit.title') },
|
||
]}
|
||
backTo={{ label: t('category.edit.back'), to: '/catalog/categories' }}
|
||
title={t('category.edit.title')}
|
||
description={t('category.edit.description')}
|
||
actions={
|
||
<Button type="submit" form="category-form">
|
||
{t('category.edit.save')}
|
||
</Button>
|
||
}
|
||
/>
|
||
```
|
||
|
||
## UX rules
|
||
|
||
### Copy
|
||
|
||
- Every label, button, tooltip, and message is a simple, complete description of its purpose. Buttons name the action and its object ("Delete this category", not "Delete"). Headings describe their content. Tooltips describe the outcome, not the control.
|
||
- Error messages have three parts: what went wrong, why (if known), and what the user can do. "The file could not be uploaded because it is larger than 10 MB. Compress the image or choose a smaller file, then try again."
|
||
- Empty states say what would normally be here, why it is empty, and the next step, with a primary action when there is one: "No categories yet. Create your first category to start organizing products." plus a "Create category" button.
|
||
|
||
### Data and cache
|
||
|
||
- After every create, update, or delete, update or invalidate every query that can contain the entity (code in code-patterns.md). Users never see stale data right after changing it.
|
||
- Paginated tables use `placeholderData: keepPreviousData`, so the current page stays visible while the next one loads.
|
||
- Prefetch the next page when the pointer rests on "Next page", and prefetch detail data on row hover when latency matters.
|
||
|
||
### File uploads
|
||
|
||
- Every upload shows a progress bar with a numeric percentage ("Uploading… 63%"), the file name and size, a cancel button while uploading, and a clear success or failure state with a retry action. Multiple files show per-file progress and an overall bar. Uploads go through the feature client's `upload()`: its `onProgress` drives the bar, and the cancel button aborts the `signal`. Uploads never retry automatically; the retry action sends the file again (see [lib-http.md](lib-http.md#files)).
|
||
|
||
### Surfaces, color, and contrast
|
||
|
||
The interface is never just black and white. Define these as semantic tokens in island `theme.css`:
|
||
|
||
- Page background: a soft tinted neutral (for example `#F4F6FA` light, `#0F1319` dark), never pure white or pure black.
|
||
- Navbar and sidebar: a surface distinct from the page (darker or brand-tinted), so navigation separates at a glance.
|
||
- Cards and panels: lighter than the page (`#FFFFFF` light, `#161B23` dark), with a subtle 1 px border at about 8–12% contrast and a soft shadow (`0 1px 2px rgba(16,24,40,.06), 0 1px 3px rgba(16,24,40,.10)`).
|
||
- Sections inside cards: separated by dividers, spacing steps, or a faint tint on headers and footers.
|
||
- Status colors (success, warning, danger, info), each with fill and text variants that meet contrast on their background.
|
||
- The accent color is reserved for primary actions and active navigation.
|
||
- Text meets WCAG 2.1 AA: 4.5:1 for body text, 3:1 for large text and UI boundaries. Check it with axe in Playwright and by inspecting screenshots.
|
||
- Interactive states are visible: hover, focus-visible (2 px ring in the accent color), active, selected, and disabled (reduced opacity plus `cursor: not-allowed`).
|
||
|
||
### Cursors and affordances
|
||
|
||
- Every enabled button, link, clickable row, sortable header, tab, and chip shows `cursor: pointer`. Build it into the island components.
|
||
- Every clickable element looks different from static text. Sortable headers show a sort icon (neutral when unsorted, filled and accent-colored with a direction arrow when sorted) and change background on hover. Clickable rows highlight on hover. Links are underlined or colored. Icon-only buttons have a tooltip and an `aria-label`. A column header is never plain text with no indicator.
|
||
|
||
### Feedback
|
||
|
||
- Every completed action shows a toast that says exactly what was done, naming the object when possible: "Category 'Kitchenware' was deleted", "3 orders were marked as shipped". Success toasts auto-dismiss after 4–6 s. Error toasts stay until dismissed and include the fix and, when possible, a retry: `toast.error(message, { description: hint, duration: Infinity, action: { label, onClick: retry } })`.
|
||
- When the user changes a table page, scroll to the top of the table, not necessarily the window: a ref on the table container and `scrollIntoView({ block: 'start', behavior })`, with `behavior: 'auto'` under `prefers-reduced-motion`.
|
||
- Destructive actions ask for confirmation, naming the object and the consequence: "Delete category 'Kitchenware'? Its 12 products will become uncategorized. This cannot be undone."
|
||
- Prefer reversible designs: soft deletes, and "Undo" in the toast when the back end supports it.
|
||
|
||
### Stability
|
||
|
||
Refetches, state updates, and re-renders must never make the UI disappear and reappear.
|
||
|
||
- Never switch between `isLoading ? <Spinner /> : <Table />` on refetch. Keep showing the data with a subtle inline indicator driven by `isFetching`.
|
||
- Keep layout containers mounted and swap only their contents.
|
||
- Use skeletons with the final content's dimensions, and reserve space for images and charts with fixed aspect ratios.
|
||
- Put a `Suspense` boundary at the page level with a skeleton of the page layout, so the shell never flickers during route transitions.
|
||
- A part whose model uses `useSuspenseQuery` changes its query key inside `startTransition`, so a page or filter change keeps the current content instead of falling back to the skeleton.
|
||
|
||
### Responsiveness
|
||
|
||
Design and verify every screen at three viewports, with the breakpoints defined in island `theme.css` (`--breakpoint-tablet: 64rem`, `--breakpoint-desktop: 90rem`, which give the `tablet:` and `desktop:` variants):
|
||
|
||
- Desktop, 1440 px and wider: full sidebar, multi-column forms, dense tables with all columns.
|
||
- Tablet, 1024–1439 px: icon-only collapsible sidebar, two-column forms, low-priority columns behind a "More" column or a row expander.
|
||
- Mobile, 0–1023 px: sidebar in a drawer, single-column forms, tables as card lists or horizontal scroll with a sticky first column, and a sticky bottom action bar for primary form actions. Touch targets are at least 44×44 px.
|
||
|
||
### Loading, progress, and empty states
|
||
|
||
- Design the loading and empty states together with the populated state. Loading states are skeletons that match the final layout. Empty states have an icon or illustration, one sentence, and a primary action when there is one.
|
||
- Anything that takes more than about 2 seconds, or has server-side steps, shows a progress bar, a numeric percentage, and the current step: "Importing products… 42% — Validating row 1,200 of 2,850." When progress is unknown, show an indeterminate bar with step labels and elapsed time. Never show a bare spinner for more than 3 seconds. Allow cancelling when the back end supports it, and say whether leaving the page interrupts the process.
|
||
- The clicked button shows a spinner, becomes disabled, and changes its label to the in-progress form ("Saving…"). The rest of the form stays visible and read-only.
|
||
|
||
### Lists and pagination
|
||
|
||
- Long lists are paginated on the server, with page sizes 10, 25, 50, and 100. Page, size, sort, and filters live in the URL (`?page=3&pageSize=50&sort=-createdAt`), so views are shareable and survive a refresh.
|
||
- The pager shows "Showing 51–100 of 1,284". Management tables never use infinite scroll; only feeds do.
|
||
- Row selection offers "select all on this page" and, when meaningful, "select all 1,284 matching items" with an explicit confirmation.
|
||
|
||
### Errors
|
||
|
||
- Show every API or action error in the right place: validation errors under their fields, errors about the whole submission in a form-level alert, background or non-form action errors in a toast, and a failed page load as a full-page error with a retry button.
|
||
- Map known server codes to actionable messages. Unknown errors say: "Something went wrong on our side. Try again in a moment. If it keeps happening, contact support and mention reference ID `a1b2c3`." Include the request ID whenever the server returns one.
|
||
- Errors never blank out the page; the shell, breadcrumbs, and back button stay usable.
|
||
- Report unexpected errors, with their request ID, to the error-tracking integration (for example Sentry).
|
||
|
||
### Lazy loading
|
||
|
||
Load everything lazily that can be: routes, heavy widgets (charts, editors, PDF viewers, maps) with skeleton fallbacks, images with `loading="lazy"` and explicit dimensions, select and autocomplete options (fetched on open, searched and paginated on the server), tab content on first activation, and modal content when the modal opens.
|
||
|
||
### Forms
|
||
|
||
- Validate on the client with valibot before submitting, and show errors inline under the field in plain language that says how to fix them ("Enter a price greater than 0. Use a dot as the decimal separator."). Validate on blur first, then on change (`mode: 'onTouched'`).
|
||
- Put server errors in the right place (code in code-patterns.md) and scroll to and focus the first invalid field.
|
||
- Disable the submit button only while submitting, never because the form is invalid; users need to click it to find out what's wrong.
|
||
- Warn before leaving a form with unsaved changes (TanStack Router `useBlocker`). Show the dirty state and offer "Discard changes" next to the primary action when the form is dirty.
|
||
|
||
### Keyboard and context
|
||
|
||
- Tab order follows reading order, Enter submits, and Esc closes. Set sensible default focus, keep primary actions in consistent places, skip confirmations for safe actions, and add shortcuts for the most common operations.
|
||
- Reduce cognitive load: group related fields, use progressive disclosure for advanced options, and prefer sensible defaults over required choices.
|
||
- Preserve context: filters, sort, page, and scroll position survive navigating to a detail page and back.
|
||
- Respect `prefers-reduced-motion` and `prefers-color-scheme`.
|
||
|
||
### Performance
|
||
|
||
- Split code by route (every screen is lazy) and by heavy widget.
|
||
- Paginate on the server; a table page stops at 100 rows. When a list still renders more than about 200 rows, such as a feed, a log, or a large tree, try `content-visibility` first; a virtualization library is outside the stack and needs approval ([rendering-patterns.md](rendering-patterns.md)).
|
||
- Colocate state, split large contexts (`FiltersContext` and `SelectionContext`, not one `TableContext`), and subscribe to store slices with selectors.
|
||
- Memoize table rows and give them stable, primitive props; wrap callbacks and expensive derived data passed to memoized children in `useCallback` and `useMemo`. If the repo enables the React Compiler, skip manual memoization and check the result in the Profiler.
|
||
- Debounce search inputs by 250–400 ms.
|
||
- Profile before optimizing: fix the top three offenders, then measure again.
|
||
- Budgets: shell JS at most 200 KB gzipped, route chunks at most 100 KB, and LCP under 2.5 s on a mid-range laptop over a throttled connection.
|
||
|
||
## Example: route, guard, and screen
|
||
|
||
`apps/<app>/src/guards/require-permission/require-permission.ts`
|
||
|
||
```ts
|
||
import { redirect } from '@tanstack/react-router';
|
||
import type { Permission } from '../../features/access';
|
||
import { ROUTES } from '../../navigation/constants';
|
||
import { useAuthStore } from '../../stores/auth';
|
||
|
||
export function requirePermission(permission: Permission, returnTo: string): void {
|
||
const { session } = useAuthStore.getState();
|
||
if (!session) {
|
||
throw redirect({ to: ROUTES.login, search: { redirect: returnTo } });
|
||
}
|
||
if (!session.permissions.includes(permission)) {
|
||
throw redirect({ to: ROUTES.noAccess });
|
||
}
|
||
}
|
||
```
|
||
|
||
`apps/<app>/src/guards/permission-guard/PermissionGuard.tsx`
|
||
|
||
```tsx
|
||
import type { ReactNode } from 'react';
|
||
import type { Permission } from '../../features/access';
|
||
import { useHasPermission } from '../../stores/auth';
|
||
|
||
type PermissionGuardProps = { permission: Permission; children: ReactNode; fallback?: ReactNode };
|
||
|
||
export function PermissionGuard({ permission, children, fallback = null }: PermissionGuardProps) {
|
||
return useHasPermission(permission) ? children : fallback;
|
||
}
|
||
```
|
||
|
||
`apps/<app>/src/navigation/navigation.ts`
|
||
|
||
```ts
|
||
import { createRootRoute, createRoute, createRouter, lazyRouteComponent } from '@tanstack/react-router';
|
||
import { requirePermission } from '../guards/require-permission';
|
||
import { productListSearchSchema } from '../shared/validations';
|
||
import { ListPageSkeleton } from './components/list-page-skeleton';
|
||
import { RootLayout } from './components/root-layout';
|
||
import { ROUTES } from './constants';
|
||
|
||
const rootRoute = createRootRoute({ component: RootLayout });
|
||
|
||
const productsRoute = createRoute({
|
||
getParentRoute: () => rootRoute,
|
||
path: ROUTES.products,
|
||
validateSearch: productListSearchSchema,
|
||
beforeLoad: ({ location }) => requirePermission('catalog.products.read', location.href),
|
||
component: lazyRouteComponent(() => import('../screen/products/page'), 'ProductsPage'),
|
||
pendingComponent: ListPageSkeleton,
|
||
});
|
||
|
||
export const router = createRouter({ routeTree: rootRoute.addChildren([productsRoute]) });
|
||
|
||
declare module '@tanstack/react-router' {
|
||
interface Register {
|
||
router: typeof router;
|
||
}
|
||
}
|
||
```
|
||
|
||
`apps/<app>/src/screen/products/page.tsx`
|
||
|
||
```tsx
|
||
import { useProductsPage } from '../../features/catalog';
|
||
import { ProductsTemplate } from './templates/products-template';
|
||
|
||
export function ProductsPage() {
|
||
const model = useProductsPage();
|
||
return <ProductsTemplate {...model} />;
|
||
}
|
||
```
|
||
|
||
## Testing
|
||
|
||
- Every feature ships Playwright specs for the happy path, the validation error path, and the server error path. Locate elements by role, label, or `data-testid`, never by CSS class.
|
||
- After implementing any UI, take Playwright screenshots at 1440, 1024, and 390 px wide and inspect them for: text overflowing its container, truncated labels without tooltips, overlapping elements, misaligned columns, invisible focus rings, low-contrast text, content hidden behind fixed headers, horizontal scrollbars on mobile, and empty areas where content should have loaded. Fix, re-screenshot, and repeat until clean, and record the checklist you used.
|
||
- Use `toHaveScreenshot()` for visual regression on island components and key screens. Update snapshots only after reviewing the diff.
|
||
- Run an axe scan (`@axe-core/playwright`, when the repo has it) with no serious or critical issues.
|
||
|
||
```ts
|
||
import { expect, test } from '@playwright/test';
|
||
|
||
test.describe('Edit product screen', () => {
|
||
test('saves changes and confirms with a toast', async ({ page }) => {
|
||
await page.goto('/products/42/edit');
|
||
await page.getByLabel('Product name').fill('Blue Ceramic Mug');
|
||
await page.getByRole('button', { name: 'Save changes to this product' }).click();
|
||
await expect(page.getByRole('status')).toContainText('Product "Blue Ceramic Mug" was saved');
|
||
});
|
||
|
||
test('shows a field error when the name is empty', async ({ page }) => {
|
||
await page.goto('/products/42/edit');
|
||
await page.getByLabel('Product name').fill('');
|
||
await page.getByRole('button', { name: 'Save changes to this product' }).click();
|
||
await expect(page.getByText('Enter a product name. It is shown to customers in the catalog.')).toBeVisible();
|
||
});
|
||
|
||
test('renders correctly at each breakpoint', async ({ page }) => {
|
||
for (const [name, width] of [['desktop', 1440], ['tablet', 1024], ['mobile', 390]] as const) {
|
||
await page.setViewportSize({ width, height: 900 });
|
||
await page.goto('/products/42/edit');
|
||
await expect(page).toHaveScreenshot(`product-edit-${name}.png`, { fullPage: true });
|
||
}
|
||
});
|
||
});
|
||
```
|
||
|
||
## Definition of Done (admin additions)
|
||
|
||
```
|
||
Structure and navigation
|
||
[ ] Title names the page and its object and matches the document title
|
||
[ ] Breadcrumbs show the full hierarchy with linked ancestors
|
||
[ ] Back button returns to the logical parent
|
||
[ ] Complex actions and flows have an info icon with their description and consequences
|
||
|
||
Access
|
||
[ ] Route guard, action gating, and sidebar filtering use the right permission
|
||
[ ] "No access" and 403 cases explain what happened
|
||
|
||
Data and states
|
||
[ ] Long lists are paginated on the server; page, size, sort, and filters are in the URL
|
||
[ ] Changing the page scrolls to the top of the table
|
||
[ ] Long processes show a progress bar, percentage, and current step
|
||
[ ] File uploads show a progress bar, percentage, and cancel
|
||
|
||
Visual
|
||
[ ] Page, navigation, card, and section surfaces are visibly distinct; status and accent colors meet AA
|
||
[ ] Enabled interactive elements use cursor: pointer; disabled ones use not-allowed
|
||
[ ] Sortable headers and every clickable element have an icon, hover, or active indicator
|
||
|
||
Stability and performance
|
||
[ ] No mount/unmount flicker on refetch or state change
|
||
[ ] Rows memoized (or React Compiler on), contexts split, Profiler checked for the heaviest interaction
|
||
|
||
Responsiveness and testing
|
||
[ ] Verified at desktop (≥ 1440), tablet (1024–1439), and mobile (0–1023); no horizontal page scroll
|
||
[ ] Screenshots at all three widths inspected, flaws fixed, re-verified
|
||
[ ] axe scan has no serious or critical issues
|
||
```
|