@devries-cameron20 / t3code Mirror · read-only / commits / e01c39969f
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 18:15 UTC

fix(mobile): chat and composer chips stay readable in light mode (#22585)

Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

oliver committed Oct 23, 2026 at 17:09 UTC e01c39969f2346d8354d6240754c0a1e312b43f2
18 files changed +816 -51
apps/mobile/src/App.tsx
+2
@@ -9,6 +9,7 @@ import { SafeAreaProvider } from "react-native-safe-area-context";
9 import { createStaticNavigation, getStateFromPath } from "@react-navigation/native";
10
11 import { RegistryContext } from "@effect/atom-react";
12 +import { ProjectChipIconRasterizer } from "./native/ProjectChipIconImages";
13 import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet";
14 import * as Dialog from "./components/ui/Dialog";
15 import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
@@ -110,6 +111,7 @@ function AppContent() {
111 </IncomingShareProvider>
112 <Dialog.Host />
113 <ThreadArrangementHost />
114 + <ProjectChipIconRasterizer />
115 </NativeLayoutMetricsProvider>
116 </GlobalVoiceInputControl>
117 {/* Anchored-menu overlays render here — in-window, so the
apps/mobile/src/components/ProjectFavicon.tsx
+6 -2
@@ -14,6 +14,7 @@ import { Atom } from "effect/reactivity";
14 import { projectFaviconUrlAtom } from "../state/assets";
15 import {
16 countGlyphs,
17 + projectAutoMonogram,
18 projectIconColorClassNames,
19 resolveProjectIconGlyph,
20 type ProjectIconGlyph,
@@ -167,6 +168,7 @@ function ProjectFaviconImage(props: {
168
169 const requestIsActive = faviconRequest !== null && activeFaviconRequest === faviconRequest;
170 const showImage = requestIsActive && status === "loaded";
171 + const fallbackGlyph = showImage ? null : projectAutoMonogram(props.projectTitle);
172
173 return (
174 <View
@@ -177,14 +179,16 @@ function ProjectFaviconImage(props: {
179 justifyContent: "center",
180 }}
181 >
180 - {!showImage ? (
182 + {showImage ? null : fallbackGlyph ? (
183 + <ProjectIconGlyphView glyph={fallbackGlyph} size={props.size} />
184 + ) : (
185 <SymbolView
186 name={{ ios: "folder.fill", android: props.open ? "folder_open" : "folder" }}
187 size={props.size}
188 tintColorClassName={"accent-icon-subtle"}
189 type="monochrome"
190 />
187 - ) : null}
191 + )}
192
193 {requestIsActive ? (
194 <Image
apps/mobile/src/features/keyboard/CommandPalette.tsx
+20 -6
@@ -18,6 +18,7 @@ import {
18
19 import { GestureHandlerRootView } from "react-native-gesture-handler";
20
21 +import { ProjectFavicon } from "../../components/ProjectFavicon";
22 import { GlassSurface } from "../../components/ui/GlassSurface";
23 import { RowPressable } from "../../components/ui/RowPressable";
24 import { AppText as Text } from "../../components/ui/AppText";
@@ -68,7 +69,6 @@ const ACTION_ICONS: Record<string, AppSymbolName> = {
69 };
70
71 function itemIcon(item: CommandPaletteItem): AppSymbolName {
71 - if (item.kind === "project") return "folder";
72 if (item.kind === "thread") return "text.bubble";
73 return ACTION_ICONS[item.key] ?? "ellipsis";
74 }
@@ -101,11 +101,24 @@ function PaletteRow(props: {
101 style={{ height: ROW_HEIGHT }}
102 >
103 <View className="w-7 items-center">
104 - <SymbolView
105 - name={itemIcon(props.item)}
106 - size={20}
107 - tintColorClassName={props.selected ? "accent-thread-selected-foreground" : "accent-icon"}
108 - />
104 + {props.item.project ? (
105 + <ProjectFavicon
106 + environmentId={props.item.project.environmentId}
107 + faviconPath={props.item.project.faviconPath}
108 + projectIcon={props.item.project.projectIcon}
109 + projectTitle={props.item.project.title}
110 + size={20}
111 + workspaceRoot={props.item.project.workspaceRoot}
112 + />
113 + ) : (
114 + <SymbolView
115 + name={itemIcon(props.item)}
116 + size={20}
117 + tintColorClassName={
118 + props.selected ? "accent-thread-selected-foreground" : "accent-icon"
119 + }
120 + />
121 + )}
122 </View>
123 <View className="flex-1">
124 <Text numberOfLines={1} className={cn("text-base", foregroundClassName)}>
@@ -310,6 +323,7 @@ export function CommandPalette(props: {
323 const projectItems: CommandPaletteItem[] = projects.map((project) => ({
324 key: `project:${scopedProjectKey(project.environmentId, project.id)}`,
325 kind: "project",
326 + project,
327 title: project.title,
328 detail: `New thread · ${savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId}`,
329 searchTerms: [project.workspaceRoot, "new thread", "project"],
apps/mobile/src/features/keyboard/commandPaletteItems.ts
+3
@@ -1,6 +1,9 @@
1 +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
2 +
3 export interface CommandPaletteItem {
4 readonly key: string;
5 readonly kind: "action" | "project" | "thread";
6 + readonly project?: EnvironmentProject;
7 readonly title: string;
8 readonly detail?: string;
9 readonly searchTerms: ReadonlyArray<string>;
apps/mobile/src/features/threads/ThreadFeed.tsx
+24 -5
@@ -4,7 +4,11 @@ import { useOpenPullRequest } from "../../native/useOpenPullRequest";
4 import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width";
5 import { ThreadMarkdownVideo, ThreadMediaVisibleContext } from "./ThreadMarkdownVideo";
6 import { useMarkdownImageSource } from "../../native/useMarkdownImageSource";
7 -import { enrichedContextLinkCustomization } from "../../native/useEnrichedLinkVariants";
7 +import {
8 + enrichedContextLinkCustomization,
9 + enrichedThreadLinkCustomization,
10 + withChipIcon,
11 +} from "../../native/useEnrichedLinkVariants";
12 import {
13 enrichedSkillDisplayName,
14 enrichedSkillInstructionsPath,
@@ -242,7 +246,11 @@ import {
246 pickWorkspaceBasenameMatch,
247 WORKSPACE_BASENAME_LOOKUP_LIMIT,
248 } from "@t3tools/client-runtime/workspace-basename-lookup";
245 -import { useLiveThreadLinkLabels, useQuietThreadShell } from "../../state/entities";
249 +import {
250 + useLiveThreadLinkLabels,
251 + useQuietThreadShell,
252 + useThreadChipIcons,
253 +} from "../../state/entities";
254 import { useThreadSelection } from "../../state/use-thread-selection";
255 import { useEnvironmentQuery } from "../../state/query";
256 import { serverEnvironment } from "../../state/server";
@@ -858,6 +866,12 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
866 }) {
867 const liveMarkdown = useLiveThreadLinkLabels(props.markdown, props.environmentId);
868 const segments = useMemo(() => splitCodexArtifactTemplateMarkdown(liveMarkdown), [liveMarkdown]);
869 + const threadIcons = useThreadChipIcons(props.environmentId, liveMarkdown);
870 + const linkHandlers: MarkdownLinkHandlers = {
871 + ...props.linkHandlers,
872 + linkCustomization: (href) =>
873 + withChipIcon(props.linkHandlers.linkCustomization?.(href), threadIcons.get(href)),
874 + };
875
876 return segments.map((segment) => {
877 if (segment.kind === "artifact-template") {
@@ -878,7 +892,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: {
892 markdown={markdown}
893 skills={props.skills}
894 textStyle={props.markdownStyles.nativeTextStyle}
881 - {...props.linkHandlers}
895 + {...linkHandlers}
896 renderImage={props.renderImage}
897 />
898 );
@@ -1781,6 +1795,7 @@ function UserMessageContent(props: UserMessageContentProps) {
1795 const navigation = useNavigation();
1796 const { selectedThread } = useThreadSelection();
1797 const liveText = useLiveThreadLinkLabels(props.text, props.environmentId);
1798 + const threadIcons = useThreadChipIcons(props.environmentId, liveText, props.context?.records);
1799 const text = replaceComposerContextReferences(liveText, (ref) => {
1800 const available = props.context?.records.some((record) => record.contextId === ref.contextId);
1801 return `[${ref.label}${available ? "" : " (unavailable)"}](t3-context://v1/${ref.kind}/${ref.contextId})`;
@@ -1864,8 +1879,11 @@ function UserMessageContent(props: UserMessageContentProps) {
1879 }
1880 },
1881 linkCustomization: (href) =>
1867 - enrichedContextLinkCustomization(href, props.context?.records ?? []) ??
1868 - props.linkHandlers.linkCustomization?.(href),
1882 + withChipIcon(
1883 + enrichedContextLinkCustomization(href, props.context?.records ?? []) ??
1884 + props.linkHandlers.linkCustomization?.(href),
1885 + threadIcons.get(href),
1886 + ),
1887 }}
1888 />
1889 {selected ? (
@@ -2323,6 +2341,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2341 });
2342 const markdownLinkHandlers: MarkdownLinkHandlers = {
2343 onLinkPress: onMarkdownLinkPress,
2344 + linkCustomization: enrichedThreadLinkCustomization,
2345 onImagePress: (href) => onMarkdownLinkPress(href, true),
2346 resolveImageSource,
2347 fileContextMenu: (href) => {
apps/mobile/src/lib/composerChipPresentation.test.ts new
+109
@@ -0,0 +1,109 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { contextChipAccent, contextChipPresentation } from "./composerChipPresentation";
4 +import {
5 + flattenThemeColor,
6 + getMobileThemeVariables,
7 + MOBILE_THEME_IDS,
8 + type MobileThemeVariables,
9 +} from "./mobileTheme";
10 +
11 +const CHIP_ACCENTS = [
12 + ...new Set(
13 + [
14 + ...[
15 + "image",
16 + "video",
17 + "file",
18 + "mention",
19 + "terminal",
20 + "element",
21 + "review-comment",
22 + "pull-request",
23 + "skill",
24 + "thread",
25 + ].map((kind) => contextChipPresentation(kind)),
26 + ...[
27 + { state: "open", isDraft: false },
28 + { state: "open", isDraft: true },
29 + { state: "merged", isDraft: false },
30 + { state: "closed", isDraft: false },
31 + ].map((pullRequest) => contextChipPresentation("pull-request", { pullRequest })),
32 + ].flatMap(({ accent }) => (accent ? [accent] : [])),
33 + ),
34 +];
35 +
36 +function relativeLuminance(hex: string): number {
37 + const [red = 0, green = 0, blue = 0] = [1, 3, 5].map((offset) => {
38 + const value = Number.parseInt(hex.slice(offset, offset + 2), 16) / 255;
39 + return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
40 + });
41 + return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
42 +}
43 +
44 +function contrastRatio(first: string, second: string): number {
45 + const [darker = 0, lighter = 0] = [relativeLuminance(first), relativeLuminance(second)].sort(
46 + (a, b) => a - b,
47 + );
48 + return (lighter + 0.05) / (darker + 0.05);
49 +}
50 +
51 +function chipSurfaces(theme: MobileThemeVariables) {
52 + const screen = theme["--color-screen"];
53 + return (
54 + [
55 + ["--color-user-bubble", "--color-user-bubble-foreground"],
56 + ["--color-thread-canvas", "--color-md-body"],
57 + ["--color-composer-surface", "--color-foreground"],
58 + ] as const
59 + ).map(([surface, text]) => ({
60 + surface: flattenThemeColor(theme[surface], screen).slice(0, 7),
61 + text: theme[text],
62 + }));
63 +}
64 +
65 +const BUILT_IN_THEMES = MOBILE_THEME_IDS.filter((id) => id !== "material-you").flatMap((id) =>
66 + (["light", "dark"] as const).map((appearance) => ({
67 + name: `${id} ${appearance}`,
68 + theme: getMobileThemeVariables(id, appearance),
69 + })),
70 +);
71 +
72 +describe("contextChipAccent", () => {
73 + it("draws one color per theme that reads at 5:1 in messages, replies and the composer", () => {
74 + for (const { name, theme } of BUILT_IN_THEMES) {
75 + for (const accent of CHIP_ACCENTS) {
76 + const shown = contextChipAccent(accent, theme, theme["--color-md-body"])!;
77 + for (const { surface, text } of chipSurfaces(theme)) {
78 + expect(contextChipAccent(accent, theme, text)).toBe(shown);
79 + expect(
80 + contrastRatio(shown, surface),
81 + `${name}: ${accent} → ${shown} on ${surface}`,
82 + ).toBeGreaterThanOrEqual(5);
83 + }
84 + }
85 + }
86 + });
87 +
88 + it("reads on both a saturated Material You bubble and the light canvas beside it", () => {
89 + const theme = {
90 + ...getMobileThemeVariables("t3-code", "light"),
91 + "--color-user-bubble": "#6750a4",
92 + "--color-user-bubble-foreground": "#ffffff",
93 + };
94 + for (const { surface, text } of chipSurfaces(theme)) {
95 + for (const accent of CHIP_ACCENTS) {
96 + const shown = contextChipAccent(accent, theme, text)!;
97 + expect(
98 + contrastRatio(shown, surface),
99 + `${accent} → ${shown} on ${surface}`,
100 + ).toBeGreaterThanOrEqual(5);
101 + }
102 + }
103 + });
104 +
105 + it("keeps an accent that already reads everywhere", () => {
106 + const theme = getMobileThemeVariables("t3-code", "dark");
107 + expect(contextChipAccent("#009f6e", theme, theme["--color-md-body"])).toBe("#009f6e");
108 + });
109 +});
apps/mobile/src/lib/composerChipPresentation.ts
+42
@@ -4,6 +4,12 @@ import { videoMimeType } from "@t3tools/shared/video";
4
5 import type { CONTEXT_CHIP_ICON_SOURCES } from "./contextChipIcons.generated";
6 import { resolveMarkdownFileIcon, type MarkdownFileIcon } from "./markdownLinks";
7 +import {
8 + flattenThemeColor,
9 + isDarkThemeColor,
10 + themeAccentWithContrast,
11 + type MobileThemeVariables,
12 +} from "./mobileTheme";
13
14 export type ContextChipIcon = keyof typeof CONTEXT_CHIP_ICON_SOURCES;
15
@@ -39,6 +45,42 @@ const CONTEXT_CHIP_PRESENTATIONS = {
45 },
46 } as const satisfies Record<string, ContextChipPresentation>;
47
48 +const CHIP_CONTRAST = 5;
49 +
50 +const readableChipAccents = new Map<string, string>();
51 +
52 +/**
53 + * A chip keeps one color per theme so it looks the same in a message, a reply and the composer,
54 + * which means it must read on all of them; the user bubble is usually the hardest. A surface
55 + * whose text is the opposite shade, like Material You's primary-colored light bubble, can't share
56 + * a color with the canvas, so chips are matched only against surfaces like the one they sit on.
57 + */
58 +export function contextChipAccent(
59 + accent: string | undefined,
60 + theme: MobileThemeVariables,
61 + textColor: string,
62 +): string | undefined {
63 + if (!accent) return undefined;
64 + const screen = theme["--color-screen"];
65 + const darkText = isDarkThemeColor(textColor);
66 + const surfaces = (
67 + [
68 + ["--color-user-bubble", "--color-user-bubble-foreground"],
69 + ["--color-thread-canvas", "--color-md-body"],
70 + ["--color-composer-surface", "--color-foreground"],
71 + ] as const
72 + )
73 + .filter(([, text]) => isDarkThemeColor(theme[text]) === darkText)
74 + .map(([surface]) => flattenThemeColor(theme[surface], screen));
75 + const key = [accent, ...surfaces].join();
76 + let readable = readableChipAccents.get(key);
77 + if (readable === undefined) {
78 + readable = themeAccentWithContrast(accent, surfaces, CHIP_CONTRAST);
79 + readableChipAccents.set(key, readable);
80 + }
81 + return readable;
82 +}
83 +
84 export const UNAVAILABLE_CONTEXT_CHIP_PRESENTATION: ContextChipPresentation = {
85 icon: "circle-dashed",
86 };
apps/mobile/src/lib/enrichedLinkPresentation.test.ts
+49
@@ -1,8 +1,11 @@
1 import { describe, expect, it } from "vite-plus/test";
2 +import type { ComposerContextId, EnvironmentId, ThreadId } from "@t3tools/contracts";
3 import {
4 enrichedLinkVariantPattern,
5 enrichedSkillLinkRegex,
6 + enrichedThreadLinkPresentation,
7 ENRICHED_INLINE_FILE_LINK_REGEX,
8 + threadChipTargets,
9 } from "./enrichedLinkPresentation";
10
11 describe("Enriched link presentation", () => {
@@ -46,4 +49,50 @@ describe("Enriched link presentation", () => {
49 expect(pattern.test(`${url}/child`)).toBe(false);
50 expect(pattern.test("file:///workspace/app1Xtsx?line=34")).toBe(false);
51 });
52 +
53 + it("presents thread links as thread chips and leaves other links alone", () => {
54 + expect(enrichedThreadLinkPresentation("t3-thread://v1/thread%3Aproject%3A1")).toEqual({
55 + accent: "#009c96",
56 + icon: { kind: "chip", name: "messages-square" },
57 + });
58 + for (const href of [
59 + "https://github.com/example/repo/pull/7",
60 + "https://example.com",
61 + "t3-context://v1/thread/thread_1",
62 + ]) {
63 + expect(enrichedThreadLinkPresentation(href), href).toBeUndefined();
64 + }
65 + });
66 +
67 + it("finds each linked thread once and resolves thread records to their own environment", () => {
68 + const here = "env-here" as EnvironmentId;
69 + const there = "env-there" as EnvironmentId;
70 + expect(
71 + threadChipTargets(
72 + here,
73 + "See [A](t3-thread://v1/thread_a), [A again](t3-thread://v1/thread_a) and [B](t3-thread://v1/thread_b).",
74 + [
75 + {
76 + version: 1,
77 + contextId: "thr1" as ComposerContextId,
78 + kind: "thread",
79 + label: "C",
80 + environmentId: there,
81 + threadId: "thread_c" as ThreadId,
82 + title: "C",
83 + },
84 + ],
85 + ),
86 + ).toEqual([
87 + { href: "t3-thread://v1/thread_a", environmentId: here, threadId: "thread_a", link: true },
88 + { href: "t3-thread://v1/thread_b", environmentId: here, threadId: "thread_b", link: true },
89 + {
90 + href: "t3-context://v1/thread/thr1",
91 + environmentId: there,
92 + threadId: "thread_c",
93 + link: false,
94 + },
95 + ]);
96 + expect(threadChipTargets(here, "No links here.")).toEqual([]);
97 + });
98 });
apps/mobile/src/lib/enrichedLinkPresentation.ts
+49 -2
@@ -1,4 +1,4 @@
1 -import type { ComposerContextRecord } from "@t3tools/contracts";
1 +import type { ComposerContextRecord, EnvironmentId, ThreadId } from "@t3tools/contracts";
2 import {
3 composerChipSizeSuffix,
4 contextChipIcon,
@@ -8,7 +8,11 @@ import {
8 UNAVAILABLE_CONTEXT_CHIP_PRESENTATION,
9 } from "./composerChipPresentation";
10 import type { SelectableMarkdownSkill } from "../native/SelectableMarkdownText.types";
11 -import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences";
11 +import {
12 + formatComposerContextHref,
13 + parseComposerContextHref,
14 +} from "@t3tools/shared/composerContextReferences";
15 +import { hasThreadLinks, parseThreadLinkHref } from "@t3tools/shared/threadLinks";
16
17 export function enrichedContextLinkPresentation(
18 href: string,
@@ -29,6 +33,49 @@ export function enrichedContextLinkPresentation(
33 };
34 }
35
36 +export function enrichedThreadLinkPresentation(
37 + href: string,
38 +): { accent?: string; icon: ContextChipIconRef } | undefined {
39 + if (!parseThreadLinkHref(href)) return undefined;
40 + const presentation = contextChipPresentation("thread");
41 + return {
42 + ...(presentation.accent ? { accent: presentation.accent } : {}),
43 + icon: contextChipIcon(presentation, ""),
44 + };
45 +}
46 +
47 +export interface ThreadChipTarget {
48 + readonly href: string;
49 + readonly environmentId: EnvironmentId;
50 + readonly threadId: ThreadId;
51 + readonly link: boolean;
52 +}
53 +
54 +export function threadChipTargets(
55 + environmentId: EnvironmentId,
56 + markdown: string,
57 + records?: ReadonlyArray<ComposerContextRecord>,
58 +): ReadonlyArray<ThreadChipTarget> {
59 + const targets = new Map<string, ThreadChipTarget>();
60 + if (hasThreadLinks(markdown)) {
61 + for (const [, href = ""] of markdown.matchAll(/\]\((t3-thread:\/\/v1\/[^\s)]+)\)/g)) {
62 + const threadId = parseThreadLinkHref(href);
63 + if (threadId) targets.set(href, { href, environmentId, threadId, link: true });
64 + }
65 + }
66 + for (const record of records ?? []) {
67 + if (record.kind !== "thread" || !("threadId" in record)) continue;
68 + const href = formatComposerContextHref("thread", record.contextId);
69 + targets.set(href, {
70 + href,
71 + environmentId: record.environmentId,
72 + threadId: record.threadId,
73 + link: false,
74 + });
75 + }
76 + return [...targets.values()];
77 +}
78 +
79 export function enrichedLinkVariantPattern(url: string) {
80 return `^${url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`;
81 }
apps/mobile/src/lib/mobileTheme.ts
+97 -15
@@ -94,6 +94,22 @@ function linearToSrgb(value: number): number {
94 return Math.round(Math.min(1, Math.max(0, converted)) * 255);
95 }
96
97 +function oklabToLinearSrgb(lightness: number, a: number, b: number) {
98 + const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;
99 + const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;
100 + const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;
101 + return [
102 + 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
103 + -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
104 + -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
105 + ] as const;
106 +}
107 +
108 +function oklabToSrgb(lightness: number, a: number, b: number) {
109 + const [red, green, blue] = oklabToLinearSrgb(lightness, a, b);
110 + return [linearToSrgb(red), linearToSrgb(green), linearToSrgb(blue)] as const;
111 +}
112 +
113 /** React Native does not accept OKLCH ColorValues, so palettes cross the app boundary as sRGB. */
114 export function themeColorToNativeColor(value: string): string {
115 const match = OKLCH_PATTERN.exec(value);
@@ -103,17 +119,7 @@ export function themeColorToNativeColor(value: string): string {
119 const chroma = Number(match[2]);
120 const hue = (Number(match[3]) * Math.PI) / 180;
121 const alpha = match[4] === undefined ? 1 : Number(match[4]);
106 - const a = chroma * Math.cos(hue);
107 - const b = chroma * Math.sin(hue);
108 - const lPrime = lightness + 0.3963377774 * a + 0.2158037573 * b;
109 - const mPrime = lightness - 0.1055613458 * a - 0.0638541728 * b;
110 - const sPrime = lightness - 0.0894841775 * a - 1.291485548 * b;
111 - const l = lPrime ** 3;
112 - const m = mPrime ** 3;
113 - const s = sPrime ** 3;
114 - const red = linearToSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s);
115 - const green = linearToSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s);
116 - const blue = linearToSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s);
122 + const [red, green, blue] = oklabToSrgb(lightness, chroma * Math.cos(hue), chroma * Math.sin(hue));
123
124 return alpha < 1
125 ? `rgba(${red}, ${green}, ${blue}, ${Number(alpha.toFixed(4))})`
@@ -168,14 +174,33 @@ export function flattenThemeColor(color: string, surface: string): string {
174 return `#${channels.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
175 }
176
177 +function srgbToLinear(channel: number): number {
178 + const value = channel / 255;
179 + return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
180 +}
181 +
182 +function srgbToOklab(channels: readonly [number, number, number]) {
183 + const [red = 0, green = 0, blue = 0] = channels.map(srgbToLinear);
184 + const l = Math.cbrt(0.4122214708 * red + 0.5363325363 * green + 0.0514459929 * blue);
185 + const m = Math.cbrt(0.2119034982 * red + 0.6806995451 * green + 0.1073969566 * blue);
186 + const s = Math.cbrt(0.0883024619 * red + 0.2817188376 * green + 0.6299787005 * blue);
187 + return [
188 + 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
189 + 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
190 + 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
191 + ] as const;
192 +}
193 +
194 function relativeLuminance(channels: readonly [number, number, number]): number {
172 - const [red, green, blue] = channels.map((channel) => {
173 - const value = channel / 255;
174 - return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
175 - });
195 + const [red, green, blue] = channels.map(srgbToLinear);
196 return 0.2126 * red! + 0.7152 * green! + 0.0722 * blue!;
197 }
198
199 +export function isDarkThemeColor(color: string): boolean {
200 + const channels = rgbChannels(color);
201 + return channels !== null && relativeLuminance(channels) < 0.18;
202 +}
203 +
204 function contrastRatio(
205 first: readonly [number, number, number],
206 second: readonly [number, number, number],
@@ -230,6 +255,63 @@ export function themeColorWithContrast(
255 return `#${readable.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
256 }
257
258 +/**
259 + * Unlike `themeColorWithContrast`, which blends toward black or white and greys the color out,
260 + * this moves only OKLCH lightness and takes the most chroma sRGB allows at each step, so a vivid
261 + * accent stays vivid at the contrast it needs.
262 + */
263 +export function themeAccentWithContrast(
264 + accent: string,
265 + surfaces: ReadonlyArray<string>,
266 + minimum = 4.5,
267 +): string {
268 + const accentChannels = rgbChannels(accent);
269 + const surfaceChannels = surfaces.map(rgbChannels).filter((channels) => channels !== null);
270 + const minimumContrast = (channels: readonly [number, number, number]) =>
271 + Math.min(...surfaceChannels.map((surface) => contrastRatio(channels, surface)));
272 + if (
273 + !accentChannels ||
274 + surfaceChannels.length === 0 ||
275 + minimumContrast(accentChannels) >= minimum
276 + ) {
277 + return accent;
278 + }
279 +
280 + const [lightness, a, b] = srgbToOklab(accentChannels);
281 + const hue = Math.atan2(b, a);
282 + const inGamut = (channels: ReadonlyArray<number>) =>
283 + channels.every((channel) => channel >= -1e-4 && channel <= 1 + 1e-4);
284 + const mostVivid = (stepLightness: number) => {
285 + let chroma = 0;
286 + let lower = 0;
287 + let upper = Math.max(Math.hypot(a, b), 0.2);
288 + for (let index = 0; index < 20; index += 1) {
289 + const candidate = (lower + upper) / 2;
290 + if (
291 + inGamut(
292 + oklabToLinearSrgb(stepLightness, candidate * Math.cos(hue), candidate * Math.sin(hue)),
293 + )
294 + ) {
295 + chroma = candidate;
296 + lower = candidate;
297 + } else {
298 + upper = candidate;
299 + }
300 + }
301 + return oklabToSrgb(stepLightness, chroma * Math.cos(hue), chroma * Math.sin(hue));
302 + };
303 +
304 + const lighten = minimumContrast([255, 255, 255]) >= minimumContrast([0, 0, 0]);
305 + const step = lighten ? 0.002 : -0.002;
306 + for (let next = lightness; lighten ? next <= 1 : next >= 0; next += step) {
307 + const candidate = mostVivid(next);
308 + if (minimumContrast(candidate) >= minimum) {
309 + return `#${candidate.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
310 + }
311 + }
312 + return lighten ? "#ffffff" : "#000000";
313 +}
314 +
315 export function themeColorWithAlpha(color: string, alpha: number): string {
316 const channels = rgbChannels(color);
317 if (channels) {
apps/mobile/src/lib/projectIcon.test.ts new
+81
@@ -0,0 +1,81 @@
1 +import type { ProjectIconOverride } from "@t3tools/contracts";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import { projectAutoMonogram, resolveProjectChipIcon } from "./projectIcon";
5 +
6 +const project = (title: string, projectIcon?: ProjectIconOverride) => ({
7 + title,
8 + workspaceRoot: `/work/${title}`,
9 + projectIcon,
10 +});
11 +
12 +describe("resolveProjectChipIcon", () => {
13 + const favicon = () => "https://env.example/favicon.png";
14 + const noFavicon = () => null;
15 +
16 + it("shows the chat bubble for unknown threads and the no-project folder", () => {
17 + expect(resolveProjectChipIcon(null, "/scratch", favicon)).toBeNull();
18 + expect(resolveProjectChipIcon(project("scratch"), "/work/scratch", favicon)).toBeNull();
19 + });
20 +
21 + it("prefers a custom icon over the favicon", () => {
22 + expect(
23 + resolveProjectChipIcon(
24 + project("t3code", { kind: "monogram", text: "Q7", color: "violet" }),
25 + null,
26 + favicon,
27 + ),
28 + ).toEqual({ kind: "monogram", text: "Q7", color: "violet" });
29 + expect(
30 + resolveProjectChipIcon(project("t3code", { kind: "emoji", emoji: "🚀" }), null, favicon),
31 + ).toEqual({ kind: "emoji", emoji: "🚀" });
32 + expect(
33 + resolveProjectChipIcon(
34 + project("lucide proj", { kind: "lucide", name: "rocket", color: "emerald" }),
35 + null,
36 + favicon,
37 + ),
38 + ).toEqual({ kind: "monogram", text: "LP", color: "emerald" });
39 + });
40 +
41 + it("uses the favicon, then a monogram of the title", () => {
42 + expect(resolveProjectChipIcon(project("t3code"), null, favicon)).toEqual({
43 + kind: "favicon",
44 + uri: "https://env.example/favicon.png",
45 + });
46 + expect(resolveProjectChipIcon(project("Auto Monogram"), null, noFavicon)).toEqual({
47 + kind: "monogram",
48 + text: "AM",
49 + color: "lime",
50 + });
51 + expect(
52 + resolveProjectChipIcon(
53 + project("t3code"),
54 + null,
55 + () => "https://env.example/api/assets/project-favicon-missing",
56 + ),
57 + ).toMatchObject({ kind: "monogram" });
58 + });
59 +});
60 +
61 +describe("projectAutoMonogram", () => {
62 + it("matches desktop's deriveProjectIdentity", () => {
63 + const desktop = [
64 + ["t3code", "T3", "teal"],
65 + ["Auto Monogram", "AM", "lime"],
66 + ["blitzdiff", "BF", "pink"],
67 + ["uoalbumdotclub", "UB", "gray"],
68 + [" Tagium ", "TM", "lime"],
69 + ["Café Ünïcode", "CÜ", "fuchsia"],
70 + ["web2 app", "W2", "emerald"],
71 + ] as const;
72 + for (const [title, text, color] of desktop) {
73 + expect(projectAutoMonogram(title)).toEqual({ kind: "monogram", text, color });
74 + }
75 + });
76 +
77 + it("leaves untitled projects to the folder icon, like desktop", () => {
78 + expect(projectAutoMonogram("")).toBeNull();
79 + expect(projectAutoMonogram(" ")).toBeNull();
80 + });
81 +});
apps/mobile/src/lib/projectIcon.ts
+40 -1
@@ -1,4 +1,6 @@
1 -import type { ProjectIconColor, ProjectIconOverride } from "@t3tools/contracts";
1 +import { isScratchProject } from "@t3tools/client-runtime/state/projects";
2 +import { ProjectIconColor, type ProjectIconOverride } from "@t3tools/contracts";
3 +import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
4
5 export type ProjectIconGlyph =
6 | { readonly kind: "emoji"; readonly emoji: string }
@@ -30,6 +32,24 @@ export function projectMonogram(projectName: string): string {
32 return Array.from(`${first}${second}`.toUpperCase()).slice(0, 2).join("");
33 }
34
35 +export function projectMonogramColor(projectName: string): ProjectIconColor {
36 + const seed = projectName.normalize("NFKC").trim().toLocaleLowerCase("en-US") || "project";
37 + let index = 0;
38 + for (const glyph of seed) {
39 + index = (index * 31 + (glyph.codePointAt(0) ?? 0)) % ProjectIconColor.literals.length;
40 + }
41 + return ProjectIconColor.literals[index] ?? "blue";
42 +}
43 +
44 +export function projectAutoMonogram(projectTitle: string): ProjectIconGlyph | null {
45 + if (!projectTitle.trim()) return null;
46 + return {
47 + kind: "monogram",
48 + text: projectMonogram(projectTitle),
49 + color: projectMonogramColor(projectTitle),
50 + };
51 +}
52 +
53 export function resolveProjectIconGlyph(
54 projectIcon: ProjectIconOverride | null | undefined,
55 projectTitle: string,
@@ -46,6 +66,25 @@ export function resolveProjectIconGlyph(
66 }
67 }
68
69 +export type ProjectChipIcon = { readonly kind: "favicon"; readonly uri: string } | ProjectIconGlyph;
70 +
71 +export function resolveProjectChipIcon(
72 + project: {
73 + readonly title: string;
74 + readonly workspaceRoot: string;
75 + readonly projectIcon?: ProjectIconOverride | null;
76 + } | null,
77 + scratchWorkspaceRoot: string | null | undefined,
78 + faviconUrl: () => string | null,
79 +): ProjectChipIcon | null {
80 + if (!project || isScratchProject(project, scratchWorkspaceRoot)) return null;
81 + const glyph = resolveProjectIconGlyph(project.projectIcon, project.title);
82 + if (glyph) return glyph;
83 + const url = faviconUrl();
84 + if (url && !isProjectFaviconFallbackUrl(url)) return { kind: "favicon", uri: url };
85 + return projectAutoMonogram(project.title);
86 +}
87 +
88 const PROJECT_ICON_COLOR_CLASSES: Record<
89 ProjectIconColor,
90 { readonly text: string; readonly background: string }
apps/mobile/src/native/ProjectChipIconImages.tsx new
+150
@@ -0,0 +1,150 @@
1 +import type { ProjectIconColor } from "@t3tools/contracts";
2 +import * as Effect from "effect/Effect";
3 +import { Atom } from "effect/reactivity";
4 +import { useRef, useSyncExternalStore } from "react";
5 +import { Platform, View } from "react-native";
6 +import Svg, { Rect, Text } from "react-native-svg";
7 +import { useResolveClassNames } from "uniwind";
8 +
9 +import { countGlyphs, projectIconColorClassNames, type ProjectIconGlyph } from "../lib/projectIcon";
10 +
11 +const TILE_SIZE = 48;
12 +
13 +interface PendingTile {
14 + readonly key: string;
15 + readonly glyph: ProjectIconGlyph;
16 + readonly promise: Promise<string>;
17 + readonly resolve: (uri: string) => void;
18 + readonly reject: () => void;
19 +}
20 +
21 +const tiles = new Map<string, PendingTile>();
22 +let pendingTiles: ReadonlyArray<PendingTile> = [];
23 +const listeners = new Set<() => void>();
24 +
25 +export function projectGlyphKey(glyph: ProjectIconGlyph): string {
26 + return JSON.stringify(
27 + glyph.kind === "emoji" ? ["emoji", glyph.emoji] : ["monogram", glyph.text, glyph.color],
28 + );
29 +}
30 +
31 +function decodeGlyphKey(key: string): ProjectIconGlyph {
32 + const [kind, text, color] = JSON.parse(key) as [string, string, ProjectIconColor];
33 + return kind === "emoji" ? { kind: "emoji", emoji: text } : { kind: "monogram", text, color };
34 +}
35 +
36 +function rasterize(key: string): Promise<string> {
37 + const existing = tiles.get(key);
38 + if (existing) return existing.promise;
39 + let resolve!: (uri: string) => void;
40 + let reject!: () => void;
41 + const promise = new Promise<string>((done, fail) => {
42 + resolve = done;
43 + reject = fail;
44 + });
45 + const tile = { key, glyph: decodeGlyphKey(key), promise, resolve, reject };
46 + tiles.set(key, tile);
47 + pendingTiles = [...pendingTiles, tile];
48 + queueMicrotask(notify);
49 + return promise;
50 +}
51 +
52 +function finish(tile: PendingTile, base64: string | undefined) {
53 + if (base64) {
54 + tile.resolve(`data:image/png;base64,${base64.replace(/\s/g, "")}`);
55 + } else {
56 + tile.reject();
57 + }
58 + pendingTiles = pendingTiles.filter((pending) => pending !== tile);
59 + notify();
60 +}
61 +
62 +function notify() {
63 + for (const listener of listeners) listener();
64 +}
65 +
66 +function subscribe(listener: () => void) {
67 + listeners.add(listener);
68 + return () => listeners.delete(listener);
69 +}
70 +
71 +export const projectGlyphImageAtom = Atom.family((key: string) =>
72 + Atom.make(Effect.tryPromise(() => rasterize(key))).pipe(
73 + Atom.keepAlive,
74 + Atom.withLabel(`mobile-project-glyph-image:${key}`),
75 + ),
76 +);
77 +
78 +export function ProjectChipIconRasterizer() {
79 + const pending = useSyncExternalStore(subscribe, () => pendingTiles);
80 + return pending.map((tile) => <GlyphCapture key={tile.key} tile={tile} />);
81 +}
82 +
83 +function captureTile(svg: Svg, tile: PendingTile) {
84 + try {
85 + svg.toDataURL(
86 + (base64?: string) => finish(tile, base64),
87 + Platform.OS === "ios" ? { width: TILE_SIZE, height: TILE_SIZE } : undefined,
88 + );
89 + } catch {
90 + finish(tile, undefined);
91 + }
92 +}
93 +
94 +function GlyphCapture(props: { readonly tile: PendingTile }) {
95 + const started = useRef(false);
96 + const capture = (svg: Svg | null) => {
97 + if (!svg || started.current) return;
98 + started.current = true;
99 + requestAnimationFrame(() => captureTile(svg, props.tile));
100 + };
101 + return (
102 + <View
103 + pointerEvents="none"
104 + style={{ position: "absolute", left: -TILE_SIZE * 4, top: 0, opacity: 0 }}
105 + >
106 + <Svg ref={capture} width={TILE_SIZE} height={TILE_SIZE}>
107 + {props.tile.glyph.kind === "emoji" ? (
108 + <Text
109 + x={TILE_SIZE / 2}
110 + y={TILE_SIZE * 0.8}
111 + textAnchor="middle"
112 + fontSize={TILE_SIZE * 0.8}
113 + >
114 + {props.tile.glyph.emoji}
115 + </Text>
116 + ) : (
117 + <MonogramTile text={props.tile.glyph.text} color={props.tile.glyph.color} />
118 + )}
119 + </Svg>
120 + </View>
121 + );
122 +}
123 +
124 +function MonogramTile(props: { readonly text: string; readonly color: ProjectIconColor }) {
125 + const classNames = projectIconColorClassNames(props.color);
126 + const background = useResolveClassNames(classNames.background);
127 + const foreground = useResolveClassNames(`font-mono ${classNames.text}`);
128 + const fontSize = TILE_SIZE * (countGlyphs(props.text) === 1 ? 0.6 : 0.515625);
129 + return (
130 + <>
131 + <Rect
132 + width={TILE_SIZE}
133 + height={TILE_SIZE}
134 + rx={TILE_SIZE * 0.25}
135 + fill={String(background.backgroundColor)}
136 + />
137 + <Text
138 + x={TILE_SIZE / 2}
139 + y={TILE_SIZE / 2 + fontSize * 0.36}
140 + textAnchor="middle"
141 + fill={String(foreground.color)}
142 + fontFamily={typeof foreground.fontFamily === "string" ? foreground.fontFamily : undefined}
143 + fontWeight="700"
144 + fontSize={fontSize}
145 + >
146 + {props.text}
147 + </Text>
148 + </>
149 + );
150 +}
apps/mobile/src/native/T3ComposerEditor.ios.tsx
+4 -2
@@ -18,6 +18,7 @@ import { StyleSheet } from "react-native";
18 import {
19 composerChipSizeSuffix,
20 contextChipIcon,
21 + contextChipAccent,
22 contextChipPresentation,
23 contextRecordFileName,
24 } from "../lib/composerChipPresentation";
@@ -157,6 +158,7 @@ export function ComposerEditor({
158 );
159
160 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
161 + const chipTextColor = createNativeComposerTheme(theme).text;
162 const tokensJson = useMemo(() => {
163 const tokens = collectComposerInlineTokens(props.value, {
164 preserveTrailingFrom: confirmedTokensRef.current,
@@ -181,7 +183,7 @@ export function ComposerEditor({
183 source: token.source,
184 start: token.start,
185 end: token.end,
184 - accent: presentation.accent,
186 + accent: contextChipAccent(presentation.accent, theme, chipTextColor),
187 label:
188 token.type === "skill"
189 ? (skillLabels.get(token.value) ?? token.value)
@@ -194,7 +196,7 @@ export function ComposerEditor({
196 };
197 }),
198 );
197 - }, [props.value, props.context, skillLabels]);
199 + }, [props.value, props.context, skillLabels, theme, chipTextColor]);
200 // Every render resolves against the snapshot history, so a render whose
201 // (value, selection) lags the acknowledged native state is stamped behind
202 // the native revision and rejected by the editor instead of re-applying a
apps/mobile/src/native/T3ComposerEditor.native.tsx
+4 -2
@@ -19,6 +19,7 @@ import { Image, Platform, StyleSheet } from "react-native";
19 import {
20 composerChipSizeSuffix,
21 contextChipIcon,
22 + contextChipAccent,
23 contextChipPresentation,
24 contextRecordFileName,
25 } from "../lib/composerChipPresentation";
@@ -155,6 +156,7 @@ export function ComposerEditor({
156 );
157
158 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
159 + const chipTextColor = createNativeComposerTheme(theme).text;
160 const tokensJson = useMemo(() => {
161 const tokens = collectComposerInlineTokens(props.value, {
162 preserveTrailingFrom: confirmedTokensRef.current,
@@ -179,7 +181,7 @@ export function ComposerEditor({
181 source: token.source,
182 start: token.start,
183 end: token.end,
182 - accent: presentation.accent,
184 + accent: contextChipAccent(presentation.accent, theme, chipTextColor),
185 label:
186 token.type === "skill"
187 ? (skillLabels.get(token.value) ?? token.value)
@@ -192,7 +194,7 @@ export function ComposerEditor({
194 };
195 }),
196 );
195 - }, [props.value, props.context, skillLabels]);
197 + }, [props.value, props.context, skillLabels, theme, chipTextColor]);
198 // Every render resolves against the snapshot history, so a render whose
199 // (value, selection) lags the acknowledged native state is stamped behind
200 // the native revision and rejected by the editor instead of re-applying a
apps/mobile/src/native/useEnrichedLinkVariants.ts
+37 -10
@@ -6,12 +6,13 @@ import type {
6 MarkdownStyle,
7 } from "react-native-enriched-markdown";
8 import type { ComposerContextRecord } from "@t3tools/contracts";
9 -import { contextChipPresentation } from "../lib/composerChipPresentation";
9 +import { contextChipAccent, contextChipPresentation } from "../lib/composerChipPresentation";
10 import { CONTEXT_CHIP_ICON_SOURCES } from "../lib/contextChipIcons.generated";
11 import { FONT_FAMILIES } from "../lib/fontFamilies";
12 import { contextChipIconSource } from "../lib/contextChipIconSource";
13 import { markdownFileIconSource } from "../lib/markdownFileIcons";
14 import { markdownLinkIconSource } from "../lib/markdownLinkIcons";
15 +import { useUniwindTheme } from "../lib/useUniwindTheme";
16 import { resolveMarkdownLinkIcon, resolveMarkdownLinkPresentation } from "../lib/markdownLinks";
17 import type {
18 MarkdownLinkCustomization,
@@ -22,19 +23,42 @@ import {
23 enrichedLinkVariantPattern,
24 enrichedSkillDisplayName,
25 enrichedSkillReference,
26 + enrichedThreadLinkPresentation,
27 } from "../lib/enrichedLinkPresentation";
28
29 +function chipCustomization(
30 + chip: ReturnType<typeof enrichedContextLinkPresentation>,
31 +): MarkdownLinkCustomization | undefined {
32 + if (!chip) return undefined;
33 + return {
34 + label: chip.label,
35 + icon: contextChipIconSource(chip.icon),
36 + chip: { accent: chip.accent, tintsIcon: chip.icon.kind === "chip" },
37 + };
38 +}
39 +
40 export function enrichedContextLinkCustomization(
41 href: string,
42 records?: ReadonlyArray<ComposerContextRecord>,
43 +) {
44 + return chipCustomization(enrichedContextLinkPresentation(href, records));
45 +}
46 +
47 +export function enrichedThreadLinkCustomization(href: string) {
48 + return chipCustomization(enrichedThreadLinkPresentation(href));
49 +}
50 +
51 +export function withChipIcon(
52 + customization: MarkdownLinkCustomization | undefined,
53 + iconUri: string | undefined,
54 ): MarkdownLinkCustomization | undefined {
31 - const context = enrichedContextLinkPresentation(href, records);
32 - if (!context) return undefined;
33 - return {
34 - label: context.label,
35 - icon: contextChipIconSource(context.icon),
36 - chip: { accent: context.accent, tintsIcon: context.icon.kind === "chip" },
37 - };
55 + return iconUri && customization?.chip
56 + ? {
57 + ...customization,
58 + icon: { uri: iconUri },
59 + chip: { ...customization.chip, tintsIcon: false },
60 + }
61 + : customization;
62 }
63
64 function presentation(
@@ -74,6 +98,7 @@ export function useEnrichedLinkVariants(
98 props: SelectableMarkdownTextProps,
99 ) {
100 const { linkCustomization, skills, textStyle } = props;
101 + const theme = useUniwindTheme();
102 const links = useMemo(() => {
103 const byUrl = new Map<string, MarkdownLinkCustomization>();
104 for (const asset of assets) {
@@ -88,10 +113,12 @@ export function useEnrichedLinkVariants(
113 new Map(
114 [...links].map(([url, link]) => [
115 url,
91 - link.chip ? (link.chip.accent ?? textStyle.color) : undefined,
116 + link.chip
117 + ? (contextChipAccent(link.chip.accent, theme, textStyle.color) ?? textStyle.color)
118 + : undefined,
119 ]),
120 ),
94 - [links, textStyle],
121 + [links, textStyle, theme],
122 );
123 const linkVariants = useMemo<MarkdownStyle["linkVariants"]>(
124 () =>
apps/mobile/src/state/entities.ts
+98 -6
@@ -7,17 +7,29 @@ import type {
7 EnvironmentThread,
8 EnvironmentThreadShell,
9 } from "@t3tools/client-runtime/state/shell";
10 -import type {
10 +import {
11 EnvironmentId,
12 - ScopedProjectRef,
13 - ScopedThreadRef,
14 - ServerConfig,
12 ThreadId,
13 + type ComposerContextRecord,
14 + type ScopedProjectRef,
15 + type ScopedThreadRef,
16 + type ServerConfig,
17 } from "@t3tools/contracts";
17 -import { hasThreadLinks, relabelThreadLinks } from "@t3tools/shared/threadLinks";
18 -import { Atom } from "effect/reactivity";
18 +import { scopeThreadRef } from "@t3tools/client-runtime/environment";
19 +import {
20 + hasThreadLinks,
21 + relabelThreadLinks,
22 + resolveThreadLinkRef,
23 +} from "@t3tools/shared/threadLinks";
24 +import * as Option from "effect/Option";
25 +import * as Schema from "effect/Schema";
26 +import { AsyncResult, Atom } from "effect/reactivity";
27 import { useMemo } from "react";
28
29 +import { threadChipTargets } from "../lib/enrichedLinkPresentation";
30 +import { resolveProjectChipIcon } from "../lib/projectIcon";
31 +import { projectGlyphImageAtom, projectGlyphKey } from "../native/ProjectChipIconImages";
32 +import { projectFaviconUrlAtom } from "./assets";
33 import { environmentProjects } from "./projects";
34 import { environmentServerConfigsAtom, serverEnvironment } from "./server";
35 import { environmentThreadDetails, environmentThreadShells } from "./threads";
@@ -53,6 +65,73 @@ const threadTitlesAtom = Atom.family((environmentId: EnvironmentId) => {
65 }).pipe(Atom.withLabel(`mobile-thread-titles:${environmentId}`));
66 });
67
68 +const decodeThreadKey = Schema.decodeUnknownSync(Schema.Tuple([EnvironmentId, ThreadId]));
69 +const decodeThreadChipTargets = Schema.decodeUnknownSync(
70 + Schema.Array(
71 + Schema.Struct({
72 + href: Schema.String,
73 + environmentId: EnvironmentId,
74 + threadId: ThreadId,
75 + link: Schema.Boolean,
76 + }),
77 + ),
78 +);
79 +
80 +const threadProjectChipIconAtom = Atom.family((key: string) => {
81 + const ref = scopeThreadRef(...decodeThreadKey(JSON.parse(key)));
82 + return Atom.make((get): string | null => {
83 + const shell = get(environmentThreadShells.threadShellAtom(ref));
84 + const project = shell
85 + ? get(
86 + environmentProjects.projectAtom({
87 + environmentId: ref.environmentId,
88 + projectId: shell.projectId,
89 + }),
90 + )
91 + : null;
92 + const icon = resolveProjectChipIcon(
93 + project,
94 + get(serverEnvironment.configValueAtom(ref.environmentId))?.scratchWorkspaceRoot,
95 + () =>
96 + project
97 + ? get(
98 + projectFaviconUrlAtom({
99 + environmentId: ref.environmentId,
100 + cwd: project.workspaceRoot,
101 + faviconPath: project.faviconPath,
102 + }),
103 + )
104 + : null,
105 + );
106 + if (!icon) return null;
107 + if (icon.kind === "favicon") return icon.uri;
108 + return Option.getOrNull(AsyncResult.value(get(projectGlyphImageAtom(projectGlyphKey(icon)))));
109 + }).pipe(Atom.withLabel(`mobile-thread-project-chip-icon:${key}`));
110 +});
111 +
112 +const EMPTY_THREAD_CHIP_ICONS: ReadonlyMap<string, string> = new Map();
113 +const EMPTY_THREAD_CHIP_ICONS_ATOM = Atom.make(EMPTY_THREAD_CHIP_ICONS).pipe(
114 + Atom.withLabel("mobile-thread-chip-icons:empty"),
115 +);
116 +
117 +const threadChipIconsAtom = Atom.family((key: string) => {
118 + const targets = decodeThreadChipTargets(JSON.parse(key));
119 + return Atom.make((get) => {
120 + const icons = new Map<string, string>();
121 + for (const target of targets) {
122 + const source = scopeThreadRef(target.environmentId, target.threadId);
123 + const ref = target.link
124 + ? (resolveThreadLinkRef(source, get(environmentThreadShells.threadRefsAtom)) ?? source)
125 + : source;
126 + const icon = get(
127 + threadProjectChipIconAtom(JSON.stringify([ref.environmentId, ref.threadId])),
128 + );
129 + if (icon) icons.set(target.href, icon);
130 + }
131 + return icons;
132 + }).pipe(Atom.withLabel(`mobile-thread-chip-icons:${key}`));
133 +});
134 +
135 export function waitForProject(
136 ref: ScopedProjectRef,
137 timeoutMs = 10_000,
@@ -123,6 +202,19 @@ export function useLiveThreadLinkLabels(markdown: string, environmentId: Environ
202 );
203 }
204
205 +export function useThreadChipIcons(
206 + environmentId: EnvironmentId,
207 + markdown: string,
208 + records?: ReadonlyArray<ComposerContextRecord>,
209 +): ReadonlyMap<string, string> {
210 + const targets = threadChipTargets(environmentId, markdown, records);
211 + return useAtomValue(
212 + targets.length === 0
213 + ? EMPTY_THREAD_CHIP_ICONS_ATOM
214 + : threadChipIconsAtom(JSON.stringify(targets)),
215 + );
216 +}
217 +
218 export function useEnvironmentServerConfig(
219 environmentId: EnvironmentId | null,
220 ): ServerConfig | null {
vite.config.ts
+1
@@ -537,6 +537,7 @@ export default defineConfig({
537 "apps/mobile/src/native/T3ComposerEditor.ios.tsx",
538 "apps/mobile/src/native/T3ComposerEditor.native.tsx",
539 "apps/mobile/src/native/SelectableMarkdownText.tsx",
540 + "apps/mobile/src/native/useEnrichedLinkVariants.ts",
541 ],
542 rules: {
543 "t3code/no-mobile-uniwind-theme-escape-hatches": ["error", { allowUniwindTheme: true }],