Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Path from "effect/Path";
4import * as Schema from "effect/Schema";
5import sharp from "sharp";
6
7import type { AuditViewport, OverlayBox } from "./diff.ts";
8
9class MobileAuditRenderError extends Schema.TaggedError<
10 MobileAuditRenderError,
11 { readonly brand: unique symbol }
12>()("MobileAuditRenderError", {
13 path: Schema.String,
14 cause: Schema.Defect(),
15}) {
16 override get message(): string {
17 return `Failed to render annotated audit image for ${this.path}.`;
18 }
19}
20
21function escapeXml(value: string): string {
22 return value
23 .replaceAll("&", "&")
24 .replaceAll("<", "<")
25 .replaceAll(">", ">")
26 .replaceAll('"', """);
27}
28
29// Covered by the caller's renderSingle / renderComparison span.
30const renderAnnotatedPanel = Effect.fnUntraced(function* (input: {
31 readonly pngPath: string;
32 readonly boxes: ReadonlyArray<OverlayBox>;
33 readonly bannerText: string;
34 readonly bannerBg: string;
35 readonly viewport?: AuditViewport | undefined;
36 readonly targetWidth: number;
37}) {
38 const fs = yield* FileSystem.FileSystem;
39 const sourceBytes = yield* fs
40 .readFile(input.pngPath)
41 .pipe(Effect.mapError((cause) => new MobileAuditRenderError({ path: input.pngPath, cause })));
42
43 return yield* Effect.tryPromise({
44 try: async () => {
45 const meta = await sharp(sourceBytes).metadata();
46 const srcWidth = meta.width ?? input.targetWidth;
47 const srcHeight = meta.height ?? input.targetWidth * 2;
48 const coordScaleX = input.viewport?.width ? srcWidth / input.viewport.width : 1;
49 const coordScaleY = input.viewport?.height ? srcHeight / input.viewport.height : 1;
50
51 const scale = input.targetWidth / srcWidth;
52 const targetHeight = Math.round(srcHeight * scale);
53 const bannerHeight = 44;
54
55 const rectsSvg = input.boxes
56 .map((box) => {
57 const rx = Math.round(box.x * coordScaleX * scale);
58 const ry = Math.round(box.y * coordScaleY * scale);
59 const rw = Math.max(8, Math.round(box.width * coordScaleX * scale));
60 const rh = Math.max(8, Math.round(box.height * coordScaleY * scale));
61 const stroke = box.color;
62 const fill = stroke === "#16a34a" ? "rgba(22,163,74,0.14)" : "rgba(239,68,68,0.16)";
63 const tag = box.tag;
64 const tagW = Math.min(
65 input.targetWidth - 12,
66 Math.max(46, Math.round(tag.length * 7.2 + 14)),
67 );
68 const tagH = 20;
69 let tx = Math.min(input.targetWidth - tagW - 4, Math.max(4, rx));
70 let ty = ry - tagH - 2;
71 if (ty < 4) ty = Math.min(targetHeight - tagH - 4, ry + rh + 2);
72 if (box.tagSide === "right") {
73 tx = Math.min(input.targetWidth - tagW - 4, rx + rw - tagW);
74 } else if (box.tagSide === "below") {
75 ty = Math.min(targetHeight - tagH - 4, ry + rh + 2);
76 } else if (box.tagSide === "inside-right") {
77 tx = Math.min(input.targetWidth - tagW - 4, rx + rw - tagW - 4);
78 ty = Math.max(4, ry + Math.round((rh - tagH) / 2));
79 }
80 return [
81 `<rect x="${rx}" y="${ry}" width="${rw}" height="${rh}" rx="5" fill="${fill}" stroke="${stroke}" stroke-width="2.5" />`,
82 tag
83 ? `<rect x="${tx}" y="${ty}" width="${tagW}" height="${tagH}" rx="4" fill="${stroke}" />` +
84 `<text x="${tx + 7}" y="${ty + 14}" font-family="DejaVu Sans, Arial, sans-serif" font-size="11.5" font-weight="700" fill="#ffffff">${escapeXml(tag)}</text>`
85 : "",
86 ].join("");
87 })
88 .join("\n");
89
90 const overlaySvg = Buffer.from(
91 `<svg width="${input.targetWidth}" height="${targetHeight}" xmlns="http://www.w3.org/2000/svg">${rectsSvg}</svg>`,
92 );
93
94 const annotatedImg = await sharp(sourceBytes)
95 .resize(input.targetWidth, targetHeight)
96 .composite([{ input: overlaySvg, top: 0, left: 0 }])
97 .png()
98 .toBuffer();
99
100 const headerSvg = Buffer.from(
101 `<svg width="${input.targetWidth}" height="${bannerHeight}" xmlns="http://www.w3.org/2000/svg">` +
102 `<rect width="${input.targetWidth}" height="${bannerHeight}" fill="${input.bannerBg}" />` +
103 `<text x="${input.targetWidth / 2}" y="28" text-anchor="middle" font-family="DejaVu Sans, Arial, sans-serif" font-size="15" font-weight="700" fill="#ffffff">${escapeXml(input.bannerText)}</text>` +
104 `</svg>`,
105 );
106
107 const combined = await sharp({
108 create: {
109 width: input.targetWidth,
110 height: targetHeight + bannerHeight,
111 channels: 4,
112 background: { r: 24, g: 24, b: 27, alpha: 1 },
113 },
114 })
115 .composite([
116 { input: headerSvg, top: 0, left: 0 },
117 { input: annotatedImg, top: bannerHeight, left: 0 },
118 ])
119 .png()
120 .toBuffer();
121
122 return { buffer: combined, width: input.targetWidth, height: targetHeight + bannerHeight };
123 },
124 catch: (cause) => new MobileAuditRenderError({ path: input.pngPath, cause }),
125 });
126});
127
128export const renderSingleAnnotatedImage = Effect.fn("mobileAudit.renderSingle")(function* (input: {
129 readonly pngPath: string;
130 readonly boxes: ReadonlyArray<OverlayBox>;
131 readonly bannerText: string;
132 readonly bannerBg: string;
133 readonly viewport?: AuditViewport | undefined;
134 readonly outPath: string;
135 readonly targetWidth?: number | undefined;
136}) {
137 const fs = yield* FileSystem.FileSystem;
138 const path = yield* Path.Path;
139 const panel = yield* renderAnnotatedPanel({
140 pngPath: input.pngPath,
141 boxes: input.boxes,
142 bannerText: input.bannerText,
143 bannerBg: input.bannerBg,
144 viewport: input.viewport,
145 targetWidth: input.targetWidth ?? 540,
146 });
147 yield* fs
148 .makeDirectory(path.dirname(input.outPath), { recursive: true })
149 .pipe(Effect.mapError((cause) => new MobileAuditRenderError({ path: input.outPath, cause })));
150 yield* fs
151 .writeFile(input.outPath, panel.buffer)
152 .pipe(Effect.mapError((cause) => new MobileAuditRenderError({ path: input.outPath, cause })));
153});
154
155export const renderBeforeAfterComparison = Effect.fn("mobileAudit.renderComparison")(
156 function* (input: {
157 readonly beforePng: string;
158 readonly beforeBoxes: ReadonlyArray<OverlayBox>;
159 readonly beforeTitle: string;
160 readonly beforeViewport?: AuditViewport | undefined;
161 readonly afterPng: string;
162 readonly afterBoxes: ReadonlyArray<OverlayBox>;
163 readonly afterTitle: string;
164 readonly afterBannerBg?: string | undefined;
165 readonly afterViewport?: AuditViewport | undefined;
166 readonly outPath: string;
167 readonly panelWidth?: number | undefined;
168 }) {
169 const fs = yield* FileSystem.FileSystem;
170 const path = yield* Path.Path;
171 const targetWidth = input.panelWidth ?? 540;
172 const [left, right] = yield* Effect.all(
173 [
174 renderAnnotatedPanel({
175 pngPath: input.beforePng,
176 boxes: input.beforeBoxes,
177 bannerText: input.beforeTitle,
178 bannerBg: "#b91c1c",
179 viewport: input.beforeViewport,
180 targetWidth,
181 }),
182 renderAnnotatedPanel({
183 pngPath: input.afterPng,
184 boxes: input.afterBoxes,
185 bannerText: input.afterTitle,
186 bannerBg: input.afterBannerBg ?? "#15803d",
187 viewport: input.afterViewport,
188 targetWidth,
189 }),
190 ],
191 { concurrency: 2 },
192 );
193
194 const gap = 16;
195 const pad = 16;
196 const width = left.width + right.width + gap + pad * 2;
197 const height = Math.max(left.height, right.height) + pad * 2;
198
199 const outputBuffer = yield* Effect.tryPromise({
200 try: () =>
201 sharp({
202 create: {
203 width,
204 height,
205 channels: 4,
206 background: { r: 24, g: 24, b: 27, alpha: 1 },
207 },
208 })
209 .composite([
210 { input: left.buffer, top: pad, left: pad },
211 { input: right.buffer, top: pad, left: pad + left.width + gap },
212 ])
213 .png()
214 .toBuffer(),
215 catch: (cause) => new MobileAuditRenderError({ path: input.outPath, cause }),
216 });
217
218 yield* fs
219 .makeDirectory(path.dirname(input.outPath), { recursive: true })
220 .pipe(Effect.mapError((cause) => new MobileAuditRenderError({ path: input.outPath, cause })));
221 yield* fs
222 .writeFile(input.outPath, outputBuffer)
223 .pipe(Effect.mapError((cause) => new MobileAuditRenderError({ path: input.outPath, cause })));
224
225 return { width, height };
226 },
227);