Merge remote-tracking branch 'origin/main' into apple-name
# Conflicts: # CHANGELOG.md
This commit is contained in:
commit
6c4f8a4551
25 changed files with 951 additions and 82 deletions
15
CHANGELOG.md
15
CHANGELOG.md
|
|
@ -17,6 +17,21 @@
|
||||||
to it is not written into the file), the listing completeness view, `check --aso`, the console app picker and `scan`'s
|
to it is not written into the file), the listing completeness view, `check --aso`, the console app picker and `scan`'s
|
||||||
beta-wording rule use it for every locale without its own `### name` block. `check` reports an App Store name over 30
|
beta-wording rule use it for every locale without its own `### name` block. `check` reports an App Store name over 30
|
||||||
characters in any locale and hints when every locale uses the plain `app.name` (`hints` in `--json`).
|
characters in any locale and hints when every locale uses the plain `app.name` (`hints` in `--json`).
|
||||||
|
- Screenshot glyphs (a Turkish render showed fallback glyphs for "ş" / "ğ" while `shots check` passed): the cause was
|
||||||
|
not subsetting (css2 `text=` already takes glyphs from every subset) but the title font: Lilita One has no ş ğ İ and
|
||||||
|
most of Latin Extended-A, so Chrome silently drew them with another font.
|
||||||
|
- `shots fonts` checks every character of every language (copy.json + config languages) against the cmap of the
|
||||||
|
faces that draw it (new pure-TS cmap reader for TTF / OTF / TTC / WOFF / WOFF2, no dependency), adds an automatic
|
||||||
|
Noto fallback per missing character (Noto Sans Display for titles at a heavy weight, Noto Sans, Noto Sans
|
||||||
|
<Script>, Symbols) and logs it; a character no fallback covers fails with the language and the characters. Writes
|
||||||
|
`.storebound/fonts/fonts.json` (faces and per-language stacks).
|
||||||
|
- `shots render` refuses fonts that no longer cover the copy, uses the per-language stacks, and measures in the page
|
||||||
|
(CDP platform fonts of one probe per face and character) which face drew every character; `report.json` keeps it
|
||||||
|
per image (`fonts`). `shots check` (and `validate`, `shots gallery`) raise an ERROR for glyphs drawn by a fallback
|
||||||
|
the config did not choose or by a system font, and warn for renders without font data.
|
||||||
|
- New `shots.fonts.fallback: ['Noto Sans Display']` to accept a fallback. Default game title font is now Paytone One
|
||||||
|
(covers Latin Extended and Vietnamese) in the template, the demo and the built-in default; README and the
|
||||||
|
store-screenshots skill document the default stack per script.
|
||||||
- `console fill`, from a real run whose App Store Connect session had expired (the add button was "not found" while
|
- `console fill`, from a real run whose App Store Connect session had expired (the add button was "not found" while
|
||||||
the window showed the sign-in form):
|
the window showed the sign-in form):
|
||||||
- Sign-in is detected by URL and frame (App Store Connect `/login`, idmsa.apple.com / appleid.apple.com frames,
|
- Sign-in is detected by URL and frame (App Store Connect `/login`, idmsa.apple.com / appleid.apple.com frames,
|
||||||
|
|
|
||||||
23
README.md
23
README.md
|
|
@ -431,10 +431,10 @@ run in the background with a log (`storebound shots render > .storebound/render.
|
||||||
| command | kind | what |
|
| command | kind | what |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `shots capture [--source web\|ios-sim\|android-emu\|folder]` | local | raw frames from your running app or game |
|
| `shots capture [--source web\|ios-sim\|android-emu\|folder]` | local | raw frames from your running app or game |
|
||||||
| `shots fonts` | network | font subsets for your copy (Noto for CJK / Arabic / Cyrillic / Devanagari ...) |
|
| `shots fonts` | network | font subsets for your copy (Noto for CJK / Arabic / Cyrillic / Devanagari ...) and the glyph coverage check per language |
|
||||||
| `shots render [--variant b \| --variants]` | local | every store size and language in the game or app style, feature graphic, contact sheet, overflow report |
|
| `shots render [--variant b \| --variants]` | local | every store size and language in the game or app style, feature graphic, contact sheet, overflow report |
|
||||||
| `shots jpeg` | local | JPEG q92 copies of the Play renders (about 4x faster uploads) |
|
| `shots jpeg` | local | JPEG q92 copies of the Play renders (about 4x faster uploads) |
|
||||||
| `shots check [--variants] [--json]` | local, read-only | store rules: sizes, alpha, format, bytes, counts, overflow, videos, folder frames |
|
| `shots check [--variants] [--json]` | local, read-only | store rules: sizes, alpha, format, bytes, counts, overflow, fallback / missing glyphs, videos, folder frames |
|
||||||
| `shots gallery` | local | `<renders>/index.html` review page |
|
| `shots gallery` | local | `<renders>/index.html` review page |
|
||||||
| `shots record [--source ...]` | local | app or gameplay clips: web (Chromium screencast), simulator, emulator, folder |
|
| `shots record [--source ...]` | local | app or gameplay clips: web (Chromium screencast), simulator, emulator, folder |
|
||||||
| `shots video [--target iphone,ipad,youtube]` | local | app previews + promo video with captions, poster, checks |
|
| `shots video [--target iphone,ipad,youtube]` | local | app previews + promo video with captions, poster, checks |
|
||||||
|
|
@ -711,7 +711,22 @@ languages, every store size, a review gallery and an app preview video. No store
|
||||||
Simulator (Unity, Godot, Flutter, React Native, native, Capacitor), `adb` for an Android emulator or device, or bring a folder of
|
Simulator (Unity, Godot, Flutter, React Native, native, Capacitor), `adb` for an Android emulator or device, or bring a folder of
|
||||||
your own frames. The status bar is cropped off and redrawn clean (9:41, full battery).
|
your own frames. The status bar is cropped off and redrawn clean (9:41, full battery).
|
||||||
2. **Copy.** Per language and scene: eyebrow, two-line title, subtitle, badges. Fonts are subset from Google Fonts to
|
2. **Copy.** Per language and scene: eyebrow, two-line title, subtitle, badges. Fonts are subset from Google Fonts to
|
||||||
exactly your characters, so Japanese, Chinese, Korean, Arabic (right to left) and Hindi just work.
|
exactly your characters, so Japanese, Chinese, Korean, Arabic (right to left) and Hindi just work. `shots fonts`
|
||||||
|
checks every character of every language against the font's cmap (TTF / OTF / WOFF / WOFF2, read in plain
|
||||||
|
TypeScript): a glyph the font lacks gets an automatic Noto fallback (logged), no fallback is a clear error, and a
|
||||||
|
render that drew any glyph with a fallback you did not choose, or with a system font, fails `shots check`.
|
||||||
|
|
||||||
|
| script | title / body font (default stack) |
|
||||||
|
|---|---|
|
||||||
|
| Latin incl. Latin Extended (tr, pl, cs, ro, hu ...) and Vietnamese | your `shots.fonts`; default game Paytone One + Montserrat, app Inter (all cover them) |
|
||||||
|
| Cyrillic, Greek | Noto Sans (whole line) |
|
||||||
|
| Arabic, Hebrew, Devanagari, Bengali, Thai | Noto Sans Arabic / Hebrew / Devanagari / Bengali / Thai (whole line) |
|
||||||
|
| Japanese, Korean, Chinese | Noto Sans JP / KR / SC (TC for zh-Hant, TW, HK) (whole line) |
|
||||||
|
| a character the stack lacks | Noto Sans Display (titles) or Noto Sans (body), Noto Sans <Script>, then Noto Sans Symbols 2 / Symbols / Math: an ERROR in `shots check` unless listed in `shots.fonts.fallback` |
|
||||||
|
|
||||||
|
Some display fonts lack Latin Extended: Lilita One has no ş ğ İ ą ę ń ś ź ż ć ă ș ț č ř ě ů ő ű or Vietnamese,
|
||||||
|
so Turkish, Polish, Czech, Romanian, Hungarian or Vietnamese titles need another title font (Paytone One, Baloo 2,
|
||||||
|
Rowdies) or `fonts: { ..., fallback: ['Noto Sans Display'] }` to accept the mixed glyphs.
|
||||||
3. **Render.** Every store size at exact pixels: iPhone 6.9" and 6.5", 13" iPad (if your app runs on iPad), Play
|
3. **Render.** Every store size at exact pixels: iPhone 6.9" and 6.5", 13" iPad (if your app runs on iPad), Play
|
||||||
phone, 7" and 10" tablets, the 1024 x 500 feature graphic. 24-bit RGB, no alpha (both stores reject it).
|
phone, 7" and 10" tablets, the 1024 x 500 feature graphic. 24-bit RGB, no alpha (both stores reject it).
|
||||||
4. **Check and review.** `shots check` applies the store rules locally (sources cited in `cli/shots/spec.ts`);
|
4. **Check and review.** `shots check` applies the store rules locally (sources cited in `cli/shots/spec.ts`);
|
||||||
|
|
@ -964,7 +979,7 @@ Some skills were sparked by other people's open work. I wrote my own text; the i
|
||||||
|
|
||||||
Built with Bun and plain `fetch` against the Google Play Developer API v3, the Play Developer Reporting API and the App
|
Built with Bun and plain `fetch` against the Google Play Developer API v3, the Play Developer Reporting API and the App
|
||||||
Store Connect API. Screenshot
|
Store Connect API. Screenshot
|
||||||
fonts come from Google Fonts at render time (Noto, Lilita One, Montserrat; SIL Open Font License 1.1). Not affiliated
|
fonts come from Google Fonts at render time (Noto, Paytone One, Montserrat, Inter; SIL Open Font License 1.1). Not affiliated
|
||||||
with Google or Apple.
|
with Google or Apple.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
|
||||||
|
|
@ -1,35 +1,95 @@
|
||||||
// Upload the App Review screenshot of every in-app purchase (idempotent: a screenshot whose MD5 matches is kept) and
|
// Upload the App Review screenshot of every in-app purchase (idempotent: a screenshot whose MD5 matches and that
|
||||||
// print each product's state. Nothing is submitted.
|
// Apple processed is kept) and print each product's state with what is still missing. Nothing is submitted.
|
||||||
// storebound apple iap-review [--dry]
|
// storebound apple iap-review [--dry]
|
||||||
// Screenshot per product: products[].reviewScreenshot, else apple.reviewShots/<product id>.(png|jpg).
|
// Screenshot per product: products[].reviewScreenshot, else apple.reviewShots/<product id>.(png|jpg).
|
||||||
// Size: a real device screenshot size (e.g. 1290 x 2796); other sizes fail with IMAGE_INCORRECT_DIMENSIONS.
|
// Size: an App Store screenshot size (iPhone or iPad, e.g. 1320 x 2868 or 1290 x 2796); Apple processes the upload
|
||||||
|
// after it is committed and fails other sizes with IMAGE_INCORRECT_DIMENSIONS, so the size is checked before the
|
||||||
|
// upload and the delivery state is read back after it (an upload is only "done" when Apple says COMPLETE).
|
||||||
import { existsSync, readFileSync } from 'node:fs';
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join, relative } from 'node:path';
|
||||||
import type { Ctx } from '../lib/ctx';
|
import type { Ctx } from '../lib/ctx';
|
||||||
import { need } from '../lib/ctx';
|
import { need } from '../lib/ctx';
|
||||||
import { done, log, warn } from '../lib/log';
|
import { done, log, warn } from '../lib/log';
|
||||||
|
import { IMAGE_SPECS, imageInfo } from '../shots/spec';
|
||||||
import { ascClient, md5 } from './asc';
|
import { ascClient, md5 } from './asc';
|
||||||
|
|
||||||
|
/** Every iPhone / iPad screenshot size App Store Connect accepts (portrait and landscape). */
|
||||||
|
export const REVIEW_SHOT_SIZES: [number, number][] = Object.values(IMAGE_SPECS)
|
||||||
|
.filter(s => s.store === 'apple' && /^APP_(IPHONE|IPAD)/.test(s.type))
|
||||||
|
.flatMap(s => s.sizes.flatMap(([w, h]) => [[w, h], [h, w]] as [number, number][]));
|
||||||
|
|
||||||
|
/** null when the image can be used as an App Review screenshot, else why not. Pure. */
|
||||||
|
export function reviewShotProblem(buf: Uint8Array): string | null {
|
||||||
|
const i = imageInfo(buf);
|
||||||
|
if (i.format === 'unknown') return 'not a PNG or JPEG';
|
||||||
|
if (!REVIEW_SHOT_SIZES.some(([w, h]) => w === i.w && h === i.h))
|
||||||
|
return `${i.w} x ${i.h} is not an App Store screenshot size (use e.g. 1320 x 2868 or 1290 x 2796 for iPhone, 2064 x 2752 for iPad; Apple fails other sizes with IMAGE_INCORRECT_DIMENSIONS)`;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Shot = { id: string; attributes: { sourceFileChecksum?: string; fileName?: string; assetDeliveryState?: { state?: string; errors?: { code?: string; description?: string }[] } } };
|
||||||
|
const stateOf = (s: Shot | undefined): string => s?.attributes.assetDeliveryState?.state ?? 'NONE';
|
||||||
|
const errorsOf = (s: Shot | undefined): string => (s?.attributes.assetDeliveryState?.errors ?? []).map(e => e.code ?? e.description).filter(Boolean).join(', ');
|
||||||
|
|
||||||
export async function run(ctx: Ctx): Promise<void> {
|
export async function run(ctx: Ctx): Promise<void> {
|
||||||
const { config, root, resolve } = ctx.loaded;
|
const { config, root, resolve } = ctx.loaded;
|
||||||
|
const dry = ctx.args.has('dry');
|
||||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||||
const appId = await c.app();
|
const appId = await c.app();
|
||||||
const defs = new Map((config.products ?? []).map(p => [p.id, p]));
|
const defs = new Map((config.products ?? []).map(p => [p.id, p]));
|
||||||
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) {
|
const shotOf = (id: string) => c.maybe(`/v2/inAppPurchases/${id}/appStoreReviewScreenshot`).then(r => r?.data as Shot | undefined);
|
||||||
|
const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`);
|
||||||
|
const seen = new Set(iaps.map((p: any) => p.attributes.productId));
|
||||||
|
const missingInStore = [...defs.keys()].filter(id => !seen.has(id));
|
||||||
|
if (missingInStore.length)
|
||||||
|
warn('apple', `not in App Store Connect yet: ${missingInStore.join(', ')} (created moments ago? the store's list can lag a minute; run again)`);
|
||||||
|
let problems = 0;
|
||||||
|
for (const p of iaps) {
|
||||||
const sku: string = p.attributes.productId;
|
const sku: string = p.attributes.productId;
|
||||||
const def = defs.get(sku);
|
const def = defs.get(sku);
|
||||||
const file = def?.reviewScreenshot ? resolve(def.reviewScreenshot)
|
const file = def?.reviewScreenshot ? resolve(def.reviewScreenshot)
|
||||||
: ['png', 'jpg', 'jpeg'].map(e => resolve(join(config.apple?.reviewShots ?? 'store/iap-review', `${sku}.${e}`))).find(existsSync);
|
: ['png', 'jpg', 'jpeg'].map(e => resolve(join(config.apple?.reviewShots ?? 'store/iap-review', `${sku}.${e}`))).find(existsSync);
|
||||||
if (!file || !existsSync(file)) { warn('apple', `${sku}: no review screenshot (set products[].reviewScreenshot)`); continue; }
|
if (!file || !existsSync(file)) { warn('apple', `${sku}: no review screenshot (set products[].reviewScreenshot)`); problems++; continue; }
|
||||||
const buf = readFileSync(file);
|
const buf = readFileSync(file);
|
||||||
const cur = (await c.maybe(`/v2/inAppPurchases/${p.id}/appStoreReviewScreenshot`))?.data;
|
const bad = reviewShotProblem(buf);
|
||||||
if (cur && cur.attributes.sourceFileChecksum === md5(buf) && cur.attributes.assetDeliveryState?.state !== 'FAILED') { log('apple', `${sku}: screenshot up to date`); continue; }
|
const cur = await shotOf(p.id);
|
||||||
if (ctx.args.has('dry')) { log('apple', `${sku}: would upload ${file}`); continue; }
|
const curState = stateOf(cur);
|
||||||
|
if (bad) {
|
||||||
|
warn('apple', `${sku}: ${relative(root, file)}: ${bad}${cur ? `; App Store Connect has ${curState}${errorsOf(cur) ? ` (${errorsOf(cur)})` : ''}` : ''}`);
|
||||||
|
problems++; continue;
|
||||||
|
}
|
||||||
|
if (cur && cur.attributes.sourceFileChecksum === md5(buf) && curState !== 'FAILED') { log('apple', `${sku}: screenshot up to date (${curState})`); continue; }
|
||||||
|
const why = !cur ? 'none in App Store Connect' : curState === 'FAILED' ? `the one there FAILED${errorsOf(cur) ? ` (${errorsOf(cur)})` : ''}` : 'a different file is there';
|
||||||
|
if (dry) { log('apple', `${sku}: would upload ${relative(root, file)} (${why})`); continue; }
|
||||||
if (cur) await c.asc('DELETE', `/v1/inAppPurchaseAppStoreReviewScreenshots/${cur.id}`);
|
if (cur) await c.asc('DELETE', `/v1/inAppPurchaseAppStoreReviewScreenshots/${cur.id}`);
|
||||||
await c.uploadAsset('inAppPurchaseAppStoreReviewScreenshots', { inAppPurchaseV2: { data: { type: 'inAppPurchases', id: p.id } } }, file);
|
await c.uploadAsset('inAppPurchaseAppStoreReviewScreenshots', { inAppPurchaseV2: { data: { type: 'inAppPurchases', id: p.id } } }, file);
|
||||||
log('apple', `${sku}: screenshot uploaded`);
|
// Apple processes the asset after the commit: read the state back (COMPLETE, or FAILED with the reason)
|
||||||
|
let after: Shot | undefined, state = 'UPLOAD_COMPLETE';
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
await Bun.sleep(i ? 3000 : 1500);
|
||||||
|
after = await shotOf(p.id); state = stateOf(after);
|
||||||
|
if (state === 'COMPLETE' || state === 'FAILED') break;
|
||||||
}
|
}
|
||||||
await Bun.sleep(3000);
|
if (state === 'FAILED') { warn('apple', `${sku}: Apple rejected the screenshot: ${errorsOf(after) || 'FAILED'}`); problems++; }
|
||||||
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) log('apple', `${p.attributes.productId}: ${p.attributes.state}`);
|
else log('apple', `${sku}: screenshot uploaded (${state})`);
|
||||||
done('apple', 'iap-review done (READY_TO_SUBMIT = complete; first IAPs go to review with a version, from the IAP page)');
|
}
|
||||||
|
// what keeps a product in MISSING_METADATA (Apple's rule: a localization, a price, availability and the screenshot)
|
||||||
|
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) {
|
||||||
|
const state: string = p.attributes.state;
|
||||||
|
if (state !== 'MISSING_METADATA') { log('apple', `${p.attributes.productId}: ${state}`); continue; }
|
||||||
|
const lack: string[] = [];
|
||||||
|
const locs = await c.maybe(`/v2/inAppPurchases/${p.id}/inAppPurchaseLocalizations?limit=50`);
|
||||||
|
if (!locs?.data?.length) lack.push('a localization (name + description)');
|
||||||
|
const price = await c.maybe(`/v2/inAppPurchases/${p.id}/iapPriceSchedule`);
|
||||||
|
if (!price?.data) lack.push('a price');
|
||||||
|
const avail = await c.maybe(`/v2/inAppPurchases/${p.id}/inAppPurchaseAvailability`);
|
||||||
|
if (!avail?.data) lack.push('availability (territories)');
|
||||||
|
const shot = await shotOf(p.id);
|
||||||
|
if (!shot) lack.push('the review screenshot');
|
||||||
|
else if (stateOf(shot) === 'FAILED') lack.push(`a working review screenshot (FAILED: ${errorsOf(shot) || 'unknown'})`);
|
||||||
|
else if (stateOf(shot) !== 'COMPLETE') lack.push(`Apple to finish processing the screenshot (${stateOf(shot)}; check again in a minute)`);
|
||||||
|
log('apple', `${p.attributes.productId}: MISSING_METADATA${lack.length ? `: needs ${lack.join(', ')}` : ' (all parts present: Apple may still be updating the state)'}`);
|
||||||
|
}
|
||||||
|
if (problems) process.exitCode = 1;
|
||||||
|
done('apple', dry ? 'iap-review dry run (nothing uploaded)' : 'iap-review done (READY_TO_SUBMIT = complete; first IAPs go to review with a version, from the IAP page)');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ import { dataSafetyRows } from './lib/data-safety';
|
||||||
import { reviewDemoAccount } from './lib/credentials';
|
import { reviewDemoAccount } from './lib/credentials';
|
||||||
import { log, printJson, warn } from './lib/log';
|
import { log, printJson, warn } from './lib/log';
|
||||||
import { profileIssues } from './lib/profile';
|
import { profileIssues } from './lib/profile';
|
||||||
|
import { reviewShotProblem } from './apple/iap-review';
|
||||||
import { allSubscriptions } from './lib/subscriptions';
|
import { allSubscriptions } from './lib/subscriptions';
|
||||||
import { type CopyFile, validateCopy } from './shots/lib';
|
import { type CopyFile, validateCopy } from './shots/lib';
|
||||||
|
|
||||||
|
|
@ -82,6 +83,13 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
if (config.apple && len(l.description) > APPLE_IAP_LIMITS.description) problems.push(`product ${p.id} ${lang}: description ${len(l.description)} > ${APPLE_IAP_LIMITS.description} (App Store limit)`);
|
if (config.apple && len(l.description) > APPLE_IAP_LIMITS.description) problems.push(`product ${p.id} ${lang}: description ${len(l.description)} > ${APPLE_IAP_LIMITS.description} (App Store limit)`);
|
||||||
if (len(l.description) > 200) problems.push(`product ${p.id} ${lang}: description ${len(l.description)} > 200 (Play limit)`);
|
if (len(l.description) > 200) problems.push(`product ${p.id} ${lang}: description ${len(l.description)} > 200 (Play limit)`);
|
||||||
}
|
}
|
||||||
|
// App Review screenshots of in-app purchases: Apple fails any non-screenshot size after upload (IMAGE_INCORRECT_DIMENSIONS)
|
||||||
|
if (config.apple) for (const f of new Set((config.products ?? []).map(p => p.reviewScreenshot).filter((x): x is string => !!x))) {
|
||||||
|
const file = resolve(f);
|
||||||
|
if (!existsSync(file)) continue; // reported with the other missing files below
|
||||||
|
const bad = reviewShotProblem(readFileSync(file));
|
||||||
|
if (bad) problems.push(`products[].reviewScreenshot ${f}: ${bad}`);
|
||||||
|
}
|
||||||
if (config.shots) tryDo('shots copy', () => {
|
if (config.shots) tryDo('shots copy', () => {
|
||||||
const copy = JSON.parse(readFileSync(resolve(config.shots!.copy), 'utf8')) as CopyFile;
|
const copy = JSON.parse(readFileSync(resolve(config.shots!.copy), 'utf8')) as CopyFile;
|
||||||
const e = validateCopy(copy, config.shots!, config.languages.map(l => l.id));
|
const e = validateCopy(copy, config.shots!, config.languages.map(l => l.id));
|
||||||
|
|
|
||||||
|
|
@ -113,8 +113,11 @@ export interface ShotsConfig {
|
||||||
out: string;
|
out: string;
|
||||||
/** Optional logo image for the hero scene and the feature graphic. */
|
/** Optional logo image for the hero scene and the feature graphic. */
|
||||||
logo?: string;
|
logo?: string;
|
||||||
/** Google Fonts families for titles / body text (downloaded and subset by `shots fonts`). */
|
/** Google Fonts families for titles / body text (downloaded and subset by `shots fonts`). Default: game Paytone One +
|
||||||
fonts?: { title?: string; body?: string };
|
* Montserrat, app Inter (all cover Latin Extended and Vietnamese). `fallback`: Noto families you accept for
|
||||||
|
* characters the title / body font lacks (e.g. ['Noto Sans Display']); without it a render that needs an automatic
|
||||||
|
* fallback is an ERROR in `shots check`. */
|
||||||
|
fonts?: { title?: string; body?: string; fallback?: string[] };
|
||||||
scenes: ShotScene[];
|
scenes: ShotScene[];
|
||||||
feature?: { frame: string; palette?: string | Palette };
|
feature?: { frame: string; palette?: string | Palette };
|
||||||
/** Phone screen size of the raw frames in CSS px (default 440 x 902 @3x, iPhone 6.9" minus the 54 px status bar).
|
/** Phone screen size of the raw frames in CSS px (default 440 x 902 @3x, iPhone 6.9" minus the 54 px status bar).
|
||||||
|
|
|
||||||
|
|
@ -28,7 +28,7 @@ document.documentElement.lang = LANG;
|
||||||
R.setProperty('--W', W + 'px'); R.setProperty('--H', H + 'px'); R.setProperty('--u', u + 'px');
|
R.setProperty('--W', W + 'px'); R.setProperty('--H', H + 'px'); R.setProperty('--u', u + 'px');
|
||||||
R.setProperty('--ink', job.ink); R.setProperty('--fs', W > H ? 6.4 : 8.2);
|
R.setProperty('--ink', job.ink); R.setProperty('--fs', W > H ? 6.4 : 8.2);
|
||||||
const X = job.fonts.script;
|
const X = job.fonts.script;
|
||||||
R.setProperty('--tf', X ? `'${X}', '${job.fonts.title}', sans-serif` : `'${job.fonts.title}', sans-serif`);
|
R.setProperty('--tf', (job.fonts.titleStack ?? (X ? [X, job.fonts.title] : [job.fonts.title])).map(f => `'${f}'`).join(', ') + ', sans-serif');
|
||||||
R.setProperty('--tw', X ? 900 : 400);
|
R.setProperty('--tw', X ? 900 : 400);
|
||||||
const el = document.createElement('div');
|
const el = document.createElement('div');
|
||||||
el.className = 'cap';
|
el.className = 'cap';
|
||||||
|
|
|
||||||
125
cli/shots/cmap.ts
Normal file
125
cli/shots/cmap.ts
Normal file
|
|
@ -0,0 +1,125 @@
|
||||||
|
// Character coverage of a font file, read from its cmap table in pure TypeScript (no font library):
|
||||||
|
// TrueType / OpenType (sfnt), TrueType collections (first font), WOFF 1 (zlib) and WOFF 2 (brotli, cmap is never
|
||||||
|
// transformed so it is read straight from the decompressed stream). node:zlib ships with Bun, so no dependency.
|
||||||
|
// cmap subtables: formats 0, 4, 6, 12 and 13 of the Unicode / Windows Unicode encodings.
|
||||||
|
import { brotliDecompressSync, inflateSync } from 'node:zlib';
|
||||||
|
|
||||||
|
const tag = (d: DataView, o: number): string => String.fromCharCode(d.getUint8(o), d.getUint8(o + 1), d.getUint8(o + 2), d.getUint8(o + 3));
|
||||||
|
const view = (b: Uint8Array): DataView => new DataView(b.buffer, b.byteOffset, b.byteLength);
|
||||||
|
|
||||||
|
/** The raw cmap table of a font file (any of the formats above). Throws on anything else. */
|
||||||
|
export function cmapTable(file: Uint8Array): Uint8Array {
|
||||||
|
const d = view(file);
|
||||||
|
const sig = tag(d, 0);
|
||||||
|
if (sig === 'wOF2') return woff2Cmap(file);
|
||||||
|
if (sig === 'wOFF') {
|
||||||
|
const n = d.getUint16(12);
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const o = 44 + i * 20;
|
||||||
|
if (tag(d, o) !== 'cmap') continue;
|
||||||
|
const off = d.getUint32(o + 4), comp = d.getUint32(o + 8), orig = d.getUint32(o + 12);
|
||||||
|
const raw = file.subarray(off, off + comp);
|
||||||
|
return comp < orig ? new Uint8Array(inflateSync(raw)) : raw;
|
||||||
|
}
|
||||||
|
throw new Error('woff: no cmap table');
|
||||||
|
}
|
||||||
|
let base = 0;
|
||||||
|
if (sig === 'ttcf') base = d.getUint32(12);
|
||||||
|
else if (!(d.getUint32(0) === 0x00010000 || sig === 'OTTO' || sig === 'true')) throw new Error(`not a font file (signature ${JSON.stringify(sig)})`);
|
||||||
|
const n = d.getUint16(base + 4);
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const o = base + 12 + i * 16;
|
||||||
|
if (tag(d, o) === 'cmap') { const off = d.getUint32(o + 8); return file.subarray(off, off + d.getUint32(o + 12)); }
|
||||||
|
}
|
||||||
|
throw new Error('sfnt: no cmap table');
|
||||||
|
}
|
||||||
|
|
||||||
|
const WOFF2_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG',
|
||||||
|
'EBDT', 'EBLC', 'gasp', 'hdmx', 'kern', 'LTSH', 'PCLT', 'VDMX', 'vhea', 'vmtx', 'BASE', 'GDEF', 'GPOS', 'GSUB', 'EBSC', 'JSTF', 'MATH',
|
||||||
|
'CBDT', 'CBLC', 'COLR', 'CPAL', 'SVG ', 'sbix', 'acnt', 'avar', 'bdat', 'bloc', 'bsln', 'cvar', 'fdsc', 'feat', 'fmtx', 'fvar', 'gvar',
|
||||||
|
'hsty', 'just', 'lcar', 'mort', 'morx', 'opbd', 'prop', 'trak', 'Zapf', 'Silf', 'Glat', 'Gloc', 'Feat', 'Sill'];
|
||||||
|
|
||||||
|
function woff2Cmap(file: Uint8Array): Uint8Array {
|
||||||
|
const d = view(file);
|
||||||
|
const n = d.getUint16(12), compLen = d.getUint32(20);
|
||||||
|
let p = 48;
|
||||||
|
const base128 = (): number => {
|
||||||
|
let v = 0;
|
||||||
|
for (let i = 0; i < 5; i++) { const b = d.getUint8(p++); v = v * 128 + (b & 0x7f); if (!(b & 0x80)) return v; }
|
||||||
|
throw new Error('woff2: bad UIntBase128');
|
||||||
|
};
|
||||||
|
let off = 0, found: [number, number] | null = null;
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const flags = d.getUint8(p++);
|
||||||
|
const t = (flags & 0x3f) === 63 ? (p += 4, tag(d, p - 4)) : WOFF2_TAGS[flags & 0x3f]!;
|
||||||
|
const orig = base128();
|
||||||
|
const version = (flags >> 6) & 3;
|
||||||
|
const transformed = t === 'glyf' || t === 'loca' ? version === 0 : version !== 0;
|
||||||
|
const len = transformed ? base128() : orig;
|
||||||
|
if (t === 'cmap') found = [off, orig];
|
||||||
|
off += len;
|
||||||
|
}
|
||||||
|
if (!found) throw new Error('woff2: no cmap table');
|
||||||
|
if (tag(d, 4) === 'ttcf') { // collection directory: skip it (version, numFonts 255UInt16, per font numTables + indices)
|
||||||
|
p += 4;
|
||||||
|
const u16 = (): number => { const c = d.getUint8(p++); return c === 253 ? (p += 2, d.getUint16(p - 2)) : c === 255 ? 253 + d.getUint8(p++) : c === 254 ? 506 + d.getUint8(p++) : c; };
|
||||||
|
const fonts = u16();
|
||||||
|
for (let f = 0; f < fonts; f++) { const k = u16(); p += 4; for (let j = 0; j < k; j++) u16(); }
|
||||||
|
}
|
||||||
|
const data = new Uint8Array(brotliDecompressSync(file.subarray(p, p + compLen)));
|
||||||
|
return data.subarray(found[0], found[0] + found[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every Unicode code point the cmap maps to a real glyph (glyph id > 0). */
|
||||||
|
export function cmapCodepoints(cmap: Uint8Array): Set<number> {
|
||||||
|
const d = view(cmap);
|
||||||
|
const n = d.getUint16(2);
|
||||||
|
const subs: { pid: number; eid: number; off: number }[] = [];
|
||||||
|
for (let i = 0; i < n; i++) subs.push({ pid: d.getUint16(4 + i * 8), eid: d.getUint16(6 + i * 8), off: d.getUint32(8 + i * 8) });
|
||||||
|
const rank = (s: { pid: number; eid: number }): number => (s.pid === 3 && s.eid === 10) || (s.pid === 0 && (s.eid === 4 || s.eid === 6)) ? 3
|
||||||
|
: (s.pid === 3 && s.eid === 1) || (s.pid === 0 && s.eid <= 3) ? 2 : s.pid === 3 && s.eid === 0 ? 1 : 0;
|
||||||
|
const out = new Set<number>();
|
||||||
|
for (const s of subs.filter(x => rank(x) > 0).sort((a, b) => rank(b) - rank(a))) readSub(d, s.off, out);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readSub(d: DataView, o: number, out: Set<number>): void {
|
||||||
|
const fmt = d.getUint16(o);
|
||||||
|
if (fmt === 0) { for (let c = 0; c < 256; c++) if (d.getUint8(o + 6 + c)) out.add(c); return; }
|
||||||
|
if (fmt === 6) { const first = d.getUint16(o + 6), cnt = d.getUint16(o + 8); for (let i = 0; i < cnt; i++) if (d.getUint16(o + 10 + i * 2)) out.add(first + i); return; }
|
||||||
|
if (fmt === 4) {
|
||||||
|
const segs = d.getUint16(o + 6) / 2;
|
||||||
|
const ends = o + 14, starts = ends + segs * 2 + 2, deltas = starts + segs * 2, ranges = deltas + segs * 2;
|
||||||
|
for (let i = 0; i < segs; i++) {
|
||||||
|
const end = d.getUint16(ends + i * 2), start = d.getUint16(starts + i * 2), delta = d.getInt16(deltas + i * 2), ro = d.getUint16(ranges + i * 2);
|
||||||
|
for (let c = start; c <= end && c !== 0xffff; c++) {
|
||||||
|
let g: number;
|
||||||
|
if (!ro) g = (c + delta) & 0xffff;
|
||||||
|
else { g = d.getUint16(ranges + i * 2 + ro + (c - start) * 2); if (g) g = (g + delta) & 0xffff; }
|
||||||
|
if (g) out.add(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (fmt === 12 || fmt === 13) {
|
||||||
|
const groups = d.getUint32(o + 12);
|
||||||
|
for (let i = 0; i < groups; i++) {
|
||||||
|
const g = o + 16 + i * 12, start = d.getUint32(g), end = d.getUint32(g + 4), gid = d.getUint32(g + 8);
|
||||||
|
for (let c = start; c <= end && c <= 0x10ffff; c++) if (fmt === 13 ? gid : gid + (c - start)) out.add(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Code points a font file covers. */
|
||||||
|
export const fontCodepoints = (file: Uint8Array): Set<number> => cmapCodepoints(cmapTable(file));
|
||||||
|
|
||||||
|
/** Characters that need a glyph: everything except whitespace, controls, joiners and variation selectors (those
|
||||||
|
* render without one or are handled by shaping). */
|
||||||
|
export const needsGlyph = (ch: string): boolean => !/^[\s\p{Cc}\p{Cf}\u{FE00}-\u{FE0F}\u{E0100}-\u{E01EF}]$/u.test(ch);
|
||||||
|
|
||||||
|
/** Characters of `text` (unique, in first-seen order) a font with `cps` does not cover. */
|
||||||
|
export function missingChars(text: string, cps: Set<number>): string[] {
|
||||||
|
const out = new Set<string>();
|
||||||
|
for (const ch of text) if (needsGlyph(ch) && !cps.has(ch.codePointAt(0)!)) out.add(ch);
|
||||||
|
return [...out];
|
||||||
|
}
|
||||||
|
|
@ -36,7 +36,7 @@ const P = job.palette, R = document.documentElement.style, dev = job.phone;
|
||||||
const rgba = (hex, a) => { const m = /^#?([0-9a-f]{6})$/i.exec(hex); if (!m) return hex; const n = parseInt(m[1], 16); return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})`; };
|
const rgba = (hex, a) => { const m = /^#?([0-9a-f]{6})$/i.exec(hex); if (!m) return hex; const n = parseInt(m[1], 16); return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})`; };
|
||||||
R.setProperty('--bg', `linear-gradient(135deg, ${P.bg[0]} 0%, ${P.bg[1]} 55%, ${P.bg[2]} 100%)`);
|
R.setProperty('--bg', `linear-gradient(135deg, ${P.bg[0]} 0%, ${P.bg[1]} 55%, ${P.bg[2]} 100%)`);
|
||||||
R.setProperty('--ink', P.ink); R.setProperty('--shadow', P.shadow); R.setProperty('--accentSoft', rgba(P.glow, .18));
|
R.setProperty('--ink', P.ink); R.setProperty('--shadow', P.shadow); R.setProperty('--accentSoft', rgba(P.glow, .18));
|
||||||
R.setProperty('--tf', `'${job.fonts.title}', sans-serif`);
|
R.setProperty('--tf', (job.fonts.titleStack ?? [job.fonts.title]).map(f => `'${f}'`).join(', ') + ', sans-serif');
|
||||||
R.setProperty('--ar', `${dev.w} / ${dev.h + dev.bar}`);
|
R.setProperty('--ar', `${dev.w} / ${dev.h + dev.bar}`);
|
||||||
R.setProperty('--appH', `${100 * dev.h / (dev.h + dev.bar)}%`);
|
R.setProperty('--appH', `${100 * dev.h / (dev.h + dev.bar)}%`);
|
||||||
R.setProperty('--barH', `${100 * dev.bar / (dev.h + dev.bar)}%`);
|
R.setProperty('--barH', `${100 * dev.bar / (dev.h + dev.bar)}%`);
|
||||||
|
|
|
||||||
|
|
@ -44,7 +44,7 @@ const job = await (await fetch(`/job.json?lang=${encodeURIComponent(lang)}&featu
|
||||||
const P = job.palette, R = document.documentElement.style, dev = job.phone;
|
const P = job.palette, R = document.documentElement.style, dev = job.phone;
|
||||||
R.setProperty('--bg', `linear-gradient(160deg, ${P.bg[0]} 0%, ${P.bg[1]} 50%, ${P.bg[2]} 100%)`);
|
R.setProperty('--bg', `linear-gradient(160deg, ${P.bg[0]} 0%, ${P.bg[1]} 50%, ${P.bg[2]} 100%)`);
|
||||||
R.setProperty('--glow', P.glow); R.setProperty('--ink', P.ink); R.setProperty('--shadow', P.shadow);
|
R.setProperty('--glow', P.glow); R.setProperty('--ink', P.ink); R.setProperty('--shadow', P.shadow);
|
||||||
R.setProperty('--tf', `'${job.fonts.title}', sans-serif`);
|
R.setProperty('--tf', (job.fonts.titleStack ?? [job.fonts.title]).map(f => `'${f}'`).join(', ') + ', sans-serif');
|
||||||
R.setProperty('--ar', `${dev.w} / ${dev.h + dev.bar}`);
|
R.setProperty('--ar', `${dev.w} / ${dev.h + dev.bar}`);
|
||||||
R.setProperty('--appH', `${100 * dev.h / (dev.h + dev.bar)}%`);
|
R.setProperty('--appH', `${100 * dev.h / (dev.h + dev.bar)}%`);
|
||||||
R.setProperty('--barH', `${100 * dev.bar / (dev.h + dev.bar)}%`);
|
R.setProperty('--barH', `${100 * dev.bar / (dev.h + dev.bar)}%`);
|
||||||
|
|
|
||||||
|
|
@ -1,62 +1,89 @@
|
||||||
// Downloads the fonts the screenshot template needs, subset by Google Fonts (css2 `text=`) to exactly the characters
|
// Downloads the fonts the screenshot template needs, subset by Google Fonts (css2 `text=`) to exactly the characters
|
||||||
// your copy uses, so even CJK stays small: title + body family for Latin text, plus one Noto family per non-Latin
|
// your copy uses, so even CJK stays small. `text=` pulls the glyphs from every subset the family has (latin, latin-ext,
|
||||||
// script found in the copy (CJK, Arabic, Hebrew, Devanagari, Thai, Cyrillic / Greek).
|
// vietnamese, cyrillic, greek ...), so a missing glyph means the family itself lacks it.
|
||||||
// storebound shots fonts (re-run after editing the copy)
|
// Then the glyph coverage check: every character of every language's copy (copy.json languages + config languages)
|
||||||
// Out: <project>/.storebound/fonts/*.woff2 + fonts.css. All of these fonts are SIL Open Font License 1.1.
|
// is looked up in the cmap of the faces that draw it (title font: titles, badge values, app name; body font: eyebrows,
|
||||||
|
// sublines, badge labels; plus the Noto face of a non-Latin script). A character the stack lacks gets an automatic
|
||||||
|
// Noto fallback (logged; `shots check` errors on renders that used it unless shots.fonts.fallback lists it); a
|
||||||
|
// character no fallback covers fails with the language and the characters.
|
||||||
|
// storebound shots fonts [--json] (re-run after editing the copy or the fonts)
|
||||||
|
// Out: <project>/.storebound/fonts/*.woff2 + fonts.css + fonts.json (faces and the per-language stacks, read by render).
|
||||||
|
// All of these fonts are SIL Open Font License 1.1.
|
||||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import type { Ctx } from '../lib/ctx';
|
import type { Ctx } from '../lib/ctx';
|
||||||
import { need } from '../lib/ctx';
|
import { need } from '../lib/ctx';
|
||||||
import { done, log } from '../lib/log';
|
import { done, log, printJson, warn } from '../lib/log';
|
||||||
import { shotsStyle } from '../lib/config';
|
import { shotsStyle } from '../lib/config';
|
||||||
import { type CopyFile, copyText, scriptFont, shotFonts } from './lib';
|
import { type CopyFile, shotFonts } from './lib';
|
||||||
|
import { fontCodepoints } from './cmap';
|
||||||
|
import { type FaceJob, type FontManifest, fontsCss, planFonts, roleTexts, type RoleTexts } from './glyphs';
|
||||||
|
|
||||||
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36';
|
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36';
|
||||||
const ASCII = Array.from({ length: 95 }, (_, i) => String.fromCharCode(32 + i)).join('') + '·';
|
const ASCII = Array.from({ length: 95 }, (_, i) => String.fromCharCode(32 + i)).join('') + '·';
|
||||||
|
|
||||||
async function fetchSubset(family: string, chars: string, variable: boolean): Promise<ArrayBuffer> {
|
export async function fetchSubset(family: string, chars: string, axis: string | null): Promise<ArrayBuffer> {
|
||||||
const fam = encodeURIComponent(family) + (variable ? ':wght@100..900' : '');
|
const fam = encodeURIComponent(family) + (axis ? ':' + axis : '');
|
||||||
let res = await fetch(`https://fonts.googleapis.com/css2?family=${fam}&text=${encodeURIComponent(chars)}&display=block`, { headers: { 'user-agent': UA } });
|
let res = await fetch(`https://fonts.googleapis.com/css2?family=${fam}&text=${encodeURIComponent(chars)}&display=block`, { headers: { 'user-agent': UA } });
|
||||||
if (!res.ok && variable) return fetchSubset(family, chars, false);
|
if (!res.ok && axis) return fetchSubset(family, chars, null);
|
||||||
if (!res.ok) throw new Error(`${family}: ${res.status} ${await res.text()}`);
|
if (!res.ok) throw new Error(`${family}: ${res.status} ${(await res.text()).slice(0, 200)}`);
|
||||||
const src = /url\((https:[^)]+)\)/.exec(await res.text())?.[1];
|
const src = /url\((https:[^)]+)\)/.exec(await res.text())?.[1];
|
||||||
if (!src) throw new Error(`${family}: no font url`);
|
if (!src) throw new Error(`${family}: no font url`);
|
||||||
res = await fetch(src, { headers: { 'user-agent': UA } });
|
res = await fetch(src, { headers: { 'user-agent': UA } });
|
||||||
|
if (!res.ok) throw new Error(`${family}: ${res.status} for ${src}`);
|
||||||
return res.arrayBuffer();
|
return res.arrayBuffer();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Per-language role texts for every language of the copy and the config. */
|
||||||
|
export function langTexts(copy: CopyFile, langs: string[], appName: string): Record<string, RoleTexts> {
|
||||||
|
const out: Record<string, RoleTexts> = {};
|
||||||
|
for (const lang of [...new Set([...Object.keys(copy), ...langs])]) out[lang] = roleTexts(lang, copy[lang], appName);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const fontsDirOf = (root: string): string => join(root, '.storebound', 'fonts');
|
||||||
|
|
||||||
|
export function readManifest(dir: string): FontManifest | null {
|
||||||
|
try { return JSON.parse(readFileSync(join(dir, 'fonts.json'), 'utf8')) as FontManifest; } catch { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
export async function run(ctx: Ctx): Promise<void> {
|
export async function run(ctx: Ctx): Promise<void> {
|
||||||
const { config, root, resolve } = ctx.loaded;
|
const { config, root, resolve } = ctx.loaded;
|
||||||
const shots = need(config.shots, 'shots');
|
const shots = need(config.shots, 'shots');
|
||||||
const copy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile;
|
const copy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile;
|
||||||
const dir = join(root, '.storebound', 'fonts');
|
const dir = fontsDirOf(root);
|
||||||
mkdirSync(dir, { recursive: true });
|
mkdirSync(dir, { recursive: true });
|
||||||
const { title, body, titleVariable } = shotFonts(shots, shotsStyle(config));
|
const style = shotsStyle(config);
|
||||||
|
const { title, body, titleVariable } = shotFonts(shots, style);
|
||||||
|
const texts = langTexts(copy, config.languages.map(l => l.id), config.app.name);
|
||||||
|
|
||||||
const latin = new Set(ASCII);
|
const sizes: string[] = [];
|
||||||
const scripts = new Map<string, { family: string; chars: Set<string> }>();
|
const manifest = await planFonts({
|
||||||
for (const [lang, c] of Object.entries(copy)) {
|
langs: texts, title, body, titleAxis: titleVariable ? 'wght@100..900' : null, bodyAxis: 'wght@100..900',
|
||||||
const text = copyText(lang, c);
|
fallbackTitleAxis: style === 'app' ? 'wght@100..900' : 'wght@800', chosen: shots.fonts?.fallback, base: ASCII,
|
||||||
const s = scriptFont(lang, text);
|
}, async (job: FaceJob) => {
|
||||||
if (!s) { for (const ch of text) latin.add(ch); continue; }
|
let bin: Uint8Array;
|
||||||
const cur = scripts.get(s.slug) ?? { family: s.family, chars: new Set(ASCII) };
|
try { bin = new Uint8Array(await fetchSubset(job.family, job.chars, job.axis)); } catch (e) {
|
||||||
for (const ch of text) cur.chars.add(ch);
|
if (job.kind !== 'fallback') throw e;
|
||||||
scripts.set(s.slug, cur);
|
log('shots', `${job.family} has none of ${[...job.chars].join(' ')} (${(e as Error).message.split(' for ')[0]}), trying the next fallback`);
|
||||||
|
return new Set<number>();
|
||||||
}
|
}
|
||||||
for (const ch of config.app.name) latin.add(ch);
|
writeFileSync(join(dir, job.file), bin);
|
||||||
const latinChars = [...latin].sort().join('');
|
const cps = fontCodepoints(bin);
|
||||||
|
sizes.push(`${job.file.padEnd(28)} ${job.family.padEnd(22)} ${(bin.byteLength / 1024).toFixed(1)} KB, ${[...job.chars].length} chars asked, ${cps.size} in the cmap`);
|
||||||
let css = '/* Generated by storebound shots fonts (Google Fonts, SIL Open Font License 1.1), subset to the copy. */\n';
|
return cps;
|
||||||
const jobs: [string, string, string, boolean][] = [[title, 'title', latinChars, titleVariable], [body, 'body', latinChars, true],
|
});
|
||||||
...[...scripts.entries()].map(([slug, s]) => [s.family, slug, [...s.chars].sort().join(''), true] as [string, string, string, boolean])];
|
writeFileSync(join(dir, 'fonts.css'), fontsCss(manifest));
|
||||||
for (const [family, slug, chars, variable] of jobs) {
|
writeFileSync(join(dir, 'fonts.json'), JSON.stringify(manifest, null, 1) + '\n');
|
||||||
const bin = await fetchSubset(family, chars, variable);
|
if (ctx.args.has('json')) return printJson(manifest);
|
||||||
const file = `${slug}.woff2`;
|
for (const s of sizes) log('shots', s);
|
||||||
writeFileSync(join(dir, file), Buffer.from(bin));
|
let auto = 0;
|
||||||
const face = slug === 'title' ? title : slug === 'body' ? body : `Store ${slug}`;
|
for (const [lang, l] of Object.entries(manifest.langs)) for (const f of l.fallbacks) {
|
||||||
css += `@font-face { font-family: '${face}'; font-weight: 100 900; src: url(${file}) format('woff2'); }\n`;
|
const ok = manifest.faces[f.face]?.chosen;
|
||||||
log('shots', `${file.padEnd(18)} ${family.padEnd(22)} ${(bin.byteLength / 1024).toFixed(1)} KB, ${[...chars].length} chars`);
|
if (!ok) auto++;
|
||||||
|
const base = f.role === 'title' ? title : body;
|
||||||
|
(ok ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} not in ${base} -> ${f.family}${ok ? ' (shots.fonts.fallback)' : ' (automatic fallback)'}`);
|
||||||
}
|
}
|
||||||
writeFileSync(join(dir, 'fonts.css'), css);
|
if (auto) warn('shots', `${auto} automatic fallbacks: renders that use them fail \`shots check\`. Pick title / body fonts that cover them${style === 'game' ? ' (titles: e.g. Paytone One, Baloo 2, Rowdies)' : ''} or accept the fallback with shots.fonts.fallback: ['<family>']`);
|
||||||
done('shots', 'fonts done');
|
done('shots', 'fonts done');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
317
cli/shots/glyphs.ts
Normal file
317
cli/shots/glyphs.ts
Normal file
|
|
@ -0,0 +1,317 @@
|
||||||
|
// Glyph coverage of the screenshot fonts, per language and role (title / body), and the automatic Noto fallbacks.
|
||||||
|
// `shots fonts` plans the faces with planFonts() (downloads through an injected getter, so tests run offline) and
|
||||||
|
// writes .storebound/fonts/fonts.json; `shots render` re-checks coverage against the local files before rendering
|
||||||
|
// (uncoveredChars) and measures, in the page, which face drew every character (measureFonts). `shots check` turns a
|
||||||
|
// glyph drawn by a fallback the config did not choose, or by a system font, into an ERROR.
|
||||||
|
//
|
||||||
|
// Default stack per script (the template defaults, documented in the README and the store-screenshots skill):
|
||||||
|
// Latin incl. Latin Extended-A / B and Vietnamese, Cyrillic, Greek: the configured title / body font
|
||||||
|
// (defaults: game Paytone One + Montserrat, app Inter + Inter; all four cover Latin Extended and Vietnamese;
|
||||||
|
// Inter and Montserrat cover Cyrillic too). A Cyrillic or Greek line switches to Noto Sans as a whole.
|
||||||
|
// Arabic / Hebrew / Devanagari / Bengali / Thai: Noto Sans Arabic / Hebrew / Devanagari / Bengali / Thai (whole line).
|
||||||
|
// Japanese / Korean / Chinese: Noto Sans JP / KR / SC (TC for zh-Hant, TW, HK) (whole line).
|
||||||
|
// Any character the stack lacks: Noto Sans Display (titles) or Noto Sans (body text) for Latin / Cyrillic / Greek,
|
||||||
|
// Noto Sans <Script> for other scripts, then Noto Sans Symbols 2, Noto Sans Symbols, Noto Sans Math and Noto Color
|
||||||
|
// Emoji, added per character (logged, and an ERROR in `shots check` unless listed in shots.fonts.fallback).
|
||||||
|
import type { SceneCopy } from './lib';
|
||||||
|
import { scriptFont } from './lib';
|
||||||
|
import { needsGlyph } from './cmap';
|
||||||
|
|
||||||
|
export type Role = 'title' | 'body';
|
||||||
|
export interface RoleTexts { title: string; body: string }
|
||||||
|
|
||||||
|
/** The text each font role draws for one language: titles, badge values and the app name (feature graphic) use the
|
||||||
|
* title font; eyebrows (also upper-cased, as the template shows them), sublines, badge labels and scene numbers the
|
||||||
|
* body font. */
|
||||||
|
export function roleTexts(lang: string, c: Record<string, SceneCopy> | undefined, appName = ''): RoleTexts {
|
||||||
|
const title: string[] = [appName], body: string[] = ['0123456789'];
|
||||||
|
for (const s of Object.values(c ?? {})) {
|
||||||
|
title.push(...(s.title ?? []).filter(Boolean));
|
||||||
|
body.push(s.eyebrow ?? '', (s.eyebrow ?? '').toLocaleUpperCase(lang), s.sub ?? '');
|
||||||
|
for (const [big, small] of s.badges ?? []) { title.push(big ?? ''); body.push(small ?? ''); }
|
||||||
|
}
|
||||||
|
return { title: title.join('').normalize('NFC'), body: body.join('').normalize('NFC') };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unique characters of a text that need a glyph, in first-seen order. */
|
||||||
|
export const glyphChars = (text: string): string[] => [...new Set([...text.normalize('NFC')].filter(needsGlyph))];
|
||||||
|
|
||||||
|
/** Characters of `text` that none of the faces covers. */
|
||||||
|
export function uncoveredChars(text: string, faces: Set<number>[]): string[] {
|
||||||
|
return glyphChars(text).filter(ch => { const cp = ch.codePointAt(0)!; return !faces.some(f => f.has(cp)); });
|
||||||
|
}
|
||||||
|
|
||||||
|
const NOTO_SCRIPTS = ['Arabic', 'Hebrew', 'Devanagari', 'Bengali', 'Thai', 'Armenian', 'Georgian', 'Ethiopic', 'Tamil', 'Telugu',
|
||||||
|
'Kannada', 'Malayalam', 'Gujarati', 'Gurmukhi', 'Oriya', 'Khmer', 'Lao', 'Myanmar', 'Sinhala', 'Thaana', 'Syriac'];
|
||||||
|
const SYMBOLS = ['Noto Sans Symbols 2', 'Noto Sans Symbols', 'Noto Sans Math', 'Noto Color Emoji'];
|
||||||
|
|
||||||
|
/** Noto families to try, in order, for a character the configured stack lacks. */
|
||||||
|
export function fallbackFamilies(ch: string, lang: string, role: Role): string[] {
|
||||||
|
const latin = role === 'title' ? ['Noto Sans Display', 'Noto Sans'] : ['Noto Sans'];
|
||||||
|
if (/\p{Extended_Pictographic}/u.test(ch) && !/[©®™]/u.test(ch)) return SYMBOLS;
|
||||||
|
if (/[\p{Script=Latin}\p{Script=Cyrillic}\p{Script=Greek}]/u.test(ch)) return latin;
|
||||||
|
if (/\p{Script=Hangul}/u.test(ch)) return ['Noto Sans KR'];
|
||||||
|
if (/[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(ch)) return ['Noto Sans JP'];
|
||||||
|
if (/\p{Script=Han}/u.test(ch)) return /Hant|TW|HK/.test(lang) ? ['Noto Sans TC', 'Noto Sans JP'] : ['Noto Sans SC', 'Noto Sans JP'];
|
||||||
|
for (const s of NOTO_SCRIPTS) if (new RegExp(`\\p{Script=${s}}`, 'u').test(ch)) return [`Noto Sans ${s}`];
|
||||||
|
return [...latin, ...SYMBOLS];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Global order the fallback families are tried in (every per-character list above is a subsequence of it). */
|
||||||
|
export const FALLBACK_ORDER = ['Noto Sans Display', 'Noto Sans', 'Noto Sans KR', 'Noto Sans JP', 'Noto Sans SC', 'Noto Sans TC',
|
||||||
|
...NOTO_SCRIPTS.map(s => `Noto Sans ${s}`), ...SYMBOLS];
|
||||||
|
|
||||||
|
const slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||||
|
|
||||||
|
export type FaceKind = 'title' | 'body' | 'script' | 'fallback';
|
||||||
|
/** One downloaded face: `face` is the @font-face family name the templates use. axis: css2 axis spec ("wght@800",
|
||||||
|
* "wght@100..900") or null for the font's default instance. */
|
||||||
|
export interface FaceJob { face: string; family: string; file: string; kind: FaceKind; role?: Role; axis: string | null; chars: string }
|
||||||
|
export interface LangFonts { title: string[]; body: string[]; fallbacks: { role: Role; face: string; family: string; chars: string }[] }
|
||||||
|
export interface FontManifest {
|
||||||
|
v: 1;
|
||||||
|
faces: Record<string, { family: string; file: string; kind: FaceKind; role?: Role; chosen: boolean }>;
|
||||||
|
langs: Record<string, LangFonts>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PlanInput {
|
||||||
|
langs: Record<string, RoleTexts>;
|
||||||
|
title: string; body: string;
|
||||||
|
/** css2 axis for the title / body family (null = default instance). */
|
||||||
|
titleAxis: string | null; bodyAxis: string | null;
|
||||||
|
/** Weight axis for automatic title fallbacks (game titles are heavy display faces: "wght@800"). */
|
||||||
|
fallbackTitleAxis: string | null;
|
||||||
|
/** shots.fonts.fallback: families the owner accepts as fallbacks. */
|
||||||
|
chosen?: string[];
|
||||||
|
/** Extra characters for the title / body downloads (ASCII, so later copy edits rarely need a new download). */
|
||||||
|
base?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** No font covers these characters: listed per language and role. */
|
||||||
|
export class GlyphError extends Error {
|
||||||
|
constructor(public readonly gaps: { lang: string; role: Role; chars: string[]; tried: string[] }[]) {
|
||||||
|
super('no font covers these characters (pick fonts that do, or change the copy):\n' + gaps.map(g =>
|
||||||
|
` ${g.lang} (${g.role}): ${g.chars.map(c => `"${c}" U+${c.codePointAt(0)!.toString(16).toUpperCase().padStart(4, '0')}`).join(', ')}; tried ${g.tried.join(', ')}`).join('\n'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Faces for every language's copy: title + body, one Noto face per non-Latin script (whole lines, as before), and an
|
||||||
|
* automatic Noto fallback for each character the stack still lacks. `get` downloads a face (only the listed chars)
|
||||||
|
* and returns the code points its cmap covers. Throws GlyphError when no fallback covers a character. */
|
||||||
|
export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise<Set<number>>): Promise<FontManifest> {
|
||||||
|
const chosen = new Set((input.chosen ?? []).map(s => s.toLowerCase()));
|
||||||
|
const base = input.base ?? '';
|
||||||
|
const scripts = new Map<string, { family: string; chars: Set<string> }>();
|
||||||
|
const langScript = new Map<string, string | null>();
|
||||||
|
const roleChars: Record<Role, Set<string>> = { title: new Set(base), body: new Set(base) };
|
||||||
|
for (const [lang, t] of Object.entries(input.langs)) {
|
||||||
|
const s = scriptFont(lang, t.title + t.body);
|
||||||
|
langScript.set(lang, s ? `Store ${s.slug}` : null);
|
||||||
|
if (s) {
|
||||||
|
const cur = scripts.get(s.slug) ?? { family: s.family, chars: new Set(base) };
|
||||||
|
for (const ch of t.title + t.body) cur.chars.add(ch);
|
||||||
|
scripts.set(s.slug, cur);
|
||||||
|
}
|
||||||
|
// the title / body faces get every Latin / common character (and every character of Latin-only copy)
|
||||||
|
for (const r of ['title', 'body'] as const) for (const ch of t[r]) if (!s || !/[^\p{Script=Latin}\p{Script=Common}\p{Script=Inherited}]/u.test(ch)) roleChars[r].add(ch);
|
||||||
|
}
|
||||||
|
const sorted = (s: Iterable<string>): string => [...new Set(s)].sort().join('');
|
||||||
|
const faces: FontManifest['faces'] = {};
|
||||||
|
const cps = new Map<string, Set<number>>();
|
||||||
|
const add = async (job: FaceJob, isChosen: boolean): Promise<void> => {
|
||||||
|
cps.set(job.face, await get(job));
|
||||||
|
if (job.kind === 'fallback' && ![...job.chars].some(ch => cps.get(job.face)!.has(ch.codePointAt(0)!))) return; // covers none: not a face
|
||||||
|
faces[job.face] = { family: job.family, file: job.file, kind: job.kind, ...(job.role ? { role: job.role } : {}), chosen: isChosen };
|
||||||
|
};
|
||||||
|
await add({ face: input.title, family: input.title, file: 'title.woff2', kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted(roleChars.title) }, true);
|
||||||
|
if (input.body !== input.title) await add({ face: input.body, family: input.body, file: 'body.woff2', kind: 'body', role: 'body', axis: input.bodyAxis, chars: sorted(roleChars.body) }, true);
|
||||||
|
else { // same family: one download (title axis) with both roles' characters
|
||||||
|
const t = faces[input.title]!;
|
||||||
|
cps.set(input.title, await get({ face: input.title, family: input.title, file: t.file, kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted([...roleChars.title, ...roleChars.body]) }));
|
||||||
|
}
|
||||||
|
for (const [s, v] of scripts) await add({ face: `Store ${s}`, family: v.family, file: `${s}.woff2`, kind: 'script', axis: 'wght@100..900', chars: sorted(v.chars) }, true);
|
||||||
|
|
||||||
|
// per language and role: the stack, and what it lacks
|
||||||
|
const langs: FontManifest['langs'] = {};
|
||||||
|
const pending: { lang: string; role: Role; ch: string; tries: string[] }[] = [];
|
||||||
|
for (const [lang, t] of Object.entries(input.langs)) {
|
||||||
|
const x = langScript.get(lang);
|
||||||
|
langs[lang] = { title: [...(x ? [x] : []), input.title], body: [...(x ? [x] : []), input.body], fallbacks: [] };
|
||||||
|
for (const role of ['title', 'body'] as const) {
|
||||||
|
const stack = langs[lang]![role].map(f => cps.get(f)!);
|
||||||
|
for (const ch of uncoveredChars(t[role], stack)) pending.push({ lang, role, ch, tries: fallbackFamilies(ch, lang, role) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const gaps = new Map<string, { lang: string; role: Role; chars: string[]; tried: string[] }>();
|
||||||
|
const hits = new Map<string, Map<string, Set<string>>>(); // lang|role -> face -> chars
|
||||||
|
for (const role of ['title', 'body'] as const) for (const family of FALLBACK_ORDER) {
|
||||||
|
const want = pending.filter(p => p.role === role && p.tries.includes(family));
|
||||||
|
if (!want.length) continue;
|
||||||
|
const face = `Store fb ${slug(family)} ${role}`;
|
||||||
|
const axis = family === 'Noto Color Emoji' ? null : role === 'title' ? input.fallbackTitleAxis : 'wght@100..900';
|
||||||
|
await add({ face, family, file: `fb-${slug(family)}-${role}.woff2`, kind: 'fallback', role, axis, chars: sorted(want.map(p => p.ch)) }, chosen.has(family.toLowerCase()));
|
||||||
|
const got = cps.get(face)!;
|
||||||
|
for (const p of want) {
|
||||||
|
p.tries = p.tries.filter(f => f !== family);
|
||||||
|
if (!got.has(p.ch.codePointAt(0)!)) continue;
|
||||||
|
const k = `${p.lang}|${role}`;
|
||||||
|
const m = hits.get(k) ?? new Map<string, Set<string>>();
|
||||||
|
m.set(face, (m.get(face) ?? new Set()).add(p.ch));
|
||||||
|
hits.set(k, m);
|
||||||
|
p.tries = [];
|
||||||
|
(p as { done?: boolean }).done = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const p of pending) {
|
||||||
|
if ((p as { done?: boolean }).done) continue;
|
||||||
|
const k = `${p.lang}|${p.role}`;
|
||||||
|
const g = gaps.get(k) ?? { lang: p.lang, role: p.role, chars: [], tried: [...langs[p.lang]![p.role].map(f => faces[f]?.family ?? f), ...fallbackFamilies(p.ch, p.lang, p.role)] };
|
||||||
|
g.chars.push(p.ch);
|
||||||
|
gaps.set(k, g);
|
||||||
|
}
|
||||||
|
if (gaps.size) throw new GlyphError([...gaps.values()]);
|
||||||
|
for (const [k, m] of hits) {
|
||||||
|
const [lang, role] = k.split('|') as [string, Role];
|
||||||
|
for (const face of [...m.keys()].sort((a, b) => FALLBACK_ORDER.indexOf(faces[a]!.family) - FALLBACK_ORDER.indexOf(faces[b]!.family))) {
|
||||||
|
langs[lang]![role].push(face);
|
||||||
|
langs[lang]!.fallbacks.push({ role, face, family: faces[face]!.family, chars: [...m.get(face)!].join('') });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { v: 1, faces, langs };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** fonts.css for a manifest (every face covers all weights: static faces are never synthesised bolder). */
|
||||||
|
export function fontsCss(m: FontManifest): string {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
let css = '/* Generated by storebound shots fonts (Google Fonts, SIL Open Font License 1.1), subset to the copy. */\n';
|
||||||
|
for (const [face, f] of Object.entries(m.faces)) {
|
||||||
|
if (seen.has(face)) continue;
|
||||||
|
seen.add(face);
|
||||||
|
css += `@font-face { font-family: '${face}'; font-weight: 100 900; font-synthesis: none; src: url(${f.file}) format('woff2'); }\n`;
|
||||||
|
}
|
||||||
|
return css;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- render time ------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Per text element of a rendered page: which face drew which characters ("(system)" = none of ours). */
|
||||||
|
export interface MeasuredText { el: string; text: string; faces: Record<string, string> }
|
||||||
|
|
||||||
|
/** Runs in the page (`(${COLLECT_TEXT})(faceNames)`): every element with its own text whose font stack starts with one
|
||||||
|
* of our faces, with the characters it shows (after text-transform) and its stack of our faces; plus one hidden probe
|
||||||
|
* span per (face, weight, style, character) in #sb-glyph-probes, whose fonts `measureFonts` reads over CDP. Marks and
|
||||||
|
* whitespace are skipped (checked offline against the cmaps). */
|
||||||
|
export const COLLECT_TEXT = `(ours) => {
|
||||||
|
const OURS = new Set(ours);
|
||||||
|
const label = el => {
|
||||||
|
const me = el.tagName.toLowerCase() + (el.classList.length ? '.' + [...el.classList].join('.') : '');
|
||||||
|
if (!/^(span|b|small|i|em|strong)$/.test(el.tagName.toLowerCase()) || !el.parentElement) return me;
|
||||||
|
const p = el.parentElement, sib = [...p.children].filter(c => c.tagName === el.tagName);
|
||||||
|
return label(p) + ' ' + me + (sib.length > 1 ? ':' + (sib.indexOf(el) + 1) : '');
|
||||||
|
};
|
||||||
|
const lang = document.documentElement.lang || undefined;
|
||||||
|
const els = [], probes = [], seen = new Map();
|
||||||
|
for (const el of document.body.querySelectorAll('*')) {
|
||||||
|
if (/^(SCRIPT|STYLE|SVG)$/i.test(el.tagName) || el.closest('#sb-glyph-probes')) continue;
|
||||||
|
let text = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.data).join('').normalize('NFC');
|
||||||
|
if (!text.trim()) continue;
|
||||||
|
const cs = getComputedStyle(el);
|
||||||
|
if (cs.display === 'none' || cs.visibility === 'hidden') continue;
|
||||||
|
const fams = cs.fontFamily.split(',').map(s => s.trim().replace(/^["']|["']$/g, ''));
|
||||||
|
if (!OURS.has(fams[0])) continue;
|
||||||
|
const stack = [];
|
||||||
|
for (const f of fams) { if (!OURS.has(f)) break; stack.push(f); }
|
||||||
|
if (cs.textTransform === 'uppercase') text = text.toLocaleUpperCase(lang);
|
||||||
|
else if (cs.textTransform === 'lowercase') text = text.toLocaleLowerCase(lang);
|
||||||
|
const chars = [...new Set([...text])].filter(ch => !/^[\\s\\p{Cc}\\p{Cf}\\p{M}\\u{FE00}-\\u{FE0F}]$/u.test(ch));
|
||||||
|
const probe = {};
|
||||||
|
for (const ch of chars) for (const face of stack) {
|
||||||
|
const k = [face, cs.fontWeight, cs.fontStyle, ch].join('|');
|
||||||
|
if (!seen.has(k)) { seen.set(k, probes.length); probes.push({ face, weight: cs.fontWeight, style: cs.fontStyle, ch }); }
|
||||||
|
probe[face + '|' + ch] = seen.get(k);
|
||||||
|
}
|
||||||
|
els.push({ el: label(el), text: text.trim().slice(0, 60), stack, chars, probe });
|
||||||
|
}
|
||||||
|
const box = document.createElement('div');
|
||||||
|
box.id = 'sb-glyph-probes';
|
||||||
|
box.style.cssText = 'position:absolute;left:-20000px;top:0;white-space:pre';
|
||||||
|
for (const p of probes) {
|
||||||
|
const s = document.createElement('span');
|
||||||
|
s.style.cssText = 'font-size:32px;font-family:"' + p.face.replace(/"/g, '') + '";font-weight:' + p.weight + ';font-style:' + p.style;
|
||||||
|
s.textContent = p.ch;
|
||||||
|
box.append(s);
|
||||||
|
}
|
||||||
|
document.body.append(box);
|
||||||
|
return { els, probes: probes.length };
|
||||||
|
}`;
|
||||||
|
|
||||||
|
export interface CollectedText { el: string; text: string; stack: string[]; chars: string[]; probe: Record<string, number> }
|
||||||
|
|
||||||
|
/** Which face drew each character: the first face of the element's stack whose probe span used a web font (the probe
|
||||||
|
* span names that face only, so a web font in its platform fonts can only be that face). Pure. */
|
||||||
|
export function attribute(els: CollectedText[], covered: boolean[]): MeasuredText[] {
|
||||||
|
return els.map(e => {
|
||||||
|
const faces: Record<string, string> = {};
|
||||||
|
for (const ch of e.chars) {
|
||||||
|
const f = e.stack.find(face => covered[e.probe[face + '|' + ch]!]) ?? '(system)';
|
||||||
|
faces[f] = (faces[f] ?? '') + ch;
|
||||||
|
}
|
||||||
|
return { el: e.el, text: e.text, faces };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Measures a rendered page (Playwright chromium page): collects the text, then asks Chrome over CDP
|
||||||
|
* (CSS.getPlatformFontsForNode) which fonts drew each probe. Removes the probes afterwards. */
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
export async function measureFonts(page: any, ours: string[]): Promise<MeasuredText[]> {
|
||||||
|
const { els } = await page.evaluate(`(${COLLECT_TEXT})(${JSON.stringify(ours)})`) as { els: CollectedText[] };
|
||||||
|
await page.evaluate('document.fonts.ready.then(() => 0)');
|
||||||
|
const cdp = await page.context().newCDPSession(page);
|
||||||
|
try {
|
||||||
|
await cdp.send('DOM.enable'); await cdp.send('CSS.enable');
|
||||||
|
const { root } = await cdp.send('DOM.getDocument', { depth: 0 });
|
||||||
|
const { nodeIds } = await cdp.send('DOM.querySelectorAll', { nodeId: root.nodeId, selector: '#sb-glyph-probes > span' }) as { nodeIds: number[] };
|
||||||
|
const covered: boolean[] = [];
|
||||||
|
for (const nodeId of nodeIds) {
|
||||||
|
const { fonts } = await cdp.send('CSS.getPlatformFontsForNode', { nodeId }) as { fonts: { isCustomFont: boolean; glyphCount: number }[] };
|
||||||
|
covered.push(fonts.some(f => f.isCustomFont && f.glyphCount > 0));
|
||||||
|
}
|
||||||
|
return attribute(els, covered);
|
||||||
|
} finally {
|
||||||
|
await cdp.detach().catch(() => {});
|
||||||
|
await page.evaluate("document.getElementById('sb-glyph-probes')?.remove()");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Font usage of one rendered image, as stored in report.json. fallback = drawn by a face the config did not choose;
|
||||||
|
* missing = drawn by a system font (no face of ours has the glyph, or the font file did not load). */
|
||||||
|
export interface FontUsage {
|
||||||
|
used: Record<string, number>;
|
||||||
|
fallback: { el: string; text: string; face: string; family: string; chars: string }[];
|
||||||
|
missing: { el: string; text: string; chars: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Classifies what the page measured: faces of kind title / body / script and chosen fallbacks are fine. */
|
||||||
|
export function fontUsage(measured: MeasuredText[], faces: FontManifest['faces']): FontUsage {
|
||||||
|
const u: FontUsage = { used: {}, fallback: [], missing: [] };
|
||||||
|
for (const m of measured) for (const [face, chars] of Object.entries(m.faces)) {
|
||||||
|
const n = [...chars].length;
|
||||||
|
const fam = face === '(system)' ? '(system)' : faces[face]?.family ?? face;
|
||||||
|
u.used[fam] = (u.used[fam] ?? 0) + n;
|
||||||
|
if (face === '(system)') u.missing.push({ el: m.el, text: m.text, chars });
|
||||||
|
else if (faces[face] && !faces[face]!.chosen) u.fallback.push({ el: m.el, text: m.text, face, family: faces[face]!.family, chars });
|
||||||
|
}
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** check messages for an image's font usage (all errors). */
|
||||||
|
export function fontIssues(u: FontUsage | undefined): { level: 'error'; code: 'font-fallback' | 'glyph-missing'; msg: string }[] {
|
||||||
|
if (!u) return [];
|
||||||
|
const sp = (s: string): string => [...s].join(' ');
|
||||||
|
return [
|
||||||
|
...u.fallback.map(f => ({ level: 'error' as const, code: 'font-fallback' as const,
|
||||||
|
msg: `${f.el} "${f.text}": ${sp(f.chars)} drawn with ${f.family}, an automatic fallback the config did not choose (use a title / body font that covers them, or add '${f.family}' to shots.fonts.fallback, then shots fonts + render)` })),
|
||||||
|
...u.missing.map(f => ({ level: 'error' as const, code: 'glyph-missing' as const,
|
||||||
|
msg: `${f.el} "${f.text}": ${sp(f.chars)} drawn with a system font (no downloaded font has them or the fonts did not load: storebound shots fonts, then render again)` })),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
@ -49,10 +49,11 @@ export const palette = (p: string | Palette | undefined, style: 'game' | 'app' =
|
||||||
return hit;
|
return hit;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Screenshot fonts: shots.fonts, else per style (game: Lilita One titles + Montserrat; app: Inter for both). The app
|
/** Screenshot fonts: shots.fonts, else per style (game: Paytone One titles + Montserrat; app: Inter for both). All
|
||||||
* title is a variable font (bold headline weights). */
|
* three cover Latin Extended-A / B (Turkish, Polish, Czech, Romanian ...) and Vietnamese; Montserrat and Inter also
|
||||||
|
* Cyrillic. The app title is a variable font (bold headline weights). Per-script stack: glyphs.ts. */
|
||||||
export function shotFonts(shots: Pick<ShotsConfig, 'fonts'> | undefined, style: 'game' | 'app'): { title: string; body: string; titleVariable: boolean } {
|
export function shotFonts(shots: Pick<ShotsConfig, 'fonts'> | undefined, style: 'game' | 'app'): { title: string; body: string; titleVariable: boolean } {
|
||||||
const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Lilita One', body: 'Montserrat' };
|
const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Paytone One', body: 'Montserrat' };
|
||||||
return { title: shots?.fonts?.title ?? d.title, body: shots?.fonts?.body ?? d.body, titleVariable: style === 'app' };
|
return { title: shots?.fonts?.title ?? d.title, body: shots?.fonts?.body ?? d.body, titleVariable: style === 'app' };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,9 +5,16 @@
|
||||||
// <lang>/sheet.png (contact sheet of every size packed into a grid, for a quick review) and <shots.out>/report.json (text overflow flags
|
// <lang>/sheet.png (contact sheet of every size packed into a grid, for a quick review) and <shots.out>/report.json (text overflow flags
|
||||||
// per image, read by `shots check` and `shots gallery`). Variants go to <shots.out>/<variant>/<lang>/...
|
// per image, read by `shots check` and `shots gallery`). Variants go to <shots.out>/<variant>/<lang>/...
|
||||||
// Default sizes: defaultSizes() (ipad13 only with apple.ipad). Needs playwright + ffmpeg.
|
// Default sizes: defaultSizes() (ipad13 only with apple.ipad). Needs playwright + ffmpeg.
|
||||||
|
// Fonts: the per-language stacks from .storebound/fonts/fonts.json (`shots fonts`). Before rendering, every character
|
||||||
|
// of the copy is checked against the cmaps of the downloaded faces (stale fonts fail with the language and the
|
||||||
|
// characters); while rendering, the page measures which face drew every character, and report.json records it per
|
||||||
|
// image (`fonts`: faces used, automatic fallbacks, system-font glyphs) for `shots check`.
|
||||||
// Style: shotsStyle() = shots.style, else app for the app / subscription-app profiles (template-app.html,
|
// Style: shotsStyle() = shots.style, else app for the app / subscription-app profiles (template-app.html,
|
||||||
// feature-app.html: calm gradient, device frame, headline + subline), else game (template.html, feature.html).
|
// feature-app.html: calm gradient, device frame, headline + subline), else game (template.html, feature.html).
|
||||||
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
|
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
|
||||||
|
import { fontCodepoints } from './cmap';
|
||||||
|
import { readManifest } from './fonts';
|
||||||
|
import { type FontManifest, fontUsage, measureFonts, roleTexts, uncoveredChars } from './glyphs';
|
||||||
import { join, relative } from 'node:path';
|
import { join, relative } from 'node:path';
|
||||||
import { spawnSync } from 'node:child_process';
|
import { spawnSync } from 'node:child_process';
|
||||||
import type { Ctx } from '../lib/ctx';
|
import type { Ctx } from '../lib/ctx';
|
||||||
|
|
@ -51,12 +58,46 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
return done('shots', `render planned (dry run): ${n} images`);
|
return done('shots', `render planned (dry run): ${n} images`);
|
||||||
}
|
}
|
||||||
const fontsDir = join(root, '.storebound', 'fonts');
|
const fontsDir = join(root, '.storebound', 'fonts');
|
||||||
if (!existsSync(join(fontsDir, 'fonts.css'))) warn('shots', 'no .storebound/fonts/fonts.css: run `storebound shots fonts` first (falling back to system fonts)');
|
if (!existsSync(join(fontsDir, 'fonts.css'))) warn('shots', 'no .storebound/fonts/fonts.css: run `storebound shots fonts` first (falling back to system fonts; shots check will fail)');
|
||||||
const { phone, tablet } = frameDims(config);
|
const { phone, tablet } = frameDims(config);
|
||||||
const rtl = new Map(config.languages.map(l => [l.id, !!l.rtl] as const));
|
const rtl = new Map(config.languages.map(l => [l.id, !!l.rtl] as const));
|
||||||
const style = shotsStyle(config);
|
const style = shotsStyle(config);
|
||||||
const sf = shotFonts(shots, style);
|
const sf = shotFonts(shots, style);
|
||||||
const fonts = { title: sf.title, body: sf.body };
|
const fonts = { title: sf.title, body: sf.body };
|
||||||
|
const manifest = existsSync(join(fontsDir, 'fonts.css')) ? readManifest(fontsDir) : null;
|
||||||
|
if (existsSync(join(fontsDir, 'fonts.css')) && !manifest) warn('shots', 'fonts from an older storebound (no fonts.json): run `storebound shots fonts` again for the glyph coverage check');
|
||||||
|
if (manifest && (!manifest.faces[sf.title] || !manifest.faces[sf.body])) throw new Error(`shots render: .storebound/fonts has other fonts than shots.fonts (${sf.title} / ${sf.body}): run \`storebound shots fonts\``);
|
||||||
|
const stacks = (lang: string, copy: CopyFile): { title: string[]; body: string[]; script: string | null } => {
|
||||||
|
const m = manifest?.langs[lang];
|
||||||
|
if (m) return { title: m.title, body: m.body, script: m.title[0]?.startsWith('Store ') && !m.title[0].startsWith('Store fb ') ? m.title[0] : null };
|
||||||
|
const sc = scriptFont(lang, copyText(lang, copy[lang]));
|
||||||
|
const x = sc ? `Store ${sc.slug}` : null;
|
||||||
|
return { title: [...(x ? [x] : []), sf.title], body: [...(x ? [x] : []), sf.body], script: x };
|
||||||
|
};
|
||||||
|
const faces: FontManifest['faces'] = manifest?.faces ?? { [sf.title]: { family: sf.title, file: '', kind: 'title', chosen: true }, [sf.body]: { family: sf.body, file: '', kind: 'body', chosen: true } };
|
||||||
|
if (!manifest) for (const [, job] of jobs) for (const lang of langs) {
|
||||||
|
const x = stacks(lang, job.copy).script;
|
||||||
|
if (x) faces[x] = { family: x, file: '', kind: 'script', chosen: true };
|
||||||
|
}
|
||||||
|
if (manifest) { // glyph coverage of the local font files, before rendering anything
|
||||||
|
const cmaps = new Map<string, Set<number>>();
|
||||||
|
const cps = (face: string): Set<number> => {
|
||||||
|
if (!cmaps.has(face)) { const f = manifest.faces[face]; cmaps.set(face, f && existsSync(join(fontsDir, f.file)) ? fontCodepoints(readFileSync(join(fontsDir, f.file))) : new Set()); }
|
||||||
|
return cmaps.get(face)!;
|
||||||
|
};
|
||||||
|
const gaps: string[] = [];
|
||||||
|
for (const [, job] of jobs) for (const lang of langs) {
|
||||||
|
if (!manifest.langs[lang]) { gaps.push(`${lang}: no font stack (language added after \`shots fonts\`)`); continue; }
|
||||||
|
const t = roleTexts(lang, job.copy[lang], config.app.name);
|
||||||
|
for (const role of ['title', 'body'] as const) {
|
||||||
|
const miss = uncoveredChars(t[role], manifest.langs[lang]![role].map(cps));
|
||||||
|
if (miss.length) gaps.push(`${lang} (${role}): ${miss.join(' ')}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (gaps.length) throw new Error(`shots render: the downloaded fonts do not cover the copy (edited since \`shots fonts\`?): run \`storebound shots fonts\`\n ${[...new Set(gaps)].join('\n ')}`);
|
||||||
|
for (const lang of langs) for (const f of manifest.langs[lang]?.fallbacks ?? [])
|
||||||
|
(manifest.faces[f.face]?.chosen ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} from ${f.family}${manifest.faces[f.face]?.chosen ? '' : ' (automatic fallback: shots check will fail)'}`);
|
||||||
|
}
|
||||||
const tpl = import.meta.dir;
|
const tpl = import.meta.dir;
|
||||||
|
|
||||||
const server = Bun.serve({
|
const server = Bun.serve({
|
||||||
|
|
@ -67,10 +108,9 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
if (p === '/job.json') {
|
if (p === '/job.json') {
|
||||||
const lang = url.searchParams.get('lang') ?? '';
|
const lang = url.searchParams.get('lang') ?? '';
|
||||||
const { scenes, copy } = jobs.get(url.searchParams.get('v') ?? '') ?? jobs.values().next().value!;
|
const { scenes, copy } = jobs.get(url.searchParams.get('v') ?? '') ?? jobs.values().next().value!;
|
||||||
const text = copyText(lang, copy[lang]);
|
const st = stacks(lang, copy);
|
||||||
const script = scriptFont(lang, text);
|
|
||||||
const base = { style, phone, tablet, rtl: rtl.get(lang), logo: !!shots.logo, appName: config.app.name,
|
const base = { style, phone, tablet, rtl: rtl.get(lang), logo: !!shots.logo, appName: config.app.name,
|
||||||
fonts: { ...fonts, script: script ? `Store ${script.slug}` : null } };
|
fonts: { ...fonts, script: st.script, titleStack: st.title, bodyStack: st.body } };
|
||||||
if (url.searchParams.has('feature'))
|
if (url.searchParams.has('feature'))
|
||||||
return Response.json({ ...base, frame: shots.feature?.frame ?? scenes[0]!.frames[0]!.src, palette: palette(shots.feature?.palette ?? scenes[0]!.palette, style) });
|
return Response.json({ ...base, frame: shots.feature?.frame ?? scenes[0]!.frames[0]!.src, palette: palette(shots.feature?.palette ?? scenes[0]!.palette, style) });
|
||||||
const sid = url.searchParams.get('s') ?? '';
|
const sid = url.searchParams.get('s') ?? '';
|
||||||
|
|
@ -108,7 +148,13 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
await page.waitForTimeout(200);
|
await page.waitForTimeout(200);
|
||||||
const tmp = out + '.tmp.png';
|
const tmp = out + '.tmp.png';
|
||||||
const overflow = JSON.parse((await page.evaluate('document.body.dataset.overflow')) ?? '[]') as string[];
|
const overflow = JSON.parse((await page.evaluate('document.body.dataset.overflow')) ?? '[]') as string[];
|
||||||
if (!out.endsWith('sheet.png')) report[relative(outDir, out)] = { overflow, missing: errs.filter(e => e.startsWith('404')) };
|
if (!out.endsWith('sheet.png')) {
|
||||||
|
const measured = await measureFonts(page, Object.keys(faces));
|
||||||
|
const usage = fontUsage(measured, faces);
|
||||||
|
report[relative(outDir, out)] = { overflow, missing: errs.filter(e => e.startsWith('404')), fonts: usage };
|
||||||
|
for (const f of usage.fallback) warn('shots', `${relative(root, out)}: ${f.el} ${[...f.chars].join(' ')} drawn with ${f.family} (automatic fallback)`);
|
||||||
|
for (const f of usage.missing) warn('shots', `${relative(root, out)}: ${f.el} ${[...f.chars].join(' ')} drawn with a system font`);
|
||||||
|
}
|
||||||
if (overflow.length) warn('shots', `${relative(root, out)}: ${overflow.join('; ')}`);
|
if (overflow.length) warn('shots', `${relative(root, out)}: ${overflow.join('; ')}`);
|
||||||
await page.screenshot({ path: tmp, clip: { x: 0, y: 0, width: w, height: h } });
|
await page.screenshot({ path: tmp, clip: { x: 0, y: 0, width: w, height: h } });
|
||||||
const r = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', tmp, '-pix_fmt', 'rgb24', out]);
|
const r = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', tmp, '-pix_fmt', 'rgb24', out]);
|
||||||
|
|
|
||||||
|
|
@ -4,10 +4,12 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { spawnSync } from 'node:child_process';
|
import { spawnSync } from 'node:child_process';
|
||||||
import { SIZES } from './lib';
|
import { SIZES } from './lib';
|
||||||
|
import { fontIssues, type FontUsage } from './glyphs';
|
||||||
import { checkCount, checkImage, checkVideo, type ImageInfo, imageInfo, type Issue, IMAGE_SPECS, parseProbe, PREVIEW_RULES, type ProbeInfo, VIDEO_TARGETS } from './spec';
|
import { checkCount, checkImage, checkVideo, type ImageInfo, imageInfo, type Issue, IMAGE_SPECS, parseProbe, PREVIEW_RULES, type ProbeInfo, VIDEO_TARGETS } from './spec';
|
||||||
|
|
||||||
/** <renders>/report.json: path relative to the renders dir -> flags found while rendering. */
|
/** <renders>/report.json: path relative to the renders dir -> flags found while rendering. missing = 404s (frames);
|
||||||
export type RenderReport = Record<string, { overflow: string[]; missing?: string[] }>;
|
* fonts = which face drew the text (glyphs.ts FontUsage): automatic fallbacks and system-font glyphs are errors. */
|
||||||
|
export type RenderReport = Record<string, { overflow: string[]; missing?: string[]; fonts?: FontUsage }>;
|
||||||
|
|
||||||
export function readReport(dir: string): RenderReport {
|
export function readReport(dir: string): RenderReport {
|
||||||
try { return JSON.parse(readFileSync(join(dir, 'report.json'), 'utf8')) as RenderReport; } catch { return {}; }
|
try { return JSON.parse(readFileSync(join(dir, 'report.json'), 'utf8')) as RenderReport; } catch { return {}; }
|
||||||
|
|
@ -49,7 +51,10 @@ export function scanRenders(dir: string, o: { langs: string[]; variants?: string
|
||||||
const info = imageInfo(readFileSync(file));
|
const info = imageInfo(readFileSync(file));
|
||||||
const rel = (variant ? `${variant}/` : '') + `${lang}/${size}/${f}`;
|
const rel = (variant ? `${variant}/` : '') + `${lang}/${size}/${f}`;
|
||||||
const issues = checkImage(info, size);
|
const issues = checkImage(info, size);
|
||||||
for (const msg of report[rel.replace(/\.jpe?g$/i, '.png')]?.overflow ?? []) issues.push({ level: 'warn', code: 'overflow', msg });
|
const entry = report[rel.replace(/\.jpe?g$/i, '.png')];
|
||||||
|
for (const msg of entry?.overflow ?? []) issues.push({ level: 'warn', code: 'overflow', msg });
|
||||||
|
issues.push(...fontIssues(entry?.fonts));
|
||||||
|
if (entry && !entry.fonts) issues.push({ level: 'warn', code: 'fonts', msg: 'font usage not recorded (rendered by an older storebound): run shots fonts + shots render again so missing glyphs are caught' });
|
||||||
out.images.push({ rel, lang, variant, size, file, info, issues });
|
out.images.push({ rel, lang, variant, size, file, info, issues });
|
||||||
}
|
}
|
||||||
const required = req[size] ?? false;
|
const required = req[size] ?? false;
|
||||||
|
|
|
||||||
|
|
@ -90,7 +90,7 @@ export function imageInfo(b: Uint8Array): ImageInfo {
|
||||||
}
|
}
|
||||||
|
|
||||||
export type IssueLevel = 'error' | 'warn';
|
export type IssueLevel = 'error' | 'warn';
|
||||||
export interface Issue { level: IssueLevel; code: 'size' | 'alpha' | 'format' | 'bytes' | 'count' | 'overflow' | 'video'; msg: string }
|
export interface Issue { level: IssueLevel; code: 'size' | 'alpha' | 'format' | 'bytes' | 'count' | 'overflow' | 'video' | 'font-fallback' | 'glyph-missing' | 'fonts'; msg: string }
|
||||||
|
|
||||||
/** Problems with one image for a size key. */
|
/** Problems with one image for a size key. */
|
||||||
export function checkImage(info: ImageInfo, sizeKey: string): Issue[] {
|
export function checkImage(info: ImageInfo, sizeKey: string): Issue[] {
|
||||||
|
|
|
||||||
|
|
@ -89,8 +89,10 @@ R.setProperty('--line2', dark ? P.glow : P.ink);
|
||||||
R.setProperty('--accentSoft', rgba(P.glow, dark ? .28 : .14));
|
R.setProperty('--accentSoft', rgba(P.glow, dark ? .28 : .14));
|
||||||
R.setProperty('--bg', P.bg[0] === P.bg[2] && P.bg[1] === P.bg[0] ? P.bg[0] : `linear-gradient(180deg, ${P.bg[0]} 0%, ${P.bg[1]} 55%, ${P.bg[2]} 100%)`);
|
R.setProperty('--bg', P.bg[0] === P.bg[2] && P.bg[1] === P.bg[0] ? P.bg[0] : `linear-gradient(180deg, ${P.bg[0]} 0%, ${P.bg[1]} 55%, ${P.bg[2]} 100%)`);
|
||||||
const T = job.fonts.title, B = job.fonts.body, X = job.fonts.script;
|
const T = job.fonts.title, B = job.fonts.body, X = job.fonts.script;
|
||||||
R.setProperty('--tf', X ? `'${X}', '${T}', sans-serif` : `'${T}', sans-serif`);
|
// titleStack / bodyStack (from shots fonts): script face, the configured font, then any automatic Noto fallback
|
||||||
R.setProperty('--bf', X ? `'${X}', '${B}', sans-serif` : `'${B}', sans-serif`);
|
const fstack = (st, def) => (st ?? (X ? [X, def] : [def])).map(f => `'${f}'`).join(', ') + ', sans-serif';
|
||||||
|
R.setProperty('--tf', fstack(job.fonts.titleStack, T));
|
||||||
|
R.setProperty('--bf', fstack(job.fonts.bodyStack, B));
|
||||||
R.setProperty('--tw', 750);
|
R.setProperty('--tw', 750);
|
||||||
const CJK = /^(ja|ko|zh)/.test(LANG);
|
const CJK = /^(ja|ko|zh)/.test(LANG);
|
||||||
R.setProperty('--lh', /^(ar|hi|fa|ur|th)/.test(LANG) ? 1.3 : CJK ? 1.18 : 1.06);
|
R.setProperty('--lh', /^(ar|hi|fa|ur|th)/.test(LANG) ? 1.3 : CJK ? 1.18 : 1.06);
|
||||||
|
|
|
||||||
|
|
@ -126,8 +126,10 @@ R.setProperty('--bg', `linear-gradient(180deg, ${P.bg[0]} 0%, ${P.bg[1]} 48%, ${
|
||||||
// A script the title font lacks (CJK, Arabic, Cyrillic, ...): the whole line switches to the Noto subset so a word
|
// A script the title font lacks (CJK, Arabic, Cyrillic, ...): the whole line switches to the Noto subset so a word
|
||||||
// never mixes two typefaces.
|
// never mixes two typefaces.
|
||||||
const T = job.fonts.title, B = job.fonts.body, X = job.fonts.script;
|
const T = job.fonts.title, B = job.fonts.body, X = job.fonts.script;
|
||||||
R.setProperty('--tf', X ? `'${X}', '${T}', sans-serif` : `'${T}', sans-serif`);
|
// titleStack / bodyStack (from shots fonts): script face, the configured font, then any automatic Noto fallback
|
||||||
R.setProperty('--bf', X ? `'${X}', '${B}', sans-serif` : `'${B}', sans-serif`);
|
const fstack = (st, def) => (st ?? (X ? [X, def] : [def])).map(f => `'${f}'`).join(', ') + ', sans-serif';
|
||||||
|
R.setProperty('--tf', fstack(job.fonts.titleStack, T));
|
||||||
|
R.setProperty('--bf', fstack(job.fonts.bodyStack, B));
|
||||||
R.setProperty('--tw', X ? 900 : job.fonts.titleWeight ?? 400);
|
R.setProperty('--tw', X ? 900 : job.fonts.titleWeight ?? 400);
|
||||||
const CJK = /^(ja|ko|zh)/.test(LANG);
|
const CJK = /^(ja|ko|zh)/.test(LANG);
|
||||||
R.setProperty('--lh', /^(ar|hi|fa|ur|th)/.test(LANG) ? 1.28 : CJK ? 1.12 : .98);
|
R.setProperty('--lh', /^(ar|hi|fa|ur|th)/.test(LANG) ? 1.28 : CJK ? 1.12 : .98);
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ import { need } from '../lib/ctx';
|
||||||
import { done, log, warn } from '../lib/log';
|
import { done, log, warn } from '../lib/log';
|
||||||
import { launch } from './browser';
|
import { launch } from './browser';
|
||||||
import { shotsStyle } from '../lib/config';
|
import { shotsStyle } from '../lib/config';
|
||||||
|
import { readManifest } from './fonts';
|
||||||
import { captionsFor, type CopyFile, copyText, palette, renderDir, scriptFont, shotFonts } from './lib';
|
import { captionsFor, type CopyFile, copyText, palette, renderDir, scriptFont, shotFonts } from './lib';
|
||||||
import { ffprobe } from './report';
|
import { ffprobe } from './report';
|
||||||
import { checkVideo, PREVIEW_RULES, VIDEO_TARGETS } from './spec';
|
import { checkVideo, PREVIEW_RULES, VIDEO_TARGETS } from './spec';
|
||||||
|
|
@ -158,7 +159,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const style = shotsStyle(ctx.loaded.config);
|
const style = shotsStyle(ctx.loaded.config);
|
||||||
const pal = palette(shots.scenes[0]?.palette, style);
|
const pal = palette(shots.scenes[0]?.palette, style);
|
||||||
return Response.json({ text: texts[Number(url.searchParams.get('i'))] ?? '', ink: style === 'app' ? '#111827' : pal.ink, rtl: rtl.get(lang),
|
return Response.json({ text: texts[Number(url.searchParams.get('i'))] ?? '', ink: style === 'app' ? '#111827' : pal.ink, rtl: rtl.get(lang),
|
||||||
fonts: { title: shotFonts(shots, style).title, script: script ? `Store ${script.slug}` : null } });
|
fonts: { title: shotFonts(shots, style).title, script: script ? `Store ${script.slug}` : null, titleStack: readManifest(fontsDir)?.langs[lang]?.title } });
|
||||||
}
|
}
|
||||||
if (url.pathname === '/caption.html') return new Response(Bun.file(join(import.meta.dir, 'caption.html')), { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
if (url.pathname === '/caption.html') return new Response(Bun.file(join(import.meta.dir, 'caption.html')), { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
||||||
if (url.pathname.startsWith('/fonts/') && !url.pathname.includes('..')) {
|
if (url.pathname.startsWith('/fonts/') && !url.pathname.includes('..')) {
|
||||||
|
|
|
||||||
|
|
@ -41,7 +41,7 @@ const config: ShipConfig = {
|
||||||
copy: 'store/shots/copy.json',
|
copy: 'store/shots/copy.json',
|
||||||
frames: 'store/shots/frames',
|
frames: 'store/shots/frames',
|
||||||
out: 'store/renders',
|
out: 'store/renders',
|
||||||
fonts: { title: 'Lilita One', body: 'Montserrat' },
|
fonts: { title: 'Paytone One', body: 'Montserrat' },
|
||||||
scenes: [
|
scenes: [
|
||||||
{ id: 'hero', palette: 'violet', hero: true, over: 30, frames: [{ src: 'play.png', rotate: -4 }],
|
{ id: 'hero', palette: 'violet', hero: true, over: 30, frames: [{ src: 'play.png', rotate: -4 }],
|
||||||
badges: [{ y: 0.42, side: 'l', icon: 'offline', iconBg: 'blue', rot: -4 }, { y: 0.68, side: 'r', icon: 'bolt', iconBg: 'violet', rot: 3 }] },
|
badges: [{ y: 0.42, side: 'l', icon: 'offline', iconBg: 'blue', rot: -4 }, { y: 0.68, side: 'r', icon: 'bolt', iconBg: 'violet', rot: 3 }] },
|
||||||
|
|
|
||||||
|
|
@ -74,20 +74,29 @@ in a plain Android tablet body instead of the iPad one.
|
||||||
`badges` [[big, small]] (game style). Short and true (only claim what is in the app); about 15 Latin characters per title line.
|
`badges` [[big, small]] (game style). Short and true (only claim what is in the app); about 15 Latin characters per title line.
|
||||||
Natural marketing tone per language, not literal translation; use the app's own terms.
|
Natural marketing tone per language, not literal translation; use the app's own terms.
|
||||||
4. **Fonts.** `storebound shots fonts` downloads title/body fonts and a Noto subset for every non-Latin script found in
|
4. **Fonts.** `storebound shots fonts` downloads title/body fonts and a Noto subset for every non-Latin script found in
|
||||||
the copy (CJK, Arabic, Hebrew, Devanagari, Thai, Cyrillic/Greek). Re-run after copy edits.
|
the copy (CJK, Arabic, Hebrew, Devanagari, Thai, Cyrillic/Greek), then checks every character of every language
|
||||||
|
(copy.json + config languages) against the cmap of the fonts that draw it. A character the title / body font lacks
|
||||||
|
gets an automatic Noto fallback (`WARN tr title: ş ğ not in Lilita One -> Noto Sans Display`); no fallback at all
|
||||||
|
fails with the language and the characters. Renders that used an automatic fallback (or a system font) are ERRORS in
|
||||||
|
`shots check`: fix it with a title / body font that covers the language (Paytone One, Baloo 2, Rowdies for game
|
||||||
|
titles; Montserrat, Inter, Nunito for body), or, if the owner accepts mixed glyphs, `shots.fonts.fallback:
|
||||||
|
['Noto Sans Display']`. Lilita One lacks most of Latin Extended (Turkish ş ğ İ, Polish, Czech, Romanian) and
|
||||||
|
Vietnamese. Re-run after copy or font edits (render refuses fonts that no longer cover the copy).
|
||||||
5. **Style and scenes.** `shots.style`: `game` (sunburst, sparkles, outlined titles, badges) or `app` (calm gradient,
|
5. **Style and scenes.** `shots.style`: `game` (sunburst, sparkles, outlined titles, badges) or `app` (calm gradient,
|
||||||
one clean device frame, headline + subline, no sparkles; badges only as quiet chips when the copy has them).
|
one clean device frame, headline + subline, no sparkles; badges only as quiet chips when the copy has them).
|
||||||
Default: `app` for the app / subscription-app profiles, `game` otherwise. `shots.scenes`: palette (game: fire,
|
Default: `app` for the app / subscription-app profiles, `game` otherwise. `shots.scenes`: palette (game: fire,
|
||||||
violet, blast, green, night, sky, gold, candy; app: mist, paper, mint, sand, rose, sky, ocean, slate; or custom
|
violet, blast, green, night, sky, gold, candy; app: mist, paper, mint, sand, rose, sky, ocean, slate; or custom
|
||||||
`{ bg, glow, ink, shadow }`), frames (one front phone + optional back phones with x / dy / scale / rotate), badge
|
`{ bg, glow, ink, shadow }`), frames (one front phone + optional back phones with x / dy / scale / rotate), badge
|
||||||
slots (y, side, icon, hot, stars). Fonts default to Lilita One + Montserrat (game) or Inter (app).
|
slots (y, side, icon, hot, stars). Fonts default to Paytone One + Montserrat (game) or Inter (app): all cover
|
||||||
|
Latin Extended and Vietnamese.
|
||||||
6. **Render.** `storebound shots render --lang en` first, review `store/renders/en/sheet.png` (contact sheet, sizes
|
6. **Render.** `storebound shots render --lang en` first, review `store/renders/en/sheet.png` (contact sheet, sizes
|
||||||
packed into a grid), then
|
packed into a grid), then
|
||||||
all languages in the background: `storebound shots render > .storebound/render.log 2>&1 &`.
|
all languages in the background: `storebound shots render > .storebound/render.log 2>&1 &`.
|
||||||
7. **JPEG for Play.** `storebound shots jpeg` (q92, about 4x smaller than PNG; App Store stays PNG).
|
7. **JPEG for Play.** `storebound shots jpeg` (q92, about 4x smaller than PNG; App Store stays PNG).
|
||||||
8. **Check.** `storebound shots check` (read-only, exit 1 on errors): pixel sizes (Apple: a listed size, portrait or
|
8. **Check.** `storebound shots check` (read-only, exit 1 on errors): pixel sizes (Apple: a listed size, portrait or
|
||||||
landscape; Play screenshots 320-3840 px at most 2:1; feature graphic exactly 1024 x 500), alpha, Play JPEG /
|
landscape; Play screenshots 320-3840 px at most 2:1; feature graphic exactly 1024 x 500), alpha, Play JPEG /
|
||||||
24-bit PNG and 8 MB, counts per set (Apple 1-10, Play 2-8), text overflow flags (warnings). `--variants` also checks
|
24-bit PNG and 8 MB, counts per set (Apple 1-10, Play 2-8), text overflow flags (warnings), glyphs drawn by an
|
||||||
|
automatic font fallback or a system font (errors; `shots render` measures every character in the page). `--variants` also checks
|
||||||
A/B variant folders. `storebound validate` runs the same checks on the renders folder and lists errors as
|
A/B variant folders. `storebound validate` runs the same checks on the renders folder and lists errors as
|
||||||
blockers next to the store state (`--no-local` skips them).
|
blockers next to the store state (`--no-local` skips them).
|
||||||
9. **Review.** `storebound shots gallery` writes `<renders>/index.html`: one self-contained page (no network, open it
|
9. **Review.** `storebound shots gallery` writes `<renders>/index.html`: one self-contained page (no network, open it
|
||||||
|
|
|
||||||
|
|
@ -125,7 +125,9 @@ const config: ShipConfig = {
|
||||||
frames: 'store/shots/frames', // <lang>/phone/<name>.png, <lang>/tablet/<name>.png
|
frames: 'store/shots/frames', // <lang>/phone/<name>.png, <lang>/tablet/<name>.png
|
||||||
out: 'store/renders',
|
out: 'store/renders',
|
||||||
logo: 'store/shots/logo.png', // optional: hero scene + feature graphic
|
logo: 'store/shots/logo.png', // optional: hero scene + feature graphic
|
||||||
fonts: { title: 'Lilita One', body: 'Montserrat' },
|
// Google Fonts; both cover Latin Extended (tr, pl, cs, ro ...) and Vietnamese. `shots fonts` checks every glyph of the
|
||||||
|
// copy; a character the font lacks needs a font that has it or fallback: ['Noto Sans Display'] (else shots check fails).
|
||||||
|
fonts: { title: 'Paytone One', body: 'Montserrat' },
|
||||||
// phone: { w: 440, h: 902, dpr: 3 }, // raw frame size in CSS px (screen below a 54 px status bar)
|
// phone: { w: 440, h: 902, dpr: 3 }, // raw frame size in CSS px (screen below a 54 px status bar)
|
||||||
// tablet: { w: 1032, h: 1352, dpr: 2 }, // default with apple.ipad (13" iPad below its 24 px bar), else 800 x 1240
|
// tablet: { w: 1032, h: 1352, dpr: 2 }, // default with apple.ipad (13" iPad below its 24 px bar), else 800 x 1240
|
||||||
scenes: [
|
scenes: [
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ function fixture(): string {
|
||||||
put('b/en/ios69/01.png', png(1320, 2868));
|
put('b/en/ios69/01.png', png(1320, 2868));
|
||||||
put('en/preview/iphone/01.mp4', new Uint8Array(10));
|
put('en/preview/iphone/01.mp4', new Uint8Array(10));
|
||||||
put('en/preview/iphone/01-poster.png', png(886, 1920));
|
put('en/preview/iphone/01-poster.png', png(886, 1920));
|
||||||
writeFileSync(join(dir, 'report.json'), JSON.stringify({ 'tr/ios69/01.png': { overflow: ['title line 1 shrunk to 60 %: consider shorter words'] } }));
|
writeFileSync(join(dir, 'report.json'), JSON.stringify({ 'tr/ios69/01.png': { overflow: ['title line 1 shrunk to 60 %: consider shorter words'], fonts: { used: { 'Paytone One': 20 }, fallback: [], missing: [] } } }));
|
||||||
return dir;
|
return dir;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
220
tests/glyphs.test.ts
Normal file
220
tests/glyphs.test.ts
Normal file
|
|
@ -0,0 +1,220 @@
|
||||||
|
// Glyph coverage of the screenshot fonts: the pure-TS cmap reader (TTF / WOFF / WOFF2), the per-language plan with
|
||||||
|
// automatic Noto fallbacks, and `shots check` errors for renders that needed a fallback or a system font.
|
||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { brotliCompressSync, deflateSync } from 'node:zlib';
|
||||||
|
import { cmapTable, fontCodepoints, missingChars } from '../cli/shots/cmap';
|
||||||
|
import { attribute, type FaceJob, type MeasuredText, fontIssues, fontsCss, fontUsage, GlyphError, planFonts, roleTexts, uncoveredChars } from '../cli/shots/glyphs';
|
||||||
|
import { langTexts } from '../cli/shots/fonts';
|
||||||
|
import { allIssues, scanRenders } from '../cli/shots/report';
|
||||||
|
import { shotFonts } from '../cli/shots/lib';
|
||||||
|
|
||||||
|
// ---- tiny font builders (only a cmap table: enough for the reader) ----
|
||||||
|
function cmapBytes(cps: number[]): Uint8Array {
|
||||||
|
const sorted = [...new Set(cps)].sort((a, b) => a - b);
|
||||||
|
const bmp = sorted.filter(c => c < 0xffff);
|
||||||
|
// format 4: one segment per code point (+ the 0xFFFF terminator), glyph id = index + 1 via idDelta
|
||||||
|
const segs = [...bmp.map((c, i) => ({ s: c, e: c, d: (i + 1 - c) & 0xffff })), { s: 0xffff, e: 0xffff, d: 1 }];
|
||||||
|
const f4len = 16 + segs.length * 8;
|
||||||
|
const f12len = 16 + sorted.length * 12;
|
||||||
|
const b = new DataView(new ArrayBuffer(4 + 16 + f4len + f12len));
|
||||||
|
b.setUint16(0, 0); b.setUint16(2, 2);
|
||||||
|
b.setUint16(4, 3); b.setUint16(6, 1); b.setUint32(8, 20);
|
||||||
|
b.setUint16(12, 3); b.setUint16(14, 10); b.setUint32(16, 20 + f4len);
|
||||||
|
let o = 20;
|
||||||
|
b.setUint16(o, 4); b.setUint16(o + 2, f4len); b.setUint16(o + 6, segs.length * 2);
|
||||||
|
segs.forEach((s, i) => {
|
||||||
|
b.setUint16(o + 14 + i * 2, s.e);
|
||||||
|
b.setUint16(o + 16 + segs.length * 2 + i * 2, s.s);
|
||||||
|
b.setUint16(o + 16 + segs.length * 4 + i * 2, s.d);
|
||||||
|
b.setUint16(o + 16 + segs.length * 6 + i * 2, 0);
|
||||||
|
});
|
||||||
|
o += f4len;
|
||||||
|
b.setUint16(o, 12); b.setUint32(o + 4, f12len); b.setUint32(o + 12, sorted.length);
|
||||||
|
sorted.forEach((c, i) => { b.setUint32(o + 16 + i * 12, c); b.setUint32(o + 20 + i * 12, c); b.setUint32(o + 24 + i * 12, i + 1); });
|
||||||
|
return new Uint8Array(b.buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ttf(cps: number[]): Uint8Array {
|
||||||
|
const cmap = cmapBytes(cps);
|
||||||
|
const out = new Uint8Array(12 + 16 + cmap.length);
|
||||||
|
const d = new DataView(out.buffer);
|
||||||
|
d.setUint32(0, 0x00010000); d.setUint16(4, 1);
|
||||||
|
out.set([...'cmap'].map(c => c.charCodeAt(0)), 12);
|
||||||
|
d.setUint32(20, 28); d.setUint32(24, cmap.length);
|
||||||
|
out.set(cmap, 28);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function woff(cps: number[]): Uint8Array {
|
||||||
|
const cmap = cmapBytes(cps), z = new Uint8Array(deflateSync(cmap));
|
||||||
|
const out = new Uint8Array(44 + 20 + z.length);
|
||||||
|
const d = new DataView(out.buffer);
|
||||||
|
out.set([...'wOFF'].map(c => c.charCodeAt(0)), 0); d.setUint32(4, 0x00010000); d.setUint32(8, out.length); d.setUint16(12, 1);
|
||||||
|
out.set([...'cmap'].map(c => c.charCodeAt(0)), 44);
|
||||||
|
d.setUint32(48, 64); d.setUint32(52, z.length); d.setUint32(56, cmap.length);
|
||||||
|
out.set(z, 64);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function woff2(cps: number[]): Uint8Array {
|
||||||
|
// two tables: an untransformed 'head' stand-in (8 bytes) and cmap, both inside one brotli stream
|
||||||
|
const cmap = cmapBytes(cps), head = new Uint8Array(8);
|
||||||
|
const stream = new Uint8Array(brotliCompressSync(Buffer.concat([head, cmap])));
|
||||||
|
const base128 = (n: number): number[] => { const b = [n & 0x7f]; n = Math.floor(n / 128); while (n) { b.unshift(0x80 | (n & 0x7f)); n = Math.floor(n / 128); } return b; };
|
||||||
|
const dir = [1, ...base128(head.length), 0, ...base128(cmap.length)]; // flags: index 1 = head, 0 = cmap (transform version 0)
|
||||||
|
const out = new Uint8Array(48 + dir.length + stream.length);
|
||||||
|
const d = new DataView(out.buffer);
|
||||||
|
out.set([...'wOF2'].map(c => c.charCodeAt(0)), 0); d.setUint32(4, 0x00010000); d.setUint32(8, out.length);
|
||||||
|
d.setUint16(12, 2); d.setUint32(20, stream.length);
|
||||||
|
out.set(dir, 48); out.set(stream, 48 + dir.length);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const range = (a: number, b: number): number[] => Array.from({ length: b - a + 1 }, (_, i) => a + i);
|
||||||
|
const ASCII = range(0x20, 0x7e);
|
||||||
|
const cpsOf = (s: string): number[] => [...s].map(c => c.codePointAt(0)!);
|
||||||
|
|
||||||
|
describe('cmap reader', () => {
|
||||||
|
const want = [...ASCII, 0x15f, 0x11f, 0x1f600];
|
||||||
|
test('TTF, WOFF and WOFF2 give the same code points (format 4 + 12)', () => {
|
||||||
|
for (const f of [ttf(want), woff(want), woff2(want)]) {
|
||||||
|
const got = fontCodepoints(f);
|
||||||
|
expect([...got].sort((a, b) => a - b)).toEqual([...want].sort((a, b) => a - b));
|
||||||
|
}
|
||||||
|
expect(cmapTable(woff2(want)).length).toBe(cmapBytes(want).length);
|
||||||
|
});
|
||||||
|
test('missingChars skips whitespace and joiners, reports each character once', () => {
|
||||||
|
const cps = fontCodepoints(ttf(ASCII));
|
||||||
|
expect(missingChars("Taş Devri'nden şş", cps)).toEqual(['ş']);
|
||||||
|
});
|
||||||
|
test('not a font: a clear error', () => {
|
||||||
|
expect(() => fontCodepoints(new Uint8Array(64))).toThrow('not a font file');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Copy in six languages whose glyphs an ASCII-only title / body font does not have.
|
||||||
|
const COPY = {
|
||||||
|
tr: { s1: { eyebrow: 'Bilgi', title: ["Taş Devri'nden", '2100\'e'] as [string, string], sub: 'Kasabaları yağmala' } },
|
||||||
|
pl: { s1: { title: ['Zażółć', 'gęślą jaźń'] as [string, string], sub: 'Łódź' } },
|
||||||
|
vi: { s1: { title: ['Chiến đấu', 'Thế giới'] as [string, string], sub: 'Trận chiến nhanh' } },
|
||||||
|
ru: { s1: { title: ['Битвы', 'за 2 минуты'] as [string, string], sub: 'Грабь деревни' } },
|
||||||
|
ar: { s1: { title: ['معارك', 'سريعة'] as [string, string], sub: '2 دقيقة' } },
|
||||||
|
ja: { s1: { title: ['2分', 'バトル'] as [string, string], sub: '村を襲え' } },
|
||||||
|
};
|
||||||
|
|
||||||
|
// Fake Google Fonts: what each family covers.
|
||||||
|
const COVER: Record<string, (cp: number) => boolean> = {
|
||||||
|
'Lilita One': cp => cp < 0x7f || cp === 0x131 || cp === 0x141 || cp === 0x142,
|
||||||
|
Montserrat: cp => cp < 0x7f,
|
||||||
|
'Noto Sans': cp => cp < 0x250 || (cp >= 0x400 && cp <= 0x4ff) || (cp >= 0x1ea0 && cp <= 0x1ef9),
|
||||||
|
'Noto Sans Display': cp => cp < 0x250 || (cp >= 0x1ea0 && cp <= 0x1ef9),
|
||||||
|
'Noto Sans Arabic': cp => cp >= 0x600 && cp <= 0x6ff,
|
||||||
|
'Noto Sans JP': cp => cp < 0x7f || (cp >= 0x3040 && cp <= 0x30ff) || (cp >= 0x4e00 && cp <= 0x9fff),
|
||||||
|
};
|
||||||
|
function fakeGet(asked: FaceJob[]): (job: FaceJob) => Promise<Set<number>> {
|
||||||
|
return async job => { asked.push(job); const f = COVER[job.family] ?? (() => false); return new Set(cpsOf(job.chars).filter(f)); };
|
||||||
|
}
|
||||||
|
const input = (chosen?: string[]) => ({ langs: langTexts(COPY, ['en'], 'STAR DASH'), title: 'Lilita One', body: 'Montserrat', titleAxis: null,
|
||||||
|
bodyAxis: 'wght@100..900', fallbackTitleAxis: 'wght@800', chosen, base: String.fromCharCode(...ASCII) });
|
||||||
|
|
||||||
|
describe('glyph coverage plan (shots fonts)', () => {
|
||||||
|
test('tr / pl / vi / ru / ar / ja against fonts that lack the glyphs: flagged and an automatic Noto fallback added', async () => {
|
||||||
|
const asked: FaceJob[] = [];
|
||||||
|
const m = await planFonts(input(), fakeGet(asked));
|
||||||
|
// whole-line script faces stay as before
|
||||||
|
expect(m.langs.ru!.title[0]).toBe('Store cyrgreek');
|
||||||
|
expect(m.langs.ar!.title[0]).toBe('Store arabic');
|
||||||
|
expect(m.langs.ja!.title[0]).toBe('Store jp');
|
||||||
|
// Latin Extended + Vietnamese titles: Noto Sans Display after Lilita One; body text: Noto Sans after Montserrat
|
||||||
|
const fb = (lang: string, role: 'title' | 'body') => m.langs[lang]!.fallbacks.filter(f => f.role === role).map(f => `${f.family}:${f.chars}`);
|
||||||
|
expect(fb('tr', 'title')).toEqual(['Noto Sans Display:ş']);
|
||||||
|
expect(fb('tr', 'body')).toEqual(['Noto Sans:İığ']); // "BİLGİ" (Turkish upper case) + the subline
|
||||||
|
expect(fb('pl', 'title')).toEqual(['Noto Sans Display:żóćęśąźń']); // ł: the title font has it
|
||||||
|
expect(fb('pl', 'body')).toEqual(['Noto Sans:Łóź']);
|
||||||
|
expect(fb('vi', 'title')).toEqual(['Noto Sans Display:ếđấớ']);
|
||||||
|
expect(fb('vi', 'body')).toEqual(['Noto Sans:ậế']);
|
||||||
|
expect(m.langs.tr!.title).toEqual(['Lilita One', 'Store fb noto-sans-display title']);
|
||||||
|
expect(m.faces['Store fb noto-sans-display title']).toMatchObject({ family: 'Noto Sans Display', kind: 'fallback', chosen: false });
|
||||||
|
expect(asked.find(j => j.family === 'Noto Sans Display')!.axis).toBe('wght@800');
|
||||||
|
// ru / ar / ja need no fallback: their Noto script face covers the line, ASCII digits come from it or the font
|
||||||
|
for (const l of ['ru', 'ar', 'ja', 'en']) expect(m.langs[l]!.fallbacks).toEqual([]);
|
||||||
|
expect(fontsCss(m)).toContain("font-family: 'Store fb noto-sans-display title'; font-weight: 100 900; font-synthesis: none; src: url(fb-noto-sans-display-title.woff2)");
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shots.fonts.fallback marks the family as chosen', async () => {
|
||||||
|
const m = await planFonts(input(['Noto Sans Display', 'Noto Sans']), fakeGet([]));
|
||||||
|
expect(m.faces['Store fb noto-sans-display title']!.chosen).toBe(true);
|
||||||
|
expect(m.faces['Store fb noto-sans body']!.chosen).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a character no fallback covers fails with the language and the characters', async () => {
|
||||||
|
const copy = { ...COPY, tr: { s1: { title: ['Taş ', 'x'] as [string, string] } } };
|
||||||
|
const err = await planFonts({ ...input(), langs: langTexts(copy, [], '') }, fakeGet([])).catch(e => e);
|
||||||
|
expect(err).toBeInstanceOf(GlyphError);
|
||||||
|
expect(err.message).toContain('tr (title): "" U+E000; tried Lilita One, Noto Sans Display, Noto Sans');
|
||||||
|
expect((err as GlyphError).gaps.map(g => g.lang)).toEqual(['tr']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('role texts: Turkish upper-case eyebrow, badges split between title and body', () => {
|
||||||
|
const t = roleTexts('tr', { a: { eyebrow: 'bilgi', title: ['A', 'B'], badges: [['9x', 'şarj']] } }, 'Game');
|
||||||
|
expect(t.title).toContain('9x');
|
||||||
|
expect(t.body).toContain('BİLGİ');
|
||||||
|
expect(t.body).toContain('şarj');
|
||||||
|
expect(uncoveredChars(t.body, [new Set(ASCII)])).toEqual(['İ', 'ş']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('defaults cover Latin Extended and Vietnamese (game: Paytone One + Montserrat)', () => {
|
||||||
|
expect(shotFonts(undefined, 'game')).toEqual({ title: 'Paytone One', body: 'Montserrat', titleVariable: false });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('render report fonts -> shots check', () => {
|
||||||
|
const faces = {
|
||||||
|
'Lilita One': { family: 'Lilita One', file: 'title.woff2', kind: 'title' as const, chosen: true },
|
||||||
|
Montserrat: { family: 'Montserrat', file: 'body.woff2', kind: 'body' as const, chosen: true },
|
||||||
|
'Store fb noto-sans-display title': { family: 'Noto Sans Display', file: 'fb.woff2', kind: 'fallback' as const, role: 'title' as const, chosen: false },
|
||||||
|
};
|
||||||
|
const measured: MeasuredText[] = [
|
||||||
|
{ el: 'h1 span:1', text: "Taş Devri'nden", faces: { 'Lilita One': "TaDevri'nden", 'Store fb noto-sans-display title': 'ş' } },
|
||||||
|
{ el: 'p.sub', text: 'Kasabaları yağmala', faces: { Montserrat: 'Kasbalrıyğm' } },
|
||||||
|
{ el: 'div.eyebrow', text: 'X', faces: { '(system)': '✪' } },
|
||||||
|
];
|
||||||
|
|
||||||
|
test('attribute: first face of the stack whose probe drew with a web font, else (system)', () => {
|
||||||
|
const els = [{ el: 'h1 span:1', text: 'Taş ✪', stack: ['Lilita One', 'Store fb noto-sans-display title'], chars: ['T', 'a', 'ş', '✪'],
|
||||||
|
probe: { 'Lilita One|T': 0, 'Store fb noto-sans-display title|T': 1, 'Lilita One|a': 2, 'Store fb noto-sans-display title|a': 3,
|
||||||
|
'Lilita One|ş': 4, 'Store fb noto-sans-display title|ş': 5, 'Lilita One|✪': 6, 'Store fb noto-sans-display title|✪': 7 } }];
|
||||||
|
expect(attribute(els, [true, true, true, true, false, true, false, false])).toEqual([
|
||||||
|
{ el: 'h1 span:1', text: 'Taş ✪', faces: { 'Lilita One': 'Ta', 'Store fb noto-sans-display title': 'ş', '(system)': '✪' } }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('fallback the config did not choose and system-font glyphs are errors', () => {
|
||||||
|
const u = fontUsage(measured, faces);
|
||||||
|
expect(u.used).toEqual({ 'Lilita One': 12, 'Noto Sans Display': 1, Montserrat: 11, '(system)': 1 });
|
||||||
|
const issues = fontIssues(u);
|
||||||
|
expect(issues.map(i => i.code)).toEqual(['font-fallback', 'glyph-missing']);
|
||||||
|
expect(issues[0]!.msg).toContain('ş drawn with Noto Sans Display');
|
||||||
|
// a chosen fallback is fine
|
||||||
|
const ok = fontUsage(measured.slice(0, 2), { ...faces, 'Store fb noto-sans-display title': { ...faces['Store fb noto-sans-display title'], chosen: true } });
|
||||||
|
expect(fontIssues(ok)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('scanRenders: ERROR per image, warn for renders without font usage', () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'sb-glyphs-'));
|
||||||
|
try {
|
||||||
|
mkdirSync(join(dir, 'tr', 'ios69'), { recursive: true });
|
||||||
|
const png = (w: number, h: number) => { const b = new Uint8Array(33); b.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52]); const d = new DataView(b.buffer); d.setUint32(16, w); d.setUint32(20, h); b[24] = 8; b[25] = 2; return b; };
|
||||||
|
for (const n of ['01', '02', '03']) writeFileSync(join(dir, 'tr', 'ios69', `${n}.png`), png(1320, 2868));
|
||||||
|
writeFileSync(join(dir, 'report.json'), JSON.stringify({
|
||||||
|
'tr/ios69/01.png': { overflow: [], fonts: fontUsage(measured.slice(0, 2), faces) },
|
||||||
|
'tr/ios69/02.png': { overflow: [], fonts: { used: { 'Paytone One': 20 }, fallback: [], missing: [] } },
|
||||||
|
'tr/ios69/03.png': { overflow: [] },
|
||||||
|
}));
|
||||||
|
const got = allIssues(scanRenders(dir, { langs: ['tr'], sizes: ['ios69'], probe: () => null })).map(x => `${x.where} ${x.issue.level} ${x.issue.code}`);
|
||||||
|
expect(got).toEqual(['tr/ios69/01.png error font-fallback', 'tr/ios69/03.png warn fonts']);
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -163,7 +163,7 @@ describe('renders scan', () => {
|
||||||
put('de/play/01.jpg', jpeg(1080, 1920));
|
put('de/play/01.jpg', jpeg(1080, 1920));
|
||||||
put('de/play/02.jpg', jpeg(1080, 1920));
|
put('de/play/02.jpg', jpeg(1080, 1920));
|
||||||
put('de/feature/1024x500.jpg', jpeg(1024, 500));
|
put('de/feature/1024x500.jpg', jpeg(1024, 500));
|
||||||
writeFileSync(join(dir, 'report.json'), JSON.stringify({ 'en/ios69/01.png': { overflow: ['title line 1 shrunk to 60 %'] } }));
|
writeFileSync(join(dir, 'report.json'), JSON.stringify({ 'en/ios69/01.png': { overflow: ['title line 1 shrunk to 60 %'], fonts: { used: { Montserrat: 20 }, fallback: [], missing: [] } } }));
|
||||||
const scan = scanRenders(dir, { langs: ['en', 'de'], required: lang => requiredSets(config, lang), probe: () => null });
|
const scan = scanRenders(dir, { langs: ['en', 'de'], required: lang => requiredSets(config, lang), probe: () => null });
|
||||||
const got = allIssues(scan).map(x => `${x.where} ${x.issue.level} ${x.issue.code}`).sort();
|
const got = allIssues(scan).map(x => `${x.where} ${x.issue.level} ${x.issue.code}`).sort();
|
||||||
expect(got).toEqual([
|
expect(got).toEqual([
|
||||||
|
|
|
||||||
|
|
@ -457,3 +457,14 @@ describe('config + scrub', () => {
|
||||||
expect(hits.map(h => h.rule).sort()).toEqual(['apple-id-like', 'email', 'ip-address', 'private-key']);
|
expect(hits.map(h => h.rule).sort()).toEqual(['apple-id-like', 'email', 'ip-address', 'private-key']);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('iap review screenshot size', () => {
|
||||||
|
const png = (w: number, h: number) => { const b = Buffer.alloc(33); b.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0); b.writeUInt32BE(13, 8); b.write('IHDR', 12); b.writeUInt32BE(w, 16); b.writeUInt32BE(h, 20); b[24] = 8; b[25] = 2; return b; };
|
||||||
|
test('only App Store screenshot sizes pass (1320 x 2706 was rejected by Apple with IMAGE_INCORRECT_DIMENSIONS)', async () => {
|
||||||
|
const { reviewShotProblem } = await import('../cli/apple/iap-review');
|
||||||
|
expect(reviewShotProblem(png(1320, 2706))).toContain('IMAGE_INCORRECT_DIMENSIONS');
|
||||||
|
expect(reviewShotProblem(png(1320, 2868))).toBeNull();
|
||||||
|
expect(reviewShotProblem(png(2796, 1290))).toBeNull(); // landscape
|
||||||
|
expect(reviewShotProblem(png(2064, 2752))).toBeNull(); // iPad 13"
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue