AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(fonts): add on-demand Maple Mono CN and sync monospace code fonts
tianma-if28c85a94b14d
diff --git a/apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swift b/apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swiftindex 74504b8d..e63bb28d 100644--- a/apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swift+++ b/apps/ios/EdgeEver/Data/Preferences/PreferencesStore.swift@@ -25,6 +25,7 @@ enum NoteImageFontCatalog {(id: "dmserif", zh: "DM Serif Display", en: "DM Serif Display"),(id: "bebas", zh: "Bebas Neue", en: "Bebas Neue"),(id: "spacegrotesk", zh: "Space Grotesk", en: "Space Grotesk"),+ (id: "maple-mono-cn", zh: "Maple Mono CN", en: "Maple Mono CN"),(id: "jetbrains", zh: "JetBrains Mono", en: "JetBrains Mono"),]static let templateLabels: [String: (zh: String, en: String, ja: String, pl: String)] = [diff --git a/apps/ios/EditorSource/src/font-picker.ts b/apps/ios/EditorSource/src/font-picker.tsindex 03155deb..509a4c03 100644--- a/apps/ios/EditorSource/src/font-picker.ts+++ b/apps/ios/EditorSource/src/font-picker.ts@@ -1,4 +1,4 @@-import { FONT_IDS, isRemoteNoteImageFont } from "@edgeever/shared/font-catalog";+import { FONT_IDS, isRemoteNoteImageFont, shouldLoadFontPreview } from "@edgeever/shared/font-catalog";import { resolveNoteImageTypography, type NoteImageFontStyle, type NoteImageTheme } from "@edgeever/shared/note-image-card";import { prepareNoteImageAssets } from "@edgeever/shared/note-image-fonts";import { noteImageAssetUrls } from "@edgeever/shared/note-image-assets";@@ -63,8 +63,9 @@ if (config && list) {name.textContent = item.label;const sample = document.createElement("span");const needsFont = item.id === "auto" || isRemoteNoteImageFont(item.id);- sample.className = needsFont ? "font-status" : "font-sample";- sample.textContent = needsFont ? config.loading : text;+ const previewEnabled = shouldLoadFontPreview(item.id, item.id === config.selected);+ sample.className = needsFont && previewEnabled ? "font-status" : "font-sample";+ sample.textContent = needsFont && previewEnabled ? config.loading : text;if (!needsFont) sample.style.fontFamily = resolveNoteImageTypography(config.theme, item.id).bodyFamily;copy.append(name, sample);const check = document.createElement("span");@@ -90,6 +91,7 @@ if (config && list) {observer.unobserve(entry.target);const row = byElement.get(entry.target as HTMLButtonElement);if (!row) continue;+ if (!shouldLoadFontPreview(row.id, row.id === config.selected)) continue;void prepareNoteImageAssets({ theme: config.theme, fontStyle: row.id, text: row.text, urls: noteImageAssetUrls, embed: false }).then(() => {row.sample.className = "font-sample";diff --git a/apps/mobile/src/components/MobileNoteImageFontPicker.tsx b/apps/mobile/src/components/MobileNoteImageFontPicker.tsxindex a19c2407..659ac9ce 100644--- a/apps/mobile/src/components/MobileNoteImageFontPicker.tsx+++ b/apps/mobile/src/components/MobileNoteImageFontPicker.tsx@@ -2,7 +2,7 @@import { useEffect, useRef, useState } from "react";import type { DOMProps } from "expo/dom";-import { isRemoteNoteImageFont } from "@edgeever/shared/font-catalog";+import { isRemoteNoteImageFont, shouldLoadFontPreview } from "@edgeever/shared/font-catalog";import { resolveNoteImageTypography, type NoteImageFontStyle, type NoteImageTheme } from "@edgeever/shared/note-image-card";import { prepareNoteImageAssets } from "@edgeever/shared/note-image-fonts";import { getMobileNoteImageFontLabel, MOBILE_FONT_OPTIONS, type NoteImageFontLabels } from "../lib/note-image-font-options";@@ -44,6 +44,7 @@ export default function MobileNoteImageFontPicker({ selected, theme, chinese, coif (!entry.isIntersecting) continue;observer.unobserve(entry.target);const id = entry.target.getAttribute("data-font") as NoteImageFontStyle;+ if (!shouldLoadFontPreview(id, id === selected)) continue;const text = chinese && !LATIN_FONTS.has(id) ? "记录此刻的灵感" : "Capture a little inspiration";void prepareNoteImageAssets({ theme, fontStyle: id, text, urls: noteImageAssetUrls, embed: false }).then(() => { if (active) setPreviews(previous => ({ ...previous, [id]: "ready" })); })@@ -76,6 +77,7 @@ export default function MobileNoteImageFontPicker({ selected, theme, chinese, coconst loaded = previews[item.id] === "ready";const failed = previews[item.id] === "error";const needsFont = item.id === "auto" || isRemoteNoteImageFont(item.id);+ const previewEnabled = shouldLoadFontPreview(item.id, item.id === selected);return (<buttonkey={item.id}@@ -93,8 +95,8 @@ export default function MobileNoteImageFontPicker({ selected, theme, chinese, co><span className="font-option-copy"><span className="font-name">{label}</span>- {loaded || !needsFont ? (- <span className="font-sample" style={{ fontFamily: resolveNoteImageTypography(theme, item.id).bodyFamily }}>{sampleFor(item.id)}</span>+ {loaded || !needsFont || !previewEnabled ? (+ <span className="font-sample" style={previewEnabled ? { fontFamily: resolveNoteImageTypography(theme, item.id).bodyFamily } : undefined}>{sampleFor(item.id)}</span>) : (<span className="font-status">{failed? copy.previewUnavailablediff --git a/apps/web/src/components/FontLabel.tsx b/apps/web/src/components/FontLabel.tsxindex a07cbe91..85794e0c 100644--- a/apps/web/src/components/FontLabel.tsx+++ b/apps/web/src/components/FontLabel.tsx@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from "react";import { FontLoadIcon } from "./FontLoadFeedback";import type { FontLoadStatus } from "@/lib/font-load-state";import { useTranslation } from "react-i18next";-import { FONT_CATALOG, isRemoteNoteImageFont } from "@edgeever/shared/font-catalog";+import { FONT_CATALOG, isRemoteNoteImageFont, shouldLoadFontPreview } from "@edgeever/shared/font-catalog";import { LEGACY_BODY_FONTS } from "@edgeever/shared/font-resources";import { loadCatalogFont, loadBodyFont, type BodyFontId } from "@edgeever/shared/font-loader";@@ -25,8 +25,9 @@ export const FontLabel = ({ label, fontId, fontFamily, registrationFamily, enablconst [readyKey, setReadyKey] = useState("");const family = fontFamily ?? (fontId ? `"${registrationFamily ?? (isRemoteNoteImageFont(fontId) ? FONT_CATALOG[fontId].family : LEGACY_BODY_FONTS[fontId].family)}", "EdgeEver Offline Sans", sans-serif` : undefined);const key = `${fontId ?? ""}:${family ?? ""}:${label}:${retryKey}`;+ const canLoad = enabled && shouldLoadFontPreview(fontId, !visibleOnly);useEffect(() => {- if (!enabled) return;+ if (!canLoad) return;let active = true;let started = false;const load = () => {@@ -44,9 +45,9 @@ export const FontLabel = ({ label, fontId, fontFamily, registrationFamily, enablobserver.observe(ref.current);} else load();return () => { active = false; observer?.disconnect(); };- }, [enabled, visibleOnly, fontId, registrationFamily, label, key, loadFont]);+ }, [canLoad, visibleOnly, fontId, registrationFamily, label, key, loadFont]);const ownStatus = progress.key === key ? progress.status : "idle";- useEffect(() => { if (enabled) onStatusChange?.(ownStatus === "idle" ? "loading" : ownStatus); }, [enabled, onStatusChange, ownStatus]);+ useEffect(() => { if (canLoad) onStatusChange?.(ownStatus === "idle" ? "loading" : ownStatus); }, [canLoad, onStatusChange, ownStatus]);const displayStatus = status === "error" || ownStatus === "error" ? "error": status === "loading" || ownStatus === "loading" ? "loading" : status ?? ownStatus;return <span ref={ref} className="inline-flex items-center gap-1.5 text-sm leading-6" aria-busy={displayStatus === "loading"}>diff --git a/apps/web/src/components/PublicSharePage.tsx b/apps/web/src/components/PublicSharePage.tsxindex 0f2c82aa..4c3b1049 100644--- a/apps/web/src/components/PublicSharePage.tsx+++ b/apps/web/src/components/PublicSharePage.tsx@@ -330,10 +330,7 @@ export const PublicShareArticle = ({useEffect(() => {if (publishedBodyFont === undefined) return undefined;if (!publishedBodyFont) {- delete document.documentElement.dataset.editorBodyFont;- document.documentElement.style.removeProperty(- "--editor-body-font-family",- );+ applyEditorBodyFontPreference({ choice: "system", customFamily: "" });} else {applyEditorBodyFontPreference({choice: publishedBodyFont,diff --git a/apps/web/src/components/editor/MarkdownSourceEditor.tsx b/apps/web/src/components/editor/MarkdownSourceEditor.tsxindex 85c09f76..1d2a8785 100644--- a/apps/web/src/components/editor/MarkdownSourceEditor.tsx+++ b/apps/web/src/components/editor/MarkdownSourceEditor.tsx@@ -34,6 +34,7 @@ import { isPrimaryModifierPressed } from "@/lib/app-helpers";import { getAiSlashCommandStart } from "@/lib/editor-shortcuts";import { lightMarkdownHighlightStyles } from "@/lib/markdown-source-highlight";import { cn } from "@/lib/utils";+import { editorFontLoadState } from "@/lib/editor-catalog-fonts";import { getResourceFilesFromDataTransfer } from "./editor-pane-helpers";type PendingPaste = { from: number; to: number; originalText: string };@@ -94,7 +95,7 @@ const baseEditorTheme = EditorView.theme({width: "100%",fontSize: "var(--editor-body-font-size, 16px)",fontFamily:- 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',+ 'var(--editor-code-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace)',},".cm-scroller": {overflow: "auto",@@ -151,6 +152,19 @@ export const MarkdownSourceEditor = forwardRef<MarkdownSourceEditorRef, Markdownconst onSelectionChangeRef = useRef(onSelectionChange);onSelectionChangeRef.current = onSelectionChange;+ useEffect(() => {+ // A CSS variable change and a later font download can both change glyph+ // widths without changing the document. Refresh CodeMirror's measurements.+ const measure = () => cmRef.current?.view?.requestMeasure();+ const observer = new MutationObserver(measure);+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ["style", "data-editor-code-font"],+ });+ const unsubscribe = editorFontLoadState.subscribe(measure);+ return () => { observer.disconnect(); unsubscribe(); };+ }, []);+useEffect(() => {let frame = 0;let cancelled = false;diff --git a/apps/web/src/lib/editor-body-font.test.mjs b/apps/web/src/lib/editor-body-font.test.mjsindex 7d32cd71..69aa6671 100644--- a/apps/web/src/lib/editor-body-font.test.mjs+++ b/apps/web/src/lib/editor-body-font.test.mjs@@ -120,6 +120,28 @@ describe("editor body font preference", () => {expect(style.has("--editor-body-font-family")).toBe(false);});+ test("only known monospace fonts follow the body choice into code, and switching restores the fallback", () => {+ const style = new Map();+ const dataset = {};+ globalThis.document = {+ documentElement: { dataset, style: {+ setProperty: (key, value) => style.set(key, value),+ removeProperty: key => style.delete(key),+ } },+ };+ for (const id of ["maple-mono-cn", "jetbrains"]) {+ applyEditorBodyFontPreference({ choice: id, customFamily: "" });+ expect(dataset.editorCodeFont).toBe(id);+ expect(style.get("--editor-code-font-family")).toContain(FONT_CATALOG[id].family);+ expect(style.get("--editor-code-font-family")).toEndWith("monospace");+ for (const next of ["wenkai", "source-han-serif", "heavy", "custom", "system"]) {+ applyEditorBodyFontPreference({ choice: next, customFamily: "Arial" });+ expect(dataset.editorCodeFont).toBeUndefined();+ expect(style.has("--editor-code-font-family")).toBe(false);+ }+ }+ });+test("returns font preview stacks for bundled choices", () => {expect(getFontChoicePreviewStack("system")).toBeUndefined();expect(getFontChoicePreviewStack("custom")).toBeUndefined();diff --git a/apps/web/src/lib/editor-body-font.ts b/apps/web/src/lib/editor-body-font.tsindex 60c0a0ff..877023e4 100644--- a/apps/web/src/lib/editor-body-font.ts+++ b/apps/web/src/lib/editor-body-font.ts@@ -1,4 +1,4 @@-import { FONT_IDS, isRemoteNoteImageFont, catalogFontStack } from "@edgeever/shared/font-catalog-data";+import { FONT_IDS, isRemoteNoteImageFont, catalogFontStack, catalogCodeFontStack } from "@edgeever/shared/font-catalog-data";import { LEGACY_BODY_FONTS } from "@edgeever/shared/font-defaults";import type { BodyFontId } from "@edgeever/shared/font-loader";import { watchEditorCatalogFont } from "./editor-catalog-fonts";@@ -6,7 +6,7 @@ import { watchEditorCatalogFont } from "./editor-catalog-fonts";export const EDITOR_BODY_FONT_STORAGE_KEY = "edgeever.editorBodyFont";export const EDITOR_BODY_FONT_CUSTOM_STORAGE_KEY = "edgeever.editorBodyFontCustom";-// Legacy choices remain readable, but new selections use the common 23-font directory.+// Legacy choices remain readable, but new selections use the shared font directory.export const LEGACY_EDITOR_BODY_FONT_CHOICES = ["wenkai-screen", "neo-zhi-song", "source-serif"] as const;export const EDITOR_BODY_FONT_CHOICES = ["system", ...FONT_IDS, ...LEGACY_EDITOR_BODY_FONT_CHOICES, "custom"] as const;@@ -97,6 +97,14 @@ export const applyEditorBodyFontPreference = (preference = readEditorBodyFontPrewatchEditorCatalogFont(isRemoteNoteImageFont(preference.choice) || preference.choice in LEGACY_BODY_FONTS ? preference.choice as BodyFontId : undefined);const root = document.documentElement;const stack = resolveEditorBodyFontStack(preference);+ const codeStack = catalogCodeFontStack(preference.choice);+ if (codeStack) {+ root.dataset.editorCodeFont = preference.choice;+ root.style.setProperty("--editor-code-font-family", codeStack);+ } else {+ delete root.dataset.editorCodeFont;+ root.style.removeProperty("--editor-code-font-family");+ }if (!stack) {delete root.dataset.editorBodyFont;root.style.removeProperty("--editor-body-font-family");diff --git a/apps/web/src/lib/editor-catalog-fonts.ts b/apps/web/src/lib/editor-catalog-fonts.tsindex 43aceff1..5fb16117 100644--- a/apps/web/src/lib/editor-catalog-fonts.ts+++ b/apps/web/src/lib/editor-catalog-fonts.ts@@ -21,7 +21,7 @@ const createFontWatcher = (ui = false) => {let last = "";const refresh = () => {if (!active) return;- const text = ui ? document.body.textContent ?? "" : Array.from(document.querySelectorAll<HTMLElement>(".edgeever-editor .ProseMirror, .edgeever-mobile-tiptap-content, .edgeever-editor textarea"))+ const text = ui ? document.body.textContent ?? "" : Array.from(document.querySelectorAll<HTMLElement>(".edgeever-editor .ProseMirror, .edgeever-mobile-tiptap-content, .edgeever-editor textarea, .edgeever-editor .cm-content")).map(node => node instanceof HTMLTextAreaElement ? node.value : node.textContent ?? "").join(" ");const characters = Array.from(new Set(Array.from(text))).sort().join("");if (characters === last && state.getSnapshot() !== "idle") return;diff --git a/apps/web/src/lib/note-print-appearance.test.mjs b/apps/web/src/lib/note-print-appearance.test.mjsindex cd13d005..34d3f6e8 100644--- a/apps/web/src/lib/note-print-appearance.test.mjs+++ b/apps/web/src/lib/note-print-appearance.test.mjs@@ -3,6 +3,17 @@ import { resolveNoteProse } from "@edgeever/shared";import { notePrintAppearanceCss, notePrintAppearanceFromProse } from "./note-print-appearance.ts";describe("note print appearance", () => {+ test("print code follows a selected monospace face but keeps its own fallback for proportional prose", () => {+ for (const choice of ["maple-mono-cn", "jetbrains", "wenkai", "system"]) {+ const css = notePrintAppearanceCss(notePrintAppearanceFromProse(+ resolveNoteProse({}), "github-light", { choice, customFamily: "" },+ ));+ if (choice === "maple-mono-cn" || choice === "jetbrains") {+ expect(css).toContain("--editor-code-font-family:");+ expect(css).toContain(choice === "jetbrains" ? "EdgeEver Share JetBrains Mono" : "EdgeEver Share Maple Mono CN");+ } else expect(css).not.toContain("--editor-code-font-family:");+ }+ });test("keeps native prose on the editor neutrals and passes the account type size", () => {const appearance = notePrintAppearanceFromProse(resolveNoteProse({fontSize: 18,@@ -33,4 +44,4 @@ describe("note print appearance", () => {expect(css).toContain(".edgeever-editor .ProseMirror strong { color: #112233; }");expect(css).not.toContain("not-a-theme");});-});\ No newline at end of file+});diff --git a/apps/web/src/lib/note-print-appearance.ts b/apps/web/src/lib/note-print-appearance.tsindex a99200c6..96efe8f2 100644--- a/apps/web/src/lib/note-print-appearance.ts+++ b/apps/web/src/lib/note-print-appearance.ts@@ -4,7 +4,7 @@ import {type NoteProsePaletteChoice,type ResolvedNoteProse,} from "@edgeever/shared";-import { isRemoteNoteImageFont } from "@edgeever/shared/font-catalog-data";+import { catalogCodeFontStack, isRemoteNoteImageFont } from "@edgeever/shared/font-catalog-data";import { LEGACY_BODY_FONTS } from "@edgeever/shared/font-defaults";import type { BodyFontId } from "@edgeever/shared/font-loader";import type { MermaidThemeName } from "@/components/ThemeProvider";@@ -82,6 +82,8 @@ export const notePrintAppearanceCss = (appearance: NotePrintAppearance) => {if (appearance.fontFamily && CSS_DECLARATION_VALUE.test(appearance.fontFamily)) {declarations.push(`--editor-body-font-family: ${appearance.fontFamily}`);}+ const codeStack = catalogCodeFontStack(appearance.fontId);+ if (codeStack) declarations.push(`--editor-code-font-family: ${codeStack}`);return [`:root { ${declarations.join("; ")}; }`, paletteRules(appearance.palette), appearance.customCss].filter(Boolean).join("\n");diff --git a/apps/web/src/styles/editor-body-fonts.css b/apps/web/src/styles/editor-body-fonts.cssindex 2a9825a7..94d8405b 100644--- a/apps/web/src/styles/editor-body-fonts.css+++ b/apps/web/src/styles/editor-body-fonts.css@@ -1,7 +1,7 @@/* Font files are registered from editor-body-font-faces.ts so Vite emits* desktop-safe asset URLs. These rules only apply the chosen stack.* Missing glyphs fall through to the system CJK fonts in that stack.- * Code, pre, and formula faces keep their own monospace families.+ * Verified monospace choices also apply to code; formulas retain their own faces.*/html[data-editor-body-font] .edgeever-editor .ProseMirror,html[data-editor-body-font] .edgeever-editor textarea[data-edgeever-mobile-editor="plain-textarea"],@@ -15,6 +15,16 @@ html[data-editor-body-font] .edgeever-mobile-tiptap-content :is(h1, h2, h3, h4,font-family: var(--editor-body-font-family);}++/* Explicit monospace choices win over editor themes without restyling math,+ * diagram labels, toolbar controls, or code in the AI sidebar. */+html[data-editor-code-font] .edgeever-editor .ProseMirror :is(code, pre, .edgeever-code-source),+html[data-editor-code-font] .edgeever-editor[data-editor-theme] .ProseMirror :is(code, pre, .edgeever-code-source),+html[data-editor-code-font] .edgeever-mobile-tiptap-content :is(code, pre, .edgeever-code-source),+html[data-editor-code-font] .edgeever-editor textarea[data-edgeever-mobile-editor="plain-textarea"] {+ font-family: var(--editor-code-font-family);+}+/* Interface font is the device chrome. A system note stays on the product* sans stack, and a chosen note face still wins above. Themed editors keep* their own family. Share pages stay on the sans stack so a viewer'sdiff --git a/apps/web/src/styles/note-print.css b/apps/web/src/styles/note-print.cssindex 6b9274d6..77d05f8e 100644--- a/apps/web/src/styles/note-print.css+++ b/apps/web/src/styles/note-print.css@@ -268,7 +268,7 @@box-shadow: inset 0 0 0 1px rgb(61 68 80 / 0.08);padding: 0.08em 0.28em;color: #3d4450;- font-family: "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;+ font-family: var(--editor-code-font-family, "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);font-size: var(--editor-code-font-size, 14px);font-weight: 400;}@@ -284,7 +284,7 @@padding: 0.9rem 1rem;color: #24292e;box-shadow: 0 1px 2px rgb(24 24 24 / 0.03);- font-family: "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;+ font-family: var(--editor-code-font-family, "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);font-size: var(--editor-code-font-size, 14px);font-weight: 550;line-height: 1.6;diff --git a/packages/shared/src/font-catalog-data.ts b/packages/shared/src/font-catalog-data.tsindex 3ed77f76..b209832d 100644--- a/packages/shared/src/font-catalog-data.ts+++ b/packages/shared/src/font-catalog-data.ts@@ -27,7 +27,8 @@ export const FONT_CATALOG = {"dmserif": {"zh": "DM Serif Display", "en": "DM Serif Display", "posterFamily": "DM Serif Display", "labelKey": "editor.imageShare.fontStyles.dmserif", "family": "EdgeEver Share DM Serif Display", "path": "gh/tianma-if/edgeever@0da78f6ce8a4643b2dfb7afe9f7a5101472c4ffb/apps/web/public/poster-fonts/dmserif.woff2", "weight": "400", "bytes": 27692, "sha256": "c0652f22903b1a547ad50495aa3f5314e4f666e34921e9e953e3f545fdde14ba"},"bebas": {"zh": "Bebas Neue", "en": "Bebas Neue", "posterFamily": "Bebas Neue", "labelKey": "editor.imageShare.fontStyles.bebas", "family": "EdgeEver Share Bebas Neue", "path": "gh/tianma-if/edgeever@0da78f6ce8a4643b2dfb7afe9f7a5101472c4ffb/apps/web/public/poster-fonts/bebas.woff2", "weight": "400", "bytes": 15428, "sha256": "83baf2705cd75f7047e8d11dc9aceeb4ee50407a72f1981937b0b909227b1e68"},"spacegrotesk": {"zh": "Space Grotesk", "en": "Space Grotesk", "posterFamily": "Space Grotesk", "labelKey": "editor.imageShare.fontStyles.spacegrotesk", "family": "EdgeEver Share Space Grotesk", "path": "gh/tianma-if/edgeever@0da78f6ce8a4643b2dfb7afe9f7a5101472c4ffb/apps/web/public/poster-fonts/spacegrotesk.woff2", "weight": "400", "bytes": 15600, "sha256": "8c3d72df71f151bd549c89d78b146858c25e4d16d3a3bfe79bf93bf37ee2c9ae"},- "jetbrains": {"zh": "JetBrains Mono", "en": "JetBrains Mono", "posterFamily": "JetBrains Mono", "labelKey": "editor.imageShare.fontStyles.jetbrains", "family": "EdgeEver Share JetBrains Mono", "path": "gh/tianma-if/edgeever@0da78f6ce8a4643b2dfb7afe9f7a5101472c4ffb/apps/web/public/poster-fonts/jetbrains.woff2", "weight": "400", "bytes": 22516, "sha256": "1d5b5738120473ecb0d758290426d6d4b59873b7f3d4608541989cd0ab5452e3"},+ "maple-mono-cn": { zh: "Maple Mono CN", en: "Maple Mono CN", posterFamily: "Maple Mono CN", labelKey: "editor.imageShare.fontStyles.mapleMonoCn", family: "EdgeEver Share Maple Mono CN", path: "@chinese-fonts/[email protected]/dist/MapleMono-CN-Regular/result.css", downloadOnSelect: true, monospace: true },+ "jetbrains": {"monospace": true, "zh": "JetBrains Mono", "en": "JetBrains Mono", "posterFamily": "JetBrains Mono", "labelKey": "editor.imageShare.fontStyles.jetbrains", "family": "EdgeEver Share JetBrains Mono", "path": "gh/tianma-if/edgeever@0da78f6ce8a4643b2dfb7afe9f7a5101472c4ffb/apps/web/public/poster-fonts/jetbrains.woff2", "weight": "400", "bytes": 22516, "sha256": "1d5b5738120473ecb0d758290426d6d4b59873b7f3d4608541989cd0ab5452e3"},} as const;/** The five entries in Qiaomu's approximately 15 MB designer starter pack. */@@ -40,10 +41,26 @@ export const FONT_IDS = Object.keys(FONT_CATALOG) as RemoteNoteImageFont[];/** Note-body settings menu only. Poster and image-share lists keep FONT_IDS order. */export const NOTE_BODY_FONT_MENU_GROUPS = {- chineseReading: ["wenkai", "zhuque", "source-han-serif", "source-han-sans", "puhui"],+ chineseReading: ["wenkai", "zhuque", "source-han-serif", "source-han-sans", "puhui", "maple-mono-cn"],chineseDisplay: ["smiley", "heavy", "puhui-heavy", "youshe", "shuhei", "douyin", "mashan", "jiangcheng", "huangyou", "glow", "kuaile", "source-han-serif-heavy"],latin: ["inter", "spacegrotesk", "dmserif", "anton", "bebas", "jetbrains"],} as const satisfies Record<"chineseReading" | "chineseDisplay" | "latin", readonly RemoteNoteImageFont[]>;export const findCatalogFont = (idOrFamily: string) => FONT_IDS.find(id => id === idOrFamily || FONT_CATALOG[id].family === idOrFamily || FONT_CATALOG[id].posterFamily === idOrFamily);export const catalogFontStack = (id: RemoteNoteImageFont) => `"${FONT_CATALOG[id].family}", "${OFFLINE_SANS_FAMILY}", system-ui, sans-serif`;export const CATALOG_FONT_STACKS = Object.fromEntries(FONT_IDS.map(id => [id, catalogFontStack(id)])) as Record<RemoteNoteImageFont, string>;++/** Selection-only fonts must not download merely because their menu row is visible. */+export const shouldLoadFontPreview = (id: string | undefined, selected: boolean) => {+ if (!id || !isRemoteNoteImageFont(id)) return true;+ const font = FONT_CATALOG[id];+ return selected || !("downloadOnSelect" in font && font.downloadOnSelect);+};++/** Only verified monospace choices can replace a code editor's font. */+export const catalogCodeFontStack = (id: string | null | undefined): string | null => {+ if (!id || !isRemoteNoteImageFont(id)) return null;+ const font = FONT_CATALOG[id];+ return "monospace" in font && font.monospace+ ? `"${font.family}", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace`+ : null;+};diff --git a/packages/shared/src/font-catalog.test.mjs b/packages/shared/src/font-catalog.test.mjsindex 980a39ac..a2f587b0 100644--- a/packages/shared/src/font-catalog.test.mjs+++ b/packages/shared/src/font-catalog.test.mjs@@ -1,5 +1,5 @@import { expect, test } from "bun:test";-import { FONT_CATALOG, FONT_IDS, NOTE_BODY_FONT_MENU_GROUPS, findCatalogFont } from "./font-catalog";+import { FONT_CATALOG, FONT_IDS, NOTE_BODY_FONT_MENU_GROUPS, findCatalogFont, shouldLoadFontPreview } from "./font-catalog";import { NOTE_IMAGE_REMOTE_FONTS } from "./note-image-remote-fonts";import { NOTE_IMAGE_FONT_FAMILIES } from "./note-image-card";import { NoteBodyFontUpdateSchema } from "./schemas";@@ -7,8 +7,8 @@ import { parsePublishedNoteBodyFont } from "./sharing";import { POSTER_FONTS } from "./poster-fonts";import { createPosterDocument, parsePosterDocument, serializePosterDocument } from "./poster";-test("all 23 catalog fonts are available to sharing, body settings and posters without duplicate poster families", () => {- expect(FONT_IDS).toHaveLength(23);+test("all catalog fonts are available to sharing, body settings and posters without duplicate poster families", () => {+ expect(FONT_IDS).toHaveLength(24);expect(POSTER_FONTS.map(font => font.family)).toEqual(FONT_IDS.map(id => FONT_CATALOG[id].posterFamily));expect(NOTE_IMAGE_REMOTE_FONTS).toBe(FONT_CATALOG);expect(new Set(POSTER_FONTS.map(font => font.family)).size).toBe(POSTER_FONTS.length);@@ -30,7 +30,7 @@ test("all 23 catalog fonts are available to sharing, body settings and posters wtest("the note body menu groups every catalog font once, with reading Chinese before display faces and Latin last", () => {const { chineseReading, chineseDisplay, latin } = NOTE_BODY_FONT_MENU_GROUPS;- expect([...chineseReading]).toEqual(["wenkai", "zhuque", "source-han-serif", "source-han-sans", "puhui"]);+ expect([...chineseReading]).toEqual(["wenkai", "zhuque", "source-han-serif", "source-han-sans", "puhui", "maple-mono-cn"]);expect([...chineseDisplay]).toEqual(["smiley", "heavy", "puhui-heavy", "youshe", "shuhei", "douyin", "mashan", "jiangcheng", "huangyou", "glow", "kuaile", "source-han-serif-heavy"]);expect([...latin]).toEqual(["inter", "spacegrotesk", "dmserif", "anton", "bebas", "jetbrains"]);const grouped = [...chineseReading, ...chineseDisplay, ...latin];@@ -39,6 +39,15 @@ test("the note body menu groups every catalog font once, with reading Chinese beexpect(FONT_IDS[0]).toBe("smiley");});+test("Maple Mono CN waits for selection while existing font previews stay available", () => {+ expect(shouldLoadFontPreview("maple-mono-cn", false)).toBe(false);+ expect(shouldLoadFontPreview("maple-mono-cn", true)).toBe(true);+ for (const id of FONT_IDS.filter(id => id !== "maple-mono-cn")) {+ expect(shouldLoadFontPreview(id, false)).toBe(true);+ }+ expect(shouldLoadFontPreview(undefined, false)).toBe(true);+});+test("poster downloads reuse pinned assets and retain their integrity and license metadata", async () => {const { readFile } = await import("node:fs/promises");const { createHash } = await import("node:crypto");diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex 1d32708b..95f9429c 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -2690,6 +2690,7 @@ export const enUS = {"bebas": "Bebas Neue","spacegrotesk": "Space Grotesk","jetbrains": "JetBrains Mono",+ mapleMonoCn: "Maple Mono CN",auto: "Follow Theme",kai: "Handwritten Kai",diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.tsindex dd566b75..3e66451a 100644--- a/packages/shared/src/i18n/ja.ts+++ b/packages/shared/src/i18n/ja.ts@@ -2679,6 +2679,7 @@ export const ja = {"bebas": "Bebas Neue","spacegrotesk": "Space Grotesk","jetbrains": "JetBrains Mono",+ mapleMonoCn: "Maple Mono CN",auto: "テーマに合わせる",kai: "手書き・楷書",diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.tsindex 586f5eb1..cb50a64e 100644--- a/packages/shared/src/i18n/pl.ts+++ b/packages/shared/src/i18n/pl.ts@@ -2679,6 +2679,7 @@ export const pl = {"bebas": "Bebas Neue","spacegrotesk": "Space Grotesk","jetbrains": "JetBrains Mono",+ mapleMonoCn: "Maple Mono CN",auto: "Zgodnie z motywem",kai: "Pismo odręczne / Kaligrafia",diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.tsindex 3f1f4d62..1a82922f 100644--- a/packages/shared/src/i18n/ru.ts+++ b/packages/shared/src/i18n/ru.ts@@ -2690,6 +2690,7 @@ export const ru = {"bebas": "Bebas Neue","spacegrotesk": "Space Grotesk","jetbrains": "JetBrains Mono",+ mapleMonoCn: "Maple Mono CN",auto: "Как в теме",kai: "Рукописный кай",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex f1a523b9..028fd58a 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -2688,6 +2688,7 @@ export const zhCN = {"bebas": "Bebas Neue","spacegrotesk": "Space Grotesk","jetbrains": "JetBrains Mono",+ mapleMonoCn: "Maple Mono CN",auto: "跟随主题",kai: "文楷手书",diff --git a/packages/shared/src/maple-font-notice.ts b/packages/shared/src/maple-font-notice.tsnew file mode 100644index 00000000..7dcd450e--- /dev/null+++ b/packages/shared/src/maple-font-notice.ts@@ -0,0 +1,2 @@+// Retained with Maple Mono CN font CSS when exporting images and posters.+export const MAPLE_FONT_NOTICE = "Maple Mono CN\nSource: https://github.com/subframe7536/maple-font\nWOFF2 subsets: @chinese-fonts/[email protected] (MapleMono-CN-Regular)\n\nCopyright 2022 The Maple Mono Project Authors (https://github.com/subframe7536/maple-font)\n\nThis Font Software is licensed under the SIL Open Font License, Version 1.1.\nThis license is copied below, and is also available with a FAQ at:\nhttps://openfontlicense.org\n\n\n-----------------------------------------------------------\nSIL OPEN FONT LICENSE Version 1.1 - 26 February 2007\n-----------------------------------------------------------\n\nPREAMBLE\nThe goals of the Open Font License (OFL) are to stimulate worldwide\ndevelopment of collaborative font projects, to support the font creation\nefforts of academic and linguistic communities, and to provide a free and\nopen framework in which fonts may be shared and improved in partnership\nwith others.\n\nThe OFL allows the licensed fonts to be used, studied, modified and\nredistributed freely as long as they are not sold by themselves. The\nfonts, including any derivative works, can be bundled, embedded,\nredistributed and/or sold with any software provided that any reserved\nnames are not used by derivative works. The fonts and derivatives,\nhowever, cannot be released under any other type of license. The\nrequirement for fonts to remain under this license does not apply\nto any document created using the fonts or their derivatives.\n\nDEFINITIONS\n\"Font Software\" refers to the set of files released by the Copyright\nHolder(s) under this license and clearly marked as such. This may\ninclude source files, build scripts and documentation.\n\n\"Reserved Font Name\" refers to any names specified as such after the\ncopyright statement(s).\n\n\"Original Version\" refers to the collection of Font Software components as\ndistributed by the Copyright Holder(s).\n\n\"Modified Version\" refers to any derivative made by adding to, deleting,\nor substituting -- in part or in whole -- any of the components of the\nOriginal Version, by changing formats or by porting the Font Software to a\nnew environment.\n\n\"Author\" refers to any designer, engineer, programmer, technical\nwriter or other person who contributed to the Font Software.\n\nPERMISSION & CONDITIONS\nPermission is hereby granted, free of charge, to any person obtaining\na copy of the Font Software, to use, study, copy, merge, embed, modify,\nredistribute, and sell modified and unmodified copies of the Font\nSoftware, subject to the following conditions:\n\n1) Neither the Font Software nor any of its individual components,\nin Original or Modified Versions, may be sold by itself.\n\n2) Original or Modified Versions of the Font Software may be bundled,\nredistributed and/or sold with any software, provided that each copy\ncontains the above copyright notice and this license. These can be\nincluded either as stand-alone text files, human-readable headers or\nin the appropriate machine-readable metadata fields within text or\nbinary files as long as those fields can be easily viewed by the user.\n\n3) No Modified Version of the Font Software may use the Reserved Font\nName(s) unless explicit written permission is granted by the corresponding\nCopyright Holder. This restriction only applies to the primary font name as\npresented to the users.\n\n4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font\nSoftware shall not be used to promote, endorse or advertise any\nModified Version, except to acknowledge the contribution(s) of the\nCopyright Holder(s) and the Author(s) or with their explicit written\npermission.\n\n5) The Font Software, modified or unmodified, in part or in whole,\nmust be distributed entirely under this license, and must not be\ndistributed under any other license. The requirement for fonts to\nremain under this license does not apply to any document created\nusing the Font Software.\n\nTERMINATION\nThis license becomes null and void if any of the above conditions are\nnot met.\n\nDISCLAIMER\nTHE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\nOF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE\nCOPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nINCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL\nDAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM\nOTHER DEALINGS IN THE FONT SOFTWARE.\n";diff --git a/packages/shared/src/poster-font-notices.ts b/packages/shared/src/poster-font-notices.tsindex 300cdf0d..9a6c74ff 100644--- a/packages/shared/src/poster-font-notices.ts+++ b/packages/shared/src/poster-font-notices.ts@@ -1,5 +1,8 @@+import { MAPLE_FONT_NOTICE } from "./maple-font-notice";+// Existing poster font copyright and license notices, retained in exported font CSS.export const POSTER_FONT_NOTICES: Readonly<Record<string, string>> = {+ "maple-mono-cn": MAPLE_FONT_NOTICE,"source-han-serif": "思源宋体 (Noto Serif SC)\nSource: https://fonts.google.com/noto/specimen/Noto+Serif+SC\nThis copy: subset and converted to WOFF2 by Qiaomu Cover Design\n\n(c) 2017-2024 Adobe (http://www.adobe.com/).\n\nThis Font Software is licensed under the SIL Open Font License, Version 1.1.\nThis license is copied below, and is also available with a FAQ at: https://openfontlicense.org\n\n-----------------------------------------------------------\nSIL OPEN FONT LICENSE Version 1.1 - 26 February 2007\n-----------------------------------------------------------\n\nPREAMBLE\nThe goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.\nThe OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.\nDEFINITIONS\n\"Font Software\" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.\n\"Reserved Font Name\" refers to any names specified as such after the copyright statement(s).\n\"Original Version\" refers to the collection of Font Software components as distributed by the Copyright Holder(s).\n\"Modified Version\" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.\n\"Author\" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.\nPERMISSION & CONDITIONS\nPermission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:\n- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.\n- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.\n- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.\n- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.\n- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.\nTERMINATION\nThis license becomes null and void if any of the above conditions are not met.\nDISCLAIMER\nTHE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.\n","anton": "Anton (Anton)\nSource: https://fonts.google.com/specimen/Anton\nThis copy: subset and converted to WOFF2 by Qiaomu Cover Design\n\nCopyright 2020 The Anton Project Authors (https://github.com/googlefonts/AntonFont.git)\n\nThis Font Software is licensed under the SIL Open Font License, Version 1.1.\nThis license is copied below, and is also available with a FAQ at: https://openfontlicense.org\n\n-----------------------------------------------------------\nSIL OPEN FONT LICENSE Version 1.1 - 26 February 2007\n-----------------------------------------------------------\n\nPREAMBLE\nThe goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.\nThe OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.\nDEFINITIONS\n\"Font Software\" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.\n\"Reserved Font Name\" refers to any names specified as such after the copyright statement(s).\n\"Original Version\" refers to the collection of Font Software components as distributed by the Copyright Holder(s).\n\"Modified Version\" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.\n\"Author\" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.\nPERMISSION & CONDITIONS\nPermission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:\n- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.\n- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.\n- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.\n- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.\n- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.\nTERMINATION\nThis license becomes null and void if any of the above conditions are not met.\nDISCLAIMER\nTHE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.\n","douyin": "抖音美好体 (Douyin Sans)\nSource: https://github.com/bytedance/fonts\nThis copy: unmodified original\n\nCopyright (c) , 2023 Beijing Zitiao Network Technology Co. Ltd.\nwith Reserved Font Names \"Douyin\", \"抖音\", \"抖音美好\".\n\nThis Font Software is licensed under the SIL Open Font License, Version 1.1.\nThis license is copied below, and is also available with a FAQ at: https://openfontlicense.org\n\n-----------------------------------------------------------\nSIL OPEN FONT LICENSE Version 1.1 - 26 February 2007\n-----------------------------------------------------------\n\nPREAMBLE\nThe goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.\nThe OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.\nDEFINITIONS\n\"Font Software\" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.\n\"Reserved Font Name\" refers to any names specified as such after the copyright statement(s).\n\"Original Version\" refers to the collection of Font Software components as distributed by the Copyright Holder(s).\n\"Modified Version\" refers to any derivative made by adding to, deleting, or substituting — in part or in whole — any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.\n\"Author\" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.\nPERMISSION & CONDITIONS\nPermission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:\n- 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.\n- 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.\n- 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.\n- 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.\n- 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.\nTERMINATION\nThis license becomes null and void if any of the above conditions are not met.\nDISCLAIMER\nTHE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.\n",diff --git a/tests/browser/maple-font.html b/tests/browser/maple-font.htmlnew file mode 100644index 00000000..e8ae7c59--- /dev/null+++ b/tests/browser/maple-font.html@@ -0,0 +1,16 @@+<!doctype html>+<html lang="zh-CN">+<head><meta charset="UTF-8"><title>Maple Mono CN 按需下载验证</title></head>+<body style="margin:32px;font:16px/1.8 system-ui,sans-serif">+ <h1>Maple Mono CN 按需下载验证</h1>+ <div id="root"></div>+ <script type="module">+ import RefreshRuntime from "/@react-refresh";+ RefreshRuntime.injectIntoGlobalHook(window);+ window.$RefreshReg$ = () => {};+ window.$RefreshSig$ = () => type => type;+ window.__vite_plugin_react_preamble_installed__ = true;+ </script>+ <script type="module" src="./maple-font.tsx"></script>+</body>+</html>diff --git a/tests/browser/maple-font.tsx b/tests/browser/maple-font.tsxnew file mode 100644index 00000000..53cea947--- /dev/null+++ b/tests/browser/maple-font.tsx@@ -0,0 +1,110 @@+import { useEffect, useRef, useState, useSyncExternalStore } from "react";+import { createRoot } from "react-dom/client";+import i18next from "i18next";+import { I18nextProvider } from "react-i18next";+import { FontLabel } from "../../apps/web/src/components/FontLabel";+import { loadCatalogFont, createRemoteFontResourceLoader } from "../../packages/shared/src/font-loader";+import { FONT_CATALOG, parseRemoteFontCss, remoteFontCssUrl } from "../../packages/shared/src/font-catalog";+import { fontSubsetContains } from "../../packages/shared/src/font-loader";+import type { FontLoadStatus } from "../../apps/web/src/lib/font-load-state";+import { applyEditorBodyFontPreference } from "../../apps/web/src/lib/editor-body-font";+import { editorFontLoadState } from "../../apps/web/src/lib/editor-catalog-fonts";+import { MarkdownSourceEditor, type MarkdownSourceEditorRef } from "../../apps/web/src/components/editor/MarkdownSourceEditor";+import "../../apps/web/src/styles/globals.css";+import "../../apps/web/src/styles/editor-body-fonts.css";++await i18next.init({ lng: "en", resources: { en: { translation: { fontLoad: { loading: "Loading", error: "Unavailable" } } } } });+const font = "maple-mono-cn";+const sample = "记录此刻的灵感 中文 English 0123456789 => !=";+const requests: string[] = [];+const originalOpen = XMLHttpRequest.prototype.open;+XMLHttpRequest.prototype.open = function (...args: Parameters<XMLHttpRequest["open"]>) {+ if (String(args[1]).includes("@chinese-fonts/maple-mono-cn@")) requests.push(String(args[1]));+ return originalOpen.apply(this, args);+};++function Verification() {+ const source = useRef<MarkdownSourceEditorRef>(null);+ const [markdown, setMarkdown] = useState("iii WWW 中文 => !=\n源码独有字:龘\n| 项目 | Value |\n| ---- | ----- |\n| 字体 | Maple |\n");+ const [selected, setSelected] = useState(false);+ const [status, setStatus] = useState<FontLoadStatus>("idle");+ const contentStatus = useSyncExternalStore(editorFontLoadState.subscribe, editorFontLoadState.getSnapshot);+ const [result, setResult] = useState("正在检查未选中选项…");+ useEffect(() => {+ const timer = setTimeout(() => setResult(requests.length === 0+ ? "PASS:列表条目可见时,Maple 字体请求为 0。"+ : `FAIL:未选择就产生了 ${requests.length} 个请求。`), 1200);+ return () => clearTimeout(timer);+ }, []);++ const verifyExportAndCache = async () => {+ try {+ const css = await loadCatalogFont(font, sample, { embed: true });+ if (!css.includes("Copyright 2022 The Maple Mono Project Authors") || !css.includes("data:font/woff2;base64,")) throw new Error("Missing export font or license");+ await document.fonts.ready;+ const ctx = document.createElement("canvas").getContext("2d")!;+ ctx.font = `20px "${FONT_CATALOG[font].family}"`;+ const ratio = ctx.measureText("中").width / ctx.measureText("M").width;+ if (Math.abs(ratio - 2) > 0.01) throw new Error(`CJK/Latin width ratio ${ratio}`);+ const before = requests.length;+ const loader = createRemoteFontResourceLoader();+ const manifest = remoteFontCssUrl(font);+ const blocks = parseRemoteFontCss(new TextDecoder().decode(await loader(manifest, true)), font);+ const points = new Set(Array.from(sample, char => char.codePointAt(0)!));+ const used = blocks.filter(block => fontSubsetContains(block.range, points));+ await Promise.all(used.map(block => loader(block.asset)));+ if (requests.length !== before) throw new Error("Fresh loader did not reuse persistent cache");+ setResult(`PASS:选中后加载成功;中英文宽度 2:1;导出保留字体与授权;新加载器读取缓存时请求为 0。实际下载 ${used.length}/${blocks.length} 个分片。`);+ } catch (error) { setResult(`FAIL:${String(error)}`); }+ };++ const verifyCodeFonts = async () => {+ try {+ const expected = FONT_CATALOG[font].family;+ if (![...document.fonts].some(face => face.family === expected && face.status === "loaded" && fontSubsetContains(face.unicodeRange, new Set([0x9f98])))) throw new Error("Source-only character was not loaded");+ const codeNodes = document.querySelectorAll(".ProseMirror code, .ProseMirror pre, .ProseMirror .edgeever-code-source, .cm-scroller, .cm-content");+ if (codeNodes.length < 7 || [...codeNodes].some(node => !getComputedStyle(node).fontFamily.includes(expected))) throw new Error("A code surface did not follow Maple");+ const before = markdown;+ const x: number[] = [];+ for (const position of [0, 1, 2, 3, 8, 9, 10]) {+ source.current!.setSelection(position, position);+ await new Promise(resolve => requestAnimationFrame(resolve));+ const coords = source.current!.getSelectionCoordinates();+ if (!coords) throw new Error("Missing source cursor coordinates");+ x.push(coords.left);+ }+ const latin = x[1] - x[0];+ if (latin <= 0 || Math.abs((x[2] - x[1]) - latin) > 1 || Math.abs((x[5] - x[4]) - latin * 2) > 1) throw new Error(`Cursor widths: ${x}`);+ source.current!.setSelection(0, 3);+ if (source.current!.sliceText(0, 3) !== "iii") throw new Error("Source selection changed text");+ applyEditorBodyFontPreference({ choice: "custom", customFamily: "Arial" });+ await new Promise(resolve => requestAnimationFrame(resolve));+ if ([...codeNodes].some(node => getComputedStyle(node).fontFamily.includes(expected))) throw new Error("Switching to proportional body did not restore code fallback");+ if (source.current!.sliceText(0, source.current!.getDocumentLength()) !== before) throw new Error("Font switch changed document contents");+ applyEditorBodyFontPreference({ choice: font, customFamily: "" });+ setResult("PASS:默认及主题代码块、行内代码、Mermaid 源码和真实 CodeMirror 均使用 Maple;光标位置与选区正确;切回比例字体恢复代码等宽回退,文档内容不变。");+ } catch (error) { setResult(`FAIL:${String(error)}`); }+ };++ return <>+ <p role="status">{result}</p>+ <p>列表选项:<FontLabel label="Maple Mono CN" fontId={font} enabled visibleOnly /></p>+ <button onClick={() => { applyEditorBodyFontPreference({ choice: font, customFamily: "" }); setSelected(true); }}>选择 Maple Mono CN</button>{" "}+ <button disabled={status !== "ready"} onClick={() => void verifyExportAndCache()}>验证导出与缓存</button>+ {" "}<button disabled={status !== "ready" || contentStatus !== "ready"} onClick={() => void verifyCodeFonts()}>验证代码字体与光标</button>+ {selected && <div>+ <p>选中状态:{status}</p>+ <FontLabel label={sample} fontId={font} enabled onStatusChange={setStatus} />+ </div>}+ {["default", "wechat-green"].map(theme => <section key={theme} className="edgeever-editor" data-editor-theme={theme}>+ <h2>{theme} · 富文本代码</h2>+ <div className="ProseMirror"><p>正文与行内代码 <code>{sample}</code></p><pre><code>{sample}</code></pre><pre className="edgeever-code-source">graph TD; A --> B</pre></div>+ </section>)}+ <section className="edgeever-editor" style={{ height: 220 }}>+ <h2>Markdown 源码</h2>+ <MarkdownSourceEditor ref={source} memoId="maple-font-test" value={markdown} onChange={setMarkdown} themeName="github-light" ariaLabel="字体测试源码" />+ </section>+ </>;+}++createRoot(document.getElementById("root")!).render(<I18nextProvider i18n={i18next}><Verification /></I18nextProvider>);