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 multiple shortcut bindings and contextual resolution https://github.com/siyuan-note/siyuan/issues/19136
Vanessa3fe3a2b91f24
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 897ffd7e7f..ff3a229258 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,12 @@{+ "keymapUnset": "غير معيّن",+ "keymapPrimary": "تعيين كاختصار رئيسي",+ "keymapRecording": "اضغط اختصارًا...",+ "keymapShared": "اختصار مشترك",+ "keymapSharedTip": "تُعطى الأولوية للأوامر المحلية. في كل سياق تُجرَّب الأوامر بالترتيب المعروض؛ بعد بدء أمر لا يُنفَّذ أي أمر آخر",+ "keymapLegacyConflict": "يتعارض هذا الاختصار مع إجراء لا يدعم الاختصارات المشتركة بعد",+ "keymapSystemScope": "على مستوى النظام",+ "keymapSaveFailed": "تعذر حفظ الاختصارات","templateSearch": "البحث عن القوالب بالاسم أو المسار","templateContextSearch": "البحث عن مستندات السياق","templateContextTip": "تشغيل القالب باستخدام عنوان المستند المحدد ومعرّفه ومعلوماته الأخرى دون تعديل المستند",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 2acec5f15d..c8c71525ff 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Nicht festgelegt",+ "keymapPrimary": "Als primäres Tastenkürzel festlegen",+ "keymapRecording": "Tastenkürzel drücken...",+ "keymapShared": "Gemeinsames Tastenkürzel",+ "keymapSharedTip": "Lokale Befehle haben Vorrang. Pro Kontext werden Befehle in der angezeigten Reihenfolge geprüft; sobald ein Befehl startet, wird kein weiterer ausgeführt",+ "keymapLegacyConflict": "Dieses Tastenkürzel steht im Konflikt mit einer Aktion, die gemeinsame Belegungen noch nicht unterstützt",+ "keymapSystemScope": "Systemweit",+ "keymapSaveFailed": "Tastenkürzel konnten nicht gespeichert werden","templateSearch": "Vorlagen nach Name oder Pfad suchen","templateContextSearch": "Kontextdokumente suchen","templateContextTip": "Die Vorlage mit Titel, ID und weiteren Informationen des ausgewählten Dokuments ausführen, ohne dieses zu ändern",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 92039873ca..fe45c648df 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Not set",+ "keymapPrimary": "Set as primary shortcut",+ "keymapRecording": "Press shortcut...",+ "keymapShared": "Shared shortcut",+ "keymapSharedTip": "Local commands take priority. Within each context, commands are tried in the displayed order; once a command starts, no other command runs",+ "keymapLegacyConflict": "This shortcut conflicts with an action that does not support shared bindings yet",+ "keymapSystemScope": "System-wide",+ "keymapSaveFailed": "Unable to save shortcuts","templateSearch": "Search templates by name or path","templateContextSearch": "Search context documents","templateContextTip": "Run the template using the selected document's title, ID, and other information without modifying that document",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex a5a7ba1081..41c2c30282 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Sin asignar",+ "keymapPrimary": "Establecer como atajo principal",+ "keymapRecording": "Pulsa un atajo...",+ "keymapShared": "Atajo compartido",+ "keymapSharedTip": "Los comandos locales tienen prioridad. En cada contexto se prueban en el orden mostrado; una vez iniciado un comando, no se ejecuta ningún otro",+ "keymapLegacyConflict": "Este atajo entra en conflicto con una acción que aún no admite asignaciones compartidas",+ "keymapSystemScope": "En todo el sistema",+ "keymapSaveFailed": "No se pudieron guardar los atajos","templateSearch": "Buscar plantillas por nombre o ruta","templateContextSearch": "Buscar documentos de contexto","templateContextTip": "Ejecutar la plantilla con el título, el ID y otros datos del documento seleccionado sin modificarlo",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 4523fc0fb1..c93038e032 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Non défini",+ "keymapPrimary": "Définir comme raccourci principal",+ "keymapRecording": "Appuyez sur un raccourci...",+ "keymapShared": "Raccourci partagé",+ "keymapSharedTip": "Les commandes locales sont prioritaires. Dans chaque contexte, les commandes sont examinées dans l’ordre affiché ; dès qu’une commande démarre, aucune autre n’est exécutée",+ "keymapLegacyConflict": "Ce raccourci entre en conflit avec une action qui ne prend pas encore en charge les raccourcis partagés",+ "keymapSystemScope": "À l’échelle du système",+ "keymapSaveFailed": "Impossible d’enregistrer les raccourcis","templateSearch": "Rechercher des modèles par nom ou chemin","templateContextSearch": "Rechercher des documents de contexte","templateContextTip": "Exécuter le modèle avec le titre, l’identifiant et les autres informations du document sélectionné sans le modifier",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex e200cf3781..8bcc90e473 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,12 @@{+ "keymapUnset": "לא הוגדר",+ "keymapPrimary": "הגדר כקיצור ראשי",+ "keymapRecording": "הקש קיצור מקשים...",+ "keymapShared": "קיצור משותף",+ "keymapSharedTip": "לפקודות מקומיות יש עדיפות. בכל הקשר הפקודות נבדקות בסדר המוצג; לאחר שפקודה מתחילה, לא מופעלת פקודה נוספת",+ "keymapLegacyConflict": "קיצור זה מתנגש עם פעולה שעדיין אינה תומכת בקיצורים משותפים",+ "keymapSystemScope": "כלל המערכת",+ "keymapSaveFailed": "לא ניתן לשמור את קיצורי המקשים","templateSearch": "חיפוש תבניות לפי שם או נתיב","templateContextSearch": "חיפוש מסמכי הקשר","templateContextTip": "הפעלת התבנית באמצעות הכותרת, המזהה ומידע נוסף מהמסמך שנבחר, ללא שינוי המסמך",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex f29190c3e8..56d03c90b8 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,12 @@{+ "keymapUnset": "सेट नहीं है",+ "keymapPrimary": "मुख्य शॉर्टकट बनाएँ",+ "keymapRecording": "शॉर्टकट दबाएँ...",+ "keymapShared": "साझा शॉर्टकट",+ "keymapSharedTip": "स्थानीय कमांड को प्राथमिकता मिलती है। हर संदर्भ में कमांड दिखाए गए क्रम में जाँचे जाते हैं; एक कमांड शुरू होने के बाद कोई दूसरा नहीं चलता",+ "keymapLegacyConflict": "यह शॉर्टकट ऐसी क्रिया से टकराता है जो अभी साझा शॉर्टकट का समर्थन नहीं करती",+ "keymapSystemScope": "पूरे सिस्टम में",+ "keymapSaveFailed": "शॉर्टकट सहेजे नहीं जा सके","templateSearch": "नाम या पथ से टेम्पलेट खोजें","templateContextSearch": "संदर्भ दस्तावेज़ खोजें","templateContextTip": "चुने हुए दस्तावेज़ में बदलाव किए बिना उसके शीर्षक, ID और अन्य जानकारी का उपयोग करके टेम्पलेट चलाएँ",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex e14e6d77fa..8a3faf07a9 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Belum diatur",+ "keymapPrimary": "Jadikan pintasan utama",+ "keymapRecording": "Tekan pintasan...",+ "keymapShared": "Pintasan bersama",+ "keymapSharedTip": "Perintah lokal diprioritaskan. Dalam setiap konteks, perintah dicoba sesuai urutan yang ditampilkan; setelah satu perintah dimulai, perintah lain tidak dijalankan",+ "keymapLegacyConflict": "Pintasan ini bertentangan dengan tindakan yang belum mendukung pintasan bersama",+ "keymapSystemScope": "Seluruh sistem",+ "keymapSaveFailed": "Tidak dapat menyimpan pintasan","templateSearch": "Cari templat berdasarkan nama atau jalur","templateContextSearch": "Cari dokumen konteks","templateContextTip": "Jalankan templat menggunakan judul, ID, dan informasi lain dari dokumen yang dipilih tanpa mengubah dokumen tersebut",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 7bd10b4d6e..6da4db724a 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Non impostato",+ "keymapPrimary": "Imposta come scorciatoia principale",+ "keymapRecording": "Premi una scorciatoia...",+ "keymapShared": "Scorciatoia condivisa",+ "keymapSharedTip": "I comandi locali hanno la precedenza. In ogni contesto vengono valutati nell’ordine mostrato; quando un comando inizia, nessun altro viene eseguito",+ "keymapLegacyConflict": "Questa scorciatoia è in conflitto con un’azione che non supporta ancora le assegnazioni condivise",+ "keymapSystemScope": "A livello di sistema",+ "keymapSaveFailed": "Impossibile salvare le scorciatoie","templateSearch": "Cerca modelli per nome o percorso","templateContextSearch": "Cerca documenti di contesto","templateContextTip": "Esegui il modello usando il titolo, l’ID e le altre informazioni del documento selezionato senza modificarlo",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex c5fb9905b3..e129bb12f9 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,12 @@{+ "keymapUnset": "未設定",+ "keymapPrimary": "メインのショートカットに設定",+ "keymapRecording": "ショートカットを入力...",+ "keymapShared": "共有ショートカット",+ "keymapSharedTip": "局所的なコマンドが優先されます。同じコンテキストでは表示順に判定し、コマンドの実行開始後は他のコマンドを実行しません",+ "keymapLegacyConflict": "このショートカットは、共有割り当てにまだ対応していない操作と競合しています",+ "keymapSystemScope": "システム全体",+ "keymapSaveFailed": "ショートカットを保存できませんでした","templateSearch": "テンプレート名またはパスを検索","templateContextSearch": "コンテキスト用ドキュメントを検索","templateContextTip": "選択したドキュメントのタイトルや ID などの情報を使ってテンプレートを実行します。ドキュメントは変更されません",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 0d616a99b4..f973428fcf 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,12 @@{+ "keymapUnset": "설정되지 않음",+ "keymapPrimary": "기본 단축키로 설정",+ "keymapRecording": "단축키를 누르세요...",+ "keymapShared": "공유 단축키",+ "keymapSharedTip": "로컬 명령이 우선합니다. 각 컨텍스트에서 표시된 순서대로 명령을 확인하며, 명령이 실행되기 시작하면 다른 명령은 실행하지 않습니다",+ "keymapLegacyConflict": "이 단축키는 아직 공유 할당을 지원하지 않는 작업과 충돌합니다",+ "keymapSystemScope": "시스템 전체",+ "keymapSaveFailed": "단축키를 저장할 수 없습니다","templateSearch": "템플릿 이름 또는 경로 검색","templateContextSearch": "컨텍스트 문서 검색","templateContextTip": "선택한 문서의 제목, ID 등의 정보로 템플릿을 실행하며 해당 문서는 수정하지 않습니다",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 5092512388..39dba7d61d 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Niet ingesteld",+ "keymapPrimary": "Instellen als primaire sneltoets",+ "keymapRecording": "Druk op een sneltoets...",+ "keymapShared": "Gedeelde sneltoets",+ "keymapSharedTip": "Lokale opdrachten hebben voorrang. Per context worden opdrachten in de getoonde volgorde geprobeerd; zodra een opdracht begint, wordt geen andere uitgevoerd",+ "keymapLegacyConflict": "Deze sneltoets conflicteert met een actie die gedeelde toewijzingen nog niet ondersteunt",+ "keymapSystemScope": "Systeembreed",+ "keymapSaveFailed": "Sneltoetsen konden niet worden opgeslagen","templateSearch": "Sjablonen zoeken op naam of pad","templateContextSearch": "Contextdocumenten zoeken","templateContextTip": "Voer het sjabloon uit met de titel, ID en andere informatie van het geselecteerde document zonder dat document te wijzigen",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 9d5ad2cab7..67bbb9ec44 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Nie ustawiono",+ "keymapPrimary": "Ustaw jako główny skrót",+ "keymapRecording": "Naciśnij skrót...",+ "keymapShared": "Wspólny skrót",+ "keymapSharedTip": "Polecenia lokalne mają pierwszeństwo. W każdym kontekście polecenia są sprawdzane w wyświetlonej kolejności; po rozpoczęciu jednego żadne inne nie zostanie wykonane",+ "keymapLegacyConflict": "Ten skrót koliduje z działaniem, które nie obsługuje jeszcze wspólnych przypisań",+ "keymapSystemScope": "Cały system",+ "keymapSaveFailed": "Nie można zapisać skrótów","templateSearch": "Szukaj szablonów według nazwy lub ścieżki","templateContextSearch": "Szukaj dokumentów kontekstowych","templateContextTip": "Uruchom szablon, używając tytułu, ID i innych informacji z wybranego dokumentu, bez jego modyfikowania",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex a244d10a84..1752221e91 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Não definido",+ "keymapPrimary": "Definir como atalho principal",+ "keymapRecording": "Pressione um atalho...",+ "keymapShared": "Atalho compartilhado",+ "keymapSharedTip": "Comandos locais têm prioridade. Em cada contexto, os comandos são avaliados na ordem exibida; após o início de um comando, nenhum outro é executado",+ "keymapLegacyConflict": "Este atalho entra em conflito com uma ação que ainda não aceita atribuições compartilhadas",+ "keymapSystemScope": "Todo o sistema",+ "keymapSaveFailed": "Não foi possível salvar os atalhos","templateSearch": "Pesquisar modelos por nome ou caminho","templateContextSearch": "Pesquisar documentos de contexto","templateContextTip": "Executar o modelo usando o título, o ID e outras informações do documento selecionado sem modificá-lo",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 14acc495b6..070e55a064 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Не назначено",+ "keymapPrimary": "Сделать основным сочетанием",+ "keymapRecording": "Нажмите сочетание клавиш...",+ "keymapShared": "Общее сочетание клавиш",+ "keymapSharedTip": "Локальные команды имеют приоритет. В каждом контексте команды проверяются в указанном порядке; после запуска одной команды другие не выполняются",+ "keymapLegacyConflict": "Это сочетание конфликтует с действием, которое пока не поддерживает общие назначения",+ "keymapSystemScope": "Вся система",+ "keymapSaveFailed": "Не удалось сохранить сочетания клавиш","templateSearch": "Поиск шаблонов по имени или пути","templateContextSearch": "Поиск документов контекста","templateContextTip": "Выполнить шаблон с заголовком, ID и другими данными выбранного документа, не изменяя сам документ",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex cf083a49e9..f2f48672d9 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Nenastavené",+ "keymapPrimary": "Nastaviť ako hlavnú skratku",+ "keymapRecording": "Stlačte klávesovú skratku...",+ "keymapShared": "Zdieľaná skratka",+ "keymapSharedTip": "Miestne príkazy majú prednosť. V každom kontexte sa príkazy skúšajú v zobrazenom poradí; po spustení jedného sa ďalší nevykoná",+ "keymapLegacyConflict": "Táto skratka je v konflikte s akciou, ktorá zatiaľ nepodporuje zdieľané priradenia",+ "keymapSystemScope": "Celý systém",+ "keymapSaveFailed": "Klávesové skratky sa nepodarilo uložiť","templateSearch": "Hľadať šablóny podľa názvu alebo cesty","templateContextSearch": "Hľadať kontextové dokumenty","templateContextTip": "Spustiť šablónu s názvom, ID a ďalšími údajmi vybraného dokumentu bez jeho zmeny",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex c1244a6f3f..af95fa9db6 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,12 @@{+ "keymapUnset": "ยังไม่ได้ตั้งค่า",+ "keymapPrimary": "ตั้งเป็นปุ่มลัดหลัก",+ "keymapRecording": "กดปุ่มลัด...",+ "keymapShared": "ปุ่มลัดที่ใช้ร่วมกัน",+ "keymapSharedTip": "คำสั่งเฉพาะบริบทมีลำดับความสำคัญสูงกว่า ในแต่ละบริบทจะตรวจสอบคำสั่งตามลำดับที่แสดง เมื่อคำสั่งหนึ่งเริ่มทำงานแล้วจะไม่เรียกใช้คำสั่งอื่น",+ "keymapLegacyConflict": "ปุ่มลัดนี้ขัดแย้งกับการทำงานที่ยังไม่รองรับการใช้ปุ่มลัดร่วมกัน",+ "keymapSystemScope": "ทั้งระบบ",+ "keymapSaveFailed": "ไม่สามารถบันทึกปุ่มลัดได้","templateSearch": "ค้นหาเทมเพลตตามชื่อหรือเส้นทาง","templateContextSearch": "ค้นหาเอกสารบริบท","templateContextTip": "เรียกใช้เทมเพลตโดยใช้ชื่อ ID และข้อมูลอื่นจากเอกสารที่เลือก โดยไม่แก้ไขเอกสารนั้น",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex f7e73adbbc..7644eeacca 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Ayarlanmadı",+ "keymapPrimary": "Birincil kısayol olarak ayarla",+ "keymapRecording": "Kısayola basın...",+ "keymapShared": "Paylaşılan kısayol",+ "keymapSharedTip": "Yerel komutlar önceliklidir. Her bağlamda komutlar gösterilen sırayla denenir; bir komut başladığında başka bir komut çalıştırılmaz",+ "keymapLegacyConflict": "Bu kısayol, henüz paylaşılan atamaları desteklemeyen bir işlemle çakışıyor",+ "keymapSystemScope": "Sistem genelinde",+ "keymapSaveFailed": "Kısayollar kaydedilemedi","templateSearch": "Şablonları ada veya yola göre ara","templateContextSearch": "Bağlam belgelerini ara","templateContextTip": "Şablonu, seçilen belgenin başlığını, kimliğini ve diğer bilgilerini kullanarak belgeyi değiştirmeden çalıştırın",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 230ff81de1..919538ab0d 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,12 @@{+ "keymapUnset": "Не призначено",+ "keymapPrimary": "Зробити основним сполученням",+ "keymapRecording": "Натисніть сполучення клавіш...",+ "keymapShared": "Спільне сполучення клавіш",+ "keymapSharedTip": "Локальні команди мають пріоритет. У кожному контексті команди перевіряються в показаному порядку; після запуску однієї інші не виконуються",+ "keymapLegacyConflict": "Це сполучення конфліктує з дією, яка ще не підтримує спільні призначення",+ "keymapSystemScope": "Уся система",+ "keymapSaveFailed": "Не вдалося зберегти сполучення клавіш","templateSearch": "Пошук шаблонів за назвою або шляхом","templateContextSearch": "Пошук документів контексту","templateContextTip": "Виконати шаблон із заголовком, ID та іншими даними вибраного документа, не змінюючи сам документ",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 2b05f9b02d..fcec960327 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,12 @@{+ "keymapUnset": "未设置",+ "keymapPrimary": "设为主快捷键",+ "keymapRecording": "按下快捷键...",+ "keymapShared": "共用快捷键",+ "keymapSharedTip": "局部命令优先。同一上下文按显示顺序匹配;命令开始执行后,不再执行其他命令",+ "keymapLegacyConflict": "此快捷键与尚不支持共用绑定的操作冲突",+ "keymapSystemScope": "系统全局",+ "keymapSaveFailed": "无法保存快捷键","templateSearch": "搜索模板名称或路径","templateContextSearch": "搜索上下文文档","templateContextTip": "使用所选文档的标题、ID 等信息运行模板,不会修改该文档",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex b480658d40..8aca857c83 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,12 @@{+ "keymapUnset": "未設定",+ "keymapPrimary": "設為主要快捷鍵",+ "keymapRecording": "按下快捷鍵...",+ "keymapShared": "共用快捷鍵",+ "keymapSharedTip": "局部命令優先。同一上下文依顯示順序比對;命令開始執行後,不再執行其他命令",+ "keymapLegacyConflict": "此快捷鍵與尚不支援共用綁定的操作衝突",+ "keymapSystemScope": "系統全域",+ "keymapSaveFailed": "無法儲存快捷鍵","templateSearch": "搜尋範本名稱或路徑","templateContextSearch": "搜尋上下文文件","templateContextTip": "使用所選文件的標題、ID 等資訊執行範本,不會修改該文件",diff --git a/app/electron/globalShortcutBindings.js b/app/electron/globalShortcutBindings.jsnew file mode 100644index 0000000000..1bd853e105--- /dev/null+++ b/app/electron/globalShortcutBindings.js@@ -0,0 +1,63 @@+const updateGlobalShortcutBindings = (owner, data, options) => {+ const {workspaces, globalShortcut, convert, getActiveId, toggle, dispatch, reportError} = options;+ const previous = owner.hotkeys || [];+ owner.shortcutsSuspended = data.suspended === true;+ if (!owner.shortcutsSuspended) {+ owner.hotkeys = [...new Set(data.hotkeys.filter(key => typeof key === "string" && key))];+ owner.toggleHotkeys = Array.isArray(data.toggleHotkeys) ? data.toggleHotkeys : data.hotkeys.slice(0, 1);+ owner.hotkeyLanguages = data.languages;+ }+ const keys = workspaces.flatMap(workspace => workspace.hotkeys || []);+ const activeHotkeys = new Set(keys.map(convert));+ if (workspaces.some(workspace => workspace.shortcutsSuspended)) {+ new Set([...previous, ...keys].map(convert)).forEach(key => {+ if (key) {+ globalShortcut.unregister(key);+ }+ });+ return [];+ }+ previous.forEach(key => {+ const accelerator = convert(key);+ if (accelerator && !activeHotkeys.has(accelerator)) {+ globalShortcut.unregister(accelerator);+ }+ });+ const failed = [];+ const registered = new Set();+ keys.forEach(key => {+ const accelerator = convert(key);+ if (!accelerator || registered.has(accelerator)) {+ return;+ }+ registered.add(accelerator);+ globalShortcut.unregister(accelerator);+ let success = false;+ try {+ success = globalShortcut.register(accelerator, () => {+ const eligible = workspaces.filter(workspace =>+ !workspace.browserWindow.isDestroyed() &&+ workspace.hotkeys?.some(item => convert(item) === accelerator));+ const activeId = getActiveId();+ const current = eligible.find(workspace => workspace.browserWindow.webContents.id === activeId) ||+ eligible.find(workspace => workspace === owner) || eligible[0];+ if (!current) {+ return;+ }+ if (current.toggleHotkeys?.some(item => convert(item) === accelerator)) {+ toggle(current);+ } else {+ dispatch(current, current.hotkeys.find(item => convert(item) === accelerator));+ }+ });+ } catch (error) {+ reportError(error);+ }+ if (!success) {+ failed.push(key);+ }+ });+ return failed;+};++module.exports = {updateGlobalShortcutBindings};diff --git a/app/electron/globalShortcutBindings.test.js b/app/electron/globalShortcutBindings.test.jsnew file mode 100644index 0000000000..502b94efbe--- /dev/null+++ b/app/electron/globalShortcutBindings.test.js@@ -0,0 +1,87 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const {updateGlobalShortcutBindings} = require("./globalShortcutBindings");++const fixture = () => {+ const callbacks = new Map();+ const calls = [];+ const errors = [];+ let activeId = 1;+ const workspaces = [1, 2].map(id => ({browserWindow: {webContents: {id}, isDestroyed: () => false}}));+ const options = {+ workspaces,+ globalShortcut: {unregister: key => callbacks.delete(key), register: (key, callback) => {+ callbacks.set(key, callback);+ return true;+ }},+ convert: key => key.toUpperCase(),+ getActiveId: () => activeId,+ toggle: workspace => calls.push([workspace.browserWindow.webContents.id, "toggle"]),+ dispatch: (workspace, key) => calls.push([workspace.browserWindow.webContents.id, key]),+ reportError: error => errors.push(error),+ };+ return {callbacks, calls, errors, workspaces, options, activate: id => activeId = id,+ update: (index, hotkeys, toggleHotkeys = []) => updateGlobalShortcutBindings(workspaces[index], {hotkeys, toggleHotkeys}, options)};+};++test("registers multiple window-toggle keys and deduplicates accelerators", () => {+ const f = fixture();+ assert.deepEqual(f.update(0, ["a", "A", "b", "c"], ["a", "b"]), []);+ assert.equal(f.callbacks.size, 3);+ f.callbacks.get("A")();+ f.callbacks.get("B")();+ f.callbacks.get("C")();+ assert.deepEqual(f.calls, [[1, "toggle"], [1, "toggle"], [1, "c"]]);+});++test("removing one workspace binding preserves another owner and uses eligible focus", () => {+ const f = fixture();+ f.update(0, ["a", "b"]);+ f.update(1, ["a"]);+ f.activate(2);+ f.callbacks.get("A")();+ f.callbacks.get("B")();+ assert.deepEqual(f.calls, [[2, "a"], [1, "b"]]);+ f.update(1, []);+ assert.equal(f.callbacks.has("A"), true);+ f.callbacks.get("A")();+ assert.deepEqual(f.calls.at(-1), [1, "a"]);+ f.update(0, []);+ assert.equal(f.callbacks.size, 0);+});++test("replacing and restoring bindings leaves no stale registrations", () => {+ const f = fixture();+ f.update(0, ["a", "b"]);+ f.update(0, ["c"]);+ assert.deepEqual([...f.callbacks.keys()], ["C"]);+ f.update(0, []);+ assert.equal(f.callbacks.size, 0);+ f.update(0, ["a", "b"]);+ assert.deepEqual([...f.callbacks.keys()], ["A", "B"]);+});++test("reports host rejection and thrown registration errors", () => {+ const f = fixture();+ f.options.globalShortcut.register = key => {+ if (key === "B") {+ throw new Error("unsupported accelerator");+ }+ return false;+ };+ assert.deepEqual(f.update(0, ["a", "b"]), ["a", "b"]);+ assert.equal(f.errors.length, 1);+});++test("recording suspends all workspace shortcuts and restores their bindings afterward", () => {+ const f = fixture();+ f.update(0, ["a"]);+ f.update(1, ["b"]);+ updateGlobalShortcutBindings(f.workspaces[0], {hotkeys: [], suspended: true}, f.options);+ assert.equal(f.callbacks.size, 0);+ assert.deepEqual(f.workspaces[0].hotkeys, ["a"]);+ f.update(1, ["c"]);+ assert.equal(f.callbacks.size, 0);+ f.update(0, ["a"]);+ assert.deepEqual([...f.callbacks.keys()].sort(), ["A", "C"]);+});diff --git a/app/electron/main.js b/app/electron/main.jsindex 31d18da204..b8c7dab6e5 100644--- a/app/electron/main.js+++ b/app/electron/main.js@@ -36,6 +36,7 @@ const {systemPreferences,powerMonitor} = require("electron");+const {updateGlobalShortcutBindings} = require("./globalShortcutBindings");const path = require("path");const fs = require("fs");const {pathToFileURL} = require("url");@@ -3624,7 +3625,7 @@ app.whenReady().then(() => {return capabilities;});ipcMain.on("siyuan-hotkey", (event, data) => {- if (!data.hotkeys || data.hotkeys.length === 0) {+ if (!Array.isArray(data.hotkeys)) {return;}const ownerWorkspace = workspaces.find(workspaceItem =>@@ -3632,53 +3633,22 @@ app.whenReady().then(() => {if (!ownerWorkspace) {return;}- ownerWorkspace.hotkeys = data.hotkeys;- data.hotkeys.forEach((item, index) => {- const shortcut = hotKey2Electron(item);- if (!shortcut) {- return;- }- if (globalShortcut.isRegistered(shortcut)) {- globalShortcut.unregister(shortcut);- }- if (index === 0) {- globalShortcut.register(shortcut, () => {- let currentWorkspace;- const currentWebContentsId = (latestActiveWindow && !latestActiveWindow.isDestroyed()) ? latestActiveWindow.webContents.id : undefined;- workspaces.find(workspaceItem => {- if (currentWebContentsId === workspaceItem.browserWindow.webContents.id && workspaceItem.hotkeys[0] === item) {- currentWorkspace = workspaceItem;- return true;- }- });- if (!currentWorkspace) {- workspaces.find(workspaceItem => {- if (workspaceItem.hotkeys[0] === item && event.sender.id === workspaceItem.browserWindow.webContents.id) {- currentWorkspace = workspaceItem;- return true;- }- });- }- if (!currentWorkspace) {- return;- }- const mainWindow = currentWorkspace.browserWindow;- toggleMainWindow(mainWindow);- if ("win32" === process.platform || "linux" === process.platform) {- resetTrayMenu(currentWorkspace.tray, data.languages, mainWindow);- }- });- } else {- globalShortcut.register(shortcut, () => {- const targetWorkspace = getGlobalShortcutWorkspace(ownerWorkspace);- if (targetWorkspace) {- targetWorkspace.browserWindow.webContents.send("siyuan-hotkey", {- hotkey: item- });- }- });- }+ const failed = updateGlobalShortcutBindings(ownerWorkspace, data, {+ workspaces,+ globalShortcut,+ convert: hotKey2Electron,+ getActiveId: () => latestActiveWindow && !latestActiveWindow.isDestroyed() ?+ latestActiveWindow.webContents.id : undefined,+ toggle: workspace => {+ toggleMainWindow(workspace.browserWindow);+ if (process.platform === "win32" || process.platform === "linux") {+ resetTrayMenu(workspace.tray, workspace.hotkeyLanguages, workspace.browserWindow);+ }+ },+ dispatch: (workspace, hotkey) => workspace.browserWindow.webContents.send("siyuan-hotkey", {hotkey}),+ reportError: error => console.error("Global shortcut registration failed:", error),});+ event.sender.send("siyuan-hotkey", {failed});});ipcMain.on("siyuan-send-windows", (event, data) => {BrowserWindow.getAllWindows().forEach(item => {diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.syindex 2b69470d21..2f52189e36 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy@@ -7,9 +7,55 @@"id": "20200924100950-9op5xi1","title": "Shortcuts","type": "doc",- "updated": "20260906013806"+ "updated": "20260908092714"},"Children": [+ {+ "ID": "20260908092714-3tm4lvq",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260908092714-3tm4lvq",+ "updated": "20260908092714"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "In "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Settings"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Keymap"+ },+ {+ "Type": "NodeText",+ "Data": ", you can assign multiple shortcuts to the same action. Click the plus button at the end of a row and press a key combination to save it. Click an existing shortcut to edit it, its close button to remove it, or the reset button to restore all defaults for that action. Press Esc or click outside to cancel recording. The first shortcut appears in menu hints; right-click another shortcut to make it the primary shortcut."+ }+ ]+ },+ {+ "ID": "20260908092714-jbgcc13",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260908092714-jbgcc13",+ "updated": "20260908092714"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Click “Shared shortcut” to see contexts and execution order. Use the up and down buttons to reorder commands within the same context. Local commands take priority, with unavailable commands skipped. Once a command starts, cancellation or failure does not trigger another command. Some actions do not support shared bindings yet; if recording reports a conflict, choose another shortcut."+ }+ ]+ },{"ID": "20260813143406-k7m2x9q","Type": "NodeParagraph",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.syindex 1626742872..91d4753926 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy@@ -7,9 +7,55 @@"id": "20200813004551-gm0pbn1","title": "快捷键","type": "doc",- "updated": "20260906013806"+ "updated": "20260908092714"},"Children": [+ {+ "ID": "20260908092714-514td5y",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260908092714-514td5y",+ "updated": "20260908092714"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "可在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "设置"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "快捷键"+ },+ {+ "Type": "NodeText",+ "Data": " 中为同一个操作配置多个快捷键。点击行末的加号后按下组合键即可保存;点击已有快捷键可修改,点击其关闭按钮可删除,点击恢复按钮可恢复该操作的全部默认快捷键。按 Esc 或点击外部可取消录入。第一项用于菜单提示,右击其他快捷键可将其设为主快捷键。"+ }+ ]+ },+ {+ "ID": "20260908092714-88wn8r6",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260908092714-88wn8r6",+ "updated": "20260908092714"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "点击「共用快捷键」可查看适用上下文和执行顺序,并用上下按钮调整同一上下文内的顺序。局部命令优先,不可用时继续匹配;命令开始执行后,即使取消或失败,也不会执行其他命令。部分操作暂不支持共用绑定,录入时会提示冲突,此时请使用其他快捷键。"+ }+ ]+ },{"ID": "20260813143407-p4v8n2c","Type": "NodeParagraph",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.syindex fc99b26258..2471f42522 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy@@ -7,9 +7,55 @@"id": "20211226122549-jktxego","title": "快捷鍵","type": "doc",- "updated": "20260906013806"+ "updated": "20260908092714"},"Children": [+ {+ "ID": "20260908092714-e1q4nu2",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260908092714-e1q4nu2",+ "updated": "20260908092714"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "可在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "快捷鍵"+ },+ {+ "Type": "NodeText",+ "Data": " 中為同一個操作設定多個快捷鍵。點擊列末的加號後按下組合鍵即可儲存;點擊既有快捷鍵可修改,點擊其關閉按鈕可刪除,點擊還原按鈕可還原該操作的全部預設快捷鍵。按 Esc 或點擊外部可取消輸入。第一項用於選單提示,右擊其他快捷鍵可將其設為主要快捷鍵。"+ }+ ]+ },+ {+ "ID": "20260908092714-g928py1",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260908092714-g928py1",+ "updated": "20260908092714"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "點擊「共用快捷鍵」可查看適用上下文和執行順序,並以上下按鈕調整同一上下文內的順序。局部命令優先,不可用時繼續比對;命令開始執行後,即使取消或失敗,也不會執行其他命令。部分操作暫不支援共用綁定,輸入時會提示衝突,此時請使用其他快捷鍵。"+ }+ ]+ },{"ID": "20260813143408-r6w3j9h","Type": "NodeParagraph",diff --git a/app/src/assets/scss/business/_config.scss b/app/src/assets/scss/business/_config.scssindex 13b491ad86..bb9796a34f 100644--- a/app/src/assets/scss/business/_config.scss+++ b/app/src/assets/scss/business/_config.scss@@ -400,6 +400,136 @@}&-keymap {+ &__row {+ flex-wrap: wrap;++ &:hover .b3-list-item__action,+ &:focus-within .b3-list-item__action {+ display: flex;+ }+ }++ &__controls,+ &__bindings {+ display: flex;+ align-items: center;+ }++ &__controls {+ max-width: 70%;+ margin-left: auto;+ }++ &__bindings {+ flex-wrap: wrap;+ justify-content: flex-end;+ min-width: 0;+ }++ &__chip {+ display: inline-flex;+ align-items: center;+ white-space: nowrap;+ }++ &__text {+ border: 0;+ padding: 0;+ background: transparent;+ color: inherit;+ font: inherit;+ cursor: pointer;+ }++ &__remove {+ border: 0;+ background: transparent;+ color: inherit;+ box-sizing: content-box;+ margin-left: 3px;+ margin-right: -2px;++ svg {+ display: block;+ width: 12px;+ height: 12px;+ }+ }++ &__action {+ border: 0;+ background: transparent;+ cursor: pointer;++ &--active {+ color: var(--b3-theme-primary);+ }++ &:disabled {+ opacity: .35;+ cursor: default;+ }+ }++ &__shared-button {+ border: 0;+ background: transparent;+ color: var(--b3-theme-on-surface);+ cursor: pointer;+ flex-shrink: 0;+ padding: 4px;+ border-radius: var(--b3-border-radius);++ &:hover,+ &--active {+ color: var(--b3-theme-primary);+ }++ &:focus-visible {+ outline: 2px solid var(--b3-theme-primary);+ }++ &:disabled {+ opacity: .35;+ cursor: default;+ }++ svg {+ display: block;+ width: 16px;+ height: 16px;+ }+ }++ &__record {+ width: 150px;+ max-width: 100%;+ }++ &__shared {+ flex-basis: 100%;+ padding: 8px 12px;+ background: var(--b3-theme-surface);+ border-radius: var(--b3-border-radius);+ white-space: normal;+ }++ &__shared-title {+ margin: 8px 0;+ font-weight: bold;+ }++ &__shared-button--conflict {+ color: var(--b3-card-warning-color);+ }++ &__candidate {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 4px 0;+ }+&__key {padding: 2px 4px;font-family: var(--b3-font-family-kbd);@@ -415,6 +545,12 @@cursor: pointer;height: 14px;min-width: 17px;+ font-size: inherit;+ box-sizing: content-box;++ &:focus-visible {+ outline: 2px solid var(--b3-theme-primary);+ }}.b3-list__panel .b3-text-field {@@ -425,6 +561,10 @@padding-left: 4px;user-select: none;}++ div.config-keymap__row > .b3-list-item__text {+ padding-left: 0;+ }}&-bazaar {diff --git a/app/src/assets/scss/util/_responsive.scss b/app/src/assets/scss/util/_responsive.scssindex b200b50bd6..79ffb473cb 100644--- a/app/src/assets/scss/util/_responsive.scss+++ b/app/src/assets/scss/util/_responsive.scss@@ -124,19 +124,8 @@}&-keymap {- label.b3-list-item {- flex-wrap: wrap;- }-- .b3-list-item__action {- display: flex;- }-- .config-keymap__key,- .b3-text-field {- width: 100%;- margin-left: 0 !important;- text-align: center;+ .config-keymap__controls {+ max-width: 100%;}}}diff --git a/app/src/boot/globalEvent/command/panel.ts b/app/src/boot/globalEvent/command/panel.tsindex 5d4103b034..a517befb4e 100644--- a/app/src/boot/globalEvent/command/panel.ts+++ b/app/src/boot/globalEvent/command/panel.ts@@ -1,3 +1,4 @@+import {getKeymapBindings, getKeymapItem} from "../../../util/keymapBindings";import {Dialog} from "../../../dialog";import type {App} from "../../../index";import {upDownHint} from "../../../util/upDownHint";@@ -27,7 +28,9 @@ const renderCommands = (listElement: HTMLElement, commands: ICommandDefinition[]textElement.textContent = command.label();const hotkeyElement = document.createElement("span");hotkeyElement.className = `b3-list-item__meta${isMobile() ? " fn__none" : ""}`;- hotkeyElement.textContent = updateHotkeyTip(command.hotkey?.() || "");+ hotkeyElement.textContent = command.keymapPath ?+ getKeymapBindings(getKeymapItem(window.siyuan.config.keymap, command.keymapPath)).map(key => updateHotkeyTip(key)).join(" / ") :+ updateHotkeyTip(command.hotkey?.() || "");itemElement.append(textElement, hotkeyElement);fragment.append(itemElement);});@@ -110,7 +113,7 @@ export const commandPanel = (app: App) => {if (event.isComposing) {return;}- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.general.commandPanel.custom, event)) {+ if (!event.repeat && matchHotKey(window.siyuan.config.keymap.general.commandPanel, event)) {dialog.destroy();event.preventDefault();return;diff --git a/app/src/boot/globalEvent/commonHotkey.ts b/app/src/boot/globalEvent/commonHotkey.tsindex 90fd581902..d9e6018af9 100644--- a/app/src/boot/globalEvent/commonHotkey.ts+++ b/app/src/boot/globalEvent/commonHotkey.ts@@ -1,3 +1,4 @@+import {mergeKeymapDefault} from "../../util/keymapBindings";import {Constants} from "../../constants";import {fetchPost} from "../../util/fetch";/// #if !BROWSER@@ -55,7 +56,7 @@ const matchKeymap = (keymap: Config.IKeys, key1: "general" | "editor", key2?: "g});/// #endifmatch = false;- window.siyuan.config.keymap[key1][key] = keymap[key];+ window.siyuan.config.keymap[key1][key] = mergeKeymapDefault(window.siyuan.config.keymap[key1][key], keymap[key]);}} else {if (!window.siyuan.config.keymap[key1][key2][key] || window.siyuan.config.keymap[key1][key2][key].default !== keymap[key].default) {@@ -66,7 +67,7 @@ const matchKeymap = (keymap: Config.IKeys, key1: "general" | "editor", key2?: "g});/// #endifmatch = false;- window.siyuan.config.keymap[key1][key2][key] = keymap[key];+ window.siyuan.config.keymap[key1][key2][key] = mergeKeymapDefault(window.siyuan.config.keymap[key1][key2][key], keymap[key]);}}});@@ -162,7 +163,7 @@ export const correctHotkey = (app: App) => {let lastHotkeys: Record<string, string>;-export const syncAppMenuShortcuts = () => {+export const syncAppMenuShortcuts = (suspended = false) => {/// #if !BROWSERif (!isMac()) {return;@@ -176,7 +177,7 @@ export const syncAppMenuShortcuts = () => {const hotkey: Record<string, string> = {};Object.keys(appMenuHotkeyItems).forEach(id => {const item = appMenuHotkeyItems[id];- hotkey[id] = item.custom ?? item.default ?? "";+ hotkey[id] = suspended ? "" : item.custom ?? item.default ?? "";});if (lastHotkeys && Object.keys(appMenuHotkeyItems).every(id => lastHotkeys[id] === hotkey[id])) {return;diff --git a/app/src/boot/globalEvent/event.ts b/app/src/boot/globalEvent/event.tsindex b2d2e5c890..b115d89bbf 100644--- a/app/src/boot/globalEvent/event.ts+++ b/app/src/boot/globalEvent/event.ts@@ -19,6 +19,8 @@ import {initHarmonyTextSelectionMenu} from "../../util/harmonyTextSelectionMenu"import {clearDragTipGhost, hideDragTip} from "../../protyle/util/dragTip";import {formatPainter} from "../../protyle/toolbar/FormatPainter";import {SELECTION_TOOLBAR_SUB_ELEMENT_SOURCE} from "../../protyle/toolbar/subElementLifecycle";+import {dispatchSharedShortcut} from "../../command/shortcutRuntime";+import {ensureCommandSystem} from "../../command/executor";const KANBAN_GROUP_DRAG_TYPE = `${Constants.SIYUAN_DROP_GUTTER}NodeAttributeView${Constants.ZWSP}Group${Constants.ZWSP}`.toLowerCase();@@ -253,6 +255,10 @@ export const initWindowEvent = (app: App) => {windowKeyUp(app, event);});+ window.addEventListener("keydown", (event) => {+ dispatchSharedShortcut(app, event, () => ensureCommandSystem(app));+ }, true);+window.addEventListener("keydown", (event) => {windowKeyDown(app, event);});diff --git a/app/src/boot/globalEvent/globalShortcut.ts b/app/src/boot/globalEvent/globalShortcut.tsindex 50124f7c21..6bacccdc46 100644--- a/app/src/boot/globalEvent/globalShortcut.ts+++ b/app/src/boot/globalEvent/globalShortcut.ts@@ -2,51 +2,53 @@ import type {App} from "../../index";import {Constants} from "../../constants";import {isWindow} from "../../util/functions";import {clearDisallowedTextInputHotkey} from "../../util/hotKeyPolicy";+import {getKeymapBindings} from "../../util/keymapBindings";+import {syncAppMenuShortcuts} from "./commonHotkey";/// #if !BROWSERimport {ipcRenderer} from "electron";/// #endifexport const sendGlobalShortcut = (app: App) => {/// #if !BROWSER+ if (document.activeElement?.matches(".config-keymap__record, #searchByKey")) {+ sendUnregisterGlobalShortcut(app);+ return;+ }+ syncAppMenuShortcuts();if (isWindow()) {return;}- const hotkeys = [clearDisallowedTextInputHotkey(window.siyuan.config.keymap.general.toggleWin.custom)];+ const toggleHotkeys = getKeymapBindings(window.siyuan.config.keymap.general.toggleWin)+ .map(clearDisallowedTextInputHotkey).filter(Boolean);+ const hotkeys = new Set(toggleHotkeys);app.plugins.forEach(plugin => {plugin.commands.forEach(command => {- if (command.globalCallback && command.customHotkey) {- const hotkey = clearDisallowedTextInputHotkey(command.customHotkey);- if (hotkey) {- hotkeys.push(hotkey);- }+ if (command.globalCallback) {+ getKeymapBindings(window.siyuan.config.keymap.plugin?.[plugin.name]?.[command.langKey] ||+ {custom: command.customHotkey}).forEach(key => {+ const hotkey = clearDisallowedTextInputHotkey(key);+ if (hotkey) {+ hotkeys.add(hotkey);+ }+ });}});});ipcRenderer.send(Constants.SIYUAN_HOTKEY, {languages: window.siyuan.languages["_trayMenu"],- hotkeys+ hotkeys: Array.from(hotkeys),+ toggleHotkeys,});/// #endif};export const sendUnregisterGlobalShortcut = (app: App) => {/// #if !BROWSER- if (isWindow()) {- return;+ if (app) {+ syncAppMenuShortcuts(true);+ if (!isWindow()) {+ ipcRenderer.send(Constants.SIYUAN_HOTKEY, {hotkeys: [], suspended: true});+ }}- ipcRenderer.send(Constants.SIYUAN_CMD, {- cmd: "unregisterGlobalShortcut",- accelerator: window.siyuan.config.keymap.general.toggleWin.custom- });- app.plugins.forEach(plugin => {- plugin.commands.forEach(command => {- if (command.globalCallback) {- ipcRenderer.send(Constants.SIYUAN_CMD, {- cmd: "unregisterGlobalShortcut",- accelerator: command.customHotkey- });- }- });- });/// #endif};diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.tsindex bd66a518b4..1938a3b9dc 100644--- a/app/src/boot/globalEvent/keydown.ts+++ b/app/src/boot/globalEvent/keydown.ts@@ -30,7 +30,8 @@ import {goBack, goForward} from "../../util/backForward";import {getDisplayName, getNotebookName, isEncryptedBox} from "../../util/pathName";import {openFileById} from "../../editor/util";import {getAllDocks, getAllEditor, getAllModels, getAllTabs} from "../../layout/getAll";-import {getDockHotkey} from "../../layout/dock/hotkey";+import {getDockHotkey, getDockKeymap} from "../../layout/dock/hotkey";+import {getKeymapBindings} from "../../util/keymapBindings";import {focusBlock, focusByRange, getBlockElementsByRange, selectBlocksByRange} from "../../protyle/util/selection";import {initFileMenu, initNavigationMenu} from "../../menus/navigation";import {bindMenuKeydown} from "../../menus/Menu";@@ -67,7 +68,7 @@ import {getPlainText} from "../../protyle/util/paste";import {commandPanel} from "./command/panel";import {execByCommand} from "../../command/executor";import {captureCommandContext} from "../../command/context";-import {resolvePluginCommandCallback, supportsPluginCommandSource} from "../../plugin/commandAdapter";+import {captureShortcutContext, dispatchPluginShortcut} from "../../command/shortcutRuntime";import {filterHotkey} from "./commonHotkey";import {editorConfigApi} from "../../config/tabs/editorRuntime";import {copyPNGByLink} from "../../menus/util";@@ -304,7 +305,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {return false;}}- if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.replace.custom, event)) {+ if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.replace, event)) {execByCommand({command: "replace",app,@@ -314,7 +315,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {event.preventDefault();return true;}- if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.search.custom, event)) {+ if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.search, event)) {execByCommand({command: "search",app,@@ -324,7 +325,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {event.preventDefault();return true;}- if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.quickMakeCard.custom, event) && !window.siyuan.config.readonly && !isEncryptedBox(protyle.notebookId)) {+ if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.quickMakeCard, event) && !window.siyuan.config.readonly && !isEncryptedBox(protyle.notebookId)) {if (protyle.title?.editElement.contains(range.startContainer)) {quickMakeCard(protyle, [protyle.title.element]);} else {@@ -343,7 +344,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {event.preventDefault();return true;}- if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.addToDatabase.custom, event)) {+ if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.addToDatabase, event)) {execByCommand({command: "addToDatabase",app,@@ -353,7 +354,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {event.preventDefault();return true;}- if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.spaceRepetition.custom, event) &&+ if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.spaceRepetition, event) &&!window.siyuan.config.readonly && !isEncryptedBox(protyle.notebookId)) {fetchPost("/api/riff/getTreeRiffDueCards", {rootID: protyle.block.rootID}, (response) => {openCardByData(app, response.data, "doc", protyle.block.rootID, protyle.title?.editElement.textContent || window.siyuan.languages.untitled);@@ -361,7 +362,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {event.preventDefault();return true;}- if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.move.custom, event)) {+ if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.general.move, event)) {execByCommand({command: "move",app,@@ -373,7 +374,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {}if (!isFileFocus && !event.repeat && !protyle.disabled &&- matchHotKey(window.siyuan.config.keymap.editor.general.duplicate.custom, event)) {+ matchHotKey(window.siyuan.config.keymap.editor.general.duplicate, event)) {event.preventDefault();event.stopPropagation();let selectsElement: HTMLElement[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));@@ -408,18 +409,18 @@ const editKeydown = (app: App, event: KeyboardEvent) => {event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.exitFocus.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.exitFocus, event)) {event.preventDefault();zoomOut({protyle, id: protyle.block.rootID, focusId: protyle.block.id});return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.focusBreadcrumb.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.focusBreadcrumb, event)) {if (protyle.breadcrumb?.focus(range)) {event.preventDefault();return true;}}- if (matchHotKey(window.siyuan.config.keymap.editor.general.switchReadonly.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.switchReadonly, event)) {event.preventDefault();onlyProtyleCommand({protyle,@@ -428,7 +429,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {});return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.switchAdjust.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.switchAdjust, event)) {event.preventDefault();onlyProtyleCommand({protyle,@@ -438,7 +439,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.backlinks.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.backlinks, event)) {event.preventDefault();if (range) {const refElement = hasClosestByAttribute(range.startContainer, "data-type", "block-ref");@@ -461,7 +462,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {});return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.graphView.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.graphView, event)) {event.preventDefault();if (range) {const refElement = hasClosestByAttribute(range.startContainer, "data-type", "block-ref");@@ -484,7 +485,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {});return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.outline.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.outline, event)) {event.preventDefault();openOutline({app,@@ -496,7 +497,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {return true;}/// #if !MOBILE- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyRichText.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyRichText, event)) {if (!hasClosestBlock(range.startContainer)) {return false;}@@ -505,7 +506,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {return true;}/// #endif- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyPlainText.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyPlainText, event)) {const nodeElement = hasClosestBlock(range.startContainer);if (!nodeElement) {return false;@@ -526,7 +527,7 @@ const editKeydown = (app: App, event: KeyboardEvent) => {event.preventDefault();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.duplicateCompletely.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.duplicateCompletely, event)) {const nodeElement = hasClosestBlock(range.startContainer);if (!nodeElement || !nodeElement.classList.contains("av")) {return false;@@ -535,25 +536,25 @@ const editKeydown = (app: App, event: KeyboardEvent) => {event.preventDefault();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.refresh.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.refresh, event)) {reloadProtyle(protyle, true);event.preventDefault();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.fullscreen.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.fullscreen, event)) {const editor = protyle.getInstance();editor.setFullscreen(!editor.isFullscreen());event.preventDefault();return true;}if (!event.repeat && !protyle.options.backlinkData &&- matchHotKey(window.siyuan.config.keymap.editor.general.editMode.custom, event)) {+ matchHotKey(window.siyuan.config.keymap.editor.general.editMode, event)) {toggleEditMode(protyle);saveLayout();event.preventDefault();return true;}- if (range && !isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockRef.custom, event)) {+ if (range && !isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockRef, event)) {event.preventDefault();event.stopPropagation();if (hasClosestByClassName(range.startContainer, "protyle-title")) {@@ -587,12 +588,12 @@ const editKeydown = (app: App, event: KeyboardEvent) => {return false;}// 没有光标时,无法撤销 https://ld246.com/article/1624021111567- if (matchHotKey(window.siyuan.config.keymap.editor.general.undo.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.undo, event)) {protyle.undo.undo(protyle);event.preventDefault();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.redo.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.redo, event)) {protyle.undo.redo(protyle);event.preventDefault();return true;@@ -610,7 +611,7 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {return true;}- if (matchHotKey(window.siyuan.config.keymap.general.selectOpen1.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.selectOpen1, event)) {event.preventDefault();globalCommand("selectOpen1", app);return;@@ -621,28 +622,10 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {}const liElements = Array.from(files.element.querySelectorAll(".b3-list-item--focus"));- let matchedCommand: ICommand | undefined;- app.plugins.find(item => {- item.commands.find(command => {- if (supportsPluginCommandSource(command, "fileTreeShortcut") &&- matchHotKey(command.customHotkey, event)) {- matchedCommand = command;- return true;- }- });- return Boolean(matchedCommand);- });- if (matchedCommand) {- const commandContext = captureCommandContext({- app,- source: "fileTreeShortcut",- fileLiElements: liElements,- });- const callback = resolvePluginCommandCallback(matchedCommand, commandContext);- if (callback) {- void callback();- return true;- }+ if (dispatchPluginShortcut(app, event, "fileTreeShortcut", () => captureCommandContext({+ app, source: "fileTreeShortcut", fileLiElements: liElements,+ }))) {+ return true;}if (liElements.length === 0) {@@ -670,7 +653,7 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {}});- if (matchHotKey(window.siyuan.config.keymap.editor.general.spaceRepetition.custom, event) && !window.siyuan.config.readonly && !isEncryptedBox(notebookId)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.spaceRepetition, event) && !window.siyuan.config.readonly && !isEncryptedBox(notebookId)) {if (isFile) {const id = liElements[0].getAttribute("data-node-id");fetchPost("/api/riff/getTreeRiffDueCards", {rootID: id}, (response) => {@@ -685,7 +668,7 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.quickMakeCard.custom, event) && !isEncryptedBox(notebookId)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.quickMakeCard, event) && !isEncryptedBox(notebookId)) {if (ids.length > 0) {transaction(undefined, [{action: "addFlashcards",@@ -697,7 +680,7 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {return true;}- if (matchHotKey(window.siyuan.config.keymap.general.addToDatabase.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.addToDatabase, event)) {execByCommand({command: "addToDatabase",app,@@ -707,7 +690,7 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.rename.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.rename, event)) {window.siyuan.menus.menu.remove();if (isFile) {const docInfoParam: IObject = {@@ -750,7 +733,7 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {return true;}- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.duplicate.custom, event)) {+ if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.duplicate, event)) {event.preventDefault();event.stopPropagation();ids.forEach(item => {@@ -761,47 +744,47 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {return true;}- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockRef.custom, event)) {+ if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockRef, event)) {event.preventDefault();event.stopPropagation();copyTextByType(ids, "ref");return true;}- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockEmbed.custom, event)) {+ if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockEmbed, event)) {event.preventDefault();event.stopPropagation();copyTextByType(ids, "blockEmbed");return true;}- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocol.custom, event)) {+ if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocol, event)) {event.preventDefault();event.stopPropagation();copyTextByType(ids, "protocol");return true;}- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocolInMd.custom, event)) {+ if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocolInMd, event)) {event.preventDefault();event.stopPropagation();copyTextByType(ids, "protocolMd");return true;}- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyHPath.custom, event)) {+ if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyHPath, event)) {event.preventDefault();event.stopPropagation();copyTextByType(ids, "hPath");return true;}- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyID.custom, event)) {+ if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.copyID, event)) {event.preventDefault();event.stopPropagation();copyTextByType(ids, "id");return true;}- if (isFile && matchHotKey(window.siyuan.config.keymap.general.move.custom, event)) {+ if (isFile && matchHotKey(window.siyuan.config.keymap.general.move, event)) {window.siyuan.menus.menu.remove();execByCommand({command: "move",@@ -812,7 +795,7 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {return true;}- if (isFile && matchHotKey(window.siyuan.config.keymap.editor.general.insertRight.custom, event)) {+ if (isFile && matchHotKey(window.siyuan.config.keymap.editor.general.insertRight, event)) {window.siyuan.menus.menu.remove();openFileById({app,@@ -824,7 +807,7 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {return true;}- if (matchHotKey(window.siyuan.config.keymap.general.replace.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.replace, event)) {window.siyuan.menus.menu.remove();execByCommand({command: "replace",@@ -834,7 +817,7 @@ const fileTreeKeydown = (app: App, event: KeyboardEvent) => {event.preventDefault();return true;}- if (matchHotKey(window.siyuan.config.keymap.general.search.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.search, event)) {window.siyuan.menus.menu.remove();execByCommand({command: "search",@@ -1057,33 +1040,13 @@ const panelTreeKeydown = (app: App, event: KeyboardEvent) => {return false;}- let matchedCommand: ICommand | undefined;- if (!bottomBacklink) {- app.plugins.find(item => {- item.commands.find(command => {- if (supportsPluginCommandSource(command, "dockShortcut") &&- matchHotKey(command.customHotkey, event)) {- matchedCommand = command;- return true;- }- });- return Boolean(matchedCommand);- });- }- if (matchedCommand) {- const commandContext = captureCommandContext({- app,- source: "dockShortcut",- dockElement: activePanelElement as HTMLElement,- });- const callback = resolvePluginCommandCallback(matchedCommand, commandContext);- if (callback) {- void callback();- return true;- }+ if (!bottomBacklink && dispatchPluginShortcut(app, event, "dockShortcut", () => captureCommandContext({+ app, source: "dockShortcut", dockElement: activePanelElement as HTMLElement,+ }))) {+ return true;}- const matchCollapse = matchHotKey(window.siyuan.config.keymap.editor.general.collapse.custom, event);- const matchExpand = matchHotKey(window.siyuan.config.keymap.editor.general.expand.custom, event);+ const matchCollapse = matchHotKey(window.siyuan.config.keymap.editor.general.collapse, event);+ const matchExpand = matchHotKey(window.siyuan.config.keymap.editor.general.expand, event);if (bottomBacklink && (matchCollapse || matchExpand)) {return false;}@@ -1298,8 +1261,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {return;}if (switchDialog &&- (matchAuxiliaryHotKey(window.siyuan.config.keymap.general.goToEditTabNext.custom, event) ||- matchAuxiliaryHotKey(window.siyuan.config.keymap.general.goToEditTabPrev.custom, event))+ matchAuxiliaryHotKey(switchDialog.element.dataset.shortcut || window.siyuan.config.keymap.general.goToEditTabNext, event)&& event.key.startsWith("Arrow")) {dialogArrow(app, switchDialog.element, event);return;@@ -1312,9 +1274,11 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {}const isTabWindow = isWindow();- if (matchHotKey(window.siyuan.config.keymap.general.goToEditTabNext.custom, event) ||- matchHotKey(window.siyuan.config.keymap.general.goToEditTabPrev.custom, event)) {+ const switchHotkey = [...getKeymapBindings(window.siyuan.config.keymap.general.goToEditTabNext),+ ...getKeymapBindings(window.siyuan.config.keymap.general.goToEditTabPrev)].find(key => matchHotKey(key, event));+ if (switchHotkey) {if (switchDialog && switchDialog.element.parentElement) {+ switchDialog.element.dataset.shortcut = switchHotkey;return;}let tabHtml = "";@@ -1373,6 +1337,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {</div>`,});switchDialog.element.setAttribute("data-key", Constants.DIALOG_SWITCHTAB);+ switchDialog.element.dataset.shortcut = switchHotkey;// 需移走光标,否则编辑器会继续监听并执行按键操作switchDialog.element.querySelector("input").focus();if (isMac()) {@@ -1400,7 +1365,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {}}- if (matchHotKey(window.siyuan.config.keymap.general.recentDocs.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.recentDocs, event)) {openRecentDocs();event.preventDefault();return;@@ -1461,74 +1426,74 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {}/// #endif- if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.syncNow.custom, event)) {+ if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.syncNow, event)) {event.preventDefault();syncGuide(app);return;}- if (matchHotKey(window.siyuan.config.keymap.general.commandPanel.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.commandPanel, event)) {event.preventDefault();commandPanel(app);return;}const editorFontSizeCommand = EDITOR_FONT_SIZE_COMMANDS.find((item) =>- matchHotKey(window.siyuan.config.keymap.general[item.command].custom, event));+ matchHotKey(window.siyuan.config.keymap.general[item.command], event));if (editorFontSizeCommand) {event.preventDefault();adjustEditorFontSize(editorFontSizeCommand.action);return;}- if (matchHotKey(window.siyuan.config.keymap.general.editReadonly.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.editReadonly, event)) {event.preventDefault();editorConfigApi.patch("editor.readOnly", !window.siyuan.config.editor.readOnly);return;}- if (matchHotKey(window.siyuan.config.keymap.general.lockScreen.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.lockScreen, event)) {lockScreen();event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.dataHistory.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.dataHistory, event)) {openHistory(app);event.preventDefault();return;}- if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleDock.custom, event)) {+ if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleDock, event)) {toggleDockBar(document.querySelector("#barDock use"));event.preventDefault();return;}- if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.switchLeftDock.custom, event)) {+ if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.switchLeftDock, event)) {window.siyuan.layout.leftDock.togglePin();event.preventDefault();return;}- if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.switchRightDock.custom, event)) {+ if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.switchRightDock, event)) {window.siyuan.layout.rightDock.togglePin();event.preventDefault();return;}- if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.switchBottomDock.custom, event)) {+ if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.switchBottomDock, event)) {window.siyuan.layout.bottomDock.togglePin();event.preventDefault();return;}- if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleLeftDockPanel.custom, event)) {+ if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleLeftDockPanel, event)) {toggleDockPanel("Left");event.preventDefault();return;}- if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleRightDockPanel.custom, event)) {+ if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleRightDockPanel, event)) {toggleDockPanel("Right");event.preventDefault();return;}- if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleBottomDockPanel.custom, event)) {+ if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.toggleBottomDockPanel, event)) {toggleDockPanel("Bottom");event.preventDefault();return;}- if (!isTabWindow && !window.siyuan.config.readonly && matchHotKey(window.siyuan.config.keymap.general.config.custom, event)) {+ if (!isTabWindow && !window.siyuan.config.readonly && matchHotKey(window.siyuan.config.keymap.general.config, event)) {openSetting(app);event.preventDefault();return;@@ -1538,7 +1503,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {return;}const matchDock = getAllDocks().find(item => {- if (matchHotKey(getDockHotkey(item), event)) {+ if (matchHotKey(getDockKeymap(item), event)) {getDockByType(item.type).toggleModel(item.type);event.preventDefault();return true;@@ -1547,7 +1512,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {if (matchDock) {return;}- if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.riffCard.custom, event)) {+ if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.riffCard, event)) {openCard(app);if (document.activeElement) {(document.activeElement as HTMLElement).blur();@@ -1555,13 +1520,13 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {event.preventDefault();return;}- if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.dailyNote.custom, event)) {+ if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.dailyNote, event)) {newDailyNote(app);event.stopPropagation();event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.newFile.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.newFile, event)) {newFile(app);event.preventDefault();return;@@ -1683,26 +1648,26 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {return;}- if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.mainMenu.custom, event)) {+ if (!isTabWindow && matchHotKey(window.siyuan.config.keymap.general.mainMenu, event)) {workspaceMenu(app, document.querySelector("#barWorkspace").getBoundingClientRect());event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goForward.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.goForward, event)) {goForward(app);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goBack.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.goBack, event)) {goBack(app);event.preventDefault();return;}// close tab- if (matchHotKey(window.siyuan.config.keymap.general.closeTab.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.closeTab, event) && !event.repeat) {execByCommand({command: "closeTab"});@@ -1710,7 +1675,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {return;}- if (matchHotKey(window.siyuan.config.keymap.general.recentClosed.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.recentClosed, event)) {execByCommand({command: "recentClosed",app@@ -1719,133 +1684,133 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {return;}- if (matchHotKey(window.siyuan.config.keymap.general.goToTab1.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToTab1, event) && !event.repeat) {switchTabByIndex(0);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goToTab2.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToTab2, event) && !event.repeat) {switchTabByIndex(1);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goToTab3.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToTab3, event) && !event.repeat) {switchTabByIndex(2);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goToTab4.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToTab4, event) && !event.repeat) {switchTabByIndex(3);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goToTab5.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToTab5, event) && !event.repeat) {switchTabByIndex(4);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goToTab6.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToTab6, event) && !event.repeat) {switchTabByIndex(5);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goToTab7.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToTab7, event) && !event.repeat) {switchTabByIndex(6);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goToTab8.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToTab8, event) && !event.repeat) {switchTabByIndex(7);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goToTab9.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToTab9, event) && !event.repeat) {switchTabByIndex(-1);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goToTabNext.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToTabNext, event) && !event.repeat) {switchTabByIndex(-3);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.goToTabPrev.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToTabPrev, event) && !event.repeat) {switchTabByIndex(-2);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.closeOthers.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.closeOthers, event) && !event.repeat) {execByCommand({command: "closeOthers"});event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.closeAll.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.closeAll, event) && !event.repeat) {execByCommand({command: "closeAll"});event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.closeUnmodified.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.closeUnmodified, event) && !event.repeat) {execByCommand({command: "closeUnmodified"});event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.closeLeft.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.closeLeft, event) && !event.repeat) {execByCommand({command: "closeLeft"});event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.closeRight.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.closeRight, event) && !event.repeat) {execByCommand({command: "closeRight"});event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.splitLR.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.splitLR, event) && !event.repeat) {event.preventDefault();globalCommand("splitLR", app);return;}- if (matchHotKey(window.siyuan.config.keymap.general.splitMoveR.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.splitMoveR, event) && !event.repeat) {event.preventDefault();globalCommand("splitMoveR", app);return;}- if (matchHotKey(window.siyuan.config.keymap.general.splitTB.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.splitTB, event) && !event.repeat) {event.preventDefault();globalCommand("splitTB", app);return;}- if (matchHotKey(window.siyuan.config.keymap.general.tabToWindow.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.tabToWindow, event) && !event.repeat) {event.preventDefault();globalCommand("tabToWindow", app);return;}- if (matchHotKey(window.siyuan.config.keymap.general.splitMoveB.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.splitMoveB, event) && !event.repeat) {event.preventDefault();globalCommand("splitMoveB", app);return;}- if (matchHotKey(window.siyuan.config.keymap.general.stickSearch.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.stickSearch, event)) {globalCommand("stickSearch", app);event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.unsplit.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.unsplit, event) && !event.repeat) {event.preventDefault();globalCommand("unsplit", app);return;}- if (matchHotKey(window.siyuan.config.keymap.general.unsplitAll.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.general.unsplitAll, event) && !event.repeat) {event.preventDefault();globalCommand("unsplitAll", app);return;@@ -1864,28 +1829,11 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {return;}- let matchedCommand: ICommand | undefined;- app.plugins.find(item => {- item.commands.find(command => {- if (supportsPluginCommandSource(command, "shortcut") && matchHotKey(command.customHotkey, event)) {- matchedCommand = command;- return true;- }- });- return Boolean(matchedCommand);- });- if (matchedCommand) {- const commandContext = captureCommandContext({app, source: "shortcut"});- const callback = resolvePluginCommandCallback(matchedCommand, commandContext);- if (callback) {- void callback();- event.stopPropagation();- event.preventDefault();- return true;- }+ if (dispatchPluginShortcut(app, event, "shortcut", () => captureShortcutContext(app, event))) {+ return true;}- if (matchHotKey(window.siyuan.config.keymap.general.replace.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.replace, event)) {execByCommand({command: "replace",app,@@ -1893,7 +1841,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.general.globalSearch.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.globalSearch, event)) {execByCommand({command: "globalSearch",app,@@ -1901,7 +1849,7 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {event.preventDefault();return;}- if (!hasClosestByClassName(target, "pdf__outer") && matchHotKey(window.siyuan.config.keymap.general.search.custom, event)) {+ if (!hasClosestByClassName(target, "pdf__outer") && matchHotKey(window.siyuan.config.keymap.general.search, event)) {execByCommand({command: "search",app,diff --git a/app/src/boot/globalEvent/keyup.ts b/app/src/boot/globalEvent/keyup.tsindex b58011c2f5..0ff27bfa0a 100644--- a/app/src/boot/globalEvent/keyup.ts+++ b/app/src/boot/globalEvent/keyup.ts@@ -1,3 +1,4 @@+import {getKeymapBindings} from "../../util/keymapBindings";import {fetchPost} from "../../util/fetch";import {escapeHtml} from "../../util/escape";import {openCard} from "../../card/openCard";@@ -19,11 +20,13 @@ export const windowKeyUp = (app: App, event: KeyboardEvent) => {}});if (switchDialog && switchDialog.element.parentElement) {- if (window.siyuan.config.keymap.general.goToEditTabNext.custom.endsWith(Constants.KEYCODELIST[event.keyCode]) ||- window.siyuan.config.keymap.general.goToEditTabPrev.custom.endsWith(Constants.KEYCODELIST[event.keyCode])) {+ const activeHotkeys = switchDialog.element.dataset.shortcut ? [switchDialog.element.dataset.shortcut] :+ [...getKeymapBindings(window.siyuan.config.keymap.general.goToEditTabNext),+ ...getKeymapBindings(window.siyuan.config.keymap.general.goToEditTabPrev)];+ if (activeHotkeys.some(key => key.endsWith(Constants.KEYCODELIST[event.keyCode]))) {let currentLiElement = switchDialog.element.querySelector(".b3-list-item--focus");currentLiElement.classList.remove("b3-list-item--focus");- if (matchHotKey(window.siyuan.config.keymap.general.goToEditTabPrev.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToEditTabPrev, event)) {while (true) {if (currentLiElement.previousElementSibling) {currentLiElement = currentLiElement.previousElementSibling;@@ -93,13 +96,12 @@ export const windowKeyUp = (app: App, event: KeyboardEvent) => {if (originalElement) {originalElement.removeAttribute("data-original");}- } else if (window.siyuan.config.keymap.general.goToEditTabNext.custom.startsWith(Constants.KEYCODELIST[event.keyCode]) ||- window.siyuan.config.keymap.general.goToEditTabPrev.custom.startsWith(Constants.KEYCODELIST[event.keyCode])) {+ } else if (activeHotkeys.some(key => key.startsWith(Constants.KEYCODELIST[event.keyCode]))) {let currentLiElement = switchDialog.element.querySelector(".b3-list-item--focus");// 快速切换时,不触发 Tabif (currentLiElement.getAttribute("data-original")) {currentLiElement.classList.remove("b3-list-item--focus");- if (matchHotKey(window.siyuan.config.keymap.general.goToEditTabPrev.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.goToEditTabPrev, event)) {// 上一个if (currentLiElement.previousElementSibling) {currentLiElement.previousElementSibling.classList.add("b3-list-item--focus");diff --git a/app/src/boot/globalEvent/searchKeydown.ts b/app/src/boot/globalEvent/searchKeydown.tsindex 86b019de18..69c2740063 100644--- a/app/src/boot/globalEvent/searchKeydown.ts+++ b/app/src/boot/globalEvent/searchKeydown.ts@@ -62,7 +62,7 @@ export const searchKeydown = (app: App, event: KeyboardEvent) => {const searchType = assetsElement.classList.contains("fn__none") ? (unRefElement.classList.contains("fn__none") ? "doc" : "unRef") : "asset";const listElement = searchType === "asset" ? assetsElement.querySelector("#searchAssetList") : (searchType === "doc" ? element.querySelector("#searchList") : unRefElement.querySelector("#searchUnRefList"));const searchInputElement = element.querySelector("#searchInput") as HTMLInputElement;- if (searchType === "doc" && matchHotKey(window.siyuan.config.keymap.general.newFile.custom, event)) {+ if (searchType === "doc" && matchHotKey(window.siyuan.config.keymap.general.newFile, event)) {if (config.method === 0) {newFile(app, searchInputElement.value);}@@ -98,7 +98,7 @@ export const searchKeydown = (app: App, event: KeyboardEvent) => {return false;}if (searchType !== "asset") {- if (matchHotKey(window.siyuan.config.keymap.editor.general.insertRight.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.insertRight, event)) {openSearchEditor({protyle: edit.protyle,rootId: currentList.getAttribute("data-root-id"),@@ -124,27 +124,27 @@ export const searchKeydown = (app: App, event: KeyboardEvent) => {});return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockRef.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockRef, event)) {fetchPost("/api/block/getRefText", {id}, (response) => {writeText(`((${id} '${response.data}'))`);});return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockEmbed.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockEmbed, event)) {writeText(`{{select * from blocks where id='${id}'}}`);return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocol.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocol, event)) {writeText(`siyuan://blocks/${id}`);return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocolInMd.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocolInMd, event)) {fetchPost("/api/block/getRefText", {id}, (response) => {writeText(`[${response.data}](siyuan://blocks/${id})`);});return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyHPath.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyHPath, event)) {fetchPost("/api/filetree/getHPathByID", {id}, (response) => {@@ -152,7 +152,7 @@ export const searchKeydown = (app: App, event: KeyboardEvent) => {});return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyID.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyID, event)) {writeText(id);return true;}diff --git a/app/src/boot/onGetConfig.ts b/app/src/boot/onGetConfig.tsindex 40c628ef6a..d5d8595455 100644--- a/app/src/boot/onGetConfig.ts+++ b/app/src/boot/onGetConfig.ts@@ -1,6 +1,6 @@import {adjustLayout, exportLayout, JSONToLayout, resetLayout, resizeTopBar} from "../layout/util";import {resizeTabs, setTabPosition} from "../layout/tabUtil";-import {initWindowOpenOverride, isWindows, setStorageVal} from "../protyle/util/compatibility";+import {initWindowOpenOverride, isMac, isWindows, setStorageVal, updateHotkeyTip} from "../protyle/util/compatibility";/// #if !BROWSERimport {initNativeDialogOverride} from "../protyle/util/compatibility";/// #endif@@ -223,8 +223,13 @@ export const initWindow = async (app: App) => {onWindowsMsg(ipcData);});ipcRenderer.on(Constants.SIYUAN_HOTKEY, (e, data) => {- if (!isWindow()) {- dispatchPluginGlobalShortcut(app.plugins, data.hotkey);+ if (Array.isArray(data.failed)) {+ if (data.failed.length) {+ showMessage(window.siyuan.languages.keymapSystemScope + " " + window.siyuan.languages.conflict ++ " [" + data.failed.map(updateHotkeyTip).join("] [") + "]");+ }+ } else if (!isWindow()) {+ dispatchPluginGlobalShortcut(app.plugins, data.hotkey, window.siyuan.config.keymap.plugin, isMac());}});ipcRenderer.on(Constants.SIYUAN_EXPORT_PDF, async (e, ipcData) => {diff --git a/app/src/command/registry.test.ts b/app/src/command/registry.test.tsindex 506bb80f3e..eb28f1bd9c 100644--- a/app/src/command/registry.test.ts+++ b/app/src/command/registry.test.ts@@ -27,6 +27,20 @@ const createCommand = (});describe("command registry", () => {+ it("isolates a throwing availability condition while listing commands", () => {+ const registry = new CommandRegistry();+ registry.register(createCommand("broken", {when: () => { throw new Error("condition"); }}), "broken");+ registry.register(createCommand("available"), "available");+ const original = console.error;+ const errors: unknown[] = [];+ console.error = (...args) => errors.push(args);+ try {+ assert.deepEqual(registry.list(createContext()).map(item => item.id), ["available"]);+ assert.equal(errors.length, 1);+ } finally {+ console.error = original;+ }+ });it("rejects duplicate IDs and unregisters commands by owner", () => {const registry = new CommandRegistry();const firstOwner = {};diff --git a/app/src/command/registry.ts b/app/src/command/registry.tsindex b4d33b31a6..365e4ac9a2 100644--- a/app/src/command/registry.ts+++ b/app/src/command/registry.ts@@ -69,7 +69,14 @@ export class CommandRegistry {public list(context: ICommandContextSnapshot) {return Array.from(this.entries.values())- .filter(entry => isAvailable(entry.command, context))+ .filter(entry => {+ try {+ return isAvailable(entry.command, context);+ } catch (error) {+ console.error(`Command "${entry.command.id}" availability check failed:`, error);+ return false;+ }+ }).sort((first, second) => {const order = (first.command.order ?? 0) - (second.command.order ?? 0);return order || first.sequence - second.sequence;@@ -78,20 +85,27 @@ export class CommandRegistry {}public async execute(id: string, context: ICommandContextSnapshot, args?: unknown): Promise<ICommandExecutionResult> {+ const prepared = this.prepare(id, context, args);+ return prepared.run ? prepared.run() : prepared.result;+ }++ public prepare(id: string, context: ICommandContextSnapshot, args?: unknown): {+ result: ICommandExecutionResult;+ run?: () => Promise<ICommandExecutionResult>;+ } {const command = this.get(id);if (!command) {- return {status: "notFound"};+ return {result: {status: "notFound"}};}if (!isAvailable(command, context)) {- return {status: "unavailable", command};+ return {result: {status: "unavailable", command}};}if (command.enabled && !command.enabled(context)) {- return {status: "disabled", command};+ return {result: {status: "disabled", command}};}return {- status: "executed",- command,- value: await command.execute(context, args),+ result: {status: "executed", command},+ run: async () => ({status: "executed", command, value: await command.execute(context, args)}),};}}diff --git a/app/src/command/shortcutCatalog.ts b/app/src/command/shortcutCatalog.tsnew file mode 100644index 0000000000..28ed8d1ddb--- /dev/null+++ b/app/src/command/shortcutCatalog.ts@@ -0,0 +1,77 @@+export type TShortcutScope = "editor" | "fileTree" | "dock" | "global" | "system";++export const getShortcutId = (path: readonly string[]) => path[0] === "plugin" ?+ `plugin/${encodeURIComponent(path[1])}/${encodeURIComponent(path[2])}` : `core.${path.join(".")}`;++interface IShortcutPlugin {+ name: string;+ commands: Array<{+ langKey: string;+ callback?: unknown;+ execute?: unknown;+ editorCallback?: unknown;+ fileTreeCallback?: unknown;+ dockCallback?: unknown;+ globalCallback?: unknown;+ }>;+}++// 这些命令的快捷键只执行标签页切换,无编辑器局部执行分支。+export const SHARED_NATIVE_SHORTCUTS = [+ "goToTab1", "goToTab2", "goToTab3", "goToTab4", "goToTab5", "goToTab6", "goToTab7", "goToTab8", "goToTab9",+ "goToTabNext", "goToTabPrev",+];++export const getShortcutScopes = (path: readonly string[], plugins: IShortcutPlugin[] = window.siyuan.ws.app.plugins): TShortcutScope[] => {+ if (path[0] === "general" && SHARED_NATIVE_SHORTCUTS.includes(path[1])) {+ return ["global"];+ }+ if (path[0] !== "plugin") {+ return [];+ }+ const command = plugins.find(plugin => plugin.name === path[1])?.commands.find(item => item.langKey === path[2]);+ if (!command) {+ return [];+ }+ const scopes: TShortcutScope[] = [];+ if (command.editorCallback) {+ scopes.push("editor");+ }+ if (command.fileTreeCallback) {+ scopes.push("fileTree");+ }+ if (command.dockCallback) {+ scopes.push("dock");+ }+ if (command.globalCallback) {+ scopes.push("system");+ }+ if (!scopes.length && (command.callback || command.execute)) {+ scopes.push("global");+ }+ return scopes;+};++export const canShareKeymap = (path: readonly string[], plugins?: IShortcutPlugin[]) =>+ getShortcutScopes(path, plugins).length > 0;++export const canShareShortcutPaths = (paths: readonly (readonly string[])[], plugins?: IShortcutPlugin[]) => {+ const scopes = paths.map(path => getShortcutScopes(path, plugins));+ // 系统级注册会先于窗口按键事件触发,共用绑定必须属于相同的触发入口。+ return scopes.every(scope => scope.length > 0 && scope.includes("system") === scopes[0].includes("system"));+};++export interface IShortcutOrder {+ id: string;+ scope: TShortcutScope;+ priority?: number;+ order?: number;+}++export const compareShortcutBindings = (first: IShortcutOrder, second: IShortcutOrder) => {+ const scope = (first.scope === "global" ? 1 : 0) - (second.scope === "global" ? 1 : 0);+ const priority = (Number.isFinite(second.priority) ? second.priority : 0) -+ (Number.isFinite(first.priority) ? first.priority : 0);+ return scope || priority || (first.order ?? 0) - (second.order ?? 0) ||+ (first.id < second.id ? -1 : first.id > second.id ? 1 : 0);+};diff --git a/app/src/command/shortcutResolver.test.ts b/app/src/command/shortcutResolver.test.tsnew file mode 100644index 0000000000..5091b1adac--- /dev/null+++ b/app/src/command/shortcutResolver.test.ts@@ -0,0 +1,92 @@+import * as assert from "node:assert/strict";+import test from "node:test";+import {CommandRegistry} from "./registry";+import {IShortcutCandidate, resolveShortcut} from "./shortcutResolver";+import {canShareKeymap, canShareShortcutPaths, getShortcutScopes} from "./shortcutCatalog";+import type {ICommandContextSnapshot, ICommandDefinition} from "./types";++const context: ICommandContextSnapshot = {app: {}, source: "shortcut", environment: "desktop", focus: "editor", selectedBlocks: []};+const candidate = (id: string, priority = 0, scope: IShortcutCandidate["scope"] = "global"): IShortcutCandidate =>+ ({id, priority, scope, context});+const definition = (id: string, overrides: Partial<ICommandDefinition> = {}): ICommandDefinition =>+ ({id, category: "core", label: () => id, execute: () => undefined, ...overrides});++test("local scope wins before explicit priorities; disabled local commands fall back", async () => {+ const registry = new CommandRegistry();+ let enabled = true;+ registry.register(definition("local", {enabled: () => enabled}), "local");+ registry.register(definition("global"), "global");+ const candidates = [candidate("global", 100), candidate("local", 0, "editor")];+ assert.equal(resolveShortcut(registry, candidates, assert.fail).candidate.id, "local");+ enabled = false;+ assert.equal(resolveShortcut(registry, candidates, assert.fail).candidate.id, "global");+});++test("source, platform, when and enabled are checked before execution", () => {+ const registry = new CommandRegistry();+ registry.register(definition("source", {surfaces: ["menu"]}), "source");+ registry.register(definition("platform", {platform: environment => environment === "mobile"}), "platform");+ registry.register(definition("when", {when: () => false}), "when");+ registry.register(definition("enabled", {enabled: () => false}), "enabled");+ registry.register(definition("available"), "available");+ assert.equal(resolveShortcut(registry, [candidate("source", 4), candidate("platform", 3),+ candidate("when", 2), candidate("enabled", 1), candidate("available")], assert.fail).candidate.id, "available");+});++test("tie breaking survives registration and plugin reload order", () => {+ for (const order of [["b", "a"], ["a", "b"]]) {+ const registry = new CommandRegistry();+ order.forEach(id => registry.register(definition(id), id));+ assert.equal(resolveShortcut(registry, order.map(id => candidate(id)), assert.fail).candidate.id, "a");+ registry.unregisterOwner("a");+ assert.equal(resolveShortcut(registry, order.map(id => candidate(id)), assert.fail).candidate.id, "b");+ registry.register(definition("a"), "a");+ assert.equal(resolveShortcut(registry, order.map(id => candidate(id)), assert.fail).candidate.id, "a");+ }+});++test("preparing a shortcut has no execution side effects and failures never run another candidate", async () => {+ for (const failure of [false, new Error("failed")]) {+ const calls: string[] = [];+ const registry = new CommandRegistry();+ registry.register(definition("first", {execute: async () => {+ calls.push("first");+ if (failure instanceof Error) {+ throw failure;+ }+ return failure;+ }}), "first");+ registry.register(definition("second", {execute: () => calls.push("second")}), "second");+ const prepared = resolveShortcut(registry, [candidate("first", 1), candidate("second")], assert.fail);+ assert.deepEqual(calls, []);+ if (failure instanceof Error) {+ await assert.rejects(prepared.run, /failed/);+ } else {+ assert.equal((await prepared.run()).value, false);+ }+ assert.deepEqual(calls, ["first"]);+ }+});++test("a throwing condition is reported and skipped", () => {+ const errors: unknown[] = [];+ const registry = new CommandRegistry();+ registry.register(definition("first", {when: () => { throw new Error("condition"); }}), "first");+ registry.register(definition("second"), "second");+ assert.equal(resolveShortcut(registry, [candidate("first", 1), candidate("second")], error => errors.push(error)).candidate.id, "second");+ assert.equal(errors.length, 1);+});++test("shared bindings expose only migrated native actions and installed plugin commands", () => {+ assert.equal(canShareKeymap(["general", "goToTab5"], []), true);+ assert.equal(canShareKeymap(["editor", "insert", "bold"], []), false);+ assert.equal(canShareKeymap(["plugin", "missing", "command"], []), false);+ assert.deepEqual(getShortcutScopes(["plugin", "test", "command"], [{name: "test", commands: [{langKey: "command",+ callback: (): void => {}, editorCallback: (): void => {}, globalCallback: (): void => {}}]}]), ["editor", "system"]);+});++test("system-wide bindings cannot shadow application bindings through sharing", () => {+ const plugins = [{name: "test", commands: [{langKey: "system", globalCallback: true}, {langKey: "other", globalCallback: true}]}];+ assert.equal(canShareShortcutPaths([["general", "goToTab5"], ["plugin", "test", "system"]], plugins), false);+ assert.equal(canShareShortcutPaths([["plugin", "test", "other"], ["plugin", "test", "system"]], plugins), true);+});diff --git a/app/src/command/shortcutResolver.ts b/app/src/command/shortcutResolver.tsnew file mode 100644index 0000000000..575f3be017--- /dev/null+++ b/app/src/command/shortcutResolver.ts@@ -0,0 +1,21 @@+import {compareShortcutBindings, IShortcutOrder} from "./shortcutCatalog";+import type {CommandRegistry} from "./registry";+import type {ICommandContextSnapshot} from "./types";++export interface IShortcutCandidate extends IShortcutOrder {+ context: ICommandContextSnapshot;+}++export const resolveShortcut = (registry: CommandRegistry, candidates: IShortcutCandidate[], reportError: (error: unknown) => void) => {+ for (const candidate of [...candidates].sort(compareShortcutBindings)) {+ try {+ const prepared = registry.prepare(candidate.id, candidate.context);+ if (prepared.run) {+ return {candidate, run: prepared.run};+ }+ } catch (error) {+ reportError(error);+ }+ }+ return undefined;+};diff --git a/app/src/command/shortcutRuntime.ts b/app/src/command/shortcutRuntime.tsnew file mode 100644index 0000000000..f2385c54e9--- /dev/null+++ b/app/src/command/shortcutRuntime.ts@@ -0,0 +1,134 @@+import type {App} from "../index";+import {captureCommandContext} from "./context";+import {getCommandRegistry} from "./service";+import type {CommandRegistry} from "./registry";+import {getNativeCommandId} from "./nativeCommands";+import {getPluginCommandId, supportsPluginCommandSource} from "../plugin/commandAdapter";+import {getKeymapBindings, getKeymapItem, visitKeymapItems} from "../util/keymapBindings";+import {matchHotKey} from "../protyle/util/hotKey";+import {canShareShortcutPaths, getShortcutScopes, SHARED_NATIVE_SHORTCUTS} from "./shortcutCatalog";+import {IShortcutCandidate, resolveShortcut} from "./shortcutResolver";+import type {ICommandContextSnapshot, TCommandSource} from "./types";+import {areProtylePluginExtensionsEnabled} from "../protyle/runtimeCapabilities";++const reportError = (error: unknown) => console.error("Shortcut command failed:", error);+const handledEvents = new WeakSet<KeyboardEvent>();++export const captureShortcutContext = (app: App, event: KeyboardEvent) => {+ const target = event.target as HTMLElement;+ const fileTree = target.closest(".sy__file");+ const context = captureCommandContext({app, source: "shortcut",+ fileLiElements: fileTree ? Array.from(fileTree.querySelectorAll(".b3-list-item--focus")) : undefined});+ const textInput = Boolean(target.closest("input, textarea"));+ const editorFocused = !textInput && Boolean(context.protyle?.wysiwyg?.element?.contains(target));+ const dockFocused = !textInput && Boolean(context.dock?.element.contains(target));+ context.focus = editorFocused ? "editor" : fileTree && !textInput ? "fileTree" : dockFocused ? "dock" : "global";+ if (!editorFocused) {+ context.protyle = undefined;+ context.range = undefined;+ context.document = undefined;+ context.block = undefined;+ context.tableCell = undefined;+ context.selectedBlocks = [];+ }+ if (context.focus !== "fileTree") {+ context.fileTree = undefined;+ }+ if (context.focus !== "dock") {+ context.dock = undefined;+ }+ return context;+};++const runCandidates = (app: App, event: KeyboardEvent, candidates: IShortcutCandidate[],+ registry = getCommandRegistry(app)) => {+ const resolved = resolveShortcut(registry, candidates, reportError);+ if (!resolved) {+ return false;+ }+ handledEvents.add(event);+ event.preventDefault();+ event.stopImmediatePropagation();+ void resolved.run().catch(reportError);+ return true;+};++export const dispatchPluginShortcut = (app: App, event: KeyboardEvent,+ source: "shortcut" | "editorShortcut" | "fileTreeShortcut" | "dockShortcut",+ capture: () => ICommandContextSnapshot) => {+ if (handledEvents.has(event)) {+ return true;+ }+ const matches: Array<{id: string; priority?: number}> = [];+ app.plugins.forEach(plugin => plugin.commands.forEach(command => {+ if (!supportsPluginCommandSource(command, source)) {+ return;+ }+ const item = getKeymapItem(window.siyuan.config.keymap, ["plugin", plugin.name, command.langKey]);+ const hotkey = getKeymapBindings(item || {custom: command.customHotkey}).find(key => matchHotKey(key, event));+ if (hotkey) {+ const scope = ({shortcut: "global", editorShortcut: "editor", fileTreeShortcut: "fileTree", dockShortcut: "dock"})[source];+ matches.push({id: getPluginCommandId(plugin.name, command.langKey),+ priority: item?.bindings?.priority?.[`${scope}:${hotkey}`]});+ }+ }));+ if (!matches.length) {+ return false;+ }+ const context = capture();+ return runCandidates(app, event, matches.map(item => ({...item, context,+ scope: source === "shortcut" ? "global" : context.focus})));+};++// 共用绑定在捕获阶段统一选择;未接入的按键继续使用原有事件入口。+export const dispatchSharedShortcut = (app: App, event: KeyboardEvent, ensureCommands: () => CommandRegistry) => {+ if (handledEvents.has(event) || event.defaultPrevented || event.isComposing || !event.key ||+ (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && !/^F\d{1,2}$/.test(event.key))) {+ return false;+ }+ const target = event.target as HTMLElement;+ if (target.closest(".config-keymap, .b3-menu, .av__panel, .av__mask") ||+ document.getElementById("progress") || document.getElementById("errorLog")) {+ return false;+ }+ const matches: Array<{path: string[]; hotkey: string; priorities?: Record<string, number>}> = [];+ visitKeymapItems(window.siyuan.config.keymap, (item, path) => {+ const hotkey = getKeymapBindings(item).find(key => matchHotKey(key, event));+ if (hotkey) {+ matches.push({path, hotkey, priorities: item.bindings?.priority});+ }+ });+ if (matches.length < 2 || !canShareShortcutPaths(matches.map(item => item.path), app.plugins)) {+ return false;+ }+ const context = captureShortcutContext(app, event);+ const candidates: IShortcutCandidate[] = [];+ const sources: Record<string, TCommandSource> = {+ global: "shortcut", editor: "editorShortcut", fileTree: "fileTreeShortcut", dock: "dockShortcut",+ };+ matches.forEach(({path, hotkey, priorities}) => {+ const scopes = getShortcutScopes(path, app.plugins);+ const scope = scopes.includes(context.focus) ? context.focus : scopes.includes("global") ? "global" : undefined;+ if (!scope || (scope === "editor" && (!context.protyle || !areProtylePluginExtensionsEnabled(context.protyle)))) {+ return;+ }+ if (["mobile", "browser-mobile"].includes(context.environment) && scope !== "global") {+ return;+ }+ const priority = priorities?.[`${scope}:${hotkey}`];+ if (path[0] === "general") {+ if (event.repeat || !SHARED_NATIVE_SHORTCUTS.includes(path[1])) {+ return;+ }+ candidates.push({id: getNativeCommandId(path[1]), context, scope, priority});+ } else {+ candidates.push({id: getPluginCommandId(path[1], path[2]),+ context: {...context, source: sources[scope]}, scope, priority});+ }+ });+ if (!runCandidates(app, event, candidates, ensureCommands())) {+ // 已仲裁的共用绑定不再进入旧命令分支,浏览器默认输入仍可继续。+ event.stopImmediatePropagation();+ }+ return true;+};diff --git a/app/src/config/tabs/keymapRow.ts b/app/src/config/tabs/keymapRow.tsnew file mode 100644index 0000000000..2f480f50d8--- /dev/null+++ b/app/src/config/tabs/keymapRow.ts@@ -0,0 +1,36 @@+import {updateHotkeyTip} from "../../protyle/util/compatibility";+import {escapeAttr, escapeHtml} from "../../util/escape";+import {getDefaultKeymapBindings, getKeymapBindings, IShortcutKeymap} from "../../util/keymapBindings";++const attr = (text: string) => escapeAttr(escapeHtml(text));++export const keymapActionHtml = (type: string, icon: string, label: string, extra = "") =>+ `<button type="button" data-type="${type}" class="config-keymap__action b3-list-item__action b3-tooltips b3-tooltips__w" aria-label="${attr(label)}" ${extra}><svg><use xlink:href="#${icon}"></use></svg></button>`;++export const keymapBindingsHtml = (keys: string[], defaults: string[]) => {+ const languages = window.siyuan.languages;+ const changed = JSON.stringify(keys) !== JSON.stringify(defaults);+ return `<div class="config-keymap__bindings">${keys.map((key, index) =>+ `<span class="config-keymap__key config-keymap__chip" data-index="${index}">+ <button type="button" data-type="update" class="config-keymap__text" aria-label="${attr(languages.keymap + ": " + updateHotkeyTip(key))}">${escapeHtml(updateHotkeyTip(key))}</button>+ <button type="button" data-type="remove" class="b3-chip__close config-keymap__remove ariaLabel" aria-label="${attr(languages.remove)}"><svg><use xlink:href="#iconClose"></use></svg></button>+ </span>`).join("")}</div>+ ${keymapActionHtml("reset", "iconUndo", languages.reset, changed ? "" : 'style="display:none" tabindex="-1"')}+ ${keymapActionHtml("add", "iconAdd", languages.keymapRecording)}`;+};++export const genKeymapRowHtml = (label: string, dataKey: string, item: IShortcutKeymap) => {+ const keys = getKeymapBindings(item);+ return `<div class="b3-list-item b3-list-item--narrow b3-list-item--hide-action config-keymap__row" data-key="${attr(dataKey)}" data-keys="${attr(JSON.stringify(keys))}" data-defaults="${attr(JSON.stringify(getDefaultKeymapBindings(item)))}">+ <span class="b3-list-item__text">${escapeHtml(label)}</span>+ <div class="config-keymap__controls">${keymapBindingsHtml(keys, getDefaultKeymapBindings(item))}</div>+ <div class="config-keymap__shared fn__none"></div>+ </div>`;+};++export const getRowBindings = (row: HTMLElement): string[] => JSON.parse(row.dataset.keys);++export const renderRowBindings = (row: HTMLElement, keys: string[]) => {+ row.dataset.keys = JSON.stringify(keys);+ row.querySelector(".config-keymap__controls").innerHTML = keymapBindingsHtml(keys, JSON.parse(row.dataset.defaults));+};diff --git a/app/src/config/tabs/keymapUi.ts b/app/src/config/tabs/keymapUi.tsindex 7d63382496..ba93ad9243 100644--- a/app/src/config/tabs/keymapUi.ts+++ b/app/src/config/tabs/keymapUi.ts@@ -1,11 +1,8 @@-/// #if !BROWSER-import {ipcRenderer} from "electron";-/// #endifimport {isMac, updateHotkeyTip} from "../../protyle/util/compatibility";import {matchHotKey} from "../../protyle/util/hotKey";import {Constants} from "../../constants";import {hideMessage, showMessage} from "../../dialog/message";-import {fetchPost} from "../../util/fetch";+import {fetchSyncPost} from "../../util/fetch";import {exportLayout} from "../../layout/util";import {updateDockHotkeys} from "../../layout/dock/util";import {confirmDialog} from "../../dialog/confirmDialog";@@ -15,9 +12,14 @@ import {normalizeSearchText} from "../search/normalize";import {genButtonRowHtml, genConfigGroup} from "../render/render";import type {Plugin} from "../../plugin";import {isDisallowedTextInputHotkey, isReservedKeymap} from "../../util/hotKeyPolicy";-import {isWindow} from "../../util/functions";import {resolvePluginToolbar} from "../../plugin/toolbarItem";-import {ensurePluginKeymap, setPluginKeymapCustom} from "../../plugin/keymap";+import {ensurePluginKeymap} from "../../plugin/keymap";+import {getKeymapBindings, getKeymapItem, setKeymapBindings, visitKeymapItems, normalizeShortcutKey} from "../../util/keymapBindings";+import {genKeymapRowHtml, getRowBindings, renderRowBindings} from "./keymapRow";+import {escapeAttr, escapeHtml} from "../../util/escape";+import {canShareShortcutPaths, getShortcutScopes, compareShortcutBindings, getShortcutId} from "../../command/shortcutCatalog";+import {Menu} from "../../plugin/Menu";+const keymapToolbarSearchStrings = (): string[] => [window.siyuan.languages.keymapTip,window.siyuan.languages.keymapTip2,@@ -54,29 +56,20 @@ const bindKeymapToolbar = (root: HTMLElement) => {});root.querySelector("#keymapResetBtn")?.addEventListener("click", () => {confirmDialog("⚠️ " + window.siyuan.languages.reset, window.siyuan.languages.confirmReset, () => {- fetchPost("/api/setting/setKeymap", {- data: Constants.SIYUAN_KEYMAP,- }, () => {- /// #if !BROWSER- ipcRenderer.send(Constants.SIYUAN_CMD, {- cmd: "writeLog",- msg: "user reset keymap",- });- if (!isWindow() && window.siyuan.config.keymap.general.toggleWin.default !==- window.siyuan.config.keymap.general.toggleWin.custom) {- ipcRenderer.send(Constants.SIYUAN_CMD, {- cmd: "unregisterGlobalShortcut",- accelerator: window.siyuan.config.keymap.general.toggleWin.custom,- });+ keymapSaveQueue = keymapSaveQueue.then(async () => {+ try {+ const data = JSON.parse(JSON.stringify(Constants.SIYUAN_KEYMAP));+ const response = await fetchSyncPost("/api/setting/setKeymap", {data});+ if (response.code !== 0) {+ throw new Error(response.msg);+ }+ savedKeymap = data;+ applyKeymap(data);+ void exportLayout({cb: () => window.location.reload(), errorExit: false});+ } catch (error) {+ console.error("Could not reset shortcuts:", error);+ showMessage(window.siyuan.languages.keymapSaveFailed);}- sendGlobalShortcut(window.siyuan.ws.app);- /// #endif- void exportLayout({- cb() {- window.location.reload();- },- errorExit: false,- });});});});@@ -230,21 +223,6 @@ const genKeymapListHtml = () => {</div>`;};-const genKeymapRowHtml = (label: string, dataKey: string, custom: string, defaultValue: string) => {- const keyValue = updateHotkeyTip(custom);- return `<label class="b3-list-item b3-list-item--narrow b3-list-item--hide-action">- <span class="b3-list-item__text">${label}</span>- <span data-type="reset" class="b3-list-item__action b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.reset}">- <svg><use xlink:href="#iconUndo"></use></svg>- </span>- <span data-type="clear" class="b3-list-item__action b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.remove}">- <svg><use xlink:href="#iconTrashcan"></use></svg>- </span>- <span data-type="update" class="config-keymap__key">${keyValue}</span>- <input data-key="${dataKey}" data-value="${custom}" data-default="${defaultValue}" class="b3-text-field fn__none" value="${keyValue}" spellcheck="false" autocomplete="off" inputmode="none" readonly>-</label>`;-};-/** 编辑器快捷键分组,与 {@link Config.IKeymapEditor} 的键一致 */const EDITOR_KEYMAP_SEGMENTS = ["general", "insert", "heading", "list", "table"] as const satisfies readonly (keyof Config.IKeymapEditor)[];@@ -281,7 +259,7 @@ const genKeymapItem = (keys: string) => {continue;}const item = config[key] ?? template[key];- html.push(genKeymapRowHtml(window.siyuan.languages[key], keys + Constants.ZWSP + key, item.custom, item.default));+ html.push(genKeymapRowHtml(window.siyuan.languages[key], keys + Constants.ZWSP + key, item));}return html.join("");};@@ -311,8 +289,7 @@ const buildKeymapPluginCommandHtml = (item: Plugin) => {html.push(genKeymapRowHtml(command.langText || (item.i18n ? item.i18n[command.langKey] : "") || command.langKey,pluginKeyPrefix + command.langKey,- command.customHotkey,- command.hotkey,+ ensurePluginKeymap(item.name, command.langKey, command.hotkey),));}@@ -324,8 +301,7 @@ const buildKeymapPluginCommandHtml = (item: Plugin) => {html.push(genKeymapRowHtml(toolbarItem.tip || window.siyuan.languages[toolbarItem.lang],pluginKeyPrefix + toolbarItem.name,- toolbarKeymap.custom,- toolbarKeymap.default,+ toolbarKeymap,));}@@ -334,8 +310,7 @@ const buildKeymapPluginCommandHtml = (item: Plugin) => {html.push(genKeymapRowHtml(item.docks[key].config.title,pluginKeyPrefix + key,- dockKeymap.custom,- dockKeymap.default,+ dockKeymap,));}return html.join("");@@ -376,140 +351,187 @@ const bindKeymapList = (root: HTMLElement) => {searchKeymapElement.dataset.keymap = "";resetKeymapList(keymapListElement);});- keymapListElement.addEventListener("click", (event) => {- let target = event.target as HTMLElement;- while (target && !target.isEqualNode(keymapListElement)) {- const type = target.getAttribute("data-type");- if (type === "reset") {- const inputElement = target.parentElement.querySelector(".b3-text-field") as HTMLInputElement;- inputElement.value = updateHotkeyTip(inputElement.getAttribute("data-default"));- inputElement.setAttribute("data-value", inputElement.getAttribute("data-default"));- inputElement.previousElementSibling.textContent = inputElement.value;- setKeymapFromDom(root);- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "clear") {- const inputElement = target.parentElement.querySelector(".b3-text-field") as HTMLInputElement;- inputElement.value = "";- inputElement.previousElementSibling.textContent = "";- inputElement.setAttribute("data-value", "");- setKeymapFromDom(root);- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "update") {- target.classList.add("fn__none");- const inputElement = target.nextElementSibling as HTMLInputElement;- inputElement.classList.remove("fn__none");- inputElement.focus();- event.preventDefault();- event.stopPropagation();- break;- } else if (target.classList.contains("b3-list-item--hide-action")) {- const inputElement = target.querySelector(".b3-text-field") as HTMLInputElement;- inputElement.classList.remove("fn__none");- inputElement.focus();- inputElement.previousElementSibling.classList.add("fn__none");- event.preventDefault();- event.stopPropagation();- break;- } else if (target.classList.contains("toggle")) {- if (target.nextElementSibling.classList.contains("fn__none")) {- target.firstElementChild.firstElementChild.classList.add("b3-list-item__arrow--open");- target.nextElementSibling.classList.remove("fn__none");- } else {- target.firstElementChild.firstElementChild.classList.remove("b3-list-item__arrow--open");- target.nextElementSibling.classList.add("fn__none");- }- event.preventDefault();- event.stopPropagation();- break;- }- target = target.parentElement;+ let recording: {row: HTMLElement; input: HTMLInputElement; index: number} | undefined;+ const outsideRecording = (event: PointerEvent) => {+ if (recording && event.target !== recording.input &&+ !(event.target as HTMLElement).closest(".config-keymap__controls")) {+ cancelRecording();+ refreshShared();+ }+ };+ const cancelRecording = (restoreFocus = false) => {+ if (!recording) {+ return;+ }+ const {row} = recording;+ recording = undefined;+ document.removeEventListener("pointerdown", outsideRecording, true);+ renderRowBindings(row, getRowBindings(row));+ hideMessage("keymapInvalid");+ hideMessage("keymapConflict");+ sendGlobalShortcut(window.siyuan.ws.app);+ if (restoreFocus) {+ row.querySelector<HTMLButtonElement>('[data-type="add"]').focus();+ }+ };+ const refreshShared = () => refreshSharedBindings(root);+ const saveRow = (row: HTMLElement, keys: string[], reset = false) => {+ renderRowBindings(row, keys);+ saveKeymapRow(root, row, keys, reset ? data => {+ delete getKeymapItem(data, row.dataset.key.split(Constants.ZWSP)).bindings.priority;+ } : undefined);+ refreshShared();+ };+ keymapListElement.addEventListener("pointerdown", (event) => {+ if (recording && (event.target as HTMLElement).closest(".config-keymap__controls") &&+ event.target !== recording.input) {+ event.preventDefault();}});- let timeout: number;- const getKeymapInput = (target: EventTarget | null): HTMLInputElement | null =>- (target as HTMLElement)?.closest?.("label.b3-list-item")?.querySelector("input") as HTMLInputElement || null;- keymapListElement.addEventListener("keydown", (event: KeyboardEvent) => {- const inputElement = getKeymapInput(event.target);- if (!inputElement) {+ keymapListElement.addEventListener("contextmenu", (event: MouseEvent) => {+ const chip = (event.target as HTMLElement).closest<HTMLElement>(".config-keymap__chip");+ if (!chip || recording) {return;}+ const index = Number(chip.dataset.index);+ if (index === 0) {+ return;+ }+ event.preventDefault();event.stopPropagation();+ const row = chip.closest<HTMLElement>(".config-keymap__row");+ const menu = new Menu();+ menu.addItem({label: window.siyuan.languages.keymapPrimary, click: () => {+ const keys = getRowBindings(row);+ keys.unshift(keys.splice(index, 1)[0]);+ saveRow(row, keys);+ }});+ menu.open({x: event.clientX, y: event.clientY});+ });+ keymapListElement.addEventListener("click", (event) => {+ const target = event.target as HTMLElement;+ const action = target.closest<HTMLElement>("[data-type]");+ const row = target.closest<HTMLElement>(".config-keymap__row");+ const toggle = target.closest<HTMLElement>(".toggle");+ if (toggle) {+ const hidden = toggle.nextElementSibling.classList.toggle("fn__none");+ toggle.querySelector(".b3-list-item__arrow").classList.toggle("b3-list-item__arrow--open", !hidden);+ }+ if (!row || !action) {+ return;+ }event.preventDefault();- const keymapStr = getKeymapString(event);- const adoptKeymapStr = updateHotkeyTip(keymapStr);- clearTimeout(timeout);- timeout = window.setTimeout(() => {- const keys = inputElement.getAttribute("data-key").split(Constants.ZWSP);- let hasConflict = false;- if (["⌘", "⇧", "⌥", "⌃"].includes(keymapStr.at(-1) ?? "")) {- hasConflict = true;- }- if (- !hasConflict && (isDisallowedTextInputHotkey(keymapStr) || isReservedKeymap(keymapStr, keys) ||- !matchHotKey(keymapStr, event) ||- (isMac() && keys[0] === "general" && ["goToEditTabNext", "goToEditTabPrev"].includes(keys[1]) && keymapStr.includes("⌘")))- ) {- showMessage(`${window.siyuan.languages.invalid} [${adoptKeymapStr}]`, undefined, undefined, "keymapInvalid");- hasConflict = true;+ event.stopPropagation();+ const index = Number(action.closest<HTMLElement>("[data-index]")?.dataset.index ?? -1);+ const type = action.dataset.type;+ cancelRecording();+ const keys = getRowBindings(row);+ if (type === "reset") {+ saveRow(row, JSON.parse(row.dataset.defaults), true);+ } else if (type === "remove") {+ keys.splice(index, 1);+ saveRow(row, keys);+ row.querySelector<HTMLButtonElement>('[data-type="add"]').focus();+ } else if (type === "add" || type === "update") {+ const input = document.createElement("input");+ input.className = "b3-text-field config-keymap__record";+ input.readOnly = true;+ input.spellcheck = false;+ input.autocomplete = "off";+ input.inputMode = "none";+ input.placeholder = window.siyuan.languages.keymapRecording;+ input.setAttribute("aria-label", window.siyuan.languages.keymapRecording);+ if (type === "update") {+ row.querySelector(`[data-index="${index}"]`).replaceWith(input);} else {- hideMessage("keymapInvalid");+ row.querySelector(".config-keymap__bindings").append(input);}- if (!hasConflict) {- const conflictTips: string[] = [];- for (const inputItem of root.querySelectorAll<HTMLInputElement>(`label.b3-list-item input[data-value="${CSS.escape(keymapStr)}"]`)) {- if (inputItem === inputElement) {- continue;- }- const thirdElement = inputItem.parentElement;- const secondElement = thirdElement.parentElement.previousElementSibling;- const firstElement = secondElement.parentElement.previousElementSibling;- const tipParts: string[] = [];- if (firstElement.classList.contains("b3-list-item")) {- tipParts.push(firstElement.textContent.trim());- }- tipParts.push(secondElement.textContent.trim());- tipParts.push(thirdElement.querySelector(".b3-list-item__text").textContent.trim());- conflictTips.push(tipParts.join("-"));- }- // 目前插件注册的命令没有限制跟已有命令重复,所以这里可能有多个冲突- if (conflictTips.length > 0) {- showMessage(`${adoptKeymapStr} ${window.siyuan.languages.conflict} [${conflictTips.join("] [")}]`, undefined, undefined, "keymapConflict");- hasConflict = true;- } else {- hideMessage("keymapConflict");- }- }- if (hasConflict) {- inputElement.value = updateHotkeyTip(inputElement.getAttribute("data-value"));- return;- }- inputElement.setAttribute("data-value", keymapStr);- inputElement.value = adoptKeymapStr;- setKeymapFromDom(root);- }, Constants.TIMEOUT_TRANSITION);+ recording = {row, input, index: type === "update" ? index : -1};+ document.addEventListener("pointerdown", outsideRecording, true);+ row.querySelector('[data-type="add"]').classList.add("config-keymap__action--active");+ sendUnregisterGlobalShortcut(window.siyuan.ws.app);+ input.focus();+ } else if (type === "shared") {+ const detail = row.querySelector<HTMLElement>(".config-keymap__shared");+ const hidden = detail.classList.toggle("fn__none");+ action.setAttribute("aria-expanded", String(!hidden));+ } else if (type === "priority-up" || type === "priority-down") {+ moveSharedBinding(root, row, action, type === "priority-up" ? -1 : 1);+ refreshShared();+ }});- keymapListElement.addEventListener("focusout", (event: FocusEvent) => {- const inputElement = getKeymapInput(event.target);- if (!inputElement) {+ keymapListElement.addEventListener("keydown", (event: KeyboardEvent) => {+ if (!recording || event.target !== recording.input) {return;}- sendGlobalShortcut(window.siyuan.ws.app);- setTimeout(() => {- inputElement.classList.add("fn__none");- inputElement.previousElementSibling.textContent = inputElement.value;- inputElement.previousElementSibling.classList.remove("fn__none");- }, Constants.TIMEOUT_INPUT);- });- keymapListElement.addEventListener("focusin", (event: FocusEvent) => {- if (!getKeymapInput(event.target)) {+ event.preventDefault();+ event.stopImmediatePropagation();+ if (event.key === "Escape") {+ cancelRecording(true);return;}- sendUnregisterGlobalShortcut(window.siyuan.ws.app);+ if (event.repeat) {+ return;+ }+ const hotkey = getKeymapString(event);+ if (!hotkey || ["⌘", "⇧", "⌥", "⌃"].includes(hotkey.at(-1))) {+ return;+ }+ const {row, index, input} = recording;+ const path = row.dataset.key.split(Constants.ZWSP);+ if (isDisallowedTextInputHotkey(hotkey) || isReservedKeymap(hotkey, path) ||+ !matchHotKey(hotkey, event) ||+ (isMac() && path[0] === "general" && ["goToEditTabNext", "goToEditTabPrev"].includes(path[1]) && hotkey.includes("⌘"))) {+ input.setAttribute("aria-invalid", "true");+ showMessage(`${window.siyuan.languages.invalid} [${updateHotkeyTip(hotkey)}]`, undefined, undefined, "keymapInvalid");+ return;+ }+ const conflicts: string[] = [];+ visitKeymapItems(window.siyuan.config.keymap, (item, otherPath) => {+ if (otherPath.join(Constants.ZWSP) !== row.dataset.key &&+ getKeymapBindings(item).some(key => matchHotKey(key, event)) &&+ !canShareShortcutPaths([path, otherPath])) {+ const otherRow = Array.from(root.querySelectorAll<HTMLElement>(".config-keymap__row"))+ .find(candidate => candidate.dataset.key === otherPath.join(Constants.ZWSP));+ conflicts.push(otherRow?.querySelector(".b3-list-item__text").textContent || otherPath.join(" - "));+ }+ });+ if (conflicts.length) {+ showMessage(`${window.siyuan.languages.keymapLegacyConflict} [${conflicts.map(escapeHtml).join("] [")}]`, undefined, undefined, "keymapConflict");+ return;+ }+ const keys = getRowBindings(row);+ const duplicate = keys.findIndex((key, keyIndex) => keyIndex !== index && matchHotKey(key, event));+ cancelRecording();+ if (duplicate !== -1) {+ row.querySelector<HTMLButtonElement>(`[data-index="${duplicate}"] [data-type="update"]`).focus();+ return;+ }+ if (index < 0) {+ keys.push(hotkey);+ } else {+ keys[index] = hotkey;+ }+ saveRow(row, keys);+ row.querySelector<HTMLButtonElement>('[data-type="add"]').focus();+ }, true);+ keymapListElement.addEventListener("keyup", (event: KeyboardEvent) => {+ if ((event.target as HTMLElement).closest(".config-keymap__controls")) {+ event.stopPropagation();+ }+ });+ keymapListElement.addEventListener("focusout", (event: FocusEvent) => {+ if (recording && event.target === recording.input) {+ // 等待当前点击完成,避免移除目标按钮后丢失添加、删除或恢复操作。+ setTimeout(() => {+ if (recording && document.activeElement !== recording.input) {+ cancelRecording();+ refreshShared();+ }+ }, 0);+ }});+ refreshShared();};const getKeymapString = (event: KeyboardEvent) => {@@ -579,7 +601,7 @@ const searchKeymapList = (keymapListElement: HTMLElement, keywords: string, keymconst liElement = item.parentElement;let matchedKeymap = true;if (keymapStrLower) {- const dataValue = liElement.querySelector(".b3-text-field").getAttribute("data-value") || "";+ const dataValue = getRowBindings(liElement).join(" ");if (!dataValue || dataValue.toLowerCase().indexOf(keymapStrLower) === -1) {matchedKeymap = false;}@@ -630,54 +652,166 @@ const toggleKeymapSearchItem = (editorKeymapElement: HTMLElement, isFiltering: b}};-const setKeymapFromDom = (root: HTMLElement) => {- const data: Config.IKeymap = JSON.parse(JSON.stringify(Constants.SIYUAN_KEYMAP));- data.plugin = window.siyuan.config.keymap.plugin || {};- root.querySelectorAll("label.b3-list-item input").forEach((item) => {- const keys = item.getAttribute("data-key").split(Constants.ZWSP);- const newHotkey = item.getAttribute("data-value");- if (keys[0] === "general") {- data[keys[0]][keys[1]].custom = newHotkey;- } else if (keys[0] === "editor" && isEditorKeymapSegment(keys[1])) {- data.editor[keys[1]][keys[2]].custom = newHotkey;- } else if (keys[0] === "plugin") {- setPluginKeymapCustom(data.plugin, keys[1], keys[2], newHotkey,- item.getAttribute("data-default") || "");- const plugin = window.siyuan.ws.app.plugins.find((item) => item.name === keys[1]);- const command = plugin?.commands.find((item) => item.langKey === keys[2]);- if (!command) {- return;- }- /// #if !BROWSER- if (!isWindow() && command.globalCallback && command.customHotkey && command.customHotkey !== newHotkey) {- ipcRenderer.send(Constants.SIYUAN_CMD, {- cmd: "unregisterGlobalShortcut",- accelerator: command.customHotkey,- });- }- /// #endif- command.customHotkey = newHotkey;+const scopeLabel = (scope: string) => {+ const languages = window.siyuan.languages;+ return ({editor: languages.editor, fileTree: languages.fileTree, dock: languages.entryDock,+ global: languages.general, system: languages.keymapSystemScope})[scope] || scope;+};++const getRowHotkey = (row: HTMLElement, hotkey: string) => getRowBindings(row)+ .find(key => normalizeShortcutKey(key, isMac()) === normalizeShortcutKey(hotkey, isMac()));++const sharedRows = (root: HTMLElement, hotkey: string) =>+ Array.from(root.querySelectorAll<HTMLElement>(".config-keymap__row"))+ .filter(row => getRowBindings(row).some(key => normalizeShortcutKey(key, isMac()) === normalizeShortcutKey(hotkey, isMac())));++const refreshSharedBindings = (root: HTMLElement) => {+ root.querySelectorAll<HTMLElement>(".config-keymap__row").forEach(row => {+ const keys = getRowBindings(row).filter(key => sharedRows(root, key).length > 1);+ const controls = row.querySelector(".config-keymap__controls");+ const config = getKeymapItem(window.siyuan.config.keymap, row.dataset.key.split(Constants.ZWSP));+ const resetButton = controls.querySelector<HTMLButtonElement>('[data-type="reset"]');+ if (config?.bindings && config.bindings.version !== 1) {+ controls.querySelectorAll<HTMLButtonElement>("button").forEach(button => {+ button.disabled = true;+ button.title = window.siyuan.languages.invalid;+ });}+ const changed = JSON.stringify(getRowBindings(row)) !== row.dataset.defaults ||+ Object.keys(config?.bindings?.priority || {}).length > 0;+ resetButton.style.display = changed ? "" : "none";+ resetButton.tabIndex = changed ? 0 : -1;+ controls.querySelector('[data-type="shared"]')?.remove();+ const detail = row.querySelector<HTMLElement>(".config-keymap__shared");+ if (!keys.length) {+ detail.classList.add("fn__none");+ detail.innerHTML = "";+ return;+ }+ const button = document.createElement("button");+ button.type = "button";+ button.dataset.type = "shared";+ button.className = "config-keymap__shared-button";+ button.textContent = window.siyuan.languages.keymapShared;+ const ambiguous = keys.some(hotkey => {+ const seen = new Set<string>();+ return sharedRows(root, hotkey).some(item => {+ const path = item.dataset.key.split(Constants.ZWSP);+ const config = getKeymapItem(window.siyuan.config.keymap, path);+ return getShortcutScopes(path).some(scope => {+ const priority = config?.bindings?.priority?.[`${scope}:${getRowHotkey(item, hotkey)}`] || 0;+ const identity = `${scope}:${priority}`;+ if (seen.has(identity)) {+ return true;+ }+ seen.add(identity);+ return false;+ });+ });+ });+ button.classList.toggle("config-keymap__shared-button--conflict", ambiguous);+ button.title = ambiguous ? window.siyuan.languages.conflict : window.siyuan.languages.keymapShared;+ button.setAttribute("aria-expanded", String(!detail.classList.contains("fn__none")));+ controls.prepend(button);+ detail.innerHTML = keys.map(hotkey => {+ const rows = sharedRows(root, hotkey);+ const supported = canShareShortcutPaths(rows.map(item => item.dataset.key.split(Constants.ZWSP)));+ const groups = new Map<string, HTMLElement[]>();+ rows.forEach(item => {+ const scopes = getShortcutScopes(item.dataset.key.split(Constants.ZWSP));+ (scopes.length ? scopes : ["global"]).forEach(scope => {+ const group = groups.get(scope) || [];+ group.push(item);+ groups.set(scope, group);+ });+ });+ return `<div class="config-keymap__shared-title">${escapeHtml(updateHotkeyTip(hotkey))}</div>` ++ Array.from(groups, ([scope, items]) => {+ items.sort((first, second) => compareShortcutBindings(+ {id: getShortcutId(first.dataset.key.split(Constants.ZWSP)), scope: "global", priority: getKeymapItem(window.siyuan.config.keymap,+ first.dataset.key.split(Constants.ZWSP))?.bindings?.priority?.[`${scope}:${getRowHotkey(first, hotkey)}`]},+ {id: getShortcutId(second.dataset.key.split(Constants.ZWSP)), scope: "global", priority: getKeymapItem(window.siyuan.config.keymap,+ second.dataset.key.split(Constants.ZWSP))?.bindings?.priority?.[`${scope}:${getRowHotkey(second, hotkey)}`]},+ ));+ return `<div class="ft__on-surface">${escapeHtml(scopeLabel(scope))}</div>` + items.map((item, index) =>+ `<div class="config-keymap__candidate"><span class="fn__flex-1">${index + 1}. ${escapeHtml(item.querySelector(".b3-list-item__text").textContent)}</span>${supported ?+ ["up", "down"].map(direction => `<button type="button" class="config-keymap__action b3-list-item__action" data-type="priority-${direction}" data-path="${escapeAttr(escapeHtml(item.dataset.key))}" data-hotkey="${escapeAttr(escapeHtml(hotkey))}" data-scope="${scope}" aria-label="${escapeAttr(window.siyuan.languages[direction])}" ${((direction === "up" && index === 0) || (direction === "down" && index === items.length - 1)) ? "disabled" : ""}><svg><use xlink:href="#${direction === "up" ? "iconUp" : "iconDown"}"></use></svg></button>`).join("") : ""}</div>`).join("");+ }).join("") + `<div class="ft__on-surface">${escapeHtml(window.siyuan.languages[supported ? "keymapSharedTip" : "keymapLegacyConflict"])}</div>`;+ }).join("");});- const oldToggleWin = window.siyuan.config.keymap.general.toggleWin.custom;+};++const moveSharedBinding = (root: HTMLElement, row: HTMLElement, action: HTMLElement, direction: number) => {+ const hotkey = action.dataset.hotkey;+ const items = sharedRows(root, hotkey).filter(item =>+ getShortcutScopes(item.dataset.key.split(Constants.ZWSP)).includes(action.dataset.scope as "global"));+ items.sort((first, second) => compareShortcutBindings(+ {id: getShortcutId(first.dataset.key.split(Constants.ZWSP)), scope: "global", priority: getKeymapItem(window.siyuan.config.keymap,+ first.dataset.key.split(Constants.ZWSP))?.bindings?.priority?.[`${action.dataset.scope}:${getRowHotkey(first, hotkey)}`]},+ {id: getShortcutId(second.dataset.key.split(Constants.ZWSP)), scope: "global", priority: getKeymapItem(window.siyuan.config.keymap,+ second.dataset.key.split(Constants.ZWSP))?.bindings?.priority?.[`${action.dataset.scope}:${getRowHotkey(second, hotkey)}`]},+ ));+ const index = items.findIndex(item => item.dataset.key === action.dataset.path);+ const next = index + direction;+ if (index < 0 || next < 0 || next >= items.length) {+ return;+ }+ [items[index], items[next]] = [items[next], items[index]];+ saveKeymapRow(root, row, getRowBindings(row), data => {+ items.forEach((item, position) => {+ const config = getKeymapItem(data, item.dataset.key.split(Constants.ZWSP));+ setKeymapBindings(config, getKeymapBindings(config));+ config.bindings.priority[`${action.dataset.scope}:${getRowHotkey(item, hotkey)}`] = items.length - position;+ });+ });+};++let keymapSaveQueue = Promise.resolve();+let keymapRevision = 0;+let savedKeymap: Config.IKeymap | undefined;++const applyKeymap = (data: Config.IKeymap) => {+ sendUnregisterGlobalShortcut(window.siyuan.ws.app);window.siyuan.config.keymap = data;- updateDockHotkeys();- fetchPost("/api/setting/setKeymap", {- data,- }, () => {- /// #if !BROWSER- ipcRenderer.send(Constants.SIYUAN_CMD, {- cmd: "writeLog",- msg: "user update keymap:" + JSON.stringify(window.siyuan.config.keymap),+ window.siyuan.ws.app.plugins.forEach(plugin => {+ plugin.commands.forEach(command => {+ command.customHotkey = data.plugin?.[plugin.name]?.[command.langKey]?.custom || "";});- if (!isWindow() && oldToggleWin !== window.siyuan.config.keymap.general.toggleWin.custom) {- ipcRenderer.send(Constants.SIYUAN_CMD, {- cmd: "unregisterGlobalShortcut",- accelerator: oldToggleWin,+ });+ updateDockHotkeys();+ sendGlobalShortcut(window.siyuan.ws.app);+ syncAppMenuShortcuts(Boolean(document.activeElement?.matches(".config-keymap__record, #searchByKey")));+};++const saveKeymapRow = (root: HTMLElement, row: HTMLElement, keys: string[], change?: (data: Config.IKeymap) => void) => {+ savedKeymap ||= JSON.parse(JSON.stringify(window.siyuan.config.keymap));+ const data: Config.IKeymap = JSON.parse(JSON.stringify(window.siyuan.config.keymap));+ const item = getKeymapItem(data, row.dataset.key.split(Constants.ZWSP));+ if (!item) {+ return;+ }+ setKeymapBindings(item, keys);+ change?.(data);+ applyKeymap(data);+ const revision = ++keymapRevision;+ keymapSaveQueue = keymapSaveQueue.then(async () => {+ try {+ const response = await fetchSyncPost("/api/setting/setKeymap", {data});+ if (response.code !== 0) {+ throw new Error(response.msg);+ }+ savedKeymap = data;+ } catch (error) {+ console.error("Could not save shortcuts:", error);+ if (revision !== keymapRevision) {+ return;+ }+ applyKeymap(savedKeymap);+ root.querySelectorAll<HTMLElement>(".config-keymap__row").forEach(element => {+ renderRowBindings(element, getKeymapBindings(getKeymapItem(savedKeymap, element.dataset.key.split(Constants.ZWSP))));});+ refreshSharedBindings(root);+ showMessage(window.siyuan.languages.keymapSaveFailed);}- sendGlobalShortcut(window.siyuan.ws.app);- syncAppMenuShortcuts();- /// #endif});};diff --git a/app/src/layout/dock/agent/AgentComposer.ts b/app/src/layout/dock/agent/AgentComposer.tsindex f56085da7c..54efee60be 100644--- a/app/src/layout/dock/agent/AgentComposer.ts+++ b/app/src/layout/dock/agent/AgentComposer.ts@@ -266,7 +266,7 @@ export function mountComposer(host: HTMLElement, onSend: () => void, onChange?:return;}- if (matchHotKey(window.siyuan.config.keymap.general.agentSend.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.agentSend, event)) {event.preventDefault();event.stopPropagation();onSend();diff --git a/app/src/layout/dock/hotkey.ts b/app/src/layout/dock/hotkey.tsindex f1adfc2efc..d39d581966 100644--- a/app/src/layout/dock/hotkey.ts+++ b/app/src/layout/dock/hotkey.ts@@ -3,6 +3,14 @@ interface IPluginDockOwner {docks: Record<string, unknown>;}+export const getDockKeymap = (dock: Config.IUILayoutDockTab) => {+ if (dock.hotkeyLangId) {+ return window.siyuan.config.keymap.general[dock.hotkeyLangId];+ }+ const plugin = window.siyuan.ws.app.plugins.find(item => Object.prototype.hasOwnProperty.call(item.docks, dock.type));+ return plugin ? window.siyuan.config.keymap.plugin?.[plugin.name]?.[dock.type] : undefined;+};+interface IDockKeymap {general: Config.IKeys;plugin?: Config.IKeymapPlugin;diff --git a/app/src/mobile/util/keydown.ts b/app/src/mobile/util/keydown.tsindex 6b0856efd5..08e05fc267 100644--- a/app/src/mobile/util/keydown.ts+++ b/app/src/mobile/util/keydown.ts@@ -1,18 +1,20 @@import type {App} from "../../index";-import {execByCommand} from "../../command/executor";+import {ensureCommandSystem, execByCommand} from "../../command/executor";import {matchHotKey} from "../../protyle/util/hotKey";import {getCurrentEditor} from "../editor";import {filterHotkey} from "../../boot/globalEvent/commonHotkey";-import {captureCommandContext} from "../../command/context";-import {resolvePluginCommandCallback, supportsPluginCommandSource} from "../../plugin/commandAdapter";+import {captureShortcutContext, dispatchPluginShortcut, dispatchSharedShortcut} from "../../command/shortcutRuntime";export const mobileKeydown = (app: App, event: KeyboardEvent) => {// 移动端输入框默认填充无 event.keyif (!event.key || filterHotkey(event, app)) {return;}+ if (dispatchSharedShortcut(app, event, () => ensureCommandSystem(app))) {+ return;+ }const matchGeneral = Object.keys(window.siyuan.config.keymap.general).find((key) => {- if (matchHotKey(window.siyuan.config.keymap.general[key].custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general[key], event)) {const protyle = getCurrentEditor()?.protyle;if (protyle) {execByCommand({command: key, app, protyle, previousRange: protyle.toolbar.range});@@ -26,23 +28,5 @@ export const mobileKeydown = (app: App, event: KeyboardEvent) => {return;}- let matchedCommand: ICommand | undefined;- app.plugins.find(item => {- item.commands.find(command => {- if (supportsPluginCommandSource(command, "shortcut") && matchHotKey(command.customHotkey, event)) {- matchedCommand = command;- return true;- }- });- return Boolean(matchedCommand);- });- if (matchedCommand) {- const commandContext = captureCommandContext({app, source: "shortcut"});- const callback = resolvePluginCommandCallback(matchedCommand, commandContext);- if (callback) {- void callback();- event.preventDefault();- return true;- }- }+ return dispatchPluginShortcut(app, event, "shortcut", () => captureShortcutContext(app, event));};diff --git a/app/src/plugin/commandAdapter.test.ts b/app/src/plugin/commandAdapter.test.tsindex 0e2f7d7369..2350760703 100644--- a/app/src/plugin/commandAdapter.test.ts+++ b/app/src/plugin/commandAdapter.test.ts@@ -13,6 +13,14 @@ import {const owners: object[] = [];+it("preserves async legacy callback results so execution failures reach the dispatcher", async () => {+ const command: ICommand = {langKey: "async", editorCallback: async () => {+ throw new Error("editor failed");+ }};+ const callback = resolvePluginCommandCallback(command, createContext({source: "editorShortcut", protyle: {} as IProtyle}));+ await assert.rejects(async () => callback(), /editor failed/);+});+afterEach(() => {owners.forEach(owner => unregisterPluginCommands(owner));owners.length = 0;diff --git a/app/src/plugin/commandAdapter.ts b/app/src/plugin/commandAdapter.tsindex e3d77de7c8..1ae9a7fd67 100644--- a/app/src/plugin/commandAdapter.ts+++ b/app/src/plugin/commandAdapter.ts@@ -81,12 +81,12 @@ export const resolvePluginCommandCallback = (command: ICommand, context: ICommanif (!isMobileContext(context)) {if (context.focus === "editor" && context.protyle && command.editorCallback) {return resolvePluginCommandExecution(command, context, pluginContext => {- command.editorCallback(context.protyle, pluginContext);+ return command.editorCallback(context.protyle, pluginContext);});}if (context.focus === "fileTree" && context.fileTree?.model && command.fileTreeCallback) {return resolvePluginCommandExecution(command, context, pluginContext => {- command.fileTreeCallback(+ return command.fileTreeCallback(context.fileTree.model as import("../layout/dock/Files").Files,pluginContext,);@@ -94,13 +94,13 @@ export const resolvePluginCommandCallback = (command: ICommand, context: IComman}if (context.focus === "dock" && hasPluginDockContext(context) && command.dockCallback) {return resolvePluginCommandExecution(command, context, pluginContext => {- command.dockCallback(context.dock.element, pluginContext);+ return command.dockCallback(context.dock.element, pluginContext);});}}if (command.globalCallback && ["desktop", "browser-desktop"].includes(context.environment)) {return resolvePluginCommandExecution(command, context, pluginContext => {- command.globalCallback(pluginContext);+ return command.globalCallback(pluginContext);});}if (command.execute && !hasPluginCommandLegacyCallback(command)) {@@ -110,12 +110,12 @@ export const resolvePluginCommandCallback = (command: ICommand, context: IComman}if (context.source === "editorShortcut" && context.protyle && command.editorCallback) {return resolvePluginCommandExecution(command, context, pluginContext => {- command.editorCallback(context.protyle, pluginContext);+ return command.editorCallback(context.protyle, pluginContext);});}if (context.source === "fileTreeShortcut" && context.fileTree?.model && command.fileTreeCallback) {return resolvePluginCommandExecution(command, context, pluginContext => {- command.fileTreeCallback(+ return command.fileTreeCallback(context.fileTree.model as import("../layout/dock/Files").Files,pluginContext,);@@ -123,7 +123,7 @@ export const resolvePluginCommandCallback = (command: ICommand, context: IComman}if (context.source === "dockShortcut" && hasPluginDockContext(context) && command.dockCallback) {return resolvePluginCommandExecution(command, context, pluginContext => {- command.dockCallback(context.dock.element, pluginContext);+ return command.dockCallback(context.dock.element, pluginContext);});}if (context.source === "shortcut") {@@ -147,7 +147,9 @@ export const createPluginCommandDefinition = (keymapPath: ["plugin", plugin.name, command.langKey],hotkey: () => command.customHotkey || "",order: 10_000,- enabled: context => Boolean(resolvePluginCommandCallback(command, context)),+ when: context => !command.when || command.when(createPluginCommandContext(context)),+ enabled: context => Boolean(resolvePluginCommandCallback(command, context)) &&+ (!command.enabled || command.enabled(createPluginCommandContext(context))),execute: context => resolvePluginCommandCallback(command, context)?.(),};};diff --git a/app/src/plugin/globalShortcut.test.ts b/app/src/plugin/globalShortcut.test.tsindex 2455d928fb..216da7df36 100644--- a/app/src/plugin/globalShortcut.test.ts+++ b/app/src/plugin/globalShortcut.test.ts@@ -3,6 +3,19 @@ import * as assert from "node:assert/strict";import {dispatchPluginGlobalShortcut} from "./globalShortcut";describe("plugin global shortcuts", () => {+ it("matches secondary bindings and skips disabled high priority commands", () => {+ const calls: string[] = [];+ const plugins = ["first", "second"].map(name => ({name, commands: [{+ langKey: "action", customHotkey: "⌘K", enabled: () => name !== "first",+ globalCallback: () => calls.push(name),+ }]}));+ const keymap = Object.fromEntries(plugins.map(plugin => [plugin.name, {action: {+ custom: "⌘K", bindings: {version: 1 as const, keys: ["⌘K", "⌘L"],+ priority: {"system:⌘L": plugin.name === "first" ? 10 : 0}},+ }}]));+ assert.equal(dispatchPluginGlobalShortcut(plugins, "⌘L", keymap), true);+ assert.deepEqual(calls, ["second"]);+ });it("runs only the first matching command", () => {const calls: string[] = [];const plugins = ["first", "second"].map(name => ({diff --git a/app/src/plugin/globalShortcut.ts b/app/src/plugin/globalShortcut.tsindex ddd4f0989d..07ba1c57c8 100644--- a/app/src/plugin/globalShortcut.ts+++ b/app/src/plugin/globalShortcut.ts@@ -1,25 +1,49 @@+import {getKeymapBindings, IShortcutKeymap, normalizeShortcutKey} from "../util/keymapBindings";+import {compareShortcutBindings} from "../command/shortcutCatalog";+interface IPluginGlobalShortcutCommand {+ langKey?: string;customHotkey?: string;execute?: (context: ICommandContext) => void | Promise<void>;globalCallback?: (context?: ICommandContext) => void;+ when?: (context: ICommandContext) => boolean;+ enabled?: (context: ICommandContext) => boolean;}interface IPluginGlobalShortcutOwner {+ name?: string;commands: IPluginGlobalShortcutCommand[];}-export const dispatchPluginGlobalShortcut = (plugins: IPluginGlobalShortcutOwner[], hotkey: string) => {+export const dispatchPluginGlobalShortcut = (plugins: IPluginGlobalShortcutOwner[], hotkey: string,+ keymap?: Record<string, Record<string, IShortcutKeymap>>, mac = true) => {const context: ICommandContext = {source: "globalShortcut", focus: "global"};- for (const plugin of plugins) {- const command = plugin.commands.find(item => item.globalCallback && item.customHotkey === hotkey);- if (command) {+ const candidates = plugins.flatMap((plugin, index) => plugin.commands.map((command, commandIndex) => {+ const item = keymap?.[plugin.name]?.[command.langKey];+ const key = getKeymapBindings(item || {custom: command.customHotkey})+ .find(key => normalizeShortcutKey(key, mac) === normalizeShortcutKey(hotkey, mac));+ return {command, item, id: `plugin/${encodeURIComponent(plugin.name ?? String(index))}/${encodeURIComponent(command.langKey ?? String(commandIndex))}`,+ scope: "system" as const, priority: item?.bindings?.priority?.[`system:${key}`], key};+ })).filter(({command, key}) => command.globalCallback && key).sort(compareShortcutBindings);+ for (const {command} of candidates) {+ try {+ if ((command.when && !command.when(context)) || (command.enabled && !command.enabled(context))) {+ continue;+ }+ } catch (error) {+ console.error("Global shortcut condition failed:", error);+ continue;+ }+ try {if (command.execute) {- void command.execute(context);+ void Promise.resolve(command.execute(context)).catch(error => console.error("Global shortcut failed:", error));} else {- command.globalCallback(context);+ void Promise.resolve(command.globalCallback(context)).catch(error => console.error("Global shortcut failed:", error));}- return true;+ } catch (error) {+ console.error("Global shortcut failed:", error);}+ return true;}return false;};diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.tsindex 114d931f01..49b2907bea 100644--- a/app/src/plugin/index.ts+++ b/app/src/plugin/index.ts@@ -1,3 +1,4 @@+import {sendGlobalShortcut} from "../boot/globalEvent/globalShortcut";import type {App} from "../index";import {EventBus} from "./EventBus";import {fetchPost} from "../util/fetch";@@ -12,9 +13,6 @@ import {clearOBG} from "../layout/dock/util";///#elseimport {MobileCustom} from "../mobile/dock/MobileCustom";/// #endif-/// #if !BROWSER-import {ipcRenderer} from "electron";-/// #endifimport {hasClosestByAttribute} from "../protyle/util/hasClosest";import {BlockPanel} from "../block/Panel";import {Setting} from "./Setting";@@ -23,7 +21,6 @@ import {addPluginDock, removePluginDock} from "./loader";import {normalizeStoragePath} from "../util/pathName";import {Kernel} from "./kernel";import {IAgentCapabilityEffects, registerCapability} from "../layout/dock/agent/frontendCapabilities";-import {isDisallowedTextInputHotkey} from "../util/hotKeyPolicy";import {addBreadcrumbButton as addPluginBreadcrumbButton,removeBreadcrumbButton as removePluginBreadcrumbButton,@@ -195,7 +192,7 @@ export class Plugin {if (typeof command.hotkey !== "string") {command.hotkey = "";}- const keymapItem = updatePluginKeymap(this.name, command.langKey, command.hotkey);+ const keymapItem = updatePluginKeymap(this.name, command.langKey, command.hotkey, command.hotkeys);command.hotkey = keymapItem.default;command.customHotkey = keymapItem.custom;if (typeof command.customHotkey !== "string") {@@ -204,12 +201,8 @@ export class Plugin {this.commands.push(command);registerPluginCommand(this.app, this, command);/// #if !BROWSER- if (!isWindow() && command.globalCallback && command.customHotkey &&- !isDisallowedTextInputHotkey(command.customHotkey)) {- ipcRenderer.send(Constants.SIYUAN_CMD, {- cmd: "registerGlobalShortcut",- accelerator: command.customHotkey- });+ if (command.globalCallback) {+ sendGlobalShortcut(this.app);}/// #endif}diff --git a/app/src/plugin/keymap.test.ts b/app/src/plugin/keymap.test.tsindex d7ad46036e..40168d9bfe 100644--- a/app/src/plugin/keymap.test.ts+++ b/app/src/plugin/keymap.test.ts@@ -44,3 +44,16 @@ test("setting a custom plugin hotkey creates a missing editable item", () => {setPluginKeymapCustom(plugin, "plugin", "item", "⌘J", "⌘K");assert.deepEqual(plugin, {plugin: {item: {default: "⌘K", custom: "⌘J"}}});});++test("plugin default lists are available on first registration and preserve custom lists on reload", () => {+ withKeymap({}, () => {+ const item = updatePluginKeymap("test", "command", "", ["⌘K", "⌘L", "⌘K", "A"]);+ assert.deepEqual(item.bindings.keys, ["⌘K", "⌘L"]);+ item.bindings.keys = ["⌘M", "⌘N"];+ item.custom = "⌘M";+ const reloaded = updatePluginKeymap("test", "command", "", ["⌘O"]);+ assert.deepEqual(reloaded.bindings.keys, ["⌘M", "⌘N"]);+ assert.deepEqual(reloaded.bindings.defaults, ["⌘O"]);+ assert.equal(reloaded.custom, "⌘M");+ });+});diff --git a/app/src/plugin/keymap.ts b/app/src/plugin/keymap.tsindex 7205ddfda2..16c832a70b 100644--- a/app/src/plugin/keymap.ts+++ b/app/src/plugin/keymap.ts@@ -1,6 +1,7 @@import {normalizePluginHotkey} from "../util/hotKeyPolicy";+import {getKeymapBindings, setKeymapBindings} from "../util/keymapBindings";-export const updatePluginKeymap = (pluginName: string, key: string, hotkey: unknown) => {+export const updatePluginKeymap = (pluginName: string, key: string, hotkey: unknown, hotkeys?: string[]) => {if (!window.siyuan.config.keymap.plugin) {window.siyuan.config.keymap.plugin = {};}@@ -18,10 +19,21 @@ export const updatePluginKeymap = (pluginName: string, key: string, hotkey: unknkeymapItem.default = normalized.defaultHotkey;keymapItem.custom = normalized.customHotkey;}+ if (keymapItem?.bindings?.version === 1) {+ const keys = getKeymapBindings(keymapItem).map(key => normalizePluginHotkey(key).defaultHotkey).filter(Boolean);+ setKeymapBindings(keymapItem, keys);+ }normalized.ignoredHotkeys.forEach((ignoredHotkey) => {console.warn(`Plugin ${pluginName} ignored disallowed hotkey "${ignoredHotkey}" for "${key}".`);});- return window.siyuan.config.keymap.plugin[pluginName][key];+ const item = window.siyuan.config.keymap.plugin[pluginName][key];+ if (Array.isArray(hotkeys) && (!item.bindings || item.bindings.version === 1)) {+ const defaults = [...new Set(hotkeys.map(key => normalizePluginHotkey(key).defaultHotkey).filter(Boolean))];+ setKeymapBindings(item, keymapItem ? getKeymapBindings(item) : defaults);+ item.bindings.defaults = defaults;+ item.default = defaults[0] || "";+ }+ return item;};export const ensurePluginKeymap = (pluginName: string, key: string, hotkey: unknown) => {@@ -40,4 +52,7 @@ export const setPluginKeymapCustom = (keymap: Config.IKeymapPlugin, pluginName:custom: "",};keymap[pluginName][key].custom = custom;+ if (keymap[pluginName][key].bindings) {+ setKeymapBindings(keymap[pluginName][key], custom ? [custom] : []);+ }};diff --git a/app/src/plugin/uninstall.ts b/app/src/plugin/uninstall.tsindex 0bf107b76c..0dc5dfd18b 100644--- a/app/src/plugin/uninstall.ts+++ b/app/src/plugin/uninstall.ts@@ -5,9 +5,6 @@ import {getAllModels} from "../layout/getAll";import {resizeTopBar} from "../layout/util";import {setTabPosition} from "../layout/tabUtil";/// #endif-/// #if !BROWSER-import {ipcRenderer} from "electron";-/// #endifimport {Constants} from "../constants";import {setStorageVal} from "../protyle/util/compatibility";import {getAllEditor} from "../layout/getAll";@@ -149,18 +146,6 @@ export const destroyPlugin = (app: App, plugin: Plugin, isUninstall: boolean) =>runCleanup(plugin, "commands", () => unregisterPluginCommands(plugin));/// #if !BROWSERif (!isWindow()) {- runCleanup(plugin, "global shortcut", () => {- plugin.commands.forEach(command => {- if (command.globalCallback && command.customHotkey) {- runCleanup(plugin, "global shortcut", () => {- ipcRenderer.send(Constants.SIYUAN_CMD, {- cmd: "unregisterGlobalShortcut",- accelerator: command.customHotkey- });- });- }- });- });if (window.siyuan.languages?.["_trayMenu"]) {runCleanup(plugin, "global shortcut sync", () => sendGlobalShortcut(app));}diff --git a/app/src/protyle/header/Title.ts b/app/src/protyle/header/Title.tsindex 38d4a91090..8a02d56833 100644--- a/app/src/protyle/header/Title.ts+++ b/app/src/protyle/header/Title.ts@@ -122,7 +122,7 @@ export class Title {}return;}- if (matchHotKey(window.siyuan.config.keymap.general.enterBack.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.enterBack, event)) {const parentDocumentID = getParentDocumentID({path: protyle.path,notebookID: protyle.notebookId,@@ -165,7 +165,7 @@ export class Title {enterDocumentFromTitle(protyle);event.preventDefault();event.stopPropagation();- } else if (matchHotKey(window.siyuan.config.keymap.editor.general.attr.custom, event)) {+ } else if (matchHotKey(window.siyuan.config.keymap.editor.general.attr, event)) {const docInfoParam: IObject = {id: protyle.block.rootID};diff --git a/app/src/protyle/render/av/keydown.ts b/app/src/protyle/render/av/keydown.tsindex 3249ca3b43..471d180cfc 100644--- a/app/src/protyle/render/av/keydown.ts+++ b/app/src/protyle/render/av/keydown.ts@@ -32,8 +32,8 @@ export const avKeydown = (event: KeyboardEvent, nodeElement: HTMLElement, protylevent.preventDefault();return true;}- const isNewNameFile = matchHotKey(window.siyuan.config.keymap.editor.general.newNameFile.custom, event);- const isNewNameSettingFile = matchHotKey(window.siyuan.config.keymap.editor.general.newNameSettingFile.custom, event);+ const isNewNameFile = matchHotKey(window.siyuan.config.keymap.editor.general.newNameFile, event);+ const isNewNameSettingFile = matchHotKey(window.siyuan.config.keymap.editor.general.newNameSettingFile, event);if (isNewNameFile || isNewNameSettingFile) {if (event.repeat) {event.preventDefault();diff --git a/app/src/protyle/toolbar/hotkey.test.ts b/app/src/protyle/toolbar/hotkey.test.tsnew file mode 100644index 0000000000..cc6e97d4af--- /dev/null+++ b/app/src/protyle/toolbar/hotkey.test.ts@@ -0,0 +1,27 @@+import * as assert from "node:assert/strict";+import test from "node:test";+import {getToolbarHotkey, markToolbarHotkey} from "./hotkey";+import {markPluginToolbarEntries} from "./defaults";++test("built-in toolbar items resolve all current bindings after configuration changes", () => {+ const item: IMenuItem = {name: "strong", hotkey: "⌘B"};+ markToolbarHotkey(item, "strong");+ const current = {custom: "⌘M", bindings: {version: 1, keys: ["⌘M", "⌘L"]}};+ const copied = {...item};+ markToolbarHotkey(copied, item);+ assert.equal(getToolbarHotkey(copied, {editor: {insert: {bold: current}}}), current);+});++test("explicit per-editor toolbar shortcuts remain independent of the global configuration", () => {+ for (const hotkey of ["⌘J", ""]) {+ const item: IMenuItem = {name: "strong", hotkey};+ markToolbarHotkey(item, item);+ assert.equal(getToolbarHotkey(item, {editor: {insert: {bold: {custom: "⌘B"}}}}), hotkey);+ }+});++test("plugin toolbar bindings are resolved through their actual owner", () => {+ const [item] = markPluginToolbarEntries([], [{name: "action", hotkey: "⌘J"}], "owner", () => "Action");+ const current = {custom: "⌘M", bindings: {version: 1, keys: ["⌘M", "⌘L"]}};+ assert.equal(getToolbarHotkey(item as IMenuItem, {plugin: {owner: {action: current}}}), current);+});diff --git a/app/src/protyle/toolbar/hotkey.ts b/app/src/protyle/toolbar/hotkey.tsnew file mode 100644index 0000000000..256337481e--- /dev/null+++ b/app/src/protyle/toolbar/hotkey.ts@@ -0,0 +1,28 @@+import {getToolbarEntryId} from "./defaults";+import {getKeymapItem} from "../../util/keymapBindings";++const configuredHotkey = Symbol("configuredHotkey");+type TShortcutToolbarItem = IMenuItem & {[configuredHotkey]?: boolean};++export const markToolbarHotkey = (item: IMenuItem, source: string | IMenuItem) => {+ (item as TShortcutToolbarItem)[configuredHotkey] = typeof source === "string" || source.hotkey === undefined ||+ (source as TShortcutToolbarItem)[configuredHotkey] === true;+};++const inlineKeys: Record<string, string> = {+ "block-ref": "ref", a: "link", strong: "bold", em: "italic", u: "underline", s: "strike",+ code: "inline-code", "inline-memo": "memo", text: "appearance", clear: "clearInline",+ mark: "mark", sup: "sup", sub: "sub", kbd: "kbd", tag: "tag", "inline-math": "inline-math",+};++export const getToolbarHotkey = (item: IMenuItem, keymap: object = window.siyuan.config.keymap) => {+ const id = getToolbarEntryId(item);+ if (id?.startsWith("plugin:")) {+ const parts = id.split(":");+ return getKeymapItem(keymap, ["plugin", decodeURIComponent(parts[1]), decodeURIComponent(parts[2])]) || item.hotkey;+ }+ if (inlineKeys[item.name] && (item as TShortcutToolbarItem)[configuredHotkey]) {+ return getKeymapItem(keymap, ["editor", "insert", inlineKeys[item.name]]) || item.hotkey;+ }+ return item.hotkey;+};diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.tsindex f69e4cd627..f5c64abc20 100644--- a/app/src/protyle/toolbar/index.ts+++ b/app/src/protyle/toolbar/index.ts@@ -1691,7 +1691,7 @@ export class Toolbar {textElement.addEventListener("keydown", (event: KeyboardEvent) => {event.stopPropagation();// 阻止 ctrl+m 缩小窗口 https://github.com/siyuan-note/siyuan/issues/5541- if (matchHotKey(window.siyuan.config.keymap.editor.insert["inline-math"].custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.insert["inline-math"], event)) {event.preventDefault();return;}diff --git a/app/src/protyle/toolbar/tableCell.ts b/app/src/protyle/toolbar/tableCell.tsindex 21bbf44c1b..2dbecc5684 100644--- a/app/src/protyle/toolbar/tableCell.ts+++ b/app/src/protyle/toolbar/tableCell.ts@@ -85,7 +85,7 @@ export const applyTableCellStyleHotkey = (protyle: IProtyle, cellElements: HTMLTif (event.repeat || cellElements.length === 0) {return false;}- if (matchHotKey(window.siyuan.config.keymap.editor.insert.lastUsed.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.insert.lastUsed, event)) {fontEvent(protyle, [], undefined, undefined, false, (type, color) => {applyTableCellFontStyle(protyle, cellElements, type, color);onApply?.();diff --git a/app/src/protyle/toolbar/util.ts b/app/src/protyle/toolbar/util.tsindex 78a92376d0..28825073bc 100644--- a/app/src/protyle/toolbar/util.ts+++ b/app/src/protyle/toolbar/util.ts@@ -1,4 +1,5 @@import {fetchPost, fetchSyncPost} from "../../util/fetch";+import {markToolbarHotkey} from "./hotkey";import {Constants} from "../../constants";import {focusByRange, focusByWbr} from "../util/selection";import {isDisabledFeature, writeText} from "../util/compatibility";@@ -308,10 +309,12 @@ export const toolbarKeyToMenu = (toolbar: Array<string | IMenuItem>) => {toolbarItem.find((defaultMenuItem: IMenuItem) => {if (typeof menuItem === "string" && defaultMenuItem.name === menuItem) {currentMenuItem = defaultMenuItem;+ markToolbarHotkey(currentMenuItem, menuItem);return true;}if (typeof menuItem === "object" && defaultMenuItem.name === menuItem.name) {currentMenuItem = Object.assign({}, defaultMenuItem, menuItem);+ markToolbarHotkey(currentMenuItem, menuItem);return true;}});diff --git a/app/src/protyle/undo/index.ts b/app/src/protyle/undo/index.tsindex 5e27f636c4..4cbf1cc181 100644--- a/app/src/protyle/undo/index.ts+++ b/app/src/protyle/undo/index.ts@@ -243,13 +243,13 @@ export class LocalUndo implements IUndo {export const electronUndo = (event: KeyboardEvent) => {/// #if !BROWSER- if (matchHotKey(window.siyuan.config.keymap.editor.general.undo.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.undo, event)) {ipcRenderer.send(Constants.SIYUAN_CMD, "undo");event.preventDefault();event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.redo.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.redo, event)) {ipcRenderer.send(Constants.SIYUAN_CMD, "redo");event.preventDefault();event.stopPropagation();diff --git a/app/src/protyle/util/hotKey.ts b/app/src/protyle/util/hotKey.tsindex e364be1db8..b4fdc04eab 100644--- a/app/src/protyle/util/hotKey.ts+++ b/app/src/protyle/util/hotKey.ts@@ -1,8 +1,12 @@import {isMac, isNotCtrl, isOnlyMeta} from "./compatibility";import {Constants} from "../../constants";+import {getKeymapBindings, IShortcutKeymap, normalizeShortcutKey, visitKeymapItems} from "../../util/keymapBindings";// 是否匹配辅助键 ⌃⌥⇧⌘-export const matchAuxiliaryHotKey = (hotKey: string, event: KeyboardEvent) => {+export const matchAuxiliaryHotKey = (hotKey: string | IShortcutKeymap, event: KeyboardEvent): boolean => {+ if (typeof hotKey !== "string") {+ return getKeymapBindings(hotKey).some(key => matchAuxiliaryHotKey(key, event));+ }if (hotKey.includes("⌃")) {if (!event.ctrlKey) {return false;@@ -42,21 +46,17 @@ export const matchAuxiliaryHotKey = (hotKey: string, event: KeyboardEvent) => {return true;};-export const matchHotKey = (hotKey: string, event: KeyboardEvent) => {+export const matchHotKey = (hotKey: string | IShortcutKeymap, event: KeyboardEvent): boolean => {+ if (typeof hotKey !== "string") {+ return getKeymapBindings(hotKey).some(key => matchHotKey(key, event));+ }if (!hotKey) {return false;}- // https://github.com/siyuan-note/siyuan/issues/9770- if (hotKey.startsWith("⌃") && !isMac()) {- if (hotKey === "⌃D") {- // https://github.com/siyuan-note/siyuan/issues/9841- return false;- }- hotKey = hotKey.replace("⌘", "").replace("⌃", "⌘")- .replace("⌘⇧", "⇧⌘")- .replace("⌘⌥⇧", "⌥⇧⌘")- .replace("⌘⌥", "⌥⌘");+ hotKey = normalizeShortcutKey(hotKey, isMac());+ if (!hotKey) {+ return false;}// []@@ -166,34 +166,11 @@ export const matchHotKey = (hotKey: string, event: KeyboardEvent) => {};export const isIncludesHotKey = (hotKey: string) => {- let isInclude = false;- Object.keys(window.siyuan.config.keymap).find(key => {- const item = window.siyuan.config.keymap[key as "editor"];- Object.keys(item).find(key2 => {- const item2 = item[key2 as "general"];- if (typeof item2.custom === "string") {- if (item2.custom === hotKey) {- isInclude = true;- return true;- }- } else {- Object.keys(item2).forEach(key3 => {- const item3: Config.IKey = item2[key3];- if (item3.custom === hotKey) {- isInclude = true;- return true;- }- });- if (isInclude) {- return true;- }- }- });-- if (isInclude) {- return true;+ let included = false;+ visitKeymapItems(window.siyuan.config.keymap, item => {+ if (getKeymapBindings(item).includes(hotKey)) {+ included = true;}});-- return isInclude;+ return included;};diff --git a/app/src/protyle/util/table.ts b/app/src/protyle/util/table.tsindex 51a6f69323..a7a275c507 100644--- a/app/src/protyle/util/table.ts+++ b/app/src/protyle/util/table.ts@@ -629,19 +629,19 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)}// 居左- if (matchHotKey(window.siyuan.config.keymap.editor.general.alignLeft.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.alignLeft, event)) {setTableAlign(protyle, [cellElement], nodeElement, "left", range);event.preventDefault();return true;}// 居中- if (matchHotKey(window.siyuan.config.keymap.editor.general.alignCenter.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.alignCenter, event)) {setTableAlign(protyle, [cellElement], nodeElement, "center", range);event.preventDefault();return true;}// 居右- if (matchHotKey(window.siyuan.config.keymap.editor.general.alignRight.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.alignRight, event)) {setTableAlign(protyle, [cellElement], nodeElement, "right", range);event.preventDefault();return true;@@ -721,7 +721,7 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)return true;}});- if (matchHotKey(window.siyuan.config.keymap.editor.table.moveToUp.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.table.moveToUp, event)) {if ((!hasNone || (hasNone && !hasRowSpan && hasColSpan)) &&(!previousHasNone || (previousHasNone && !previousHasRowSpan && previousHasColSpan))) {moveRowToUp(protyle, range, cellElement, nodeElement);@@ -730,7 +730,7 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.table.moveToDown.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.table.moveToDown, event)) {if ((!hasNone || (hasNone && !hasRowSpan && hasColSpan)) &&(!nextHasNone || (nextHasNone && !nextHasRowSpan && nextHasColSpan))) {moveRowToDown(protyle, range, cellElement, nodeElement);@@ -739,7 +739,7 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.table.moveToLeft.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.table.moveToLeft, event)) {if (colIsPure && previousColIsPure) {moveColumnToLeft(protyle, range, cellElement, nodeElement);}@@ -747,7 +747,7 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.table.moveToRight.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.table.moveToRight, event)) {if (colIsPure && nextColIsPure) {moveColumnToRight(protyle, range, cellElement, nodeElement);}@@ -756,7 +756,7 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)}// 上方新添加一行- if (matchHotKey(window.siyuan.config.keymap.editor.table.insertRowAbove.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.table.insertRowAbove, event)) {insertRowAbove(protyle, range, cellElement, nodeElement);event.preventDefault();event.stopPropagation();@@ -764,7 +764,7 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)}// 下方新添加一行 https://github.com/Vanessa219/vditor/issues/46- if (matchHotKey(window.siyuan.config.keymap.editor.table.insertRowBelow.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.table.insertRowBelow, event)) {if (!nextHasNone || (nextHasNone && !nextHasRowSpan && nextHasColSpan)) {insertRow(protyle, range, cellElement, nodeElement);}@@ -773,7 +773,7 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)}// 左方新添加一列- if (matchHotKey(window.siyuan.config.keymap.editor.table.insertColumnLeft.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.table.insertColumnLeft, event)) {if (colIsPure || previousColIsPure) {insertColumn(protyle, nodeElement, cellElement, "beforebegin", range);}@@ -782,7 +782,7 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)}// 后方新添加一列- if (matchHotKey(window.siyuan.config.keymap.editor.table.insertColumnRight.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.table.insertColumnRight, event)) {if (colIsPure || nextColIsPure) {insertColumn(protyle, nodeElement, cellElement, "afterend", range);}@@ -791,7 +791,7 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)}// 删除当前行- if (matchHotKey(window.siyuan.config.keymap.editor.table["delete-row"].custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.table["delete-row"], event)) {deleteRow(protyle, range, cellElement, nodeElement);event.preventDefault();event.stopPropagation();@@ -799,7 +799,7 @@ export const fixTable = (protyle: IProtyle, event: KeyboardEvent, range: Range)}// 删除当前列- if (matchHotKey(window.siyuan.config.keymap.editor.table["delete-column"].custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.table["delete-column"], event)) {deleteColumn(protyle, range, nodeElement, cellElement);event.preventDefault();return true;diff --git a/app/src/protyle/wysiwyg/commonHotkey.ts b/app/src/protyle/wysiwyg/commonHotkey.tsindex d84e36695c..33d12171d7 100644--- a/app/src/protyle/wysiwyg/commonHotkey.ts+++ b/app/src/protyle/wysiwyg/commonHotkey.ts@@ -19,26 +19,26 @@ import {remapTabsDOMIDs} from "../util/tabsCopy";import {isEncryptedBox} from "../../util/pathName";import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";import {captureCommandContext} from "../../command/context";-import {resolvePluginCommandCallback, supportsPluginCommandSource} from "../../plugin/commandAdapter";+import {dispatchPluginShortcut} from "../../command/shortcutRuntime";import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";import {waitForPendingTransactions} from "../util/transactionQueue";export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElement?: HTMLElement) => {- if (matchHotKey(window.siyuan.config.keymap.editor.general.netImg2LocalAsset.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.netImg2LocalAsset, event)) {net2LocalAssets(protyle, "Img");event.preventDefault();event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.netAssets2LocalAssets.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.netAssets2LocalAssets, event)) {net2LocalAssets(protyle, "Assets");event.preventDefault();event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.optimizeTypography.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.optimizeTypography, event)) {fetchPost("/api/format/autoSpace", {id: protyle.block.rootID});@@ -46,7 +46,7 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemenevent.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyHPath.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyHPath, event)) {fetchPost("/api/filetree/getHPathByID", {id: protyle.block.rootID}, (response) => {@@ -57,7 +57,7 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemenreturn true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocolInMd.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocolInMd, event)) {if (nodeElement) {const selectElements = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));if (selectElements.length === 0) {@@ -72,7 +72,7 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemenreturn true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyID.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyID, event)) {if (nodeElement) {const selectElements = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));if (selectElements.length === 0) {@@ -86,7 +86,7 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemenevent.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocol.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyProtocol, event)) {if (nodeElement) {const selectElements = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));if (selectElements.length === 0) {@@ -101,7 +101,7 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemenreturn true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockEmbed.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyBlockEmbed, event)) {if (nodeElement) {const selectElements = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));if (selectElements.length === 0) {@@ -117,29 +117,10 @@ export const commonHotkey = (protyle: IProtyle, event: KeyboardEvent, nodeElemen}/// #if !MOBILEif (areProtylePluginExtensionsEnabled(protyle)) {- let matchedCommand: ICommand | undefined;- protyle.app.plugins.find(item => {- item.commands.find(command => {- if (supportsPluginCommandSource(command, "editorShortcut") &&- matchHotKey(command.customHotkey, event)) {- matchedCommand = command;- return true;- }- });- return Boolean(matchedCommand);- });- if (matchedCommand) {- const commandContext = captureCommandContext({- app: protyle.app,- source: "editorShortcut",- protyle,- range: protyle.toolbar.range,- });- const callback = resolvePluginCommandCallback(matchedCommand, commandContext);- if (callback) {- void callback();- return true;- }+ if (dispatchPluginShortcut(protyle.app, event, "editorShortcut", () => captureCommandContext({+ app: protyle.app, source: "editorShortcut", protyle, range: protyle.toolbar.range,+ }))) {+ return true;}}/// #endif@@ -162,7 +143,7 @@ export const upSelect = (options: {const nodeEditableElement = (tdElement || getContenteditableElement(options.nodeElement) || options.nodeElement) as HTMLElement;const startIndex = getSelectionOffset(nodeEditableElement, options.editorElement, options.range).start;const innerText = nodeEditableElement.innerText;- const isExpandUp = matchHotKey(window.siyuan.config.keymap.editor.general.expandUp.custom, options.event);+ const isExpandUp = matchHotKey(window.siyuan.config.keymap.editor.general.expandUp, options.event);if (!isMac() && isExpandUp) {// Windows 中 ⌥⇧↑ 默认无选中功能会导致 https://ld246.com/article/1716635371149} else if (startIndex > 0) {@@ -209,7 +190,7 @@ export const downSelect = (options: {const nodeEditableElement = (tdElement || getContenteditableElement(options.nodeElement) || options.nodeElement) as HTMLElement;const endIndex = getSelectionOffset(nodeEditableElement, options.editorElement, options.range).end;const innerText = nodeEditableElement.innerText;- const isExpandDown = matchHotKey(window.siyuan.config.keymap.editor.general.expandDown.custom, options.event);+ const isExpandDown = matchHotKey(window.siyuan.config.keymap.editor.general.expandDown, options.event);if (!isMac() && isExpandDown) {// Windows 中 ⌥⇧↓ 默认无选中功能会导致 https://ld246.com/article/1716635371149} else if (endIndex < innerText.length) {diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex cf5ed0871a..60bdc7eb1d 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -61,6 +61,7 @@ import {isNotEditBlock,} from "./getBlock";import {isIncludesHotKey, matchHotKey} from "../util/hotKey";+import {getToolbarHotkey} from "../toolbar/hotkey";import {enter, softEnter} from "./enter";import {clearTableCell, fixTable, isIncludeCell} from "../util/table";import {@@ -653,7 +654,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}const nodeType = nodeElement.getAttribute("data-type");- if (matchHotKey(window.siyuan.config.keymap.editor.general.collapse.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.collapse, event) && !event.repeat) {getFoldBlock(protyle, nodeElement, (elements) => {setFold(protyle, elements[0]);});@@ -662,7 +663,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return false;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.expand.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.expand, event) && !event.repeat) {getFoldBlock(protyle, nodeElement, (elements) => {setFold(protyle, elements[0], true);});@@ -671,7 +672,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.foldChildHeadings.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.foldChildHeadings, event) && !event.repeat) {getFoldBlock(protyle, nodeElement, (elements) => {foldHeadingGroup(protyle, elements[0], "children");});@@ -681,7 +682,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.foldSiblingHeadings.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.foldSiblingHeadings, event) && !event.repeat) {getFoldBlock(protyle, nodeElement, (elements) => {foldHeadingGroup(protyle, elements[0], "siblings");});@@ -691,7 +692,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.foldRecursive.custom, event) && !event.repeat) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.foldRecursive, event) && !event.repeat) {getFoldBlock(protyle, nodeElement, (elements) => {foldBlocksRecursively(protyle, elements);});@@ -714,7 +715,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}}- if (matchHotKey(window.siyuan.config.keymap.editor.general.expandUp.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.expandUp, event)) {upSelect({protyle, event, nodeElement, editorElement, range,cb(selectElements) {@@ -742,7 +743,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.expandDown.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.expandDown, event)) {downSelect({protyle, event, nodeElement, editorElement, range,cb(selectElements) {@@ -861,7 +862,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- if (matchHotKey(window.siyuan.config.keymap.general.enter.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.enter, event)) {onlyProtyleCommand({protyle,command: "enter",@@ -872,7 +873,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- if (matchHotKey(window.siyuan.config.keymap.general.enterBack.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.general.enterBack, event)) {onlyProtyleCommand({protyle,command: "enterBack",@@ -884,9 +885,9 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}let selectToPageStart: boolean | undefined;- if (matchHotKey(window.siyuan.config.keymap.editor.general.selectToPageStart.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.selectToPageStart, event)) {selectToPageStart = true;- } else if (matchHotKey(window.siyuan.config.keymap.editor.general.selectToPageEnd.custom, event)) {+ } else if (matchHotKey(window.siyuan.config.keymap.editor.general.selectToPageEnd, event)) {selectToPageStart = false;}if (selectToPageStart !== undefined) {@@ -911,9 +912,9 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {hideElements(["hint"], protyle);}let scrollDirection: "up" | "down" | undefined;- if (matchHotKey(window.siyuan.config.keymap.editor.general.scrollPageUpWithoutMovingCaret.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.scrollPageUpWithoutMovingCaret, event)) {scrollDirection = "up";- } else if (matchHotKey(window.siyuan.config.keymap.editor.general.scrollPageDownWithoutMovingCaret.custom, event)) {+ } else if (matchHotKey(window.siyuan.config.keymap.editor.general.scrollPageDownWithoutMovingCaret, event)) {scrollDirection = "down";}if (scrollDirection) {@@ -1728,14 +1729,14 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.undo.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.undo, event)) {protyle.undo.undo(protyle);event.preventDefault();event.stopPropagation();return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.redo.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.redo, event)) {protyle.undo.redo(protyle);event.preventDefault();event.stopPropagation();@@ -1748,7 +1749,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}/// #endif- if (matchHotKey(window.siyuan.config.keymap.editor.general.copyText.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.copyText, event)) {// 用于标识复制文本 *if (selectText !== "") {// 和复制块引用保持一致 https://github.com/siyuan-note/siyuan/issues/9093@@ -1769,7 +1770,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.attr.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.attr, event)) {const topElement = getTopAloneElement(nodeElement);if (selectText === "") {const selectElements = protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select");@@ -1797,7 +1798,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.rename.custom, event) && !protyle.disabled) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.rename, event) && !protyle.disabled) {if (selectText === "") {const docInfoParam: IObject = {id: protyle.block.rootID@@ -1827,21 +1828,21 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- const isNewNameFile = matchHotKey(window.siyuan.config.keymap.editor.general.newNameFile.custom, event);- if (isNewNameFile || matchHotKey(window.siyuan.config.keymap.editor.general.newNameSettingFile.custom, event)) {+ const isNewNameFile = matchHotKey(window.siyuan.config.keymap.editor.general.newNameFile, event);+ if (isNewNameFile || matchHotKey(window.siyuan.config.keymap.editor.general.newNameSettingFile, event)) {newFileBySelectRange(protyle, range, isNewNameFile ? "subDoc" : "configured");event.preventDefault();event.stopPropagation();return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.newContentFile.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.newContentFile, event)) {newFileContentBySelect(protyle);event.preventDefault();event.stopPropagation();return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.alignLeft.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.alignLeft, event)) {const imgSelectElements = nodeElement.querySelectorAll(".img--select");if (imgSelectElements.length > 0) {alignImgLeft(protyle, nodeElement, Array.from(imgSelectElements), nodeElement.getAttribute("data-node-id"), nodeElement.outerHTML);@@ -1865,7 +1866,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.alignCenter.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.alignCenter, event)) {const imgSelectElements = nodeElement.querySelectorAll(".img--select");if (imgSelectElements.length > 0) {alignImgCenter(protyle, nodeElement, Array.from(imgSelectElements), nodeElement.getAttribute("data-node-id"), nodeElement.outerHTML);@@ -1889,7 +1890,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.alignRight.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.alignRight, event)) {let selectElements: HTMLElement[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));if (selectElements.length === 0 && !range.collapsed) {selectElements = getBlockElementsByRange(range);@@ -1908,7 +1909,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.rtl.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.rtl, event)) {let selectElements: HTMLElement[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));if (selectElements.length === 0) {selectElements = [nodeElement];@@ -1920,7 +1921,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.preventDefault();return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.ltr.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.ltr, event)) {let selectElements: HTMLElement[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));if (selectElements.length === 0) {selectElements = [nodeElement];@@ -1978,7 +1979,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}// h1 - h6 hotkey- if (matchHotKey(window.siyuan.config.keymap.editor.heading.paragraph.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.heading.paragraph, event)) {if (turnCrossBlockRangeInto("Blocks2Ps")) {return true;}@@ -2027,7 +2028,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading1.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading1, event)) {if (turnCrossBlockRangeInto("Blocks2Hs", 1)) {return true;}@@ -2041,7 +2042,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading2.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading2, event)) {if (turnCrossBlockRangeInto("Blocks2Hs", 2)) {return true;}@@ -2055,7 +2056,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading3.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading3, event)) {if (turnCrossBlockRangeInto("Blocks2Hs", 3)) {return true;}@@ -2069,7 +2070,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading4.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading4, event)) {if (turnCrossBlockRangeInto("Blocks2Hs", 4)) {return true;}@@ -2083,7 +2084,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading5.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading5, event)) {if (turnCrossBlockRangeInto("Blocks2Hs", 5)) {return true;}@@ -2097,7 +2098,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading6.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.heading.heading6, event)) {if (turnCrossBlockRangeInto("Blocks2Hs", 6)) {return true;}@@ -2111,7 +2112,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.insert.code.custom, event) &&+ if (matchHotKey(window.siyuan.config.keymap.editor.insert.code, event) &&!["NodeCodeBlock", "NodeHeading", "NodeTable"].includes(nodeType) &&!isInEmbedBlock(nodeElement)) {if (turnParagraphIntoCode(protyle, nodeElement)) {@@ -2141,7 +2142,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return true;}}- if (matchHotKey(window.siyuan.config.keymap.editor.insert.lastUsed.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.insert.lastUsed, event)) {protyle.toolbar.range = range;const selectElements: Element[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));if (selectText === "" && selectElements.length === 0) {@@ -2156,10 +2157,10 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {if ((!nodeElement.classList.contains("code-block") || isCrossBlock) && !event.repeat) {let findToolbar = false;protyle.options.toolbar.find((menuItem: IMenuItem) => {- if (!menuItem.hotkey || menuItem.name === "ai") {+ if (menuItem.name === "ai") {return false;}- if (matchHotKey(menuItem.hotkey, event)) {+ if (matchHotKey(getToolbarHotkey(menuItem), event)) {// 设置 lastHTMLs 会导致 protyle.toolbar.range 和 range 不一致,需重置一下 https://github.com/siyuan-note/siyuan/issues/10933protyle.toolbar.range = range;if (menuItem.name === "text") {@@ -2186,8 +2187,8 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return true;}}- const isListOutdent = matchHotKey(window.siyuan.config.keymap.editor.list.outdent.custom, event);- const isListIndent = matchHotKey(window.siyuan.config.keymap.editor.list.indent.custom, event);+ const isListOutdent = matchHotKey(window.siyuan.config.keymap.editor.list.outdent, event);+ const isListIndent = matchHotKey(window.siyuan.config.keymap.editor.list.indent, event);const rangeListItemElements = (isListOutdent || isListIndent) && isCrossBlock && selectText !== "" ?getRangeListItemElements(protyle.wysiwyg.element, range) : [];const rangeListItemFocusContext = rangeListItemElements.length > 0 ?@@ -2243,10 +2244,10 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return true;}}- const isMatchList = matchHotKey(window.siyuan.config.keymap.editor.insert.list.custom, event);- const isMatchCheck = matchHotKey(window.siyuan.config.keymap.editor.insert.check.custom, event);- const isMatchOList = matchHotKey(window.siyuan.config.keymap.editor.insert["ordered-list"].custom, event);- const isMatchQuote = matchHotKey(window.siyuan.config.keymap.editor.insert.quote.custom, event);+ const isMatchList = matchHotKey(window.siyuan.config.keymap.editor.insert.list, event);+ const isMatchCheck = matchHotKey(window.siyuan.config.keymap.editor.insert.check, event);+ const isMatchOList = matchHotKey(window.siyuan.config.keymap.editor.insert["ordered-list"], event);+ const isMatchQuote = matchHotKey(window.siyuan.config.keymap.editor.insert.quote, event);if ((isMatchList || isMatchOList || isMatchCheck || isMatchQuote) && !isInEmbedBlock(nodeElement)) {const rangeElements = isCrossBlock && selectText !== "" ? getBlockElementsByRange(range) : [];if (rangeElements.length > 1 && !rangeElements.some(item => item.classList.contains("li"))) {@@ -2418,7 +2419,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- if (matchHotKey(window.siyuan.config.keymap.editor.insert.table.custom, event) &&+ if (matchHotKey(window.siyuan.config.keymap.editor.insert.table, event) &&!isInEmbedBlock(nodeElement)) {protyle.hint.splitChar = "/";protyle.hint.lastIndex = -1;@@ -2428,7 +2429,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- if (matchHotKey(window.siyuan.config.keymap.editor.list.prependListItem.custom, event) &&+ if (matchHotKey(window.siyuan.config.keymap.editor.list.prependListItem, event) &&!isInEmbedBlock(nodeElement) && getAppendListContext(nodeElement, protyle.wysiwyg.element)) {void prependListItem(protyle, nodeElement, range);event.preventDefault();@@ -2436,7 +2437,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.list.appendListItem.custom, event) &&+ if (matchHotKey(window.siyuan.config.keymap.editor.list.appendListItem, event) &&!isInEmbedBlock(nodeElement) && getAppendListContext(nodeElement, protyle.wysiwyg.element)) {void appendListItem(protyle, nodeElement, range);event.preventDefault();@@ -2444,7 +2445,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.list.checkToggle.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.list.checkToggle, event)) {const taskItemElement = hasClosestByAttribute(range.startContainer, "data-subtype", "t");if (!taskItemElement) {return;@@ -2454,7 +2455,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.stopPropagation();return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.insertBefore.custom, event) &&+ if (matchHotKey(window.siyuan.config.keymap.editor.general.insertBefore, event) &&!isInEmbedBlock(nodeElement)) {// https://github.com/siyuan-note/siyuan/issues/14290#issuecomment-2846594701nodeElement.querySelector(".img--select")?.classList.remove("img--select");@@ -2462,7 +2463,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.preventDefault();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.insertAfter.custom, event) &&+ if (matchHotKey(window.siyuan.config.keymap.editor.general.insertAfter, event) &&!isInEmbedBlock(nodeElement)) {nodeElement.querySelector(".img--select")?.classList.remove("img--select");insertEmptyBlock(protyle, "afterend");@@ -2470,54 +2471,54 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.insertSuperBlockLeft.custom, event) &&+ if (matchHotKey(window.siyuan.config.keymap.editor.general.insertSuperBlockLeft, event) &&!isInEmbedBlock(nodeElement)) {insertEmptySuperBlockColumn(protyle, "left");event.preventDefault();event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.insertSuperBlockRight.custom, event) &&+ if (matchHotKey(window.siyuan.config.keymap.editor.general.insertSuperBlockRight, event) &&!isInEmbedBlock(nodeElement)) {insertEmptySuperBlockColumn(protyle, "right");event.preventDefault();event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.jumpToParentNext.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.jumpToParentNext, event)) {jumpToParent(protyle, nodeElement, "next");event.preventDefault();event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.jumpToParent.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.jumpToParent, event)) {jumpToParent(protyle, nodeElement, "parent");event.preventDefault();event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.jumpToParentPrev.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.jumpToParentPrev, event)) {jumpToParent(protyle, nodeElement, "previous");event.preventDefault();event.stopPropagation();return true;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.moveToUp.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.moveToUp, event)) {event.preventDefault();event.stopPropagation();moveToUp(protyle, nodeElement, range);return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.moveToDown.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.moveToDown, event)) {event.preventDefault();event.stopPropagation();moveToDown(protyle, nodeElement, range);return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.vLayout.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.vLayout, event)) {event.preventDefault();event.stopPropagation();const selectsElement = getSuperBlockSelectElements();@@ -2546,7 +2547,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- if (matchHotKey(window.siyuan.config.keymap.editor.general.hLayout.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.hLayout, event)) {event.preventDefault();event.stopPropagation();const selectsElement = getSuperBlockSelectElements();@@ -2575,7 +2576,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.ai.custom, event)) {+ if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.ai, event)) {event.preventDefault();event.stopPropagation();if (!range.collapsed && protyle.wysiwyg.element.contains(range.startContainer) &&@@ -2591,14 +2592,14 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {return;}- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.aiWriting.custom, event)) {+ if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.aiWriting, event)) {event.preventDefault();event.stopPropagation();AIChat(protyle, nodeElement);return;}- if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.openInNewTab.custom, event)) {+ if (!event.repeat && matchHotKey(window.siyuan.config.keymap.editor.general.openInNewTab, event)) {event.preventDefault();event.stopPropagation();const blockPanel = window.siyuan.blockPanels.find(item => {@@ -2671,7 +2672,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {const refElement = hasClosestByAttribute(range.startContainer, "data-type", "block-ref");if (refElement) {const id = refElement.getAttribute("data-id");- if (matchHotKey(window.siyuan.config.keymap.editor.general.openBy.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.openBy, event)) {checkFold(id, (zoomIn, action, isRoot) => {if (!isRoot) {action.push(Constants.CB_GET_HL);@@ -2687,7 +2688,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.preventDefault();event.stopPropagation();return true;- } else if (matchHotKey(window.siyuan.config.keymap.editor.general.refTab.custom, event)) {+ } else if (matchHotKey(window.siyuan.config.keymap.editor.general.refTab, event)) {// 打开块引和编辑器中引用、反链、书签中点击事件需保持一致,都加载上下文checkFold(id, (zoomIn) => {openFileById({@@ -2702,7 +2703,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.preventDefault();event.stopPropagation();return true;- } else if (matchHotKey(window.siyuan.config.keymap.editor.general.insertRight.custom, event)) {+ } else if (matchHotKey(window.siyuan.config.keymap.editor.general.insertRight, event)) {checkFold(id, (zoomIn, action, isRoot) => {if (!isRoot) {action.push(Constants.CB_GET_HL);@@ -2719,7 +2720,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.preventDefault();event.stopPropagation();return true;- } else if (matchHotKey(window.siyuan.config.keymap.editor.general.insertBottom.custom, event)) {+ } else if (matchHotKey(window.siyuan.config.keymap.editor.general.insertBottom, event)) {checkFold(id, (zoomIn, action, isRoot) => {if (!isRoot) {action.push(Constants.CB_GET_HL);@@ -2736,7 +2737,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {event.preventDefault();event.stopPropagation();return true;- } else if (matchHotKey(window.siyuan.config.keymap.editor.general.refPopover.custom, event)) {+ } else if (matchHotKey(window.siyuan.config.keymap.editor.general.refPopover, event)) {// open popoverwindow.siyuan.blockPanels.push(new BlockPanel({app: protyle.app,@@ -2761,7 +2762,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}/// #if !BROWSER- if (matchHotKey(window.siyuan.config.keymap.editor.general.showInFolder.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.showInFolder, event)) {const aElement = hasClosestByAttribute(range.startContainer, "data-type", "a");if (aElement) {const linkAddress = aElement.getAttribute("data-href");@@ -2775,7 +2776,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {}/// #endif- if (matchHotKey(window.siyuan.config.keymap.editor.general.openBy.custom, event)) {+ if (matchHotKey(window.siyuan.config.keymap.editor.general.openBy, event)) {const aElement = hasClosestByAttribute(range.startContainer, "data-type", "a");if (aElement) {openLink(protyle.app, aElement.getAttribute("data-href"), undefined, false);diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex cf04b30280..3b9b2f0ad7 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -1282,6 +1282,13 @@ declare namespace Config {* SiYuan shortcut key*/export interface IKey {+ /** 多快捷键配置,custom 保留第一项以兼容单快捷键调用方。 */+ bindings?: {+ version: 1;+ keys: string[];+ defaults?: string[];+ priority?: Record<string, number>;+ };/*** Custom shortcut key*/diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex a88c28335f..966af62a15 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -904,6 +904,9 @@ interface ICommand {langText?: string, // 显示的文本, 指定后不再使用 langKey 对应的 i18n 文本hotkey?: string, // 快捷键,默认为空字符串customHotkey?: string,+ hotkeys?: string[], // 默认快捷键列表,优先于 hotkey+ when?: (context: ICommandContext) => boolean,+ enabled?: (context: ICommandContext) => boolean,execute?: (context: ICommandContext) => void | Promise<void>callback?: (context?: ICommandContext) => void // 其余回调存在时将不会触发globalCallback?: (context?: ICommandContext) => void // 焦点不在应用内时执行的回调@@ -1035,6 +1038,7 @@ interface IGraphCommon {}interface IKeymapItem {+ bindings?: Config.IKey["bindings"],default: string,custom: string}diff --git a/app/src/util/hotKeyPolicy.ts b/app/src/util/hotKeyPolicy.tsindex bbe47a80db..6f1979cf40 100644--- a/app/src/util/hotKeyPolicy.ts+++ b/app/src/util/hotKeyPolicy.ts@@ -1,3 +1,5 @@+import {getKeymapBindings, IShortcutKeymap, setKeymapBindings} from "./keymapBindings";+const MODIFIER_KEYS = "⌃⌥⇧⌘";const NON_CHARACTER_KEYS = new Set(["←", "↑", "→", "↓", "⇥", "⌫", "⌦", "↩"]);const RESERVED_KEYMAPS = new Set(["⌘A", "⌘X", "⌘C", "⌘V", "⌘-", "⌘=", "⌘0", "⇧⌘V", "⌘/", "⇧↑", "⇧↓", "⇧→", "⇧←", "⇧⇥",@@ -45,6 +47,15 @@ export const clearDisallowedKeymapItems = () => {let changed = false;Object.values(keymap || {}).forEach((item) => {+ const multi = item as IShortcutKeymap;+ if (multi.bindings?.version === 1) {+ const keys = getKeymapBindings(multi);+ const allowed = keys.filter(key => !isDisallowedTextInputHotkey(key));+ if (allowed.length !== keys.length || multi.custom !== (allowed[0] || "")) {+ setKeymapBindings(multi, allowed);+ changed = true;+ }+ }if (typeof item.custom === "string") {const custom = clearDisallowedTextInputHotkey(item.custom);if (custom !== item.custom) {diff --git a/app/src/util/keymapBindings.test.ts b/app/src/util/keymapBindings.test.tsnew file mode 100644index 0000000000..4a688a926f--- /dev/null+++ b/app/src/util/keymapBindings.test.ts@@ -0,0 +1,68 @@+import * as assert from "node:assert/strict";+import test from "node:test";+import {getDefaultKeymapBindings, getKeymapBindings, getKeymapItem, IShortcutKeymap, mergeKeymapDefault, normalizeShortcutKey,+ setKeymapBindings, visitKeymapItems} from "./keymapBindings";+import {clearDisallowedKeymapItems} from "./hotKeyPolicy";++test("legacy bindings preserve custom keys and explicitly cleared shortcuts", () => {+ assert.deepEqual(getKeymapBindings({default: "⌘K", custom: "⌘J"}), ["⌘J"]);+ assert.deepEqual(getKeymapBindings({default: "⌘K", custom: ""}), []);+ const item: IShortcutKeymap = {default: "⌘K", custom: "⌘J"};+ setKeymapBindings(item, ["⌘J", "⌘L", "⌘J"]);+ assert.deepEqual(getKeymapBindings(JSON.parse(JSON.stringify(item))), ["⌘J", "⌘L"]);+ assert.equal(item.custom, "⌘J");+ setKeymapBindings(item, []);+ assert.equal(item.custom, "");+ assert.deepEqual(getKeymapBindings(item), []);+});++test("default changes preserve custom bindings and unknown configuration fields", () => {+ const item = {default: "⌘K", custom: "⌘J", extra: {value: 1}, bindings: {version: 1 as const, keys: ["⌘J", "⌘L"]}};+ const merged = mergeKeymapDefault(item, {default: "⌘M", custom: "⌘M"} as typeof item);+ assert.equal(merged.default, "⌘M");+ assert.deepEqual(merged.bindings, item.bindings);+ assert.deepEqual(merged.extra, {value: 1});+ assert.equal(item.default, "⌘K");+});++test("unsupported binding formats are preserved and cannot be overwritten", () => {+ const item = {default: "⌘K", custom: "⌘J", bindings: {version: 2, keys: ["⌘L"]}} as unknown as IShortcutKeymap;+ const original = JSON.stringify(item);+ assert.deepEqual(getKeymapBindings(item), []);+ assert.throws(() => setKeymapBindings(item, ["⌘M"]), /Unsupported/);+ assert.equal(JSON.stringify(item), original);+});++test("removing a binding drops only its priorities and retains plugin defaults", () => {+ const item: IShortcutKeymap = {custom: "⌘J", bindings: {version: 1, keys: ["⌘J", "⌘L"],+ defaults: ["⌘K", "⌘M"], priority: {"editor:⌘J": 2, "global:⌘L": 5}}};+ setKeymapBindings(item, ["⌘L"]);+ assert.deepEqual(item.bindings.priority, {"global:⌘L": 5});+ assert.deepEqual(getDefaultKeymapBindings(item), ["⌘K", "⌘M"]);+ assert.equal(item.custom, "⌘L");+});++test("unsafe text input bindings are removed from the full list", () => {+ const item = {default: "⌘K", custom: "A", bindings: {version: 1 as const, keys: ["A", "⇧B", "⌘L"]}};+ assert.equal(clearDisallowedKeymapItems({item}), true);+ assert.deepEqual(getKeymapBindings(item), ["⌘L"]);+ assert.equal(item.custom, "⌘L");+ assert.equal(clearDisallowedKeymapItems({item}), false);+});++test("walking bindings includes unloaded plugins without traversing extension data", () => {+ const keymap = {general: {test: {custom: "⌘K"}}, editor: {insert: {bold: {custom: "⌘B"}}},+ plugin: {unloaded: {action: {custom: "⌘L", bindings: {version: 1, keys: ["⌘L", "⌘M"]}}}}};+ const paths: string[][] = [];+ visitKeymapItems(keymap, (_item, path) => paths.push(path));+ assert.deepEqual(paths, [["general", "test"], ["editor", "insert", "bold"], ["plugin", "unloaded", "action"]]);+ assert.equal(getKeymapItem(keymap, ["general", "test"]).custom, "⌘K");+ assert.equal(getKeymapItem(keymap, ["__proto__", "test"]), undefined);+});++test("portable modifier normalization retains the platform-specific deletion exception", () => {+ assert.equal(normalizeShortcutKey("⌃⇧K", false), "⇧⌘K");+ assert.equal(normalizeShortcutKey("⌃⌥⇧K", false), "⌥⇧⌘K");+ assert.equal(normalizeShortcutKey("⌃D", false), "");+ assert.equal(normalizeShortcutKey("⌃D", true), "⌃D");+});diff --git a/app/src/util/keymapBindings.ts b/app/src/util/keymapBindings.tsnew file mode 100644index 0000000000..6d5dbade07--- /dev/null+++ b/app/src/util/keymapBindings.ts@@ -0,0 +1,82 @@+export interface IShortcutBindings {+ version: 1;+ keys: string[];+ defaults?: string[];+ priority?: Record<string, number>;+}++export const normalizeShortcutKey = (key: string, mac: boolean) => {+ if (mac || !key.startsWith("⌃")) {+ return key;+ }+ if (key === "⌃D") {+ return "";+ }+ return key.replace("⌘", "").replace("⌃", "⌘")+ .replace("⌘⇧", "⇧⌘").replace("⌘⌥⇧", "⌥⇧⌘").replace("⌘⌥", "⌥⌘");+};++export const getDefaultKeymapBindings = (item: IShortcutKeymap): string[] =>+ item.bindings?.version === 1 && Array.isArray(item.bindings.defaults) ?+ [...new Set(item.bindings.defaults.filter(key => typeof key === "string" && key.length > 0))] :+ item.default ? [item.default] : [];++export interface IShortcutKeymap {+ custom: string;+ default?: string;+ bindings?: IShortcutBindings;+}++export const getKeymapBindings = (item?: IShortcutKeymap): string[] => {+ if (!item) {+ return [];+ }+ if (item.bindings) {+ if (item.bindings.version !== 1 || !Array.isArray(item.bindings.keys)) {+ return [];+ }+ return [...new Set(item.bindings.keys.filter(key => typeof key === "string" && key.length > 0))];+ }+ return typeof item.custom === "string" && item.custom ? [item.custom] : [];+};++export const setKeymapBindings = (item: IShortcutKeymap, keys: string[]) => {+ if (item.bindings && item.bindings.version !== 1) {+ throw new Error("Unsupported shortcut binding version");+ }+ const uniqueKeys = [...new Set(keys.filter(Boolean))];+ const priority = Object.fromEntries(Object.entries(item.bindings?.priority || {})+ .filter(([key]) => uniqueKeys.some(hotkey => key === hotkey || key.endsWith(":" + hotkey))));+ item.bindings = {...item.bindings, version: 1, keys: uniqueKeys, priority};+ item.custom = uniqueKeys[0] || "";+};++export const getKeymapItem = (keymap: object, path: readonly string[]): IShortcutKeymap | undefined => {+ let value: unknown = keymap;+ for (const key of path) {+ if (!value || typeof value !== "object" || !Object.prototype.hasOwnProperty.call(value, key)) {+ return undefined;+ }+ value = (value as Record<string, unknown>)[key];+ }+ return value && typeof value === "object" && typeof (value as IShortcutKeymap).custom === "string" ?+ value as IShortcutKeymap : undefined;+};++export const visitKeymapItems = (keymap: object, visit: (item: IShortcutKeymap, path: string[]) => void) => {+ const walk = (value: unknown, path: string[]) => {+ if (!value || typeof value !== "object") {+ return;+ }+ if (typeof (value as IShortcutKeymap).custom === "string") {+ visit(value as IShortcutKeymap, path);+ return;+ }+ Object.entries(value).forEach(([key, item]) => walk(item, [...path, key]));+ };+ ["general", "editor", "plugin"].forEach(key => walk((keymap as Record<string, unknown>)[key], [key]));+};++// 默认值更新时保留用户绑定及扩展字段。+export const mergeKeymapDefault = <T extends IShortcutKeymap>(item: T | undefined, template: T): T =>+ item ? {...item, default: template.default} : JSON.parse(JSON.stringify(template));