fix(icons): repair the FA5 generator and drop the 404 font references

generate-fa5-icons.php read fa-{brands,regular,solid}.svg from
webfonts/, but only woff/woff2 ship with the theme, so the generator
died on file_get_contents() and the committed fa5-icons.php could not
be regenerated from what the theme actually distributes.

Decode the style split from each shipped woff's cmap table instead.
The split has to come from the font: FA5 assigns different drawings to
the same codepoint per style, so fas/far/fab membership is unanswerable
from the CSS alone. Output is byte-identical to the committed catalog
(1001/151/456), so the picker is unaffected.

all.min.css also declared eot / eot?#iefix / ttf / svg fallbacks for all
three families while webfonts/ holds only woff2 + woff, so a browser
that stops at woff requested six files that do not exist. Add
tools/strip-fa5-legacy-fonts.mjs to keep the src: list to what ships;
it is idempotent and touches nothing but the @font-face blocks.
This commit is contained in:
kate522 committed 2026-11-01 11:52:14 +08:00
1 parent 9c70d7929a
commit 4740078135
4 files changed
+199 -44

No files matched your search

+31 -31
View File
@@ -1,5 +1,5 @@
{
"generated_at": "2026-10-29T05:44:00+00:00",
"generated_at": "2026-11-01T03:45:46+00:00",
"errors": [],
"warnings": [
"customPage tools-update section 'tools/update' not in PHP schema (ok if pure operational page)",
@@ -258,39 +258,39 @@
"entry": true,
"missing_chunks": [],
"chunks": [
"SchemaPage.BBTFBTmo.js",
"vendor-vue.AXlcobq-.js",
"FaIcon.Cta3HYOc.js",
"useCollapsibleItems.BqcC9pDK.js",
"vendor-draggable.CsbWt1CM.js",
"FaIconPicker.DJI1XtMq.js",
"SchemaPage.BM05qq7c.js",
"vendor-vue.CibbKclz.js",
"FaIcon.DB-L86Cm.js",
"useCollapsibleItems.B7EjDmsr.js",
"vendor-draggable.CJPlJ2VA.js",
"FaIconPicker.BFlucdpY.js",
"shared-api.GLIRMK1p.js",
"vendor-misc.DSSPvhm2.js",
"AksColorPicker.JO2GmxwS.js",
"sortable-options.Do4PkQoR.js",
"vendor-misc.DkFG_sHo.js",
"AksColorPicker.YAbprujg.js",
"sortable-options.eXkhlrfL.js",
"level.E3ANSDAX.js",
"badge.ClviT45t.js",
"vendor-naive.DgdCsaiA.js",
"DeferredPage.CDpa6_lq.js",
"NativeOpsRedirect.CD8j4uaH.js",
"FloatingButtonsSettings.BI3xnao1.js",
"PageHeader.C1t645NL.js",
"FooterTabbarSettings.DcDH4CdV.js",
"PostPageSettings.CIkb2bLS.js",
"CommentSettings.d47RErzk.js",
"PermissionsCapabilities.eEUosHCJ.js",
"CmsCredits.DUise9Hl.js",
"ThemeInfoPage.DuqoCync.js",
"ThemeAuthorizationPage.BDGht6JA.js",
"DocsPage.CBhfO0JX.js",
"UsersVerify.CWq6m0ZY.js",
"UsersLevel.BnvrTSj0.js",
"UsersBadge.Cv_yOzWA.js",
"UsersWechatTemplate.BGKwGvbY.js",
"UsersTicket.B_nhzy9S.js",
"ToolsImportExport.CuVI1mrN.js",
"ToolsHealth.BT7gJFVm.js",
"ToolsUpdate.59iH8s4m.js"
"vendor-naive.Dfu2WQKq.js",
"DeferredPage.DbbPIOR7.js",
"NativeOpsRedirect.GFQhzjCJ.js",
"FloatingButtonsSettings.DYWR59AW.js",
"PageHeader.UHsfBDVL.js",
"FooterTabbarSettings.D8ujMgd9.js",
"PostPageSettings.Bhei4Dk4.js",
"CommentSettings.Ct-HES9S.js",
"PermissionsCapabilities.DXXFzINq.js",
"CmsCredits.DESOnIkP.js",
"ThemeInfoPage.D5AogccB.js",
"ThemeAuthorizationPage.MnnPj70n.js",
"DocsPage.UUs_OZP9.js",
"UsersVerify.Dab-auoO.js",
"UsersLevel.B-jXEukF.js",
"UsersBadge.DVCEC3QE.js",
"UsersWechatTemplate.DHoNsqm_.js",
"UsersTicket.DcwmQE5D.js",
"ToolsImportExport.C-XhCKwl.js",
"ToolsHealth.DNZ1YaWo.js",
"ToolsUpdate.38p6GYou.js"
]
}
}
+111 -12
View File
@@ -4,9 +4,14 @@
*
* Sources (shipped with the theme):
* - assets/fontawesome5/css/all.min.css → glyph class names + codepoints
* - assets/fontawesome5/webfonts/fa-*.svg → per-style glyph codepoints
* - assets/fontawesome5/webfonts/fa-*.woff → per-style codepoints (cmap table)
*
* Usage: php tools/generate-fa5-icons.php
*
* The style split comes from each font's own cmap subtable rather than from the
* CSS: FA5 assigns the same codepoint to different glyphs per style (e.g. far
* "address-book" and fas "address-book" are different drawings), so membership
* in fas / far / fab can only be answered by the font itself.
*/
defined('ABSPATH') || define('ABSPATH', __DIR__ . '/');
@@ -16,30 +21,122 @@ $css_path = $root . '/assets/fontawesome5/css/all.min.css';
$fonts_path = $root . '/assets/fontawesome5/webfonts';
$out_path = $root . '/src/Icons/fa5-icons.php';
/** Font file per style group, matching the FA5 family naming. */
const FA5_FONTS = [
'fas' => 'fa-solid-900.woff',
'far' => 'fa-regular-400.woff',
'fab' => 'fa-brands-400.woff',
];
/**
* Extract one table's uncompressed bytes from a WOFF container.
*
* WOFF stores each table zlib-deflated when compLen differs from origLen.
*/
function fa5_woff_table(string $raw, string $tag): ?string {
$num_tables = (int) (unpack('n', substr($raw, 12, 2))[1] ?? 0);
if ($num_tables < 1 || strlen($raw) < 44 + $num_tables * 20) {
return null;
}
for ($i = 0; $i < $num_tables; $i++) {
$entry = substr($raw, 44 + $i * 20, 20);
if (substr($entry, 0, 4) !== $tag) {
continue;
}
$p = unpack('Noffset/NcompLen/NorigLen', substr($entry, 4, 12));
$data = substr($raw, $p['offset'], $p['compLen']);
if ($p['compLen'] !== $p['origLen']) {
$data = gzuncompress($data);
if ($data === false) {
return null;
}
}
return $data;
}
return null;
}
/**
* Codepoints mapped by a cmap table, keyed for O(1) membership tests.
*
* Only format-4 (Unicode BMP) subtables are decoded — the (3,1) record is
* preferred, falling back to the first (3,x) then (0,x) record so a font that
* ships a different platform order still resolves.
*/
function fa5_cmap_codepoints(string $cmap): array {
$records = (int) (unpack('n', substr($cmap, 2, 2))[1] ?? 0);
$best = null;
$fallback = null;
for ($i = 0; $i < $records; $i++) {
$rec = unpack('nplatform/nencoding/Noffset', substr($cmap, 4 + $i * 8, 8));
if ($rec['platform'] === 3 && $rec['encoding'] === 1) {
$best = $rec['offset'];
break;
}
if ($fallback === null && ($rec['platform'] === 3 || $rec['platform'] === 0)) {
$fallback = $rec['offset'];
}
}
$offset = $best ?? $fallback;
if ($offset === null || $offset + 14 > strlen($cmap)) {
return [];
}
$table = substr($cmap, $offset);
$format = (int) (unpack('n', substr($table, 0, 2))[1] ?? 0);
if ($format !== 4) {
fwrite(STDERR, "Unsupported cmap format {$format}; only format 4 is decoded\n");
exit(1);
}
$seg_x2 = (int) (unpack('n', substr($table, 6, 2))[1] ?? 0);
$seg_count = intdiv($seg_x2, 2);
if ($seg_count < 1) {
return [];
}
$end_base = 14;
$start_base = $end_base + $seg_x2 + 2;
$codes = [];
for ($i = 0; $i < $seg_count; $i++) {
$start = (int) (unpack('n', substr($table, $start_base + $i * 2, 2))[1] ?? 0);
$end = (int) (unpack('n', substr($table, $end_base + $i * 2, 2))[1] ?? 0);
if ($start > $end || $end === 0xFFFF) {
continue;
}
for ($code = $start; $code <= $end; $code++) {
$codes[$code] = true;
}
}
return $codes;
}
$css = (string) file_get_contents($css_path);
// class name → codepoint (e.g. 'home' => 0xf015)
$name_to_code = [];
if (!preg_match_all('/\.fa-([a-z0-9-]+):before\{content:"\\\\([0-9a-f]{4})"\}/i', $css, $m, PREG_SET_ORDER)) {
fwrite(STDERR, "No glyph rules matched in all.min.css\n");
exit(1);
}
$name_to_code = [];
foreach ($m as $hit) {
$name_to_code[$hit[1]] = hexdec($hit[2]);
}
// style → set of codepoints, parsed from the SVG font files
$code_to_style = ['fas' => [], 'far' => [], 'fab' => []];
foreach (array_keys($code_to_style) as $style) {
$file = $fonts_path . '/fa-' . ($style === 'fab' ? 'brands-400' : ($style === 'far' ? 'regular-400' : 'solid-900')) . '.svg';
$src = (string) file_get_contents($file);
if (!preg_match_all('/<glyph[^>]*unicode="&#x([0-9a-f]+);"/i', $src, $g, PREG_SET_ORDER)) {
fwrite(STDERR, "No glyphs matched in {$file}\n");
// style → set of codepoints, decoded from the shipped woff cmaps
$code_to_style = [];
foreach (FA5_FONTS as $style => $file) {
$path = $fonts_path . '/' . $file;
if (!is_readable($path)) {
fwrite(STDERR, "Missing font: {$path}\n");
exit(1);
}
foreach ($g as $hit) {
$code_to_style[$style][hexdec($hit[1])] = true;
$cmap = fa5_woff_table((string) file_get_contents($path), 'cmap');
if ($cmap === null) {
fwrite(STDERR, "No readable cmap table in {$path}\n");
exit(1);
}
$code_to_style[$style] = fa5_cmap_codepoints($cmap);
}
$groups = ['fas' => [], 'far' => [], 'fab' => []];
@@ -72,7 +169,9 @@ defined('ABSPATH') || exit;
return {$export}
PHP;
file_put_contents($out_path, $php . ";\n");
// .gitattributes declares *.php eol=crlf for the working tree; emit CRLF so the
// regenerated file matches its neighbours instead of tripping the normalize warning.
file_put_contents($out_path, str_replace("\n", "\r\n", $php . ";\n"));
printf(
"fas=%d far=%d fab=%d (css glyph classes=%d)\nWrote %s\n",
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env node
/**
* Strip the font formats we do not ship from the bundled Font Awesome 5 CSS.
*
* assets/fontawesome5/webfonts only contains woff2 + woff, but all.min.css
* still advertises eot / ttf / svg fallbacks. A browser that stops at woff
* (IE11, older Safari) requests files that were never distributed, so each of
* the three styles 404s once per page load.
*
* The rewrite is scoped to @font-face src: declarations only — glyph rules,
* utilities and the license header are left untouched.
*/
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const target = join(root, 'assets/fontawesome5/css/all.min.css');
const css = readFileSync(target, 'utf8');
// Each @font-face carries two src statements: the IE-only eot shim
// (`src:url(...eot);`) and the formatted source list (`src:url(...),url(...)`).
// Match the whole run of consecutive src statements up to the closing brace so
// both dangling statements collapse into one clean list.
const SHIPPED = new Set(['woff2', 'woff']);
const srcRun = /(?:src:[^;{}]*(?:;[^;{}]*?)?)*(?=\})/gi;
const rewritten = css.replace(srcRun, (run) => {
// Only touch runs that are actually src declarations, not other properties.
if (!/^src:/.test(run)) return run;
const sources = [...run.matchAll(/url\(([^)]+)\)\s*(?:format\(["']?([a-z0-9-]+)["']?\))?/gi)]
.map(([, url, format]) => ({ url: url.trim(), format: (format || '').toLowerCase() }));
// Drop every source whose format we do not ship; a source with no format()
// is the eot shim, which no browser that loads this file can use.
const kept = sources.filter((s) => SHIPPED.has(s.format));
if (!kept.length) return run;
const declaration = `src:${kept.map((s) => `url(${s.url}) format("${s.format}")`).join(',')}`;
// Already clean: re-running the script must stay a no-op rather than a failure.
return declaration === run ? run : declaration;
});
const dropped = [...css.matchAll(/url\(([^)]*webfonts[^)]*)\)/g)]
.map((m) => m[1])
.filter((url) => !/\.woff2?(\?|\)|$)/.test(url));
const alreadyClean = rewritten === css;
if (!alreadyClean) writeFileSync(target, rewritten);
if (dropped.length) {
console.log(`dropped ${dropped.length} non-shipped font references: ${[...new Set(dropped)].join(', ')}`);
} else {
console.log('all.min.css already ships only woff2 + woff — nothing to do');
}