ar-test/docs/FRONTEND_RULES.md
2026-10-27 16:29:00 +05:30

18 KiB
Raw Blame History

Frontend Rules — AR-Test

React 19 + React Router 7 (framework mode, client loaders/actions) + TypeScript + Tailwind CSS 4 + PocketBase JS SDK.

These rules apply to everything under app/. Read them before changing code; a change that breaks one of them is not done.


1. Reusability

Repeated code is a defect, not a style preference.

  • Search before writing. Grep app/components, app/hooks, app/lib and app/services for what you need. A second implementation of something that already exists is the most expensive mistake.
  • Second occurrence = extract. Write it inline once. The second time, extract it to a shared component/hook/util/constant and update the first caller too. Never a third copy.
  • Extend, don't clone. A variant is a new prop, not a copied file. AssetCard + AssetCardCompact as two files with duplicated markup is a bug.
  • Repeated JSX is data. Blocks that differ only in text/icon/link become an array and one .map() over one component.
  • Repeated stateful logic → hook in app/hooks/.
  • Repeated pure logic → util in app/lib/. One function, one place.
  • Constants are declared once. Any string, URL, collection name, route path, key or option list used twice is imported, not retyped.
  • Types are composed. Use Pick, Omit, Partial, z.infer. Never hand-write a second interface with the same fields.
  • Delete what you replaced. An extraction that leaves the old copies behind made things worse.

Exception: two things that merely look alike but serve different requirements are not duplication. Reuse identical functionality, not coincidental resemblance.

1.1 Matching classes are one component (non-negotiable)

When two or more elements carry the same classes — or most of them — they are one component, and both must use it. Not the third time; the second. A class string that differs only by a margin, a weight or one colour is the same thing drawn twice; the difference becomes a prop or a variant.

  • Visual identity is what counts: surface (background, border, radius, padding, shadow), typography (size, weight, colour, tracking, case) and shape. A match on those is a component.
  • Layout glue alone is not. flex items-center justify-between gap-4 or grid-cols-* on its own is how Tailwind is written; wrapping it adds a name without removing anything.
  • Text is a component, never a class string. Every piece of text (p, span, h1–h4, label, dt, dd) renders through <Text> with a named variant (e.g. <Text as='h1' variant='title'>). Size, weight, colour, tracking and case live in the variant; className carries only layout (margin, width, alignment, visibility).
  • A missing variant is a variant added to Text (or the relevant primitive), never a class string at the call site.
  • A shared component may take className for placement (margin, grid span), never to restyle what makes it that component. A new look is a new variant.

Check with a scan, not by eye. Before handing over UI work, compare class strings — identical ones and any two sharing about three-quarters of their classes, including two in the same file — and compare JSX structure: the same element tree appearing twice (e.g. an icon + input wrapper, a Cancel + Save footer) is one component even if no single class string repeats. Each hit is merged or explicitly justified as layout glue.


2. Imports

  • Import the names you use, never the namespace. import { useState, useEffect } from 'react', not import * as React from 'react'.
  • Types come through the same import with type: import { useState, type ReactNode } from 'react'.
  • Always the ~/ alias, never deep relative paths (../../).
  • Exception — vendored source: files under components/ui/ that come from shadcn keep whatever upstream wrote, so shadcn add and upstream diffs still apply cleanly.

3. Files and components

  • One component per file, named after the file. Two components in one file fails review at any size.
  • 150-line cap for every file, routes included. Past that, split into focused components — one file, one visual/behavioural responsibility.
  • Extract when it is a component, not in anticipation. A panel, list item, control or form is its own file from the moment it exists. Markup pulled out only to shorten a parent is not.
  • File names are kebab-case (asset-card.tsx); the exported component is PascalCase (AssetCard).
  • Feature components live in components/<feature>/ (e.g. components/assets/, components/auth/, components/ar-viewer/). Shared primitives live in components/ui/. The moment a feature component is used by a second feature, it moves to ui/ — it is never copied.

3.1 Split a feature folder past ~8 files

Past about eight components, group into subfolders by the page area the component serves — typically list/, detail/, form/, plus a folder for any sub-feature that owns several files. A component used by two areas of the same feature stays at the feature root.

components/assets/
    list/      asset-grid.tsx, asset-card.tsx, pagination.tsx
    form/      asset-form.tsx, file-or-url-field.tsx
    detail/    preview-viewer.tsx, qr-panel.tsx
  • Drop the prefix the folder already states. Inside assets/list/, the file is card.tsx or asset-card.tsx only if removing the word leaves it ambiguous.
  • The exported name keeps its full meaning (AssetCard), so call sites read clearly without tracing the import.

Eight is a threshold, not a law.


4. Routes

app/routes mirrors the URL. Someone who knows the URL must be able to name the file, and vice versa.

  • A folder exists only to hold more than one thing. A single-file route is that file (routes/login.tsx), not routes/login/route.tsx. A folder is right when a section owns several routes or a layout wrapping children.
  • React Router naming conventions: $ marks a dynamic segment ($id ↔ :id), and a dot is the URL's slash (preview.$id.tsx ↔ /preview/:id).
  • Layouts are layout.tsx, section landings are index.tsx. route.tsx names nothing — never use it.
  • Routes are registered explicitly in app/routes.ts. File names have no effect on URLs, so the convention is a discipline: rename the file and its routes.ts entry together. A file under app/routes that no entry points to is dead code.
  • Quote $ paths in the shell: git mv 'routes/preview.$id.tsx' ….

Target layout for this app:

URL File
(auth guard + sidebar layout) routes/admin/layout.tsx
/ (redirects to /projects) routes/admin/index.tsx
/projects routes/admin/projects/index.tsx
/projects/:id routes/admin/projects/$id.tsx
/assets (?filter=all|unassigned|<projectId>) routes/admin/assets/index.tsx
/assets/:id routes/admin/assets/$id.tsx
/settings routes/admin/settings.tsx
/preview/:id (old links, redirects) routes/admin/preview.$id.tsx
/login routes/login.tsx
/ar/:id routes/ar.$id.tsx
* routes/not-found.tsx
  • Route files hold composition, not implementation. A route wires params, loader/action data and state to components; markup lives in components/<feature>/.
  • Auth is checked in one place — the protected layout's clientLoader — never repeated in each page's loader.
  • Shared admin data comes from the layout. Projects (with asset counts), settings and totals are loaded once by routes/admin/layout.tsx; pages read them with useAdminData() instead of loading them again.
  • Dialogs used from several pages are rendered once by AdminDialogsProvider and opened with useAdminDialogs(). Each dialog submits with its own useFetcher to the route that owns the action (/projects, /assets, /settings).

5. UI primitives (shadcn/ui)

app/components/ui/ holds shadcn/ui primitives, added with npx shadcn@latest add <name>. The cn() helper lives in app/lib/utils.ts.

  • Check the registry before writing any component. A hand-written select, dialog, table, dropdown, tooltip, tabs or sheet is a defect when shadcn ships one. Sequence: search the registry → install → adapt to the theme with a variant. Only when nothing fits do you write one, in components/<feature>/.
  • Prefer reuse in general: an existing library, an established pattern in this repo, or a public reference over new code.
  • Vendored, not authored. Upstream shadcn files are exempt from the import and comment rules. Anything written by hand (e.g. Text) follows every rule.
  • Never restyle a primitive at the call site. A new look is a new variant on the primitive.
  • Add on demand, when a screen needs it.
  • Theme tokens only inside primitives — no raw Tailwind palette classes, no hex values.
  • Check the CLI's output. shadcn add rewrites app/app.css with its own theme and has installed an unrelated cn npm package with import { cn } from "cn". After every add: restore app/app.css, run yarn remove cn, and point the import at ~/lib/utils.
  • shadcn's token names are mapped in app/app.css (foreground, muted-foreground, popover, input, ring, …) so vendored files render in this theme without edits. Small edits to fit the dark theme are fine; keep them minimal.
  • Deliberate exception — the admin sidebar (components/admin/sidebar/) is hand-built to the approved design: a fixed list of links with a Sheet on mobile. shadcn's Sidebar brings collapse/icon modes and replaces Button and Input, none of which the design uses.

6. Theme

The palette is defined once, as @theme tokens in app/app.css. Tailwind 4 is CSS-first; there is no tailwind.config.js.

Dark admin with an orange accent, from the approved design (Geist / Geist Mono):

Token Use
bg-background, bg-sidebar Page and sidebar background
bg-surface (cards), -dialog, -raised, -control, -sunken, -well Surfaces from darkest to lightest use
bg-surface-hover-subtle, bg-surface-hover, bg-surface-pressed Hover and selected states
bg-overlay Dialog / sheet backdrop
primary, primary-hover, primary-foreground Orange actions; white text on orange
accent-100 … accent-900 Orange shades for illustrations
text-text-primary / -emphasis / -secondary / -subtle / -muted / -faint / -placeholder Text hierarchy on dark surfaces
text-ink, bg-viewer The light customer AR page
border-border-divider / -subtle / -dialog / -control / -dashed / -strong Dividers, card rings, control borders, hover ring
danger, warning, success, note-* Status colours and the amber note
logo-tile-*, logo-chip-*, logo-badge Client logo tiles and backing chips (light / dark)
qr-surface QR code background

Radii are tokens too (rounded-chip 5, -option 7, -item 8, -control 9, -group 10, -field 11, -card-sm 12, -card 14, -panel 16).

Breakpoints: Tailwind's sm (640) plus split (960) and wide (1200) for the login layout. Add a named breakpoint to @theme rather than writing min-[960px]:.

  • Tinted surfaces come from toneSurface (components/ui/tone.ts) — badges, icon tiles and alerts share it.

  • Client brand colours are data, not theme. A project's colours (logo_bg_color, brand_color, button_text_color) are applied with an inline style; preset lists live in data/projects/constants.ts. Colours are picked with ui/color-picker.tsx (presets + system picker + hex field) — shadcn has no colour picker.

  • Never hardcode a hex value (bg-[#0D0D0D]) or reach for a stock palette class (bg-neutral-900) in feature code. If a shade is missing, add a token.

  • SVG illustrations may use token colours via var(--color-…); brand-specific gradients get their own named tokens.

6.1 Type scale

  • Text sizes are @theme tokens: 3xs 10, 2xs 11, xs 12, sm 13, base 14, md 15, lg 17, xl 20, display 26, and for the login headings 2xl 28, 3xl 32, 4xl 36, 5xl 44 (px). Changing how big the app's text is means editing the tokens — one place, never the call sites.
  • Never an arbitrary size (text-[11px], text-[15px]). If no step fits, add one to @theme.
  • CSS outside Tailwind reads the same tokens (font-size: var(--text-sm)).
  • The small uppercase label is <Text variant='eyebrow'>, never retyped classes.

7. Where non-component files go

Kind Location Import as
Hooks app/hooks/ ~/hooks/...
Constants, static data app/data/ ~/data/...
Pure helpers app/lib/ ~/lib/...
Types app/types/ ~/types/...
PocketBase client and data access app/services/ ~/services/...
Zod schemas app/schemas/ ~/schemas/...

Never inline these in component or route files.

  • Group by feature. hooks/, data/, lib/, schemas/ mirror components/<feature>/ — e.g. schemas/assets/asset-form.ts, lib/assets/media-url.ts. A file is placed by the feature it is about, not the feature that imports it.
  • Only feature-less code stays at the root — generic helpers (lib/format.ts) and app-wide data (data/routes.ts, data/brand.ts).
  • Folder prefix rule applies: inside data/assets/, a file is constants.ts, not asset-constants.ts.
  • lib/utils.ts never moves — shadcn imports cn() from that exact path.

8. Data access (PocketBase)

  • Components never call pb directly. All PocketBase access goes through functions in app/services/ (e.g. services/assets.ts → listAssets, getAsset, createAsset, updateAsset, deleteAsset). The client instance lives in one file in services/.
  • Collection records are typed in app/types/ and service functions return those types — no any for records.
  • Collection and field names are constants, never retyped strings.
  • Shared record logic lives once — e.g. resolving a model URL (uploaded file first, then external URL) is one helper, not repeated per page.
  • Loading = clientLoader, writing = clientAction. Pages read with useLoaderData, write with useSubmit/<Form>/useFetcher.
  • Never mirror request state into useState. Pending state comes from useNavigation() / fetcher.state; errors from useActionData() / fetcher.data. A hand-rolled isSubmitting or const [error, setError] fed from an action result is a second copy that goes stale.
  • No try/catch in components. Errors are caught in the loader/action (or service) and returned as data, or thrown to the route ErrorBoundary.
  • Always toast on success and on failure of a write, from one shared place (a hook), not re-implemented per page.

9. Application rules

  • State: local state or URL search params first (pagination, filters, tabs belong in the URL). Global state only when it is truly global.
  • Forms: react-hook-form + Zod only. No per-field useState. Schemas live in app/schemas/.
  • Loading and errors: reusable <LoadingScreen /> / <ErrorScreen /> / empty-state components — never a hand-built spinner per page.
  • A one- or two-line handler belongs in the JSX. Name it only when it grows past a couple of statements, is used twice, or genuinely needs useCallback (memoized child or dependency array).
  • Performance: memoize where it matters. Don't create new objects/functions inline when the prop feeds a memoized child, a dependency array or a list row. A trivial arrow on a plain DOM element is fine.
  • Styling: Tailwind only, theme tokens only.
  • Accessibility: every input has a linked <label>, icon-only buttons have aria-label, errors use role='alert'.

10. UI copy

Copy tells the user what they are looking at and what they can do. It never explains the system.

  • No source, ownership or mechanics — not "stored in PocketBase", "generated automatically", "synced", "read-only".
  • Public pages reveal nothing internal. The login page and the AR viewer (/ar/:id) are seen by people outside the team: no feature lists, internal workflow, file formats, data or admin details.
  • When a slot has nothing user-facing to say, drop it. An empty subtitle beats an explanation of the system.
  • Exception: admin-facing helper text may say what a field controls ("Optional — used on iPhone and iPad").

11. Global scripts and CSS

  • <model-viewer> is loaded once, globally, in root.tsx. Pages wait for the custom element; they do not inject their own script tags.
  • Library stylesheets that must outlive one page are @imported in app/app.css, never imported from a route module — in the production build a route's CSS is removed when the route stops matching. Verify styling fixes with yarn build && yarn start, not only yarn dev.
  • Keyframes and @utility styles live in app/app.css.

12. Devices

  • The admin (dashboard, preview) is desktop-first, but must remain usable on a phone.
  • The AR viewer (/ar/:id) is mobile-first — it is opened by scanning a QR code. Test it on real iOS (Quick Look) and Android (Scene Viewer) devices.
  • The login page works at every width.

13. Type safety and checks

  • yarn typecheck must pass before any commit.
  • strict is on. Don't use any for records, props or action data; type them.
  • Where a lookup can miss (find, a route param, getOne on a deleted record), let it return | undefined / handle the error, and deal with the miss at the call site.

Appendix — Status

Open items:

Rule Open item
§5 shadcn The older hand-adapted primitives (button, input, dialog, card, badge) were not re-added through the CLI. New ones (select, sheet, switch, textarea, breadcrumb) were.
§8 Security ar_assets API rules still allow anyone to create, edit and delete. The new projects and app_settings collections only allow signed-in users to write.