An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Improve font preview responsiveness and regular style selection https://github.com/siyuan-note/siyuan/issues/19283
Daniel8a9a12daea24
diff --git a/app/src/util/fontPreview.test.ts b/app/src/util/fontPreview.test.tsindex 21216f611a..c43f894c30 100644--- a/app/src/util/fontPreview.test.ts+++ b/app/src/util/fontPreview.test.ts@@ -2,8 +2,9 @@ import * as assert from "node:assert/strict";import test from "node:test";import {observeFontPreview} from "./fontPreview";-test("font previews wait for loading, retain prepared fonts and stop after cleanup", async () => {- const saved = new Map(["window", "document", "IntersectionObserver", "getComputedStyle"].map(key =>+test("font previews defer loading, discard invisible items and stop after cleanup", async () => {+ const saved = new Map(["window", "document", "IntersectionObserver", "getComputedStyle", "setTimeout", "clearTimeout",+ "requestAnimationFrame", "cancelAnimationFrame"].map(key =>[key, Object.getOwnPropertyDescriptor(globalThis, key)]));let callback: (entries: unknown[]) => void;let finish: () => void;@@ -11,6 +12,8 @@ test("font previews wait for loading, retain prepared fonts and stop after cleanlet loads = 0;let applies = 0;let disconnected = false;+ let scheduled: () => void;+ let nextFrame: () => void;const pending = () => new Promise<void>((resolve, fail) => {finish = resolve;reject = fail;@@ -23,11 +26,15 @@ test("font previews wait for loading, retain prepared fonts and stop after clean}},};const item = {querySelector: () => label};- const list = {querySelectorAll: () => [item]} as unknown as HTMLElement;+ const list = {querySelectorAll: () => [item], addEventListener() {}, removeEventListener() {}} as unknown as HTMLElement;const emit = (visible: boolean) => callback([{target: item, isIntersecting: visible}]);const apply = () => { applies++; label.style.fontFamily = "Preview"; };try {Object.assign(globalThis, {+ setTimeout: (cb: () => void) => { scheduled = cb; return 1; },+ clearTimeout: () => { scheduled = undefined; },+ requestAnimationFrame: (cb: () => void) => { nextFrame = cb; return 1; },+ cancelAnimationFrame: () => { nextFrame = undefined; },window: {IntersectionObserver: true},document: {fonts: {load: () => { loads++; return loading; }}},getComputedStyle: () => ({fontWeight: "400", fontSize: "16px", fontFamily: "Preview"}),@@ -35,7 +42,7 @@ test("font previews wait for loading, retain prepared fonts and stop after cleanconstructor(cb: typeof callback, options: IntersectionObserverInit) {callback = cb;assert.equal(options.root, list);- assert.equal(options.rootMargin, "200px 0px");+ assert.equal(options.rootMargin, undefined);}observe() {}unobserve() {}@@ -43,11 +50,21 @@ test("font previews wait for loading, retain prepared fonts and stop after clean},});const cleanup = observeFontPreview(list, apply);- assert.equal(label.style.visibility, "hidden");+ assert.equal(label.style.visibility, "");+ emit(false);+ assert.equal(loads, 0);+ emit(true);+ assert.equal(loads, 0);emit(false);+ scheduled();assert.equal(loads, 0);emit(true);- assert.equal(label.style.visibility, "hidden");+ scheduled();+ assert.equal(loads, 1);+ emit(true);+ scheduled();+ assert.equal(loads, 1);+ assert.equal(label.style.visibility, "");finish();await loading;assert.equal(label.style.visibility, "");@@ -61,6 +78,7 @@ test("font previews wait for loading, retain prepared fonts and stop after cleanloading = pending();const cleanupFailure = observeFontPreview(list, apply);emit(true);+ scheduled();reject(new Error("Font unavailable"));await loading.catch(() => {});assert.equal(label.style.visibility, "");@@ -70,10 +88,29 @@ test("font previews wait for loading, retain prepared fonts and stop after cleanloading = pending();const cleanupPending = observeFontPreview(list, apply);emit(true);+ scheduled();cleanupPending();finish();await loading;- assert.equal(label.style.visibility, "hidden");+ assert.equal(label.style.visibility, "");+ assert.equal(scheduled, undefined);++ loading = pending();+ const cleanupQueue = observeFontPreview(list, apply);+ const secondItem = {querySelector: () => label};+ callback([{target: item, isIntersecting: true}, {target: secondItem, isIntersecting: true}]);+ scheduled();+ const firstLoadCount = loads;+ assert.equal(nextFrame, undefined);+ finish();+ await loading;+ await Promise.resolve();+ assert.equal(loads, firstLoadCount);+ assert.equal(typeof nextFrame, "function");+ nextFrame();+ assert.equal(loads, firstLoadCount + 1);+ cleanupQueue();+ assert.equal(nextFrame, undefined);} finally {saved.forEach((descriptor, key) => {if (descriptor) {diff --git a/app/src/util/fontPreview.ts b/app/src/util/fontPreview.tsindex 2a9b722b37..09fd0811eb 100644--- a/app/src/util/fontPreview.ts+++ b/app/src/util/fontPreview.ts@@ -2,6 +2,37 @@ export const observeFontPreview = (listElement: HTMLElement,applyFont: (label: HTMLElement, item: HTMLElement) => void) => {let closed = false;let observer: IntersectionObserver;+ let timer: ReturnType<typeof setTimeout>;+ let frame: number;+ let loading = false;+ const pending = new Set<HTMLElement>();+ const schedule = () => {+ clearTimeout(timer);+ cancelAnimationFrame(frame);+ if (!closed) {+ timer = setTimeout(() => {+ timer = undefined;+ void next();+ }, 150);+ }+ };+ const next = async () => {+ if (closed || loading) {+ return;+ }+ const item = pending.values().next().value;+ if (!item) {+ return;+ }+ pending.delete(item);+ loading = true;+ await prepare(item);+ loading = false;+ // 后续字体逐帧加载,仅滚动或可见范围变化时重新等待防抖。+ if (!closed && pending.size && timer === undefined) {+ frame = requestAnimationFrame(() => void next());+ }+ };const prepared = new WeakSet<HTMLElement>();const prepare = async (item: HTMLElement) => {const label = item.querySelector<HTMLElement>(".b3-menu__label");@@ -25,27 +56,32 @@ export const observeFontPreview = (listElement: HTMLElement,}};const items = listElement.querySelectorAll<HTMLElement>(".b3-list-item");- // 名称在预览字体就绪后显示,离开可见区域时保留字体,避免滚动时反复切换。- items.forEach(item => {- const label = item.querySelector<HTMLElement>(".b3-menu__label");- if (label?.dataset.family) {- label.style.visibility = "hidden";- }- });+ // 名称立即显示,滚动停止后逐项加载可见字体,避免快速滚动时集中加载。+ listElement.addEventListener("scroll", schedule, {passive: true});if ("IntersectionObserver" in window) {observer = new IntersectionObserver(entries => {entries.forEach(entry => {if (entry.isIntersecting) {- void prepare(entry.target as HTMLElement);+ if (!prepared.has(entry.target as HTMLElement)) {+ pending.add(entry.target as HTMLElement);+ }+ } else {+ pending.delete(entry.target as HTMLElement);}});- }, {root: listElement, rootMargin: "200px 0px"});+ schedule();+ }, {root: listElement});items.forEach(item => observer.observe(item));} else {- items.forEach(item => void prepare(item));+ items.forEach(item => pending.add(item));+ schedule();}return () => {closed = true;+ clearTimeout(timer);+ cancelAnimationFrame(frame);+ pending.clear();+ listElement.removeEventListener("scroll", schedule);observer?.disconnect();};};diff --git a/kernel/util/font.go b/kernel/util/font.goindex 98447cc04b..b6acb4b6b2 100644--- a/kernel/util/font.go+++ b/kernel/util/font.go@@ -60,11 +60,12 @@ func LoadSysFonts() []*Font {}type Font struct {- Family string `json:"family"` // 对应 CSS font-family- Weight int `json:"weight"` // 对应 CSS font-weight- DisplayName string `json:"displayName"` // 给人看的名称 (Family + Subfamily)- Aliases []string `json:"aliases,omitempty"` // 用于字体搜索的本地化名称和内部名称- Spacing string `json:"spacing,omitempty"` // 字体间距分类+ nonNormalStyle bool+ Family string `json:"family"` // 对应 CSS font-family+ Weight int `json:"weight"` // 对应 CSS font-weight+ DisplayName string `json:"displayName"` // 给人看的名称 (Family + Subfamily)+ Aliases []string `json:"aliases,omitempty"` // 用于字体搜索的本地化名称和内部名称+ Spacing string `json:"spacing,omitempty"` // 字体间距分类}const (@@ -139,6 +140,12 @@ func addFont(fonts []*Font, f *Font) []*Font {if strings.EqualFold(f.Family, font.Family) && f.Weight == font.Weight {font.Aliases = mergeFontAliases(font.Aliases, f.Aliases, font.Family, font.DisplayName)font.Spacing = mergeFontSpacing(font.Spacing, f.Spacing)+ // 字体选择仅保存字体族和字重,同字重优先使用直立样式的名称。+ if font.nonNormalStyle && !f.nonNormalStyle {+ font.Aliases = appendFontAlias(font.Aliases, font.DisplayName)+ font.DisplayName = f.DisplayName+ font.nonNormalStyle = false+ }return fonts}}@@ -264,11 +271,12 @@ func parseFontVariations(font *sfnt.Font, defaultFont *Font) (ret []*Font) {aliases := collectFontAliases(entries, sfnt.NameID(subfamilyNameID))aliases = append(aliases, defaultFont.Aliases...)ret = append(ret, &Font{- Family: defaultFont.Family,- Weight: weight,- DisplayName: displayName,- Aliases: aliases,- Spacing: defaultFont.Spacing,+ nonNormalStyle: defaultFont.nonNormalStyle || isNonNormalFontStyle(subfamily),+ Family: defaultFont.Family,+ Weight: weight,+ DisplayName: displayName,+ Aliases: aliases,+ Spacing: defaultFont.Spacing,})}return@@ -314,14 +322,20 @@ func parseFontInfo(font *sfnt.Font) (*Font, error) {sfnt.NameFull, sfnt.NameCompatibleFull, sfnt.NamePostscript)return &Font{- Family: family,- Weight: weight,- DisplayName: displayName,- Aliases: aliases,- Spacing: detectFontSpacing(font),+ nonNormalStyle: isNonNormalFontStyle(subfamily),+ Family: family,+ Weight: weight,+ DisplayName: displayName,+ Aliases: aliases,+ Spacing: detectFontSpacing(font),}, nil}+func isNonNormalFontStyle(style string) bool {+ style = strings.ToLower(style)+ return strings.Contains(style, "italic") || strings.Contains(style, "oblique")+}+func detectFontSpacing(font *sfnt.Font) string {postTable, postErr := font.Table(sfnt.MustNamedTag("post"))postData := []byte(nil)diff --git a/kernel/util/font_platform_darwin.go b/kernel/util/font_platform_darwin.goindex 29248c09d0..075cd94f67 100644--- a/kernel/util/font_platform_darwin.go+++ b/kernel/util/font_platform_darwin.go@@ -170,11 +170,12 @@ func loadPlatformFonts() (ret []*Font) {font.DisplayName = font.Family}ret = addFont(ret, &Font{- Family: font.Family,- Weight: fontWeightFromNormalizedTrait(font.Weight, font.Style),- DisplayName: font.DisplayName,- Aliases: font.Aliases,- Spacing: font.Spacing,+ nonNormalStyle: isNonNormalFontStyle(font.Style),+ Family: font.Family,+ Weight: fontWeightFromNormalizedTrait(font.Weight, font.Style),+ DisplayName: font.DisplayName,+ Aliases: font.Aliases,+ Spacing: font.Spacing,})}returndiff --git a/kernel/util/font_platform_windows.go b/kernel/util/font_platform_windows.goindex d7936251e0..58ea68eab3 100644--- a/kernel/util/font_platform_windows.go+++ b/kernel/util/font_platform_windows.go@@ -370,11 +370,12 @@ func loadPlatformFonts() (ret []*Font) {weight = inferFontWeight(400, style)}ret = addFont(ret, &Font{- Family: family,- Weight: weight,- DisplayName: displayName,- Aliases: aliases,- Spacing: directWriteFontSpacing(int(font.spacing)),+ nonNormalStyle: isNonNormalFontStyle(style),+ Family: family,+ Weight: weight,+ DisplayName: displayName,+ Aliases: aliases,+ Spacing: directWriteFontSpacing(int(font.spacing)),})}returndiff --git a/kernel/util/font_test.go b/kernel/util/font_test.goindex c57dae004c..f6c6fc250b 100644--- a/kernel/util/font_test.go+++ b/kernel/util/font_test.go@@ -58,6 +58,21 @@ func TestLocalizedFontNamesAndAliases(t *testing.T) {}}+func TestAddFontPrefersUprightStyle(t *testing.T) {+ for _, italicFirst := range []bool{true, false} {+ upright := &Font{Family: "Cascadia Code", Weight: 400, DisplayName: "Cascadia Code"}+ italic := &Font{Family: "Cascadia Code", Weight: 400, DisplayName: "Cascadia Code Italic", nonNormalStyle: true}+ first, second := upright, italic+ if italicFirst {+ first, second = italic, upright+ }+ fonts := addFont(addFont(nil, first), second)+ if len(fonts) != 1 || fonts[0].DisplayName != "Cascadia Code" || fonts[0].nonNormalStyle {+ t.Fatalf("unexpected merged font: %+v", fonts)+ }+ }+}+func TestAddFontMergesAliases(t *testing.T) {fonts := addFont(nil, &Font{Family: "LXGW WenKai",diff --git a/kernel/util/fontconfig.go b/kernel/util/fontconfig.goindex 890fffc357..6d2d2241ee 100644--- a/kernel/util/fontconfig.go+++ b/kernel/util/fontconfig.go@@ -88,11 +88,12 @@ func parseFontconfigFonts(data []byte, lang string) (ret []*Font) {}weight := parseFontconfigWeight(string(fields[4]), style)ret = addFont(ret, &Font{- Family: family,- Weight: weight,- DisplayName: displayName,- Aliases: aliases,- Spacing: parseFontconfigSpacing(string(fields[5])),+ nonNormalStyle: isNonNormalFontStyle(style),+ Family: family,+ Weight: weight,+ DisplayName: displayName,+ Aliases: aliases,+ Spacing: parseFontconfigSpacing(string(fields[5])),})}return