An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support separate mobile toolbar context profiles https://github.com/siyuan-note/siyuan/issues/20034
Daniele8fa4cecd726
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex e7ced67942..c6750b5dbb 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "دون تحديد نص",+ "mobileToolbarTextSelection": "نص محدد","ocrAIModel": "نموذج الذكاء الاصطناعي","ocrAIModelTip": "اختر نموذجًا يدعم إدخال الصور؛ يرسل التعرف اليدوي والتلقائي الصور إلى مزود النموذج وقد تترتب رسوم","viewRefContent": "عرض المحتوى المشار إليه",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 52e3f9c18e..496836d368 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Kein Text ausgewählt",+ "mobileToolbarTextSelection": "Text ausgewählt","ocrAIModel": "KI-Modell","ocrAIModelTip": "Ein Modell mit Bildeingabe wählen; manuelle und automatische Erkennung senden Bilder an dessen Anbieter und können Kosten verursachen","viewRefContent": "Referenzierten Inhalt anzeigen",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 9c2177eca5..55c4b1bcb0 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "No text selected",+ "mobileToolbarTextSelection": "Text selected","ocrAIModel": "AI model","ocrAIModelTip": "Select a model that supports image input; manual and automatic recognition send images to its provider and may incur charges","viewRefContent": "View referenced content",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 4256d7ee24..ca473e0d81 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Sin texto seleccionado",+ "mobileToolbarTextSelection": "Texto seleccionado","ocrAIModel": "Modelo de IA","ocrAIModelTip": "Selecciona un modelo que admita imágenes; el reconocimiento manual y automático envía imágenes a su proveedor y puede generar cargos","viewRefContent": "Ver contenido referenciado",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex b1133564b6..4b3c9cd105 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Aucun texte sélectionné",+ "mobileToolbarTextSelection": "Texte sélectionné","ocrAIModel": "Modèle d’IA","ocrAIModelTip": "Sélectionnez un modèle acceptant les images ; la reconnaissance manuelle et automatique envoie les images à son fournisseur et peut entraîner des frais","viewRefContent": "Afficher le contenu référencé",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 888c4e2f6d..bd60e66f28 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "ללא טקסט נבחר",+ "mobileToolbarTextSelection": "טקסט נבחר","ocrAIModel": "מודל בינה מלאכותית","ocrAIModelTip": "יש לבחור מודל התומך בקלט תמונות; זיהוי ידני ואוטומטי שולח תמונות לספק ועלול להיות כרוך בתשלום","viewRefContent": "הצג את התוכן שאליו מפנים",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex f6e305ac6a..cf35bf5bd6 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "कोई पाठ चयनित नहीं",+ "mobileToolbarTextSelection": "पाठ चयनित","ocrAIModel": "AI मॉडल","ocrAIModelTip": "छवि इनपुट का समर्थन करने वाला मॉडल चुनें; मैन्युअल और स्वचालित पहचान छवियाँ प्रदाता को भेजती है और शुल्क लग सकता है","viewRefContent": "संदर्भित सामग्री देखें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 323416a37f..b3d29b95f8 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Tidak ada teks dipilih",+ "mobileToolbarTextSelection": "Teks dipilih","ocrAIModel": "Model AI","ocrAIModelTip": "Pilih model yang mendukung masukan gambar; pengenalan manual dan otomatis mengirim gambar ke penyedia dan dapat dikenai biaya","viewRefContent": "Lihat konten yang dirujuk",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 3b14d56917..7244cdae7f 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Nessun testo selezionato",+ "mobileToolbarTextSelection": "Testo selezionato","ocrAIModel": "Modello IA","ocrAIModelTip": "Seleziona un modello che supporti le immagini; il riconoscimento manuale e automatico invia le immagini al suo fornitore e può comportare costi","viewRefContent": "Visualizza il contenuto a cui si fa riferimento",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex b1960074ef..d93894033b 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "テキスト未選択",+ "mobileToolbarTextSelection": "テキスト選択中","ocrAIModel": "AI モデル","ocrAIModelTip": "画像入力に対応するモデルを選択します。手動認識と自動認識では画像をプロバイダーに送信し、料金が発生する場合があります","viewRefContent": "参照先の内容を表示",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 1fa908c4f7..6a7a0e7355 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "텍스트 선택 안 함",+ "mobileToolbarTextSelection": "텍스트 선택됨","ocrAIModel": "AI 모델","ocrAIModelTip": "이미지 입력을 지원하는 모델을 선택하세요. 수동 및 자동 인식은 이미지를 제공업체에 전송하며 요금이 발생할 수 있습니다","viewRefContent": "참조된 콘텐츠 보기",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 78350d8c92..30e5a832b7 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Geen tekst geselecteerd",+ "mobileToolbarTextSelection": "Tekst geselecteerd","ocrAIModel": "AI-model","ocrAIModelTip": "Kies een model dat afbeeldingen ondersteunt; handmatige en automatische herkenning sturen afbeeldingen naar de aanbieder en kunnen kosten veroorzaken","viewRefContent": "Inhoud waarnaar wordt verwezen bekijken",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex af1cb08e88..c864dd3719 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Brak zaznaczonego tekstu",+ "mobileToolbarTextSelection": "Zaznaczony tekst","ocrAIModel": "Model AI","ocrAIModelTip": "Wybierz model obsługujący obrazy; rozpoznawanie ręczne i automatyczne wysyła obrazy do dostawcy i może wiązać się z opłatami","viewRefContent": "Wyświetl treść, do której prowadzi odnośnik",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 2b9695038d..4895981b6e 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Sem texto selecionado",+ "mobileToolbarTextSelection": "Texto selecionado","ocrAIModel": "Modelo de IA","ocrAIModelTip": "Selecione um modelo que aceite imagens; o reconhecimento manual e automático envia imagens ao provedor e pode gerar cobranças","viewRefContent": "Ver conteúdo referenciado",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 063c496633..36da5c93bb 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Текст не выделен",+ "mobileToolbarTextSelection": "Текст выделен","ocrAIModel": "Модель ИИ","ocrAIModelTip": "Выберите модель с поддержкой изображений; ручное и автоматическое распознавание отправляет изображения провайдеру и может быть платным","viewRefContent": "Просмотреть содержимое по ссылке",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex b1996b1201..446127a62f 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Žiadny vybratý text",+ "mobileToolbarTextSelection": "Vybratý text","ocrAIModel": "Model AI","ocrAIModelTip": "Vyberte model podporujúci obrázky; ručné aj automatické rozpoznávanie odosiela obrázky poskytovateľovi a môže byť spoplatnené","viewRefContent": "Zobraziť odkazovaný obsah",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 3c37d12b3b..0ed81f7d1d 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Без изабраног текста",+ "mobileToolbarTextSelection": "Изабрани текст","ocrAIModel": "AI модел","ocrAIModelTip": "Изаберите модел који подржава слике; ручно и аутоматско препознавање шаље слике добављачу и може изазвати трошкове","viewRefContent": "Prikaži sadržaj na koji se upućuje",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex fd0d0c0ad2..75fa99dc81 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "ไม่มีข้อความที่เลือก",+ "mobileToolbarTextSelection": "ข้อความที่เลือก","ocrAIModel": "โมเดล AI","ocrAIModelTip": "เลือกโมเดลที่รองรับภาพ การรู้จำด้วยตนเองและอัตโนมัติจะส่งภาพไปยังผู้ให้บริการและอาจมีค่าใช้จ่าย","viewRefContent": "ดูเนื้อหาที่อ้างอิง",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex fab8bea8bc..6ebdd16b7f 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Metin seçilmedi",+ "mobileToolbarTextSelection": "Metin seçildi","ocrAIModel": "Yapay zekâ modeli","ocrAIModelTip": "Görüntü girişini destekleyen bir model seçin; elle ve otomatik tanıma, görüntüleri sağlayıcıya gönderir ve ücret doğurabilir","viewRefContent": "Referans verilen içeriği görüntüle",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex b8dbd914ee..d437ed5ee2 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "Текст не виділено",+ "mobileToolbarTextSelection": "Текст виділено","ocrAIModel": "Модель ШІ","ocrAIModelTip": "Виберіть модель із підтримкою зображень; ручне й автоматичне розпізнавання надсилає зображення провайдеру та може бути платним","viewRefContent": "Переглянути вміст за посиланням",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 0812ee6ba1..77bd7f1e21 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "未选中文本",+ "mobileToolbarTextSelection": "选中文本","ocrAIModel": "AI 模型","ocrAIModelTip": "选择支持图片输入的模型;手动和自动识别都会将图片发送给该提供商,可能产生费用","viewRefContent": "查看引用内容",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 6d1aa824de..c4f9db2d2f 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,6 @@{+ "mobileToolbarNoSelection": "未選取文字",+ "mobileToolbarTextSelection": "已選取文字","ocrAIModel": "AI 模型","ocrAIModelTip": "選擇支援圖片輸入的模型;手動和自動辨識都會將圖片傳送給該提供商,可能產生費用","viewRefContent": "查看引用內容",diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex 7c2e854067..693051be3a 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -4,6 +4,7 @@ import {DESKTOP_TOOLBAR_ENTRIES,getToolbarEntryId,getToolbarEntryLabel,+ MOBILE_TOOLBAR_NAMES,TOOLBAR_ENTRY_ROOT_PATH,} from "../../protyle/toolbar/defaults";import {mergeEntryOrderPreservingUnknown} from "./order";@@ -14,6 +15,7 @@ import {getPluginTopBarEntryKey,isPluginTopBarEntryKey,} from "../../plugin/topBarKey";+import {MOBILE_TOOLBAR_CONTEXT_KEYS} from "./mobileToolbarContext";export {getPluginDockEntryKey} from "../../plugin/dockKey";export {getLegacyPluginTopBarEntryKey, getPluginTopBarEntryKey} from "../../plugin/topBarKey";@@ -522,6 +524,17 @@ const toolbarBuiltinChildren = [];const toolbarBuiltinNodeMap = new Map(toolbarBuiltinChildren.map((item) => [item.key, item]));+const mobileToolbarContexts = (children: IEntryCatalogNode[]) => MOBILE_TOOLBAR_CONTEXT_KEYS.map((key) => {+ const selection = key === "mobile-selection";+ const entries = children.filter(item => item.type === "separator" || item.key.startsWith("plugin:") ||+ (selection ? MOBILE_TOOLBAR_NAMES.includes(item.key) && item.key !== "block-type" :+ item.key.startsWith("mobile-") || ["block-type", "block-ref"].includes(item.key)))+ .map(item => !selection && item.key === "block-ref" ? {...item,+ defaultVisible: () => false, customDefaultVisible: false} : item);+ return node(key, lang(selection ? "mobileToolbarTextSelection" : "mobileToolbarNoSelection"), true,+ normalizeToolbarCatalogSeparators(entries), true, {fixed: true});+});+const slashMenuBuiltinChildren = [node("template", lang("template")),node("widget", lang("widget")),@@ -607,7 +620,7 @@ const slashMenuRoot = {const toolbarCatalogSection: IEntryCatalogSection = {key: TOOLBAR_ENTRY_ROOT_PATH,label: location(lang("editor"), lang("entryToolbar")),- children: toolbarBuiltinChildren,+ children: [...toolbarBuiltinChildren, ...mobileToolbarContexts(toolbarBuiltinChildren)],};export const TOP_BAR_ROOT_PATH = "topBar";@@ -1278,7 +1291,7 @@ export const refreshDockCatalog = (plugins: IDockCatalogPlugin[]) => {rebuildCatalogIndexes();};-const normalizeToolbarCatalogSeparators = (nodes: IEntryCatalogNode[]) => {+function normalizeToolbarCatalogSeparators(nodes: IEntryCatalogNode[]) {const result: IEntryCatalogNode[] = [];nodes.forEach((item) => {if (item.type === "separator" && (result.length === 0 || result[result.length - 1].type === "separator")) {@@ -1290,7 +1303,7 @@ const normalizeToolbarCatalogSeparators = (nodes: IEntryCatalogNode[]) => {result.pop();}return result;-};+}const toolbarCatalogNodeSignature = (item: IEntryCatalogNode, pluginLabels: Map<string, string>) => [item.key,@@ -1329,7 +1342,7 @@ export const refreshToolbarCatalog = (items: Array<string | IMenuItem>) => {if (signature === toolbarCatalogSignature) {return;}- toolbarCatalogSection.children = children;+ toolbarCatalogSection.children = [...children, ...mobileToolbarContexts(children)];toolbarCatalogSignature = signature;rebuildCatalogIndexes();};diff --git a/app/src/config/entryVisibility/mobileToolbarContext.ts b/app/src/config/entryVisibility/mobileToolbarContext.tsnew file mode 100644index 0000000000..fbfc8c60c5--- /dev/null+++ b/app/src/config/entryVisibility/mobileToolbarContext.ts@@ -0,0 +1,19 @@+import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";++export const MOBILE_TOOLBAR_CONTEXT_KEYS = ["mobile-input", "mobile-selection"];++export const getMobileToolbarContextPath = (hasText: boolean) =>+ `${TOOLBAR_ENTRY_ROOT_PATH}.${hasText ? "mobile-selection" : "mobile-input"}`;++export const isMobileToolbarContextPath = (path: string) =>+ MOBILE_TOOLBAR_CONTEXT_KEYS.some(key => path === `${TOOLBAR_ENTRY_ROOT_PATH}.${key}`);++export const getLegacyMobileToolbarEntryPath = (path: string) => {+ // 未选中文字时的引用入口采用新默认值,可在该上下文中单独启用。+ if (path === `${getMobileToolbarContextPath(false)}.block-ref`) {+ return;+ }+ const context = MOBILE_TOOLBAR_CONTEXT_KEYS.find(key => path.startsWith(`${TOOLBAR_ENTRY_ROOT_PATH}.${key}.`));+ return context ? `${TOOLBAR_ENTRY_ROOT_PATH}.${path.substring(`${TOOLBAR_ENTRY_ROOT_PATH}.${context}.`.length)}` :+ undefined;+};diff --git a/app/src/config/entryVisibility/mobileUi.test.ts b/app/src/config/entryVisibility/mobileUi.test.tsindex 8519439650..c5de72aefd 100644--- a/app/src/config/entryVisibility/mobileUi.test.ts+++ b/app/src/config/entryVisibility/mobileUi.test.ts@@ -297,11 +297,14 @@ const browserCases = async (sources: Record<string, string>, languages: Record<smobile = true;window.siyuan.mobile = {} as typeof window.siyuan.mobile;view = open();+ check(view.querySelectorAll("[data-entry-row]").length === 2, "Mobile toolbar exposes two context groups");+ view.querySelector<HTMLElement>("[data-entry-path-row='editor.toolbar.mobile-input']").click();const toolbarBrowser = view.querySelector<HTMLElement>("[data-type='entry-browser']");toolbarBrowser.setPointerCapture = () => { captured = true; };toolbarBrowser.hasPointerCapture = () => captured;toolbarBrowser.releasePointerCapture = () => { captured = false; };- const toolbarRows = Array.from(toolbarBrowser.querySelectorAll<HTMLElement>("[data-entry-row]"));+ const toolbarRows = Array.from(toolbarBrowser.querySelectorAll<HTMLElement>(+ "[data-entry-row][data-entry-parent='editor.toolbar.mobile-input']"));const firstKey = toolbarRows[0].dataset.entryKey;const secondKey = toolbarRows[1].dataset.entryKey;const toolbarHandle = toolbarRows[0].querySelector(".config-entry-visibility__drag");@@ -309,7 +312,7 @@ const browserCases = async (sources: Record<string, string>, languages: Record<ssend(toolbarBrowser, "pointermove", point(toolbarRows[1]));send(toolbarBrowser, "pointerup", point(toolbarRows[1]));view.querySelector<HTMLElement>("[data-action='confirm']").click();- const toolbarOrder = config().profiles[0].orders["editor.toolbar"];+ const toolbarOrder = config().profiles[0].orders["editor.toolbar.mobile-input"];check(toolbarOrder.indexOf(secondKey) < toolbarOrder.indexOf(firstKey), "Toolbar touch sorting must persist");view = open();selectSlash();@@ -323,7 +326,7 @@ const browserCases = async (sources: Record<string, string>, languages: Record<sresetOrder();view.querySelector<HTMLElement>("[data-action='confirm']").click();check(!("editor.slash.menu" in config().profiles[0].orders), "Single reset must delete the order record");- check(config().profiles[0].orders["editor.toolbar"], "Single reset must preserve other levels");+ check(config().profiles[0].orders["editor.toolbar.mobile-input"], "Single reset must preserve other levels");check(config().profiles[0].entries["editor.slash.menu"] === true, "Reset must preserve visibility");view = open();view.querySelector<HTMLElement>("[data-action='reset-all-entry-orders']").click();@@ -339,7 +342,8 @@ test("mobile entry settings preserve preferences and support touch sorting withotimeout: 45000,}, async () => {const modules = ["config/entryVisibility/ui", "config/entryVisibility/catalog", "config/entryVisibility/order",- "config/entryVisibility/profile", "config/entryVisibility/dockOrder", "config/entryVisibility/touchOrder",+ "config/entryVisibility/profile", "config/entryVisibility/mobileToolbarContext",+ "config/entryVisibility/dockOrder", "config/entryVisibility/touchOrder","protyle/toolbar/defaults", "mobile/util/toolbarActions", "protyle/wysiwyg/codeBlockUtil", "protyle/gutter/turnIntoMenu","plugin/dockKey", "plugin/topBarKey", "util/escape"];const sources = Object.fromEntries(modules.map(id => [id, transpileModule(diff --git a/app/src/config/entryVisibility/profile.test.ts b/app/src/config/entryVisibility/profile.test.tsindex 7b76337567..d04d89bdf6 100644--- a/app/src/config/entryVisibility/profile.test.ts+++ b/app/src/config/entryVisibility/profile.test.ts@@ -2,14 +2,82 @@ import * as assert from "node:assert/strict";import test from "node:test";import {readFileSync} from "node:fs";import {resolve} from "node:path";-import {getEntryCatalogCustomDefaultVisibility, getEntryCatalogDefaultVisibility, getEntryCatalogNode} from "./catalog";+import {+ getEntryCatalogChildren,+ getEntryCatalogCustomDefaultVisibility,+ getEntryCatalogDefaultVisibility,+ getEntryCatalogNode,+} from "./catalog";import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";import {getBuiltinProfileEntryVisibility,getProfileEntryVisibility,+ getSavedEntryOrder,isEntryVisibilityImportVersionSupported,normalizeEntryVisibilityImportProfile,+ resetEntryProfileOrder,} from "./profile";+import {getMobileToolbarContextPath} from "./mobileToolbarContext";+import {mergeEntryOrderPreservingUnknown, resolveEntryOrder} from "./order";++test("mobile toolbar contexts expose relevant entries and hide caret references by default", () => {+ const input = getMobileToolbarContextPath(false);+ const selection = getMobileToolbarContextPath(true);+ const inputKeys = getEntryCatalogChildren(input).map(item => item.key);+ const selectionKeys = getEntryCatalogChildren(selection).map(item => item.key);+ assert.ok(inputKeys.includes("mobile-add") && inputKeys.includes("mobile-indent") && inputKeys.includes("block-ref"));+ assert.equal(inputKeys.includes("strong"), false);+ assert.ok(selectionKeys.includes("strong") && selectionKeys.includes("block-ref"));+ assert.equal(selectionKeys.some(key => key.startsWith("mobile-")), false);+ assert.equal(selectionKeys.includes("block-type"), false);+ for (const template of ["full", "simple"] as const) {+ for (const [path, expected] of [[`${input}.block-ref`, false], [`${selection}.block-ref`, true]] as const) {+ const node = getEntryCatalogNode(path);+ assert.equal(getBuiltinProfileEntryVisibility(template, node.simple,+ getEntryCatalogDefaultVisibility(path)), expected);+ }+ }+});++test("mobile context visibility inherits legacy choices and permits independent overrides", () => {+ const input = getMobileToolbarContextPath(false);+ const selection = getMobileToolbarContextPath(true);+ const profile: {entries: Record<string, boolean>} = {entries: {"editor.toolbar.block-ref": false}};+ assert.equal(getProfileEntryVisibility(profile, `${input}.block-ref`,+ getEntryCatalogCustomDefaultVisibility(`${input}.block-ref`)), false);+ assert.equal(getProfileEntryVisibility(profile, `${selection}.block-ref`, true), false);+ profile.entries[`${selection}.block-ref`] = true;+ assert.equal(getProfileEntryVisibility(profile, `${selection}.block-ref`, false), true);+ assert.equal(getProfileEntryVisibility(profile, `${input}.block-ref`,+ getEntryCatalogCustomDefaultVisibility(`${input}.block-ref`)), false);+ assert.equal(getProfileEntryVisibility(profile, "editor.toolbar.block-ref", true), false);+ assert.equal(getProfileEntryVisibility({entries: {}}, `${input}.block-ref`,+ getEntryCatalogCustomDefaultVisibility(`${input}.block-ref`)), false);+ assert.equal(getProfileEntryVisibility({entries: {"editor.toolbar.block-ref": true}}, `${input}.block-ref`,+ getEntryCatalogCustomDefaultVisibility(`${input}.block-ref`)), false);+});++test("mobile context orders retain legacy plugin slots and reset independently", () => {+ const input = getMobileToolbarContextPath(false);+ const selection = getMobileToolbarContextPath(true);+ const legacy = ["strong", "plugin:disabled:item", "block-ref", "mobile-add", "mobile-block"];+ const profile: Pick<Config.IEntryVisibilityProfile, "orders" | "entries" | "name"> = {+ orders: {"editor.toolbar": legacy}, entries: {}, name: "Custom",+ };+ const defaults = ["mobile-add", "mobile-block", "block-ref"];+ const inherited = getSavedEntryOrder(profile, input, defaults);+ assert.deepEqual(inherited, ["plugin:disabled:item", "block-ref", "mobile-add", "mobile-block"]);+ profile.orders[input] = mergeEntryOrderPreservingUnknown(defaults, inherited,+ ["mobile-block", "mobile-add", "block-ref"]);+ assert.ok(profile.orders[input].includes("plugin:disabled:item"));+ assert.deepEqual(getSavedEntryOrder(profile, selection, ["block-ref", "strong"]),+ ["strong", "plugin:disabled:item", "block-ref"]);+ assert.deepEqual(profile.orders["editor.toolbar"], legacy);+ resetEntryProfileOrder(profile, input);+ assert.deepEqual(resolveEntryOrder(defaults, getSavedEntryOrder(profile, input, defaults), new Set()), defaults);+ assert.deepEqual(profile.orders["editor.toolbar"], legacy);+ assert.deepEqual(normalizeEntryVisibilityImportProfile(profile, 6, {}), profile);+});test("chart height migration retains shared visibility and plugin order", () => {for (const existing of [undefined, true, false]) {diff --git a/app/src/config/entryVisibility/profile.ts b/app/src/config/entryVisibility/profile.tsindex 7e7d64c073..e0d0f9d88d 100644--- a/app/src/config/entryVisibility/profile.ts+++ b/app/src/config/entryVisibility/profile.ts@@ -1,6 +1,24 @@+import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";+import {getLegacyMobileToolbarEntryPath, isMobileToolbarContextPath} from "./mobileToolbarContext";+export const getProfileEntryVisibility = (profile: Pick<Config.IEntryVisibilityProfile, "entries"> | undefined,- path: string, defaultVisible = true) =>- typeof profile?.entries[path] === "boolean" ? profile.entries[path] : defaultVisible;+ path: string, defaultVisible = true) => {+ if (typeof profile?.entries[path] === "boolean") {+ return profile.entries[path];+ }+ const legacyPath = getLegacyMobileToolbarEntryPath(path);+ return legacyPath && typeof profile?.entries[legacyPath] === "boolean" ? profile.entries[legacyPath] : defaultVisible;+};++export const getSavedEntryOrder = (profile: Pick<Config.IEntryVisibilityProfile, "orders"> | undefined,+ path: string, defaultOrder: string[]) => {+ if (profile?.orders?.[path] || !isMobileToolbarContextPath(path)) {+ return profile?.orders?.[path];+ }+ // 新上下文沿用已有顺序,同时保留暂未加载的插件位置。+ return profile?.orders?.[TOOLBAR_ENTRY_ROOT_PATH]?.filter(key => defaultOrder.includes(key) ||+ key.startsWith("plugin:") || key.startsWith("plugin-separator:"));+};export const getBuiltinProfileEntryVisibility = (profile: "simple" | "full",@@ -13,7 +31,11 @@ export const getBuiltinProfileEntryVisibility = (export const resetEntryProfileOrder = (profile: Pick<Config.IEntryVisibilityProfile, "orders">, parentPath?: string) => {if (parentPath) {- delete profile.orders[parentPath];+ if (isMobileToolbarContextPath(parentPath)) {+ profile.orders[parentPath] = [];+ } else {+ delete profile.orders[parentPath];+ }} else {profile.orders = {};}diff --git a/app/src/config/entryVisibility/runtime.ts b/app/src/config/entryVisibility/runtime.tsindex f60c9fea3c..6ab80bf8e6 100644--- a/app/src/config/entryVisibility/runtime.ts+++ b/app/src/config/entryVisibility/runtime.ts@@ -23,7 +23,7 @@ import {resolveEntryOrderWithBoundaryDefaults,} from "./order";import {getDocTreeEntryScope} from "./docTreeScope";-import {getBuiltinProfileEntryVisibility, getProfileEntryVisibility} from "./profile";+import {getBuiltinProfileEntryVisibility, getProfileEntryVisibility, getSavedEntryOrder} from "./profile";import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";import {resolveToolbarItems} from "../../protyle/toolbar/entryVisibility";import {syncDockBarVisibility} from "../../layout/dock/barVisibility";@@ -118,7 +118,7 @@ export const getEntryOrder = (parentPath: string, profile = getActiveEntryProfilif (parentPath === STATUS_BAR_ROOT_PATH) {return resolveEntryOrderWithBoundaryDefaults(defaultOrder, profile?.orders?.[parentPath], "spacer", separatorKeys);}- return resolveEntryOrder(defaultOrder, profile?.orders?.[parentPath], separatorKeys);+ return resolveEntryOrder(defaultOrder, getSavedEntryOrder(profile, parentPath, defaultOrder), separatorKeys);};export const createEntryOrderSnapshot = (current = false) => {@@ -180,7 +180,7 @@ export const setEntryOrderValue = (parentPath: string, order: string[]) => {const separatorKeys = new Set(nodes?.filter((item) => item.type === "separator").map((item) => item.key));profile.orders[parentPath] = mergeEntryOrderPreservingUnknown(defaultOrder,- profile.orders[parentPath],+ getSavedEntryOrder(profile, parentPath, defaultOrder),order,separatorKeys,);diff --git a/app/src/config/entryVisibility/ui.test.ts b/app/src/config/entryVisibility/ui.test.tsindex e5cbe73483..aa1ac547cf 100644--- a/app/src/config/entryVisibility/ui.test.ts+++ b/app/src/config/entryVisibility/ui.test.ts@@ -7,6 +7,7 @@ import {ModuleKind, transpileModule} from "typescript";import {entryCatalog, TOP_BAR_ROOT_PATH} from "./catalog";import {MOBILE_TOOLBAR_NAMES, TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";import * as dockOrder from "./dockOrder";+import {MOBILE_TOOLBAR_CONTEXT_KEYS} from "./mobileToolbarContext";test("entry settings show exit only on native tablets without changing the persisted catalog", () => {const source = readFileSync(resolve(process.cwd(), "src/config/entryVisibility/ui.ts"), "utf8");@@ -19,7 +20,7 @@ test("entry settings show exit only on native tablets without changing the persirunInNewContext(compiled, {exports,require: () => ({- entryCatalog, TOP_BAR_ROOT_PATH, MOBILE_TOOLBAR_NAMES, TOOLBAR_ENTRY_ROOT_PATH,+ entryCatalog, TOP_BAR_ROOT_PATH, MOBILE_TOOLBAR_NAMES, TOOLBAR_ENTRY_ROOT_PATH, MOBILE_TOOLBAR_CONTEXT_KEYS,isMobile: () => mobile,isInMobileApp: () => nativeTablet,DOCK_ORDER_SCOPES_BY_SIDE: {},@@ -37,10 +38,9 @@ test("entry settings show exit only on native tablets without changing the persiconst catalog = exports.catalog();assert.deepEqual(Array.from(catalog, item => item.key), [TOOLBAR_ENTRY_ROOT_PATH, "editor.image", "editor.slash"]);assert.equal(catalog.find(item => item.key === "editor.slash"), entryCatalog.find(item => item.key === "editor.slash"));- assert.ok(catalog[0].children.every(item => item.type === "separator" ||- item.key.startsWith("mobile-") || MOBILE_TOOLBAR_NAMES.includes(item.key)));+ assert.deepEqual(Array.from(catalog[0].children, item => item.key), MOBILE_TOOLBAR_CONTEXT_KEYS);for (const name of ["undo", "indent", "heading1", "table", "template"]) {- assert.ok(catalog[0].children.some(item => item.key === `mobile-${name}`));+ assert.ok(catalog[0].children[0].children.some(item => item.key === `mobile-${name}`));}});diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.tsindex 024dceaf25..a0ddef9425 100644--- a/app/src/config/entryVisibility/ui.ts+++ b/app/src/config/entryVisibility/ui.ts@@ -36,6 +36,7 @@ import {} from "./order";import {getProfileEntryVisibility,+ getSavedEntryOrder,isEntryVisibilityImportVersionSupported,normalizeEntryVisibilityImportProfile,resetEntryProfileOrder,@@ -45,7 +46,8 @@ import {getHostCapabilities} from "../../util/hostCapabilities";import {isMobile} from "../../util/functions";import {isInMobileApp} from "../../protyle/util/compatibility";import {bindTouchOrder} from "./touchOrder";-import {MOBILE_TOOLBAR_NAMES, TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";+import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";+import {MOBILE_TOOLBAR_CONTEXT_KEYS} from "./mobileToolbarContext";/// #if !MOBILEimport {getSettingsWindowHost, isSettingsWindow} from "../setting/windowContext";/// #endif@@ -64,9 +66,8 @@ import {const getVisibleEntryCatalog = () => isMobile() ? entryCatalog.filter(item =>item.key === TOOLBAR_ENTRY_ROOT_PATH || item.key === "editor.slash" || item.key === "editor.image")- .map(item => item.key === TOOLBAR_ENTRY_ROOT_PATH ? {...item, children: item.children.filter(child =>- child.type === "separator" || child.key.startsWith("mobile-") ||- MOBILE_TOOLBAR_NAMES.includes(child.key) || child.key.startsWith("plugin:"))} : item) : entryCatalog.map(item =>+ .map(item => item.key === TOOLBAR_ENTRY_ROOT_PATH ? {...item, sortable: false,+ children: item.children.filter(child => MOBILE_TOOLBAR_CONTEXT_KEYS.includes(child.key))} : item) : entryCatalog.map(item =>item.key === TOOLBAR_ENTRY_ROOT_PATH ? {...item, children: item.children.filter(child => !child.key.startsWith("mobile-"))} :item.key === TOP_BAR_ROOT_PATH && !isInMobileApp() ?{...item, children: item.children.filter(child => child.key !== "barExit")} : item);@@ -241,7 +242,7 @@ const resolveProfileEntryOrder = (profile: Config.IEntryVisibilityProfile, parenif (parentPath === STATUS_BAR_ROOT_PATH) {return resolveEntryOrderWithBoundaryDefaults(defaultOrder, profile.orders?.[parentPath], "spacer", separatorKeys);}- return resolveEntryOrder(defaultOrder, profile.orders?.[parentPath], separatorKeys);+ return resolveEntryOrder(defaultOrder, getSavedEntryOrder(profile, parentPath, defaultOrder), separatorKeys);};const getProfileEntryOrder = (profile: Config.IEntryVisibilityProfile, parentPath: string,@@ -827,8 +828,8 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {return;}draft.orders ||= {};- const savedOrder = draft.orders[dragging.parentPath];const context = getEntryOrderContext(dragging.parentPath, dockOrderSnapshot);+ const savedOrder = getSavedEntryOrder(draft, dragging.parentPath, dragging.defaultOrder);const separatorKeys = new Set([...context.separatorKeys,...(savedOrder || []).filter((key) =>diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex 620b8e8b72..6d858c93ea 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -81,7 +81,7 @@ import {isMobile} from "../../util/functions";import {createFontSizePicker} from "../../protyle/toolbar/fontControls";import {applyMobileToolbarEntries} from "./toolbarEntries";import {getEntryOrder, isEntryVisible} from "../../config/entryVisibility/runtime";-import {MOBILE_TOOLBAR_NAMES, TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";+import {MOBILE_TOOLBAR_NAMES} from "../../protyle/toolbar/defaults";import {getKeyboardPanelHeight} from "./keyboardPanelHeight";import {isMobileLandscape} from "./orientation";import {restoreGutterBySelection} from "../../protyle/gutter/restore";@@ -93,6 +93,7 @@ import {MOBILE_TOOLBAR_ACTION_NAMES, MOBILE_TOOLBAR_ACTIONS, MOBILE_TOOLBAR_INSEimport {pauseMobileBarsScroll} from "./mobileBars";import {getBlockTypeSelection, openBlockTypeMenu, updateBlockTypeButton} from "../../protyle/toolbar/BlockType";import {TTextBlockSelection} from "../../protyle/toolbar/blockTypeCore";+import {getMobileToolbarContextPath} from "../../config/entryVisibility/mobileToolbarContext";const getCurrentEditor = () => getMobileToolbarProtyle()?.getInstance() || getDocumentEditor();let toolbarProtyle: IProtyle;@@ -106,9 +107,10 @@ const applyKeyboardToolbarEntries = (element: HTMLElement, toolbar: Array<stringconst nodeElement = (range && hasClosestBlock(range.startContainer)) || undefined;const inCode = nodeElement?.classList.contains("code-block");const hasText = !!range && !!stripSemanticMarkersFromRangeText(range).split(Constants.ZWSP).join("");+ const contextPath = getMobileToolbarContextPath(hasText);applyMobileToolbarEntries(element, toolbar, {- order: getEntryOrder(TOOLBAR_ENTRY_ROOT_PATH),- isVisible: key => isEntryVisible(`${TOOLBAR_ENTRY_ROOT_PATH}.${key}`),+ order: getEntryOrder(contextPath),+ isVisible: key => isEntryVisible(`${contextPath}.${key}`),isAvailable: name => {if (hasText && (name === "block-type" || MOBILE_TOOLBAR_ACTION_NAMES.includes(name))) {return false;diff --git a/app/tests/mobileEditingToolbar.test.js b/app/tests/mobileEditingToolbar.test.jsindex 7ee7d566a1..a6e77c7cb8 100644--- a/app/tests/mobileEditingToolbar.test.js+++ b/app/tests/mobileEditingToolbar.test.js@@ -19,6 +19,7 @@ const runCases = async (sources, platform) => {"mobile-outdent", "mobile-block", "mobile-add", "mobile-heading1", "strong", "em", "a", "block-ref", "text","mobile-separator"]);const order = ["strong", "mobile-undo", "mobile-separator", "mobile-heading1", "em", "mobile-indent", "mobile-outdent"];+ const contextEntries = new Map([["editor.toolbar.mobile-input.block-ref", false]]);const constants = {INLINE_TYPE: ["a", "block-ref", "strong", "em", "u", "s", "code"], ZWSP: "\u200b",TIMEOUT_TRANSITION: 20, TIMEOUT_COUNT: 50};class LocalUndo {}@@ -35,7 +36,17 @@ const runCases = async (sources, platform) => {"protyle/undo": {LocalUndo},"protyle/undo/globalUndo": {getUndoRootID: () => "doc", hasUndoStateMirror: () => true,getMirror: () => ({canUndo: true, canRedo: false})},- "config/entryVisibility/runtime": {getEntryOrder: () => order, isEntryVisible: key => visible.has(key.slice("editor.toolbar.".length))},+ "config/entryVisibility/runtime": {getEntryOrder: path => {+ if (!path.endsWith(".mobile-input")) {+ return order;+ }+ const {MOBILE_TOOLBAR_ACTIONS, MOBILE_TOOLBAR_INSERTS, getMobileToolbarActionKey} =+ load("mobile/util/toolbarActions");+ return [...MOBILE_TOOLBAR_ACTIONS.map(item => getMobileToolbarActionKey(item.name)),+ "mobile-separator", "block-type", "block-ref",+ ...MOBILE_TOOLBAR_INSERTS.map(item => getMobileToolbarActionKey(item.name))];+ }, isEntryVisible: key =>+ (contextEntries.get(key) ?? true) && visible.has(key.split(".").at(-1))},"util/functions": {isMobile: () => true},"mobile/util/menuKeyboard": {captureMenuKeyboard: () => () => {}},"protyle/util/tableCellRichContext": {getTableCellRichContext: () => undefined},@@ -178,6 +189,9 @@ const runCases = async (sources, platform) => {assert.equal(keyboardHides, 0);assert.equal(editable.hasAttribute("inputmode"), false);assert.equal(document.activeElement, editable);+ const actualOrder = [...toolbar.querySelector(".keyboard__dynamic").children].map(item => item.dataset.id);+ assert.ok(actualOrder.indexOf("strong") < actualOrder.indexOf("mobile-undo"));+ assert.ok(actualOrder.indexOf("mobile-heading1") < actualOrder.indexOf("em"));select(0);await settle();assert.equal(hidden("undo"), false);@@ -188,9 +202,6 @@ const runCases = async (sources, platform) => {assert.equal(undoCalls, 1);action("heading1");assert.equal(inserts[0], "# ‸");- const actualOrder = [...toolbar.querySelector(".keyboard__dynamic").children].map(item => item.dataset.id);- assert.ok(actualOrder.indexOf("strong") < actualOrder.indexOf("mobile-undo"));- assert.ok(actualOrder.indexOf("mobile-heading1") < actualOrder.indexOf("em"));// 显隐变化和编辑器切换不得恢复隐藏项,也不得向受限的字段编辑器插入文档块。visible.delete("mobile-undo");window.dispatchEvent(new Event("siyuan-entry-visibility"));@@ -239,6 +250,7 @@ const runCases = async (sources, platform) => {assert.equal(keyboardShows, showsBeforeClose);assert.equal(toolbar.classList.contains("fn__none"), true);// 短按继续输入时保留已有 inputmode,折叠选区恢复上下文工具栏。+ visible.delete("mobile-heading1");editable.setAttribute("inputmode", "text");touch("pointerdown");editable.focus();@@ -252,6 +264,10 @@ const runCases = async (sources, platform) => {for (const name of ["indent", "outdent", "strong", "em", "a", "text"]) {assert.equal(hidden(name), true);}+ assert.equal(hidden("block-ref"), true);+ assert.equal(toolbar.querySelector('[data-id="mobile-separator"]').classList.contains("fn__none"), true);+ contextEntries.set("editor.toolbar.mobile-input.block-ref", true);+ await settle();assert.equal(hidden("block-ref"), false);action("block-ref");assert.equal(inserts.at(-1), "((");@@ -305,7 +321,8 @@ const runElectron = async () => {const modules = ["mobile/util/keyboardToolbar", "mobile/util/toolbarActions","mobile/util/toolbarEntries", "mobile/util/mobileAppUtil", "mobile/util/mobileKeyboardChange","mobile/util/touchSelection", "mobile/util/visibleViewport", "protyle/util/hasClosest",- "protyle/toolbar/defaults", "protyle/toolbar/entryVisibility", "config/entryVisibility/order"];+ "protyle/toolbar/defaults", "protyle/toolbar/entryVisibility", "config/entryVisibility/order",+ "config/entryVisibility/mobileToolbarContext"];const sources = Object.fromEntries(modules.map(name => [name, ts.transpileModule(readFileSync(path.join(__dirname, "../src", name + ".ts"), "utf8"),{compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText]));