Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectChipIconImages.tsx

162 lines4.9 KB

1import type { ProjectIconColor } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import { Atom } from "effect/reactivity";
5import { useRef, useSyncExternalStore } from "react";
6import { Platform, View } from "react-native";
7import Svg, { Rect, Text } from "react-native-svg";
8import { useResolveClassNames } from "uniwind";
9​
10import { countGlyphs, projectIconColorClassNames, type ProjectIconGlyph } from "../lib/projectIcon";
11​
12const TILE_SIZE = 48;
13​
14interface PendingTile {
15 readonly key: string;
16 readonly glyph: ProjectIconGlyph;
17 readonly promise: Promise<string>;
18 readonly resolve: (uri: string) => void;
19 readonly reject: () => void;
21​
22const tiles = new Map<string, PendingTile>();
23let pendingTiles: ReadonlyArray<PendingTile> = [];
24const listeners = new Set<() => void>();
25​
26export function projectGlyphKey(glyph: ProjectIconGlyph): string {
27 return JSON.stringify(
28 glyph.kind === "emoji" ? ["emoji", glyph.emoji] : ["monogram", glyph.text, glyph.color],
29 );
31​
32function decodeGlyphKey(key: string): ProjectIconGlyph {
33 const [kind, text, color] = JSON.parse(key) as [string, string, ProjectIconColor];
34 return kind === "emoji" ? { kind: "emoji", emoji: text } : { kind: "monogram", text, color };
36​
37function rasterize(key: string): Promise<string> {
38 const existing = tiles.get(key);
39 if (existing) return existing.promise;
40 let resolve!: (uri: string) => void;
41 let reject!: () => void;
42 const promise = new Promise<string>((done, fail) => {
43 resolve = done;
44 reject = fail;
45 });
46 const tile = { key, glyph: decodeGlyphKey(key), promise, resolve, reject };
47 tiles.set(key, tile);
48 pendingTiles = [...pendingTiles, tile];
49 queueMicrotask(notify);
50 return promise;
52​
53function finish(tile: PendingTile, base64: string | undefined) {
54 if (base64) {
55 tile.resolve(`data:image/png;base64,${base64.replace(/\s/g, "")}`);
56 } else {
57 tile.reject();
58 }
59 pendingTiles = pendingTiles.filter((pending) => pending !== tile);
60 notify();
62​
63function notify() {
64 for (const listener of listeners) listener();
66​
67function subscribe(listener: () => void) {
68 listeners.add(listener);
69 return () => listeners.delete(listener);
71​
72class ProjectGlyphRasterizeError extends Schema.TaggedError<ProjectGlyphRasterizeError>()(
73 "ProjectGlyphRasterizeError",
74 { key: Schema.String, cause: Schema.Defect() },
75) {
76 override get message(): string {
77 return `Could not rasterize the project glyph ${this.key}.`;
78 }
80​
81export const projectGlyphImageAtom = Atom.family((key: string) =>
82 Atom.make(
83 Effect.tryPromise({
84 try: () => rasterize(key),
85 catch: (cause) => new ProjectGlyphRasterizeError({ key, cause }),
86 }),
87 ).pipe(Atom.keepAlive, Atom.withLabel(`mobile-project-glyph-image:${key}`)),
88);
89​
90export function ProjectChipIconRasterizer() {
91 const pending = useSyncExternalStore(subscribe, () => pendingTiles);
92 return pending.map((tile) => <GlyphCapture key={tile.key} tile={tile} />);
94​
95function captureTile(svg: Svg, tile: PendingTile) {
96 try {
97 svg.toDataURL(
98 (base64?: string) => finish(tile, base64),
99 Platform.OS === "ios" ? { width: TILE_SIZE, height: TILE_SIZE } : undefined,
100 );
101 } catch {
102 finish(tile, undefined);
103 }
105​
106function GlyphCapture(props: { readonly tile: PendingTile }) {
107 const started = useRef(false);
108 const capture = (svg: Svg | null) => {
109 if (!svg || started.current) return;
110 started.current = true;
111 requestAnimationFrame(() => captureTile(svg, props.tile));
112 };
113 return (
114 <View
115 pointerEvents="none"
116 style={{ position: "absolute", left: -TILE_SIZE * 4, top: 0, opacity: 0 }}
117 >
118 <Svg ref={capture} width={TILE_SIZE} height={TILE_SIZE}>
119 {props.tile.glyph.kind === "emoji" ? (
120 <Text
121 x={TILE_SIZE / 2}
122 y={TILE_SIZE * 0.8}
123 textAnchor="middle"
124 fontSize={TILE_SIZE * 0.8}
125 >
126 {props.tile.glyph.emoji}
127 </Text>
128 ) : (
129 <MonogramTile text={props.tile.glyph.text} color={props.tile.glyph.color} />
130 )}
131 </Svg>
132 </View>
133 );
135​
136function MonogramTile(props: { readonly text: string; readonly color: ProjectIconColor }) {
137 const classNames = projectIconColorClassNames(props.color);
138 const background = useResolveClassNames(classNames.background);
139 const foreground = useResolveClassNames(`font-mono ${classNames.text}`);
140 const fontSize = TILE_SIZE * (countGlyphs(props.text) === 1 ? 0.6 : 0.515625);
141 return (
142 <>
143 <Rect
144 width={TILE_SIZE}
145 height={TILE_SIZE}
146 rx={TILE_SIZE * 0.25}
147 fill={String(background.backgroundColor)}
148 />
149 <Text
150 x={TILE_SIZE / 2}
151 y={TILE_SIZE / 2 + fontSize * 0.36}
152 textAnchor="middle"
153 fill={String(foreground.color)}
154 fontFamily={typeof foreground.fontFamily === "string" ? foreground.fontFamily : undefined}
155 fontWeight="700"
156 fontSize={fontSize}
157 >
158 {props.text}
159 </Text>
160 </>
161 );