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

export-android-icons.ts

235 lines9.6 KB

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