Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(web): add custom bot avatar colors (#258)

Leo537e6585be0a
diff --git a/apps/web/src/components/onboarding/DesktopOnboarding.tsx b/apps/web/src/components/onboarding/DesktopOnboarding.tsx
index a8142a69e..49e3a1b39 100644
--- a/apps/web/src/components/onboarding/DesktopOnboarding.tsx
+++ b/apps/web/src/components/onboarding/DesktopOnboarding.tsx
@@ -42,10 +42,11 @@ import {
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { BotAvatarView } from "../roster/BotAvatarView";
+import { AvatarColorPicker } from "../roster/AvatarColorPicker";
import { BotPromptComposer } from "../roster/BotPromptComposer";
import { writeBotDraft } from "../roster/botDraftStore";
import { DEFAULT_BOT_RUNTIME_MODE } from "../roster/botSandbox";
-import { BLOB_COLORS, BLOB_SHAPES } from "../roster/roster.logic";
+import { BLOB_SHAPES } from "../roster/roster.logic";
import { useRosterStore } from "../roster/rosterStore";
import { useBotThreadRuntime } from "../roster/useBotThreadRuntime";
import {
@@ -540,23 +541,11 @@ function IdentityStep({
</div>
<div className="space-y-3">
<h2 className="text-center text-xs font-medium text-muted-foreground">Color</h2>
- <div className="mx-auto grid w-fit grid-cols-5 gap-3">
- {BLOB_COLORS.map((color) => (
- <button
- key={color}
- type="button"
- aria-label={`${color} avatar color`}
- aria-pressed={draft.avatar.color === color}
- onClick={() => onChange({ ...draft, avatar: { ...draft.avatar, color } })}
- className={`size-8 rounded-full border border-foreground/10 outline-none transition-shadow focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none ${
- draft.avatar.color === color
- ? "ring-2 ring-ring ring-offset-2 ring-offset-background"
- : ""
- }`}
- style={{ backgroundColor: color }}
- />
- ))}
- </div>
+ <AvatarColorPicker
+ className="mx-auto"
+ value={draft.avatar.color}
+ onChange={(color) => onChange({ ...draft, avatar: { ...draft.avatar, color } })}
+ />
</div>
</section>
{providerReadiness.status === "loading" ? (
diff --git a/apps/web/src/components/onboarding/desktopOnboarding.logic.test.ts b/apps/web/src/components/onboarding/desktopOnboarding.logic.test.ts
index 6af31a936..b9c1ce57f 100644
--- a/apps/web/src/components/onboarding/desktopOnboarding.logic.test.ts
+++ b/apps/web/src/components/onboarding/desktopOnboarding.logic.test.ts
@@ -158,6 +158,19 @@ describe("desktop onboarding", () => {
expect(parseDesktopOnboardingDraft(JSON.stringify(DEFAULT_DESKTOP_ONBOARDING_DRAFT))).toEqual(
DEFAULT_DESKTOP_ONBOARDING_DRAFT,
);
+ const customColorDraft = {
+ ...DEFAULT_DESKTOP_ONBOARDING_DRAFT,
+ avatar: { ...DEFAULT_DESKTOP_ONBOARDING_DRAFT.avatar, color: "#123ABC" },
+ };
+ expect(parseDesktopOnboardingDraft(JSON.stringify(customColorDraft))).toEqual(customColorDraft);
+ expect(
+ parseDesktopOnboardingDraft(
+ JSON.stringify({
+ ...DEFAULT_DESKTOP_ONBOARDING_DRAFT,
+ avatar: { ...DEFAULT_DESKTOP_ONBOARDING_DRAFT.avatar, color: "not-a-color" },
+ }),
+ ),
+ ).toBeNull();
expect(parseDesktopOnboardingDraft("not json")).toBeNull();
expect(
parseDesktopOnboardingDraft(
diff --git a/apps/web/src/components/onboarding/desktopOnboarding.logic.ts b/apps/web/src/components/onboarding/desktopOnboarding.logic.ts
index c072bc667..947291679 100644
--- a/apps/web/src/components/onboarding/desktopOnboarding.logic.ts
+++ b/apps/web/src/components/onboarding/desktopOnboarding.logic.ts
@@ -6,7 +6,7 @@ import {
} from "@t3tools/contracts";
import type { BotAvatar, BotBlobShape } from "../roster/types";
-import { BLOB_COLORS, BLOB_SHAPES } from "../roster/roster.logic";
+import { BLOB_SHAPES, isBotAvatarColor } from "../roster/roster.logic";
export const DESKTOP_ONBOARDING_STORAGE_KEY = "akeru:desktop-onboarding:v1";
export const DESKTOP_ONBOARDING_COMPLETED_STORAGE_KEY = "akeru:desktop-onboarding-completed:v1";
@@ -96,7 +96,7 @@ function isBlobShape(value: unknown): value is BotBlobShape {
}
function isBlobColor(value: unknown): value is string {
- return typeof value === "string" && BLOB_COLORS.includes(value);
+ return isBotAvatarColor(value);
}
const providerIds: readonly SubscriptionProviderId[] = [
diff --git a/apps/web/src/components/roster/AvatarColorPicker.tsx b/apps/web/src/components/roster/AvatarColorPicker.tsx
new file mode 100644
index 000000000..71b7eb07c
--- /dev/null
+++ b/apps/web/src/components/roster/AvatarColorPicker.tsx
@@ -0,0 +1,231 @@
+import { useEffect, useState, type KeyboardEvent, type PointerEvent } from "react";
+
+import { cn } from "../../lib/utils";
+import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
+import {
+ clampColorFraction,
+ formatColorFieldValueText,
+ hexToHsv,
+ hsvToHex,
+ type HsvColor,
+} from "./avatarColorPicker.logic";
+import { BLOB_COLORS, DEFAULT_BLOB_COLOR, isBotAvatarColor } from "./roster.logic";
+
+function ColorThumb({ color, left, top }: { color: string; left: string; top: string }) {
+ return (
+ <span
+ aria-hidden
+ className="pointer-events-none absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/60%)]"
+ style={{ backgroundColor: color, left, top }}
+ />
+ );
+}
+
+function pointerFraction(event: PointerEvent<HTMLDivElement>) {
+ const bounds = event.currentTarget.getBoundingClientRect();
+ return {
+ x: clampColorFraction((event.clientX - bounds.left) / bounds.width),
+ y: clampColorFraction((event.clientY - bounds.top) / bounds.height),
+ };
+}
+
+function ColorPickerPanel({
+ value,
+ onChange,
+}: {
+ value: string;
+ onChange: (color: string) => void;
+}) {
+ const [hsv, setHsv] = useState<HsvColor>(() => hexToHsv(value) ?? { h: 210, s: 0.5, v: 0.7 });
+ const [draft, setDraft] = useState<string | null>(null);
+
+ useEffect(() => {
+ const next = hexToHsv(value);
+ if (!next) return;
+ setHsv((current) => (next.s === 0 || next.v === 0 ? { ...next, h: current.h } : next));
+ setDraft(null);
+ }, [value]);
+
+ const commitHsv = (next: HsvColor) => {
+ setHsv(next);
+ setDraft(null);
+ onChange(hsvToHex(next));
+ };
+
+ const commitHex = (candidate: string) => {
+ const next = hexToHsv(candidate);
+ if (next) commitHsv(next);
+ else setDraft(null);
+ };
+
+ const updateField = (event: PointerEvent<HTMLDivElement>) => {
+ event.currentTarget.setPointerCapture(event.pointerId);
+ const { x, y } = pointerFraction(event);
+ commitHsv({ ...hsv, s: x, v: 1 - y });
+ };
+
+ const updateHue = (event: PointerEvent<HTMLDivElement>) => {
+ event.currentTarget.setPointerCapture(event.pointerId);
+ commitHsv({ ...hsv, h: pointerFraction(event).x * 360 });
+ };
+
+ const handleFieldKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ const step = event.shiftKey ? 0.1 : 0.02;
+ const next = { ...hsv };
+ if (event.key === "ArrowLeft") next.s = clampColorFraction(hsv.s - step);
+ else if (event.key === "ArrowRight") next.s = clampColorFraction(hsv.s + step);
+ else if (event.key === "ArrowUp") next.v = clampColorFraction(hsv.v + step);
+ else if (event.key === "ArrowDown") next.v = clampColorFraction(hsv.v - step);
+ else return;
+ event.preventDefault();
+ commitHsv(next);
+ };
+
+ const handleHueKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ const direction = event.key === "ArrowLeft" ? -1 : event.key === "ArrowRight" ? 1 : 0;
+ if (direction === 0) return;
+ event.preventDefault();
+ const step = event.shiftKey ? 30 : 4;
+ commitHsv({ ...hsv, h: (hsv.h + direction * step + 360) % 360 });
+ };
+
+ const color = hsvToHex(hsv);
+ const hueColor = hsvToHex({ h: hsv.h, s: 1, v: 1 });
+
+ return (
+ <div className="w-60 p-3">
+ <div
+ role="slider"
+ tabIndex={0}
+ aria-label="Saturation and brightness"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round(hsv.v * 100)}
+ aria-valuetext={formatColorFieldValueText(hsv, color)}
+ className="relative h-36 cursor-crosshair touch-none rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ style={{
+ backgroundColor: hueColor,
+ backgroundImage:
+ "linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent)",
+ }}
+ onKeyDown={handleFieldKeyDown}
+ onPointerDown={updateField}
+ onPointerMove={(event) => {
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) updateField(event);
+ }}
+ >
+ <ColorThumb color={color} left={`${hsv.s * 100}%`} top={`${(1 - hsv.v) * 100}%`} />
+ </div>
+
+ <div
+ role="slider"
+ tabIndex={0}
+ aria-label="Hue"
+ aria-valuemin={0}
+ aria-valuemax={360}
+ aria-valuenow={Math.round(hsv.h)}
+ className="relative mt-3 h-3 cursor-ew-resize touch-none rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ style={{
+ background: "linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)",
+ }}
+ onKeyDown={handleHueKeyDown}
+ onPointerDown={updateHue}
+ onPointerMove={(event) => {
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) updateHue(event);
+ }}
+ >
+ <ColorThumb color={hueColor} left={`${(hsv.h / 360) * 100}%`} top="50%" />
+ </div>
+
+ <label className="mt-3 flex items-center gap-2 text-xs text-muted-foreground">
+ Hex
+ <span className="flex h-8 flex-1 items-center rounded-md border border-input bg-background px-2 font-mono text-foreground focus-within:ring-2 focus-within:ring-ring">
+ #
+ <input
+ aria-label="Avatar color hex value"
+ className="min-w-0 flex-1 bg-transparent outline-none"
+ value={(draft ?? color).replace("#", "")}
+ maxLength={6}
+ spellCheck={false}
+ onChange={(event) => setDraft(event.currentTarget.value)}
+ onBlur={() => commitHex(draft ?? color)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ commitHex(draft ?? color);
+ } else if (event.key === "Escape") {
+ setDraft(null);
+ }
+ }}
+ />
+ </span>
+ </label>
+ </div>
+ );
+}
+
+export function AvatarColorPicker({
+ value,
+ onChange,
+ className,
+ label = "Avatar color",
+}: {
+ value: string;
+ onChange: (color: string) => void;
+ className?: string;
+ label?: string;
+}) {
+ const color = isBotAvatarColor(value) ? value.toUpperCase() : DEFAULT_BLOB_COLOR;
+ const presetSelected = BLOB_COLORS.includes(color);
+
+ return (
+ <div
+ role="group"
+ aria-label={label}
+ className={cn("flex flex-wrap items-center gap-2.5", className)}
+ >
+ {BLOB_COLORS.map((preset) => (
+ <button
+ key={preset}
+ type="button"
+ aria-label={`Use ${preset}`}
+ aria-pressed={color === preset}
+ onClick={() => onChange(preset)}
+ style={{ backgroundColor: preset }}
+ className={cn(
+ "size-8 cursor-pointer rounded-full border border-foreground/10 outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ color === preset && "ring-2 ring-ring ring-offset-2 ring-offset-background",
+ )}
+ />
+ ))}
+
+ <Popover>
+ <PopoverTrigger
+ render={
+ <button
+ type="button"
+ aria-label={`Choose a custom avatar color. Current color ${color}`}
+ aria-pressed={!presetSelected}
+ className={cn(
+ "size-8 cursor-pointer rounded-full border border-foreground/15 outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ !presetSelected && "ring-2 ring-ring ring-offset-2 ring-offset-background",
+ )}
+ style={{
+ background:
+ "conic-gradient(from 90deg, #ff3b30, #ffcc00, #34c759, #00c7be, #0a84ff, #bf5af2, #ff375f, #ff3b30)",
+ }}
+ />
+ }
+ />
+ <PopoverPopup
+ align="end"
+ sideOffset={8}
+ className="overflow-hidden"
+ viewportClassName="p-0 [--viewport-inline-padding:0px]"
+ >
+ <ColorPickerPanel value={color} onChange={onChange} />
+ </PopoverPopup>
+ </Popover>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/roster/AvatarPickerDialog.tsx b/apps/web/src/components/roster/AvatarPickerDialog.tsx
index 51a449320..748e404f5 100644
--- a/apps/web/src/components/roster/AvatarPickerDialog.tsx
+++ b/apps/web/src/components/roster/AvatarPickerDialog.tsx
@@ -12,6 +12,7 @@ import {
} from "../ui/dialog";
import { Switch } from "../ui/switch";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
+import { AvatarColorPicker } from "./AvatarColorPicker";
import { BotAvatarView } from "./BotAvatarView";
import {
ditherSeedForName,
@@ -20,7 +21,7 @@ import {
resolveUploadAvatar,
type UploadRendering,
} from "./dither.logic";
-import { BLOB_COLORS, BLOB_SHAPES, resolveBlobRendering } from "./roster.logic";
+import { BLOB_SHAPES, resolveBlobRendering } from "./roster.logic";
import type { Bot, BotAvatar, BotBlobShape } from "./types";
import { useSaveBotAvatar } from "./useServerRoster";
@@ -197,22 +198,7 @@ export function AvatarPickerDialog({
</button>
))}
</div>
- <div className="flex flex-wrap justify-center gap-2">
- {BLOB_COLORS.map((option) => (
- <button
- key={option}
- type="button"
- aria-label={option}
- aria-pressed={color === option}
- onClick={() => setColor(option)}
- style={{ backgroundColor: option }}
- className={cn(
- "size-7 cursor-pointer rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring",
- color === option && "ring-2 ring-ring ring-offset-2 ring-offset-background",
- )}
- />
- ))}
- </div>
+ <AvatarColorPicker className="mx-auto" value={color} onChange={setColor} />
</>
) : tab === "generate" ? (
<div className="flex h-40 flex-col items-center justify-center gap-3">
diff --git a/apps/web/src/components/roster/BotAvatarView.test.tsx b/apps/web/src/components/roster/BotAvatarView.test.tsx
index 9d3f36cf4..576a44c25 100644
--- a/apps/web/src/components/roster/BotAvatarView.test.tsx
+++ b/apps/web/src/components/roster/BotAvatarView.test.tsx
@@ -12,10 +12,19 @@ describe("BotAvatarView", () => {
expect(markup).toContain('class="bot-eyes"');
expect(markup).toContain('viewBox="-22 -18 44 36"');
expect(markup).toContain('data-bot-state="idle"');
+ expect(markup).toContain('fill="#0A0A0A"');
expect(markup).not.toContain("</text>");
expect(markup).not.toContain(">T</text>");
});
+ it("uses light eyes when the blob color is dark", () => {
+ const markup = renderToStaticMarkup(
+ <BotAvatarView name="Theo" avatar={{ kind: "blob", shape: "pill", color: "#141062" }} />,
+ );
+
+ expect(markup).toContain('fill="#FFFFFF"');
+ });
+
it("shortens the eyes while working", () => {
const idle = renderToStaticMarkup(
<BotAvatarView
diff --git a/apps/web/src/components/roster/BotAvatarView.tsx b/apps/web/src/components/roster/BotAvatarView.tsx
index b5e83177b..22dfd623f 100644
--- a/apps/web/src/components/roster/BotAvatarView.tsx
+++ b/apps/web/src/components/roster/BotAvatarView.tsx
@@ -2,7 +2,7 @@ import { useMemo, type CSSProperties } from "react";
import { cn } from "~/lib/utils";
import { generateDitherIdenticon, identiconPathData } from "./dither.logic";
-import { blinkDelayMs, resolveBlobRendering } from "./roster.logic";
+import { blinkDelayMs, resolveBlobEyeColor, resolveBlobRendering } from "./roster.logic";
import type { BotAvatar, BotBlobShape } from "./types";
/**
@@ -13,9 +13,6 @@ import type { BotAvatar, BotBlobShape } from "./types";
*/
export type BotAnimationState = "idle" | "working" | "needs-you" | "success";
-/** Eyes are always near-black, ink on the body. */
-const INK = "#0A0A0A";
-
/**
* Where the face sits on the 100×100 viewBox. Bottom-heavy shapes (triangle,
* drop) carry the face lower; small bodies (pill, cloud) shrink it a touch.
@@ -77,7 +74,7 @@ function BlobShape({ shape, color }: { shape: BotBlobShape; color: string }) {
* a focused face. Needs-you raises and spreads them. Success closes them into
* happy arcs.
*/
-function Eyes({ state }: { state: BotAnimationState }) {
+function Eyes({ state, color }: { state: BotAnimationState; color: string }) {
switch (state) {
case "working":
return (
@@ -89,7 +86,7 @@ function Eyes({ state }: { state: BotAnimationState }) {
height="10"
rx="4.5"
transform="rotate(14 -9 5)"
- fill={INK}
+ fill={color}
/>
<rect
x="4.5"
@@ -98,7 +95,7 @@ function Eyes({ state }: { state: BotAnimationState }) {
height="10"
rx="4.5"
transform="rotate(14 9 5)"
- fill={INK}
+ fill={color}
/>
</>
);
@@ -112,7 +109,7 @@ function Eyes({ state }: { state: BotAnimationState }) {
height="26"
rx="4.5"
transform="rotate(10 -11 0)"
- fill={INK}
+ fill={color}
/>
<rect
x="6.5"
@@ -121,7 +118,7 @@ function Eyes({ state }: { state: BotAnimationState }) {
height="26"
rx="4.5"
transform="rotate(10 11 0)"
- fill={INK}
+ fill={color}
/>
</>
);
@@ -130,14 +127,14 @@ function Eyes({ state }: { state: BotAnimationState }) {
<>
<path
d="M-17 1 Q-11 -9 -5 1"
- stroke={INK}
+ stroke={color}
strokeWidth="4"
strokeLinecap="round"
fill="none"
/>
<path
d="M5 1 Q11 -9 17 1"
- stroke={INK}
+ stroke={color}
strokeWidth="4"
strokeLinecap="round"
fill="none"
@@ -154,7 +151,7 @@ function Eyes({ state }: { state: BotAnimationState }) {
height="20"
rx="4.5"
transform="rotate(14 -9.5 0)"
- fill={INK}
+ fill={color}
/>
<rect
x="5"
@@ -163,7 +160,7 @@ function Eyes({ state }: { state: BotAnimationState }) {
height="20"
rx="4.5"
transform="rotate(14 9.5 0)"
- fill={INK}
+ fill={color}
/>
</>
);
@@ -174,7 +171,15 @@ function Eyes({ state }: { state: BotAnimationState }) {
* The face. A nested svg owns the blink so scaleY uses that svg's viewBox,
* not a <g> fill-box that collapses as the eyes close and strobes the avatar.
*/
-function Face({ shape, state }: { shape: BotBlobShape; state: BotAnimationState }) {
+function Face({
+ shape,
+ state,
+ color,
+}: {
+ shape: BotBlobShape;
+ state: BotAnimationState;
+ color: string;
+}) {
const { y, scale } = FACE_LAYOUT[shape];
return (
<g transform={`translate(50 ${y}) scale(${scale})`}>
@@ -188,7 +193,7 @@ function Face({ shape, state }: { shape: BotBlobShape; state: BotAnimationState
overflow="visible"
aria-hidden
>
- <Eyes state={state} />
+ <Eyes state={state} color={color} />
</svg>
</g>
);
@@ -251,6 +256,7 @@ export function BotAvatarView({
}
const { shape, color } = resolveBlobRendering(avatar);
+ const eyeColor = resolveBlobEyeColor(color);
return (
<svg
viewBox="0 0 100 100"
@@ -263,7 +269,7 @@ export function BotAvatarView({
>
<g className="bot-body">
<BlobShape shape={shape} color={color} />
- <Face shape={shape} state={state} />
+ <Face shape={shape} state={state} color={eyeColor} />
</g>
</svg>
);
diff --git a/apps/web/src/components/roster/NewBotDialog.tsx b/apps/web/src/components/roster/NewBotDialog.tsx
index 793beb4bf..349b77ef2 100644
--- a/apps/web/src/components/roster/NewBotDialog.tsx
+++ b/apps/web/src/components/roster/NewBotDialog.tsx
@@ -5,8 +5,9 @@ import { readFileAsDataUrl } from "../ChatView.logic";
import { Button } from "../ui/button";
import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
import { Input } from "../ui/input";
+import { AvatarColorPicker } from "./AvatarColorPicker";
import { BotAvatarView } from "./BotAvatarView";
-import { BLOB_COLORS, BLOB_SHAPES, randomBotAvatar } from "./roster.logic";
+import { BLOB_SHAPES, randomBotAvatar } from "./roster.logic";
import type { BotAvatar } from "./types";
/** A compact bot creation form with all required choices in one view. */
@@ -113,25 +114,10 @@ export function NewBotDialog({
})}
</div>
- <div className="flex flex-wrap gap-2.5">
- {BLOB_COLORS.map((color) => {
- const selected = avatar.kind === "blob" && blobAvatar.color === color;
- return (
- <button
- key={color}
- type="button"
- aria-label={color}
- aria-pressed={selected}
- onClick={() => updateBlobAvatar({ ...blobAvatar, color })}
- style={{ backgroundColor: color }}
- className={cn(
- "size-8 cursor-pointer rounded-full border border-foreground/10 outline-none focus-visible:ring-2 focus-visible:ring-ring",
- selected && "ring-2 ring-ring ring-offset-2 ring-offset-popover",
- )}
- />
- );
- })}
- </div>
+ <AvatarColorPicker
+ value={blobAvatar.color}
+ onChange={(color) => updateBlobAvatar({ ...blobAvatar, color })}
+ />
</section>
</div>
diff --git a/apps/web/src/components/roster/avatarColorPicker.logic.test.ts b/apps/web/src/components/roster/avatarColorPicker.logic.test.ts
new file mode 100644
index 000000000..3c410e2bb
--- /dev/null
+++ b/apps/web/src/components/roster/avatarColorPicker.logic.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ clampColorFraction,
+ formatColorFieldValueText,
+ hexToHsv,
+ hsvToHex,
+} from "./avatarColorPicker.logic";
+
+describe("avatar color picker", () => {
+ it("round trips custom hex colors through HSV", () => {
+ const hsv = hexToHsv("#17B890");
+
+ expect(hsv).not.toBeNull();
+ expect(hsvToHex(hsv!)).toBe("#17B890");
+ });
+
+ it("accepts hex without a hash and rejects invalid colors", () => {
+ expect(hexToHsv("17b890")).not.toBeNull();
+ expect(hexToHsv("rainbow")).toBeNull();
+ expect(hexToHsv("#1234")).toBeNull();
+ });
+
+ it("clamps pointer coordinates to the picker bounds", () => {
+ expect(clampColorFraction(-0.5)).toBe(0);
+ expect(clampColorFraction(0.4)).toBe(0.4);
+ expect(clampColorFraction(1.5)).toBe(1);
+ });
+
+ it("announces both dimensions of the saturation and brightness field", () => {
+ expect(formatColorFieldValueText({ h: 240, s: 0.75, v: 0.4 }, "#191966")).toBe(
+ "Saturation 75%, brightness 40%, #191966",
+ );
+ });
+});
diff --git a/apps/web/src/components/roster/avatarColorPicker.logic.ts b/apps/web/src/components/roster/avatarColorPicker.logic.ts
new file mode 100644
index 000000000..fa94dcb15
--- /dev/null
+++ b/apps/web/src/components/roster/avatarColorPicker.logic.ts
@@ -0,0 +1,50 @@
+export interface HsvColor {
+ readonly h: number;
+ readonly s: number;
+ readonly v: number;
+}
+
+const HEX_COLOR = /^#?([\da-f]{6})$/i;
+
+export function hexToHsv(value: string): HsvColor | null {
+ const hex = HEX_COLOR.exec(value.trim())?.[1];
+ if (!hex) return null;
+
+ const numeric = Number.parseInt(hex, 16);
+ const red = ((numeric >> 16) & 255) / 255;
+ const green = ((numeric >> 8) & 255) / 255;
+ const blue = (numeric & 255) / 255;
+ const max = Math.max(red, green, blue);
+ const min = Math.min(red, green, blue);
+ const delta = max - min;
+
+ let hue = 0;
+ if (delta !== 0) {
+ if (max === red) hue = ((green - blue) / delta) % 6;
+ else if (max === green) hue = (blue - red) / delta + 2;
+ else hue = (red - green) / delta + 4;
+ hue = (hue * 60 + 360) % 360;
+ }
+
+ return { h: hue, s: max === 0 ? 0 : delta / max, v: max };
+}
+
+export function hsvToHex({ h, s, v }: HsvColor): string {
+ const channel = (offset: number) => {
+ const k = (offset + h / 60) % 6;
+ const value = v - v * s * Math.max(0, Math.min(k, 4 - k, 1));
+ return Math.round(value * 255)
+ .toString(16)
+ .padStart(2, "0");
+ };
+
+ return `#${channel(5)}${channel(3)}${channel(1)}`.toUpperCase();
+}
+
+export function clampColorFraction(value: number): number {
+ return Math.min(1, Math.max(0, value));
+}
+
+export function formatColorFieldValueText(color: HsvColor, hex: string): string {
+ return `Saturation ${Math.round(color.s * 100)}%, brightness ${Math.round(color.v * 100)}%, ${hex}`;
+}
diff --git a/apps/web/src/components/roster/roster.logic.test.ts b/apps/web/src/components/roster/roster.logic.test.ts
index 8e0bdbf7b..ca8ecf358 100644
--- a/apps/web/src/components/roster/roster.logic.test.ts
+++ b/apps/web/src/components/roster/roster.logic.test.ts
@@ -17,6 +17,7 @@ import {
parseChatPath,
randomBotAvatar,
resolveBlobRendering,
+ resolveBlobEyeColor,
resolveBotPresence,
resolveLatestRosterMessage,
resolveRosterBotId,
@@ -52,6 +53,15 @@ function bot(input: Partial<Bot> & Pick<Bot, "id" | "name">): Bot {
};
}
+describe("resolveBlobEyeColor", () => {
+ it("chooses the eye color with the stronger contrast", () => {
+ expect(resolveBlobEyeColor("#141062")).toBe("#FFFFFF");
+ expect(resolveBlobEyeColor("#E0645C")).toBe("#0A0A0A");
+ expect(resolveBlobEyeColor("#FFFFFF")).toBe("#0A0A0A");
+ expect(resolveBlobEyeColor("#000000")).toBe("#FFFFFF");
+ });
+});
+
describe("resolveRosterBotId", () => {
it("does not redirect to a persisted bot that is absent from the loaded roster", () => {
expect(resolveRosterBotId("missing", [])).toBeNull();
diff --git a/apps/web/src/components/roster/roster.logic.ts b/apps/web/src/components/roster/roster.logic.ts
index e8f415784..e6556de35 100644
--- a/apps/web/src/components/roster/roster.logic.ts
+++ b/apps/web/src/components/roster/roster.logic.ts
@@ -35,6 +35,45 @@ export const BLOB_COLORS: readonly string[] = [
export const DEFAULT_BLOB_SHAPE: BotBlobShape = "circle";
export const DEFAULT_BLOB_COLOR = "#7A8699";
+const DARK_EYES = "#0A0A0A";
+const LIGHT_EYES = "#FFFFFF";
+
+function relativeLuminance(hexColor: string) {
+ const channels = hexColor
+ .slice(1)
+ .match(/.{2}/g)
+ ?.map((channel) => Number.parseInt(channel, 16) / 255);
+
+ if (!channels || channels.length !== 3 || channels.some(Number.isNaN)) return null;
+
+ const [red, green, blue] = channels.map((channel) =>
+ channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4,
+ ) as [number, number, number];
+ return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
+}
+
+function contrastRatio(first: number, second: number) {
+ const lighter = Math.max(first, second);
+ const darker = Math.min(first, second);
+ return (lighter + 0.05) / (darker + 0.05);
+}
+
+/** Picks whichever eye color has the stronger contrast against the blob. */
+export function resolveBlobEyeColor(color: string) {
+ if (!isBotAvatarColor(color)) return DARK_EYES;
+
+ const bodyLuminance = relativeLuminance(color);
+ const darkLuminance = relativeLuminance(DARK_EYES);
+ if (bodyLuminance === null || darkLuminance === null) return DARK_EYES;
+
+ const darkContrast = contrastRatio(bodyLuminance, darkLuminance);
+ const lightContrast = contrastRatio(bodyLuminance, 1);
+ return lightContrast > darkContrast ? LIGHT_EYES : DARK_EYES;
+}
+
+export function isBotAvatarColor(value: unknown): value is string {
+ return typeof value === "string" && /^#[\da-f]{6}$/i.test(value);
+}
export function isBotBlobShape(value: string): value is BotBlobShape {
return (BLOB_SHAPES as readonly string[]).includes(value);