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

export-android-icons.ts

218 lines8.4 KB

1#!/usr/bin/env node
2​
3// Icon Composer exports already contain a rounded-square silhouette, and Android masks
4// the central 72dp of a 108dp adaptive canvas, so exporting them as a foreground produces
5// a double-framed icon with the letters cropped by the mask. Instead, each variant gets a
6// full-bleed background layer (the artwork behind the wordmark) and a shared transparent
7// foreground that keeps the wordmark inside the safe zone.
8​
9import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
10import * as NodeServices from "@effect/platform-node/NodeServices";
11import * as Console from "effect/Console";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import sharp from "sharp";
17​
18type IconVariant = "dev" | "nightly" | "prod";
19​
20const ADAPTIVE_CANVAS = 432;
21const SPLASH_CANVAS = 1152;
22const TEXT = { x: 15.53, y: 37, width: 94.5, height: 57 };
23const WORDMARK_FRACTION = 0.48;
24const COMPOSER_CANVAS_PT = 1024;
25const SVG_DENSITY = 300;
26const OUTPUT_DIRECTORY = "apps/mobile/assets";
27const PRODUCTION_BACKGROUND_COLOR = "#000000";
28​
29export class AndroidIconRenderError extends Schema.TaggedError<AndroidIconRenderError>()(
30 "AndroidIconRenderError",
31 { layer: Schema.String, cause: Schema.Defect() },
32) {}
33​
34const wordmarkTransform = (size: number) => {
35 const scale = (size * WORDMARK_FRACTION) / TEXT.width;
36 const tx = (size - TEXT.width * scale) / 2 - TEXT.x * scale;
37 const ty = (size - TEXT.height * scale) / 2 - TEXT.y * scale;
38 return `translate(${tx.toFixed(3)} ${ty.toFixed(3)}) scale(${scale.toFixed(4)})`;
39};
40​
41const canvasSvg = (size: number, inner: string) =>
42 `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" fill="none">${inner}</svg>`;
43​
44// The layer sources clip to a 10pt rounded rectangle for the iOS silhouette. Android
45// applies its own mask, so the layer must bleed to the canvas edge.
46const fullBleed = (svg: string) =>
47 svg.replace(/<rect width="128" height="128" rx="10"\/>/, '<rect width="128" height="128"/>');
48​
49const rasterize = (layer: string, svg: string, width: number, height = width) =>
50 Effect.tryPromise({
51 try: () =>
52 sharp(Buffer.from(svg), { density: SVG_DENSITY }).resize(width, height).png().toBuffer(),
53 catch: (cause) => new AndroidIconRenderError({ layer, cause }),
54 });
55​
56const composite = (
57 layer: string,
58 base: Buffer,
59 overlays: ReadonlyArray<{ input: Buffer; left?: number; top?: number }>,
60) =>
61 Effect.tryPromise({
62 try: () =>
63 sharp(base)
64 .composite([...overlays])
65 .png()
66 .toBuffer(),
67 catch: (cause) => new AndroidIconRenderError({ layer, cause }),
68 });
69​
70const solidCanvas = (layer: string, size: number, background: string) =>
71 Effect.tryPromise({
72 try: () =>
73 sharp({ create: { width: size, height: size, channels: 4, background } })
74 .png()
75 .toBuffer(),
76 catch: (cause) => new AndroidIconRenderError({ layer, cause }),
77 });
78​
79const readLayerSource = Effect.fn("androidIcons.readLayerSource")(function* (
80 repositoryRoot: string,
81 variant: IconVariant,
82 file: string,
83) {
84 const fs = yield* FileSystem.FileSystem;
85 const path = yield* Path.Path;
86 return yield* fs.readFileString(
87 path.join(repositoryRoot, "assets", variant, "app-icon.icon", "Assets", file),
88 );
89});
90​
91const renderForeground = Effect.fn("androidIcons.renderForeground")(function* (
92 repositoryRoot: string,
93 size: number,
94) {
95 const text = yield* readLayerSource(repositoryRoot, "prod", "text.svg");
96 const paths = text.match(/<path[^>]*\/>/g) ?? [];
97 return yield* rasterize(
98 "foreground",
99 canvasSvg(size, `<g transform="${wordmarkTransform(size)}">${paths.join("")}</g>`),
100 size,
101 );
102});
103​
104const renderDevelopmentBackground = Effect.fn("androidIcons.renderDevelopmentBackground")(
105 function* (repositoryRoot: string, size: number) {
106 const annotations = yield* readLayerSource(repositoryRoot, "dev", "annotations.svg");
107 const defs = annotations.match(/<defs>[\s\S]*?<\/defs>/)?.[0] ?? "";
108 const body = annotations.replace(/^[\s\S]*?<\/defs>/, "").replace(/<\/svg>\s*$/, "");
109 const paper = yield* readLayerSource(repositoryRoot, "dev", "background.svg");
110 const background = yield* rasterize("dev-background", fullBleed(paper), size);
111 const overlay = yield* rasterize(
112 "dev-annotations",
113 canvasSvg(size, `${defs}<g transform="${wordmarkTransform(size)}">${body}</g>`),
114 size,
115 );
116 return yield* composite("dev-background", background, [{ input: overlay }]);
117 },
118);
119​
120const renderNightlyBackground = Effect.fn("androidIcons.renderNightlyBackground")(function* (
121 repositoryRoot: string,
122 size: number,
123) {
124 // Positions mirror assets/nightly/app-icon.icon/icon.json. The SVG blur filter is
125 // dropped because Icon Composer ignores it and it smears at this raster size.
126 const clouds = [
127 { file: "cloud-lower-left.svg", scale: 25, translation: [-309.6375, 268.66077693836917] },
128 {
129 file: "cloud-upper-right.svg",
130 scale: 15,
131 translation: [387.9605131881942, -134.30064713259117],
132 },
133 ] as const;
134 const k = size / COMPOSER_CANVAS_PT;
135 const overlays = yield* Effect.forEach(clouds, (cloud) =>
136 Effect.gen(function* () {
137 const width = Math.round(64 * cloud.scale * k);
138 const height = Math.round(32 * cloud.scale * k);
139 const left = Math.round((COMPOSER_CANVAS_PT / 2 + cloud.translation[0]) * k - width / 2);
140 const top = Math.round((COMPOSER_CANVAS_PT / 2 + cloud.translation[1]) * k - height / 2);
141 const source = yield* readLayerSource(repositoryRoot, "nightly", cloud.file);
142 const png = yield* rasterize(
143 cloud.file,
144 source.replace(/ filter="url\(#soft\)"/, ""),
145 width,
146 height,
147 );
148 const x0 = Math.max(0, left);
149 const y0 = Math.max(0, top);
150 const x1 = Math.min(size, left + width);
151 const y1 = Math.min(size, top + height);
152 const clipped = yield* Effect.tryPromise({
153 try: () =>
154 sharp(png)
155 .extract({ left: x0 - left, top: y0 - top, width: x1 - x0, height: y1 - y0 })
156 .png()
157 .toBuffer(),
158 catch: (cause) => new AndroidIconRenderError({ layer: cloud.file, cause }),
159 });
160 return { input: clipped, left: x0, top: y0 };
161 }),
162 );
163 const sky = yield* readLayerSource(repositoryRoot, "nightly", "background.svg");
164 const background = yield* rasterize("nightly-background", fullBleed(sky), size);
165 return yield* composite("nightly-background", background, overlays);
166});
167​
168const renderBackground = Effect.fn("androidIcons.renderBackground")(function* (
169 repositoryRoot: string,
170 variant: IconVariant,
171 size: number,
172) {
173 switch (variant) {
174 case "dev":
175 return yield* renderDevelopmentBackground(repositoryRoot, size);
176 case "nightly":
177 return yield* renderNightlyBackground(repositoryRoot, size);
178 case "prod":
179 return yield* solidCanvas("prod-background", size, PRODUCTION_BACKGROUND_COLOR);
180 }
181});
182​
183const renderSplashIcon = Effect.fn("androidIcons.renderSplashIcon")(function* (
184 repositoryRoot: string,
185 variant: IconVariant,
186) {
187 const background = yield* renderBackground(repositoryRoot, variant, SPLASH_CANVAS);
188 const foreground = yield* renderForeground(repositoryRoot, SPLASH_CANVAS);
189 return yield* composite(`${variant}-splash`, background, [{ input: foreground }]);
190});
191​
192const exportAndroidIcons = Effect.gen(function* () {
193 const fs = yield* FileSystem.FileSystem;
194 const path = yield* Path.Path;
195 const repositoryRoot = path.resolve(import.meta.dirname, "..");
196 const outputs = [
197 ["android-icon-foreground.png", yield* renderForeground(repositoryRoot, ADAPTIVE_CANVAS)],
198 [
199 "android-icon-background-dev.png",
200 yield* renderDevelopmentBackground(repositoryRoot, ADAPTIVE_CANVAS),
201 ],
202 [
203 "android-icon-background-nightly.png",
204 yield* renderNightlyBackground(repositoryRoot, ADAPTIVE_CANVAS),
205 ],
206 ["android-splash-icon-dev.png", yield* renderSplashIcon(repositoryRoot, "dev")],
207 ["android-splash-icon-nightly.png", yield* renderSplashIcon(repositoryRoot, "nightly")],
208 ["android-splash-icon-prod.png", yield* renderSplashIcon(repositoryRoot, "prod")],
209 ] as const;
210 for (const [name, contents] of outputs) {
211 yield* fs.writeFile(path.join(repositoryRoot, OUTPUT_DIRECTORY, name), contents);
212 yield* Console.log(`wrote ${OUTPUT_DIRECTORY}/${name}`);
213 }
214});
215​
216if (import.meta.main) {
217 exportAndroidIcons.pipe(Effect.provide(NodeServices.layer), NodeRuntime.runMain);