feat(webui): 重构 main.ts 模块化 + 字重映射编辑器完善

- main.ts 从 1039 行拆分为 material/constants/dom/slots/wght/apply/
  testFonts/home/navigation 等模块
- 字重映射区: 撤销/导出/导入/重置工具栏, 各模式实时预览,
  修改自动切自定义模式, 轴值对比标注, 按住并水平滑动才触发滑条
- 高级配置卡片默认收起, 映射行取消限高
- 首页捐赠新增爱发电入口 (am start 默认浏览器)
- fix(wght): Go XML 覆写用深度计数匹配嵌套 family, 整行替换避免
  重复缩进, 修复段被切掉导致无法开机的严重问题
This commit is contained in:
YuleBest committed 2026-08-09 04:29:12 +08:00
1 parent e5399789ed
commit 7a26d1aa76
17 files changed
+1716 -1089

No files matched your search

+88 -5
View File
@@ -79,21 +79,104 @@ func GenerateFamily(min, max, mode int, customMap map[int]int) string {
}
// 在完整 XML 中替换 sans-serif family 段; 未找到或 mode 0 时原样返回
// 通过深度计数匹配对应的 </family> (防止嵌套 family 误切), 并整行替换避免段首被重复缩进
func ApplyWghtMode(xml string, mode, min, max int, customMap map[int]int) string {
if mode == 0 {
return xml
}
startTag := `<family name="sans-serif">`
start := strings.Index(xml, startTag)
const startTag = `<family name="sans-serif">`
start := findFamilyStart(xml, startTag)
if start < 0 {
return xml
}
end := strings.Index(xml[start:], "</family>")
end := matchFamilyClose(xml, start+len(startTag))
if end < 0 {
return xml
}
end += start + len("</family>")
return xml[:start] + GenerateFamily(min, max, mode, customMap) + xml[end:]
// 整行替换 (含行首缩进与闭合标签后的换行), 保持与原有段一致的缩进
lineStart := start
for lineStart > 0 && xml[lineStart-1] != '\n' {
lineStart--
}
lineEnd := end
for lineEnd < len(xml) && xml[lineEnd] != '\n' {
lineEnd++
}
if lineEnd < len(xml) {
lineEnd++ // 吃掉换行
}
return xml[:lineStart] + GenerateFamily(min, max, mode, customMap) + "\n" + xml[lineEnd:]
}
// 查找 startTag 的位置 (跳过 XML 注释, 避免误匹配注释内的文本)
func findFamilyStart(xml, startTag string) int {
searchFrom := 0
for {
i := strings.Index(xml[searchFrom:], startTag)
if i < 0 {
return -1
}
i += searchFrom
open := strings.LastIndex(xml[:i], "<!--")
if open < 0 {
return i
}
if rel := strings.Index(xml[open:], "-->"); rel < 0 || open+rel+3 > i {
// 命中位置在注释内, 继续向后找
searchFrom = i + 1
continue
}
return i
}
}
// 从紧随 <family name="sans-serif"> 之后的位置开始, 找到配对的 </family> (含嵌套),
// 返回其结束位置 (含标签); 未找到返回 -1
func matchFamilyClose(xml string, start int) int {
depth := 1
i := start
for i < len(xml) {
// 跳过注释
if strings.HasPrefix(xml[i:], "<!--") {
if rel := strings.Index(xml[i:], "-->"); rel >= 0 {
i += rel + len("-->")
continue
}
}
// 找下一个 '<'
lt := strings.IndexByte(xml[i:], '<')
if lt < 0 {
return -1
}
i += lt
if strings.HasPrefix(xml[i:], "</family>") {
depth--
if depth == 0 {
return i + len("</family>")
}
i += len("</family>")
continue
}
if strings.HasPrefix(xml[i:], "<family") {
gt := strings.IndexByte(xml[i:], '>')
if gt < 0 {
return -1
}
// 自闭合 <family .../> 不增加嵌套深度
if xml[i+gt-1] != '/' {
depth++
}
i += gt + 1
continue
}
// 其他标签: 跳到 '>' 之后
gt := strings.IndexByte(xml[i:], '>')
if gt < 0 {
return -1
}
i += gt + 1
}
return -1
}
// 读取自定义映射文件 (每行 "weight axis")
+59
View File
@@ -98,3 +98,62 @@ func TestApplyWghtMode(t *testing.T) {
t.Error("mode=0 应原样返回")
}
}
// 段内有嵌套 family (如 sans-serif-black) 时, 必须配对正确的 </family>,
// 不能把嵌套段的闭合当成外层闭合导致尾部丢失 (曾导致无法开机)
func TestApplyWghtModeNestedFamily(t *testing.T) {
xml := "<?xml version=\"1.0\"?>\n<familyset>\n" +
" <!-- #ifdef OPLUS_FEATURE_FONT_FLIP -->\n" +
" <family name=\"sans-serif\">\n" +
" <family name=\"sans-serif-black\">\n" +
" <font weight=\"900\" style=\"normal\">Black.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"900\" />\n" +
" </font>\n" +
" </family>\n" +
" <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\" />\n" +
" </font>\n" +
" </family>\n" +
" <!-- #endif -->\n" +
" <family name=\"sans-serif-medium\">\n" +
" <font weight=\"500\" style=\"normal\">Medium.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"500\" />\n" +
" </font>\n" +
" </family>\n" +
"</familyset>\n"
replaced := ApplyWghtMode(xml, 2, 150, 700, nil)
// 后续的 sans-serif-medium 段必须完整保留 (嵌套闭合误配会导致其被切掉)
if !strings.Contains(replaced, `<family name="sans-serif-medium">`) {
t.Fatal("覆写后丢失了 sans-serif-medium 段")
}
if strings.Contains(replaced, `<family name="sans-serif-black">`) {
t.Error("sans-serif-black 嵌套段未随段替换被移除")
}
// 闭合标签数量应与开始标签数量一致 (结构完整)
open := strings.Count(replaced, "<family ")
closeN := strings.Count(replaced, "</family>")
if open != closeN {
t.Errorf("family 标签不平衡: open=%d close=%d\n%s", open, closeN, replaced)
}
if !strings.HasSuffix(replaced, "</familyset>\n") {
t.Errorf("文件末尾被破坏:\n%s", replaced)
}
}
// 段首不应被重复缩进 (原行缩进 + 生成段自带缩进)
func TestApplyWghtModeNoDoubleIndent(t *testing.T) {
xml := "<familyset>\n" +
" <family name=\"sans-serif\">\n" +
" <font weight=\"100\" style=\"normal\">SysFont-Regular.ttf\n" +
" <axis tag=\"wght\" stylevalue=\"100\" />\n" +
" </font>\n" +
" </family>\n" +
"</familyset>\n"
replaced := ApplyWghtMode(xml, 1, 100, 900, nil)
if strings.Contains(replaced, " <family name=\"sans-serif\">") {
t.Errorf("段首出现重复缩进 (8 空格):\n%s", replaced)
}
if !strings.Contains(replaced, " <family name=\"sans-serif\">") {
t.Errorf("段首应为 4 空格缩进:\n%s", replaced)
}
}
+80 -31
View File
@@ -50,9 +50,14 @@
</div>
<div class="home-entry-expand" id="donate-expand" hidden>
<div class="home-donate-note">感谢您的自愿捐献</div>
<button class="home-donate-item" id="donate-alipay">
<span class="home-donate-logo">支付宝</span>
</button>
<div class="home-donate-row">
<button class="home-donate-item" id="donate-alipay">
<span class="home-donate-logo">支付宝</span>
</button>
<button class="home-donate-item" id="donate-ifdian">
<span class="home-donate-logo">爱发电</span>
</button>
</div>
</div>
</md-elevated-card>
@@ -100,36 +105,64 @@
<main id="config-view" class="view view-config">
<div class="home-title">字体配置</div>
<!-- 高级配置 -->
<md-elevated-card class="wght-advanced">
<div class="wght-advanced-title">高级配置</div>
<div id="slots"></div>
<div class="wght-mode-row">
<div class="wght-mode-info">
<div class="wght-mode-title">字重覆写模式</div>
<div class="wght-mode-sub" id="wght-mode-sub">
可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置
</div>
</div>
<md-outlined-select id="wght-mode-select" label="覆写模式">
<md-select-option value="0" selected>不处理</md-select-option>
<md-select-option value="1">裁切粗细等级</md-select-option>
<md-select-option value="2">平均分配字重</md-select-option>
<md-select-option value="3">自定义映射</md-select-option>
</md-outlined-select>
<!-- 高级配置 (可折叠/展开) -->
<md-filled-card class="wght-advanced">
<div class="wght-advanced-header" id="wght-advanced-header">
<div class="wght-advanced-title">高级配置</div>
<md-icon class="wght-advanced-arrow">expand_more</md-icon>
</div>
<!-- 自定义字重映射 (模式=自定义映射时显示) -->
<div class="wght-map" id="wght-map" hidden>
<div class="wght-map-title">字重映射</div>
<div class="wght-map-sub">
设置每个字重等级对应的实际 wght 轴值 (字重等级 1-1000, 可增删)
<div class="wght-advanced-body">
<div class="wght-advanced-content">
<div class="wght-mode-row">
<div class="wght-mode-info">
<div class="wght-mode-title">字重覆写模式</div>
<div class="wght-mode-sub" id="wght-mode-sub">
可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置
</div>
</div>
<md-outlined-select id="wght-mode-select" label="覆写模式">
<md-select-option value="0" selected>不处理</md-select-option>
<md-select-option value="1">裁切粗细等级</md-select-option>
<md-select-option value="2">平均分配字重</md-select-option>
<md-select-option value="3">自定义映射</md-select-option>
</md-outlined-select>
</div>
<!-- 字重映射 (各模式实时预览, 修改即切为自定义) -->
<div class="wght-map" id="wght-map">
<div class="wght-map-inner">
<div class="wght-map-title">字重映射</div>
<div class="wght-map-sub">
各模式的实时映射结果 (字重等级 → wght 轴值),
修改任意值将自动切换为「自定义映射」
</div>
<div id="wght-map-rows"></div>
<div class="wght-map-footer">
<md-text-button id="wght-map-add" class="wght-map-add">
<md-icon slot="icon">add</md-icon>
新增映射
</md-text-button>
<div class="wght-map-toolbar">
<md-icon-button id="wght-map-undo" aria-label="撤销">
<md-icon>undo</md-icon>
</md-icon-button>
<md-icon-button id="wght-map-export" aria-label="导出映射">
<md-icon>file_upload</md-icon>
</md-icon-button>
<md-icon-button id="wght-map-import" aria-label="导入映射">
<md-icon>file_download</md-icon>
</md-icon-button>
<md-icon-button id="wght-map-reset" aria-label="重置映射">
<md-icon>restart_alt</md-icon>
</md-icon-button>
</div>
</div>
</div>
</div>
</div>
<div id="wght-map-rows"></div>
<md-text-button id="wght-map-add" class="wght-map-add">
<md-icon slot="icon">add</md-icon>
新增映射
</md-text-button>
</div>
<!-- 新增字重映射对话框 -->
@@ -150,9 +183,25 @@
<md-text-button id="wght-map-add-confirm">添加</md-text-button>
</div>
</md-dialog>
</md-elevated-card>
<div id="slots"></div>
<!-- 映射导入/导出对话框 (base64 JSON 文本) -->
<md-dialog id="wght-map-transfer-dialog">
<div slot="headline" id="wght-map-transfer-title">导出映射</div>
<div slot="content">
<div class="wght-map-transfer-note" id="wght-map-transfer-note"></div>
<textarea
id="wght-map-transfer-input"
class="wght-map-transfer-input"
rows="4"
spellcheck="false"
></textarea>
</div>
<div slot="actions">
<md-text-button id="wght-map-transfer-cancel">取消</md-text-button>
<md-text-button id="wght-map-transfer-confirm">关闭</md-text-button>
</div>
</md-dialog>
</md-filled-card>
</main>
<!-- 字体测试视图 -->
+84
View File
@@ -0,0 +1,84 @@
import { exec, shellQuote, toast } from './ksu';
import { copyFont, pickWghtRange, renderSlots, slots } from './slots';
import { applyWghtOverride, getSelectedWghtMode, writeWghtMode } from './wght';
import { invalidateTestFonts } from './testFonts';
import { applyBtn } from './dom';
import { FONTS_DIR } from './constants';
const logDialog = document.getElementById('log-dialog') as any;
const logContent = document.getElementById('log-content')!;
document.getElementById('log-close')?.addEventListener('click', () => {
logDialog.open = false;
});
async function apply() {
if (!slots.hans.path) return;
applyBtn.disabled = true;
renderSlots();
try {
// 字重范围覆写: 用 UI 当前模式 (持久化到 FONTS/wght-mode.txt), 仅当存在可变字体且模式非 0 时处理
const wghtMode = getSelectedWghtMode();
await writeWghtMode(wghtMode);
const wghtPick = pickWghtRange();
if (wghtMode !== 0 && wghtPick) {
// Go 程序自行读取 wght-map.txt (mode 3)
await applyWghtOverride(wghtMode, wghtPick.min, wghtPick.max);
}
// 启动加载的字体 path 即 FONT/ 内的文件, 无需再复制
if (slots.hans.path !== `${FONTS_DIR}/hans.ttf`) {
await copyFont(slots.hans.path, `${FONTS_DIR}/hans.ttf`);
}
if (slots.hant.path) {
if (slots.hant.path !== `${FONTS_DIR}/hant.ttf`) {
await copyFont(slots.hant.path, `${FONTS_DIR}/hant.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/hant.ttf`)}`);
}
if (slots.en.path) {
if (slots.en.path !== `${FONTS_DIR}/en.ttf`) {
await copyFont(slots.en.path, `${FONTS_DIR}/en.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/en.ttf`)}`);
}
if (slots.mono.path) {
if (slots.mono.path !== `${FONTS_DIR}/mono.ttf`) {
await copyFont(slots.mono.path, `${FONTS_DIR}/mono.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/mono.ttf`)}`);
}
if (slots.emoji.path) {
if (slots.emoji.path !== `${FONTS_DIR}/emoji.ttf`) {
await copyFont(slots.emoji.path, `${FONTS_DIR}/emoji.ttf`);
}
} else {
await exec(`rm -f ${shellQuote(`${FONTS_DIR}/emoji.ttf`)}`);
}
const { errno, stdout, stderr } = await exec('sh /data/adb/modules/FontMM/apply.sh');
if (errno !== 0) throw new Error(stderr || 'apply.sh 执行失败');
if (logContent && logDialog) {
logContent.textContent = stdout;
logDialog.open = true;
}
toast('字体已应用,重启后生效');
// 字体已变化: 下次进入测试页时重新加载
invalidateTestFonts();
} catch (e) {
toast(`应用失败: ${String(e)}`);
} finally {
applyBtn.disabled = false;
renderSlots();
}
}
applyBtn?.addEventListener('click', apply);
+13
View File
@@ -0,0 +1,13 @@
// 全局路径与外部链接常量
export const FONTS_DIR = '/data/adb/modules/FontMM/FONTS';
export const WEBROOT_DIR = '/data/adb/modules/FontMM/webroot';
export const TEST_FONT_DIR = `${WEBROOT_DIR}/fonts-test`;
// 覆写字体配置: 调用模块内置 Go 程序 fontmm-wght (本地读写全部 6 个 XML, 无命令长度限制)
export const WGHT_BIN = '/data/adb/modules/FontMM/tools/fontmm-wght';
// 捐献 (支付宝/爱发电) 与开发者主页 (浏览器) 链接
export const DONATE_ALIPAY_URI =
'alipays://platformapi/startapp?saId=10000007&qrcode=https://qr.alipay.com/2m615805eflrafv8ipc2p15';
export const ALIPAY_PKG = 'com.eg.android.AlipayGphone';
export const DONATE_IFDIAN_URL = 'https://www.ifdian.net/a/xiaoyule';
export const DEV_PROFILE_URL = 'https://github.com/YuleBest';
+3
View File
@@ -0,0 +1,3 @@
// 跨模块共享的 DOM 元素引用
export const applyBtn = document.getElementById('apply-btn') as HTMLButtonElement;
export const rebootBtn = document.getElementById('reboot-btn');
+36
View File
@@ -0,0 +1,36 @@
import { exec, shellQuote } from './ksu';
import { FONTS_DIR, TEST_FONT_DIR } from './constants';
// 复制 FONT/ 到 webroot/fonts-test, 供页面加载与名称解析
// (WebView 无法直接访问模块外部目录, 符号链接在真机也不可靠, 直接复制)
export async function ensureFontsCopy(): Promise<string[]> {
const copyCmd = [
`rm -rf '${TEST_FONT_DIR}'`,
`mkdir -p '${TEST_FONT_DIR}'`,
`cp -f '${FONTS_DIR}'/*.ttf '${TEST_FONT_DIR}'/ 2>/dev/null`,
].join('\n');
try {
const { errno } = await exec(copyCmd);
if (errno !== 0) return [];
} catch {
return [];
}
return listFontsDir();
}
// 列出 fonts-test/ 下的字体文件 (每行一个完整路径)
export async function listFontsDir(): Promise<string[]> {
try {
const { errno, stdout } = await exec(
`find ${shellQuote(TEST_FONT_DIR)} -maxdepth 1 -mindepth 1 -type f`,
);
if (errno !== 0) return [];
return stdout
.split('\n')
.map((s) => s.trim())
.filter(Boolean)
.map((p) => p.slice(p.lastIndexOf('/') + 1));
} catch {
return [];
}
}
+74
View File
@@ -0,0 +1,74 @@
import * as opentype from 'opentype.js';
export interface FontInfo {
name?: string;
sizeText?: string;
isVariable?: boolean;
wghtRange?: string;
}
// 从字体名称表提取 family name, 优先中文字体名
function extractFamilyName(font: any): string | null {
const pick = (table: any): string | null => {
if (!table) return null;
const family = table.fontFamily ?? table.fullName;
if (!family || typeof family !== 'object') return null;
for (const lang of ['zh-CN', 'zh-Hans', 'zh', 'zh-TW', 'zh-Hant', 'en', 'en-US']) {
if (typeof family[lang] === 'string' && family[lang]) return family[lang];
}
const first = Object.values(family).find((v) => typeof v === 'string' && v);
return first ? String(first) : null;
};
return pick(font.names?.windows) ?? pick(font.names?.macintosh);
}
// 可变字体时返回 wght 轴范围
function extractWghtRange(font: any): string | undefined {
const fvar = font?.tables?.fvar;
if (!fvar?.axes) return undefined;
const wght = fvar.axes.find((a: any) => a.tag === 'wght');
if (!wght) return undefined;
return `${Math.round(wght.minValue)}-${Math.round(wght.maxValue)}`;
}
// 读取 fonts-test/ 下字体文件的名称与大小 (WebView 仅能访问 webroot 内文件)
export async function readFontInfo(file: string): Promise<FontInfo> {
// dev 假数据: 模拟各槽位字体的名称/大小/可变标识
if (import.meta.env.DEV) {
const MOCK_FONT_INFO: Record<
string,
{ name: string; size: string; variable: boolean; wght?: string }
> = {
'hans.ttf': { name: 'HarmonyOS Sans SC', size: '13.5 MB', variable: true, wght: '100-900' },
'hant.ttf': { name: '源樣明體', size: '21.2 MB', variable: false },
'en.ttf': { name: 'Inter Variable', size: '0.8 MB', variable: true, wght: '200-700' },
'mono.ttf': { name: 'JetBrains Mono', size: '1.2 MB', variable: false },
'emoji.ttf': { name: 'Noto Color Emoji', size: '9.8 MB', variable: false },
};
const mock = MOCK_FONT_INFO[file];
return mock
? {
name: mock.name,
sizeText: mock.size,
isVariable: mock.variable,
wghtRange: mock.wght,
}
: {};
}
try {
const res = await fetch(`fonts-test/${file}`);
if (!res.ok) return {};
const buf = await res.arrayBuffer();
const font = opentype.parse(buf);
const name = extractFamilyName(font);
const sizeText = `${(buf.byteLength / 1024 / 1024).toFixed(1)} MB`;
return {
name: name ?? undefined,
sizeText,
isVariable: Boolean(font.tables?.fvar),
wghtRange: extractWghtRange(font),
};
} catch {
return {};
}
}
+102
View File
@@ -0,0 +1,102 @@
import { amStart, exec, getSystemInfo, moduleInfo } from './ksu';
import { rebootBtn } from './dom';
import { ALIPAY_PKG, DEV_PROFILE_URL, DONATE_ALIPAY_URI, DONATE_IFDIAN_URL } from './constants';
interface ModuleProp {
[key: string]: string;
}
// 解析 module.prop 风格文本 (key=value 每行一个)
function parseProp(text: string): ModuleProp {
const out: ModuleProp = {};
for (const line of text.split('\n')) {
const idx = line.indexOf('=');
if (idx > 0) {
const key = line.slice(0, idx).trim();
if (key) out[key] = line.slice(idx + 1).trim();
}
}
return out;
}
// 渲染主页: 模块状态 + 设备信息
export async function loadHome(): Promise<void> {
// 模块信息 (module.prop)
let prop: ModuleProp = {};
try {
prop = { ...prop, ...parseProp(moduleInfo()) };
} catch {
// dev 或 API 不可用时忽略, 走下方兜底
}
try {
const { errno, stdout } = await exec('cat /data/adb/modules/FontMM/module.prop');
if (errno === 0) prop = { ...prop, ...parseProp(stdout) };
} catch {
// 忽略读取失败
}
// 挂载状态与设备信息
const sys = await getSystemInfo();
const mounted = sys.fontCount > 0;
const set = (id: string, value: string) => {
const el = document.getElementById(id);
if (el) el.textContent = value;
};
set('home-status', mounted ? '已挂载字体' : '未挂载字体');
set('home-version', prop.version || '未知');
set('home-android-version', sys.androidVersion || '未知');
set('home-device-model', sys.deviceModel || '未知');
set('home-abi', sys.abi || '未知');
set('home-font-count', `${sys.fontCount} 个`);
// 元模块: /data/adb/metamodule 是符号链接, cat 可直接读取其 module.prop 的 name
try {
const { errno, stdout } = await exec('cat /data/adb/metamodule/module.prop');
if (errno === 0 && stdout.trim()) {
set('home-metamodule', parseProp(stdout).name || '未知');
} else {
set('home-metamodule', '未安装');
}
} catch {
set('home-metamodule', '未安装');
}
}
// 支付宝捐献: 必须在 WebUI 外打开 (am start), 否则 alipays 协议无法唤起
let donateOpen = false;
const donateExpand = document.getElementById('donate-expand')!;
const donateArrow = document.getElementById('donate-arrow')!;
document.getElementById('donate-entry')?.addEventListener('click', () => {
donateOpen = !donateOpen;
donateExpand.hidden = !donateOpen;
donateArrow.classList.toggle('expanded', donateOpen);
});
document.getElementById('donate-alipay')?.addEventListener('click', () => {
void amStart(DONATE_ALIPAY_URI, ALIPAY_PKG);
});
// 爱发电: 用系统默认浏览器打开 (am start)
document.getElementById('donate-ifdian')?.addEventListener('click', () => {
void amStart(DONATE_IFDIAN_URL);
});
// 开发者主页: 用系统默认浏览器打开 (am start, 避免在 WebView 内打开)
document.getElementById('dev-entry')?.addEventListener('click', () => {
void amStart(DEV_PROFILE_URL);
});
// 重启设备 (二次确认): dev 模式由 mockExec 模拟输出; 真机立即重启
const rebootDialog = document.getElementById('reboot-dialog') as any;
rebootBtn?.addEventListener('click', () => {
if (rebootDialog) rebootDialog.open = true;
});
document.getElementById('reboot-cancel')?.addEventListener('click', () => {
if (rebootDialog) rebootDialog.open = false;
});
document.getElementById('reboot-confirm')?.addEventListener('click', () => {
if (rebootDialog) rebootDialog.open = false;
void exec('sync; reboot');
});
+9 -1028
View File
File diff suppressed because it is too large. Load diff
+19
View File
@@ -0,0 +1,19 @@
import '@material/web/button/outlined-button.js';
import '@material/web/button/text-button.js';
import '@material/web/button/filled-button.js';
import '@material/web/iconbutton/icon-button.js';
import '@material/web/icon/icon.js';
import '@material/web/textfield/outlined-text-field.js';
import '@material/web/dialog/dialog.js';
import '@material/web/slider/slider.js';
import '@material/web/select/outlined-select.js';
import '@material/web/select/select-option.js';
import '@material/web/progress/linear-progress.js';
import '@material/web/labs/card/elevated-card.js';
import '@material/web/labs/card/filled-card.js';
import '@material/web/labs/navigationbar/navigation-bar.js';
import '@material/web/labs/navigationtab/navigation-tab.js';
import 'material-symbols/outlined.css';
import './theme.scss';
import './style.scss';
+85
View File
@@ -0,0 +1,85 @@
import { slots } from './slots';
import { loadHome } from './home';
import { loadTestFonts } from './testFonts';
import { applyBtn, rebootBtn } from './dom';
// ---------------- 导航与视图切换 ----------------
const homeView = document.getElementById('home-view')!;
const configView = document.getElementById('config-view')!;
const testView = document.getElementById('test-view')!;
const toolsView = document.getElementById('tools-view')!;
const views = [homeView, configView, testView, toolsView];
const navBar = document.getElementById('nav-bar') as any;
// 悬浮应用按钮 (与配置页绑定, 仅配置页显示)
const applyFab = applyBtn;
// 滑动视图轨道
const viewTrack = document.getElementById('view-track')!;
let currentIndex = 0;
// 顶栏滚动标题: 各页标题元素与相对偏移 (标题中心移出视口顶部时固定在顶栏)
const topBarTitle = document.getElementById('top-bar-title')!;
const pageTitleEls = Array.from(document.querySelectorAll<HTMLElement>('.home-title'));
const titleOffsets = views.map((view, i) => {
const el = pageTitleEls[i];
if (!el) return 0;
return el.getBoundingClientRect().top - view.getBoundingClientRect().top + view.scrollTop;
});
// 视口 pager: 轨道高度 = 视口 - 顶栏 (显式计算, 避免依赖 vh/dvh/flex 解析)
function updateTrackHeight() {
const topBar = document.querySelector<HTMLElement>('.top-app-bar');
const h = window.innerHeight - (topBar?.offsetHeight ?? 64);
viewTrack.style.height = `${Math.max(0, h)}px`;
}
updateTrackHeight();
window.addEventListener('resize', updateTrackHeight);
window.addEventListener('orientationchange', () => setTimeout(updateTrackHeight, 100));
function showView(index: number) {
const target = Math.max(0, Math.min(views.length - 1, index));
currentIndex = target;
views.forEach((v, i) => v.classList.toggle('active', i === target));
// 轨道滑动切换动画
viewTrack.style.transform = `translateX(${-target * 100}%)`;
// 悬浮应用按钮仅配置页显示, 且未选简体字体时不展示
applyFab.style.display = target === 1 && slots.hans.path ? '' : 'none';
// 重启按钮仅主页显示 (visibility 保持顶栏布局不跳动)
if (rebootBtn) rebootBtn.style.visibility = target === 0 ? 'visible' : 'hidden';
// 同步底部导航高亮
if (navBar) navBar.activeIndex = target;
// 每页独立滚动, 切换后回到该页顶部
views[target].scrollTop = 0;
// 顶栏标题: 切换页时更新文字, 并回到未滚动状态 (标题在内容区显示)
topBarTitle.textContent = pageTitleEls[target]?.textContent ?? '';
document.body.classList.remove('title-scrolled');
if (target === 0) loadHome();
if (target === 2) loadTestFonts();
}
// 悬浮按钮滚动隐藏: 向下滚动移出视口, 向上滚动出现 (每页独立滚动)
views.forEach((view, i) => {
let lastY = 0;
view.addEventListener(
'scroll',
() => {
const y = view.scrollTop;
if (y > lastY + 4) applyFab.classList.add('fab-hidden');
else if (y < lastY - 4) applyFab.classList.remove('fab-hidden');
lastY = y;
// 顶栏标题: 当前页标题中心移出视口顶部时固定在顶栏
if (view === views[currentIndex] && pageTitleEls[i]) {
const titleCenter = titleOffsets[i] + pageTitleEls[i].offsetHeight / 2;
document.body.classList.toggle('title-scrolled', y > titleCenter);
}
},
{ passive: true },
);
});
navBar?.addEventListener('navigation-bar-activated', (e: { detail: { activeIndex: number } }) => {
showView(e.detail.activeIndex);
});
// 初始加载主页
void loadHome();
+211
View File
@@ -0,0 +1,211 @@
import { FontFilePicker } from './fontPicker';
import { exec, shellQuote } from './ksu';
import { readFontInfo } from './fontInfo';
import { ensureFontsCopy } from './fontFiles';
import { FONTS_DIR, TEST_FONT_DIR } from './constants';
import { applyBtn } from './dom';
import type { FontSlot } from './types';
export const SLOT_KEYS = ['hans', 'hant', 'en', 'mono', 'emoji'] as const;
export type SlotKey = (typeof SLOT_KEYS)[number];
export const slots: Record<SlotKey, FontSlot> = {
hans: {
key: 'hans',
title: '中文简体',
path: null,
fileName: '',
},
hant: {
key: 'hant',
title: '中文繁体',
path: null,
fileName: '',
},
en: {
key: 'en',
title: '英文 & 数字',
path: null,
fileName: '',
},
mono: {
key: 'mono',
title: '等宽字体',
path: null,
fileName: '',
},
emoji: {
key: 'emoji',
title: 'Emoji 表情',
path: null,
fileName: '',
},
};
const slotsEl = document.getElementById('slots')!;
// 字重覆写模式选择 (声明提前: renderSlots 首轮调用会访问)
const wghtModeSelect = document.getElementById('wght-mode-select') as any;
const wghtModeSub = document.getElementById('wght-mode-sub');
let pickingKey: SlotKey = 'hans';
const picker = new FontFilePicker((path, name) => {
const slot = slots[pickingKey];
slot.path = path;
slot.fileName = name;
renderSlots();
void refreshSlotInfo(slot);
});
// 未选择时的占位文案: 回退可视化 (WYSIWYG)
function slotPlaceholder(slot: FontSlot): string {
if (slot.path) return slot.fileName;
if (slot.key === 'hans') return '未选择字体文件';
if (slots.hans.path) {
if (slot.key === 'mono') return '未选择,保持系统等宽字体';
if (slot.key === 'emoji') return '未选择,保持系统 Emoji';
return `默认使用:${slots.hans.fileName}`;
}
return '未选择字体文件';
}
// 根据是否有可变字体决定是否禁用字重覆写 (emoji/mono 不计入)
export function updateWghtModeDisabled(): void {
const hasVar = ['hans', 'hant', 'en'].some((k) => slots[k as 'hans']?.isVariable);
if (wghtModeSelect) wghtModeSelect.disabled = !hasVar;
if (wghtModeSub) {
wghtModeSub.textContent = hasVar
? '可变字体 wght 范围与实际字重等级不符时, 按所选方式覆写 sans-serif 配置'
: '当前未选择可变字体 (中文/繁体/英文), 此功能不可用';
}
}
export function renderSlots() {
slotsEl.innerHTML = Object.values(slots)
.map((slot) => {
// 选了其他槽位但未选简体时, 简体卡片提示"必选"
const required =
slot.key === 'hans' &&
!slot.path &&
Object.values(slots).some((s) => s.key !== 'hans' && s.path);
const nameText = required ? '未选择字体,此项为必选项' : slotPlaceholder(slot);
// 扩展名大写 (TTF/OTF...), 从源文件路径动态提取, 不硬编码
const ext = slot.path ? (slot.path.split('.').pop() ?? '').toUpperCase() : '';
return `
<md-filled-card class="slot-card ${slot.key === 'hans' ? 'slot-hans' : ''} ${slot.path ? 'selected' : ''}" data-key="${slot.key}">
<div class="slot-header">
<div class="slot-title-group">
<span class="slot-title">${slot.title}</span>
</div>
<md-icon class="slot-arrow">chevron_right</md-icon>
</div>
<div class="slot-file">
${
slot.path
? `<md-icon-button class="slot-clear" data-key="${slot.key}" aria-label="取消选择">
<md-icon>close</md-icon>
</md-icon-button>`
: ''
}
<div class="slot-file-text">
<div class="slot-name ${!slot.path ? 'placeholder' : ''} ${required ? 'required' : ''}">${nameText}</div>
${
slot.path
? `<div class="slot-meta"><span class="slot-meta-badge">${slot.sizeText || '…'}</span>${ext ? `<span class="slot-meta-badge">${ext}</span>` : ''}${slot.isVariable ? `<span class="slot-meta-badge slot-meta-badge--variable">可变字体${slot.wghtRange ? ` ${slot.wghtRange}` : ''}</span>` : ''}</div>`
: ''
}
</div>
</div>
</md-filled-card>
`;
})
.join('');
// 绑定事件: 整卡点击选择字体
slotsEl.querySelectorAll<HTMLElement>('.slot-card').forEach((card) => {
card.addEventListener('click', () => {
pickingKey = card.dataset.key as SlotKey;
picker.show();
});
});
slotsEl.querySelectorAll<HTMLElement>('.slot-clear').forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation(); // 阻止冒泡触发卡片选择
const slot = slots[btn.dataset.key as SlotKey];
slot.path = null;
slot.fileName = '';
renderSlots();
});
});
if (applyBtn) {
// 未选择简体字体时直接隐藏按钮 (不做半透明禁用)
applyBtn.style.display = !slots.hans.path ? 'none' : '';
}
updateWghtModeDisabled();
// 通知其他模块 (如字重映射预览) 槽位已变化
document.dispatchEvent(new CustomEvent('slots-rendered'));
}
export async function copyFont(src: string, dest: string) {
const { errno, stderr } = await exec(`cp -f ${shellQuote(src)} ${shellQuote(dest)}`);
if (errno !== 0) throw new Error(`复制失败: ${stderr}`);
}
// 选择用于覆写的 wght 范围: 从 hans/hant/en 收集 (emoji/mono 除外), 取跨度最小者; 无可变返回 null
export function pickWghtRange(): { min: number; max: number } | null {
let best: { min: number; max: number } | null = null;
let bestSpan = Infinity;
for (const key of ['hans', 'hant', 'en'] as const) {
const r = slots[key]?.wghtRange;
if (!r) continue;
const m = r.match(/^(\d+)-(\d+)$/);
if (!m) continue;
const min = Number(m[1]);
const max = Number(m[2]);
const span = max - min;
if (span < bestSpan) {
bestSpan = span;
best = { min, max };
}
}
return best;
}
// 选择新字体后: 复制到 fonts-test 供解析, 更新卡片显示的名称/大小
async function refreshSlotInfo(slot: FontSlot) {
if (!slot.path) return;
try {
await exec(`cp -f ${shellQuote(slot.path)} ${shellQuote(`${TEST_FONT_DIR}/${slot.key}.ttf`)}`);
const info = await readFontInfo(`${slot.key}.ttf`);
if (info.name) slot.fileName = info.name;
if (info.sizeText) slot.sizeText = info.sizeText;
// 无条件同步: 防止换字体后旧的可变标记残留
slot.isVariable = Boolean(info.isVariable);
slot.wghtRange = info.wghtRange;
renderSlots();
} catch {
// 忽略解析失败, 保持选择器返回的文件名
}
}
// 打开 WebUI 时: 复制 FONT/ 到 fonts-test, 读取已有字体的名称/大小填充卡片
async function loadExistingFonts() {
const available = await ensureFontsCopy();
for (const key of SLOT_KEYS) {
const file = `${key}.ttf`;
if (!available.includes(file)) continue;
const slot = slots[key];
const info = await readFontInfo(file);
slot.path = `${FONTS_DIR}/${file}`;
slot.fileName = info.name ?? file;
if (info.sizeText) slot.sizeText = info.sizeText;
slot.isVariable = Boolean(info.isVariable);
slot.wghtRange = info.wghtRange;
}
renderSlots();
}
renderSlots();
void loadExistingFonts();
+173 -23
View File
@@ -451,12 +451,19 @@ md-dialog {
color: var(--md-sys-color-on-surface-variant);
}
.home-donate-row {
display: flex;
gap: 12px;
padding: 0 20px 18px;
}
.home-donate-item {
flex: 1;
display: flex;
align-items: center;
gap: 12px;
width: 100%;
padding: 12px 20px 18px calc(20px + 40px + 16px);
justify-content: center;
gap: 8px;
padding: 12px 16px;
border: none;
background: transparent;
cursor: pointer;
@@ -1144,22 +1151,74 @@ md-dialog {
// ---- 字重覆写模式选择 ----
// ---- 高级配置 (字重覆写 + 自定义映射) ----
// ---- 高级配置 (字重覆写 + 自定义映射, 可折叠) ----
// 与槽位卡片同为 filled-card 层级: 无阴影无边框
.wght-advanced {
margin-bottom: 16px;
padding: 16px;
--md-elevated-card-container-shape: var(--md-shape-corner-large);
display: block;
padding: 12px;
overflow: hidden;
margin: 16px 0 0;
--md-filled-card-container-color: var(--md-sys-color-surface-container-low);
--md-filled-card-container-shape: var(--md-shape-corner-large);
.wght-advanced-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
cursor: pointer;
user-select: none;
padding: 2px 0;
border-radius: var(--md-shape-corner-extra-small);
&:active {
opacity: 0.7;
}
}
.wght-advanced-title {
font-size: var(--md-sys-typescale-title-medium-size);
font-weight: var(--md-sys-typescale-title-medium-weight);
margin-bottom: 4px;
}
.wght-advanced-arrow {
flex-shrink: 0;
color: var(--md-sys-color-on-surface-variant);
transition: transform var(--md-duration-emphasized) var(--md-easing-emphasized);
}
&.collapsed {
// 收起态压缩底部留白, 整卡只留标题一行
padding-bottom: 8px;
.wght-advanced-arrow {
transform: rotate(-90deg);
}
.wght-advanced-body {
grid-template-rows: 0fr;
}
}
// 折叠动画: grid-rows 0fr->1fr, 内容由 overflow:hidden 裁剪
// 注意: 内容必须包在单个子元素里, 否则多余子项落入隐式 auto 行, 0fr 无法收起
.wght-advanced-body {
display: grid;
grid-template-rows: 1fr;
transition: grid-template-rows var(--md-duration-emphasized) var(--md-easing-emphasized);
> .wght-advanced-content {
min-height: 0;
overflow: hidden;
}
}
.wght-mode-row {
display: flex;
align-items: center;
gap: 12px;
// 与标题的间距放在首行 padding 上: 收起后随 0fr 一并裁剪
padding-top: 8px;
.wght-mode-info {
flex: 1;
@@ -1184,9 +1243,12 @@ md-dialog {
}
.wght-map {
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid var(--md-sys-color-outline-variant);
.wght-map-inner {
// 与上方模式选择的分隔线及间距 (置于内层, 折叠时可一并收起)
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid var(--md-sys-color-outline-variant);
}
.wght-map-title {
font-size: var(--md-sys-typescale-title-small-size);
@@ -1196,53 +1258,141 @@ md-dialog {
.wght-map-sub {
font-size: var(--md-sys-typescale-body-small-size);
color: var(--md-sys-color-on-surface-variant);
margin-bottom: 8px;
margin-bottom: 4px;
}
// 映射行列表: 不设限高, 全部行平铺显示
#wght-map-rows {
display: flex;
flex-direction: column;
gap: 2px;
}
.wght-map-row {
display: flex;
align-items: center;
gap: 8px;
padding: 2px 0;
padding: 0;
.wght-map-label {
flex-shrink: 0;
width: 28px;
width: 24px;
text-align: right;
font-size: var(--md-sys-typescale-body-small-size);
color: var(--md-sys-color-on-surface-variant);
}
md-slider {
.wght-map-slider {
position: relative;
flex: 1;
// 覆盖组件默认 min-inline-size: 200px, 适配手机窄屏
min-inline-size: 64px;
min-width: 64px;
}
// 手势覆盖层: 覆盖滑条, 按下不立即跳值, 水平滑动才激活调整
.wght-map-slider-overlay {
position: absolute;
inset: 0;
touch-action: none;
cursor: pointer;
}
md-slider {
display: block;
width: 100%;
// 覆盖组件默认 min-inline-size: 200px, 适配手机窄屏
min-inline-size: 0;
min-width: 0;
pointer-events: none;
// 压缩滑块高度 (默认触控区 40px, 9 行时过长)
--md-slider-n: 28px;
--md-slider-handle-height: 16px;
}
.wght-map-diff {
flex-shrink: 0;
min-width: 34px;
text-align: right;
font-size: var(--md-sys-typescale-body-small-size);
font-family: monospace;
color: var(--md-sys-color-on-surface-variant);
}
.wght-map-input {
flex-shrink: 0;
width: 64px;
width: 56px;
padding: 2px 0 2px 4px;
font-size: var(--md-sys-typescale-body-small-size);
}
.wght-map-del {
flex-shrink: 0;
width: 32px;
height: 32px;
--md-icon-button-state-layer-size: 32px;
width: 28px;
height: 28px;
--md-icon-button-state-layer-size: 28px;
md-icon {
font-size: 18px;
font-size: 16px;
}
}
}
.wght-map-add {
margin-top: 8px;
.wght-map-footer {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 4px;
.wght-map-add {
// 与按钮内联图标对齐
--md-text-button-icon-spacing: 4px;
}
.wght-map-toolbar {
display: flex;
gap: 2px;
md-icon-button {
// 与删除按钮同尺寸
width: 28px;
height: 28px;
--md-icon-button-state-layer-size: 28px;
md-icon {
font-size: 16px;
}
}
}
}
}
}
// 映射转移对话框: 说明文本 + base64 文本框
.wght-map-transfer-note {
font-size: var(--md-sys-typescale-body-small-size);
color: var(--md-sys-color-on-surface-variant);
margin-bottom: 8px;
}
.wght-map-transfer-input {
width: 100%;
box-sizing: border-box;
padding: 8px;
border: 1px solid var(--md-sys-color-outline-variant);
border-radius: 8px;
background: var(--md-sys-color-surface-container);
color: var(--md-sys-color-on-surface);
font-family: monospace;
font-size: 0.72rem;
line-height: 1.4;
resize: vertical;
outline: none;
&:focus {
border-color: var(--md-sys-color-primary);
}
}
// 字重映射输入框: 底线式 (顶层通用, 行内与新增弹窗共用)
.wght-map-input {
padding: 4px 0 4px 4px;
+190
View File
@@ -0,0 +1,190 @@
import { slots } from './slots';
import { listFontsDir } from './fontFiles';
import type { FontSlot } from './types';
const testStatusText = document.getElementById('test-status-text')!;
const testContent = document.getElementById('test-content')!;
type TestSlot = 'hans' | 'hant' | 'en';
const TEST_FONTS: { slot: TestSlot; file: string; family: string }[] = [
{ slot: 'hans', file: 'hans.ttf', family: 'FontMM-Hans' },
{ slot: 'hant', file: 'hant.ttf', family: 'FontMM-Hant' },
{ slot: 'en', file: 'en.ttf', family: 'FontMM-En' },
];
async function registerFont(family: string, file: string): Promise<boolean> {
try {
// 声明完整字重范围: 否则 FontFace 默认只覆盖 weight 400,
// CSS font-weight 100-900 将无法匹配到该字体 (真机表现: 100-400 无变化)
const font = new FontFace(family, `url('fonts-test/${file}')`, { weight: '100 900' });
await font.load();
document.fonts.add(font);
return true;
} catch {
return false;
}
}
// 测试页字体只加载一次 (进入时), 应用新字体后重置, 避免每次进入重复加载
let testLoaded = false;
// 字体已变化: 下次进入测试页时重新加载
export function invalidateTestFonts(): void {
testLoaded = false;
}
export async function loadTestFonts(): Promise<void> {
if (testLoaded) return;
testContent.hidden = true;
testStatusText.textContent = '正在加载字体...';
// 字体已在 WebUI 打开时复制到 fonts-test, 此处直接读取
const available = await listFontsDir();
// 注册字体, 记录每个槽位是否加载成功
const loaded = new Map<TestSlot, boolean>();
for (const tf of TEST_FONTS) {
loaded.set(
tf.slot,
available.includes(tf.file) ? await registerFont(tf.family, tf.file) : false,
);
}
// fallback 逻辑: hant/en 缺失回退 hans
const hans = loaded.get('hans') ? 'FontMM-Hans' : 'sans-serif';
const hant = loaded.get('hant') ? 'FontMM-Hant' : hans;
const en = loaded.get('en') ? 'FontMM-En' : hans;
// 显示字体名称 (解析出的 family name; 未解析到时为文件名)
const slotLabel = (key: TestSlot): string => slots[key].fileName;
const hasFont = (key: TestSlot): boolean => available.includes(`${key}.ttf`);
const hansLabel = hasFont('hans') ? slotLabel('hans') : null;
const setTag = (id: string, text: string) => {
const el = document.getElementById(id);
if (el) el.textContent = text;
};
setTag('hans-tag', hasFont('hans') ? slotLabel('hans') : '未设置, 使用系统字体');
setTag(
'hant-tag',
hasFont('hant') ? slotLabel('hant') : hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体',
);
setTag(
'en-tag',
hasFont('en') ? slotLabel('en') : hansLabel ? `回退 ${hansLabel}` : '未设置, 使用系统字体',
);
setTag('weight-tag', `使用 ${hansLabel ?? '系统字体'}`);
// 可变字体提示: 若所选字体为可变字体, 显示 wght 轴范围
const varSlot: FontSlot | null = slots.hans.isVariable ? slots.hans : null;
setTag(
'var-tag',
`使用 ${hansLabel ?? '系统字体'}${varSlot?.wghtRange ? ` (可变字体 wght ${varSlot.wghtRange})` : ''}`,
);
const setFamily = (id: string, family: string, fallback: string) => {
const el = document.getElementById(id);
if (el) el.style.fontFamily = `'${family}', ${fallback}`;
};
setFamily('test-hans', hans, 'sans-serif');
setFamily('test-hant', hant, `'${hans}', sans-serif`);
setFamily('test-en', en, `'${hans}', sans-serif`);
// 字重 / 可变字体测试: 用完整 fallback 链渲染 (Hans → Hant → En 按用户选择顺序,
// 浏览器逐字形回退, 所见即所得地体现系统真实 fallback)
const fallbackChain = [...new Set([hans, hant, en])].map((f) => `'${f}'`).join(', ');
const fullChain = `${fallbackChain}, sans-serif`;
document.querySelectorAll<HTMLElement>('.test-w-text').forEach((el) => {
el.style.fontFamily = fullChain;
});
const vp = document.getElementById('test-var-preview');
if (vp) vp.style.fontFamily = fullChain;
applyWght(400); // 与滑条初始值保持一致
testStatusText.textContent =
available.length === 0
? '未找到已设置的字体 (FONTS 为空), 当前使用系统字体预览'
: '字体已加载, 下方为预览效果 (按 fallback 逻辑)';
testContent.hidden = false;
testLoaded = true;
}
// 字重档位名称 (与字重测试区一致)
const WEIGHT_NAMES: Record<number, string> = {
100: '淡体 Thin',
200: '特细 ExtraLight',
300: '细体 Light',
400: '标准 Regular',
500: '适中 Medium',
600: '次粗 SemiBold',
700: '粗体 Bold',
800: '特粗 ExtraBold',
900: '浓体 Black',
};
// 可变字体滑动条: 滑动中只更新数值显示, 停止 250ms 后才应用字重 (省性能)
const wghtSlider = document.getElementById('wght-slider') as any;
const wghtValue = document.getElementById('wght-value')!;
const varPreview = document.getElementById('test-var-preview') as HTMLElement | null;
let wghtTimer: number | undefined;
function applyWght(weight: number) {
if (varPreview) varPreview.style.fontVariationSettings = `'wght' ${weight}`;
}
function updateVarPreview(weight: number) {
if (!varPreview) return;
const key = Math.round(weight / 100) * 100;
const name = WEIGHT_NAMES[key] ?? String(weight);
varPreview.textContent = `${weight} - ${name}`;
}
wghtSlider?.addEventListener('input', (e: Event) => {
const value = Number((e.target as any).value);
wghtValue.textContent = String(value);
updateVarPreview(value);
window.clearTimeout(wghtTimer);
wghtTimer = window.setTimeout(() => applyWght(value), 250);
});
// 松手时立即应用最终值, 避免防抖延迟
wghtSlider?.addEventListener('change', (e: Event) => {
const value = Number((e.target as any).value);
wghtValue.textContent = String(value);
updateVarPreview(value);
applyWght(value);
});
// 字号滑条: 直接应用 (12-40px), 设置 style 开销小无需防抖
const sizeSlider = document.getElementById('size-slider') as any;
const sizeValue = document.getElementById('size-value')!;
sizeSlider?.addEventListener('input', (e: Event) => {
const value = Number((e.target as any).value);
sizeValue.textContent = String(value);
if (varPreview) varPreview.style.fontSize = `${value}px`;
});
// 点击可编辑测试卡片 (简体/繁体/英文) 修改测试文本
let editTargetId: string | null = null;
const editDialog = document.getElementById('edit-text-dialog') as any;
const editInput = document.getElementById('edit-text-input') as any;
document.querySelectorAll<HTMLElement>('.test-card-editable').forEach((card) => {
card.addEventListener('click', () => {
const targetId = card.dataset.editTarget;
if (!targetId) return;
const target = document.getElementById(targetId);
if (!target) return;
editTargetId = targetId;
editInput.value = target.textContent ?? '';
if (editDialog) editDialog.open = true;
});
});
document.getElementById('edit-text-cancel')?.addEventListener('click', () => {
if (editDialog) editDialog.open = false;
});
document.getElementById('edit-text-save')?.addEventListener('click', () => {
if (editDialog) editDialog.open = false;
if (!editTargetId) return;
const target = document.getElementById(editTargetId);
if (target) target.textContent = editInput.value;
});
+2 -2
View File
@@ -107,7 +107,7 @@ const PIC_BASE = 'https://t17.market.mi-img.com/thumbnail/webp/w120q70/';
export const MiFontToolDef: ToolDef = {
id: 'mi-font',
title: '下载国际版小米主题字体',
subtitle: '搜索并下载国际版主题商店的字体 (.mtz)',
subtitle: '搜索并下载国际版主题商店的字体',
icon: 'download',
version: '1.0.0',
template: () => `
@@ -683,7 +683,7 @@ export const FontEditorToolDef: ToolDef = {
title: '字体编辑',
subtitle: '打开 ttf 字体, 缩放/偏移字形并导出 (实验性)',
icon: 'edit',
version: '0.0.1',
version: '1.0.0',
template: () => `
<div class="view-topbar">
<md-icon-button class="tool-page-back" aria-label="返回">
+488
View File
@@ -0,0 +1,488 @@
import { exec, toast } from './ksu';
import { pickWghtRange, updateWghtModeDisabled } from './slots';
import { WEIGHTS, averagedAxis } from './fontsXml';
import { FONTS_DIR, WGHT_BIN } from './constants';
export type WghtMode = 0 | 1 | 2 | 3;
const wghtModeSelect = document.getElementById('wght-mode-select') as any;
const wghtMapRows = document.getElementById('wght-map-rows');
const wghtMapAddBtn = document.getElementById('wght-map-add');
const wghtMapAddDialog = document.getElementById('wght-map-add-dialog') as any;
const wghtMapAddWeight = document.getElementById('wght-map-add-weight') as HTMLInputElement;
const wghtMapUndoBtn = document.getElementById('wght-map-undo');
const wghtMapExportBtn = document.getElementById('wght-map-export');
const wghtMapImportBtn = document.getElementById('wght-map-import');
const wghtMapResetBtn = document.getElementById('wght-map-reset');
const wghtMapTransferDialog = document.getElementById('wght-map-transfer-dialog') as any;
const wghtMapTransferTitle = document.getElementById('wght-map-transfer-title');
const wghtMapTransferNote = document.getElementById('wght-map-transfer-note');
const wghtMapTransferInput = document.getElementById(
'wght-map-transfer-input',
) as HTMLTextAreaElement;
const wghtMapTransferCancel = document.getElementById('wght-map-transfer-cancel');
const wghtMapTransferConfirm = document.getElementById('wght-map-transfer-confirm');
// 撤销历史栈 (每次用户编辑前的映射快照)
const undoStack: Record<number, number>[] = [];
const UNDO_LIMIT = 30;
// 最近一次已提交/已渲染的映射 (撤销入栈的基准)
let lastSnapshot: Record<number, number> | null = null;
// 高级配置卡片折叠/展开 (默认收起)
const wghtAdvancedHeader = document.getElementById('wght-advanced-header');
wghtAdvancedHeader?.closest('.wght-advanced')?.classList.add('collapsed');
wghtAdvancedHeader?.addEventListener('click', () => {
wghtAdvancedHeader.closest('.wght-advanced')?.classList.toggle('collapsed');
});
// 读取当前 UI 选择的字重覆写模式 (默认 0 不处理)
export function getSelectedWghtMode(): WghtMode {
return (Number(wghtModeSelect?.value ?? 0) || 0) as WghtMode;
}
// 写入模式到 FONTS/wght-mode.txt
export async function writeWghtMode(mode: WghtMode): Promise<void> {
try {
await exec(`echo '${mode}' > '${FONTS_DIR}/wght-mode.txt'`);
} catch {
// 忽略写入失败
}
}
// 读取字重覆写模式 (FONTS/wght-mode.txt), 默认 0 不处理
async function readWghtMode(): Promise<WghtMode> {
try {
const { errno, stdout } = await exec(`cat '${FONTS_DIR}/wght-mode.txt' 2>/dev/null || true`);
if (errno === 0) {
const n = Number(stdout.trim());
if (n === 1 || n === 2 || n === 3) return n as WghtMode;
}
} catch {
// 忽略
}
return 0;
}
// 覆写字体配置: 调用模块内置 Go 程序 fontmm-wght (本地读写全部 6 个 XML, 无命令长度限制)
export async function applyWghtOverride(mode: 1 | 2 | 3, min: number, max: number): Promise<void> {
const mapArg = mode === 3 ? ` -map '${FONTS_DIR}/wght-map.txt'` : '';
// 日志写到 FONTS/wght-apply.log 方便真机排查; 先 chmod +x 保证可执行
const logFile = `${FONTS_DIR}/wght-apply.log`;
const cmd = `chmod +x '${WGHT_BIN}' 2>/dev/null; '${WGHT_BIN}' -mode ${mode} -min ${min} -max ${max}${mapArg} > '${logFile}' 2>&1`;
try {
const { errno } = await exec(cmd);
// 读取并回显执行日志 (同时 console 输出供排查)
const { stdout: log } = await exec(`cat '${logFile}' 2>/dev/null || true`);
console.log(`[wght-override] mode=${mode} min=${min} max=${max} errno=${errno}`);
if (log) console.log(`[wght-override] log:\n${log}`);
if (errno !== 0) {
console.warn('[wght-override] 执行失败:', log);
// 覆写失败不阻断应用主流程, 但把失败原因带出
throw new Error(log || `fontmm-wght 执行失败 (errno=${errno})`);
}
} catch (e) {
// 覆写失败不阻断应用主流程
console.warn('字重范围覆写失败:', e);
}
}
// 读取自定义字重映射 (FONTS/wght-map.txt: 每行 "weight axis")
async function readWghtMap(): Promise<Record<number, number>> {
const map: Record<number, number> = {};
try {
const { errno, stdout } = await exec(`cat '${FONTS_DIR}/wght-map.txt' 2>/dev/null || true`);
if (errno === 0) {
for (const line of stdout.split('\n')) {
const m = line.trim().match(/^(\d+)\s+(\d+)$/);
if (m) map[Number(m[1])] = Number(m[2]);
}
}
} catch {
// 忽略
}
return map;
}
// 保存自定义字重映射 (DOM 驱动: 每行 data-weight + 输入值)
async function saveWghtMap(): Promise<void> {
const lines: string[] = [];
document.querySelectorAll<HTMLElement>('#wght-map-rows .wght-map-row').forEach((row) => {
const w = Number(row.dataset.weight);
const input = row.querySelector<HTMLInputElement>('.wght-map-input');
const v = Number(input?.value);
if (Number.isFinite(w) && Number.isFinite(v)) lines.push(`${w} ${Math.round(v)}`);
});
try {
await exec(`rm -f '${FONTS_DIR}/wght-map.txt'`);
for (const line of lines) {
await exec(`echo '${line}' >> '${FONTS_DIR}/wght-map.txt'`);
}
} catch {
// 忽略写入失败
}
}
// 当前 DOM 行的映射快照 (weight -> axis)
function snapshotMap(): Record<number, number> {
const map: Record<number, number> = {};
document.querySelectorAll<HTMLElement>('#wght-map-rows .wght-map-row').forEach((row) => {
const w = Number(row.dataset.weight);
const input = row.querySelector<HTMLInputElement>('.wght-map-input');
const v = Number(input?.value);
if (Number.isFinite(w) && Number.isFinite(v)) map[w] = Math.round(v);
});
return map;
}
// 用户编辑提交时入栈上一次状态 (编辑后 DOM 已成为新基准), 供撤销恢复
function recordUndo(): void {
if (lastSnapshot) {
undoStack.push(lastSnapshot);
if (undoStack.length > UNDO_LIMIT) undoStack.shift();
}
lastSnapshot = snapshotMap();
}
// 撤销: 弹回上一次快照并重建 DOM 行 + 落盘
function undoMap(): void {
const prev = undoStack.pop();
if (!prev || !wghtMapRows) {
if (!prev) toast('没有可撤销的操作');
return;
}
const range = pickWghtRange();
const min = range?.min ?? 1;
const max = range?.max ?? 1000;
wghtMapRows.textContent = '';
for (const w of Object.keys(prev)
.map(Number)
.sort((a, b) => a - b)) {
appendWghtMapRow(wghtMapRows, w, prev[w], min, max);
}
lastSnapshot = snapshotMap();
void saveWghtMap();
toast('已撤销');
}
// 导出: 当前映射 -> JSON -> base64 (UTF-8 安全)
function exportMap(): string {
const map = snapshotMap();
const json = JSON.stringify({ format: 'fontmm-wght-map', version: 1, map });
return btoa(unescape(encodeURIComponent(json)));
}
// 导入: base64 -> JSON -> 重建 DOM 行并落盘 (自动切换为自定义映射)
async function importMap(b64: string): Promise<void> {
let json: unknown;
try {
json = JSON.parse(decodeURIComponent(escape(atob(b64.replace(/\s/g, '')))));
} catch {
toast('导入失败: 不是有效的 base64 数据');
return;
}
const map = (json as { map?: Record<string, unknown> } | undefined)?.map ?? json;
const entries: [number, number][] = [];
for (const [k, v] of Object.entries(map as Record<string, unknown>)) {
const w = Number(k);
const axis = Number(v);
if (Number.isFinite(w) && Number.isFinite(axis)) entries.push([w, Math.round(axis)]);
}
if (!entries.length) {
toast('导入失败: 未解析到有效映射');
return;
}
const range = pickWghtRange();
const min = range?.min ?? 1;
const max = range?.max ?? 1000;
if (!wghtMapRows) return;
wghtMapRows.textContent = '';
for (const [w, axis] of entries.sort((a, b) => a[0] - b[0])) {
appendWghtMapRow(wghtMapRows, w, axis, min, max);
}
onUserEdit();
toast(`已导入 ${entries.length} 条映射`);
}
// 追加一行映射 (weight 标签 + 滑块 + 输入框 + 删除按钮)
function appendWghtMapRow(
rowsEl: HTMLElement,
w: number,
axis: number,
min: number,
max: number,
): void {
const row = document.createElement('div');
row.className = 'wght-map-row';
row.dataset.weight = String(w);
const label = document.createElement('span');
label.className = 'wght-map-label';
label.textContent = String(w);
const slider = document.createElement('md-slider') as any;
slider.min = min;
slider.max = max;
slider.step = 1;
// 原生 input 接管手势, 禁用以避免轻触即跳值
slider.style.pointerEvents = 'none';
// 滑条容器 + 手势覆盖层: 按住并水平滑动才激活调整
const sliderWrap = document.createElement('div');
sliderWrap.className = 'wght-map-slider';
const overlay = document.createElement('div');
overlay.className = 'wght-map-slider-overlay';
overlay.ariaLabel = `weight ${w} 的滑条`;
const input = document.createElement('input');
input.type = 'number';
input.min = String(min);
input.max = String(max);
input.className = 'wght-map-input';
input.ariaLabel = `weight ${w} 的轴值`;
// 与粗细等级的对比 (轴值 - 字重, 如 +25 / -100)
const diff = document.createElement('span');
diff.className = 'wght-map-diff';
const setDiff = (v: number) => {
const d = Math.round(v) - w;
diff.textContent = d > 0 ? `+${d}` : String(d);
};
const setBoth = (v: number) => {
const clamped = Math.min(max, Math.max(min, Math.round(v)));
slider.value = clamped;
input.value = String(clamped);
setDiff(clamped);
};
setBoth(axis);
// 手势: 按住后水平位移超过阈值才激活; 激活后仅按水平位置更新值 (垂直移动不影响)
let dragActive = false;
let dragStartX = 0;
let dragPointerId = -1;
const DRAG_THRESHOLD = 8;
overlay.addEventListener('pointerdown', (e) => {
if (e.pointerType === 'mouse' && e.button !== 0) return;
dragPointerId = e.pointerId;
dragStartX = e.clientX;
dragActive = false;
overlay.setPointerCapture(dragPointerId);
});
overlay.addEventListener('pointermove', (e) => {
if (e.pointerId !== dragPointerId) return;
if (!dragActive && Math.abs(e.clientX - dragStartX) <= DRAG_THRESHOLD) return;
dragActive = true;
const rect = slider.getBoundingClientRect();
const frac = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width));
setBoth(min + (max - min) * frac);
});
const endDrag = (e: PointerEvent) => {
if (e.pointerId !== dragPointerId) return;
dragPointerId = -1;
const wasActive = dragActive;
dragActive = false;
try {
overlay.releasePointerCapture(e.pointerId);
} catch {
// 已释放则忽略
}
if (wasActive) onUserEdit();
};
overlay.addEventListener('pointerup', endDrag);
overlay.addEventListener('pointercancel', endDrag);
input.addEventListener('input', () => {
const v = Number(input.value);
if (Number.isFinite(v)) {
slider.value = Math.min(max, Math.max(min, v));
setDiff(v);
}
});
input.addEventListener('change', () => {
const v = Number(input.value);
if (!Number.isFinite(v)) {
input.value = String(slider.value);
return;
}
setBoth(v);
void onUserEdit();
});
const delBtn = document.createElement('md-icon-button') as any;
delBtn.ariaLabel = `删除字重 ${w} 映射`;
delBtn.className = 'wght-map-del';
const delIcon = document.createElement('md-icon');
delIcon.textContent = 'close';
delBtn.appendChild(delIcon);
delBtn.addEventListener('click', () => {
row.remove();
void onUserEdit();
});
row.append(label, sliderWrap, diff, input, delBtn);
sliderWrap.append(slider, overlay);
rowsEl.appendChild(row);
}
// 计算所选模式的实时映射结果 (weight -> axis)
// mode 1=裁切: 仅保留范围内字重, axis=weight; mode 2=平均: 9 档线性插值;
// mode 0/3: 优先展示已保存的自定义映射, 空则回退平均默认
function effectiveMapping(
mode: WghtMode,
min: number,
max: number,
saved: Record<number, number>,
): Record<number, number> {
const map: Record<number, number> = {};
if (mode === 1) {
for (const w of WEIGHTS) if (w >= min && w <= max) map[w] = w;
return map;
}
if (mode === 2) {
for (const w of WEIGHTS) map[w] = averagedAxis(min, max, w);
return map;
}
if (Object.keys(saved).length > 0) return saved;
for (const w of WEIGHTS) map[w] = averagedAxis(min, max, w);
return map;
}
// 用户在映射区修改任意值 (改值/删除/新增/导入): 入栈撤销 + 自动切换为自定义映射并保存
function onUserEdit(): void {
recordUndo();
if (getSelectedWghtMode() !== 3) {
if (wghtModeSelect) wghtModeSelect.value = '3';
void writeWghtMode(3);
}
void saveWghtMap();
}
// 渲染字重映射行 (按当前模式实时预览: 读 wght-map.txt; 空时默认 9 档平均插值)
function renderWghtMapRows(): void {
if (!wghtMapRows) return;
const range = pickWghtRange();
const min = range?.min ?? 1;
const max = range?.max ?? 1000;
const mode = getSelectedWghtMode();
void readWghtMap().then((saved) => {
if (!wghtMapRows) return;
wghtMapRows.textContent = '';
const map = effectiveMapping(mode, min, max, saved);
for (const w of Object.keys(map)
.map(Number)
.sort((a, b) => a - b)) {
appendWghtMapRow(wghtMapRows, w, map[w], min, max);
}
lastSnapshot = snapshotMap();
});
}
// 回填模式选择
async function initWghtModeUI(): Promise<void> {
const mode = await readWghtMode();
if (wghtModeSelect) wghtModeSelect.value = String(mode);
updateWghtModeDisabled();
renderWghtMapRows();
}
wghtModeSelect?.addEventListener('change', () => {
const v = Number(wghtModeSelect.value);
if (v === 0 || v === 1 || v === 2 || v === 3) {
void writeWghtMode(v as WghtMode);
renderWghtMapRows();
}
});
// 槽位变化 (新字体 wght 范围变更) 时刷新映射预览
document.addEventListener('slots-rendered', () => renderWghtMapRows());
void initWghtModeUI();
// 新增字重映射对话框
wghtMapAddBtn?.addEventListener('click', () => {
if (wghtMapAddWeight) wghtMapAddWeight.value = '';
if (wghtMapAddDialog) wghtMapAddDialog.open = true;
});
document.getElementById('wght-map-add-cancel')?.addEventListener('click', () => {
if (wghtMapAddDialog) wghtMapAddDialog.open = false;
});
document.getElementById('wght-map-add-confirm')?.addEventListener('click', () => {
if (wghtMapAddDialog) wghtMapAddDialog.open = false;
const w = Number(wghtMapAddWeight?.value);
if (!Number.isFinite(w) || w < 1 || w > 1000) {
toast('字重等级需为 1-1000 的整数');
return;
}
const weight = Math.round(w);
// 重复 weight 则更新, 否则新增一行
const existing = document.querySelector<HTMLElement>(
`#wght-map-rows .wght-map-row[data-weight="${weight}"]`,
);
if (!wghtMapRows) return;
const range = pickWghtRange();
const min = range?.min ?? 1;
const max = range?.max ?? 1000;
if (existing) {
existing.scrollIntoView({ block: 'center' });
} else {
appendWghtMapRow(wghtMapRows, weight, averagedAxis(min, max, weight), min, max);
}
onUserEdit();
});
// 工具栏: 撤销 / 导出 / 导入 / 重置
wghtMapUndoBtn?.addEventListener('click', () => {
undoMap();
});
// 重置: 清空已保存自定义映射, 恢复当前模式默认预览
wghtMapResetBtn?.addEventListener('click', () => {
void (async () => {
try {
await exec(`rm -f '${FONTS_DIR}/wght-map.txt'`);
} catch {
// 忽略删除失败
}
renderWghtMapRows();
toast('已重置为默认映射');
})();
});
// 转移对话框 (导出显示 / 导入粘贴复用)
let transferMode: 'export' | 'import' = 'export';
wghtMapExportBtn?.addEventListener('click', () => {
transferMode = 'export';
if (wghtMapTransferTitle) wghtMapTransferTitle.textContent = '导出映射';
if (wghtMapTransferNote)
wghtMapTransferNote.textContent = '以下为当前映射的 base64 编码 (JSON),请复制保存到其他设备';
if (wghtMapTransferInput) {
wghtMapTransferInput.readOnly = true;
wghtMapTransferInput.value = exportMap();
wghtMapTransferInput.select();
}
if (wghtMapTransferConfirm) wghtMapTransferConfirm.textContent = '关闭';
if (wghtMapTransferDialog) wghtMapTransferDialog.open = true;
});
wghtMapImportBtn?.addEventListener('click', () => {
transferMode = 'import';
if (wghtMapTransferTitle) wghtMapTransferTitle.textContent = '导入映射';
if (wghtMapTransferNote)
wghtMapTransferNote.textContent =
'粘贴从其他设备导出的 base64 编码 (JSON),导入将替换当前自定义映射';
if (wghtMapTransferInput) {
wghtMapTransferInput.readOnly = false;
wghtMapTransferInput.value = '';
}
if (wghtMapTransferConfirm) wghtMapTransferConfirm.textContent = '导入';
if (wghtMapTransferDialog) wghtMapTransferDialog.open = true;
});
wghtMapTransferCancel?.addEventListener('click', () => {
if (wghtMapTransferDialog) wghtMapTransferDialog.open = false;
});
wghtMapTransferConfirm?.addEventListener('click', () => {
if (wghtMapTransferDialog) wghtMapTransferDialog.open = false;
if (transferMode === 'import' && wghtMapTransferInput) {
void importMap(wghtMapTransferInput.value);
}
});