Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support configurable font controls on desktop and mobile https://github.com/siyuan-note/siyuan/issues/19226

Daniel260d92bd206b
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 42960ed382..ada8b6ba43 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "اضبط ظهور عناصر شريط الأدوات على الأجهزة المحمولة وترتيبها باستخدام ملفات التعريف نفسها لسطح المكتب",
"keymapAssigned": "مُعيَّن",
"keymapCustomized": "مخصص بواسطتي",
"keymapUnassigned": "غير مُعيَّن",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 76bd4eb8d9..14241f691b 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Sichtbarkeit und Reihenfolge der mobilen Werkzeugleiste mit denselben Profilen wie auf dem Desktop konfigurieren",
"keymapAssigned": "Zugewiesen",
"keymapCustomized": "Von mir angepasst",
"keymapUnassigned": "Nicht zugewiesen",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index c0a7099827..a8421a4fe3 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Configure mobile toolbar visibility and order using the same profiles as desktop",
"keymapAssigned": "Assigned",
"keymapCustomized": "Customized by me",
"keymapUnassigned": "Unassigned",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index b693c76d44..c03e229b6a 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Configura la visibilidad y el orden de la barra de herramientas móvil con los mismos perfiles que en escritorio",
"keymapAssigned": "Asignados",
"keymapCustomized": "Personalizados por mí",
"keymapUnassigned": "Sin asignar",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index ec44013a21..37e8116ac8 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Configurer la visibilité et l’ordre de la barre d’outils mobile avec les mêmes profils que sur ordinateur",
"keymapAssigned": "Attribués",
"keymapCustomized": "Personnalisés par moi",
"keymapUnassigned": "Non attribués",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index a3166e322e..77f503fb9c 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "הגדרת הנראות והסדר של סרגל הכלים בנייד באמצעות אותם פרופילים כמו במחשב",
"keymapAssigned": "מוקצים",
"keymapCustomized": "מותאמים אישית על ידי",
"keymapUnassigned": "לא מוקצים",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 90877ce292..acde84484b 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "डेस्कटॉप वाली प्रोफ़ाइल का उपयोग करके मोबाइल टूलबार की दृश्यता और क्रम कॉन्फ़िगर करें",
"keymapAssigned": "असाइन किए गए",
"keymapCustomized": "मेरे द्वारा अनुकूलित",
"keymapUnassigned": "असाइन नहीं किए गए",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index c4db690db0..665993253f 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Atur visibilitas dan urutan bilah alat seluler menggunakan profil yang sama dengan desktop",
"keymapAssigned": "Ditetapkan",
"keymapCustomized": "Disesuaikan oleh saya",
"keymapUnassigned": "Belum ditetapkan",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 610c8dd197..18dd964a7a 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Configura visibilità e ordine della barra degli strumenti mobile usando gli stessi profili del desktop",
"keymapAssigned": "Assegnate",
"keymapCustomized": "Personalizzate da me",
"keymapUnassigned": "Non assegnate",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 8bb0d7c079..cca94af19c 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "デスクトップと共通のプロファイルで、モバイルのツールバー項目の表示と順序を設定",
"keymapAssigned": "割り当て済み",
"keymapCustomized": "自分でカスタマイズ",
"keymapUnassigned": "未割り当て",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 47dbc5f3bf..3a93938025 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "데스크톱과 동일한 프로필로 모바일 도구 모음 항목의 표시 여부와 순서 설정",
"keymapAssigned": "할당됨",
"keymapCustomized": "내가 사용자 지정함",
"keymapUnassigned": "할당되지 않음",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 2ac29728ac..bd9fa7af5a 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Configureer de zichtbaarheid en volgorde van de mobiele werkbalk met dezelfde profielen als op de desktop",
"keymapAssigned": "Toegewezen",
"keymapCustomized": "Door mij aangepast",
"keymapUnassigned": "Niet toegewezen",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 5d44862a68..fee26c6ba4 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Skonfiguruj widoczność i kolejność mobilnego paska narzędzi przy użyciu tych samych profili co na komputerze",
"keymapAssigned": "Przypisane",
"keymapCustomized": "Dostosowane przeze mnie",
"keymapUnassigned": "Nieprzypisane",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 47c8a1bda0..315263bfa5 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Configure a visibilidade e a ordem da barra de ferramentas móvel usando os mesmos perfis da versão para computador",
"keymapAssigned": "Atribuídos",
"keymapCustomized": "Personalizados por mim",
"keymapUnassigned": "Não atribuídos",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index fba75b7d40..7c8a39f164 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Настройте видимость и порядок элементов мобильной панели инструментов, используя общие с настольной версией профили",
"keymapAssigned": "Назначенные",
"keymapCustomized": "Настроенные мной",
"keymapUnassigned": "Неназначенные",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index f0c77a489b..b81a65daf2 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Nastavte viditeľnosť a poradie mobilného panela nástrojov pomocou rovnakých profilov ako na počítači",
"keymapAssigned": "Priradené",
"keymapCustomized": "Upravené mnou",
"keymapUnassigned": "Nepriradené",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 62cb45b7bf..6aabe64cfc 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "กำหนดการแสดงและลำดับรายการในแถบเครื่องมือบนมือถือโดยใช้โปรไฟล์เดียวกับเดสก์ท็อป",
"keymapAssigned": "กำหนดแล้ว",
"keymapCustomized": "ปรับแต่งโดยฉัน",
"keymapUnassigned": "ยังไม่ได้กำหนด",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index ac322d2068..2111e5eae4 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Masaüstü ile aynı profilleri kullanarak mobil araç çubuğunun görünürlüğünü ve sırasını yapılandırın",
"keymapAssigned": "Atanmış",
"keymapCustomized": "Benim özelleştirdiklerim",
"keymapUnassigned": "Atanmamış",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 4dbfd8e873..8a4e9f6ab1 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "Налаштуйте видимість і порядок елементів мобільної панелі інструментів, використовуючи спільні з настільною версією профілі",
"keymapAssigned": "Призначені",
"keymapCustomized": "Налаштовані мною",
"keymapUnassigned": "Непризначені",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 82d4454e3b..68df0124e9 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "配置移动端工具栏项的显隐与排序,与桌面端共用方案",
"keymapAssigned": "已分配",
"keymapCustomized": "由我分配",
"keymapUnassigned": "未分配",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 94908c0321..5904e99e63 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "mobileToolbarEntryTip": "設定行動端工具列項目的顯示與排序,與桌面端共用方案",
"keymapAssigned": "已指派",
"keymapCustomized": "由我指派",
"keymapUnassigned": "未指派",
diff --git a/app/src/assets/scss/business/_config.scss b/app/src/assets/scss/business/_config.scss
index 6ce76a732b..fdf15693c0 100644
--- a/app/src/assets/scss/business/_config.scss
+++ b/app/src/assets/scss/business/_config.scss
@@ -1145,6 +1145,25 @@
}
&-entry-visibility {
+ &__view--mobile {
+ .config-entry-visibility__column {
+ flex: 1 0 100%;
+ }
+
+ .config-entry-visibility__browser {
+ margin: 0 8px 8px;
+ }
+
+ .config-entry-visibility__drag,
+ .config-entry-visibility__arrow-space {
+ display: none;
+ }
+
+ .config-entry-visibility__row {
+ min-height: 44px;
+ }
+ }
+
&__content {
box-sizing: border-box;
display: flex;
diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scss
index 1932f9a098..8f0ba23f5f 100644
--- a/app/src/assets/scss/main/_mobile.scss
+++ b/app/src/assets/scss/main/_mobile.scss
@@ -1284,6 +1284,20 @@ body.mobile-topbar--merged {
border: 0;
color: var(--b3-theme-on-surface);
+ &[data-type="font-family"],
+ &[data-type="font-size"] {
+ padding: 0 8px;
+ white-space: nowrap;
+ flex-shrink: 0;
+ max-width: 100px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+
+ &.protyle-toolbar__item--current {
+ color: var(--b3-theme-primary);
+ }
+ }
+
span {
padding: 6px;
white-space: nowrap;
diff --git a/app/src/assets/scss/protyle/_toolbar.scss b/app/src/assets/scss/protyle/_toolbar.scss
index 25f19bddf6..0d79b87987 100644
--- a/app/src/assets/scss/protyle/_toolbar.scss
+++ b/app/src/assets/scss/protyle/_toolbar.scss
@@ -63,6 +63,23 @@
margin: 6px 4px;
}
+ &__font {
+ font-size: 12px;
+ max-width: 96px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ }
+
+ &-font-size {
+ padding: 8px;
+ width: 220px;
+
+ input[type="number"] {
+ min-width: 0;
+ width: 120px;
+ }
}
&-hint {
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index 437ec59113..e4220a9531 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -308,7 +308,7 @@ test("toolbar catalog follows the default toolbar declaration", () => {
const children = getEntryCatalogChildren(TOOLBAR_ENTRY_ROOT_PATH);
assert.deepEqual(children.map((item) => item.key), DESKTOP_TOOLBAR_ENTRIES.map((item) => item.key));
assert.equal(children.filter((item) => item.type === "separator").length, 2);
- assert.equal(children.every((item) => item.simple), true);
+ assert.deepEqual(children.filter((item) => !item.simple).map(item => item.key), ["font-family", "font-size"]);
});
test("inline text paste entries follow the menu order", () => {
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index e4c5f3e269..7950ff06fd 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -470,7 +470,7 @@ export const SLASH_MENU_ROOT_PATH = "editor.slash.menu";
const toolbarBuiltinChildren = DESKTOP_TOOLBAR_ENTRIES.map((item) => item.separator
? separator(item.key)
- : node(item.key, lang(item.lang)));
+ : node(item.key, lang(item.lang), !["font-family", "font-size"].includes(item.key)));
const toolbarBuiltinNodeMap = new Map(toolbarBuiltinChildren.map((item) => [item.key, item]));
const slashMenuBuiltinChildren = [
diff --git a/app/src/config/entryVisibility/dockOrder.test.ts b/app/src/config/entryVisibility/dockOrder.test.ts
index 6dc2e2679d..df272dcdae 100644
--- a/app/src/config/entryVisibility/dockOrder.test.ts
+++ b/app/src/config/entryVisibility/dockOrder.test.ts
@@ -53,6 +53,23 @@ class FakeDockItem {
}
}
+test("entry settings can read dock defaults without a desktop layout", () => {
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, "window");
+ Object.defineProperty(globalThis, "window", {configurable: true, value: {siyuan: {}}});
+ try {
+ assert.equal(getDockOrderContainer(DOCK_ORDER_SCOPE_BY_POSITION.LeftTop), undefined);
+ const snapshot = getCurrentDockEntryOrderSnapshot();
+ assert.equal(DOCK_ORDER_SCOPES.every(scope => snapshot[scope].length === 0), true);
+ assert.doesNotThrow(() => getDockEntryOrderSnapshot());
+ } finally {
+ if (descriptor) {
+ Object.defineProperty(globalThis, "window", descriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, "window");
+ }
+ }
+});
+
class FakeDockContainer {
public children: FakeDockItem[] = [];
diff --git a/app/src/config/entryVisibility/dockOrder.ts b/app/src/config/entryVisibility/dockOrder.ts
index 93e48584d7..224ff3bdfa 100644
--- a/app/src/config/entryVisibility/dockOrder.ts
+++ b/app/src/config/entryVisibility/dockOrder.ts
@@ -136,17 +136,17 @@ export const getDockOrderContainer = (
) => {
switch (getDockOrderScopePosition(scope)) {
case "LeftTop":
- return layout.leftDock?.elements[0];
+ return layout?.leftDock?.elements[0];
case "LeftBottom":
- return layout.leftDock?.elements[1];
+ return layout?.leftDock?.elements[1];
case "RightTop":
- return layout.rightDock?.elements[0];
+ return layout?.rightDock?.elements[0];
case "RightBottom":
- return layout.rightDock?.elements[1];
+ return layout?.rightDock?.elements[1];
case "BottomLeft":
- return layout.bottomDock?.elements[0];
+ return layout?.bottomDock?.elements[0];
case "BottomRight":
- return layout.bottomDock?.elements[1];
+ return layout?.bottomDock?.elements[1];
}
};
diff --git a/app/src/config/entryVisibility/runtime.ts b/app/src/config/entryVisibility/runtime.ts
index b3cc387fa8..a3ab0b2302 100644
--- a/app/src/config/entryVisibility/runtime.ts
+++ b/app/src/config/entryVisibility/runtime.ts
@@ -56,8 +56,14 @@ const getTemplateVisibility = (path: string, template: TEntryVisibilityTemplate)
export const isEntryVisible = (path: string): boolean => {
/// #if MOBILE
- return true;
- /// #else
+ if (!path.startsWith(`${TOOLBAR_ENTRY_ROOT_PATH}.`)) {
+ return true;
+ }
+ /// #endif
+ return getConfiguredEntryVisibility(path);
+};
+
+export const getConfiguredEntryVisibility = (path: string): boolean => {
const config = getConfig();
const active = config.active;
let visible: boolean;
@@ -73,10 +79,9 @@ export const isEntryVisible = (path: string): boolean => {
}
const parentPath = getEntryParentPath(path);
if (parentPath && getEntryCatalogNode(parentPath)) {
- return isEntryVisible(parentPath);
+ return getConfiguredEntryVisibility(parentPath);
}
return true;
- /// #endif
};
export const createEntryProfileSnapshot = (template: TEntryVisibilityTemplate) => {
@@ -442,8 +447,8 @@ const applyEntryVisibilityLocal = (config: Config.IEntryVisibility) => {
applyTopBarEntryVisibility();
applyDockEntryVisibility();
document.querySelectorAll<HTMLElement>(".protyle-toolbar").forEach(applyToolbarEntryVisibility);
- window.dispatchEvent(new CustomEvent("siyuan-entry-visibility"));
/// #endif
+ window.dispatchEvent(new CustomEvent("siyuan-entry-visibility"));
};
export const applyEntryVisibility = (config: Config.IEntryVisibility) => {
diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.ts
index f44885f76f..d2fe0b90c8 100644
--- a/app/src/config/entryVisibility/ui.ts
+++ b/app/src/config/entryVisibility/ui.ts
@@ -23,7 +23,7 @@ import {
ENTRY_PROFILE_FULL,
ENTRY_PROFILE_SIMPLE,
ENTRY_VISIBILITY_VERSION,
- isEntryVisible,
+ getConfiguredEntryVisibility as isEntryVisible,
saveEntryVisibility,
TEntryVisibilityTemplate,
} from "./runtime";
@@ -40,6 +40,8 @@ import {
TEntryVisibilityImportProfile,
} from "./profile";
import {getHostCapabilities} from "../../util/hostCapabilities";
+import {isMobile} from "../../util/functions";
+import {MOBILE_TOOLBAR_NAMES, TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";
import {
DOCK_ORDER_SCOPES,
DOCK_ORDER_SCOPES_BY_SIDE,
@@ -52,6 +54,15 @@ import {
TDockOrderSnapshot,
} from "./dockOrder";
+const getVisibleEntryCatalog = () => isMobile() ? entryCatalog.filter(item => item.key === TOOLBAR_ENTRY_ROOT_PATH)
+ .map(item => ({...item, children: item.children.filter(child => child.type === "separator" ||
+ MOBILE_TOOLBAR_NAMES.includes(child.key) || child.key.startsWith("plugin:"))})) : entryCatalog;
+
+const renderTouchOrderButtons = (enabled: boolean) => isMobile() && enabled ? ["up", "down"].map(direction =>
+ `<button type="button" class="block__icon block__icon--show" data-entry-move="${direction}"
+ aria-label="${escapeAttr(window.siyuan.languages[direction])}">
+ <svg><use xlink:href="#${direction === "up" ? "iconUp" : "iconDown"}"></use></svg></button>`).join("") : "";
+
type TImportFile = {
type: "siyuan-entry-profile" | "siyuan-entry-profile-bundle";
version: number;
@@ -154,6 +165,9 @@ const createEntryView = (root: HTMLElement) => {
removeEntryView(root);
const view = document.createElement("div");
view.className = "config-entry-visibility__view config__view";
+ if (isMobile()) {
+ view.classList.add("config-entry-visibility__view--mobile");
+ }
view.innerHTML = `<div class="b3-dialog__header fn__flex">
<div class="block__logo fn__pointer fn__flex-1" data-action="back">
<svg class="block__logoicon"><use xlink:href="#iconLeft"></use></svg>
@@ -248,6 +262,7 @@ const renderEntryRows = (profile: Config.IEntryVisibilityProfile, prefix: string
data-entry-row data-entry-key="${escapeAttr(item.key)}" data-entry-parent="${escapeAttr(prefix)}">
${draggable ? '<span class="config-entry-visibility__drag" draggable="true"><svg><use xlink:href="#iconDrag"></use></svg></span>' : ""}
<span class="config-entry-visibility__label">${window.siyuan.languages.entrySeparator}</span>
+ ${renderTouchOrderButtons(draggable && !readOnly)}
${renderEntrySwitch(profile, path, item, parentEnabled, readOnly)}
<span class="config-entry-visibility__arrow-space"></span>
</div>`;
@@ -265,6 +280,7 @@ const renderEntryRows = (profile: Config.IEntryVisibilityProfile, prefix: string
<span>${escapeHtml(label)}</span>
</button>` : `<span class="config-entry-visibility__label" title="${escapeAttr(label)}">${escapeHtml(label)}</span>`}
${configurable ? renderEntrySwitch(profile, path, item, parentEnabled, readOnly) : ""}
+ ${renderTouchOrderButtons(draggable && !readOnly)}
${hasChildren ? `<button class="block__icon block__icon--show config-entry-visibility__arrow" data-action="navigate-entry"
data-entry-path="${escapeAttr(path)}" data-entry-depth="${depth}" aria-label="${escapeAttr(window.siyuan.languages.expand)}">
<svg><use xlink:href="#iconRight"></use></svg>
@@ -409,17 +425,18 @@ const getDockEntrySelectedPaths = (key: string) => [`${DOCK_SECTION_KEY}.${key}`
const renderEntryColumns = (profile: Config.IEntryVisibilityProfile, sectionKey: string,
selectedPaths: string[], readOnly: boolean, visiblePaths?: Set<string>,
visibleSectionKeys?: Set<string>, dockOrderSnapshot = getDockEntryOrderSnapshot()) => {
+ const catalog = getVisibleEntryCatalog();
const sections = visibleSectionKeys
- ? entryCatalog.filter((item) => visibleSectionKeys.has(item.key))
- : entryCatalog;
- const section = sections.find((item) => item.key === sectionKey) || sections[0] || entryCatalog[0];
+ ? catalog.filter((item) => visibleSectionKeys.has(item.key))
+ : catalog;
+ const section = sections.find((item) => item.key === sectionKey) || sections[0] || catalog[0];
const locationColumn = `<section class="config-entry-visibility__column config-entry-visibility__column--locations" data-entry-column>
<div class="config-entry-visibility__column-title">${window.siyuan.languages.position}</div>
<div class="config-entry-visibility__column-list">
${sections.map((item) => renderEntryLocation(profile, item, item.key === section.key, readOnly)).join("")}
</div>
</section>`;
- const columns = [locationColumn];
+ const columns = isMobile() ? [] : [locationColumn];
if (section.key === DOCK_SECTION_KEY) {
renderDockColumns(columns, profile, selectedPaths, readOnly, dockOrderSnapshot, visiblePaths);
return `<div class="config-entry-visibility__columns">${columns.join("")}</div>`;
@@ -486,7 +503,7 @@ const getEntrySearchResults = (query: string) => {
}
});
};
- entryCatalog.forEach((section) => visit(section, section.key, section.children, [section.label()]));
+ getVisibleEntryCatalog().forEach((section) => visit(section, section.key, section.children, [section.label()]));
return results;
};
@@ -562,7 +579,7 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {
</div>`;
const browser = view.querySelector<HTMLElement>("[data-type='entry-browser']");
const searchInput = view.querySelector<HTMLInputElement>("[data-type='entry-search']");
- let selectedSectionKey = entryCatalog[0].key;
+ let selectedSectionKey = getVisibleEntryCatalog()[0].key;
let selectedPaths: string[] = [];
let previousQuery = "";
let dragging: {
@@ -635,6 +652,35 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {
};
renderBrowser();
searchInput.addEventListener("input", () => renderBrowser());
+ browser.addEventListener("click", event => {
+ const button = (event.target as Element).closest<HTMLElement>("[data-entry-move]");
+ if (!button) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ if (builtin || searchInput.value.trim()) {
+ return;
+ }
+ const row = button.closest<HTMLElement>("[data-entry-row]");
+ const parent = row.dataset.entryParent;
+ const nodes = getEntryCatalogChildren(parent);
+ const order = getProfileEntryOrder(draft, parent, nodes);
+ const rows = Array.from(row.parentElement.querySelectorAll<HTMLElement>("[data-entry-row]"));
+ const after = button.dataset.entryMove === "down";
+ const target = rows[rows.indexOf(row) + (after ? 1 : -1)];
+ if (!target) {
+ return;
+ }
+ const updated = moveEntryOrder(order, row.dataset.entryKey, target.dataset.entryKey, after,
+ new Set(nodes.filter(item => item.type === "separator").map(item => item.key)));
+ if (updated) {
+ draft.orders ||= {};
+ draft.orders[parent] = mergeEntryOrderPreservingUnknown(nodes.map(item => item.key),
+ draft.orders[parent], updated, new Set(nodes.filter(item => item.type === "separator").map(item => item.key)));
+ renderBrowser();
+ }
+ });
browser.addEventListener("dragstart", (event: DragEvent) => {
if (builtin || searchInput.value.trim()) {
event.preventDefault();
@@ -887,7 +933,7 @@ const importProfiles = async (root: HTMLElement, file: File) => {
export const genEntryVisibilityHtml = () => `<div class="b3-label config-item" data-type="entry-visibility">
<div class="fn__flex">
- <div><div class="config-name">${window.siyuan.languages.entryVisibility}</div><div class="b3-label__text">${window.siyuan.languages.entryVisibilityTip}</div></div>
+ <div><div class="config-name">${window.siyuan.languages.entryVisibility}</div><div class="b3-label__text">${isMobile() ? window.siyuan.languages.mobileToolbarEntryTip : window.siyuan.languages.entryVisibilityTip}</div></div>
<span class="fn__space fn__flex-1"></span>
${getHostCapabilities().importExport ? `<button class="b3-button b3-button--outline" data-action="import"><svg class="b3-button__icon"><use xlink:href="#iconUpload"></use></svg>${window.siyuan.languages.import}</button>
<span class="fn__space"></span>
diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.ts
index 9dc9533407..5497df120b 100644
--- a/app/src/config/tabs/appearanceTab.ts
+++ b/app/src/config/tabs/appearanceTab.ts
@@ -928,13 +928,13 @@ const registerAppearanceControlsGroup = (tab: SettingTabBuilder) => {
afterMount: mountMobileSidePanelSetting,
});
/// #endif
- /// #if !MOBILE
group.slot({
key: "entryVisibility",
keywords: [window.siyuan.languages.entryVisibility, window.siyuan.languages.entryVisibilityTip],
html: genEntryVisibilityHtml,
afterMount: mountEntryVisibility,
});
+ /// #if !MOBILE
group.select("editor.floatWindowMode", {
title: window.siyuan.languages.floatWindowMode,
desc: window.siyuan.languages.floatWindowModeTip,
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 371f3bc440..ee0b2edd3b 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -71,6 +71,17 @@ import {
} from "../../protyle/toolbar/fontFamilyMenu";
import {notifyMobileKeyboardChange} from "./mobileKeyboardChange";
import {getEditorFocusRange, restoreEditorFocusRange} from "../../protyle/util/editorFocus";
+import {createFontSizePicker} from "../../protyle/toolbar/fontControls";
+import {applyMobileToolbarEntries} from "./toolbarEntries";
+import {getEntryOrder, isEntryVisible} from "../../config/entryVisibility/runtime";
+import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";
+
+const applyKeyboardToolbarEntries = (element: HTMLElement, toolbar: Array<string | IMenuItem>) => {
+ applyMobileToolbarEntries(element, toolbar, {
+ order: getEntryOrder(TOOLBAR_ENTRY_ROOT_PATH),
+ isVisible: key => isEntryVisible(`${TOOLBAR_ENTRY_ROOT_PATH}.${key}`),
+ });
+};
type TAndroidBoundedSelection = {
container: HTMLElement,
@@ -122,7 +133,7 @@ export const updateMobilePluginToolbar = (protyle: IProtyle) => {
return;
}
inlineToolbarElement.querySelectorAll('[data-plugin-toolbar="true"]').forEach(item => item.remove());
- getMobilePluginToolbarItems(protyle.options.toolbar, Constants.INLINE_TYPE).forEach(toolbarItem => {
+ getMobilePluginToolbarItems(protyle.options.toolbar, Constants.INLINE_TYPE.concat("font-family", "font-size")).forEach(toolbarItem => {
const itemElement = document.createElement("button");
itemElement.className = "keyboard__action";
itemElement.dataset.type = toolbarItem.name;
@@ -134,6 +145,7 @@ export const updateMobilePluginToolbar = (protyle: IProtyle) => {
}
inlineToolbarElement.append(itemElement);
});
+ applyKeyboardToolbarEntries(inlineToolbarElement, protyle.options.toolbar);
};
const clearAndroidBoundedSelection = () => {
@@ -767,6 +779,8 @@ const hideKeyboardToolbarUtil = () => {
}
toolbarElement.querySelector('.keyboard__action[data-type="add"]').classList.remove("protyle-toolbar__item--current");
toolbarElement.querySelector('.keyboard__action[data-type="text"]').classList.remove("protyle-toolbar__item--current");
+ toolbarElement.querySelectorAll('[data-type="font-family"], [data-type="font-size"]').forEach(item =>
+ item.classList.remove("protyle-toolbar__item--current"));
toolbarElement.querySelector('.keyboard__action[data-type="done"] use').setAttribute("xlink:href", "#iconKeyboardHide");
};
@@ -1219,7 +1233,10 @@ export const initKeyboardToolbar = () => {
<button class="keyboard__action" data-type="goback"><svg><use xlink:href="#iconBack"></use></svg></button>
<button class="keyboard__action" data-type="block-ref"><svg><use xlink:href="#iconRef"></use></svg></button>
<button class="keyboard__action" data-type="a"><svg><use xlink:href="#iconLink"></use></svg></button>
+ <span class="keyboard__split" data-id="separator_1"></span>
<button class="keyboard__action" data-type="text"><svg><use xlink:href="#iconFont"></use></svg></button>
+ <button class="keyboard__action" data-type="font-family" aria-label="${window.siyuan.languages.fontFamily}">${window.siyuan.languages.fontFamily}</button>
+ <button class="keyboard__action" data-type="font-size" aria-label="${window.siyuan.languages.fontSize}">${window.siyuan.languages.fontSize}</button>
<button class="keyboard__action" data-type="strong"><svg><use xlink:href="#iconBold"></use></svg></button>
<button class="keyboard__action" data-type="em"><svg><use xlink:href="#iconItalic"></use></svg></button>
<button class="keyboard__action" data-type="u"><svg><use xlink:href="#iconUnderline"></use></svg></button>
@@ -1227,18 +1244,27 @@ export const initKeyboardToolbar = () => {
<button class="keyboard__action" data-type="mark"><svg><use xlink:href="#iconMark"></use></svg></button>
<button class="keyboard__action" data-type="sup"><svg><use xlink:href="#iconSup"></use></svg></button>
<button class="keyboard__action" data-type="sub"><svg><use xlink:href="#iconSub"></use></svg></button>
- <button class="keyboard__action" data-type="clear"><svg><use xlink:href="#iconClear"></use></svg></button>
<button class="keyboard__action" data-type="code"><svg><use xlink:href="#iconInlineCode"></use></svg></button>
- <button class="keyboard__action" data-type="kbd"<use xlink:href="#iconKeymap"></use></svg></button>
+ <button class="keyboard__action" data-type="kbd"><svg><use xlink:href="#iconKeymap"></use></svg></button>
<button class="keyboard__action" data-type="tag"><svg><use xlink:href="#iconTag"></use></svg></button>
<button class="keyboard__action" data-type="inline-math"><svg><use xlink:href="#iconMath"></use></svg></button>
<button class="keyboard__action" data-type="inline-memo"><svg><use xlink:href="#iconM"></use></svg></button>
+ <span class="keyboard__split" data-id="separator_2"></span>
+ <button class="keyboard__action" data-type="clear"><svg><use xlink:href="#iconClear"></use></svg></button>
</div>
</div>
<span class="keyboard__split"></span>
<button class="keyboard__action" data-type="done"><svg style="width: 36px"><use xlink:href="#iconKeyboardHide"></use></svg></button>
</div>
<div class="keyboard__util"></div>`;
+ const refreshEntries = () => {
+ const protyle = getCurrentEditor()?.protyle;
+ const inline = toolbarElement.querySelector<HTMLElement>('.keyboard__action[data-type="goback"]').parentElement;
+ applyKeyboardToolbarEntries(inline, protyle?.options.toolbar || []);
+ hideKeyboardToolbarUtil();
+ };
+ refreshEntries();
+ window.addEventListener("siyuan-entry-visibility", refreshEntries);
let startY = 0;
let startX = 0;
let moved = false;
@@ -1434,11 +1460,70 @@ export const initKeyboardToolbar = () => {
protyle.toolbar.setInlineMark(protyle, type, "toolbar");
}
return;
+ } else if (type === "font-family" || type === "font-size") {
+ if (buttonElement.classList.contains("protyle-toolbar__item--current")) {
+ hideKeyboardToolbarUtil();
+ focusByRange(range);
+ return;
+ }
+ hideKeyboardToolbarUtil();
+ buttonElement.classList.add("protyle-toolbar__item--current");
+ toolbarElement.querySelector('.keyboard__action[data-type="done"] use').setAttribute("xlink:href", "#iconCloseRound");
+ const savedRange = range.cloneRange();
+ protyle.toolbar.range = savedRange;
+ const nodes = getFontNodeElements(protyle);
+ const util = toolbarElement.querySelector<HTMLElement>(".keyboard__util");
+ const valid = () => getCurrentEditor()?.protyle === protyle && !protyle.disabled &&
+ savedRange.startContainer.isConnected && savedRange.endContainer.isConnected &&
+ buttonElement.classList.contains("protyle-toolbar__item--current");
+ const finish = () => {
+ hideKeyboardToolbarUtil();
+ focusByRange(protyle.toolbar.range);
+ };
+ const apply = (style: string, value: string) => {
+ if (!valid()) {
+ return;
+ }
+ protyle.toolbar.range = savedRange;
+ fontEvent(protyle, nodes, style, value, false);
+ finish();
+ };
+ preventKeyboardToolbarRender();
+ if (type === "font-family") {
+ const state = getInlineFontFamilyState(protyle, nodes);
+ if (state.disabled) {
+ finish();
+ return;
+ }
+ void renderMobileFontFamilyMenu(util, {
+ ...state,
+ isOpenValid: valid,
+ onInteraction: preventKeyboardToolbarRender,
+ onBack() {
+ if (valid()) {
+ protyle.toolbar.range = savedRange;
+ finish();
+ }
+ },
+ onSelect: family => apply("fontFamily", getInlineFontFamilyValue(family)),
+ });
+ } else {
+ util.replaceChildren(createFontSizePicker(protyle, value => apply("fontSize", value), preventKeyboardToolbarRender, () => {
+ if (valid()) {
+ protyle.toolbar.range = savedRange;
+ finish();
+ }
+ }));
+ }
+ showKeyboardToolbarUtil(protyle.contentElement.scrollTop);
+ window.JSAndroid?.hideKeyboard();
+ return;
} else if (type === "text") {
if (buttonElement.classList.contains("protyle-toolbar__item--current")) {
hideKeyboardToolbarUtil();
focusByRange(range);
} else {
+ hideKeyboardToolbarUtil();
buttonElement.classList.add("protyle-toolbar__item--current");
toolbarElement.querySelector('.keyboard__action[data-type="done"] use').setAttribute("xlink:href", "#iconCloseRound");
const oldScrollTop = protyle.contentElement.scrollTop;
diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.ts
index 69803ba656..27c69a6f7b 100644
--- a/app/src/mobile/util/onMessage.ts
+++ b/app/src/mobile/util/onMessage.ts
@@ -24,6 +24,7 @@ import {applyCloudUserState} from "../../config/tabs/accountUi";
import {isInMobileApp} from "../../protyle/util/compatibility";
import {handleMobileKernelExit} from "./kernelExit";
import {sanitizeKernelHTML} from "../../util/hostCapabilities";
+import {applyEntryVisibility} from "../../config/entryVisibility/runtime";
let statusTimeout: number;
const statusElement = document.querySelector("#status") as HTMLElement;
@@ -35,6 +36,9 @@ const dispatchMobileSidePanelConfigChange = () => {
export const onMessage = (app: App, data: IWebSocketData) => {
if (data) {
switch (data.cmd) {
+ case "setEntryVisibility":
+ applyEntryVisibility(data.data);
+ break;
case "logoutAuth":
redirectToCheckAuth();
break;
diff --git a/app/src/mobile/util/toolbarEntries.test.ts b/app/src/mobile/util/toolbarEntries.test.ts
new file mode 100644
index 0000000000..39d1a03b02
--- /dev/null
+++ b/app/src/mobile/util/toolbarEntries.test.ts
@@ -0,0 +1,67 @@
+import * as assert from "node:assert/strict";
+import {test} from "node:test";
+import {applyMobileToolbarEntries} from "./toolbarEntries";
+import {getDefaultToolbar, getPluginToolbarEntryKey, markPluginToolbarEntries} from "../../protyle/toolbar/defaults";
+
+class ToolbarElement {
+ public children: ToolbarElement[] = [];
+ public dataset: {type?: string; id?: string};
+ private classes = new Set<string>();
+ public classList = {
+ contains: (name: string) => this.classes.has(name),
+ toggle: (name: string, enabled: boolean) => enabled ? this.classes.add(name) : this.classes.delete(name),
+ };
+
+ constructor(type?: string, separator?: string) {
+ this.dataset = {type};
+ if (separator) {
+ this.dataset.id = separator;
+ this.classes.add("keyboard__split");
+ }
+ }
+
+ public append(item: ToolbarElement) {
+ this.children = this.children.filter(child => child !== item);
+ this.children.push(item);
+ }
+}
+
+test("mobile toolbar keeps navigation reachable and removes empty separators", () => {
+ const root = new ToolbarElement();
+ const back = new ToolbarElement("goback");
+ const family = new ToolbarElement("font-family");
+ const size = new ToolbarElement("font-size");
+ const first = new ToolbarElement(undefined, "separator_1");
+ const second = new ToolbarElement(undefined, "separator_2");
+ root.children = [back, first, family, second, size];
+ const toolbar = getDefaultToolbar(true);
+ const order = ["separator_1", "font-family", "separator_2", "font-size"];
+ applyMobileToolbarEntries(root as unknown as HTMLElement, toolbar, {order, isVisible: key => key !== "font-family"});
+ assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [back, size]);
+ applyMobileToolbarEntries(root as unknown as HTMLElement, toolbar, {order, isVisible: () => false});
+ assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [back]);
+ applyMobileToolbarEntries(root as unknown as HTMLElement, toolbar, {
+ order: ["font-size", "separator_1", "font-family", "separator_2"], isVisible: () => true,
+ });
+ assert.deepEqual(root.children.filter(item => !item.classList.contains("fn__none")), [back, size, first, family]);
+});
+
+test("mobile toolbar applies plugin visibility and restores its configured order", () => {
+ const defaults = getDefaultToolbar(true);
+ const plugin = {name: "plugin-action"};
+ const toolbar = markPluginToolbarEntries(defaults, [...defaults, plugin], "example", () => "Example");
+ const key = getPluginToolbarEntryKey("example", "plugin-action");
+ const root = new ToolbarElement();
+ const back = new ToolbarElement("goback");
+ const family = new ToolbarElement("font-family");
+ const custom = new ToolbarElement(plugin.name);
+ root.children = [back, family, custom];
+ const order = [key, "font-family"];
+ applyMobileToolbarEntries(root as unknown as HTMLElement, toolbar, {order, isVisible: id => id !== key});
+ assert.equal(custom.dataset.id, key);
+ assert.deepEqual(root.children, [back, custom, family]);
+ assert.equal(custom.classList.contains("fn__none"), true);
+ applyMobileToolbarEntries(root as unknown as HTMLElement, toolbar, {order, isVisible: () => true});
+ assert.deepEqual(root.children, [back, custom, family]);
+ assert.equal(custom.classList.contains("fn__none"), false);
+});
diff --git a/app/src/mobile/util/toolbarEntries.ts b/app/src/mobile/util/toolbarEntries.ts
new file mode 100644
index 0000000000..1fcdd01b51
--- /dev/null
+++ b/app/src/mobile/util/toolbarEntries.ts
@@ -0,0 +1,28 @@
+import {getToolbarEntryId, MOBILE_TOOLBAR_NAMES} from "../../protyle/toolbar/defaults";
+import {resolveToolbarItems} from "../../protyle/toolbar/entryVisibility";
+export const applyMobileToolbarEntries = (element: HTMLElement, toolbar: Array<string | IMenuItem>, options: {
+ order: string[];
+ isVisible: (key: string) => boolean;
+}) => {
+ const items = new Map(toolbar.filter((item): item is IMenuItem => typeof item !== "string")
+ .map(item => [item.name, item]));
+ const children = Array.from(element.children).filter((child: HTMLElement) => child.dataset.type !== "goback") as HTMLElement[];
+ children.forEach(child => {
+ const item = items.get(child.dataset.type);
+ const key = item ? getToolbarEntryId(item) : MOBILE_TOOLBAR_NAMES.includes(child.dataset.type) ? child.dataset.type : undefined;
+ if (key) {
+ child.dataset.id = key;
+ }
+ });
+ const result = resolveToolbarItems(children, {
+ getKey: item => item.dataset.id,
+ isSeparator: item => item.classList.contains("keyboard__split"),
+ isVisible: options.isVisible,
+ order: options.order,
+ });
+ const visible = new Set(result.visible);
+ result.ordered.forEach(item => {
+ element.append(item);
+ item.classList.toggle("fn__none", !visible.has(item));
+ });
+};
diff --git a/app/src/protyle/toolbar/defaults.ts b/app/src/protyle/toolbar/defaults.ts
index 3020127f7d..09f41a5299 100644
--- a/app/src/protyle/toolbar/defaults.ts
+++ b/app/src/protyle/toolbar/defaults.ts
@@ -37,6 +37,14 @@ export const DESKTOP_TOOLBAR_ENTRIES: IToolbarEntry[] = [{
key: "text",
name: "text",
lang: "appearance",
+}, {
+ key: "font-family",
+ name: "font-family",
+ lang: "fontFamily",
+}, {
+ key: "font-size",
+ name: "font-size",
+ lang: "fontSize",
}, {
key: "strong",
name: "strong",
@@ -104,6 +112,9 @@ const desktopToolbarEntryKeys = new Map(DESKTOP_TOOLBAR_ENTRIES
.filter((item) => !item.separator)
.map((item) => [item.name, item.key]));
+export const MOBILE_TOOLBAR_NAMES = DESKTOP_TOOLBAR_ENTRIES
+ .filter(item => !item.separator && item.name !== "format-painter").map(item => item.name);
+
export const isBuiltinToolbarItemName = (name: string) => name === "|" || desktopToolbarEntryKeys.has(name);
const setToolbarEntryMetadata = (item: IMenuItem, id: string, label?: string) => {
@@ -117,25 +128,7 @@ const toolbarSeparator = (entryId: string): IMenuItem => {
};
export const getDefaultToolbar = (mobile: boolean): Array<string | IMenuItem> => {
- if (mobile) {
- return [
- "block-ref",
- "a",
- "ai",
- "|",
- "text",
- "strong",
- "em",
- "u",
- "clear",
- "|",
- "code",
- "tag",
- "inline-math",
- "inline-memo",
- ];
- }
- return DESKTOP_TOOLBAR_ENTRIES.map((item) => {
+ return DESKTOP_TOOLBAR_ENTRIES.filter(item => !mobile || item.name !== "format-painter").map((item) => {
if (item.separator) {
return toolbarSeparator(item.key);
}
diff --git a/app/src/protyle/toolbar/entryVisibility.test.ts b/app/src/protyle/toolbar/entryVisibility.test.ts
index e032c8a945..8c78e475e4 100644
--- a/app/src/protyle/toolbar/entryVisibility.test.ts
+++ b/app/src/protyle/toolbar/entryVisibility.test.ts
@@ -9,12 +9,37 @@ import {
markPluginToolbarEntries,
} from "./defaults";
import {normalizeToolbarSeparators, resolveToolbarItems} from "./entryVisibility";
+import {mergeEntryOrderPreservingUnknown, moveEntryOrder} from "../../config/entryVisibility/order";
interface IToolbarTestItem {
key?: string;
separator?: boolean;
}
+test("mobile toolbar shares desktop identifiers and declaration order", () => {
+ const mobile = getDefaultToolbar(true).map(item => typeof item === "string" ? {name: item} : item);
+ assert.deepEqual(mobile.map(getToolbarEntryId),
+ DESKTOP_TOOLBAR_ENTRIES.filter(item => item.name !== "format-painter").map(item => item.key));
+});
+
+test("font entries merge into old profiles while preserving plugin slots and hidden entries", () => {
+ const defaults = DESKTOP_TOOLBAR_ENTRIES.map(item => item.key);
+ const separators = new Set(DESKTOP_TOOLBAR_ENTRIES.filter(item => item.separator).map(item => item.key));
+ const saved = defaults.filter(key => !["font-family", "font-size"].includes(key));
+ saved.splice(saved.indexOf("strong"), 0, "plugin:unloaded:action");
+ const merged = mergeEntryOrderPreservingUnknown(defaults, saved, undefined, separators);
+ assert.ok(merged.includes("plugin:unloaded:action"));
+ assert.deepEqual(merged.filter(key => !["font-family", "font-size"].includes(key)), saved);
+ const items = defaults.map(key => ({key, separator: separators.has(key)}));
+ const result = resolve(items, {order: merged, hidden: ["text", "font-family"]});
+ assert.equal(result.visible.some(item => item.key === "text" || item.key === "font-family"), false);
+ assert.equal(result.visible.some(item => item.key === "font-size"), true);
+ const moved = moveEntryOrder(defaults, "font-size", "font-family", false, separators);
+ const updated = mergeEntryOrderPreservingUnknown(defaults, merged, moved, separators);
+ assert.ok(updated.includes("plugin:unloaded:action"));
+ assert.ok(updated.indexOf("font-size") < updated.indexOf("font-family"));
+});
+
const resolve = (items: IToolbarTestItem[], options: {
hidden?: string[];
order?: string[];
diff --git a/app/src/protyle/toolbar/entryVisibility.ts b/app/src/protyle/toolbar/entryVisibility.ts
index c1ae8caef4..f3649ee8fa 100644
--- a/app/src/protyle/toolbar/entryVisibility.ts
+++ b/app/src/protyle/toolbar/entryVisibility.ts
@@ -18,7 +18,7 @@ export const normalizeToolbarSeparators = <T>(items: T[], isSeparator: (item: T)
}
result.push(item);
});
- if (isSeparator(result[result.length - 1])) {
+ if (result.length > 0 && isSeparator(result[result.length - 1])) {
result.pop();
}
return result;
diff --git a/app/src/protyle/toolbar/fontControls.ts b/app/src/protyle/toolbar/fontControls.ts
new file mode 100644
index 0000000000..e056ecdc2e
--- /dev/null
+++ b/app/src/protyle/toolbar/fontControls.ts
@@ -0,0 +1,167 @@
+import {Menu} from "../../plugin/Menu";
+import {ToolbarItem} from "./ToolbarItem";
+import {convertFontSize, fontEvent, getFontNodeElements, getFontSizeInfo} from "./Font";
+import {getInlineFontFamilyLabel, getInlineFontFamilyState, getInlineFontFamilyValue, openFontFamilyMenu} from "./fontFamilyMenu";
+import {focusByRange} from "../util/selection";
+import {escapeAttr} from "../../util/escape";
+import {isMixedFontSize, normalizeFontSizeInput} from "./fontSizeCore";
+import {closeSubElement} from "./subElementLifecycle";
+
+export const getFontSizeState = (protyle: IProtyle) => {
+ const nodes = getFontNodeElements(protyle);
+ const info = getFontSizeInfo(protyle, nodes);
+ const sizes: string[] = [];
+ const range = protyle.toolbar.range;
+ const root = range.commonAncestorContainer;
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ const collect = (node: Node) => {
+ const start = node === range.startContainer ? range.startOffset : 0;
+ const end = node === range.endContainer ? range.endOffset : node.textContent?.length;
+ if (start === end) {
+ return;
+ }
+ if (node.textContent?.trim() && range.intersectsNode(node) && node.parentElement) {
+ sizes.push(getComputedStyle(node.parentElement).fontSize);
+ }
+ };
+ if (nodes?.length) {
+ nodes.forEach(node => sizes.push(getComputedStyle(node).fontSize));
+ } else if (!range.collapsed) {
+ if (root.nodeType === Node.TEXT_NODE) {
+ collect(root);
+ }
+ while (walker.nextNode()) {
+ collect(walker.currentNode);
+ }
+ }
+ return {...info, mixed: isMixedFontSize(sizes), disabled: nodes?.some(node => node.classList.contains("li")) || false};
+};
+
+export const createFontSizePicker = (protyle: IProtyle, onApply: (size: string) => void,
+ onInteraction?: () => void, onCancel?: () => void) => {
+ const state = getFontSizeState(protyle);
+ const element = document.createElement("div");
+ element.className = "protyle-font-size";
+ element.innerHTML = `<label class="fn__flex">${window.siyuan.languages.relativeFontSize}<span class="fn__flex-1"></span>
+ <input class="b3-switch" type="checkbox" ${state.fontSize.endsWith("em") ? "checked" : ""}></label>
+ <div class="fn__hr"></div>
+ <div class="fn__flex"><input class="b3-text-field fn__flex-1" type="number" step="1"
+ aria-label="${escapeAttr(window.siyuan.languages.fontSize)}" placeholder="${escapeAttr(window.siyuan.languages.mixed)}">
+ <span class="fn__space"></span><span data-unit class="fn__flex-center"></span></div>
+ <div class="fn__hr"></div><input class="b3-slider fn__block" type="range" step="1" aria-label="${escapeAttr(window.siyuan.languages.fontSize)}">
+ <div class="fn__hr"></div><button class="b3-button fn__block">${window.siyuan.languages.confirm}</button>`;
+ const relative = element.querySelector<HTMLInputElement>(".b3-switch");
+ const input = element.querySelector<HTMLInputElement>('input[type="number"]');
+ const slider = element.querySelector<HTMLInputElement>('input[type="range"]');
+ const button = element.querySelector("button");
+ const update = (size: string, mixed = false) => {
+ input.min = slider.min = relative.checked ? "56" : "9";
+ input.max = slider.max = relative.checked ? "450" : "72";
+ const value = relative.checked ? Math.round(parseFloat(size) * 100) : Math.round(parseFloat(size));
+ input.value = mixed ? "" : value.toString();
+ slider.value = value.toString();
+ element.querySelector("[data-unit]").textContent = relative.checked ? "%" : "px";
+ button.disabled = state.disabled || !normalizeFontSizeInput(input.value, relative.checked);
+ };
+ const apply = () => {
+ const value = normalizeFontSizeInput(input.value, relative.checked);
+ if (!state.disabled && value) {
+ onApply(value);
+ }
+ };
+ update(state.fontSize, state.mixed);
+ relative.addEventListener("change", () => {
+ const oldSize = normalizeFontSizeInput(input.value, !relative.checked) || state.fontSize;
+ update(convertFontSize(oldSize, relative.checked ? "em" : "px", state.baseFontSize), input.value === "");
+ });
+ input.addEventListener("input", () => {
+ button.disabled = state.disabled || !normalizeFontSizeInput(input.value, relative.checked);
+ if (!button.disabled) {
+ slider.value = input.value;
+ }
+ });
+ slider.addEventListener("input", () => {
+ input.value = slider.value;
+ button.disabled = state.disabled;
+ });
+ button.addEventListener("click", apply);
+ element.addEventListener("keydown", event => {
+ event.stopPropagation();
+ if (event.key === "Enter" && !event.isComposing) {
+ event.preventDefault();
+ apply();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ onCancel?.();
+ }
+ });
+ ["pointerdown", "input", "keydown"].forEach(type => element.addEventListener(type, () => onInteraction?.()));
+ return element;
+};
+
+export const updateFontControls = (protyle: IProtyle) => {
+ const familyButton = protyle.toolbar.element.querySelector<HTMLButtonElement>('[data-type="font-family"]');
+ const sizeButton = protyle.toolbar.element.querySelector<HTMLButtonElement>('[data-type="font-size"]');
+ if (familyButton) {
+ const state = getInlineFontFamilyState(protyle, getFontNodeElements(protyle));
+ familyButton.textContent = getInlineFontFamilyLabel(state);
+ familyButton.disabled = state.disabled;
+ }
+ if (sizeButton) {
+ const state = getFontSizeState(protyle);
+ sizeButton.textContent = state.mixed ? window.siyuan.languages.mixed : state.fontSize.endsWith("em") ?
+ `${Math.round(parseFloat(state.fontSize) * 100)}%` : state.fontSize;
+ sizeButton.disabled = state.disabled;
+ }
+};
+
+export class FontControl extends ToolbarItem {
+ constructor(protyle: IProtyle, item: IMenuItem) {
+ super(protyle, item);
+ this.element.classList.add("protyle-toolbar__font");
+ this.element.textContent = window.siyuan.languages[item.lang];
+ this.element.setAttribute("aria-haspopup", "true");
+ this.element.addEventListener("mousedown", event => event.preventDefault());
+ this.element.addEventListener("click", () => {
+ closeSubElement(protyle.toolbar);
+ protyle.toolbar.subElement.classList.add("fn__none");
+ const range = protyle.toolbar.range.cloneRange();
+ const nodes = getFontNodeElements(protyle);
+ const valid = () => range.startContainer.isConnected && range.endContainer.isConnected &&
+ !protyle.disabled && this.element.isConnected;
+ const apply = (type: string, value: string) => {
+ if (!valid()) {
+ return;
+ }
+ protyle.toolbar.range = range;
+ fontEvent(protyle, nodes, type, value);
+ protyle.toolbar.render(protyle, protyle.toolbar.range);
+ };
+ if (item.name === "font-family") {
+ void openFontFamilyMenu(this.element, {
+ ...getInlineFontFamilyState(protyle, nodes),
+ isOpenValid: valid,
+ onSelect: family => apply("fontFamily", getInlineFontFamilyValue(family)),
+ });
+ return;
+ }
+ const menu = new Menu("inlineFontSize", () => {
+ if (valid()) {
+ focusByRange(protyle.toolbar.range);
+ }
+ });
+ if (menu.isOpen) {
+ return;
+ }
+ menu.addItem({type: "empty", label: "", bind: element => {
+ element.append(createFontSizePicker(protyle, value => {
+ menu.close();
+ apply("fontSize", value);
+ }, undefined, () => menu.close()));
+ }});
+ const rect = this.element.getBoundingClientRect();
+ menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: this.element});
+ menu.element.querySelector<HTMLInputElement>('input[type="number"]')?.focus();
+ });
+ }
+}
diff --git a/app/src/protyle/toolbar/fontSizeCore.test.ts b/app/src/protyle/toolbar/fontSizeCore.test.ts
new file mode 100644
index 0000000000..407776ae11
--- /dev/null
+++ b/app/src/protyle/toolbar/fontSizeCore.test.ts
@@ -0,0 +1,29 @@
+import * as assert from "node:assert/strict";
+import {test} from "node:test";
+import {isMixedFontSize, normalizeFontSizeInput} from "./fontSizeCore";
+
+test("font size input preserves pixel and relative units within supported bounds", () => {
+ assert.equal(normalizeFontSizeInput("9", false), "9px");
+ assert.equal(normalizeFontSizeInput("72", false), "72px");
+ assert.equal(normalizeFontSizeInput("56", true), "0.56em");
+ assert.equal(normalizeFontSizeInput("450", true), "4.5em");
+ assert.equal(normalizeFontSizeInput("125", true), "1.25em");
+ assert.equal(normalizeFontSizeInput(" 16 ", false), "16px");
+});
+
+test("font size input rejects blank, non-finite and out-of-range values", () => {
+ for (const value of ["", " ", "NaN", "Infinity", "-1", "0", "16px"]) {
+ assert.equal(normalizeFontSizeInput(value, false), undefined);
+ assert.equal(normalizeFontSizeInput(value, true), undefined);
+ }
+ assert.equal(normalizeFontSizeInput("8", false), undefined);
+ assert.equal(normalizeFontSizeInput("73", false), undefined);
+ assert.equal(normalizeFontSizeInput("55", true), undefined);
+ assert.equal(normalizeFontSizeInput("451", true), undefined);
+});
+
+test("font size selection distinguishes uniform, mixed and empty selections", () => {
+ assert.equal(isMixedFontSize([]), false);
+ assert.equal(isMixedFontSize(["16px", "16px"]), false);
+ assert.equal(isMixedFontSize(["16px", "24px"]), true);
+});
diff --git a/app/src/protyle/toolbar/fontSizeCore.ts b/app/src/protyle/toolbar/fontSizeCore.ts
new file mode 100644
index 0000000000..cf8c902753
--- /dev/null
+++ b/app/src/protyle/toolbar/fontSizeCore.ts
@@ -0,0 +1,12 @@
+export const normalizeFontSizeInput = (value: string, relative: boolean) => {
+ if (!value.trim()) {
+ return;
+ }
+ const size = Number(value);
+ if (!Number.isFinite(size) || size < (relative ? 56 : 9) || size > (relative ? 450 : 72)) {
+ return;
+ }
+ return relative ? `${Math.round(size) / 100}em` : `${Math.round(size)}px`;
+};
+
+export const isMixedFontSize = (sizes: string[]) => new Set(sizes).size > 1;
diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.ts
index cd8088e6c8..b426940869 100644
--- a/app/src/protyle/toolbar/index.ts
+++ b/app/src/protyle/toolbar/index.ts
@@ -98,6 +98,7 @@ import {
normalizeCalloutTitleRange
} from "./inlineRangeBoundary";
import {resolvePluginToolbar} from "../../plugin/toolbarItem";
+import {FontControl, updateFontControls} from "./fontControls";
import {
areProtylePluginExtensionsEnabled,
getProtyleLockedToolbar,
@@ -108,7 +109,7 @@ const filterPluginToolbar = (toolbar: Array<string | IMenuItem>, lite: boolean)
return toolbar;
}
const filtered = toolbar.filter(item => typeof item === "string" ||
- Constants.INLINE_TYPE.concat("|").includes(item.name) || item.showInLite);
+ Constants.INLINE_TYPE.concat("|", "font-family", "font-size").includes(item.name) || item.showInLite);
return filtered.filter((item, index) => {
const name = typeof item === "string" ? item : item.name;
if (name !== "|") {
@@ -134,7 +135,7 @@ const applyPluginToolbar = (toolbar: Array<string | IMenuItem>, protyle: IProtyl
});
result = filterPluginToolbar(result, protyle.lite);
result.forEach((toolbarItem) => {
- if (typeof toolbarItem === "string" || Constants.INLINE_TYPE.concat("|").includes(toolbarItem.name)) {
+ if (typeof toolbarItem === "string" || Constants.INLINE_TYPE.concat("|", "font-family", "font-size").includes(toolbarItem.name)) {
return;
}
if (typeof toolbarItem.hotkey !== "string") {
@@ -181,7 +182,7 @@ export class Toolbar {
/// #endif
this.toolbarHeight = 29;
options.toolbar = applyPluginToolbar(options.toolbar, protyle);
- if (!isMobile() && !protyle.lite) {
+ if (!protyle.lite) {
refreshToolbarCatalog(options.toolbar);
}
options.toolbar.forEach((menuItem: IMenuItem) => {
@@ -200,7 +201,7 @@ export class Toolbar {
this.element.innerHTML = "";
protyle.options.toolbar = toolbarKeyToMenu(getProtyleLockedToolbar(protyle) || getDefaultToolbar(isMobile()));
protyle.options.toolbar = applyPluginToolbar(protyle.options.toolbar, protyle);
- if (!isMobile() && !protyle.lite) {
+ if (!protyle.lite) {
refreshToolbarCatalog(protyle.options.toolbar);
}
protyle.options.toolbar.forEach((menuItem: IMenuItem) => {
@@ -303,6 +304,7 @@ export class Toolbar {
return;
}
this.rangePosition = getSelectionPosition(nodeElement, range, true, position);
+ updateFontControls(protyle);
this.element.classList.remove("fn__none");
this.toolbarHeight = this.element.clientHeight;
const y = this.setSelectionElementPosition(protyle, this.element);
@@ -2517,6 +2519,10 @@ export class Toolbar {
case "text":
menuItemObj = new Font(protyle, menuItem);
break;
+ case "font-family":
+ case "font-size":
+ menuItemObj = new FontControl(protyle, menuItem);
+ break;
case "format-painter":
menuItemObj = menuItem.click ? new ToolbarItem(protyle, menuItem) :
new FormatPainter(protyle, menuItem);
diff --git a/app/src/protyle/toolbar/util.ts b/app/src/protyle/toolbar/util.ts
index 28825073bc..b6474a375e 100644
--- a/app/src/protyle/toolbar/util.ts
+++ b/app/src/protyle/toolbar/util.ts
@@ -289,6 +289,16 @@ export const toolbarKeyToMenu = (toolbar: Array<string | IMenuItem>) => {
hotkey: window.siyuan.config.keymap.editor.insert.appearance.custom,
icon: "iconFont",
tipPosition: "n",
+ }, {
+ name: "font-family",
+ lang: "fontFamily",
+ icon: "iconFont",
+ tipPosition: "n",
+ }, {
+ name: "font-size",
+ lang: "fontSize",
+ icon: "iconFont",
+ tipPosition: "n",
}, {
name: "clear",
lang: "clearInline",