Compare commits

..

No commits in common. "381e01e030ccba5339b7d0aeba6716acb364f7f7" and "495f800f1f3e7e4dcfca0bbf1580bace8d16d1da" have entirely different histories.

254 changed files with 153 additions and 8864 deletions

View File

@ -1,6 +1,6 @@
---
name: front-end-architect
description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites (Next.js App Router, server rendering, web vitals, bundle and hydration budgets for millions of visitors). Applies a fixed architecture of apps, platforms, the island atomic design system, libs (HTTP client with retry and refresh; error handler; env; cookie; local storage; PWA service worker; JSON-LD structured data), integrations, and tools, with kebab-case naming, tree-shakeable exports with server and client entries, and DDD features (entities, repositories, caches, actions, models), on Tailwind v4 with cva, valibot, react-hook-form, zustand, i18next, and sonner, and keeps each project's decision records (ADR, DDR). Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, or Nx projects, when planning a feature, when the user states a lasting rule or asks to record or change a decision, or when another skill (product designer, architect) needs front-end input.
description: Principal front-end architect for Nx monorepos that ship B2C/B2B websites (Next.js App Router, server rendering, web vitals, bundle and hydration budgets for millions of daily visitors). Applies a fixed architecture of apps, platforms, the island atomic design system, libs (HTTP client with retry and token refresh; error handler; env; cookie; local storage), integrations, and tools, with kebab-case naming, tree-shakeable exports with server and client entries, and DDD features (entities, repositories, caches, actions, models), on Tailwind v4 with cva, valibot, react-hook-form, zustand, i18next, and sonner, and keeps each project's architecture and design decision records (ADR, DDR). Use when designing, scaffolding, implementing, refactoring, or reviewing front-end code, pages, components, features, or Nx projects in these monorepos, when planning a feature, when the user states a lasting project rule or asks to record or change a decision, or when another skill such as a product designer or architect needs front-end input.
---
# Front-end Architect
@ -23,7 +23,7 @@ How you work:
- Server entry: every project except apps has `src/server.ts`.
- Critical: a fresh server render per request with no server cache, web vitals, bundle and chunk size, and hydration and navigation speed.
Read the playbook before designing or writing code: [references/b2c-b2b.md](references/b2c-b2b.md). When the work changes what the user sees or what search engines read (a page, template, organism, form, copy, upload, image, font, icon, metadata, or structured data), also read [references/ui-rules.md](references/ui-rules.md): UX, SEO, images, fonts, and the icon sprite.
Read the playbook before designing or writing code: [references/b2c-b2b.md](references/b2c-b2b.md). When the work changes what the user sees or what search engines read (a page, template, organism, form, copy, upload, image, font, icon, or metadata), also read [references/ui-rules.md](references/ui-rules.md): UX, SEO, images, fonts, and the icon sprite.
## 2. Stack
@ -43,8 +43,6 @@ Read the playbook before designing or writing code: [references/b2c-b2b.md](refe
| Lint and format | oxlint, prettier | ESLint runs module-boundary rules only |
| TS scripts and configs | jiti | Runs `tools/` scripts and TypeScript config files without a build step |
| Icons | svgo | Through island's `icon-sprite-plugin`, into `symbol-defs.svg`, which no step hashes; linked with `?v=<N>` |
| Service worker | Native Service Worker and Cache APIs | Only through the pwa lib: one worker per app that stores JS, CSS, fonts, and `symbol-defs.svg`, nothing else. No Workbox or Serwist |
| Structured data | schema.org JSON-LD | Only through the json-ld lib's builders, rendered on the server by island's `JsonLd` primitive. No schema-dts or next-seo |
TanStack Query is implied by `configs/react-query.ts`; confirm the repo uses it before adding it. Don't add any dependency outside this stack without stating why and getting approval.
@ -56,15 +54,13 @@ The rules below are enough for work inside existing projects and features. Read
- Component placement (its atomic level and the project and folder it belongs in), before you add or move a component: only the "Choosing where a component goes" section of [references/project-structure.md](references/project-structure.md#choosing-where-a-component-goes)
- Code patterns, one section at a time: read only the section for the layer you write (island component, tokens, repository, action, form and model, mutation, store, persisted store, env), as its Contents line lists. Copy an existing file of the same kind when the repo has one: [references/code-patterns.md](references/code-patterns.md)
Shared libs have full specs. Read the matching one only when you build or change the lib itself, or when a feature needs lib behavior that "Env, HTTP, cookies, storage, the service worker, and structured data" below doesn't describe. To use a lib from a feature, that section and code-patterns.md are enough:
Shared libs have full specs. Read the matching one only when you build or change the lib itself, or when a feature needs lib behavior that "Env, HTTP, cookies, and storage" below doesn't describe. To use a lib from a feature, that section and code-patterns.md are enough:
- HTTP client: [references/lib-http.md](references/lib-http.md)
- Error handler: [references/lib-error-handler.md](references/lib-error-handler.md)
- Env: [references/lib-env.md](references/lib-env.md)
- Cookies: [references/lib-cookie.md](references/lib-cookie.md)
- Local storage: [references/lib-local-storage.md](references/lib-local-storage.md)
- PWA and the service worker, also whenever work touches `/sw.js`, the web app manifest, or what the browser keeps between visits: [references/lib-pwa.md](references/lib-pwa.md)
- JSON-LD structured data, also whenever work adds an indexable page type or changes what a page tells search engines about the business, a product, its price, or its policies: [references/lib-json-ld.md](references/lib-json-ld.md)
Error handling, patterns, and refactoring have their own references. Read each one only when its trigger applies:
@ -114,7 +110,7 @@ Error handling, patterns, and refactoring have their own references. Read each o
- Client side (the parts of a page that load in the browser): repository → model → UI. Every page has a skeleton (`loading.tsx`). Every part that loads on its own has its own `<Suspense>` with a same-size skeleton and its own part boundary (EB-S), so one slow or failing part never blocks the others.
- Server side: repository → cache → server components. Pages, `generateMetadata`, and server components read data only through caches. A client component gets server data as props, or through React Query hydration when it must stay live. Details: [references/b2c-b2b.md](references/b2c-b2b.md#data-flow).
**Env, HTTP, cookies, storage, the service worker, and structured data**
**Env, HTTP, cookies, and storage**
- Env (`packages/libs/src/env`): only the app's `env/` files read `process.env`, through `createClientEnv` (public) and `createServerEnv` (server only). Other projects read their own values with `getEnv`, filled by the app's bootstrap. Libs never read env; the bootstrap passes their settings through `configure`.
- No project hard-codes an env value: a value that changes between environments, such as a service or CDN address, a key, a third-party ID, or a feature flag. Not as a literal, a fallback (`?? 'http://localhost:3000'`), or a schema default. Every env value comes from the `.env` of the app that serves it, and only apps have `.env` files. Values that are the same in every environment stay in `constants/`.
@ -125,10 +121,6 @@ Error handling, patterns, and refactoring have their own references. Read each o
- Cookies (`packages/libs/cookie`, the `cookie` instance): only small values the server needs on the request, such as locale and theme. Never tokens: auth cookies are HttpOnly and belong to the server. Browser only; server code reads cookies with `next/headers`.
- Local storage (`packages/libs/local-storage`, the `storage` instance): client-only, non-critical data under the app's key prefix, and the storage behind persisted zustand stores. Never tokens or personal data.
- `cookie` and `storage` are never read during render, at module top level, or in repositories.
- Service worker (`packages/libs/pwa`): each app serves one worker at `/sw.js`, written by the lib's `writeServiceWorker` and registered from the `AppShell` when the app's env turns it on. It stores only JS and CSS from `/_next/static/`, fonts from `/fonts/`, and `/icons/symbol-defs.svg`, by exact URL, stale-while-revalidate unless the developer explicitly chooses cache first. Pages, RSC payloads, API data, images, and every other SVG reach the network untouched.
- Storing any other kind of URL needs a recorded decision. `/sw.js` is never renamed or removed; turning the env flag off unregisters the worker for every visitor.
- Structured data (`packages/libs/json-ld`, server only): every indexable page renders one schema.org JSON-LD graph with island's `JsonLd`, in its page entry, from the data its first paint already awaits. The home page describes the business (`OnlineStore`) and the website from the app's `configs/seo.ts`; other page types get theirs from a builder in the platform's `app/json-ld/`, such as the product with its offer, rating, and breadcrumb.
- The graph says only what the page shows, the same for every visitor: never a member or personal price, and no rating on the business itself. `noindex` pages and not-found, no-access, and error states render none.
**Design system (island)**
@ -143,10 +135,9 @@ Error handling, patterns, and refactoring have their own references. Read each o
- Separate concerns: components render, models orchestrate, actions run operations, repositories talk to the network through their feature's HTTP client, and caches share server reads within a request. No `fetch` outside the HTTP lib.
- Keep one source of truth per kind of state: server state in the query cache, URL state in the URL, form state in react-hook-form, shared client state in zustand, and ephemeral UI state in the component. Never copy one into another.
- Deploys never break open tabs: build once per release, mark it with `NEXT_DEPLOYMENT_ID` from CI, and keep old releases' `/_next/static/` files for 30 days ([references/b2c-b2b.md](references/b2c-b2b.md#deploys-and-version-skew)).
- Keep the UI stable: colocate state, split large contexts, never let an update unmount and remount a visible subtree, and never use random values or array indexes as keys for dynamic lists.
- Model multi-step flows (wizards, imports, bulk actions) as explicit states, such as `idle → validating → uploading → processing → done | failed`, never as a set of booleans.
- Handle errors with one model ([references/error-handling.md](references/error-handling.md)): EB-W at the app root only, a page-size EB-S inside the shell for every page, and a part-size EB-S around every part that loads on its own, so one broken part never takes down the page. A failed read shows in its boundary or as an empty state (404 and 403) and never toasts. A failed action shows an error toast with its hint or a reference ID and the retry its cause allows. `ABORTED` and 401 stay silent. A chunk that fails to load after a deploy is outdated: a page reloads once, a part or toast offers Reload page, and nothing is reported.
- Handle errors with one model ([references/error-handling.md](references/error-handling.md)): EB-W at the app root only, a page-size EB-S inside the shell for every page, and a part-size EB-S around every part that loads on its own, so one broken part never takes down the page. A failed read shows in its boundary or as an empty state (404 and 403) and never toasts. A failed action shows an error toast with its hint or a reference ID and the retry its cause allows. `ABORTED` and 401 stay silent.
- Every text comes from i18next and is a simple, complete description of its purpose ("Save changes to this category", not "Save"). Support RTL and LTR: set `lang` and `dir` from the locale, and use logical utilities (`ms-*`, `pe-*`, `start-*`) instead of left and right.
- Meet WCAG 2.1 AA: 4.5:1 text contrast, visible focus rings, full keyboard operation, and an `aria-label` on every icon-only button.
@ -205,8 +196,6 @@ Structure
[ ] Each new or moved part went through rendering-patterns.md's "Choosing where a part loads"; every deferred part and its trigger is written in the PR
[ ] The server render is the same for every visitor; every auth-dependent page or part renders in the browser behind a same-size skeleton, unless the developer asked otherwise and the PR says so
[ ] Fonts and the icon sprite keep fixed names that no step hashes; every sprite change raised ICON_SPRITE_VERSION in the same commit
[ ] The service worker stores only JS, CSS, fonts, and symbol-defs.svg, stale-while-revalidate unless the developer explicitly chose cache first; /sw.js keeps its name and its no-cache header
[ ] Every indexable page renders one JSON-LD graph through the json-ld lib and island's JsonLd, from its first-paint data; it says only what the page shows, the same for every visitor; noindex pages and error states have none
[ ] Refactors are in their own commits, and the PR states how unchanged behavior was checked; smells noticed but not fixed are listed as debt
[ ] Code follows every accepted decision in docs/decisions; lasting decisions made in this work are recorded
@ -232,4 +221,4 @@ Every review comment names the rule, shows the problem, and proposes the fix. Fo
Name a code smell and its technique, with the target layer or file, as [references/refactoring.md](references/refactoring.md#review-comments) does. A smell is a suggestion; when it also breaks a rule on the list below, lead with that rule, mark it blocking, and name the smell in the body. In a feature PR, raise smells only in the code the PR touches. Flag a pattern from the "Not used here" list in [references/design-patterns.md](references/design-patterns.md#not-used-here) with its alternative. Never flag the smells that refactoring.md marks as intended.
Block a merge only for: code that breaks an accepted project decision; a boundary or layer violation; a client-side dependency in a repository; server-only code reachable from a client bundle; tokens or personal data readable by JavaScript (a non-HttpOnly cookie or local storage); stale cache after a mutation; a sprite change without a version bump, a font changed under its old name, or a font or sprite name that a build step hashes; a service worker that stores anything beyond JS, CSS, fonts, and the icon sprite, or a renamed or removed `/sw.js`; structured data that says what the page doesn't show or depends on the viewer, or an `application/ld+json` script written outside island's `JsonLd`; missing error handling; missing loading or empty states; inaccessible contrast; UI that flickers on update; a server-side cache; a server render that depends on auth without the developer's explicit request; a page not rendered per request, or a web-vitals or bundle-budget regression. Everything else is a suggestion with a rationale.
Block a merge only for: code that breaks an accepted project decision; a boundary or layer violation; a client-side dependency in a repository; server-only code reachable from a client bundle; tokens or personal data readable by JavaScript (a non-HttpOnly cookie or local storage); stale cache after a mutation; a sprite change without a version bump, a font changed under its old name, or a font or sprite name that a build step hashes; missing error handling; missing loading or empty states; inaccessible contrast; UI that flickers on update; a server-side cache; a server render that depends on auth without the developer's explicit request; a page not rendered per request, or a web-vitals or bundle-budget regression. Everything else is a suggestion with a rationale.

View File

@ -2,7 +2,7 @@
Public websites with 1–20 million visitors a day, like Amazon, eBay, and Digikala. Every kilobyte and millisecond is multiplied by millions of sessions. Most visitors arrive from search on mid-range phones, and many are logged out. Performance and SEO decide the architecture, the server renders every page fresh and caches nothing, and the codebase must stay maintainable as teams and features grow.
Contents: Targets · No server cache · Rendering · Server and client entries · Data flow · Errors · State and auth · Bundle and code splitting · Hydration and navigation · Deploys and version skew · Responsiveness and monitoring · Example: caches, page, and parts · Definition of Done
Contents: Targets · No server cache · Rendering · Server and client entries · Data flow · Errors · State and auth · Bundle and code splitting · Hydration and navigation · Responsiveness and monitoring · Example: caches, page, and parts · Definition of Done
## Targets
@ -26,16 +26,8 @@ The Next.js server renders a fresh page for every request and keeps nothing betw
- Keep Cache Components (`cacheComponents` in `next.config.ts`) off, because it prerenders a static shell at build time. Every root layout declares `export const dynamic = 'force-dynamic'`, which renders each route at request time and sends every `fetch` with `no-store`. Metadata routes (`sitemap.ts`, `robots.ts`, generated icons and Open Graph images) are cached by default and no layout covers them, so each one declares it too.
- Never use `'use cache'`, `unstable_cache`, `fetch` caching (`cache: 'force-cache'`, `next: { revalidate, tags }`), the `revalidate` segment config, `dynamic = 'force-static'` or `'error'`, or `generateStaticParams`. The HTTP lib sends every server request with `cache: 'no-store'` (see [lib-http.md](lib-http.md#server-side)).
- Never keep back-end data or rendered output in module scope, such as a `Map`, an LRU, or a memoized promise. Settings made once at startup, like env and the root `http` client, are fine.
- Caches that end with the request are fine: React `cache()` (the features' `caches/`) and the per-request `QueryClient`. So are caches in the browser: the TanStack Query cache, the router cache, and the service worker's cache, which holds only JS, CSS, fonts, and the icon sprite, never pages or data ([lib-pwa.md](lib-pwa.md)).
- Caches that end with the request are fine: React `cache()` (the features' `caches/`) and the per-request `QueryClient`. So are caches in the browser, like the TanStack Query cache and the router cache.
- Nothing needs revalidating. After a mutation that changes server-rendered content, call `router.refresh()` and the server renders the page again.
- Every app's `next.config.ts` turns on fetch logging with full URLs, so the dev server prints each server `fetch` with its whole URL, status, time, and cache result. That shows which back-end calls a page makes and proves each one skips the cache:
```ts
logging: {
fetches: { fullUrl: true },
},
```
- Every request pays for a full render, so keep it cheap: stream slow parts, fetch in parallel, and when a back-end call is slow, fix or cache it in the back end, never in Next.js.
## Rendering
@ -47,12 +39,11 @@ The Next.js server renders a fresh page for every request and keeps nothing betw
- Pages are thin entrypoints. The page resolves the device on the server and renders the mobile or the desktop template. Only that view's client code ships, the markup matches on hydration, and nothing shifts. Never choose between layouts with viewport checks in components.
- Stream: add `loading.tsx` per route group and `<Suspense>` with same-size skeletons around slow parts, each inside its own `PartBoundary`. One slow or failing backend call must never block the whole page. Record each route's streamed and auth-dependent parts in the plan.
- Server code reads data through the features' caches, so `generateMetadata`, the page, and every server component share one request per distinct call (see Data flow).
- Every indexable page renders its JSON-LD in the page entry, outside every `<Suspense>`, from the data its first paint already awaits, so structured data is in the initial HTML and costs no extra request ([lib-json-ld.md](lib-json-ld.md#rendering)).
## Server and client entries
- Each project except apps exposes `src/index.ts`, safe to import anywhere, and `src/server.ts`, server only. `server.ts` starts with `import 'server-only';` and is exported as `@project/<name>/server`. Client code imports only `index.ts` entries, and `index.ts` never re-exports from `server.ts`.
- `server.ts` holds server-only capabilities: caches, page data loaders, SEO builders (the platform's `app/json-ld/`), device detection, the server HTTP configuration, and server-side integrations. Server-only files are exported only from `server.ts`, never from a module's `index.ts`.
- `server.ts` holds server-only capabilities: caches, page data loaders, SEO builders, device detection, the server HTTP configuration, and server-side integrations. Server-only files are exported only from `server.ts`, never from a module's `index.ts`.
- Repositories have no client-side dependencies, so they are exported from `index.ts` and run on both sides.
- A server page loader that combines several caches for one page's first paint sits in that page's `models/<page>/` folder (`load-<page>-page.ts`) and is exported only through `server.ts`.
- `bootstrap.server.ts` must run before server rendering: import it at the top of every root layout. `bootstrap.client.ts` must run before client components render, both during SSR and in the browser: import it first in the app's root client component, the one that renders the platform's `AppShell`. Client components render in a separate module graph, so values set by server-only code are invisible to them. Make both bootstraps idempotent.
@ -124,23 +115,10 @@ The model, the boundaries, and their code are in [error-handling.md](error-handl
- Navigate with `next/link` so routes prefetch. Keep the header and footer in layouts, so navigation re-renders only the page segment.
- Protect INP: keep event handlers light, wrap non-urgent updates in `startTransition`, debounce search input by 250–400 ms, and for long interactive lists try `content-visibility` first; a virtualization library needs approval ([rendering-patterns.md](rendering-patterns.md)).
## Deploys and version skew
A deploy doesn't end the sessions already open. A tab keeps running the old release's JavaScript until it reloads, while the servers already run the new release. These rules keep that tab working, or move it to the new release with a normal page load instead of an error.
- Build once per release, and run that same output on every instance, so all of them share one build ID and one set of asset files. Never build on each server.
- Mark every release with Next.js's deployment ID. CI sets `NEXT_DEPLOYMENT_ID` to the release's commit SHA when it runs `next build`; Next.js reads it itself. It adds `?dpl=<id>` to its asset URLs and sends the ID with every client-side navigation. When an old tab navigates and the IDs differ, Next.js does a full page load into the new release instead of a client-side navigation. The value changes on every release, so it comes from CI, never from `.env` or a literal `deploymentId` in `next.config.ts`; no app code reads it.
- Keep old releases' static files. Serve `/_next/static/` on the app's own origin from storage that every release adds to: on deploy, copy the build's `.next/static/` into it without deleting what's there, and delete a release's files only 30 days after it stopped serving. An old tab that loads a lazy chunk (`next/dynamic`, `LoadOnVisible`, or a route it hasn't visited) then still finds it. Replacing `.next/` in place, as a plain `next start` deploy does, deletes the old chunks, and those loads fail with 404. Keep the same origin: the service worker stores only same-origin files ([lib-pwa.md](lib-pwa.md)).
- During a rolling deploy, old and new instances serve side by side. Shared static storage lets every page find its chunks whichever instance rendered it, and a navigation that reaches the other release gets the deployment ID's full page load.
- The back-end contract changes compatibly: each back-end release keeps serving the previous front-end release for as long as its tabs live (additive fields, old endpoints kept), and each front-end release works with the back end it may meet during a rolling deploy.
- Feature actions run in the browser and Server Actions aren't used, so no action ID goes stale between releases.
- The service worker keeps the chunks each visitor already loaded, so an old tab often gets them from the device, and it never caches pages, so a reload always lands on the current release ([lib-pwa.md](lib-pwa.md)).
- What still fails, a chunk missing despite these rules, is classified as outdated by the error handler. A page or app boundary reloads the page once, a part boundary and an action's toast offer Reload page, and nothing is reported ([error-handling.md](error-handling.md#boundaries)). Watch 404s on `/_next/static/` in the CDN logs after each deploy instead: a rise means old files were deleted too early.
## Responsiveness and monitoring
- Each route has a mobile and a desktop template, and each template stays fluid across its device range. Touch targets are at least 44×44 px on mobile.
- Report field web vitals per route (`useReportWebVitals` into the analytics integration), each with whether the service worker controlled the page ([lib-pwa.md](lib-pwa.md#measuring)), report errors through the error handler to the Sentry integration (`instrumentation.ts` on the server, `bootstrap.client.ts` in the browser), and review p75 per release.
- Report field web vitals per route (`useReportWebVitals` into the analytics integration), report errors through the error handler to the Sentry integration (`instrumentation.ts` on the server, `bootstrap.client.ts` in the browser), and review p75 per release.
## Example: caches, page, and parts
@ -151,7 +129,6 @@ In [page-example.md](page-example.md). Read it when you add a new page, or a par
```
[ ] Fresh page per request: Cache Components off; every root layout and metadata route exports dynamic = 'force-dynamic'
[ ] next.config.ts sets logging: { fetches: { fullUrl: true } }
[ ] No server cache: no 'use cache', unstable_cache, fetch caching, revalidate, or generateStaticParams; no back-end data kept in module scope
[ ] Server code reads data only through caches with primitive arguments; no page, loader, or server component calls a repository directly
[ ] Each client part gets server data as props or through query hydration; server prefetches call the cache
@ -167,7 +144,5 @@ In [page-example.md](page-example.md). Read it when you add a new page, or a par
[ ] No hydration warnings; LCP image not lazy; images, fonts, and banners cause no layout shift
[ ] No store writes during server render; per-request QueryClient on the server
[ ] No cookie or local-storage reads during render; persisted stores rehydrate after mount
[ ] Metadata, canonical URL, and hreflang; every indexable page's JSON-LD follows lib-json-ld.md and passes the Rich Results Test
[ ] Each release is built once, runs the same output on every instance, and is marked with NEXT_DEPLOYMENT_ID from CI
[ ] /_next/static/ keeps every release's files until 30 days after that release stopped serving
[ ] Metadata, canonical URL, hreflang, and structured data where relevant
```

View File

@ -155,18 +155,6 @@ This is an excerpt. The real file defines every semantic token the components us
@import './fonts.css';
@import './utilities.css';
@source '../';
@layer base {
* {
scroll-behavior: smooth;
}
@media (prefers-reduced-motion: reduce) {
* {
scroll-behavior: auto;
}
}
}
```
`styles/fonts.css`. Each `src` is a root path to the file in the app's `public/fonts/`, so no build step renames it ([ui-rules.md](ui-rules.md#fonts-and-the-icon-sprite)). The fallback face is a local font resized to the web font's metrics, so the swap doesn't shift layout. Measure the override values once for each face, and list the fallback after the web font in `--font-sans` in `theme.css`.
@ -405,9 +393,7 @@ export function showActionError(error: unknown, { t, failedMessage, retry, reloa
? { label: t('errors:action.try-again'), onClick: retry }
: errorClass.retry === 'reload' && reload
? { label: t('errors:action.reload'), onClick: reload }
: errorClass.retry === 'reload-page'
? { label: t('errors:action.reload-page'), onClick: () => window.location.reload() }
: undefined;
: undefined;
toast.error(failedMessage, {
id: `action-error:${failedMessage}`,

View File

@ -34,9 +34,9 @@ Reuse these before you add anything.
| Module | Every module's `index.ts`; `server.ts` for server-only code | Every module. Re-export the public API by name and keep the rest private: never `export *`, never import another module's internal file, and never re-export `server.ts` from `index.ts` ([project-structure.md](project-structure.md#exports-and-tree-shaking)) |
| Singleton | The root `http`, `cookie`, `storage`, `eventEmitter`, zustand stores, and the browser `QueryClient` from `getQueryClient()` | For a service the whole app shares: a module instance that the bootstrap configures (`export const cookie = new CookieAdapter()`), never a class with `getInstance`. On the server one instance serves every request, so per-request objects come from a function (a new `QueryClient` per `getQueryClient()` call, a per-request i18next instance), and nothing writes to a store during server render ([b2c-b2b.md](b2c-b2b.md#state-and-auth)) |
| Factory functions | `createHttpClient`, `createClientEnv`, `createServerEnv`, `makeQueryClient`, and key factories such as `productKeys` | When several callers build the same kind of object from different inputs: a function that returns a new object or closure. Query keys always come from the repository's key factory ([code-patterns.md](code-patterns.md#repository)). Don't add a factory for an object built in one place |
| Adapter | `CookieAdapter` over `document.cookie`; each repository's `mappers.ts`; each integration over its vendor API; the json-ld lib over the schema.org vocabulary | At a boundary whose shape you don't own. Translate once, at the edge, so no `*Dto`, vendor type, cookie string syntax, or schema.org shape crosses it. Don't adapt two of your own modules to each other; change one of them |
| Adapter | `CookieAdapter` over `document.cookie`; each repository's `mappers.ts`; each integration over its vendor API | At a boundary whose shape you don't own. Translate once, at the edge, so no `*Dto`, vendor type, or cookie string syntax crosses it. Don't adapt two of your own modules to each other; change one of them |
| Facade | The `http` client over `fetch`, `XMLHttpRequest`, retry, refresh, and abort; feature actions over repositories, stores, storage, and events | When callers would repeat the same sequence of calls into several parts: one function, or one object with a few verbs. Callers never reach past it: no `fetch` outside the HTTP lib, and no model that repeats an action's steps |
| Proxy | Features' `caches/` (React `cache()`); `LocalStorageAdapter`; route guards; lazy widgets; the pwa lib's service worker | A cache dedupes calls within one request and never outlives it. The service worker stands in front of the network only for JS, CSS, fonts, and the icon sprite ([lib-pwa.md](lib-pwa.md)). `LocalStorageAdapter` keeps the `Storage` interface while it namespaces keys and absorbs blocked storage, so it works as a Proxy; keep the name its spec gives it. A guard lets a route through only when its check passes. When lazy loading pays off is in rendering-patterns.md |
| Proxy | Features' `caches/` (React `cache()`); `LocalStorageAdapter`; route guards; lazy widgets | A cache dedupes calls within one request and never outlives it. `LocalStorageAdapter` keeps the `Storage` interface while it namespaces keys and absorbs blocked storage, so it works as a Proxy; keep the name its spec gives it. A guard lets a route through only when its check passes. When lazy loading pays off is in rendering-patterns.md |
| Decorator | zustand middleware: `immer` and `persist` | When a store needs cross-cutting behavior: wrap the creator and keep its shape, as in `persist(immer(...))` ([code-patterns.md](code-patterns.md#persisted-store)). No TypeScript decorator syntax, and no higher-order components that wrap components (see HOC below) |
| Chain of Responsibility | HTTP request and response interceptors; Next.js `proxy.ts`; nested error boundaries | For steps that every request or error passes through. Interceptors run root first and carry only cross-cutting concerns ([lib-http.md](lib-http.md#interceptors)). `proxy.ts` either answers (a redirect) or passes the request on, after it refreshes an expired session. An error stops at the nearest error boundary: part, then page, then app ([error-handling.md](error-handling.md#boundaries)). Never put business logic in a link |
| Observer | Action events through `eventEmitter`; zustand selectors; the TanStack Query cache and the queries that observe it | When code must react to a change that its source shouldn't know about. Events fire only after an operation completes. A listener subscribes once in an AppShell effect and unsubscribes in its cleanup, and a component subscribes to the smallest slice. The emitter only broadcasts, so coordination stays in actions and models |
@ -367,7 +367,7 @@ The GoF patterns that the architecture doesn't already use:
- **Factory Method**: not used in its class form, because nothing here inherits. When a caller needs one of several implementations by key, use a factory function (table above) or a `Record` from key to implementation in the owning module's `constants.ts`. A map of components inside a client component bundles every entry, so heavy entries map to lazy components; a map in a Server Component ships only the client entries it renders (rendering-patterns.md).
- **Abstract Factory**: rarely needed, because matching families are already chosen once, higher up: the theme through tokens (Bridge) and the device through the template. Don't build a context that swaps whole component kits; a second brand is a theme in `theme.css`. A real need for different component sets, such as white-label apps, is decided in the plan first.
- **Builder**: rarely needed. When a value has many optional parts, such as metadata from `configs/seo.ts` or JSON-LD built from a `*Payload` (the json-ld lib's `build*` functions and the platform's `app/json-ld/`, [lib-json-ld.md](lib-json-ld.md)), write a pure function that takes an options object with defaults and returns the finished value. No chained, mutable builder classes; valibot's `pipe` already composes schemas step by step.
- **Builder**: rarely needed. When a value has many optional parts, such as metadata from `configs/seo.ts` or JSON-LD built from a `*Payload`, write a pure function that takes an options object with defaults and returns the finished value. No chained, mutable builder classes; valibot's `pipe` already composes schemas step by step.
- **Prototype**: copying is an immutable update: spread for a shallow copy, `structuredClone` for a deep copy of plain data, and immer drafts inside stores. `http.extend` isn't a Prototype: it delegates to the root live instead of copying it, so settings made later in bootstrap still apply ([lib-http.md](lib-http.md#api)). Never `structuredClone` an object that holds functions or class instances; it throws on functions and drops prototypes.
- **Template Method**: not used in its class form. Its component form already exists: island templates and organisms such as `PageHeader` fix the layout and take the varying parts as slots. For logic, write a function that owns the sequence and takes the varying steps as callbacks, such as `runImport({ validate, upload, dispatch })`, and move it to `shared/utils/` only when a third feature needs the same sequence.
- **Visitor**: rarely needed in app code. To run type-specific logic over mixed nodes, such as CMS content blocks or filter expressions, switch exhaustively over the discriminated union with `assertNever`, or use a `Record` from `type` to handler. A new operation is a new function, and a new node type fails type-check at every switch. No `accept` and `visit` double dispatch.
@ -383,7 +383,7 @@ Keep these out of designs, and flag each one in review with its alternative. A m
- **Inheritance between components.** Compose with `children`, slots, cva variants, and compound parts.
- **HOCs and mixins in new code.** Use a hook or a wrapper component.
- **Events for request and response flows**, such as emitting `cart.totalRequested` and waiting for a reply event. Call the action or repository and await it; events only fan out after an operation completes.
- **A second event bus, cache layer, or state library**, such as RxJS subjects, a hand-made fetch cache, a service worker that stores pages or data, Redux, or a context used as a store. Use the event emitter, the query cache (or `cache()` within one server request), the pwa lib's worker for JS, CSS, fonts, and the icon sprite only, and zustand.
- **A second event bus, cache layer, or state library**, such as RxJS subjects, a hand-made fetch cache, Redux, or a context used as a store. Use the event emitter, the query cache (or `cache()` within one server request), and zustand.
- **A pattern for a future that isn't planned.** Write the direct code, and extract the pattern when the third case arrives (refactoring.md).
- **A pattern that needs an upward or cross-product import, or `export *`**, such as an integration that imports a feature to listen to it. Wire it one level up, in the AppShell or the bootstrap, and re-export by name.
- **A pattern library without approval**, such as XState or InversifyJS. Use the in-stack alternative first: a discriminated union and a pure reducer in `useReducer` or a zustand store instead of XState, and the bootstrap's `configure` and `setEnv` instead of InversifyJS. Any dependency outside [the stack](../SKILL.md#2-stack) needs a stated reason and approval.

View File

@ -39,7 +39,7 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
}
```
**The fallback.** `app/error-boundaries/error-fallback/ErrorFallback.tsx`. `size` is `'app' | 'page' | 'part'`; island's molecules take `'page' | 'part'`. The outdated fallback needs no branch of its own: `cause` picks its copy, and it gets Reload page like the logic fallback.
**The fallback.** `app/error-boundaries/error-fallback/ErrorFallback.tsx`. `size` is `'app' | 'page' | 'part'`; island's molecules take `'page' | 'part'`.
```tsx
'use client';
@ -50,21 +50,18 @@ import { classifyError, describeError, handleError } from '@project/libs/error-h
import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { StatusEmptyState } from '../status-empty-state';
import { reloadOnce } from './reload-once';
import type { ErrorFallbackProps } from './types';
export function ErrorFallback({ error, size, name, onRetry }: ErrorFallbackProps) {
const { t } = useTranslation('errors');
const headingRef = useRef<HTMLHeadingElement>(null);
const { read, cause, retry } = classifyError(error);
const { read, cause } = classifyError(error);
const islandSize = size === 'part' ? 'part' : 'page';
useEffect(() => {
handleError(error, { where: size, name });
// Code from an older deploy: a failed page or app reloads into the current deploy. A part never does.
if (retry === 'reload-page' && size !== 'part' && reloadOnce()) return;
if (size !== 'part') headingRef.current?.focus();
}, [error, size, name, retry]);
}, [error, size, name]);
if (read === 'silent') return null;
if (read !== 'boundary') return <StatusEmptyState variant={read} size={islandSize} headingRef={headingRef} />;
@ -89,23 +86,6 @@ export function ErrorFallback({ error, size, name, onRetry }: ErrorFallbackProps
}
```
`error-fallback/reload-once.ts`. `constants.ts` holds `OUTDATED_RELOAD_STORAGE_KEY = 'outdated-reload-at'` and `OUTDATED_RELOAD_WINDOW_MS = 60_000`.
```ts
import { storage } from '@project/libs/local-storage';
import { OUTDATED_RELOAD_STORAGE_KEY, OUTDATED_RELOAD_WINDOW_MS } from './constants';
// At most one reload a minute, so a deploy that is still missing files shows the fallback instead of a reload loop.
export function reloadOnce(): boolean {
if (!navigator.onLine) return false;
const last = storage.getJSON<number>(OUTDATED_RELOAD_STORAGE_KEY);
if (typeof last === 'number' && Date.now() - last < OUTDATED_RELOAD_WINDOW_MS) return false;
storage.setJSON(OUTDATED_RELOAD_STORAGE_KEY, Date.now());
window.location.reload();
return true;
}
```
`StatusEmptyState` (`error-boundaries/status-empty-state/`) renders island's `EmptyState` with the `errors:empty.<variant>` copy and, at page size, the link back. It is a client component, so the server page and parts can render it too.
**Part boundary.** `app/error-boundaries/part-boundary/PartBoundary.tsx`. `PartBoundaryProps` is `{ name: string }`; `catchError` adds `children`.

View File

@ -10,8 +10,7 @@ Contents: The model · What each failure shows · Boundaries · Reads · Actions
1) Error boundary ─┬─> Whole app (EB-W)
└─> Section (EB-S): a page or a part
Fallback types ─┬─> Network: the API or the connection failed; retry helps
├─> Logic: a JavaScript bug; retry rarely helps; reported
└─> Outdated: the page runs code from an older deploy; a page reload fixes it
└─> Logic: a JavaScript bug; retry rarely helps; reported
2) API error ─┬─> 5xx ─┬─> Read ───> EB-X
│ └─> Action ─┐
@ -45,7 +44,6 @@ Contents: The model · What each failure shows · Boundaries · Reads · Actions
| 401 | Never reaches the UI: the HTTP lib refreshes, or a failed refresh logs out | Same |
| `ABORTED` | Nothing | Nothing |
| Logic error (a bug) | EB-X, logic fallback with Reload page and the reference ID; reported | Toast with the support sentence; reported |
| A chunk that failed to load (code from an older deploy) | A page or app boundary reloads the page once; a part boundary shows the outdated fallback with Reload page | Toast that the page was updated, with Reload page; the form keeps its values |
| Success with no items | ES `no-data`, or `no-results` when filters or a search are active | Not an error |
- A failed refetch keeps the data on screen and shows nothing. Only a first load that fails reaches a boundary.
@ -63,7 +61,7 @@ Every boundary renders the same `ErrorFallback`, which decides what the user see
1. It classifies the error. A `silent` read renders nothing: an `ABORTED` request, or a 401 whose logout redirect is already on its way.
2. `not-found` and `no-access` render the `StatusEmptyState` at the boundary's size.
3. Everything else renders island's `ErrorState`: the network fallback with Try again, or the logic or outdated fallback with Reload page. They show the reference ID when there is one.
3. Everything else renders island's `ErrorState`: the network fallback with Try again, or the logic fallback with Reload page. Both show the reference ID when there is one.
4. It calls `handleError` once, in an effect, so the error that stopped here is reported once.
Rules:
@ -73,8 +71,7 @@ Rules:
- Retry resets the failed queries first, then the boundary. Otherwise a query that threw keeps its error and throws again at once. There is no provider for this: `useQueryErrorResetBoundary()` returns the global reset.
- In a part boundary, an error with a `digest` came from the server, so Try again calls `retry()`. A browser-side error calls `reset()`, which re-renders without a server round trip.
- Put `PartBoundary` outside the part's `<Suspense>`, so the fallback replaces the skeleton and the part together. Widgets that load inside a form, such as select options and lazy tabs, get their own `PartBoundary`, so their failure never unmounts the form and loses what the user typed.
- `LoadOnVisible` and dynamic imports need nothing extra: a chunk that fails to load throws to the part's boundary ([rendering-patterns.md](rendering-patterns.md#loading-patterns)), and the error handler classifies it as outdated.
- An outdated error at page or app size reloads the page at once, because the page is already gone: at most once a minute, with the time kept in local storage, and only while the browser is online. Otherwise the boundary shows the outdated fallback. A part boundary never reloads on its own, because the user may be typing elsewhere on the page; it offers Reload page. The deploy rules that keep these errors rare are in [b2c-b2b.md](b2c-b2b.md#deploys-and-version-skew).
- `LoadOnVisible` and dynamic imports need nothing extra: a chunk that fails to load throws to the part's boundary ([rendering-patterns.md](rendering-patterns.md#loading-patterns)).
## Reads
@ -91,7 +88,7 @@ Rules:
- `showActionError` is the one error toast: it calls `handleError`, returns early for `silent` errors, and shows `toast.error` with:
- the title: what failed, from the caller's `failedMessage`, naming the object ("Category 'Kitchenware' wasn't saved");
- the description: the error's message and hint (the guide), or, when there is neither (5xx, unknown, logic), one support sentence with the reference ID;
- a button from the retry kind: Try again for `again` when the caller passes `retry`, Reload for `reload` when the caller passes `reload`, Reload page for `reload-page`, and none for `wait`, `fix`, and `none`;
- a button from the retry kind: Try again for `again` when the caller passes `retry`, Reload for `reload` when the caller passes `reload`, and none for `wait`, `fix`, and `none`;
- `duration: Infinity`, an `id` built from `failedMessage` so a repeated failure replaces its toast instead of stacking, and `testId: 'action-error'`.
- `applyServerErrors` puts each server field error under its field and focuses the first, puts field errors for fields the form doesn't render (and whole-submission errors) in the form alert, and then calls `showActionError`. The form keeps every value.
- The caller passes `retry` only when running the action again is safe (see What each failure shows). Pass `reload` for actions on data that can change underneath the user (409, 404): it invalidates or refetches the affected queries, and the user tries again on fresh data.
@ -113,7 +110,7 @@ Server reads classify on the server, because a Server Component error reaches th
- The page reads its main data through `readOnServer`, a server-only helper in the platform's `app/error-boundaries/`. It returns `{ status: 'ok', data }`, or `not-found` for 404 and 410 and `no-access` for 403, and rethrows the rest to the page's `error.tsx`. Server reads send no auth cookies, so only pages that are the same for every visitor read on the server; a page that needs a logged-in user loads in the browser ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)).
- `not-found` calls `notFound()`, which renders the group's `not-found.tsx`. When the page has already started streaming (it has a `loading.tsx`), the status stays 200 and Next.js adds a `noindex` robots tag, which search engines treat as not found.
- `no-access` renders the page-size `StatusEmptyState`, and `generateMetadata` returns `robots: { index: false }` for it. Like `not-found` and every error page, it renders no JSON-LD ([lib-json-ld.md](lib-json-ld.md#rendering)). `forbidden()` and `unauthorized()` are experimental and not used ([rendering-patterns.md](rendering-patterns.md#rendering-patterns)).
- `no-access` renders the page-size `StatusEmptyState`, and `generateMetadata` returns `robots: { index: false }` for it. `forbidden()` and `unauthorized()` are experimental and not used ([rendering-patterns.md](rendering-patterns.md#rendering-patterns)).
- A server part reads through `readOnServer` too: it renders the part-size `StatusEmptyState` for `not-found` and `no-access`, and rethrows the rest to its `PartBoundary`.
- A part that must show an empty state awaits its read on the server. An un-awaited prefetch streams its error to the browser as a digest, so use it only for reads that can't answer 404 or 403. `shouldRedactErrors: () => false` in the dehydrate options keeps the real error on the server, so Next.js reports it and the browser gets its digest instead of a generic "redacted" error.
- `error.tsx` and `global-error.tsx` render `<meta name="robots" content="noindex" />`, so an error page is never indexed.
@ -129,7 +126,7 @@ Server reads classify on the server, because a Server Component error reaches th
## Copy, accessibility, and i18n
- Every fallback, empty state, and toast says what happened and what the user can do, following the copy rules in [b2c-b2b.md](ui-rules.md#copy). Unknown errors say: "Something went wrong on our side. Try again in a moment. If it keeps happening, contact support and mention reference ID `a1b2c3`."
- The `errors` namespace loads on every route, because any route can fail. It holds the HTTP lib's keys (`http.network`, `http.timeout`, their hints, and `http.retry-after`), the support sentences, the fallback copy (`network`, `logic`, and `outdated`), the `app.outdated` message, the `not-found` and `no-access` copy, and the button labels.
- The `errors` namespace loads on every route, because any route can fail. It holds the HTTP lib's keys (`http.network`, `http.timeout`, their hints, and `http.retry-after`), the support sentences, the fallback copy, the `not-found` and `no-access` copy, and the button labels.
- Server field errors and messages arrive translated; never pass them through `t` again.
- Page and app fallbacks move focus to their heading (`tabIndex={-1}`), so keyboard and screen-reader users land on the explanation. Part fallbacks don't take focus and have no live role, so a failed part never interrupts what the user is doing elsewhere.
- One `<Toaster>` in the AppShell, with `dir` from the locale and its position on the logical end side (`bottom-right` in LTR, `bottom-left` in RTL).
@ -148,7 +145,6 @@ The boundaries, `ErrorFallback`, `readOnServer`, and the query client's error se
[ ] Every failed action shows the action-error toast with its hint or the support sentence and reference ID; the form keeps its values
[ ] Server field errors sit under their rendered fields and the rest in the form alert
[ ] Retry follows the retry kind: again only when safe, reload for 409 and 404, a wait hint for 429, fix and resubmit for other 4xx
[ ] A chunk that failed to load reloads the page once at page or app size, offers Reload page in parts and toasts, and isn't reported
[ ] ABORTED and 401 never show anything
[ ] Successful empty responses show the no-data or no-results empty state with a next step
[ ] handleError runs once per error, where it stops; 5xx and logic errors reach the tracker with requestId or digest

View File

@ -12,7 +12,7 @@ Contents: Structure · Types · API · Classification · Messages and reference
packages/libs/src/error-handler/
├── error-handler.ts # configureErrorHandler, classifyError, describeError, handleError
├── types.ts # ErrorClass and its unions, ErrorContext, ErrorReport, ErrorHandlerConfig, TranslateFn, ErrorDescription
├── constants.ts # NOT_FOUND_STATUSES, LIB_MESSAGE_PREFIX, RETRY_AFTER_HINT_KEY, OUTDATED_MESSAGE_KEY, CHUNK_ERROR_PATTERN
├── constants.ts # NOT_FOUND_STATUSES, LIB_MESSAGE_PREFIX, RETRY_AFTER_HINT_KEY
└── index.ts
```
@ -22,10 +22,10 @@ packages/libs/src/error-handler/
## Types
```ts
type ErrorCause = 'network' | 'logic' | 'outdated'; // network: the API or the connection failed, retry helps; logic: a bug, retry rarely helps; outdated: the page runs code from an older deploy, a page reload fixes it
type ErrorCause = 'network' | 'logic'; // network: the API or the connection failed, retry helps; logic: a bug, retry rarely helps
type ReadOutcome = 'silent' | 'not-found' | 'no-access' | 'boundary'; // what a failed read shows
type ActionOutcome = 'silent' | 'toast'; // what a failed action shows
type RetryKind = 'again' | 'wait' | 'reload' | 'reload-page' | 'fix' | 'none';
type RetryKind = 'again' | 'wait' | 'reload' | 'fix' | 'none';
interface ErrorClass {
cause: ErrorCause;
@ -67,7 +67,7 @@ interface ErrorDescription {
## API
- `configureErrorHandler(config)`: once per module graph, in the app's browser bootstrap (`bootstrap.client.ts`) and in `instrumentation.ts`'s `register()` for the server. It merges `config` into the stored settings, so calling it again is safe. Libs never read env; the bootstrap passes everything in.
- `classifyError(error): ErrorClass`: pure. It decides from the status first, then the code (table below). Anything that isn't an `HttpError` is a logic error, except a chunk that failed to load (outdated) and a server error that reached the browser with only its `digest`.
- `classifyError(error): ErrorClass`: pure. It decides from the status first, then the code (table below). Anything that isn't an `HttpError` is a logic error, except a server error that reached the browser with only its `digest`.
- `describeError(error, t): ErrorDescription`: the words for a toast or a fallback. Only strings that start with `errors:` go through `t`: those are the keys the HTTP lib creates. Server messages and hints arrive translated and pass through as they are.
- `handleError(error, context?): ErrorClass`: call it once, where the error stops (the fallback that renders it, the toast that shows it, the refetch that swallows it, or the server's `onRequestError`). It classifies the error, sends a report when `report` is true, runs `onForbidden` on a 403, and returns the class. It never throws: a failing reporter or callback is swallowed, so handling an error never causes a second one.
@ -87,18 +87,16 @@ The first matching row wins.
| Other 4xx (400, 408, 422, …) | network | boundary | toast | fix | no |
| `NETWORK_ERROR`, `TIMEOUT` | network | boundary | toast | again | no |
| `PARSE_ERROR`, `INTERCEPTOR_ERROR`, `UNKNOWN` | logic | boundary | toast | none | yes |
| Not an `HttpError`: a chunk that failed to load | outdated | boundary | toast | reload-page | no |
| Not an `HttpError`, with a `digest` | network | boundary | toast | again | no |
| Anything else | logic | boundary | toast | none | yes |
- 401 never reaches the UI: the HTTP lib refreshes, and a failed refresh logs out ([lib-http.md](lib-http.md#refresh-token)). The server has no refresh and sends no auth cookies, so a server read never expects a 401; `readOnServer` rethrows one to its boundary like any other error ([error-handling.md](error-handling.md#b2cb2b-server)).
- A `digest` without `HttpError` fields is a Server Component error seen in the browser: Next.js sends only the digest in production, so the browser can't classify it. The server already classified and reported it, and a retry renders the part again on the server.
- A chunk that failed to load means the page runs code from an older deploy whose file is gone, or the connection dropped while the code loaded. It isn't a bug, so it isn't reported, and a page reload fixes both. The lib matches webpack's `ChunkLoadError` and both bundlers' messages (`CHUNK_ERROR_PATTERN`); check the pattern once against the repo's bundler by deleting a chunk in a production build. Deploy rules that keep it rare: [b2c-b2b.md](b2c-b2b.md#deploys-and-version-skew).
- Retry kinds: `again` offers a button that runs the same thing again; `wait` offers none and the hint says how long; `reload` offers a button that loads the latest data first; `reload-page` offers a button that reloads the whole page; `fix` offers none, because the user must change the input; `none` offers none.
- Retry kinds: `again` offers a button that runs the same thing again; `wait` offers none and the hint says how long; `reload` offers a button that loads the latest data first; `fix` offers none, because the user must change the input; `none` offers none.
## Messages and reference ID
- `message` is set for 4xx statuses (the back end localizes them from `Accept-Language`) and for `NETWORK_ERROR` and `TIMEOUT` (the lib's `errors:` keys). It is left out for 5xx and logic errors, whose text means nothing to users and can leak internals. A chunk that failed to load gets `t('errors:app.outdated')`: the page was updated, and reloading it continues.
- `message` is set for 4xx statuses (the back end localizes them from `Accept-Language`) and for `NETWORK_ERROR` and `TIMEOUT` (the lib's `errors:` keys). It is left out for 5xx and logic errors, whose text means nothing to users and can leak internals.
- `hint` is the error's hint. When there is none and the error has `retryAfter`, it is `t('errors:http.retry-after', { seconds })`.
- `referenceId` is `requestId`, or the `digest` when there is no request id. Support finds the report by either.
@ -110,17 +108,11 @@ The first matching row wins.
## Implementation
`error-handler.ts`, the parts that decide. `constants.ts` holds `NOT_FOUND_STATUSES: readonly number[] = [404, 410]`, `LIB_MESSAGE_PREFIX = 'errors:'`, `RETRY_AFTER_HINT_KEY = 'errors:http.retry-after'`, `OUTDATED_MESSAGE_KEY = 'errors:app.outdated'`, and `CHUNK_ERROR_PATTERN = /Loading (CSS )?chunk .+ failed|Failed to load chunk/`.
`error-handler.ts`, the parts that decide. `constants.ts` holds `NOT_FOUND_STATUSES: readonly number[] = [404, 410]`, `LIB_MESSAGE_PREFIX = 'errors:'`, and `RETRY_AFTER_HINT_KEY = 'errors:http.retry-after'`.
```ts
import { isHttpError } from '../http';
import {
CHUNK_ERROR_PATTERN,
LIB_MESSAGE_PREFIX,
NOT_FOUND_STATUSES,
OUTDATED_MESSAGE_KEY,
RETRY_AFTER_HINT_KEY,
} from './constants';
import { LIB_MESSAGE_PREFIX, NOT_FOUND_STATUSES, RETRY_AFTER_HINT_KEY } from './constants';
import type {
ErrorClass,
ErrorContext,
@ -139,7 +131,6 @@ export function configureErrorHandler(next: ErrorHandlerConfig): void {
const SILENT: ErrorClass = { cause: 'network', read: 'silent', action: 'silent', retry: 'none', report: false };
const LOGIC: ErrorClass = { cause: 'logic', read: 'boundary', action: 'toast', retry: 'none', report: true };
const OUTDATED: ErrorClass = { cause: 'outdated', read: 'boundary', action: 'toast', retry: 'reload-page', report: false };
function apiError(read: ReadOutcome, retry: RetryKind, report = false): ErrorClass {
return { cause: 'network', read, action: 'toast', retry, report };
@ -150,15 +141,8 @@ function getDigest(error: unknown): string | undefined {
return typeof error.digest === 'string' ? error.digest : undefined;
}
function isChunkLoadError(error: unknown): boolean {
return error instanceof Error && (error.name === 'ChunkLoadError' || CHUNK_ERROR_PATTERN.test(error.message));
}
export function classifyError(error: unknown): ErrorClass {
if (!isHttpError(error)) {
if (isChunkLoadError(error)) return OUTDATED;
return getDigest(error) ? apiError('boundary', 'again') : LOGIC;
}
if (!isHttpError(error)) return getDigest(error) ? apiError('boundary', 'again') : LOGIC;
const { status, code } = error;
if (code === 'ABORTED' || status === 401) return SILENT;
if (status === 403) return apiError('no-access', 'none');
@ -172,9 +156,7 @@ export function classifyError(error: unknown): ErrorClass {
}
export function describeError(error: unknown, t: TranslateFn): ErrorDescription {
if (!isHttpError(error)) {
return isChunkLoadError(error) ? { message: t(OUTDATED_MESSAGE_KEY) } : { referenceId: getDigest(error) };
}
if (!isHttpError(error)) return { referenceId: getDigest(error) };
const translate = (text?: string) => (text?.startsWith(LIB_MESSAGE_PREFIX) ? t(text) : text);
const isUserFacing =
(error.status >= 400 && error.status < 500) || error.code === 'NETWORK_ERROR' || error.code === 'TIMEOUT';
@ -248,7 +230,6 @@ For building or changing the lib:
[ ] Every row of the classification table returns its class, with status checked before code
[ ] ABORTED and 401 are silent for reads and actions; 403 runs onForbidden once per handleError call
[ ] A plain Error is a reported logic error; an object with only a digest is a network error that isn't reported
[ ] A webpack ChunkLoadError and a Turbopack "Failed to load chunk" error are outdated, retry reload-page, not reported, and describeError gives them the errors:app.outdated message
[ ] describeError translates only errors:-prefixed strings; server messages pass through unchanged
[ ] describeError leaves out the message for 5xx and logic errors and keeps it for 4xx, network, and timeout
[ ] A 429 or 503 with retryAfter and no hint gets the retry-after hint with its seconds

File diff suppressed because it is too large Load Diff

View File

@ -1,492 +0,0 @@
# PWA lib (`packages/libs/src/pwa`)
Makes each app an installable PWA whose repeat visits load JS, CSS, fonts, and the icon sprite from the device. Each app serves one service worker, built from this lib, and the worker stores exactly four kinds of files: JS and CSS from `/_next/static/`, fonts from `/fonts/`, and `/icons/symbol-defs.svg`. Every other request, pages and data included, reaches the network as if no worker existed. Framework-agnostic; built on the native Service Worker and Cache APIs; no dependency (no Workbox or Serwist).
It isn't an offline app. Every page renders fresh on the server for each request ([b2c-b2b.md](b2c-b2b.md#no-server-cache)), so a visitor without a connection sees the browser's offline page.
Contents: What the worker stores · Structure · Types · API · The worker · Updates and the kill switch · Serving the worker · Measuring · Web app manifest · Not in this lib · Implementation · Usage · Acceptance checklist
## What the worker stores
| Kind | URL | Why a stored copy stays correct |
|---|---|---|
| JS | `/_next/static/**/*.js` | Next.js puts a content hash in every name, so a URL never changes content |
| CSS | `/_next/static/**/*.css` | The same content hash |
| Fonts | `/fonts/*.woff2` | A font never changes under its name; a changed font ships under a new name ([ui-rules.md](ui-rules.md#fonts-and-the-icon-sprite)) |
| Icon sprite | `/icons/symbol-defs.svg?v=<N>` | Every change raises `ICON_SPRITE_VERSION`, so the URL changes with the content |
- Same origin and `GET` only. A response is stored only when it has status 200, came from the same origin (`type` is `'basic'`), and wasn't redirected. Never a partial (206), opaque, redirected, or error response.
- Stale-while-revalidate, by the exact URL with its query string, is the default: a stored file is served at once, and a background request checks it. When that response has a different `ETag` (or, without one, a different `Last-Modified`), it replaces the stored copy; an unchanged file is never written again. A miss goes to the network, and the response is stored for the next request.
- Cache first only when the developer explicitly asks for it, with `writeServiceWorker({ strategy: 'cache-first' })` in the app's `next.config.ts`. A stored file is then served with no network request at all. Write the choice and its reason in the plan, and record it as a decision when it's lasting ([decisions.md](decisions.md)).
- The trade-off: these files are immutable under their URLs, so the HTTP cache answers almost every background check, but a visitor whose HTTP cache dropped the file downloads it again. In return, a file that changed under its URL against the rules, such as a font changed under its old name, heals after one visit. Cache first saves those checks and never notices such a change.
- `symbol-defs.svg` is the only SVG the worker stores. Every other SVG, such as a logo, an illustration, `/_next/static/media/*.svg`, or an image on the CDN, is an image, and the worker leaves images alone.
- Storing a new sprite version deletes the older ones, so the cache holds one sprite.
- Everything sits in one cache, `pwa-assets-v1`. Above 200 entries, the oldest go first. An evicted file costs one request, usually answered by the HTTP cache.
- The cache holds only public files that are the same for every visitor, so logout and shared devices need nothing from this lib.
- Storing any other kind of URL changes the architecture. Record it as a decision first ([decisions.md](decisions.md)).
## Structure
```
packages/libs/src/pwa/
├── pwa.ts # configureServiceWorker and registerServiceWorker: the page side
├── service-worker.ts # the worker: a classic script that writeServiceWorker compiles into public/sw.js
├── service-worker-plugin.ts # writeServiceWorker: the build and dev plugin
├── types.ts # ServiceWorkerOptions, ServiceWorkerConfig, CacheStrategy, CacheLoadedMessage, ServiceWorkerPluginOptions
├── constants.ts # SERVICE_WORKER_URL, SERVICE_WORKER_SCOPE, CACHE_NAME_PREFIX, SERVICE_WORKER_CONFIG, SERVICE_WORKER_HEADERS
├── index.ts # the page side
└── plugin.ts # the build side; imported only from build configs
```
- `index.ts` exports `configureServiceWorker`, `registerServiceWorker`, `SERVICE_WORKER_URL`, `SERVICE_WORKER_CONFIG`, and the types `ServiceWorkerOptions` and `ServiceWorkerConfig`. It runs nothing at import, so `bootstrap.client.ts` can import it during SSR. Nothing goes in `server.ts`.
- `plugin.ts` exports `writeServiceWorker`, `SERVICE_WORKER_URL`, `SERVICE_WORKER_HEADERS`, and the types `ServiceWorkerPluginOptions` and `CacheStrategy`, on the `@project/libs/pwa/plugin` subpath. It runs in Node, because it reads and writes files. Only build configs import it, never app code, and no root entry re-exports it. A client import fails the build, because the browser has no `node:fs`.
- `service-worker.ts` runs in the worker's own global scope. It has no `import` or `export`, so the plugin can emit it as one script, and it reads its settings from `SERVICE_WORKER_CONFIG`, which the plugin writes above it. `packages/libs/tsconfig.worker.json` type-checks it with `lib: ["ES2022", "WebWorker"]`. The lib's main tsconfig excludes it, so worker globals such as `clients` never reach the page code's types: the `DOM` and `WebWorker` libs declare the same globals differently.
- Import by subpath: `import { registerServiceWorker } from '@project/libs/pwa'`, and in `next.config.ts`, `import { writeServiceWorker } from '@project/libs/pwa/plugin'`.
## Types
```ts
type ServiceWorkerOptions = {
enabled: boolean; // from the app's env; false unregisters the worker and deletes its caches
};
type CacheStrategy = 'stale-while-revalidate' | 'cache-first';
// The worker's settings. writeServiceWorker writes them into public/sw.js; the worker reads nothing else.
type ServiceWorkerConfig = {
strategy: CacheStrategy; // 'stale-while-revalidate' unless the developer explicitly chose 'cache-first'
cacheName: string; // the one cache, e.g. 'pwa-assets-v1'
cachePrefix: string; // every cache this lib owns starts with it
maxEntries: number; // above it, the oldest entries go first
cacheLoadedMessage: string; // the type of the message that lists what the page already loaded
paths: {
static: string; // '/_next/static/': .js and .css only
fonts: string; // '/fonts/': .woff2 only
sprite: string; // '/icons/symbol-defs.svg', stored with its ?v=<N>
};
};
// The page lists what it loaded before the worker controlled it.
type CacheLoadedMessage = {
type: string;
urls: string[];
};
type ServiceWorkerPluginOptions = {
publicDir: string; // absolute path of the app's public/
strategy?: CacheStrategy; // only when the developer explicitly changes it; default 'stale-while-revalidate'
};
```
## API
- `configureServiceWorker(options)` runs once, in `bootstrap.client.ts`, with `enabled` from the app's env. It only stores options, so it's safe during SSR. Until it runs, `enabled` is `false`.
- `registerServiceWorker()` runs once per page load, in an effect of the platform's `AppShell`. It returns at once and does its work in the background:
- With `enabled: true`, it waits for the window's `load` event, so the worker never competes with the page for the network. Then it registers `/sw.js` with scope `/` and `updateViaCache: 'none'`. When the worker didn't control this page load yet (a first visit, or a hard reload), it sends the worker the URLs the page has already loaded (`performance.getEntriesByType('resource')`), so the worker stores the matching files from the HTTP cache at once.
- With `enabled: false`, it unregisters every worker of the origin and deletes every cache whose name starts with `pwa-`. That's the kill switch.
- Browsers without service workers, and plain-`http` hosts other than `localhost`, skip it. A failed registration is ignored: the worker only makes repeat visits faster, and the site works the same without it.
- On the server, it throws a clear error ("registerServiceWorker is browser-only; call it in an effect") instead of the unclear "window is not defined".
- `writeServiceWorker({ publicDir, strategy })` compiles `service-worker.ts` with the workspace's own `typescript` (`transpileModule`; no new dependency), writes `SERVICE_WORKER_CONFIG` above it with the developer's `strategy` when one is passed, and saves the result as `<publicDir>/sw.js`. It writes only when the content changed, so the dev server's file watchers don't restart for nothing.
- `sw.js` is generated, so git ignores it, like the fonts and the sprite in `public/`.
- Add `{projectRoot}/public/sw.js` to the app's build target `outputs`, so an Nx cache hit restores it together with `.next/`. A deploy without it serves a 404 at `/sw.js`.
## The worker
- `install`: calls `skipWaiting()`. On Chromium (Chrome 123 and later, Static Routing API) it also adds one route that sends navigations straight to the network, so the worker never starts only to let a page through.
- `activate`: turns on navigation preload, deletes every `pwa-` cache except the current one, and calls `clients.claim()`, so the open pages use the new worker at once.
- `fetch`:
- Non-`GET` requests: untouched.
- Navigations, on browsers without static routing: answered with the navigation preload response, so the page request starts while the worker starts (Chrome 59, Edge 18, Firefox 99, and Safari 15.4 and later), or with `fetch` when preload is off. Never stored.
- The four kinds in the table: stale-while-revalidate, or cache first when the developer chose it.
- Everything else (RSC payloads, API calls, images, media, other SVGs, and cross-origin requests): no `respondWith`, so the browser handles it as if no worker existed.
- An `only-if-cached` request whose mode isn't `same-origin` (DevTools sends them) is left alone, because `fetch` rejects it.
- `message`: the page's list of loaded URLs. The worker checks each URL against the four kinds again, because it trusts no message, and stores the ones it doesn't have.
- The worker runs only this lib's code: no `importScripts`, no third-party code, and no push, sync, or other events.
## Updates and the kill switch
- `sw.js` changes only when this lib changes (its worker code or `SERVICE_WORKER_CONFIG`). The deploy that ships the change reaches each visitor at their next navigation: the browser checks `/sw.js`, installs the new worker, and the new worker takes over at once.
- Taking over at once is safe because the worker never stores pages. Every page already comes from the current deploy, and every stored file is immutable under its URL. So there is no "new version available" prompt.
- Raise the `v1` in `SERVICE_WORKER_CONFIG.cacheName` whenever the worker changes what it stores or how it keys it. Activation deletes the old cache, and visitors refill the new one as they browse.
- Changing the strategy changes `sw.js`, so it reaches visitors like any other worker update. The stored files stay valid under both strategies, so `cacheName` keeps its version.
- Kill switch: set `NEXT_PUBLIC_SERVICE_WORKER_ENABLED=false` in the app's `.env.production`, then build and deploy (public variables are inlined at build time). On each visitor's next page load, the page unregisters the worker and deletes its caches. Pages are never stored, so the new page code always arrives.
- A broken worker is replaced by a fixed one: deploy the fix, and the next update check installs it.
- Never delete or rename `/sw.js`. Browsers check that URL for updates, and without a valid script there, no new worker can replace the installed one. To retire the worker, turn it off and keep `/sw.js`.
- Keep it off in development (`.env.development`): a dev chunk can keep its name while its code changes, and the worker would serve the old code at least once. Test the worker in a production build (`next build` and `next start`) on `localhost`, which browsers treat as secure.
## Serving the worker
- Each app's `next.config.ts` calls `writeServiceWorker` and adds `SERVICE_WORKER_HEADERS` for `/sw.js` to `headers()` (code in Usage):
- `Cache-Control: no-cache`: browsers and the CDN revalidate it on every update check, so a new worker reaches visitors at their next navigation. Never give it the immutable header that fonts and the sprite get, and make the CDN honor `no-cache` for it.
- `Content-Security-Policy: default-src 'self'; script-src 'self'`: the worker can't load or fetch anything from another origin.
- `proxy.ts`'s matcher leaves out `/sw.js` and `/manifest.webmanifest`. Browsers refuse a worker script behind a redirect, and a locale or auth redirect would break registration.
- Each app has its own origin and is served from the origin's root, as the root paths of its fonts and sprite already require. Two apps on one origin would share one worker scope and one cache.
## Measuring
- Every web-vitals report says whether a service worker controlled the page: `navigator.serviceWorker?.controller ? 'controlled' : 'none'`, sent by the analytics integration with each `useReportWebVitals` metric.
- Compare the p75 of LCP, FCP, TTFB, and INP for controlled and uncontrolled page loads in every release review. When controlled loads are slower, turn the worker off and fix it.
## Web app manifest
- Each app has `app/manifest.ts`. Next.js serves it at `/manifest.webmanifest` and adds the `<link rel="manifest">`. It exports `dynamic = 'force-dynamic'`, like every metadata route ([b2c-b2b.md](b2c-b2b.md#no-server-cache)).
- Its fixed fields live in `configs/pwa.ts`: `id: '/'`, which keeps the installed app's identity if `start_url` changes; `start_url: '/'`; `scope: '/'`; `display: 'standalone'`; `background_color`; `theme_color`; and the icons.
- `name`, `short_name`, and `description` come from i18next. Browsers fetch the manifest without cookies, so it can't follow the visitor's locale cookie: use the app's default locale, and set `lang` and `dir` from it.
- `background_color` and `theme_color` are the light theme's hex values for the page surface and the brand color in island `theme.css`. The manifest can't read CSS variables, so change both files together. The root layout's `generateViewport` sets `themeColor` for the theme the server chose.
- Icons are PNG files in the app's `public/pwa/`: 192×192, 512×512, and a 512×512 `maskable` icon whose logo sits in the center 80%. `app/apple-icon.png` (180×180) covers iOS. The worker doesn't store them, because they're images.
## Not in this lib
| Not here | Why |
|---|---|
| Pages, RSC payloads, and an offline page | Every page renders fresh per request, and auth-dependent UI renders in the browser. A stored page would be stale, or another visitor's |
| API data | The TanStack Query cache holds server state, and the HTTP lib owns retries |
| Images, media, and other SVGs | They're many, large, and different per page; the HTTP cache and the CDN keep them. Only the sprite serves every page |
| Cross-origin files and third-party scripts | Opaque responses can't be checked, and they count heavily against the storage quota |
| Push, background sync, and a custom install prompt | Product features: each needs product design, its own worker code, and a recorded decision |
## Implementation
`constants.ts`
```ts
import type { ServiceWorkerConfig } from './types';
export const SERVICE_WORKER_URL = '/sw.js';
export const SERVICE_WORKER_SCOPE = '/';
export const CACHE_NAME_PREFIX = 'pwa-';
export const SERVICE_WORKER_CONFIG: ServiceWorkerConfig = {
strategy: 'stale-while-revalidate', // the default; only the developer switches an app to 'cache-first'
cacheName: `${CACHE_NAME_PREFIX}assets-v1`, // raise v1 when the worker changes what it stores or how
cachePrefix: CACHE_NAME_PREFIX,
maxEntries: 200,
cacheLoadedMessage: 'pwa.cache-loaded',
paths: { static: '/_next/static/', fonts: '/fonts/', sprite: '/icons/symbol-defs.svg' },
};
export const SERVICE_WORKER_HEADERS: Readonly<Record<string, string>> = {
'Cache-Control': 'no-cache',
'Content-Security-Policy': "default-src 'self'; script-src 'self'",
};
```
`pwa.ts`
```ts
import { CACHE_NAME_PREFIX, SERVICE_WORKER_CONFIG, SERVICE_WORKER_SCOPE, SERVICE_WORKER_URL } from './constants';
import type { CacheLoadedMessage, ServiceWorkerOptions } from './types';
let options: ServiceWorkerOptions = { enabled: false };
export function configureServiceWorker(next: ServiceWorkerOptions): void {
options = next;
}
export function registerServiceWorker(): void {
if (typeof window === 'undefined') {
throw new Error('registerServiceWorker is browser-only; call it in an effect');
}
if (!('serviceWorker' in navigator)) return;
// Best effort: the site works the same without the worker.
void (options.enabled ? register() : unregister()).catch(() => undefined);
}
async function register(): Promise<void> {
const wasControlled = navigator.serviceWorker.controller !== null;
await loaded();
await navigator.serviceWorker.register(SERVICE_WORKER_URL, { scope: SERVICE_WORKER_SCOPE, updateViaCache: 'none' });
if (wasControlled) return;
// The page loaded before the worker controlled it, so the worker stores what the page already has.
const { active } = await navigator.serviceWorker.ready;
const message: CacheLoadedMessage = {
type: SERVICE_WORKER_CONFIG.cacheLoadedMessage,
urls: performance.getEntriesByType('resource').map((entry) => entry.name),
};
active?.postMessage(message);
}
async function unregister(): Promise<void> {
const registrations = await navigator.serviceWorker.getRegistrations();
await Promise.all(registrations.map((registration) => registration.unregister()));
const names = await caches.keys();
await Promise.all(names.filter((name) => name.startsWith(CACHE_NAME_PREFIX)).map((name) => caches.delete(name)));
}
function loaded(): Promise<void> {
if (document.readyState === 'complete') return Promise.resolve();
return new Promise((resolve) => window.addEventListener('load', () => resolve(), { once: true }));
}
```
`service-worker.ts`
```ts
// A classic script: no import or export, so writeServiceWorker can emit it as one file.
// writeServiceWorker writes SERVICE_WORKER_CONFIG above it.
declare const SERVICE_WORKER_CONFIG: import('./types').ServiceWorkerConfig;
type InstallEventWithRoutes = ExtendableEvent & {
addRoutes?: (rules: { condition: { requestMode: RequestMode }; source: 'network' }[]) => Promise<void>;
};
const worker = self as unknown as ServiceWorkerGlobalScope;
const { strategy, cacheName, cachePrefix, maxEntries, cacheLoadedMessage, paths } = SERVICE_WORKER_CONFIG;
function isStoredKind(url: URL): boolean {
if (url.origin !== worker.location.origin) return false;
const { pathname } = url;
if (pathname.startsWith(paths.static)) return pathname.endsWith('.js') || pathname.endsWith('.css');
if (pathname.startsWith(paths.fonts)) return pathname.endsWith('.woff2');
return pathname === paths.sprite;
}
function isStorable(response: Response): boolean {
return response.status === 200 && response.type === 'basic' && !response.redirected;
}
async function store(request: Request, response: Response): Promise<void> {
try {
const cache = await caches.open(cacheName);
if (new URL(request.url).pathname === paths.sprite) {
const versions = await cache.keys(request, { ignoreSearch: true });
await Promise.all(versions.map((version) => cache.delete(version)));
}
await cache.put(request, response);
const keys = await cache.keys();
await Promise.all(keys.slice(0, Math.max(0, keys.length - maxEntries)).map((key) => cache.delete(key)));
} catch {
// A full or blocked cache costs one network request next time, nothing more.
}
}
// Matching validators mean the same file. A response without one counts as changed.
function isSameFile(stored: Response, fresh: Response): boolean {
const validator = (response: Response) => response.headers.get('etag') ?? response.headers.get('last-modified');
const freshValidator = validator(fresh);
return freshValidator !== null && freshValidator === validator(stored);
}
async function fromNetwork(event: FetchEvent, stored?: Response): Promise<Response> {
const response = await fetch(event.request);
if (isStorable(response) && !(stored && isSameFile(stored, response))) {
event.waitUntil(store(event.request, response.clone()));
}
return response;
}
async function staleWhileRevalidate(event: FetchEvent): Promise<Response> {
const stored = await caches.match(event.request, { cacheName, ignoreVary: true });
const fresh = fromNetwork(event, stored);
if (!stored) return fresh;
// The check finishes after the response; when it fails, the stored copy stays.
event.waitUntil(fresh.then(() => undefined, () => undefined));
return stored;
}
async function cacheFirst(event: FetchEvent): Promise<Response> {
const stored = await caches.match(event.request, { cacheName, ignoreVary: true });
return stored ?? fromNetwork(event);
}
const respond = strategy === 'cache-first' ? cacheFirst : staleWhileRevalidate;
function toStoredKindUrl(value: unknown): URL | null {
if (typeof value !== 'string') return null;
try {
const url = new URL(value);
return isStoredKind(url) ? url : null;
} catch {
return null;
}
}
async function storeLoaded(urls: unknown[]): Promise<void> {
const wanted = urls.map(toStoredKindUrl).filter((url): url is URL => url !== null);
await Promise.all(
wanted.slice(0, maxEntries).map(async (url) => {
if (await caches.match(url.href, { cacheName, ignoreVary: true })) return;
// The page loaded it a moment ago, so the HTTP cache answers.
const response = await fetch(url.href).catch(() => null);
if (response && isStorable(response)) await store(new Request(url.href), response);
}),
);
}
worker.addEventListener('install', (event) => {
void worker.skipWaiting();
// Chromium sends navigations straight to the network, so the worker never starts only to let a page through.
// Other browsers use navigation preload (activate).
const routable = event as InstallEventWithRoutes;
if (!routable.addRoutes) return;
event.waitUntil(
routable.addRoutes([{ condition: { requestMode: 'navigate' }, source: 'network' }]).catch(() => undefined),
);
});
worker.addEventListener('activate', (event) => {
event.waitUntil(
(async () => {
await worker.registration.navigationPreload?.enable().catch(() => undefined);
const names = await caches.keys();
await Promise.all(
names.filter((name) => name.startsWith(cachePrefix) && name !== cacheName).map((name) => caches.delete(name)),
);
await worker.clients.claim();
})(),
);
});
worker.addEventListener('fetch', (event) => {
const { request } = event;
if (request.method !== 'GET') return;
if (request.mode === 'navigate') {
// Passed through, never stored.
event.respondWith(Promise.resolve(event.preloadResponse).then((preloaded?: Response) => preloaded ?? fetch(request)));
return;
}
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') return;
if (isStoredKind(new URL(request.url))) event.respondWith(respond(event));
});
worker.addEventListener('message', (event) => {
const message = event.data as Partial<import('./types').CacheLoadedMessage> | null;
if (message?.type === cacheLoadedMessage && Array.isArray(message.urls)) event.waitUntil(storeLoaded(message.urls));
});
```
- `event.waitUntil` inside `fromNetwork` runs after an `await`. The spec allows it while the event has a pending promise: the `respondWith` promise, or the background check that `staleWhileRevalidate` passes to `waitUntil` first.
- `cache.keys()` lists entries in the order they were stored, so the slice deletes the oldest. The worker writes an entry again only when its file changed, so the order stays first in, first out.
`service-worker-plugin.ts`. It runs from source when `next.config.ts` loads, so `__dirname` is the lib's folder.
```ts
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import ts from 'typescript';
import { SERVICE_WORKER_CONFIG, SERVICE_WORKER_URL } from './constants';
import type { ServiceWorkerPluginOptions } from './types';
export function writeServiceWorker({ publicDir, strategy }: ServiceWorkerPluginOptions): void {
const source = readFileSync(path.join(__dirname, 'service-worker.ts'), 'utf8');
const { outputText } = ts.transpileModule(source, {
compilerOptions: { target: ts.ScriptTarget.ES2022, removeComments: true },
});
const config = { ...SERVICE_WORKER_CONFIG, strategy: strategy ?? SERVICE_WORKER_CONFIG.strategy };
const script = `const SERVICE_WORKER_CONFIG = ${JSON.stringify(config)};\n${outputText}`;
const file = path.join(publicDir, SERVICE_WORKER_URL);
// The same bytes again would restart the dev server's file watchers for nothing.
if (existsSync(file) && readFileSync(file, 'utf8') === script) return;
writeFileSync(file, script);
}
```
## Usage
`apps/<app>/src/env/env.client.ts` declares the flag. Like every env value, it's required and has no default ([lib-env.md](lib-env.md#the-apps-env)).
```ts
// in schema
NEXT_PUBLIC_SERVICE_WORKER_ENABLED: v.pipe(v.picklist(['true', 'false']), v.transform((value) => value === 'true')),
// in runtimeEnv
NEXT_PUBLIC_SERVICE_WORKER_ENABLED: process.env.NEXT_PUBLIC_SERVICE_WORKER_ENABLED,
```
`.env.production` sets `NEXT_PUBLIC_SERVICE_WORKER_ENABLED=true`, and `.env.development` sets it to `false`.
`bootstrap.client.ts`
```ts
configureServiceWorker({ enabled: clientEnv.NEXT_PUBLIC_SERVICE_WORKER_ENABLED });
```
`platforms/<platform>/src/app/app-shell/AppShell.tsx`, beside its other startup effects:
```tsx
useEffect(() => {
registerServiceWorker();
}, []);
```
`apps/<app>/next.config.ts`. Load the plugin the way the island plugins are loaded: through jiti when the config can't resolve workspace TypeScript. The call passes no `strategy`, so the worker uses stale-while-revalidate; only a developer who explicitly chose cache first adds `strategy: 'cache-first'`.
```ts
import path from 'node:path';
import { SERVICE_WORKER_HEADERS, SERVICE_WORKER_URL, writeServiceWorker } from '@project/libs/pwa/plugin';
writeServiceWorker({ publicDir: path.join(__dirname, 'public') });
// inside headers()
{
source: SERVICE_WORKER_URL,
headers: Object.entries(SERVICE_WORKER_HEADERS).map(([key, value]) => ({ key, value })),
},
```
`apps/<app>/src/configs/pwa.ts`. The colors are the light theme's `--surface-page` and `--action-primary` values from island `theme.css`.
```ts
import type { MetadataRoute } from 'next';
export const PWA_MANIFEST = {
id: '/',
start_url: '/',
scope: '/',
display: 'standalone',
background_color: '#f4f6fa',
theme_color: '#2563eb',
icons: [
{ src: '/pwa/icon-192.png', sizes: '192x192', type: 'image/png' },
{ src: '/pwa/icon-512.png', sizes: '512x512', type: 'image/png' },
{ src: '/pwa/icon-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
],
} satisfies MetadataRoute.Manifest;
```
`apps/<app>/src/app/manifest.ts`. `getServerI18n` and `DEFAULT_LOCALE` stand for the app's per-request i18next setup in `src/i18n/`; match their real names.
```ts
import type { MetadataRoute } from 'next';
import { PWA_MANIFEST } from '../configs';
import { DEFAULT_LOCALE, getServerI18n } from '../i18n';
export const dynamic = 'force-dynamic';
export default async function manifest(): Promise<MetadataRoute.Manifest> {
// Browsers fetch the manifest without cookies, so it uses the default locale.
const i18n = await getServerI18n(DEFAULT_LOCALE);
return {
...PWA_MANIFEST,
name: i18n.t('app:pwa.name'),
short_name: i18n.t('app:pwa.short-name'),
description: i18n.t('app:pwa.description'),
lang: DEFAULT_LOCALE,
dir: i18n.dir(DEFAULT_LOCALE),
};
}
```
## Acceptance checklist
For building or changing the lib:
```
[ ] Once the worker is active, every /_next/static/ JS and CSS file, /fonts/*.woff2 file, and /icons/symbol-defs.svg?v=<N> the page requests is served from the cache without waiting for the network
[ ] By default (no strategy passed), each served copy starts one background check; a response with the same ETag or Last-Modified isn't written, a changed one replaces the copy, and a failed check keeps it
[ ] With strategy 'cache-first', a stored file is served with no network request at all
[ ] Nothing else is stored: pages, RSC payloads, API responses, images, /_next/static/media/*, other SVGs, cross-origin files, non-GET requests, and partial, redirected, or error responses
[ ] Storing symbol-defs.svg?v=2 deletes symbol-defs.svg?v=1
[ ] The cache never keeps more than maxEntries entries, and the oldest go first
[ ] Navigations always reach the network: Chromium sends them past the worker, other browsers get the navigation preload response, and none is stored
[ ] After the first registration, the matching files the page already loaded are stored from the HTTP cache, with no new network requests
[ ] A changed sw.js activates at once, deletes every pwa- cache except the current one, and controls the open pages
[ ] With enabled: false, the next page load unregisters the worker and deletes every pwa- cache
[ ] registerServiceWorker throws the browser-only error on the server; configureServiceWorker doesn't
[ ] Without service worker support, or when registration fails, the site works and shows no error
[ ] /sw.js is served with SERVICE_WORKER_HEADERS and isn't redirected by proxy.ts; writeServiceWorker rewrites it only when its content changes
[ ] An Nx cache hit on the app's build restores public/sw.js
[ ] service-worker.ts type-checks with the WebWorker lib and has no import, export, or importScripts
```

View File

@ -1,6 +1,6 @@
# Page example: caches, page, and parts
A full page for [b2c-b2b.md](b2c-b2b.md): device detection, caches, a server page loader, the page entrypoint with its JSON-LD, streamed parts, and query hydration. Read it when you add a new page, or a part that reads server data in a way the repo doesn't have yet. Otherwise copy the shape of an existing page.
A full page for [b2c-b2b.md](b2c-b2b.md): device detection, caches, a server page loader, the page entrypoint, streamed parts, and query hydration. Read it when you add a new page, or a part that reads server data in a way the repo doesn't have yet. Otherwise copy the shape of an existing page.
`platforms/<platform>/src/shared/utils/get-device.ts`
@ -45,16 +45,14 @@ export { getProduct, getProductReviews, getRelatedProducts } from './products';
```ts
import 'server-only';
export { buildProductPageJsonLd } from './app/json-ld/server';
export { getProduct, getProductReviews, getRelatedProducts } from './features/catalog/caches/server';
export { getDevice } from './shared/utils/get-device';
```
`apps/<app>/src/app/(shop)/product/[id]/page.tsx`. `generateMetadata` and the page both call `getProduct(id)`, and the cache sends one request. The page renders its JSON-LD from the same product, beside the template and outside every `<Suspense>`; `buildProductPageJsonLd` is in [lib-json-ld.md](lib-json-ld.md#usage). A page whose main read can answer 404 or 403 reads through `readOnServer` instead, as the seller page in [error-handling-code.md](error-handling-code.md) does, and renders JSON-LD only for an `ok` read.
`apps/<app>/src/app/(shop)/product/[id]/page.tsx`. `generateMetadata` and the page both call `getProduct(id)`, and the cache sends one request. A page whose main read can answer 404 or 403 reads through `readOnServer` instead, as the seller page in [error-handling-code.md](error-handling-code.md) does.
```tsx
import { JsonLd } from '@project/island/primitives/json-ld/server';
import { buildProductPageJsonLd, getDevice, getProduct } from '@project/<platform>/server';
import { getDevice, getProduct } from '@project/<platform>/server';
import type { Metadata } from 'next';
import { ProductDesktop } from './templates/product-desktop';
import { ProductMobile } from './templates/product-mobile';
@ -70,12 +68,7 @@ export async function generateMetadata({ params }: ProductPageProps): Promise<Me
export default async function ProductPage({ params }: ProductPageProps) {
const { id } = await params;
const [device, product] = await Promise.all([getDevice(), getProduct(id)]);
return (
<>
<JsonLd data={buildProductPageJsonLd(product)} />
{device === 'mobile' ? <ProductMobile product={product} /> : <ProductDesktop product={product} />}
</>
);
return device === 'mobile' ? <ProductMobile product={product} /> : <ProductDesktop product={product} />;
}
```

View File

@ -38,7 +38,6 @@ apps/<app>/src/
├── app/ # Next.js App Router
│ ├── global-error.tsx # EB-W: replaces the root layout; own <html> and <body>
│ ├── not-found.tsx
│ ├── manifest.ts # web app manifest; force-dynamic, default locale (see lib-pwa.md)
│ └── (auth)/
│ ├── layout.tsx
│ ├── loading.tsx
@ -52,9 +51,8 @@ apps/<app>/src/
│ ├── app.css # Tailwind entry; imports island.css
│ └── index.ts
├── configs/
│ ├── seo.ts # metadata defaults and the business facts for JSON-LD (see lib-json-ld.md)
│ ├── seo.ts
│ ├── react-query.ts
│ ├── pwa.ts # the manifest's fixed fields: id, start_url, display, colors, icons
│ └── index.ts
├── constants/
│ ├── auth.ts # e.g. the OTP re-send timeout
@ -67,7 +65,6 @@ apps/<app>/src/
```
- Pages are thin entrypoints. A page picks the mobile or the desktop template on the server, so no component branches on viewport size.
- `apps/<app>/public/` holds the committed manifest icons in `pwa/` and three generated outputs that git ignores: `fonts/`, `icons/symbol-defs.svg`, and `sw.js` ([lib-pwa.md](lib-pwa.md)).
- Every route level may keep its own `organisms/` and `templates/`, shaped like island organisms. They are not routable because they contain no `page.tsx`. They hold only what this route uses; UI that knows a domain and serves several routes or apps lives in the platform's `screens/`.
- `styles/`, `configs/`, and `constants/` grow as needed; each keeps an `index.ts`.
- The app holds no features, stores, or business logic; those live in `platforms/<platform>/`. Apps never import each other.
@ -90,10 +87,6 @@ platforms/<platform>/src/
│ │ ├── error-fallback/ # ErrorFallback: what every boundary renders
│ │ ├── status-empty-state/ # the not-found and no-access empty states
│ │ └── read-on-server/ # readOnServer; server-only, exported through server.ts
│ ├── json-ld/ # one JSON-LD builder per page type; server-only, see lib-json-ld.md
│ │ ├── <page-type>-json-ld.ts
│ │ ├── constants.ts
│ │ └── server.ts # the module's entry; no index.ts
│ ├── navigation/
│ │ ├── navigation.ts # typed route paths and navigation menus
│ │ ├── constants.ts
@ -127,8 +120,6 @@ platforms/<platform>/src/
- It is UI: it may import `features/`, `stores/`, `shared/`, the rest of `app/`, island, and integrations. Nothing in `features/`, `stores/`, or `shared/` imports it.
- A module that reads caches is server-only, like `read-on-server/`: its entry is `server.ts`, and the platform's `server.ts` re-exports it.
`json-ld/` holds what each indexable page type tells search engines: pure functions such as `buildProductPageJsonLd(product)`, which turn a feature's `*Payload` and the navigation paths into one graph with the json-ld lib's builders. It sits in `app/` because it needs `navigation/`, which `features/` can't import. It's server-only, and pages render its graph with island's `JsonLd` ([lib-json-ld.md](lib-json-ld.md)).
## Feature anatomy
```
@ -215,7 +206,7 @@ packages/island/src/
├── organisms/
│ └── <component-name>/ # component module + private components/ and hooks/
├── templates/ # like organisms
├── primitives/ # non-visual structural pieces, e.g. portal, error-boundary, json-ld; like organisms
├── primitives/ # non-visual structural pieces, e.g. portal, error-boundary; like organisms
├── tools/
│ └── <tool-name>/ # e.g. cn, cvx, icon-sprite-plugin, font-copy-plugin, icon-name-extraction
│ ├── <tool-name>.ts or <tool-name>.tsx
@ -294,7 +285,7 @@ A piece that knows a domain but is smaller than an organism, such as a price lin
```
packages/libs/src/<lib-name>/ # e.g. http, env, error-handler, cookie, local-storage,
├── <lib-name>.ts # pwa, json-ld, custom prototypes, regex, event-emitter
├── <lib-name>.ts # custom prototypes, regex, event-emitter
├── types.ts
├── constants.ts
└── index.ts
@ -328,10 +319,8 @@ Fundamental libs have full specs:
| `env` | `createClientEnv`; `createServerEnv` (server) | Validating the app's env: public variables on both sides, server variables on the server only | [lib-env.md](lib-env.md) |
| `cookie` | `cookie` | Browser cookies for small values the server needs (locale, theme); never tokens | [lib-cookie.md](lib-cookie.md) |
| `local-storage` | `storage` | Prefixed, client-only, non-critical data and persisted zustand stores; never tokens or personal data | [lib-local-storage.md](lib-local-storage.md) |
| `pwa` | `configureServiceWorker`, `registerServiceWorker`; `writeServiceWorker` (plugin) | The web app manifest's rules and one service worker per app, which stores only JS, CSS, fonts, and the icon sprite | [lib-pwa.md](lib-pwa.md) |
| `json-ld` | `configureJsonLd`, `buildGraph`, and `build*` per schema.org type (server) | The schema.org JSON-LD each indexable page renders: the business, the website, products and their offers, policies, breadcrumbs, and stores | [lib-json-ld.md](lib-json-ld.md) |
`cookie` and `storage` are browser-only and export nothing from `server.ts`; `error-handler` runs on both sides and exports nothing from it either. `http` exports `configureServerHttp` from `server.ts`. `env` exports `createServerEnv` from its own `env/server.ts`, which the project's `server.ts` re-exports. `pwa` exports nothing from `server.ts`: its page side is browser-only, and its build plugin sits on its own `pwa/plugin` subpath. `json-ld` is server-only: it has only `json-ld/server.ts`, which the project's `server.ts` re-exports.
`cookie` and `storage` are browser-only and export nothing from `server.ts`; `error-handler` runs on both sides and exports nothing from it either. `http` exports `configureServerHttp` from `server.ts`. `env` exports `createServerEnv` from its own `env/server.ts`, which the project's `server.ts` re-exports.
## Env flow
@ -403,4 +392,3 @@ Workspaces that use `tsconfig.base.json` path aliases instead map `"@project/isl
- `sideEffects`: pure TypeScript modules have none. List every file that must run on import, such as CSS and custom prototype extensions; otherwise bundlers drop it.
- The root `index.ts` re-exports every module by name, so `@project/island` and `@project/island/atoms/button` expose the same symbols.
- A module with its own `server.ts` also gets a `<module>/server` subpath, for example `"./env/server": "./src/env/server.ts"` in libs. The project's `server.ts` re-exports it, so `@project/libs/server` and `@project/libs/env/server` expose the same symbols.
- A build-only module gets a `<module>/plugin` subpath, for example `"./pwa/plugin": "./src/pwa/plugin.ts"` in libs. Only build configs such as `next.config.ts` import it, and no root entry re-exports it.

View File

@ -103,7 +103,7 @@ The budgets these patterns protect are in [b2c-b2b.md](b2c-b2b.md#targets). Reco
| Route-based splitting | Automatic | The App Router splits each route segment. |
| Bundle splitting | Automatic | Steer it with small client boundaries and dynamic imports rather than the bundler's chunk settings, and check each route against its budget. |
| Tree shaking | Always | Use named re-exports without `export *`, subpath imports, and `sideEffects` in every package ([project-structure.md](project-structure.md#exports-and-tree-shaking)). |
| PRPL | Built in | Preload critical files (next row). Render the route with the streamed server render. Pre-cache through prefetch, and for repeat visits through the pwa lib's service worker, which keeps JS, CSS, fonts, and the icon sprite and never pages ([lib-pwa.md](lib-pwa.md)). Lazy-load the rest with route splitting and dynamic imports. |
| PRPL | Built in | Preload critical files (next row). Render the route with the streamed server render. Pre-cache only through prefetch, because a service worker is outside the stack and needs approval. Lazy-load the rest with route splitting and dynamic imports. |
| Preload | LCP image, critical font | Preload what [b2c-b2b.md](ui-rules.md#images-fonts-and-css) lists, and use React 19's resource functions for other origins and late files (notes below). |
| Prefetch | `next/link` default | Keep `next/link`'s default prefetch (notes below). |
| Loading sequence | Always | Load the stylesheet, the critical font, and the LCP image first, then first-party JavaScript, then third parties after hydration. |

View File

@ -30,12 +30,9 @@ const immutable = [{ key: 'Cache-Control', value: 'public, max-age=31536000, imm
{ source: '/icons/:path*', headers: immutable },
```
- The pwa lib's service worker keeps them too, by exact URL with the `?v=` included ([lib-pwa.md](lib-pwa.md)). A new sprite version reaches each visitor with their next request, and the worker deletes the old one. A font changed under its old name reaches each visitor one visit late under the default stale-while-revalidate strategy, and long after the change when the developer chose cache first, so a changed font still always gets a new name.
## SEO and i18n
- Build `generateMetadata` from `configs/seo.ts`: title, description, canonical URL, `hreflang` alternates, and Open Graph. Provide `sitemap.ts`, `robots.ts`, and the web app manifest's `manifest.ts` ([lib-pwa.md](lib-pwa.md#web-app-manifest)).
- Every indexable page renders its schema.org JSON-LD with the json-ld lib ([lib-json-ld.md](lib-json-ld.md)): the business and the website on the home page, the product with its offer, rating, and breadcrumb on product pages, the breadcrumb on listing pages, and the store-wide return and shipping policies on their own pages. It says only what the page shows: the same name, price, availability, rating, and trail, in the page's language, with machine values (Latin digits, ISO 8601 dates, ISO 4217 currency).
- Build `generateMetadata` from `configs/seo.ts`: title, description, canonical URL, `hreflang` alternates, and Open Graph. Add JSON-LD for products, breadcrumbs, and the organization. Provide `sitemap.ts` and `robots.ts`.
- Server Components translate with a per-request i18next instance from `apps/<app>/src/i18n/`; react-i18next hooks run only in client components. Set `lang` and `dir` on `<html>` from the locale.
## Copy
@ -80,6 +77,3 @@ Refetches, state updates, and re-renders must never make the UI disappear and re
- Tab order follows reading order, Enter submits, and Esc closes. Set sensible default focus and keep primary actions in consistent places.
- Preserve context: filters, sort, page, and scroll position survive navigating to a detail page and back. Filters, sort, and page live in the URL, so views are shareable and survive a refresh.
- Respect `prefers-reduced-motion` and `prefers-color-scheme`.
- Every scroll the page starts is smooth: anchor jumps, `scrollIntoView`, and `scrollTo` animate instead of jumping, so the user sees where they went. island's `island.css` sets `scroll-behavior: smooth` on every element and turns it off under `prefers-reduced-motion` ([code-patterns.md](code-patterns.md#tokens-and-tailwind-wiring)). Code that scrolls never passes `behavior`, so the CSS and the user's motion setting decide.
- Every root layout's `<html>` has `data-scroll-behavior="smooth"`. Without it, Next.js 16 animates the jump to the top on every route change.
- A scroll container that code holds in place, such as a virtualized list or a chat log pinned to its end, adds `scroll-auto`, or every position fix animates.

View File

@ -1,33 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { DesktopHeader, DesktopPageTitle } from '@lumina/market/app/navigation';
import { CheckoutCreatorSkeleton } from '@lumina/market/app/screens/(flow)/checkout/[username]/organisms/checkout-creator';
import { CheckoutSkeleton } from '@lumina/market/app/screens/(flow)/checkout/[username]/organisms/checkout-panel';
import { i18n } from '../../../../i18n';
/** Checkout before the page arrives, block for block, in its 480 column. */
export default function Loading() {
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-bg-page">
<DesktopHeader />
<FlexBox
tag="main"
justifyContent="justify-center"
className="px-8 py-10"
>
<FlexBox
direction="flex-col"
gap="gap-4"
className="w-full max-w-checkout"
>
<DesktopPageTitle title={i18n.t('payment:checkout.title')} />
<CheckoutSkeleton
layout="desktop"
creator={<CheckoutCreatorSkeleton />}
label={i18n.t('payment:checkout.loading')}
/>
</FlexBox>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,35 +0,0 @@
import { ROUTES } from '@lumina/market/app/navigation';
import { getChannel, readOnServer } from '@lumina/market/server';
import { toChannelUsername } from '@lumina/market/shared/utils';
import type { Metadata } from 'next';
import { notFound, permanentRedirect, redirect } from 'next/navigation';
import { i18n } from '../../../../i18n';
import { CheckoutTemplate } from './templates/checkout-template';
type CheckoutPageProps = { params: Promise<{ username: string }> };
export function generateMetadata(): Metadata {
return {
title: i18n.t('payment:checkout.title'),
robots: { index: false },
};
}
/**
* Checkout for a creator's channel (U9), reached only from its «اشتراک». The server renders the
* same page for everyone: the bar and who is being paid; the investor's own checkout loads in the
* browser. Another spelling of the username redirects to the stored one; a suspended channel
* sends the visitor to the channel, which says it is unavailable.
*/
export default async function CheckoutPage({ params }: CheckoutPageProps) {
const segment = (await params).username;
const username = toChannelUsername(segment);
if (!username) notFound();
if (username !== segment) permanentRedirect(ROUTES.checkout(username));
const channel = await readOnServer(() => getChannel(username));
if (channel.status !== 'ok') notFound();
if (channel.data.suspended) redirect(ROUTES.channel(username));
return <CheckoutTemplate channel={channel.data} />;
}

View File

@ -1,56 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import {
DesktopHeader,
DesktopPageTitle,
ROUTES,
} from '@lumina/market/app/navigation';
import { CheckoutCreator } from '@lumina/market/app/screens/(flow)/checkout/[username]/organisms/checkout-creator';
import { CheckoutPanel } from '@lumina/market/app/screens/(flow)/checkout/[username]/organisms/checkout-panel';
import { i18n } from '../../../../../../i18n';
import type { CheckoutTemplateProps } from './types';
/**
* Checkout on desktop (U9 ۹.۱): one centred column of 480 under the header, back beside the
* title, and the pay block stuck to the bottom of the window while the tiers scroll.
*/
export function CheckoutTemplate({ channel }: CheckoutTemplateProps) {
const t = i18n.getFixedT(null, 'payment');
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-bg-page">
<DesktopHeader />
<FlexBox
tag="main"
justifyContent="justify-center"
className="px-8 py-10"
>
<FlexBox
direction="flex-col"
gap="gap-4"
className="w-full max-w-checkout"
>
<DesktopPageTitle title={t('checkout.title')} />
<PartBoundary
name="checkout"
description={t('checkout.error')}
framed
>
<CheckoutPanel
creatorId={channel.creatorId}
channelHref={ROUTES.channel(channel.username)}
layout="desktop"
creator={
<CheckoutCreator
creator={channel}
labels={{ verified: t('checkout.verified') }}
/>
}
/>
</PartBoundary>
</FlexBox>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,2 +0,0 @@
export { CheckoutTemplate } from './CheckoutTemplate';
export type { CheckoutTemplateProps } from './types';

View File

@ -1,3 +0,0 @@
import type { PublicCreatorPayload } from '@lumina/market/features/channel';
export type CheckoutTemplateProps = { channel: PublicCreatorPayload };

View File

@ -1,26 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { DesktopHeader } from '@lumina/market/app/navigation';
import { PaymentResultSkeleton } from '@lumina/market/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result';
import { i18n } from '../../../../../i18n';
/** The result before the page arrives, in its 480 column. */
export default function Loading() {
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-bg-page">
<DesktopHeader />
<FlexBox
tag="main"
justifyContent="justify-center"
className="px-8 py-10"
>
<FlexBox direction="flex-col" className="w-full max-w-checkout">
<PaymentResultSkeleton
layout="desktop"
label={i18n.t('payment:result.loading')}
/>
</FlexBox>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,56 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { DesktopHeader } from '@lumina/market/app/navigation';
import {
PaymentResult,
PaymentResultSkeleton,
} from '@lumina/market/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result';
import type { Metadata } from 'next';
import { i18n } from '../../../../../i18n';
type PaymentResultPageProps = { params: Promise<{ paymentId: string }> };
export function generateMetadata(): Metadata {
return {
title: i18n.t('payment:result.meta-title'),
robots: { index: false },
};
}
/** «نتیجه پرداخت» on desktop (U10 ۹.۴, ۹.۵): one panel in the 480 column under the header. */
export default async function PaymentResultPage({
params,
}: PaymentResultPageProps) {
const { paymentId } = await params;
const skeleton = (
<PaymentResultSkeleton
layout="desktop"
label={i18n.t('payment:result.loading')}
/>
);
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-bg-page">
<DesktopHeader />
<FlexBox
tag="main"
justifyContent="justify-center"
className="px-8 py-10"
>
<FlexBox direction="flex-col" className="w-full max-w-checkout">
<PartBoundary
name="payment-result"
description={i18n.t('payment:result.error')}
framed
>
<AuthGuard role="investor" fallback={skeleton}>
<PaymentResult paymentId={paymentId} layout="desktop" />
</AuthGuard>
</PartBoundary>
</FlexBox>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,16 +0,0 @@
import { PaymentConfirming } from '@lumina/market/app/screens/(flow)/payment/return/organisms/payment-confirming';
import { i18n } from '../../../../i18n';
/** The confirming screen itself: nothing else may show on the way back from the bank. */
export default function Loading() {
return (
<PaymentConfirming
layout="desktop"
labels={{
title: i18n.t('payment:confirm.title'),
description: i18n.t('payment:confirm.description'),
}}
/>
);
}

View File

@ -1,46 +0,0 @@
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import { PaymentConfirming } from '@lumina/market/app/screens/(flow)/payment/return/organisms/payment-confirming';
import { PaymentReturn } from '@lumina/market/app/screens/(flow)/payment/return/organisms/payment-return';
import type { Metadata } from 'next';
import { i18n } from '../../../../i18n';
type PaymentReturnPageProps = {
searchParams: Promise<{ paymentId?: string | string[] }>;
};
export function generateMetadata(): Metadata {
return {
title: i18n.t('payment:confirm.meta-title'),
robots: { index: false },
};
}
/**
* Back from the bank (U10 ۱.۱): «در حال تأیید پرداخت...» while the payment settles, then its
* result page in this one's place. The same screen before the session is known.
*/
export default async function PaymentReturnPage({
searchParams,
}: PaymentReturnPageProps) {
const raw = (await searchParams).paymentId;
const paymentId = typeof raw === 'string' && raw ? raw : null;
const confirming = (
<PaymentConfirming
layout="desktop"
labels={{
title: i18n.t('payment:confirm.title'),
description: i18n.t('payment:confirm.description'),
}}
/>
);
return (
<AuthGuard role="investor" fallback={confirming}>
<PartBoundary name="payment-return">
<PaymentReturn paymentId={paymentId}>{confirming}</PaymentReturn>
</PartBoundary>
</AuthGuard>
);
}

View File

@ -1,19 +0,0 @@
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
import { i18n } from '../../../../i18n';
/** The terms before they arrive: a few paragraphs' worth of lines. */
export default function Loading() {
return (
<SkeletonRegion
delayed
label={i18n.t('terms:meta-title')}
className="mx-auto w-full max-w-content p-4"
>
<Skeleton width="40%" height="1.25rem" className="mb-3" />
<Skeleton lines={4} />
<Skeleton width="35%" height="1.25rem" className="mt-6 mb-3" />
<Skeleton lines={5} />
</SkeletonRegion>
);
}

View File

@ -1,57 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Card } from '@lumina/island/molecules/card';
import { DesktopHeader, DesktopPageTitle } from '@lumina/market/app/navigation';
import {
SubscriptionTerms,
subscriptionTermsLabels,
} from '@lumina/market/app/screens/(flow)/terms/subscription/organisms/subscription-terms';
import { supportChatUrls } from '@lumina/market/app/screens/organisms/support-entry';
import { getEnv } from '@lumina/market/env';
import type { Metadata } from 'next';
import { i18n } from '../../../../i18n';
export function generateMetadata(): Metadata {
return {
title: i18n.t('terms:meta-title'),
description: i18n.t('terms:meta-description'),
};
}
/**
* «شرایط اشتراک» on desktop (S5 ۲.۱): the text in a panel of the 640 column under the header,
* about 75 characters a line, with back beside the title.
*/
export default function SubscriptionTermsPage() {
const labels = subscriptionTermsLabels(
i18n.getFixedT(null, 'terms'),
i18n.getFixedT(null, 'auth'),
getEnv().supportHours,
);
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-bg-page">
<DesktopHeader />
<FlexBox
tag="main"
justifyContent="justify-center"
className="px-8 py-10"
>
<FlexBox
direction="flex-col"
gap="gap-4"
className="w-full max-w-content"
>
<DesktopPageTitle title={labels.title} />
<Card padding="lg">
<SubscriptionTerms
layout="desktop"
chats={supportChatUrls()}
labels={labels}
/>
</Card>
</FlexBox>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,15 +0,0 @@
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { i18n } from '../../../../../i18n';
/** The list before it arrives, card for card; the layout keeps the bar and the tabs. */
export default function Loading() {
return (
<SkeletonPreset
preset="list"
cards="lg"
delayed
label={i18n.t('dashboard:subscriptions.loading')}
/>
);
}

View File

@ -1,43 +0,0 @@
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { SubscriptionList } from '@lumina/market/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list';
import type { Metadata } from 'next';
import { Suspense } from 'react';
import { i18n } from '../../../../../i18n';
export function generateMetadata(): Metadata {
return {
title: i18n.t('dashboard:subscriptions.meta-title'),
robots: { index: false },
};
}
/**
* داشبورد › اشتراک‌ها (U2, U11): the investor's own subscriptions, in the browser only, behind
* cards of the same size. A failed read shows in place of the list; the tabs stay (U2 ۳.۴).
*/
export default function SubscriptionsPage() {
const skeleton = (
<SkeletonPreset
preset="list"
cards="lg"
label={i18n.t('dashboard:subscriptions.loading')}
/>
);
return (
<PartBoundary
name="subscription-list"
description={i18n.t('dashboard:subscriptions.error')}
framed
>
<AuthGuard role="investor" fallback={skeleton}>
<Suspense fallback={skeleton}>
<SubscriptionList layout="desktop" />
</Suspense>
</AuthGuard>
</PartBoundary>
);
}

View File

@ -1,16 +0,0 @@
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { i18n } from '../../../../../i18n';
/** The payments before they arrive, row for row; the layout keeps the bar and the tabs. */
export default function Loading() {
return (
<SkeletonPreset
preset="list"
cards="lg"
avatar={false}
delayed
label={i18n.t('dashboard:transactions.loading')}
/>
);
}

View File

@ -1,44 +0,0 @@
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { TransactionList } from '@lumina/market/app/screens/(main)/dashboard/transactions/organisms/transaction-list';
import type { Metadata } from 'next';
import { Suspense } from 'react';
import { i18n } from '../../../../../i18n';
export function generateMetadata(): Metadata {
return {
title: i18n.t('dashboard:transactions.meta-title'),
robots: { index: false },
};
}
/**
* داشبورد › تراکنش‌ها (U4): the investor's own payments, in the browser only, behind rows of the
* same size. A failed read shows in place of the list, without the chips; the tabs stay (U4 ۴.۳).
*/
export default function TransactionsPage() {
const skeleton = (
<SkeletonPreset
preset="list"
cards="lg"
avatar={false}
label={i18n.t('dashboard:transactions.loading')}
/>
);
return (
<PartBoundary
name="transaction-list"
description={i18n.t('dashboard:transactions.error')}
framed
>
<AuthGuard role="investor" fallback={skeleton}>
<Suspense fallback={skeleton}>
<TransactionList layout="desktop" />
</Suspense>
</AuthGuard>
</PartBoundary>
);
}

View File

@ -1,26 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { DesktopPageTitle } from '@lumina/market/app/navigation';
import { i18n } from '../../../i18n';
/** The centre before it arrives, in its column. */
export default function Loading() {
return (
<FlexBox tag="main" justifyContent="justify-center" className="px-8 py-10">
<FlexBox
direction="flex-col"
gap="gap-4"
className="w-full max-w-content"
>
<DesktopPageTitle title={i18n.t('notifications:title')} />
<SkeletonPreset
preset="list"
avatar={false}
delayed
label={i18n.t('notifications:loading')}
/>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,54 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { DesktopPageTitle } from '@lumina/market/app/navigation';
import { NotificationCentre } from '@lumina/market/app/screens/(main)/notifications/organisms/notification-centre';
import type { Metadata } from 'next';
import { Suspense } from 'react';
import { i18n } from '../../../i18n';
export function generateMetadata(): Metadata {
return {
title: i18n.t('notifications:title'),
robots: { index: false },
};
}
/**
* اعلان‌ها at its own address on desktop, such as a link opened from elsewhere: the same centre the
* header's bell opens as a panel (U5 ۴.۱), in the 640 column.
*/
export default function NotificationsPage() {
const skeleton = (
<SkeletonPreset
preset="list"
avatar={false}
label={i18n.t('notifications:loading')}
/>
);
return (
<FlexBox tag="main" justifyContent="justify-center" className="px-8 py-10">
<FlexBox
direction="flex-col"
gap="gap-4"
className="w-full max-w-content"
>
<DesktopPageTitle title={i18n.t('notifications:title')} />
<PartBoundary
name="notification-centre"
description={i18n.t('notifications:error')}
framed
>
<AuthGuard fallback={skeleton}>
<Suspense fallback={skeleton}>
<NotificationCentre layout="page" supportPlacement="popover" />
</Suspense>
</AuthGuard>
</PartBoundary>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,22 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { MobileTopBar } from '@lumina/market/app/navigation';
import { CheckoutCreatorSkeleton } from '@lumina/market/app/screens/(flow)/checkout/[username]/organisms/checkout-creator';
import { CheckoutSkeleton } from '@lumina/market/app/screens/(flow)/checkout/[username]/organisms/checkout-panel';
import { i18n } from '../../../../i18n';
/** Checkout before the page arrives, block for block, under its bar. */
export default function Loading() {
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-bg-page">
<MobileTopBar title={i18n.t('payment:checkout.title')} />
<FlexBox tag="main" direction="flex-col" className="flex-1">
<CheckoutSkeleton
layout="mobile"
creator={<CheckoutCreatorSkeleton />}
label={i18n.t('payment:checkout.loading')}
/>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,35 +0,0 @@
import { ROUTES } from '@lumina/market/app/navigation';
import { getChannel, readOnServer } from '@lumina/market/server';
import { toChannelUsername } from '@lumina/market/shared/utils';
import type { Metadata } from 'next';
import { notFound, permanentRedirect, redirect } from 'next/navigation';
import { i18n } from '../../../../i18n';
import { CheckoutTemplate } from './templates/checkout-template';
type CheckoutPageProps = { params: Promise<{ username: string }> };
export function generateMetadata(): Metadata {
return {
title: i18n.t('payment:checkout.title'),
robots: { index: false },
};
}
/**
* Checkout for a creator's channel (U9), reached only from its «اشتراک». The server renders the
* same page for everyone: the bar and who is being paid; the investor's own checkout loads in the
* browser. Another spelling of the username redirects to the stored one; a suspended channel
* sends the visitor to the channel, which says it is unavailable.
*/
export default async function CheckoutPage({ params }: CheckoutPageProps) {
const segment = (await params).username;
const username = toChannelUsername(segment);
if (!username) notFound();
if (username !== segment) permanentRedirect(ROUTES.checkout(username));
const channel = await readOnServer(() => getChannel(username));
if (channel.status !== 'ok') notFound();
if (channel.data.suspended) redirect(ROUTES.channel(username));
return <CheckoutTemplate channel={channel.data} />;
}

View File

@ -1,37 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import { MobileTopBar, ROUTES } from '@lumina/market/app/navigation';
import { CheckoutCreator } from '@lumina/market/app/screens/(flow)/checkout/[username]/organisms/checkout-creator';
import { CheckoutPanel } from '@lumina/market/app/screens/(flow)/checkout/[username]/organisms/checkout-panel';
import { i18n } from '../../../../../../i18n';
import type { CheckoutTemplateProps } from './types';
/**
* Checkout on mobile: a task page pushed from the channel, back · «خرید اشتراک» · support and no
* bottom nav (U9 §۲), with the pay block pinned to the bottom of the screen.
*/
export function CheckoutTemplate({ channel }: CheckoutTemplateProps) {
const t = i18n.getFixedT(null, 'payment');
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-bg-page">
<MobileTopBar title={t('checkout.title')} />
<FlexBox tag="main" direction="flex-col" className="flex-1">
<PartBoundary name="checkout" description={t('checkout.error')}>
<CheckoutPanel
creatorId={channel.creatorId}
channelHref={ROUTES.channel(channel.username)}
layout="mobile"
creator={
<CheckoutCreator
creator={channel}
labels={{ verified: t('checkout.verified') }}
/>
}
/>
</PartBoundary>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,2 +0,0 @@
export { CheckoutTemplate } from './CheckoutTemplate';
export type { CheckoutTemplateProps } from './types';

View File

@ -1,3 +0,0 @@
import type { PublicCreatorPayload } from '@lumina/market/features/channel';
export type CheckoutTemplateProps = { channel: PublicCreatorPayload };

View File

@ -1,20 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { MobileTopBar } from '@lumina/market/app/navigation';
import { PaymentResultSkeleton } from '@lumina/market/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result';
import { i18n } from '../../../../../i18n';
/** The result before the page arrives, under its bar. */
export default function Loading() {
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-surface">
<MobileTopBar title={i18n.t('payment:result.title')} back={false} />
<FlexBox tag="main" direction="flex-col" className="flex-1">
<PaymentResultSkeleton
layout="mobile"
label={i18n.t('payment:result.loading')}
/>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,52 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { MobileTopBar } from '@lumina/market/app/navigation';
import {
PaymentResult,
PaymentResultSkeleton,
} from '@lumina/market/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result';
import type { Metadata } from 'next';
import { i18n } from '../../../../../i18n';
type PaymentResultPageProps = { params: Promise<{ paymentId: string }> };
export function generateMetadata(): Metadata {
return {
title: i18n.t('payment:result.meta-title'),
robots: { index: false },
};
}
/**
* «نتیجه پرداخت» (U10 ۹.۱–۹.۳): the name and support with no back, since the bank is behind it,
* the investor's own payment in the browser, and its two ways on pinned to the bottom.
*/
export default async function PaymentResultPage({
params,
}: PaymentResultPageProps) {
const { paymentId } = await params;
const skeleton = (
<PaymentResultSkeleton
layout="mobile"
label={i18n.t('payment:result.loading')}
/>
);
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-surface">
<MobileTopBar title={i18n.t('payment:result.title')} back={false} />
<FlexBox tag="main" direction="flex-col" className="flex-1">
<PartBoundary
name="payment-result"
description={i18n.t('payment:result.error')}
>
<AuthGuard role="investor" fallback={skeleton}>
<PaymentResult paymentId={paymentId} layout="mobile" />
</AuthGuard>
</PartBoundary>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,16 +0,0 @@
import { PaymentConfirming } from '@lumina/market/app/screens/(flow)/payment/return/organisms/payment-confirming';
import { i18n } from '../../../../i18n';
/** The confirming screen itself: nothing else may show on the way back from the bank. */
export default function Loading() {
return (
<PaymentConfirming
layout="mobile"
labels={{
title: i18n.t('payment:confirm.title'),
description: i18n.t('payment:confirm.description'),
}}
/>
);
}

View File

@ -1,46 +0,0 @@
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import { PaymentConfirming } from '@lumina/market/app/screens/(flow)/payment/return/organisms/payment-confirming';
import { PaymentReturn } from '@lumina/market/app/screens/(flow)/payment/return/organisms/payment-return';
import type { Metadata } from 'next';
import { i18n } from '../../../../i18n';
type PaymentReturnPageProps = {
searchParams: Promise<{ paymentId?: string | string[] }>;
};
export function generateMetadata(): Metadata {
return {
title: i18n.t('payment:confirm.meta-title'),
robots: { index: false },
};
}
/**
* Back from the bank (U10 ۱.۱): «در حال تأیید پرداخت...» while the payment settles, then its
* result page in this one's place. The same screen before the session is known.
*/
export default async function PaymentReturnPage({
searchParams,
}: PaymentReturnPageProps) {
const raw = (await searchParams).paymentId;
const paymentId = typeof raw === 'string' && raw ? raw : null;
const confirming = (
<PaymentConfirming
layout="mobile"
labels={{
title: i18n.t('payment:confirm.title'),
description: i18n.t('payment:confirm.description'),
}}
/>
);
return (
<AuthGuard role="investor" fallback={confirming}>
<PartBoundary name="payment-return">
<PaymentReturn paymentId={paymentId}>{confirming}</PaymentReturn>
</PartBoundary>
</AuthGuard>
);
}

View File

@ -1,19 +0,0 @@
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
import { i18n } from '../../../../i18n';
/** The terms before they arrive: a few paragraphs' worth of lines. */
export default function Loading() {
return (
<SkeletonRegion
delayed
label={i18n.t('terms:meta-title')}
className="mx-auto w-full max-w-content p-4"
>
<Skeleton width="40%" height="1.25rem" className="mb-3" />
<Skeleton lines={4} />
<Skeleton width="35%" height="1.25rem" className="mt-6 mb-3" />
<Skeleton lines={5} />
</SkeletonRegion>
);
}

View File

@ -1,47 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { MobileTopBar } from '@lumina/market/app/navigation';
import {
SubscriptionTerms,
subscriptionTermsLabels,
} from '@lumina/market/app/screens/(flow)/terms/subscription/organisms/subscription-terms';
import { supportChatUrls } from '@lumina/market/app/screens/organisms/support-entry';
import { getEnv } from '@lumina/market/env';
import type { Metadata } from 'next';
import { i18n } from '../../../../i18n';
export function generateMetadata(): Metadata {
return {
title: i18n.t('terms:meta-title'),
description: i18n.t('terms:meta-description'),
};
}
/**
* «شرایط اشتراک» on mobile (S5 ۱.۱): a task page pushed from checkout, a suspended card or the
* support sheet, back · title · support and no bottom nav; back returns to where it was opened.
*/
export default function SubscriptionTermsPage() {
const labels = subscriptionTermsLabels(
i18n.getFixedT(null, 'terms'),
i18n.getFixedT(null, 'auth'),
getEnv().supportHours,
);
return (
<FlexBox direction="flex-col" className="min-h-dvh bg-surface">
<MobileTopBar title={labels.title} />
<FlexBox
tag="main"
direction="flex-col"
className="flex-1 px-4 pt-4 pb-8"
>
<SubscriptionTerms
layout="mobile"
chats={supportChatUrls()}
labels={labels}
/>
</FlexBox>
</FlexBox>
);
}

View File

@ -1,15 +0,0 @@
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { i18n } from '../../../../../i18n';
/** The list before it arrives, card for card; the layout keeps the bar and the tabs. */
export default function Loading() {
return (
<SkeletonPreset
preset="list"
cards="md"
delayed
label={i18n.t('dashboard:subscriptions.loading')}
/>
);
}

View File

@ -1,43 +0,0 @@
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { SubscriptionList } from '@lumina/market/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list';
import type { Metadata } from 'next';
import { Suspense } from 'react';
import { i18n } from '../../../../../i18n';
export function generateMetadata(): Metadata {
return {
title: i18n.t('dashboard:subscriptions.meta-title'),
robots: { index: false },
};
}
/**
* داشبورد › اشتراک‌ها (U2, U11): the investor's own subscriptions, in the browser only, behind
* cards of the same size. A failed read shows in place of the list; the tabs stay (U2 ۳.۴).
*/
export default function SubscriptionsPage() {
const skeleton = (
<SkeletonPreset
preset="list"
cards="md"
label={i18n.t('dashboard:subscriptions.loading')}
/>
);
return (
<PartBoundary
name="subscription-list"
description={i18n.t('dashboard:subscriptions.error')}
framed
>
<AuthGuard role="investor" fallback={skeleton}>
<Suspense fallback={skeleton}>
<SubscriptionList layout="mobile" />
</Suspense>
</AuthGuard>
</PartBoundary>
);
}

View File

@ -1,16 +0,0 @@
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { i18n } from '../../../../../i18n';
/** The payments before they arrive, row for row; the layout keeps the bar and the tabs. */
export default function Loading() {
return (
<SkeletonPreset
preset="list"
cards="md"
avatar={false}
delayed
label={i18n.t('dashboard:transactions.loading')}
/>
);
}

View File

@ -1,44 +0,0 @@
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { TransactionList } from '@lumina/market/app/screens/(main)/dashboard/transactions/organisms/transaction-list';
import type { Metadata } from 'next';
import { Suspense } from 'react';
import { i18n } from '../../../../../i18n';
export function generateMetadata(): Metadata {
return {
title: i18n.t('dashboard:transactions.meta-title'),
robots: { index: false },
};
}
/**
* داشبورد › تراکنش‌ها (U4): the investor's own payments, in the browser only, behind rows of the
* same size. A failed read shows in place of the list, without the chips; the tabs stay (U4 ۴.۳).
*/
export default function TransactionsPage() {
const skeleton = (
<SkeletonPreset
preset="list"
cards="md"
avatar={false}
label={i18n.t('dashboard:transactions.loading')}
/>
);
return (
<PartBoundary
name="transaction-list"
description={i18n.t('dashboard:transactions.error')}
framed
>
<AuthGuard role="investor" fallback={skeleton}>
<Suspense fallback={skeleton}>
<TransactionList layout="mobile" />
</Suspense>
</AuthGuard>
</PartBoundary>
);
}

View File

@ -1,22 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { MobileTopBar } from '@lumina/market/app/navigation';
import { i18n } from '../../../i18n';
/** The centre before it arrives, under its bar. */
export default function Loading() {
return (
<>
<MobileTopBar title={i18n.t('notifications:title')} />
<FlexBox tag="main" direction="flex-col" className="flex-1 p-4">
<SkeletonPreset
preset="list"
avatar={false}
delayed
label={i18n.t('notifications:loading')}
/>
</FlexBox>
</>
);
}

View File

@ -1,49 +0,0 @@
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset';
import { PartBoundary } from '@lumina/market/app/error-boundaries';
import { AuthGuard } from '@lumina/market/app/guards/auth-guard';
import { MobileTopBar } from '@lumina/market/app/navigation';
import { NotificationCentre } from '@lumina/market/app/screens/(main)/notifications/organisms/notification-centre';
import type { Metadata } from 'next';
import { Suspense } from 'react';
import { i18n } from '../../../i18n';
export function generateMetadata(): Metadata {
return {
title: i18n.t('notifications:title'),
robots: { index: false },
};
}
/**
* اعلان‌ها on mobile (U5 ۲.۱): a page pushed from the bell, back · «اعلان‌ها» · support, with the
* nav kept. The member's own notifications, in the browser only, behind rows of the same size.
*/
export default function NotificationsPage() {
const skeleton = (
<SkeletonPreset
preset="list"
avatar={false}
label={i18n.t('notifications:loading')}
/>
);
return (
<>
<MobileTopBar title={i18n.t('notifications:title')} />
<FlexBox tag="main" direction="flex-col" className="flex-1 p-4">
<PartBoundary
name="notification-centre"
description={i18n.t('notifications:error')}
>
<AuthGuard fallback={skeleton}>
<Suspense fallback={skeleton}>
<NotificationCentre layout="page" supportPlacement="bottom" />
</Suspense>
</AuthGuard>
</PartBoundary>
</FlexBox>
</>
);
}

View File

@ -1,23 +0,0 @@
# 0029 Every payment ends on its result page
Status: Proposed · Area: architecture · Date: 2026-10-08 · Decided by: agent
## Context
U10 §۹ (Oct 2026) ends every payment on one result page. The API, not the front, verifies with the bank: its `/payments/callback` redirects the browser to `CHECKOUT_SUCCESS_URL`, `CHECKOUT_CANCEL_URL` or `CHECKOUT_PENDING_URL` with `?paymentId=&status=`.
## Decision
- Set those three API URLs to the site's `/payment/return` (`ROUTES.paymentReturn`). The page shows «در حال تأیید پرداخت...», reads the payment every 2 s until it is settled, then `router.replace`s itself with `/payment/result/[paymentId]` (`ROUTES.paymentResult`). After 30 s it moves on anyway, and the result shows «در حال بررسی».
- Subscribe, renew and reactivate all end there, including a development grant (no bank).
- Both pages render in the browser behind `AuthGuard role="investor"`; the return page's skeleton is the confirming screen itself.
## Alternatives
- Return straight to checkout or the channel with a toast (U9 ۵.۲, U10 ۱.۲): superseded by the design.
- Point the API at the result page: its callback appends a query string, not a path segment.
## Consequences
- Each deployment's API env must name the right site; bull and bear share the URL, and the edge routes by device.
- The in-sheet renew success and failure states (R3 03, 04) are not built: the result page replaces them.

View File

@ -1,22 +0,0 @@
# 0030 The last checkout's period and code survive the bank
Status: Proposed · Area: architecture · Date: 2026-10-08 · Decided by: agent
## Context
Back from the gateway and «تلاش دوباره» on a failed result must reopen checkout with the same period and invite code (U10 ۶.۳, ۹.۲). The browser leaves the app for the bank, so memory is lost unless bfcache keeps the page.
## Decision
- `stores/checkout-draft` is a persisted zustand store, `session.checkout-draft`, holding one `{ creatorId, tierId, referralCode, paymentId }`; `paymentId` is the payment sent to the bank, kept until it is settled (0033).
- `startCheckout` and `startRenewal` write it once a payment exists (redirect or grant); the result page clears it on success; checkout restores it once, for the same creator, when the form is untouched; logout clears it.
- A page restored from bfcache resets its pay button and reads its screen again (`pageshow`).
## Alternatives
- Period and code in the URL: an invite code would land in history, logs and shares.
- Ask the API to return the code with the payment: not available.
## Consequences
- The invite code sits in local storage until success or logout; it is a creator's shared invitation, not personal data.

View File

@ -1,20 +0,0 @@
# 0031 Renew and reactivate list periods as TierOption cards
Status: Proposed · Area: design · Date: 2026-10-08 · Decided by: agent
## Context
R3 01–06 draw the renew and reactivate sheet's periods as a two-column chip grid with the price under each name. U9 (Oct 2026) made island `TierOption` the one tier card, with the per-month line and the saving against monthly.
## Decision
The renew and reactivate sheet (and modal on desktop) lists the creator's periods as `TierOption` radio cards in one column, as checkout does; the dates panel, price-changed note, total and pay button follow them as drawn.
## Alternatives
- A new island chip-radio for the grid: a second way to show the same tier, with less information.
## Consequences
- The sheet is taller than R3 draws; it scrolls inside at 85% height.
- A live promotion applies to renew and reactivate as it does to subscribe (product rule, Oct 2026), so each card shows its discount tag and countdown, as R3 01 and the terms' §۵ do.

View File

@ -1,21 +0,0 @@
# 0032 The notification centre is a page on mobile and a panel on desktop
Status: Proposed · Area: architecture · Date: 2026-10-08 · Decided by: agent
## Context
U5 §۲ opens the centre from a bell in the top bar: a full-screen pushed page on mobile, a 400px side panel on desktop. Same URL tree in bull and bear (0001).
## Decision
- `ROUTES.notifications` (`/notifications`) is a `(main)` page in both apps; bull's bell links there, and bear renders it in the 640 column for a direct visit.
- bear's header bell opens `NotificationPanel` (island `Sheet placement="side"`), loaded with `next/dynamic` on the first click; it closes when an item leads to another page.
- The bell shows for a member of either role on tab bars and the desktop header, never on pushed bars; its count is a browser-only query, and opening the centre marks all read.
## Alternatives
- A panel on mobile too: the design asks for a page.
## Consequences
- Items render the server's Persian title and body; a creator link (`/traders/<profileId>`) is looked up before navigating.

View File

@ -1,29 +0,0 @@
# 0033 A payment left at the bank is settled when the investor comes back
Status: Proposed · Area: architecture · Date: 2026-10-08 · Decided by: agent
## Context
An investor who backs out of the gateway (back button) never reaches `/payment/return`, so the payment stays `pending` and blocks a new one until the API reviews it (checkout answers `pending_review`, subscribe 409). U10 ۶.۳ expects checkout to be untouched. The API settles such a payment on request: `POST /subscriptions/payments/:id/abandon` asks the bank and answers `completed`, `abandoned`, `pending` or `closed`. A bank that has not been paid yet answers "not paid", so the request must never be sent while the bank's page may still be open.
## Decision
- The payment sent to the bank is kept as `paymentId` in the checkout draft (0030), only when the browser really leaves for a bank URL. `settleAbandonedPayment` is the one action that settles it, deduplicated while in flight, and it keeps each step in the store's in-memory `settlement`.
- Only the page that came back settles: a page restored from the back cache that sent the payment itself (`sentHere`, in memory), or a document opened from the history (`back_forward`). A new tab, a reload or a typed address never settles; that payment goes to the API's review.
- A `pending` answer is not asked again in the same page load.
- The app shell triggers the action for a signed-in investor outside `/payment/*`, once the draft is restored and again on a bfcache `pageshow`; moving between pages triggers nothing. When a settlement ends it invalidates checkout, channel, subscription and transaction queries.
- Checkout's screen read awaits the action before it reads, so the screen never shows a settled payment as in review. It shows a same-size skeleton with «در حال بررسی پرداخت قبلی شما با بانک…» while the store says settling. It goes to the result page when this creator's settlement is `completed`, before any other way out. It shows the pending state only when the bank has not answered.
- `/payment/return` forgets the draft's payment, once the draft is restored, when it is the one returned, so a bank answer is never settled twice.
## Alternatives
- Settle on every app load that finds a payment in the draft: a second tab or a reload while the bank's page is open would abandon a payment the investor may still pay.
- Remember the leaving tab in `sessionStorage`: more precise, but it needs a second storage lib for one flag. The history-load check covers backing out.
- Let the review run: the investor cannot retry for 15 minutes and may pay twice from another device.
- Settle only on the checkout page: the subscriptions and transactions tabs would show a stale pending payment.
## Consequences
- One extra request after a gateway round trip that did not come back; none otherwise.
- An investor who closes the bank's tab and opens the app fresh, rather than going back, waits for the API's review (15 minutes) before paying again.
- A payment the bank has not answered stays pending (`pending` outcome). The draft keeps it, and the next page opened from the history asks again.

View File

@ -30,8 +30,3 @@
- 0023 architecture: On desktop «پست جدید» is a dialog over the page through bear's `@modal` intercept of /compose/post; slots are emptied by explicit null pages, never a catch-all, and a hard load gets the full page.
- 0025 architecture: The investor's داشبورد is a tabbed section, one route per tab in `dashboard/(investor)`, whose layout holds the top bar or heading and `DashboardTabs`; each tab has its own loading.
- 0028 design: Landing-only island tokens: `tablet` (720px, the landing's grids only), `hero` and `section` type, `container-page` and `image-shade`.
- 0029 architecture: End every payment on `/payment/result/[paymentId]`; the API's bank callback returns to `/payment/return`, which polls the payment until settled (30 s at most) and replaces itself.
- 0030 architecture: Keep the last checkout's period, invite code and bank payment in the persisted `session.checkout-draft` store from payment start until success, and restore them on the same creator's checkout.
- 0031 design: List renew and reactivate periods as island `TierOption` cards, as checkout does, instead of R3's chip grid.
- 0032 architecture: Serve the notification centre at `/notifications` on mobile and as a lazily loaded side panel from bear's header bell; opening it marks all read.
- 0033 architecture: Keep the payment sent to the bank in the checkout draft and settle it through `POST /subscriptions/payments/:id/abandon` only on the page that came back from the bank (bfcache or a history load), triggered by the app shell and awaited by checkout's screen read.

View File

@ -1,33 +0,0 @@
import { number } from '@lumina/tools/format';
import { Element } from '../../primitives/element';
import { cn } from '../../tools/cn';
import type { CountBadgeProps } from './types';
/**
* An unread count on an icon, such as the bell's (U5 ۲.۲): white digits on danger, «۳», «۲۴»,
* then «۹۹+». Nothing at 0. Decorative: the control's accessible name says the count, so the badge
* is hidden from screen readers. The caller places it, usually at the icon's top end.
*/
export function CountBadge({
count,
cap = 99,
className,
...props
}: CountBadgeProps) {
if (count <= 0) return null;
return (
<Element
tag="span"
aria-hidden
className={cn(
'inline-grid h-4.5 min-w-4.5 place-items-center rounded-full bg-danger-solid px-1 text-micro font-bold text-text-on-action tabular-nums',
className,
)}
{...props}
>
{count > cap ? `${number(cap)}+` : number(count)}
</Element>
);
}

View File

@ -1,2 +0,0 @@
export { CountBadge } from './CountBadge';
export type { CountBadgeProps } from './types';

View File

@ -1,11 +0,0 @@
import type { ComponentPropsWithRef } from 'react';
export type CountBadgeProps = Omit<
ComponentPropsWithRef<'span'>,
'children'
> & {
/** How many; nothing shows at 0. */
count: number;
/** Above it the badge reads «۹۹+», so it never holds more than two digits and a plus. */
cap?: number;
};

View File

@ -1,15 +0,0 @@
import { date, time } from '@lumina/tools/format';
import { Separator } from '../separator';
import type { DateTimeProps } from './types';
/** A Shamsi day and its minute, apart: «۲ تیر ۱۴۰۴ | ۱۴:۲۳». */
export function DateTime({ value }: DateTimeProps) {
return (
<>
{date(value, { time: false })}
<Separator />
{time(value)}
</>
);
}

View File

@ -1,2 +0,0 @@
export { DateTime } from './DateTime';
export type { DateTimeProps } from './types';

View File

@ -1,4 +0,0 @@
export type DateTimeProps = {
/** An ISO date-time. */
value: string;
};

View File

@ -1,18 +1,17 @@
import { Element } from '../../primitives/element';
import { cn } from '../../tools/cn';
import type { SpinnerProps } from './types';
import { spinnerVariants } from './variants';
/**
* A ring that turns while one action is in flight, or on the one screen that only says "wait".
* Never for loading a page: use Skeleton.
*/
export function Spinner({ size, className, ...props }: SpinnerProps) {
/** A ring that turns while one action is in flight. Never for loading a page: use Skeleton. */
export function Spinner({ className, ...props }: SpinnerProps) {
return (
<Element
tag="span"
aria-hidden
className={cn(spinnerVariants({ size }), className)}
className={cn(
'inline-block size-[1.125rem] flex-none animate-spin rounded-full border-2 border-current border-e-transparent',
className,
)}
{...props}
/>
);

View File

@ -1,3 +1,2 @@
export { Spinner } from './Spinner';
export type { SpinnerProps } from './types';
export { spinnerVariants } from './variants';

View File

@ -1,7 +1,3 @@
import type { VariantProps } from 'class-variance-authority';
import type { ComponentPropsWithRef } from 'react';
import type { spinnerVariants } from './variants';
export type SpinnerProps = Omit<ComponentPropsWithRef<'span'>, 'children'> &
VariantProps<typeof spinnerVariants>;
export type SpinnerProps = Omit<ComponentPropsWithRef<'span'>, 'children'>;

View File

@ -1,19 +0,0 @@
import { cva } from 'class-variance-authority';
export const spinnerVariants = cva(
'inline-block flex-none animate-spin rounded-full',
{
variants: {
size: {
/** Inside a button or beside a label, in the text's colour. */
inline: 'size-[1.125rem] border-2 border-current border-e-transparent',
/**
* A screen that exists only to say "wait", such as «در حال تأیید پرداخت...»: 40px, a muted
* ring with the brand arc.
*/
page: 'size-10 border-3 border-action-primary-muted border-e-action-primary',
},
},
defaultVariants: { size: 'inline' },
},
);

View File

@ -13,8 +13,6 @@ export { Checkbox, checkboxVariants } from './atoms/checkbox';
export type { CheckboxProps } from './atoms/checkbox';
export { Chip, chipVariants } from './atoms/chip';
export type { ChipProps, ChipSize } from './atoms/chip';
export { CountBadge } from './atoms/count-badge';
export type { CountBadgeProps } from './atoms/count-badge';
export { Countdown, countdownTone } from './atoms/countdown';
export type {
CountdownKind,
@ -69,11 +67,9 @@ export {
skeletonVariants,
} from './atoms/skeleton';
export type { SkeletonProps, SkeletonRegionProps } from './atoms/skeleton';
export { DateTime } from './atoms/date-time';
export type { DateTimeProps } from './atoms/date-time';
export { Separator } from './atoms/separator';
export type { SeparatorProps } from './atoms/separator';
export { Spinner, spinnerVariants } from './atoms/spinner';
export { Spinner } from './atoms/spinner';
export { useCountdown } from './hooks/use-countdown';
export type { CountdownOptions } from './hooks/use-countdown';
export { useOnline } from './hooks/use-online';
@ -117,19 +113,12 @@ export { ChipGroup } from './molecules/chip-group';
export type { ChipGroupOption, ChipGroupProps } from './molecules/chip-group';
export { ChoiceCard, choiceCardVariants } from './molecules/choice-card';
export type { ChoiceCardProps } from './molecules/choice-card';
export { DetailRow, detailRowVariants } from './molecules/detail-row';
export type { DetailRowProps } from './molecules/detail-row';
export { EmptyState } from './molecules/empty-state';
export type { EmptyStateProps, EmptyStateTone } from './molecules/empty-state';
export { ERROR_KIND_STYLES, ErrorState } from './molecules/error-state';
export type { ErrorKind, ErrorStateProps } from './molecules/error-state';
export { FactCard } from './molecules/fact-card';
export type { FactCardProps } from './molecules/fact-card';
export { FilterChips } from './molecules/filter-chips';
export type {
FilterChipOption,
FilterChipsProps,
} from './molecules/filter-chips';
export { FormSection } from './molecules/form-section';
export type { FormSectionProps } from './molecules/form-section';
export { LockedTeaser } from './molecules/locked-teaser';

View File

@ -1,29 +0,0 @@
import { FlexBox } from '../../atoms/flex-box';
import { Typography } from '../../atoms/typography';
import { Element } from '../../primitives/element';
import type { DetailRowProps } from './types';
import { detailRowVariants } from './variants';
/**
* One line of a `<dl>`, such as a receipt or a payment's detail: the label at the start, its
* value at the end, on one baseline.
*/
export function DetailRow({ label, children, size }: DetailRowProps) {
return (
<FlexBox
alignItems="items-baseline"
justifyContent="justify-between"
gap="gap-3"
className={detailRowVariants({ size })}
>
<Element tag="dt">
<Typography tag="span" variant="body-sm" color="secondary">
{label}
</Typography>
</Element>
<Element tag="dd" className="m-0 text-end font-semibold">
{children}
</Element>
</FlexBox>
);
}

View File

@ -1,3 +0,0 @@
export { DetailRow } from './DetailRow';
export type { DetailRowProps } from './types';
export { detailRowVariants } from './variants';

View File

@ -1,10 +0,0 @@
import type { VariantProps } from 'class-variance-authority';
import type { ReactNode } from 'react';
import type { detailRowVariants } from './variants';
export type DetailRowProps = VariantProps<typeof detailRowVariants> & {
label: ReactNode;
/** The value, at the end. */
children: ReactNode;
};

View File

@ -1,12 +0,0 @@
import { cva } from 'class-variance-authority';
/** `sm` for a receipt card, `md` for a detail sheet's divided list. */
export const detailRowVariants = cva('', {
variants: {
size: {
sm: 'py-1.5',
md: 'py-2',
},
},
defaultVariants: { size: 'md' },
});

View File

@ -1,64 +0,0 @@
import { useId } from 'react';
import { chipVariants } from '../../atoms/chip';
import { FlexBox } from '../../atoms/flex-box';
import { Typography } from '../../atoms/typography';
import { Element } from '../../primitives/element';
import { cn } from '../../tools/cn';
import type { FilterChipsProps } from './types';
/**
* A one-of filter as a wrapping row of chips, such as a list's status (U4 ۳.۱): it applies at
* once, with no apply button. A named radiogroup of real radios, so Tab reaches the chosen chip
* and the arrow keys move the choice. The chosen chip fills brand; unlike a multiple-choice Chip
* it has no check, since exactly one is always chosen.
*/
export function FilterChips<T extends string>({
options,
value,
onChange,
label,
size = 'md',
disabled = false,
className,
}: FilterChipsProps<T>) {
const name = useId();
return (
<FlexBox
tag="fieldset"
role="radiogroup"
aria-label={label}
disabled={disabled}
wrap="flex-wrap"
gap="gap-2"
className={cn('m-0 min-w-0 border-0 p-0', className)}
>
{options.map((option) => (
<FlexBox
key={option.value}
tag="label"
display="inline-flex"
alignItems="items-center"
className={cn(
chipVariants({ selected: option.value === value, size }),
'relative has-[input:focus-visible]:focus-ring',
)}
>
<Element
tag="input"
type="radio"
name={name}
value={option.value}
checked={option.value === value}
onChange={() => onChange(option.value)}
className="pointer-events-none absolute m-0 size-px opacity-0"
/>
<Typography tag="span" variant="label" color="inherit">
{option.label}
</Typography>
</FlexBox>
))}
</FlexBox>
);
}

View File

@ -1,2 +0,0 @@
export { FilterChips } from './FilterChips';
export type { FilterChipOption, FilterChipsProps } from './types';

View File

@ -1,20 +0,0 @@
import type { ReactNode } from 'react';
import type { ChipSize } from '../../atoms/chip';
export type FilterChipOption<T extends string> = { value: T; label: ReactNode };
export type FilterChipsProps<T extends string> = {
/** In reading order, such as «همه» · «موفق» · «در حال بررسی» · «ناموفق». */
options: readonly FilterChipOption<T>[];
/** The one shown now. */
value: T;
/** Called with the chip picked by a press or the arrow keys; never for the chosen one. */
onChange: (value: T) => void;
/** The group's accessible name, such as «وضعیت». */
label: string;
/** `md` (44px) on a page, `sm` (36px) in a compact row. */
size?: ChipSize;
disabled?: boolean;
className?: string;
};

View File

@ -5,8 +5,7 @@ import type { MediaCarouselProps } from './types';
/**
* A post's images. One shows full width at its own ratio, letterboxed at 400px on
* `surface-sunken`; 2–4 swipe in 280px slides with dots and a «۱ / ۳» count, and from 480px wide
* also move with ‹ › buttons on the image. Server-renderable:
* `surface-sunken`; 2–4 swipe in 280px slides with dots and a «۱ / ۳» count. Server-renderable:
* a single image ships no JavaScript, and only the swipe track is a client component, so every
* prop it takes is serializable except `onOpen`, which only a client caller can pass.
*/
@ -16,8 +15,6 @@ export function MediaCarousel({
href,
onOpen,
label,
previousLabel,
nextLabel,
className,
}: MediaCarouselProps) {
const shown = items.slice(0, MAX_MEDIA);
@ -45,8 +42,6 @@ export function MediaCarousel({
href={href}
onOpen={onOpen}
label={label}
previousLabel={previousLabel}
nextLabel={nextLabel}
className={className}
/>
);

View File

@ -1,30 +0,0 @@
import { GridBox } from '../../../atoms/grid-box';
import { Icon } from '../../../atoms/icon';
import type { MediaNavButtonProps } from '../types';
import { mediaNavVariants } from '../variants';
/** A ‹ › button on the track; its chevron points the way it moves, flipped in LTR. */
export function MediaNavButton({
side,
label,
isDisabled,
onClick,
}: MediaNavButtonProps) {
return (
<GridBox
tag="button"
type="button"
justifyItems="justify-items-center"
alignItems="items-center"
aria-label={label}
aria-disabled={isDisabled || undefined}
onClick={isDisabled ? undefined : onClick}
className={mediaNavVariants({ side })}
>
<Icon
name={side === 'previous' ? 'chevron-right' : 'chevron-left'}
className="ltr:-scale-x-100"
/>
</GridBox>
);
}

View File

@ -46,7 +46,7 @@ export function MediaSlide({
className={cn(
box,
'actionable:cursor-zoom-in',
// A slide's ring would be clipped by the scrolling track, so the track draws it.
// A slide's ring would be clipped by the scrolling track, so the track's frame draws it.
single ? 'focus-visible:focus-ring' : 'outline-none',
)}
>

View File

@ -1,25 +1,19 @@
'use client';
import { number } from '@lumina/tools/format';
import { useRef, useState } from 'react';
import type { KeyboardEvent, UIEvent } from 'react';
import { useState } from 'react';
import type { UIEvent } from 'react';
import { FlexBox } from '../../../atoms/flex-box';
import { Typography } from '../../../atoms/typography';
import { Element } from '../../../primitives/element';
import { cn } from '../../../tools/cn';
import type { MediaCarouselProps } from '../types';
import { mediaDotVariants } from '../variants';
import { MediaNavButton } from './MediaNavButton';
import { MediaSlide } from './MediaSlide';
const isRtl = (node: HTMLElement) => getComputedStyle(node).direction === 'rtl';
/**
* 2–4 images in a native swipe (scroll snap), with a «۱ / ۳» count and a dot per image. From 480px
* wide, ‹ › buttons on the image move it too, and ← → on a focused slide. Moving never opens the
* Lightbox: only a tap on an image does. The only client part of a post: it follows the scroll to
* light the current dot and count.
* 2–4 images in a native swipe (scroll snap), with a «۱ / ۳» chip and a dot per image. The only
* client part of a post: it follows the scroll to light the current dot and count.
*/
export function MediaTrack({
items,
@ -27,12 +21,9 @@ export function MediaTrack({
href,
onOpen,
label,
previousLabel,
nextLabel,
className,
}: MediaCarouselProps) {
const [current, setCurrent] = useState(0);
const trackRef = useRef<HTMLDivElement>(null);
const count = items.length;
// scrollLeft is negative in RTL, so its size gives the slide either way.
@ -42,52 +33,18 @@ export function MediaTrack({
setCurrent(Math.min(count - 1, index));
};
// Only scrolls: `handleScroll` then moves the dots and the count.
const goTo = (index: number) => {
const track = trackRef.current;
if (!track) return;
const reduced = window.matchMedia(
'(prefers-reduced-motion: reduce)',
).matches;
track.scrollTo({
left: (isRtl(track) ? -1 : 1) * index * track.clientWidth,
behavior: reduced ? 'auto' : 'smooth',
});
};
// ← is next in RTL, as in the Lightbox. Focus moves with the image, so Enter opens the one shown.
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const track = event.currentTarget;
const slides = Array.from(track.children) as HTMLElement[];
const from = slides.indexOf(event.target as HTMLElement);
if (from === -1) return;
const [next, previous] = isRtl(track)
? ['ArrowLeft', 'ArrowRight']
: ['ArrowRight', 'ArrowLeft'];
const step = event.key === next ? 1 : event.key === previous ? -1 : 0;
if (step === 0) return;
event.preventDefault();
const to = Math.min(Math.max(from + step, 0), count - 1);
if (to === from) return;
slides[to].focus({ preventScroll: true });
goTo(to);
};
return (
<FlexBox
tag="section"
direction="flex-col"
gap="gap-2"
aria-label={label}
className={cn('@container', className)}
className={className}
>
<Element className="relative">
<Element className="relative rounded-md has-[:focus-visible]:focus-ring">
<FlexBox
ref={trackRef}
onScroll={handleScroll}
onKeyDown={handleKeyDown}
// A slide's ring would be clipped by the scroll, so the track draws it; not the buttons'.
className="snap-x snap-mandatory overflow-x-auto overscroll-x-contain rounded-md bg-surface-sunken [scrollbar-width:none] has-[:focus-visible]:focus-ring [&::-webkit-scrollbar]:hidden"
className="snap-x snap-mandatory overflow-x-auto overscroll-x-contain rounded-md bg-surface-sunken [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
>
{items.map((item, index) => (
<MediaSlide
@ -102,28 +59,12 @@ export function MediaTrack({
/>
))}
</FlexBox>
{previousLabel && nextLabel && (
<>
<MediaNavButton
side="previous"
label={previousLabel}
isDisabled={current === 0}
onClick={() => goTo(current - 1)}
/>
<MediaNavButton
side="next"
label={nextLabel}
isDisabled={current === count - 1}
onClick={() => goTo(current + 1)}
/>
</>
)}
{/* Each slide button already says «۱ از ۳»; the chip is for the eye only. */}
<Typography
tag="span"
variant="micro"
color="on-action"
aria-live="polite"
aria-atomic
aria-hidden
className="absolute end-2 top-2 rounded-sm bg-scrim-chip px-2"
>
<Element tag="bdi" dir="ltr">

View File

@ -26,12 +26,6 @@ export type MediaCarouselProps = {
onOpen?: (index: number) => void;
/** The swipe section's accessible name, such as «تصاویر پست». */
label?: string;
/**
* The ‹ › buttons' names, «تصویر قبلی» and «تصویر بعدی». The buttons show only with both, on a
* carousel at least 480px wide.
*/
previousLabel?: string;
nextLabel?: string;
className?: string;
};
@ -46,12 +40,3 @@ export type MediaSlideProps = {
onOpen?: (index: number) => void;
className?: string;
};
export type MediaNavButtonProps = {
/** Previous sits at inline-start, next at inline-end. */
side: 'previous' | 'next';
label: string;
/** At the first or last image: frozen, but it keeps focus. */
isDisabled: boolean;
onClick: () => void;
};

View File

@ -33,20 +33,3 @@ export const mediaDotVariants = cva(
defaultVariants: { active: false },
},
);
/**
* A 44px ‹ › control on the image, vertically centred. Hidden until the carousel (its `@container`)
* is 480px wide, so phones swipe. Ends use `aria-disabled`, so a focused button keeps focus when
* it runs out.
*/
export const mediaNavVariants = cva(
'absolute top-1/2 z-1 hidden size-touch-target -translate-y-1/2 rounded-full bg-image-control text-text-primary shadow-2 transition-[opacity,background-color] duration-120 ease-standard @min-[480px]:grid focus-visible:focus-ring actionable:cursor-pointer actionable:hover:bg-surface aria-disabled:frozen',
{
variants: {
side: {
previous: 'start-3',
next: 'end-3',
},
},
},
);

View File

@ -46,8 +46,6 @@ export function PostContent({
href={href}
onOpen={onImageClick}
label={labels.images}
previousLabel={labels.previousImage}
nextLabel={labels.nextImage}
className={ABOVE_LINK_CLASS}
/>
)}

View File

@ -65,9 +65,6 @@ export type PostCardLabels = {
* تصویر ۱ از ۳، نمودار طلا».
*/
openSlide?: (n: string, total: string, alt: string) => string;
/** The carousel's ‹ › buttons, «تصویر قبلی» and «تصویر بعدی»; they show only with both. */
previousImage?: string;
nextImage?: string;
/** A locked post's image count, from 2 images: `(n) => <>{n} تصویر</>` → «۳ تصویر». */
imageCount: (count: string) => ReactNode;
/** «اشتراک‌گذاری». */

View File

@ -250,8 +250,6 @@
--inverse-control-hover: rgba(255, 255, 255, 0.2);
/* Counters drawn over images («۱ / ۳»). */
--scrim-chip: rgba(12, 16, 24, 0.64);
/* Controls drawn over images (the post carousel's ‹ ›): near-opaque white pills. */
--image-control: rgba(255, 255, 255, 0.94);
--text-on-action: #ffffff;
--text-link: var(--indigo-600);
--border-subtle: var(--slate-150);
@ -321,7 +319,6 @@
--color-inverse-control: var(--inverse-control);
--color-inverse-control-hover: var(--inverse-control-hover);
--color-scrim-chip: var(--scrim-chip);
--color-image-control: var(--image-control);
--color-text-on-action: var(--text-on-action);
--color-text-link: var(--text-link);
--color-border-subtle: var(--border-subtle);

View File

@ -5,11 +5,9 @@ import { QueryClientProvider } from '@tanstack/react-query';
import { useEffect } from 'react';
import { I18nextProvider } from 'react-i18next';
import { useCheckoutDraftStore } from '../../stores/checkout-draft';
import { usePostDraftStore } from '../../stores/post-draft';
import { NetworkBoundary } from './components/NetworkBoundary';
import { useSession } from './hooks/use-session';
import { useSettleAbandonedPayment } from './hooks/use-settle-abandoned-payment';
import type { AppShellProps } from './types';
/**
@ -19,11 +17,9 @@ import type { AppShellProps } from './types';
*/
export function AppShell({ queryClient, i18n, children }: AppShellProps) {
useSession(queryClient);
useSettleAbandonedPayment(queryClient);
// Persisted stores wait for the first browser render, so it matches the server's.
useEffect(() => {
void usePostDraftStore.persist.rehydrate();
void useCheckoutDraftStore.persist.rehydrate();
}, []);
return (

View File

@ -6,7 +6,6 @@ import { useEffect } from 'react';
import { AUTH_EVENTS, restoreSession } from '../../../features/auth';
import { useAuthStore } from '../../../stores/auth';
import { useCheckoutDraftStore } from '../../../stores/checkout-draft';
import { usePostDraftStore } from '../../../stores/post-draft';
/**
@ -33,7 +32,6 @@ export function useSession(queryClient: QueryClient): void {
// The account's own drafts and choices stay with it, not with the device. The stores go
// first: a persisted store writes its key again on every change.
usePostDraftStore.getState().clearDraft();
useCheckoutDraftStore.getState().clearDraft();
storage.clearByPrefix('session.');
});
return () => {

View File

@ -1,75 +0,0 @@
import { handleError } from '@lumina/libs/error-handler';
import { eventEmitter } from '@lumina/libs/event-emitter';
import type { QueryClient } from '@tanstack/react-query';
import { useEffect } from 'react';
import { channelKeys } from '../../../features/channel';
import {
CHECKOUT_EVENTS,
checkoutKeys,
settleAbandonedPayment,
} from '../../../features/checkout';
import { subscriptionKeys } from '../../../features/subscription';
import { transactionKeys } from '../../../features/transaction';
import { useCurrentAccount, useViewerStatus } from '../../../stores/auth';
import { useCheckoutDraftStore } from '../../../stores/checkout-draft';
import { ROUTES } from '../../navigation/navigation';
// The return and result pages read the bank's answer themselves.
const isPaymentPage = (pathname: string) =>
pathname === ROUTES.paymentReturn ||
pathname.startsWith(ROUTES.paymentResult(''));
/**
* A payment handed to the bank whose callback never came: the investor backed out of the bank to
* any page but the return and result pages, as a fresh load or a page restored from the back
* cache. Once the draft is loaded and the viewer is a signed-in investor, the settle action asks
* the bank (it decides whether this page is the one that came back), and whatever shows this
* creator's standing, the subscriptions or the transactions reads again (U10 ۶.۳). Moving between
* pages asks nothing.
*/
export function useSettleAbandonedPayment(queryClient: QueryClient): void {
const status = useViewerStatus();
const account = useCurrentAccount();
const isInvestor = status === 'member' && account?.role === 'investor';
useEffect(
() =>
eventEmitter.on(
CHECKOUT_EVENTS.paymentSettled,
({ creatorId, outcome }) => {
if (outcome === 'pending') return;
void queryClient.invalidateQueries({ queryKey: checkoutKeys.all });
void queryClient.invalidateQueries({
queryKey: channelKeys.creator(creatorId),
});
void queryClient.invalidateQueries({
queryKey: subscriptionKeys.all,
});
void queryClient.invalidateQueries({ queryKey: transactionKeys.all });
},
),
[queryClient],
);
useEffect(() => {
if (!isInvestor) return;
const settle = () => {
if (isPaymentPage(window.location.pathname)) return;
settleAbandonedPayment().catch((error: unknown) =>
handleError(error, { where: 'app', name: 'settle-abandoned-payment' }),
);
};
const onPageShow = (event: PageTransitionEvent) => {
if (event.persisted) settle();
};
const offHydrated = useCheckoutDraftStore.persist.hasHydrated()
? (settle(), undefined)
: useCheckoutDraftStore.persist.onFinishHydration(settle);
window.addEventListener('pageshow', onPageShow);
return () => {
offHydrated?.();
window.removeEventListener('pageshow', onPageShow);
};
}, [isInvestor]);
}

View File

@ -4,8 +4,8 @@ import { Avatar } from '@lumina/island/atoms/avatar';
import { Button } from '@lumina/island/atoms/button';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { GridBox } from '@lumina/island/atoms/grid-box';
import { Skeleton } from '@lumina/island/atoms/skeleton';
import { Typography } from '@lumina/island/atoms/typography';
import { Element } from '@lumina/island/primitives/element';
import NextLink from 'next/link';
import { usePathname } from 'next/navigation';
import { useTranslation } from 'react-i18next';
@ -15,16 +15,15 @@ import { SupportEntry } from '../../../screens/organisms/support-entry';
import { activeTab } from '../../active-tab';
import { useHomeHref } from '../../hooks/use-home-href';
import { loginRoute, ROUTES } from '../../navigation';
import { NotificationBell } from '../notification-bell';
import { PublishMenu } from '../publish-menu';
import { HeaderNavLink } from './components/HeaderNavLink';
/**
* The desktop header on every main page: the brand, the nav, then support, the bell and the
* account at the end. An investor's nav is خانه · داشبورد; a creator's is کانال · داشبورد, with
* «انتشار» before support. A guest sees only the brand, support and «ورود/ثبت‌نام», which returns
* here. The brand goes home, or to a creator's own channel. Who is looking is known only in the
* browser; until then the guest's end holds its place.
* The desktop header on every main page: the brand, the nav, then support and the account at the
* end. An investor's nav is خانه · داشبورد; a creator's is کانال · داشبورد, with «انتشار» before
* support. A guest sees only the brand, support and «ورود/ثبت‌نام», which returns here. The brand
* goes home, or to a creator's own channel. Who is looking is known only in the browser; until then
* the account's place is a skeleton.
*/
export function DesktopHeader() {
const { t } = useTranslation();
@ -88,15 +87,15 @@ export function DesktopHeader() {
<FlexBox alignItems="items-center" gap="gap-2" className="ms-auto">
{isCreator && <PublishMenu placement="header" />}
<SupportEntry trigger="icon" placement="popover" />
{status === 'member' && <NotificationBell placement="panel" />}
{status === 'unknown' && (
// Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so it
// doesn't move when the session arrives.
<Element tag="span" aria-hidden className="invisible flex-none">
<Button variant="primary" tabIndex={-1}>
{t('nav.login')}
</Button>
</Element>
// The account link's size, so the end doesn't move when the session arrives.
<GridBox
justifyItems="justify-items-center"
alignItems="items-center"
className="size-touch-target"
>
<Skeleton shape="circle" width="2rem" height="2rem" />
</GridBox>
)}
{status === 'guest' && (
<Button variant="primary" href={loginRoute(pathname)}>

View File

@ -1,25 +0,0 @@
'use client';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import { Typography } from '@lumina/island/atoms/typography';
import { useTranslation } from 'react-i18next';
import { BackButton } from '../mobile-top-bar/components/BackButton';
import type { DesktopPageTitleProps } from './types';
/**
* A pushed page's heading on desktop, at the top of its column: back, then the page's name (U9
* ۹.۱, S5 ۲.۱). Back returns where the person came from, or home for a page opened on its own.
*/
export function DesktopPageTitle({ title, onBack }: DesktopPageTitleProps) {
const { t } = useTranslation();
return (
<FlexBox alignItems="items-center" gap="gap-1" className="-ms-2">
<BackButton label={t('nav.back')} onBack={onBack} />
<Typography tag="h1" variant="heading-md">
{title}
</Typography>
</FlexBox>
);
}

View File

@ -1,2 +0,0 @@
export { DesktopPageTitle } from './DesktopPageTitle';
export type { DesktopPageTitleProps } from './types';

View File

@ -1,6 +0,0 @@
export type DesktopPageTitleProps = {
/** The page's name: «خرید اشتراک». */
title: string;
/** Back asks first; without it back goes back. */
onBack?: () => void;
};

View File

@ -6,8 +6,6 @@ import { FlexBox } from '@lumina/island/atoms/flex-box';
import { GridBox } from '@lumina/island/atoms/grid-box';
import { Skeleton } from '@lumina/island/atoms/skeleton';
import { Typography } from '@lumina/island/atoms/typography';
import { Element } from '@lumina/island/primitives/element';
import { cn } from '@lumina/island/tools/cn';
import NextLink from 'next/link';
import { usePathname } from 'next/navigation';
import { useTranslation } from 'react-i18next';
@ -17,7 +15,6 @@ import { SupportEntry } from '../../../screens/organisms/support-entry';
import { useHomeHref } from '../../hooks/use-home-href';
import { useIsOwnPreview } from '../../hooks/use-is-own-preview';
import { loginRoute, ROUTES } from '../../navigation';
import { NotificationBell } from '../notification-bell';
import { BackButton } from './components/BackButton';
import { Brand } from './components/Brand';
import type { MobileTopBarProps } from './types';
@ -28,17 +25,15 @@ import type { MobileTopBarProps } from './types';
* main screen, and a creator on their own tab, get the tab bar: the brand, the tab's name centred
* when it has one («داشبورد»; خانه has none), support and the member's account (Main A, U8 ۴.۱).
* Who is looking is known only in the browser, so the server and the first browser render show a
* tab's bar with its brand and name, and a pushed page's bar without its start; both hold the
* guest's «ورود/ثبت‌نام» unseen at the end, since most visitors are guests. A creator's brand goes to their own channel, their home tab, and a
* guest's to the landing. A pushed page with nothing behind it drops back (`back={false}`). The tab
* bar carries the bell between support and the account (U5 ۲.۲); a pushed bar has neither.
* tab's bar with its brand and name and a placeholder where the account goes, and a pushed page's
* bar without its start. A creator's brand goes to their own channel, their home tab, and a
* guest's to the landing.
*/
export function MobileTopBar({
title,
isTab = false,
tabOwnerId,
onBack,
back = true,
previewTitle,
}: MobileTopBarProps) {
const { t } = useTranslation();
@ -80,31 +75,30 @@ export function MobileTopBar({
)}
{status === 'member' && !isTabBar && (
<>
{back && <BackButton label={t('nav.back')} onBack={onBack} />}
<BackButton label={t('nav.back')} onBack={onBack} />
<Typography
tag="span"
variant="heading-sm"
className={cn('flex-1 truncate', !back && 'ps-2')}
className="flex-1 truncate"
>
{isPreview && previewTitle ? previewTitle : title}
</Typography>
</>
)}
<SupportEntry trigger="icon" placement="bottom" />
{status === 'member' && isTabBar && <NotificationBell placement="link" />}
{status === 'guest' && (
<Button variant="ghost" size="sm" href={loginRoute(pathname)}>
{t('nav.login')}
</Button>
)}
{status === 'unknown' && (
// Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so the bar
// doesn't move when the session arrives.
<Element tag="span" aria-hidden className="invisible flex-none">
<Button variant="ghost" size="sm" tabIndex={-1}>
{t('nav.login')}
</Button>
</Element>
{status === 'unknown' && isTabBar && (
<GridBox
justifyItems="justify-items-center"
alignItems="items-center"
className="size-touch-target"
>
<Skeleton shape="circle" width="2rem" height="2rem" />
</GridBox>
)}
{status === 'member' && isTabBar && account && (
<GridBox

View File

@ -10,11 +10,6 @@ type PushedBarProps = {
tabOwnerId?: string;
/** Back asks first (a composer with unsaved text); without it back goes back. */
onBack?: () => void;
/**
* `false`: nothing behind the page to go back to, such as the payment result with the bank behind
* it (U10 ۹.۱), so the bar has only the name and support.
*/
back?: boolean;
/** The title while the page is in the creator's preview (`?preview`): «پیش‌نمایش پست». */
previewTitle?: string;
};
@ -26,7 +21,6 @@ type TabBarProps = {
title?: string;
tabOwnerId?: never;
onBack?: never;
back?: never;
previewTitle?: never;
};

View File

@ -1,84 +0,0 @@
'use client';
import { Button } from '@lumina/island/atoms/button';
import { CountBadge } from '@lumina/island/atoms/count-badge';
import { FlexBox } from '@lumina/island/atoms/flex-box';
import dynamic from 'next/dynamic';
import { usePathname } from 'next/navigation';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
UNREAD_BADGE_CAP,
useUnreadCount,
} from '../../../../features/notification';
import { ROUTES } from '../../navigation';
import type { NotificationBellProps } from './types';
// The centre's code loads on the first open, not with every page's header.
const NotificationPanel = dynamic(
() =>
import(
'../../../screens/(main)/notifications/organisms/notification-centre'
).then((module) => module.NotificationPanel),
{ ssr: false },
);
/**
* The bell (U5 ۲.۲), for a signed-in member of either role, between support and the account: the
* unread count on it in red up to «۹۹+», gone at 0 and once the centre is opened. Mobile goes to
* the centre's page; desktop opens it as a side panel over the page, which closes when an item
* leads elsewhere.
*/
export function NotificationBell({ placement }: NotificationBellProps) {
const { t } = useTranslation('notifications');
const count = useUnreadCount();
const pathname = usePathname();
// Open on the page it was opened on: an item that leads to another page closes it.
const [openedOn, setOpenedOn] = useState<string | null>(null);
const [hasOpened, setHasOpened] = useState(false);
const isOpen = openedOn === pathname;
const label = count > 0 ? t('bell-unread', { count }) : t('bell');
const badge = (
<CountBadge
count={count}
cap={UNREAD_BADGE_CAP}
className="pointer-events-none absolute end-1 top-1"
/>
);
if (placement === 'link') {
return (
<FlexBox className="relative">
<Button
variant="ghost"
icon="bell"
label={label}
href={ROUTES.notifications}
/>
{badge}
</FlexBox>
);
}
return (
<FlexBox className="relative">
<Button
variant="ghost"
icon="bell"
label={label}
aria-haspopup="dialog"
aria-expanded={isOpen}
onClick={() => {
setHasOpened(true);
setOpenedOn(pathname);
}}
/>
{badge}
{hasOpened && (
<NotificationPanel open={isOpen} onClose={() => setOpenedOn(null)} />
)}
</FlexBox>
);
}

Some files were not shown because too many files have changed in this diff Show More