# Frontend Development — Rules & Guidelines Rules and conventions every frontend developer must follow. Read this before writing your first line of code. --- ## 1. Language & Typing - **TypeScript** is mandatory — no plain JavaScript files (`.js`, `.jsx`) in the codebase. - Use **strict mode** (`"strict": true` in `tsconfig.json`) — the project must compile with zero errors. - Never use `any`. If a type is truly unknown, use `unknown` and narrow it with type guards. - Prefer **interfaces** for object shapes that may be extended, **type aliases** for unions, intersections, and utility types. - Every function must have explicit parameter types and return types — including React components (`React.FC` is discouraged; type props and return `JSX.Element` explicitly). - Use `T | null` or `T | undefined` instead of `Optional` patterns — be explicit about nullability. - Use `as const` for constant literals and enums where it improves type narrowness. - Run `tsc --noEmit` in CI — the codebase must pass with zero type errors. ```tsx // Good interface BanEntry { ip: string; jail: string; bannedAt: string; expiresAt: string | null; } function BanRow({ ban }: { ban: BanEntry }): JSX.Element { return {ban.ip}{ban.jail}; } // Bad — untyped, uses `any` function BanRow({ ban }: any) { return {ban.ip}; } ``` --- ## 2. Reusable Types - All **shared type definitions** live in a dedicated `types/` directory. - Group types by domain: `types/ban.ts`, `types/jail.ts`, `types/auth.ts`, `types/api.ts`, etc. - Import types using the `import type` syntax when the import is only used for type checking — this keeps the runtime bundle clean. - Component-specific prop types may live in the same file as the component, but any type used by **two or more files** must move to `types/`. - Never duplicate a type definition — define it once, import everywhere. - Export API response shapes alongside their domain types so consumers always know what the server returns. ```ts // types/ban.ts export interface Ban { ip: string; jail: string; bannedAt: string; expiresAt: string | null; banCount: number; country: string | null; } export interface BanListResponse { bans: Ban[]; total: number; } ``` ```tsx // components/BanTable.tsx import type { Ban } from "../types/ban"; ``` --- ## 3. Type Safety in API Calls - Every API call must have a **typed request** and **typed response**. - Define response shapes as TypeScript interfaces in `types/` and cast the response through them. - Use a **central API client** (e.g., a thin wrapper around `fetch` or `axios`) that returns typed data — individual components never call `fetch` directly. - Validate or assert the response structure at the boundary when dealing with untrusted data; for critical flows, consider a runtime validation library (e.g., `zod`). - API endpoint paths are **constants** defined in a single file (`api/endpoints.ts`) — never hard-code URLs in components. - **All API functions that perform a `GET` request must accept an optional `signal?: AbortSignal` parameter and forward it to the HTTP client.** This enables hooks to cancel in-flight requests when components unmount, preventing silent state-update errors and wasted resources. When an API function calls another internal API function, thread the signal through to the underlying call. ```ts // api/client.ts const BASE_URL = import.meta.env.VITE_API_URL ?? "/api"; async function get(path: string, signal?: AbortSignal): Promise { const response: Response = await fetch(`${BASE_URL}${path}`, { credentials: "include", signal, }); if (!response.ok) { throw new ApiError(response.status, await response.text()); } return (await response.json()) as T; } export const api = { get, post, put, del } as const; ``` ```ts // api/bans.ts import type { BanListResponse } from "../types/ban"; import { api } from "./client"; export async function fetchBans(hours: number, signal?: AbortSignal): Promise { return api.get(`/bans?hours=${hours}`, signal); } ``` ```ts // hooks/useBans.ts const ctrl = new AbortController(); fetchBans(24, ctrl.signal) // Pass the signal to enable cancellation on unmount .then(resp => { /* ... */ }) .catch(err => { /* ... */ }); ``` ### CSRF Protection Header All state-mutating requests (POST, PUT, DELETE, PATCH) automatically include the custom header `X-BanGUI-Request: 1` via the central API client. This protects against Cross-Site Request Forgery (CSRF) attacks by requiring a custom header that cross-site JavaScript cannot set without CORS preflight. **How it works:** - The `request()` function in `api/client.ts` includes `"X-BanGUI-Request": "1"` in the default headers. - GET, HEAD, and OPTIONS requests are unaffected. - Bearer token authentication bypasses the check (tokens are not CSRF-vulnerable). - The backend `CsrfMiddleware` validates this header for cookie-authenticated state-mutating requests. - Requests missing the header receive a `403 Forbidden` response. **No Action Required:** As a developer, you do not need to manually add this header — the centralized API client handles it automatically. All `api.post()`, `api.put()`, `api.del()` calls will include it. ### Request Deduplication & Shared Caching When multiple components mount simultaneously and need the same data, **implement shared hooks with request deduplication** to avoid duplicate API calls. Use a module-level cache to ensure all consumers share a single in-flight request: - Create a custom hook with module-level state to track in-flight requests - When multiple hook instances request the same data concurrently, they await the same promise - Implement cache invalidation via an exported function that notifies all subscribers - Consumers call the shared hook instead of raw API functions ```ts // hooks/useSharedSetupStatus.ts — shared, deduplicated setup status const subscribers: Set<() => void> = new Set(); let cache: CacheEntry | null = null; export function invalidateSetupStatus(): void { cache = null; subscribers.forEach(notify => notify()); } export function useSharedSetupStatus(): UseSharedSetupStatusResult { const [status, setStatus] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const refresh = useCallback(async () => { const now = Date.now(); const isCacheValid = cache && now - cache.timestamp < 30000; if (!isCacheValid) { cache = { promise: getSetupStatus(), timestamp: now, }; } const result = await cache.promise; setStatus(result); }, []); useEffect(() => { void refresh(); subscribers.add(refresh); return () => { subscribers.delete(refresh); }; }, [refresh]); return { status, loading, error, refresh }; } ``` **When to use shared hooks:** - When a critical status or configuration is checked by multiple components on mount (e.g., setup completion, session validation, feature flags) - When concurrent requests for the same data waste backend resources or introduce race conditions - When cache TTL is short and invalidation is simple **Guidelines:** - Shared hooks should be used in low-level consumer code (direct consumers of the setup flow) - The cache can be **invalidated explicitly** after mutations (e.g., after setup completes, call `invalidateSetupStatus()`) - Cache TTL should be relatively short (30 seconds) unless the data is truly static - Subscribers receive notifications when the cache is invalidated, allowing them to trigger a fresh fetch if needed --- ## 4. Code Organization ### Project Structure ``` frontend/ ├── public/ ├── src/ │ ├── api/ # API client, endpoint definitions, per-domain request files │ ├── assets/ # Static images, fonts, icons │ ├── components/ # Reusable UI components (buttons, modals, tables, etc.) │ ├── hooks/ # Custom React hooks │ ├── layouts/ # Page-level layout wrappers (sidebar, header, etc.) │ ├── pages/ # Route-level page components (one per route) │ ├── providers/ # React context providers (auth, theme, etc.) │ ├── theme/ # Fluent UI custom theme, tokens, and overrides │ ├── types/ # Shared TypeScript type definitions │ ├── utils/ # Pure helper functions, constants, formatters │ ├── App.tsx # Root component, FluentProvider + router setup │ ├── main.tsx # Entry point │ └── vite-env.d.ts # Vite type shims ├── .eslintrc.cjs ├── .prettierrc ├── tsconfig.json ├── vite.config.ts # Dev proxy: /api → http://backend:8000 (service DNS) └── package.json ``` > **Dev proxy target:** `vite.config.ts` proxies all `/api` requests to > `http://backend:8000` by default. Set `VITE_BACKEND_URL` in `frontend/.env` > or your shell to override the backend address for local development outside > Docker. > > Use the compose **service name** (`backend`), not `localhost` — inside the > container network `localhost` resolves to the frontend container itself and > causes `ECONNREFUSED`. ### Pages vs Components The distinction between **`pages/`** and **`components/`** is fundamental to the project structure: - **`pages/`** contains route-level entry point components — exactly **one component per route**. Pages map directly to URL paths (e.g., `JailDetailPage.tsx` → `/jail/:name`). Pages orchestrate the layout and compose multiple components, but contain **no reusable UI logic**. Pages should rarely be reused. - **`components/`** contains **reusable UI building blocks** — anything that could plausibly be used on multiple pages or in multiple contexts. This includes: - Presentation components (Button wrappers, Cards, custom form fields, data tables) - Feature sub-sections (e.g., `JailInfoSection`, `BannedIpsSection` — components that render a logical grouping of related UI within a page) - Modals, dialogs, popovers - Complex, stateful UI patterns **Rule of thumb:** If a component is only ever used on a single page, it **still belongs in `components/`** if it represents a coherent, self-contained piece of UI that could logically be reused on another page in the future. Pages are entry points; components are building blocks. **Example:** `BannedIpsSection` lives in `components/jail/` (not `pages/jail/`) because it is a reusable UI section that presents banned IPs. If a future report or dashboard also needed to show banned IPs, the same component could be imported and reused. By contrast, `JailDetailPage.tsx` lives in `pages/` because it is the top-level route component. ### Tab Orchestration — ConfigPage Example When a page contains tab-based navigation (like the configuration page), isolate routing and tab state management into a dedicated **container component** to prevent the page from becoming over-centralized. This pattern applies to any multi-tab page. **Architecture:** 1. **Page component** (`ConfigPage.tsx`) — renders page layout (header, title, description) and delegates tab routing to a container. 2. **Container component** (`ConfigPageContainer.tsx`) — orchestrates tab navigation, manages which tab content is visible, and routes tab selection events. 3. **Tab router hook** (`useTabRouter.ts`) — encapsulates tab state synchronization with browser history and supports deep linking (e.g., navigating directly to a specific tab with optional active item like a jail name). 4. **Tab components** (`JailsTab.tsx`, `FiltersTab.tsx`, etc.) — domain-specific tab content; each is fully self-contained and receives tab-specific props only. **Component tree:** ``` ConfigPage (page layout) └── ConfigPageContainer (tab orchestration) ├── useTabRouter (routing logic) ├── JailsTab (jail editing UI) ├── FiltersTab (filter editing UI) ├── ActionsTab (action editing UI) ├── ServerTab (server settings UI) └── RegexTesterTab (regex testing UI) ``` **Benefits:** - **Focused pages** — `ConfigPage` renders only layout; routing logic is in the container. - **Reusable routing** — `useTabRouter` can be used by other pages with tab navigation. - **Isolated tabs** — each tab is a focused component; no shared state entanglement. - **Deep linking** — tab state is synchronized to browser history, allowing bookmarkable URLs and the back/forward buttons to work correctly. **Key pattern:** ```tsx // hooks/useTabRouter.ts — routes and state export type ConfigTabId = "jails" | "filters" | "actions" | "server" | "regex"; export function useTabRouter(): { activeTab: ConfigTabId; selectTab: (tab: ConfigTabId) => void; ... } { const location = useLocation(); const navigate = useNavigate(); // Sync tab state to location.state for deep linking // ... (see implementation) } // components/config/ConfigPageContainer.tsx — renders tabs export function ConfigPageContainer(): JSX.Element { const { activeTab, selectTab } = useTabRouter(); return ( <> {/* Tabs */} {/* Tab content panels, conditionally rendered via CSS */} ); } // pages/ConfigPage.tsx — layout only export function ConfigPage(): JSX.Element { return (
{/* Page header, title, description */}
); } ``` **Avoid:** - Mixing page layout, tab orchestration, and tab content in one file. - Duplicating tab state across multiple hooks or components. - Hardcoding tab IDs as strings — use the `ConfigTabId` type. ### Separation of Concerns - **Pages** handle routing and compose layout + components — they contain no business logic. - **Components** are reusable, receive data via props, and emit changes via callbacks — they never call the API directly. - **Hooks** encapsulate stateful logic, side effects, and API calls so components stay declarative. - **API layer** handles all HTTP communication — components and hooks consume typed functions from `api/`, never raw `fetch`. - **Types** are purely declarative — no runtime code in `types/` files. - **Utils** are pure functions with no side effects and no React dependency. - **Theme** contains exclusively Fluent UI custom token overrides and theme definitions — no component logic. ### Providers — App-Wide vs Page-Scoped The `providers/` directory is reserved for **app-wide context providers** — providers that wrap the entire application or large sections of it and are used by many pages or components. **App-wide providers belong in `providers/`:** - `AuthProvider` — authentication state for the whole app - `ThemeProvider` — theme/styling state for the whole app - `TimezoneProvider` — timezone preference for the whole app **Page-scoped providers belong co-located with their consumer:** If a React Context provider is used by **only one page** (e.g., `DashboardFilterProvider` is used only by `DashboardPage`), it should live **in the same directory as the page** or in a subdirectory alongside the page's components. This prevents the `providers/` directory from being cluttered with page-specific state and makes the scope of these providers clear to future contributors. **Example:** `DashboardFilterProvider` manages dashboard time-range and origin filters. It is instantiated only inside `DashboardPage.tsx` and its sub-components. Therefore, it lives in `pages/DashboardFilterProvider.tsx` (or `pages/dashboard/DashboardFilterProvider.tsx` if the page is split into a subdirectory), not in `providers/`. ### State Ownership & Prop Drilling When a page uses a hook (e.g., `useJails()`) that provides state and actions, and this state needs to be accessed by multiple child components, **eliminate prop drilling by wrapping the page in a context provider**. This reduces coupling, simplifies refactoring, and keeps prop lists focused on component-specific data. **When to use context instead of props:** - A page calls a hook that returns both data and actions (e.g., `useJails()` returns `jails`, `loading`, `refresh`, `startJail`, etc.) - Two or more child components need access to the same hook's state - The prop chain would be longer than 2 levels deep **Pattern:** 1. Create a context and provider in the same directory as the page's components (e.g., `pages/jails/JailContext.tsx`) 2. Wrap the page content with the provider, passing the hook's result as the context value 3. Child components use the context hook instead of receiving props 4. Update tests to wrap components with the provider **Example:** ```tsx // pages/jails/JailContext.tsx const JailContext = createContext(undefined); export function JailProvider({ children }: { children: ReactNode }): JSX.Element { const jailState = useJails(); return {children}; } export function useJailContext(): JailContextValue { const context = useContext(JailContext); if (!context) throw new Error("useJailContext must be used within JailProvider"); return context; } // pages/JailsPage.tsx export function JailsPage(): JSX.Element { return ( {/* Uses useJailContext() */} ); } ``` **Important:** Context should only wrap the minimal subtree that needs access. Do not wrap the entire app with page-specific contexts — keep providers scoped to where they're used. --- ## 5. UI Framework — Fluent UI React (v9) - **Fluent UI React Components v9** (`@fluentui/react-components`) is the only UI component library allowed — do not add alternative component libraries (Material UI, Chakra, Ant Design, etc.). - Install via npm: ```bash npm install @fluentui/react-components @fluentui/react-icons ``` ### FluentProvider - Wrap the entire application in `` at the root — this supplies the theme and design tokens to all Fluent components. - The provider must sit above the router so every page inherits the theme. ```tsx // App.tsx import { FluentProvider, webLightTheme } from "@fluentui/react-components"; import { BrowserRouter } from "react-router-dom"; import AppRoutes from "./AppRoutes"; function App(): JSX.Element { return ( ); } export default App; ``` ### Theming & Design Tokens - Use the built-in themes (`webLightTheme`, `webDarkTheme`) as the base. - Customise design tokens by creating a **custom theme** in `theme/` — never override Fluent styles with raw CSS. - Reference tokens via the `tokens` object from `@fluentui/react-components` when writing `makeStyles` rules. - If light/dark mode is needed, switch the `theme` prop on `FluentProvider` — never duplicate style definitions for each mode. ```ts // theme/customTheme.ts import { createLightTheme, createDarkTheme } from "@fluentui/react-components"; import type { BrandVariants, Theme } from "@fluentui/react-components"; const brandColors: BrandVariants = { 10: "#020305", // ... define brand colour ramp 160: "#e8ebf9", }; export const lightTheme: Theme = createLightTheme(brandColors); export const darkTheme: Theme = createDarkTheme(brandColors); ``` ### Styling with `makeStyles` (Griffel) - All custom styling is done via `makeStyles` from `@fluentui/react-components` — Fluent UI uses **Griffel** (CSS-in-JS with atomic classes) under the hood. - Never use inline `style` props, global CSS, or external CSS frameworks for Fluent components. - Co-locate styles in the same file as the component they belong to, defined above the component function. - Use `mergeClasses` when combining multiple style sets conditionally. - Reference Fluent **design tokens** (`tokens.colorBrandBackground`, `tokens.fontSizeBase300`, etc.) instead of hard-coded values — this ensures consistency and automatic theme support. - **Inline styles are only allowed for genuinely dynamic values** (e.g., tooltip position calculated from mouse position, or height derived from data count). All static layout properties (`display`, `gap`, `margin`, `padding`, colour) must go in `makeStyles`. ```tsx import { makeStyles, tokens, mergeClasses } from "@fluentui/react-components"; const useStyles = makeStyles({ root: { padding: tokens.spacingVerticalM, backgroundColor: tokens.colorNeutralBackground1, }, highlighted: { backgroundColor: tokens.colorPaletteRedBackground2, }, }); function BanCard({ isHighlighted }: BanCardProps): JSX.Element { const styles = useStyles(); return (
{/* ... */}
); } ``` ### Component Usage Rules - **Always** prefer Fluent UI components over plain HTML elements for interactive and presentational UI: `