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 frequently used slash menu items https://github.com/siyuan-note/siyuan/issues/20240
Daniel2031e1637d0e
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 6b5271c38d..14e6570839 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "كثيرة الاستخدام","snippetConflict": "تم تغيير مقتطفات الشيفرة ولم تُحفظ مسودتك. انسخ تعديلاتك، ثم أعد فتح مربع الحوار لدمجها مع أحدث المقتطفات.","agentWelcomeFirst1": "مرحبًا، يسعدني لقاؤك\nلنبدأ بفكرة","agentWelcomeFirst2": "هل تود تدوين شيء أو البحث أو البدء بعمل ما؟\nأخبرني، ولنبدأ معًا",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex f222f14984..5f97bb2f50 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Häufig verwendet","snippetConflict": "Die Snippets wurden geändert. Ihr Entwurf wurde nicht gespeichert. Kopieren Sie Ihre Änderungen und öffnen Sie den Dialog erneut, um sie mit den aktuellen Snippets zusammenzuführen.","agentWelcomeFirst1": "Hallo, schön, dich kennenzulernen\nFangen wir mit einer Idee an","agentWelcomeFirst2": "Möchtest du etwas festhalten, suchen oder anpacken?\nSag mir, was dir vorschwebt, und wir legen gemeinsam los",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 6c432e2ed8..3538f1ba6e 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Frequently used","snippetConflict": "Snippets have changed. Your draft was not saved. Copy your edits, then reopen the dialog to merge them with the latest snippets.","agentWelcomeFirst1": "Hi, it's nice to meet you\nLet's start with an idea","agentWelcomeFirst2": "Want to make a note, find something, or get something done?\nTell me, and let's begin",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 5b5f6c3bff..8527e68c78 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Uso frecuente","snippetConflict": "Los fragmentos han cambiado. El borrador no se guardó. Copia tus cambios y vuelve a abrir el diálogo para combinarlos con los fragmentos más recientes.","agentWelcomeFirst1": "Hola, qué gusto conocerte\nEmpecemos con una idea","agentWelcomeFirst2": "¿Quieres anotar algo, buscar o ponerte manos a la obra?\nCuéntame y empezamos juntos",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 1f08e0f598..04a652e341 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Fréquemment utilisés","snippetConflict": "Les extraits ont changé. Votre brouillon n’a pas été enregistré. Copiez vos modifications, puis rouvrez la boîte de dialogue pour les fusionner avec les derniers extraits.","agentWelcomeFirst1": "Salut, ravi de faire ta connaissance\nCommençons par une idée","agentWelcomeFirst2": "Envie de noter quelque chose, de chercher ou de te lancer ?\nDis-moi, et on commence ensemble",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 1294d2bd95..84b2b8d7fc 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "בשימוש תכוף","snippetConflict": "קטעי הקוד השתנו. הטיוטה שלך לא נשמרה. יש להעתיק את השינויים ולפתוח מחדש את תיבת הדו־שיח כדי לשלב אותם בקטעי הקוד העדכניים.","agentWelcomeFirst1": "היי, נעים להכיר\nנתחיל מרעיון אחד","agentWelcomeFirst2": "רוצה לרשום משהו, לחפש או להתחיל לעשות?\nספר לי, ונתחיל יחד",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 8aec6d755c..a585deed8e 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "अक्सर उपयोग किए जाने वाले","snippetConflict": "कोड स्निपेट बदल गए हैं। आपका ड्राफ़्ट सहेजा नहीं गया। अपने बदलाव कॉपी करें, फिर संवाद दोबारा खोलकर उन्हें नवीनतम स्निपेट में मिलाएँ।","agentWelcomeFirst1": "नमस्ते, आपसे मिलकर अच्छा लगा\nएक विचार से शुरुआत करें","agentWelcomeFirst2": "कुछ लिखना है, खोजना है या कोई काम शुरू करना है?\nमुझे बताइए, साथ मिलकर शुरू करते हैं",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 5dd7d3a909..7a29569059 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Sering digunakan","snippetConflict": "Cuplikan telah berubah. Draf Anda belum disimpan. Salin perubahan Anda, lalu buka kembali dialog untuk menggabungkannya dengan cuplikan terbaru.","agentWelcomeFirst1": "Hai, senang berkenalan denganmu\nMari mulai dari sebuah ide","agentWelcomeFirst2": "Ingin mencatat, mencari, atau mulai mengerjakan sesuatu?\nCeritakan padaku, kita mulai bersama",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex c4d14b2542..a091a5673d 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Usati di frequente","snippetConflict": "Gli snippet sono cambiati. La bozza non è stata salvata. Copia le modifiche e riapri la finestra di dialogo per unirle agli snippet aggiornati.","agentWelcomeFirst1": "Ciao, è un piacere conoscerti\nCominciamo da un’idea","agentWelcomeFirst2": "Vuoi annotare qualcosa, cercare o metterti all’opera?\nDimmi pure, cominciamo insieme",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 8ded4161fe..d7106afc6c 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "よく使う項目","snippetConflict": "スニペットが変更されたため、下書きは保存されませんでした。編集内容をコピーしてからダイアログを開き直し、最新のスニペットに反映してください。","agentWelcomeFirst1": "こんにちは、はじめまして\nひとつのアイデアから始めましょう","agentWelcomeFirst2": "記録する、探す、それとも何か作ってみる?\nやりたいことを教えてください。一緒に始めましょう",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 1e68dfee74..9a220ed0a8 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "자주 사용","snippetConflict": "스니펫이 변경되어 초안이 저장되지 않았습니다. 수정 내용을 복사한 다음 대화 상자를 다시 열어 최신 스니펫과 병합하세요.","agentWelcomeFirst1": "안녕하세요, 만나서 반가워요\n작은 생각 하나부터 시작해 봐요","agentWelcomeFirst2": "기록하거나 찾아보거나, 무언가 해 보고 싶으세요?\n말씀해 주세요, 함께 시작해 봐요",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 132ab6177b..4b37d5fe33 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Veelgebruikt","snippetConflict": "De fragmenten zijn gewijzigd. Je concept is niet opgeslagen. Kopieer je wijzigingen en open het dialoogvenster opnieuw om ze met de nieuwste fragmenten samen te voegen.","agentWelcomeFirst1": "Hoi, leuk je te ontmoeten\nLaten we met een idee beginnen","agentWelcomeFirst2": "Wil je iets vastleggen, opzoeken of aanpakken?\nVertel het me, dan gaan we samen aan de slag",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 61d7dc459d..2434bd7e35 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Często używane","snippetConflict": "Fragmenty kodu zostały zmienione. Szkic nie został zapisany. Skopiuj swoje zmiany, a następnie ponownie otwórz okno, aby połączyć je z aktualnymi fragmentami.","agentWelcomeFirst1": "Cześć, miło cię poznać\nZacznijmy od jednego pomysłu","agentWelcomeFirst2": "Chcesz coś zapisać, znaleźć albo zrobić?\nPowiedz mi i zacznijmy razem",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex f8ae1be7fe..9c3cd8b766 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Usados com frequência","snippetConflict": "Os trechos foram alterados. Seu rascunho não foi salvo. Copie suas alterações e reabra a caixa de diálogo para mesclá-las com os trechos mais recentes.","agentWelcomeFirst1": "Oi, que bom te conhecer\nVamos começar com uma ideia","agentWelcomeFirst2": "Quer anotar, encontrar ou fazer alguma coisa?\nMe conte, e vamos começar juntos",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 86675d010a..ee02ae7e2f 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Часто используемые","snippetConflict": "Фрагменты кода изменились. Черновик не сохранён. Скопируйте свои правки, затем откройте диалог заново и объедините их с актуальными фрагментами.","agentWelcomeFirst1": "Привет, приятно познакомиться\nДавай начнём с одной идеи","agentWelcomeFirst2": "Хочешь что-то записать, найти или сделать?\nРасскажи, и начнём вместе",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 273b1cd8e2..d2a4efd166 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Často používané","snippetConflict": "Úryvky sa zmenili. Koncept nebol uložený. Skopírujte svoje úpravy a znovu otvorte dialóg, aby ste ich zlúčili s najnovšími úryvkami.","agentWelcomeFirst1": "Ahoj, teší ma\nZačnime jedným nápadom","agentWelcomeFirst2": "Chceš niečo zapísať, nájsť alebo urobiť?\nPovedz mi a pustíme sa do toho spolu",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 179fd84c64..46ec97a717 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Често коришћено","snippetConflict": "Исечци кода су промењени. Нацрт није сачуван. Копирајте своје измене, па поново отворите дијалог да их спојите са најновијим исечцима.","agentWelcomeFirst1": "Здраво, драго ми је што се упознајемо\nПочнимо од једне идеје","agentWelcomeFirst2": "Желиш нешто да забележиш, пронађеш или урадиш?\nРеци ми, па да почнемо заједно",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 728aad360e..9b4a2dabf4 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "ใช้บ่อย","snippetConflict": "ข้อมูลโค้ดมีการเปลี่ยนแปลง จึงยังไม่ได้บันทึกฉบับร่าง โปรดคัดลอกสิ่งที่แก้ไข แล้วเปิดกล่องโต้ตอบอีกครั้งเพื่อรวมกับข้อมูลโค้ดล่าสุด","agentWelcomeFirst1": "สวัสดี ยินดีที่ได้รู้จัก\nมาเริ่มจากไอเดียสักอย่างกัน","agentWelcomeFirst2": "อยากจด ค้นหา หรือลงมือทำอะไรสักอย่างไหม\nบอกมาได้เลย แล้วเราเริ่มด้วยกัน",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 7ed2c9b249..9d7cb15fbe 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Sık kullanılanlar","snippetConflict": "Kod parçacıkları değişti. Taslağınız kaydedilmedi. Düzenlemelerinizi kopyalayın, ardından iletişim kutusunu yeniden açarak güncel parçacıklarla birleştirin.","agentWelcomeFirst1": "Merhaba, tanıştığımıza sevindim\nBir fikirle başlayalım","agentWelcomeFirst2": "Bir şey not almak, bulmak ya da yapmak mı istiyorsun?\nAnlat, birlikte başlayalım",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 4d77b155a3..6d49a3323d 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "Часто використовувані","snippetConflict": "Фрагменти коду змінилися. Чернетку не збережено. Скопіюйте свої зміни, потім знову відкрийте діалог і об’єднайте їх з актуальними фрагментами.","agentWelcomeFirst1": "Привіт, приємно познайомитися\nПочнімо з однієї ідеї","agentWelcomeFirst2": "Хочеш щось записати, знайти чи зробити?\nРозкажи, і почнімо разом",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 1225e14a8a..a19354e0aa 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "常用","snippetConflict": "代码片段已发生变化,草稿尚未保存。请复制当前修改,重新打开对话框后与最新片段合并。","agentWelcomeFirst1": "嗨,很高兴见到你\n从一个想法开始吧","agentWelcomeFirst2": "想记录、查找,还是动手做点什么?\n告诉我,我们一起开始",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 42b070d4a5..6d7569bb50 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,5 @@{+ "slashMenuFrequent": "常用","snippetConflict": "程式碼片段已發生變更,草稿尚未儲存。請複製目前的修改,重新開啟對話框後與最新片段合併。","agentWelcomeFirst1": "嗨,很高興見到你\n從一個想法開始吧","agentWelcomeFirst2": "想記錄、查找,還是動手做點什麼?\n告訴我,我們一起開始",diff --git a/app/src/config/entryVisibility/frequentSlashUi.test.ts b/app/src/config/entryVisibility/frequentSlashUi.test.tsnew file mode 100644index 0000000000..8569bf7fc5--- /dev/null+++ b/app/src/config/entryVisibility/frequentSlashUi.test.ts@@ -0,0 +1,202 @@+import * as assert from "node:assert/strict";+import {readFileSync, readdirSync} from "node:fs";+import {resolve} from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, transpileModule} from "typescript";+import * as dockOrder from "./dockOrder";++const loadEditor = (builtin = false, initialEnabled = true) => {+ const listeners: Record<string, (event: any) => void> = {};+ const search = {value: "", addEventListener: (_event: string, callback: typeof listeners.input) => {+ listeners.search = callback;+ }};+ const browser = {innerHTML: "", addEventListener() {}, querySelectorAll: (): [] => [], querySelector: (): null => null};+ const view = {closed: false,+ querySelector: (selector: string) => ({+ ".b3-dialog__body": {innerHTML: ""},+ "[data-type='entry-browser']": browser,+ "[data-type='entry-search']": search,+ "[data-profile-field='name']": {focus() {}},+ }[selector]),+ addEventListener: (event: string, callback: typeof listeners.input) => { listeners[event] = callback; },+ };+ const entries = [{key: "template", label: () => "Template"}, {key: "heading1", label: () => "Heading 1"}];+ const rootEntry = {key: "menu", label: () => "Slash menu", displayChildrenDirectly: true, children: entries};+ const sections = [{key: "editor.slash", label: () => "Slash menu", children: [rootEntry]}];+ const config = {active: "custom", profiles: [{id: "custom", name: "Custom", entries: {}, orders: {}}]};+ const siyuan = {languages: new Proxy({slashMenuFrequent: "Frequently used"}, {+ get: (target, key) => target[key as keyof typeof target] || String(key),+ }), config: {appearance: {entryVisibility: config}}};+ let enabled = initialEnabled;+ let discardPrompts = 0;+ let allowDiscard = true;+ const writes: boolean[] = [];+ const emptyDock = dockOrder.createDockEntryOrderSnapshot({});+ const dependencies = {+ ...dockOrder,+ SLASH_MENU_ROOT_PATH: "editor.slash.menu",+ ENTRY_PROFILE_FULL: "full", ENTRY_PROFILE_SIMPLE: "simple",+ entryCatalog: sections,+ getSettingsOwnerApp: (): undefined => undefined,+ getSettingsWindowHost: (): undefined => undefined,+ isSettingsWindow: () => false,+ getEditorToolbarCatalogSnapshot: (): [] => [],+ refreshToolbarCatalogEntries() {}, refreshTopBarCatalog() {}, refreshDockCatalog() {}, refreshSlashMenuCatalog() {},+ getDockEntryOrderSnapshot: () => emptyDock,+ createEntryProfileSnapshot: () => ({}), createEntryOrderSnapshot: () => ({}),+ isMobile: () => false,+ isInMobileApp: () => false,+ isFrequentSlashEnabled: () => enabled,+ setFrequentSlashEnabled: (value: boolean) => { enabled = value; writes.push(value); },+ getHostCapabilities: () => ({importExport: false}),+ getEntryCatalogChildren: () => entries,+ getEntryCatalogPathChain: (_section: string, path: string) => [path],+ getSavedEntryOrder: (): undefined => undefined,+ resolveEntryOrder: (order: string[]) => order,+ getProfileEntryVisibility: () => true,+ getEntryCatalogCustomDefaultVisibility: () => true,+ isEntryCatalogNodeConfigurable: () => true,+ isEntryOrderSortable: () => true,+ escapeAttr: (value: string) => value,+ escapeHtml: (value: string) => value,+ saveEntryVisibility: (value: typeof config) => { siyuan.config.appearance.entryVisibility = value; },+ confirmDialog: (_title: string, _text: string, callback: () => void) => {+ discardPrompts++;+ if (allowDiscard) callback();+ },+ };+ const source = readFileSync(resolve("src/config/entryVisibility/ui.ts"), "utf8");+ const code = transpileModule(source + `+createEntryView = () => fixtureView;+removeEntryView = () => { fixtureView.closed = true; };+exports.open = openProfileEditor;`, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;+ const exports = {} as {open: (root: any, id: string) => void};+ runInNewContext(code, {exports, require: () => dependencies, window: {siyuan}, fixtureView: view});+ const root = {querySelector: (): null => null};+ const open = () => { view.closed = false; exports.open(root, builtin ? "full" : "custom"); };+ open();+ return {browser, view, writes, open,+ config: () => siyuan.config.appearance.entryVisibility,+ enabled: () => enabled,+ discardPrompts: () => discardPrompts,+ preventDiscard: () => { allowDiscard = false; },+ externalChange: (value: boolean) => { enabled = value; },+ toggle: (checked: boolean) => listeners.change({target: {dataset: {type: "slash-menu-frequent"}, checked}}),+ rerender: () => listeners.search({}),+ search: (value: string) => { search.value = value; listeners.search({}); },+ action: (action: string) => listeners.click({target: {closest: (selector: string) =>+ selector === "[data-action]" ? {dataset: {action}} : null}}),+ };+};++const frequentRow = (html: string) => html.match(/<label[^>]*>\s*<span[^>]*>Frequently used<\/span>[\s\S]*?<\/label>/)?.[0];++test("frequent slash setting uses the first compact row without profile or drag identifiers", () => {+ const fixture = loadEditor();+ const row = frequentRow(fixture.browser.innerHTML);+ assert.ok(row);+ assert.match(row, /config-entry-visibility__row--toggleable/);+ assert.match(row, /class="b3-switch"[^>]*data-type="slash-menu-frequent"[^>]* checked/);+ assert.doesNotMatch(row, /data-entry-|draggable|config-entry-visibility__drag|readonly|disabled/);+ assert.ok(fixture.browser.innerHTML.indexOf(row) < fixture.browser.innerHTML.indexOf('data-entry-key="template"'));+ assert.equal(fixture.writes.length, 0);+});++test("custom frequent slash changes are staged across rerenders and discarded on Cancel or Back", () => {+ for (const action of ["cancel", "back"]) {+ const fixture = loadEditor();+ const profile = JSON.stringify(fixture.config());+ fixture.toggle(false);+ fixture.rerender();+ assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);+ assert.equal(fixture.enabled(), true);+ assert.equal(fixture.writes.length, 0);+ fixture.action(action);+ assert.equal(fixture.discardPrompts(), 1);+ assert.equal(fixture.view.closed, true);+ assert.equal(JSON.stringify(fixture.config()), profile);+ fixture.open();+ assert.match(frequentRow(fixture.browser.innerHTML), / checked/);+ }+});++test("searching the frequent label finds its workspace switch without adding a profile entry", () => {+ const fixture = loadEditor();+ const profile = JSON.stringify(fixture.config());+ fixture.toggle(false);+ fixture.search("frequently used");+ assert.ok(frequentRow(fixture.browser.innerHTML));+ assert.doesNotMatch(fixture.browser.innerHTML, /data-entry-key="template"|config-entry-visibility__drag/);+ assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);+ fixture.search("");+ assert.match(fixture.browser.innerHTML, /data-entry-key="template"/);+ assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);+ assert.equal(JSON.stringify(fixture.config()), profile);+});++test("custom frequent slash changes persist only with Confirm and stay out of profiles", () => {+ const fixture = loadEditor();+ const profile = JSON.stringify(fixture.config());+ fixture.toggle(false);+ fixture.action("confirm");+ assert.deepEqual(fixture.writes, [false]);+ assert.equal(fixture.enabled(), false);+ assert.equal(fixture.view.closed, true);+ assert.equal(JSON.stringify(fixture.config()), profile);+ fixture.open();+ assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);+});++test("declining discard preserves a pending frequent slash change until Confirm", () => {+ const fixture = loadEditor();+ fixture.preventDiscard();+ fixture.toggle(false);+ fixture.action("cancel");+ assert.equal(fixture.view.closed, false);+ assert.equal(fixture.writes.length, 0);+ fixture.action("confirm");+ assert.deepEqual(fixture.writes, [false]);+});++test("unchanged or reverted custom settings do not overwrite a newer workspace preference", () => {+ for (const reverted of [false, true]) {+ const fixture = loadEditor();+ if (reverted) {+ fixture.toggle(false);+ fixture.toggle(true);+ }+ fixture.externalChange(false);+ fixture.action("confirm");+ assert.equal(fixture.enabled(), false);+ assert.equal(fixture.writes.length, 0);+ }+});++test("built-in profile viewers apply the independent workspace switch immediately", () => {+ const fixture = loadEditor(true);+ const profile = JSON.stringify(fixture.config());+ assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), /readonly|disabled/);+ assert.match(fixture.browser.innerHTML, /data-entry-readonly/);+ fixture.toggle(false);+ assert.deepEqual(fixture.writes, [false]);+ fixture.rerender();+ assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);+ fixture.action("cancel");+ assert.equal(fixture.discardPrompts(), 0);+ assert.equal(fixture.view.closed, true);+ assert.equal(JSON.stringify(fixture.config()), profile);+ fixture.open();+ assert.doesNotMatch(frequentRow(fixture.browser.innerHTML), / checked/);+});++test("all bundled languages include a tab-indented frequent slash translation", () => {+ const files = readdirSync("appearance/langs").filter(file => file.endsWith(".json"));+ assert.equal(files.length, 22);+ for (const file of files) {+ const source = readFileSync(resolve("appearance/langs", file), "utf8");+ const language = JSON.parse(source);+ assert.ok(language.slashMenuFrequent.trim(), file);+ assert.match(source, /^\t"slashMenuFrequent":/m, file);+ }+});diff --git a/app/src/config/entryVisibility/mobileUi.test.ts b/app/src/config/entryVisibility/mobileUi.test.tsindex b17792d406..22664aee07 100644--- a/app/src/config/entryVisibility/mobileUi.test.ts+++ b/app/src/config/entryVisibility/mobileUi.test.ts@@ -20,6 +20,7 @@ const browserCases = async (sources: Record<string, string>, languages: Record<slet settingsWindow = false;const ownerSnapshot: Record<string, string[]> = {};let ownerReads = 0;+ let frequentSlashEnabled = true;const cache: Record<string, Record<string, any>> = {};const noop = () => {};window.siyuan = {languages, mobile: {}, storage: {}, config: {editor: {codeTabSpaces: 4}, appearance: {@@ -47,6 +48,8 @@ const browserCases = async (sources: Record<string, string>, languages: Record<s"dialog/confirmDialog": {confirmDialog: (_title: string, _text: string, callback: () => void) => callback()},"dialog/message": {showMessage: noop},"protyle/util/compatibility": {isInMobileApp: () => true},+ "protyle/hint/frequentSlashStorage": {isFrequentSlashEnabled: () => frequentSlashEnabled,+ setFrequentSlashEnabled: (enabled: boolean) => { frequentSlashEnabled = enabled; }},"protyle/toolbar/catalogSnapshot": {getEditorToolbarCatalogSnapshot: (): [] => []},"config/setting/windowContext": {isSettingsWindow: () => settingsWindow,getSettingsOwnerApp: () => window.siyuan.ws?.app,@@ -100,7 +103,18 @@ const browserCases = async (sources: Record<string, string>, languages: Record<scheck(editor?.querySelector("[data-type='entry-section']"), "Profile cards must open the mobile editor");check(Boolean(editor.querySelector("[data-action='confirm']")) === (id === "custom"),"Built-in profiles must remain read-only and custom profiles editable");+ const section = editor.querySelector<HTMLSelectElement>("[data-type='entry-section']");+ section.value = "editor.slash";+ section.dispatchEvent(new Event("change", {bubbles: true}));+ const frequent = editor.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']");+ check(frequent?.checked && !frequent.disabled, "Frequent slash defaults to on in every profile view");+ frequent.click();+ check(frequentSlashEnabled === (id === "custom"), "Only built-in views save the workspace switch immediately");+ if (id !== "custom") {+ frequent.click();+ }editor.querySelector<HTMLElement>("[data-action='cancel']").click();+ check(frequentSlashEnabled, "Cancelling a custom draft does not change the workspace switch");}check(JSON.stringify(config()) === saved, "Viewing and cancelling profiles must preserve saved preferences");root.querySelector<HTMLElement>("[data-profile-id='full'] [data-action='activate']").click();@@ -166,9 +180,19 @@ const browserCases = async (sources: Record<string, string>, languages: Record<sreturn "Narrow new and existing profiles passed";}selectSlash();+ const frequent = view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']");+ check(frequent.checked, "Frequent slash defaults to on");+ const frequentRow = frequent.closest("label");+ check(frequentRow === frequentRow.parentElement.firstElementChild, "Frequent is the first compact slash row");+ check(!frequentRow.hasAttribute("data-entry-row") && !frequentRow.querySelector(".config-entry-visibility__drag"),+ "The workspace switch must not participate in profile sorting");+ frequent.click();+ check(frequentSlashEnabled, "Custom frequent changes must remain staged until confirmed");let enabled = view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu']");check(!enabled.checked, "Mobile slash defaults to off");enabled.click();+ check(!view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']").checked,+ "Frequent switch draft must survive a list rerender");check(config().profiles[0].entries["editor.slash.menu"] !== true, "Total switch must remain a draft until confirmed");check(view.querySelectorAll("[data-type='entry-mobile-options'] input").length === 1, "Only one total switch is shown");check(!view.querySelector("[data-entry-move]"), "No arrow sort controls");@@ -220,6 +244,7 @@ const browserCases = async (sources: Record<string, string>, languages: Record<ssend(browser, "pointerup", {clientX: -20, clientY: -20});check(!browser.querySelector(".config-entry-visibility__row--drop-after"), "Outside release clears drop target");view.querySelector<HTMLElement>("[data-action='confirm']").click();+ check(!frequentSlashEnabled, "Confirm must save the independent frequent switch");const order = config().profiles[0].orders["editor.slash.menu"];check(config().profiles[0].entries["editor.slash.menu"] === true, "Confirm saves total switch in the profile");check(order.includes("plugin:missing:item"), "Unavailable plugin slots must survive sorting");@@ -228,7 +253,15 @@ const browserCases = async (sources: Record<string, string>, languages: Record<sselectSlash();enabled = view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu']");check(enabled.checked, "Reopening must preserve profile setting");+ check(!view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']").checked,+ "Reopening must preserve the workspace frequent setting");+ view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']").click();const search = view.querySelector<HTMLInputElement>("[data-type='entry-search']");+ search.value = languages.slashMenuFrequent;+ search.dispatchEvent(new Event("input", {bubbles: true}));+ check(view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']")?.checked,+ "Searching the frequent label must reveal the pending workspace switch");+ check(!view.querySelector("[data-entry-key='template']"), "Frequent search must not include unrelated candidates");search.value = "heading1";search.dispatchEvent(new Event("input", {bubbles: true}));check(!view.querySelector(".config-entry-visibility__drag"), "Search results must not permit partial-list sorting");@@ -240,6 +273,7 @@ const browserCases = async (sources: Record<string, string>, languages: Record<scheck(view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu.heading1']").disabled,"Disabled menu must disable candidate controls");view.querySelector<HTMLElement>("[data-action='cancel']").click();+ check(!frequentSlashEnabled, "Cancel must discard the staged frequent change");check(config().profiles[0].entries["editor.slash.menu"] === true, "Cancel must discard the total switch change");view = open("full");selectSlash();@@ -249,6 +283,8 @@ const browserCases = async (sources: Record<string, string>, languages: Record<senabled = view.querySelector<HTMLInputElement>("[data-entry-path='editor.slash.menu']");enabled.click();check(!enabled.checked, "Built-in total switch follows mobile default and remains read-only");+ view.querySelector<HTMLInputElement>("[data-type='slash-menu-frequent']").click();+ check(frequentSlashEnabled, "Built-in viewers must allow immediate workspace frequent changes");view.querySelector<HTMLElement>("[data-action='cancel']").click();mobile = false;delete window.siyuan.mobile;diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.tsindex 838c33462c..74db83a71a 100644--- a/app/src/config/entryVisibility/ui.ts+++ b/app/src/config/entryVisibility/ui.ts@@ -16,6 +16,7 @@ import {refreshSlashMenuCatalog,refreshTopBarCatalog,refreshToolbarCatalogEntries,+ SLASH_MENU_ROOT_PATH,TOP_BAR_ROOT_PATH,STATUS_BAR_ROOT_PATH,} from "./catalog";@@ -50,6 +51,7 @@ import {bindTouchOrder} from "./touchOrder";import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";import {MOBILE_TOOLBAR_CONTEXT_KEYS} from "./mobileToolbarContext";import {getSettingsOwnerApp} from "../setting/windowContext";+import {isFrequentSlashEnabled, setFrequentSlashEnabled} from "../../protyle/hint/frequentSlashStorage";/// #if !MOBILEimport {getSettingsWindowHost, isSettingsWindow} from "../setting/windowContext";import {getEditorToolbarCatalogSnapshot} from "../../protyle/toolbar/catalogSnapshot";@@ -314,7 +316,7 @@ const renderEntryRows = (profile: Config.IEntryVisibilityProfile, prefix: stringconst renderEntryColumn = (profile: Config.IEntryVisibilityProfile, title: string, prefix: string,nodes: IEntryCatalogNode[], depth: number, selectedPaths: string[],- parentEnabled: boolean, readOnly: boolean, sortable: boolean,+ parentEnabled: boolean, readOnly: boolean, sortable: boolean, frequentSlashEnabled: boolean,getItemPath = (item: IEntryCatalogNode) => `${prefix}.${item.key}`) => `<section class="config-entry-visibility__column"data-entry-column data-entry-depth="${depth}"><div class="config-entry-visibility__column-title">@@ -322,6 +324,12 @@ const renderEntryColumn = (profile: Config.IEntryVisibilityProfile, title: strin${sortable ? renderOrderReset(prefix) : ""}</div><div class="config-entry-visibility__column-list">+ ${prefix === SLASH_MENU_ROOT_PATH ? `<label class="config-entry-visibility__row config-entry-visibility__row--toggleable">+ <span class="config-entry-visibility__label">${escapeHtml(window.siyuan.languages.slashMenuFrequent)}</span>+ <input class="b3-switch" type="checkbox" data-type="slash-menu-frequent"+ aria-label="${escapeAttr(window.siyuan.languages.slashMenuFrequent)}"${frequentSlashEnabled ? " checked" : ""}>+ <span class="config-entry-visibility__arrow-space"></span>+ </label>` : ""}${renderEntryRows(profile, prefix, nodes, depth, selectedPaths, parentEnabled, readOnly, sortable, getItemPath)}</div></section>`;@@ -458,7 +466,8 @@ 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()) => {+ visibleSectionKeys?: Set<string>, dockOrderSnapshot = getDockEntryOrderSnapshot(),+ frequentSlashEnabled = isFrequentSlashEnabled()) => {const catalog = getVisibleEntryCatalog();const sections = visibleSectionKeys? catalog.filter((item) => visibleSectionKeys.has(item.key))@@ -496,11 +505,11 @@ const renderEntryColumns = (profile: Config.IEntryVisibilityProfile, sectionKey:const columnNodes = visiblePaths? orderedNodes.filter((item) => item.type !== "separator" && visiblePaths.has(`${prefix}.${item.key}`)): orderedNodes;- if (columnNodes.length === 0) {+ if (columnNodes.length === 0 && prefix !== SLASH_MENU_ROOT_PATH) {break;}columns.push(renderEntryColumn(profile, title, prefix, columnNodes, depth, columnSelectedPaths,- parentEnabled, readOnly, !visiblePaths && isEntryOrderSortable(prefix) && !readOnly));+ parentEnabled, readOnly, !visiblePaths && isEntryOrderSortable(prefix) && !readOnly, frequentSlashEnabled));const selectedPath = columnSelectedPaths[depth];const selectedNode = selectedPath && columnNodes.find((item) => `${prefix}.${item.key}` === selectedPath);if (!selectedNode?.children?.length) {@@ -540,7 +549,15 @@ const getEntrySearchResults = (query: string) => {}});};- getVisibleEntryCatalog().forEach((section) => visit(section, section.key, section.children, [section.label()]));+ getVisibleEntryCatalog().forEach((section) => {+ visit(section, section.key, section.children, [section.label()]);+ const root = getDirectDisplayRoot(section);+ if (root && `${section.key}.${root.key}` === SLASH_MENU_ROOT_PATH &&+ window.siyuan.languages.slashMenuFrequent.toLowerCase().includes(query)) {+ results.push({section, item: root, path: SLASH_MENU_ROOT_PATH,+ labels: [section.label(), window.siyuan.languages.slashMenuFrequent]});+ }+ });return results;};@@ -613,6 +630,8 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {: createProfile(ENTRY_PROFILE_SIMPLE);draft.orders ||= createEntryOrderSnapshot();const initialJSON = JSON.stringify(draft);+ const initialFrequentSlashEnabled = isFrequentSlashEnabled();+ let frequentSlashEnabled = initialFrequentSlashEnabled;const creating = !builtin && !existing;const view = createEntryView(root);const body = view.querySelector<HTMLElement>(".b3-dialog__body");@@ -712,7 +731,7 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {</label>` : "";}browser.innerHTML = renderEntryColumns(draft, selectedSectionKey, selectedPaths, builtin,- filter?.visiblePaths, filter?.visibleSectionKeys, dockOrderSnapshot);+ filter?.visiblePaths, filter?.visibleSectionKeys, dockOrderSnapshot, frequentSlashEnabled);previousQuery = query;const columnsContainer = browser.querySelector<HTMLElement>(".config-entry-visibility__columns");const columns = Array.from(browser.querySelectorAll<HTMLElement>("[data-entry-column]"));@@ -738,7 +757,7 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {removeEntryView(root, view);};const closeEditor = () => {- if (JSON.stringify(draft) !== initialJSON) {+ if (JSON.stringify(draft) !== initialJSON || !builtin && frequentSlashEnabled !== initialFrequentSlashEnabled) {confirmDialog(window.siyuan.languages.confirm, window.siyuan.languages.discardUnsavedChanges, leaveEditor);return;}@@ -901,6 +920,13 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {});view.addEventListener("change", (event) => {const control = event.target as HTMLInputElement | HTMLSelectElement;+ if (control.dataset.type === "slash-menu-frequent") {+ frequentSlashEnabled = (control as HTMLInputElement).checked;+ if (builtin) {+ setFrequentSlashEnabled(frequentSlashEnabled);+ }+ return;+ }if (control.dataset.type === "entry-section") {selectedSectionKey = control.value;selectedPaths = [];@@ -976,6 +1002,9 @@ const openProfileEditor = (root: HTMLElement, profileID?: string) => {config.profiles.push(draft);}saveEntryVisibility(config);+ if (frequentSlashEnabled !== initialFrequentSlashEnabled) {+ setFrequentSlashEnabled(frequentSlashEnabled);+ }renderProfileCards(root);leaveEditor();}diff --git a/app/src/constants.ts b/app/src/constants.tsindex f8a06b07f3..54e0b159a8 100644--- a/app/src/constants.ts+++ b/app/src/constants.ts@@ -191,6 +191,8 @@ export abstract class Constants {public static readonly LOCAL_DAILYNOTEID = "local-dailynoteid"; // stringpublic static readonly LOCAL_HISTORY = "local-history";public static readonly LOCAL_CODELANG = "local-codelang"; // string+ public static readonly LOCAL_SLASH_FREQUENT_ENABLED = "local-slash-frequent-enabled";+ public static readonly LOCAL_SLASH_USAGE = "local-slash-usage";public static readonly LOCAL_FONTSTYLES = "local-fontstyles";public static readonly LOCAL_EXPORTPDF = "local-exportpdf";public static readonly LOCAL_EXPORTWORD = "local-exportword";diff --git a/app/src/mobile/util/frequentSlashMenu.test.ts b/app/src/mobile/util/frequentSlashMenu.test.tsnew file mode 100644index 0000000000..730a9dd0ef--- /dev/null+++ b/app/src/mobile/util/frequentSlashMenu.test.ts@@ -0,0 +1,204 @@+import * as assert from "node:assert/strict";+import {spawnSync} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";+import {getFrequentSlashButtons, prependFrequentSlashButtons} from "./liteSlashMenu";+import {rankFrequentSlashItems} from "../../protyle/hint/frequentSlash";++class Button {+ public dataset: {slashEntryKey: string};+ public cloned = false;++ constructor(entryKey: string, public variant = false) {+ this.dataset = {slashEntryKey: entryKey};+ }++ public querySelector() {+ return this.variant ? {} : null;+ }++ public cloneNode(deep: boolean) {+ assert.equal(deep, true);+ const copy = new Button(this.dataset.slashEntryKey, this.variant);+ copy.cloned = true;+ return copy;+ }+}++const container = (buttons: Button[]) => ({querySelectorAll: () => buttons}) as unknown as HTMLElement;++test("mobile frequent candidates intersect actual buttons with eligible configured order", () => {+ const buttons = [new Button("hidden"), new Button("plugin:a:insert"), new Button("code"),+ new Button("plugin:b:insert"), new Button("heading1")];+ const eligible = ["heading1", "plugin:b:insert", "missing", "code", "plugin:a:insert", "code"];+ const result = getFrequentSlashButtons(container(buttons), eligible);+ assert.deepEqual(result.map(button => button.dataset.slashEntryKey),+ ["heading1", "plugin:b:insert", "code", "plugin:a:insert"]);+ assert.deepEqual(rankFrequentSlashItems(result, item => item.dataset.slashEntryKey,+ {hidden: 100, missing: 99, heading1: 1, code: 2, "plugin:b:insert": 2})+ .map(button => button.dataset.slashEntryKey), ["plugin:b:insert", "code", "heading1"]);+ assert.equal(buttons.length, 5);+});++test("mobile Android upload variants share one identity and prefer the ordinary upload button", () => {+ const buttons = [new Button("insertAsset", true), new Button("insertAsset", true), new Button("insertAsset")];+ assert.deepEqual(getFrequentSlashButtons(container(buttons), ["insertAsset"]), [buttons[2]]);+ assert.deepEqual(getFrequentSlashButtons(container(buttons.slice(0, 2)), ["insertAsset"]), [buttons[0]]);+});++test("mobile frequent group clones supported buttons and preserves the original menu nodes", () => {+ const previousDocument = Object.getOwnPropertyDescriptor(globalThis, "document");+ class Element {+ public className = "";+ public attributes: Record<string, string> = {};+ public children: unknown[] = [];+ public setAttribute(key: string, value: string) { this.attributes[key] = value; }+ public appendChild(value: unknown) { this.children.push(value); }+ public prepend(...values: unknown[]) { this.children.unshift(...values); }+ }+ Object.defineProperty(globalThis, "document", {configurable: true, value: {createElement: () => new Element()}});+ try {+ const root = new Element();+ const original = new Element();+ root.children.push(original);+ prependFrequentSlashButtons(root as unknown as HTMLElement, []);+ assert.deepEqual(root.children, [original]);+ const code = new Button("code");+ prependFrequentSlashButtons(root as unknown as HTMLElement, [code] as unknown as HTMLButtonElement[]);+ const [group, separator] = root.children as Element[];+ assert.equal(group.className, "keyboard__slash-block");+ assert.equal((group.children[0] as Button).dataset.slashEntryKey, "code");+ assert.equal((group.children[0] as Button).cloned, true);+ assert.notEqual(group.children[0], code);+ assert.equal(separator.className, "b3-menu__separator");+ assert.equal(separator.attributes.role, "separator");+ assert.equal(root.children[2], original);+ } finally {+ if (previousDocument) {+ Object.defineProperty(globalThis, "document", previousDocument);+ } else {+ delete globalThis.document;+ }+ }+});++test("full mobile slash panel keeps original hidden items and only prefixes eligible rendered commands", () => {+ const filename = path.join(__dirname, "keyboardToolbar.ts");+ const file = createSourceFile(filename, readFileSync(filename, "utf8"), ScriptTarget.Latest, true);+ const source = file.statements.filter(statement => isVariableStatement(statement) &&+ statement.declarationList.declarations.some(declaration =>+ ["getSlashItem", "renderSlashMenu"].includes(declaration.name.getText(file))))+ .map(statement => statement.getText(file)).join("\n");+ let mounted = 0;+ let boundUploads = 0;+ let eligibilityCalls = 0;+ let frequentButtons: HTMLButtonElement[] = [];+ const util = {+ innerHTML: "",+ querySelectorAll: () => Array.from(util.innerHTML.matchAll(/<button[^>]+data-slash-entry-key="([^"]+)"[^>]*>/g),+ match => new Button(match[1])),+ };+ const root = {querySelector: () => util};+ const protyle = {+ lite: false,+ app: {plugins: [] as unknown[]},+ hint: {splitChar: "", lastIndex: 0, bindUploadEvent: () => boundUploads++},+ options: {upload: {}},+ };+ const environment = {+ Constants: {ZWSP: "\u200b", CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap"},+ Lute: {Caret: "caret"},+ window: {siyuan: {languages: {}}},+ SLASH_MENU_ROOT_PATH: "editor.slash.menu",+ getHostCapabilities: () => ({widgets: false, remoteKernel: true}),+ isDisabledFeature: () => true,+ isInAndroid: () => false,+ isBuiltinInlineStyleVisible: () => false,+ getSuperBlockCommand: (layout: string) => layout,+ escapeHtml: (value: string) => value,+ getFrequentSlashButtons,+ getFrequentSlashItems: (buttons: HTMLButtonElement[], getKey: (button: HTMLButtonElement) => string) =>+ rankFrequentSlashItems(buttons, getKey, {heading1: 100, code: 1, insertHTMLFile: 99}),+ hintSlash: (key: string, editor: unknown, hideConfiguredCreate: boolean, options: {visibilityRoot: string}) => {+ eligibilityCalls++;+ assert.equal(key, "");+ assert.equal(editor, protyle);+ assert.equal(hideConfiguredCreate, false);+ assert.equal(options.visibilityRoot, "editor.slash.menu");+ return [{entryKey: "code", html: "Code"}, {entryKey: "insertHTMLFile", html: "HTML upload"},+ {entryKey: "separator_1", html: "separator"}];+ },+ prependFrequentSlashButtons: (_container: unknown, buttons: HTMLButtonElement[]) => frequentButtons = buttons,+ mountLiteSlashMenu: () => { mounted++; },+ };+ const render = new Function("environment", "const {" + Object.keys(environment).join(",") ++ "} = environment; let unmountLiteSlashMenu; " + transpileModule(source,+ {compilerOptions: {target: ScriptTarget.ES2021}}).outputText + "\nreturn renderSlashMenu;")(environment) as+ (editor: unknown, toolbar: unknown) => void;+ render(protyle, root);+ assert.equal(eligibilityCalls, 1);+ assert.deepEqual(frequentButtons.map(button => button.dataset.slashEntryKey), ["code"]);+ assert.equal((util.innerHTML.match(/data-slash-entry-key="heading1"/g) || []).length, 1);+ assert.equal((util.innerHTML.match(/data-slash-entry-key="code"/g) || []).length, 1);+ assert.equal((util.innerHTML.match(/data-slash-entry-key="insertAsset"/g) || []).length, 1);+ assert.equal((util.innerHTML.match(/data-slash-entry-key="insertHTMLFile"/g) || []).length, 0);+ assert.equal(boundUploads, 1);+ assert.equal(protyle.hint.splitChar, "/");+ assert.equal(protyle.hint.lastIndex, -1);+ protyle.lite = true;+ render(protyle, root);+ assert.equal(mounted, 1);+ assert.equal(eligibilityCalls, 1);+ assert.equal(boundUploads, 1);+});++const chromium = process.env.CHROMIUM_PATH;++test("mobile lite renderer preserves stable keys, separate uploads, original order and frequent divider", {+ skip: !chromium,+}, () => {+ const source = transpileModule(readFileSync(path.join(__dirname, "liteSlashMenu.ts"), "utf8")+ .replace(/^import type .*;\n/gm, "").replace(/^export /gm, ""),+ {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;+ const directory = mkdtempSync(path.join(tmpdir(), "siyuan-frequent-mobile-"));+ try {+ const html = path.join(directory, "index.html");+ writeFileSync(html, `<body><script>${source}+ const item = (entryKey, html, value = "shared-upload") => ({entryKey, html, value});+ const code = item("code", '<span class="b3-list-item__text">Code</span>', "code");+ const asset = item("insertAsset", '<span class="b3-list-item__text">File</span><input type="file">');+ const embed = item("insertHTMLFile", '<span class="b3-list-item__text">HTML</span><input type="file" data-upload-mode="html-iframe">');+ const untracked = {id: "custom", value: "custom", html: "Custom"};+ const original = [code, asset, embed, untracked];+ const result = document.createElement("div");+ result.innerHTML = getLiteSlashMenuHTML([asset, item("__frequent_separator__", "separator"), ...original]);+ document.body.append(result);+ const keys = Array.from(result.querySelectorAll("button"), button => button.dataset.slashEntryKey || "");+ const checks = [+ keys.join(",") === "insertAsset,code,insertAsset,insertHTMLFile,",+ result.firstElementChild.className === "keyboard__slash-block",+ result.querySelectorAll('.b3-menu__separator[role="separator"]').length === 1,+ result.querySelectorAll('.keyboard__slash-title').length === 1,+ result.querySelectorAll('input[type="file"]').length === 3,+ result.querySelectorAll('input[data-upload-mode="html-iframe"]').length === 1,+ !result.querySelector('[data-id="custom"]').hasAttribute("data-slash-entry-key"),+ ];+ const saved = result.innerHTML;+ result.innerHTML = getLiteSlashMenuHTML(original);+ checks.push(!result.querySelector('.b3-menu__separator'));+ checks.push(Array.from(result.querySelectorAll("button"), button => button.dataset.slashEntryKey || "").join(",") === "code,insertAsset,insertHTMLFile,");+ document.body.setAttribute("data-results", checks.join(","));+ result.innerHTML = saved;+ </script></body>`, "utf8");+ const result = spawnSync(chromium, ["--headless", "--no-sandbox", "--disable-dev-shm-usage", "--disable-gpu",+ "--dump-dom", `--user-data-dir=${path.join(directory, "profile")}`, `file://${html}`],+ {encoding: "utf8", timeout: 30000, env: {...process.env, HOME: directory, XDG_CONFIG_HOME: directory}});+ assert.equal(result.status, 0, result.error?.message || result.stderr);+ assert.match(result.stdout, /data-results="true,true,true,true,true,true,true,true,true"/);+ } finally {+ rmSync(directory, {recursive: true, force: true});+ }+});diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.tsindex a47db76a55..4c5fbd6f72 100644--- a/app/src/mobile/util/keyboardToolbar.ts+++ b/app/src/mobile/util/keyboardToolbar.ts@@ -85,7 +85,10 @@ import {MOBILE_TOOLBAR_NAMES} from "../../protyle/toolbar/defaults";import {getKeyboardPanelHeight} from "./keyboardPanelHeight";import {isMobileLandscape} from "./orientation";import {restoreGutterBySelection} from "../../protyle/gutter/restore";-import {mountLiteSlashMenu} from "./liteSlashMenu";+import {getFrequentSlashButtons, mountLiteSlashMenu, prependFrequentSlashButtons} from "./liteSlashMenu";+import {getPluginSlashEntryKey, SLASH_MENU_ROOT_PATH} from "../../config/entryVisibility/catalog";+import {hintSlash} from "../../protyle/hint/extend";+import {getFrequentSlashItems} from "../../protyle/hint/frequentSlashStorage";import {getTableCellRichContext} from "../../protyle/util/tableCellRichContext";import {insertEmptyBlock} from "../../block/util";import {getIconByType} from "../../editor/getIcon";@@ -468,14 +471,14 @@ const updateKeyboardPanelHeight = () => {}};-const getSlashItem = (value: string, icon: string, text: string, focus = "false") => {+const getSlashItem = (entryKey: string, value: string, icon: string, text: string, focus = "false") => {let iconHTML;if (icon && icon.startsWith("icon")) {iconHTML = `<svg class="keyboard__slash-icon"><use xlink:href="#${icon}"></use></svg>`;} else {iconHTML = icon;}- return `<button class="keyboard__slash-item" data-focus="${focus}" data-value="${encodeURIComponent(value)}">+ return `<button class="keyboard__slash-item"${entryKey ? ` data-slash-entry-key="${escapeHtml(entryKey)}"` : ""} data-focus="${focus}" data-value="${encodeURIComponent(value)}">${iconHTML}<span class="keyboard__slash-text">${text}</span></button>`;@@ -740,8 +743,8 @@ const renderSlashMenu = (protyle: IProtyle, toolbarElement: Element) => {let pluginHTML = "";protyle.app.plugins.forEach((plugin) => {plugin.protyleSlash.forEach(slash => {- pluginHTML += getSlashItem(`plugin${Constants.ZWSP}${plugin.name}${Constants.ZWSP}${slash.id}`,- "", slash.html, "true");+ pluginHTML += getSlashItem(slash.html === "separator" ? "" : getPluginSlashEntryKey(plugin.name, slash.id),+ `plugin${Constants.ZWSP}${plugin.name}${Constants.ZWSP}${slash.id}`, "", slash.html, "true");});});if (pluginHTML) {@@ -754,74 +757,78 @@ const renderSlashMenu = (protyle: IProtyle, toolbarElement: Element) => {}const style = getBuiltinStyleCSS(id);const preview = getBuiltinInlineStylePreview(id);- builtinStyleHTML += getSlashItem(`style${Constants.ZWSP}${style}`,+ builtinStyleHTML += getSlashItem(id + "Style", `style${Constants.ZWSP}${style}`,`<div style="color:${preview.color};background-color:${preview.backgroundColor};" class="keyboard__slash-icon">A</div>`,getBuiltinStyleLabel(id), "true");});const utilElement = toolbarElement.querySelector(".keyboard__util") as HTMLElement;utilElement.innerHTML = `<div class="keyboard__slash-title"></div><div class="keyboard__slash-block">- ${getSlashItem(Constants.ZWSP, "iconMarkdown", window.siyuan.languages.template)}- ${getHostCapabilities().widgets ? getSlashItem(Constants.ZWSP + 1, "iconBoth", window.siyuan.languages.widget) : ""}- ${getSlashItem(Constants.ZWSP + 2, "iconImage", window.siyuan.languages.assets)}- ${getSlashItem("((", "iconRef", window.siyuan.languages.ref, "true")}- ${getSlashItem("{{", "iconSQL", window.siyuan.languages.blockEmbed, "true")}- ${isDisabledFeature("ai") ? "" : getSlashItem(Constants.ZWSP + 5, "iconSparkles", window.siyuan.languages.aiWriting)}- ${getSlashItem('<div data-type="NodeAttributeView" data-av-type="table"></div>', "iconDatabase", window.siyuan.languages.database, "true")}- ${getSlashItem(Constants.ZWSP + 6, "iconFile", window.siyuan.languages.newSubDocRef)}+ ${getSlashItem("template", Constants.ZWSP, "iconMarkdown", window.siyuan.languages.template)}+ ${getHostCapabilities().widgets ? getSlashItem("widget", Constants.ZWSP + 1, "iconBoth", window.siyuan.languages.widget) : ""}+ ${getSlashItem("assets", Constants.ZWSP + 2, "iconImage", window.siyuan.languages.assets)}+ ${getSlashItem("ref", "((", "iconRef", window.siyuan.languages.ref, "true")}+ ${getSlashItem("blockEmbed", "{{", "iconSQL", window.siyuan.languages.blockEmbed, "true")}+ ${isDisabledFeature("ai") ? "" : getSlashItem("aiWriting", Constants.ZWSP + 5, "iconSparkles", window.siyuan.languages.aiWriting)}+ ${getSlashItem("database", '<div data-type="NodeAttributeView" data-av-type="table"></div>', "iconDatabase", window.siyuan.languages.database, "true")}+ ${getSlashItem("newSubDocRef", Constants.ZWSP + 6, "iconFile", window.siyuan.languages.newSubDocRef)}</div><div class="keyboard__slash-title"></div><div class="keyboard__slash-block">- ${isInAndroid() ? getSlashItem(Constants.ZWSP + 3, "iconImage", window.siyuan.languages.insertImage + '<input class="b3-form__upload" type="file" multiple="multiple" accept="image/*,application/x-siyuan-image-picker"/>', "true") : ""}- ${isInAndroid() ? getSlashItem(Constants.ZWSP + 3, "iconCamera", window.siyuan.languages.insertPhoto + '<input class="b3-form__upload" capture="user" type="file"' + (protyle.options.upload.accept ? (' multiple="' + protyle.options.upload.accept + '"') : "") + "/>", "true") : ""}- ${getSlashItem(Constants.ZWSP + 3, "iconDownload", window.siyuan.languages.insertAsset + '<input class="b3-form__upload" type="file" multiple="multiple"' + (protyle.options.upload.accept ? (' accept="' + protyle.options.upload.accept + '"') : "") + "/>", "true")}- ${getHostCapabilities().remoteKernel ? "" : getSlashItem('<iframe sandbox="allow-forms allow-presentation allow-same-origin allow-scripts allow-modals allow-popups allow-storage-access-by-user-activation" src="" border="0" frameborder="no" framespacing="0" allowfullscreen="true"></iframe>', "iconGlobe", window.siyuan.languages.insertIframeURL, "true")}- ${getSlashItem("![]()", "iconImage", window.siyuan.languages.insertImgURL, "true")}- ${getSlashItem('<video controls="controls" src=""></video>', "iconVideo", window.siyuan.languages.insertVideoURL, "true")}- ${getSlashItem('<audio controls="controls" src=""></audio>', "iconRecord", window.siyuan.languages.insertAudioURL, "true")}- ${getSlashItem("emoji", "iconEmoji", window.siyuan.languages.emoji, "true")}+ ${isInAndroid() ? getSlashItem("insertAsset", Constants.ZWSP + 3, "iconImage", window.siyuan.languages.insertImage + '<input class="b3-form__upload" type="file" multiple="multiple" accept="image/*,application/x-siyuan-image-picker"/>', "true") : ""}+ ${isInAndroid() ? getSlashItem("insertAsset", Constants.ZWSP + 3, "iconCamera", window.siyuan.languages.insertPhoto + '<input class="b3-form__upload" capture="user" type="file"' + (protyle.options.upload.accept ? (' multiple="' + protyle.options.upload.accept + '"') : "") + "/>", "true") : ""}+ ${getSlashItem("insertAsset", Constants.ZWSP + 3, "iconDownload", window.siyuan.languages.insertAsset + '<input class="b3-form__upload" type="file" multiple="multiple"' + (protyle.options.upload.accept ? (' accept="' + protyle.options.upload.accept + '"') : "") + "/>", "true")}+ ${getHostCapabilities().remoteKernel ? "" : getSlashItem("insertIframeURL", '<iframe sandbox="allow-forms allow-presentation allow-same-origin allow-scripts allow-modals allow-popups allow-storage-access-by-user-activation" src="" border="0" frameborder="no" framespacing="0" allowfullscreen="true"></iframe>', "iconGlobe", window.siyuan.languages.insertIframeURL, "true")}+ ${getSlashItem("insertImgURL", "![]()", "iconImage", window.siyuan.languages.insertImgURL, "true")}+ ${getSlashItem("insertVideoURL", '<video controls="controls" src=""></video>', "iconVideo", window.siyuan.languages.insertVideoURL, "true")}+ ${getSlashItem("insertAudioURL", '<audio controls="controls" src=""></audio>', "iconRecord", window.siyuan.languages.insertAudioURL, "true")}+ ${getSlashItem("emoji", "emoji", "iconEmoji", window.siyuan.languages.emoji, "true")}</div><div class="keyboard__slash-title"></div><div class="keyboard__slash-block">- ${getSlashItem("# " + Lute.Caret, "iconH1", window.siyuan.languages.heading1, "true")}- ${getSlashItem("## " + Lute.Caret, "iconH2", window.siyuan.languages.heading2, "true")}- ${getSlashItem("### " + Lute.Caret, "iconH3", window.siyuan.languages.heading3, "true")}- ${getSlashItem("#### " + Lute.Caret, "iconH4", window.siyuan.languages.heading4, "true")}- ${getSlashItem("##### " + Lute.Caret, "iconH5", window.siyuan.languages.heading5, "true")}- ${getSlashItem("###### " + Lute.Caret, "iconH6", window.siyuan.languages.heading6, "true")}- ${getSlashItem("- " + Lute.Caret, "iconList", window.siyuan.languages.list, "true")}- ${getSlashItem("1. " + Lute.Caret, "iconOrderedList", window.siyuan.languages["ordered-list"], "true")}- ${getSlashItem("- [ ] " + Lute.Caret, "iconCheck", window.siyuan.languages.check, "true")}- ${getSlashItem("> " + Lute.Caret, "iconQuote", window.siyuan.languages.quote, "true")}- ${getSlashItem(getSuperBlockCommand("col"), "iconSuper", window.siyuan.languages.horizontalSuperBlock, "true")}- ${getSlashItem(getSuperBlockCommand("row"), "iconSuper", window.siyuan.languages.verticalSuperBlock, "true")}- ${getSlashItem(`::: tabs\n@tab\n\n${Lute.Caret}\n\n@tab\n\n:::\n`, "iconTabs", window.siyuan.languages.tabs, "true")}- ${getSlashItem(`- ${Lute.Caret}\n{: ${Constants.CUSTOM_SY_LIST_MINDMAP}="1"}`, "iconMindmap", window.siyuan.languages.mindmap, "true")}- ${getSlashItem(`> [!NOTE]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">✏️</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-note)">Note</span>`, "true")}- ${getSlashItem(`> [!TIP]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">💡</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-tip)">Tip</span>`, "true")}- ${getSlashItem(`> [!IMPORTANT]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">❗</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-important)">Important</span>`, "true")}- ${getSlashItem(`> [!WARNING]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">⚠️</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-warning)">Warning</span>`, "true")}- ${getSlashItem(`> [!CAUTION]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">🚨</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-caution)">Caution</span>`, "true")}- ${getSlashItem("```", "iconCode", window.siyuan.languages.code, "true")}- ${getSlashItem(`| ${Lute.Caret} | | |\n| --- | --- | --- |\n| | | |\n| | | |`, "iconTable", window.siyuan.languages.table, "true")}- ${getSlashItem("---", "iconLine", window.siyuan.languages.line, "true")}- ${getSlashItem("$$", "iconMath", window.siyuan.languages.math)}- ${getSlashItem("<div>", "iconHTML5", "HTML")}+ ${getSlashItem("heading1", "# " + Lute.Caret, "iconH1", window.siyuan.languages.heading1, "true")}+ ${getSlashItem("heading2", "## " + Lute.Caret, "iconH2", window.siyuan.languages.heading2, "true")}+ ${getSlashItem("heading3", "### " + Lute.Caret, "iconH3", window.siyuan.languages.heading3, "true")}+ ${getSlashItem("heading4", "#### " + Lute.Caret, "iconH4", window.siyuan.languages.heading4, "true")}+ ${getSlashItem("heading5", "##### " + Lute.Caret, "iconH5", window.siyuan.languages.heading5, "true")}+ ${getSlashItem("heading6", "###### " + Lute.Caret, "iconH6", window.siyuan.languages.heading6, "true")}+ ${getSlashItem("list", "- " + Lute.Caret, "iconList", window.siyuan.languages.list, "true")}+ ${getSlashItem("orderedList", "1. " + Lute.Caret, "iconOrderedList", window.siyuan.languages["ordered-list"], "true")}+ ${getSlashItem("check", "- [ ] " + Lute.Caret, "iconCheck", window.siyuan.languages.check, "true")}+ ${getSlashItem("quote", "> " + Lute.Caret, "iconQuote", window.siyuan.languages.quote, "true")}+ ${getSlashItem("horizontalSuperBlock", getSuperBlockCommand("col"), "iconSuper", window.siyuan.languages.horizontalSuperBlock, "true")}+ ${getSlashItem("verticalSuperBlock", getSuperBlockCommand("row"), "iconSuper", window.siyuan.languages.verticalSuperBlock, "true")}+ ${getSlashItem("tabs", `::: tabs\n@tab\n\n${Lute.Caret}\n\n@tab\n\n:::\n`, "iconTabs", window.siyuan.languages.tabs, "true")}+ ${getSlashItem("mindmap", `- ${Lute.Caret}\n{: ${Constants.CUSTOM_SY_LIST_MINDMAP}="1"}`, "iconMindmap", window.siyuan.languages.mindmap, "true")}+ ${getSlashItem("calloutNote", `> [!NOTE]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">✏️</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-note)">Note</span>`, "true")}+ ${getSlashItem("calloutTip", `> [!TIP]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">💡</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-tip)">Tip</span>`, "true")}+ ${getSlashItem("calloutImportant", `> [!IMPORTANT]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">❗</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-important)">Important</span>`, "true")}+ ${getSlashItem("calloutWarning", `> [!WARNING]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">⚠️</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-warning)">Warning</span>`, "true")}+ ${getSlashItem("calloutCaution", `> [!CAUTION]\n> ${Lute.Caret}`, '<span class="keyboard__slash-icon">🚨</span>', `${window.siyuan.languages.callout} - <span style="color: var(--b3-callout-caution)">Caution</span>`, "true")}+ ${getSlashItem("code", "```", "iconCode", window.siyuan.languages.code, "true")}+ ${getSlashItem("table", `| ${Lute.Caret} | | |\n| --- | --- | --- |\n| | | |\n| | | |`, "iconTable", window.siyuan.languages.table, "true")}+ ${getSlashItem("line", "---", "iconLine", window.siyuan.languages.line, "true")}+ ${getSlashItem("math", "$$", "iconMath", window.siyuan.languages.math)}+ ${getSlashItem("html", "<div>", "iconHTML5", "HTML")}</div><div class="keyboard__slash-title"></div><div class="keyboard__slash-block">- ${getSlashItem("```abc\n```", "", window.siyuan.languages.staff, "true")}- ${getSlashItem("```echarts\n```", "", window.siyuan.languages.chart, "true")}- ${getSlashItem("```flowchart\n```", "", "Flow Chart", "true")}- ${getSlashItem("```graphviz\n```", "", "Graph", "true")}- ${getSlashItem("```mermaid\n```", "", "Mermaid", "true")}- ${getSlashItem("```plantuml\n```", "", "UML", "true")}+ ${getSlashItem("staff", "```abc\n```", "", window.siyuan.languages.staff, "true")}+ ${getSlashItem("chart", "```echarts\n```", "", window.siyuan.languages.chart, "true")}+ ${getSlashItem("flowChart", "```flowchart\n```", "", "Flow Chart", "true")}+ ${getSlashItem("graph", "```graphviz\n```", "", "Graph", "true")}+ ${getSlashItem("mermaid", "```mermaid\n```", "", "Mermaid", "true")}+ ${getSlashItem("UML", "```plantuml\n```", "", "UML", "true")}</div><div class="keyboard__slash-title"></div><div class="keyboard__slash-block">${builtinStyleHTML}- ${getSlashItem(`style${Constants.ZWSP}`, '<div class="keyboard__slash-icon">A</div>', window.siyuan.languages.clearFontStyle, "true")}+ ${getSlashItem("clearFontStyle", `style${Constants.ZWSP}`, '<div class="keyboard__slash-icon">A</div>', window.siyuan.languages.clearFontStyle, "true")}</div>${pluginHTML}`;+ const eligibleItems = hintSlash("", protyle, false, {visibilityRoot: SLASH_MENU_ROOT_PATH});+ const buttons = getFrequentSlashButtons(utilElement, eligibleItems+ .filter(item => item.html !== "separator").map(item => item.entryKey));+ prependFrequentSlashButtons(utilElement, getFrequentSlashItems(buttons, button => button.dataset.slashEntryKey));protyle.hint.bindUploadEvent(protyle, utilElement);};@@ -1675,7 +1682,7 @@ export const initKeyboardToolbar = () => {}hideKeyboardToolbarUtil();}- protyle.hint.fillCommand(dataValue, protyle, false); // 点击后 range 会改变+ protyle.hint.fillCommand(dataValue, protyle, false, slashBtnElement.dataset.slashEntryKey); // 点击后 range 会改变event.preventDefault();event.stopPropagation();if (dataValue === "((" || dataValue === "{{") {diff --git a/app/src/mobile/util/liteSlashMenu.test.ts b/app/src/mobile/util/liteSlashMenu.test.tsindex b95f4f2973..0642ee7da7 100644--- a/app/src/mobile/util/liteSlashMenu.test.ts+++ b/app/src/mobile/util/liteSlashMenu.test.ts@@ -9,8 +9,9 @@ import {createSourceFile, isClassDeclaration, isMethodDeclaration, ScriptTarget,const browserCases = async (source: string, hintSource: string) => {const check: typeof assert = require("node:assert/strict");- const {mount, render, paddingElement} = new Function(source + hintSource +- "\nreturn {mount: mountLiteSlashMenu, render: Hint.prototype.getHTMLByData, paddingElement: getMobileToolbarPaddingElement};")() as {+ const {mount, render, paddingElement} = new Function("getFrequentSlashItems", "getSlashEntryKey", "escapeAttr", source + hintSource ++ "\nreturn {mount: mountLiteSlashMenu, render: Hint.prototype.getHTMLByData, paddingElement: getMobileToolbarPaddingElement};")(+ (): IHintData[] => [], (item: {entryKey?: string}) => item.entryKey || "", (value: string) => value) as {mount: typeof import("./liteSlashMenu").mountLiteSlashMenu,render: (data: IHintData[]) => string,paddingElement: typeof import("../../protyle/lite/mobileToolbar").getMobileToolbarPaddingElement,@@ -161,7 +162,8 @@ test("mobile slash panel retains synchronous and asynchronous candidates and rel}, async () => {const source = transpileModule((readFileSync(path.join(__dirname, "liteSlashMenu.ts"), "utf8") + "\n" +readFileSync(path.join(__dirname, "../../protyle/lite/mobileToolbar.ts"), "utf8"))- .replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;+ .replace(/^import type .*;\n/gm, "").replace(/^export /gm, ""),+ {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;const hintFile = createSourceFile("hint.ts", readFileSync(path.join(__dirname, "../../protyle/hint/index.ts"), "utf8"),ScriptTarget.Latest, true);const hintClass = hintFile.statements.find(isClassDeclaration);diff --git a/app/src/mobile/util/liteSlashMenu.ts b/app/src/mobile/util/liteSlashMenu.tsindex 3f04f3a826..840bdc97f3 100644--- a/app/src/mobile/util/liteSlashMenu.ts+++ b/app/src/mobile/util/liteSlashMenu.ts@@ -1,23 +1,61 @@+import type {TSlashMenuItem} from "../../protyle/hint/slashMenu";++export const getFrequentSlashButtons = (container: HTMLElement, entryKeys: string[]) => {+ const buttons = Array.from(container.querySelectorAll<HTMLButtonElement>("button[data-slash-entry-key]"));+ return entryKeys.map(entryKey => {+ const matches = buttons.filter(button => button.dataset.slashEntryKey === entryKey);+ // 安卓图片和拍照入口共用附件命令,常用区保留完整文件选择入口。+ return matches.find(button => !button.querySelector('input[capture], input[accept*="x-siyuan-image-picker"]')) || matches[0];+ }).filter((button, index, items) => button && items.indexOf(button) === index);+};++export const prependFrequentSlashButtons = (container: HTMLElement, buttons: HTMLButtonElement[]) => {+ if (buttons.length === 0) {+ return;+ }+ const group = document.createElement("div");+ group.className = "keyboard__slash-block";+ buttons.forEach(button => group.appendChild(button.cloneNode(true)));+ const separator = document.createElement("div");+ separator.className = "b3-menu__separator";+ separator.setAttribute("role", "separator");+ container.prepend(group, separator);+};+export const getLiteSlashMenuHTML = (items: IHintData[]) => {const menu = document.createElement("div");+ const hasFrequentItems = items.some(item => (item as TSlashMenuItem).entryKey === "__frequent_separator__");let group: HTMLElement;items.forEach(item => {+ const entryKey = (item as TSlashMenuItem).entryKey;if (item.html === "separator") {+ if (entryKey === "__frequent_separator__") {+ const separator = document.createElement("div");+ separator.className = "b3-menu__separator";+ separator.setAttribute("role", "separator");+ menu.appendChild(separator);+ }group = undefined;return;}if (!group) {- const space = document.createElement("div");- space.className = "keyboard__slash-title";+ if (menu.childElementCount > 0 || !hasFrequentItems) {+ const space = document.createElement("div");+ space.className = "keyboard__slash-title";+ menu.appendChild(space);+ }group = document.createElement("div");group.className = "keyboard__slash-block";- menu.append(space, group);+ menu.appendChild(group);}const button = document.createElement("button");button.className = "keyboard__slash-item";button.dataset.id = item.id || "";button.dataset.value = encodeURIComponent(item.value);button.dataset.focus = item.focus === false ? "false" : "true";+ if (typeof entryKey === "string" && entryKey) {+ button.dataset.slashEntryKey = entryKey;+ }const content = document.createElement("div");content.innerHTML = item.html;if (content.querySelector('[data-type="agent-skill"]')) {diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.tsindex 01edc7d431..a629aaaa24 100644--- a/app/src/protyle/hint/extend.ts+++ b/app/src/protyle/hint/extend.ts@@ -452,9 +452,12 @@ export const getBuiltinSlashMenuItems = (protyle: IProtyle): IHintData[] => {}];};-export const hintSlash = registerBuiltinSlashHint((key: string, protyle: IProtyle, sourceOrHideConfiguredCreate: THintSource | boolean = false) => {+export const hintSlash = registerBuiltinSlashHint((key: string, protyle: IProtyle,+ sourceOrHideConfiguredCreate: THintSource | boolean = false,+ options: {visibilityRoot?: string} = {}) => {// 加号面板由用户主动打开,复用插入项配置但不受输入斜杠的提示开关影响。- const visibilityRoot = protyle.hint.element.closest("#keyboardToolbar") ? SLASH_MENU_ROOT_PATH : undefined;+ const visibilityRoot = options.visibilityRoot ||+ (protyle.hint.element.closest("#keyboardToolbar") ? SLASH_MENU_ROOT_PATH : undefined);const enabled = getConfiguredEntryVisibility(SLASH_MENU_ROOT_PATH, visibilityRoot);if (!enabled) {return [];@@ -464,6 +467,7 @@ export const hintSlash = registerBuiltinSlashHint((key: string, protyle: IProtylconst allList = builtinList.map<TSlashMenuItem>((item) => ({...item,entryKey: item.id || "",+ frequentEligible: key === "",}));let hasPlugin = false;if (areProtylePluginExtensionsEnabled(protyle)) {@@ -475,6 +479,7 @@ export const hintSlash = registerBuiltinSlashHint((key: string, protyle: IProtylid: slash.id,entryKey: getPluginSlashEntryKey(plugin.name, slash.id,slash.html === "separator" ? "separator" : "entry"),+ frequentEligible: key === "",value: `plugin${Constants.ZWSP}${plugin.name}${Constants.ZWSP}${slash.id}`,html: slash.html});diff --git a/app/src/protyle/hint/frequentSlash.test.ts b/app/src/protyle/hint/frequentSlash.test.tsnew file mode 100644index 0000000000..814b108fd1--- /dev/null+++ b/app/src/protyle/hint/frequentSlash.test.ts@@ -0,0 +1,70 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {normalizeSlashUsage, rankFrequentSlashItems} from "./frequentSlash";++const item = (key: string, value = key) => ({key, value});+const getKey = (entry: ReturnType<typeof item>) => entry.key;++test("frequent slash starts empty and never adds unrecorded or unavailable entries", () => {+ const entries = [item("heading1"), item("code")];+ assert.deepEqual(rankFrequentSlashItems(entries, getKey, {}), []);+ assert.deepEqual(rankFrequentSlashItems(entries, getKey, {unavailable: 100}), []);+ assert.deepEqual(rankFrequentSlashItems([], getKey, {code: 4}), []);+});++test("frequent slash returns at most five items by count and keeps original order on ties", () => {+ const entries = ["a", "b", "c", "d", "e", "f", "g"].map(key => item(key));+ const original = structuredClone(entries);+ const usage = {a: 2, b: 5, c: 5, d: 3, e: 1, f: 4, g: 2};+ const ranked = rankFrequentSlashItems(entries, getKey, usage);+ assert.deepEqual(ranked.map(getKey), ["b", "c", "f", "d", "a"]);+ assert.equal(ranked[0], entries[1]);+ assert.deepEqual(entries, original);+ assert.deepEqual(usage, {a: 2, b: 5, c: 5, d: 3, e: 1, f: 4, g: 2});+});++test("frequent slash uses first identity occurrence and does not deduplicate command values", () => {+ const entries = [item("code", "same"), item("code", "duplicate"), item("plugin:first:code", "same"),+ item("plugin:second:code", "same"), item("", "separator")];+ const ranked = rankFrequentSlashItems(entries, getKey, {+ code: 2, "plugin:first:code": 3, "plugin:second:code": 4, "": 100,+ });+ assert.deepEqual(ranked, [entries[3], entries[2], entries[0]]);+ assert.equal(entries.length, 5);+});++test("frequent slash ignores inherited counts but safely accepts own prototype-like keys", () => {+ const entries = [item("code"), item("toString"), item("constructor"), item("__proto__")];+ assert.deepEqual(rankFrequentSlashItems(entries, getKey, Object.create({code: 5, toString: 8})), []);+ const usage = normalizeSlashUsage(JSON.parse('{"__proto__":7,"constructor":4,"toString":2}'));+ assert.equal(Object.getPrototypeOf(usage), Object.prototype);+ assert.deepEqual(rankFrequentSlashItems(entries, getKey, usage).map(getKey),+ ["__proto__", "constructor", "toString"]);+ assert.equal(Object.prototype.hasOwnProperty.call({}, "code"), false);+});++test("slash usage normalization discards malformed roots and counts without mutating input", () => {+ for (const value of [undefined, null, false, 4, "{}", [], [1, 2]]) {+ assert.deepEqual(normalizeSlashUsage(value), {});+ }+ const source = {+ valid: 3, zero: 0, negative: -2, fraction: 1.5, infinite: Infinity, nan: NaN,+ string: "5", boolean: true, object: {count: 2}, tooLarge: Number.MAX_SAFE_INTEGER + 1,+ max: Number.MAX_SAFE_INTEGER, "": 3, ["a".repeat(1024)]: 1, ["b".repeat(1025)]: 1,+ "plugin:uninstalled:insert": 9,+ };+ const normalized = normalizeSlashUsage(source);+ assert.deepEqual(normalized, {+ valid: 3, max: Number.MAX_SAFE_INTEGER, ["a".repeat(1024)]: 1, "plugin:uninstalled:insert": 9,+ });+ assert.equal(source.string, "5");+ normalized.valid++;+ assert.equal(source.valid, 3);+});++test("slash usage normalization copies only own enumerable entries", () => {+ const source = Object.create({inherited: 9});+ source.code = 2;+ Object.defineProperty(source, "hidden", {value: 8});+ assert.deepEqual(normalizeSlashUsage(source), {code: 2});+});diff --git a/app/src/protyle/hint/frequentSlash.ts b/app/src/protyle/hint/frequentSlash.tsnew file mode 100644index 0000000000..7f4fb6622b--- /dev/null+++ b/app/src/protyle/hint/frequentSlash.ts@@ -0,0 +1,21 @@+export type TSlashUsage = Record<string, number>;++// 仅保存稳定入口标识与次数,不保存正文、搜索词或插件显示内容。+export const normalizeSlashUsage = (value: unknown): TSlashUsage => {+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ return {};+ }+ return Object.fromEntries(Object.entries(value).filter(([key, count]) =>+ key.length > 0 && key.length <= 1024 && Number.isSafeInteger(count) && (count as number) > 0));+};++export const rankFrequentSlashItems = <T>(items: T[], getKey: (item: T) => string, usage: TSlashUsage): T[] => {+ const seen = new Set<string>();+ return items.map((item, index) => ({item, index, key: getKey(item)})).filter(({key}) => {+ if (!key || seen.has(key) || !Object.prototype.hasOwnProperty.call(usage, key) || !(usage[key] > 0)) {+ return false;+ }+ seen.add(key);+ return true;+ }).sort((a, b) => usage[b.key] - usage[a.key] || a.index - b.index).slice(0, 5).map(({item}) => item);+};diff --git a/app/src/protyle/hint/frequentSlashExecution.test.ts b/app/src/protyle/hint/frequentSlashExecution.test.tsnew file mode 100644index 0000000000..74a06ea2d2--- /dev/null+++ b/app/src/protyle/hint/frequentSlashExecution.test.ts@@ -0,0 +1,93 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, isClassDeclaration, ScriptTarget, transpileModule} from "typescript";+import {getSlashEntryKey, TSlashMenuItem} from "./slashMenu";+import {rankFrequentSlashItems} from "./frequentSlash";+import {escapeAttr} from "../../util/escape";++const text = readFileSync("src/protyle/hint/index.ts", "utf8");+const source = createSourceFile("index.ts", text, ScriptTarget.Latest);+const declaration = source.statements.find(node => isClassDeclaration(node) && node.name.text === "Hint");+assert.ok(declaration && isClassDeclaration(declaration));+const methods = declaration.members.filter(member => ["fillCommand", "fill", "getHTMLByData"].includes(member.name?.getText(source)))+ .map(member => member.getText(source)).join("\n");+const code = transpileModule(`class Hint { ${methods} } new Hint();`, {+ compilerOptions: {target: ScriptTarget.ES2020},+}).outputText;++const fixture = () => {+ const counts: string[] = [];+ let available = true;+ const block = {outerHTML: "paragraph", getAttribute: () => "NodeParagraph", setAttribute() {}};+ const range = {startContainer: block, deleteContents() {}};+ const hint = runInNewContext(code, {+ Constants: {ZWSP: "\u200b", BLOCK_HINT_KEYS: [], INLINE_TYPE: []},+ Lute: {Caret: "caret"}, hideElements() {}, isProtyleListItemFragment: () => false,+ hasClosestBlock: () => available ? block : undefined,+ getEditorRange: () => range, shouldCaptureHintUndoFocus: () => false,+ updateTransaction() {}, recordSlashExecution: (key: string) => counts.push(key),+ getSlashEntryKey, escapeAttr,+ getFrequentSlashItems: (items: TSlashMenuItem[]) => rankFrequentSlashItems(items, getSlashEntryKey,+ {code: 4, table: 2, "plugin:one:same": 3, "plugin:two:same": 1}),+ });+ Object.assign(hint, {source: "hint", splitChar: "/", lastIndex: -1, fixImageCursor() {},+ element: {closest: () => undefined}});+ const protyle = {toolbar: {range}, wysiwyg: {element: {}}};+ return {hint, protyle, counts, unavailable: () => { available = false; }};+};++test("explicit slash selections count once, while ordinary commands and upload-picker opening do not", () => {+ const {hint, protyle, counts} = fixture();+ hint.fill("style\u200b", protyle, false, false, "clearFontStyle");+ assert.deepEqual(counts, ["clearFontStyle"]);+ hint.fillCommand("style\u200b", protyle, false, "clearFontStyle");+ assert.deepEqual(counts, ["clearFontStyle", "clearFontStyle"]);+ hint.fillCommand("style\u200b", protyle, false);+ hint.fill("\u200b3", protyle, false, false, "insertAsset");+ assert.equal(counts.length, 2);+});++test("invalid insertion target cannot record a slash selection", () => {+ const f = fixture();+ f.unavailable();+ f.hint.fillCommand("style\u200b", f.protyle, false, "clearFontStyle");+ assert.deepEqual(f.counts, []);+});++test("rendering preserves original rows, selects favorites after context filtering, and never records", () => {+ const {hint, counts} = fixture();+ const items = ["table", "plugin:one:same", "plugin:two:same"].map(entryKey => ({+ id: entryKey.startsWith("plugin:") ? "same" : entryKey,+ entryKey, value: entryKey, html: entryKey, frequentEligible: true,+ }));+ const html: string = hint.getHTMLByData(items);+ assert.equal((html.match(/data-slash-entry-key=/g) || []).length, 6);+ assert.equal((html.match(/b3-menu__separator/g) || []).length, 1);+ assert.ok(html.indexOf('data-value="plugin%3Aone%3Asame"') < html.indexOf('data-value="table"'));+ assert.ok(!html.includes('data-value="code"'));+ const original = html.slice(html.indexOf('class="b3-menu__separator"'));+ assert.ok(original.indexOf('data-value="table"') < original.indexOf('data-value="plugin%3Aone%3Asame"'));+ assert.deepEqual(counts, []);+});++test("query results retain their order without duplicates or divider and keep execution identities", () => {+ const {hint} = fixture();+ const items = ["table", "code"].map(entryKey => ({id: entryKey, entryKey, value: entryKey,+ html: entryKey, frequentEligible: false}));+ const html: string = hint.getHTMLByData(items);+ assert.equal((html.match(/data-slash-entry-key=/g) || []).length, 2);+ assert.ok(!html.includes("b3-menu__separator"));+ assert.ok(html.indexOf('data-value="table"') < html.indexOf('data-value="code"'));+});++test("click and keyboard execution paths forward stable keys and divider buttons cannot execute", () => {+ assert.match(text, /btnElement && btnElement\.hasAttribute\("data-value"\)/);+ assert.match(text, /isOnlyMeta\(event\), btnElement\.dataset\.slashEntryKey/);+ assert.match(text, /this\.fill\(mark,[\s\S]*?dataset\.slashEntryKey/);+ const upload = text.slice(text.indexOf('item.addEventListener("change"'), text.indexOf("private getHTMLByData"));+ assert.ok(upload.indexOf("event.target.files.length === 0") < upload.indexOf("recordSlashExecution"));+ assert.ok(upload.indexOf("if (!range)") < upload.indexOf("recordSlashExecution"));+ assert.equal((upload.match(/recordSlashExecution/g) || []).length, 1);+});diff --git a/app/src/protyle/hint/frequentSlashStorage.test.ts b/app/src/protyle/hint/frequentSlashStorage.test.tsnew file mode 100644index 0000000000..297353a695--- /dev/null+++ b/app/src/protyle/hint/frequentSlashStorage.test.ts@@ -0,0 +1,260 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {join} from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import * as frequentSlash from "./frequentSlash";++const constants = {LOCAL_SLASH_FREQUENT_ENABLED: "enabled", LOCAL_SLASH_USAGE: "usage"};+const compiled = transpileModule(readFileSync(join(__dirname, "frequentSlashStorage.ts"), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++type TWrite = {key: string; value: unknown};++const fixture = (values: Record<string, unknown> = {},+ persist: (write: TWrite) => Promise<unknown> = () => Promise.resolve()) => {+ const writes: TWrite[] = [];+ const storage: Record<string, unknown> = structuredClone(values);+ const siyuan = {storage, config: {readonly: false}, isPublish: false};+ const exports = {} as typeof import("./frequentSlashStorage");+ const settings = {} as typeof import("../../config/setting/pending");+ runInNewContext(transpileModule(readFileSync(join(__dirname, "../../config/setting/pending.ts"), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText, {exports: settings});+ runInNewContext(compiled, {+ exports,+ window: {siyuan},+ console: {warn() {}, error() {}},+ require: (id: string) => {+ if (id === "../../constants") return {Constants: constants};+ if (id === "./frequentSlash") return frequentSlash;+ if (id === "../../config/setting/pending") return settings;+ assert.equal(id, "../util/compatibility");+ return {setStorageVal: (key: string, value: unknown) => {+ const write = {key, value: structuredClone(value)};+ writes.push(write);+ return persist(write);+ }};+ },+ });+ return {...exports, storage, writes, siyuan, settings};+};++const settle = () => new Promise<void>(resolve => setImmediate(resolve));+const entries = [{key: "code"}, {key: "heading1"}];+const getKey = (entry: {key: string}) => entry.key;++test("frequent slash defaults on and honors only an explicit false preference", () => {+ for (const enabled of [undefined, null, true, "false", 0, {}, []]) {+ assert.equal(fixture({enabled}).isFrequentSlashEnabled(), true);+ }+ assert.equal(fixture({enabled: false}).isFrequentSlashEnabled(), false);+});++test("disabled frequent slash preserves history and stops all execution writes", async () => {+ const f = fixture({usage: {code: 4, "plugin:uninstalled:item": 2}});+ f.setFrequentSlashEnabled(false);+ assert.equal(f.isFrequentSlashEnabled(), false);+ assert.equal(f.getFrequentSlashItems(entries, getKey).length, 0);+ f.recordSlashExecution("code");+ f.recordSlashExecution("heading1");+ await settle();+ assert.deepEqual(f.storage.usage, {code: 4, "plugin:uninstalled:item": 2});+ assert.deepEqual(f.writes, [{key: "enabled", value: false}]);+ f.setFrequentSlashEnabled(true);+ assert.deepEqual(f.getFrequentSlashItems(entries, getKey), [entries[0]]);+ f.recordSlashExecution("heading1");+ await settle();+ assert.deepEqual(f.storage.usage, {code: 4, "plugin:uninstalled:item": 2, heading1: 1});+ assert.equal(f.writes.filter(write => write.key === "usage").length, 1);+});++test("usage records stable plugin identities independently and normalizes damaged storage", async () => {+ const f = fixture({usage: {code: "wrong", zero: 0, "plugin:uninstalled:item": 3}});+ for (const key of ["code", "plugin:first:code", "plugin:second:code", "code"]) {+ f.recordSlashExecution(key);+ }+ await settle();+ assert.deepEqual(f.storage.usage, {+ "plugin:uninstalled:item": 3, code: 2, "plugin:first:code": 1, "plugin:second:code": 1,+ });+ assert.equal(f.storage.enabled, undefined);+ assert.ok(f.writes.every(write => write.key === "usage"));+});++test("usage rejects empty or oversized identities and saturates at the safe integer limit", async () => {+ const f = fixture({usage: {code: Number.MAX_SAFE_INTEGER}});+ f.recordSlashExecution("");+ f.recordSlashExecution("x".repeat(1025));+ await settle();+ assert.equal(f.writes.length, 0);+ f.recordSlashExecution("code");+ f.recordSlashExecution("x".repeat(1024));+ await settle();+ assert.deepEqual(f.storage.usage, {code: Number.MAX_SAFE_INTEGER, ["x".repeat(1024)]: 1});+});++test("usage safely records prototype-like own keys without changing object prototypes", async () => {+ const f = fixture();+ for (const key of ["__proto__", "constructor", "toString", "__proto__"]) {+ f.recordSlashExecution(key);+ }+ await settle();+ const usage = f.storage.usage as Record<string, number>;+ assert.equal(Object.getPrototypeOf(usage), Object.prototype);+ assert.equal(usage.__proto__, 2);+ assert.equal(usage.constructor, 1);+ assert.equal(usage.toString, 1);+ assert.deepEqual(Object.keys(usage), ["__proto__", "constructor", "toString"]);+ assert.equal(Object.prototype.hasOwnProperty.call({}, "usage"), false);+});++test("readonly, published, and missing storage contexts do not mutate or persist preferences", async () => {+ for (const mode of ["readonly", "publish", "missing"]) {+ const f = fixture({usage: {code: 3}});+ if (mode === "readonly") f.siyuan.config.readonly = true;+ if (mode === "publish") f.siyuan.isPublish = true;+ if (mode === "missing") f.siyuan.storage = undefined;+ f.setFrequentSlashEnabled(false);+ f.recordSlashExecution("code");+ await settle();+ assert.deepEqual(f.storage, {usage: {code: 3}});+ assert.equal(f.writes.length, 0);+ assert.equal(f.isFrequentSlashEnabled(), true);+ }+});++test("ranking and counting read storage updates from other windows without cached preferences", async () => {+ const f = fixture({enabled: false, usage: {code: 1}});+ f.storage.enabled = true;+ f.storage.usage = {heading1: 6};+ assert.deepEqual(f.getFrequentSlashItems(entries, getKey), [entries[1]]);+ f.recordSlashExecution("heading1");+ assert.deepEqual(f.storage.usage, {heading1: 7});+ f.storage.enabled = false;+ f.recordSlashExecution("code");+ await settle();+ assert.deepEqual(f.storage.usage, {heading1: 7});+ assert.equal(f.getFrequentSlashItems(entries, getKey).length, 0);+});++test("usage persistence serializes and coalesces snapshots so old writes cannot replace newer counts", async () => {+ const release: Array<() => void> = [];+ const f = fixture({}, () => new Promise<void>(resolve => release.push(resolve)));+ f.recordSlashExecution("code");+ f.recordSlashExecution("code");+ f.recordSlashExecution("heading1");+ await settle();+ assert.deepEqual(f.storage.usage, {code: 2, heading1: 1});+ assert.equal(f.writes.length, 1);+ assert.deepEqual(f.writes[0].value, {code: 1});+ release.shift()();+ await settle();+ assert.equal(f.writes.length, 2);+ assert.deepEqual(f.writes[1].value, {code: 2, heading1: 1});+ release.shift()();+ await settle();+ assert.equal(f.writes.length, 2);+});++test("disabling while usage is saving preserves both pending counts and the separate preference", async () => {+ const release: Array<() => void> = [];+ const f = fixture({}, () => new Promise<void>(resolve => release.push(resolve)));+ f.recordSlashExecution("code");+ f.recordSlashExecution("code");+ f.setFrequentSlashEnabled(false);+ f.recordSlashExecution("heading1");+ assert.equal(f.storage.enabled, false);+ assert.deepEqual(f.storage.usage, {code: 2});+ for (let index = 0; index < 3; index++) {+ await settle();+ assert.equal(f.writes.length, index + 1);+ release.shift()();+ }+ await settle();+ assert.deepEqual(f.writes, [+ {key: "usage", value: {code: 1}},+ {key: "usage", value: {code: 2}},+ {key: "enabled", value: false},+ ]);+});++test("failed persistence does not poison the queue or discard newer in-memory counts", async () => {+ let fail = true;+ const persisted: TWrite[] = [];+ const f = fixture({}, write => {+ if (fail) {+ fail = false;+ return Promise.reject(new Error("storage unavailable"));+ }+ persisted.push(write);+ return Promise.resolve();+ });+ f.recordSlashExecution("code");+ await settle();+ assert.deepEqual(f.storage.usage, {code: 1});+ f.recordSlashExecution("code");+ await settle();+ assert.deepEqual(persisted, [{key: "usage", value: {code: 2}}]);+ assert.deepEqual(f.storage.usage, {code: 2});+});++test("settings close waits for the complete queued preference drain", async () => {+ const release: Array<() => void> = [];+ const f = fixture({}, () => new Promise<void>(resolve => release.push(resolve)));+ f.setFrequentSlashEnabled(false);+ f.setFrequentSlashEnabled(true);+ let flushed = false;+ const flush = f.settings.flushSettingSaves().then(() => { flushed = true; });+ await settle();+ assert.equal(f.writes.length, 1);+ assert.equal(flushed, false);+ release.shift()();+ await settle();+ assert.equal(f.writes.length, 2);+ assert.equal(flushed, false);+ release.shift()();+ await flush;+ assert.equal(flushed, true);+ assert.deepEqual(f.writes, [{key: "enabled", value: false}, {key: "enabled", value: true}]);+});++test("a rejected storage operation does not poison the drain or make settings flush reject", async () => {+ let reject: (error: Error) => void;+ let release: () => void;+ let first = true;+ const f = fixture({}, () => {+ if (first) {+ first = false;+ return new Promise<void>((_resolve, rejectPromise) => { reject = rejectPromise; });+ }+ return new Promise<void>(resolve => { release = resolve; });+ });+ f.recordSlashExecution("code");+ f.recordSlashExecution("code");+ let flushed = false;+ const flush = f.settings.flushSettingSaves().then(() => { flushed = true; });+ reject(new Error("storage failed"));+ await settle();+ assert.equal(f.writes.length, 2);+ assert.equal(flushed, false);+ release();+ await flush;+ assert.deepEqual(f.writes[1], {key: "usage", value: {code: 2}});+ assert.equal(f.settings.settingSaveFailures(), 0);+});++test("the drain preserves failures already tracked by the storage request", async () => {+ let reject: (error: Error) => void;+ const f = fixture({}, () => f.settings.trackSettingSave(new Promise<void>((_resolve, rejectPromise) => {+ reject = rejectPromise;+ })));+ f.setFrequentSlashEnabled(false);+ const flush = f.settings.flushSettingSaves();+ reject(new Error("request failed"));+ await assert.rejects(flush, /request failed/);+ assert.equal(f.settings.settingSaveFailures(), 1);+ await assert.doesNotReject(f.settings.flushSettingSaves());+});diff --git a/app/src/protyle/hint/frequentSlashStorage.ts b/app/src/protyle/hint/frequentSlashStorage.tsnew file mode 100644index 0000000000..2e0109d8d8--- /dev/null+++ b/app/src/protyle/hint/frequentSlashStorage.ts@@ -0,0 +1,59 @@+import {Constants} from "../../constants";+import {trackSettingSave} from "../../config/setting/pending";+import {setStorageVal} from "../util/compatibility";+import {normalizeSlashUsage, rankFrequentSlashItems} from "./frequentSlash";++export const isFrequentSlashEnabled = () => window.siyuan.storage?.[Constants.LOCAL_SLASH_FREQUENT_ENABLED] !== false;++const writable = () => window.siyuan.storage && !window.siyuan.config.readonly && !window.siyuan.isPublish;++const pending = new Map<string, unknown>();+let saving = false;++// 同一窗口的快速操作合并并按顺序保存,避免较早的请求覆盖新次数。+const persist = (key: string, value: unknown) => {+ pending.set(key, value);+ if (saving) {+ return;+ }+ saving = true;+ void trackSettingSave((async () => {+ try {+ while (pending.size > 0) {+ const [nextKey, nextValue] = pending.entries().next().value as [string, unknown];+ pending.delete(nextKey);+ try {+ await setStorageVal(nextKey, nextValue);+ } catch (_error) {+ // 保留内存状态,下一次操作继续保存;统计失败不阻止编辑。+ }+ }+ } finally {+ saving = false;+ }+ })());+};++export const setFrequentSlashEnabled = (enabled: boolean) => {+ if (!writable()) {+ return;+ }+ window.siyuan.storage[Constants.LOCAL_SLASH_FREQUENT_ENABLED] = enabled;+ void persist(Constants.LOCAL_SLASH_FREQUENT_ENABLED, enabled);+};++export const getFrequentSlashItems = <T>(items: T[], getKey: (item: T) => string): T[] =>+ isFrequentSlashEnabled() ? rankFrequentSlashItems(items, getKey,+ normalizeSlashUsage(window.siyuan.storage?.[Constants.LOCAL_SLASH_USAGE])) : [];++export const recordSlashExecution = (entryKey: string) => {+ if (!entryKey || entryKey.length > 1024 || !writable() || !isFrequentSlashEnabled()) {+ return;+ }+ const usage = normalizeSlashUsage(window.siyuan.storage[Constants.LOCAL_SLASH_USAGE]);+ const count = Object.prototype.hasOwnProperty.call(usage, entryKey) ? usage[entryKey] : 0;+ Object.defineProperty(usage, entryKey, {value: Math.min(count + 1, Number.MAX_SAFE_INTEGER),+ enumerable: true, configurable: true, writable: true});+ window.siyuan.storage[Constants.LOCAL_SLASH_USAGE] = usage;+ void persist(Constants.LOCAL_SLASH_USAGE, usage);+};diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex c78e58bcf8..d941341a04 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -19,6 +19,9 @@ import {} from "../util/selection";import {focusByRange, getSelectionOffset} from "../util/selectionOffsets";import {genHintItemHTML, hintEmbed, hintRef, hintSlash, hintTag} from "./extend";+import {getSlashEntryKey, TSlashMenuItem} from "./slashMenu";+import {getFrequentSlashItems, recordSlashExecution} from "./frequentSlashStorage";+import {escapeAttr} from "../../util/escape";import {createDailyNoteReference} from "./dailyNote";import {captureDailyNoteSelection, insertDailyNoteReference} from "./dailyNoteSelection";import {@@ -154,8 +157,9 @@ export class Hint {return;}const btnElement = hasClosestByTag(eventTarget, "BUTTON");- if (btnElement && !btnElement.classList.contains("emojis__item") && !btnElement.classList.contains("emojis__type")) {- this.fill(decodeURIComponent(btnElement.getAttribute("data-value")), protyle, false, this.source === "search" ? isNotCtrl(event) : isOnlyMeta(event));+ if (btnElement && btnElement.hasAttribute("data-value") && !btnElement.classList.contains("emojis__item") && !btnElement.classList.contains("emojis__type")) {+ this.fill(decodeURIComponent(btnElement.getAttribute("data-value")), protyle, false,+ this.source === "search" ? isNotCtrl(event) : isOnlyMeta(event), btnElement.dataset.slashEntryKey);event.preventDefault();event.stopPropagation(); // https://github.com/siyuan-note/siyuan/issues/3710return;@@ -552,6 +556,7 @@ export class Hint {}range.deleteContents();range.collapse(true);+ recordSlashExecution(item.closest<HTMLElement>("[data-slash-entry-key]")?.dataset.slashEntryKey);uploadFiles(protyle, event.target.files, event.target, undefined, undefined, {document: uploadDocument,htmlAsIframe: event.target.dataset.uploadMode === "html-iframe",@@ -566,6 +571,14 @@ export class Hint {}private getHTMLByData(data: IHintData[]) {+ if (this.source === "hint") {+ // 所有上下文过滤完成后再选常用项,保留原列表及搜索结果顺序。+ const frequent = getFrequentSlashItems(data.filter(item => item.html !== "separator" &&+ (item as TSlashMenuItem).frequentEligible === true), getSlashEntryKey);+ if (frequent.length > 0) {+ data = [...frequent, {html: "separator", entryKey: "__frequent_separator__"} as TSlashMenuItem, ...data];+ }+ }if (this.source === "hint" && this.element.closest("#keyboardToolbar")) {return getLiteSlashMenuHTML(data);}@@ -580,7 +593,8 @@ export class Hint {if (hintData.html === "separator") {hintsHTML += `<button data-id="${hintData.id || ""}" class="b3-menu__separator"></button>`;} else {- hintsHTML += `<button data-id="${hintData.id || ""}" style="width: calc(100% - 16px)" class="b3-list-item b3-list-item--two${focusClass}" data-value="${encodeURIComponent(hintData.value)}">${hintData.html}</button>`;+ const entryKey = getSlashEntryKey(hintData);+ hintsHTML += `<button data-id="${hintData.id || ""}"${entryKey ? ` data-slash-entry-key="${escapeAttr(entryKey)}"` : ""} style="width: calc(100% - 16px)" class="b3-list-item b3-list-item--two${focusClass}" data-value="${encodeURIComponent(hintData.value)}">${hintData.html}</button>`;}});return `${hintsHTML}</div>`;@@ -794,15 +808,15 @@ ${genHintItemHTML(item)}}// 直接插入命令使用正文选区,不沿用候选面板的来源和触发位置。- public fillCommand(value: string, protyle: IProtyle, updateRange = true) {+ public fillCommand(value: string, protyle: IProtyle, updateRange = true, slashEntryKey?: string) {this.source = "hint";this.splitChar = "/";this.lastIndex = -1;this.hashTagSearchElement = undefined;- this.fill(value, protyle, updateRange);+ this.fill(value, protyle, updateRange, false, slashEntryKey);}- public fill(value: string, protyle: IProtyle, updateRange = true, refIsS = false) {+ public fill(value: string, protyle: IProtyle, updateRange = true, refIsS = false, slashEntryKey?: string) {this.bindingDismissController?.abort();hideElements(["hint", "toolbar"], protyle);if (updateRange && this.source !== "av") {@@ -1039,6 +1053,9 @@ ${genHintItemHTML(item)}blockRender(protyle, protyle.wysiwyg.element);return;} else if (this.splitChar === "/" || this.splitChar === "、") {+ if (slashEntryKey && value !== Constants.ZWSP + 3) {+ recordSlashExecution(slashEntryKey);+ }// 精简模式的自定义候选按文本插入,内置候选执行命令;块引用保留本地事务和后续提示。if (protyle.lite && (Constants.BLOCK_HINT_KEYS.includes(value) ||!isBuiltinSlashHint(protyle.options.hint.extend.find((item) => item.key === "/" && item.hint)?.hint,@@ -1431,7 +1448,8 @@ ${genHintItemHTML(item)}if (mark === Constants.ZWSP + 3) {(this.element.querySelector(".b3-list-item--focus input") as HTMLElement).click();} else {- this.fill(mark, protyle, true, isOnlyMeta(event));+ this.fill(mark, protyle, true, isOnlyMeta(event),+ (this.element.querySelector(".b3-list-item--focus") as HTMLElement).dataset.slashEntryKey);}}event.preventDefault();diff --git a/app/src/protyle/hint/slashMenu.ts b/app/src/protyle/hint/slashMenu.tsindex 527c2f0945..e2e7b49261 100644--- a/app/src/protyle/hint/slashMenu.ts+++ b/app/src/protyle/hint/slashMenu.ts@@ -3,8 +3,12 @@ import {reorderEntrySlots} from "../../config/entryVisibility/order";export type TSlashMenuItem = IHintData & {entryKey: string;showInLite?: boolean;+ frequentEligible?: boolean;};+export const getSlashEntryKey = (item: IHintData): string =>+ "entryKey" in item && typeof item.entryKey === "string" ? item.entryKey : "";+interface IResolveSlashMenuOptions {enabled: boolean;hideConfiguredCreate: boolean;