Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(react): draw generated avatars on the server as cached SVGs

naveenkashf0d593524f8e
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 68579bd81d..7e0c953164 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -3353,3 +3353,13 @@ of `salesInvoice`; backfilled by `20261006220901_sales-invoice-opportunity-backf
**Rule:** In a component that every page renders, import a heavy library with `import()` at the point of first use, and keep only `import type` at the top of the file. Check with a split bundle: `npx esbuild <file> --bundle --splitting --format=esm --minify --outdir=/tmp/out '--external:@carbon/*' --external:react`. The entry file must stay small, and the library must be a separate chunk.
**Applies to:** `packages/react/src/**` components used in app shells (`Avatar`, `NavRail`, layout parts); any new dependency of `@carbon/react`.
+
+## A JSON import attribute fixes the server and breaks the browser
+
+**Context:** `@carbon/react` loads each DiceBear style's JSON with `import()` (`packages/react/src/utils/generatedAvatar.ts`). The same code runs in the browser (the avatar picker) and on the server (the `/file/avatar/:value` route).
+
+**Problem:** On the server, Vite leaves a dependency's import external, and Node refuses JSON without `with: { type: "json" }` (`ERR_IMPORT_ATTRIBUTE_MISSING`). Adding the attribute fixed the route. But Vite passes the attribute through to the browser's `import()`, and serves the JSON as `text/javascript`, so the browser rejected every style and the picker previews stayed grey (2026-10-08). Typecheck, unit tests and the server route all passed; only the browser saw it.
+
+**Rule:** Never put an import attribute on a JSON import in code that also runs in the browser. Make the server bundle the package instead: add it to `ssrNoExternal` in each app's `vite.config.ts` (the ERP and MES lists apply to both `ssr.noExternal` and `environments.ssr.resolve.noExternal`). To check the browser side, fetch the module from the dev server (`curl $ERP_URL/@fs<absolute path>`) and confirm the `import()` call has no second argument.
+
+**Applies to:** `packages/react/src/utils/generatedAvatar.ts`; any isomorphic code that imports JSON from a dependency.
diff --git a/.ai/runs/2026-10-08-dicebear-avatars.md b/.ai/runs/2026-10-08-dicebear-avatars.md
index 8b6fe12143..25eda91c9b 100644
--- a/.ai/runs/2026-10-08-dicebear-avatars.md
+++ b/.ai/runs/2026-10-08-dicebear-avatars.md
@@ -18,6 +18,7 @@
- Avatar styles: a style select with 10 styles (user request). DiceBear moves from 9 to 10, because Loops, Voxel Art, Voxel Bot and Planets exist only in version 10. New users keep Croodles Neutral — 2026-10-08
- Line-art avatars: black lines on white in both themes, no invert — user request — 2026-10-08
- Background color: user picks one per avatar with the ERP `ColorPicker`; stored as an optional `:<rrggbb>` value segment; dark backgrounds switch the neutral line styles to white ink — user request — 2026-10-08
+- Server-drawn avatars: a public `/file/avatar/:value` route in each app renders the SVG with DiceBear and caches it as immutable; `Avatar` uses it, the picker still draws in the browser — user approved the route after a slow-refresh report — 2026-10-08
## Phase log
- spec: written at `.ai/specs/2026-10-08-dicebear-avatars.md`. All 4 questions answered by the user before writing. STE-80 pass done.
@@ -32,5 +33,7 @@
- self-review 3 (user asked to fix the must-fix and suggestions): the DiceBear core loads lazily (renderer entry 2.5 KB in a split bundle); `generatedAvatarClassName` and `avatarSrc` extracted with tests; the order-dependent test isolated with `vi.resetModules`; the profile action has 6 tests (a delete-before-save mutation fails 4 of them). Docs: 2 lessons, both AGENTS notes, the spec.
+- self-review 4: image helpers split into `generatedAvatarImage.ts` (Avatar bundle 3.4 KB, no DiceBear); version constant in tests; regression test against JSON import attributes (mutation fails it); spec updated for the route.
+
## Outcome
- Uncommitted on `naveenkash/75pu7`. The migration is not applied. The user commits and applies it.
diff --git a/.ai/specs/2026-10-08-dicebear-avatars.md b/.ai/specs/2026-10-08-dicebear-avatars.md
index 97c9671da0..4089b26668 100644
--- a/.ai/specs/2026-10-08-dicebear-avatars.md
+++ b/.ai/specs/2026-10-08-dicebear-avatars.md
@@ -72,9 +72,12 @@ A storage path never contains `:`, because the upload names the file
| Unit | Location | Job |
|------|----------|-----|
| `GENERATED_AVATAR_STYLES`, `parseGeneratedAvatar`, `isGeneratedAvatar`, `newGeneratedAvatar(style?)`, `isAllowedAvatarValue` | `packages/utils/src/avatar.ts` (exported from `@carbon/utils`) | Pure string helpers. Server and client code use them. No DiceBear import |
-| `STYLE_LOADERS`, `loadGeneratedAvatarStyle`, `generatedAvatarDataUri`, `useGeneratedAvatar`, `generatedAvatarClassName` | `packages/react/src/utils/generatedAvatar.ts` | Loads the DiceBear core and each style's JSON definition as separate chunks on first use. Renders `new Avatar(style, { seed }).toDataUri()` and caches the result per value. Picks the image classes per style |
-| `Avatar` | `packages/react/src/Avatar.tsx` | If `src` is a generated-avatar value, renders the data URI. Shows a plain circle while the style loads |
-| `GeneratedAvatarPicker` | `apps/erp/app/modules/account/ui/Profile/GeneratedAvatarPicker.tsx` | Modal with a style `Select`, a grid of generated options, a Shuffle button and the credit for the selected style. Each option is an `Avatar` with the value as `src`, so the `@carbon/react` barrel does not change |
+| `GENERATED_AVATAR_RENDER_VERSION`, `generatedAvatarUrl`, `generatedAvatarClassName` | `packages/react/src/utils/generatedAvatarImage.ts` | What `Avatar` needs: the URL of the server-drawn SVG and the classes of the image. No DiceBear import, so `Avatar` stays small |
+| `STYLE_LOADERS`, `loadGeneratedAvatarStyle`, `renderGeneratedAvatarSvg`, `generatedAvatarDataUri`, `useGeneratedAvatar` | `packages/react/src/utils/generatedAvatar.ts` | The renderer. Loads the DiceBear core and each style's JSON as separate chunks on first use. Draws an SVG string for the route, or a cached data URI for the picker |
+| `generatedAvatarLoader`, `GeneratedAvatarPreview` | `packages/react/src/GeneratedAvatar.tsx` (subpath `@carbon/react/GeneratedAvatar`) | The route loader, and the browser-drawn preview the picker uses |
+| `/file/avatar/:value` route | `apps/{erp,mes,academy}/app/routes/file+/avatar.$value.ts` | One line each: re-exports `generatedAvatarLoader` as the route's `loader`. Public: the route reads no data |
+| `Avatar` | `packages/react/src/Avatar.tsx` | If `src` is a generated-avatar value, renders `<img src={generatedAvatarUrl(value)}>`. The image is in the first HTML |
+| `GeneratedAvatarPicker` | `apps/erp/app/modules/account/ui/Profile/GeneratedAvatarPicker.tsx` | Modal with a style `Select`, a Background row, a grid of `GeneratedAvatarPreview` options, a Shuffle button and the credit for the selected style |
| `avatarSrc` + app `Avatar` wrappers | `packages/utils/src/avatar.ts`, `apps/{erp,mes,academy}/app/components/Avatar.tsx` | `avatarSrc` passes a generated-avatar value through as `src` and turns a storage path into a URL. The 3 wrappers call it |
### Rendering options
@@ -88,20 +91,33 @@ first and need no change. A background never changes the face. Rendered
avatars sit in one cache, capped at 300 and evicted least recently used,
because a drag in the color picker makes a new value at each step.
-A style definition is 10 KB to 370 KB of JSON, and `Avatar` renders on every
-page. So `STYLE_LOADERS` imports each style with a dynamic `import()`, and the
-bundler makes each one a separate chunk. The browser fetches a style the first
-time it shows an avatar in that style. The DiceBear core (about 25 KB gzipped)
-loads the same way, with the first style, so a page with no generated avatar
-downloads none of it.
+`Avatar` and the picker draw in different places:
-`useGeneratedAvatar` reads the state through `useSyncExternalStore`:
+| Where | Draws on | Why |
+|-------|----------|-----|
+| `Avatar` (every page) | The server. `<img src="/file/avatar/:value?v=1">`; the route answers `Cache-Control: public, max-age=31536000, immutable` | The image is in the first HTML, so the browser fetches it while the page loads. A refresh reads it from the browser cache. No DiceBear code reaches the page |
+| `GeneratedAvatarPreview` (the picker) | The browser | A color drag or a shuffle makes a new value per step, too fast to fetch from the server |
-| State | When | `Avatar` shows |
-|-------|------|----------------|
-| `loading` | The server render, and the browser until the style arrives | A plain `bg-muted` circle. The initials do not flash |
+`GENERATED_AVATAR_RENDER_VERSION` is the `v` in every URL. Bump it when the
+same value would draw a different picture: a DiceBear upgrade, or a change to
+the rendering options. Without a bump, browsers keep the old image.
+
+In the browser, a style definition is 10 KB to 370 KB of JSON. `STYLE_LOADERS`
+imports each style with a dynamic `import()`, and the bundler makes each one a
+separate chunk. The DiceBear core (about 25 KB gzipped) loads with the first
+style. The imports have no `json` import attribute: the browser rejects one,
+because Vite serves the JSON as JavaScript. The server instead bundles
+`@dicebear/styles` (`ssrNoExternal` in each app's `vite.config.ts`), because
+Node refuses a package's JSON without the attribute.
+
+`useGeneratedAvatar` reads the picker preview's state through
+`useSyncExternalStore`:
+
+| State | When | `GeneratedAvatarPreview` shows |
+|-------|------|--------------------------------|
+| `loading` | The server render, and the browser until the style arrives | A plain `bg-muted` circle |
| `ready` | The style is loaded | The data URI |
-| `failed` | The style chunk did not load | The initials. The next avatar that mounts tries the load again |
+| `failed` | The style chunk did not load | The plain circle. The next preview that mounts tries the load again |
The 10 styles fall into 2 groups. `generatedAvatarClassName` picks the classes:
@@ -199,7 +215,9 @@ style is under the grid.
|------|----------|------------|
| A list with many avatars generates many SVGs | Low | A module-level cache keys each data URI by value, so each value generates once per page load |
| A large style definition slows the first page | Low | Each style is its own chunk, fetched only when an avatar in that style shows. Notionists is the largest at 370 KB of JSON |
-| The DiceBear core enlarges every page | Med | `Avatar` is in every app shell, and the core is about 25 KB gzipped. It is never imported statically: it loads with the first style (`import()`). A split bundle shows the renderer entry at 2.5 KB |
+| DiceBear code enlarges every page | Med | `Avatar` imports only `generatedAvatarImage.ts`. A split bundle of `Avatar.tsx` is one 3.4 KB file with no DiceBear reference; the core and the 10 styles are chunks behind the picker only |
+| A CDN does not cache the avatar route | Low | `Cache-Control` has `max-age`, so browsers cache it. A CDN may also need `s-maxage` to serve it without running the function. Not yet checked on a deployed preview |
+| A JSON import attribute is added back | Med | The browser rejects it and the picker goes grey. A unit test fails if any style `import()` has a second argument |
| Non-React code reads `avatarUrl` as a storage path | Low | A repo search finds no non-React reader. The Jira type and the workflow catalog list only the column name |
| An invite of an existing user overwrites the avatar | Low | `createUser` runs only on the new-user branch, and no longer sends `avatarUrl` |
| CC BY 4.0 credit missing | Med | The picker shows the credit. Self-review checks it |
@@ -223,4 +241,7 @@ style is under the grid.
- 2026-10-08: Line-art avatars no longer invert on the light theme (user request). They are black lines on white in both themes.
- 2026-10-08: Background color picker added (user request). The value gains an optional `:<rrggbb>` segment; old values still parse. The avatar cache is now a capped LRU.
- 2026-10-08: Self-review 3 fixes. The DiceBear core loads with the first style, not on every page. `generatedAvatarClassName` and `avatarSrc` replace inline logic and have tests. The profile action has a test for the save-then-delete order. Two lessons added to `.ai/lessons.md`.
+- 2026-10-08: Server-drawn avatars (user request, refresh was slow). `Avatar` renders a generated value as `<img src="/file/avatar/:value?v=1">`; each app serves that route with `generatedAvatarLoader` (`@carbon/react/GeneratedAvatar`), which draws the SVG on the server and caches it for a year as immutable. The avatar is in the first HTML instead of waiting for hydration and two client downloads. The picker keeps drawing previews in the browser (`GeneratedAvatarPreview`). `GENERATED_AVATAR_RENDER_VERSION` is in every URL; bump it when the drawing changes.
+- 2026-10-08: Fix: picker previews stayed grey. The style imports had a JSON import attribute for the server, which the browser rejected. The attribute is gone; each app's `vite.config.ts` bundles `@dicebear/styles` into the server build instead.
+- 2026-10-08: Self-review 4. `generatedAvatarUrl` and `generatedAvatarClassName` moved to `generatedAvatarImage.ts`, so `Avatar` no longer bundles the renderer. A test guards against JSON import attributes. The spec now describes the route.
- 2026-10-08: Implemented (uncommitted). The picker lives in the ERP account module. The account reference doc (`docs/content/docs/reference/account.mdx`) describes the new Photo behavior.
diff --git a/apps/academy/app/routes/file+/avatar.$value.ts b/apps/academy/app/routes/file+/avatar.$value.ts
new file mode 100644
index 0000000000..df8e565f7a
--- /dev/null
+++ b/apps/academy/app/routes/file+/avatar.$value.ts
@@ -0,0 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// /file/avatar/:value — a generated avatar drawn on the server as a cached SVG.
+// `Avatar` (@carbon/react) points <img> here; the loader is shared by every app.
+export { generatedAvatarLoader as loader } from "@carbon/react/GeneratedAvatar";
diff --git a/apps/academy/vite.config.ts b/apps/academy/vite.config.ts
index 4879cd3c11..2c75ddf715 100644
--- a/apps/academy/vite.config.ts
+++ b/apps/academy/vite.config.ts
@@ -35,6 +35,8 @@ export default defineConfig(({ isSsrBuild }) => ({
"react-icons",
"react-phone-number-input",
"tailwind-merge",
+ // Avatar styles are JSON loaded with import(); see apps/erp/vite.config.ts.
+ "@dicebear/styles",
],
},
server: {
diff --git a/apps/erp/app/modules/account/ui/Profile/GeneratedAvatarPicker.tsx b/apps/erp/app/modules/account/ui/Profile/GeneratedAvatarPicker.tsx
index 3cfcd7a754..0f62d77497 100644
--- a/apps/erp/app/modules/account/ui/Profile/GeneratedAvatarPicker.tsx
+++ b/apps/erp/app/modules/account/ui/Profile/GeneratedAvatarPicker.tsx
@@ -3,7 +3,6 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import {
- Avatar,
Button,
cn,
HStack,
@@ -20,6 +19,7 @@ import {
SelectTrigger,
SelectValue
} from "@carbon/react";
+import { GeneratedAvatarPreview } from "@carbon/react/GeneratedAvatar";
import type { GeneratedAvatarStyle } from "@carbon/utils";
import {
DEFAULT_GENERATED_AVATAR_STYLE,
@@ -260,7 +260,9 @@ const GeneratedAvatarPicker = ({
isSelected ? "ring-primary" : "hover:ring-border"
)}
>
- <Avatar size="lg" src={valueOf(seed)} />
+ {/* Drawn in the browser: a color drag makes a new value per
+ step, too fast to fetch each one from the server. */}
+ <GeneratedAvatarPreview size="lg" value={valueOf(seed)} />
</button>
);
})}
diff --git a/apps/erp/app/routes/file+/avatar.$value.ts b/apps/erp/app/routes/file+/avatar.$value.ts
new file mode 100644
index 0000000000..df8e565f7a
--- /dev/null
+++ b/apps/erp/app/routes/file+/avatar.$value.ts
@@ -0,0 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// /file/avatar/:value — a generated avatar drawn on the server as a cached SVG.
+// `Avatar` (@carbon/react) points <img> here; the loader is shared by every app.
+export { generatedAvatarLoader as loader } from "@carbon/react/GeneratedAvatar";
diff --git a/apps/erp/vite.config.ts b/apps/erp/vite.config.ts
index 2bd5aced0b..66caef0860 100644
--- a/apps/erp/vite.config.ts
+++ b/apps/erp/vite.config.ts
@@ -79,6 +79,15 @@ export default defineConfig(({ command, isSsrBuild, mode }) => {
* Bundling it lets each importer keep its own version.
*/
"zustand",
+ /**
+ * @carbon/react imports each avatar style's JSON with a dynamic import().
+ * Externalized, Node loads that JSON natively and refuses it without an
+ * import attribute (ERR_IMPORT_ATTRIBUTE_MISSING), so /file/avatar fails.
+ * The attribute cannot go in the source: Vite passes it to the browser,
+ * which then rejects the JSON it serves as JavaScript. Bundled, Vite turns
+ * the JSON into a module on both sides.
+ */
+ "@dicebear/styles",
];
return {
diff --git a/apps/mes/app/routes/file+/avatar.$value.ts b/apps/mes/app/routes/file+/avatar.$value.ts
new file mode 100644
index 0000000000..df8e565f7a
--- /dev/null
+++ b/apps/mes/app/routes/file+/avatar.$value.ts
@@ -0,0 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// /file/avatar/:value — a generated avatar drawn on the server as a cached SVG.
+// `Avatar` (@carbon/react) points <img> here; the loader is shared by every app.
+export { generatedAvatarLoader as loader } from "@carbon/react/GeneratedAvatar";
diff --git a/apps/mes/vite.config.ts b/apps/mes/vite.config.ts
index 9e9bcedbd1..449818f83c 100644
--- a/apps/mes/vite.config.ts
+++ b/apps/mes/vite.config.ts
@@ -55,6 +55,15 @@ export default defineConfig(({ command, mode, isSsrBuild }) => {
* Bundling it lets each importer keep its own version.
*/
"zustand",
+ /**
+ * @carbon/react imports each avatar style's JSON with a dynamic import().
+ * Externalized, Node loads that JSON natively and refuses it without an
+ * import attribute (ERR_IMPORT_ATTRIBUTE_MISSING), so /file/avatar fails.
+ * The attribute cannot go in the source: Vite passes it to the browser,
+ * which then rejects the JSON it serves as JavaScript. Bundled, Vite turns
+ * the JSON into a module on both sides.
+ */
+ "@dicebear/styles",
];
return {
diff --git a/packages/react/AGENTS.md b/packages/react/AGENTS.md
index a5945ecb62..a2daa108ad 100644
--- a/packages/react/AGENTS.md
+++ b/packages/react/AGENTS.md
@@ -49,7 +49,7 @@ import { Button, Card, HStack, VStack, IconButton, cn } from "@carbon/react";
- **Data**: `Table` (TanStack), chart components via sub-exports (`@carbon/react/Chart`)
- **Rich text**: `@carbon/react/Editor` and `@carbon/react/RichText` (wraps `@carbon/tiptap`)
- **Error boundary**: `@carbon/react/ErrorBoundary` — `RouteErrorBoundary` (exported as `ErrorBoundary` from a module layout so a failed loader shows inside the app shell; it shows the status code and, for a 4xx, the message the server threw — `routeErrorCopy` — so throw a `Response` whose body says what was wrong. A 5xx or thrown `Error` gets generic copy) and `RootErrorBoundary` (drop-in root `ErrorBoundary` for RR v7 that maps 404 / other HTTP / thrown `Error` to a styled screen) plus its parts (`ErrorScreen`, `GlitchHeading`, `StatusReadout`, `MagneticLink`, `NoiseOverlay`). Wrap it in the app's `Document` and pass `env` so `window.env` is set (the client crashes hydration otherwise). Copy is intentionally hardcoded English, not i18n.
-- **Avatar**: `src` may be a URL or a generated-avatar value from `user.avatarUrl` (`dicebear:<style>:<seed>[:<rrggbb>]`; the styles and value helpers are in `@carbon/utils` `avatar.ts`). It renders that in the browser with DiceBear 10 (`utils/generatedAvatar.ts`). Nothing from DiceBear is imported statically — the core (about 25 KB gzipped) and each style's JSON definition load with `import()` the first time an avatar needs them (`STYLE_LOADERS`, typed `Record<GeneratedAvatarStyle, …>` so a new style without a loader fails typecheck); keep it that way, `Avatar` is in every app shell. `useGeneratedAvatar` reads the state through `useSyncExternalStore`: `loading` on the server and until the chunks arrive (a plain `bg-muted` circle, no initials flash), `failed` falls back to initials. `generatedAvatarClassName(style)` picks the image classes: line-art styles on white (`bg-white`) in both themes, color styles on `bg-muted`. A value's optional background goes to DiceBear as `backgroundColor`; on a dark one (`isDarkBackground`, WCAG contrast) the styles that draw lines straight onto the background (`INK_OPTIONS`: Croodles Neutral, Notionists Neutral, Lorelei Neutral) get white ink. Rendered avatars sit in one LRU cache capped at `MAX_CACHED_AVATARS`, since a picker drag produces a new value per step. The app `Avatar` wrappers turn a stored value into `src` with `avatarSrc` (`@carbon/utils`); new users get a Croodles Neutral avatar from the column default
+- **Avatar**: `src` may be a URL or a generated-avatar value from `user.avatarUrl` (`dicebear:<style>:<seed>[:<rrggbb>]`; the styles and value helpers are in `@carbon/utils` `avatar.ts`). A generated value renders as a plain `<img>` of `generatedAvatarUrl(value)` (`utils/generatedAvatarImage.ts`, which `Avatar` imports instead of the renderer so no bundle that shows an avatar carries DiceBear) — `/file/avatar/:value?v=<GENERATED_AVATAR_RENDER_VERSION>` — so it is in the server-rendered HTML and needs no client JavaScript. Every app (ERP, MES, academy) serves that path with a one-line route re-exporting `generatedAvatarLoader` from `@carbon/react/GeneratedAvatar`: it draws the SVG on the server with DiceBear 10 and answers `Cache-Control: public, max-age=31536000, immutable`, so a refresh reads it from the browser cache. **Bump `GENERATED_AVATAR_RENDER_VERSION` whenever the same value would draw differently** (a DiceBear upgrade, a change to the rendering options), or browsers keep the old image. The avatar picker draws in the browser instead (`GeneratedAvatarPreview`, `useGeneratedAvatar`), because a color drag makes a new value per step; there the DiceBear core and each style's JSON load with `import()` (`STYLE_LOADERS`, typed `Record<GeneratedAvatarStyle, …>`), never with a `with: { type: "json" }` attribute (Vite passes it to the browser, which rejects the JSON Vite serves as JavaScript, and the picker stays grey); the server side instead bundles `@dicebear/styles` through `ssrNoExternal` in each app's `vite.config.ts`, because Node refuses a package's JSON without the attribute. `generatedAvatarClassName(style)` picks the image classes: line-art styles on white (`bg-white`) in both themes, color styles on `bg-muted`. A value's optional background goes to DiceBear as `backgroundColor`; on a dark one (`isDarkBackground`, WCAG contrast) the styles that draw lines straight onto the background (`INK_OPTIONS`) get white ink. The app `Avatar` wrappers turn a stored value into `src` with `avatarSrc` (`@carbon/utils`); new users get a Croodles Neutral avatar from the column default
- **Polish**: shadows over borders, `tabular-nums` for dynamic numbers, `active:scale-[0.98]` on pressables, `text-balance`/`text-pretty` for text wrapping
## Cross-References
diff --git a/packages/react/package.json b/packages/react/package.json
index 3d67a5f5c9..f10d402315 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -113,6 +113,7 @@
"./Editor": "./src/Editor/index.ts",
"./ErrorBoundary": "./src/ErrorBoundary/index.ts",
"./FunnelChart": "./src/FunnelChart.tsx",
+ "./GeneratedAvatar": "./src/GeneratedAvatar.tsx",
"./HTML": "./src/HTML.tsx",
"./RichText": "./src/RichText/index.ts",
"./VariableText": "./src/VariableText/index.ts"
diff --git a/packages/react/src/Avatar.tsx b/packages/react/src/Avatar.tsx
index 26c386e7dc..74bef20845 100644
--- a/packages/react/src/Avatar.tsx
+++ b/packages/react/src/Avatar.tsx
@@ -25,8 +25,8 @@ import {
import { cn } from "./utils/cn";
import {
generatedAvatarClassName,
- useGeneratedAvatar
-} from "./utils/generatedAvatar";
+ generatedAvatarUrl
+} from "./utils/generatedAvatarImage";
export const avatarVariants = cva(
"flex flex-shrink-0 overflow-hidden rounded-full items-center justify-center font-medium transition-transform duration-200 ease-in-out",
@@ -63,14 +63,11 @@ const Avatar = forwardRef<HTMLSpanElement, AvatarProps>(
({ className, name, src, size, children, ...props }, ref) => {
const isGroup = !!useAvatarGroupContext()?.limit;
const avatarInitials = getInitials(name ?? "");
- // `src` may be a generated-avatar value from `user.avatarUrl` rather than a URL.
+ // `src` may be a generated-avatar value from `user.avatarUrl` rather than a
+ // URL. The app draws that on the server (`/file/avatar/:value`), so it is a
+ // plain image in the first HTML, cached by the browser after one load.
const generated = useMemo(() => parseGeneratedAvatar(src), [src]);
- const generatedState = useGeneratedAvatar(generated ? src : undefined);
- const imageSrc = !generated
- ? src
- : generatedState.status === "ready"
- ? generatedState.src
- : undefined;
+ const imageSrc = generated && src ? generatedAvatarUrl(src) : src;
// Remember which source failed, so a new `src` (a changed avatar) is tried.
const [failedSrc, setFailedSrc] = useState<string>();
const error = imageSrc !== undefined && imageSrc === failedSrc;
@@ -79,23 +76,6 @@ const Avatar = forwardRef<HTMLSpanElement, AvatarProps>(
const background = colorValue?.background;
const color = colorValue?.color;
- // A generated avatar whose style is still loading (or the server render):
- // a plain circle, so the initials do not flash before the avatar. A style
- // that failed to load falls through to the initials.
- if (generated && generatedState.status === "loading") {
- return (
- <span
- className={cn(
- avatarVariants({ size, isGroup }),
- "bg-muted",
- className
- )}
- {...props}
- ref={ref}
- />
- );
- }
-
return imageSrc && !error ? (
<img
className={cn(
diff --git a/packages/react/src/GeneratedAvatar.tsx b/packages/react/src/GeneratedAvatar.tsx
new file mode 100644
index 0000000000..f6e3295628
--- /dev/null
+++ b/packages/react/src/GeneratedAvatar.tsx
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { getLogger } from "@carbon/logger";
+import { parseGeneratedAvatar } from "@carbon/utils";
+import type { VariantProps } from "class-variance-authority";
+import type { LoaderFunctionArgs } from "react-router";
+import { avatarVariants } from "./Avatar";
+import { cn } from "./utils/cn";
+import {
+ renderGeneratedAvatarSvg,
+ useGeneratedAvatar
+} from "./utils/generatedAvatar";
+import { generatedAvatarClassName } from "./utils/generatedAvatarImage";
+
+const log = getLogger("react", "generated-avatar-route");
+
+const SVG_HEADERS = {
+ "Content-Type": "image/svg+xml; charset=utf-8",
+ // The same value always draws the same picture, and the URL carries
+ // GENERATED_AVATAR_RENDER_VERSION, so a response never goes stale.
+ "Cache-Control": "public, max-age=31536000, immutable",
+ "X-Content-Type-Options": "nosniff",
+ // Opened directly, an SVG is a document; it may draw, nothing else.
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'"
+};
+
+/**
+ * The loader of each app's `/file/avatar/:value` route: renders a generated
+ * avatar as an SVG on the server. Public by design: it reads no data, and a
+ * value is only a style, a seed and a color. Each app's route file re-exports
+ * it (`export { generatedAvatarLoader as loader } from "@carbon/react/GeneratedAvatar"`).
+ */
+export async function generatedAvatarLoader({ params }: LoaderFunctionArgs) {
+ const value = params.value ?? "";
+ if (!parseGeneratedAvatar(value)) {
+ return new Response("Not a generated avatar", { status: 404 });
+ }
+
+ const svg = await renderGeneratedAvatarSvg(value);
+ if (!svg) {
+ log.error("Failed to render a generated avatar", { value });
+ return new Response("The avatar could not be drawn", { status: 500 });
+ }
+ return new Response(svg, { headers: SVG_HEADERS });
+}
+
+type GeneratedAvatarPreviewProps = VariantProps<typeof avatarVariants> & {
+ value: string;
+ className?: string;
+};
+
+/**
+ * A generated avatar drawn in the browser, for previews whose value changes
+ * faster than it is worth fetching — the avatar picker, where a color drag or
+ * a shuffle makes a new value per step. Everywhere else, `Avatar` loads the
+ * server-drawn SVG instead.
+ */
+export function GeneratedAvatarPreview({
+ value,
+ size,
+ className
+}: GeneratedAvatarPreviewProps) {
+ const parsed = parseGeneratedAvatar(value);
+ const state = useGeneratedAvatar(parsed ? value : undefined);
+ const classes = cn(
+ avatarVariants({ size }),
+ "border",
+ parsed ? generatedAvatarClassName(parsed.style) : "bg-muted",
+ className
+ );
+
+ if (state.status !== "ready") {
+ return <span className={cn(classes, "bg-muted")} aria-hidden />;
+ }
+ return <img className={cn(classes, "object-cover")} alt="" src={state.src} />;
+}
diff --git a/packages/react/src/__tests__/Avatar.test.tsx b/packages/react/src/__tests__/Avatar.test.tsx
index b90b737290..c6f4ca5df3 100644
--- a/packages/react/src/__tests__/Avatar.test.tsx
+++ b/packages/react/src/__tests__/Avatar.test.tsx
@@ -6,17 +6,19 @@ import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { Avatar } from "../Avatar";
+import { GENERATED_AVATAR_RENDER_VERSION } from "../utils/generatedAvatarImage";
describe("Avatar", () => {
- it("renders a generated avatar as a plain placeholder on the server", () => {
- // The style loads in the browser; the server render (and hydration) shows
- // a neutral circle, never the initials, so nothing flashes.
- const html = renderToStaticMarkup(
- <Avatar name="Jane Doe" src="dicebear:croodles-neutral:seed-one" />
+ it("renders a generated avatar as an image of its server-drawn SVG", () => {
+ // In the first HTML, before any JavaScript runs: the browser fetches the
+ // avatar while the page loads, and caches it for the next refresh.
+ const value = "dicebear:croodles-neutral:seed-one:1e3a8a";
+ const html = renderToStaticMarkup(<Avatar name="Jane Doe" src={value} />);
+ expect(html).toContain(
+ `src="/file/avatar/${encodeURIComponent(value)}?v=${GENERATED_AVATAR_RENDER_VERSION}"`
);
- expect(html).not.toContain("<img");
+ expect(html).toContain("bg-white");
expect(html).not.toContain("JD");
- expect(html).toContain("bg-muted");
});
it("renders a URL as it is, without the generated-avatar styling", () => {
diff --git a/packages/react/src/__tests__/generatedAvatar.test.ts b/packages/react/src/__tests__/generatedAvatar.test.ts
index 3ee1ff06e8..8f70907976 100644
--- a/packages/react/src/__tests__/generatedAvatar.test.ts
+++ b/packages/react/src/__tests__/generatedAvatar.test.ts
@@ -2,14 +2,15 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { readFileSync } from "node:fs";
import { GENERATED_AVATAR_STYLES } from "@carbon/utils";
import { describe, expect, it, vi } from "vitest";
import {
- generatedAvatarClassName,
generatedAvatarDataUri,
isDarkBackground,
loadGeneratedAvatarStyle
} from "../utils/generatedAvatar";
+import { generatedAvatarClassName } from "../utils/generatedAvatarImage";
const svgOf = (uri: string | undefined) =>
decodeURIComponent((uri ?? "").replace(/^data:image\/svg\+xml;[^,]*,/, ""));
@@ -117,4 +118,22 @@ describe("generatedAvatarDataUri", () => {
}
});
});
+
+ it("never passes import attributes to a style's import()", () => {
+ // `import(x, { with: { type: "json" } })` makes the server route work but
+ // the browser rejects it — Vite serves the JSON as JavaScript — and every
+ // picker preview stayed grey. The server bundles @dicebear/styles instead
+ // (`ssrNoExternal` in each app's vite.config.ts). See .ai/lessons.md.
+ const source = readFileSync(
+ new URL("../utils/generatedAvatar.ts", import.meta.url),
+ "utf8"
+ );
+ const styleImports = source.match(
+ /import\(\s*["']@dicebear\/styles\/[^)]*\)/g
+ );
+ expect(styleImports).toHaveLength(10);
+ for (const call of styleImports ?? []) {
+ expect(call).toMatch(/^import\(\s*["'][^"']+["']\s*\)$/);
+ }
+ });
});
diff --git a/packages/react/src/__tests__/generatedAvatarRoute.test.ts b/packages/react/src/__tests__/generatedAvatarRoute.test.ts
new file mode 100644
index 0000000000..6ed81bf809
--- /dev/null
+++ b/packages/react/src/__tests__/generatedAvatarRoute.test.ts
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import { generatedAvatarLoader } from "../GeneratedAvatar";
+import { renderGeneratedAvatarSvg } from "../utils/generatedAvatar";
+import {
+ GENERATED_AVATAR_RENDER_VERSION,
+ generatedAvatarUrl
+} from "../utils/generatedAvatarImage";
+
+const load = (value: string) =>
+ generatedAvatarLoader({ params: { value } } as never) as Promise<Response>;
+
+describe("generatedAvatarLoader (/file/avatar/:value)", () => {
+ it("serves the SVG, cacheable forever", async () => {
+ const response = await load("dicebear:voxel-art:seed-route:3b82f6");
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Content-Type")).toBe(
+ "image/svg+xml; charset=utf-8"
+ );
+ expect(response.headers.get("Cache-Control")).toBe(
+ "public, max-age=31536000, immutable"
+ );
+ expect(response.headers.get("Content-Security-Policy")).toContain(
+ "default-src 'none'"
+ );
+ const svg = await response.text();
+ expect(svg.startsWith("<svg")).toBe(true);
+ expect(svg.toLowerCase()).toContain("#3b82f6");
+ });
+
+ it("draws the same picture the browser preview draws", async () => {
+ const value = "dicebear:lorelei:seed-same";
+ const response = await load(value);
+ expect(await response.text()).toBe(await renderGeneratedAvatarSvg(value));
+ });
+
+ it("returns 404 for anything that is not a generated avatar", async () => {
+ for (const value of [
+ "user-1.webp",
+ "dicebear:adventurer:abc",
+ "dicebear:croodles-neutral:../../x",
+ ""
+ ]) {
+ expect((await load(value)).status).toBe(404);
+ }
+ });
+});
+
+describe("generatedAvatarUrl", () => {
+ it("encodes the value and carries the render version", () => {
+ expect(generatedAvatarUrl("dicebear:planets:seed-1:ffd5dc")).toBe(
+ `/file/avatar/dicebear%3Aplanets%3Aseed-1%3Affd5dc?v=${GENERATED_AVATAR_RENDER_VERSION}`
+ );
+ });
+});
diff --git a/packages/react/src/utils/generatedAvatar.ts b/packages/react/src/utils/generatedAvatar.ts
index fdbbba3f24..dbcb10b78c 100644
--- a/packages/react/src/utils/generatedAvatar.ts
+++ b/packages/react/src/utils/generatedAvatar.ts
@@ -10,10 +10,14 @@ import { useEffect, useSyncExternalStore } from "react";
const log = getLogger("react", "generated-avatar");
-// One loader per style. A style definition is 10–370 KB of JSON and the Avatar
-// renders on every page, so each style is its own chunk, fetched the first time
-// an avatar in that style is shown. `Record` makes a style in
-// GENERATED_AVATAR_STYLES without a loader a type error.
+// One loader per style. A style definition is 10–370 KB of JSON, so each
+// style is its own chunk, fetched the first time something renders it.
+// No `json` import attribute: Vite passes it through to the browser, which then
+// rejects the style (Vite serves it as JavaScript) — the picker stayed grey.
+// The server side instead bundles @dicebear/styles (`ssrNoExternal` in each
+// app's vite.config.ts), because Node refuses a package's JSON without one.
+// `Record` makes a style in GENERATED_AVATAR_STYLES without a loader a type
+// error.
const STYLE_LOADERS: Record<GeneratedAvatarStyle, () => Promise<unknown>> = {
"croodles-neutral": () => import("@dicebear/styles/croodles-neutral.json"),
notionists: () => import("@dicebear/styles/notionists.json"),
@@ -28,33 +32,6 @@ const STYLE_LOADERS: Record<GeneratedAvatarStyle, () => Promise<unknown>> = {
planets: () => import("@dicebear/styles/planets.json")
};
-/**
- * Styles drawn as black lines on a transparent background. `Avatar` puts them
- * on white in both themes. The rest are full color with their own background.
- */
-const LINE_ART_STYLES: ReadonlySet<GeneratedAvatarStyle> = new Set([
- "croodles-neutral",
- "notionists",
- "notionists-neutral",
- "lorelei",
- "lorelei-neutral"
-]);
-
-function isLineArtStyle(style: GeneratedAvatarStyle) {
- return LINE_ART_STYLES.has(style);
-}
-
-/**
- * The classes `Avatar` puts on a generated avatar's image. Line-art styles are
- * black lines on transparent, so they sit on white in both themes; color
- * styles keep their own colors. A chosen background paints over either.
- */
-export function generatedAvatarClassName(style: GeneratedAvatarStyle) {
- return isLineArtStyle(style)
- ? "bg-white border-black/10"
- : "bg-muted border-transparent";
-}
-
/**
* The line-color options of the styles that draw lines straight onto the
* background. On a dark background they switch to white so the face stays
@@ -129,6 +106,32 @@ function remember(value: string, state: ReadyState) {
}
}
+function drawAvatar(
+ dicebear: DiceBearCore,
+ style: Style,
+ avatar: NonNullable<ReturnType<typeof parseGeneratedAvatar>>
+) {
+ return new dicebear.Avatar(style, {
+ seed: avatar.seed,
+ ...backgroundOptions(avatar.style, avatar.background)
+ });
+}
+
+/**
+ * The SVG markup for a generated-avatar value, or `null` when the value is not
+ * one or its style cannot load. Used on the server by `generatedAvatarLoader`.
+ */
+export async function renderGeneratedAvatarSvg(
+ value: string
+): Promise<string | null> {
+ const parsed = parseGeneratedAvatar(value);
+ if (!parsed) return null;
+ await loadGeneratedAvatarStyle(parsed.style);
+ const style = styles.get(parsed.style);
+ if (!style || !core) return null;
+ return drawAvatar(core, style, parsed).toString();
+}
+
function renderReadyState(value: string): ReadyState | undefined {
const cached = rendered.get(value);
if (cached) {
@@ -144,10 +147,7 @@ function renderReadyState(value: string): ReadyState | undefined {
const state: ReadyState = {
status: "ready",
- src: new core.Avatar(style, {
- seed: parsed.seed,
- ...backgroundOptions(parsed.style, parsed.background)
- }).toDataUri()
+ src: drawAvatar(core, style, parsed).toDataUri()
};
remember(value, state);
return state;
diff --git a/packages/react/src/utils/generatedAvatarImage.ts b/packages/react/src/utils/generatedAvatarImage.ts
new file mode 100644
index 0000000000..2030f5d410
--- /dev/null
+++ b/packages/react/src/utils/generatedAvatarImage.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// What `Avatar` needs to show a generated avatar: the URL of its server-drawn
+// SVG and the classes of the <img>. Kept apart from `generatedAvatar.ts` on
+// purpose — `Avatar` renders on every page, and importing the renderer would
+// pull its style chunks and hooks into every bundle, client and server.
+
+import type { GeneratedAvatarStyle } from "@carbon/utils";
+
+/**
+ * Bump when the same value would draw a different picture: a DiceBear
+ * upgrade, or a change to the rendering options in `generatedAvatar.ts`. It
+ * is part of every avatar URL, and those responses are cached forever, so
+ * without a bump browsers keep the old image.
+ */
+export const GENERATED_AVATAR_RENDER_VERSION = "1";
+
+/**
+ * Where `Avatar` loads a generated avatar from: each app serves it from
+ * `/file/avatar/:value` (`generatedAvatarLoader`, `@carbon/react/GeneratedAvatar`).
+ * Same-origin and relative, so it works in the ERP, MES and academy alike.
+ */
+export function generatedAvatarUrl(value: string) {
+ return `/file/avatar/${encodeURIComponent(value)}?v=${GENERATED_AVATAR_RENDER_VERSION}`;
+}
+
+/**
+ * Styles drawn as black lines on a transparent background. `Avatar` puts them
+ * on white in both themes. The rest are full color with their own background.
+ */
+const LINE_ART_STYLES: ReadonlySet<GeneratedAvatarStyle> = new Set([
+ "croodles-neutral",
+ "notionists",
+ "notionists-neutral",
+ "lorelei",
+ "lorelei-neutral"
+]);
+
+function isLineArtStyle(style: GeneratedAvatarStyle) {
+ return LINE_ART_STYLES.has(style);
+}
+
+/**
+ * The classes `Avatar` puts on a generated avatar's image. Line-art styles are
+ * black lines on transparent, so they sit on white in both themes; color
+ * styles keep their own colors. A chosen background paints over either.
+ */
+export function generatedAvatarClassName(style: GeneratedAvatarStyle) {
+ return isLineArtStyle(style)
+ ? "bg-white border-black/10"
+ : "bg-muted border-transparent";
+}