From 511a5df25187b8906c9a7b4d321362227649ce4f Mon Sep 17 00:00:00 2001 From: Avi Shah Date: Thu, 15 Oct 2026 14:23:17 +0530 Subject: [PATCH 1/7] ADD: irene-react-patterns skill for working in this repo, and a Storybook preview launch config. --- .claude/launch.json | 11 + .claude/skills/irene-react-patterns/SKILL.md | 85 ++++++++ .../references/api-and-data.md | 200 ++++++++++++++++++ .../references/components-and-styles.md | 196 +++++++++++++++++ .../references/configuration.md | 57 +++++ .../references/routing.md | 62 ++++++ .../references/testing.md | 49 +++++ .../references/websocket.md | 69 ++++++ 8 files changed, 729 insertions(+) create mode 100644 .claude/launch.json create mode 100644 .claude/skills/irene-react-patterns/SKILL.md create mode 100644 .claude/skills/irene-react-patterns/references/api-and-data.md create mode 100644 .claude/skills/irene-react-patterns/references/components-and-styles.md create mode 100644 .claude/skills/irene-react-patterns/references/configuration.md create mode 100644 .claude/skills/irene-react-patterns/references/routing.md create mode 100644 .claude/skills/irene-react-patterns/references/testing.md create mode 100644 .claude/skills/irene-react-patterns/references/websocket.md diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 000000000..5f18425dc --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "storybook", + "runtimeExecutable": "pnpm", + "runtimeArgs": ["--filter", "@irene/ui", "storybook", "--no-open"], + "port": 6006 + } + ] +} diff --git a/.claude/skills/irene-react-patterns/SKILL.md b/.claude/skills/irene-react-patterns/SKILL.md new file mode 100644 index 000000000..3578997cc --- /dev/null +++ b/.claude/skills/irene-react-patterns/SKILL.md @@ -0,0 +1,85 @@ +--- +name: irene-react-patterns +description: How code is written in the irene-react monorepo (Appknox dashboard, React + TanStack Router/Query + Tailwind + Zustand). Use this skill whenever adding or changing anything in apps/dashboard or packages/* — a page, route, component, form, layout, API endpoint, service, query, mutation, store, websocket/live-update handling, normalized cache, configuration (getConfigValue, feature flags, whitelabel), translation, or test — and whenever porting a screen from the Ember app (irene). Also use it when the user asks where something should go, how a feature should be structured, or "how do we do X here", even if they don't name a specific pattern. +--- + +# irene-react patterns + +A React port of Appknox's Ember dashboard (irene). New code should look like the +code around it. `CLAUDE.md` is the authority on styling, TypeScript, comments, +tests, storage and commits; read it first. This skill covers structure and +per-layer patterns. + +## Map + +``` +apps/dashboard/src/ + routes/ thin TanStack file routes: guards, search params, loader, title, component + features// real code for one domain + pages// index.tsx + components/ hooks/ used only by that page + components/ hooks/ queries/ schemas/ actions/ utils/ store.ts + index.ts public entry, only if something outside renders the feature + components/ layouts/ hooks/ queries/ actions/ utils/ app-wide equivalents +packages/ + api/ endpoints, services, types, transforms, stores, normalization, request client + websocket/ server push + ui/ Ak* components, icons, svgs, styles/theme.css + translations/ en.json + ja.json, akMT, , FORMATS + config/ constants/ enums/ +``` + +## Where does it go? + +Narrowest level that uses it; move up when a second user appears. + +| What | Where | +| ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| URL, guard, search params, title | `routes/…/.tsx` | +| Page | `features//pages//index.tsx` | +| Component: one page / one feature / app-wide | `pages//components/` / `features//components/` / `src/components/` | +| Generic, no app data or API | `packages/ui/src/components/ak-/` | +| Endpoint paths / HTTP call / response types | `packages/api/src/services//endpoints.ts` / `service.ts` / `types.ts` | +| Query keys + `xOptions()` | `features//queries/` or `src/queries/` | +| Form schema + typed field | `features//schemas/
.ts` | +| **Action**: plain async fn taking `queryClient`; spans cache/stores/storage, or called from guards/loaders | `actions/` (`endSession`, `setupUserAndOrgContext`) | +| **Hook** (`use…`): re-renders on state, or tied to component lifetime. Hands work to actions (`useLogout` → `endSession`) | `hooks/` (`useOrganization`, `useDashboardWebsocket`) | +| Client-only shared state | Zustand: `features//store.ts` or `packages/api/src/stores/` | +| Server codes (status, platform, risk…) | `ENUMS` from `@irene/enums`, never raw numbers | +| Client-named constants (HTTP statuses, hostnames, support email) | `@irene/constants` | +| Deployment settings / release constants / backend config | `@irene/config` / `@irene/config/product` / `configurationStore` (see [configuration.md](references/configuration.md)) | +| Live updates | tag records in services, then `useWebsocketSignal` / `useWebsocketRecord` (see [websocket.md](references/websocket.md)) | + +## Building a feature (bottom-up) + +1. Endpoints, types, service in `packages/api`. Then query keys and options. + See [api-and-data.md](references/api-and-data.md). +2. A thin route. See [routing.md](references/routing.md). +3. The page and its components. See [components-and-styles.md](references/components-and-styles.md). +4. Live updates if the data changes server-side. Usually tagging the record is + enough. See [websocket.md](references/websocket.md). +5. Copy in **both** `en.json` and `ja.json`. Use `` in + JSX, and `akMT()` in props, schemas, toasts and titles. Format dates and + numbers through the named `FORMATS`. +6. Tests next to the code (MSW + factories, ≥90% coverage). See + [testing.md](references/testing.md). +7. Porting from irene: carry every condition across. Record deliberate + differences in `DESIGN-DECISIONS.md` and scenarios in `QA-SCENARIOS.md`. + +## Everywhere + +- JSDoc on every export, saying what it does and **why**. +- Import via package paths (`@irene/ui/ak-button`, `@/features/…`). Apps never + use `@ui/*`, `@api/*` or `@config/*`. +- No `any`, `!`, `@ts-ignore` or `as unknown as`. Derive types from `z.infer`, + `ReturnType`, enums or the route tree. +- Server data lives in TanStack Query. Stores hold client state only. +- Records that are pushed or shared across queries are tagged in the service + (`tagRecordForCaching`). +- Component files stay under 350 lines of code (lint). Private helpers are + `_prefixed` and not exported. Use `data-test-*` hooks for tests. + +## Before finishing + +```bash +pnpm lint:fix && pnpm lint && pnpm lint:types && pnpm --filter @irene/dashboard test +``` diff --git a/.claude/skills/irene-react-patterns/references/api-and-data.md b/.claude/skills/irene-react-patterns/references/api-and-data.md new file mode 100644 index 000000000..53f8f4436 --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/api-and-data.md @@ -0,0 +1,200 @@ +# API, queries, mutations and state + +Flow: **endpoints → service → query options → component**, one file per step. + +## Endpoints, types, index (`packages/api/src/services//`) + +```ts +// endpoints.ts: path builders only; encode segments; `as const` +export const OrganizationEndpoints = { + list: () => `${API_NAMESPACES.v1}/organizations` as const, + me: (id: number | string) => + `${API_NAMESPACES.v1}/organizations/${encodeURIComponent(id)}/me` as const, +}; + +// index.ts: always this shape +export * from './endpoints'; +export type * from './types'; +export { default as OrganizationService } from './service'; +``` + +- Namespaces: `v1` `api`, `v2` `api/v2`, `v3` `api/v3`, `hudson` + `api/hudson-api`. Use the one irene used for that endpoint. Tests build MSW + URLs from the same endpoints. +- `types.ts`: `Api*` interfaces with the server's snake_case fields, plus + `ApiRequest` and `ApiResponse`. + +## Service (`service.ts`) + +A default-exported class of `public static readonly` arrow functions. Each one +calls `apiRequest.(url, …)`, which returns the **body**. + +```ts +public static readonly getOrganizations = async () => { + const page = await apiRequest.get>( + OrganizationEndpoints.list(), { signal: AbortSignal.timeout(REQUEST_ABORT_TIMEOUT_MS) }); + + return transformPaginatedResponse(page); +}; +``` + +- **Lists**: `ApiPageEnvelope` → `transformPaginatedResponse` → `ApiPage` + (`items`, `count`, `hasNext`…). Components never read `results`. +- **JSON:API responses** (`data.attributes`, kebab-case) are flattened in + `utils/transforms.ts`. +- **Timeouts** are off by default. Add `AbortSignal.timeout(REQUEST_ABORT_TIMEOUT_MS)` + to requests that hold a screen (loaders, boot). Never add it to uploads. +- **Tag** records that are pushed or shared (see Normalized cache below). +- Resolve instead of rejecting only when failure _is_ the answer + (`StatusService`). Otherwise let it reject. + +## Enums and status codes + +- Server codes come from `ENUMS` (`@irene/enums`, ported 1:1 from irene): + `submission.status === ENUMS.SUBMISSION_STATUS.ANALYZING`, never `=== 6`. +- Each group also has `UNKNOWN` (-1), `BASE_VALUES` / `BASE_CHOICES` (as + declared), and `VALUES` / `CHOICES` (with UNKNOWN). +- Type fields from the group: + `type ApiSubmissionStatus = (typeof ENUMS.SUBMISSION_STATUS)['BASE_VALUES'][number]`. +- Group values with typed `Set`s and `Record`s (`FAILED_STATUSES`, + `PROGRESS_BY_STATUS` in `upload-app/utils.ts`), not `===` chains. +- Display, in order of preference: the server's `*_humanized` field, then + `ENUMS_DISPLAY` (e.g. `'iOS'`), then reduce to an outcome and `akMT` it. + Never show the key. +- Adding an enum: copy it exactly from irene into + `packages/enums/src/categories/.ts`, and update the group and key + counts in `packages/enums/src/index.test.ts`. +- HTTP statuses: `HTTP_STATUS_CODES` from `@irene/constants`, compared against + `getApiErrorStatus(error)`. Never bare numbers. Add missing codes, with a doc + comment, to `status-codes.ts`. The type is `HttpStatusCode`. + +## Queries (`features//queries/.ts`) + +```ts +export const organizationKeys = { + all: () => ['organization'] as const, + me: (orgId: number | string) => [...organizationKeys.all(), 'me', orgId] as const, +}; + +/** Builds the query for this account's role in one organization. */ +export const organizationMeOptions = (orgId: number | string) => + queryOptions({ + queryKey: organizationKeys.me(orgId), + queryFn: () => OrganizationService.getOrganizationMe(orgId), + staleTime: Infinity, + }); +``` + +- **Every `queryFn` calls a service**, never `apiRequest` or `fetch`. It may + add logic around the call. +- Keys nest under `all()`, so `invalidateQueries({ queryKey: xKeys.all() })` + clears the whole domain. +- Defaults: 30s stale time, retries only on network errors and 5xx, no + refetch on focus. Comment any override (`staleTime: Infinity`, + `retry: false` when a 404 is an answer). + +**Reading**, always through the `xOptions()` builder: + +- In a component that renders the data: `useQuery(xOptions())`. Handle + `isPending` with a skeleton and errors in place (`getApiErrorStatus`, + `isRateLimited`). Most pages fetch this way. +- In guards, loaders and actions: `await queryClient.query(xOptions())`. If a + loader pre-fills the cache, the component still reads it with `useQuery`. + Never use `useLoaderData`. +- Conditional queries use `enabled`, never a hook inside an `if`. No + `useEffect` fetching. `getQueryData` only for rare merges. + `useSuspenseQuery` and `useInfiniteQuery` aren't used. + +## Mutations + +Put `useMutation` inline when it's short, or in a `use` hook when the +logic is long or reused (`useLogin`, which returns `{ login, failure }`). + +```ts +const recover = useMutation({ + mutationFn: ({ username }: RecoverFormSchema) => AuthService.recoverPassword(username), + onError: unlessRateLimited((error) => { + const message = getApiFieldErrors<'username'>(error).username?.[0]; + + if (message) { + form.setError('username', { message }); + } else { + akNotify.error(akMT('somethingWentWrong')); + } + }), +}); +``` + +- `mutationFn` calls a service. Trigger with `.mutate()` and handle outcomes + in callbacks; `mutateAsync` isn't used. +- `isPending` → ``. Use `onSettled` for "either way" cleanup + (`useLogout`). Mutations are never retried. +- Wrap `onError` in `unlessRateLimited` (429s are announced globally). Field + errors go onto the form; anything else becomes `akNotify.error(akMT(…))`. +- Updating the cache afterwards, in order of preference: + 1. tagged reply → `useNormalizedRecordCache().write(type, record)` + 2. new row in a visible list → `prependRecordToPage` + 3. patch one row → `setQueryData` + `patchPaginationItem` + 4. otherwise `invalidateQueries` +- Optimistic updates only for small, reversible toggles (the notification + read state): `cancelQueries`, snapshot, `setQueryData` in `onMutate`, and + restore the snapshot in `onError`. + +## Normalized cache (`@normy/react-query`) + +`NormalizationProvider` (in `App.tsx` and the test render helpers) keys records +by `":"`, so writing a record once updates **every** query holding +it. Only records carrying the client-added `__record` field take part; +everything else behaves like plain TanStack Query. + +- **Tag in the service**, after any transform: + `tagRecordForCaching('file', file)` or + `tagPaginatedRecordsForCaching('submission', page)`. The result type is + `ApiTaggedRecord`. Tag every endpoint that returns that type, or one copy + never updates. +- **New type**: add it to `API_RECORD_TYPES` (the server's name), and to + `ApiRecordShapes` if hooks need it typed. Only tag types that are pushed or + shared. +- **Writing**: `useNormalizedRecordCache()` gives `.write(type, record)` to + patch everywhere and `.readQueriesHolding(type, id)` to invalidate. + Normalization can't _add_ rows to a list, so use `prependRecordToPage` for + that. +- **Gotcha**: strip `__record` before sending a cached record as a request + body. + +## Actions + +Plain async functions taking `queryClient` first (`endSession`, +`loadConfiguration`, `setupUserAndOrgContext`), callable from routes, hooks +and tests. Use `Promise.all` for independent fetches, and `allSettled` when +one failure shouldn't block the rest. + +## Stores (Zustand) vs queries + +| | Query | Store | +| --------------------- | -------------------------------- | ------------------------------------------------------------------- | +| Holds | server data (a service's answer) | client state, or a server value that must be read synchronously | +| Filled by | its `queryFn` → service | an action, the interceptor or the UI. **Never a service directly.** | +| Stays fresh by itself | yes | no | +| Read | `useQuery` / `queryClient.query` | a `use…` hook / `xStore.getState()` | + +Today's stores: `configurationStore`, `organizationStore` and +`vulnerabilityStore` are filled from queries by actions for synchronous +reads. `rateLimitStore` is filled by the 429 interceptor, and `uploadAppStore` +holds client-only upload progress. + +```ts +export const organizationStore = createStore((set) => ({ + ...NONE_SELECTED, + select: (organization) => set({ selected: organization }), + clear: () => set(NONE_SELECTED), +})); + +export const useOrganization = () => useStore(organizationStore); // src/hooks +``` + +- Use `createStore` from `zustand/vanilla`, so guards can read it. +- Give each store a `clear()` and call it from `endSession`, or one account's + data leaks into the next sign-in. +- Persisted values go under `irene:` keys, with storage access wrapped + in try/catch. diff --git a/.claude/skills/irene-react-patterns/references/components-and-styles.md b/.claude/skills/irene-react-patterns/references/components-and-styles.md new file mode 100644 index 000000000..ac22acbfb --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/components-and-styles.md @@ -0,0 +1,196 @@ +# Components, styles, forms and copy + +Read `CLAUDE.md` → Styling alongside this. + +## App components + +Named function exports, kebab-case files, the props interface right above the +component, `Readonly`, and a JSDoc saying what it's for. + +- Build from `Ak*` components (`packages/ui/src/components/` has button, + typography, input, select, checkbox, link, icon, alert, table, skeleton, + modal, drawer, popover, menu, tooltip, chip, form…). +- Blank line between sibling JSX elements (lint). Logic longer than a few + lines goes in a `use…` hook; pure helpers go in `utils.ts` with a test. +- Loading: an `AkSkeleton` shaped like the content, or `loading` on the + button. Failures: `AkAlert` or `akNotify`. +- A feature rendered from outside exports its entry in `features//index.ts`. + +## Design-system components (`packages/ui/src/components/ak-/`) + +Generic only, with no app data or API calls. Files: `index.tsx` +(`Ak…`), `variants.ts` (`cva`), `index.stories.tsx` +(`'Components/Ak'`, autodocs), `index.test.tsx`, plus +`helpers`/`context`/`styles.module.css` when needed. + +```tsx +function AkBadge({ + className, + color = 'neutral', + ...props +}: ComponentProps<'span'> & VariantProps) { + return ( + + ); +} +``` + +- Extend the native element's props and spread the rest. Expose state as + `data-*` and style from it (`data-loading:…`). Use Radix `Slot` for + `asChild`. Use `compoundVariants` for variant × colour. +- Icons: ``. SVGs: + `import X from '@irene/ui/svgs/x.svg?react'`. +- **shadcn**: `pnpm --filter @irene/ui shadcn:add `, never the bare + CLI. It writes `ak-/index.tsx`, renames exports to `Ak*`, splits `cva` + into `variants.ts` and fixes imports. Then restyle with tokens, match irene's + props, and add a story and tests. Check what already exists first. + +## Styles + +- Inline Tailwind classes with theme tokens (`bg-primary`, + `text-foreground-disabled`, `rounded-md`). No hex, rgb, or arbitrary + radius, spacing or text size (lint). +- The root font is 14px and spacing steps are 4px (`w-14` = 56px). Use at most + two decimals (`py-2.75` works; `gap-4.375` generates nothing). +- Runtime values: `style={{ '--progress': `${pct}%` }} className="w-(--progress)"`. +- CSS Modules only for keyframes and complex selectors. No dark mode + (`dark:`), and no styled-components or inline style objects. + +### `cn` (`@irene/ui/cn` = clsx + tailwind-merge; last class wins) + +- Put the component's own classes first and the caller's `className` last, so + the caller overrides: `cn(akXVariants({ color }), isCompact && 'px-1', className)`. +- Use it when combining with conditions, variables, variants or props: + `cn('rounded-full', isUnread && 'bg-secondary')`, or `{ 'opacity-50': disabled }` + for several flags. +- **Class lists declared outside the JSX as constants** are wrapped in `cn()`, + even single literals. The lint rules only read `className`, `cn()`/`cva()` + and `*Props={{ className }}`, so a bare string would escape them. + ```tsx + const SEVERITY_DOT = { critical: cn('bg-danger'), low: cn('bg-success') } satisfies Record< + Severity, + string + >; + const CELL = cn('px-3 py-2.75 text-sm'); + ``` + Keep such constants in their own file and never export them. Shared styling + belongs in a component or a `cva` variant. (`variants.ts` is exempt.) +- Don't use it for a single inline literal: `className="flex items-center"`. +- tailwind-merge already understands the theme (`text-2xs` and `text-md` vs + colours, fractional spacing, semantic colours). Numbered shadows are + registered via `SHADOW_SCALE`. **A new non-standard token name** needs + registering in `cn/index.ts` plus a test, or merges break silently. + +## Forms (react-hook-form + zod + AkForm) + +**One schema file per form** (`features//schemas/.ts`), exporting +three things: + +```ts +/** Built per render, so its messages follow the locale. */ +export const buildResetPasswordSchema = () => + z + .object({ + password: z.string().min(1, akMT('enterNewPassword')), + confirm_password: z.string().min(1, akMT('enterConfirmPassword')), + }) + .refine((v) => v.password === v.confirm_password, { + message: akMT('passwordMatchError'), + path: ['confirm_password'], + }); + +export type ResetPasswordFormSchema = z.infer>; +export const ResetPasswordFormField = createAkFormField(); // module scope +``` + +- **Builder functions, never constants** (`akMT` is read when called). They + can take parameters (`buildStoreLinkSchema(isOffsec)`). +- Field names are the API's names, so values are the request body and API + errors map back onto fields. +- **Why `XFormField` and not `AkFormField`:** a bare `AkFormField` falls back + to the generic `FieldValues` type and accepts any string as `name`. A typo + then compiles, registers a field the schema doesn't know, and **never + validates**. `createAkFormField()` fixes the schema type once, + so `name` autocompletes and a typo is a type error, without spelling out + the generics on every field. Always use the bound field, never `AkFormField` + directly. +- Create it **once, at module scope**, in the schema file. Each call returns + a new component, so calling it during a render remounts the field on every + render and loses what was typed. +- Patterns: + - required text: `z.string().trim().min(1, akMT(…))` + - must-tick checkbox: `.refine(Boolean, …)` + - cross-field checks: `.refine` with a `path` + - several messages for one field: `.superRefine` with `_validate…` helpers + - multi-step forms: `.extend()` per step (login) + +**The form**: + +```tsx +const form = useForm({ + resolver: zodResolver(buildXSchema()), + defaultValues: { username: '' }, + reValidateMode: 'onSubmit', +}); +const usernameIsEmpty = useRequiredField('username', form); + + + mutation.mutate(v))}> + + + + + + … + + +; +``` + +- Every field gets a default value. The control is the field's **child**. +- `reValidateMode: 'onSubmit'` is the default. Use `'onChange'` for long forms + and `mode: 'onChange'` only for live checks (store link). +- `useRequiredField` disables submit while required text is empty, and hides + that field's "required" message. +- API errors: `toFormFieldErrors(schema, error)` → `setFormFieldErrors(form, …)`. + If nothing matches, show a toast. For one known field, + `getApiFieldErrors` + `form.setError` is fine. + +**zod beyond forms**: route `validateSearch` (optional params, plus +`.catch(undefined)` on navigation values), and notification `context.ts` +schemas checked with `safeParse` before rendering. Fall back on failure. Types +always come from `z.infer`. + +## Copy and translations + +- Add every key to **both** `en.json` and `ja.json`. Search first: irene's keys + exist. Nested ids use dots. +- **JSX children → ``**. It's preferred + for IntelliSense: `id` autocompletes and `values` is typed per message. +- **Everywhere else → `akMT('…', values)`**: props (`label`, `placeholder`, + `aria-label`), zod messages, toasts, route titles, hooks and tests. It + returns a string, or React nodes when the message has markup. +- Messages may contain `
` (`RICH_TEXT_TAGS`). + Never use `dangerouslySetInnerHTML`. +- Never choose the id with a ternary: branch around the call, + `cond ? akMT('a') : akMT('b')`. + +### Dates, times and numbers + +- Use the named `FORMATS` (`packages/translations/src/formats.ts`: `hhmmss` + for date/time, `USD`/`EUR` for numbers). In a message: + `"Last scanned at {at, time, hhmmss}"` with `values={{ at: new Date(…) }}`. + Standalone: `useIntl().formatTime(v, { format: 'hhmmss' })` (or `getIntl()` + outside React). +- Need another format? Add it to `FORMATS`. Never use `toLocaleString`, inline + `Intl` options or pattern strings. +- Relative time: `formatRelativeTime` from `@/utils/relative-time`. dayjs is + for parsing and arithmetic. If it must format, use + `.locale(getLocale())` per call, never the global `dayjs.locale()`. (The + fixed patterns in `notifications/utils.ts` are legacy and English-only.) +- Unreadable dates render as `''`, never "Invalid Date". diff --git a/.claude/skills/irene-react-patterns/references/configuration.md b/.claude/skills/irene-react-patterns/references/configuration.md new file mode 100644 index 000000000..8babe3f5d --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/configuration.md @@ -0,0 +1,57 @@ +# Configuration + +Choose by **who decides the value**: + +| Decided by | Source | Read with | +| ---------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------ | +| Deployment (CI or container) | `@irene/config`, 12 registered keys | `getConfigValue`, `getConfigFlag`, `isPluginEnabled`, `isWhitelabelEnabled` | +| Release | `@irene/config/product` | constants: `PRODUCT_VERSIONS`, `G_RECAPTCHA`, `PENDO_API_KEY` | +| Backend at runtime | `configurationStore`, filled by `loadConfiguration` | `useServerConfiguration()`, `useWhitelabel()`, `configurationStore.getState()` | + +## Deployment keys + +Each key resolves through three sources, first match wins: + +1. `window.runtimeGlobalConfig` (injected at container start) +2. `__BUILD_CONFIG__` (from CI env, via `buildConfigDefine` in `vite.config.ts`) +3. `DEFAULTS` + +The keys are `IRENE_API_HOST`, `IRENE_SHOW_LICENSE`, `IRENE_ENABLE_PENDO`, +`IRENE_ENABLE_MARKETPLACE`, `IRENE_POSTHOG_API_KEY`, `IRENE_POSTHOG_API_HOST`, +`ENTERPRISE`, and `WHITELABEL_ENABLED` / `NAME` / `LOGO` / `THEME` / `FAVICON`. + +- Strings: `getConfigValue(key)` (unset → `''`; API host `'/'` → `''`, meaning + same origin). +- Flags: `getConfigFlag(key)`. Never compare raw values, because `'false'` is + truthy. +- Pendo / Marketplace: always `isPluginEnabled(key)`. When unset they follow + the inverse of `ENTERPRISE`. +- `getConfig(key)` gives the raw value, only when "unset" matters + (`WHITELABEL_FAVICON`). +- Read inside functions, not in module constants. Unknown keys fail type-checking. +- **Never add a key** (every deployment would need it). Release-fixed public + values go in `@irene/config/product`; backend-decided values come from + `configurationStore` or org features. + +## Backend config + +`configurationStore` exposes getters (`isEnterprise()`, `socketHost()`, +`deviceFarmUrl()`) that fall back to the deployment keys. Boot doesn't wait +for it, so components reserve space until it arrives. + +## Tests + +`tests/setup.ts` resets both sources. Set the one you mean with string values, +then restore it: + +```ts +beforeEach(() => { + globalThis.__BUILD_CONFIG__ = { WHITELABEL_ENABLED: 'true' }; +}); +afterEach(() => { + globalThis.__BUILD_CONFIG__ = {}; +}); +``` + +For backend config, answer the config endpoints via MSW with +`buildFrontendConfiguration` / `buildServerConfiguration`. diff --git a/.claude/skills/irene-react-patterns/references/routing.md b/.claude/skills/irene-react-patterns/references/routing.md new file mode 100644 index 000000000..5dc792493 --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/routing.md @@ -0,0 +1,62 @@ +# Routing + +TanStack Router, file-based, in `apps/dashboard/src/routes/`. `routeTree.gen.ts` +is generated on save; never edit it. + +| File | Meaning | +| --------------------------------------- | ------------------------------------------------------ | +| `__root.tsx` | restores locale, checks session, starts config load | +| `_authenticated.tsx` | guard (→ `/login?redirectTo=…`), then loads user + org | +| `_unauthenticated.tsx` | layout for login, register, reset | +| `_authenticated/dashboard/projects.tsx` | `/dashboard/projects` | +| `_unauthenticated/reset/$token.tsx` | `/reset/:token` | + +`_name` adds a layout or guard without a URL segment. New signed-in pages go +under `_authenticated/`. A page outside both guards (`/dashboard/status`) needs +a comment saying why. + +## A route file is wiring only + +```ts +export const Route = createFileRoute('/_unauthenticated/login')({ + staticData: { pageTitle: () => akMT('login') }, + validateSearch: z.object({ + sessionExpired: z.boolean().optional(), + redirectTo: returnPathSchema, + }), + beforeLoad: async ({ context }) => { + if (await context.queryClient.query(sessionCheckOptions())) { + throw redirect({ to: '/' }); + } + }, + component: LoginPage, // from features/ +}); +``` + +- **`pageTitle`**: always set it, as a function so it follows the locale. + `RouterPageTitleContext<'/path/$p'>` types params. +- **`validateSearch`**: params are optional. Validate navigation targets + (`returnPathSchema` blocks open redirects). +- **`beforeLoad`**: guards and redirects (`replace: true` when there should be + no history entry). Its return value merges into child `context`. +- **`loader`** + `pendingComponent: RoutePending` + `errorComponent: RouteError`: + for data needed before render. The component then reads the same query with + `useQuery`. +- A guard needing data a parent _loader_ fills must await that setup itself. + Loaders run after all guards; cached queries make the second call free + (`dashboard/home.tsx`). +- Moved URL: keep the old file as a redirect-only route (`routes/status.tsx`). + +## In components + +- `` and `useNavigate()` are type-checked against the tree. +- `getRouteApi('/_unauthenticated/login').useSearch()` reads another route's + search params. +- Path unions come from `FileRouteTypes['to']`, never hand-written. + +## New page + +Add the route file (title + component) and the page in +`features//pages//` (named export). Add a loader and pending/error +components if needed, a nav entry in `layouts/*/nav-items`, and a +`renderAtRoute` test. diff --git a/.claude/skills/irene-react-patterns/references/testing.md b/.claude/skills/irene-react-patterns/references/testing.md new file mode 100644 index 000000000..55c45a507 --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/testing.md @@ -0,0 +1,49 @@ +# Tests + +Vitest + Testing Library + MSW. Test files sit next to the code. Coverage must +be ≥90% on every column. See also `CLAUDE.md` → Tests. + +```tsx +const RECOVER_URL = buildAPITestURL(AuthEndpoints.recover()); + +it('posts the username and shows the confirmation', async () => { + let body: unknown; + + server.use( + http.post(RECOVER_URL, async ({ request }) => { + body = await request.json(); + return HttpResponse.json({}); + }) + ); + + await renderAtRoute('/recover'); + await userEvent.type(screen.getByLabelText(akMT('usernameEmailIdTextLabel')), USERNAME); + await userEvent.click(screen.getByRole('button', { name: akMT('resetPassword') })); + + expect(body).toEqual({ username: USERNAME }); +}); +``` + +- **Render helpers** (`tests/render.tsx`): + - `renderAtRoute(path, { settle })` for pages: real guards, loaders and + layouts. `settle: false` shows the pending state. + - `renderWithRouterContext(ui)` for components containing ``. + - `renderWithProviders(ui)` for everything else. +- **MSW** runs the real axios stack. Build URLs with + `buildAPITestURL(XEndpoints.y())`. Use `HTTP_STATUS_CODES` for statuses (older + tests' raw `204`/`500` are legacy). `tests/server.ts` already answers config, + session and signed-in setup. +- Query elements by role, label or text, with `akMT` for copy; `data-test-*` + only as a fallback. Test names state the behaviour. +- **Factories** (`tests/factories/`): `build(overrides = {})` with + faker. Pin only the fields the test is about, and assert against the built + object, never literals. +- **Don't `vi.mock` modules the app imports.** With `isolate: false`, files + share modules per worker, so the mock is silently ignored whenever another + file loaded the page first, and the test becomes flaky. Fake at the + boundary instead: MSW for HTTP; for globals and third-party scripts, set the + global and fire the event the library waits for (`loadRecaptchaWidget` in + the register test); `vi.spyOn(window, …)` for browser APIs; module state is + reset in `tests/setup.ts`. +- Packages: `api` tests services against MSW, plus stores and transforms. + `ui` gets `index.test.tsx` + a story per component. diff --git a/.claude/skills/irene-react-patterns/references/websocket.md b/.claude/skills/irene-react-patterns/references/websocket.md new file mode 100644 index 000000000..1551d1011 --- /dev/null +++ b/.claude/skills/irene-react-patterns/references/websocket.md @@ -0,0 +1,69 @@ +# Websocket (`@irene/websocket`) + +Server push becomes cache updates and signals. Read the Normalized cache +section of `api-and-data.md` first: most live updates are just tagged records. + +> `packages/websocket/README.md` is out of date; follow the code. The real +> connection options are `noticeHandlers: { onMessage, onUnreadCount }` (no +> `product`). Counter signals are `'Counter'`. The cache adapter is +> `useNormalizedRecordCache`. + +## Flow + +The connection is Socket.IO, joining room = `user.socket_id`. All event policy +lives in **`cache/dispatch.ts`**: + +| Event | Effect | +| ---------------------- | ------------------------------------------------------------------------- | +| `model_updated` | `cache.write` (every query holding the record updates) + record listeners | +| `model_created` | signal `''` + record listeners (not cached: no list holds it yet) | +| `object` / `newobject` | invalidate queries holding it (300ms debounce) | +| `counter` | signal `'Counter'` | +| `message` | `akNotify` toast | +| `notification` | unread count written into its query | + +The connection opens **once**, in `AuthenticatedLayout` via +`useDashboardWebsocket`. `endSession` closes it. Pages never connect. + +## In a page (pick the first that fits) + +1. **Record changes** → tag it in the service. No page code needed. +2. **List should grow** → `useWebsocketSignal('SubmissionCounter', refetch)`, + or `useWebsocketSignal('submission', invalidate)`. Signal names are typed. +3. **Act on the pushed record** → + `useWebsocketRecord('submission', (s) => prependRecordToPage(queryClient, key, 'submission', s))`. +4. **After your own mutation** → `raiseWebsocketSignal('InvitationCounter')`. +5. **No event exists** → `...pollUntil({ intervalMs, isDone })` on the query + (not used yet). + +Device-farm streams (`holdDeviceSession` etc.) exist but aren't used yet. + +## New server event + +- **New record type**: add it to `API_RECORD_TYPES` (plus `ApiRecordShapes`) + and tag it in its services. If the server sends `object` events for it, + map the plural in `_RECORD_TYPE_BY_OBJECT_TYPE` (`dispatch.ts`). +- **New counter**: add it to `WEBSOCKET_COUNTERS` (`events/index.ts`). +- **New event name**: add it to `WEBSOCKET_EVENTS` with a payload type + (mirror the server's `notify.py`). Add a handler via `_onPayloadWith` in + `dispatch.ts`, and update the event list in `dispatch.test.ts`. UI-facing + events extend `WebsocketNoticeHandlers`. + +## Tests + +```ts +const serverSends = (event: string, payload: unknown) => + act(() => { + websocketTransport.emit(event, payload); + }); + +server.use(http.get(LIST_URL, () => HttpResponse.error())); // only the push can update the UI +serverSends(WEBSOCKET_EVENTS.modelUpdated, { + model_name: 'submission', + data: tagRecordForCaching('submission', updated), +}); +``` + +`websocketTransport` (from `@tests/setup`) is a fake installed for every test. +`.room` shows the joined room. Break the refetch path so the test proves the +push worked. From a8e43d3a5ddfe660ba37e733df4321ff67a763f2 Mon Sep 17 00:00:00 2001 From: Avi Shah Date: Thu, 15 Oct 2026 14:23:23 +0530 Subject: [PATCH 2/7] FIX: Load the reCAPTCHA widget in the register test rather than mocking its module, which a shared worker ignores. --- .../auth/pages/register/index.test.tsx | 44 ++++++++++++------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/apps/dashboard/src/features/auth/pages/register/index.test.tsx b/apps/dashboard/src/features/auth/pages/register/index.test.tsx index 752f4fa57..3e705f956 100644 --- a/apps/dashboard/src/features/auth/pages/register/index.test.tsx +++ b/apps/dashboard/src/features/auth/pages/register/index.test.tsx @@ -1,9 +1,8 @@ import { faker } from '@faker-js/faker'; -import { screen, waitFor } from '@testing-library/react'; +import { act, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { ReactNode } from 'react'; import { ConfigurationEndpoints } from '@irene/api/services/configuration/endpoints'; import { RegistrationEndpoints } from '@irene/api/services/registration/endpoints'; @@ -15,18 +14,34 @@ import { renderAtRoute } from '@tests/render'; import { buildAPITestURL, server } from '@tests/server'; /* - The widget's script never loads in a test environment, so the real hook hands - back no `executeRecaptcha` and the page sends its disabled placeholder. Held - here so a test can put a score in its place. + The widget's script never loads in a test environment, so the provider hands + back no `executeRecaptcha` and the page sends its disabled placeholder. + + A test that needs a score loads the widget the way a browser would, through + the real provider, rather than mocking the module: workers share modules + across files (`isolate: false`), so a module mock here is ignored whenever + another file in the same worker loaded the page first. */ -const recaptcha: { score?: string } = {}; +const RECAPTCHA_SCRIPT_ID = 'google-recaptcha-v3'; + +/** + * Puts the widget's global in place and fires the load event the provider + * waits for on its script, so the page gets a working `executeRecaptcha`. + * + * @param token - The token the widget issues for any action. + */ +function loadRecaptchaWidget(token: string) { + Object.assign(window, { + grecaptcha: { + ready: (onReady: () => void) => onReady(), + execute: () => Promise.resolve(token), + }, + }); -vi.mock('react-google-recaptcha-v3', () => ({ - GoogleReCaptchaProvider: ({ children }: { children: ReactNode }) => children, - useGoogleReCaptcha: () => ({ - executeRecaptcha: recaptcha.score ? () => Promise.resolve(recaptcha.score) : undefined, - }), -})); + act(() => { + document.getElementById(RECAPTCHA_SCRIPT_ID)?.dispatchEvent(new Event('load')); + }); +} const registrationUrl = buildAPITestURL(RegistrationEndpoints.register()); @@ -59,12 +74,10 @@ describe('RegisterPage', () => { }); afterEach(() => { - delete recaptcha.score; + Reflect.deleteProperty(window, 'grecaptcha'); }); it('posts the token the reCAPTCHA widget issued', async () => { - recaptcha.score = 'recaptcha-score-token'; - let sent: Record | undefined; server.use( @@ -76,6 +89,7 @@ describe('RegisterPage', () => { ); await renderAtRoute('/register'); + loadRecaptchaWidget('recaptcha-score-token'); await register(); await waitFor(() => expect(sent?.recaptcha).toBe('recaptcha-score-token')); From 3dcc3b224fde6a03b1c1b62d9025d3e6f87cac1e Mon Sep 17 00:00:00 2001 From: Avi Shah Date: Thu, 15 Oct 2026 14:23:37 +0530 Subject: [PATCH 3/7] ADD: AkTabs component on Radix tabs, with irene's line and shadow indicators, a segmented variant and a count badge. --- DESIGN-DECISIONS.md | 1 + .../src/components/ak-tabs/index.stories.tsx | 195 ++++++++++++++++++ .../ui/src/components/ak-tabs/index.test.tsx | 181 ++++++++++++++++ packages/ui/src/components/ak-tabs/index.tsx | 120 +++++++++++ .../ui/src/components/ak-tabs/variants.ts | 120 +++++++++++ 5 files changed, 617 insertions(+) create mode 100644 packages/ui/src/components/ak-tabs/index.stories.tsx create mode 100644 packages/ui/src/components/ak-tabs/index.test.tsx create mode 100644 packages/ui/src/components/ak-tabs/index.tsx create mode 100644 packages/ui/src/components/ak-tabs/variants.ts diff --git a/DESIGN-DECISIONS.md b/DESIGN-DECISIONS.md index 9d716279d..b5710ea15 100644 --- a/DESIGN-DECISIONS.md +++ b/DESIGN-DECISIONS.md @@ -33,6 +33,7 @@ not when someone notices it. | Security dashboard has a side navigation | `/security/*` | A bar carrying three tabs, and no navigation beside the page | The shared side navigation with its own three items, and the product switcher in it | The product was the only one reached without the navigation every other product has, so leaving it put the switcher out of reach from inside it | | One navigation width for every product | Every product layout | Reporting stores `reportSidebarState`; every other product shares `sidebarState`, so reporting collapses on its own | One `irene:sidebar-state` for all of them, so collapsing in any product collapses them all | The width is a reading preference, not a property of a product; irene's split means the same person sets it twice | | Offensive security spaces its navigation like every other product | `/dashboard/offensive-security` | `@isOffsec` puts `offsec-sidenav` on the aside, which zeroes the item list's top margin | The same gap below the switcher that every other product's navigation has | The product has one item today; spacing it differently makes it read as a different navigation rather than the same one with less in it | +| Tabs show focus as a ring | Every `AkTabsTrigger` | A focused tab takes the same grey tint as a hovered one | A focused tab takes the ring every other control has; hover keeps the tint | Keyboard focus and the pointer resting on a tab looked identical, so a keyboard user could not tell which tab the arrow keys had reached | ## Accepted diff --git a/packages/ui/src/components/ak-tabs/index.stories.tsx b/packages/ui/src/components/ak-tabs/index.stories.tsx new file mode 100644 index 000000000..a5a263a9d --- /dev/null +++ b/packages/ui/src/components/ak-tabs/index.stories.tsx @@ -0,0 +1,195 @@ +import { useState } from 'react'; +import type { Meta, StoryObj } from '@storybook/react-vite'; + +import { AkIcon } from '@irene/ui/ak-icon'; +import { AkTabs, AkTabsBadge, AkTabsContent, AkTabsList, AkTabsTrigger } from '@irene/ui/ak-tabs'; +import { AkTypography } from '@irene/ui/ak-typography'; +import { StorySection } from '@irene/ui/story-layout'; + +const VARIANTS = ['line', 'shadow', 'segmented'] as const; + +const TABS = [ + { value: 'files', label: 'Files', icon: 'material-symbols:assignment', count: 9 }, + { value: 'members', label: 'Members', icon: 'material-symbols:group', count: 100 }, + { value: 'settings', label: 'Settings', icon: 'material-symbols:settings', count: 0 }, +] as const; + +const meta = { + title: 'Components/AkTabs', + component: AkTabsList, + tags: ['autodocs'], + argTypes: { + variant: { control: 'inline-radio', options: VARIANTS }, + }, + args: { variant: 'line' }, +} satisfies Meta; + +export default meta; + +type Story = StoryObj; + +/** A row with icons and counts, and a view under it for each tab. */ +export const Playground: Story = { + render: (args) => ( + + + {TABS.map((tab) => ( + + + + {tab.label} + + {tab.count} + + ))} + + + {TABS.map((tab) => ( + + The content for {tab.label}. + + ))} + + ), +}; + +/** Each variant, with a disabled tab at the end. */ +export const Variants: Story = { + render: () => ( +
+ {VARIANTS.map((variant) => ( + + + + {TABS.map((tab) => ( + + {tab.label} + + ))} + + + Archived + + + + + ))} +
+ ), +}; + +/** A count on a tint, the default, or as bare text; and any content in place of a number. */ +export const Badges: Story = { + render: (args) => ( +
+ + + + {TABS.map((tab) => ( + + {tab.label} + + {tab.count} + + ))} + + + + + + + + {TABS.map((tab) => ( + + {tab.label} + + {tab.count} + + ))} + + + + + + + + {TABS.map((tab) => ( + + {tab.label} + + + + {tab.count} + + + ))} + + + +
+ ), +}; + +/** Selection held by the caller, as a route or a search param would hold it. */ +export const Controlled: Story = { + render: function ControlledTabs(args) { + const [active, setActive] = useState('members'); + + return ( +
+ + + {TABS.map((tab) => ( + + {tab.label} + + ))} + + + + Active: {active} +
+ ); + }, +}; + +/** + * Tabs that navigate: each tab is a link, the route decides which is active, + * and `manual` activation stops the arrow keys from navigating as they move. + */ +export const AsLinks: Story = { + render: (args) => ( + + + {TABS.map((tab) => ( + + {tab.label} + + ))} + + + ), +}; + +/** A column of tabs beside its view. */ +export const Vertical: Story = { + render: (args) => ( + + + {TABS.map((tab) => ( + + + + {tab.label} + + ))} + + + {TABS.map((tab) => ( + + The content for {tab.label}. + + ))} + + ), +}; diff --git a/packages/ui/src/components/ak-tabs/index.test.tsx b/packages/ui/src/components/ak-tabs/index.test.tsx new file mode 100644 index 000000000..b77c6dbdd --- /dev/null +++ b/packages/ui/src/components/ak-tabs/index.test.tsx @@ -0,0 +1,181 @@ +import { render, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; +import { type ComponentProps } from 'react'; + +import { AkTabs, AkTabsBadge, AkTabsContent, AkTabsList, AkTabsTrigger } from '@irene/ui/ak-tabs'; + +type RenderTabsOptions = ComponentProps & { + variant?: ComponentProps['variant']; +}; + +const renderTabs = ({ variant, ...props }: RenderTabsOptions = {}) => + render( + + + + Files + 9 + + + Members + + + Archived + + + + Files view + + Members view + + ); + +const tab = (name: string) => screen.getByRole('tab', { name: new RegExp(name) }); + +describe('AkTabs', () => { + it('reads as a tablist with one tab per trigger', () => { + renderTabs(); + + expect(screen.getByRole('tablist')).toBeInTheDocument(); + expect(screen.getAllByRole('tab')).toHaveLength(3); + }); + + it('shows the view for the tab active on mount, and only that one', () => { + renderTabs(); + + expect(tab('Files')).toHaveAttribute('aria-selected', 'true'); + expect(screen.getByRole('tabpanel')).toHaveTextContent('Files view'); + expect(screen.queryByText('Members view')).not.toBeInTheDocument(); + }); + + it('switches the view when another tab is pressed', async () => { + renderTabs(); + + await userEvent.click(tab('Members')); + + expect(tab('Members')).toHaveAttribute('aria-selected', 'true'); + expect(screen.getByRole('tabpanel')).toHaveTextContent('Members view'); + }); + + it('reports the chosen tab to the caller, as irene’s onTabClick did', async () => { + const onValueChange = vi.fn(); + + renderTabs({ onValueChange }); + + await userEvent.click(tab('Members')); + + expect(onValueChange).toHaveBeenCalledWith('members'); + }); + + it('follows the value it is given rather than its own selection', async () => { + renderTabs({ value: 'files', defaultValue: undefined }); + + await userEvent.click(tab('Members')); + + expect(tab('Files')).toHaveAttribute('aria-selected', 'true'); + }); + + it('moves between tabs with the arrow keys', async () => { + renderTabs(); + + await userEvent.click(tab('Files')); + await userEvent.keyboard('{ArrowRight}'); + + expect(tab('Members')).toHaveFocus(); + }); + + it('keeps a disabled tab out of reach', async () => { + const onValueChange = vi.fn(); + + renderTabs({ onValueChange }); + + await userEvent.click(tab('Archived')); + + expect(tab('Archived')).toBeDisabled(); + expect(onValueChange).not.toHaveBeenCalled(); + }); + + it('renders a link as the tab when given one, for tabs that navigate', () => { + render( + + + + Files + + + + ); + + expect(tab('Files').tagName).toBe('A'); + expect(tab('Files')).toHaveAttribute('href', '/files'); + }); +}); + +describe('the variant a row is drawn in', () => { + it('marks the active tab with a bar under it unless another variant is asked for', () => { + renderTabs(); + + expect(screen.getByRole('tablist')).toHaveAttribute('data-variant', 'line'); + expect(tab('Files')).toHaveClass('after:bg-primary'); + }); + + it('runs the row over a rule for the line and shadow variants', () => { + renderTabs({ variant: 'shadow' }); + + expect(screen.getByRole('tablist')).toHaveClass( + 'data-[orientation=horizontal]:border-b', + 'w-full' + ); + }); + + it('lays a vertical row out as a column, with the rule down its side', () => { + renderTabs({ orientation: 'vertical' }); + + expect(screen.getByRole('tablist')).toHaveAttribute('aria-orientation', 'vertical'); + expect(screen.getByRole('tablist')).toHaveClass('data-[orientation=vertical]:border-r'); + }); + + it('lifts the active tab as a card for the shadow variant', () => { + renderTabs({ variant: 'shadow' }); + + expect(tab('Files')).toHaveClass('data-[state=active]:shadow-4'); + expect(tab('Files')).not.toHaveClass('after:bg-primary'); + }); + + it('draws the row as a tinted track for the segmented variant', () => { + renderTabs({ variant: 'segmented' }); + + expect(screen.getByRole('tablist')).toHaveClass('bg-divider-strong', 'w-fit'); + expect(tab('Files')).toHaveClass('data-[state=active]:bg-background'); + }); +}); + +describe('the count beside a tab', () => { + it('sits inside the tab it counts for', () => { + renderTabs(); + + expect(within(tab('Files')).getByText('9')).toBeInTheDocument(); + }); + + it('sits on a tint that follows the tab, unless asked to be bare text', () => { + render( + + + + Files + 9 + + + + Members + 4 + + + + ); + + expect(screen.getByText('9')).toHaveClass('bg-divider-strong'); + expect(screen.getByText('4')).toHaveClass('bg-transparent'); + }); +}); diff --git a/packages/ui/src/components/ak-tabs/index.tsx b/packages/ui/src/components/ak-tabs/index.tsx new file mode 100644 index 000000000..4b221dadf --- /dev/null +++ b/packages/ui/src/components/ak-tabs/index.tsx @@ -0,0 +1,120 @@ +import { Tabs as TabsPrimitive } from 'radix-ui'; +import { createContext, useContext, type ComponentProps } from 'react'; +import { type VariantProps } from 'class-variance-authority'; + +import { cn } from '@irene/ui/cn'; + +import { akTabsBadgeVariants, akTabsListVariants, akTabsTriggerVariants } from './variants'; + +type AkTabsVariant = NonNullable['variant']>; + +/* Carries the list's variant to its tabs, so the variant is set once per row. */ +const AkTabsVariantContext = createContext('line'); + +/** + * A set of views, one shown at a time, chosen from a row of tabs. + * + * Built on Radix's tabs, so the row reads as a tablist to assistive technology + * and takes the arrow keys, Home and End. Values are strings: irene's numeric + * tab ids become their string form. + * + * @param props.value - The active tab, for a row whose selection lives elsewhere (a route, a search param). + * @param props.defaultValue - The tab active on mount, for a row that keeps its own selection. + * @param props.onValueChange - Called with the chosen tab's value; irene's `onTabClick`. + * @param props.orientation - Lays the row out horizontally (the default) or vertically. + * @param props.activationMode - `manual` waits for Enter or Space; use it for tabs that navigate. + */ +function AkTabs({ + className, + orientation = 'horizontal', + ...props +}: ComponentProps) { + return ( + + ); +} + +/** + * The row of tabs. + * + * @param props.variant - How the active tab is marked: a bar under it (`line`), a raised card + * (`shadow`), or a raised pill on a tinted track (`segmented`). + */ +function AkTabsList({ + className, + variant = 'line', + ...props +}: ComponentProps & { variant?: AkTabsVariant }) { + return ( + + + + ); +} + +/** + * One tab. Its children are the label, with an icon before it and an + * `AkTabsBadge` after it as needed. + * + * @param props.value - Which `AkTabsContent` it shows, and what `onValueChange` receives. + * @param props.disabled - Keeps it in the row but out of reach. + * @param props.asChild - Makes the child the tab; pass a router link for tabs that navigate. + */ +function AkTabsTrigger({ className, ...props }: ComponentProps) { + const variant = useContext(AkTabsVariantContext); + + return ( + + ); +} + +/** + * The count beside a tab's label, tinted to follow the tab it sits in. + * + * @param props.background - Draws it on a tint (the default), or as bare text. + */ +function AkTabsBadge({ + className, + background, + ...props +}: ComponentProps<'span'> & VariantProps) { + return ( + + ); +} + +/** + * The view for one tab, rendered while that tab is active. + * + * @param props.value - The tab it belongs to. + * @param props.forceMount - Keeps it mounted while hidden, for a view that holds state. + */ +function AkTabsContent({ className, ...props }: ComponentProps) { + return ( + + ); +} + +export { AkTabs, AkTabsList, AkTabsTrigger, AkTabsBadge, AkTabsContent }; diff --git a/packages/ui/src/components/ak-tabs/variants.ts b/packages/ui/src/components/ak-tabs/variants.ts new file mode 100644 index 000000000..5bf2fecb9 --- /dev/null +++ b/packages/ui/src/components/ak-tabs/variants.ts @@ -0,0 +1,120 @@ +import { cva } from 'class-variance-authority'; + +/* + The row of tabs. `line` and `shadow` are irene's two indicators and run the + width of their container over a rule; `segmented` is a pill-shaped switch for + a choice between a few views, sized to its tabs. +*/ +export const akTabsListVariants = cva( + ` + inline-flex items-center + data-[orientation=vertical]:h-fit data-[orientation=vertical]:w-fit + data-[orientation=vertical]:flex-col data-[orientation=vertical]:items-stretch + `, + { + variants: { + variant: { + /* The rule runs under a row, and down the side of a column. */ + line: ` + w-full border-border + data-[orientation=horizontal]:border-b + data-[orientation=vertical]:border-r + `, + shadow: ` + w-full border-border + data-[orientation=horizontal]:border-b + data-[orientation=vertical]:border-r + `, + segmented: ` + w-fit gap-0.5 rounded-md bg-divider-strong p-0.75 + data-[orientation=horizontal]:h-9 + `, + }, + }, + + defaultVariants: { variant: 'line' }, + } +); + +/* + One tab. Every variant marks the active tab by `data-state=active`, which + Radix sets on a button and on a link passed through `asChild` alike. +*/ +export const akTabsTriggerVariants = cva( + ` + group/tabs-trigger relative inline-flex shrink-0 cursor-pointer items-center justify-center + gap-2 text-base whitespace-nowrap text-foreground-muted transition-colors outline-none + focus-visible:ring-3 focus-visible:ring-ring/50 + data-disabled:pointer-events-none data-disabled:text-foreground-disabled + [&_svg]:pointer-events-none [&_svg]:shrink-0 + [&_svg:not([class*='size-'])]:size-4.5 + data-[orientation=vertical]:justify-start + `, + { + variants: { + variant: { + /* A 3px bar under the active tab, in the primary colour. */ + line: ` + h-10 px-4 + hover:bg-hover-light + data-[state=active]:font-bold data-[state=active]:text-foreground + data-[state=active]:hover:bg-transparent + after:absolute after:bg-primary after:opacity-0 after:transition-opacity + data-[state=active]:after:opacity-100 + data-[orientation=horizontal]:after:inset-x-0 data-[orientation=horizontal]:after:bottom-0 + data-[orientation=horizontal]:after:h-0.75 + data-[orientation=horizontal]:after:rounded-t-xs + data-[orientation=vertical]:after:inset-y-0 data-[orientation=vertical]:after:right-0 + data-[orientation=vertical]:after:w-0.75 data-[orientation=vertical]:after:rounded-l-xs + `, + + /* The active tab is lifted out of the row as a card, open on the side facing its view. */ + shadow: ` + h-10 border border-transparent px-4 + data-[orientation=horizontal]:rounded-t-md data-[orientation=horizontal]:border-b-0 + data-[orientation=vertical]:rounded-l-md data-[orientation=vertical]:border-r-0 + hover:bg-hover-light + data-[state=active]:border-border data-[state=active]:bg-background + data-[state=active]:font-bold data-[state=active]:text-primary + data-[state=active]:shadow-4 + data-[state=active]:hover:bg-background + data-[state=active]:[&_svg]:text-foreground + `, + + /* The active tab is a raised surface on the tinted track. */ + segmented: ` + rounded-sm px-3 font-medium + data-[orientation=horizontal]:h-full data-[orientation=horizontal]:flex-1 + data-[orientation=vertical]:h-8 + hover:text-foreground + data-[state=active]:bg-background data-[state=active]:text-foreground + data-[state=active]:shadow-15 + `, + }, + }, + + defaultVariants: { variant: 'line' }, + } +); + +/* + The count beside a tab's label. It tints with the tab it sits in, so the + active tab's count reads as part of the selection. +*/ +export const akTabsBadgeVariants = cva( + 'inline-flex h-5 min-w-6 items-center justify-center rounded-xs px-1 text-sm font-normal', + { + variants: { + background: { + true: ` + bg-divider-strong text-foreground-muted + group-data-[state=active]/tabs-trigger:bg-primary/20 + group-data-[state=active]/tabs-trigger:text-foreground + `, + false: 'bg-transparent', + }, + }, + + defaultVariants: { background: true }, + } +); From 1b035011572661faa8cedff6d63c3cfd3e569790 Mon Sep 17 00:00:00 2001 From: Avi Shah Date: Thu, 15 Oct 2026 14:23:48 +0530 Subject: [PATCH 4/7] ADD: AkToggle switch on Radix, in irene's three sizes, green when on and grey when off. --- .../components/ak-toggle/index.stories.tsx | 66 +++++++++++++++++++ .../src/components/ak-toggle/index.test.tsx | 65 ++++++++++++++++++ .../ui/src/components/ak-toggle/index.tsx | 37 +++++++++++ .../ui/src/components/ak-toggle/variants.ts | 46 +++++++++++++ 4 files changed, 214 insertions(+) create mode 100644 packages/ui/src/components/ak-toggle/index.stories.tsx create mode 100644 packages/ui/src/components/ak-toggle/index.test.tsx create mode 100644 packages/ui/src/components/ak-toggle/index.tsx create mode 100644 packages/ui/src/components/ak-toggle/variants.ts diff --git a/packages/ui/src/components/ak-toggle/index.stories.tsx b/packages/ui/src/components/ak-toggle/index.stories.tsx new file mode 100644 index 000000000..2b5950220 --- /dev/null +++ b/packages/ui/src/components/ak-toggle/index.stories.tsx @@ -0,0 +1,66 @@ +import { useState } from 'react'; +import type { Meta, StoryObj } from '@storybook/react-vite'; + +import { AkToggle } from '@irene/ui/ak-toggle'; +import { AkTypography } from '@irene/ui/ak-typography'; +import { StorySection } from '@irene/ui/story-layout'; + +const SIZES = ['small', 'default', 'large'] as const; + +const meta = { + title: 'Components/AkToggle', + component: AkToggle, + tags: ['autodocs'], + argTypes: { + size: { control: 'inline-radio', options: SIZES }, + disabled: { control: 'boolean' }, + }, + args: { size: 'default', disabled: false, 'aria-label': 'Email me' }, +} satisfies Meta; + +export default meta; + +type Story = StoryObj; + +export const Playground: Story = {}; + +/** Each size, off and on. */ +export const Sizes: Story = { + render: (args) => ( +
+ {SIZES.map((size) => ( + + + + + + ))} +
+ ), +}; + +/** Disabled, off and on: it keeps its colour, faded. */ +export const Disabled: Story = { + render: (args) => ( +
+ + + +
+ ), +}; + +/** A setting row: the label names the switch, and the state lives with the caller. */ +export const WithLabel: Story = { + render: function WithLabelToggle(args) { + const [isOn, setIsOn] = useState(true); + + return ( + + ); + }, +}; diff --git a/packages/ui/src/components/ak-toggle/index.test.tsx b/packages/ui/src/components/ak-toggle/index.test.tsx new file mode 100644 index 000000000..5fa126c6c --- /dev/null +++ b/packages/ui/src/components/ak-toggle/index.test.tsx @@ -0,0 +1,65 @@ +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; + +import { AkToggle } from '@irene/ui/ak-toggle'; + +describe('AkToggle', () => { + it('reads as a switch, off unless told otherwise', () => { + render(); + + expect(screen.getByRole('switch', { name: 'Email me' })).not.toBeChecked(); + }); + + it('reports the new state when flipped', async () => { + const onCheckedChange = vi.fn(); + + render(); + + await userEvent.click(screen.getByRole('switch')); + + expect(onCheckedChange).toHaveBeenCalledWith(true); + }); + + it('follows the state it is given rather than its own', async () => { + render(); + + await userEvent.click(screen.getByRole('switch')); + + expect(screen.getByRole('switch')).not.toBeChecked(); + }); + + it('flips on Space, as a switch does', async () => { + const onCheckedChange = vi.fn(); + + render(); + + screen.getByRole('switch').focus(); + await userEvent.keyboard(' '); + + expect(onCheckedChange).toHaveBeenCalledWith(true); + }); + + it('stays where it is while disabled', async () => { + const onCheckedChange = vi.fn(); + + render(); + + await userEvent.click(screen.getByRole('switch')); + + expect(onCheckedChange).not.toHaveBeenCalled(); + }); + + it('draws green when on and grey when off', () => { + render(); + + expect(screen.getByRole('switch')).toHaveClass('data-[state=checked]:bg-success'); + expect(screen.getByRole('switch')).toHaveAttribute('data-state', 'checked'); + }); + + it('takes the small height beside body text', () => { + render(); + + expect(screen.getByRole('switch')).toHaveClass('h-4', 'w-8'); + }); +}); diff --git a/packages/ui/src/components/ak-toggle/index.tsx b/packages/ui/src/components/ak-toggle/index.tsx new file mode 100644 index 000000000..8e6bc8aca --- /dev/null +++ b/packages/ui/src/components/ak-toggle/index.tsx @@ -0,0 +1,37 @@ +import { Switch as SwitchPrimitive } from 'radix-ui'; +import { type VariantProps } from 'class-variance-authority'; +import { type ComponentProps } from 'react'; + +import { cn } from '@irene/ui/cn'; + +import { akToggleThumbVariants, akToggleVariants } from './variants'; + +type AkToggleProps = ComponentProps & + VariantProps; + +/** + * Turns one setting on or off, taking effect as it is flipped rather than on a + * submit. + * + * Built on Radix's switch, so it reads as a switch to assistive technology and + * flips on Space. It is a button rather than a checkbox, so it takes its name + * from `aria-label` or a `