Skip to content

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

:sparkles: Improve template manager navigation and preview context https://github.com/siyuan-note/siyuan/issues/19167

Daniel4091a7bf21b5
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 5ad4332529..696e04ae1d 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,7 @@
{
+ "templateSearch": "البحث عن القوالب بالاسم أو المسار",
+ "templateContextSearch": "البحث عن مستندات السياق",
+ "templateContextTip": "تشغيل القالب باستخدام عنوان المستند المحدد ومعرّفه ومعلوماته الأخرى دون تعديل المستند",
"fileTreeDragRemoveSorts": "تتعارض هذه النقلة مع قاعدة الفرز الحالية. هل تريد تحويل هذه القائمة إلى ترتيب مخصص وحفظ الترتيب الكامل بعد السحب؟",
"pasteAndKeepSourceFormat": "لصق مع الاحتفاظ بتنسيق المصدر",
"templatePackageMoveTip": "لا يمكن إعادة تسمية مجلدات حزم القوالب أو نقلها",
@@ -6,7 +9,7 @@
"templateManager": "إدارة القوالب",
"templateSource": "مصدر القالب",
"templatePreview": "معاينة القالب",
- "templateContext": "مستند المعاينة",
+ "templateContext": "سياق المعاينة",
"templateNewFolder": "مجلد جديد",
"templateDeleteTip": "هل تريد حذف هذا العنصر وكل محتوياته؟ تُحفظ الملفات المحذوفة في data/templates/.trash لاستعادتها.",
"task": "مهمة",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index c214fda2bd..dc45259241 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,7 @@
{
+ "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",
"fileTreeDragRemoveSorts": "Diese Verschiebung widerspricht der aktuellen Sortierregel. Diese Liste auf benutzerdefinierte Sortierung umstellen und die vollständige Reihenfolge nach dem Ziehen speichern?",
"pasteAndKeepSourceFormat": "Einfügen und Quellformatierung beibehalten",
"templatePackageMoveTip": "Ordner von Vorlagenpaketen können nicht umbenannt oder verschoben werden",
@@ -6,7 +9,7 @@
"templateManager": "Vorlagenverwaltung",
"templateSource": "Vorlagenquelltext",
"templatePreview": "Vorlage anzeigen",
- "templateContext": "Vorschaudokument",
+ "templateContext": "Vorschaukontext",
"templateNewFolder": "Neuer Ordner",
"templateDeleteTip": "Dieses Element und seinen gesamten Inhalt löschen? Gelöschte Dateien bleiben zur Wiederherstellung unter data/templates/.trash erhalten.",
"task": "Aufgabe",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 843e2fbf0a..5750247ae0 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,7 @@
{
+ "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",
"fileTreeDragRemoveSorts": "This move conflicts with the current sort rule. Switch this list to custom sorting and save the complete order after dragging?",
"pasteAndKeepSourceFormat": "Paste and keep source formatting",
"templatePackageMoveTip": "Template package folders cannot be renamed or moved",
@@ -6,7 +9,7 @@
"templateManager": "Template manager",
"templateSource": "Template source",
"templatePreview": "Preview template",
- "templateContext": "Preview document",
+ "templateContext": "Preview context",
"templateNewFolder": "New folder",
"templateDeleteTip": "Delete this item and all its contents? Deleted files are retained in data/templates/.trash for recovery.",
"task": "Task",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index d17cbfc6e2..e94fe7035f 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,7 @@
{
+ "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",
"fileTreeDragRemoveSorts": "Este movimiento entra en conflicto con la regla de ordenación actual. ¿Cambiar esta lista a ordenación personalizada y guardar el orden completo después de arrastrar?",
"pasteAndKeepSourceFormat": "Pegar y conservar el formato de origen",
"templatePackageMoveTip": "Las carpetas de paquetes de plantillas no se pueden renombrar ni mover",
@@ -6,7 +9,7 @@
"templateManager": "Gestor de plantillas",
"templateSource": "Código de la plantilla",
"templatePreview": "Vista previa de la plantilla",
- "templateContext": "Documento de vista previa",
+ "templateContext": "Contexto de vista previa",
"templateNewFolder": "Nueva carpeta",
"templateDeleteTip": "¿Eliminar este elemento y todo su contenido? Los archivos eliminados se conservan en data/templates/.trash para recuperarlos.",
"task": "Tarea",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index bfffbadf9a..8d38cfeca5 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,7 @@
{
+ "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",
"fileTreeDragRemoveSorts": "Ce déplacement est incompatible avec la règle de tri actuelle. Passer cette liste au tri personnalisé et enregistrer l’ordre complet après le déplacement ?",
"pasteAndKeepSourceFormat": "Coller en conservant la mise en forme source",
"templatePackageMoveTip": "Les dossiers de paquets de modèles ne peuvent pas être renommés ni déplacés",
@@ -6,7 +9,7 @@
"templateManager": "Gestionnaire de modèles",
"templateSource": "Source du modèle",
"templatePreview": "Aperçu du modèle",
- "templateContext": "Document d’aperçu",
+ "templateContext": "Contexte de l’aperçu",
"templateNewFolder": "Nouveau dossier",
"templateDeleteTip": "Supprimer cet élément et tout son contenu ? Les fichiers supprimés sont conservés dans data/templates/.trash pour permettre leur restauration.",
"task": "Tâche",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 1d0d7a4fc7..42877ac601 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,7 @@
{
+ "templateSearch": "חיפוש תבניות לפי שם או נתיב",
+ "templateContextSearch": "חיפוש מסמכי הקשר",
+ "templateContextTip": "הפעלת התבנית באמצעות הכותרת, המזהה ומידע נוסף מהמסמך שנבחר, ללא שינוי המסמך",
"fileTreeDragRemoveSorts": "העברה זו מתנגשת עם כלל המיון הנוכחי. להעביר רשימה זו למיון מותאם אישית ולשמור את הסדר המלא לאחר הגרירה?",
"pasteAndKeepSourceFormat": "הדבק ושמור על עיצוב המקור",
"templatePackageMoveTip": "לא ניתן לשנות שם או להעביר תיקיות של חבילות תבניות",
@@ -6,7 +9,7 @@
"templateManager": "מנהל תבניות",
"templateSource": "מקור התבנית",
"templatePreview": "תצוגה מקדימה של התבנית",
- "templateContext": "מסמך לתצוגה מקדימה",
+ "templateContext": "הקשר לתצוגה מקדימה",
"templateNewFolder": "תיקייה חדשה",
"templateDeleteTip": "למחוק פריט זה ואת כל תוכנו? הקבצים שנמחקו נשמרים ב־data/templates/.trash לצורך שחזור.",
"task": "משימה",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 8509f21a26..b06bf2de5e 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,7 @@
{
+ "templateSearch": "नाम या पथ से टेम्पलेट खोजें",
+ "templateContextSearch": "संदर्भ दस्तावेज़ खोजें",
+ "templateContextTip": "चुने हुए दस्तावेज़ में बदलाव किए बिना उसके शीर्षक, ID और अन्य जानकारी का उपयोग करके टेम्पलेट चलाएँ",
"fileTreeDragRemoveSorts": "यह स्थानांतरण वर्तमान क्रमबद्ध करने के नियम से मेल नहीं खाता। क्या इस सूची को कस्टम क्रम में बदलकर खींचने के बाद का पूरा क्रम सहेजें?",
"pasteAndKeepSourceFormat": "स्रोत स्वरूपण बनाए रखते हुए चिपकाएँ",
"templatePackageMoveTip": "टेम्पलेट पैकेज फ़ोल्डर का नाम बदलना या उसे स्थानांतरित करना संभव नहीं है",
@@ -6,7 +9,7 @@
"templateManager": "टेम्पलेट प्रबंधक",
"templateSource": "टेम्पलेट स्रोत",
"templatePreview": "टेम्पलेट पूर्वावलोकन",
- "templateContext": "पूर्वावलोकन दस्तावेज़",
+ "templateContext": "पूर्वावलोकन संदर्भ",
"templateNewFolder": "नया फ़ोल्डर",
"templateDeleteTip": "क्या यह आइटम और इसकी सारी सामग्री हटाएँ? हटाई गई फ़ाइलें पुनर्स्थापना के लिए data/templates/.trash में रखी जाती हैं।",
"task": "कार्य",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 04cd825eb2..0b4e14a3f5 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,7 @@
{
+ "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",
"fileTreeDragRemoveSorts": "Pemindahan ini bertentangan dengan aturan pengurutan saat ini. Alihkan daftar ini ke pengurutan khusus dan simpan urutan lengkap setelah menyeret?",
"pasteAndKeepSourceFormat": "Tempel dan pertahankan pemformatan sumber",
"templatePackageMoveTip": "Folder paket templat tidak dapat diganti namanya atau dipindahkan",
@@ -6,7 +9,7 @@
"templateManager": "Pengelola templat",
"templateSource": "Sumber templat",
"templatePreview": "Pratinjau templat",
- "templateContext": "Dokumen pratinjau",
+ "templateContext": "Konteks pratinjau",
"templateNewFolder": "Folder baru",
"templateDeleteTip": "Hapus item ini beserta seluruh isinya? Berkas yang dihapus disimpan di data/templates/.trash untuk dipulihkan.",
"task": "Tugas",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 81925335f1..e2274e6c48 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,7 @@
{
+ "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",
"fileTreeDragRemoveSorts": "Questo spostamento è in conflitto con la regola di ordinamento attuale. Passare questa lista all’ordinamento personalizzato e salvare l’ordine completo dopo il trascinamento?",
"pasteAndKeepSourceFormat": "Incolla mantenendo la formattazione originale",
"templatePackageMoveTip": "Le cartelle dei pacchetti di modelli non possono essere rinominate o spostate",
@@ -6,7 +9,7 @@
"templateManager": "Gestione modelli",
"templateSource": "Sorgente del modello",
"templatePreview": "Anteprima del modello",
- "templateContext": "Documento di anteprima",
+ "templateContext": "Contesto dell’anteprima",
"templateNewFolder": "Nuova cartella",
"templateDeleteTip": "Eliminare questo elemento e tutto il suo contenuto? I file eliminati vengono conservati in data/templates/.trash per il ripristino.",
"task": "Attività",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index cc0417ef75..cece54714c 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,7 @@
{
+ "templateSearch": "テンプレート名またはパスを検索",
+ "templateContextSearch": "コンテキスト用ドキュメントを検索",
+ "templateContextTip": "選択したドキュメントのタイトルや ID などの情報を使ってテンプレートを実行します。ドキュメントは変更されません",
"fileTreeDragRemoveSorts": "この移動は現在の並び替えルールと競合します。このリストをカスタム順に切り替え、ドラッグ後の全体の順序を保存しますか?",
"pasteAndKeepSourceFormat": "元の書式を保持して貼り付け",
"templatePackageMoveTip": "テンプレートパッケージのフォルダーは名前の変更や移動ができません",
@@ -6,7 +9,7 @@
"templateManager": "テンプレート管理",
"templateSource": "テンプレートのソース",
"templatePreview": "テンプレートをプレビュー",
- "templateContext": "プレビュー用ドキュメント",
+ "templateContext": "プレビューのコンテキスト",
"templateNewFolder": "新しいフォルダー",
"templateDeleteTip": "この項目とその内容をすべて削除しますか?削除したファイルは復元できるように data/templates/.trash に保持されます。",
"task": "タスク",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 656806f57d..d5a7171ea4 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,7 @@
{
+ "templateSearch": "템플릿 이름 또는 경로 검색",
+ "templateContextSearch": "컨텍스트 문서 검색",
+ "templateContextTip": "선택한 문서의 제목, ID 등의 정보로 템플릿을 실행하며 해당 문서는 수정하지 않습니다",
"fileTreeDragRemoveSorts": "이 이동은 현재 정렬 규칙과 충돌합니다. 이 목록을 사용자 지정 정렬로 전환하고 드래그 후의 전체 순서를 저장하시겠습니까?",
"pasteAndKeepSourceFormat": "원본 서식을 유지하여 붙여넣기",
"templatePackageMoveTip": "템플릿 패키지 폴더는 이름을 변경하거나 이동할 수 없습니다",
@@ -6,7 +9,7 @@
"templateManager": "템플릿 관리",
"templateSource": "템플릿 소스",
"templatePreview": "템플릿 미리보기",
- "templateContext": "미리보기 문서",
+ "templateContext": "미리보기 컨텍스트",
"templateNewFolder": "새 폴더",
"templateDeleteTip": "이 항목과 모든 내용을 삭제하시겠습니까? 삭제된 파일은 복구할 수 있도록 data/templates/.trash에 보관됩니다.",
"task": "작업",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 2ae4c1a576..b0bdb11cf6 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,7 @@
{
+ "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",
"fileTreeDragRemoveSorts": "Deze verplaatsing is in strijd met de huidige sorteerregel. Deze lijst omzetten naar een aangepaste sortering en de volledige volgorde na het slepen opslaan?",
"pasteAndKeepSourceFormat": "Plakken met behoud van bronopmaak",
"templatePackageMoveTip": "Mappen van sjabloonpakketten kunnen niet worden hernoemd of verplaatst",
@@ -6,7 +9,7 @@
"templateManager": "Sjabloonbeheer",
"templateSource": "Sjabloonbron",
"templatePreview": "Sjabloonvoorbeeld",
- "templateContext": "Voorbeelddocument",
+ "templateContext": "Voorbeeldcontext",
"templateNewFolder": "Nieuwe map",
"templateDeleteTip": "Dit item en alle inhoud verwijderen? Verwijderde bestanden blijven voor herstel bewaard in data/templates/.trash.",
"task": "Taak",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index b100f26ff4..2d19f7f435 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,7 @@
{
+ "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",
"fileTreeDragRemoveSorts": "To przeniesienie jest sprzeczne z bieżącą regułą sortowania. Przełączyć tę listę na sortowanie niestandardowe i zapisać pełną kolejność po przeciągnięciu?",
"pasteAndKeepSourceFormat": "Wklej z zachowaniem formatowania źródłowego",
"templatePackageMoveTip": "Nie można zmieniać nazw ani przenosić folderów pakietów szablonów",
@@ -6,7 +9,7 @@
"templateManager": "Menedżer szablonów",
"templateSource": "Źródło szablonu",
"templatePreview": "Podgląd szablonu",
- "templateContext": "Dokument podglądu",
+ "templateContext": "Kontekst podglądu",
"templateNewFolder": "Nowy folder",
"templateDeleteTip": "Usunąć ten element i całą jego zawartość? Usunięte pliki są przechowywane w data/templates/.trash, aby można je było przywrócić.",
"task": "Zadanie",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index f78e0185a5..812c200449 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,7 @@
{
+ "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",
"fileTreeDragRemoveSorts": "Este movimento entra em conflito com a regra de ordenação atual. Alterar esta lista para ordenação personalizada e salvar a ordem completa após arrastar?",
"pasteAndKeepSourceFormat": "Colar mantendo a formatação original",
"templatePackageMoveTip": "As pastas de pacotes de modelos não podem ser renomeadas ou movidas",
@@ -6,7 +9,7 @@
"templateManager": "Gerenciador de modelos",
"templateSource": "Código-fonte do modelo",
"templatePreview": "Pré-visualizar modelo",
- "templateContext": "Documento de pré-visualização",
+ "templateContext": "Contexto da pré-visualização",
"templateNewFolder": "Nova pasta",
"templateDeleteTip": "Excluir este item e todo o seu conteúdo? Os arquivos excluídos são mantidos em data/templates/.trash para recuperação.",
"task": "Tarefa",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 0f47ed5a0a..7d2a7dde05 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,7 @@
{
+ "templateSearch": "Поиск шаблонов по имени или пути",
+ "templateContextSearch": "Поиск документов контекста",
+ "templateContextTip": "Выполнить шаблон с заголовком, ID и другими данными выбранного документа, не изменяя сам документ",
"fileTreeDragRemoveSorts": "Это перемещение противоречит текущему правилу сортировки. Переключить этот список на пользовательскую сортировку и сохранить полный порядок после перетаскивания?",
"pasteAndKeepSourceFormat": "Вставить с сохранением исходного форматирования",
"templatePackageMoveTip": "Папки пакетов шаблонов нельзя переименовывать или перемещать",
@@ -6,7 +9,7 @@
"templateManager": "Управление шаблонами",
"templateSource": "Исходный код шаблона",
"templatePreview": "Предпросмотр шаблона",
- "templateContext": "Документ для предпросмотра",
+ "templateContext": "Контекст предпросмотра",
"templateNewFolder": "Новая папка",
"templateDeleteTip": "Удалить этот элемент и всё его содержимое? Удалённые файлы сохраняются в data/templates/.trash для восстановления.",
"task": "Задача",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index fc710123e9..d27b2e3054 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,7 @@
{
+ "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",
"fileTreeDragRemoveSorts": "Tento presun je v rozpore s aktuálnym pravidlom zoradenia. Prepnúť tento zoznam na vlastné zoradenie a uložiť úplné poradie po potiahnutí?",
"pasteAndKeepSourceFormat": "Prilepiť so zachovaním zdrojového formátovania",
"templatePackageMoveTip": "Priečinky balíkov šablón nemožno premenovať ani presunúť",
@@ -6,7 +9,7 @@
"templateManager": "Správca šablón",
"templateSource": "Zdrojový kód šablóny",
"templatePreview": "Náhľad šablóny",
- "templateContext": "Dokument náhľadu",
+ "templateContext": "Kontext náhľadu",
"templateNewFolder": "Nový priečinok",
"templateDeleteTip": "Odstrániť túto položku a celý jej obsah? Odstránené súbory sa uchovajú v data/templates/.trash na obnovenie.",
"task": "Úloha",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 525c8a9606..7795e9062d 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,7 @@
{
+ "templateSearch": "ค้นหาเทมเพลตตามชื่อหรือเส้นทาง",
+ "templateContextSearch": "ค้นหาเอกสารบริบท",
+ "templateContextTip": "เรียกใช้เทมเพลตโดยใช้ชื่อ ID และข้อมูลอื่นจากเอกสารที่เลือก โดยไม่แก้ไขเอกสารนั้น",
"fileTreeDragRemoveSorts": "การย้ายนี้ขัดแย้งกับกฎการเรียงลำดับปัจจุบัน ต้องการเปลี่ยนรายการนี้เป็นการเรียงลำดับแบบกำหนดเองและบันทึกลำดับทั้งหมดหลังลากหรือไม่?",
"pasteAndKeepSourceFormat": "วางโดยคงการจัดรูปแบบต้นฉบับ",
"templatePackageMoveTip": "ไม่สามารถเปลี่ยนชื่อหรือย้ายโฟลเดอร์แพ็กเกจแม่แบบได้",
@@ -6,7 +9,7 @@
"templateManager": "ตัวจัดการแม่แบบ",
"templateSource": "ซอร์สแม่แบบ",
"templatePreview": "ดูตัวอย่างแม่แบบ",
- "templateContext": "เอกสารสำหรับดูตัวอย่าง",
+ "templateContext": "บริบทการดูตัวอย่าง",
"templateNewFolder": "โฟลเดอร์ใหม่",
"templateDeleteTip": "ลบรายการนี้และเนื้อหาทั้งหมดหรือไม่? ไฟล์ที่ลบจะเก็บไว้ใน data/templates/.trash เพื่อให้กู้คืนได้",
"task": "งาน",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index f1e8ebcb48..4dd053f5d2 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,7 @@
{
+ "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",
"fileTreeDragRemoveSorts": "Bu taşıma geçerli sıralama kuralıyla çakışıyor. Bu liste özel sıralamaya geçirilsin ve sürükleme sonrası tam sıralama kaydedilsin mi?",
"pasteAndKeepSourceFormat": "Kaynak biçimlendirmesini koruyarak yapıştır",
"templatePackageMoveTip": "Şablon paketi klasörleri yeniden adlandırılamaz veya taşınamaz",
@@ -6,7 +9,7 @@
"templateManager": "Şablon yöneticisi",
"templateSource": "Şablon kaynağı",
"templatePreview": "Şablonu önizle",
- "templateContext": "Önizleme belgesi",
+ "templateContext": "Önizleme bağlamı",
"templateNewFolder": "Yeni klasör",
"templateDeleteTip": "Bu öğe ve tüm içeriği silinsin mi? Silinen dosyalar kurtarma için data/templates/.trash içinde saklanır.",
"task": "Görev",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index fabc5c95e8..30711f1cab 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,7 @@
{
+ "templateSearch": "Пошук шаблонів за назвою або шляхом",
+ "templateContextSearch": "Пошук документів контексту",
+ "templateContextTip": "Виконати шаблон із заголовком, ID та іншими даними вибраного документа, не змінюючи сам документ",
"fileTreeDragRemoveSorts": "Це переміщення суперечить поточному правилу сортування. Перемкнути цей список на власне сортування та зберегти повний порядок після перетягування?",
"pasteAndKeepSourceFormat": "Вставити зі збереженням вихідного форматування",
"templatePackageMoveTip": "Папки пакетів шаблонів не можна перейменовувати або переміщувати",
@@ -6,7 +9,7 @@
"templateManager": "Керування шаблонами",
"templateSource": "Вихідний код шаблону",
"templatePreview": "Перегляд шаблону",
- "templateContext": "Документ для перегляду",
+ "templateContext": "Контекст попереднього перегляду",
"templateNewFolder": "Нова папка",
"templateDeleteTip": "Видалити цей елемент і весь його вміст? Видалені файли зберігаються в data/templates/.trash для відновлення.",
"task": "Завдання",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index c2938eaca4..ae7adbe239 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,7 @@
{
+ "templateSearch": "搜索模板名称或路径",
+ "templateContextSearch": "搜索上下文文档",
+ "templateContextTip": "使用所选文档的标题、ID 等信息运行模板,不会修改该文档",
"fileTreeDragRemoveSorts": "此次拖拽与当前排序规则冲突,是否将此列表切换为自定义排序,并保存拖拽后的完整顺序?",
"pasteAndKeepSourceFormat": "粘贴并保留源格式",
"templatePackageMoveTip": "模板包文件夹不支持重命名或移动",
@@ -6,7 +9,7 @@
"templateManager": "模板管理",
"templateSource": "模板源码",
"templatePreview": "预览模板",
- "templateContext": "预览文档",
+ "templateContext": "预览上下文",
"templateNewFolder": "新建文件夹",
"templateDeleteTip": "删除此项目及其全部内容?删除的文件将保留在 data/templates/.trash 中,以便恢复。",
"task": "任务",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index bdc472eec5..ab26b51e27 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,7 @@
{
+ "templateSearch": "搜尋範本名稱或路徑",
+ "templateContextSearch": "搜尋上下文文件",
+ "templateContextTip": "使用所選文件的標題、ID 等資訊執行範本,不會修改該文件",
"fileTreeDragRemoveSorts": "此次拖曳與目前排序規則衝突,是否將此清單切換為自訂排序,並儲存拖曳後的完整順序?",
"pasteAndKeepSourceFormat": "貼上並保留來源格式",
"templatePackageMoveTip": "範本套件資料夾不支援重新命名或移動",
@@ -6,7 +9,7 @@
"templateManager": "範本管理",
"templateSource": "範本原始碼",
"templatePreview": "預覽範本",
- "templateContext": "預覽文件",
+ "templateContext": "預覽上下文",
"templateNewFolder": "新增資料夾",
"templateDeleteTip": "刪除此項目及其全部內容?刪除的檔案將保留在 data/templates/.trash 中,以便復原。",
"task": "任務",
diff --git a/app/src/assets/scss/business/_template-manager.scss b/app/src/assets/scss/business/_template-manager.scss
index d7acc3f0d3..80f65e4fa8 100644
--- a/app/src/assets/scss/business/_template-manager.scss
+++ b/app/src/assets/scss/business/_template-manager.scss
@@ -20,21 +20,84 @@
gap: 12px;
}
- &__files {
+ &__sidebar {
+ display: flex;
+ flex-direction: column;
width: 28%;
- overflow: auto;
+ min-width: 0;
+ min-height: 0;
+ gap: 8px;
+ padding-inline-end: 8px;
border-right: 1px solid var(--b3-border-color);
+ }
- button {
- width: 100%;
- text-align: start;
- overflow-wrap: anywhere;
- white-space: normal;
+ &__search {
+ width: 100%;
+ box-sizing: border-box;
+ }
+
+ &__files {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+
+ .b3-list-item {
min-height: 36px;
height: auto;
}
}
+ &__file,
+ &__toggle {
+ display: flex;
+ align-items: center;
+ padding: 0;
+ border: 0;
+ border-radius: var(--b3-border-radius);
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ cursor: pointer;
+
+ &:focus-visible {
+ outline: 1px solid var(--b3-theme-primary);
+ outline-offset: -1px;
+ }
+ }
+
+ &__file {
+ flex: 1;
+ min-width: 0;
+ min-height: 36px;
+ text-align: start;
+
+ .b3-list-item__text {
+ text-align: start;
+ }
+ }
+
+ &__toggle {
+ flex: 0 0 24px;
+ height: 32px;
+ justify-content: center;
+
+ svg {
+ width: 12px;
+ height: 12px;
+ }
+
+ &:disabled {
+ cursor: default;
+ }
+ }
+
+ &__empty {
+ padding: 8px;
+ }
+
&__editor {
display: flex;
flex: 1;
@@ -55,6 +118,21 @@
}
&__context {
+ summary {
+ cursor: pointer;
+ overflow-wrap: anywhere;
+ }
+
+ &-name {
+ margin-inline-start: 8px;
+ }
+
+ > div {
+ margin-top: 8px;
+ }
+ }
+
+ &__context-fields {
display: flex;
flex-wrap: wrap;
align-items: center;
@@ -79,14 +157,15 @@
flex-direction: column;
}
- &__files {
+ &__sidebar {
width: 100%;
- flex: 0 0 120px;
+ flex: 0 0 min(180px, 30vh);
+ padding-inline-end: 0;
border-right: 0;
border-bottom: 1px solid var(--b3-border-color);
}
- &__context {
+ &__context-fields {
input, select {
flex-basis: 100%;
}
diff --git a/app/src/template/actionState.test.ts b/app/src/template/actionState.test.ts
new file mode 100644
index 0000000000..072149598c
--- /dev/null
+++ b/app/src/template/actionState.test.ts
@@ -0,0 +1,34 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {getTemplateActionState} from "./actionState";
+
+describe("template manager action state", () => {
+ it("keeps native button appearance stable while blocking repeated operations", () => {
+ const entry = {path: "note.md", isDir: false};
+ for (const action of ["new", "mkdir", "rename", "move", "remove", "refresh", "save", "preview"]) {
+ const idle = getTemplateActionState(action, entry, true, false);
+ const busy = getTemplateActionState(action, entry, true, true);
+ assert.equal(idle.disabled, false, action);
+ assert.equal(busy.disabled, idle.disabled, action);
+ assert.equal(busy.ariaDisabled, true, action);
+ assert.equal(idle.ariaDisabled, false, action);
+ }
+ });
+
+ it("still disables unavailable actions and protects package directories", () => {
+ for (const busy of [true, false]) {
+ assert.equal(getTemplateActionState("save", {path: "note.md", isDir: false}, false, busy).disabled, true);
+ for (const action of ["save", "preview", "rename", "move", "remove"]) {
+ assert.equal(getTemplateActionState(action, undefined, false, busy).disabled, true, action);
+ }
+ const folder = {path: "package", isDir: true, isPackage: true};
+ for (const action of ["rename", "move"]) {
+ const state = getTemplateActionState(action, folder, false, busy);
+ assert.equal(state.disabled, true);
+ assert.equal(state.packageMove, true);
+ }
+ assert.equal(getTemplateActionState("remove", folder, false, busy).disabled, false);
+ assert.equal(getTemplateActionState("preview", folder, false, busy).disabled, true);
+ }
+ });
+});
diff --git a/app/src/template/actionState.ts b/app/src/template/actionState.ts
new file mode 100644
index 0000000000..29229ca8eb
--- /dev/null
+++ b/app/src/template/actionState.ts
@@ -0,0 +1,10 @@
+import {TemplateEntry} from "./fileTree";
+
+export const getTemplateActionState = (action: string, selected: TemplateEntry | undefined, dirty: boolean, busy: boolean) => {
+ const packageMove = !!selected?.isPackage && ["rename", "move"].includes(action);
+ const disabled = (["save", "preview"].includes(action) && (!selected || selected.isDir)) ||
+ (action === "save" && !dirty) || packageMove ||
+ (["rename", "move", "remove"].includes(action) && !selected);
+ // 忙碌状态仅影响操作可用性,不切换原生禁用样式。
+ return {disabled, ariaDisabled: busy || disabled, packageMove};
+};
diff --git a/app/src/template/fileTree.test.ts b/app/src/template/fileTree.test.ts
new file mode 100644
index 0000000000..7384e0b8b0
--- /dev/null
+++ b/app/src/template/fileTree.test.ts
@@ -0,0 +1,50 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {getTemplateTree, TemplateEntry} from "./fileTree";
+
+const entries: TemplateEntry[] = [
+ {path: "note10.md", isDir: false},
+ {path: "Work/Weekly/Review.md", isDir: false},
+ {path: "Work/daily.md", isDir: false},
+ {path: "Work/Weekly", isDir: true},
+ {path: "Work", isDir: true, isPackage: true},
+ {path: "Empty", isDir: true},
+ {path: "note2.md", isDir: false},
+];
+
+describe("template file tree", () => {
+ it("groups folders first and naturally sorts files without changing the input", () => {
+ const original = entries.slice();
+ const rows = getTemplateTree(entries, "", new Set());
+ assert.deepEqual(rows.map(item => item.path), ["Empty", "Work", "note2.md", "note10.md"]);
+ assert.equal(rows[1].isPackage, true);
+ assert.deepEqual(entries, original);
+ });
+
+ it("respects nested expansion and keeps empty directories", () => {
+ const rows = getTemplateTree(entries, "", new Set(["Work", "Work/Weekly", "Empty"]));
+ assert.deepEqual(rows.map(item => [item.path, item.depth]), [
+ ["Empty", 0], ["Work", 0], ["Work/Weekly", 1], ["Work/Weekly/Review.md", 2],
+ ["Work/daily.md", 1], ["note2.md", 0], ["note10.md", 0],
+ ]);
+ assert.equal(rows[3].name, "Review.md");
+ });
+
+ it("searches names case-insensitively and reveals ancestors without changing expansion", () => {
+ const expanded = new Set(["Empty"]);
+ const rows = getTemplateTree(entries, " REVIEW ", expanded);
+ assert.deepEqual(rows.map(item => item.path), ["Work", "Work/Weekly", "Work/Weekly/Review.md"]);
+ assert.equal(rows[0].expanded, true);
+ assert.equal(rows[1].expanded, true);
+ assert.deepEqual([...expanded], ["Empty"]);
+ assert.deepEqual(getTemplateTree(entries, "", expanded).map(item => item.path),
+ ["Empty", "Work", "note2.md", "note10.md"]);
+ });
+
+ it("matches full paths and includes descendants of matching folders", () => {
+ assert.deepEqual(getTemplateTree(entries, "work/week", new Set()).map(item => item.path),
+ ["Work", "Work/Weekly", "Work/Weekly/Review.md"]);
+ assert.deepEqual(getTemplateTree(entries, "missing", new Set()), []);
+ assert.deepEqual(getTemplateTree([], "", new Set()), []);
+ });
+});
diff --git a/app/src/template/fileTree.ts b/app/src/template/fileTree.ts
new file mode 100644
index 0000000000..d299c35acd
--- /dev/null
+++ b/app/src/template/fileTree.ts
@@ -0,0 +1,49 @@
+export interface TemplateEntry {
+ path: string;
+ isDir: boolean;
+ isPackage?: boolean;
+}
+
+export interface TemplateTreeEntry extends TemplateEntry {
+ name: string;
+ depth: number;
+ expanded: boolean;
+}
+
+export const getTemplateTree = (entries: TemplateEntry[], query: string, expandedPaths: Set<string>): TemplateTreeEntry[] => {
+ const keyword = query.trim().toLowerCase();
+ const children = new Map<string, TemplateEntry[]>();
+ const matches = new Set<string>();
+ entries.forEach(entry => {
+ const parent = entry.path.substring(0, entry.path.lastIndexOf("/"));
+ if (!children.has(parent)) {
+ children.set(parent, []);
+ }
+ children.get(parent).push(entry);
+ if (keyword && entry.path.toLowerCase().includes(keyword)) {
+ // 搜索结果保留祖先目录,临时展开但不改变用户的展开状态。
+ let path = entry.path;
+ while (path) {
+ matches.add(path);
+ path = path.substring(0, path.lastIndexOf("/"));
+ }
+ }
+ });
+ children.forEach(items => items.sort((a, b) => Number(b.isDir) - Number(a.isDir) ||
+ a.path.localeCompare(b.path, undefined, {numeric: true, sensitivity: "base"})));
+ const result: TemplateTreeEntry[] = [];
+ const visit = (parent: string, depth: number) => {
+ children.get(parent)?.forEach(entry => {
+ if (keyword && !matches.has(entry.path)) {
+ return;
+ }
+ const expanded = entry.isDir && (!!keyword || expandedPaths.has(entry.path));
+ result.push({...entry, name: entry.path.split("/").pop(), depth, expanded});
+ if (expanded) {
+ visit(entry.path, depth + 1);
+ }
+ });
+ };
+ visit("", 0);
+ return result;
+};
diff --git a/app/src/template/manager.ts b/app/src/template/manager.ts
index 0ce1f40c25..c16290b4ee 100644
--- a/app/src/template/manager.ts
+++ b/app/src/template/manager.ts
@@ -4,12 +4,8 @@ import {fetchSyncPost} from "../util/fetch";
import {escapeHtml} from "../util/escape";
import {showMessage} from "../dialog/message";
import {clearTemplatePreview, previewTemplate} from "../protyle/toolbar/util";
-
-interface TemplateEntry {
- path: string;
- isDir: boolean;
- isPackage?: boolean;
-}
+import {getTemplateTree, TemplateEntry} from "./fileTree";
+import {getTemplateActionState} from "./actionState";
export const loadTemplateDirectories = async (select: HTMLSelectElement) => {
const response = await fetchSyncPost("/api/template/manage", {action: "list"});
@@ -34,6 +30,7 @@ export const openTemplateManager = (contextID: string, onClose?: () => void) =>
let previewPath = "";
let busy = false;
let closed = false;
+ const expandedPaths = new Set<string>();
const button = (action: string, label: string) => `<button type="button" class="b3-button b3-button--outline" data-action="${action}">${label}</button>`;
const dialog = new Dialog({
title: lang.templateManager,
@@ -45,14 +42,20 @@ ${button("new", lang.new + " " + lang.template)}${button("mkdir", lang.templateN
${button("rename", lang.rename)}${button("move", lang.move)}${button("remove", lang.remove)}${button("refresh", lang.refresh)}
</div>
<div class="template-manager__panels">
-<div class="template-manager__files b3-list b3-list--background" role="list" aria-label="${lang.template}"></div>
+<div class="template-manager__sidebar">
+<input class="b3-text-field template-manager__search" type="search" placeholder="${lang.templateSearch}" aria-label="${lang.templateSearch}">
+<ul class="template-manager__files b3-list b3-list--background" aria-label="${lang.template}"></ul>
+</div>
<div class="template-manager__editor">
<div class="template-manager__path ft__breakword"></div>
<textarea class="b3-text-field template-manager__source" spellcheck="false" aria-label="${lang.templateSource}" disabled></textarea>
<div class="template-manager__actions">${button("save", lang.save)}${button("preview", lang.templatePreview)}</div>
-<label class="template-manager__context">${lang.templateContext}
-<input class="b3-text-field" type="search" placeholder="${lang.search}" aria-label="${lang.search}">
-<select class="b3-select" aria-label="${lang.templateContext}"></select></label>
+<details class="template-manager__context">
+<summary>${lang.templateContext}<span class="template-manager__context-name ft__secondary"></span></summary>
+<div class="ft__secondary">${lang.templateContextTip}</div>
+<div class="template-manager__context-fields">
+<input class="b3-text-field" type="search" placeholder="${lang.templateContextSearch}" aria-label="${lang.templateContextSearch}">
+<select class="b3-select" aria-label="${lang.templateContext}"></select></div></details>
<div class="template-manager__preview"></div>
</div></div>
</div>`,
@@ -66,9 +69,16 @@ ${button("rename", lang.rename)}${button("move", lang.move)}${button("remove", l
const list = dialog.element.querySelector<HTMLElement>(".template-manager__files");
const pathLabel = dialog.element.querySelector<HTMLElement>(".template-manager__path");
const preview = dialog.element.querySelector<HTMLElement>(".template-manager__preview");
- const search = dialog.element.querySelector<HTMLInputElement>("input");
+ const fileSearch = dialog.element.querySelector<HTMLInputElement>(".template-manager__search");
+ const search = dialog.element.querySelector<HTMLInputElement>(".template-manager__context input");
const context = dialog.element.querySelector<HTMLSelectElement>("select");
+ const contextName = dialog.element.querySelector<HTMLElement>(".template-manager__context-name");
context.add(new Option(contextID, contextID));
+ const updateContextName = () => {
+ contextName.textContent = context.selectedOptions[0].text;
+ contextName.title = context.selectedOptions[0].text;
+ };
+ updateContextName();
const dirty = () => source.value !== saved;
const beforeUnload = (event: BeforeUnloadEvent) => {
if (dirty() || busy) {
@@ -95,15 +105,16 @@ ${button("rename", lang.rename)}${button("move", lang.move)}${button("remove", l
});
const update = () => {
pathLabel.textContent = (selected?.path || lang.templateSource) + (dirty() ? " *" : "");
- source.disabled = busy || !selected || selected.isDir;
+ source.disabled = !selected || selected.isDir;
+ source.readOnly = busy;
+ list.setAttribute("aria-busy", String(busy));
dialog.element.querySelectorAll<HTMLButtonElement>(".template-manager__actions > [data-action]").forEach(element => {
const action = element.dataset.action;
- const packageMove = selected?.isPackage && ["rename", "move"].includes(action);
- element.title = packageMove ? lang.templatePackageMoveTip : "";
- element.disabled = busy || (["save", "preview"].includes(action) && (!selected || selected.isDir)) ||
- (action === "save" && !dirty()) ||
- packageMove ||
- (["rename", "move", "remove"].includes(action) && !selected);
+ const state = getTemplateActionState(action, selected, dirty(), busy);
+ element.title = state.packageMove ? lang.templatePackageMoveTip : "";
+ element.disabled = state.disabled;
+ // 请求期间保留按钮外观,由事件入口拦截重复操作。
+ element.setAttribute("aria-disabled", String(state.ariaDisabled));
});
};
const run = async (action: () => Promise<void>) => {
@@ -126,16 +137,63 @@ ${button("rename", lang.rename)}${button("move", lang.move)}${button("remove", l
return response.code === 0 ? response : undefined;
};
const renderList = () => {
+ const scrollTop = list.scrollTop;
list.replaceChildren();
- entries.forEach(entry => {
+ const rows = getTemplateTree(entries, fileSearch.value, expandedPaths);
+ if (rows.length === 0) {
+ const empty = document.createElement("li");
+ empty.className = "ft__secondary template-manager__empty";
+ empty.textContent = lang.emptyContent;
+ list.append(empty);
+ }
+ rows.forEach(entry => {
+ const row = document.createElement("li");
+ row.className = "b3-list-item" + (entry.path === selected?.path ? " b3-list-item--focus" : "");
+ row.style.paddingInlineStart = `${Math.min(entry.depth, 16) * 16 + 4}px`;
+ row.dataset.path = entry.path;
+ if (entry.isDir) {
+ const toggle = document.createElement("button");
+ toggle.type = "button";
+ toggle.className = "template-manager__toggle";
+ toggle.setAttribute("aria-expanded", String(entry.expanded));
+ toggle.setAttribute("aria-label", (entry.expanded ? lang.collapse : lang.expand) + " " + entry.name);
+ toggle.innerHTML = `<svg><use xlink:href="#${entry.expanded ? "iconDown" : "iconRight"}"></use></svg>`;
+ toggle.disabled = !!fileSearch.value.trim();
+ toggle.addEventListener("click", () => {
+ if (expandedPaths.has(entry.path)) {
+ expandedPaths.delete(entry.path);
+ } else {
+ expandedPaths.add(entry.path);
+ }
+ renderList();
+ Array.from(list.querySelectorAll<HTMLElement>("li[data-path]"))
+ .find(item => item.dataset.path === entry.path)?.querySelector<HTMLButtonElement>("button").focus({preventScroll: true});
+ });
+ row.append(toggle);
+ } else {
+ const spacer = document.createElement("span");
+ spacer.className = "template-manager__toggle";
+ row.append(spacer);
+ }
const element = document.createElement("button");
element.type = "button";
- element.className = "b3-list-item" + (entry.path === selected?.path ? " b3-list-item--focus" : "");
- element.textContent = entry.path + (entry.isDir ? "/" : "");
+ element.className = "template-manager__file";
+ element.setAttribute("aria-current", String(entry.path === selected?.path));
+ element.innerHTML = `<svg class="b3-list-item__graphic"><use xlink:href="#${entry.isDir ? "iconFolder" : "iconFile"}"></use></svg>`;
+ const name = document.createElement("span");
+ name.className = "b3-list-item__text";
+ name.textContent = entry.name;
+ element.append(name);
element.title = entry.path;
- element.addEventListener("click", () => guard(() => run(() => select(entry))));
- list.append(element);
+ element.addEventListener("click", () => {
+ if (entry.path !== selected?.path) {
+ guard(() => run(() => select(entry)));
+ }
+ });
+ row.append(element);
+ list.append(row);
});
+ list.scrollTop = scrollTop;
};
const select = async (entry?: TemplateEntry) => {
if (entry) {
@@ -156,16 +214,32 @@ ${button("rename", lang.rename)}${button("move", lang.move)}${button("remove", l
source.value = saved;
saved = source.value;
clearTemplatePreview(preview);
- renderList();
+ list.querySelectorAll<HTMLElement>("li[data-path]").forEach(row => {
+ const active = row.dataset.path === selected?.path;
+ row.classList.toggle("b3-list-item--focus", active);
+ row.querySelector(".template-manager__file").setAttribute("aria-current", String(active));
+ });
update();
};
- const reload = async (path = selected?.path) => {
+ const reload = async (path = selected?.path, reveal = false) => {
const response = await api({action: "list"});
if (!response) {
return;
}
entries = response.data;
+ if (reveal) {
+ fileSearch.value = "";
+ }
+ let parent = path?.substring(0, path.lastIndexOf("/"));
+ while (parent) {
+ expandedPaths.add(parent);
+ parent = parent.substring(0, parent.lastIndexOf("/"));
+ }
await select(entries.find(entry => entry.path === path));
+ renderList();
+ if (reveal) {
+ list.querySelector(".b3-list-item--focus")?.scrollIntoView({block: "nearest", inline: "nearest"});
+ }
};
const inputPath = (title: string, value: string, callback: (value: string) => Promise<void>) => {
const prompt = new Dialog({
@@ -210,7 +284,7 @@ ${button("rename", lang.rename)}${button("move", lang.move)}${button("remove", l
}
void run(async () => {
if (await api({action: "move", path: entry.path, target, revision})) {
- await reload(target);
+ await reload(target, true);
}
});
});
@@ -226,7 +300,11 @@ ${button("rename", lang.rename)}${button("move", lang.move)}${button("remove", l
dialog.destroy();
}
});
- context.addEventListener("change", () => clearTemplatePreview(preview));
+ fileSearch.addEventListener("input", renderList);
+ context.addEventListener("change", () => {
+ updateContextName();
+ clearTemplatePreview(preview);
+ });
let searchRequest = 0;
search.addEventListener("input", async () => {
const request = ++searchRequest;
@@ -250,12 +328,13 @@ ${button("rename", lang.rename)}${button("move", lang.move)}${button("remove", l
void fetchSyncPost("/api/block/getRefText", {id: contextID}).then(response => {
if (!closed && response.code === 0 && context.options[0]?.value === contextID) {
context.options[0].text = response.data || contextID;
+ updateContextName();
}
}).catch(() => {});
dialog.element.addEventListener("click", event => {
const target = (event.target as Element).closest<HTMLElement>(".template-manager__actions > [data-action]");
const action = preview.contains(target) ? undefined : target?.dataset.action;
- if (!action || busy) {
+ if (!action || busy || closed || (target as HTMLButtonElement).disabled) {
return;
}
if (action === "save") {
@@ -297,7 +376,7 @@ ${button("rename", lang.rename)}${button("move", lang.move)}${button("remove", l
response = await api({action: "move", path: selected.path, target: value, revision});
}
if (response) {
- await reload(value);
+ await reload(value, true);
}
});
}
diff --git a/docs/TEMPLATE-MANAGER.md b/docs/TEMPLATE-MANAGER.md
index 3693ef045a..bc5bb880b5 100644
--- a/docs/TEMPLATE-MANAGER.md
+++ b/docs/TEMPLATE-MANAGER.md
@@ -2,7 +2,7 @@
在编辑器的模板选择面板中点击「模板管理」,或从文档的「导出 - 模板」窗口进入。桌面、浏览器和移动端共用同一管理窗口。
-左侧列出 `data/templates` 中的目录和 Markdown 文件。选中目录后,新建模板或文件夹默认放入该目录。重命名可以编辑相对路径,移动使用目录选择器;已有目标不会被覆盖。重命名或移动不会自动改写其他模板、笔记本配置或文档中引用的模板路径,需要相应调整。
+左侧以可折叠的文件夹树列出 `data/templates` 中的目录和 Markdown 文件,目录优先排列。搜索框匹配模板名称或完整路径,搜索结果自动展开父目录,清空搜索后恢复原来的展开状态。点击目录旁的展开按钮展开或收起子项,点击目录名称选中目录;选中目录后,新建模板或文件夹默认放入该目录。重命名可以编辑相对路径,移动使用目录选择器;已有目标不会被覆盖。新建、重命名和移动成功后清空搜索并展开目标的父目录。重命名或移动不会自动改写其他模板、笔记本配置或文档中引用的模板路径,需要相应调整。
包含 `template.json` 的模板包目录不支持重命名或移动,以保留包身份和集市更新能力;包内模板仍可编辑。访问已有文件时保留原始文件名,不因单引号等合法字符而拒绝访问。
@@ -12,7 +12,7 @@
## 预览
-点击「预览模板」执行当前文本框中的内容,无须先保存或插入文档。默认使用打开窗口时的文档或块作为上下文;可以搜索并选择其他预览文档。预览继续使用现有模板渲染流程,因此标题、ID、路径和 SQL 查询等结果取决于所选上下文及当前数据。
+点击「预览模板」执行当前文本框中的内容,无须先保存或插入文档。默认使用打开窗口时的文档或块作为上下文;「预览上下文」默认收起并显示当前选择的名称,展开后可以搜索并选择其他文档。此处搜索的是上下文文档,不是左侧模板列表。预览使用所选文档的标题、ID 等信息运行模板,不会修改该文档;标题、ID、路径和 SQL 查询等结果取决于所选上下文及当前数据。
预览使用现有只读渲染模式,不保存当前源码,也不提交文档树创建计划。数据库预览仍使用表格展示,不能等同于实际插入后的全部交互效果。