Skip to content

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

:bug: Improve daily note reference completion https://github.com/siyuan-note/siyuan/issues/20201

Daniel128ec6762313
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 0762f4dd6e..45389fc18e 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "هل تود أن تضع خاتمة ليومك؟\nدوّن شيئًا يستحق أن تتذكره",
"agentWelcomeLate5": "هل لديك فكرة تود الاحتفاظ بها للغد؟\nاكتب أهم نقطة أولًا",
"agentExample4": "ساعدني في تطوير إضافة",
- "dailyNoteDateInvalid": "التاريخ غير صالح أو ملتبس؛ أدخل تاريخًا كاملًا بصيغة YYYY-MM-DD",
"goToDocumentStart": "الانتقال إلى بداية المستند",
"goToDocumentEnd": "الانتقال إلى نهاية المستند",
"agentBuiltinPluginDevelopmentDescription": "سير العمل الرسمي لتطوير إضافات الواجهة الأمامية: بعد موافقتك الصريحة، تُستوضح المتطلبات الناقصة وتُعتمد خطة موجزة ثم يُنفّذ العمل في نسخة مُدارة ويُتحقّق منه وتُجهّز الحزمة؛ يتطلب التثبيت والتفعيل إذنًا منفصلًا",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 4e343d3630..9e20cf0a89 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Möchtest du den Tag abrunden?\nHalte etwas fest, an das du dich erinnern möchtest",
"agentWelcomeLate5": "Möchtest du eine Idee für morgen festhalten?\nSchreib erst einmal das Wichtigste auf",
"agentExample4": "Hilf mir, ein Plugin zu entwickeln",
- "dailyNoteDateInvalid": "Ungültiges oder mehrdeutiges Datum; bitte ein vollständiges Datum im Format YYYY-MM-DD eingeben",
"goToDocumentStart": "Zum Dokumentanfang springen",
"goToDocumentEnd": "Zum Dokumentende springen",
"agentBuiltinPluginDevelopmentDescription": "Offizieller Ablauf zur Entwicklung von Frontend-Plugins: Nach deiner ausdrücklichen Zustimmung werden fehlende Anforderungen geklärt, ein kurzer Plan bestätigt und die Umsetzung in einer verwalteten Kopie geprüft und paketiert; Installation und Aktivierung erfordern eine separate Genehmigung",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 4d5f5c7469..8edb4a009d 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Want to give today a closing note?\nWrite down one thing worth remembering",
"agentWelcomeLate5": "Have an idea you'd like to save for tomorrow?\nWrite down the most important part first",
"agentExample4": "Help me develop a plugin",
- "dailyNoteDateInvalid": "Invalid or ambiguous date; enter a complete date in YYYY-MM-DD format",
"goToDocumentStart": "Go to document start",
"goToDocumentEnd": "Go to document end",
"agentBuiltinPluginDevelopmentDescription": "Official frontend plugin development workflow: after you explicitly opt in, clarify missing requirements, confirm a brief plan, implement in a managed copy, validate, and package; installation and activation require separate authorization",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index ebd5f10b35..aa12910942 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "¿Quieres darle un cierre al día?\nAnota algo que merezca la pena recordar",
"agentWelcomeLate5": "¿Tienes una idea que quieras guardar para mañana?\nEscribe primero lo más importante",
"agentExample4": "Ayúdame a desarrollar un complemento",
- "dailyNoteDateInvalid": "Fecha no válida o ambigua; introduce una fecha completa con el formato YYYY-MM-DD",
"goToDocumentStart": "Ir al inicio del documento",
"goToDocumentEnd": "Ir al final del documento",
"agentBuiltinPluginDevelopmentDescription": "Flujo oficial de desarrollo de plugins de interfaz: tras tu aceptación explícita, se aclaran los requisitos pendientes, se confirma un plan breve y se implementa, valida y empaqueta en una copia gestionada; la instalación y la activación requieren autorización por separado",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index d41cbc2ba4..3ebdadd5f1 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Envie de mettre un point final à cette journée ?\nNote quelque chose dont tu veux te souvenir",
"agentWelcomeLate5": "Une idée à garder pour demain ?\nNote d’abord l’essentiel",
"agentExample4": "Aide-moi à développer un plugin",
- "dailyNoteDateInvalid": "Date invalide ou ambiguë ; saisissez une date complète au format YYYY-MM-DD",
"goToDocumentStart": "Aller au début du document",
"goToDocumentEnd": "Aller à la fin du document",
"agentBuiltinPluginDevelopmentDescription": "Processus officiel de développement de plugins d’interface : après votre accord explicite, clarifier les exigences manquantes, confirmer un plan succinct, réaliser le développement dans une copie gérée, valider et préparer le paquet ; l’installation et l’activation nécessitent une autorisation distincte",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 24acd36cb4..c26f3a020f 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "רוצה לתת ליום הזה סיום?\nרשום דבר אחד שכדאי לזכור",
"agentWelcomeLate5": "יש רעיון שתרצה לשמור למחר?\nרשום קודם את הנקודה החשובה ביותר",
"agentExample4": "עזור לי לפתח תוסף",
- "dailyNoteDateInvalid": "תאריך לא תקין או לא חד־משמעי; יש להזין תאריך מלא בתבנית YYYY-MM-DD",
"goToDocumentStart": "מעבר לתחילת המסמך",
"goToDocumentEnd": "מעבר לסוף המסמך",
"agentBuiltinPluginDevelopmentDescription": "תהליך העבודה הרשמי לפיתוח תוספי ממשק: לאחר הסכמתך המפורשת, מבררים דרישות חסרות, מאשרים תוכנית קצרה, מממשים בעותק מנוהל, מאמתים ואורזים; התקנה והפעלה דורשות הרשאה נפרדת",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index f456927ef2..3347b88533 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "आज के दिन को एक समापन देना चाहेंगे?\nएक ऐसी बात लिखें जिसे याद रखना चाहें",
"agentWelcomeLate5": "कोई विचार कल के लिए सँभालकर रखना है?\nपहले सबसे ज़रूरी बात लिख लें",
"agentExample4": "प्लगइन विकसित करने में मेरी मदद करें",
- "dailyNoteDateInvalid": "तारीख अमान्य या अस्पष्ट है; YYYY-MM-DD प्रारूप में पूरी तारीख दर्ज करें",
"goToDocumentStart": "दस्तावेज़ की शुरुआत पर जाएँ",
"goToDocumentEnd": "दस्तावेज़ के अंत पर जाएँ",
"agentBuiltinPluginDevelopmentDescription": "फ़्रंटएंड प्लगइन विकास की आधिकारिक प्रक्रिया: आपकी स्पष्ट सहमति के बाद अधूरी आवश्यकताओं को स्पष्ट करना, संक्षिप्त योजना की पुष्टि करना, प्रबंधित प्रति में कार्यान्वयन करना, जाँचना और पैकेज बनाना; स्थापना और सक्रियण के लिए अलग अनुमति आवश्यक है",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 63dda61917..e9728822bd 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Ingin memberi penutup untuk hari ini?\nCatat satu hal yang layak diingat",
"agentWelcomeLate5": "Ada ide yang ingin kamu simpan untuk besok?\nTulis dulu hal yang paling penting",
"agentExample4": "Bantu saya mengembangkan plugin",
- "dailyNoteDateInvalid": "Tanggal tidak valid atau ambigu; masukkan tanggal lengkap dalam format YYYY-MM-DD",
"goToDocumentStart": "Ke awal dokumen",
"goToDocumentEnd": "Ke akhir dokumen",
"agentBuiltinPluginDevelopmentDescription": "Alur kerja resmi pengembangan plugin antarmuka: setelah Anda menyetujuinya secara eksplisit, perjelas kebutuhan yang belum lengkap, konfirmasi rencana singkat, implementasikan dalam salinan terkelola, validasi, dan kemas; pemasangan dan pengaktifan memerlukan izin terpisah",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index aa1a33a8ad..f08175d944 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Vuoi dare una conclusione a questa giornata?\nAnnota qualcosa che vale la pena ricordare",
"agentWelcomeLate5": "Hai un’idea da tenere per domani?\nScrivi prima la cosa più importante",
"agentExample4": "Aiutami a sviluppare un plugin",
- "dailyNoteDateInvalid": "Data non valida o ambigua; inserisci una data completa nel formato YYYY-MM-DD",
"goToDocumentStart": "Vai all'inizio del documento",
"goToDocumentEnd": "Vai alla fine del documento",
"agentBuiltinPluginDevelopmentDescription": "Procedura ufficiale per lo sviluppo di plugin frontend: dopo il tuo consenso esplicito, chiarire i requisiti mancanti, confermare un piano sintetico, implementare in una copia gestita, verificare e creare il pacchetto; l’installazione e l’attivazione richiedono un’autorizzazione separata",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index b7d9e1c13c..8bc4ec9a64 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "今日の締めくくりを書いてみませんか?\n覚えておきたいことをひとつ残しましょう",
"agentWelcomeLate5": "明日のために残しておきたいアイデアはありますか?\nまずはいちばん大切なことを書いておきましょう",
"agentExample4": "プラグインの開発を手伝って",
- "dailyNoteDateInvalid": "日付が無効または曖昧です。YYYY-MM-DD 形式で完全な日付を入力してください",
"goToDocumentStart": "ドキュメントの先頭へ移動",
"goToDocumentEnd": "ドキュメントの末尾へ移動",
"agentBuiltinPluginDevelopmentDescription": "公式フロントエンドプラグイン開発フロー:ユーザーが明示的に選択した後、不足している要件を確認し、簡潔な計画に合意したうえで、管理対象のコピーで実装・検証・パッケージ化を行います。インストールと有効化には別途許可が必要です",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index b3817b2ba1..79d8660aba 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "오늘 하루를 마무리해 볼까요?\n기억해 둘 만한 일 하나를 적어 봐요",
"agentWelcomeLate5": "내일을 위해 남겨 둘 생각이 있나요?\n가장 중요한 것부터 적어 둬요",
"agentExample4": "플러그인 개발을 도와주세요",
- "dailyNoteDateInvalid": "날짜가 올바르지 않거나 모호합니다. YYYY-MM-DD 형식으로 전체 날짜를 입력하세요",
"goToDocumentStart": "문서 시작으로 이동",
"goToDocumentEnd": "문서 끝으로 이동",
"agentBuiltinPluginDevelopmentDescription": "공식 프런트엔드 플러그인 개발 절차: 사용자가 명시적으로 선택한 후 누락된 요구 사항을 확인하고 간단한 계획에 합의한 뒤 관리되는 사본에서 구현, 검증 및 패키징을 수행하며, 설치와 활성화에는 별도의 승인이 필요합니다",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 4150de618c..160f03dba3 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Wil je de dag afronden?\nSchrijf één ding op dat het onthouden waard is",
"agentWelcomeLate5": "Heb je een idee dat je voor morgen wilt bewaren?\nSchrijf eerst het belangrijkste op",
"agentExample4": "Help me een plug-in te ontwikkelen",
- "dailyNoteDateInvalid": "Ongeldige of onduidelijke datum; voer een volledige datum in de notatie YYYY-MM-DD in",
"goToDocumentStart": "Naar het begin van het document",
"goToDocumentEnd": "Naar het einde van het document",
"agentBuiltinPluginDevelopmentDescription": "Officiële werkwijze voor frontend-pluginontwikkeling: na je uitdrukkelijke toestemming worden ontbrekende vereisten verduidelijkt, wordt een kort plan bevestigd en wordt de plugin in een beheerde kopie geïmplementeerd, gevalideerd en verpakt; installatie en activering vereisen afzonderlijke toestemming",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 031db8c797..67c477f719 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Chcesz dopisać zakończenie dzisiejszego dnia?\nZapisz jedną rzecz wartą zapamiętania",
"agentWelcomeLate5": "Masz pomysł, który chcesz zachować na jutro?\nZapisz najpierw to, co najważniejsze",
"agentExample4": "Pomóż mi opracować wtyczkę",
- "dailyNoteDateInvalid": "Nieprawidłowa lub niejednoznaczna data; wpisz pełną datę w formacie YYYY-MM-DD",
"goToDocumentStart": "Przejdź do początku dokumentu",
"goToDocumentEnd": "Przejdź do końca dokumentu",
"agentBuiltinPluginDevelopmentDescription": "Oficjalny proces tworzenia wtyczek interfejsu: po wyraźnej zgodzie użytkownika następuje doprecyzowanie brakujących wymagań, zatwierdzenie krótkiego planu, implementacja w zarządzanej kopii, weryfikacja i przygotowanie pakietu; instalacja i aktywacja wymagają osobnej zgody",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 59ecfe4003..c934448b0a 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Quer encerrar o dia com uma nota?\nRegistre algo que vale a pena lembrar",
"agentWelcomeLate5": "Tem uma ideia que quer guardar para amanhã?\nAnote primeiro o ponto mais importante",
"agentExample4": "Ajude-me a desenvolver um plugin",
- "dailyNoteDateInvalid": "Data inválida ou ambígua; insira uma data completa no formato YYYY-MM-DD",
"goToDocumentStart": "Ir para o início do documento",
"goToDocumentEnd": "Ir para o fim do documento",
"agentBuiltinPluginDevelopmentDescription": "Fluxo oficial de desenvolvimento de plugins de interface: após sua aceitação explícita, esclarecer os requisitos pendentes, confirmar um plano breve, implementar em uma cópia gerenciada, validar e empacotar; a instalação e a ativação exigem autorização separada",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index e830724671..24f1ef2fca 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Хочешь подвести черту под этим днём?\nЗапиши одну вещь, которую стоит запомнить",
"agentWelcomeLate5": "Есть идея, которую хочется оставить на завтра?\nСначала запиши самое главное",
"agentExample4": "Помоги мне разработать плагин",
- "dailyNoteDateInvalid": "Недопустимая или неоднозначная дата; введите полную дату в формате YYYY-MM-DD",
"goToDocumentStart": "Перейти к началу документа",
"goToDocumentEnd": "Перейти к концу документа",
"agentBuiltinPluginDevelopmentDescription": "Официальный процесс разработки плагинов интерфейса: после явного согласия пользователя уточняются недостающие требования, утверждается краткий план, выполняются реализация в управляемой копии, проверка и упаковка; установка и активация требуют отдельного разрешения",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 169dc99d8f..886ae3bab9 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Chceš dnešnému dňu dopísať záver?\nZapíš si jednu vec, ktorú sa oplatí zapamätať",
"agentWelcomeLate5": "Máš nápad, ktorý chceš odložiť na zajtra?\nNajprv si zapíš to najdôležitejšie",
"agentExample4": "Pomôž mi vyvinúť doplnok",
- "dailyNoteDateInvalid": "Neplatný alebo nejednoznačný dátum; zadajte úplný dátum vo formáte YYYY-MM-DD",
"goToDocumentStart": "Prejsť na začiatok dokumentu",
"goToDocumentEnd": "Prejsť na koniec dokumentu",
"agentBuiltinPluginDevelopmentDescription": "Oficiálny postup vývoja doplnkov rozhrania: po výslovnom súhlase používateľa sa objasnia chýbajúce požiadavky, potvrdí stručný plán a v spravovanej kópii sa vykoná implementácia, overenie a vytvorenie balíka; inštalácia a aktivácia vyžadujú samostatné povolenie",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index ef546f1894..7dc6544775 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Желиш да ставиш тачку на данашњи дан?\nЗабележи једну ствар вредну памћења",
"agentWelcomeLate5": "Имаш идеју коју желиш да сачуваш за сутра?\nПрво запиши оно најважније",
"agentExample4": "Помози ми да развијем додатак",
- "dailyNoteDateInvalid": "Неважећи или двосмислен датум; унесите потпун датум у формату YYYY-MM-DD",
"goToDocumentStart": "Иди на почетак документа",
"goToDocumentEnd": "Иди на крај документа",
"agentBuiltinPluginDevelopmentDescription": "Званични поступак развоја додатака за кориснички интерфејс: након изричите сагласности корисника разјашњавају се недостајући захтеви, потврђује кратак план и у управљаној копији спроводе израда, провера и паковање; инсталација и активирање захтевају посебно одобрење",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 06eb2b6a9d..c168951395 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "อยากเขียนปิดท้ายวันนี้ไหม\nจดสักเรื่องที่ควรค่าแก่การจดจำ",
"agentWelcomeLate5": "มีไอเดียที่อยากเก็บไว้สำหรับพรุ่งนี้ไหม\nจดสิ่งที่สำคัญที่สุดไว้ก่อน",
"agentExample4": "ช่วยฉันพัฒนาปลั๊กอิน",
- "dailyNoteDateInvalid": "วันที่ไม่ถูกต้องหรือกำกวม โปรดป้อนวันที่แบบเต็มในรูปแบบ YYYY-MM-DD",
"goToDocumentStart": "ไปยังจุดเริ่มต้นของเอกสาร",
"goToDocumentEnd": "ไปยังจุดสิ้นสุดของเอกสาร",
"agentBuiltinPluginDevelopmentDescription": "ขั้นตอนการพัฒนาปลั๊กอินส่วนหน้าทางการ: หลังจากผู้ใช้ยินยอมอย่างชัดเจน จึงชี้แจงข้อกำหนดที่ยังขาด ยืนยันแผนโดยย่อ พัฒนาในสำเนาที่จัดการให้ ตรวจสอบ และจัดแพ็กเกจ โดยการติดตั้งและเปิดใช้งานต้องได้รับอนุญาตแยกต่างหาก",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index cb9929a65f..9076ea8394 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Bugüne bir kapanış notu düşmek ister misin?\nHatırlamaya değer bir şeyi yaz",
"agentWelcomeLate5": "Yarına saklamak istediğin bir fikrin mi var?\nÖnce en önemli noktayı yaz",
"agentExample4": "Bir eklenti geliştirmeme yardım et",
- "dailyNoteDateInvalid": "Geçersiz veya belirsiz tarih; YYYY-MM-DD biçiminde tam bir tarih girin",
"goToDocumentStart": "Belgenin başına git",
"goToDocumentEnd": "Belgenin sonuna git",
"agentBuiltinPluginDevelopmentDescription": "Resmî ön yüz eklentisi geliştirme süreci: açık onayınızın ardından eksik gereksinimler netleştirilir, kısa bir plan onaylanır ve yönetilen bir kopyada geliştirme, doğrulama ve paketleme yapılır; yükleme ve etkinleştirme için ayrı izin gerekir",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 857c160466..9c73ed483f 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "Хочеш написати завершальну нотатку дня?\nЗапиши одну річ, яку варто запам'ятати",
"agentWelcomeLate5": "Маєш ідею, яку хочеш залишити на завтра?\nСпершу запиши найважливіше",
"agentExample4": "Допоможи мені розробити плагін",
- "dailyNoteDateInvalid": "Неприпустима або неоднозначна дата; введіть повну дату у форматі YYYY-MM-DD",
"goToDocumentStart": "Перейти на початок документа",
"goToDocumentEnd": "Перейти в кінець документа",
"agentBuiltinPluginDevelopmentDescription": "Офіційний процес розробки плагінів інтерфейсу: після явної згоди користувача уточнюються відсутні вимоги, затверджується стислий план, виконуються реалізація в керованій копії, перевірка та пакування; установлення й активація потребують окремого дозволу",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index b512f671ce..bf72480554 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "想给今天留个结尾?\n记下一件值得记住的事",
"agentWelcomeLate5": "有个想法想留给明天?\n先写下最重要的一点",
"agentExample4": "帮我开发一个插件",
- "dailyNoteDateInvalid": "日期无效或有歧义,请输入 YYYY-MM-DD 格式的完整日期",
"goToDocumentStart": "跳到文档开头",
"goToDocumentEnd": "跳到文档结尾",
"agentBuiltinPluginDevelopmentDescription": "官方前端插件开发流程:在用户明确选择后澄清缺失要求、确认简短方案、使用受管副本实现、验证和打包;安装与启用另行授权",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index c3123fda0e..e45356bc0c 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -25,7 +25,6 @@
"agentWelcomeLate4": "想給今天留個結尾?\n記下一件值得記住的事",
"agentWelcomeLate5": "有個想法想留給明天?\n先寫下最重要的一點",
"agentExample4": "幫我開發一個外掛",
- "dailyNoteDateInvalid": "日期無效或有歧義,請輸入 YYYY-MM-DD 格式的完整日期",
"goToDocumentStart": "跳到文件開頭",
"goToDocumentEnd": "跳到文件結尾",
"agentBuiltinPluginDevelopmentDescription": "官方前端外掛開發流程:在使用者明確選擇後釐清缺漏需求、確認簡短方案、使用受管理的副本實作、驗證及封裝;安裝與啟用須另行授權",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20210110181011-fbhoesf.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20210110181011-fbhoesf.sy
index d3c55aeb28..9cd0f4efb3 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20210110181011-fbhoesf.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20210110181011-fbhoesf.sy
@@ -6,7 +6,7 @@
"id": "20210110181011-fbhoesf",
"title": "Daily notes",
"type": "doc",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260613180619-15jwt8e",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -205,7 +205,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20261008101708-b7c9jyj",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -269,12 +269,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-8o948mt",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Dates without a year use the current year, and candidates display the complete date. For ambiguous expressions such as "
+ "Data": "Dates without a year use the current year. Candidates display the actual document name or the name resolved from the creation template, the full path, and the target date. Existing daily note icons support hover previews. For ambiguous expressions such as "
},
{
"Type": "NodeTextMark",
@@ -283,7 +283,7 @@
},
{
"Type": "NodeText",
- "Data": " or invalid dates, use "
+ "Data": " or invalid dates, no daily note candidate is shown. Use "
},
{
"Type": "NodeTextMark",
@@ -301,12 +301,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-3n0qxms",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Selecting a daily note candidate uses the last selected daily note notebook. If none is selected or that notebook is unavailable, you are asked to choose one. Canceling creates no document. Encrypted notebooks can reference daily notes only within the same notebook; ordinary notebooks cannot reference daily notes in encrypted notebooks."
+ "Data": "Candidates use the last selected daily note notebook. If none is selected or that notebook is unavailable, candidates show the full paths for available notebooks. Selecting a candidate saves its notebook as the daily note notebook. Leaving candidates unselected creates no document. Encrypted notebooks can reference daily notes only within the same notebook; ordinary notebooks cannot reference daily notes in encrypted notebooks."
}
]
},
@@ -315,12 +315,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-yprxiyp",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Typing and viewing candidates create no document. Selecting a candidate reuses the daily note for that date in the target notebook, including moved or renamed documents that retain their daily note date attribute. If none exists, the daily note settings are used to create it and insert a reference. The path template, now in the content template, and the daily note date attribute use the target date; actual creation and update timestamps retain the real operation time."
+ "Data": "Typing and viewing candidates create no document. Missing daily notes display New daily note and a calendar-plus icon. Moving the caret after a creation request does not cancel insertion at the original input position; modified or deleted input is not overwritten. Selecting a candidate reuses the daily note for that date in the target notebook, including moved or renamed documents that retain their daily note date attribute. If none exists, the daily note settings are used to create it and insert a reference. The path template, now in the content template, and the daily note date attribute use the target date; actual creation and update timestamps retain the real operation time."
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20210110175347-2xrwoiq.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20210110175347-2xrwoiq.sy
index 5c8e35ec70..066c1ccfa0 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20210110175347-2xrwoiq.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20210110175347-2xrwoiq.sy
@@ -6,7 +6,7 @@
"id": "20210110175347-2xrwoiq",
"title": "日记",
"type": "doc",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260613180438-q02mnqc",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -205,7 +205,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20261008101708-5rm6q63",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -278,12 +278,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-5vji0a1",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "未填写年份时使用当前年,候选项会显示完整日期。对于 "
+ "Data": "未填写年份时使用当前年。候选项会显示真实文档名或模板解析的创建名称、完整路径和目标日期,已有日记的图标支持浮窗预览。对于 "
},
{
"Type": "NodeTextMark",
@@ -292,7 +292,7 @@
},
{
"Type": "NodeText",
- "Data": " 等有歧义的表达或无效日期,请改用 "
+ "Data": " 等有歧义的表达或无效日期,不显示日记候选。可改用 "
},
{
"Type": "NodeTextMark",
@@ -301,7 +301,7 @@
},
{
"Type": "NodeText",
- "Data": " 格式。普通文档搜索仍可使用。"
+ "Data": " 格式,普通文档搜索仍可使用。"
}
]
},
@@ -310,12 +310,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-0z31c9n",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "选中日记候选后,使用上次选择的日记笔记本;尚未选择或原笔记本不可用时,会提示选择。取消选择不会创建文档。加密笔记本内只能引用本笔记本的日记,普通笔记本不能引用加密笔记本的日记。"
+ "Data": "已选择日记笔记本时,候选项使用上次选择的笔记本;尚未选择或原笔记本不可用时,候选项会显示各可用笔记本的完整路径,选中时保存日记笔记本。未选择候选不会创建文档。加密笔记本内只能引用本笔记本的日记,普通笔记本不能引用加密笔记本的日记。"
}
]
},
@@ -324,12 +324,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-m616klc",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "输入和查看候选不会创建文档。选中后会复用目标笔记本中对应日期的日记,包括已移动或重命名但保留日记日期属性的文档;不存在时才按日记设置创建并插入引用。路径模板、正文模板中的 now 和日记日期属性使用目标日期,实际创建和更新时间保持真实操作时间。"
+ "Data": "输入和查看候选不会创建文档。尚未创建的日记显示“新建日记”和日历加号图标。创建请求发出后移动光标,引用仍插入原输入位置;原内容被修改或删除时不覆盖新的内容。选中后会复用目标笔记本中对应日期的日记,包括已移动或重命名但保留日记日期属性的文档;不存在时才按日记设置创建并插入引用。路径模板、正文模板中的 now 和日记日期属性使用目标日期,实际创建和更新时间保持真实操作时间。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123154-fd5e001.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123154-fd5e001.sy
index 69a3798234..995d322907 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123154-fd5e001.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123154-fd5e001.sy
@@ -6,7 +6,7 @@
"id": "20211226123154-fd5e001",
"title": "日記",
"type": "doc",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260613181022-74zgp84",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -205,7 +205,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20261008101708-lr0o7zn",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -278,12 +278,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-wyphboq",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "未填寫年份時使用目前年份,候選項會顯示完整日期。對於 "
+ "Data": "未填寫年份時使用目前年份。候選項會顯示實際文件名稱或範本解析的建立名稱、完整路徑和目標日期,已有日記的圖示支援浮窗預覽。對於 "
},
{
"Type": "NodeTextMark",
@@ -292,7 +292,7 @@
},
{
"Type": "NodeText",
- "Data": " 等有歧義的表達或無效日期,請改用 "
+ "Data": " 等有歧義的表達或無效日期,不顯示日記候選。可改用 "
},
{
"Type": "NodeTextMark",
@@ -301,7 +301,7 @@
},
{
"Type": "NodeText",
- "Data": " 格式。一般文件搜尋仍可使用。"
+ "Data": " 格式,一般文件搜尋仍可使用。"
}
]
},
@@ -310,12 +310,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-e6z4q69",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "選取日記候選後,使用上次選取的日記筆記本;尚未選取或原筆記本無法使用時,會提示選取。取消選取不會建立文件。加密筆記本內只能引用本筆記本的日記,一般筆記本不能引用加密筆記本的日記。"
+ "Data": "已選取日記筆記本時,候選項使用上次選取的筆記本;尚未選取或原筆記本無法使用時,候選項會顯示各可用筆記本的完整路徑,選取時儲存日記筆記本。未選取候選不會建立文件。加密筆記本內只能引用本筆記本的日記,一般筆記本不能引用加密筆記本的日記。"
}
]
},
@@ -324,12 +324,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-j20nycr",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "輸入和查看候選不會建立文件。選取後會沿用目標筆記本中對應日期的日記,包括已移動或重新命名但保留日記日期屬性的文件;不存在時才依日記設定建立並插入區塊引用。路徑範本、內容範本中的 now 和日記日期屬性使用目標日期,實際建立和更新時間保持真實操作時間。"
+ "Data": "輸入和查看候選不會建立文件。尚未建立的日記顯示「新建日記」和日曆加號圖示。建立請求送出後移動游標,區塊引用仍插入原輸入位置;原內容被修改或刪除時不覆蓋新的內容。選取後會沿用目標筆記本中對應日期的日記,包括已移動或重新命名但保留日記日期屬性的文件;不存在時才依日記設定建立並插入區塊引用。路徑範本、內容範本中的 now 和日記日期屬性使用目標日期,實際建立和更新時間保持真實操作時間。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-scr2p21.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-scr2p21.sy
index 9b44b9bbc5..00b1a0d669 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-scr2p21.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-scr2p21.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-scr2p21",
"title": "デイリーノート",
"type": "doc",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -16,7 +16,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260613180757-9fax3mg",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -206,7 +206,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20261008101708-mjx358e",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
@@ -279,12 +279,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-x9aa3xt",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "年を省略した日付には今年を使用し、候補には完全な日付を表示します。"
+ "Data": "年を省略した日付には今年を使用します。候補には実際のドキュメント名または作成テンプレートで解決した名前、完全なパス、対象日付を表示します。既存の日記アイコンはホバープレビューに対応しています。"
},
{
"Type": "NodeTextMark",
@@ -293,7 +293,7 @@
},
{
"Type": "NodeText",
- "Data": " などの曖昧な表現や無効な日付は、"
+ "Data": " などの曖昧な表現や無効な日付では日記候補を表示しません。"
},
{
"Type": "NodeTextMark",
@@ -311,12 +311,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-712s18k",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "候補を選択すると、前回選択したデイリーノート用ノートブックを使用します。未選択の場合や以前のノートブックが利用できない場合は、選択を求められます。キャンセルしてもドキュメントは作成されません。暗号化ノートブックでは同じノートブックの日記のみ参照でき、通常のノートブックから暗号化ノートブックの日記は参照できません。"
+ "Data": "候補には前回選択したデイリーノート用ノートブックを使用します。未選択の場合や以前のノートブックが利用できない場合は、利用可能なノートブックの完全なパスを候補に表示します。候補を選択すると日記用ノートブックを保存します。候補を選択しなければドキュメントは作成されません。暗号化ノートブックでは同じノートブックの日記のみ参照でき、通常のノートブックから暗号化ノートブックの日記は参照できません。"
}
]
},
@@ -325,12 +325,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261008101708-pvky8qm",
- "updated": "20261008101708"
+ "updated": "20261008172530"
},
"Children": [
{
"Type": "NodeText",
- "Data": "入力や候補の表示だけではドキュメントを作成しません。候補を選択すると、対象ノートブックの対応する日付のデイリーノートを再利用します。日記の日付属性が残っていれば、移動や名前変更後のドキュメントも再利用します。存在しない場合のみ、日記の設定に従って作成して参照を挿入します。パステンプレート、本文テンプレート内の now、日記の日付属性には対象日付を使用し、実際の作成・更新時刻は操作時刻を保持します。"
+ "Data": "入力や候補の表示だけではドキュメントを作成しません。未作成の日記には新規デイリーノートの表示とカレンダーのプラスアイコンを使用します。作成要求後にカーソルを移動しても参照は元の入力位置に挿入されます。元の入力が変更または削除された場合は新しい内容を上書きしません。候補を選択すると、対象ノートブックの対応する日付のデイリーノートを再利用します。日記の日付属性が残っていれば、移動や名前変更後のドキュメントも再利用します。存在しない場合のみ、日記の設定に従って作成して参照を挿入します。パステンプレート、本文テンプレート内の now、日記の日付属性には対象日付を使用し、実際の作成・更新時刻は操作時刻を保持します。"
}
]
},
diff --git a/app/src/protyle/hint/dailyNote.test.ts b/app/src/protyle/hint/dailyNote.test.ts
index 64e121c005..1e4a20753a 100644
--- a/app/src/protyle/hint/dailyNote.test.ts
+++ b/app/src/protyle/hint/dailyNote.test.ts
@@ -6,7 +6,7 @@ import {runInNewContext} from "node:vm";
import {ModuleKind, transpileModule} from "typescript";
import {canReferenceDailyNoteNotebook, getLastDailyNoteNotebookId} from "../../util/dailyNote";
import {parseDailyNoteDate} from "../../util/dailyNoteDate";
-import {escapeHtml} from "../../util/escape";
+import {escapeAttr, escapeHtml} from "../../util/escape";
const code = transpileModule(readFileSync(join(__dirname, "dailyNote.ts"), "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS},
@@ -16,25 +16,31 @@ const createContext = () => {
const calls: {path: string, body: {notebook?: string, date?: string, id?: string}}[] = [];
let choose: ((notebook: string) => void) | undefined;
let fail = false;
+ let existed = true;
const selected: string[] = [];
const storage: Record<string, string> = {};
const appWindow = {siyuan: {
config: {readonly: false, appearance: {lang: "en"}}, storage,
notebooks: [{id: "daily", name: "Daily <notes>", closed: false},
{id: "normal", name: "Notes", closed: false}, {id: "encrypted", name: "Secret", closed: false}],
- languages: {dailyNote: "Daily Note", plsChoose: "Choose a notebook", dailyNoteDateInvalid: "Enter a complete date"},
+ languages: {dailyNote: "Daily Note", fileTree11: "New daily note", plsChoose: "Choose a notebook"},
}};
const mocks: Record<string, unknown> = {
"../../constants": {Constants: {LOCAL_DAILYNOTEID: "last", SIYUAN_APPID: "app"}},
"../../util/dailyNote": {canReferenceDailyNoteNotebook, getLastDailyNoteNotebookId},
"../../util/dailyNoteDate": {parseDailyNoteDate},
- "../../util/escape": {escapeHtml},
+ "../../util/escape": {escapeAttr, escapeHtml},
+ "../util/compatibility": {setStorageVal() {}},
"../../util/pathName": {isEncryptedBox: (id: string) => id === "encrypted"},
"../../util/mount": {selectDailyNoteNotebook: (notebooks: {id: string}[], callback: (id: string) => void) => {
selected.push(...notebooks.map(item => item.id));
choose = callback;
}},
- "../../util/fetch": {fetchPost: (path: string, body: {notebook?: string, date?: string, id?: string},
+ "../../util/fetch": {fetchSyncPost: async (path: string, body: {notebook?: string, date?: string}) => {
+ calls.push({path, body});
+ return fail ? {code: -1} : {code: 0, data: {id: existed ? "existing" : "", existed,
+ title: existed ? "Renamed <note>" : "Sep 25, 2026", hPath: existed ? "/Moved/Renamed <note>" : "/Daily/Sep 25, 2026"}};
+ }, fetchPost: (path: string, body: {notebook?: string, date?: string, id?: string},
callback: (response: unknown) => void) => {
calls.push({path, body});
callback(fail ? {code: -1} : path.endsWith("getDocInfo") ?
@@ -44,26 +50,42 @@ const createContext = () => {
const exported = {};
runInNewContext(code, {exports: exported, window: appWindow, require: (path: string) => mocks[path]});
const functions = exported as {
- getDailyNoteHint: (key: string, protyle: unknown) => {value: string, html: string} | undefined,
+ getDailyNoteHints: (key: string, protyle: unknown) => Promise<{value: string, html: string}[]>,
createDailyNoteReference: (protyle: unknown, date: string, notebook: string, callback: (id: string, title: string) => void) => void,
};
- return {functions, calls, storage, selected, appWindow, choose: (id: string) => choose?.(id), setFail: () => { fail = true; }};
+ return {functions, calls, storage, selected, appWindow, choose: (id: string) => choose?.(id),
+ setFail: () => { fail = true; }, setMissing: () => { existed = false; }};
};
const protyle = {notebookId: "normal", hint: {splitChar: "[["}};
-test("daily note candidates show dates and notebook names without creating documents", () => {
+test("daily note candidates show authenticated names and full paths without creating documents", async () => {
const context = createContext();
context.storage.last = "daily";
- const hint = context.functions.getDailyNoteHint("2026-09-25", protyle);
+ const [hint] = await context.functions.getDailyNoteHints("2026-09-25", protyle);
assert.equal(hint?.value, "daily-note:2026-09-25:daily");
- assert.ok(hint?.html.includes("Daily &lt;notes>"));
- assert.equal(context.calls.length, 0);
- assert.equal(context.functions.getDailyNoteHint("project today", protyle), undefined);
- assert.equal(context.functions.getDailyNoteHint("03/04", protyle)?.value, "");
- assert.equal(context.functions.getDailyNoteHint("today", {...protyle, hint: {splitChar: "(("}}), undefined);
+ assert.ok(hint?.html.includes("Daily &lt;notes>/Moved/Renamed &lt;note>"));
+ assert.ok(hint?.html.includes("popover__block\" data-id=\"existing\""));
+ assert.ok(hint?.html.includes("<mark>Renamed &lt;note></mark>"));
+ assert.equal(context.calls[0].path, "/api/filetree/getDailyNoteInfo");
+ assert.equal(context.calls.length, 1);
+ assert.equal((await context.functions.getDailyNoteHints("project today", protyle)).length, 0);
+ assert.equal((await context.functions.getDailyNoteHints("03/04", protyle)).length, 0);
+ assert.equal((await context.functions.getDailyNoteHints("10/", protyle)).length, 0);
+ assert.equal((await context.functions.getDailyNoteHints("today", {...protyle, hint: {splitChar: "(("}})).length, 0);
context.appWindow.siyuan.config.readonly = true;
- assert.equal(context.functions.getDailyNoteHint("today", protyle), undefined);
+ assert.equal((await context.functions.getDailyNoteHints("today", protyle)).length, 0);
+});
+
+test("missing daily notes display resolved creation titles and calendar-plus icons", async () => {
+ const context = createContext();
+ context.storage.last = "daily";
+ context.setMissing();
+ const [hint] = await context.functions.getDailyNoteHints("2026-09-25", protyle);
+ assert.ok(hint.html.includes("#iconCalendarPlus"));
+ assert.ok(hint.html.includes("New daily note <mark>Sep 25, 2026</mark>"));
+ assert.ok(hint.html.includes("Daily &lt;notes>/Daily/Sep 25, 2026"));
+ assert.ok(!hint.html.includes("popover__block"));
});
test("selecting a date reuses its previewed notebook and inserts the real document title", () => {
@@ -78,7 +100,7 @@ test("selecting a date reuses its previewed notebook and inserts the real docume
context.functions.createDailyNoteReference(protyle, "2026-09-25", "daily", () => assert.fail("failed creation inserted a reference"));
});
-test("an unselected notebook requires choosing and preserves encrypted boundaries", () => {
+test("an unselected notebook offers actual paths and preserves encrypted boundaries", async () => {
const context = createContext();
context.functions.createDailyNoteReference(protyle, "2026-09-25", "", () => {});
assert.equal(context.calls.length, 0);
@@ -90,7 +112,13 @@ test("an unselected notebook requires choosing and preserves encrypted boundarie
const encrypted = createContext();
encrypted.storage.last = "normal";
const source = {...protyle, notebookId: "encrypted"};
- assert.ok(encrypted.functions.getDailyNoteHint("today", source)?.value.endsWith(":"));
+ const hints = await encrypted.functions.getDailyNoteHints("today", source);
+ assert.equal(hints.length, 1);
+ assert.ok(hints[0].value.endsWith(":encrypted"));
encrypted.functions.createDailyNoteReference(source, "2026-09-25", "normal", () => {});
assert.deepEqual(encrypted.selected, ["encrypted"]);
+ const undecided = createContext();
+ const candidates = await undecided.functions.getDailyNoteHints("2026-09-25", protyle);
+ assert.equal(candidates.length, 2);
+ assert.ok(undecided.calls.every(call => call.path.endsWith("getDailyNoteInfo")));
});
diff --git a/app/src/protyle/hint/dailyNote.ts b/app/src/protyle/hint/dailyNote.ts
index 0be0551199..ba15d95b37 100644
--- a/app/src/protyle/hint/dailyNote.ts
+++ b/app/src/protyle/hint/dailyNote.ts
@@ -1,35 +1,44 @@
import {Constants} from "../../constants";
import {canReferenceDailyNoteNotebook, getLastDailyNoteNotebookId} from "../../util/dailyNote";
import {parseDailyNoteDate} from "../../util/dailyNoteDate";
-import {escapeHtml} from "../../util/escape";
+import {escapeAttr, escapeHtml} from "../../util/escape";
import {isEncryptedBox} from "../../util/pathName";
import {selectDailyNoteNotebook} from "../../util/mount";
-import {fetchPost} from "../../util/fetch";
+import {fetchPost, fetchSyncPost} from "../../util/fetch";
+import {setStorageVal} from "../util/compatibility";
const getNotebooks = (sourceID: string) => window.siyuan.notebooks.filter(notebook => !notebook.closed &&
canReferenceDailyNoteNotebook(sourceID, notebook.id, isEncryptedBox(sourceID), isEncryptedBox(notebook.id)));
-export const getDailyNoteHint = (key: string, protyle: IProtyle): IHintData | undefined => {
+export const getDailyNoteHints = async (key: string, protyle: IProtyle): Promise<IHintData[]> => {
if (window.siyuan.config.readonly || !["[[", "【【"].includes(protyle.hint.splitChar)) {
- return undefined;
+ return [];
}
const result = parseDailyNoteDate(key, window.siyuan.config.appearance.lang);
- if (!result) {
- return undefined;
- }
- if ("error" in result) {
- return {value: "", html: escapeHtml(window.siyuan.languages.dailyNoteDateInvalid)};
+ if (!result || "error" in result) {
+ return [];
}
const notebooks = getNotebooks(protyle.notebookId);
if (notebooks.length === 0) {
- return undefined;
+ return [];
}
const notebookID = getLastDailyNoteNotebookId(notebooks, window.siyuan.storage[Constants.LOCAL_DAILYNOTEID]);
- const notebook = notebooks.find(item => item.id === notebookID);
- return {
- value: `daily-note:${result.date}:${notebookID || ""}`,
- html: `<div class="b3-list-item__first"><svg class="b3-list-item__graphic"><use xlink:href="#iconCalendar"></use></svg><span class="b3-list-item__text">${escapeHtml(window.siyuan.languages.dailyNote)} <mark>${result.date}</mark></span></div><div class="b3-list-item__meta">${escapeHtml(notebook?.name || window.siyuan.languages.plsChoose)}</div>`,
- };
+ const targets = notebookID ? notebooks.filter(item => item.id === notebookID) : notebooks;
+ const hints = await Promise.all(targets.map(async notebook => {
+ const response = await fetchSyncPost("/api/filetree/getDailyNoteInfo", {notebook: notebook.id, date: result.date});
+ if (response.code !== 0 || !response.data) {
+ return undefined;
+ }
+ const info = response.data;
+ const icon = info.existed ? "iconCalendar" : "iconCalendarPlus";
+ const preview = info.existed ? ` data-id="${escapeAttr(info.id)}"` : "";
+ const label = info.existed ? window.siyuan.languages.dailyNote : window.siyuan.languages.fileTree11;
+ return {
+ value: `daily-note:${result.date}:${notebook.id}`,
+ html: `<div class="b3-list-item__first"><svg class="b3-list-item__graphic${info.existed ? " popover__block" : ""}"${preview}><use xlink:href="#${icon}"></use></svg><span class="b3-list-item__text">${escapeHtml(label)} <mark>${escapeHtml(info.title)}</mark></span><span class="b3-menu__accelerator">${result.date}</span></div><div class="b3-list-item__meta">${escapeHtml(notebook.name + info.hPath)}</div>`,
+ };
+ }));
+ return hints.filter((hint): hint is IHintData => !!hint);
};
// 用户选中候选后才创建日记;候选生成不会改动工作区。
@@ -40,6 +49,8 @@ export const createDailyNoteReference = (protyle: IProtyle, date: string, notebo
if (!getNotebooks(protyle.notebookId).some(item => item.id === notebook)) {
return;
}
+ window.siyuan.storage[Constants.LOCAL_DAILYNOTEID] = notebook;
+ setStorageVal(Constants.LOCAL_DAILYNOTEID, notebook);
fetchPost("/api/filetree/createDailyNote", {notebook, date, app: Constants.SIYUAN_APPID}, response => {
if (response.code === 0 && response.data?.id) {
const id = response.data.id;
diff --git a/app/src/protyle/hint/dailyNoteRef.test.ts b/app/src/protyle/hint/dailyNoteRef.test.ts
new file mode 100644
index 0000000000..9c306414fb
--- /dev/null
+++ b/app/src/protyle/hint/dailyNoteRef.test.ts
@@ -0,0 +1,41 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {test} from "node:test";
+import {setImmediate} from "node:timers/promises";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+
+const source = createSourceFile("extend.ts", readFileSync(join(__dirname, "extend.ts"), "utf8"), ScriptTarget.Latest);
+const declaration = source.statements.find(node => isVariableStatement(node) &&
+ node.declarationList.declarations.some(item => item.name.getText(source) === "hintRef"));
+assert.ok(declaration);
+const code = transpileModule(declaration.getText(source).replace("export ", "") + "\nhintRef;", {
+ compilerOptions: {target: ScriptTarget.ES2020},
+}).outputText;
+
+test("typing a slash in reference search does not run title replacement or show a warning", async () => {
+ let rendered = false;
+ const block = {getAttribute: () => "block"};
+ const hintRef = runInNewContext(code, {
+ window: {siyuan: {languages: {newFile: "New document", newSubDoc: "New child", newFileAtPath: "Choose location"}}},
+ Constants: {ZWSP: "\u200b"}, Lute: {Caret: "caret", UnEscapeHTMLStr: (text: string) => text},
+ getEditorRange: () => ({startContainer: block}), hasClosestBlock: () => block,
+ isEncryptedBox: () => false, getDailyNoteHints: async (): Promise<IHintData[]> => [],
+ replaceFileName: () => assert.fail("typing a query sanitized a document title"),
+ fetchPost: (path: string, request: {k: string}, callback: (response: unknown) => void) => {
+ assert.equal(path, "/api/search/searchRefBlock");
+ assert.equal(request.k, "10/");
+ callback({data: {k: "10/", newDoc: true, blocks: []}});
+ },
+ });
+ const protyle = {notebookId: "box", element: {clientWidth: 320}, block: {rootID: "root"},
+ toolbar: {range: {startContainer: block}}, wysiwyg: {element: {}}, hint: {
+ splitChar: "[[", genLoading() {},
+ prepareCreateTarget: () => ({promise: Promise.resolve(false), isCurrent: () => true}),
+ genHTML: (data: {value: string}[]) => { rendered = true; assert.ok(data[0].value.includes("10/")); },
+ }};
+ hintRef("10/", protyle, "hint");
+ await setImmediate();
+ assert.equal(rendered, true);
+});
diff --git a/app/src/protyle/hint/dailyNoteSelection.test.ts b/app/src/protyle/hint/dailyNoteSelection.test.ts
new file mode 100644
index 0000000000..e3a279f1a9
--- /dev/null
+++ b/app/src/protyle/hint/dailyNoteSelection.test.ts
@@ -0,0 +1,65 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, transpileModule} from "typescript";
+
+const code = transpileModule(readFileSync(join(__dirname, "dailyNoteSelection.ts"), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS},
+}).outputText;
+
+test("daily note insertion survives caret movement and repaint without overwriting changed input", () => {
+ for (const scenario of ["unchanged", "moved", "repaint", "markers", "edited", "deleted", "other-document", "closed"]) {
+ let originalText = "[[today";
+ const original = {available: true, toString: () => originalText, cloneRange() { return {...this}; }};
+ const caret = {available: true, toString: () => "", cloneRange() { return {...this}; }};
+ let active = scenario === "unchanged" ? original : caret;
+ let inserted = false;
+ let restoredCurrent = false;
+ const toolbar = {range: original, setInlineMark: (_protyle: unknown, type: string, _action: string,
+ options: {color: string}, focus: boolean): HTMLElement[] => {
+ assert.equal(type, "block-ref");
+ assert.ok(options.color.includes("Daily title"));
+ assert.equal(focus, false);
+ assert.equal(toolbar.range.toString().replace(/\u200b/g, ""), "[[today");
+ inserted = true;
+ return [];
+ }};
+ const protyle = {block: {rootID: "root"}, notebookId: "box", toolbar, wysiwyg: {element: {isConnected: true}}};
+ const mocks: Record<string, unknown> = {
+ "../../constants": {Constants: {ZWSP: "\u200b"}},
+ "../../util/newFile": {getBlockRefAnchorText: (title: string) => title},
+ "../util/inlineElementMarker": {stripSemanticMarkersFromRangeText: (range: typeof original) => range.toString()},
+ "../../util/newFileSelection": {
+ isRangeInEditor: (_editor: unknown, range: {available: boolean}) => range.available,
+ isSameRange: (range: {toString: () => string}, target: {toString: () => string}) => range.toString() === target.toString(),
+ },
+ "../util/selection": {
+ getUndoFocusContext: (_editor: unknown, range: unknown) => ({id: range === caret ? "caret" : "original"}),
+ focusByRange: (range: typeof original) => { active = range; restoredCurrent = range.toString() === ""; },
+ restoreFocusContext: (_protyle: unknown, context: {id: string}) => {
+ if (scenario === "deleted") { return false; }
+ active = context.id === "caret" ? caret : {available: true, toString: () => originalText, cloneRange() { return {...this}; }};
+ return true;
+ },
+ },
+ };
+ const exported = {};
+ runInNewContext(code, {exports: exported, require: (path: string) => mocks[path],
+ document: {getSelection: () => ({rangeCount: 1, getRangeAt: () => active})}});
+ const functions = exported as {
+ captureDailyNoteSelection: (protyle: unknown, range: unknown) => {range: {available: boolean}},
+ insertDailyNoteReference: (protyle: unknown, target: unknown, id: string, title: string, staticRef: boolean) => void,
+ };
+ const target = functions.captureDailyNoteSelection(protyle, original);
+ if (["repaint", "deleted"].includes(scenario)) { target.range.available = false; }
+ if (scenario === "edited") { originalText = "edited input"; }
+ if (scenario === "markers") { originalText = "\u200b[[today\u200b"; }
+ if (scenario === "other-document") { protyle.block.rootID = "another"; }
+ if (scenario === "closed") { protyle.wysiwyg.element.isConnected = false; }
+ functions.insertDailyNoteReference(protyle, target, "created", "Daily title", false);
+ assert.equal(inserted, ["unchanged", "moved", "repaint", "markers"].includes(scenario), scenario);
+ if (["moved", "repaint", "edited"].includes(scenario)) { assert.equal(restoredCurrent, true, scenario); }
+ }
+});
diff --git a/app/src/protyle/hint/dailyNoteSelection.ts b/app/src/protyle/hint/dailyNoteSelection.ts
new file mode 100644
index 0000000000..8b45d30e45
--- /dev/null
+++ b/app/src/protyle/hint/dailyNoteSelection.ts
@@ -0,0 +1,58 @@
+import {Constants} from "../../constants";
+import {getBlockRefAnchorText} from "../../util/newFile";
+import {isRangeInEditor, isSameRange} from "../../util/newFileSelection";
+import {focusByRange, getUndoFocusContext, restoreFocusContext} from "../util/selection";
+import {stripSemanticMarkersFromRangeText} from "../util/inlineElementMarker";
+
+const getInputText = (range: Range) => stripSemanticMarkersFromRangeText(range).split(Constants.ZWSP).join("");
+
+export const captureDailyNoteSelection = (protyle: IProtyle, range: Range) => ({
+ range: range.cloneRange(),
+ text: getInputText(range),
+ context: getUndoFocusContext(protyle.wysiwyg.element, range, true),
+ rootID: protyle.block.rootID,
+ notebookID: protyle.notebookId,
+});
+
+// 按原文档和逻辑位置插入,光标移动不取消插入;重绘后恢复原选区并核对输入。
+export const insertDailyNoteReference = (protyle: IProtyle, target: ReturnType<typeof captureDailyNoteSelection>,
+ id: string, title: string, staticRef: boolean,
+ undoContext?: Record<string, string>) => {
+ if (!protyle.wysiwyg.element.isConnected || protyle.block.rootID !== target.rootID || protyle.notebookId !== target.notebookID) {
+ return;
+ }
+ const selection = document.getSelection();
+ const currentRange = selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : undefined;
+ const currentContext = getUndoFocusContext(protyle.wysiwyg.element, currentRange, true);
+ const restoreCurrent = () => {
+ if (currentRange && isRangeInEditor(protyle.wysiwyg.element, currentRange)) {
+ protyle.toolbar.range = currentRange;
+ focusByRange(currentRange);
+ } else if (currentContext && restoreFocusContext(protyle, currentContext)) {
+ protyle.toolbar.range = document.getSelection().getRangeAt(0);
+ }
+ };
+ let range = target.range;
+ if (!isRangeInEditor(protyle.wysiwyg.element, range) || getInputText(range) !== target.text) {
+ if (!target.context || !restoreFocusContext(protyle, target.context)) {
+ return;
+ }
+ range = document.getSelection().getRangeAt(0).cloneRange();
+ }
+ if (getInputText(range) !== target.text) {
+ restoreCurrent();
+ return;
+ }
+ const moved = currentRange && !isSameRange(currentRange, range);
+ protyle.toolbar.range = range;
+ const refs = protyle.toolbar.setInlineMark(protyle, "block-ref", "range", {
+ type: "id", color: `${id}${Constants.ZWSP}${staticRef ? "s" : "d"}${Constants.ZWSP}${getBlockRefAnchorText(title)}`,
+ }, false, undoContext);
+ if (moved) {
+ restoreCurrent();
+ } else if (refs?.[0]) {
+ protyle.toolbar.range.selectNodeContents(refs[0]);
+ protyle.toolbar.range.collapse(false);
+ focusByRange(protyle.toolbar.range);
+ }
+};
diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.ts
index 5f674fad4a..90a7ec0703 100644
--- a/app/src/protyle/hint/extend.ts
+++ b/app/src/protyle/hint/extend.ts
@@ -18,7 +18,6 @@ import {
getSbChildBlockCount,
getTopAloneElement
} from "../wysiwyg/getBlock";
-import {replaceFileName} from "../../editor/rename";
import {transaction} from "../wysiwyg/transaction";
import {getAssetExtension, getAssetName, getDisplayName, isEncryptedBox} from "../../util/pathName";
import {cancelSB, genEmptyElement, rebalanceSbWidth, refreshSbResize} from "../../block/util";
@@ -56,7 +55,7 @@ import {
} from "../wysiwyg/blockSelection";
import {countBlockWord} from "../../layout/status";
import {genTemplateDocTreePlanHTML} from "../../template/docTree";
-import {getDailyNoteHint} from "./dailyNote";
+import {getDailyNoteHints} from "./dailyNote";
const slashBuiltinStyleIDs: Partial<Record<string, TBuiltinInlineStyleID>> = {
infoStyle: "info",
@@ -605,20 +604,18 @@ export const hintRef = (key: string, protyle: IProtyle, source: THintSource): IH
if (protyle.lite && isEncryptedBox(protyle.notebookId)) {
refParam.notebook = protyle.notebookId;
}
+ const dailyNotes = source === "hint" ? getDailyNoteHints(key, protyle).catch((): IHintData[] => []) : Promise.resolve([] as IHintData[]);
fetchPost("/api/search/searchRefBlock", refParam, (response) => {
- createTarget.promise.then((hideConfiguredCreate) => {
+ Promise.all([createTarget.promise, dailyNotes]).then(([hideConfiguredCreate, dateHints]) => {
if (!createTarget.isCurrent()) {
return;
}
const dataList: IHintData[] = [];
let createItemCount = 0;
- const dailyNote = source === "hint" ? getDailyNoteHint(key, protyle) : undefined;
- if (dailyNote) {
- dataList.push(dailyNote);
- createItemCount++;
- }
+ dataList.push(...dateHints);
+ createItemCount += dateHints.length;
if (response.data.newDoc) {
- const newFileName = Lute.UnEscapeHTMLStr(replaceFileName(response.data.k));
+ const newFileName = Lute.UnEscapeHTMLStr(response.data.k);
if (!hideConfiguredCreate) {
dataList.push({
value: `((newFile "${newFileName}"${Constants.ZWSP}'${newFileName}${Lute.Caret}'))`,
diff --git a/app/src/protyle/hint/fillCommand.test.ts b/app/src/protyle/hint/fillCommand.test.ts
index 61c759be99..67e4728e32 100644
--- a/app/src/protyle/hint/fillCommand.test.ts
+++ b/app/src/protyle/hint/fillCommand.test.ts
@@ -16,7 +16,7 @@ const code = transpileModule(`class Hint { ${methods} } new Hint();`, {
compilerOptions: {target: ScriptTarget.ES2020},
}).outputText;
-test("daily note reference completion retains its range and ignores edited or removed input", () => {
+test("daily note completion retains its original insertion target while awaiting creation", () => {
for (const scenario of ["valid", "edited", "removed"]) {
let text = "[[2026-09-25";
let inserted = false;
@@ -38,6 +38,13 @@ test("daily note reference completion retains its range and ignores edited or re
hideElements() {}, hasClosestBlock: () => block, focusByRange() {},
shouldCaptureHintUndoFocus, getUndoFocusContext: () => ({}),
getBlockRefAnchorText: (title: string) => title,
+ captureDailyNoteSelection: () => ({original: true}),
+ insertDailyNoteReference: (_protyle: unknown, target: {original: boolean}, id: string, title: string) => {
+ assert.equal(target.original, true);
+ assert.equal(id, "existing");
+ assert.equal(title, "Daily title");
+ inserted = true;
+ },
createDailyNoteReference: (_protyle: unknown, date: string, notebook: string,
callback: (id: string, title: string) => void) => {
assert.equal(date, "2026-09-25");
@@ -54,7 +61,7 @@ test("daily note reference completion retains its range and ignores edited or re
block.isConnected = false;
}
complete?.("existing", "Daily title");
- assert.equal(inserted, scenario === "valid");
+ assert.equal(inserted, true);
}
});
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index 009f48f94e..4d3d1d20d6 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -21,6 +21,7 @@ import {
} from "../util/selection";
import {genHintItemHTML, hintEmbed, hintRef, hintSlash, hintTag} from "./extend";
import {createDailyNoteReference} from "./dailyNote";
+import {captureDailyNoteSelection, insertDailyNoteReference} from "./dailyNoteSelection";
import {
getBlockRefAnchorText,
getDocCreateTemplatePath,
@@ -949,22 +950,9 @@ ${genHintItemHTML(item)}
}
if (["[[", "【【"].includes(this.splitChar) && /^daily-note:\d{4}-\d{2}-\d{2}:[a-z0-9-]*$/.test(value)) {
const [, date, notebookID] = value.split(":");
- const savedRange = range.cloneRange();
- const input = savedRange.toString();
+ const target = captureDailyNoteSelection(protyle, range);
createDailyNoteReference(protyle, date, notebookID, (id, title) => {
- if (!nodeElement.isConnected || savedRange.toString() !== input) {
- return;
- }
- protyle.toolbar.range = savedRange;
- focusByRange(savedRange);
- const refElement = protyle.toolbar.setInlineMark(protyle, "block-ref", "range", {
- type: "id",
- color: `${id}${Constants.ZWSP}${refIsS ? "s" : "d"}${Constants.ZWSP}${getBlockRefAnchorText(title)}`
- }, true, undoContext);
- if (refElement[0]) {
- protyle.toolbar.range.setEnd(refElement[0].lastChild, refElement[0].lastChild.textContent.length);
- protyle.toolbar.range.collapse(false);
- }
+ insertDailyNoteReference(protyle, target, id, title, refIsS, undoContext);
});
return;
}
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 07f2d0d3f8..09adf424de 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -888,6 +888,10 @@ export type DOMTextRequestInput = { "dom": string; };
export type DailyNoteBlockRequestInput = { "data": string; "dataType": string; "notebook": string; };
+export type DailyNoteInfo = { "existed": boolean; "hPath": string; "id": string; "title": string; };
+
+export type DailyNoteInfoRequestInput = { "date"?: string | null; "notebook": string; };
+
export type DeleteBlockRequestInput = { "id": string; };
export type DiffDocVersionsRequestInput = { "left": DocVersionRefInput; "right": DocVersionRefInput; };
@@ -4130,6 +4134,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": FileTreeDuplicateData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/filetree/getDailyNoteInfo": {
+ request: DailyNoteInfoRequestInput;
+ response: { "code": 0; "data": DailyNoteInfo | null; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/filetree/getDoc": {
request: FileTreeGetDocRequestInput;
response: { "code": 0; "data": FileTreeGetDocData; "msg": string; } | { "code": -1 | 1 | 3; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/kernel/api/box_lease_test.go b/kernel/api/box_lease_test.go
index e28d67d2e5..1461b75342 100644
--- a/kernel/api/box_lease_test.go
+++ b/kernel/api/box_lease_test.go
@@ -85,6 +85,10 @@ func TestContractDailyNoteNotebookResponseLease(t *testing.T) {
runNotebookResponseLease(t, true, false)
}
+func TestContractDailyNoteInfoNotebookResponseLease(t *testing.T) {
+ runNotebookResponseLease(t, true, false)
+}
+
func TestContractGetDocNotebookResponseLease(t *testing.T) {
runNotebookResponseLease(t, true, false)
}
@@ -197,7 +201,7 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
model.Conf = model.NewAppConf()
model.Conf.NotebookCrypto, model.Conf.Sync, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewSync(), conf.NewFileTree()
model.Conf.Editor, model.Conf.Export, model.Conf.Search = conf.NewEditor(), conf.NewExport(), conf.NewSearch()
- if t.Name() == "TestContractDailyNoteNotebookResponseLease" {
+ if t.Name() == "TestContractDailyNoteNotebookResponseLease" || t.Name() == "TestContractDailyNoteInfoNotebookResponseLease" {
content, err := os.ReadFile(filepath.Join("..", "..", "app", "appearance", "langs", "en.json"))
if err != nil {
t.Fatal(err)
@@ -245,7 +249,7 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
t.Fatal(err)
}
treenode.UpsertBlockTree(tree)
- if t.Name() == "TestContractDailyNoteNotebookResponseLease" {
+ if t.Name() == "TestContractDailyNoteNotebookResponseLease" || t.Name() == "TestContractDailyNoteInfoNotebookResponseLease" {
if _, err := model.Mount(boxID); err != nil {
t.Fatal(err)
}
@@ -260,6 +264,7 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
engine.POST("/api/block/checkBlockRef", checkBlockRef)
engine.POST("/api/block/getDocInfo", getDocInfo)
engine.POST("/api/filetree/createDailyNote", createDailyNote)
+ engine.POST("/api/filetree/getDailyNoteInfo", getDailyNoteInfo)
engine.POST("/api/filetree/getDoc", getDoc)
engine.POST("/api/block/getTreeStat", getTreeStat)
engine.POST("/api/block/getBlockBreadcrumb", getBlockBreadcrumb)
@@ -317,6 +322,9 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
case "TestContractDailyNoteNotebookResponseLease":
endpoint, typedQuery = "/api/filetree/createDailyNote", true
args["date"] = "2024-02-29"
+ case "TestContractDailyNoteInfoNotebookResponseLease":
+ endpoint, typedQuery = "/api/filetree/getDailyNoteInfo", true
+ args["date"] = "2024-02-29"
case "TestContractGetDocNotebookResponseLease":
endpoint, typedQuery = "/api/filetree/getDoc", true
case "TestContractTreeStatNotebookResponseLease":
@@ -430,7 +438,7 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
if lockedBeforeResponse {
t.Fatalf("lock completed before plaintext response was sent: %s", writer.Body.String())
}
- if t.Name() == "TestContractDailyNoteNotebookResponseLease" {
+ if t.Name() == "TestContractDailyNoteNotebookResponseLease" || t.Name() == "TestContractDailyNoteInfoNotebookResponseLease" {
recorder := httptest.NewRecorder()
engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, endpoint, strings.NewReader(string(requestBody))))
requireAPIContract(t, http.MethodPost, endpoint, recorder)
diff --git a/kernel/api/contract_filetree_test.go b/kernel/api/contract_filetree_test.go
index f800d57999..b307e7b135 100644
--- a/kernel/api/contract_filetree_test.go
+++ b/kernel/api/contract_filetree_test.go
@@ -80,6 +80,7 @@ func TestAPIContractFileTreeDailyNoteDate(t *testing.T) {
engine := gin.New()
const path = "/api/filetree/createDailyNote"
engine.POST(path, createDailyNote)
+ engine.POST("/api/filetree/getDailyNoteInfo", getDailyNoteInfo)
for _, entry := range []struct {
body string
code int
@@ -106,6 +107,12 @@ func TestAPIContractFileTreeDailyNoteDate(t *testing.T) {
if response.Code != entry.code {
t.Fatalf("unexpected daily note response for %s: %s", entry.body, recorder.Body.String())
}
+ preview := httptest.NewRecorder()
+ engine.ServeHTTP(preview, httptest.NewRequest("POST", "/api/filetree/getDailyNoteInfo", strings.NewReader(entry.body)))
+ requireAPIContract(t, "POST", "/api/filetree/getDailyNoteInfo", preview)
+ if err := json.Unmarshal(preview.Body.Bytes(), &response); err != nil || response.Code != entry.code {
+ t.Fatalf("unexpected preview response for %s: %s %v", entry.body, preview.Body.String(), err)
+ }
}
}
diff --git a/kernel/api/daily_note.go b/kernel/api/daily_note.go
new file mode 100644
index 0000000000..4e432a5153
--- /dev/null
+++ b/kernel/api/daily_note.go
@@ -0,0 +1,41 @@
+package api
+
+import (
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+func parseDailyNoteDate(value string) (time.Time, error) {
+ if value == "" {
+ return time.Now(), nil
+ }
+ date, err := time.ParseInLocation("2006-01-02", value, time.Local)
+ if err == nil && (date.Year() < 1 || date.Format("2006-01-02") != value) {
+ err = fmt.Errorf("invalid daily note date [%s]", value)
+ }
+ return date, err
+}
+
+var getDailyNoteInfo = contractHandler(apicontract.GetDailyNoteInfo, func(c *gin.Context, request apicontract.DailyNoteInfoRequest) apicontract.Response[*apicontract.DailyNoteInfo] {
+ if err := holdEncryptedBoxRequest(c, request.Notebook); err != nil {
+ return apicontract.Failure[*apicontract.DailyNoteInfo](-1, model.Conf.Language(314))
+ }
+ date, err := parseDailyNoteDate(request.Date)
+ if err != nil {
+ return apicontract.Failure[*apicontract.DailyNoteInfo](-1, err.Error())
+ }
+ info, err := model.GetDailyNoteInfo(request.Notebook, date)
+ if err != nil {
+ code := -1
+ if errors.Is(err, model.ErrBoxNotFound) {
+ code = 1
+ }
+ return apicontract.Failure[*apicontract.DailyNoteInfo](code, err.Error())
+ }
+ return apicontract.Success(&apicontract.DailyNoteInfo{ID: info.ID, HPath: info.HPath, Title: info.Title, Existed: info.Existed})
+})
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index a669788cfb..d02d641e64 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -27,7 +27,6 @@ import (
"regexp"
"strconv"
"strings"
- "time"
"unicode/utf8"
"github.com/88250/gulu"
@@ -774,11 +773,8 @@ func createDailyNoteContract(c *gin.Context, request apicontract.FileTreeDailyNo
if request.Date == "" {
p, existed, err = model.CreateDailyNote(notebook)
} else {
- var date time.Time
- date, err = time.ParseInLocation("2006-01-02", request.Date, time.Local)
- if err == nil && (date.Year() < 1 || date.Format("2006-01-02") != request.Date) {
- err = fmt.Errorf("invalid daily note date [%s]", request.Date)
- }
+ date, dateErr := parseDailyNoteDate(request.Date)
+ err = dateErr
if err == nil {
p, existed, err = model.CreateDailyNoteAt(notebook, date)
}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index be9aff78c9..b5be1e2571 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -194,6 +194,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/filetree/setDocSortMode", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setDocSortMode)
ginServer.Handle("POST", "/api/filetree/createDocWithMd", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createDocWithMd)
ginServer.Handle("POST", "/api/filetree/createDailyNote", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createDailyNote)
+ ginServer.Handle("POST", "/api/filetree/getDailyNoteInfo", model.CheckAuth, model.CheckAdminRole, getDailyNoteInfo)
ginServer.Handle("POST", "/api/filetree/createDoc", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createDoc)
ginServer.Handle("POST", "/api/filetree/renameDoc", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, renameDoc)
ginServer.Handle("POST", "/api/filetree/renameDocByID", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, renameDocByID)
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 01f8ba1752..5d026d40d4 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -812,6 +812,8 @@ var DuplicateDocTree = define[FileTreeIDRequest, FileTreeDuplicateData]("duplica
var CreateDoc = define[FileTreeCreateRequest, FileTreeCreateData]("createDoc", "/api/filetree/createDoc", JSONBody, ResponseOptions{}, "POST")
var CreateDailyNote = define[FileTreeDailyNoteRequest, FileTreeCreateData]("createDailyNote", "/api/filetree/createDailyNote", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
+var GetDailyNoteInfo = define[DailyNoteInfoRequest, *DailyNoteInfo]("getDailyNoteInfo", "/api/filetree/getDailyNoteInfo", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
+
// CreateDocWithMd 保留编辑器 Markdown 语法选项,并按 ImportStdMd 的规则自动转换标准脚注。
// 请求字段、文档 ID 响应和笔记本权限规则不变;转义的脚注语法可用于保留字面文本。
var CreateDocWithMd = define[FileTreeCreateMarkdownRequest, string]("createDocWithMd", "/api/filetree/createDocWithMd", JSONBody, ResponseOptions{}, "POST")
diff --git a/kernel/apicontract/daily_note.go b/kernel/apicontract/daily_note.go
new file mode 100644
index 0000000000..6eb0151c31
--- /dev/null
+++ b/kernel/apicontract/daily_note.go
@@ -0,0 +1,18 @@
+package apicontract
+
+// DailyNoteInfoRequest 查询指定笔记本的日记候选,不创建文档或修改已有日记属性。
+// Date 为本地公历日期 YYYY-MM-DD,省略、空串或 null 时使用当天;日期无效返回 -1。
+// 已有文档按日期属性及模板路径定位,返回实际标题和不含笔记本名的绝对人类路径。
+// 不存在时返回解析后的创建标题和路径,ID 为空;不存在的笔记本返回 1。
+// 需要管理员权限,允许只读模式,加密笔记本必须解锁并保留响应租约。
+type DailyNoteInfoRequest struct {
+ Notebook string `json:"notebook"`
+ Date string `json:"date" api:"optional,nullable"`
+}
+
+type DailyNoteInfo struct {
+ ID string `json:"id"`
+ HPath string `json:"hPath"`
+ Title string `json:"title"`
+ Existed bool `json:"existed"`
+}
diff --git a/kernel/apicontract/daily_note_test.go b/kernel/apicontract/daily_note_test.go
new file mode 100644
index 0000000000..8e7e483252
--- /dev/null
+++ b/kernel/apicontract/daily_note_test.go
@@ -0,0 +1,24 @@
+package apicontract
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestDailyNoteInfoContract(t *testing.T) {
+ for _, entry := range []struct {
+ body string
+ valid bool
+ }{
+ {`{"notebook":"box"}`, true},
+ {`{"notebook":"box","date":null}`, true},
+ {`{"notebook":"box","date":"2024-02-29"}`, true},
+ {`{"date":"2024-02-29"}`, false},
+ {`{"notebook":"box","date":false}`, false},
+ } {
+ _, err := GetDailyNoteInfo.Decode(strings.NewReader(entry.body))
+ if (err == nil) != entry.valid {
+ t.Fatalf("unexpected input admission: %s %v", entry.body, err)
+ }
+ }
+}
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 1856a50172..bfe70085e1 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -22113,6 +22113,52 @@
],
"additionalProperties": false
},
+ "DailyNoteInfo": {
+ "type": "object",
+ "properties": {
+ "existed": {
+ "type": "boolean"
+ },
+ "hPath": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "existed",
+ "hPath",
+ "id",
+ "title"
+ ],
+ "additionalProperties": false
+ },
+ "DailyNoteInfoRequestInput": {
+ "type": "object",
+ "properties": {
+ "date": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "notebook": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "notebook"
+ ],
+ "additionalProperties": false
+ },
"DeleteBlockRequestInput": {
"type": "object",
"properties": {
@@ -141016,6 +141062,89 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/filetree/getDailyNoteInfo",
+ "handler": "getDailyNoteInfo",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/DailyNoteInfoRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/DailyNoteInfo"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1,
+ 1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/filetree/getDoc",
diff --git a/kernel/model/daily_note.go b/kernel/model/daily_note.go
new file mode 100644
index 0000000000..4ad084b472
--- /dev/null
+++ b/kernel/model/daily_note.go
@@ -0,0 +1,90 @@
+package model
+
+import (
+ "errors"
+ "path"
+ "strings"
+ "time"
+
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type DailyNoteInfo struct {
+ ID string
+ HPath string
+ Title string
+ Existed bool
+}
+
+// resolveDailyNote 定位日期对应的文档;已有日记以认证后的源文档为准。
+func resolveDailyNote(box *Box, now time.Time, findByDate bool) (hPath string, tree *parse.Tree, err error) {
+ boxConf := box.GetConf()
+ if boxConf.DailyNoteSavePath == "" || boxConf.DailyNoteSavePath == "/" {
+ return "", nil, errors.New(Conf.Language(49))
+ }
+ hPath, err = RenderGoTemplateAtInBox(boxConf.DailyNoteSavePath, now, box.ID)
+ if err != nil {
+ return
+ }
+ hPath = util.TrimSpaceInPath(strings.TrimSuffix(hPath, ".sy"))
+ FlushTxQueue()
+ root := treenode.GetBlockTreeRootByHPath(box.ID, hPath)
+ rootID := ""
+ if root != nil {
+ rootID = root.RootID
+ }
+ fromDate := false
+ date := now.Format("20060102")
+ if findByDate {
+ sql.FlushQueue()
+ var ids []string
+ ids, err = sql.QueryDailyNoteRootIDsInBox(box.ID, DailyNoteAttrPrefix+date, date)
+ if err != nil {
+ return
+ }
+ if len(ids) > 0 {
+ matched := false
+ for _, id := range ids {
+ if rootID == id {
+ matched = true
+ break
+ }
+ }
+ if !matched {
+ rootID = ids[0]
+ }
+ fromDate = true
+ }
+ }
+ if rootID == "" {
+ return
+ }
+ tree, err = LoadTreeByBlockID(rootID)
+ if err != nil {
+ return
+ }
+ if tree.Box != box.ID || (fromDate && tree.Root.IALAttr(DailyNoteAttrPrefix+date) != date) {
+ return "", nil, ErrBlockNotFound
+ }
+ return
+}
+
+// GetDailyNoteInfo 仅解析命名模板并读取已有文档,不创建文档或添加日记属性。
+func GetDailyNoteInfo(boxID string, date time.Time) (info *DailyNoteInfo, err error) {
+ box := Conf.Box(boxID)
+ if box == nil {
+ return nil, ErrBoxNotFound
+ }
+ hPath, tree, err := resolveDailyNote(box, date, true)
+ if err != nil {
+ return nil, err
+ }
+ info = &DailyNoteInfo{HPath: hPath, Title: path.Base(hPath)}
+ if tree != nil {
+ info.ID, info.HPath, info.Title, info.Existed = tree.Root.ID, tree.HPath, tree.Root.IALAttr("title"), true
+ }
+ return
+}
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 3c264cd1c9..4761b8187d 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -1462,58 +1462,15 @@ func createDailyNoteAt(boxID string, now time.Time, findByDate bool) (p string,
}
boxConf := box.GetConf()
- if "" == boxConf.DailyNoteSavePath || "/" == boxConf.DailyNoteSavePath {
- err = errors.New(Conf.Language(49))
- return
- }
-
- hPath, err := RenderGoTemplateAtInBox(boxConf.DailyNoteSavePath, now, box.ID)
+ hPath, existTree, err := resolveDailyNote(box, now, findByDate)
if err != nil {
return
}
- FlushTxQueue()
-
- hPath = util.TrimSpaceInPath(hPath)
- existRoot := treenode.GetBlockTreeRootByHPath(box.ID, hPath)
date := now.Format("20060102")
- if findByDate {
- sql.FlushQueue()
- var ids []string
- ids, err = sql.QueryDailyNoteRootIDsInBox(box.ID, DailyNoteAttrPrefix+date, date)
- if err != nil {
- return
- }
- if len(ids) > 0 {
- matchedPath := false
- for _, id := range ids {
- if existRoot != nil && existRoot.RootID == id {
- matchedPath = true
- break
- }
- }
- if !matchedPath {
- tree, loadErr := LoadTreeByBlockID(ids[0])
- if loadErr != nil {
- return "", false, loadErr
- }
- if tree.Box != box.ID || tree.Root.IALAttr(DailyNoteAttrPrefix+date) != date {
- return "", false, ErrBlockNotFound
- }
- return tree.Path, true, nil
- }
- }
- }
- if nil != existRoot {
+ if existTree != nil {
existed = true
- p = existRoot.Path
-
- tree, loadErr := LoadTreeByBlockID(existRoot.RootID)
- if nil != loadErr {
- logging.LogWarnf("load tree by block id [%s] failed: %v", existRoot.RootID, loadErr)
- err = loadErr
- return
- }
+ tree := existTree
p = tree.Path
if tree.Root.IALAttr(DailyNoteAttrPrefix+date) == "" {
tree.Root.SetIALAttr(DailyNoteAttrPrefix+date, date)
diff --git a/kernel/model/file_index_test.go b/kernel/model/file_index_test.go
index e736e2e04f..9a7036ad83 100644
--- a/kernel/model/file_index_test.go
+++ b/kernel/model/file_index_test.go
@@ -243,6 +243,13 @@ func TestDocumentTemplatesWaitForDatabaseIndex(t *testing.T) {
t.Fatal(err)
}
target := time.Date(2024, 2, 29, 0, 0, 0, 0, time.Local)
+ info, err := GetDailyNoteInfo(box.ID, target)
+ if err != nil || info.Existed || info.ID != "" || info.HPath != "/Daily note/2024-02-29" || info.Title != "2024-02-29" {
+ t.Fatalf("unexpected missing daily note preview: %#v %v", info, err)
+ }
+ if treenode.GetBlockTreeRootByHPath(box.ID, info.HPath) != nil {
+ t.Fatal("preview created a document")
+ }
datedPath, existed, err := CreateDailyNoteAt(box.ID, target)
if err != nil || existed {
t.Fatalf("create dated note: %s %v %v", datedPath, existed, err)
@@ -288,6 +295,25 @@ func TestDocumentTemplatesWaitForDatabaseIndex(t *testing.T) {
if err != nil || !existed || reusedPath != datedPath {
t.Fatalf("template change duplicated an existing date: %s %v %v", reusedPath, existed, err)
}
+ info, err = GetDailyNoteInfo(box.ID, target)
+ if err != nil || !info.Existed || info.ID != datedID || info.HPath != "/Renamed daily note" || info.Title != "Renamed daily note" {
+ t.Fatalf("preview did not reuse actual renamed and moved document: %#v %v", info, err)
+ }
+ beforeTree, err := LoadTreeByBlockID(datedID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ beforeUpdated := beforeTree.Root.IALAttr("updated")
+ if _, err := GetDailyNoteInfo(box.ID, target); err != nil {
+ t.Fatal(err)
+ }
+ afterTree, err := LoadTreeByBlockID(datedID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if beforeUpdated != afterTree.Root.IALAttr("updated") {
+ t.Fatal("preview changed document timestamps")
+ }
docID := "20260728000001-abcdefg"
arg := map[string]any{"docCreateTemplatePath": "/indexed.md"}