Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/heph-avatar-brand-export.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
---

Repository tooling only: adds a Storybook capture story and an `export:brand-assets` script that
render the Heph mentor avatar into versioned brand PNGs under `docs/static/img/brand/`. Nothing in
the shipped application changes, so operators and users see no difference.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/static/img/brand/heph-avatar-1024.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions webapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"chromatic:ci": "chromatic --only-changed",
"chromatic:dry-run": "chromatic --dry-run",
"test:e2e": "playwright test",
"export:brand-assets": "node scripts/export-brand-assets.ts",
"export:readme-assets": "node scripts/export-readme-assets.ts",
"storybook:dev": "storybook dev -p 6006",
"generate:api": "openapi-ts"
Expand Down
161 changes: 161 additions & 0 deletions webapp/scripts/export-brand-assets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import { spawn } from "node:child_process";
import { mkdir, readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { inflateSync } from "node:zlib";

import { type Browser, chromium } from "playwright";

const scriptDirectory = import.meta.dirname;
const webappDirectory = resolve(scriptDirectory, "..");
const outputDirectory = resolve(webappDirectory, "../docs/static/img/brand");
const port = 6107;
const storybookUrl = `http://127.0.0.1:${port}`;
const storyId = "components-mentor-mentoricon--brand-export";

interface CaptureConfig {
/** Output filename inside docs/static/img/brand/. */
fileName: string;
selector: string;
/** Whether to capture with a transparent backdrop instead of the tile's own background. */
transparent: boolean;
}

// Each tile is 512 CSS pixels; deviceScaleFactor 2 yields the 1024x1024 brand asset.
const expectedTileSize = 512;
const expectedPixelSize = 1024;

const captureConfigs: CaptureConfig[] = [
{
fileName: "heph-avatar-1024.png",
selector: '[data-brand-export="heph-avatar"]',
transparent: false,
},
{
fileName: "heph-avatar-1024-transparent.png",
selector: '[data-brand-export="heph-avatar-transparent"]',
transparent: true,
},
];

function indexContains(index: unknown): boolean {
if (!index || typeof index !== "object" || !("entries" in index)) return false;
const { entries } = index;
return Boolean(entries && typeof entries === "object" && storyId in entries);
}

async function waitForStorybook(): Promise<void> {
for (let attempt = 0; attempt < 120; attempt += 1) {
const response = await fetch(`${storybookUrl}/index.json`).catch(() => undefined);
if (response?.ok) {
if (!indexContains(await response.json())) {
throw new Error(`Story ${storyId} is not in the Storybook index. Was it renamed?`);
}
return;
}
await new Promise((resolveDelay) => {
setTimeout(resolveDelay, 500);
});
}
throw new Error("Storybook did not start within 60 seconds.");
}

/**
* Asserted after render; a mismatch fails the export instead of committing a wrong image.
* Beyond the dimensions, the solid export must be opaque RGB (Slack rejects icons that rely on
* transparency) and the transparent export must actually carry an alpha channel with an empty
* corner, so a silently ignored `omitBackground` cannot slip through.
*/
async function assertPng(path: string, transparent: boolean): Promise<void> {
const png = await readFile(path);
const width = png.readUInt32BE(16);
const height = png.readUInt32BE(20);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
if (width !== expectedPixelSize || height !== expectedPixelSize) {
throw new Error(`${path} is ${width}x${height}px; expected ${expectedPixelSize}px square.`);
}
const colorType = png.readUInt8(25);
if (!transparent) {
if (colorType !== 2) {
throw new Error(`${path} has PNG color type ${colorType}; the solid export must be RGB (2).`);
}
return;
}
if (colorType !== 6) {
throw new Error(
`${path} has PNG color type ${colorType}; the transparent export must be RGBA (6).`,
);
}
const idat: Buffer[] = [];
for (let offset = 8; offset + 8 <= png.length;) {
const chunkLength = png.readUInt32BE(offset);
const chunkType = png.toString("latin1", offset + 4, offset + 8);
if (chunkType === "IDAT") idat.push(png.subarray(offset + 8, offset + 8 + chunkLength));
if (chunkType === "IEND") break;
offset += chunkLength + 12;
}
// Every PNG filter reads the first pixel's neighbours as zero, so its RGBA bytes appear
// verbatim right after row 0's filter byte and the corner alpha is byte 4.
const cornerAlpha = inflateSync(Buffer.concat(idat)).readUInt8(4);
if (cornerAlpha !== 0) {
throw new Error(`${path} has corner alpha ${cornerAlpha}; the transparent export needs 0.`);
}
}

async function capture(browser: Browser, config: CaptureConfig): Promise<void> {
const page = await browser.newPage({
viewport: { width: 1400, height: 700 },
deviceScaleFactor: 2,
colorScheme: "light",
reducedMotion: "reduce",
});

try {
const globals = encodeURIComponent("theme:light");
await page.goto(`${storybookUrl}/iframe.html?id=${storyId}&viewMode=story&globals=${globals}`);
await page.waitForLoadState("networkidle");
await page.addStyleTag({
content: `*,*::before,*::after{animation:none!important;transition:none!important}${
config.transparent ? "html,body{background:transparent!important}" : ""
}`,
});

const exportSurface = page.locator(config.selector);
await exportSurface.waitFor({ state: "visible" });
const bounds = await exportSurface.boundingBox();
if (!bounds || Math.round(bounds.width) !== expectedTileSize) {
throw new Error(
`${config.fileName} export width was ${bounds?.width ?? "missing"}px; expected ${expectedTileSize}px.`,
);
}

const outputPath = resolve(outputDirectory, config.fileName);
await exportSurface.screenshot({ path: outputPath, omitBackground: config.transparent });
await assertPng(outputPath, config.transparent);
process.stdout.write(`Exported ${outputPath}\n`);
} finally {
await page.close();
}
}

// The brand directory also holds hand-drawn SVG marks, so it is never wiped — the
// export only overwrites the PNGs it owns.
await mkdir(outputDirectory, { recursive: true });
const storybook = spawn(
"pnpm",
["run", "storybook:dev", "--port", String(port), "--ci", "--host", "127.0.0.1"],
{
cwd: webappDirectory,
stdio: "ignore",
},
);

try {
await waitForStorybook();
const browser = await chromium.launch();
try {
for (const config of captureConfigs) await capture(browser, config);
} finally {
await browser.close();
}
} finally {
storybook.kill("SIGTERM");
}
28 changes: 28 additions & 0 deletions webapp/src/components/mentor/MentorIcon.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,34 @@ export const MultipleIcons: Story = {
},
};

export const BrandExport: Story = {
parameters: {
chromatic: { disableSnapshot: true },
docs: {
description: {
story:
"Capture surfaces for `pnpm --filter webapp run export:brand-assets`, which screenshots them into `docs/static/img/brand/`. Colors are literal white and black so the export matches the hammer marks and never follows the Storybook theme.",
},
},
},
render: () => (
<div className="flex gap-8">
<div
data-brand-export="heph-avatar"
className="flex size-[512px] items-center justify-center bg-white text-black"
>
<MentorIcon size={400} pad={2} animated={false} />
</div>
<div
data-brand-export="heph-avatar-transparent"
className="flex size-[512px] items-center justify-center bg-transparent text-black"
>
<MentorIcon size={400} pad={2} animated={false} />
</div>
</div>
),
};

export const AccessibilityPreference: Story = {
render: () => (
<div className="space-y-4">
Expand Down
Loading