Skip to content
TypeScript

fix(web): chips drop their pill and stay readable on every theme (#25066)

oliver4914cdd98f3d
diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx
index ba5b4625259..af5a200e264 100644
--- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx
+++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx
@@ -1,4 +1,4 @@
-import { documentIconColorForFileName } from "~/pierre-icons";
+import { documentChipKindForFileName } from "~/pierre-icons";
import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills";
import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
import {
@@ -46,7 +46,6 @@ import {
useLayoutEffect,
useRef,
useState,
- type CSSProperties,
type KeyboardEvent as ReactKeyboardEvent,
type RefObject,
} from "react";
@@ -232,7 +231,7 @@ function resolvedThemeFromDocument(): "light" | "dark" {
}
const CHIP_NODE_SELECTION_CLASS_NAME =
- "relative inline-flex select-none items-center align-middle leading-none data-[composer-chip-selected]:after:pointer-events-none data-[composer-chip-selected]:after:absolute data-[composer-chip-selected]:after:inset-0 data-[composer-chip-selected]:after:rounded-sm data-[composer-chip-selected]:after:bg-[Highlight] data-[composer-chip-selected]:after:opacity-30 data-[composer-chip-selected]:after:content-['']";
+ "relative inline-flex min-w-0 max-w-full select-none items-baseline data-[composer-chip-selected]:after:pointer-events-none data-[composer-chip-selected]:after:absolute data-[composer-chip-selected]:after:inset-0 data-[composer-chip-selected]:after:rounded-sm data-[composer-chip-selected]:after:bg-[Highlight] data-[composer-chip-selected]:after:opacity-30 data-[composer-chip-selected]:after:content-['']";
const ComposerMentionExtension = Node.create({
name: "composer-mention",
@@ -260,11 +259,9 @@ const ComposerMentionExtension = Node.create({
function ComposerMentionNodeView({ node }: NodeViewProps) {
const actions = use(ComposerContextActionsContext);
const path = (node.attrs.path as string) ?? "";
- const accent = documentIconColorForFileName(path);
const chip = (
<ContextChip
- kind="mention"
- style={accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined}
+ kind={documentChipKindForFileName(path) ?? "mention"}
dir="ltr"
render={<button type="button" />}
onClick={() => actions.openMention(path)}
@@ -442,7 +439,7 @@ function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) {
return (
<NodeViewWrapper
as="span"
- className={cn(CHIP_NODE_SELECTION_CLASS_NAME, "min-w-0 max-w-full")}
+ className={CHIP_NODE_SELECTION_CLASS_NAME}
contentEditable={false}
spellCheck={false}
data-composer-citation-chip="true"
diff --git a/apps/web/src/components/ContextChip.browser.test.tsx b/apps/web/src/components/ContextChip.browser.test.tsx
new file mode 100644
index 00000000000..ed13d4996af
--- /dev/null
+++ b/apps/web/src/components/ContextChip.browser.test.tsx
@@ -0,0 +1,42 @@
+import { FileIcon } from "lucide-react";
+import { describe, expect, it } from "vite-plus/test";
+
+import "~/index.css";
+import { render } from "../../test/render";
+import { ContextChip, ContextChipLabel } from "./ContextChip";
+
+// An empty inline-block's bottom edge sits on the baseline of the line it is in.
+function BaselineMarker(props: { id: string }) {
+ return <span data-baseline={props.id} className="inline-block size-0" />;
+}
+
+describe("ContextChip", () => {
+ it("sets its label on the sentence baseline at the sentence size without growing the line", async () => {
+ await using screen = await render(
+ <p className="w-[60ch] text-sm leading-relaxed">
+ Open
+ <BaselineMarker id="text" /> the{" "}
+ <ContextChip kind="mention" render={<button type="button" />}>
+ <FileIcon />
+ <ContextChipLabel>
+ src/
+ <BaselineMarker id="chip" />
+ Typography.tsx
+ </ContextChipLabel>
+ </ContextChip>{" "}
+ file
+ </p>,
+ );
+ const paragraph = screen.container.querySelector("p")!;
+ const label = screen.container.querySelector<HTMLElement>('[data-slot="context-chip-label"]')!;
+ const baseline = (id: string) =>
+ screen.container.querySelector(`[data-baseline="${id}"]`)!.getBoundingClientRect().bottom;
+
+ expect(getComputedStyle(label).fontSize).toBe(getComputedStyle(paragraph).fontSize);
+ expect(Math.abs(baseline("chip") - baseline("text"))).toBeLessThanOrEqual(0.5);
+ expect(paragraph.getBoundingClientRect().height).toBeCloseTo(
+ Number.parseFloat(getComputedStyle(paragraph).lineHeight),
+ 0,
+ );
+ });
+});
diff --git a/apps/web/src/components/ContextChip.tsx b/apps/web/src/components/ContextChip.tsx
index 72633d478e1..b6abe578770 100644
--- a/apps/web/src/components/ContextChip.tsx
+++ b/apps/web/src/components/ContextChip.tsx
@@ -6,60 +6,40 @@ import type * as React from "react";
import { cn } from "~/lib/utils";
const contextChipVariants = cva(
- "inline-flex h-[1.41em] max-w-full items-center gap-[0.33em] rounded-[0.5em] border px-[0.5em] align-middle font-medium text-[0.86em] leading-none [&_svg]:block [&_svg]:size-[1.17em] [&_svg]:shrink-0 [&_svg]:self-center [button&,a&,[data-popup-open]&]:cursor-pointer [button&,a&]:transition-colors [button&,a&]:motion-reduce:transition-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-foreground disabled:cursor-default",
+ "inline-flex max-w-full items-center gap-[0.2em] font-medium leading-[normal] text-(--context-chip-ink) [--context-chip-ink:var(--context-chip-accent)] [--document-icon-stroke:var(--context-chip-ink)] [&_svg]:block [&_svg]:size-[1em] [&_svg]:shrink-0 [&_svg]:self-center [button&,a&,[data-popup-open]&]:cursor-pointer focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-current rounded-sm disabled:cursor-default",
{
defaultVariants: { kind: "neutral" },
variants: {
kind: {
- neutral: "border-border/70 bg-accent/40 text-foreground",
- image: "[--context-chip-accent:oklch(0.62_0.16_16)]",
- video: "[--context-chip-accent:oklch(0.62_0.16_48)]",
- file: "[--context-chip-accent:oklch(0.62_0.136_237)]",
- mention: "[--context-chip-accent:oklch(0.62_0.11_215)]",
- terminal: "[--context-chip-accent:oklch(0.62_0.134_163)]",
- element: "[--context-chip-accent:oklch(0.62_0.134_70)]",
- "preview-annotation": "[--context-chip-accent:oklch(0.62_0.134_70)]",
- "review-comment": "[--context-chip-accent:oklch(0.62_0.16_292)]",
- "pull-request": "[--context-chip-accent:oklch(0.62_0.16_277)]",
- "pr-open": "[--context-chip-accent:oklch(0.62_0.134_163)]",
- "pr-draft": "[--context-chip-accent:oklch(0.62_0.02_259)]",
- "pr-merged": "[--context-chip-accent:oklch(0.62_0.16_292)]",
- "pr-closed": "[--context-chip-accent:oklch(0.62_0.16_16)]",
- skill: "[--context-chip-accent:oklch(0.62_0.16_322)]",
- thread: "[--context-chip-accent:oklch(0.62_0.12_190)]",
- citation: "[--context-chip-accent:oklch(0.62_0.16_259)]",
+ neutral: "[--context-chip-accent:currentColor]",
+ image: "[--context-chip-accent:var(--context-chip-image)]",
+ video: "[--context-chip-accent:var(--context-chip-video)]",
+ file: "[--context-chip-accent:var(--context-chip-file)]",
+ mention: "[--context-chip-accent:var(--context-chip-mention)]",
+ terminal: "[--context-chip-accent:var(--context-chip-terminal)]",
+ element: "[--context-chip-accent:var(--context-chip-element)]",
+ "preview-annotation": "[--context-chip-accent:var(--context-chip-preview-annotation)]",
+ "review-comment": "[--context-chip-accent:var(--context-chip-review-comment)]",
+ "pull-request": "[--context-chip-accent:var(--context-chip-pull-request)]",
+ "pr-open": "[--context-chip-accent:var(--context-chip-pr-open)]",
+ "pr-draft": "[--context-chip-accent:var(--context-chip-pr-draft)]",
+ "pr-merged": "[--context-chip-accent:var(--context-chip-pr-merged)]",
+ "pr-closed": "[--context-chip-accent:var(--context-chip-pr-closed)]",
+ skill: "[--context-chip-accent:var(--context-chip-skill)]",
+ thread: "[--context-chip-accent:var(--context-chip-thread)]",
+ citation: "[--context-chip-accent:var(--context-chip-citation)]",
+ "doc-pdf": "[--context-chip-accent:var(--context-chip-doc-pdf)]",
+ "doc-word": "[--context-chip-accent:var(--context-chip-doc-word)]",
+ "doc-spreadsheet": "[--context-chip-accent:var(--context-chip-doc-spreadsheet)]",
+ "doc-slides": "[--context-chip-accent:var(--context-chip-doc-slides)]",
+ "doc-epub": "[--context-chip-accent:var(--context-chip-doc-epub)]",
},
state: {
- unresolved: "border-dashed",
- invalid: "",
+ unresolved: "data-[state=unresolved]:[--context-chip-accent:currentColor]",
+ invalid:
+ "data-[state=invalid]:[--context-chip-accent:var(--context-chip-invalid,var(--destructive-foreground))]",
},
},
- compoundVariants: [
- {
- kind: [
- "image",
- "video",
- "file",
- "mention",
- "terminal",
- "element",
- "preview-annotation",
- "review-comment",
- "pull-request",
- "pr-open",
- "pr-draft",
- "pr-merged",
- "pr-closed",
- "skill",
- "thread",
- "citation",
- ],
- className:
- "[--context-chip-border:color-mix(in_oklab,var(--context-chip-accent)_34%,var(--contrast-border))] [--context-chip-border-hover:color-mix(in_oklab,var(--context-chip-accent)_48%,var(--contrast-border))] [--context-chip-foreground:color-mix(in_oklab,var(--context-chip-accent)_22%,var(--contrast-foreground))] border-(--context-chip-border) bg-(--context-chip-accent)/11 text-(--context-chip-foreground) [button:enabled&,a&]:hover:border-(--context-chip-border-hover) [button:enabled&,a&]:hover:bg-(--context-chip-accent)/17",
- },
- { state: "unresolved", className: "text-foreground" },
- { state: "invalid", className: "border-destructive/35 bg-destructive/8 text-destructive" },
- ],
},
);
@@ -86,7 +66,10 @@ function ContextChip({ className, kind, state, render, ...props }: ContextChipPr
function ContextChipLabel({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
- className={cn("block min-w-0 self-center truncate leading-tight", className)}
+ className={cn(
+ "block min-w-0 self-baseline overflow-x-clip text-ellipsis whitespace-nowrap underline decoration-transparent decoration-1 underline-offset-[0.2em] transition-colors motion-reduce:transition-none [:is(button:enabled,a):hover>&]:decoration-current",
+ className,
+ )}
data-slot="context-chip-label"
{...props}
/>
@@ -96,7 +79,7 @@ function ContextChipLabel({ className, ...props }: React.ComponentProps<"span">)
function ContextChipAction({ className, render, ...props }: useRender.ComponentProps<"button">) {
const defaultProps = {
className: cn(
- "ml-[0.17em] inline-flex size-[1.17em] shrink-0 cursor-pointer items-center justify-center rounded-sm text-current transition-colors hover:bg-(--context-chip-accent,var(--color-foreground))/17 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring motion-reduce:transition-none [&_svg]:size-[0.85em]",
+ "ml-[0.17em] inline-flex size-[1em] shrink-0 cursor-pointer items-center justify-center rounded-sm text-current transition-colors hover:bg-(--context-chip-accent,var(--color-foreground))/17 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring motion-reduce:transition-none [&_svg]:size-[0.85em]",
className,
),
"data-slot": "context-chip-action",
diff --git a/apps/web/src/components/ThreadContextChip.tsx b/apps/web/src/components/ThreadContextChip.tsx
index 5f1a4202f1d..715a210f4e9 100644
--- a/apps/web/src/components/ThreadContextChip.tsx
+++ b/apps/web/src/components/ThreadContextChip.tsx
@@ -30,7 +30,7 @@ export function ThreadContextChip(props: {
className="no-underline"
>
{project ? (
- <ProjectFavicon project={project} className="size-[1.17em] self-center" />
+ <ProjectFavicon project={project} className="size-[1em] self-center" />
) : (
<MessagesSquareIcon />
)}
diff --git a/apps/web/src/components/chat/AssistantCitationChip.tsx b/apps/web/src/components/chat/AssistantCitationChip.tsx
index dd21f7c4668..1e97f00319c 100644
--- a/apps/web/src/components/chat/AssistantCitationChip.tsx
+++ b/apps/web/src/components/chat/AssistantCitationChip.tsx
@@ -124,7 +124,7 @@ export function AssistantCitationChip({
const composerSourceLink = (
<Link
{...sourceLinkProps}
- className="inline-flex h-full min-w-0 items-center gap-[0.33em] rounded-sm text-inherit no-underline focus-visible:outline-2 focus-visible:outline-foreground"
+ className="inline-flex min-w-0 items-center gap-[0.2em] self-baseline text-inherit no-underline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-current rounded-sm"
aria-label={`View cited assistant text: ${label}`}
>
<QuoteIcon aria-hidden="true" />
diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx
index 872ce0de8dc..6a250f93d21 100644
--- a/apps/web/src/components/chat/MarkdownFileLink.tsx
+++ b/apps/web/src/components/chat/MarkdownFileLink.tsx
@@ -5,13 +5,13 @@ import {
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
-import { memo, type CSSProperties, type MouseEvent as ReactMouseEvent } from "react";
+import { memo, type MouseEvent as ReactMouseEvent } from "react";
import { readLocalApi } from "../../localApi";
import { cn } from "../../lib/utils";
import { shouldOpenMarkdownFileLinkInEditor } from "../../markdown-links";
import type { markdownFileCopyPaths } from "../../markdownFileHostPath";
-import { documentIconColorForFileName } from "../../pierre-icons";
+import { documentChipKindForFileName } from "../../pierre-icons";
import { ContextChip } from "../ContextChip";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -321,8 +321,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
canOpenInBrowser,
canOpenInPanel,
});
- const accent = documentIconColorForFileName(iconPath);
- const chipStyle = accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined;
+ const chipKind = documentChipKindForFileName(iconPath) ?? "mention";
return (
<Tooltip>
@@ -330,11 +329,10 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
render={
hasPrimaryAction ? (
<ContextChip
- kind="mention"
+ kind={chipKind}
dir="ltr"
render={<a href={href} />}
className={MARKDOWN_FILE_LINK_CLASS_NAME}
- style={chipStyle}
data-markdown-copy={copyMarkdown}
onClick={(event) => {
event.preventDefault();
@@ -360,13 +358,12 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({
</ContextChip>
) : (
<ContextChip
- kind="mention"
+ kind={chipKind}
dir="ltr"
render={<button type="button" />}
aria-label={`File options for ${label}`}
aria-haspopup="menu"
className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")}
- style={chipStyle}
data-markdown-copy={copyMarkdown}
onClick={handleContextMenu}
onContextMenu={handleContextMenu}
diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx
index 203fb34d2db..342b903847c 100644
--- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx
+++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx
@@ -75,6 +75,9 @@ import {
import { UserMessageContextReferenceChip } from "./UserMessageContextChips";
import { resolvePreviewAnnotationImage } from "./TimelineUserMessageRow.logic";
+const BUBBLE_CHIP_CLASS_NAME =
+ "[&_[data-slot=context-chip]]:[--context-chip-ink:var(--context-chip-message,var(--context-chip-accent))]";
+
function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) {
const ctx = use(TimelineRowCtx);
// Row updates rebuild attachment objects, so the asset follows only the
@@ -165,6 +168,7 @@ function AutomationMessageRow({ row }: { row: Extract<TimelineRow, { kind: "mess
<div
className={cn(
"min-w-0 max-w-[80%] rounded-2xl bg-message text-message-foreground",
+ BUBBLE_CHIP_CLASS_NAME,
expanded && "w-full",
)}
>
@@ -454,6 +458,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
<div
className={cn(
"relative min-w-0 max-w-[80%] rounded-2xl text-message-foreground",
+ BUBBLE_CHIP_CLASS_NAME,
userMessage.attribution === "guest" ? guestBubbleClassName(false) : "bg-message",
!folded && "p-3",
folded && expanded && "w-full",
diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsx
index b1179a83c77..25bc56ccf99 100644
--- a/apps/web/src/components/chat/UserMessageContextChips.tsx
+++ b/apps/web/src/components/chat/UserMessageContextChips.tsx
@@ -1,4 +1,4 @@
-import { documentIconColorForFileName } from "~/pierre-icons";
+import { documentChipKindForFileName } from "~/pierre-icons";
import { isSvgAttachment } from "@t3tools/shared/image";
import { useRenderedAppearance } from "../../hooks/useTheme";
import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
@@ -6,7 +6,7 @@ import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";
import { useRightPanelStore } from "~/rightPanelStore";
import { COMPOSER_CONTEXT_KINDS } from "@t3tools/contracts";
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
-import { use, type CSSProperties, type ReactNode } from "react";
+import { use, type ReactNode } from "react";
import { FileDiff } from "@pierre/diffs/react";
import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
import {
@@ -65,14 +65,12 @@ function UserMessageMentionChip(props: {
copyMarkdown: string;
}) {
const ctx = use(TimelineRowCtx);
- const accent = documentIconColorForFileName(props.record.path);
return (
<Tooltip>
<TooltipTrigger
render={
<ContextChip
- kind="mention"
- style={accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined}
+ kind={documentChipKindForFileName(props.record.path) ?? "mention"}
render={<button type="button" />}
aria-label={`Preview ${props.record.path}`}
data-markdown-copy={props.copyMarkdown}
diff --git a/apps/web/src/components/contextChipParts.tsx b/apps/web/src/components/contextChipParts.tsx
index 9fac67baec2..46476d0388e 100644
--- a/apps/web/src/components/contextChipParts.tsx
+++ b/apps/web/src/components/contextChipParts.tsx
@@ -1,15 +1,8 @@
import type { EnvironmentId, PullRequestContextMetadata } from "@t3tools/contracts";
import { CircleDashedIcon, FilmIcon, ImageIcon } from "lucide-react";
-import {
- useEffect,
- useState,
- type ComponentProps,
- type CSSProperties,
- type MouseEvent,
- type ReactNode,
-} from "react";
+import { useEffect, useState, type ComponentProps, type MouseEvent, type ReactNode } from "react";
import { useAssetUrlState } from "~/assets/assetUrls";
-import { documentIconColorForFileName } from "~/pierre-icons";
+import { documentChipKindForFileName } from "~/pierre-icons";
import { PULL_REQUEST_STATE_PRESENTATION } from "~/components/pullRequest/pullRequestIcons";
import type { PullRequestContextDisplayState } from "~/lib/composerContextRecords";
@@ -139,32 +132,6 @@ export function PullRequestChip(props: {
);
}
-function averageImageColor(image: HTMLImageElement): string | undefined {
- try {
- const canvas = document.createElement("canvas");
- canvas.width = canvas.height = 16;
- const context = canvas.getContext("2d");
- if (!context) return;
- context.drawImage(image, 0, 0, 16, 16);
- const { data } = context.getImageData(0, 0, 16, 16);
- let red = 0;
- let green = 0;
- let blue = 0;
- let alpha = 0;
- for (let index = 0; index < data.length; index += 4) {
- const weight = data[index + 3]!;
- red += data[index]! * weight;
- green += data[index + 1]! * weight;
- blue += data[index + 2]! * weight;
- alpha += weight;
- }
- if (alpha === 0) return;
- return `rgb(${Math.round(red / alpha)} ${Math.round(green / alpha)} ${Math.round(blue / alpha)})`;
- } catch {
- return;
- }
-}
-
export function ImageChipButton({
name,
previewUrl,
@@ -172,7 +139,6 @@ export function ImageChipButton({
suffix,
disabled,
onPreviewError,
- style,
...props
}: Omit<ComponentProps<typeof ContextChip>, "kind" | "render"> & {
name: string;
@@ -182,31 +148,20 @@ export function ImageChipButton({
disabled?: boolean | undefined;
onPreviewError?: (() => void) | undefined;
}) {
- const [sample, setSample] = useState<{ url: string; color: string | undefined }>();
- const [corsFailedUrl, setCorsFailedUrl] = useState<string>();
- const accent = sample?.url === previewUrl ? sample?.color : undefined;
return (
<ContextChip
kind="image"
render={<button type="button" disabled={disabled} />}
aria-label={`Image attachment, ${name}, ${size}`}
- style={{ ...style, ...(accent ? { "--context-chip-accent": accent } : {}) } as CSSProperties}
{...props}
>
{previewUrl ? (
<img
key={previewUrl}
- crossOrigin={corsFailedUrl === previewUrl ? undefined : "anonymous"}
src={previewUrl}
alt=""
- className="size-[1.17em] shrink-0 rounded-sm object-cover"
- onError={() => {
- if (corsFailedUrl === previewUrl) onPreviewError?.();
- else setCorsFailedUrl(previewUrl);
- }}
- onLoad={(event) =>
- setSample({ url: previewUrl, color: averageImageColor(event.currentTarget) })
- }
+ className="size-[1em] shrink-0 self-center rounded-sm object-cover"
+ onError={onPreviewError}
/>
) : (
<ImageIcon />
@@ -243,15 +198,13 @@ export function FileChip(props: {
}) {
if (props.svgPreview && !props.unresolved) return <SvgFileChip {...props} />;
const content = <FileChipContent {...props} />;
- const accent = props.isVideo ? undefined : documentIconColorForFileName(props.name);
const state = props.unresolved
? ("unresolved" as const)
: props.error
? ("invalid" as const)
: null;
const attributes = {
- kind: props.isVideo ? "video" : "file",
- style: accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined,
+ kind: props.isVideo ? "video" : (documentChipKindForFileName(props.name) ?? "file"),
...(state ? { state } : {}),
"aria-label": [props.accessibleLabel, props.suffix].filter(Boolean).join(", "),
"data-markdown-copy": props.copyMarkdown,
@@ -348,10 +301,13 @@ function FileChipContent(props: {
isVideo: boolean;
theme: "light" | "dark";
suffix?: string | null;
+ unresolved?: boolean;
}) {
return (
<>
- {props.isVideo ? (
+ {props.unresolved ? (
+ <CircleDashedIcon />
+ ) : props.isVideo ? (
<FilmIcon />
) : (
<PierreEntryIcon pathValue={props.name} kind="file" theme={props.theme} />
diff --git a/apps/web/src/components/files/AudioPreview.tsx b/apps/web/src/components/files/AudioPreview.tsx
index 735a56e524e..0a8f4bcfe16 100644
--- a/apps/web/src/components/files/AudioPreview.tsx
+++ b/apps/web/src/components/files/AudioPreview.tsx
@@ -111,7 +111,7 @@ function AudioChip(props: AudioPreviewProps) {
<ContextChip
kind="file"
{...(props.failed ? { state: "invalid" as const } : {})}
- className="relative isolate overflow-hidden has-[button:enabled]:hover:border-(--context-chip-border-hover) has-[button:enabled]:hover:bg-(--context-chip-accent)/17"
+ className="relative isolate overflow-hidden"
title={props.failed ? "Audio unavailable. Open the file or retry playback." : props.name}
>
<span
@@ -120,7 +120,7 @@ function AudioChip(props: AudioPreviewProps) {
style={{ width: `${duration > 0 ? Math.min(100, (elapsed / duration) * 100) : 0}%` }}
/>
<ContextChipAction
- className="ml-0 [&_svg]:size-[1.17em]"
+ className="ml-0 [&_svg]:size-[1em]"
aria-label={`${props.failed ? "Audio unavailable. " : ""}${action} ${props.name}`}
disabled={loading}
onClick={() => {
@@ -154,7 +154,7 @@ function AudioChip(props: AudioPreviewProps) {
middleTruncateAttachmentName(props.name)
)}
</ContextChipLabel>
- <span className="shrink-0 text-3xs text-current">
+ <span className="shrink-0 self-baseline text-3xs text-current">
{props.failed
? "Unavailable"
: loading
diff --git a/apps/web/src/lib/contextChipAccents.ts b/apps/web/src/lib/contextChipAccents.ts
new file mode 100644
index 00000000000..683da019443
--- /dev/null
+++ b/apps/web/src/lib/contextChipAccents.ts
@@ -0,0 +1,29 @@
+export const CONTEXT_CHIP_ACCENTS = {
+ image: "oklch(0.62 0.16 16)",
+ video: "oklch(0.62 0.16 48)",
+ file: "oklch(0.62 0.136 237)",
+ mention: "oklch(0.62 0.11 215)",
+ terminal: "oklch(0.62 0.134 163)",
+ element: "oklch(0.62 0.134 70)",
+ "preview-annotation": "oklch(0.62 0.134 70)",
+ "review-comment": "oklch(0.62 0.16 292)",
+ "pull-request": "oklch(0.62 0.16 277)",
+ "pr-open": "oklch(0.62 0.134 163)",
+ "pr-draft": "oklch(0.62 0.02 259)",
+ "pr-merged": "oklch(0.62 0.16 292)",
+ "pr-closed": "oklch(0.62 0.16 16)",
+ skill: "oklch(0.62 0.16 322)",
+ thread: "oklch(0.62 0.12 190)",
+ citation: "oklch(0.62 0.16 259)",
+ "doc-pdf": "oklch(0.62 0.16 24)",
+ "doc-word": "oklch(0.62 0.136 248)",
+ "doc-spreadsheet": "oklch(0.62 0.134 148)",
+ "doc-slides": "oklch(0.62 0.134 56)",
+ "doc-epub": "oklch(0.62 0.16 291)",
+} as const;
+
+export type ContextChipAccentKind = keyof typeof CONTEXT_CHIP_ACCENTS;
+
+export function contextChipColorVariable(kind: ContextChipAccentKind): string {
+ return `--context-chip-${kind}`;
+}
diff --git a/apps/web/src/pierre-icons.ts b/apps/web/src/pierre-icons.ts
index 882fbb83a9f..852ccc26e12 100644
--- a/apps/web/src/pierre-icons.ts
+++ b/apps/web/src/pierre-icons.ts
@@ -6,6 +6,8 @@ import {
import { VIDEO_FILE_EXTENSIONS } from "@t3tools/shared/video";
import { fileIconPathForMimeType } from "@t3tools/shared/mediaPreview";
+import type { ContextChipAccentKind } from "~/lib/contextChipAccents";
+
export interface PierreIconResolution {
name: string;
token?: string;
@@ -51,7 +53,7 @@ const T3_FILE_ICON_SPRITE = `
</symbol>
<!-- Lucide File Type, File Text, File Spreadsheet, Presentation and Book Open icons, ISC license. -->
<symbol id="t3-file-icon-pdf" viewBox="0 0 24 24">
- <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-pdf"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <g fill="none" style="stroke: var(--document-icon-stroke, ${DOCUMENT_ICON_COLORS["t3-file-icon-pdf"]})" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />
<path d="M14 2v5a1 1 0 0 0 1 1h5" />
<path d="M11 18h2" />
@@ -60,7 +62,7 @@ const T3_FILE_ICON_SPRITE = `
</g>
</symbol>
<symbol id="t3-file-icon-word" viewBox="0 0 24 24">
- <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-word"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <g fill="none" style="stroke: var(--document-icon-stroke, ${DOCUMENT_ICON_COLORS["t3-file-icon-word"]})" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />
<path d="M14 2v5a1 1 0 0 0 1 1h5" />
<path d="M10 9H8" />
@@ -69,7 +71,7 @@ const T3_FILE_ICON_SPRITE = `
</g>
</symbol>
<symbol id="t3-file-icon-spreadsheet" viewBox="0 0 24 24">
- <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-spreadsheet"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <g fill="none" style="stroke: var(--document-icon-stroke, ${DOCUMENT_ICON_COLORS["t3-file-icon-spreadsheet"]})" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />
<path d="M14 2v5a1 1 0 0 0 1 1h5" />
<path d="M8 13h2" />
@@ -79,14 +81,14 @@ const T3_FILE_ICON_SPRITE = `
</g>
</symbol>
<symbol id="t3-file-icon-slides" viewBox="0 0 24 24">
- <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-slides"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <g fill="none" style="stroke: var(--document-icon-stroke, ${DOCUMENT_ICON_COLORS["t3-file-icon-slides"]})" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 3h20" />
<path d="M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3" />
<path d="m7 21 5-5 5 5" />
</g>
</symbol>
<symbol id="t3-file-icon-epub" viewBox="0 0 24 24">
- <g fill="none" style="stroke: ${DOCUMENT_ICON_COLORS["t3-file-icon-epub"]}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <g fill="none" style="stroke: var(--document-icon-stroke, ${DOCUMENT_ICON_COLORS["t3-file-icon-epub"]})" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 7v14" />
<path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />
</g>
@@ -244,9 +246,17 @@ export function resolvePierreIconForEntry(
: icon;
}
-export function documentIconColorForFileName(fileName: string) {
+const DOCUMENT_CHIP_KINDS: Readonly<Record<string, ContextChipAccentKind>> = {
+ "t3-file-icon-pdf": "doc-pdf",
+ "t3-file-icon-word": "doc-word",
+ "t3-file-icon-spreadsheet": "doc-spreadsheet",
+ "t3-file-icon-slides": "doc-slides",
+ "t3-file-icon-epub": "doc-epub",
+};
+
+export function documentChipKindForFileName(fileName: string) {
const icon = resolvePierreIconForEntry(fileName, "file");
- return icon ? DOCUMENT_ICON_COLORS[icon.name] : undefined;
+ return icon ? DOCUMENT_CHIP_KINDS[icon.name] : undefined;
}
export function hasSpecificPierreIconForFileName(fileName: string): boolean {
diff --git a/apps/web/src/themePalette.browser.test.ts b/apps/web/src/themePalette.browser.test.ts
new file mode 100644
index 00000000000..51136eb7af5
--- /dev/null
+++ b/apps/web/src/themePalette.browser.test.ts
@@ -0,0 +1,56 @@
+import { converter } from "culori/fn";
+import { describe, expect, it } from "vite-plus/test";
+
+import "~/index.css";
+import { getStandardPaintedThemeColors } from "./themePalette";
+
+const toRgb = converter("rgb");
+
+function paintedChannels(variable: string, canvas: readonly number[] = [0, 0, 0]): number[] {
+ const probe = document.createElement("div");
+ probe.style.backgroundColor = `var(${variable})`;
+ document.body.append(probe);
+ try {
+ const color = toRgb(getComputedStyle(probe).backgroundColor)!;
+ const alpha = color.alpha ?? 1;
+ return [color.r, color.g, color.b].map(
+ (channel, index) => (channel * alpha + (canvas[index]! / 255) * (1 - alpha)) * 255,
+ );
+ } finally {
+ probe.remove();
+ }
+}
+
+describe("standard painted theme colors", () => {
+ it("match the chip surfaces index.css paints", () => {
+ const root = document.documentElement;
+ try {
+ for (const redesign of [false, true, false]) {
+ root.toggleAttribute("data-redesign", redesign);
+ for (const appearance of ["light", "dark"] as const) {
+ root.classList.toggle("dark", appearance === "dark");
+ const colors = getStandardPaintedThemeColors(appearance, redesign);
+ const canvas = paintedChannels("--background");
+ for (const [variable, role] of [
+ ["--background", "canvas"],
+ ["--card", "surface"],
+ ["--surface-raised", "surfaceRaised"],
+ ["--message-surface", "messageSurface"],
+ ] as const) {
+ const expected = toRgb(colors[role])!;
+ const painted = paintedChannels(variable, canvas);
+ [expected.r, expected.g, expected.b].forEach((channel, index) => {
+ expect(
+ Math.abs(channel * 255 - painted[index]!),
+ `${appearance} ${role}`,
+ ).toBeLessThan(1.5);
+ });
+ }
+ }
+ }
+ } finally {
+ root.removeAttribute("data-redesign");
+ root.classList.remove("dark");
+ }
+ });
+});
diff --git a/apps/web/src/themePalette.test.ts b/apps/web/src/themePalette.test.ts
index fc1962566bc..f6903655449 100644
--- a/apps/web/src/themePalette.test.ts
+++ b/apps/web/src/themePalette.test.ts
@@ -2,7 +2,11 @@ import { describe, expect, it, vi } from "vite-plus/test";
import { converter } from "culori/fn";
import { BUILT_IN_THEMES } from "@t3tools/shared/themePalettes";
+import { CONTEXT_CHIP_ACCENTS, contextChipColorVariable } from "./lib/contextChipAccents";
+
import {
+ applyThemePalette,
+ contextChipVariables,
getThemeColorsForMode,
getThemeModes,
getCustomThemes,
@@ -539,6 +543,153 @@ describe("theme files", () => {
});
});
+describe("context chip colors", () => {
+ it.each([
+ ["#ffffff", 5],
+ ["#777777", 4.5],
+ ] as const)(
+ "chooses readable chip lightness on %s when the text is medium gray",
+ (surface, minimum) => {
+ const colors = {
+ ...getStandardThemeColors("light"),
+ canvas: surface,
+ surface,
+ surfaceRaised: surface,
+ messageSurface: surface,
+ text: "#767676",
+ messageForeground: "#767676",
+ };
+ for (const color of Object.values(contextChipVariables(colors))) {
+ expect(contrastRatio(color, surface)).toBeGreaterThanOrEqual(minimum);
+ }
+ },
+ );
+
+ const toOklch = converter("oklch");
+ const toRgb = converter("rgb");
+ // Surfaces stay unrounded, as CSS paints them; the chip is the 8-bit hex the solver returns.
+ const paintedContrastRatio = (chip: string, surface: string, canvas: string) => {
+ const channels = (value: string) => {
+ const rgb = toRgb(value)!;
+ return [rgb.r, rgb.g, rgb.b].map((channel) => Math.min(1, Math.max(0, channel)));
+ };
+ const back = channels(canvas);
+ const alpha = toRgb(surface)!.alpha ?? 1;
+ const painted = channels(surface).map(
+ (channel, index) => back[index]! * (1 - alpha) + channel * alpha,
+ );
+ const luminance = (rgb: number[]) =>
+ rgb
+ .map((channel) =>
+ channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4,
+ )
+ .reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);
+ const first = luminance(channels(asHex(chip)));
+ const second = luminance(painted);
+ return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
+ };
+ const palettes = [
+ getStandardThemeColors("light"),
+ getStandardThemeColors("dark"),
+ ...BUILT_IN_THEMES.flatMap((theme) =>
+ getThemeModes(theme).map((mode) => getThemeColorsForMode(theme, mode)!),
+ ),
+ ];
+
+ it("reads at 5:1 on every chip surface of every built-in theme and keeps each hue", () => {
+ for (const colors of palettes) {
+ const variables = contextChipVariables(colors);
+ expect(variables["--context-chip-message"]).toBeUndefined();
+ for (const [kind, accent] of Object.entries(CONTEXT_CHIP_ACCENTS)) {
+ const chip =
+ variables[contextChipColorVariable(kind as keyof typeof CONTEXT_CHIP_ACCENTS)]!;
+ for (const surface of [
+ colors.canvas,
+ colors.surface,
+ colors.surfaceRaised,
+ colors.messageSurface,
+ ]) {
+ expect(paintedContrastRatio(chip, surface, colors.canvas)).toBeGreaterThanOrEqual(5);
+ }
+ const solved = toOklch(chip)!;
+ if ((solved.c ?? 0) > 0.04) {
+ const drift = Math.abs((((solved.h ?? 0) - toOklch(accent)!.h! + 540) % 360) - 180);
+ expect(drift).toBeLessThan(4);
+ }
+ }
+ }
+ });
+
+ it("reads at 5:1 on the standard surfaces as index.css paints them", () => {
+ const painted = {
+ light: ["#fcfcfc", "#ffffff", "#ebebed"],
+ dark: ["#000000", "#0a0a0a", "#111111", "#141414", "#1e1e1e"],
+ } as const;
+ const properties = new Map<string, string>();
+ vi.stubGlobal("window", { localStorage: { getItem: () => null } });
+ vi.stubGlobal("document", {
+ documentElement: {
+ dataset: {},
+ style: {
+ setProperty: (name: string, value: string) => properties.set(name, value),
+ removeProperty: (name: string) => properties.delete(name),
+ },
+ },
+ });
+ invalidateCustomThemes();
+ try {
+ for (const appearance of ["light", "dark"] as const) {
+ applyThemePalette("system", appearance);
+ for (const kind of Object.keys(CONTEXT_CHIP_ACCENTS) as Array<
+ keyof typeof CONTEXT_CHIP_ACCENTS
+ >) {
+ for (const surface of painted[appearance]) {
+ expect(
+ contrastRatio(properties.get(contextChipColorVariable(kind))!, surface),
+ ).toBeGreaterThanOrEqual(5);
+ }
+ }
+ }
+ } finally {
+ vi.unstubAllGlobals();
+ invalidateCustomThemes();
+ }
+ });
+
+ it("solves the invalid state's error color to 5:1 on every chip surface", () => {
+ for (const colors of palettes) {
+ const invalid = contextChipVariables(colors)["--context-chip-invalid"];
+ expect(invalid).toBeDefined();
+ for (const surface of [
+ colors.canvas,
+ colors.surface,
+ colors.surfaceRaised,
+ colors.messageSurface,
+ ]) {
+ expect(paintedContrastRatio(invalid!, surface, colors.canvas)).toBeGreaterThanOrEqual(5);
+ }
+ }
+ });
+
+ it("leaves a bubble with opposite-shade text out of the shared solve", () => {
+ const colors = {
+ ...getStandardThemeColors("light"),
+ messageSurface: "#1b4ed8",
+ messageForeground: "#ffffff",
+ };
+ const variables = contextChipVariables(colors);
+ expect(variables["--context-chip-message"]).toBe("#ffffff");
+ for (const kind of Object.keys(CONTEXT_CHIP_ACCENTS) as Array<
+ keyof typeof CONTEXT_CHIP_ACCENTS
+ >) {
+ expect(
+ contrastRatio(variables[contextChipColorVariable(kind)]!, colors.canvas),
+ ).toBeGreaterThanOrEqual(5);
+ }
+ expect(toOklch(variables[contextChipColorVariable("file")])!.c).toBeGreaterThan(0.08);
+ });
+});
+
describe("stored theme preferences", () => {
it("lets a configured half unlock an appearance the base theme lacks", () => {
const lightOnly = parseThemeFile({
diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.ts
index faae797483f..4aaa6062b74 100644
--- a/apps/web/src/themePalette.ts
+++ b/apps/web/src/themePalette.ts
@@ -22,6 +22,11 @@ import {
type ThemeDefinition,
type ThemeVariants,
} from "@t3tools/shared/themePalettes";
+import {
+ CONTEXT_CHIP_ACCENTS,
+ contextChipColorVariable,
+ type ContextChipAccentKind,
+} from "./lib/contextChipAccents";
import { appAtomRegistry, subscribeAtomChanges } from "./rpc/atomRegistry";
import { primaryServerEnvironmentThemesAtom } from "./state/server";
@@ -395,6 +400,24 @@ export function getStandardThemeColors(appearance: ThemeAppearance): ThemeColors
return (standardLightThemeColors ??= decodeThemeColors(T3_CODE_LIGHT_THEME_COLORS));
}
+// index.css paints the light bubble a step darker than the shared palette mobile uses.
+const STANDARD_WEB_PAINTED_COLORS: Record<ThemeAppearance, Partial<ThemeColors>> = {
+ light: { messageSurface: "#ebebed" },
+ dark: {},
+};
+
+/** The standard theme as index.css paints it, for solves that measure the page. */
+export function getStandardPaintedThemeColors(
+ appearance: ThemeAppearance,
+ redesign = false,
+): ThemeColors {
+ return {
+ ...getStandardThemeColors(appearance),
+ ...STANDARD_WEB_PAINTED_COLORS[appearance],
+ ...(redesign && appearance === "dark" ? { canvas: "#000000", messageSurface: "#1e1e1e" } : {}),
+ };
+}
+
type ThemeRgbColor = {
r: number;
g: number;
@@ -541,9 +564,10 @@ function srgbChannelToLinear(channel: number): number {
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
}
-function linearChannelToSrgb(channel: number): number {
+function linearChannelToSrgb(channel: number, round = true): number {
const c = channel <= 0.0031308 ? channel * 12.92 : 1.055 * channel ** (1 / 2.4) - 0.055;
- return Math.round(Math.min(1, Math.max(0, c)) * 255);
+ const srgb = Math.min(1, Math.max(0, c)) * 255;
+ return round ? Math.round(srgb) : srgb;
}
function themeRgbToOklch(color: ThemeRgbColor): ThemeOklch {
@@ -597,12 +621,12 @@ function mapThemeOklchToSrgbGamut(color: ThemeOklch): ThemeOklch {
return { ...color, C: low };
}
-function themeOklchToRgb(color: ThemeOklch): ThemeRgbColor {
+function themeOklchToRgb(color: ThemeOklch, round = true): ThemeRgbColor {
const linear = oklchToRgbUnclamped(mapThemeOklchToSrgbGamut(color));
return {
- r: linearChannelToSrgb(linear.r),
- g: linearChannelToSrgb(linear.g),
- b: linearChannelToSrgb(linear.b),
+ r: linearChannelToSrgb(linear.r, round),
+ g: linearChannelToSrgb(linear.g, round),
+ b: linearChannelToSrgb(linear.b, round),
};
}
@@ -612,19 +636,20 @@ function themeOklchToThemeColor(color: ThemeOklch): string {
function solveOklchLightness(
base: ThemeOklch,
- against: ThemeRgbColor,
+ against: ReadonlyArray<ThemeRgbColor>,
minContrast: number,
direction: "lighter" | "darker",
): ThemeOklch {
+ const contrastOf = (color: ThemeOklch) =>
+ Math.min(...against.map((surface) => themeContrastRatio(themeOklchToRgb(color), surface)));
let low = direction === "lighter" ? base.L : 0;
let high = direction === "lighter" ? 1 : base.L;
let candidate = { ...base };
- if (themeContrastRatio(themeOklchToRgb(candidate), against) >= minContrast) return candidate;
+ if (contrastOf(candidate) >= minContrast) return candidate;
for (let step = 0; step < 18; step += 1) {
const mid = (low + high) / 2;
candidate = { ...base, L: mid };
- const contrast = themeContrastRatio(themeOklchToRgb(candidate), against);
- if (contrast >= minContrast) {
+ if (contrastOf(candidate) >= minContrast) {
if (direction === "lighter") high = mid;
else low = mid;
} else {
@@ -648,12 +673,63 @@ export function readableThemeColorOn(color: string, surface: string, minContrast
return color;
}
const direction = themeRelativeLuminance(surfaceRgb) < 0.179 ? "lighter" : "darker";
- const solved = solveOklchLightness(parsedColor.color, surfaceRgb, minContrast, direction);
+ const solved = solveOklchLightness(parsedColor.color, [surfaceRgb], minContrast, direction);
// Return the 8-bit color the solver measured: the unrounded OKLCH can round
// to a neighbor just under the target once it is stored and read back.
return themeRgbToHexColor(themeOklchToRgb(solved));
}
+const CONTEXT_CHIP_CONTRAST = 5;
+const CONTEXT_CHIP_MESSAGE_VARIABLE = "--context-chip-message";
+const CONTEXT_CHIP_INVALID_VARIABLE = "--context-chip-invalid";
+
+export function contextChipVariables(colors: ThemeColors): Readonly<Record<string, string>> {
+ // CSS paints surfaces from their unrounded OKLCH, so measure them unrounded.
+ const parsedCanvas = parseThemeColor(colors.canvas);
+ const canvas = parsedCanvas ? themeOklchToRgb(parsedCanvas.color, false) : THEME_WHITE_FOREGROUND;
+ const onCanvas = (value: string) => {
+ const parsed = parseThemeColor(value);
+ return parsed
+ ? mixThemeRgbColors(canvas, themeOklchToRgb(parsed.color, false), parsed.alpha)
+ : canvas;
+ };
+ const isDark = (color: ThemeRgbColor) => themeRelativeLuminance(color) < 0.179;
+ const messageMatchesCanvas = isDark(onCanvas(colors.messageSurface)) === isDark(canvas);
+ const surfaces = [canvas, onCanvas(colors.surface), onCanvas(colors.surfaceRaised)];
+ if (messageMatchesCanvas) surfaces.push(onCanvas(colors.messageSurface));
+ const contrastOnSurfaces = (color: ThemeRgbColor) =>
+ Math.min(...surfaces.map((surface) => themeContrastRatio(color, surface)));
+ const blackContrast = contrastOnSurfaces(THEME_BLACK_FOREGROUND);
+ const whiteContrast = contrastOnSurfaces(THEME_WHITE_FOREGROUND);
+ const direction = blackContrast >= whiteContrast ? "darker" : "lighter";
+ const minContrast = Math.min(CONTEXT_CHIP_CONTRAST, Math.max(blackContrast, whiteContrast));
+ const accents: Array<[string, string]> = [
+ ...(Object.entries(CONTEXT_CHIP_ACCENTS) as Array<[ContextChipAccentKind, string]>).map(
+ ([kind, accent]): [string, string] => [contextChipColorVariable(kind), accent],
+ ),
+ [CONTEXT_CHIP_INVALID_VARIABLE, colors.errorForeground],
+ ];
+ const variables: Record<string, string> = Object.fromEntries(
+ accents.flatMap(([variable, accent]) => {
+ const parsed = parseThemeColor(accent);
+ if (!parsed) return [];
+ const solved = solveOklchLightness(parsed.color, surfaces, minContrast, direction);
+ return [[variable, themeRgbToHexColor(themeOklchToRgb(solved))]];
+ }),
+ );
+ if (!messageMatchesCanvas) variables[CONTEXT_CHIP_MESSAGE_VARIABLE] = colors.messageForeground;
+ return variables;
+}
+
+function applyContextChipVariables(root: HTMLElement, colors: ThemeColors): void {
+ const variables = contextChipVariables(colors);
+ root.style.removeProperty(CONTEXT_CHIP_MESSAGE_VARIABLE);
+ root.style.removeProperty(CONTEXT_CHIP_INVALID_VARIABLE);
+ for (const [variable, value] of Object.entries(variables)) {
+ root.style.setProperty(variable, value);
+ }
+}
+
const STANDARD_STATUS_COLORS = {
light: {
error: "#fb2c36",
@@ -686,7 +762,7 @@ function standardStatusColors(canvas: ThemeRgbColor): {
themeOklchToThemeColor(
solveOklchLightness(
themeRgbToOklch(parseThemeRgbColor(foreground, canvas)),
- surface,
+ [surface],
4.6,
appearance === "dark" ? "lighter" : "darker",
),
@@ -734,7 +810,7 @@ export function createVividThemeColors(
C: Math.min(0.035, accent.C * 0.25),
h: hue,
};
- const text = solveOklchLightness(textBase, canvasRgb, 7, dark ? "lighter" : "darker");
+ const text = solveOklchLightness(textBase, [canvasRgb], 7, dark ? "lighter" : "darker");
const textRgb = themeOklchToRgb(text);
const textMutedRgb = standardMutedThemeText(canvasRgb, textRgb);
@@ -768,7 +844,7 @@ export function createVividThemeColors(
const foregroundOn = (surfaceRgb: ThemeRgbColor): string =>
themeOklchToThemeColor(
- solveOklchLightness(textBase, surfaceRgb, 4.6, dark ? "lighter" : "darker"),
+ solveOklchLightness(textBase, [surfaceRgb], 4.6, dark ? "lighter" : "darker"),
);
const mutedForeground = themeRgbToThemeColor(readableThemeText(mutedRgb, textRgb, 1, 4.6));
const placeholder = themeRgbToThemeColor(readableThemeText(surfaceRaisedRgb, textRgb, 1, 4.6));
@@ -930,7 +1006,7 @@ export function updateThemeColorFamily(
themeOklchToThemeColor(
solveOklchLightness(
parsedSelected.color,
- background,
+ [background],
4.6,
themeRelativeLuminance(background) < 0.179 ? "lighter" : "darker",
),
@@ -1532,6 +1608,7 @@ export function applyThemeColorPreview(colors: ThemeColors, appearance: ThemeApp
for (const [role, value] of Object.entries(colors) as Array<[ThemeColorRole, string]>) {
if (isThemeColor(value)) root.style.setProperty(APP_THEME_VARIABLES[role], value);
}
+ applyContextChipVariables(root, colors);
setThemePreviewAppearance(appearance);
}
@@ -1551,6 +1628,7 @@ export function applyThemePalette(theme: ThemePreference, appearance?: ThemeAppe
for (const [role, value] of Object.entries(colors) as Array<[ThemeColorRole, string]>) {
root.style.setProperty(APP_THEME_VARIABLES[role], value);
}
+ applyContextChipVariables(root, colors);
return;
}
@@ -1558,6 +1636,8 @@ export function applyThemePalette(theme: ThemePreference, appearance?: ThemeAppe
for (const variable of Object.values(APP_THEME_VARIABLES)) {
root.style.removeProperty(variable);
}
+ // The redesign's lighter dark bubble is the stricter surface, so this ink also covers legacy UI.
+ applyContextChipVariables(root, getStandardPaintedThemeColors(appearance ?? "light", true));
}
export function resolveThemeAppearance(
diff --git a/vite.config.ts b/vite.config.ts
index 2ed89c178d4..9492eb7f350 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -521,9 +521,9 @@ export default defineConfig({
"transition",
"rounded-[inherit]",
"gap-[0.33em]",
- "px-[0.5em]",
- "rounded-[0.5em]",
- "text-[0.86em]",
+ "gap-[0.2em]",
+ "leading-[normal]",
+ "underline-offset-[0.2em]",
"rounded-[25%]",
"text-[length:80cqh]",
"bg-[Highlight]",