An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support creating and referencing daily notes by date https://github.com/siyuan-note/siyuan/issues/20201
Daniela87680eb28b5
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 8ae2a2dca4..0b9a078af4 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,5 @@{+ "dailyNoteDateInvalid": "التاريخ غير صالح أو ملتبس؛ أدخل تاريخًا كاملًا بصيغة YYYY-MM-DD","goToDocumentStart": "الانتقال إلى بداية المستند","goToDocumentEnd": "الانتقال إلى نهاية المستند","agentBuiltinPluginDevelopmentDescription": "سير العمل الرسمي لتطوير إضافات الواجهة الأمامية: بعد موافقتك الصريحة، تُستوضح المتطلبات الناقصة وتُعتمد خطة موجزة ثم يُنفّذ العمل في نسخة مُدارة ويُتحقّق منه وتُجهّز الحزمة؛ يتطلب التثبيت والتفعيل إذنًا منفصلًا",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 5e8e4350aa..105857eeb6 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,5 @@{+ "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.jsonindex 05f056cbb5..e333b8b78f 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,5 @@{+ "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.jsonindex f7d9e7cd56..7b6f237baa 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,5 @@{+ "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.jsonindex a60e1508f0..8aebda7f54 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,5 @@{+ "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.jsonindex 2da1700f3f..9cbd8b9ef8 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,5 @@{+ "dailyNoteDateInvalid": "תאריך לא תקין או לא חד־משמעי; יש להזין תאריך מלא בתבנית YYYY-MM-DD","goToDocumentStart": "מעבר לתחילת המסמך","goToDocumentEnd": "מעבר לסוף המסמך","agentBuiltinPluginDevelopmentDescription": "תהליך העבודה הרשמי לפיתוח תוספי ממשק: לאחר הסכמתך המפורשת, מבררים דרישות חסרות, מאשרים תוכנית קצרה, מממשים בעותק מנוהל, מאמתים ואורזים; התקנה והפעלה דורשות הרשאה נפרדת",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 857dcc3a05..facef7aab0 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,5 @@{+ "dailyNoteDateInvalid": "तारीख अमान्य या अस्पष्ट है; YYYY-MM-DD प्रारूप में पूरी तारीख दर्ज करें","goToDocumentStart": "दस्तावेज़ की शुरुआत पर जाएँ","goToDocumentEnd": "दस्तावेज़ के अंत पर जाएँ","agentBuiltinPluginDevelopmentDescription": "फ़्रंटएंड प्लगइन विकास की आधिकारिक प्रक्रिया: आपकी स्पष्ट सहमति के बाद अधूरी आवश्यकताओं को स्पष्ट करना, संक्षिप्त योजना की पुष्टि करना, प्रबंधित प्रति में कार्यान्वयन करना, जाँचना और पैकेज बनाना; स्थापना और सक्रियण के लिए अलग अनुमति आवश्यक है",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 9a28bd7c58..d3706b4d63 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,5 @@{+ "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.jsonindex 524d73fafb..92164dd627 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,5 @@{+ "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.jsonindex dfae92c5e0..6656141dd6 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,5 @@{+ "dailyNoteDateInvalid": "日付が無効または曖昧です。YYYY-MM-DD 形式で完全な日付を入力してください","goToDocumentStart": "ドキュメントの先頭へ移動","goToDocumentEnd": "ドキュメントの末尾へ移動","agentBuiltinPluginDevelopmentDescription": "公式フロントエンドプラグイン開発フロー:ユーザーが明示的に選択した後、不足している要件を確認し、簡潔な計画に合意したうえで、管理対象のコピーで実装・検証・パッケージ化を行います。インストールと有効化には別途許可が必要です",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex eebcfea890..642daba584 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,5 @@{+ "dailyNoteDateInvalid": "날짜가 올바르지 않거나 모호합니다. YYYY-MM-DD 형식으로 전체 날짜를 입력하세요","goToDocumentStart": "문서 시작으로 이동","goToDocumentEnd": "문서 끝으로 이동","agentBuiltinPluginDevelopmentDescription": "공식 프런트엔드 플러그인 개발 절차: 사용자가 명시적으로 선택한 후 누락된 요구 사항을 확인하고 간단한 계획에 합의한 뒤 관리되는 사본에서 구현, 검증 및 패키징을 수행하며, 설치와 활성화에는 별도의 승인이 필요합니다",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 2cf03f1864..a8110d8287 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,5 @@{+ "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.jsonindex 4ad47b8786..7f705eda3e 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,5 @@{+ "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.jsonindex f45c9f1c0b..472cb36ce7 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,5 @@{+ "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.jsonindex 0c4d54ddb2..76bf26c893 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,5 @@{+ "dailyNoteDateInvalid": "Недопустимая или неоднозначная дата; введите полную дату в формате YYYY-MM-DD","goToDocumentStart": "Перейти к началу документа","goToDocumentEnd": "Перейти к концу документа","agentBuiltinPluginDevelopmentDescription": "Официальный процесс разработки плагинов интерфейса: после явного согласия пользователя уточняются недостающие требования, утверждается краткий план, выполняются реализация в управляемой копии, проверка и упаковка; установка и активация требуют отдельного разрешения",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 347d9dc801..117833a4e4 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,5 @@{+ "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.jsonindex 480e21a2f9..432eed9c4a 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,5 @@{+ "dailyNoteDateInvalid": "Неважећи или двосмислен датум; унесите потпун датум у формату YYYY-MM-DD","goToDocumentStart": "Иди на почетак документа","goToDocumentEnd": "Иди на крај документа","agentBuiltinPluginDevelopmentDescription": "Званични поступак развоја додатака за кориснички интерфејс: након изричите сагласности корисника разјашњавају се недостајући захтеви, потврђује кратак план и у управљаној копији спроводе израда, провера и паковање; инсталација и активирање захтевају посебно одобрење",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex ece493c8fa..abd280d771 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,5 @@{+ "dailyNoteDateInvalid": "วันที่ไม่ถูกต้องหรือกำกวม โปรดป้อนวันที่แบบเต็มในรูปแบบ YYYY-MM-DD","goToDocumentStart": "ไปยังจุดเริ่มต้นของเอกสาร","goToDocumentEnd": "ไปยังจุดสิ้นสุดของเอกสาร","agentBuiltinPluginDevelopmentDescription": "ขั้นตอนการพัฒนาปลั๊กอินส่วนหน้าทางการ: หลังจากผู้ใช้ยินยอมอย่างชัดเจน จึงชี้แจงข้อกำหนดที่ยังขาด ยืนยันแผนโดยย่อ พัฒนาในสำเนาที่จัดการให้ ตรวจสอบ และจัดแพ็กเกจ โดยการติดตั้งและเปิดใช้งานต้องได้รับอนุญาตแยกต่างหาก",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex dd07427e1a..a45bf084e7 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,5 @@{+ "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.jsonindex a3ec937385..29128ffdb2 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,5 @@{+ "dailyNoteDateInvalid": "Неприпустима або неоднозначна дата; введіть повну дату у форматі YYYY-MM-DD","goToDocumentStart": "Перейти на початок документа","goToDocumentEnd": "Перейти в кінець документа","agentBuiltinPluginDevelopmentDescription": "Офіційний процес розробки плагінів інтерфейсу: після явної згоди користувача уточнюються відсутні вимоги, затверджується стислий план, виконуються реалізація в керованій копії, перевірка та пакування; установлення й активація потребують окремого дозволу",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 67ab2387e9..11c049b191 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,5 @@{+ "dailyNoteDateInvalid": "日期无效或有歧义,请输入 YYYY-MM-DD 格式的完整日期","goToDocumentStart": "跳到文档开头","goToDocumentEnd": "跳到文档结尾","agentBuiltinPluginDevelopmentDescription": "官方前端插件开发流程:在用户明确选择后澄清缺失要求、确认简短方案、使用受管副本实现、验证和打包;安装与启用另行授权",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 057f7eb72d..314cfc9aeb 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,5 @@{+ "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.syindex bde77f5b3f..d3c55aeb28 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": "20260809232000"+ "updated": "20261008101708"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20260613180619-15jwt8e",- "updated": "20260803171606"+ "updated": "20261008101708"},"Children": [{@@ -199,6 +199,131 @@}]},+ {+ "ID": "20261008101708-b7c9jyj",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20261008101708-b7c9jyj",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Create and reference daily notes by date"+ }+ ]+ },+ {+ "ID": "20261008101708-65762qi",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-65762qi",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Type "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[today"+ },+ {+ "Type": "NodeText",+ "Data": ", "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[tomorrow"+ },+ {+ "Type": "NodeText",+ "Data": ", or "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[25 sept"+ },+ {+ "Type": "NodeText",+ "Data": " in the editor to show a daily note candidate in reference completion. Relative dates and full or abbreviated month names are recognized in the interface language and English. Complete Gregorian dates such as "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[2026-09-25"+ },+ {+ "Type": "NodeText",+ "Data": " are also supported."+ }+ ]+ },+ {+ "ID": "20261008101708-8o948mt",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-8o948mt",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Dates without a year use the current year, and candidates display the complete date. For ambiguous expressions such as "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "03/04"+ },+ {+ "Type": "NodeText",+ "Data": " or invalid dates, use "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "YYYY-MM-DD"+ },+ {+ "Type": "NodeText",+ "Data": ". Regular document search remains available."+ }+ ]+ },+ {+ "ID": "20261008101708-3n0qxms",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-3n0qxms",+ "updated": "20261008101708"+ },+ "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."+ }+ ]+ },+ {+ "ID": "20261008101708-yprxiyp",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-yprxiyp",+ "updated": "20261008101708"+ },+ "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."+ }+ ]+ },{"ID": "20260613180619-9fh070b","Type": "NodeHeading",@@ -598,4 +723,4 @@}}]-}\ No newline at end of file+}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.syindex f9178fe385..5c8e35ec70 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": "20260809232000"+ "updated": "20261008101708"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20260613180438-q02mnqc",- "updated": "20260803171606"+ "updated": "20261008101708"},"Children": [{@@ -199,6 +199,140 @@}]},+ {+ "ID": "20261008101708-5rm6q63",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20261008101708-5rm6q63",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "按日期创建和引用"+ }+ ]+ },+ {+ "ID": "20261008101708-71fpzn5",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-71fpzn5",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在编辑器中输入 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[今天"+ },+ {+ "Type": "NodeText",+ "Data": "、"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[明天"+ },+ {+ "Type": "NodeText",+ "Data": "、"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[9月25日"+ },+ {+ "Type": "NodeText",+ "Data": " 或 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[25 sept"+ },+ {+ "Type": "NodeText",+ "Data": ",可在引用补全中显示对应日期的日记候选。支持当前界面语言和英文的相对日期、月份全称及缩写,也支持 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[2026-09-25"+ },+ {+ "Type": "NodeText",+ "Data": " 这样的完整公历日期。"+ }+ ]+ },+ {+ "ID": "20261008101708-5vji0a1",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-5vji0a1",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "未填写年份时使用当前年,候选项会显示完整日期。对于 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "03/04"+ },+ {+ "Type": "NodeText",+ "Data": " 等有歧义的表达或无效日期,请改用 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "YYYY-MM-DD"+ },+ {+ "Type": "NodeText",+ "Data": " 格式。普通文档搜索仍可使用。"+ }+ ]+ },+ {+ "ID": "20261008101708-0z31c9n",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-0z31c9n",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "选中日记候选后,使用上次选择的日记笔记本;尚未选择或原笔记本不可用时,会提示选择。取消选择不会创建文档。加密笔记本内只能引用本笔记本的日记,普通笔记本不能引用加密笔记本的日记。"+ }+ ]+ },+ {+ "ID": "20261008101708-m616klc",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-m616klc",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "输入和查看候选不会创建文档。选中后会复用目标笔记本中对应日期的日记,包括已移动或重命名但保留日记日期属性的文档;不存在时才按日记设置创建并插入引用。路径模板、正文模板中的 now 和日记日期属性使用目标日期,实际创建和更新时间保持真实操作时间。"+ }+ ]+ },{"ID": "20260613180438-konhms4","Type": "NodeHeading",@@ -598,4 +732,4 @@}}]-}\ No newline at end of file+}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.syindex c2306a75f7..69a3798234 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": "20260809232000"+ "updated": "20261008101708"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20260613181022-74zgp84",- "updated": "20260803171606"+ "updated": "20261008101708"},"Children": [{@@ -199,6 +199,140 @@}]},+ {+ "ID": "20261008101708-lr0o7zn",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20261008101708-lr0o7zn",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "按日期建立和引用"+ }+ ]+ },+ {+ "ID": "20261008101708-idqliwj",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-idqliwj",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在編輯器中輸入 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[今天"+ },+ {+ "Type": "NodeText",+ "Data": "、"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[明天"+ },+ {+ "Type": "NodeText",+ "Data": "、"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[9月25日"+ },+ {+ "Type": "NodeText",+ "Data": " 或 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[25 sept"+ },+ {+ "Type": "NodeText",+ "Data": ",可在區塊引用補全中顯示對應日期的日記候選。支援目前介面語言和英文的相對日期、月份全稱及縮寫,也支援 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[2026-09-25"+ },+ {+ "Type": "NodeText",+ "Data": " 這樣的完整公曆日期。"+ }+ ]+ },+ {+ "ID": "20261008101708-wyphboq",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-wyphboq",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "未填寫年份時使用目前年份,候選項會顯示完整日期。對於 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "03/04"+ },+ {+ "Type": "NodeText",+ "Data": " 等有歧義的表達或無效日期,請改用 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "YYYY-MM-DD"+ },+ {+ "Type": "NodeText",+ "Data": " 格式。一般文件搜尋仍可使用。"+ }+ ]+ },+ {+ "ID": "20261008101708-e6z4q69",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-e6z4q69",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "選取日記候選後,使用上次選取的日記筆記本;尚未選取或原筆記本無法使用時,會提示選取。取消選取不會建立文件。加密筆記本內只能引用本筆記本的日記,一般筆記本不能引用加密筆記本的日記。"+ }+ ]+ },+ {+ "ID": "20261008101708-j20nycr",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-j20nycr",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "輸入和查看候選不會建立文件。選取後會沿用目標筆記本中對應日期的日記,包括已移動或重新命名但保留日記日期屬性的文件;不存在時才依日記設定建立並插入區塊引用。路徑範本、內容範本中的 now 和日記日期屬性使用目標日期,實際建立和更新時間保持真實操作時間。"+ }+ ]+ },{"ID": "20260613181022-txx9v8s","Type": "NodeHeading",@@ -598,4 +732,4 @@}}]-}\ No newline at end of file+}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.syindex 42d33d14e7..9b44b9bbc5 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": "20260809232000"+ "updated": "20261008101708"},"Children": [{@@ -16,7 +16,7 @@"HeadingLevel": 2,"Properties": {"id": "20260613180757-9fax3mg",- "updated": "20260803163243"+ "updated": "20261008101708"},"Children": [{@@ -200,6 +200,140 @@}]},+ {+ "ID": "20261008101708-mjx358e",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20261008101708-mjx358e",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "日付による作成と参照"+ }+ ]+ },+ {+ "ID": "20261008101708-54h6a3e",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-54h6a3e",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "エディターで "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[今日"+ },+ {+ "Type": "NodeText",+ "Data": "、"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[明日"+ },+ {+ "Type": "NodeText",+ "Data": "、"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[9月25日"+ },+ {+ "Type": "NodeText",+ "Data": "、または "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[25 sept"+ },+ {+ "Type": "NodeText",+ "Data": " と入力すると、参照候補にその日付のデイリーノートが表示されます。インターフェース言語と英語の相対日付、月の正式名称と略称に対応しています。"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "[[2026-09-25"+ },+ {+ "Type": "NodeText",+ "Data": " のような完全なグレゴリオ暦の日付も使用できます。"+ }+ ]+ },+ {+ "ID": "20261008101708-x9aa3xt",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-x9aa3xt",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "年を省略した日付には今年を使用し、候補には完全な日付を表示します。"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "03/04"+ },+ {+ "Type": "NodeText",+ "Data": " などの曖昧な表現や無効な日付は、"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "YYYY-MM-DD"+ },+ {+ "Type": "NodeText",+ "Data": " 形式で入力してください。通常のドキュメント検索も引き続き使用できます。"+ }+ ]+ },+ {+ "ID": "20261008101708-712s18k",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-712s18k",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "候補を選択すると、前回選択したデイリーノート用ノートブックを使用します。未選択の場合や以前のノートブックが利用できない場合は、選択を求められます。キャンセルしてもドキュメントは作成されません。暗号化ノートブックでは同じノートブックの日記のみ参照でき、通常のノートブックから暗号化ノートブックの日記は参照できません。"+ }+ ]+ },+ {+ "ID": "20261008101708-pvky8qm",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261008101708-pvky8qm",+ "updated": "20261008101708"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "入力や候補の表示だけではドキュメントを作成しません。候補を選択すると、対象ノートブックの対応する日付のデイリーノートを再利用します。日記の日付属性が残っていれば、移動や名前変更後のドキュメントも再利用します。存在しない場合のみ、日記の設定に従って作成して参照を挿入します。パステンプレート、本文テンプレート内の now、日記の日付属性には対象日付を使用し、実際の作成・更新時刻は操作時刻を保持します。"+ }+ ]+ },{"ID": "20260613180757-yov9hyx","Type": "NodeHeading",@@ -599,4 +733,4 @@}}]-}\ No newline at end of file+}diff --git a/app/src/protyle/hint/dailyNote.test.ts b/app/src/protyle/hint/dailyNote.test.tsnew file mode 100644index 0000000000..64e121c005--- /dev/null+++ b/app/src/protyle/hint/dailyNote.test.ts@@ -0,0 +1,96 @@+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";+import {canReferenceDailyNoteNotebook, getLastDailyNoteNotebookId} from "../../util/dailyNote";+import {parseDailyNoteDate} from "../../util/dailyNoteDate";+import {escapeHtml} from "../../util/escape";++const code = transpileModule(readFileSync(join(__dirname, "dailyNote.ts"), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS},+}).outputText;++const createContext = () => {+ const calls: {path: string, body: {notebook?: string, date?: string, id?: string}}[] = [];+ let choose: ((notebook: string) => void) | undefined;+ let fail = false;+ 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"},+ }};+ const mocks: Record<string, unknown> = {+ "../../constants": {Constants: {LOCAL_DAILYNOTEID: "last", SIYUAN_APPID: "app"}},+ "../../util/dailyNote": {canReferenceDailyNoteNotebook, getLastDailyNoteNotebookId},+ "../../util/dailyNoteDate": {parseDailyNoteDate},+ "../../util/escape": {escapeHtml},+ "../../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},+ callback: (response: unknown) => void) => {+ calls.push({path, body});+ callback(fail ? {code: -1} : path.endsWith("getDocInfo") ?+ {code: 0, data: {name: "Renamed daily note", ial: {title: "Date"}}} : {code: 0, data: {id: "existing"}});+ }},+ };+ 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,+ 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; }};+};++const protyle = {notebookId: "normal", hint: {splitChar: "[["}};++test("daily note candidates show dates and notebook names without creating documents", () => {+ const context = createContext();+ context.storage.last = "daily";+ const hint = context.functions.getDailyNoteHint("2026-09-25", protyle);+ assert.equal(hint?.value, "daily-note:2026-09-25:daily");+ assert.ok(hint?.html.includes("Daily <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);+ context.appWindow.siyuan.config.readonly = true;+ assert.equal(context.functions.getDailyNoteHint("today", protyle), undefined);+});++test("selecting a date reuses its previewed notebook and inserts the real document title", () => {+ const context = createContext();+ context.storage.last = "normal";+ let inserted = "";+ context.functions.createDailyNoteReference(protyle, "2026-09-25", "daily", (id, title) => { inserted = `${id}:${title}`; });+ assert.equal(context.calls[0].body.notebook, "daily");+ assert.equal(context.calls[0].body.date, "2026-09-25");+ assert.equal(inserted, "existing:Renamed daily note");+ context.setFail();+ 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", () => {+ const context = createContext();+ context.functions.createDailyNoteReference(protyle, "2026-09-25", "", () => {});+ assert.equal(context.calls.length, 0);+ assert.deepEqual(context.selected, ["daily", "normal"]);+ context.choose("encrypted");+ assert.equal(context.calls.length, 0);+ context.choose("daily");+ assert.equal(context.calls[0].body.notebook, "daily");+ const encrypted = createContext();+ encrypted.storage.last = "normal";+ const source = {...protyle, notebookId: "encrypted"};+ assert.ok(encrypted.functions.getDailyNoteHint("today", source)?.value.endsWith(":"));+ encrypted.functions.createDailyNoteReference(source, "2026-09-25", "normal", () => {});+ assert.deepEqual(encrypted.selected, ["encrypted"]);+});diff --git a/app/src/protyle/hint/dailyNote.ts b/app/src/protyle/hint/dailyNote.tsnew file mode 100644index 0000000000..0be0551199--- /dev/null+++ b/app/src/protyle/hint/dailyNote.ts@@ -0,0 +1,59 @@+import {Constants} from "../../constants";+import {canReferenceDailyNoteNotebook, getLastDailyNoteNotebookId} from "../../util/dailyNote";+import {parseDailyNoteDate} from "../../util/dailyNoteDate";+import {escapeHtml} from "../../util/escape";+import {isEncryptedBox} from "../../util/pathName";+import {selectDailyNoteNotebook} from "../../util/mount";+import {fetchPost} from "../../util/fetch";++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 => {+ if (window.siyuan.config.readonly || !["[[", "【【"].includes(protyle.hint.splitChar)) {+ return undefined;+ }+ 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)};+ }+ const notebooks = getNotebooks(protyle.notebookId);+ if (notebooks.length === 0) {+ return undefined;+ }+ 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>`,+ };+};++// 用户选中候选后才创建日记;候选生成不会改动工作区。+export const createDailyNoteReference = (protyle: IProtyle, date: string, notebookID: string,+ onCreated: (id: string, title: string) => void) => {+ const notebooks = getNotebooks(protyle.notebookId);+ const create = (notebook: string) => {+ if (!getNotebooks(protyle.notebookId).some(item => item.id === notebook)) {+ return;+ }+ fetchPost("/api/filetree/createDailyNote", {notebook, date, app: Constants.SIYUAN_APPID}, response => {+ if (response.code === 0 && response.data?.id) {+ const id = response.data.id;+ fetchPost("/api/block/getDocInfo", {id, notebook}, info => {+ if (info.code === 0 && info.data) {+ onCreated(id, info.data.name || info.data.ial?.title || date);+ }+ });+ }+ });+ };+ if (notebookID && notebooks.some(item => item.id === notebookID)) {+ create(notebookID);+ } else if (notebooks.length > 0) {+ selectDailyNoteNotebook(notebooks, create);+ }+};diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.tsindex 8c68849812..9ec13a1039 100644--- a/app/src/protyle/hint/extend.ts+++ b/app/src/protyle/hint/extend.ts@@ -56,6 +56,7 @@ import {} from "../wysiwyg/blockSelection";import {countBlockWord} from "../../layout/status";import {genTemplateDocTreePlanHTML} from "../../template/docTree";+import {getDailyNoteHint} from "./dailyNote";const slashBuiltinStyleIDs: Partial<Record<string, TBuiltinInlineStyleID>> = {infoStyle: "info",@@ -611,6 +612,11 @@ export const hintRef = (key: string, protyle: IProtyle, source: THintSource): IH}const dataList: IHintData[] = [];let createItemCount = 0;+ const dailyNote = source === "hint" ? getDailyNoteHint(key, protyle) : undefined;+ if (dailyNote) {+ dataList.push(dailyNote);+ createItemCount++;+ }if (response.data.newDoc) {const newFileName = Lute.UnEscapeHTMLStr(replaceFileName(response.data.k));if (!hideConfiguredCreate) {diff --git a/app/src/protyle/hint/fillCommand.test.ts b/app/src/protyle/hint/fillCommand.test.tsindex 229a9a3026..61c759be99 100644--- a/app/src/protyle/hint/fillCommand.test.ts+++ b/app/src/protyle/hint/fillCommand.test.ts@@ -16,6 +16,48 @@ 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", () => {+ for (const scenario of ["valid", "edited", "removed"]) {+ let text = "[[2026-09-25";+ let inserted = false;+ let complete: ((id: string, title: string) => void) | undefined;+ const block = {outerHTML: "paragraph", isConnected: true, getAttribute: () => "paragraph"};+ const range = {startContainer: block, setStart() {}, setEnd() {}, collapse() {},+ toString: () => text, cloneRange: () => range};+ const protyle = {toolbar: {range, setInlineMark: (_protyle: unknown, type: string, source: string,+ options: {color: string}): HTMLElement[] => {+ assert.equal(type, "block-ref");+ assert.equal(source, "range");+ assert.ok(options.color.includes("existing"));+ assert.ok(options.color.includes("Daily title"));+ inserted = true;+ return [];+ }}, wysiwyg: {element: {}}};+ const hint = runInNewContext(code, {+ Constants: {BLOCK_HINT_KEYS: ["[["], ZWSP: "\u200b"},+ hideElements() {}, hasClosestBlock: () => block, focusByRange() {},+ shouldCaptureHintUndoFocus, getUndoFocusContext: () => ({}),+ getBlockRefAnchorText: (title: string) => title,+ createDailyNoteReference: (_protyle: unknown, date: string, notebook: string,+ callback: (id: string, title: string) => void) => {+ assert.equal(date, "2026-09-25");+ assert.equal(notebook, "daily");+ complete = callback;+ },+ });+ Object.assign(hint, {source: "hint", splitChar: "[[", lastIndex: 0});+ hint.fill("daily-note:2026-09-25:daily", protyle, false);+ assert.equal(inserted, false);+ if (scenario === "edited") {+ text = "edited input";+ } else if (scenario === "removed") {+ block.isConnected = false;+ }+ complete?.("existing", "Daily title");+ assert.equal(inserted, scenario === "valid");+ }+});+test("mobile reference command inserts at the saved caret and resets stale hint context", () => {for (const [text, offset] of [["", 0], ["text", 0], ["text", 2], ["text", 4]] as const) {for (const source of ["av", "search", "hint"]) {diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex 73cfe4036b..3990917f42 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -20,6 +20,7 @@ import {getUndoFocusContext,} from "../util/selection";import {genHintItemHTML, hintEmbed, hintRef, hintSlash, hintTag} from "./extend";+import {createDailyNoteReference} from "./dailyNote";import {getBlockRefAnchorText,getDocCreateTemplatePath,@@ -946,6 +947,27 @@ ${genHintItemHTML(item)}range.setStart(range.startContainer, this.lastIndex);focusByRange(range);}+ 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();+ 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);+ }+ });+ return;+ }if (Constants.BLOCK_HINT_KEYS.includes(this.splitChar) && value.startsWith("((newSubDoc ") &&value.endsWith(`${Lute.Caret}'))`)) {const prefix = "((newSubDoc ";diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 9be9afcf6d..e43ad95ba7 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -1030,7 +1030,7 @@ export type FileTreeCreateRequestInput = { "docCreateTemplatePath"?: string | nuexport type FileTreeCreateSavePathData = { "box": string; "docCreateTemplatePath": string; "path": string; };-export type FileTreeDailyNoteRequestInput = { "app"?: string | null; "notebook": string; };+export type FileTreeDailyNoteRequestInput = { "app"?: string | null; "date"?: string | null; "notebook": string; };export type FileTreeDocFile = { "children"?: Array<FileTreeDocFile | null>; "id": string; };diff --git a/app/src/util/dailyNote.ts b/app/src/util/dailyNote.tsindex 767d32f2cb..42832815c3 100644--- a/app/src/util/dailyNote.ts+++ b/app/src/util/dailyNote.ts@@ -21,3 +21,8 @@ export const getLastDailyNoteNotebookId = (}return notebooks.some(item => item.id === storedNotebookId && !item.closed) ? storedNotebookId : undefined;};++// 加密文档只允许引用同一笔记本,普通文档不跨入加密笔记本。+export const canReferenceDailyNoteNotebook = (sourceID: string, targetID: string,+ sourceEncrypted: boolean, targetEncrypted: boolean) =>+ sourceEncrypted ? sourceID === targetID : !targetEncrypted;diff --git a/app/src/util/dailyNoteDate.test.ts b/app/src/util/dailyNoteDate.test.tsnew file mode 100644index 0000000000..454b102d7e--- /dev/null+++ b/app/src/util/dailyNoteDate.test.ts@@ -0,0 +1,67 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {readdirSync} from "node:fs";+import {join} from "node:path";+import {parseDailyNoteDate} from "./dailyNoteDate";+import {canReferenceDailyNoteNotebook} from "./dailyNote";++const now = new Date(2026, 9, 8, 12);++test("daily note dates recognize current-language and English expressions", () => {+ for (const [locale, input, date] of [+ ["en", "today", "2026-10-08"], ["zh-CN", "明天", "2026-10-09"],+ ["zh-TW", "昨天", "2026-10-07"], ["ja", "今日", "2026-10-08"],+ ["fr", "aujourd’hui", "2026-10-08"], ["de", "morgen", "2026-10-09"],+ ["es", "mañana", "2026-10-09"], ["fr", "TODAY", "2026-10-08"],+ ["zh-CN", "25 sept", "2026-09-25"], ["en", "September 25, 2027", "2027-09-25"],+ ["en", "7th October 2026", "2026-10-07"], ["fr", "25 septembre", "2026-09-25"],+ ["de", "25. September", "2026-09-25"], ["es", "25 de septiembre", "2026-09-25"],+ ["ru", "25 сентября", "2026-09-25"], ["zh-CN", "9月25日", "2026-09-25"],+ ["ja", "2027年9月25日", "2027-09-25"], ["ko", "9월25일", "2026-09-25"],+ ["en", "2024-02-29", "2024-02-29"], ["en", "2026-09-25", "2026-09-25"],+ ]) {+ assert.deepEqual(parseDailyNoteDate(input, locale, now), {date}, `${locale}: ${input}`);+ }+});++test("all bundled languages recognize their relative dates and Gregorian month forms", () => {+ const languages = readdirSync(join(__dirname, "../../appearance/langs")).filter(file => file.endsWith(".json"));+ assert.equal(languages.length, 22);+ for (const filename of languages) {+ const locale = filename.slice(0, -5);+ const relative = new Intl.RelativeTimeFormat(locale, {numeric: "auto"});+ for (const [offset, expected] of [[-1, "2026-10-07"], [0, "2026-10-08"], [1, "2026-10-09"]] as const) {+ const word = relative.format(offset, "day");+ const ambiguous = offset !== 0 && word === relative.format(-offset, "day");+ assert.deepEqual(parseDailyNoteDate(word, locale, now), ambiguous ? {error: true} : {date: expected}, locale);+ const numeric = new Intl.RelativeTimeFormat(locale, {numeric: "always"});+ assert.deepEqual(parseDailyNoteDate(numeric.format(offset, "day"), locale, now), {date: expected}, locale);+ }+ for (const month of ["long", "short"] as const) {+ const formatter = new Intl.DateTimeFormat(locale, {+ calendar: "gregory", numberingSystem: "latn", month, day: "numeric",+ });+ const input = formatter.format(new Date(2026, 8, 25));+ const numericMonth = /^\d+$/.test(formatter.formatToParts(new Date(2026, 8, 25)).find(part => part.type === "month")?.value || "") && !/[月월]/.test(input);+ assert.deepEqual(parseDailyNoteDate(input, locale, now), numericMonth ? {error: true} : {date: "2026-09-25"}, `${locale}: ${input}`);+ }+ }+});++test("date parsing rejects invalid and ambiguous dates without hijacking document names", () => {+ for (const input of ["03/04", "25/09/2026", "2026-02-29", "2026-13-01", "31 sept", "9月31日"]) {+ assert.deepEqual(parseDailyNoteDate(input, "zh-CN", now), {error: true}, input);+ }+ for (const input of ["", "my today notes", "25 septembernotes", "project May", "yesterday report", "25 octobre"]) {+ assert.equal(parseDailyNoteDate(input, "en", now), undefined, input);+ }+ assert.deepEqual(parseDailyNoteDate("tomorrow", "en", new Date(2026, 11, 31, 23, 59)), {date: "2027-01-01"});+});++test("daily note references preserve encrypted notebook boundaries", () => {+ assert.equal(canReferenceDailyNoteNotebook("a", "a", true, true), true);+ assert.equal(canReferenceDailyNoteNotebook("a", "b", true, true), false);+ assert.equal(canReferenceDailyNoteNotebook("a", "b", true, false), false);+ assert.equal(canReferenceDailyNoteNotebook("a", "b", false, true), false);+ assert.equal(canReferenceDailyNoteNotebook("a", "b", false, false), true);+});diff --git a/app/src/util/dailyNoteDate.ts b/app/src/util/dailyNoteDate.tsnew file mode 100644index 0000000000..d4c627e75a--- /dev/null+++ b/app/src/util/dailyNoteDate.ts@@ -0,0 +1,140 @@+export type TDailyNoteDateResult = {date: string} | {error: true};++const normalize = (value: string) => value.normalize("NFKC").toLowerCase()+ .replace(/[\u200e\u200f\u061c]/g, "").replace(/[’‘]/g, "'").trim();++const formatDate = (date: Date) => `${date.getFullYear().toString().padStart(4, "0")}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;++const calendarDate = (year: number, month: number, day: number): TDailyNoteDateResult => {+ const date = new Date(0);+ date.setFullYear(year, month - 1, day);+ date.setHours(12, 0, 0, 0);+ if (year < 1 || year > 9999 || date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {+ return {error: true};+ }+ return {date: formatDate(date)};+};++type TDateVocabulary = {relative: Map<string, number | null>, months: Map<string, number>};+const vocabularies = new Map<string, TDateVocabulary>();++// 公历月份同时收集独立形式和日期中的形式,兼容俄语等语言的月份变格。+const getVocabulary = (locale: string) => {+ let vocabulary = vocabularies.get(locale);+ if (vocabulary) {+ return vocabulary;+ }+ const relative = new Map<string, number | null>();+ for (const numeric of ["auto", "always"] as const) {+ const relativeFormat = new Intl.RelativeTimeFormat(locale, {numeric});+ [-1, 0, 1].forEach(offset => {+ const word = normalize(relativeFormat.format(offset, "day"));+ relative.set(word, relative.has(word) && relative.get(word) !== offset ? null : offset);+ });+ }+ if (locale === "hi") {+ relative.set("बीता कल", -1);+ relative.set("आने वाला कल", 1);+ }+ const months = new Map<string, number>();+ for (const width of ["long", "short"] as const) {+ for (const withDay of [false, true]) {+ const formatter = new Intl.DateTimeFormat(locale, {+ calendar: "gregory", numberingSystem: "latn", month: width,+ ...(withDay ? {day: "numeric"} : {}),+ });+ for (let month = 0; month < 12; month++) {+ const parts = formatter.formatToParts(new Date(2026, month, 15));+ const monthIndex = parts.findIndex(item => item.type === "month");+ const part = parts[monthIndex];+ if (part && !/^\d+$/.test(part.value)) {+ const name = normalize(part.value).replace(/\.$/, "");+ months.set(name, month + 1);+ const prefix = parts[monthIndex - 1];+ if (prefix?.type === "literal" && new RegExp("^\\s*\\p{L}+$", "u").test(prefix.value)) {+ months.set(normalize(prefix.value) + name, month + 1);+ }+ }+ }+ }+ }+ if (locale === "en") {+ months.set("sept", 9);+ }+ vocabulary = {relative, months};+ vocabularies.set(locale, vocabulary);+ return vocabulary;+};++const latinDigits = (text: string, locale: string) => {+ const formatter = new Intl.NumberFormat(locale, {useGrouping: false});+ for (let digit = 0; digit <= 9; digit++) {+ text = text.split(formatter.format(digit)).join(String(digit));+ }+ return text;+};++// 日期候选仅解析输入,不使用 Date.parse 猜测日期,也不会创建文档。+export const parseDailyNoteDate = (input: string, locale: string, now = new Date()): TDailyNoteDateResult | undefined => {+ let text = normalize(input);+ if (!text || text.length > 80) {+ return undefined;+ }+ const locales = [...new Set([locale, "en"])];+ for (const language of locales) {+ const vocabulary = getVocabulary(language);+ const offset = vocabulary.relative.get(text);+ if (offset === null) {+ return {error: true};+ }+ if (offset !== undefined) {+ const date = new Date(now);+ date.setDate(date.getDate() + offset);+ return {date: formatDate(date)};+ }+ text = latinDigits(text, language);+ }+ const fullDate = text.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/);+ if (fullDate) {+ return calendarDate(Number(fullDate[1]), Number(fullDate[2]), Number(fullDate[3]));+ }+ const eastAsianDate = text.match(/^(?:(\d{4})[年년]\s*)?(\d{1,2})[月월]\s*(\d{1,2})[日일]?$/);+ if (eastAsianDate) {+ return calendarDate(Number(eastAsianDate[1] || now.getFullYear()), Number(eastAsianDate[2]), Number(eastAsianDate[3]));+ }+ // 数字月日缺少年份或日期顺序不明确时,要求输入明确日期。+ if (/^\d{1,2}\s*[-/.]\s*\d{1,2}(?:\s*[-/.]\s*\d{2,4})?\.?$/.test(text)) {+ return {error: true};+ }+ for (const language of locales) {+ const months = [...getVocabulary(language).months.entries()].sort((a, b) => b[0].length - a[0].length);+ for (const [name, month] of months) {+ const index = text.indexOf(name);+ if (index < 0) {+ continue;+ }+ const before = text.slice(0, index);+ const after = text.slice(index + name.length);+ // 月份必须是完整词,避免将普通文档名中的英文片段解释为日期。+ if (new RegExp("\\p{L}$", "u").test(before) || new RegExp("^\\p{L}", "u").test(after)) {+ continue;+ }+ const remainder = `${before} ${after}`.replace(/\b(\d{1,2})(?:st|nd|rd|th)\b/g, "$1")+ .replace(/\b(?:de|del|of)\b/g, " ").replace(/[年日년일]/g, " ")+ .replace(/[\s.,/-]+/g, " ").trim();+ if (!/^\d{1,4}(?: \d{1,4})?$/.test(remainder)) {+ continue;+ }+ const numbers = remainder.split(" ").map(Number);+ if (numbers.length === 1) {+ return calendarDate(now.getFullYear(), month, numbers[0]);+ }+ const yearIndex = remainder.split(" ").findIndex(number => number.length === 4);+ if (yearIndex < 0) {+ return {error: true};+ }+ return calendarDate(numbers[yearIndex], month, numbers[1 - yearIndex]);+ }+ }+ return undefined;+};diff --git a/app/src/util/mount.ts b/app/src/util/mount.tsindex 8d05bb52a5..48370295a7 100644--- a/app/src/util/mount.ts+++ b/app/src/util/mount.ts@@ -66,34 +66,45 @@ const openDailyNote = (app: App, useLastNotebook: boolean) => {if (lastNotebookId && useLastNotebook) {fetchNewDailyNote(app, lastNotebookId);} else {- const optionsHTML = genNotebookOptionsHTML(window.siyuan.notebooks);- const dialog = new Dialog({- positionId: Constants.DIALOG_DIALYNOTE,- title: window.siyuan.languages.plsChoose,- content: `<div class="b3-dialog__content">+ selectDailyNoteNotebook(window.siyuan.notebooks, notebook => fetchNewDailyNote(app, notebook));+ }+};++export const selectDailyNoteNotebook = (notebooks: readonly {id: string, name: string, closed: boolean}[],+ callback: (notebook: string) => void) => {+ const optionsHTML = genNotebookOptionsHTML(notebooks);+ const dialog = new Dialog({+ positionId: Constants.DIALOG_DIALYNOTE,+ title: window.siyuan.languages.plsChoose,+ content: `<div class="b3-dialog__content"><select class="b3-select fn__block">${optionsHTML}</select></div><div class="b3-dialog__action"><button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div><button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button></div>`,- width: isMobile() ? "92vw" : "520px",- });- dialog.element.setAttribute("data-key", Constants.DIALOG_DIALYNOTE);- const btnsElement = dialog.element.querySelectorAll(".b3-button");- const selectElement = dialog.element.querySelector(".b3-select") as HTMLSelectElement;+ width: isMobile() ? "92vw" : "520px",+ });+ dialog.element.setAttribute("data-key", Constants.DIALOG_DIALYNOTE);+ const btnsElement = dialog.element.querySelectorAll(".b3-button");+ const selectElement = dialog.element.querySelector(".b3-select") as HTMLSelectElement;+ const localNotebookId = getLastDailyNoteNotebookId(notebooks, window.siyuan.storage[Constants.LOCAL_DAILYNOTEID]);+ if (localNotebookId) {selectElement.value = localNotebookId;- btnsElement[0].addEventListener("click", () => {- dialog.destroy();- });- btnsElement[1].addEventListener("click", () => {- const notebook = selectElement.value;- window.siyuan.storage[Constants.LOCAL_DAILYNOTEID] = notebook;- setStorageVal(Constants.LOCAL_DAILYNOTEID, window.siyuan.storage[Constants.LOCAL_DAILYNOTEID]);- fetchNewDailyNote(app, notebook);- dialog.destroy();- });}+ btnsElement[0].addEventListener("click", () => {+ dialog.destroy();+ });+ btnsElement[1].addEventListener("click", () => {+ const notebook = selectElement.value;+ if (!notebooks.some(item => item.id === notebook && !item.closed)) {+ return;+ }+ window.siyuan.storage[Constants.LOCAL_DAILYNOTEID] = notebook;+ setStorageVal(Constants.LOCAL_DAILYNOTEID, notebook);+ callback(notebook);+ dialog.destroy();+ });};export const newDailyNote = (app: App) => {diff --git a/kernel/api/box_lease_test.go b/kernel/api/box_lease_test.goindex 4a6aec24a3..e28d67d2e5 100644--- a/kernel/api/box_lease_test.go+++ b/kernel/api/box_lease_test.go@@ -81,6 +81,10 @@ func TestContractDocInfoNotebookResponseLease(t *testing.T) {runNotebookResponseLease(t, true, false)}+func TestContractDailyNoteNotebookResponseLease(t *testing.T) {+ runNotebookResponseLease(t, true, false)+}+func TestContractGetDocNotebookResponseLease(t *testing.T) {runNotebookResponseLease(t, true, false)}@@ -193,6 +197,20 @@ 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" {+ content, err := os.ReadFile(filepath.Join("..", "..", "app", "appearance", "langs", "en.json"))+ if err != nil {+ t.Fatal(err)+ }+ var language struct {+ Time map[string]any `json:"_time"`+ }+ if err := json.Unmarshal(content, &language); err != nil {+ t.Fatal(err)+ }+ model.Conf.Lang = "en"+ util.TimeLangs = map[string]map[string]any{"en": language.Time}+ }*model.Conf.FileTree.BoxDocEnabled = truesql.InitDatabase(true)sql.InitHistoryDatabase(true)@@ -227,6 +245,11 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {t.Fatal(err)}treenode.UpsertBlockTree(tree)+ if t.Name() == "TestContractDailyNoteNotebookResponseLease" {+ if _, err := model.Mount(boxID); err != nil {+ t.Fatal(err)+ }+ }}gin.SetMode(gin.TestMode)engine := gin.New()@@ -236,6 +259,7 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {engine.POST("/api/block/getRefIDs", getRefIDs)engine.POST("/api/block/checkBlockRef", checkBlockRef)engine.POST("/api/block/getDocInfo", getDocInfo)+ engine.POST("/api/filetree/createDailyNote", createDailyNote)engine.POST("/api/filetree/getDoc", getDoc)engine.POST("/api/block/getTreeStat", getTreeStat)engine.POST("/api/block/getBlockBreadcrumb", getBlockBreadcrumb)@@ -290,6 +314,9 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {args["scope"] = "notebook"case "TestContractDocInfoNotebookResponseLease":endpoint, typedQuery = "/api/block/getDocInfo", true+ case "TestContractDailyNoteNotebookResponseLease":+ endpoint, typedQuery = "/api/filetree/createDailyNote", true+ args["date"] = "2024-02-29"case "TestContractGetDocNotebookResponseLease":endpoint, typedQuery = "/api/filetree/getDoc", truecase "TestContractTreeStatNotebookResponseLease":@@ -403,6 +430,17 @@ 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" {+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, endpoint, strings.NewReader(string(requestBody))))+ requireAPIContract(t, http.MethodPost, endpoint, recorder)+ var response struct {+ Code int `json:"code"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != -1 {+ t.Fatalf("locked notebook daily note creation was admitted: %s, %v", recorder.Body.String(), err)+ }+ }if t.Name() == "TestGetBlockInfoNotebookResponseLease" {for _, explicit := range []bool{false, true} {args := map[string]any{"id": boxIDs[0]}diff --git a/kernel/api/contract_filetree_test.go b/kernel/api/contract_filetree_test.goindex d6a1f306d6..f800d57999 100644--- a/kernel/api/contract_filetree_test.go+++ b/kernel/api/contract_filetree_test.go@@ -73,6 +73,42 @@ func TestAPIContractFileTreeMissingDocuments(t *testing.T) {}}+func TestAPIContractFileTreeDailyNoteDate(t *testing.T) {+ previousConf := model.Conf+ model.Conf = model.NewAppConf()+ t.Cleanup(func() { model.Conf = previousConf })+ engine := gin.New()+ const path = "/api/filetree/createDailyNote"+ engine.POST(path, createDailyNote)+ for _, entry := range []struct {+ body string+ code int+ }{+ {`{"notebook":"missing"}`, 1},+ {`{"notebook":"missing","date":null}`, 1},+ {`{"notebook":"missing","date":""}`, 1},+ {`{"notebook":"missing","date":"2024-02-29"}`, 1},+ {`{"notebook":"missing","date":"2026-02-29"}`, -1},+ {`{"notebook":"missing","date":"2026-9-25"}`, -1},+ {`{"notebook":"missing","date":"0000-01-01"}`, -1},+ {`{"notebook":"missing","date":"03/04"}`, -1},+ {`{"notebook":"missing","date":false}`, -1},+ } {+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", path, strings.NewReader(entry.body)))+ requireAPIContract(t, "POST", path, recorder)+ var response struct {+ Code int `json:"code"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if response.Code != entry.code {+ t.Fatalf("unexpected daily note response for %s: %s", entry.body, recorder.Body.String())+ }+ }+}+func TestAPIContractFileTreePayloadConversions(t *testing.T) {compare := func(before, after []byte) {t.Helper()diff --git a/kernel/api/filetree.go b/kernel/api/filetree.goindex 4ca10dcb90..a669788cfb 100644--- a/kernel/api/filetree.go+++ b/kernel/api/filetree.go@@ -27,6 +27,7 @@ import ("regexp""strconv""strings"+ "time""unicode/utf8""github.com/88250/gulu"@@ -764,7 +765,24 @@ func createDailyNoteContract(c *gin.Context, request apicontract.FileTreeDailyNoret := gulu.Ret.NewResult()notebook := request.Notebook- p, existed, err := model.CreateDailyNote(notebook)+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {+ return apicontract.Failure[apicontract.FileTreeCreateData](-1, model.Conf.Language(314))+ }+ var p string+ var existed bool+ var err error+ 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)+ }+ if err == nil {+ p, existed, err = model.CreateDailyNoteAt(notebook, date)+ }+ }if err != nil {if errors.Is(err, model.ErrBoxNotFound) {ret.Code = 1diff --git a/kernel/apicontract/filetree_input.go b/kernel/apicontract/filetree_input.goindex 476de5d4fa..132586f5db 100644--- a/kernel/apicontract/filetree_input.go+++ b/kernel/apicontract/filetree_input.go@@ -193,6 +193,13 @@ func init() {}value, err := fileTreeBind[FileTreeNotebookRequest](r.fields)r.Notebook = value.Notebook+ if err != nil {+ return r, err+ }+ date, err := fileTreeBind[struct {+ Date string `json:"date" api:"optional,nullable"`+ }](r.fields)+ r.Date = date.Datereturn r, err}ListDocTree.decodeRequest = func(reader io.Reader) (r FileTreePathRequest, err error) {diff --git a/kernel/apicontract/filetree_remaining.go b/kernel/apicontract/filetree_remaining.goindex 5bd5bbb698..3b41a3f412 100644--- a/kernel/apicontract/filetree_remaining.go+++ b/kernel/apicontract/filetree_remaining.go@@ -85,7 +85,12 @@ type FileTreeCreateRequest struct {type FileTreeDailyNoteRequest struct {Notebook string `json:"notebook"`App string `json:"app" api:"optional,nullable"`- fields fileTreeFields+ // Date 为本地公历日期 YYYY-MM-DD;省略、空串或 null 时使用当天。+ // 指定日期时复用同笔记本的日记日期属性,路径和正文模板中的 now 使用目标日期。+ // 日期无效返回 -1;多个匹配优先选择模板路径对应的文档,否则按文档 ID 升序选择。+ // 返回文档 ID,已有文档不重新应用正文模板;加密笔记本的响应保留解锁租约。+ Date string `json:"date" api:"optional,nullable"`+ fields fileTreeFields}type FileTreeCreateMarkdownRequest struct {FileTreePathRequestdiff --git a/kernel/apicontract/filetree_test.go b/kernel/apicontract/filetree_test.goindex fc145c5778..359b94557f 100644--- a/kernel/apicontract/filetree_test.go+++ b/kernel/apicontract/filetree_test.go@@ -125,6 +125,27 @@ func TestFileTreeHintAndDailyNoteConditions(t *testing.T) {}}+func TestDailyNoteDateContract(t *testing.T) {+ for _, body := range []string{`{"notebook":"box"}`, `{"notebook":"box","date":null}`, `{"notebook":"box","date":""}`} {+ request, err := CreateDailyNote.Decode(strings.NewReader(body))+ if err != nil || request.Date != "" {+ t.Fatalf("default date changed: %#v %v", request, err)+ }+ }+ request, err := CreateDailyNote.Decode(strings.NewReader(`{"notebook":"box","date":"2026-09-25","app":false}`))+ if err != nil || request.Date != "2026-09-25" {+ t.Fatalf("explicit date not decoded: %#v %v", request, err)+ }+ if _, err := request.AppID(); err == nil {+ t.Fatal("conditional app decoding changed")+ }+ for _, body := range []string{`{"notebook":"box","date":false}`, `{"notebook":"box","date":20260925}`} {+ if _, err := CreateDailyNote.Decode(strings.NewReader(body)); err == nil {+ t.Fatalf("non-string date accepted: %s", body)+ }+ }+}+func TestFileTreeSortModeNullableAndInteger(t *testing.T) {for _, entry := range []struct {body stringdiff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex cdb7dddc04..e8641a2c2e 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -24629,6 +24629,16 @@}]},+ "date": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },"notebook": {"type": "string"}diff --git a/kernel/model/file.go b/kernel/model/file.goindex 4b7559d7ca..c5c03df301 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -1443,6 +1443,15 @@ const ()func CreateDailyNote(boxID string) (p string, existed bool, err error) {+ return createDailyNoteAt(boxID, time.Now(), false)+}++// CreateDailyNoteAt 按指定日期创建日记,复用日期属性指向的现有文档。+func CreateDailyNoteAt(boxID string, date time.Time) (p string, existed bool, err error) {+ return createDailyNoteAt(boxID, date, true)+}++func createDailyNoteAt(boxID string, now time.Time, findByDate bool) (p string, existed bool, err error) {createDocLock.Lock()defer createDocLock.Unlock()@@ -1458,7 +1467,7 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) {return}- hPath, err := RenderGoTemplateInBox(boxConf.DailyNoteSavePath, box.ID)+ hPath, err := RenderGoTemplateAtInBox(boxConf.DailyNoteSavePath, now, box.ID)if err != nil {return}@@ -1467,6 +1476,34 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) {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 {existed = truep = existRoot.Path@@ -1474,10 +1511,10 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) {tree, loadErr := LoadTreeByBlockID(existRoot.RootID)if nil != loadErr {logging.LogWarnf("load tree by block id [%s] failed: %v", existRoot.RootID, loadErr)+ err = loadErrreturn}p = tree.Path- date := time.Now().Format("20060102")if tree.Root.IALAttr(DailyNoteAttrPrefix+date) == "" {tree.Root.SetIALAttr(DailyNoteAttrPrefix+date, date)if err = indexWriteTreeUpsertQueue(tree); err != nil {@@ -1494,7 +1531,7 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) {if "" != boxConf.DailyNoteTemplatePath {sql.FlushQueue()- if renderErr := applyDocContentTemplate(boxConf.DailyNoteTemplatePath, id); nil != renderErr {+ if renderErr := applyDocContentTemplateAt(boxConf.DailyNoteTemplatePath, id, &now); nil != renderErr {logging.LogWarnf("render daily note template [%s] failed: %s", boxConf.DailyNoteTemplatePath, renderErr)}}@@ -1508,7 +1545,6 @@ func CreateDailyNote(boxID string) (p string, existed bool, err error) {return}p = tree.Path- date := time.Now().Format("20060102")tree.Root.SetIALAttr(DailyNoteAttrPrefix+date, date)if err = indexWriteTreeUpsertQueue(tree); err != nil {returndiff --git a/kernel/model/file_index_test.go b/kernel/model/file_index_test.goindex 4305be5a8d..e736e2e04f 100644--- a/kernel/model/file_index_test.go+++ b/kernel/model/file_index_test.go@@ -23,6 +23,7 @@ import ("os/exec""path""path/filepath"+ "strings""testing""time"@@ -233,6 +234,61 @@ func TestDocumentTemplatesWaitForDatabaseIndex(t *testing.T) {dailyID := util.GetTreeID(dailyPath)assertTemplateOutputIndexed(t, dailyID)+ boxConf.DailyNoteSavePath = "/Daily note/{{now | date \"2006-01-02\"}}"+ boxConf.DailyNoteTemplatePath = "/dated.md"+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(templateDir, "dated.md"), []byte(`.action{now | date "2006-01-02"}`), 0644); err != nil {+ t.Fatal(err)+ }+ target := time.Date(2024, 2, 29, 0, 0, 0, 0, time.Local)+ datedPath, existed, err := CreateDailyNoteAt(box.ID, target)+ if err != nil || existed {+ t.Fatalf("create dated note: %s %v %v", datedPath, existed, err)+ }+ datedID := util.GetTreeID(datedPath)+ datedTree, err := LoadTreeByBlockID(datedID)+ if err != nil {+ t.Fatal(err)+ }+ if datedTree.HPath != "/Daily note/2024-02-29" || datedTree.Root.IALAttr(DailyNoteAttrPrefix+"20240229") != "20240229" {+ t.Fatalf("date did not reach path and attribute: %#v", datedTree)+ }+ if content := string(datedTree.Root.Text()); !strings.Contains(content, "2024-02-29") {+ t.Fatalf("content template used another date: %s", content)+ }+ if strings.HasPrefix(datedID, "20240229") || strings.HasPrefix(datedTree.Root.IALAttr("updated"), "20240229") {+ t.Fatal("target date replaced real document timestamps")+ }+ reusedPath, existed, err := CreateDailyNoteAt(box.ID, target)+ if err != nil || !existed || reusedPath != datedPath {+ t.Fatalf("dated note was duplicated: %s %v %v", reusedPath, existed, err)+ }+ if err := RenameDoc(box.ID, datedPath, "Renamed daily note"); err != nil {+ t.Fatal(err)+ }+ reusedPath, existed, err = CreateDailyNoteAt(box.ID, target)+ if err != nil || !existed || reusedPath != datedPath {+ t.Fatalf("renaming duplicated an existing date: %s %v %v", reusedPath, existed, err)+ }+ if err := MoveDocs([]string{box.ID + datedPath}, box.ID, "/", nil); err != nil {+ t.Fatal(err)+ }+ datedPath = "/" + datedID + ".sy"+ reusedPath, existed, err = CreateDailyNoteAt(box.ID, target)+ if err != nil || !existed || reusedPath != datedPath {+ t.Fatalf("moving duplicated an existing date: %s %v %v", reusedPath, existed, err)+ }+ boxConf.DailyNoteSavePath = "/Changed daily note/{{now | date \"2006-01-02\"}}"+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ reusedPath, existed, err = CreateDailyNoteAt(box.ID, target)+ if err != nil || !existed || reusedPath != datedPath {+ t.Fatalf("template change duplicated an existing date: %s %v %v", reusedPath, existed, err)+ }+docID := "20260728000001-abcdefg"arg := map[string]any{"docCreateTemplatePath": "/indexed.md"}createdID, err := CreateWithMarkdown("", box.ID, "/Default template", "", "", docID, false, "", arg)diff --git a/kernel/model/template.go b/kernel/model/template.goindex 19c774d9c3..0d547a1fa3 100644--- a/kernel/model/template.go+++ b/kernel/model/template.go@@ -956,6 +956,11 @@ func PreviewTemplateSource(p, id, content string) (tree *parse.Tree, dom string,}func renderTemplateSource(p, id string, mode TemplateRenderMode, content *string) (tree *parse.Tree, dom string,+ summary *TemplateDocTreePlanSummary, err error) {+ return renderTemplateSourceAt(p, id, mode, content, nil)+}++func renderTemplateSourceAt(p, id string, mode TemplateRenderMode, content *string, now *time.Time) (tree *parse.Tree, dom string,summary *TemplateDocTreePlanSummary, err error) {if TemplateRenderModeContent != mode && TemplateRenderModePreview != mode && TemplateRenderModeEditorInsert != mode {err = fmt.Errorf("unsupported template render mode [%s]", mode)@@ -1015,6 +1020,9 @@ func renderTemplateSource(p, id string, mode TemplateRenderMode, content *stringgoTpl := template.New("").Delims(".action{", "}")tplFuncMap := filesys.BuiltInTemplateFuncs()+ if now != nil {+ tplFuncMap["now"] = func() time.Time { return *now }+ }tplFuncMap["createDocTree"] = collector.createtplFuncMap["renderDocRef"] = collector.renderDocRefsql.SQLTemplateFuncs(&tplFuncMap, sourceTree.Box)@@ -1297,11 +1305,15 @@ func applyDocContentTemplateAfterIndex(templatePath, docID string) error {}func applyDocContentTemplate(templatePath, docID string) error {+ return applyDocContentTemplateAt(templatePath, docID, nil)+}++func applyDocContentTemplateAt(templatePath, docID string, now *time.Time) error {absPath, err := resolveDocContentTemplatePath(templatePath)if nil != err {return err}- templateTree, templateDOM, err := RenderTemplate(absPath, docID, false)+ templateTree, templateDOM, _, err := renderTemplateSourceAt(absPath, docID, TemplateRenderModeContent, nil, now)if nil != err {return err}diff --git a/kernel/sql/daily_note_test.go b/kernel/sql/daily_note_test.gonew file mode 100644index 0000000000..4f77f0bf14--- /dev/null+++ b/kernel/sql/daily_note_test.go@@ -0,0 +1,53 @@+package sql++import (+ gosql "database/sql"+ "reflect"+ "testing"+)++func TestQueryDailyNoteRoots(t *testing.T) {+ for _, encrypted := range []bool{false, true} {+ t.Run(map[bool]string{false: "ordinary", true: "encrypted"}[encrypted], func(t *testing.T) {+ var testDB *gosql.DB+ boxID := "daily-box"+ if encrypted {+ testDB, boxID = useEncryptedQueryTestDB(t)+ } else {+ var err error+ testDB, err = gosql.Open("sqlite3_extended", ":memory:")+ if err != nil {+ t.Fatal(err)+ }+ testDB.SetMaxOpenConns(1)+ previousDB := db+ db = testDB+ t.Cleanup(func() { db = previousDB; testDB.Close() })+ }+ if _, err := testDB.Exec("CREATE TABLE attributes (block_id TEXT, root_id TEXT, box TEXT, name TEXT, value TEXT)"); err != nil {+ t.Fatal(err)+ }+ for _, row := range [][]string{+ {"b", "b", boxID, "custom-dailynote-20240229", "20240229"},+ {"a", "a", boxID, "custom-dailynote-20240229", "20240229"},+ {"child", "a", boxID, "custom-dailynote-20240229", "20240229"},+ {"other", "other", "another-box", "custom-dailynote-20240229", "20240229"},+ {"wrong", "wrong", boxID, "custom-dailynote-20240229", "20240301"},+ } {+ if _, err := testDB.Exec("INSERT INTO attributes VALUES (?, ?, ?, ?, ?)", row[0], row[1], row[2], row[3], row[4]); err != nil {+ t.Fatal(err)+ }+ }+ ids, err := QueryDailyNoteRootIDsInBox(boxID, "custom-dailynote-20240229", "20240229")+ if err != nil || !reflect.DeepEqual(ids, []string{"a", "b"}) {+ t.Fatalf("unexpected date roots: %v %v", ids, err)+ }+ if _, err := testDB.Exec("DROP TABLE attributes"); err != nil {+ t.Fatal(err)+ }+ if _, err := QueryDailyNoteRootIDsInBox(boxID, "custom-dailynote-20240229", "20240229"); err == nil {+ t.Fatal("query error was treated as a missing date")+ }+ })+ }+}diff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.goindex dd1b26a32b..44f3663a60 100644--- a/kernel/sql/encrypted_query.go+++ b/kernel/sql/encrypted_query.go@@ -32,6 +32,23 @@ import (// 本文件提供加密笔记本的 box-scoped 读查询。每个函数接收 boxID,路由到加密 db(已打开)或全局 db。// 调用方(model 层)在加密笔记本上下文里改用这些 InBox 版;全局功能继续用原函数。+// QueryDailyNoteRootIDsInBox 按日记属性查询文档,限定笔记本并保留数据库错误。+func QueryDailyNoteRootIDsInBox(boxID, name, date string) (ids []string, err error) {+ rows, err := queryForBox(boxID, "SELECT DISTINCT block_id FROM attributes WHERE box = ? AND name = ? AND value = ? AND block_id = root_id ORDER BY block_id", boxID, name, date)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ for rows.Next() {+ var id string+ if err = rows.Scan(&id); err != nil {+ return nil, err+ }+ ids = append(ids, id)+ }+ return ids, rows.Err()+}+// GetBlockInBox 按 id 在指定 box 的 db 里查 block。boxID 为空则查全局 db。func GetBlockInBox(id, boxID string) (ret *Block) {ret = getBlockCacheInBox(id, boxID)