An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Optimize custom font resource management on mobile https://github.com/siyuan-note/siyuan/issues/18422
Danielbbdbcae87905
diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.tsindex 0ef511d6d7..984d44718e 100644--- a/app/src/config/tabs/appearanceTab.ts+++ b/app/src/config/tabs/appearanceTab.ts@@ -30,6 +30,7 @@ import {isNativeMobileContainer,loadCustomFonts,registerCustomFont,+ registerCustomFonts,unregisterCustomFont} from "../../util/customFont";import {showMessage} from "../../dialog/message";@@ -123,7 +124,6 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {return;}const systemFonts = Array.isArray(systemResponse.data) ? systemResponse.data as IFontItem[] : [];- customFonts.forEach(registerCustomFont);const curFamily = fontFamilyEl.dataset.family;const curWeight = parseInt(fontFamilyEl.dataset.weight || "400", 10);@@ -136,7 +136,9 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {genFontListItemHtml(item, item.family === curFamily && item.weight === curWeight)).join("");const canManageCustomFonts = nativeMobile && !window.siyuan.config.readonly;- const fontMenu = new Menu();+ const customFontsByID = new Map(customFonts.map((font) => [font.id, font]));+ let fontPreviewObserver: IntersectionObserver;+ const fontMenu = new Menu(undefined, () => fontPreviewObserver?.disconnect());fontMenu.addItem({iconHTML: "",type: "empty",@@ -158,6 +160,30 @@ const mountAppearanceFontFamily = (root: HTMLElement) => {item.style.fontFamily = item.dataset.family;item.style.fontWeight = item.dataset.weight;});+ if (!window.siyuan.config.system.safeMode && "IntersectionObserver" in window) {+ fontPreviewObserver = new IntersectionObserver((entries) => {+ const visibleFonts: ICustomFont[] = [];+ entries.forEach((entry) => {+ if (!entry.isIntersecting) {+ return;+ }+ const id = (entry.target as HTMLElement).dataset.id;+ const font = customFontsByID.get(id);+ if (font) {+ visibleFonts.push(font);+ }+ fontPreviewObserver.unobserve(entry.target);+ });+ registerCustomFonts(visibleFonts);+ }, {+ rootMargin: "96px 0px",+ });+ listElement.querySelectorAll<HTMLElement>(".b3-list-item[data-id]").forEach((item) => {+ if (item.dataset.id) {+ fontPreviewObserver.observe(item);+ }+ });+ }const filterFontList = () => {const value = inputElement.value.toLowerCase().trim();listElement.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");diff --git a/app/src/util/customFont.ts b/app/src/util/customFont.tsindex 49b53a9bcb..47210b4361 100644--- a/app/src/util/customFont.ts+++ b/app/src/util/customFont.ts@@ -12,6 +12,7 @@ export interface ICustomFont {let customFontsPromise: Promise<ICustomFont[]> | undefined;const registeredFonts = new Map<string, ICustomFont>();+const fontLoadPromises = new Map<string, Promise<FontFace[]>>();export const isNativeMobileContainer = () => {return ["android", "ios", "harmony"].includes(window.siyuan.config.system.container);@@ -34,21 +35,39 @@ export const invalidateCustomFonts = () => {};export const registerCustomFont = (font: ICustomFont) => {- if (window.siyuan.config.system.safeMode || !isValidCustomFont(font)) {+ registerCustomFonts([font]);+};++export const registerCustomFonts = (fonts: ICustomFont[]) => {+ if (window.siyuan.config.system.safeMode) {return;}- registeredFonts.set(font.id, {- ...font,- family: CUSTOM_FONT_FAMILY_PREFIX + font.id,- url: `/custom-fonts/${font.id}`,- weight: Math.max(1, Math.min(1000, font.weight || 400)),+ fonts.forEach((font) => {+ if (!isValidCustomFont(font)) {+ return;+ }+ const normalizedFont = {+ ...font,+ family: CUSTOM_FONT_FAMILY_PREFIX + font.id,+ url: `/custom-fonts/${font.id}`,+ weight: Math.max(1, Math.min(1000, font.weight || 400)),+ };+ const registeredFont = registeredFonts.get(font.id);+ if (registeredFont?.family === normalizedFont.family &&+ registeredFont.url === normalizedFont.url &&+ registeredFont.weight === normalizedFont.weight) {+ return;+ }+ registeredFonts.set(font.id, normalizedFont);+ fontLoadPromises.delete(font.id);+ setCustomFontStyle(normalizedFont);});- renderCustomFontStyles();};export const unregisterCustomFont = (id: string) => {+ fontLoadPromises.delete(id);if (registeredFonts.delete(id)) {- renderCustomFontStyles();+ document.getElementById(`customFontStyle-${id}`)?.remove();}};@@ -68,30 +87,34 @@ export const ensureSelectedCustomFont = async (family: string, weight: number) =return;}registerCustomFont(font);- await document.fonts.load(`${weight || font.weight || 400} 16px "${family}"`);+ let loadPromise = fontLoadPromises.get(id);+ if (!loadPromise) {+ loadPromise = document.fonts.load(`${weight || font.weight || 400} 16px "${family}"`).catch((error) => {+ fontLoadPromises.delete(id);+ throw error;+ });+ fontLoadPromises.set(id, loadPromise);+ }+ await loadPromise;} catch (error) {console.warn("load custom font failed", error);}};-const renderCustomFontStyles = () => {- let styleElement = document.getElementById("customFontStyle") as HTMLStyleElement;- if (registeredFonts.size === 0) {- styleElement?.remove();- return;- }+const setCustomFontStyle = (font: ICustomFont) => {+ let styleElement = document.getElementById(`customFontStyle-${font.id}`) as HTMLStyleElement;if (!styleElement) {styleElement = document.createElement("style");- styleElement.id = "customFontStyle";+ styleElement.id = `customFontStyle-${font.id}`;document.head.append(styleElement);}- styleElement.textContent = Array.from(registeredFonts.values()).map((font) => `@font-face {+ styleElement.textContent = `@font-face {font-family: "${font.family}";src: url("${font.url}");font-style: normal;font-weight: ${font.weight};font-display: swap;-}`).join("\n");+}`;};const isValidCustomFont = (font: ICustomFont) => {diff --git a/kernel/api/system.go b/kernel/api/system.goindex e302f14de8..a6fcb94385 100644--- a/kernel/api/system.go+++ b/kernel/api/system.go@@ -935,19 +935,14 @@ func importCustomFont(c *gin.Context) {}defer file.Close()- if err = os.MkdirAll(util.CustomFontDir(), 0755); err != nil {- ret.Code = -1- ret.Msg = err.Error()- return- }- tempFile, err := os.CreateTemp(util.CustomFontDir(), ".font-*")+ tempFile, err := util.CreateCustomFontTemp()if err != nil {ret.Code = -1ret.Msg = err.Error()return}tempPath := tempFile.Name()- defer os.Remove(tempPath)+ defer util.DiscardCustomFontTemp(tempPath)written, copyErr := io.Copy(tempFile, io.LimitReader(file, util.MaxCustomFontSize+1))closeErr := tempFile.Close()diff --git a/kernel/util/custom_font.go b/kernel/util/custom_font.goindex ad4ef947ac..8a6a23c8e6 100644--- a/kernel/util/custom_font.go+++ b/kernel/util/custom_font.go@@ -49,12 +49,40 @@ var (customFonts []*CustomFontcustomFontsLoaded boolcustomFontsLock sync.Mutex+ customFontTemps = map[string]struct{}{})func CustomFontDir() string {return filepath.Join(AppearancePath, "fonts", "custom")}+func CreateCustomFontTemp() (*os.File, error) {+ customFontsLock.Lock()+ defer customFontsLock.Unlock()++ if err := os.MkdirAll(CustomFontDir(), 0755); err != nil {+ return nil, err+ }+ tempFile, err := os.CreateTemp(CustomFontDir(), ".font-*")+ if err != nil {+ return nil, err+ }+ customFontTemps[filepath.Clean(tempFile.Name())] = struct{}{}+ return tempFile, nil+}++func DiscardCustomFontTemp(tempPath string) {+ customFontsLock.Lock()+ defer customFontsLock.Unlock()++ tempPath = filepath.Clean(tempPath)+ if _, ok := customFontTemps[tempPath]; !ok {+ return+ }+ delete(customFontTemps, tempPath)+ _ = os.Remove(tempPath)+}+func LoadCustomFonts() []*CustomFont {customFontsLock.Lock()defer customFontsLock.Unlock()@@ -183,6 +211,7 @@ func loadCustomFontsLocked() {if customFontsLoaded {return}+ cleanupCustomFontTempsLocked()customFonts = []*CustomFont{}entries, err := os.ReadDir(CustomFontDir())@@ -247,6 +276,22 @@ func loadCustomFontsLocked() {customFontsLoaded = true}+func cleanupCustomFontTempsLocked() {+ entries, err := os.ReadDir(CustomFontDir())+ if err != nil {+ return+ }+ for _, entry := range entries {+ if entry.IsDir() || !strings.HasPrefix(entry.Name(), ".font-") {+ continue+ }+ tempPath := filepath.Clean(filepath.Join(CustomFontDir(), entry.Name()))+ if _, active := customFontTemps[tempPath]; !active {+ _ = os.Remove(tempPath)+ }+ }+}+func detectCustomFontExtension(reader io.Reader) (string, error) {header := make([]byte, 4)if _, err := io.ReadFull(reader, header); err != nil {diff --git a/kernel/util/custom_font_test.go b/kernel/util/custom_font_test.goindex c021bbe44b..43df70fda7 100644--- a/kernel/util/custom_font_test.go+++ b/kernel/util/custom_font_test.go@@ -120,6 +120,50 @@ func TestInstallCustomFontRejectsInvalidData(t *testing.T) {}}+func TestLoadCustomFontsCleansAbandonedTemporaryFiles(t *testing.T) {+ oldAppearancePath := AppearancePath+ AppearancePath = t.TempDir()+ resetCustomFontCache()+ t.Cleanup(func() {+ AppearancePath = oldAppearancePath+ resetCustomFontCache()+ })++ if err := os.MkdirAll(CustomFontDir(), 0755); err != nil {+ t.Fatal(err)+ }+ abandonedFile, err := os.CreateTemp(CustomFontDir(), ".font-*")+ if err != nil {+ t.Fatal(err)+ }+ abandonedPath := abandonedFile.Name()+ if err = abandonedFile.Close(); err != nil {+ t.Fatal(err)+ }++ activeFile, err := CreateCustomFontTemp()+ if err != nil {+ t.Fatal(err)+ }+ activePath := activeFile.Name()+ if err = activeFile.Close(); err != nil {+ t.Fatal(err)+ }++ LoadCustomFonts()+ if _, err = os.Stat(abandonedPath); !os.IsNotExist(err) {+ t.Fatalf("abandoned temporary font was not removed: %v", err)+ }+ if _, err = os.Stat(activePath); err != nil {+ t.Fatalf("active temporary font was removed: %v", err)+ }++ DiscardCustomFontTemp(activePath)+ if _, err = os.Stat(activePath); !os.IsNotExist(err) {+ t.Fatalf("discarded temporary font was not removed: %v", err)+ }+}+func copyCustomFontForTest(t *testing.T, sourcePath string) string {t.Helper()@@ -148,5 +192,6 @@ func resetCustomFontCache() {customFontsLock.Lock()customFonts = nilcustomFontsLoaded = false+ customFontTemps = map[string]struct{}{}customFontsLock.Unlock()}