Skip to content

Commit 2c1ecf1

Browse files
committed
TEMPORARY, DO NOT MERGE: measure the fonts after sans-serif with more scripts
1 parent 0cf3e03 commit 2c1ecf1

2 files changed

Lines changed: 255 additions & 0 deletions

File tree

‎.github/tmp-font-probe/probe.mjs‎

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
// TEMPORARY, DO NOT MERGE: renders real Docusaurus pages with the font stacks of
2+
// meta/docusaurus#13148 (before) and of the stacked cleanup PR (after)
3+
// usage: node probe.mjs <label> <browsers, comma-separated> [locale]
4+
import fs from 'node:fs';
5+
import {chromium, firefox, webkit} from 'playwright-core';
6+
7+
const [label, browserList, locale = 'en-US'] = process.argv.slice(2);
8+
9+
const EMOJI = `'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'`;
10+
const MONO = `SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace`;
11+
const BEFORE_BASE = `system-ui, -apple-system, 'Segoe UI', Roboto, Ubuntu, Cantarell, 'Noto Sans', sans-serif, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, ${EMOJI}`;
12+
const BEFORE_MONO = MONO;
13+
const AFTER_BASE = `system-ui, -apple-system, 'Segoe UI', Roboto, Ubuntu, Cantarell, 'Noto Sans', sans-serif, ${EMOJI}`;
14+
const AFTER_MONO = MONO;
15+
16+
const css = (base, mono) =>
17+
`:root { --ifm-font-family-base: ${base} !important; --ifm-font-family-monospace: ${mono} !important; }`;
18+
const VARIANTS = {
19+
before: css(BEFORE_BASE, BEFORE_MONO),
20+
after: css(AFTER_BASE, AFTER_MONO),
21+
keepArial: css(`system-ui, -apple-system, 'Segoe UI', Roboto, Ubuntu, Cantarell, 'Noto Sans', sans-serif, Arial, ${EMOJI}`, AFTER_MONO),
22+
};
23+
24+
const PAGES = [
25+
{
26+
id: 'scripts',
27+
url: 'https://docusaurus.io/docs/installation',
28+
inject: '<div id="probe-scripts"><p id="s-ar" lang="ar">العربية: دوكوسورس يساعدك على بناء مواقع التوثيق بسرعة</p><p id="s-fa" lang="fa">فارسی: داکوسوروس به شما کمک می‌کند</p><p id="s-he" lang="he">עברית: דוקוסאורוס עוזר לך לבנות אתרי תיעוד</p><p id="s-ru" lang="ru">Русский: Docusaurus помогает быстро создавать сайты</p><p id="s-el" lang="el">Ελληνικά: Το Docusaurus σας βοηθά να φτιάξετε ιστότοπους</p><p id="s-vi" lang="vi">Tiếng Việt: Docusaurus giúp bạn xây dựng trang tài liệu</p><p id="s-th" lang="th">ไทย: Docusaurus ช่วยให้คุณสร้างเว็บไซต์เอกสาร</p><p id="s-hi" lang="hi">हिन्दी: डॉक्यूसॉरस आपको दस्तावेज़ साइटें बनाने में मदद करता है</p><p id="s-hy" lang="hy">Հայերեն: Docusaurus-ը օգնում է</p><p id="s-ka" lang="ka">ქართული: Docusaurus გეხმარებათ</p><p id="s-und" lang="und">Symbols: ← → ↑ ✓ ✔ ★ ☆ ♥ © ® ™ € £ ¥ § ¶ † ‡ • … ½ ∞ ≠ ≤ ≥ ∑ √ ⌘ ⌥ ⇧ ⏎ ₹ ₽ ₺ ₩ ﷼</p></div>',
29+
selectors: ['#s-ar', '#s-fa', '#s-he', '#s-ru', '#s-el', '#s-vi', '#s-th', '#s-hi', '#s-hy', '#s-ka', '#s-und'],
30+
clip: '#probe-scripts',
31+
},
32+
];
33+
34+
const LATIN_CANDIDATES = [
35+
'system-ui', '-apple-system', 'BlinkMacSystemFont', 'sans-serif', 'monospace', 'ui-monospace',
36+
"'Segoe UI'", "'Yu Gothic'", 'Meiryo', "'Microsoft YaHei'", 'Arial', 'Helvetica', "'Helvetica Neue'",
37+
"'Liberation Sans'", "'DejaVu Sans'", "'Ubuntu Sans'", 'Ubuntu', "'Adwaita Sans'", 'Cantarell', "'Noto Sans'",
38+
'Roboto', 'SFMono-Regular', "'SF Mono'", 'Menlo', 'Monaco', 'Consolas', "'Liberation Mono'", "'DejaVu Sans Mono'",
39+
"'Courier New'",
40+
];
41+
42+
const headless = process.platform !== 'linux';
43+
const BROWSERS = {
44+
chrome: () => chromium.launch({channel: 'chrome', headless, args: [`--lang=${locale}`]}),
45+
msedge: () => chromium.launch({channel: 'msedge', headless, args: [`--lang=${locale}`]}),
46+
firefox: () => firefox.launch({headless}),
47+
webkit: () => webkit.launch({headless}),
48+
};
49+
50+
// Non-Chromium browsers have no API for the rendered font: compare the width of a Latin sample
51+
// with the width it gets in each installed candidate font
52+
async function guessLatinFonts(page, selector) {
53+
return page.evaluate(
54+
({selector, candidates}) => {
55+
const el = document.querySelector(selector);
56+
if (!el) return null;
57+
const sample = 'The quick brown fox jumps over the lazy dog 0123456789 {}[]();';
58+
const measure = (parent, family) => {
59+
const span = document.createElement('span');
60+
span.textContent = sample;
61+
span.style.cssText = `white-space:nowrap;position:absolute;visibility:hidden;${family ? `font-family:${family}` : ''}`;
62+
parent.appendChild(span);
63+
const width = span.getBoundingClientRect().width;
64+
span.remove();
65+
return width;
66+
};
67+
const target = measure(el);
68+
const fallback = measure(el, 'fantasy');
69+
return candidates.filter((family) => {
70+
const width = measure(el, `${family}, fantasy`);
71+
const installed = width !== fallback;
72+
return installed && Math.abs(width - target) < 0.5;
73+
});
74+
},
75+
{selector, candidates: LATIN_CANDIDATES},
76+
);
77+
}
78+
79+
async function chromiumFonts(cdp, selector) {
80+
const {root} = await cdp.send('DOM.getDocument', {depth: -1});
81+
const {nodeIds} = await cdp.send('DOM.querySelectorAll', {nodeId: root.nodeId, selector});
82+
const results = [];
83+
for (const nodeId of nodeIds.slice(0, 3)) {
84+
const {fonts} = await cdp.send('CSS.getPlatformFontsForNode', {nodeId});
85+
results.push(fonts.map((f) => `${f.familyName}(${f.glyphCount})`).join(' + ') || '-');
86+
}
87+
return results;
88+
}
89+
90+
const report = [];
91+
for (const name of browserList.split(',')) {
92+
let browser;
93+
try {
94+
browser = await BROWSERS[name]();
95+
} catch (err) {
96+
console.log(`${name}: cannot launch (${err.message.split('\n')[0]})`);
97+
continue;
98+
}
99+
const context = await browser.newContext({locale, viewport: {width: 1000, height: 900}, reducedMotion: 'reduce'});
100+
const page = await context.newPage();
101+
console.log(`\n## ${label} / ${name} ${browser.version()} / locale ${locale}`);
102+
for (const {id, url, htmlLang, selectors, fullPage, scrollTo, inject, clip} of PAGES) {
103+
try {
104+
await page.goto(url, {waitUntil: 'networkidle', timeout: 60_000});
105+
} catch (err) {
106+
console.log(`${id}: cannot load (${err.message.split('\n')[0]})`);
107+
continue;
108+
}
109+
if (htmlLang) await page.evaluate((lang) => (document.documentElement.lang = lang), htmlLang);
110+
if (inject) await page.evaluate((html) => document.querySelector('article').insertAdjacentHTML('afterbegin', html), inject);
111+
for (const [variant, variantCss] of Object.entries(VARIANTS)) {
112+
await page.evaluate((variantCss) => {
113+
document.getElementById('probe-style')?.remove();
114+
const style = document.createElement('style');
115+
style.id = 'probe-style';
116+
style.textContent = variantCss;
117+
document.head.appendChild(style);
118+
}, variantCss);
119+
await page.evaluate(() => document.fonts.ready);
120+
if (scrollTo) await page.evaluate((s) => document.querySelector(s)?.scrollIntoView({block: 'start'}), scrollTo);
121+
await page.waitForTimeout(300);
122+
const file = `${label}-${name}-${id}-${variant}.png`;
123+
if (clip) await page.locator(clip).screenshot({path: file});
124+
else await page.screenshot({path: file, fullPage});
125+
console.log(`\n### ${id} / ${variant} (${file})`);
126+
const cdp = !['firefox', 'webkit'].includes(name) ? await context.newCDPSession(page) : null;
127+
if (cdp) {
128+
await cdp.send('DOM.enable');
129+
await cdp.send('CSS.enable');
130+
}
131+
for (const selector of selectors) {
132+
const fonts = cdp ? await chromiumFonts(cdp, selector) : [await guessLatinFonts(page, selector)];
133+
console.log(`${selector.padEnd(30)} ${fonts.map((f) => (Array.isArray(f) ? `latin≈[${f.join(', ')}]` : f)).join(' | ')}`);
134+
report.push({label, browser: name, page: id, variant, selector, fonts});
135+
}
136+
await cdp?.detach();
137+
}
138+
}
139+
await browser.close();
140+
}
141+
fs.appendFileSync('report.json', report.map((r) => JSON.stringify(r)).join('\n') + '\n');
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# TEMPORARY, DO NOT MERGE: screenshots of the font stacks of main without the fonts after sans-serif, scripts
2+
name: TMP font screenshots
3+
4+
on:
5+
push:
6+
branches: [claude/tmp-font-probe]
7+
8+
permissions:
9+
contents: read
10+
11+
jobs:
12+
probe:
13+
strategy:
14+
fail-fast: false
15+
matrix:
16+
include:
17+
- {os: ubuntu-24.04, fonts: ubuntu}
18+
- {os: ubuntu-24.04, fonts: bare}
19+
- {os: windows-latest, fonts: windows}
20+
- {os: macos-latest, fonts: macos}
21+
runs-on: ${{ matrix.os }}
22+
steps:
23+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
24+
with:
25+
persist-credentials: false
26+
27+
- name: Set up Node.js
28+
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
29+
with:
30+
node-version: lts/*
31+
32+
- name: Install probe
33+
shell: bash
34+
run: |
35+
mkdir -p "$RUNNER_TEMP/probe" && cp .github/tmp-font-probe/probe.mjs "$RUNNER_TEMP/probe/"
36+
cd "$RUNNER_TEMP/probe"
37+
npm init -y > /dev/null
38+
npm install --no-audit --no-fund playwright-core@1.63.0 > /dev/null
39+
40+
- name: Linux
41+
if: runner.os == 'Linux'
42+
env:
43+
FONTS: ${{ matrix.fonts }}
44+
run: |
45+
cd "$RUNNER_TEMP/probe"
46+
sudo apt-get update > /dev/null
47+
npx playwright-core install --with-deps chromium firefox > /dev/null
48+
# bare: only the fonts of the Playwright dependencies, like Argos
49+
case "$FONTS" in
50+
ubuntu) pkgs='xvfb fonts-ubuntu fonts-noto-core fonts-noto-cjk fonts-noto-color-emoji' ;;
51+
ubuntu-roboto) pkgs='xvfb fonts-ubuntu fonts-noto-core fonts-noto-cjk fonts-noto-color-emoji fonts-roboto' ;;
52+
fedora) pkgs='xvfb fonts-cantarell fonts-noto-core fonts-noto-cjk fonts-noto-color-emoji' ;;
53+
kde) pkgs='xvfb fonts-noto-core fonts-noto-cjk fonts-noto-color-emoji' ;;
54+
bare) pkgs='xvfb' ;;
55+
esac
56+
sudo apt-get install -y $pkgs > /dev/null
57+
if [ "$FONTS" = fedora ]; then
58+
curl -sSL https://download.gnome.org/sources/adwaita-fonts/48/adwaita-fonts-48.2.tar.xz | tar -xJ -C "$RUNNER_TEMP"
59+
mkdir -p ~/.local/share/fonts && find "$RUNNER_TEMP"/adwaita-fonts-48.2 -name '*.ttf' -exec cp {} ~/.local/share/fonts/ \;
60+
fc-cache -f > /dev/null
61+
fi
62+
fc-list : family | grep -iE 'adwaita|ubuntu|cantarell|roboto|noto sans($|,)|noto color emoji|dejavu sans|liberation|helvetica' | sort -u
63+
fc-match 'Helvetica Neue'; fc-match Arial; fc-match sans-serif; fc-match monospace
64+
google-chrome --version || true
65+
xvfb-run -a node probe.mjs "linux-$FONTS" chrome,firefox
66+
67+
- name: macOS
68+
if: runner.os == 'macOS'
69+
run: |
70+
cd "$RUNNER_TEMP/probe"
71+
npx playwright-core install firefox webkit > /dev/null
72+
fc-list : family 2>/dev/null | grep -i 'sf mono' || true
73+
ls /System/Library/Fonts | grep -i mono || true
74+
node probe.mjs macos chrome,msedge,firefox,webkit
75+
76+
- name: Windows
77+
if: runner.os == 'Windows'
78+
shell: pwsh
79+
run: |
80+
cd "$env:RUNNER_TEMP/probe"
81+
npx playwright-core install firefox | Out-Null
82+
Add-Type -TypeDefinition @"
83+
using System;
84+
using System.Runtime.InteropServices;
85+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
86+
public struct LOGFONT { public int lfHeight; public int lfWidth; public int lfEscapement; public int lfOrientation; public int lfWeight; public byte lfItalic; public byte lfUnderline; public byte lfStrikeOut; public byte lfCharSet; public byte lfOutPrecision; public byte lfClipPrecision; public byte lfQuality; public byte lfPitchAndFamily; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string lfFaceName; }
87+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
88+
public struct NONCLIENTMETRICS { public int cbSize; public int iBorderWidth; public int iScrollWidth; public int iScrollHeight; public int iCaptionWidth; public int iCaptionHeight; public LOGFONT lfCaptionFont; public int iSmCaptionWidth; public int iSmCaptionHeight; public LOGFONT lfSmCaptionFont; public int iMenuWidth; public int iMenuHeight; public LOGFONT lfMenuFont; public LOGFONT lfStatusFont; public LOGFONT lfMessageFont; public int iPaddedBorderWidth; }
89+
public static class Ncm {
90+
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
91+
static extern bool SystemParametersInfo(uint action, uint param, ref NONCLIENTMETRICS ncm, uint winIni);
92+
static NONCLIENTMETRICS Read() { var n = new NONCLIENTMETRICS(); n.cbSize = Marshal.SizeOf(n); SystemParametersInfo(0x29, (uint)n.cbSize, ref n, 0); return n; }
93+
public static string Get() { var n = Read(); return n.lfMenuFont.lfFaceName + " / " + n.lfMessageFont.lfFaceName; }
94+
public static bool Set(string face) { var n = Read(); n.lfMenuFont.lfFaceName = face; n.lfMessageFont.lfFaceName = face; n.lfStatusFont.lfFaceName = face; n.lfCaptionFont.lfFaceName = face; n.lfSmCaptionFont.lfFaceName = face; return SystemParametersInfo(0x2A, (uint)n.cbSize, ref n, 3); }
95+
}
96+
"@
97+
Write-Output "Menu / message fonts: $([Ncm]::Get())"
98+
node probe.mjs windows-english chrome,msedge,firefox en-US
99+
# Simulates the display languages: Chrome, Edge and Firefox read system-ui from the menu font
100+
foreach ($setup in @(@('Yu Gothic UI', 'ja-JP'), @('Microsoft YaHei UI', 'zh-CN'), @('Microsoft JhengHei UI', 'zh-TW'), @('Malgun Gothic', 'ko-KR'))) {
101+
$ok = [Ncm]::Set($setup[0])
102+
Write-Output "`n::group::UI font $($setup[0]): $ok, now '$([Ncm]::Get())'"
103+
# node probe.mjs "windows-$($setup[1])" chrome,msedge,firefox $setup[1]
104+
Write-Output "::endgroup::"
105+
}
106+
107+
- name: Upload screenshots
108+
if: always()
109+
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
110+
with:
111+
name: font-screenshots-${{ matrix.fonts }}
112+
path: |
113+
${{ runner.temp }}/probe/*.png
114+
${{ runner.temp }}/probe/report.json

0 commit comments

Comments
 (0)