Cotton code
258 lines · 11.5 KB · TypeScriptRaw
// Derive the Mac app's icons from the ONE constellation-C master, and Cotton// Dev's icons from the real ones.////   assets/brand/logo-master.png//     → assets/icon.icns          the app icon (a graphite tile, every size)//     → assets/icon.png           the 1024 tile, for anyone who wants a PNG//     → assets/icon-dev.icns      Cotton Dev for Mac — the same tiles, marked//     → assets/icon-dev.png       its 1024 tile////   App/Cotton/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png  (the phone)//     → App/Cotton/Assets.xcassets/AppIconDev.appiconset/          (Cotton Dev)//   App/Flavours/books/…/AppIconBooks.appiconset/AppIconBooks-1024.png//     → App/Flavours/books/…/AppIconBooksDev.appiconset/           (Cotton Books Dev)//// COTTON DEV IS TOLD APART AT A GLANCE, AND IS NOT NEW ART. Its icon is the// real one with the thread's hue turned (`DEV_HUE_DEGREES`) and a DEV band// across the foot (`devMark`) — so a phone or a Dock holding both apps never// leaves the owner guessing which one he is about to open, and the mark stays// the one constellation-C. `project.yml`'s `COTTON_APPICON_NAME_dev` names the// phone set; the Mac's packaging names `icon-dev.icns`.//// WHY derive rather than draw: the constellation-C is the logo and a// typographic "C" is never a stand-in for it, so every RASTER form the Mac app// needs has to come out of the master — the thread's texture is what makes it// that picture. Re-run this after the master changes; the outputs are committed// because a build must not need the network.//// THE MENU-BAR ICON IS NOT HERE, and used not to be drawn at all. This script// wrote `assets/trayTemplate.png` + `@2x` for the Electron app; the Swift port// never carried the lookup across, `build-app.sh` never copied the files into// the bundle, and the item drew an SF Symbol ring instead — which is the empty// circle the owner reported on 2026-09-10. At 22 points the master's thread is// half a pixel wide and downsamples to grey, so the answer is not a smaller// PNG: `ConstellationMarkImage` DRAWS the logo from `CottonMark`'s geometry// with a minimum stroke, and there is no file to be missing.import { spawnSync } from "node:child_process";import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import sharp from "sharp";import { centreOffset, iconsetEntries, tileGeometry } from "./lib/iconset";const appDir = join(dirname(fileURLToPath(import.meta.url)), "..");const repoRoot = join(appDir, "..", "..");const masterPath = join(repoRoot, "assets/brand/logo-master.png");const assetsDir = join(appDir, "assets");/** * Cotton Graphite — the ground the launch screen and the dark theme already use. * * Read from the palette rather than written down again: this file had its own * copy of the same hex, which is a second source for one brand colour and the * kind that drifts silently once somebody edits the palette. * * The palette moved in step 5b. It was `packages/ui/src/theme/cottonPalettes.data`, * imported here by RELATIVE PATH across a package boundary — which is how this * broke when `packages/ui` went with the Expo phone in 5c. The DECLARATION is * now `crates/cotton-core/src/design/palette.rs`, and a `cargo test` emits * `palette.json` beside it and fails on drift, so this reads the emitted JSON. * * THE PATH BELONGS TO THE RUST CORE'S LANE, so the read is checked and the * failure names the path and the command that rewrites it — a palette this * script could not read would otherwise become an undefined hex, and an * undefined hex is a transparent tile with no error. */const PALETTE_JSON = join(  repoRoot,  "crates/cotton-core/src/design/palette.json",);function graphiteGround(): string {  let raw: string;  try {    raw = readFileSync(PALETTE_JSON, "utf8");  } catch (error) {    throw new Error(      `${PALETTE_JSON} is unreadable (${String(error)}). The Rust core owns this ` +        `path; \`cargo test -p cotton-core\` writes it from src/design/palette.rs.`,    );  }  const parsed = JSON.parse(raw) as { graphite?: { ground?: string } };  const ground = parsed.graphite?.ground;  if (typeof ground !== "string" || !/^#[0-9A-Fa-f]{6}$/.test(ground)) {    throw new Error(      `${PALETTE_JSON} has no \`graphite.ground\` hex — the icon ground would be ` +        `undefined, which sharp renders as a transparent tile with no error.`,    );  }  return ground;}const GRAPHITE = graphiteGround();function run(command: string, args: string[]): void {  const result = spawnSync(command, args, { encoding: "utf8" });  if (result.status !== 0) {    throw new Error(`${command} failed: ${result.stderr || result.error?.message}`);  }}/** * One graphite tile with the logo centred on it, as PNG bytes. * * Exported because the committed `assets/icon.png` is this function's output * at 1024, and `scripts/__tests__/constellation-mark.test.ts` re-runs it to * catch a committed icon that has drifted from the master art. A derived asset * nobody re-derives is just a file. */export async function renderTile(side: number): Promise<Buffer> {  const { radius, logoBox } = tileGeometry(side);  const tile = Buffer.from(    `<svg width="${side}" height="${side}" xmlns="http://www.w3.org/2000/svg">` +      `<rect width="${side}" height="${side}" rx="${radius}" ry="${radius}" fill="${GRAPHITE}"/>` +      `</svg>`,  );  const logo = await sharp(masterPath)    .resize(logoBox, logoBox, { fit: "inside", background: { r: 0, g: 0, b: 0, alpha: 0 } })    .toBuffer({ resolveWithObject: true });  const { left, top } = centreOffset(side, logo.info.width, logo.info.height);  return sharp(tile).composite([{ input: logo.data, left, top }]).png().toBuffer();}/** * How far Cotton Dev turns the hue: the steel-blue thread goes brick-red and * the amber knots go teal. Large on purpose — at 16 px the band is a smear and * the colour is all that tells the two apps apart. */export const DEV_HUE_DEGREES = 150;/** The band's fill — a flat red no palette token means anything else by. */// eslint-disable-next-line no-restricted-syntax -- Cotton Dev's icon band is a build-flavor marker, not a design colour; no palette token should ever carry it.const DEV_BAND = "#D6453D";/** * Cotton Dev's form of a real icon: the hue turned and a DEV band across the * foot, inside the tile's own margin so a rounded Mac tile clips nothing. * `opaque` drops the alpha channel — the phone's icon must carry none (Apple * refuses one; `ios-project-spec.test.ts`), the Mac's rounded tile needs it. */export async function devMark(real: Buffer, side: number, opaque: boolean): Promise<Buffer> {  const bandWidth = Math.round(side * 0.5);  const bandHeight = Math.round(side * 0.12);  const left = Math.round((side - bandWidth) / 2);  const top = Math.round(side * 0.82);  const radius = Math.round(bandHeight / 2);  const font = Math.round(bandHeight * 0.68);  const band = Buffer.from(    `<svg width="${side}" height="${side}" xmlns="http://www.w3.org/2000/svg">` +      `<rect x="${left}" y="${top}" width="${bandWidth}" height="${bandHeight}" rx="${radius}" ry="${radius}" fill="${DEV_BAND}"/>` +      `<text x="${side / 2}" y="${top + bandHeight / 2}" dy="0.35em" text-anchor="middle" ` +      `font-family="Helvetica Neue, Helvetica, Arial, sans-serif" font-weight="700" ` +      `font-size="${font}" letter-spacing="${Math.round(font * 0.12)}" fill="#FFFFFF">DEV</text>` +      `</svg>`,  );  const turned = await sharp(real).resize(side, side).modulate({ hue: DEV_HUE_DEGREES }).png().toBuffer();  const marked = sharp(turned).composite([{ input: band, left: 0, top: 0 }]);  return (opaque ? marked.removeAlpha() : marked).png().toBuffer();}/** The phone's real icon and Cotton Dev's set beside it. */const PHONE_ICON = join(appDir, "App/Cotton/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png");const PHONE_DEV_SET = join(appDir, "App/Cotton/Assets.xcassets/AppIconDev.appiconset");const PHONE_DEV_FILE = "AppIconDev-1024.png";/** * A flavour's real phone icon and its dev twin's set beside it, marked the * way Cotton Dev's is: the painted icon is the flavour's art, never redrawn. */const FLAVOUR_DEV_ICONS = [  {    real: join(appDir, "App/Flavours/books/Assets.xcassets/AppIconBooks.appiconset/AppIconBooks-1024.png"),    set: join(appDir, "App/Flavours/books/Assets.xcassets/AppIconBooksDev.appiconset"),    file: "AppIconBooksDev-1024.png",  },];async function derivePhoneDevIcon(real: string, set: string, file: string): Promise<void> {  mkdirSync(set, { recursive: true });  writeFileSync(join(set, file), await devMark(readFileSync(real), 1024, true));  const manifest = {    images: [{ filename: file, idiom: "universal", platform: "ios", size: "1024x1024" }],    info: { author: "xcode", version: 1 },  };  writeFileSync(join(set, "Contents.json"), JSON.stringify(manifest, null, 2) + "\n");}/** Every flavour's dev twin's icon, marked from its real one. */export async function deriveFlavourDevIcons(): Promise<void> {  for (const { real, set, file } of FLAVOUR_DEV_ICONS) {    await derivePhoneDevIcon(real, set, file);    console.log(`  ${join(set, file)}`);  }}export async function deriveIcons(): Promise<void> {  statSync(masterPath); // fail loudly, naming the file, if the master moved  mkdirSync(assetsDir, { recursive: true });  const scratch = mkdtempSync(join(tmpdir(), "cottondb-icons-"));  try {    const iconset = join(scratch, "CottonDB.iconset");    const devIconset = join(scratch, "CottonDev.iconset");    mkdirSync(iconset);    mkdirSync(devIconset);    // Render each side once and reuse it for the 1x/2x names that share it.    // Cotton Dev's tile is the real tile at the same side, marked.    const rendered = new Map<number, Buffer>();    const devRendered = new Map<number, Buffer>();    for (const { file, pixels } of iconsetEntries()) {      let tile = rendered.get(pixels);      if (!tile) {        tile = await renderTile(pixels);        rendered.set(pixels, tile);      }      let devTile = devRendered.get(pixels);      if (!devTile) {        devTile = await devMark(tile, pixels, false);        devRendered.set(pixels, devTile);      }      writeFileSync(join(iconset, file), tile);      writeFileSync(join(devIconset, file), devTile);    }    run("iconutil", ["-c", "icns", iconset, "-o", join(assetsDir, "icon.icns")]);    run("iconutil", ["-c", "icns", devIconset, "-o", join(assetsDir, "icon-dev.icns")]);    const largest = rendered.get(1024);    const devLargest = devRendered.get(1024);    if (!largest || !devLargest) throw new Error("the 1024 tile was never rendered");    writeFileSync(join(assetsDir, "icon.png"), largest);    writeFileSync(join(assetsDir, "icon-dev.png"), devLargest);    await derivePhoneDevIcon(PHONE_ICON, PHONE_DEV_SET, PHONE_DEV_FILE);    await deriveFlavourDevIcons();    const sizes = ["icon.icns", "icon.png", "icon-dev.icns", "icon-dev.png"]      .map((name) => `${name} ${(statSync(join(assetsDir, name)).size / 1024).toFixed(1)} KB`)      .join(" · ");    console.log(`derived from ${masterPath}\n  ${sizes}\n  ${join(PHONE_DEV_SET, PHONE_DEV_FILE)}`);  } finally {    rmSync(scratch, { recursive: true, force: true });  }}const invokedDirectly = process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];if (invokedDirectly) {  deriveIcons().catch((error: unknown) => {    console.error(error instanceof Error ? error.message : error);    process.exit(1);  });}