Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(views): text icon for the workspace logo (#10792)
Eric Yumbdf02f70c457
diff --git a/packages/views/common/avatar-upload-control.test.tsx b/packages/views/common/avatar-upload-control.test.tsxindex a0efd6e999..4a4fda4bf7 100644--- a/packages/views/common/avatar-upload-control.test.tsx+++ b/packages/views/common/avatar-upload-control.test.tsx@@ -42,6 +42,28 @@ vi.mock("./avatar-crop-dialog", () => ({},}));+// Stands in for the text icon dialog the same way: one click hands over a+// generated PNG. The drawing itself is covered by text-avatar.test.ts.+vi.mock("./text-avatar-dialog", () => ({+ TextAvatarDialog: ({+ open,+ onGenerated,+ }: {+ open: boolean;+ onGenerated: (file: File) => void;+ }) =>+ open ? (+ <button+ type="button"+ onClick={() =>+ onGenerated(new File(["x"], "workspace-icon.png", { type: "image/png" }))+ }+ >+ generate+ </button>+ ) : null,+}));+import { AvatarUploadControl } from "./avatar-upload-control";afterEach(() => {@@ -295,4 +317,57 @@ describe("AvatarUploadControl", () => {fireEvent.click(trigger);expect(screen.queryByText("Upload image")).not.toBeInTheDocument();});++ it("offers a text icon only where it is enabled", async () => {+ const { container, unmount } = renderWithI18n(+ <AvatarUploadControl variant="user" value={null} onUploaded={vi.fn()} />,+ );+ const openDialog = spyOnFileDialog(container);+ fireEvent.click(screen.getByRole("button", { name: "Change avatar" }));+ expect(openDialog).toHaveBeenCalledTimes(1);+ expect(screen.queryByText("Text icon")).not.toBeInTheDocument();+ unmount();++ renderWithI18n(+ <AvatarUploadControl+ variant="workspace"+ value={null}+ onUploaded={vi.fn()}+ textIconEnabled+ />,+ );+ openPicker();+ expect(+ await screen.findByRole("button", { name: "Upload image" }),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Text icon" })).toBeInTheDocument();+ // Emoji stays off unless its own handler is passed.+ expect(screen.queryByText("Emoji")).not.toBeInTheDocument();+ });++ it("saves a text icon through the same upload path as an image", async () => {+ uploadMock.mockResolvedValueOnce({ link: "https://cdn.test/icon.png" });+ const onUploaded = vi.fn();+ renderWithI18n(+ <AvatarUploadControl+ variant="workspace"+ name="acme-a"+ value="https://cdn.test/old.png"+ onUploaded={onUploaded}+ textIconEnabled+ />,+ );++ openPicker();+ fireEvent.click(await screen.findByRole("button", { name: "Text icon" }));+ fireEvent.click(screen.getByRole("button", { name: "generate" }));++ await waitFor(() =>+ expect(onUploaded).toHaveBeenCalledWith("https://cdn.test/icon.png"),+ );+ const uploaded = uploadMock.mock.calls[0]![0] as File;+ expect(uploaded.type).toBe("image/png");+ await waitFor(() => expect(toastSuccess).toHaveBeenCalledWith("Avatar updated"));+ expect(screen.queryByRole("button", { name: "generate" })).not.toBeInTheDocument();+ });});diff --git a/packages/views/common/avatar-upload-control.tsx b/packages/views/common/avatar-upload-control.tsxindex ffb89f102f..e9495b858f 100644--- a/packages/views/common/avatar-upload-control.tsx+++ b/packages/views/common/avatar-upload-control.tsx@@ -1,7 +1,7 @@"use client";import { Suspense, lazy, useRef, useState } from "react";-import { Bot, Camera, ImagePlus, Loader2, Users, X } from "@multica/ui/icons";+import { Bot, Camera, ImagePlus, Loader2, Type, Users, X } from "@multica/ui/icons";import { toast } from "sonner";import { api } from "@multica/core/api";import { useFileUpload } from "@multica/core/hooks/use-file-upload";@@ -22,6 +22,7 @@ import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip"import { cn } from "@multica/ui/lib/utils";import { useT } from "../i18n";import { AvatarCropDialog } from "./avatar-crop-dialog";+import { TextAvatarDialog } from "./text-avatar-dialog";// The full emoji-mart picker is ~1MB of emoji data. Only the handful of// suggestions render eagerly; the searchable set loads when asked for.@@ -58,6 +59,13 @@ interface AvatarUploadControlProps {* way. Omit it and the control keeps its click-straight-to-upload behavior.*/onEmojiSelected?: (value: string) => void | Promise<unknown>;+ /**+ * Offers a "Text icon" entry next to the upload: 1–2 typed characters on a+ * preset color, drawn into a PNG and saved through the same upload ++ * `onUploaded` path as a cropped image. Clicking the avatar then opens a+ * menu instead of going straight to the file dialog.+ */+ textIconEnabled?: boolean;/*** When provided, shows a small clear affordance. Used by create flows to* drop a not-yet-persisted choice; edit flows omit it (removing a saved@@ -142,6 +150,7 @@ export function AvatarUploadControl({disabled = false,onUploaded,onEmojiSelected,+ textIconEnabled = false,onClear,className,ariaLabel,@@ -156,12 +165,15 @@ export function AvatarUploadControl({const [previewError, setPreviewError] = useState(false);const [pickerOpen, setPickerOpen] = useState(false);const [emojiSearchOpen, setEmojiSearchOpen] = useState(false);+ const [textDialogOpen, setTextDialogOpen] = useState(false);const emoji = parseAvatarEmoji(value);const resolved = value && !emoji ? resolvePublicFileUrl(value) : null;const hasImage = !!resolved && !previewError;const hasAvatar = !!emoji || hasImage;const emojiEnabled = !!onEmojiSelected;+ // Any alternative to an image turns the click into a menu.+ const menuEnabled = emojiEnabled || textIconEnabled;const openFileDialog = () => fileInputRef.current?.click();@@ -188,16 +200,18 @@ export function AvatarUploadControl({setDialogOpen(true);};- const handleCropped = async (cropped: File) => {- // Block dismissal during the cropper handoff, before busy has committed.+ // Shared by the cropper and the text icon: both hand over a finished image+ // file, and both dialogs stay busy until the caller has saved it.+ const uploadAndSave = async (file: File, closeDialog: () => void) => {+ // Block dismissal during the dialog handoff, before busy has committed.uploadPendingRef.current = true;setBusy(true);try {- const result = await upload(cropped);+ const result = await upload(file);if (!result) return;if (!(await persistedByCaller(() => onUploaded(result.link)))) return;- setDialogOpen(false);- setPickedFile(null);+ setPreviewError(false);+ closeDialog();toast.success(t(($) => $.avatar_upload.updated));} catch (err) {// Only the upload above can land here — see persistedByCaller.@@ -210,6 +224,15 @@ export function AvatarUploadControl({}};+ const handleCropped = (cropped: File) =>+ uploadAndSave(cropped, () => {+ setDialogOpen(false);+ setPickedFile(null);+ });++ const handleTextGenerated = (file: File) =>+ uploadAndSave(file, () => setTextDialogOpen(false));+// Busy for the whole save, same as an upload: an edit caller PATCHes on every// pick, so leaving the trigger live would let a second pick race the first.// Both writes are last-one-to-arrive-wins on the server, and the loser can be@@ -236,10 +259,10 @@ export function AvatarUploadControl({const avatarButton = (<buttontype="button"- // With emoji enabled this button is the popover trigger and Base UI+ // With a menu enabled this button is the popover trigger and Base UI// supplies the click handler; without it the click goes straight to the// file dialog, which is this control's original single-purpose shape.- onClick={emojiEnabled ? undefined : openFileDialog}+ onClick={menuEnabled ? undefined : openFileDialog}disabled={disabled || busy}aria-label={changeLabel}className={cn(@@ -286,7 +309,7 @@ export function AvatarUploadControl({return (<div className="relative shrink-0" style={{ width: size, height: size }}>- {emojiEnabled ? (+ {menuEnabled ? (<Popover open={pickerOpen} onOpenChange={handlePickerOpenChange}><DeferredTooltipcontent={changeLabel}@@ -296,7 +319,10 @@ export function AvatarUploadControl({align="start"// The emoji-mart picker sizes itself; only the suggestion grid is// laid out against the popover's own width.- className={cn("gap-0 p-0", emojiSearchOpen ? "w-auto" : "w-72")}+ className={cn(+ "gap-0 p-0",+ emojiSearchOpen ? "w-auto" : emojiEnabled ? "w-72" : "w-48",+ )}>{emojiSearchOpen ? (<Suspense@@ -322,38 +348,55 @@ export function AvatarUploadControl({<ImagePlus className="size-4 shrink-0 text-muted-foreground" />{t(($) => $.avatar_upload.upload_image)}</button>+ {textIconEnabled && (+ <button+ type="button"+ onClick={() => {+ closePicker();+ setTextDialogOpen(true);+ }}+ className="flex w-full items-center gap-1.5 rounded-md px-1.5 py-1.5 text-body outline-hidden transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground"+ >+ <Type className="size-4 shrink-0 text-muted-foreground" />+ {t(($) => $.avatar_upload.text_icon)}+ </button>+ )}</div>- <Separator />+ {emojiEnabled && (+ <>+ <Separator />- <div className="p-1">- <p className="px-1.5 py-1 text-caption font-medium text-muted-foreground">- {t(($) => $.avatar_upload.emoji_label)}- </p>- <div className="grid grid-cols-8 gap-0.5">- {AVATAR_EMOJI_SUGGESTIONS.map((suggestion) => (+ <div className="p-1">+ <p className="px-1.5 py-1 text-caption font-medium text-muted-foreground">+ {t(($) => $.avatar_upload.emoji_label)}+ </p>+ <div className="grid grid-cols-8 gap-0.5">+ {AVATAR_EMOJI_SUGGESTIONS.map((suggestion) => (+ <button+ key={suggestion}+ type="button"+ aria-pressed={emoji === suggestion}+ onClick={() => handleEmojiSelected(suggestion)}+ className={cn(+ "flex h-8 w-8 items-center justify-center rounded-md text-title-sm leading-none outline-hidden transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",+ emoji === suggestion && "bg-accent ring-1 ring-ring",+ )}+ >+ {suggestion}+ </button>+ ))}+ </div><button- key={suggestion}type="button"- aria-pressed={emoji === suggestion}- onClick={() => handleEmojiSelected(suggestion)}- className={cn(- "flex h-8 w-8 items-center justify-center rounded-md text-title-sm leading-none outline-hidden transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",- emoji === suggestion && "bg-accent ring-1 ring-ring",- )}+ onClick={() => setEmojiSearchOpen(true)}+ className="mt-1 w-full rounded-md px-1.5 py-1 text-caption text-muted-foreground outline-hidden transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground">- {suggestion}+ {t(($) => $.avatar_upload.more_emojis)}</button>- ))}- </div>- <button- type="button"- onClick={() => setEmojiSearchOpen(true)}- className="mt-1 w-full rounded-md px-1.5 py-1 text-caption text-muted-foreground outline-hidden transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground"- >- {t(($) => $.avatar_upload.more_emojis)}- </button>- </div>+ </div>+ </>+ )}</>)}</PopoverContent>@@ -399,6 +442,19 @@ export function AvatarUploadControl({}}onCropped={handleCropped}/>++ {textIconEnabled && (+ <TextAvatarDialog+ open={textDialogOpen}+ name={name}+ busy={busy}+ onOpenChange={(next) => {+ if (busy || uploadPendingRef.current) return;+ setTextDialogOpen(next);+ }}+ onGenerated={handleTextGenerated}+ />+ )}</div>);}diff --git a/packages/views/common/text-avatar-dialog.test.tsx b/packages/views/common/text-avatar-dialog.test.tsxnew file mode 100644index 0000000000..446cd49080--- /dev/null+++ b/packages/views/common/text-avatar-dialog.test.tsx@@ -0,0 +1,111 @@+// @vitest-environment jsdom++import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { renderWithI18n } from "../test/i18n";+import { TextAvatarDialog } from "./text-avatar-dialog";++const render = vi.hoisted(() => vi.fn());+vi.mock("./text-avatar", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./text-avatar")>()),+ renderTextAvatar: render,+}));++afterEach(() => {+ cleanup();+ vi.resetAllMocks();+});++function mount(name = "acme") {+ const props = {+ open: true,+ name,+ busy: false,+ onOpenChange: vi.fn(),+ onGenerated: vi.fn(),+ };+ renderWithI18n(<TextAvatarDialog {...props} />);+ const input = screen.getByLabelText("Text") as HTMLInputElement;+ const save = screen.getByRole("button", { name: "Save" });+ return { props, input, save };+}++describe("TextAvatarDialog", () => {+ it("starts from the name's first character", () => {+ const { input, save } = mount("acme-a");+ expect(input.value).toBe("A");+ expect(save).toBeEnabled();+ });++ it("cannot save empty text", () => {+ const { input, save } = mount();+ fireEvent.change(input, { target: { value: " " } });++ expect(save).toBeDisabled();+ fireEvent.click(save);+ fireEvent.keyDown(input, { key: "Enter" });+ expect(render).not.toHaveBeenCalled();+ });++ it("cuts typed text to two characters", () => {+ const { input } = mount();+ fireEvent.change(input, { target: { value: "ABC" } });+ expect(input.value).toBe("AB");+ });++ it("waits for an IME composition to finish before cutting", () => {+ const { input } = mount();+ fireEvent.compositionStart(input);+ fireEvent.change(input, { target: { value: "yanfa" } });+ expect(input.value).toBe("yanfa");++ fireEvent.change(input, { target: { value: "研发部" } });+ fireEvent.compositionEnd(input);+ expect(input.value).toBe("研发");+ });++ it("hands the chosen text and color to the renderer, then the file to the parent", async () => {+ const png = new File(["png"], "workspace-icon.png", { type: "image/png" });+ render.mockResolvedValueOnce(png);+ const { input, save, props } = mount();++ fireEvent.change(input, { target: { value: "A4" } });+ fireEvent.click(screen.getByRole("button", { name: "#22c55e" }));+ expect(screen.getByRole("button", { name: "#22c55e" })).toHaveAttribute(+ "aria-pressed",+ "true",+ );+ fireEvent.click(save);++ await waitFor(() => expect(props.onGenerated).toHaveBeenCalledWith(png));+ expect(render).toHaveBeenCalledWith("A4", "#22c55e");+ });++ it("shows an error and stays open when drawing fails", async () => {+ render.mockRejectedValueOnce(new Error("no canvas"));+ const { save, props } = mount();++ fireEvent.click(save);++ expect(+ await screen.findByText("Couldn't create the icon. Please try again."),+ ).toBeInTheDocument();+ expect(props.onGenerated).not.toHaveBeenCalled();+ expect(props.onOpenChange).not.toHaveBeenCalled();+ });++ it("locks while the parent is uploading", () => {+ renderWithI18n(+ <TextAvatarDialog+ open+ name="acme"+ busy+ onOpenChange={vi.fn()}+ onGenerated={vi.fn()}+ />,+ );+ expect(screen.getByRole("button", { name: /Uploading/ })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();+ expect(screen.getByLabelText("Text")).toBeDisabled();+ });+});diff --git a/packages/views/common/text-avatar-dialog.tsx b/packages/views/common/text-avatar-dialog.tsxnew file mode 100644index 0000000000..3dc42f3701--- /dev/null+++ b/packages/views/common/text-avatar-dialog.tsx@@ -0,0 +1,219 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Loader2 } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../i18n";+import {+ TEXT_AVATAR_COLORS,+ TEXT_AVATAR_DEFAULT_COLOR,+ defaultAvatarText,+ normalizeAvatarText,+ renderTextAvatar,+ textAvatarFontRatio,+ textAvatarTextColor,+} from "./text-avatar";++/** Sizes shown side by side: the settings avatar and the sidebar list. */+const PREVIEW_SIZES = [64, 20] as const;++interface TextAvatarDialogProps {+ open: boolean;+ /** Name the starting text is taken from (its first character). */+ name: string;+ /** Parent's upload/save is in flight — locks the controls and blocks close. */+ busy?: boolean;+ onOpenChange: (open: boolean) => void;+ /** Fires with the generated PNG. The parent uploads + persists. */+ onGenerated: (file: File) => void;+}++function TextAvatarPreview({+ text,+ color,+ size,+}: {+ text: string;+ color: string;+ size: number;+}) {+ return (+ <span+ aria-hidden+ className="flex shrink-0 select-none items-center justify-center overflow-hidden rounded-full font-semibold leading-none"+ style={{+ width: size,+ height: size,+ backgroundColor: color,+ color: textAvatarTextColor(color),+ fontSize: size * textAvatarFontRatio(text),+ }}+ >+ {text}+ </span>+ );+}++/**+ * Builds an avatar from typed text: 1–2 characters on a preset color,+ * with live previews at the sizes it is shown at. Save draws a PNG (see+ * text-avatar.ts) and hands it to the parent, which uploads it exactly like a+ * cropped image.+ */+export function TextAvatarDialog({+ open,+ name,+ busy = false,+ onOpenChange,+ onGenerated,+}: TextAvatarDialogProps) {+ const { t } = useT("common");+ const [text, setText] = useState("");+ const [color, setColor] = useState<string>(TEXT_AVATAR_DEFAULT_COLOR);+ const [encoding, setEncoding] = useState(false);+ const [failed, setFailed] = useState(false);+ const encodingRef = useRef(false);+ const composingRef = useRef(false);+ const pending = busy || encoding;++ // Every open starts from the name's first character; the color carries over+ // so a second try only needs the text changed.+ useEffect(() => {+ if (!open) return;+ setText(defaultAvatarText(name));+ setFailed(false);+ }, [open, name]);++ const value = normalizeAvatarText(text);+ const canSave = !!value && !pending;++ // Cut to the limit as the user types, but not mid-composition: an IME's+ // pinyin/romaji buffer is longer than the characters it ends up as.+ const handleTextChange = (next: string) => {+ setFailed(false);+ setText(composingRef.current ? next : normalizeAvatarText(next));+ };++ const handleSave = async () => {+ if (!value || busy || encodingRef.current) return;+ encodingRef.current = true;+ setEncoding(true);+ try {+ const file = await renderTextAvatar(value, color);+ onGenerated(file);+ } catch {+ setFailed(true);+ } finally {+ encodingRef.current = false;+ setEncoding(false);+ }+ };++ const handleOpenChange = (next: boolean) => {+ if (busy || encodingRef.current) return;+ onOpenChange(next);+ };++ return (+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent showCloseButton={!pending} className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>{t(($) => $.text_avatar.title)}</DialogTitle>+ </DialogHeader>++ <div+ className="flex items-center justify-center gap-4 rounded-lg bg-muted py-5"+ role="img"+ aria-label={t(($) => $.text_avatar.preview)}+ >+ {PREVIEW_SIZES.map((size) => (+ <TextAvatarPreview key={size} text={value} color={color} size={size} />+ ))}+ </div>++ <div className="flex flex-col gap-1.5">+ <label htmlFor="text-avatar-input" className="text-body font-medium">+ {t(($) => $.text_avatar.text_label)}+ </label>+ <Input+ id="text-avatar-input"+ autoComplete="off"+ autoFocus+ value={text}+ disabled={pending}+ onCompositionStart={() => {+ composingRef.current = true;+ }}+ onCompositionEnd={(event) => {+ composingRef.current = false;+ handleTextChange(event.currentTarget.value);+ }}+ onChange={(event) => handleTextChange(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && !event.nativeEvent.isComposing) {+ event.preventDefault();+ void handleSave();+ }+ }}+ />+ <p className="text-caption text-muted-foreground">+ {t(($) => $.text_avatar.text_hint)}+ </p>+ </div>++ <div className="flex flex-col gap-1.5">+ <p className="text-body font-medium">{t(($) => $.text_avatar.color_label)}</p>+ <div className="grid grid-cols-5 gap-2">+ {TEXT_AVATAR_COLORS.map((preset) => (+ <button+ key={preset}+ type="button"+ aria-label={preset}+ aria-pressed={color === preset}+ disabled={pending}+ onClick={() => setColor(preset)}+ className={cn(+ // eslint-disable-next-line no-restricted-syntax -- color swatch+ "size-7 justify-self-center rounded-full transition-transform hover:scale-110 disabled:opacity-50",+ color === preset &&+ "ring-2 ring-ring ring-offset-2 ring-offset-background",+ )}+ style={{ backgroundColor: preset }}+ />+ ))}+ </div>+ </div>++ {failed && (+ <p className="text-caption text-destructive">+ {t(($) => $.text_avatar.render_failed)}+ </p>+ )}++ <div className="flex justify-end gap-2">+ <Button+ variant="outline"+ onClick={() => handleOpenChange(false)}+ disabled={pending}+ >+ {t(($) => $.avatar_crop.cancel)}+ </Button>+ <Button onClick={handleSave} disabled={!canSave} aria-busy={pending}>+ {pending && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {busy+ ? t(($) => $.avatar_crop.uploading)+ : t(($) => $.avatar_crop.apply)}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/common/text-avatar.test.ts b/packages/views/common/text-avatar.test.tsnew file mode 100644index 0000000000..3633dd4dbb--- /dev/null+++ b/packages/views/common/text-avatar.test.ts@@ -0,0 +1,158 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ LABEL_TEXT_COLORS,+ PALETTE_PRESETS,+ PALETTE_SLOTS,+} from "@multica/core/appearance";+import {+ TEXT_AVATAR_COLORS,+ TEXT_AVATAR_DEFAULT_COLOR,+ TEXT_AVATAR_SIZE,+ defaultAvatarText,+ normalizeAvatarText,+ renderTextAvatar,+ textAvatarTextColor,+} from "./text-avatar";++const [DARK_TEXT, LIGHT_TEXT] = LABEL_TEXT_COLORS;++describe("text icon colors", () => {+ it("offers the app's palette presets, in the picker's order", () => {+ expect(TEXT_AVATAR_COLORS).toEqual(+ PALETTE_SLOTS.map((slot) => PALETTE_PRESETS[slot]),+ );+ expect(TEXT_AVATAR_COLORS).toHaveLength(10);+ expect(TEXT_AVATAR_DEFAULT_COLOR).toBe(PALETTE_PRESETS.blue);+ });++ it("picks dark text on light presets and light text on dark ones", () => {+ expect(textAvatarTextColor(PALETTE_PRESETS.yellow)).toBe(DARK_TEXT);+ expect(textAvatarTextColor(PALETTE_PRESETS.orange)).toBe(DARK_TEXT);+ expect(textAvatarTextColor(PALETTE_PRESETS.blue)).toBe(LIGHT_TEXT);+ expect(textAvatarTextColor(PALETTE_PRESETS.gray)).toBe(LIGHT_TEXT);+ });+});++describe("normalizeAvatarText", () => {+ it("keeps up to two characters and cuts the rest", () => {+ expect(normalizeAvatarText("A")).toBe("A");+ expect(normalizeAvatarText("A3")).toBe("A3");+ expect(normalizeAvatarText("ABC")).toBe("AB");+ expect(normalizeAvatarText("研发三部")).toBe("研发");+ });++ it("drops whitespace and keeps the typed case", () => {+ expect(normalizeAvatarText(" a b ")).toBe("ab");+ expect(normalizeAvatarText("xY")).toBe("xY");+ });++ it("is empty when nothing but whitespace was typed", () => {+ expect(normalizeAvatarText("")).toBe("");+ expect(normalizeAvatarText(" ")).toBe("");+ });++ it("counts a multi-code-point character as one", () => {+ expect(normalizeAvatarText("👍🏽👍🏽👍🏽")).toBe("👍🏽👍🏽");+ });+});++describe("defaultAvatarText", () => {+ it("takes the name's first character, upper-cased", () => {+ expect(defaultAvatarText("acme-a")).toBe("A");+ expect(defaultAvatarText(" 研发")).toBe("研");+ expect(defaultAvatarText("")).toBe("");+ });+});++describe("renderTextAvatar", () => {+ const ctx = {+ fillStyle: "",+ font: "",+ textAlign: "",+ textBaseline: "",+ fillRect: vi.fn(),+ fillText: vi.fn(),+ measureText: vi.fn(() => ({+ width: 100,+ actualBoundingBoxAscent: 40,+ actualBoundingBoxDescent: 0,+ })),+ };+ const canvases: HTMLCanvasElement[] = [];++ function stubCanvas() {+ const createElement = document.createElement.bind(document);+ vi.spyOn(document, "createElement").mockImplementation(+ (tag: string, options?: ElementCreationOptions) => {+ const el = createElement(tag, options);+ if (tag === "canvas") {+ const canvas = el as HTMLCanvasElement;+ canvases.push(canvas);+ canvas.getContext = vi.fn(() => ctx) as never;+ canvas.toBlob = ((cb: BlobCallback, type?: string) =>+ cb(new Blob(["png"], { type }))) as never;+ }+ return el;+ },+ );+ }++ afterEach(() => {+ vi.restoreAllMocks();+ canvases.length = 0;+ ctx.fillRect.mockClear();+ ctx.fillText.mockClear();+ });++ it("produces a square PNG file of the fixed size", async () => {+ stubCanvas();+ const file = await renderTextAvatar("A3", "#2563eb");++ expect(file).toBeInstanceOf(File);+ expect(file.type).toBe("image/png");+ expect(file.name).toBe("workspace-icon.png");+ expect(canvases).toHaveLength(1);+ expect(canvases[0]!.width).toBe(TEXT_AVATAR_SIZE);+ expect(canvases[0]!.height).toBe(TEXT_AVATAR_SIZE);+ expect(TEXT_AVATAR_SIZE).toBe(256);+ expect(ctx.fillRect).toHaveBeenCalledWith(0, 0, 256, 256);+ });++ it("draws only the first two characters", async () => {+ stubCanvas();+ await renderTextAvatar("ABC", "#2563eb");++ expect(ctx.fillText).toHaveBeenCalledTimes(1);+ expect(ctx.fillText.mock.calls[0]![0]).toBe("AB");+ });++ it("shrinks text that would overflow the square", async () => {+ stubCanvas();+ ctx.measureText.mockReturnValueOnce({+ width: 400,+ actualBoundingBoxAscent: 40,+ actualBoundingBoxDescent: 0,+ });+ await renderTextAvatar("WW", "#2563eb");++ // 0.42 * 256 = 108px, scaled by 0.8 * 256 / 400.+ expect(ctx.font).toMatch(/^600 55px /);+ });++ it("fills the chosen color and draws text in the color that reads on it", async () => {+ stubCanvas();+ const styles: string[] = [];+ ctx.fillRect.mockImplementationOnce(() => styles.push(ctx.fillStyle));+ ctx.fillText.mockImplementationOnce(() => styles.push(ctx.fillStyle));+ await renderTextAvatar("A3", PALETTE_PRESETS.yellow);++ expect(styles).toEqual([PALETTE_PRESETS.yellow, DARK_TEXT]);+ });++ it("refuses empty text", async () => {+ stubCanvas();+ await expect(renderTextAvatar(" ", "#2563eb")).rejects.toThrow();+ expect(canvases).toHaveLength(0);+ });+});diff --git a/packages/views/common/text-avatar.ts b/packages/views/common/text-avatar.tsnew file mode 100644index 0000000000..5470029438--- /dev/null+++ b/packages/views/common/text-avatar.ts@@ -0,0 +1,152 @@+// Text icon: a few typed characters on a solid color, drawn into a PNG.+//+// The result goes through the same upload + `onUploaded` path as a cropped+// image, so every surface that already shows an uploaded avatar shows it with+// no change. The square is fully filled; rounding stays display-only, as it is+// for cropped images.++import {+ PALETTE_PRESETS,+ PALETTE_SLOTS,+ labelTextColor,+} from "@multica/core/appearance";++/** Square side of the generated PNG. */+export const TEXT_AVATAR_SIZE = 256;++/** At most this many characters (grapheme clusters) are drawn. */+export const TEXT_AVATAR_MAX_CHARS = 2;++/**+ * Background presets: the colour picker's presets for labels, custom statuses+ * and select options, in the same order, so a workspace icon draws from the+ * colours the app already offers.+ */+export const TEXT_AVATAR_COLORS: readonly string[] = PALETTE_SLOTS.map(+ (slot) => PALETTE_PRESETS[slot],+);++/** Starting background: the blue preset. */+export const TEXT_AVATAR_DEFAULT_COLOR = PALETTE_PRESETS.blue;++/**+ * Text colour for a background: dark or light, picked the same way a label+ * chip picks its text colour.+ */+export function textAvatarTextColor(background: string): string {+ return labelTextColor(background);+}++const FALLBACK_FONT_FAMILY =+ 'system-ui, -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif';++/** Splits into user-perceived characters, so "👍🏽" or "é" count as one. */+function graphemes(text: string): string[] {+ if (typeof Intl !== "undefined" && "Segmenter" in Intl) {+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });+ return Array.from(segmenter.segment(text), (part) => part.segment);+ }+ return Array.from(text);+}++/**+ * The text that will actually be drawn: whitespace removed, cut to+ * {@link TEXT_AVATAR_MAX_CHARS} characters. Case is kept as typed. An empty+ * result means there is nothing to save.+ */+export function normalizeAvatarText(input: string): string {+ return graphemes(input.replace(/\s+/g, ""))+ .slice(0, TEXT_AVATAR_MAX_CHARS)+ .join("");+}++/** Starting text for a name: its first character, upper-cased. */+export function defaultAvatarText(name: string): string {+ return (graphemes(name.trim())[0] ?? "").toUpperCase();+}++/**+ * Font size as a fraction of the square side. Two characters get a smaller+ * size so wide CJK pairs still fit; the canvas renderer additionally shrinks+ * anything that would overflow. The live preview uses the same ratio.+ */+export function textAvatarFontRatio(text: string): number {+ return graphemes(text).length > 1 ? 0.42 : 0.52;+}++/** Widest the text may be, as a fraction of the square side. */+const MAX_TEXT_WIDTH_RATIO = 0.8;++function resolveFontFamily(): string {+ if (typeof document === "undefined" || !document.body) {+ return FALLBACK_FONT_FAMILY;+ }+ const family = getComputedStyle(document.body).fontFamily;+ return family ? `${family}, ${FALLBACK_FONT_FAMILY}` : FALLBACK_FONT_FAMILY;+}++function canvasToPng(canvas: HTMLCanvasElement): Promise<Blob> {+ return new Promise((resolve, reject) => {+ canvas.toBlob(+ (blob) => (blob ? resolve(blob) : reject(new Error("Canvas is empty"))),+ "image/png",+ );+ });+}++/**+ * Draws `text` (normalized first) on `color`, in the text colour that reads+ * on it (see {@link textAvatarTextColor}), into a+ * {@link TEXT_AVATAR_SIZE}px square PNG file. Rejects when the text is empty.+ */+export async function renderTextAvatar(+ text: string,+ color: string,+): Promise<File> {+ const value = normalizeAvatarText(text);+ if (!value) throw new Error("Text icon needs at least one character");++ // Web fonts may still be loading on a cold settings page; drawing before+ // they are ready would bake the fallback font into the image.+ if (typeof document !== "undefined" && document.fonts?.ready) {+ await document.fonts.ready;+ }++ const size = TEXT_AVATAR_SIZE;+ const canvas = document.createElement("canvas");+ canvas.width = size;+ canvas.height = size;+ const ctx = canvas.getContext("2d");+ if (!ctx) throw new Error("Canvas 2D context unavailable");++ ctx.fillStyle = color;+ ctx.fillRect(0, 0, size, size);++ const family = resolveFontFamily();+ let fontSize = Math.round(size * textAvatarFontRatio(value));+ ctx.font = `600 ${fontSize}px ${family}`;+ const maxWidth = size * MAX_TEXT_WIDTH_RATIO;+ const measuredWidth = ctx.measureText(value).width;+ if (measuredWidth > maxWidth) {+ fontSize = Math.floor((fontSize * maxWidth) / measuredWidth);+ ctx.font = `600 ${fontSize}px ${family}`;+ }++ ctx.fillStyle = textAvatarTextColor(color);+ ctx.textAlign = "center";+ // Center on the glyphs' real ink box rather than the em box, so caps,+ // digits and CJK all sit visually in the middle.+ const metrics = ctx.measureText(value);+ const ascent = metrics.actualBoundingBoxAscent;+ const descent = metrics.actualBoundingBoxDescent;+ if (Number.isFinite(ascent) && Number.isFinite(descent) && ascent + descent > 0) {+ ctx.textBaseline = "alphabetic";+ ctx.fillText(value, size / 2, size / 2 + (ascent - descent) / 2);+ } else {+ ctx.textBaseline = "middle";+ ctx.fillText(value, size / 2, size / 2);+ }++ const blob = await canvasToPng(canvas);+ return new File([blob], "workspace-icon.png", { type: "image/png" });+}diff --git a/packages/views/locales/en/common.json b/packages/views/locales/en/common.jsonindex f32986bd07..a0fb902946 100644--- a/packages/views/locales/en/common.json+++ b/packages/views/locales/en/common.json@@ -14,7 +14,8 @@"upload_image": "Upload image","emoji_label": "Emoji","more_emojis": "More emojis…",- "emoji_loading": "Loading…"+ "emoji_loading": "Loading…",+ "text_icon": "Text icon"},"avatar_crop": {"title": "Edit avatar",@@ -29,6 +30,14 @@"loading": "Loading…","load_failed": "Couldn't load image"},+ "text_avatar": {+ "title": "Text icon",+ "preview": "Preview",+ "text_label": "Text",+ "text_hint": "1–2 characters: letters, digits or Chinese. Longer text is cut.",+ "color_label": "Color",+ "render_failed": "Couldn't create the icon. Please try again."+ },"color_picker": {"saturation": "Saturation and brightness","hue": "Hue",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 020a7f9138..74fcc4755b 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -966,7 +966,7 @@"section_general": "Workspace details","logo_label": "Workspace logo","change_logo_aria": "Change workspace logo",- "click_logo_hint": "Click the logo to upload a new image",+ "click_logo_hint": "Click the logo to upload an image or create a text icon","toast_logo_failed": "Failed to upload workspace logo","name_label": "Name","description_label": "Description",diff --git a/packages/views/locales/es/common.json b/packages/views/locales/es/common.jsonindex 28da3d2745..83f1b7a987 100644--- a/packages/views/locales/es/common.json+++ b/packages/views/locales/es/common.json@@ -8,7 +8,8 @@"upload_image": "Subir imagen","emoji_label": "Emoji","more_emojis": "Más emojis…",- "emoji_loading": "Cargando…"+ "emoji_loading": "Cargando…",+ "text_icon": "Icono de texto"},"avatar_crop": {"title": "Editar avatar",@@ -23,6 +24,14 @@"loading": "Cargando…","load_failed": "No se ha podido cargar la imagen"},+ "text_avatar": {+ "title": "Icono de texto",+ "preview": "Vista previa",+ "text_label": "Texto",+ "text_hint": "1–2 caracteres: letras, números o chino. El resto se recorta.",+ "color_label": "Color",+ "render_failed": "No se pudo crear el icono. Inténtalo de nuevo."+ },"color_picker": {"saturation": "Saturación y brillo","hue": "Tono",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex ff7efd2204..a42d10696a 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -966,7 +966,7 @@"section_general": "Detalles del espacio de trabajo","logo_label": "Logo del espacio de trabajo","change_logo_aria": "Cambiar logo del espacio de trabajo",- "click_logo_hint": "Haz clic en el logo para subir una imagen nueva",+ "click_logo_hint": "Haz clic en el logotipo para subir una imagen o crear un icono de texto","toast_logo_failed": "Error al subir el logo del espacio de trabajo","name_label": "Nombre","description_label": "Descripción",diff --git a/packages/views/locales/fr/common.json b/packages/views/locales/fr/common.jsonindex 4b5c3796dd..42059cef5e 100644--- a/packages/views/locales/fr/common.json+++ b/packages/views/locales/fr/common.json@@ -14,7 +14,8 @@"upload_image": "Envoyer une image","emoji_label": "Emoji","more_emojis": "Plus d'emojis…",- "emoji_loading": "Chargement…"+ "emoji_loading": "Chargement…",+ "text_icon": "Icône texte"},"avatar_crop": {"title": "Modifier l'avatar",@@ -29,6 +30,14 @@"loading": "Chargement…","load_failed": "Impossible de charger l'image"},+ "text_avatar": {+ "title": "Icône texte",+ "preview": "Aperçu",+ "text_label": "Texte",+ "text_hint": "1–2 caractères : lettres, chiffres ou chinois. Le reste est coupé.",+ "color_label": "Couleur",+ "render_failed": "Impossible de créer l’icône. Veuillez réessayer."+ },"color_picker": {"saturation": "Saturation et luminosité","hue": "Teinte",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex c3b6f77956..2473150015 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -966,7 +966,7 @@"section_general": "Détails de l'espace de travail","logo_label": "Logo de l'espace de travail","change_logo_aria": "Changer le logo de l'espace de travail",- "click_logo_hint": "Cliquez sur le logo pour envoyer une nouvelle image",+ "click_logo_hint": "Cliquez sur le logo pour importer une image ou créer une icône texte","toast_logo_failed": "Échec de l'envoi du logo de l'espace de travail","name_label": "Nom","description_label": "Description",diff --git a/packages/views/locales/ja/common.json b/packages/views/locales/ja/common.jsonindex d934a2f499..a2b2fd2858 100644--- a/packages/views/locales/ja/common.json+++ b/packages/views/locales/ja/common.json@@ -14,7 +14,8 @@"upload_image": "画像をアップロード","emoji_label": "絵文字","more_emojis": "他の絵文字…",- "emoji_loading": "読み込み中…"+ "emoji_loading": "読み込み中…",+ "text_icon": "文字アイコン"},"avatar_crop": {"title": "アバターを編集",@@ -29,6 +30,14 @@"loading": "読み込み中…","load_failed": "画像を読み込めませんでした"},+ "text_avatar": {+ "title": "文字アイコン",+ "preview": "プレビュー",+ "text_label": "文字",+ "text_hint": "1〜2文字(英字・数字・漢字など)。超えた分は切り捨てられます。",+ "color_label": "色",+ "render_failed": "アイコンを作成できませんでした。もう一度お試しください。"+ },"color_picker": {"saturation": "彩度と明度","hue": "色相",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex b0ac3d1c60..171c5b1451 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -985,7 +985,7 @@"confirm_cancel": "キャンセル","confirm_action": "確認","change_logo_aria": "ワークスペースのロゴを変更",- "click_logo_hint": "ロゴをクリックして新しい画像をアップロード",+ "click_logo_hint": "ロゴをクリックして画像をアップロードするか、文字アイコンを作成します","toast_logo_failed": "ワークスペースのロゴをアップロードできませんでした","context_hint": "このワークスペースのエージェントに、実行のたびに渡されます。","slug_hint": "ワークスペースの URL に使われます。作成後は変更できません。",diff --git a/packages/views/locales/ko/common.json b/packages/views/locales/ko/common.jsonindex 9e3de0997b..a14e5498ff 100644--- a/packages/views/locales/ko/common.json+++ b/packages/views/locales/ko/common.json@@ -14,7 +14,8 @@"upload_image": "이미지 업로드","emoji_label": "이모지","more_emojis": "이모지 더 보기…",- "emoji_loading": "불러오는 중…"+ "emoji_loading": "불러오는 중…",+ "text_icon": "텍스트 아이콘"},"avatar_crop": {"title": "아바타 편집",@@ -29,6 +30,14 @@"loading": "불러오는 중…","load_failed": "이미지를 불러오지 못했어요"},+ "text_avatar": {+ "title": "텍스트 아이콘",+ "preview": "미리보기",+ "text_label": "텍스트",+ "text_hint": "1–2자(영문, 숫자, 한자 등). 초과한 글자는 잘립니다.",+ "color_label": "색상",+ "render_failed": "아이콘을 만들지 못했습니다. 다시 시도해 주세요."+ },"color_picker": {"saturation": "채도와 명도","hue": "색조",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 71ff975df1..e8960f4cfb 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -957,7 +957,7 @@"section_general": "워크스페이스 정보","logo_label": "워크스페이스 아이콘","change_logo_aria": "워크스페이스 로고 변경",- "click_logo_hint": "로고를 클릭하여 새 이미지를 업로드하세요",+ "click_logo_hint": "로고를 클릭해 이미지를 업로드하거나 텍스트 아이콘을 만드세요","toast_logo_failed": "워크스페이스 로고를 업로드하지 못했습니다","name_label": "이름","description_label": "설명",diff --git a/packages/views/locales/ru/common.json b/packages/views/locales/ru/common.jsonindex fd7d7446b6..2849b92e13 100644--- a/packages/views/locales/ru/common.json+++ b/packages/views/locales/ru/common.json@@ -14,7 +14,8 @@"upload_image": "Загрузить изображение","emoji_label": "Эмодзи","more_emojis": "Ещё эмодзи…",- "emoji_loading": "Загрузка…"+ "emoji_loading": "Загрузка…",+ "text_icon": "Текстовая иконка"},"avatar_crop": {"title": "Редактирование аватара",@@ -29,6 +30,14 @@"loading": "Загрузка…","load_failed": "Не удалось загрузить изображение"},+ "text_avatar": {+ "title": "Текстовая иконка",+ "preview": "Предпросмотр",+ "text_label": "Текст",+ "text_hint": "1–2 символа: буквы, цифры или иероглифы. Лишнее обрезается.",+ "color_label": "Цвет",+ "render_failed": "Не удалось создать иконку. Попробуйте ещё раз."+ },"color_picker": {"saturation": "Насыщенность и яркость","hue": "Оттенок",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 8b09aba969..51a0e797a6 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -983,7 +983,7 @@"section_general": "Данные рабочего пространства","logo_label": "Логотип рабочего пространства","change_logo_aria": "Изменить логотип рабочего пространства",- "click_logo_hint": "Нажмите на логотип, чтобы загрузить новое изображение",+ "click_logo_hint": "Нажмите на логотип, чтобы загрузить изображение или создать текстовую иконку","toast_logo_failed": "Не удалось загрузить логотип рабочего пространства","name_label": "Название","description_label": "Описание",diff --git a/packages/views/locales/zh-Hans/common.json b/packages/views/locales/zh-Hans/common.jsonindex c310baba35..6c75c93644 100644--- a/packages/views/locales/zh-Hans/common.json+++ b/packages/views/locales/zh-Hans/common.json@@ -14,7 +14,8 @@"upload_image": "上传图片","emoji_label": "表情","more_emojis": "更多表情…",- "emoji_loading": "加载中…"+ "emoji_loading": "加载中…",+ "text_icon": "文字图标"},"avatar_crop": {"title": "编辑头像",@@ -29,6 +30,14 @@"loading": "加载中…","load_failed": "图片加载失败"},+ "text_avatar": {+ "title": "文字图标",+ "preview": "预览",+ "text_label": "文字",+ "text_hint": "1–2 个字,字母、数字、汉字都可以,多出的会截掉。",+ "color_label": "颜色",+ "render_failed": "图标生成失败,请重试。"+ },"color_picker": {"saturation": "饱和度与明度","hue": "色相",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 39b4a1f5fb..be53a08788 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -957,7 +957,7 @@"section_general": "工作区信息","logo_label": "工作区图标","change_logo_aria": "更换工作区图标",- "click_logo_hint": "点击图标上传新图片",+ "click_logo_hint": "点击图标上传图片,或生成文字图标","toast_logo_failed": "上传工作区图标失败","name_label": "名称","description_label": "描述",diff --git a/packages/views/locales/zh-Hant/common.json b/packages/views/locales/zh-Hant/common.jsonindex 0b596d49cc..dd5ffbec56 100644--- a/packages/views/locales/zh-Hant/common.json+++ b/packages/views/locales/zh-Hant/common.json@@ -14,7 +14,8 @@"upload_image": "上傳圖片","emoji_label": "表情","more_emojis": "更多表情…",- "emoji_loading": "載入中…"+ "emoji_loading": "載入中…",+ "text_icon": "文字圖示"},"avatar_crop": {"title": "編輯頭像",@@ -29,6 +30,14 @@"loading": "載入中…","load_failed": "圖片載入失敗"},+ "text_avatar": {+ "title": "文字圖示",+ "preview": "預覽",+ "text_label": "文字",+ "text_hint": "1–2 個字,字母、數字、漢字都可以,多出的會截掉。",+ "color_label": "顏色",+ "render_failed": "圖示產生失敗,請重試。"+ },"color_picker": {"saturation": "飽和度與明度","hue": "色相",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex 4da9730e12..932a1498f4 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -957,7 +957,7 @@"section_general": "工作區資訊","logo_label": "工作區圖示","change_logo_aria": "更換工作區圖示",- "click_logo_hint": "點選圖示上傳新圖片",+ "click_logo_hint": "點擊圖示上傳圖片,或產生文字圖示","toast_logo_failed": "上傳工作區圖示失敗","name_label": "名稱","description_label": "描述",diff --git a/packages/views/settings/components/workspace-tab.tsx b/packages/views/settings/components/workspace-tab.tsxindex 01619721d3..b6efa8a8a5 100644--- a/packages/views/settings/components/workspace-tab.tsx+++ b/packages/views/settings/components/workspace-tab.tsx@@ -336,6 +336,7 @@ export function WorkspaceTab() {name={workspace.name}size={64}disabled={!canManageWorkspace}+ textIconEnabledariaLabel={t(($) => $.workspace.change_logo_aria)}onUploaded={async (url) => {try {