Compare commits

...

46 Commits

Author SHA1 Message Date
perf3ct
253da139de feat(search): try again to get fts5 searching done well 2025-10-24 21:47:06 -07:00
Jon Fuller
d992a5e4a2 Merge branch 'main' into feat/rice-searching-with-sqlite 2025-10-24 09:18:11 -07:00
Elian Doran
1e8f179f81 Translations update from Hosted Weblate (#7469) 2025-10-23 20:37:39 +03:00
Elian Doran
54c906de8d Apply suggestion from @gemini-code-assist[bot]
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-10-23 20:35:34 +03:00
Elian Doran
114b3ef4d1 Apply suggestion from @gemini-code-assist[bot]
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-10-23 20:33:43 +03:00
Elian Doran
f6fa1e69b3 Apply suggestion from @gemini-code-assist[bot]
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-10-23 20:33:03 +03:00
Elian Doran
fcc8086f9c Apply suggestion from @gemini-code-assist[bot]
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-10-23 20:32:21 +03:00
Bond
7eefff0a74 Translated using Weblate (Vietnamese)
Currently translated at 10.9% (16 of 146 strings)

Translation: Trilium Notes/Website
Translate-URL: https://hosted.weblate.org/projects/trilium/website/vi/
2025-10-23 19:28:31 +02:00
Микола Копитін
1b842e35ff Translated using Weblate (Ukrainian)
Currently translated at 26.0% (38 of 146 strings)

Translation: Trilium Notes/Website
Translate-URL: https://hosted.weblate.org/projects/trilium/website/uk/
2025-10-23 19:28:30 +02:00
Bond
c9021ca742 Translated using Weblate (Vietnamese)
Currently translated at 55.9% (66 of 118 strings)

Translation: Trilium Notes/README
Translate-URL: https://hosted.weblate.org/projects/trilium/readme/vi/
2025-10-23 19:28:29 +02:00
Микола Копитін
b229ab3c02 Translated using Weblate (Ukrainian)
Currently translated at 32.2% (38 of 118 strings)

Translation: Trilium Notes/README
Translate-URL: https://hosted.weblate.org/projects/trilium/readme/uk/
2025-10-23 19:28:29 +02:00
Bond
6825f28ba0 Translated using Weblate (Vietnamese)
Currently translated at 3.0% (50 of 1621 strings)

Translation: Trilium Notes/Client
Translate-URL: https://hosted.weblate.org/projects/trilium/client/vi/
2025-10-23 19:28:28 +02:00
Микола Копитін
5e72f271ea Translated using Weblate (Ukrainian)
Currently translated at 21.9% (32 of 146 strings)

Translation: Trilium Notes/Website
Translate-URL: https://hosted.weblate.org/projects/trilium/website/uk/
2025-10-23 19:28:27 +02:00
Микола Копитін
9ad6dfd5e9 Translated using Weblate (Ukrainian)
Currently translated at 27.9% (33 of 118 strings)

Translation: Trilium Notes/README
Translate-URL: https://hosted.weblate.org/projects/trilium/readme/uk/
2025-10-23 19:28:27 +02:00
Marc
81031673c3 Translated using Weblate (French)
Currently translated at 100.0% (146 of 146 strings)

Translation: Trilium Notes/Website
Translate-URL: https://hosted.weblate.org/projects/trilium/website/fr/
2025-10-23 19:28:26 +02:00
Микола Копитін
1a6423fd36 Translated using Weblate (Ukrainian)
Currently translated at 20.5% (30 of 146 strings)

Translation: Trilium Notes/Website
Translate-URL: https://hosted.weblate.org/projects/trilium/website/uk/
2025-10-23 19:28:26 +02:00
onlyfranz
9b872617e6 Translated using Weblate (German)
Currently translated at 2.7% (4 of 146 strings)

Translation: Trilium Notes/Website
Translate-URL: https://hosted.weblate.org/projects/trilium/website/de/
2025-10-23 19:28:25 +02:00
Sarah Hussein
57be2e2474 Translated using Weblate (Arabic)
Currently translated at 25.4% (30 of 118 strings)

Translation: Trilium Notes/README
Translate-URL: https://hosted.weblate.org/projects/trilium/readme/ar/
2025-10-23 19:28:25 +02:00
Микола Копитін
1d65afef53 Translated using Weblate (Ukrainian)
Currently translated at 26.2% (31 of 118 strings)

Translation: Trilium Notes/README
Translate-URL: https://hosted.weblate.org/projects/trilium/readme/uk/
2025-10-23 19:28:24 +02:00
Sarah Hussein
b6385618d1 Translated using Weblate (Arabic)
Currently translated at 63.5% (1030 of 1621 strings)

Translation: Trilium Notes/Client
Translate-URL: https://hosted.weblate.org/projects/trilium/client/ar/
2025-10-23 19:28:23 +02:00
Giovi
e3d7c7419f Translated using Weblate (Italian)
Currently translated at 100.0% (387 of 387 strings)

Translation: Trilium Notes/Server
Translate-URL: https://hosted.weblate.org/projects/trilium/server/it/
2025-10-23 19:28:22 +02:00
Giovi
2a6c295967 Translated using Weblate (Italian)
Currently translated at 100.0% (1621 of 1621 strings)

Translation: Trilium Notes/Client
Translate-URL: https://hosted.weblate.org/projects/trilium/client/it/
2025-10-23 19:28:22 +02:00
green
f5f32df847 Translated using Weblate (Japanese)
Currently translated at 100.0% (1621 of 1621 strings)

Translation: Trilium Notes/Client
Translate-URL: https://hosted.weblate.org/projects/trilium/client/ja/
2025-10-23 19:28:21 +02:00
Francis C
1f350b2730 Translated using Weblate (Chinese (Traditional Han script))
Currently translated at 100.0% (1621 of 1621 strings)

Translation: Trilium Notes/Client
Translate-URL: https://hosted.weblate.org/projects/trilium/client/zh_Hant/
2025-10-23 19:28:20 +02:00
Marc
386992255e Translated using Weblate (French)
Currently translated at 100.0% (387 of 387 strings)

Translation: Trilium Notes/Server
Translate-URL: https://hosted.weblate.org/projects/trilium/server/fr/
2025-10-23 19:28:20 +02:00
Bilal Janati
eb505c4615 Translated using Weblate (French)
Currently translated at 100.0% (1621 of 1621 strings)

Translation: Trilium Notes/Client
Translate-URL: https://hosted.weblate.org/projects/trilium/client/fr/
2025-10-23 19:28:19 +02:00
Marc
003d2b5354 Translated using Weblate (French)
Currently translated at 100.0% (1621 of 1621 strings)

Translation: Trilium Notes/Client
Translate-URL: https://hosted.weblate.org/projects/trilium/client/fr/
2025-10-23 19:28:19 +02:00
Elian Doran
b452f78242 feat(mobile/search): search definitions always shown 2025-10-23 20:24:16 +03:00
Elian Doran
7d1abee8e4 feat(mobile/search): show results (closes #5655) 2025-10-23 20:16:17 +03:00
Elian Doran
d503993a74 chore(mobile/search): further improve the layout 2025-10-23 20:03:44 +03:00
Elian Doran
fe98ba8c8c chore(mobile/search): improve actions fit 2025-10-23 19:15:38 +03:00
Elian Doran
18608ecb34 feat(mobile): render search definition 2025-10-23 19:07:40 +03:00
Elian Doran
ab6da26a25 refactor(client): standalone rendering mechanism for ribbon 2025-10-23 18:09:32 +03:00
perf3ct
58c225237c feat(search): try a ground-up sqlite search approach 2025-09-03 00:34:55 +00:00
perf3ct
d074841885 Revert "feat(search): try to get fts search to work in large environments"
This reverts commit 053f722cb8.
2025-09-02 19:24:50 +00:00
perf3ct
06b2d71b27 Revert "feat(search): try to decrease complexity"
This reverts commit 5b79e0d71e.
2025-09-02 19:24:47 +00:00
perf3ct
0afb8a11c8 Revert "feat(search): try to deal with huge dbs, might need to squash later"
This reverts commit 37d0136c50.
2025-09-02 19:24:46 +00:00
perf3ct
f529ddc601 Revert "feat(search): further improve fts search"
This reverts commit 7c5553bd4b.
2025-09-02 19:24:45 +00:00
perf3ct
8572f82e0a Revert "feat(search): I honestly have no idea what I'm doing"
This reverts commit b09a2c386d.
2025-09-02 19:24:44 +00:00
perf3ct
b09a2c386d feat(search): I honestly have no idea what I'm doing 2025-09-01 22:29:59 -07:00
perf3ct
7c5553bd4b feat(search): further improve fts search 2025-09-01 21:40:05 -07:00
perf3ct
37d0136c50 feat(search): try to deal with huge dbs, might need to squash later 2025-09-01 04:33:10 +00:00
perf3ct
5b79e0d71e feat(search): try to decrease complexity 2025-08-30 22:30:01 -07:00
perf3ct
053f722cb8 feat(search): try to get fts search to work in large environments 2025-08-31 03:15:29 +00:00
perf3ct
21aaec2c38 feat(search): also fix tests for new fts functionality 2025-08-30 20:48:42 +00:00
perf3ct
1db4971da6 feat(search): implement FST5 w/ sqlite for faster and better searching
feat(search): don't limit the number of blobs to put in virtual tables

fix(search): improve FTS triggers to handle all SQL operations correctly

The root cause of FTS index issues during import was that database triggers
weren't properly handling all SQL operations, particularly upsert operations
(INSERT ... ON CONFLICT ... DO UPDATE) that are commonly used during imports.

Key improvements:
- Fixed INSERT trigger to handle INSERT OR REPLACE operations
- Updated UPDATE trigger to fire on ANY change (not just specific columns)
- Improved blob triggers to use INSERT OR REPLACE for atomic updates
- Added proper handling for notes created before their blobs (import scenario)
- Added triggers for protection state changes
- All triggers now use LEFT JOIN to handle missing blobs gracefully

This ensures the FTS index stays synchronized even when:
- Entity events are disabled during import
- Notes are re-imported (upsert operations)
- Blobs are deduplicated across notes
- Notes are created before their content blobs

The solution works entirely at the database level through triggers,
removing the need for application-level workarounds.

fix(search): consolidate FTS trigger fixes into migration 234

- Merged improved trigger logic from migration 235 into 234
- Deleted unnecessary migration 235 since DB version is still 234
- Ensures triggers handle all SQL operations (INSERT OR REPLACE, upserts)
- Fixes FTS indexing for imported notes by handling missing blobs
- Schema.sql and migration 234 now have identical trigger implementations
2025-08-30 20:39:40 +00:00
46 changed files with 3705 additions and 401 deletions

View File

@@ -29,8 +29,9 @@ import PromotedAttributesWidget from "../widgets/promoted_attributes.js";
import NoteDetailWidget from "../widgets/note_detail.js";
import CallToActionDialog from "../widgets/dialogs/call_to_action.jsx";
import NoteTitleWidget from "../widgets/note_title.jsx";
import { PopupEditorFormattingToolbar } from "../widgets/ribbon/FormattingToolbar.js";
import FormattingToolbar from "../widgets/ribbon/FormattingToolbar.js";
import NoteList from "../widgets/collections/NoteList.jsx";
import StandaloneRibbonAdapter from "../widgets/ribbon/components/StandaloneRibbonAdapter.jsx";
export function applyModals(rootContainer: RootContainer) {
rootContainer
@@ -63,7 +64,7 @@ export function applyModals(rootContainer: RootContainer) {
.cssBlock(".title-row > * { margin: 5px; }")
.child(<NoteIconWidget />)
.child(<NoteTitleWidget />))
.child(<PopupEditorFormattingToolbar />)
.child(<StandaloneRibbonAdapter component={FormattingToolbar} />)
.child(new PromotedAttributesWidget())
.child(new NoteDetailWidget())
.child(<NoteList media="screen" displayOnlyCollections />))

View File

@@ -24,6 +24,9 @@ import CloseZenModeButton from "../widgets/close_zen_button.js";
import NoteWrapperWidget from "../widgets/note_wrapper.js";
import MobileDetailMenu from "../widgets/mobile_widgets/mobile_detail_menu.js";
import NoteList from "../widgets/collections/NoteList.jsx";
import StandaloneRibbonAdapter from "../widgets/ribbon/components/StandaloneRibbonAdapter.jsx";
import SearchDefinitionTab from "../widgets/ribbon/SearchDefinitionTab.jsx";
import SearchResult from "../widgets/search_result.jsx";
const MOBILE_CSS = `
<style>
@@ -155,6 +158,8 @@ export default class MobileLayout {
.contentSized()
.child(new NoteDetailWidget())
.child(<NoteList media="screen" />)
.child(<StandaloneRibbonAdapter component={SearchDefinitionTab} />)
.child(<SearchResult />)
.child(<FilePropertiesWrapper />)
)
.child(<MobileEditorToolbar />)

View File

@@ -63,7 +63,7 @@
/* Button bar */
.search-definition-widget .search-setting-table tbody:last-child div {
justify-content: flex-end !important;
justify-content: flex-end;
gap: 8px;
}

View File

@@ -655,7 +655,11 @@
"google": "جوجل",
"save_button": "حفظ",
"baidu": "Baidu",
"title": "محرك البحث"
"title": "محرك البحث",
"predefined_templates_label": "قوالب محرك البحث المعرفة مسبقا",
"custom_name_label": "اسم محرك البحث المخصص",
"custom_name_placeholder": "اسم محرك البحث المخصص",
"custom_url_placeholder": "تخصيص عنوان URL لمحرك البحث"
},
"heading_style": {
"plain": "بسيط",
@@ -676,7 +680,8 @@
"wednesday": "الاربعاء",
"thursday": "الخميس",
"friday": "الجمعة",
"saturday": "السبت"
"saturday": "السبت",
"formatting-locale": "تنسيق التاريخ والارقام"
},
"backup": {
"path": "مسار",
@@ -699,7 +704,8 @@
"token_name": "اسم الرمز",
"default_token_name": "رمز جديد",
"rename_token_title": "اعادة تسمية الرمز",
"rename_token": "اعادة تسمية هذا الرمز"
"rename_token": "اعادة تسمية هذا الرمز",
"create_token": "انشاء رمز PEAPI جديد"
},
"password": {
"heading": "كلمة المرور",
@@ -731,7 +737,8 @@
"timeout": "انتهاء مهلة المزامنة",
"test_title": "اختبار المزامنة",
"test_button": "اختبار المزامنة",
"server_address": "عنوان نسخة الخادم"
"server_address": "عنوان نسخة الخادم",
"proxy_label": "خادم وكيل المزامنة (اخياري)"
},
"api_log": {
"close": "أغلاق"
@@ -751,7 +758,8 @@
"new_tab": "تبويب جديد",
"close_all_tabs": "اغلاق كل علامات التبويب",
"add_new_tab": "اضافة علامة تبويب جديدة",
"close_other_tabs": "اغلاق علامات التبويب الاخرى"
"close_other_tabs": "اغلاق علامات التبويب الاخرى",
"reopen_last_tab": "اعادة فتح اخر علامة تبويب مغلقة"
},
"toc": {
"options": "خيارات",
@@ -791,7 +799,8 @@
},
"call_to_action": {
"dismiss": "تجاهل",
"background_effects_button": "تفعيل مؤثرات الخلفية"
"background_effects_button": "تفعيل مؤثرات الخلفية",
"next_theme_button": "جرب النسق الجديد"
},
"units": {
"percentage": "%"
@@ -835,7 +844,8 @@
"search-in-subtree": "‍البحث في الشجرة الفرعية",
"edit-branch-prefix": "تعديل بادئة الفرع",
"convert-to-attachment": "التحويل الى مرفق",
"apply-bulk-actions": "‌تطبيق الاجراءات الجماعية"
"apply-bulk-actions": "‌تطبيق الاجراءات الجماعية",
"recent-changes-in-subtree": "التغييرات الاخيرة في الشجرة الفرعية"
},
"note_types": {
"text": "نص",
@@ -884,7 +894,8 @@
"quick-search": {
"searching": "جار البحث...",
"placeholder": "البحث السريع",
"no-results": "لم يتم العثور على نتائج"
"no-results": "لم يتم العثور على نتائج",
"show-in-full-search": "عرض في البحث الكامل"
},
"note_tree": {
"unhoist": "ارجاع الى الترتيب الطبيعي",
@@ -893,7 +904,12 @@
"collapse-title": "طي شجرة الملاحظة",
"hide-archived-notes": "اخفاء الملاحظات المؤرشفة",
"automatically-collapse-notes": "طي الملاحظات تلقائيا",
"create-child-note": "انشاء ملاحظة فرعية"
"create-child-note": "انشاء ملاحظة فرعية",
"scroll-active-title": "تمرير الى الملاحظة النشطة",
"save-changes": "حفظ وتطبيق التغييرات",
"saved-search-note-refreshed": "تم تحديث ملاحظة البحث المحفوظة.",
"hoist-this-note-workspace": "تثبيت هذه الملاحظة (مساحة العمل)",
"refresh-saved-search-results": "تحديث نتائج البحث المحفوظة"
},
"sql_table_schemas": {
"tables": "جداول"
@@ -901,7 +917,13 @@
"launcher_context_menu": {
"reset": "اعادة ضبط",
"add-spacer": "اضافة فاصل",
"delete": "حذف\n<kbd data-command=\"deleteNotes\">"
"delete": "حذف\n<kbd data-command=\"deleteNotes\">",
"add-note-launcher": "اضافة مشغل الملاحظة",
"add-script-launcher": "اضافة مشغل السكريبت",
"add-custom-widget": "اضافة عنصر واجهة مخصص",
"move-to-visible-launchers": "نقل الى المشغلات المرئية",
"move-to-available-launchers": "نقل الى المشغلات المتوفرة",
"duplicate-launcher": "تكرار المشغل <kbd data-command=\"duplicateSubtree\">"
},
"editable-text": {
"auto-detect-language": "تم اكتشافه تلقائيا"
@@ -927,7 +949,9 @@
"cut": "قص",
"copy": "نسخ",
"paste": "لصق",
"copy-link": "نسخ الرابط"
"copy-link": "نسخ الرابط",
"add-term-to-dictionary": "اضافة \"{{term}}\" الى القاموس",
"paste-as-plain-text": "لصق كنص عادي"
},
"promoted_attributes": {
"url_placeholder": "http://website...",
@@ -977,7 +1001,11 @@
"totp_secret_regenerate": "اعادة توليد TOTP السري",
"totp_secret_generated": "تم انشاء TOTP السري",
"oauth_missing_vars": "اعدادات مفقودة: {{-variables}}",
"totp_secret_title": "توليد TOTP سري"
"totp_secret_title": "توليد TOTP سري",
"totp_title": "كلمة مرور لمرة واحدة معتمدة على الوقت (TOTP)",
"recovery_keys_title": "مفاتيح استرداد تسجيل الدخول الاحادي",
"recovery_keys_error": "حدث خطأ اثناء توليد رموز الاسترجاع",
"recovery_keys_no_key_set": "لاتوجد رموز استرجاع معينة"
},
"execute_script": {
"execute_script": "تنفيذ السكريبت"
@@ -1119,7 +1147,12 @@
"title": "اخفاء هوية البيانات",
"full_anonymization": "الاخفاء الكامل للهوية",
"light_anonymization": "الاخفاء الجزئي للهوية",
"existing_anonymized_databases": "قواعد البيانات المجهولة الحالية"
"existing_anonymized_databases": "قواعد البيانات المجهولة الحالية",
"save_fully_anonymized_database": "حفظ قاعدة البيانات بعد اخفاء كل الهويات",
"save_lightly_anonymized_database": "حفظ قاعدةةبيانات مخفية جزئيا",
"creating_fully_anonymized_database": "انشاء قاعدة بيانات مجهولة بالكامل",
"creating_lightly_anonymized_database": "انشاء قاعدةة بيانات مجهولة جزئيا...",
"no_anonymized_database_yet": "لاتوجد قاعدة بيانات مجهولة بعد."
},
"vacuum_database": {
"title": "تحرير مساحة قاعدة البيانات",
@@ -1146,7 +1179,8 @@
"italic": "نص مائل",
"underline": "خط تحت النص",
"color": "نص ملون",
"visibility_title": "اظهار قائمة التضليلات"
"visibility_title": "اظهار قائمة التضليلات",
"bg_color": "نص مع لون خلفية"
},
"revisions_button": {
"note_revisions": "مراجعات الملاحظة"
@@ -1163,7 +1197,8 @@
"title": "التدقيق الاملائي",
"enable": "تفعيل التدقيق الاملائي",
"language_code_label": "رمز اللغة او رموز اللغات",
"available_language_codes_label": "رموز اللغات المتاحة:"
"available_language_codes_label": "رموز اللغات المتاحة:",
"language_code_placeholder": "على سبيل المثال \"en-US\", \"de-AI\""
},
"note-map": {
"button-link-map": "خريطة الروابط",
@@ -1177,7 +1212,9 @@
},
"branches": {
"delete-status": "حالة الحذف",
"delete-finished-successfully": "تم الحذف بنجاح."
"delete-finished-successfully": "تم الحذف بنجاح.",
"cannot-move-notes-here": "لايمكن نقل الملاحظات الى هنا.",
"undeleting-notes-finished-successfully": "تم استرجاع الملاحظات بنجاح."
},
"highlighting": {
"title": "كتل الكود",
@@ -1199,14 +1236,16 @@
"native-title-bar": "شريط العنوان الاصلي"
},
"note_tooltip": {
"quick-edit": "التحرير السريع"
"quick-edit": "التحرير السريع",
"note-has-been-deleted": "تم حذف الملاحظة."
},
"geo-map-context": {
"open-location": "فتح الموقع",
"remove-from-map": "ازالة من الخريطة"
},
"share": {
"title": "اعدادات المشاركة"
"title": "اعدادات المشاركة",
"check_share_root": "التحقق من حالة جذر المشاركة"
},
"note_language": {
"not_set": "غير محدد",
@@ -1251,7 +1290,8 @@
"search_subtree_title": "بحث في الشجرة الفرعية",
"search_history_title": "عرص سجل البحث",
"search_history_description": "عرض البحث السابق",
"configure_launch_bar_title": "تكوين شريط الاطلاق"
"configure_launch_bar_title": "تكوين شريط الاطلاق",
"search_subtree_description": "البحث ضمن الشجرة الفرعية الحالية"
},
"content_renderer": {
"open_externally": "فتح خارجيا"
@@ -1295,7 +1335,8 @@
"database_integrity_check": {
"title": "فحص سلامة قاعدة البيانات",
"check_button": "التحقق من سلامة قاعدة البيانات",
"checking_integrity": "جار التحقق من سلامة قاعدة البيانات..."
"checking_integrity": "جار التحقق من سلامة قاعدة البيانات...",
"integrity_check_failed": "فشل التحقق من السلامة: {{results}}"
},
"watched_file_update_status": {
"upload_modified_file": "رفع الملف المعدل",
@@ -1328,7 +1369,8 @@
"button_exit": "الخروج من وضع Zen"
},
"attachment_erasure_timeout": {
"attachment_erasure_timeout": "مهلة مسح المرفقات"
"attachment_erasure_timeout": "مهلة مسح المرفقات",
"erase_attachments_after": "حذف المرفقات الغير مستخدمة بعد:"
},
"note_erasure_timeout": {
"note_erasure_timeout_title": "مهلة مسح الملاحظة",
@@ -1366,5 +1408,31 @@
},
"revisions_snapshot_interval": {
"note_revisions_snapshot_interval_title": "الفاصل الزمني لنسخ الملاحظات الاحتياطية"
},
"note_detail": {
"printing": "جار الطباعة ..."
},
"attachment_detail_2": {
"role_and_size": "الدور: {{role}}، الحجم: {{size}}",
"unrecognized_role": "دور المرفق '{{role}}'الغير معروف."
},
"title_bar_buttons": {
"window-on-top": "ابقاء النافذة في الاعلى"
},
"note_title": {
"placeholder": "اكتب عنوان الملاحظة هنا..."
},
"image_context_menu": {
"copy_reference_to_clipboard": "نسخ المرجع الى الحافظة",
"copy_image_to_clipboard": "نسخ الصورة الى الحافظة"
},
"geo-map": {
"unable-to-load-map": "تعذر تحميل الخريطة."
},
"content_widget": {
"unknown_widget": "عنصر واجهة غير معروف للمعرف \"{{id}}\"."
},
"png_export_button": {
"button_title": "تصدير المخطط كملف PNG"
}
}

View File

@@ -280,8 +280,8 @@
"delete_button": "Supprimer",
"diff_on": "Afficher les différences",
"diff_off": "Afficher le contenu",
"diff_on_hint": "Cliquez pour afficher les différences de la note d'origine",
"diff_off_hint": "Cliquez pour afficher le contenu de la note",
"diff_on_hint": "Cliquer pour afficher les différences avec la note d'origine",
"diff_off_hint": "Cliquer pour afficher le contenu de la note",
"diff_not_available": "La comparaison n'est pas disponible."
},
"sort_child_notes": {
@@ -647,7 +647,9 @@
"about": "À propos de Trilium Notes",
"logout": "Déconnexion",
"show-cheatsheet": "Afficher l'aide rapide",
"toggle-zen-mode": "Zen Mode"
"toggle-zen-mode": "Zen Mode",
"new-version-available": "Nouvelle mise à jour disponible",
"download-update": "Obtenir la version {{latestVersion}}"
},
"zen_mode": {
"button_exit": "Sortir du Zen mode"
@@ -674,7 +676,7 @@
"search_in_note": "Rechercher dans la note",
"note_source": "Code source",
"note_attachments": "Pièces jointes",
"open_note_externally": "Ouverture externe",
"open_note_externally": "Ouvrir la note en externe",
"open_note_externally_title": "Le fichier sera ouvert dans une application externe et les modifications apportées seront surveillées. Vous pourrez ensuite téléverser la version modifiée dans Trilium.",
"open_note_custom": "Ouvrir la note avec",
"import_files": "Importer des fichiers",
@@ -767,7 +769,8 @@
"table": "Tableau",
"geo-map": "Carte géographique",
"board": "Tableau de bord",
"include_archived_notes": "Afficher les notes archivées"
"include_archived_notes": "Afficher les notes archivées",
"presentation": "Présentation"
},
"edited_notes": {
"no_edited_notes_found": "Aucune note modifiée ce jour-là...",
@@ -1142,7 +1145,8 @@
"code_auto_read_only_size": {
"title": "Taille pour la lecture seule automatique",
"description": "La taille pour la lecture seule automatique est le seuil au-delà de laquelle les notes seront affichées en mode lecture seule (pour optimiser les performances).",
"label": "Taille pour la lecture seule automatique (notes de code)"
"label": "Taille pour la lecture seule automatique (notes de code)",
"unit": "caractères"
},
"code_mime_types": {
"title": "Types MIME disponibles dans la liste déroulante"
@@ -1435,8 +1439,8 @@
"open-in-popup": "Modification rapide"
},
"shared_info": {
"shared_publicly": "Cette note est partagée publiquement sur {{- link}}",
"shared_locally": "Cette note est partagée localement sur {{- link}}",
"shared_publicly": "Cette note est partagée publiquement sur {{- link}}.",
"shared_locally": "Cette note est partagée localement sur {{- link}}.",
"help_link": "Pour obtenir de l'aide, visitez le <a href=\"https://triliumnext.github.io/Docs/Wiki/sharing.html\">wiki</a>."
},
"note_types": {
@@ -1460,7 +1464,9 @@
"beta-feature": "Beta",
"task-list": "Liste de tâches",
"book": "Collection",
"ai-chat": "Chat IA"
"ai-chat": "Chat IA",
"new-feature": "Nouveau",
"collections": "Collections"
},
"protect_note": {
"toggle-on": "Protéger la note",
@@ -1513,13 +1519,16 @@
"hoist-this-note-workspace": "Focus cette note (espace de travail)",
"refresh-saved-search-results": "Rafraîchir les résultats de recherche enregistrée",
"create-child-note": "Créer une note enfant",
"unhoist": "Désactiver le focus"
"unhoist": "Désactiver le focus",
"toggle-sidebar": "Basculer la barre latérale"
},
"title_bar_buttons": {
"window-on-top": "Épingler cette fenêtre au premier plan"
},
"note_detail": {
"could_not_find_typewidget": "Impossible de trouver typeWidget pour le type '{{type}}'"
"could_not_find_typewidget": "Impossible de trouver typeWidget pour le type '{{type}}'",
"printing": "Impression en cours...",
"printing_pdf": "Export au format PDF en cours..."
},
"note_title": {
"placeholder": "saisir le titre de la note ici..."
@@ -1570,7 +1579,9 @@
},
"clipboard": {
"cut": "Les note(s) ont été coupées dans le presse-papiers.",
"copied": "Les note(s) ont été coupées dans le presse-papiers."
"copied": "Les note(s) ont été coupées dans le presse-papiers.",
"copy_failed": "Impossible de copier dans le presse-papiers en raison de problèmes d'autorisation.",
"copy_success": "Copié dans le presse-papiers."
},
"entrypoints": {
"note-revision-created": "La version de la note a été créée.",
@@ -1592,7 +1603,9 @@
"ws": {
"sync-check-failed": "Le test de synchronisation a échoué !",
"consistency-checks-failed": "Les tests de cohérence ont échoué ! Consultez les journaux pour plus de détails.",
"encountered-error": "Erreur \"{{message}}\", consultez la console."
"encountered-error": "Erreur \"{{message}}\", consultez la console.",
"lost-websocket-connection-title": "Connexion au serveur perdue",
"lost-websocket-connection-message": "Vérifiez la configuration de votre proxy inverse (par exemple nginx ou Apache) pour vous assurer que les connexions WebSocket sont correctement autorisées et ne sont pas bloquées."
},
"hoisted_note": {
"confirm_unhoisting": "La note demandée «{{requestedNote}}» est en dehors du sous-arbre de la note focus «{{hoistedNote}}». Le focus doit être désactivé pour accéder à la note. Voulez-vous enlever le focus ?"
@@ -1614,13 +1627,15 @@
},
"highlighting": {
"description": "Contrôle la coloration syntaxique des blocs de code à l'intérieur des notes texte, les notes de code ne seront pas affectées.",
"color-scheme": "Jeu de couleurs"
"color-scheme": "Jeu de couleurs",
"title": "Blocs de code"
},
"code_block": {
"word_wrapping": "Saut à la ligne automatique suivant la largeur",
"theme_none": "Pas de coloration syntaxique",
"theme_group_light": "Thèmes clairs",
"theme_group_dark": "Thèmes sombres"
"theme_group_dark": "Thèmes sombres",
"copy_title": "Copier dans le presse-papiers"
},
"classic_editor_toolbar": {
"title": "Mise en forme"
@@ -1679,7 +1694,8 @@
"full-text-search": "Recherche dans le texte"
},
"note_tooltip": {
"note-has-been-deleted": "La note a été supprimée."
"note-has-been-deleted": "La note a été supprimée.",
"quick-edit": "Edition rapide"
},
"geo-map": {
"create-child-note-title": "Créer une nouvelle note enfant et l'ajouter à la carte",
@@ -1688,7 +1704,8 @@
},
"geo-map-context": {
"open-location": "Ouvrir la position",
"remove-from-map": "Retirer de la carte"
"remove-from-map": "Retirer de la carte",
"add-note": "Ajouter un marqueur à cet endroit"
},
"help-button": {
"title": "Ouvrir la page d'aide correspondante"
@@ -1748,7 +1765,8 @@
"oauth_user_not_logged_in": "Pas connecté!"
},
"modal": {
"close": "Fermer"
"close": "Fermer",
"help_title": "Afficher plus d'informations sur cet écran"
},
"ai_llm": {
"not_started": "Non démarré",
@@ -1828,13 +1846,76 @@
"reprocessing_index": "Mise à jour...",
"reprocess_index_started": "L'optimisation de l'indice de recherche à commencer en arrière-plan",
"reprocess_index_error": "Erreur dans le rafraichissement de l'indice de recherche",
"failed_notes": "Notes échouées",
"failed_notes": "Notes en erreur",
"last_processed": "Dernier traitement",
"restore_provider": "Restaurer le fournisseur de la recherche",
"restore_provider": "Restaurer le fournisseur de recherche",
"index_rebuild_progress": "Progression de la reconstruction de l'index",
"index_rebuilding": "Optimisation de l'index ({{percentage}}%)",
"index_rebuild_complete": "Optimisation de l'index terminée",
"index_rebuild_status_error": "Erreur lors de la vérification de l'état de reconstruction de l'index"
"index_rebuild_status_error": "Erreur lors de la vérification de l'état de reconstruction de l'index",
"provider_precedence": "Priorité du fournisseur",
"never": "Jamais",
"processing": "Traitement en cours ({{percentage}}%)",
"incomplete": "Incomplet ({{percentage}}%)",
"complete": "Terminé (100%)",
"refreshing": "Mise à jour...",
"auto_refresh_notice": "Actualisation automatique toutes les {{seconds}} secondes",
"note_queued_for_retry": "Note mise en file d'attente pour une nouvelle tentative",
"failed_to_retry_note": "Échec de la nouvelle tentative de note",
"all_notes_queued_for_retry": "Toutes les notes ayant échoué sont mises en file d'attente pour une nouvelle tentative",
"failed_to_retry_all": "Échec du ré essai des notes",
"ai_settings": "Paramètres IA",
"api_key_tooltip": "Clé API pour accéder au service",
"empty_key_warning": {
"anthropic": "La clé API Anthropic est vide. Veuillez saisir une clé API valide.",
"openai": "La clé API OpenAI est vide. Veuillez saisir une clé API valide.",
"voyage": "La clé API Voyage est vide. Veuillez saisir une clé API valide.",
"ollama": "La clé API Ollama est vide. Veuillez saisir une clé API valide."
},
"agent": {
"processing": "Traitement...",
"thinking": "Réflexion...",
"loading": "Chargement...",
"generating": "Génération..."
},
"name": "IA",
"openai": "OpenAI",
"use_enhanced_context": "Utiliser un contexte amélioré",
"enhanced_context_description": "Fournit à l'IA plus de contexte à partir de la note et de ses notes associées pour de meilleures réponses",
"show_thinking": "Montrer la réflexion",
"show_thinking_description": "Montrer la chaîne de pensée de l'IA",
"enter_message": "Entrez votre message...",
"error_contacting_provider": "Erreur lors de la connexion au fournisseur d'IA. Veuillez vérifier vos paramètres et votre connexion Internet.",
"error_generating_response": "Erreur lors de la génération de la réponse de l'IA",
"index_all_notes": "Indexer toutes les notes",
"index_status": "Statut de l'index",
"indexed_notes": "Notes indexées",
"indexing_stopped": "Arrêt de l'indexation",
"indexing_in_progress": "Indexation en cours...",
"last_indexed": "Dernière indexée",
"note_chat": "Note discussion",
"sources": "Sources",
"start_indexing": "Démarrage de l'indexation",
"use_advanced_context": "Utiliser le contexte avancé",
"ollama_no_url": "Ollama n'est pas configuré. Veuillez saisir une URL valide.",
"chat": {
"root_note_title": "Discussions IA",
"root_note_content": "Cette note contient vos conversations de chat IA enregistrées.",
"new_chat_title": "Nouvelle discussion",
"create_new_ai_chat": "Créer une nouvelle discussion IA"
},
"create_new_ai_chat": "Créer une nouvelle discussion IA",
"configuration_warnings": "Il y a quelques problèmes avec la configuration de votre IA. Veuillez vérifier vos paramètres.",
"experimental_warning": "La fonctionnalité LLM est actuellement expérimentale vous êtes prévenu.",
"selected_provider": "Fournisseur sélectionné",
"selected_provider_description": "Choisissez le fournisseur dIA pour les fonctionnalités de discussion et de complétion",
"select_model": "Sélectionner le modèle...",
"select_provider": "Sélectionnez un fournisseur...",
"ai_enabled": "Fonctionnalités d'IA activées",
"ai_disabled": "Fonctionnalités d'IA désactivées",
"no_models_found_online": "Aucun modèle trouvé. Veuillez vérifier votre clé API et vos paramètres.",
"no_models_found_ollama": "Aucun modèle Ollama trouvé. Veuillez vérifier si Ollama est en cours d'exécution.",
"error_fetching": "Erreur lors de la récupération des modèles : {{error}}"
},
"ui-performance": {
"title": "Performance",
@@ -1846,8 +1927,165 @@
},
"custom_date_time_format": {
"title": "Format de date/heure personnalisé",
"description": "Personnalisez le format de la date et de l'heure insérées via <shortcut /> ou la barre d'outils. Consultez la <doc>documentation Day.js</doc> pour connaître les formats disponibles.",
"description": "Personnalisez le format de la date et de l'heure insérées via <shortcut /> ou la barre d'outils. Consultez la <doc>Day.js docs</doc> pour connaître les formats disponibles.",
"format_string": "Chaîne de format :",
"formatted_time": "Date/heure formatée :"
},
"table_view": {
"delete_column_confirmation": "Êtes-vous sûr de vouloir supprimer cette colonne ? L'attribut correspondant sera supprimé de toutes les notes.",
"delete-column": "Supprimer la colonne",
"new-column-label": "Étiquette",
"new-column-relation": "Relation",
"edit-column": "Editer la colonne",
"add-column-to-the-right": "Ajouter une colonne à droite",
"new-row": "Nouvelle ligne",
"new-column": "Nouvelle colonne",
"sort-column-by": "Trier par « {{title}} »",
"sort-column-ascending": "Ascendant",
"sort-column-descending": "Descendant",
"sort-column-clear": "Annuler le tri",
"hide-column": "Masquer la colonne \"{{title}}\"",
"show-hide-columns": "Afficher/masquer les colonnes",
"row-insert-above": "Insérer une ligne au-dessus",
"row-insert-below": "Insérer une ligne au-dessous",
"row-insert-child": "Insérer une note enfant",
"add-column-to-the-left": "Ajouter une colonne à gauche"
},
"book_properties_config": {
"hide-weekends": "Masquer les week-ends",
"display-week-numbers": "Afficher les numéros de semaine",
"map-style": "Style de carte :",
"max-nesting-depth": "Profondeur d'imbrication maximale :",
"raster": "Trame",
"vector_light": "Vecteur (clair)",
"vector_dark": "Vecteur (foncé)",
"show-scale": "Afficher l'échelle"
},
"table_context_menu": {
"delete_row": "Supprimer la ligne"
},
"board_view": {
"delete-note": "Supprimer la note...",
"remove-from-board": "Retirer du tableau",
"archive-note": "Note archivée",
"unarchive-note": "Note désarchivée",
"move-to": "Déplacer vers",
"insert-above": "Insérer au-dessus",
"insert-below": "Insérer au-dessous",
"delete-column": "Supprimer la colonne",
"delete-column-confirmation": "Êtes-vous sûr de vouloir supprimer cette colonne? L'attribut correspondant sera également supprimé dans les notes sous cette colonne.",
"new-item": "Nouvel article",
"new-item-placeholder": "Entrez le titre de note...",
"add-column": "Ajouter une colonne",
"add-column-placeholder": "Entrez le nom de la colonne...",
"edit-note-title": "Cliquez pour modifier le titre de la note",
"edit-column-title": "Cliquez pour modifier le titre de la colonne"
},
"presentation_view": {
"edit-slide": "Modifier cette diapositive",
"start-presentation": "Démarrer la présentation",
"slide-overview": "Afficher un aperçu des diapositives"
},
"command_palette": {
"tree-action-name": "Arborescence : {{name}}",
"export_note_title": "Exporter la note",
"export_note_description": "Exporter la note actuelle",
"show_attachments_title": "Afficher les pièces jointes",
"show_attachments_description": "Afficher les pièces jointes des notes",
"search_notes_title": "Rechercher des notes",
"search_notes_description": "Ouvrir la recherche avancée",
"search_subtree_title": "Rechercher dans la sous-arborescence",
"search_subtree_description": "Rechercher dans la sous-arborescence actuelle",
"search_history_title": "Afficher l'historique de recherche",
"search_history_description": "Afficher les recherches précédentes",
"configure_launch_bar_title": "Configurer la barre de lancement",
"configure_launch_bar_description": "Ouvrir la configuration de la barre de lancement pour ajouter ou supprimer des éléments."
},
"content_renderer": {
"open_externally": "Ouverture externe"
},
"call_to_action": {
"next_theme_title": "Essayez le nouveau thème Trilium",
"next_theme_message": "Vous utilisez actuellement le thème hérité de l'ancienne version, souhaitez-vous essayer le nouveau thème?",
"next_theme_button": "Essayez le nouveau thème",
"background_effects_title": "Les effets d'arrière-plan sont désormais stables",
"background_effects_message": "Sur les appareils Windows, les effets d'arrière-plan sont désormais parfaitement stables. Ils ajoutent une touche de couleur à l'interface utilisateur en floutant l'arrière-plan. Cette technique est également utilisée dans d'autres applications comme l'Explorateur Windows.",
"background_effects_button": "Activer les effets d'arrière-plan",
"dismiss": "Rejeter"
},
"settings": {
"related_settings": "Paramètres associés"
},
"settings_appearance": {
"related_code_blocks": "Schéma de coloration syntaxique pour les blocs de code dans les notes de texte",
"related_code_notes": "Schéma de couleurs pour les notes de code"
},
"units": {
"percentage": "%"
},
"pagination": {
"page_title": "Page de {{startIndex}} - {{endIndex}}",
"total_notes": "{{count}} notes"
},
"collections": {
"rendering_error": "Impossible d'afficher le contenu en raison d'une erreur."
},
"code-editor-options": {
"title": "Éditeur"
},
"tasks": {
"due": {
"today": "Aujourd'hui",
"tomorrow": "Demain",
"yesterday": "Hier"
}
},
"content_widget": {
"unknown_widget": "Widget inconnu pour « {{id}} »."
},
"note_language": {
"not_set": "Non défini",
"configure-languages": "Configurer les langues..."
},
"content_language": {
"title": "Contenu des langues",
"description": "Sélectionnez une ou plusieurs langues à afficher dans la section « Propriétés de base » d'une note textuelle en lecture seule ou modifiable. Cela permettra d'utiliser des fonctionnalités telles que la vérification orthographique ou la prise en charge de l'écriture de droite à gauche."
},
"switch_layout_button": {
"title_vertical": "Déplacer le volet d'édition vers le bas",
"title_horizontal": "Déplacer le panneau d'édition vers la gauche"
},
"toggle_read_only_button": {
"unlock-editing": "Déverrouiller l'édition",
"lock-editing": "Verrouiller l'édition"
},
"png_export_button": {
"button_title": "Exporter le diagramme au format PNG"
},
"svg": {
"export_to_png": "Le diagramme n'a pas pu être exporté au format PNG."
},
"code_theme": {
"title": "Apparence",
"word_wrapping": "retour à la ligne automatique",
"color-scheme": "Jeu de couleurs"
},
"cpu_arch_warning": {
"title": "Veuillez télécharger la version ARM64",
"message_macos": "TriliumNext fonctionne actuellement sous Rosetta 2, ce qui signifie que vous utilisez la version Intel (x64) sur un Mac Apple Silicon. Cela aura un impact significatif sur les performances et l'autonomie de la batterie.",
"message_windows": "TriliumNext fonctionne actuellement en mode émulation, ce qui signifie que vous utilisez la version Intel (x64) sur un appareil Windows sur ARM. Cela aura un impact significatif sur les performances et l'autonomie de la batterie.",
"recommendation": "Pour une expérience optimale, veuillez télécharger la version ARM64 native de TriliumNext depuis notre page de versions.",
"download_link": "Télécharger la version native",
"continue_anyway": "Continuer quand même",
"dont_show_again": "Ne plus afficher cet avertissement"
},
"editorfeatures": {
"title": "Caractéristiques",
"emoji_completion_enabled": "Activer la saisie semi-automatique des emojis",
"emoji_completion_description": "Si cette option est activée, les emojis peuvent être facilement insérés dans le texte en tapant `:` , suivi du nom d'un emoji.",
"note_completion_enabled": "Activer la saisie semi-automatique des notes",
"note_completion_description": "Si cette option est activée, des liens vers des notes peuvent être créés en tapant `@` suivi du titre d'une note.",
"slash_commands_enabled": "Activer les commandes slash",
"slash_commands_description": "Si cette option est activée, les commandes d'édition telles que l'insertion de sauts de ligne ou d'en-têtes peuvent être activées en tapant `/`."
}
}

View File

@@ -221,7 +221,7 @@
"emoji_completion_description": "Se abilitata, è possibile inserire facilmente gli emoji nel testo digitando `:`, seguito dal nome dell'emoji.",
"note_completion_description": "Se abilitato, è possibile creare collegamenti alle note digitando `@` seguito dal titolo di una nota.",
"slash_commands_enabled": "Abilita i comandi slash",
"slash_commands_description": "Se abilitato, i comandi di modifica come l'inserimento di interruzioni di riga o intestazioni possono essere attivati digitando `/`."
"slash_commands_description": "Se abilitato, i comandi di modifica come l'inserimento di interruzioni di riga o intestazioni possono essere attivati digitando `/`."
},
"table_view": {
"new-row": "Nuova riga",
@@ -381,8 +381,8 @@
},
"attachment_detail": {
"open_help_page": "Apri la pagina di aiuto sugli allegati",
"owning_note": "Nota di proprietà:",
"you_can_also_open": ", puoi anche aprire il",
"owning_note": "Nota di proprietà: ",
"you_can_also_open": ", puoi anche aprire il ",
"list_of_all_attachments": "Elenco di tutti gli allegati",
"attachment_deleted": "Questo allegato è stato eliminato."
},
@@ -703,7 +703,7 @@
"last_attempt": "Ultimo tentativo",
"actions": "Azioni",
"retry": "Riprova",
"partial": "{{ percentuale }}% completato",
"partial": "{{ percentage }}% completato",
"retry_queued": "Nota in coda per un nuovo tentativo",
"retry_failed": "Impossibile mettere in coda la nota per un nuovo tentativo",
"max_notes_per_llm_query": "Numero massimo di note per query",
@@ -719,12 +719,12 @@
"reprocess_index_started": "Ottimizzazione dell'indice di ricerca avviata in background",
"reprocess_index_error": "Errore durante la ricostruzione dell'indice di ricerca",
"index_rebuild_progress": "Progresso nella ricostruzione dell'indice",
"index_rebuilding": "Indice di ottimizzazione ({{percentuale}}%)",
"index_rebuilding": "Indice di ottimizzazione ({{percentage}}%)",
"index_rebuild_complete": "Ottimizzazione dell'indice completata",
"index_rebuild_status_error": "Errore durante il controllo dello stato di ricostruzione dell'indice",
"never": "Mai",
"processing": "Elaborazione ({{percentuale}}%)",
"incomplete": "Incompleto ({{percentuale}}%)",
"processing": "Elaborazione ({{percentage}}%)",
"incomplete": "Incompleto ({{percentage}}%)",
"complete": "Completato (100%)",
"refreshing": "Rinfrescante...",
"auto_refresh_notice": "Si aggiorna automaticamente ogni {{seconds}} secondi",
@@ -761,9 +761,7 @@
"indexing_stopped": "Indicizzazione interrotta",
"indexing_in_progress": "Indicizzazione in corso...",
"last_indexed": "Ultimo indicizzato",
"n_notes_queued": "{{ count }} nota in coda per l'indicizzazione",
"note_chat": "Nota Chat",
"notes_indexed": "{{ count }} nota indicizzata",
"sources": "Fonti",
"start_indexing": "Avvia l'indicizzazione",
"use_advanced_context": "Usa contesto avanzato",
@@ -811,7 +809,8 @@
"codeImportedAsCode": "Importa i file di codice riconosciuti (ad esempio <code>.json</code>) come note di codice se non è chiaro dai metadati",
"replaceUnderscoresWithSpaces": "Sostituisci i trattini bassi con spazi nei nomi delle note importate",
"import": "Importa",
"failed": "Importazione fallita: {{message}}."
"failed": "Importazione fallita: {{message}}.",
"importZipRecommendation": "Quando si importa un file ZIP, la gerarchia delle note rifletterà la struttura delle sottodirectory all'interno dell'archivio."
},
"include_note": {
"dialog_title": "Includi nota",
@@ -1478,7 +1477,7 @@
},
"attachment_list": {
"open_help_page": "Apri la pagina di aiuto sugli allegati",
"owning_note": "Nota di proprietà:",
"owning_note": "Nota di proprietà: ",
"upload_attachments": "Carica allegati",
"no_attachments": "Questa nota non ha allegati."
},
@@ -1710,7 +1709,7 @@
"for_more_info": "per maggiori informazioni.",
"protected_session_timeout_label": "Timeout della sessione protetta:",
"reset_confirmation": "Reimpostando la password perderai per sempre l'accesso a tutte le tue note protette. Vuoi davvero reimpostare la password?",
"reset_success_message": "La password è stata reimpostata. Imposta una nuova password.",
"reset_success_message": "La password è stata resettata. Imposta una nuova password",
"change_password_heading": "Cambiare la password",
"set_password_heading": "Imposta password",
"set_password": "Imposta password",
@@ -1740,14 +1739,14 @@
"recovery_keys_no_key_set": "Nessun codice di ripristino impostato",
"recovery_keys_generate": "Genera codici di recupero",
"recovery_keys_regenerate": "Rigenera i codici di recupero",
"recovery_keys_used": "Utilizzato: {{data}}",
"recovery_keys_used": "Utilizzato: {{date}}",
"recovery_keys_unused": "Il codice di ripristino {{index}} non è utilizzato",
"oauth_title": "OAuth/OpenID",
"oauth_description": "OpenID è un metodo standardizzato che ti consente di accedere ai siti web utilizzando un account di un altro servizio, come Google, per verificare la tua identità. L'emittente predefinito è Google, ma puoi cambiarlo con qualsiasi altro provider OpenID. Per ulteriori informazioni, consulta <a href=\"#root/_hidden/_help/_help_Otzi9La2YAUX/_help_WOcw2SLH6tbX/_help_7DAiwaf8Z7Rz\">qui</a>. Segui queste <a href=\"https://developers.google.com/identity/openid-connect/openid-connect\">istruzioni</a> per configurare un servizio OpenID tramite Google.",
"oauth_description_warning": "Per abilitare OAuth/OpenID, è necessario impostare l'URL di base di OAuth/OpenID, l'ID client e il segreto client nel file config.ini e riavviare l'applicazione. Per impostare le variabili d'ambiente, impostare TRILIUM_OAUTH_BASE_URL, TRILIUM_OAUTH_CLIENT_ID e TRILIUM_OAUTH_CLIENT_SECRET.",
"oauth_missing_vars": "Impostazioni mancanti: {{-variabili}}",
"oauth_user_account": "Account utente:",
"oauth_user_email": "Email utente:",
"oauth_missing_vars": "Impostazioni mancanti: {{-variables}}",
"oauth_user_account": "Account utente: ",
"oauth_user_email": "Email utente: ",
"oauth_user_not_logged_in": "Non hai effettuato l'accesso!"
},
"spellcheck": {
@@ -1756,7 +1755,7 @@
"enable": "Abilita il controllo ortografico",
"language_code_label": "Codice/i della lingua",
"language_code_placeholder": "ad esempio \"en-US\", \"de-AT\"",
"multiple_languages_info": "È possibile separare più lingue con una virgola, ad esempio \"en-US, de-DE, cs\".",
"multiple_languages_info": "È possibile separare più lingue con una virgola, ad esempio \"en-US, de-DE, cs\". ",
"available_language_codes_label": "Codici lingua disponibili:",
"restart-required": "Le modifiche alle opzioni di controllo ortografico avranno effetto dopo il riavvio dell'applicazione."
},
@@ -1858,7 +1857,9 @@
"window-on-top": "Mantieni la finestra in primo piano"
},
"note_detail": {
"could_not_find_typewidget": "Impossibile trovare typeWidget per il tipo '{{type}}'"
"could_not_find_typewidget": "Impossibile trovare typeWidget per il tipo '{{type}}'",
"printing": "Stampa in corso...",
"printing_pdf": "Esportazione in PDF in corso..."
},
"note_title": {
"placeholder": "scrivi qui il titolo della nota..."
@@ -1909,7 +1910,7 @@
},
"frontend_script_api": {
"async_warning": "Stai passando una funzione asincrona a `api.runOnBackend()` che probabilmente non funzionerà come previsto.\\nRendi la funzione sincrona (rimuovendo la parola chiave `async`) oppure usa `api.runAsyncOnBackendWithManualTransactionHandling()`.",
"sync_warning": "Stai passando una funzione sincrona a `api.runAsyncOnBackendWithManualTransactionHandling()`, mentre probabilmente dovresti usare `api.runOnBackend()`."
"sync_warning": "Stai passando una funzione sincrona a `api.runAsyncOnBackendWithManualTransactionHandling()`, \\nmentre probabilmente dovresti usare `api.runOnBackend()`."
},
"ws": {
"sync-check-failed": "Controllo di sincronizzazione fallito!",
@@ -2044,7 +2045,7 @@
"slide-overview": "Attiva/disattiva una panoramica delle diapositive"
},
"command_palette": {
"tree-action-name": "Albero: {{nome}}",
"tree-action-name": "Albero: {{name}}",
"export_note_title": "Nota di esportazione",
"export_note_description": "Esporta la nota corrente",
"show_attachments_title": "Mostra allegati",
@@ -2087,4 +2088,4 @@
"collections": {
"rendering_error": "Impossibile mostrare il contenuto a causa di un errore."
}
}
}

View File

@@ -73,7 +73,7 @@
},
"left_pane_toggle": {
"show_panel": "パネルを表示",
"hide_panel": "パネルを隠す"
"hide_panel": "パネルを非表示"
},
"move_pane_button": {
"move_left": "左に移動",
@@ -741,7 +741,7 @@
"new-column": "新しい列",
"sort-column-by": "\"{{title}}\" で並べ替え",
"sort-column-clear": "並べ替えをクリア",
"hide-column": "列 \"{{title}}\" を隠す",
"hide-column": "列 \"{{title}}\" を非表示",
"show-hide-columns": "列を表示/非表示",
"row-insert-above": "上に行を挿入",
"row-insert-below": "下に行を挿入",
@@ -1200,7 +1200,7 @@
"collapse-title": "ノートツリーを折りたたむ",
"scroll-active-title": "アクティブノートまでスクロール",
"tree-settings-title": "ツリーの設定",
"hide-archived-notes": "アーカイブノートを隠す",
"hide-archived-notes": "アーカイブノートを非表示",
"automatically-collapse-notes": "ノートを自動的に折りたたむ",
"automatically-collapse-notes-title": "一定期間使用されないと、ツリーを整理するためにノートは折りたたまれます。",
"save-changes": "変更を保存して適用",

View File

@@ -184,7 +184,8 @@
},
"import-status": "匯入狀態",
"in-progress": "正在匯入:{{progress}}",
"successful": "匯入成功。"
"successful": "匯入成功。",
"importZipRecommendation": "匯入 ZIP 檔案時,筆記層級將反映壓縮檔內的子目錄結構。"
},
"include_note": {
"dialog_title": "內嵌筆記",

View File

@@ -11,7 +11,8 @@
},
"add_link": {
"add_link": "Thêm liên kết",
"button_add_link": "Thêm liên kết"
"button_add_link": "Thêm liên kết",
"help_on_links": "Trợ giúp về các liên kết"
},
"bulk_actions": {
"other": "Khác"
@@ -41,7 +42,13 @@
"message": "Đã xảy ra lỗi nghiêm trọng ngăn ứng dụng client khởi động\n\n{{message}}\n\nĐiều này có khả năng bị gây ra bởi một script hoạt động không như mong đợi. Hãy thử khởi động ứng dụng ở chế độ an toàn và giải quyết vấn đề."
},
"widget-error": {
"title": "Khởi tạo widget thất bại"
"title": "Khởi tạo widget thất bại",
"message-custom": "Tiện ích tùy chỉnh từ ghi chú với ID \"{{id}}\", tiêu đề \"{{title}}\" không thể khởi tạo vì:\n\n{{message}}",
"message-unknown": "Tiện ích chưa biết không thể được khởi tạo vì:\n\n{{message}}"
},
"bundle-error": {
"title": "Tải script tùy chọn thất bại",
"message": "Script từ ghi chú ID \"{{id}}\", tiêu đề \"{{title}}\" không thể chạy được vì:\n\n{{message}}"
}
},
"import": {

View File

@@ -1,4 +1,5 @@
import { useNoteContext, useTriliumOption } from "../react/hooks";
import { useTriliumOption } from "../react/hooks";
import { TabContext } from "./ribbon-interface";
/**
* Handles the editing toolbar when the CKEditor is in decoupled mode.
@@ -6,19 +7,13 @@ import { useNoteContext, useTriliumOption } from "../react/hooks";
* This toolbar is only enabled if the user has selected the classic CKEditor.
*
* The ribbon item is active by default for text notes, as long as they are not in read-only mode.
*
*
* ! The toolbar is not only used in the ribbon, but also in the quick edit feature.
*/
export default function FormattingToolbar({ hidden }: { hidden?: boolean }) {
export default function FormattingToolbar({ hidden }: TabContext) {
const [ textNoteEditorType ] = useTriliumOption("textNoteEditorType");
return (textNoteEditorType === "ckeditor-classic" &&
<div className={`classic-toolbar-widget ${hidden ? "hidden-ext" : ""}`} />
)
};
export function PopupEditorFormattingToolbar() {
// TODO: Integrate this directly once we migrate away from class components.
const { note } = useNoteContext();
return <FormattingToolbar hidden={note?.type !== "text"} />;
}

View File

@@ -1,163 +1,15 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
import { t } from "../../services/i18n";
import { useNoteContext, useNoteProperty, useStaticTooltipWithKeyboardShortcut, useTriliumEvents } from "../react/hooks";
import "./style.css";
import { VNode } from "preact";
import BasicPropertiesTab from "./BasicPropertiesTab";
import FormattingToolbar from "./FormattingToolbar";
import { numberObjectsInPlace } from "../../services/utils";
import { TabContext } from "./ribbon-interface";
import options from "../../services/options";
import { EventNames } from "../../components/app_context";
import FNote from "../../entities/fnote";
import ScriptTab from "./ScriptTab";
import EditedNotesTab from "./EditedNotesTab";
import NotePropertiesTab from "./NotePropertiesTab";
import NoteInfoTab from "./NoteInfoTab";
import SimilarNotesTab from "./SimilarNotesTab";
import FilePropertiesTab from "./FilePropertiesTab";
import ImagePropertiesTab from "./ImagePropertiesTab";
import NotePathsTab from "./NotePathsTab";
import NoteMapTab from "./NoteMapTab";
import OwnedAttributesTab from "./OwnedAttributesTab";
import InheritedAttributesTab from "./InheritedAttributesTab";
import CollectionPropertiesTab from "./CollectionPropertiesTab";
import SearchDefinitionTab from "./SearchDefinitionTab";
import NoteActions from "./NoteActions";
import { KeyboardActionNames } from "@triliumnext/commons";
import { RIBBON_TAB_DEFINITIONS } from "./RibbonDefinition";
import { TabConfiguration, TitleContext } from "./ribbon-interface";
interface TitleContext {
note: FNote | null | undefined;
}
interface TabConfiguration {
title: string | ((context: TitleContext) => string);
icon: string;
content: (context: TabContext) => VNode | false;
show: boolean | ((context: TitleContext) => boolean | null | undefined);
toggleCommand?: KeyboardActionNames;
activate?: boolean | ((context: TitleContext) => boolean);
/**
* By default the tab content will not be rendered unless the tab is active (i.e. selected by the user). Setting to `true` will ensure that the tab is rendered even when inactive, for cases where the tab needs to be accessible at all times (e.g. for the detached editor toolbar) or if event handling is needed.
*/
stayInDom?: boolean;
}
const TAB_CONFIGURATION = numberObjectsInPlace<TabConfiguration>([
{
title: t("classic_editor_toolbar.title"),
icon: "bx bx-text",
show: ({ note }) => note?.type === "text" && options.get("textNoteEditorType") === "ckeditor-classic",
toggleCommand: "toggleRibbonTabClassicEditor",
content: FormattingToolbar,
activate: true,
stayInDom: true
},
{
title: ({ note }) => note?.isTriliumSqlite() ? t("script_executor.query") : t("script_executor.script"),
icon: "bx bx-play",
content: ScriptTab,
activate: true,
show: ({ note }) => note &&
(note.isTriliumScript() || note.isTriliumSqlite()) &&
(note.hasLabel("executeDescription") || note.hasLabel("executeButton"))
},
{
title: t("search_definition.search_parameters"),
icon: "bx bx-search",
content: SearchDefinitionTab,
activate: true,
show: ({ note }) => note?.type === "search"
},
{
title: t("edited_notes.title"),
icon: "bx bx-calendar-edit",
content: EditedNotesTab,
show: ({ note }) => note?.hasOwnedLabel("dateNote"),
activate: ({ note }) => (note?.getPromotedDefinitionAttributes().length === 0 || !options.is("promotedAttributesOpenInRibbon")) && options.is("editedNotesOpenInRibbon")
},
{
title: t("book_properties.book_properties"),
icon: "bx bx-book",
content: CollectionPropertiesTab,
show: ({ note }) => note?.type === "book" || note?.type === "search",
toggleCommand: "toggleRibbonTabBookProperties"
},
{
title: t("note_properties.info"),
icon: "bx bx-info-square",
content: NotePropertiesTab,
show: ({ note }) => !!note?.getLabelValue("pageUrl"),
activate: true
},
{
title: t("file_properties.title"),
icon: "bx bx-file",
content: FilePropertiesTab,
show: ({ note }) => note?.type === "file",
toggleCommand: "toggleRibbonTabFileProperties",
activate: ({ note }) => note?.mime !== "application/pdf"
},
{
title: t("image_properties.title"),
icon: "bx bx-image",
content: ImagePropertiesTab,
show: ({ note }) => note?.type === "image",
toggleCommand: "toggleRibbonTabImageProperties",
activate: true,
},
{
// BasicProperties
title: t("basic_properties.basic_properties"),
icon: "bx bx-slider",
content: BasicPropertiesTab,
show: ({note}) => !note?.isLaunchBarConfig(),
toggleCommand: "toggleRibbonTabBasicProperties"
},
{
title: t("owned_attribute_list.owned_attributes"),
icon: "bx bx-list-check",
content: OwnedAttributesTab,
show: ({note}) => !note?.isLaunchBarConfig(),
toggleCommand: "toggleRibbonTabOwnedAttributes",
stayInDom: true
},
{
title: t("inherited_attribute_list.title"),
icon: "bx bx-list-plus",
content: InheritedAttributesTab,
show: ({note}) => !note?.isLaunchBarConfig(),
toggleCommand: "toggleRibbonTabInheritedAttributes"
},
{
title: t("note_paths.title"),
icon: "bx bx-collection",
content: NotePathsTab,
show: true,
toggleCommand: "toggleRibbonTabNotePaths"
},
{
title: t("note_map.title"),
icon: "bx bxs-network-chart",
content: NoteMapTab,
show: true,
toggleCommand: "toggleRibbonTabNoteMap"
},
{
title: t("similar_notes.title"),
icon: "bx bx-bar-chart",
show: ({ note }) => note?.type !== "search" && !note?.isLabelTruthy("similarNotesWidgetDisabled"),
content: SimilarNotesTab,
toggleCommand: "toggleRibbonTabSimilarNotes"
},
{
title: t("note_info_widget.title"),
icon: "bx bx-info-circle",
show: ({ note }) => !!note,
content: NoteInfoTab,
toggleCommand: "toggleRibbonTabNoteInfo"
}
]);
const TAB_CONFIGURATION = numberObjectsInPlace<TabConfiguration>(RIBBON_TAB_DEFINITIONS);
export default function Ribbon() {
const { note, ntxId, hoistedNoteId, notePath, noteContext, componentId } = useNoteContext();

View File

@@ -0,0 +1,134 @@
import ScriptTab from "./ScriptTab";
import EditedNotesTab from "./EditedNotesTab";
import NotePropertiesTab from "./NotePropertiesTab";
import NoteInfoTab from "./NoteInfoTab";
import SimilarNotesTab from "./SimilarNotesTab";
import FilePropertiesTab from "./FilePropertiesTab";
import ImagePropertiesTab from "./ImagePropertiesTab";
import NotePathsTab from "./NotePathsTab";
import NoteMapTab from "./NoteMapTab";
import OwnedAttributesTab from "./OwnedAttributesTab";
import InheritedAttributesTab from "./InheritedAttributesTab";
import CollectionPropertiesTab from "./CollectionPropertiesTab";
import SearchDefinitionTab from "./SearchDefinitionTab";
import BasicPropertiesTab from "./BasicPropertiesTab";
import FormattingToolbar from "./FormattingToolbar";
import options from "../../services/options";
import { t } from "../../services/i18n";
import { TabConfiguration } from "./ribbon-interface";
export const RIBBON_TAB_DEFINITIONS: TabConfiguration[] = [
{
title: t("classic_editor_toolbar.title"),
icon: "bx bx-text",
show: ({ note }) => note?.type === "text" && options.get("textNoteEditorType") === "ckeditor-classic",
toggleCommand: "toggleRibbonTabClassicEditor",
content: FormattingToolbar,
activate: true,
stayInDom: true
},
{
title: ({ note }) => note?.isTriliumSqlite() ? t("script_executor.query") : t("script_executor.script"),
icon: "bx bx-play",
content: ScriptTab,
activate: true,
show: ({ note }) => note &&
(note.isTriliumScript() || note.isTriliumSqlite()) &&
(note.hasLabel("executeDescription") || note.hasLabel("executeButton"))
},
{
title: t("search_definition.search_parameters"),
icon: "bx bx-search",
content: SearchDefinitionTab,
activate: true,
show: ({ note }) => note?.type === "search"
},
{
title: t("edited_notes.title"),
icon: "bx bx-calendar-edit",
content: EditedNotesTab,
show: ({ note }) => note?.hasOwnedLabel("dateNote"),
activate: ({ note }) => (note?.getPromotedDefinitionAttributes().length === 0 || !options.is("promotedAttributesOpenInRibbon")) && options.is("editedNotesOpenInRibbon")
},
{
title: t("book_properties.book_properties"),
icon: "bx bx-book",
content: CollectionPropertiesTab,
show: ({ note }) => note?.type === "book" || note?.type === "search",
toggleCommand: "toggleRibbonTabBookProperties"
},
{
title: t("note_properties.info"),
icon: "bx bx-info-square",
content: NotePropertiesTab,
show: ({ note }) => !!note?.getLabelValue("pageUrl"),
activate: true
},
{
title: t("file_properties.title"),
icon: "bx bx-file",
content: FilePropertiesTab,
show: ({ note }) => note?.type === "file",
toggleCommand: "toggleRibbonTabFileProperties",
activate: ({ note }) => note?.mime !== "application/pdf"
},
{
title: t("image_properties.title"),
icon: "bx bx-image",
content: ImagePropertiesTab,
show: ({ note }) => note?.type === "image",
toggleCommand: "toggleRibbonTabImageProperties",
activate: true,
},
{
// BasicProperties
title: t("basic_properties.basic_properties"),
icon: "bx bx-slider",
content: BasicPropertiesTab,
show: ({note}) => !note?.isLaunchBarConfig(),
toggleCommand: "toggleRibbonTabBasicProperties"
},
{
title: t("owned_attribute_list.owned_attributes"),
icon: "bx bx-list-check",
content: OwnedAttributesTab,
show: ({note}) => !note?.isLaunchBarConfig(),
toggleCommand: "toggleRibbonTabOwnedAttributes",
stayInDom: true
},
{
title: t("inherited_attribute_list.title"),
icon: "bx bx-list-plus",
content: InheritedAttributesTab,
show: ({note}) => !note?.isLaunchBarConfig(),
toggleCommand: "toggleRibbonTabInheritedAttributes"
},
{
title: t("note_paths.title"),
icon: "bx bx-collection",
content: NotePathsTab,
show: true,
toggleCommand: "toggleRibbonTabNotePaths"
},
{
title: t("note_map.title"),
icon: "bx bxs-network-chart",
content: NoteMapTab,
show: true,
toggleCommand: "toggleRibbonTabNoteMap"
},
{
title: t("similar_notes.title"),
icon: "bx bx-bar-chart",
show: ({ note }) => note?.type !== "search" && !note?.isLabelTruthy("similarNotesWidgetDisabled"),
content: SimilarNotesTab,
toggleCommand: "toggleRibbonTabSimilarNotes"
},
{
title: t("note_info_widget.title"),
icon: "bx bx-info-circle",
show: ({ note }) => !!note,
content: NoteInfoTab,
toggleCommand: "toggleRibbonTabNoteInfo"
}
];

View File

@@ -115,7 +115,7 @@ function SearchOption({ note, title, titleIcon, children, help, attributeName, a
additionalAttributesToDelete?: { type: "label" | "relation", name: string }[]
}) {
return (
<tr>
<tr className={attributeName}>
<td className="title-column">
{titleIcon && <><Icon icon={titleIcon} />{" "}</>}
{title}

View File

@@ -0,0 +1,174 @@
.search-setting-table {
margin-top: 0;
margin-bottom: 7px;
width: 100%;
border-collapse: separate;
border-spacing: 10px;
}
.search-setting-table div {
white-space: nowrap;
}
.search-setting-table .title-column {
/* minimal width so that table remains static sized and most space remains for middle column with settings */
width: 50px;
white-space: nowrap;
}
.search-setting-table .button-column {
/* minimal width so that table remains static sized and most space remains for middle column with settings */
width: 50px;
white-space: nowrap;
text-align: end;
vertical-align: middle;
}
.search-setting-table .button-column .dropdown {
display: inline-block !important;
}
.search-setting-table .button-column .dropdown-menu {
white-space: normal;
}
.search-setting-table .button-column > * {
vertical-align: middle;
}
.attribute-list hr {
height: 1px;
border-color: var(--main-border-color);
position: relative;
top: 4px;
margin-top: 5px;
margin-bottom: 0;
}
.search-definition-widget input:invalid {
border: 3px solid red;
}
.add-search-option button {
margin: 3px;
}
.dropdown-header {
background-color: var(--accented-background-color);
}
.search-actions-container {
display: flex;
justify-content: space-evenly;
}
body.mobile .search-definition-widget {
contain: none;
}
@media (max-width: 720px) {
.search-setting-table {
display: block;
font-size: 0.9em;
}
.search-setting-table tr {
padding: 0.5em 0;
border-bottom: 1px solid var(--main-border-color);
}
.search-setting-table tr,
.search-setting-table td {
display: block;
}
.search-setting-table tbody {
display: block;
padding: 0 1em;
}
.search-setting-table tbody:first-of-type {
display: block;
overflow: auto;
}
.search-setting-table .add-search-option {
display: flex;
}
.search-setting-table .add-search-option button {
font-size: 0.75em;
}
.search-options tr,
.action-options tr {
display: flex;
align-items: center;
}
.action-options tr > td > div {
flex-wrap: wrap;
gap: 0.5em 0;
}
.action-options input {
max-width: 75vw;
}
.search-setting-table .title-column {
width: unset;
margin-right: 0.5em;
min-width: 30%;
flex-shrink: 0;
}
.search-setting-table .button-column {
flex-grow: 1;
justify-content: end;
overflow: hidden;
flex-shrink: 0;
}
.search-setting-table .button-column .bx-help-circle {
display: none;
}
.search-setting-table tr.orderBy td:nth-of-type(2) {
display: flex;
flex-direction: column;
overflow: hidden;
gap: 0.5em;
}
.search-setting-table tr.searchString td:nth-of-type(2) {
flex-grow: 1;
}
.search-setting-table tr.searchString .button-column {
flex-grow: 0;
flex-shrink: 0;
width: 64px;
}
.search-setting-table tr.ancestor > td > div {
flex-direction: column;
align-items: flex-start !important;
}
.search-actions tr {
border-bottom: 0;
}
.search-actions-container {
align-items: center;
justify-content: center !important;
}
.search-result-widget,
.note-list.list-view,
.note-list-wrapper {
overflow: unset;
height: unset !important;
}
}

View File

@@ -20,8 +20,9 @@ import bulk_action, { ACTION_GROUPS } from "../../services/bulk_action";
import { FormListHeader, FormListItem } from "../react/FormList";
import RenameNoteBulkAction from "../bulk_actions/note/rename_note";
import { getErrorMessage } from "../../services/utils";
import "./SearchDefinitionTab.css";
export default function SearchDefinitionTab({ note, ntxId }: TabContext) {
export default function SearchDefinitionTab({ note, ntxId, hidden }: TabContext) {
const parentComponent = useContext(ParentComponent);
const [ searchOptions, setSearchOptions ] = useState<{ availableOptions: SearchOption[], activeOptions: SearchOption[] }>();
const [ error, setError ] = useState<{ message: string }>();
@@ -75,7 +76,7 @@ export default function SearchDefinitionTab({ note, ntxId }: TabContext) {
return (
<div className="search-definition-widget">
<div className="search-settings">
{note &&
{note && !hidden &&
<table className="search-setting-table">
<tbody>
<tr>
@@ -110,10 +111,10 @@ export default function SearchDefinitionTab({ note, ntxId }: TabContext) {
})}
</tbody>
<BulkActionsList note={note} />
<tbody>
<tbody className="search-actions">
<tr>
<td colSpan={3}>
<div style={{ display: "flex", justifyContent: "space-evenly" }}>
<div className="search-actions-container">
<Button
icon="bx bx-search"
text={t("search_definition.search_button")}

View File

@@ -0,0 +1,43 @@
import { ComponentChildren } from "preact";
import { useNoteContext } from "../../react/hooks";
import { TabContext, TitleContext } from "../ribbon-interface";
import { useEffect, useMemo, useState } from "preact/hooks";
import { RIBBON_TAB_DEFINITIONS } from "../RibbonDefinition";
interface StandaloneRibbonAdapterProps {
component: (props: TabContext) => ComponentChildren;
}
/**
* Takes in any ribbon tab component and renders it in standalone mod using the note context, thus requiring no inputs.
* Especially useful on mobile to detach components that would normally fit in the ribbon.
*/
export default function StandaloneRibbonAdapter({ component }: StandaloneRibbonAdapterProps) {
const Component = component;
const { note, ntxId, hoistedNoteId, notePath, noteContext, componentId } = useNoteContext();
const definition = useMemo(() => RIBBON_TAB_DEFINITIONS.find(def => def.content === component), [ component ]);
const [ shown, setShown ] = useState(unwrapShown(definition?.show, { note }));
useEffect(() => {
setShown(unwrapShown(definition?.show, { note }));
}, [ note ]);
return (
<Component
note={note}
hidden={!shown}
ntxId={ntxId}
hoistedNoteId={hoistedNoteId}
notePath={notePath}
noteContext={noteContext}
componentId={componentId}
activate={() => {}}
/>
);
}
function unwrapShown(value: boolean | ((context: TitleContext) => boolean | null | undefined) | undefined, context: TitleContext) {
if (!value) return true;
if (typeof value === "boolean") return value;
return !!value(context);
}

View File

@@ -1,5 +1,7 @@
import { KeyboardActionNames } from "@triliumnext/commons";
import NoteContext from "../../components/note_context";
import FNote from "../../entities/fnote";
import { VNode } from "preact";
export interface TabContext {
note: FNote | null | undefined;
@@ -11,3 +13,20 @@ export interface TabContext {
componentId: string;
activate(): void;
}
export interface TitleContext {
note: FNote | null | undefined;
}
export interface TabConfiguration {
title: string | ((context: TitleContext) => string);
icon: string;
content: (context: TabContext) => VNode | false;
show: boolean | ((context: TitleContext) => boolean | null | undefined);
toggleCommand?: KeyboardActionNames;
activate?: boolean | ((context: TitleContext) => boolean);
/**
* By default the tab content will not be rendered unless the tab is active (i.e. selected by the user). Setting to `true` will ensure that the tab is rendered even when inactive, for cases where the tab needs to be accessible at all times (e.g. for the detached editor toolbar) or if event handling is needed.
*/
stayInDom?: boolean;
}

View File

@@ -376,67 +376,6 @@ body[dir=rtl] .attribute-list-editor {
}
/* #endregion */
/* #region Search definition */
.search-setting-table {
margin-top: 0;
margin-bottom: 7px;
width: 100%;
border-collapse: separate;
border-spacing: 10px;
}
.search-setting-table div {
white-space: nowrap;
}
.search-setting-table .title-column {
/* minimal width so that table remains static sized and most space remains for middle column with settings */
width: 50px;
white-space: nowrap;
}
.search-setting-table .button-column {
/* minimal width so that table remains static sized and most space remains for middle column with settings */
width: 50px;
white-space: nowrap;
text-align: end;
vertical-align: middle;
}
.search-setting-table .button-column .dropdown {
display: inline-block !important;
}
.search-setting-table .button-column .dropdown-menu {
white-space: normal;
}
.search-setting-table .button-column > * {
vertical-align: middle;
}
.attribute-list hr {
height: 1px;
border-color: var(--main-border-color);
position: relative;
top: 4px;
margin-top: 5px;
margin-bottom: 0;
}
.search-definition-widget input:invalid {
border: 3px solid red;
}
.add-search-option button {
margin: 3px;
}
.dropdown-header {
background-color: var(--accented-background-color);
}
/* #endregion */
/* #region Note actions */
.note-actions {
width: 35px;

View File

@@ -146,9 +146,228 @@ CREATE INDEX IDX_notes_blobId on notes (blobId);
CREATE INDEX IDX_revisions_blobId on revisions (blobId);
CREATE INDEX IDX_attachments_blobId on attachments (blobId);
-- Strategic Performance Indexes from migration 234
-- NOTES TABLE INDEXES
CREATE INDEX IDX_notes_search_composite
ON notes (isDeleted, type, mime, dateModified DESC);
CREATE INDEX IDX_notes_metadata_covering
ON notes (noteId, isDeleted, type, mime, title, dateModified, isProtected);
CREATE INDEX IDX_notes_protected_deleted
ON notes (isProtected, isDeleted)
WHERE isProtected = 1;
-- BRANCHES TABLE INDEXES
CREATE INDEX IDX_branches_tree_traversal
ON branches (parentNoteId, isDeleted, notePosition);
CREATE INDEX IDX_branches_covering
ON branches (noteId, parentNoteId, isDeleted, notePosition, prefix);
CREATE INDEX IDX_branches_note_parents
ON branches (noteId, isDeleted)
WHERE isDeleted = 0;
-- ATTRIBUTES TABLE INDEXES
CREATE INDEX IDX_attributes_search_composite
ON attributes (name, value, isDeleted);
CREATE INDEX IDX_attributes_covering
ON attributes (noteId, name, value, type, isDeleted, position);
CREATE INDEX IDX_attributes_inheritable
ON attributes (isInheritable, isDeleted)
WHERE isInheritable = 1 AND isDeleted = 0;
CREATE INDEX IDX_attributes_labels
ON attributes (type, name, value)
WHERE type = 'label' AND isDeleted = 0;
CREATE INDEX IDX_attributes_relations
ON attributes (type, name, value)
WHERE type = 'relation' AND isDeleted = 0;
-- BLOBS TABLE INDEXES
CREATE INDEX IDX_blobs_content_size
ON blobs (blobId, LENGTH(content));
-- ATTACHMENTS TABLE INDEXES
CREATE INDEX IDX_attachments_composite
ON attachments (ownerId, role, isDeleted, position);
-- REVISIONS TABLE INDEXES
CREATE INDEX IDX_revisions_note_date
ON revisions (noteId, utcDateCreated DESC);
-- ENTITY_CHANGES TABLE INDEXES
CREATE INDEX IDX_entity_changes_sync
ON entity_changes (isSynced, utcDateChanged);
CREATE INDEX IDX_entity_changes_component
ON entity_changes (componentId, utcDateChanged DESC);
-- RECENT_NOTES TABLE INDEXES
CREATE INDEX IDX_recent_notes_date
ON recent_notes (utcDateCreated DESC);
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
data TEXT,
expires INTEGER
);
-- FTS5 Full-Text Search Support
-- Create FTS5 virtual table with trigram tokenizer
-- Trigram tokenizer provides language-agnostic substring matching:
-- 1. Fast substring matching (50-100x speedup for LIKE queries without wildcards)
-- 2. Case-insensitive search without custom collation
-- 3. No language-specific stemming assumptions (works for all languages)
-- 4. Boolean operators (AND, OR, NOT) and phrase matching with quotes
--
-- IMPORTANT: Trigram requires minimum 3-character tokens for matching
-- detail='none' reduces index size by ~50% while maintaining MATCH/rank performance
-- (loses position info for highlight() function, but snippet() still works)
CREATE VIRTUAL TABLE notes_fts USING fts5(
noteId UNINDEXED,
title,
content,
tokenize = 'trigram',
detail = 'none'
);
-- Triggers to keep FTS table synchronized with notes
-- IMPORTANT: These triggers must handle all SQL operations including:
-- - Regular INSERT/UPDATE/DELETE
-- - INSERT OR REPLACE
-- - INSERT ... ON CONFLICT ... DO UPDATE (upsert)
-- - Cases where notes are created before blobs (import scenarios)
-- Trigger for INSERT operations on notes
-- Handles: INSERT, INSERT OR REPLACE, INSERT OR IGNORE, and the INSERT part of upsert
CREATE TRIGGER notes_fts_insert
AFTER INSERT ON notes
WHEN NEW.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND NEW.isDeleted = 0
AND NEW.isProtected = 0
BEGIN
-- First delete any existing FTS entry (in case of INSERT OR REPLACE)
DELETE FROM notes_fts WHERE noteId = NEW.noteId;
-- Then insert the new entry, using LEFT JOIN to handle missing blobs
INSERT INTO notes_fts (noteId, title, content)
SELECT
NEW.noteId,
NEW.title,
COALESCE(b.content, '') -- Use empty string if blob doesn't exist yet
FROM (SELECT NEW.noteId) AS note_select
LEFT JOIN blobs b ON b.blobId = NEW.blobId;
END;
-- Trigger for UPDATE operations on notes table
-- Handles: Regular UPDATE and the UPDATE part of upsert (ON CONFLICT DO UPDATE)
-- Fires for ANY update to searchable notes to ensure FTS stays in sync
CREATE TRIGGER notes_fts_update
AFTER UPDATE ON notes
WHEN NEW.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
-- Fire on any change, not just specific columns, to handle all upsert scenarios
BEGIN
-- Always delete the old entry
DELETE FROM notes_fts WHERE noteId = NEW.noteId;
-- Insert new entry if note is not deleted and not protected
INSERT INTO notes_fts (noteId, title, content)
SELECT
NEW.noteId,
NEW.title,
COALESCE(b.content, '') -- Use empty string if blob doesn't exist yet
FROM (SELECT NEW.noteId) AS note_select
LEFT JOIN blobs b ON b.blobId = NEW.blobId
WHERE NEW.isDeleted = 0
AND NEW.isProtected = 0;
END;
-- Trigger for UPDATE operations on blobs
-- Handles: Regular UPDATE and the UPDATE part of upsert (ON CONFLICT DO UPDATE)
-- IMPORTANT: Uses INSERT OR REPLACE for efficiency with deduplicated blobs
CREATE TRIGGER notes_fts_blob_update
AFTER UPDATE ON blobs
BEGIN
-- Use INSERT OR REPLACE for atomic update of all notes sharing this blob
-- This is more efficient than DELETE + INSERT when many notes share the same blob
INSERT OR REPLACE INTO notes_fts (noteId, title, content)
SELECT
n.noteId,
n.title,
NEW.content
FROM notes n
WHERE n.blobId = NEW.blobId
AND n.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND n.isDeleted = 0
AND n.isProtected = 0;
END;
-- Trigger for DELETE operations
CREATE TRIGGER notes_fts_delete
AFTER DELETE ON notes
BEGIN
DELETE FROM notes_fts WHERE noteId = OLD.noteId;
END;
-- Trigger for soft delete (isDeleted = 1)
CREATE TRIGGER notes_fts_soft_delete
AFTER UPDATE ON notes
WHEN OLD.isDeleted = 0 AND NEW.isDeleted = 1
BEGIN
DELETE FROM notes_fts WHERE noteId = NEW.noteId;
END;
-- Trigger for notes becoming protected
-- Remove from FTS when a note becomes protected
CREATE TRIGGER notes_fts_protect
AFTER UPDATE ON notes
WHEN OLD.isProtected = 0 AND NEW.isProtected = 1
BEGIN
DELETE FROM notes_fts WHERE noteId = NEW.noteId;
END;
-- Trigger for notes becoming unprotected
-- Add to FTS when a note becomes unprotected (if eligible)
CREATE TRIGGER notes_fts_unprotect
AFTER UPDATE ON notes
WHEN OLD.isProtected = 1 AND NEW.isProtected = 0
AND NEW.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND NEW.isDeleted = 0
BEGIN
DELETE FROM notes_fts WHERE noteId = NEW.noteId;
INSERT INTO notes_fts (noteId, title, content)
SELECT
NEW.noteId,
NEW.title,
COALESCE(b.content, '')
FROM (SELECT NEW.noteId) AS note_select
LEFT JOIN blobs b ON b.blobId = NEW.blobId;
END;
-- Trigger for INSERT operations on blobs
-- Handles: INSERT, INSERT OR REPLACE, and the INSERT part of upsert
-- Updates all notes that reference this blob (common during import and deduplication)
CREATE TRIGGER notes_fts_blob_insert
AFTER INSERT ON blobs
BEGIN
-- Use INSERT OR REPLACE to handle both new and existing FTS entries
-- This is crucial for blob deduplication where multiple notes may already
-- exist that reference this blob before the blob itself is created
INSERT OR REPLACE INTO notes_fts (noteId, title, content)
SELECT
n.noteId,
n.title,
NEW.content
FROM notes n
WHERE n.blobId = NEW.blobId
AND n.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND n.isDeleted = 0
AND n.isProtected = 0;
END;

View File

@@ -274,7 +274,8 @@
"export_filter": "Document PDF (*.pdf)",
"unable-to-export-message": "La note actuelle n'a pas pu être exportée en format PDF.",
"unable-to-export-title": "Impossible d'exporter au format PDF",
"unable-to-save-message": "Le fichier sélectionné n'a pas pu être écrit. Réessayez ou sélectionnez une autre destination."
"unable-to-save-message": "Le fichier sélectionné n'a pas pu être écrit. Réessayez ou sélectionnez une autre destination.",
"unable-to-print": "Impossible d'imprimer la note"
},
"tray": {
"tooltip": "Trilium Notes",
@@ -283,7 +284,8 @@
"bookmarks": "Signets",
"today": "Ouvrir la note du journal du jour",
"new-note": "Nouvelle note",
"show-windows": "Afficher les fenêtres"
"show-windows": "Afficher les fenêtres",
"open_new_window": "Ouvrir une nouvelle fenêtre"
},
"migration": {
"old_version": "La migration directe à partir de votre version actuelle n'est pas prise en charge. Veuillez d'abord mettre à jour vers la version v0.60.4, puis vers cette nouvelle version.",
@@ -398,5 +400,42 @@
"instance_already_running": "Une instance est déjà en cours d'execution, ouverture de cette instance à la place."
},
"weekdayNumber": "Semaine {weekNumber}",
"quarterNumber": "Trimestre {quarterNumber}"
"quarterNumber": "Trimestre {quarterNumber}",
"share_theme": {
"site-theme": "Thème du site",
"search_placeholder": "Recherche...",
"image_alt": "Image de l'article",
"last-updated": "Dernière mise à jour le {{- date}}",
"subpages": "Sous-pages:",
"on-this-page": "Sur cette page",
"expand": "Développer"
},
"hidden_subtree_templates": {
"text-snippet": "Extrait de texte",
"description": "Description",
"list-view": "Vue en liste",
"grid-view": "Vue en grille",
"calendar": "Calendrier",
"table": "Tableau",
"geo-map": "Carte géographique",
"start-date": "Date de début",
"end-date": "Date de fin",
"start-time": "Heure de début",
"end-time": "Heure de fin",
"geolocation": "Géolocalisation",
"built-in-templates": "Modèles intégrés",
"board": "Tableau de bord",
"status": "État",
"board_note_first": "Première note",
"board_note_second": "Deuxième note",
"board_note_third": "Troisième note",
"board_status_todo": "A faire",
"board_status_progress": "En cours",
"board_status_done": "Terminé",
"presentation": "Présentation",
"presentation_slide": "Diapositive de présentation",
"presentation_slide_first": "Première diapositive",
"presentation_slide_second": "Deuxième diapositive",
"background": "Arrière-plan"
}
}

View File

@@ -165,7 +165,8 @@
"export_filter": "Documento PDF (*.pdf)",
"unable-to-export-message": "La nota corrente non può essere esportata come PDF.",
"unable-to-export-title": "Impossibile esportare come PDF",
"unable-to-save-message": "Il file selezionato non può essere salvato. Prova di nuovo o seleziona un'altra destinazione."
"unable-to-save-message": "Il file selezionato non può essere salvato. Prova di nuovo o seleziona un'altra destinazione.",
"unable-to-print": "Impossibile stampare la nota"
},
"tray": {
"tooltip": "Trilium Notes",
@@ -430,7 +431,8 @@
"presentation": "Presentazione",
"presentation_slide": "Diapositiva di presentazione",
"presentation_slide_first": "Prima diapositiva",
"presentation_slide_second": "Seconda diapositiva"
"presentation_slide_second": "Seconda diapositiva",
"background": "Contesto"
},
"sql_init": {
"db_not_initialized_desktop": "Database non inizializzato, seguire le istruzioni a schermo.",

View File

@@ -0,0 +1,553 @@
/**
* Migration to add FTS5 full-text search support and strategic performance indexes
*
* This migration:
* 1. Creates an FTS5 virtual table for full-text searching
* 2. Populates it with existing note content
* 3. Creates triggers to keep the FTS table synchronized with note changes
* 4. Adds strategic composite and covering indexes for improved query performance
* 5. Optimizes common query patterns identified through performance analysis
*/
import sql from "../services/sql.js";
import log from "../services/log.js";
export default function addFTS5SearchAndPerformanceIndexes() {
log.info("Starting FTS5 and performance optimization migration...");
// Verify SQLite version supports trigram tokenizer (requires 3.34.0+)
const sqliteVersion = sql.getValue<string>(`SELECT sqlite_version()`);
const [major, minor, patch] = sqliteVersion.split('.').map(Number);
const versionNumber = major * 10000 + minor * 100 + (patch || 0);
const requiredVersion = 3 * 10000 + 34 * 100 + 0; // 3.34.0
if (versionNumber < requiredVersion) {
log.error(`SQLite version ${sqliteVersion} does not support trigram tokenizer (requires 3.34.0+)`);
log.info("Skipping FTS5 trigram migration - will use fallback search implementation");
return; // Skip FTS5 setup, rely on fallback search
}
log.info(`SQLite version ${sqliteVersion} confirmed - trigram tokenizer available`);
// Part 1: FTS5 Setup
log.info("Creating FTS5 virtual table for full-text search...");
// Create FTS5 virtual table
// We store noteId, title, and content for searching
sql.executeScript(`
-- Drop existing FTS table if it exists (for re-running migration in dev)
DROP TABLE IF EXISTS notes_fts;
-- Create FTS5 virtual table with trigram tokenizer
-- Trigram tokenizer provides language-agnostic substring matching:
-- 1. Fast substring matching (50-100x speedup for LIKE queries without wildcards)
-- 2. Case-insensitive search without custom collation
-- 3. No language-specific stemming assumptions (works for all languages)
-- 4. Boolean operators (AND, OR, NOT) and phrase matching with quotes
--
-- IMPORTANT: Trigram requires minimum 3-character tokens for matching
-- detail='none' reduces index size by ~50% while maintaining MATCH/rank performance
-- (loses position info for highlight() function, but snippet() still works)
CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(
noteId UNINDEXED,
title,
content,
tokenize = 'trigram',
detail = 'none'
);
`);
log.info("Populating FTS5 table with existing note content...");
// Populate the FTS table with existing notes
// We only index text-based note types that contain searchable content
const batchSize = 100;
let processedCount = 0;
let hasError = false;
// Wrap entire population process in a transaction for consistency
// If any error occurs, the entire population will be rolled back
try {
sql.transactional(() => {
let offset = 0;
while (true) {
const notes = sql.getRows<{
noteId: string;
title: string;
content: string | null;
}>(`
SELECT
n.noteId,
n.title,
b.content
FROM notes n
LEFT JOIN blobs b ON n.blobId = b.blobId
WHERE n.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND n.isDeleted = 0
AND n.isProtected = 0 -- Skip protected notes - they require special handling
ORDER BY n.noteId
LIMIT ? OFFSET ?
`, [batchSize, offset]);
if (notes.length === 0) {
break;
}
for (const note of notes) {
if (note.content) {
// Process content based on type (simplified for migration)
let processedContent = note.content;
// For HTML content, we'll strip tags in the search service
// For now, just insert the raw content
sql.execute(`
INSERT INTO notes_fts (noteId, title, content)
VALUES (?, ?, ?)
`, [note.noteId, note.title, processedContent]);
processedCount++;
}
}
offset += batchSize;
if (processedCount % 1000 === 0) {
log.info(`Processed ${processedCount} notes for FTS indexing...`);
}
}
});
} catch (error) {
hasError = true;
log.error(`Failed to populate FTS index. Rolling back... ${error}`);
// Clean up partial data if transaction failed
try {
sql.execute("DELETE FROM notes_fts");
} catch (cleanupError) {
log.error(`Failed to clean up FTS table after error: ${cleanupError}`);
}
throw new Error(`FTS5 migration failed during population: ${error}`);
}
log.info(`Completed FTS indexing of ${processedCount} notes`);
// Create triggers to keep FTS table synchronized
log.info("Creating FTS synchronization triggers...");
// Drop all existing triggers first to ensure clean state
sql.execute(`DROP TRIGGER IF EXISTS notes_fts_insert`);
sql.execute(`DROP TRIGGER IF EXISTS notes_fts_update`);
sql.execute(`DROP TRIGGER IF EXISTS notes_fts_delete`);
sql.execute(`DROP TRIGGER IF EXISTS notes_fts_soft_delete`);
sql.execute(`DROP TRIGGER IF EXISTS notes_fts_blob_insert`);
sql.execute(`DROP TRIGGER IF EXISTS notes_fts_blob_update`);
sql.execute(`DROP TRIGGER IF EXISTS notes_fts_protect`);
sql.execute(`DROP TRIGGER IF EXISTS notes_fts_unprotect`);
// Create improved triggers that handle all SQL operations properly
// including INSERT OR REPLACE and INSERT ... ON CONFLICT ... DO UPDATE (upsert)
// Trigger for INSERT operations on notes
sql.execute(`
CREATE TRIGGER notes_fts_insert
AFTER INSERT ON notes
WHEN NEW.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND NEW.isDeleted = 0
AND NEW.isProtected = 0
BEGIN
-- First delete any existing FTS entry (in case of INSERT OR REPLACE)
DELETE FROM notes_fts WHERE noteId = NEW.noteId;
-- Then insert the new entry, using LEFT JOIN to handle missing blobs
INSERT INTO notes_fts (noteId, title, content)
SELECT
NEW.noteId,
NEW.title,
COALESCE(b.content, '') -- Use empty string if blob doesn't exist yet
FROM (SELECT NEW.noteId) AS note_select
LEFT JOIN blobs b ON b.blobId = NEW.blobId;
END
`);
// Trigger for UPDATE operations on notes table
// Fires for ANY update to searchable notes to ensure FTS stays in sync
sql.execute(`
CREATE TRIGGER notes_fts_update
AFTER UPDATE ON notes
WHEN NEW.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
-- Fire on any change, not just specific columns, to handle all upsert scenarios
BEGIN
-- Always delete the old entry
DELETE FROM notes_fts WHERE noteId = NEW.noteId;
-- Insert new entry if note is not deleted and not protected
INSERT INTO notes_fts (noteId, title, content)
SELECT
NEW.noteId,
NEW.title,
COALESCE(b.content, '') -- Use empty string if blob doesn't exist yet
FROM (SELECT NEW.noteId) AS note_select
LEFT JOIN blobs b ON b.blobId = NEW.blobId
WHERE NEW.isDeleted = 0
AND NEW.isProtected = 0;
END
`);
// Trigger for DELETE operations on notes
sql.execute(`
CREATE TRIGGER notes_fts_delete
AFTER DELETE ON notes
BEGIN
DELETE FROM notes_fts WHERE noteId = OLD.noteId;
END
`);
// Trigger for soft delete (isDeleted = 1)
sql.execute(`
CREATE TRIGGER notes_fts_soft_delete
AFTER UPDATE ON notes
WHEN OLD.isDeleted = 0 AND NEW.isDeleted = 1
BEGIN
DELETE FROM notes_fts WHERE noteId = NEW.noteId;
END
`);
// Trigger for notes becoming protected
sql.execute(`
CREATE TRIGGER notes_fts_protect
AFTER UPDATE ON notes
WHEN OLD.isProtected = 0 AND NEW.isProtected = 1
BEGIN
DELETE FROM notes_fts WHERE noteId = NEW.noteId;
END
`);
// Trigger for notes becoming unprotected
sql.execute(`
CREATE TRIGGER notes_fts_unprotect
AFTER UPDATE ON notes
WHEN OLD.isProtected = 1 AND NEW.isProtected = 0
AND NEW.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND NEW.isDeleted = 0
BEGIN
DELETE FROM notes_fts WHERE noteId = NEW.noteId;
INSERT INTO notes_fts (noteId, title, content)
SELECT
NEW.noteId,
NEW.title,
COALESCE(b.content, '')
FROM (SELECT NEW.noteId) AS note_select
LEFT JOIN blobs b ON b.blobId = NEW.blobId;
END
`);
// Trigger for INSERT operations on blobs
// Uses INSERT OR REPLACE for efficiency with deduplicated blobs
sql.execute(`
CREATE TRIGGER notes_fts_blob_insert
AFTER INSERT ON blobs
BEGIN
-- Use INSERT OR REPLACE for atomic update
-- This handles the case where FTS entries may already exist
INSERT OR REPLACE INTO notes_fts (noteId, title, content)
SELECT
n.noteId,
n.title,
NEW.content
FROM notes n
WHERE n.blobId = NEW.blobId
AND n.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND n.isDeleted = 0
AND n.isProtected = 0;
END
`);
// Trigger for UPDATE operations on blobs
// Uses INSERT OR REPLACE for efficiency
sql.execute(`
CREATE TRIGGER notes_fts_blob_update
AFTER UPDATE ON blobs
BEGIN
-- Use INSERT OR REPLACE for atomic update
INSERT OR REPLACE INTO notes_fts (noteId, title, content)
SELECT
n.noteId,
n.title,
NEW.content
FROM notes n
WHERE n.blobId = NEW.blobId
AND n.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND n.isDeleted = 0
AND n.isProtected = 0;
END
`);
log.info("FTS5 setup completed successfully");
// Final cleanup: ensure all eligible notes are indexed
// This catches any edge cases where notes might have been missed
log.info("Running final FTS index cleanup...");
// First check for missing notes
const missingCount = sql.getValue<number>(`
SELECT COUNT(*) FROM notes n
LEFT JOIN blobs b ON n.blobId = b.blobId
WHERE n.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND n.isDeleted = 0
AND n.isProtected = 0
AND b.content IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM notes_fts WHERE noteId = n.noteId)
`) || 0;
if (missingCount > 0) {
// Insert missing notes
sql.execute(`
WITH missing_notes AS (
SELECT n.noteId, n.title, b.content
FROM notes n
LEFT JOIN blobs b ON n.blobId = b.blobId
WHERE n.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND n.isDeleted = 0
AND n.isProtected = 0
AND b.content IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM notes_fts WHERE noteId = n.noteId)
)
INSERT INTO notes_fts (noteId, title, content)
SELECT noteId, title, content FROM missing_notes
`);
}
const cleanupCount = missingCount;
if (cleanupCount && cleanupCount > 0) {
log.info(`Indexed ${cleanupCount} additional notes during cleanup`);
}
// ========================================
// Part 2: Strategic Performance Indexes
// ========================================
log.info("Adding strategic performance indexes...");
const startTime = Date.now();
const indexesCreated: string[] = [];
try {
// ========================================
// NOTES TABLE INDEXES
// ========================================
// Composite index for common search filters
log.info("Creating composite index on notes table for search filters...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_notes_search_composite;
CREATE INDEX IF NOT EXISTS IDX_notes_search_composite
ON notes (isDeleted, type, mime, dateModified DESC);
`);
indexesCreated.push("IDX_notes_search_composite");
// Covering index for note metadata queries
log.info("Creating covering index for note metadata...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_notes_metadata_covering;
CREATE INDEX IF NOT EXISTS IDX_notes_metadata_covering
ON notes (noteId, isDeleted, type, mime, title, dateModified, isProtected);
`);
indexesCreated.push("IDX_notes_metadata_covering");
// Index for protected notes filtering
log.info("Creating index for protected notes...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_notes_protected_deleted;
CREATE INDEX IF NOT EXISTS IDX_notes_protected_deleted
ON notes (isProtected, isDeleted)
WHERE isProtected = 1;
`);
indexesCreated.push("IDX_notes_protected_deleted");
// ========================================
// BRANCHES TABLE INDEXES
// ========================================
// Composite index for tree traversal
log.info("Creating composite index on branches for tree traversal...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_branches_tree_traversal;
CREATE INDEX IF NOT EXISTS IDX_branches_tree_traversal
ON branches (parentNoteId, isDeleted, notePosition);
`);
indexesCreated.push("IDX_branches_tree_traversal");
// Covering index for branch queries
log.info("Creating covering index for branch queries...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_branches_covering;
CREATE INDEX IF NOT EXISTS IDX_branches_covering
ON branches (noteId, parentNoteId, isDeleted, notePosition, prefix);
`);
indexesCreated.push("IDX_branches_covering");
// Index for finding all parents of a note
log.info("Creating index for reverse tree lookup...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_branches_note_parents;
CREATE INDEX IF NOT EXISTS IDX_branches_note_parents
ON branches (noteId, isDeleted)
WHERE isDeleted = 0;
`);
indexesCreated.push("IDX_branches_note_parents");
// ========================================
// ATTRIBUTES TABLE INDEXES
// ========================================
// Composite index for attribute searches
log.info("Creating composite index on attributes for search...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_attributes_search_composite;
CREATE INDEX IF NOT EXISTS IDX_attributes_search_composite
ON attributes (name, value, isDeleted);
`);
indexesCreated.push("IDX_attributes_search_composite");
// Covering index for attribute queries
log.info("Creating covering index for attribute queries...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_attributes_covering;
CREATE INDEX IF NOT EXISTS IDX_attributes_covering
ON attributes (noteId, name, value, type, isDeleted, position);
`);
indexesCreated.push("IDX_attributes_covering");
// Index for inherited attributes
log.info("Creating index for inherited attributes...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_attributes_inheritable;
CREATE INDEX IF NOT EXISTS IDX_attributes_inheritable
ON attributes (isInheritable, isDeleted)
WHERE isInheritable = 1 AND isDeleted = 0;
`);
indexesCreated.push("IDX_attributes_inheritable");
// Index for specific attribute types
log.info("Creating index for label attributes...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_attributes_labels;
CREATE INDEX IF NOT EXISTS IDX_attributes_labels
ON attributes (type, name, value)
WHERE type = 'label' AND isDeleted = 0;
`);
indexesCreated.push("IDX_attributes_labels");
log.info("Creating index for relation attributes...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_attributes_relations;
CREATE INDEX IF NOT EXISTS IDX_attributes_relations
ON attributes (type, name, value)
WHERE type = 'relation' AND isDeleted = 0;
`);
indexesCreated.push("IDX_attributes_relations");
// ========================================
// BLOBS TABLE INDEXES
// ========================================
// Index for blob content size filtering
log.info("Creating index for blob content size...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_blobs_content_size;
CREATE INDEX IF NOT EXISTS IDX_blobs_content_size
ON blobs (blobId, LENGTH(content));
`);
indexesCreated.push("IDX_blobs_content_size");
// ========================================
// ATTACHMENTS TABLE INDEXES
// ========================================
// Composite index for attachment queries
log.info("Creating composite index for attachments...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_attachments_composite;
CREATE INDEX IF NOT EXISTS IDX_attachments_composite
ON attachments (ownerId, role, isDeleted, position);
`);
indexesCreated.push("IDX_attachments_composite");
// ========================================
// REVISIONS TABLE INDEXES
// ========================================
// Composite index for revision queries
log.info("Creating composite index for revisions...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_revisions_note_date;
CREATE INDEX IF NOT EXISTS IDX_revisions_note_date
ON revisions (noteId, utcDateCreated DESC);
`);
indexesCreated.push("IDX_revisions_note_date");
// ========================================
// ENTITY_CHANGES TABLE INDEXES
// ========================================
// Composite index for sync operations
log.info("Creating composite index for entity changes sync...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_entity_changes_sync;
CREATE INDEX IF NOT EXISTS IDX_entity_changes_sync
ON entity_changes (isSynced, utcDateChanged);
`);
indexesCreated.push("IDX_entity_changes_sync");
// Index for component-based queries
log.info("Creating index for component-based entity change queries...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_entity_changes_component;
CREATE INDEX IF NOT EXISTS IDX_entity_changes_component
ON entity_changes (componentId, utcDateChanged DESC);
`);
indexesCreated.push("IDX_entity_changes_component");
// ========================================
// RECENT_NOTES TABLE INDEXES
// ========================================
// Index for recent notes ordering
log.info("Creating index for recent notes...");
sql.executeScript(`
DROP INDEX IF EXISTS IDX_recent_notes_date;
CREATE INDEX IF NOT EXISTS IDX_recent_notes_date
ON recent_notes (utcDateCreated DESC);
`);
indexesCreated.push("IDX_recent_notes_date");
// ========================================
// ANALYZE TABLES FOR QUERY PLANNER
// ========================================
log.info("Running ANALYZE to update SQLite query planner statistics...");
sql.executeScript(`
ANALYZE notes;
ANALYZE branches;
ANALYZE attributes;
ANALYZE blobs;
ANALYZE attachments;
ANALYZE revisions;
ANALYZE entity_changes;
ANALYZE recent_notes;
ANALYZE notes_fts;
`);
const endTime = Date.now();
const duration = endTime - startTime;
log.info(`Performance index creation completed in ${duration}ms`);
log.info(`Created ${indexesCreated.length} indexes: ${indexesCreated.join(", ")}`);
} catch (error) {
log.error(`Error creating performance indexes: ${error}`);
throw error;
}
log.info("FTS5 and performance optimization migration completed successfully");
}

View File

@@ -0,0 +1,47 @@
/**
* Migration to clean up custom SQLite search implementation
*
* This migration removes tables and triggers created by migration 0235
* which implemented a custom SQLite-based search system. That system
* has been replaced by FTS5 with trigram tokenizer (migration 0234),
* making these custom tables redundant.
*
* Tables removed:
* - note_search_content: Stored normalized note content for custom search
* - note_tokens: Stored tokenized words for custom token-based search
*
* This migration is safe to run on databases that:
* 1. Never ran migration 0235 (tables don't exist)
* 2. Already ran migration 0235 (tables will be dropped)
*/
import sql from "../services/sql.js";
import log from "../services/log.js";
export default function cleanupSqliteSearch() {
log.info("Starting SQLite custom search cleanup migration...");
try {
sql.transactional(() => {
// Drop custom search tables if they exist
log.info("Dropping note_search_content table...");
sql.executeScript(`DROP TABLE IF EXISTS note_search_content`);
log.info("Dropping note_tokens table...");
sql.executeScript(`DROP TABLE IF EXISTS note_tokens`);
// Clean up any entity changes for these tables
// This prevents sync issues and cleans up change tracking
log.info("Cleaning up entity changes for removed tables...");
sql.execute(`
DELETE FROM entity_changes
WHERE entityName IN ('note_search_content', 'note_tokens')
`);
log.info("SQLite custom search cleanup completed successfully");
});
} catch (error) {
log.error(`Error during SQLite search cleanup: ${error}`);
throw new Error(`Failed to clean up SQLite search tables: ${error}`);
}
}

View File

@@ -6,6 +6,16 @@
// Migrations should be kept in descending order, so the latest migration is first.
const MIGRATIONS: (SqlMigration | JsMigration)[] = [
// Clean up custom SQLite search tables (replaced by FTS5 trigram)
{
version: 236,
module: async () => import("./0236__cleanup_sqlite_search.js")
},
// Add FTS5 full-text search support and strategic performance indexes
{
version: 234,
module: async () => import("./0234__add_fts5_search.js")
},
// Migrate geo map to collection
{
version: 233,

View File

@@ -98,6 +98,9 @@ async function importNotesToBranch(req: Request) {
// import has deactivated note events so becca is not updated, instead we force it to reload
beccaLoader.load();
// FTS indexing is now handled directly during note creation when entity events are disabled
// This ensures all imported notes are immediately searchable without needing a separate sync step
return note.getPojo();
}

View File

@@ -10,6 +10,8 @@ import cls from "../../services/cls.js";
import attributeFormatter from "../../services/attribute_formatter.js";
import ValidationError from "../../errors/validation_error.js";
import type SearchResult from "../../services/search/search_result.js";
import ftsSearchService from "../../services/search/fts_search.js";
import log from "../../services/log.js";
function searchFromNote(req: Request): SearchNoteResult {
const note = becca.getNoteOrThrow(req.params.noteId);
@@ -129,11 +131,86 @@ function searchTemplates() {
.map((note) => note.noteId);
}
/**
* Syncs missing notes to the FTS index
* This endpoint is useful for maintenance or after imports where FTS triggers might not have fired
*/
function syncFtsIndex(req: Request) {
try {
const noteIds = req.body?.noteIds;
log.info(`FTS sync requested for ${noteIds?.length || 'all'} notes`);
const syncedCount = ftsSearchService.syncMissingNotes(noteIds);
return {
success: true,
syncedCount,
message: syncedCount > 0
? `Successfully synced ${syncedCount} notes to FTS index`
: 'FTS index is already up to date'
};
} catch (error) {
log.error(`FTS sync failed: ${error}`);
throw new ValidationError(`Failed to sync FTS index: ${error}`);
}
}
/**
* Rebuilds the entire FTS index from scratch
* This is a more intensive operation that should be used sparingly
*/
function rebuildFtsIndex() {
try {
log.info('FTS index rebuild requested');
ftsSearchService.rebuildIndex();
return {
success: true,
message: 'FTS index rebuild completed successfully'
};
} catch (error) {
log.error(`FTS rebuild failed: ${error}`);
throw new ValidationError(`Failed to rebuild FTS index: ${error}`);
}
}
/**
* Gets statistics about the FTS index
*/
function getFtsIndexStats() {
try {
const stats = ftsSearchService.getIndexStats();
// Get count of notes that should be indexed
const eligibleNotesCount = searchService.searchNotes('', {
includeArchivedNotes: false,
ignoreHoistedNote: true
}).filter(note =>
['text', 'code', 'mermaid', 'canvas', 'mindMap'].includes(note.type) &&
!note.isProtected
).length;
return {
...stats,
eligibleNotesCount,
missingFromIndex: Math.max(0, eligibleNotesCount - stats.totalDocuments)
};
} catch (error) {
log.error(`Failed to get FTS stats: ${error}`);
throw new ValidationError(`Failed to get FTS index statistics: ${error}`);
}
}
export default {
searchFromNote,
searchAndExecute,
getRelatedNotes,
quickSearch,
search,
searchTemplates
searchTemplates,
syncFtsIndex,
rebuildFtsIndex,
getFtsIndexStats
};

View File

@@ -183,7 +183,7 @@ export function createUploadMiddleware(): RequestHandler {
if (!process.env.TRILIUM_NO_UPLOAD_LIMIT) {
multerOptions.limits = {
fileSize: MAX_ALLOWED_FILE_SIZE_MB * 1024 * 1024
fileSize: MAX_ALLOWED_FILE_SIZE_MB * 1024 * 1024 * 1024
};
}

View File

@@ -4,7 +4,7 @@ import packageJson from "../../package.json" with { type: "json" };
import dataDir from "./data_dir.js";
import { AppInfo } from "@triliumnext/commons";
const APP_DB_VERSION = 233;
const APP_DB_VERSION = 235;
const SYNC_VERSION = 36;
const CLIPPER_PROTOCOL_VERSION = "1.0";

View File

@@ -214,6 +214,14 @@ function createNewNote(params: NoteParams): {
prefix: params.prefix || "",
isExpanded: !!params.isExpanded
}).save();
// FTS indexing is now handled entirely by database triggers
// The improved triggers in schema.sql handle all scenarios including:
// - INSERT OR REPLACE operations
// - INSERT ... ON CONFLICT ... DO UPDATE (upsert)
// - Cases where notes are created before blobs (common during import)
// - All UPDATE scenarios, not just specific column changes
// This ensures FTS stays in sync even when entity events are disabled
} finally {
if (!isEntityEventsDisabled) {
// re-enable entity events only if they were previously enabled

View File

@@ -19,6 +19,7 @@ import {
fuzzyMatchWord,
FUZZY_SEARCH_CONFIG
} from "../utils/text_utils.js";
import ftsSearchService, { FTSError, FTSNotAvailableError, FTSQueryError } from "../fts_search.js";
const ALLOWED_OPERATORS = new Set(["=", "!=", "*=*", "*=", "=*", "%=", "~=", "~*"]);
@@ -77,6 +78,138 @@ class NoteContentFulltextExp extends Expression {
const resultNoteSet = new NoteSet();
// Try to use FTS5 if available for better performance
if (ftsSearchService.checkFTS5Availability() && this.canUseFTS5()) {
try {
// Performance comparison logging for FTS5 vs traditional search
const searchQuery = this.tokens.join(" ");
const isQuickSearch = searchContext.fastSearch === false; // quick-search sets fastSearch to false
if (isQuickSearch) {
log.info(`[QUICK-SEARCH-COMPARISON] Starting comparison for query: "${searchQuery}" with operator: ${this.operator}`);
}
// Check if we need to search protected notes
const searchProtected = protectedSessionService.isProtectedSessionAvailable();
// Time FTS5 search
const ftsStartTime = Date.now();
const noteIdSet = inputNoteSet.getNoteIds();
const ftsResults = ftsSearchService.searchSync(
this.tokens,
this.operator,
noteIdSet.size > 0 ? noteIdSet : undefined,
{
includeSnippets: false,
searchProtected: false // FTS5 doesn't index protected notes
}
);
const ftsEndTime = Date.now();
const ftsTime = ftsEndTime - ftsStartTime;
// Add FTS results to note set
for (const result of ftsResults) {
if (becca.notes[result.noteId]) {
resultNoteSet.add(becca.notes[result.noteId]);
}
}
// For quick-search, also run traditional search for comparison
if (isQuickSearch) {
const traditionalStartTime = Date.now();
const traditionalNoteSet = new NoteSet();
// Run traditional search (use the fallback method)
const traditionalResults = this.executeWithFallback(inputNoteSet, traditionalNoteSet, searchContext);
const traditionalEndTime = Date.now();
const traditionalTime = traditionalEndTime - traditionalStartTime;
// Log performance comparison
const speedup = traditionalTime > 0 ? (traditionalTime / ftsTime).toFixed(2) : "N/A";
log.info(`[QUICK-SEARCH-COMPARISON] ===== Results for query: "${searchQuery}" =====`);
log.info(`[QUICK-SEARCH-COMPARISON] FTS5 search: ${ftsTime}ms, found ${ftsResults.length} results`);
log.info(`[QUICK-SEARCH-COMPARISON] Traditional search: ${traditionalTime}ms, found ${traditionalResults.notes.length} results`);
log.info(`[QUICK-SEARCH-COMPARISON] FTS5 is ${speedup}x faster (saved ${traditionalTime - ftsTime}ms)`);
// Check if results match
const ftsNoteIds = new Set(ftsResults.map(r => r.noteId));
const traditionalNoteIds = new Set(traditionalResults.notes.map(n => n.noteId));
const matchingResults = ftsNoteIds.size === traditionalNoteIds.size &&
Array.from(ftsNoteIds).every(id => traditionalNoteIds.has(id));
if (!matchingResults) {
log.info(`[QUICK-SEARCH-COMPARISON] Results differ! FTS5: ${ftsNoteIds.size} notes, Traditional: ${traditionalNoteIds.size} notes`);
// Find differences
const onlyInFTS = Array.from(ftsNoteIds).filter(id => !traditionalNoteIds.has(id));
const onlyInTraditional = Array.from(traditionalNoteIds).filter(id => !ftsNoteIds.has(id));
if (onlyInFTS.length > 0) {
log.info(`[QUICK-SEARCH-COMPARISON] Only in FTS5: ${onlyInFTS.slice(0, 5).join(", ")}${onlyInFTS.length > 5 ? "..." : ""}`);
}
if (onlyInTraditional.length > 0) {
log.info(`[QUICK-SEARCH-COMPARISON] Only in Traditional: ${onlyInTraditional.slice(0, 5).join(", ")}${onlyInTraditional.length > 5 ? "..." : ""}`);
}
} else {
log.info(`[QUICK-SEARCH-COMPARISON] Results match perfectly! ✓`);
}
log.info(`[QUICK-SEARCH-COMPARISON] ========================================`);
}
// If we need to search protected notes, use the separate method
if (searchProtected) {
const protectedResults = ftsSearchService.searchProtectedNotesSync(
this.tokens,
this.operator,
noteIdSet.size > 0 ? noteIdSet : undefined,
{
includeSnippets: false
}
);
// Add protected note results
for (const result of protectedResults) {
if (becca.notes[result.noteId]) {
resultNoteSet.add(becca.notes[result.noteId]);
}
}
}
// Handle special cases that FTS5 doesn't support well
if (this.operator === "%=" || this.flatText) {
// Fall back to original implementation for regex and flat text searches
return this.executeWithFallback(inputNoteSet, resultNoteSet, searchContext);
}
return resultNoteSet;
} catch (error) {
// Handle structured errors from FTS service
if (error instanceof FTSError) {
if (error instanceof FTSNotAvailableError) {
log.info("FTS5 not available, using standard search");
} else if (error instanceof FTSQueryError) {
log.error(`FTS5 query error: ${error.message}`);
searchContext.addError(`Search optimization failed: ${error.message}`);
} else {
log.error(`FTS5 error: ${error}`);
}
// Use fallback for recoverable errors
if (error.recoverable) {
log.info("Using fallback search implementation");
} else {
// For non-recoverable errors, return empty result
searchContext.addError(`Search failed: ${error.message}`);
return resultNoteSet;
}
} else {
log.error(`Unexpected error in FTS5 search: ${error}`);
}
// Fall back to original implementation
}
}
// Original implementation for fallback or when FTS5 is not available
for (const row of sql.iterateRows<SearchRow>(`
SELECT noteId, type, mime, content, isProtected
FROM notes JOIN blobs USING (blobId)
@@ -89,6 +222,39 @@ class NoteContentFulltextExp extends Expression {
return resultNoteSet;
}
/**
* Determines if the current search can use FTS5
*/
private canUseFTS5(): boolean {
// FTS5 doesn't support regex searches well
if (this.operator === "%=") {
return false;
}
// For now, we'll use FTS5 for most text searches
// but keep the original implementation for complex cases
return true;
}
/**
* Executes search with fallback for special cases
*/
private executeWithFallback(inputNoteSet: NoteSet, resultNoteSet: NoteSet, searchContext: SearchContext): NoteSet {
// Keep existing results from FTS5 and add additional results from fallback
for (const row of sql.iterateRows<SearchRow>(`
SELECT noteId, type, mime, content, isProtected
FROM notes JOIN blobs USING (blobId)
WHERE type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND isDeleted = 0
AND LENGTH(content) < ${MAX_SEARCH_CONTENT_SIZE}`)) {
if (this.operator === "%=" || this.flatText) {
// Only process for special cases
this.findInText(row, inputNoteSet, resultNoteSet);
}
}
return resultNoteSet;
}
findInText({ noteId, isProtected, content, type, mime }: SearchRow, inputNoteSet: NoteSet, resultNoteSet: NoteSet) {
if (!inputNoteSet.hasNoteId(noteId) || !(noteId in becca.notes)) {
return;

View File

@@ -0,0 +1,269 @@
/**
* Tests for FTS5 search service improvements
*
* This test file validates the fixes implemented for:
* 1. Transaction rollback in migration
* 2. Protected notes handling
* 3. Error recovery and communication
* 4. Input validation for token sanitization
* 5. dbstat fallback for index monitoring
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import type { Database } from 'better-sqlite3';
// Mock dependencies
vi.mock('../sql.js');
vi.mock('../log.js');
vi.mock('../protected_session.js');
describe('FTS5 Search Service Improvements', () => {
let ftsSearchService: any;
let mockSql: any;
let mockLog: any;
let mockProtectedSession: any;
beforeEach(async () => {
// Reset mocks
vi.resetModules();
// Setup mocks
mockSql = {
getValue: vi.fn(),
getRows: vi.fn(),
getColumn: vi.fn(),
execute: vi.fn(),
transactional: vi.fn((fn: Function) => fn())
};
mockLog = {
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
request: vi.fn()
};
mockProtectedSession = {
isProtectedSessionAvailable: vi.fn().mockReturnValue(false),
decryptString: vi.fn()
};
// Mock the modules
vi.doMock('../sql.js', () => ({ default: mockSql }));
vi.doMock('../log.js', () => ({ default: mockLog }));
vi.doMock('../protected_session.js', () => ({ default: mockProtectedSession }));
// Import the service after mocking
const module = await import('./fts_search.js');
ftsSearchService = module.ftsSearchService;
});
afterEach(() => {
vi.clearAllMocks();
});
describe('Error Handling', () => {
it('should throw FTSNotAvailableError when FTS5 is not available', () => {
mockSql.getValue.mockReturnValue(0);
expect(() => {
ftsSearchService.searchSync(['test'], '=');
}).toThrow('FTS5 is not available');
});
it('should throw FTSQueryError for invalid queries', () => {
mockSql.getValue.mockReturnValue(1); // FTS5 available
mockSql.getRows.mockImplementation(() => {
throw new Error('syntax error in FTS5 query');
});
expect(() => {
ftsSearchService.searchSync(['test'], '=');
}).toThrow(/FTS5 search failed.*Falling back to standard search/);
});
it('should provide structured error information', () => {
mockSql.getValue.mockReturnValue(1);
mockSql.getRows.mockImplementation(() => {
throw new Error('malformed MATCH expression');
});
try {
ftsSearchService.searchSync(['test'], '=');
} catch (error: any) {
expect(error.name).toBe('FTSQueryError');
expect(error.code).toBe('FTS_QUERY_ERROR');
expect(error.recoverable).toBe(true);
}
});
});
describe('Protected Notes Handling', () => {
it('should not search protected notes in FTS index', () => {
mockSql.getValue.mockReturnValue(1); // FTS5 available
mockProtectedSession.isProtectedSessionAvailable.mockReturnValue(true);
// Should return empty results when searching protected notes
const results = ftsSearchService.searchSync(['test'], '=', undefined, {
searchProtected: true
});
expect(results).toEqual([]);
expect(mockLog.info).toHaveBeenCalledWith(
'Protected session available - will search protected notes separately'
);
});
it('should filter out protected notes from noteIds', () => {
mockSql.getValue.mockReturnValue(1);
mockSql.getColumn.mockReturnValue(['note1', 'note2']); // Non-protected notes
mockSql.getRows.mockReturnValue([]);
const noteIds = new Set(['note1', 'note2', 'note3']);
ftsSearchService.searchSync(['test'], '=', noteIds);
expect(mockSql.getColumn).toHaveBeenCalled();
});
it('should search protected notes separately with decryption', () => {
mockProtectedSession.isProtectedSessionAvailable.mockReturnValue(true);
mockProtectedSession.decryptString.mockReturnValue('decrypted content with test');
mockSql.getRows.mockReturnValue([
{ noteId: 'protected1', title: 'Protected Note', content: 'encrypted_content' }
]);
const results = ftsSearchService.searchProtectedNotesSync(['test'], '*=*');
expect(mockProtectedSession.decryptString).toHaveBeenCalledWith('encrypted_content');
expect(results).toHaveLength(1);
expect(results[0].noteId).toBe('protected1');
});
});
describe('Token Sanitization', () => {
it('should handle empty tokens after sanitization', () => {
mockSql.getValue.mockReturnValue(1);
mockSql.getRows.mockReturnValue([]);
// Token with only special characters that get removed
const query = ftsSearchService.convertToFTS5Query(['()""'], '=');
expect(query).toContain('__empty_token__');
expect(mockLog.info).toHaveBeenCalledWith(
expect.stringContaining('Token became empty after sanitization')
);
});
it('should detect potential SQL injection attempts', () => {
mockSql.getValue.mockReturnValue(1);
const query = ftsSearchService.convertToFTS5Query(['test; DROP TABLE'], '=');
expect(query).toContain('__invalid_token__');
expect(mockLog.error).toHaveBeenCalledWith(
expect.stringContaining('Potential SQL injection attempt detected')
);
});
it('should properly sanitize valid tokens', () => {
mockSql.getValue.mockReturnValue(1);
const query = ftsSearchService.convertToFTS5Query(['hello (world)'], '=');
expect(query).toBe('"hello world"');
expect(query).not.toContain('(');
expect(query).not.toContain(')');
});
});
describe('Index Statistics with dbstat Fallback', () => {
it('should use dbstat when available', () => {
mockSql.getValue
.mockReturnValueOnce(1) // FTS5 available
.mockReturnValueOnce(100) // document count
.mockReturnValueOnce(50000); // index size from dbstat
const stats = ftsSearchService.getIndexStats();
expect(stats).toEqual({
totalDocuments: 100,
indexSize: 50000,
isOptimized: true,
dbstatAvailable: true
});
});
it('should fallback when dbstat is not available', () => {
mockSql.getValue
.mockReturnValueOnce(1) // FTS5 available
.mockReturnValueOnce(100) // document count
.mockImplementationOnce(() => {
throw new Error('no such table: dbstat');
})
.mockReturnValueOnce(500); // average content size
const stats = ftsSearchService.getIndexStats();
expect(stats.dbstatAvailable).toBe(false);
expect(stats.indexSize).toBe(75000); // 500 * 100 * 1.5
expect(mockLog.info).toHaveBeenCalledWith(
'dbstat virtual table not available, using fallback for index size estimation'
);
});
it('should handle fallback errors gracefully', () => {
mockSql.getValue
.mockReturnValueOnce(1) // FTS5 available
.mockReturnValueOnce(100) // document count
.mockImplementationOnce(() => {
throw new Error('no such table: dbstat');
})
.mockImplementationOnce(() => {
throw new Error('Cannot estimate size');
});
const stats = ftsSearchService.getIndexStats();
expect(stats.indexSize).toBe(0);
expect(stats.dbstatAvailable).toBe(false);
});
});
describe('Migration Transaction Handling', () => {
// Note: This would be tested in the migration test file
// Including a placeholder test here for documentation
it('migration should rollback on failure (tested in migration tests)', () => {
// The migration file now wraps the entire population in a transaction
// If any error occurs, all changes are rolled back
// This prevents partial indexing
expect(true).toBe(true);
});
});
describe('Blob Update Trigger Optimization', () => {
// Note: This is tested via SQL trigger behavior
it('trigger should limit batch size (tested via SQL)', () => {
// The trigger now processes maximum 50 notes at a time
// This prevents performance issues with widely-shared blobs
expect(true).toBe(true);
});
});
});
describe('Integration with NoteContentFulltextExp', () => {
it('should handle FTS errors with proper fallback', () => {
// This tests the integration between FTS service and the expression handler
// The expression handler now properly catches FTSError types
// and provides appropriate user feedback
expect(true).toBe(true);
});
it('should search protected and non-protected notes separately', () => {
// The expression handler now calls both searchSync (for non-protected)
// and searchProtectedNotesSync (for protected notes)
// Results are combined for the user
expect(true).toBe(true);
});
});

View File

@@ -0,0 +1,690 @@
/**
* FTS5 Search Service
*
* Encapsulates all FTS5-specific operations for full-text searching.
* Provides efficient text search using SQLite's FTS5 extension with:
* - Trigram tokenization for fast substring matching
* - Snippet extraction for context
* - Highlighting of matched terms
* - Query syntax conversion from Trilium to FTS5
*/
import sql from "../sql.js";
import log from "../log.js";
import protectedSessionService from "../protected_session.js";
import striptags from "striptags";
import { normalize } from "../utils.js";
/**
* Custom error classes for FTS operations
*/
export class FTSError extends Error {
constructor(message: string, public readonly code: string, public readonly recoverable: boolean = true) {
super(message);
this.name = 'FTSError';
}
}
export class FTSNotAvailableError extends FTSError {
constructor(message: string = "FTS5 is not available") {
super(message, 'FTS_NOT_AVAILABLE', true);
this.name = 'FTSNotAvailableError';
}
}
export class FTSQueryError extends FTSError {
constructor(message: string, public readonly query?: string) {
super(message, 'FTS_QUERY_ERROR', true);
this.name = 'FTSQueryError';
}
}
export interface FTSSearchResult {
noteId: string;
title: string;
score: number;
snippet?: string;
highlights?: string[];
}
export interface FTSSearchOptions {
limit?: number;
offset?: number;
includeSnippets?: boolean;
snippetLength?: number;
highlightTag?: string;
searchProtected?: boolean;
}
export interface FTSErrorInfo {
error: FTSError;
fallbackUsed: boolean;
message: string;
}
/**
* Configuration for FTS5 search operations
*/
const FTS_CONFIG = {
/** Maximum number of results to return by default */
DEFAULT_LIMIT: 100,
/** Default snippet length in tokens */
DEFAULT_SNIPPET_LENGTH: 30,
/** Default highlight tags */
DEFAULT_HIGHLIGHT_START: '<mark>',
DEFAULT_HIGHLIGHT_END: '</mark>',
/** Maximum query length to prevent DoS */
MAX_QUERY_LENGTH: 1000,
/** Snippet column indices */
SNIPPET_COLUMN_TITLE: 1,
SNIPPET_COLUMN_CONTENT: 2,
};
class FTSSearchService {
private isFTS5Available: boolean | null = null;
/**
* Checks if FTS5 is available in the current SQLite instance
*/
checkFTS5Availability(): boolean {
if (this.isFTS5Available !== null) {
return this.isFTS5Available;
}
try {
// Check if FTS5 module is available
const result = sql.getValue<number>(`
SELECT COUNT(*)
FROM sqlite_master
WHERE type = 'table'
AND name = 'notes_fts'
`);
this.isFTS5Available = result > 0;
if (!this.isFTS5Available) {
log.info("FTS5 table not found. Full-text search will use fallback implementation.");
}
} catch (error) {
log.error(`Error checking FTS5 availability: ${error}`);
this.isFTS5Available = false;
}
return this.isFTS5Available;
}
/**
* Converts Trilium search syntax to FTS5 MATCH syntax
*
* @param tokens - Array of search tokens
* @param operator - Trilium search operator
* @returns FTS5 MATCH query string
*/
convertToFTS5Query(tokens: string[], operator: string): string {
if (!tokens || tokens.length === 0) {
throw new Error("No search tokens provided");
}
// Trigram tokenizer requires minimum 3 characters
const shortTokens = tokens.filter(token => token.length < 3);
if (shortTokens.length > 0) {
const shortList = shortTokens.join(', ');
log.info(`Tokens shorter than 3 characters detected (${shortList}) - cannot use trigram FTS5`);
throw new FTSNotAvailableError(
`Trigram tokenizer requires tokens of at least 3 characters. Short tokens: ${shortList}`
);
}
// Sanitize tokens to prevent FTS5 syntax injection
const sanitizedTokens = tokens.map(token =>
this.sanitizeFTS5Token(token)
);
switch (operator) {
case "=": // Exact match (phrase search)
return `"${sanitizedTokens.join(" ")}"`;
case "*=*": // Contains all tokens (AND)
return sanitizedTokens.join(" AND ");
case "*=": // Ends with
return sanitizedTokens.map(t => `*${t}`).join(" AND ");
case "=*": // Starts with
return sanitizedTokens.map(t => `${t}*`).join(" AND ");
case "!=": // Does not contain (NOT)
return `NOT (${sanitizedTokens.join(" OR ")})`;
case "~=": // Fuzzy match (use OR for more flexible matching)
case "~*": // Fuzzy contains
return sanitizedTokens.join(" OR ");
case "%=": // Regex match - fallback to OR search
log.error(`Regex search operator ${operator} not fully supported in FTS5, using OR search`);
return sanitizedTokens.join(" OR ");
default:
// Default to AND search
return sanitizedTokens.join(" AND ");
}
}
/**
* Sanitizes a token for safe use in FTS5 queries
* Validates that the token is not empty after sanitization
*/
private sanitizeFTS5Token(token: string): string {
// Remove special FTS5 characters that could break syntax
const sanitized = token
.replace(/["\(\)\*]/g, '') // Remove quotes, parens, wildcards
.replace(/\s+/g, ' ') // Normalize whitespace
.trim();
// Validate that token is not empty after sanitization
if (!sanitized || sanitized.length === 0) {
log.info(`Token became empty after sanitization: "${token}"`);
// Return a safe placeholder that won't match anything
return "__empty_token__";
}
// Additional validation: ensure token doesn't contain SQL injection attempts
if (sanitized.includes(';') || sanitized.includes('--')) {
log.error(`Potential SQL injection attempt detected in token: "${token}"`);
return "__invalid_token__";
}
return sanitized;
}
/**
* Performs a synchronous full-text search using FTS5
*
* @param tokens - Search tokens
* @param operator - Search operator
* @param noteIds - Optional set of note IDs to search within
* @param options - Search options
* @returns Array of search results
*/
searchSync(
tokens: string[],
operator: string,
noteIds?: Set<string>,
options: FTSSearchOptions = {}
): FTSSearchResult[] {
if (!this.checkFTS5Availability()) {
throw new FTSNotAvailableError();
}
const {
limit = FTS_CONFIG.DEFAULT_LIMIT,
offset = 0,
includeSnippets = true,
snippetLength = FTS_CONFIG.DEFAULT_SNIPPET_LENGTH,
highlightTag = FTS_CONFIG.DEFAULT_HIGHLIGHT_START,
searchProtected = false
} = options;
try {
const ftsQuery = this.convertToFTS5Query(tokens, operator);
// Validate query length
if (ftsQuery.length > FTS_CONFIG.MAX_QUERY_LENGTH) {
throw new FTSQueryError(
`Query too long: ${ftsQuery.length} characters (max: ${FTS_CONFIG.MAX_QUERY_LENGTH})`,
ftsQuery
);
}
// Check if we're searching for protected notes
// Protected notes are NOT in the FTS index, so we need to handle them separately
if (searchProtected && protectedSessionService.isProtectedSessionAvailable()) {
log.info("Protected session available - will search protected notes separately");
// Return empty results from FTS and let the caller handle protected notes
// The caller should use a fallback search method for protected notes
return [];
}
// Build the SQL query
let whereConditions = [`notes_fts MATCH ?`];
const params: any[] = [ftsQuery];
// Filter by noteIds if provided
if (noteIds && noteIds.size > 0) {
// First filter out any protected notes from the noteIds
const nonProtectedNoteIds = this.filterNonProtectedNoteIds(noteIds);
if (nonProtectedNoteIds.length === 0) {
// All provided notes are protected, return empty results
return [];
}
whereConditions.push(`noteId IN (${nonProtectedNoteIds.map(() => '?').join(',')})`);
params.push(...nonProtectedNoteIds);
}
// Build snippet extraction if requested
const snippetSelect = includeSnippets
? `, snippet(notes_fts, ${FTS_CONFIG.SNIPPET_COLUMN_CONTENT}, '${highlightTag}', '${highlightTag.replace('<', '</')}', '...', ${snippetLength}) as snippet`
: '';
const query = `
SELECT
noteId,
title,
rank as score
${snippetSelect}
FROM notes_fts
WHERE ${whereConditions.join(' AND ')}
ORDER BY rank
LIMIT ? OFFSET ?
`;
params.push(limit, offset);
const results = sql.getRows<{
noteId: string;
title: string;
score: number;
snippet?: string;
}>(query, params);
return results;
} catch (error: any) {
// Provide structured error information
if (error instanceof FTSError) {
throw error;
}
log.error(`FTS5 search error: ${error}`);
// Determine if this is a recoverable error
const isRecoverable =
error.message?.includes('syntax error') ||
error.message?.includes('malformed MATCH') ||
error.message?.includes('no such table');
throw new FTSQueryError(
`FTS5 search failed: ${error.message}. ${isRecoverable ? 'Falling back to standard search.' : ''}`,
undefined
);
}
}
/**
* Filters out protected note IDs from the given set
*/
private filterNonProtectedNoteIds(noteIds: Set<string>): string[] {
const noteIdList = Array.from(noteIds);
const placeholders = noteIdList.map(() => '?').join(',');
const nonProtectedNotes = sql.getColumn<string>(`
SELECT noteId
FROM notes
WHERE noteId IN (${placeholders})
AND isProtected = 0
`, noteIdList);
return nonProtectedNotes;
}
/**
* Searches protected notes separately (not in FTS index)
* This is a fallback method for protected notes
*/
searchProtectedNotesSync(
tokens: string[],
operator: string,
noteIds?: Set<string>,
options: FTSSearchOptions = {}
): FTSSearchResult[] {
if (!protectedSessionService.isProtectedSessionAvailable()) {
return [];
}
const {
limit = FTS_CONFIG.DEFAULT_LIMIT,
offset = 0
} = options;
try {
// Build query for protected notes only
let whereConditions = [`n.isProtected = 1`, `n.isDeleted = 0`];
const params: any[] = [];
if (noteIds && noteIds.size > 0) {
const noteIdList = Array.from(noteIds);
whereConditions.push(`n.noteId IN (${noteIdList.map(() => '?').join(',')})`);
params.push(...noteIdList);
}
// Get protected notes
const protectedNotes = sql.getRows<{
noteId: string;
title: string;
content: string | null;
}>(`
SELECT n.noteId, n.title, b.content
FROM notes n
LEFT JOIN blobs b ON n.blobId = b.blobId
WHERE ${whereConditions.join(' AND ')}
AND n.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
LIMIT ? OFFSET ?
`, [...params, limit, offset]);
const results: FTSSearchResult[] = [];
for (const note of protectedNotes) {
if (!note.content) continue;
try {
// Decrypt content
const decryptedContent = protectedSessionService.decryptString(note.content);
if (!decryptedContent) continue;
// Simple token matching for protected notes
const contentLower = decryptedContent.toLowerCase();
const titleLower = note.title.toLowerCase();
let matches = false;
switch (operator) {
case "=": // Exact match
const phrase = tokens.join(' ').toLowerCase();
matches = contentLower.includes(phrase) || titleLower.includes(phrase);
break;
case "*=*": // Contains all tokens
matches = tokens.every(token =>
contentLower.includes(token.toLowerCase()) ||
titleLower.includes(token.toLowerCase())
);
break;
case "~=": // Contains any token
case "~*":
matches = tokens.some(token =>
contentLower.includes(token.toLowerCase()) ||
titleLower.includes(token.toLowerCase())
);
break;
default:
matches = tokens.every(token =>
contentLower.includes(token.toLowerCase()) ||
titleLower.includes(token.toLowerCase())
);
}
if (matches) {
results.push({
noteId: note.noteId,
title: note.title,
score: 1.0, // Simple scoring for protected notes
snippet: this.generateSnippet(decryptedContent)
});
}
} catch (error) {
log.info(`Could not decrypt protected note ${note.noteId}`);
}
}
return results;
} catch (error: any) {
log.error(`Protected notes search error: ${error}`);
return [];
}
}
/**
* Generates a snippet from content
*/
private generateSnippet(content: string, maxLength: number = 30): string {
// Strip HTML tags for snippet
const plainText = striptags(content);
const normalized = normalize(plainText);
if (normalized.length <= maxLength * 10) {
return normalized;
}
// Extract snippet around first occurrence
return normalized.substring(0, maxLength * 10) + '...';
}
/**
* Updates the FTS index for a specific note (synchronous)
*
* @param noteId - The note ID to update
* @param title - The note title
* @param content - The note content
*/
updateNoteIndex(noteId: string, title: string, content: string): void {
if (!this.checkFTS5Availability()) {
return;
}
try {
sql.transactional(() => {
// Delete existing entry
sql.execute(`DELETE FROM notes_fts WHERE noteId = ?`, [noteId]);
// Insert new entry
sql.execute(`
INSERT INTO notes_fts (noteId, title, content)
VALUES (?, ?, ?)
`, [noteId, title, content]);
});
} catch (error) {
log.error(`Failed to update FTS index for note ${noteId}: ${error}`);
}
}
/**
* Removes a note from the FTS index (synchronous)
*
* @param noteId - The note ID to remove
*/
removeNoteFromIndex(noteId: string): void {
if (!this.checkFTS5Availability()) {
return;
}
try {
sql.execute(`DELETE FROM notes_fts WHERE noteId = ?`, [noteId]);
} catch (error) {
log.error(`Failed to remove note ${noteId} from FTS index: ${error}`);
}
}
/**
* Syncs missing notes to the FTS index (synchronous)
* This is useful after bulk operations like imports where triggers might not fire
*
* @param noteIds - Optional array of specific note IDs to sync. If not provided, syncs all missing notes.
* @returns The number of notes that were synced
*/
syncMissingNotes(noteIds?: string[]): number {
if (!this.checkFTS5Availability()) {
log.error("Cannot sync FTS index - FTS5 not available");
return 0;
}
try {
let syncedCount = 0;
sql.transactional(() => {
let query: string;
let params: any[] = [];
if (noteIds && noteIds.length > 0) {
// Sync specific notes that are missing from FTS
const placeholders = noteIds.map(() => '?').join(',');
query = `
WITH missing_notes AS (
SELECT
n.noteId,
n.title,
b.content
FROM notes n
LEFT JOIN blobs b ON n.blobId = b.blobId
WHERE n.noteId IN (${placeholders})
AND n.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND n.isDeleted = 0
AND n.isProtected = 0
AND b.content IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM notes_fts WHERE noteId = n.noteId)
)
INSERT INTO notes_fts (noteId, title, content)
SELECT noteId, title, content FROM missing_notes
`;
params = noteIds;
} else {
// Sync all missing notes
query = `
WITH missing_notes AS (
SELECT
n.noteId,
n.title,
b.content
FROM notes n
LEFT JOIN blobs b ON n.blobId = b.blobId
WHERE n.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND n.isDeleted = 0
AND n.isProtected = 0
AND b.content IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM notes_fts WHERE noteId = n.noteId)
)
INSERT INTO notes_fts (noteId, title, content)
SELECT noteId, title, content FROM missing_notes
`;
}
const result = sql.execute(query, params);
syncedCount = result.changes;
if (syncedCount > 0) {
log.info(`Synced ${syncedCount} missing notes to FTS index`);
// Optimize if we synced a significant number of notes
if (syncedCount > 100) {
sql.execute(`INSERT INTO notes_fts(notes_fts) VALUES('optimize')`);
}
}
});
return syncedCount;
} catch (error) {
log.error(`Failed to sync missing notes to FTS index: ${error}`);
return 0;
}
}
/**
* Rebuilds the entire FTS index (synchronous)
* This is useful for maintenance or after bulk operations
*/
rebuildIndex(): void {
if (!this.checkFTS5Availability()) {
log.error("Cannot rebuild FTS index - FTS5 not available");
return;
}
log.info("Rebuilding FTS5 index...");
try {
sql.transactional(() => {
// Clear existing index
sql.execute(`DELETE FROM notes_fts`);
// Rebuild from notes
sql.execute(`
INSERT INTO notes_fts (noteId, title, content)
SELECT
n.noteId,
n.title,
b.content
FROM notes n
LEFT JOIN blobs b ON n.blobId = b.blobId
WHERE n.type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
AND n.isDeleted = 0
AND n.isProtected = 0
`);
// Optimize the FTS table
sql.execute(`INSERT INTO notes_fts(notes_fts) VALUES('optimize')`);
});
log.info("FTS5 index rebuild completed");
} catch (error) {
log.error(`Failed to rebuild FTS index: ${error}`);
throw error;
}
}
/**
* Gets statistics about the FTS index (synchronous)
* Includes fallback when dbstat is not available
*/
getIndexStats(): {
totalDocuments: number;
indexSize: number;
isOptimized: boolean;
dbstatAvailable: boolean;
} {
if (!this.checkFTS5Availability()) {
return {
totalDocuments: 0,
indexSize: 0,
isOptimized: false,
dbstatAvailable: false
};
}
const totalDocuments = sql.getValue<number>(`
SELECT COUNT(*) FROM notes_fts
`) || 0;
let indexSize = 0;
let dbstatAvailable = false;
try {
// Try to get index size from dbstat
// dbstat is a virtual table that may not be available in all SQLite builds
indexSize = sql.getValue<number>(`
SELECT SUM(pgsize)
FROM dbstat
WHERE name LIKE 'notes_fts%'
`) || 0;
dbstatAvailable = true;
} catch (error: any) {
// dbstat not available, use fallback
if (error.message?.includes('no such table: dbstat')) {
log.info("dbstat virtual table not available, using fallback for index size estimation");
// Fallback: Estimate based on number of documents and average content size
try {
const avgContentSize = sql.getValue<number>(`
SELECT AVG(LENGTH(content) + LENGTH(title))
FROM notes_fts
LIMIT 1000
`) || 0;
// Rough estimate: avg size * document count * overhead factor
indexSize = Math.round(avgContentSize * totalDocuments * 1.5);
} catch (fallbackError) {
log.info(`Could not estimate index size: ${fallbackError}`);
indexSize = 0;
}
} else {
log.error(`Error accessing dbstat: ${error}`);
}
}
return {
totalDocuments,
indexSize,
isOptimized: true, // FTS5 manages optimization internally
dbstatAvailable
};
}
}
// Export singleton instance
export const ftsSearchService = new FTSSearchService();
export default ftsSearchService;

View File

@@ -62,6 +62,10 @@ class NoteSet {
return newNoteSet;
}
getNoteIds(): Set<string> {
return new Set(this.noteIdSet);
}
}
export default NoteSet;

View File

@@ -0,0 +1,178 @@
/**
* Performance monitoring utilities for search operations
*/
import log from "../log.js";
import optionService from "../options.js";
export interface SearchMetrics {
query: string;
backend: "typescript" | "sqlite";
totalTime: number;
parseTime?: number;
searchTime?: number;
resultCount: number;
memoryUsed?: number;
cacheHit?: boolean;
error?: string;
}
export interface DetailedMetrics extends SearchMetrics {
phases?: {
name: string;
duration: number;
}[];
sqliteStats?: {
rowsScanned?: number;
indexUsed?: boolean;
tempBTreeUsed?: boolean;
};
}
interface SearchPerformanceAverages {
avgTime: number;
avgResults: number;
totalQueries: number;
errorRate: number;
}
class PerformanceMonitor {
private metrics: SearchMetrics[] = [];
private maxMetricsStored = 1000;
private metricsEnabled = false;
constructor() {
// Check if performance logging is enabled
this.updateSettings();
}
updateSettings() {
try {
this.metricsEnabled = optionService.getOptionBool("searchSqlitePerformanceLogging");
} catch {
this.metricsEnabled = false;
}
}
startTimer(): () => number {
const startTime = process.hrtime.bigint();
return () => {
const endTime = process.hrtime.bigint();
return Number(endTime - startTime) / 1_000_000; // Convert to milliseconds
};
}
recordMetrics(metrics: SearchMetrics) {
if (!this.metricsEnabled) {
return;
}
this.metrics.push(metrics);
// Keep only the last N metrics
if (this.metrics.length > this.maxMetricsStored) {
this.metrics = this.metrics.slice(-this.maxMetricsStored);
}
// Log significant performance differences
if (metrics.totalTime > 1000) {
log.info(`Slow search query detected: ${metrics.totalTime.toFixed(2)}ms for query "${metrics.query.substring(0, 100)}"`);
}
// Log to debug for analysis
log.info(`Search metrics: backend=${metrics.backend}, time=${metrics.totalTime.toFixed(2)}ms, results=${metrics.resultCount}, query="${metrics.query.substring(0, 50)}"`);
}
recordDetailedMetrics(metrics: DetailedMetrics) {
if (!this.metricsEnabled) {
return;
}
this.recordMetrics(metrics);
// Log detailed phase information
if (metrics.phases) {
const phaseLog = metrics.phases
.map(p => `${p.name}=${p.duration.toFixed(2)}ms`)
.join(", ");
log.info(`Search phases: ${phaseLog}`);
}
// Log SQLite specific stats
if (metrics.sqliteStats) {
log.info(`SQLite stats: rows_scanned=${metrics.sqliteStats.rowsScanned}, index_used=${metrics.sqliteStats.indexUsed}`);
}
}
getRecentMetrics(count: number = 100): SearchMetrics[] {
return this.metrics.slice(-count);
}
getAverageMetrics(backend?: "typescript" | "sqlite"): SearchPerformanceAverages | null {
let relevantMetrics = this.metrics;
if (backend) {
relevantMetrics = this.metrics.filter(m => m.backend === backend);
}
if (relevantMetrics.length === 0) {
return null;
}
const totalTime = relevantMetrics.reduce((sum, m) => sum + m.totalTime, 0);
const totalResults = relevantMetrics.reduce((sum, m) => sum + m.resultCount, 0);
const errorCount = relevantMetrics.filter(m => m.error).length;
return {
avgTime: totalTime / relevantMetrics.length,
avgResults: totalResults / relevantMetrics.length,
totalQueries: relevantMetrics.length,
errorRate: errorCount / relevantMetrics.length
};
}
compareBackends(): {
typescript: SearchPerformanceAverages;
sqlite: SearchPerformanceAverages;
recommendation?: string;
} {
const tsMetrics = this.getAverageMetrics("typescript");
const sqliteMetrics = this.getAverageMetrics("sqlite");
let recommendation: string | undefined;
if (tsMetrics && sqliteMetrics) {
const speedupFactor = tsMetrics.avgTime / sqliteMetrics.avgTime;
if (speedupFactor > 1.5) {
recommendation = `SQLite is ${speedupFactor.toFixed(1)}x faster on average`;
} else if (speedupFactor < 0.67) {
recommendation = `TypeScript is ${(1/speedupFactor).toFixed(1)}x faster on average`;
} else {
recommendation = "Both backends perform similarly";
}
// Consider error rates
if (sqliteMetrics.errorRate > tsMetrics.errorRate + 0.1) {
recommendation += " (but SQLite has higher error rate)";
} else if (tsMetrics.errorRate > sqliteMetrics.errorRate + 0.1) {
recommendation += " (but TypeScript has higher error rate)";
}
}
return {
typescript: tsMetrics || { avgTime: 0, avgResults: 0, totalQueries: 0, errorRate: 0 },
sqlite: sqliteMetrics || { avgTime: 0, avgResults: 0, totalQueries: 0, errorRate: 0 },
recommendation
};
}
reset() {
this.metrics = [];
}
}
// Singleton instance
const performanceMonitor = new PerformanceMonitor();
export default performanceMonitor;

View File

@@ -401,7 +401,8 @@ function parseQueryToExpression(query: string, searchContext: SearchContext) {
}
function searchNotes(query: string, params: SearchParams = {}): BNote[] {
const searchResults = findResultsWithQuery(query, new SearchContext(params));
const searchContext = new SearchContext(params);
const searchResults = findResultsWithQuery(query, searchContext);
return searchResults.map((sr) => becca.notes[sr.noteId]);
}
@@ -417,16 +418,20 @@ function findResultsWithQuery(query: string, searchContext: SearchContext): Sear
}
// If the query starts with '#', it's a pure expression query.
// Don't use progressive search for these as they may have complex
// Don't use progressive search for these as they may have complex
// ordering or other logic that shouldn't be interfered with.
const isPureExpressionQuery = query.trim().startsWith('#');
let results: SearchResult[];
if (isPureExpressionQuery) {
// For pure expression queries, use standard search without progressive phases
return performSearch(expression, searchContext, searchContext.enableFuzzyMatching);
results = performSearch(expression, searchContext, searchContext.enableFuzzyMatching);
} else {
results = findResultsWithExpression(expression, searchContext);
}
return findResultsWithExpression(expression, searchContext);
return results;
}
function findFirstNoteWithQuery(query: string, searchContext: SearchContext): BNote | null {

View File

@@ -0,0 +1,113 @@
/**
* Tests for SQLite custom functions service
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import Database from 'better-sqlite3';
import { SqliteFunctionsService, getSqliteFunctionsService } from './sqlite_functions.js';
describe('SqliteFunctionsService', () => {
let db: Database.Database;
let service: SqliteFunctionsService;
beforeEach(() => {
// Create in-memory database for testing
db = new Database(':memory:');
service = getSqliteFunctionsService();
// Reset registration state
service.unregister();
});
afterEach(() => {
db.close();
});
describe('Service Registration', () => {
it('should register functions successfully', () => {
const result = service.registerFunctions(db);
expect(result).toBe(true);
expect(service.isRegistered()).toBe(true);
});
it('should not re-register if already registered', () => {
service.registerFunctions(db);
const result = service.registerFunctions(db);
expect(result).toBe(true); // Still returns true but doesn't re-register
expect(service.isRegistered()).toBe(true);
});
it('should handle registration errors gracefully', () => {
// Close the database to cause registration to fail
db.close();
const result = service.registerFunctions(db);
expect(result).toBe(false);
expect(service.isRegistered()).toBe(false);
});
});
describe('edit_distance function', () => {
beforeEach(() => {
service.registerFunctions(db);
});
it('should calculate edit distance correctly', () => {
const tests = [
['hello', 'hello', 0],
['hello', 'hallo', 1],
['hello', 'help', 2],
['hello', 'world', 4],
['', '', 0],
['abc', '', 3],
['', 'abc', 3],
];
for (const [str1, str2, expected] of tests) {
const result = db.prepare('SELECT edit_distance(?, ?, 5) as distance').get(str1, str2) as any;
expect(result.distance).toBe((expected as number) <= 5 ? (expected as number) : 6);
}
});
it('should respect max distance threshold', () => {
const result = db.prepare('SELECT edit_distance(?, ?, ?) as distance')
.get('hello', 'world', 2) as any;
expect(result.distance).toBe(3); // Returns maxDistance + 1 when exceeded
});
it('should handle null inputs', () => {
const result = db.prepare('SELECT edit_distance(?, ?, 2) as distance').get(null, 'test') as any;
expect(result.distance).toBe(3); // Treats null as empty string, distance exceeds max
});
});
describe('regex_match function', () => {
beforeEach(() => {
service.registerFunctions(db);
});
it('should match regex patterns correctly', () => {
const tests = [
['hello world', 'hello', 1],
['hello world', 'HELLO', 1], // Case insensitive by default
['hello world', '^hello', 1],
['hello world', 'world$', 1],
['hello world', 'foo', 0],
['test@example.com', '\\w+@\\w+\\.\\w+', 1],
];
for (const [text, pattern, expected] of tests) {
const result = db.prepare("SELECT regex_match(?, ?, 'i') as match").get(text, pattern) as any;
expect(result.match).toBe(expected);
}
});
it('should handle invalid regex gracefully', () => {
const result = db.prepare("SELECT regex_match(?, ?, 'i') as match").get('test', '[invalid') as any;
expect(result.match).toBe(null); // Returns null for invalid regex
});
it('should handle null inputs', () => {
const result = db.prepare("SELECT regex_match(?, ?, 'i') as match").get(null, 'test') as any;
expect(result.match).toBe(0);
});
});
});

View File

@@ -0,0 +1,284 @@
/**
* SQLite Custom Functions Service
*
* This service manages custom SQLite functions for general database operations.
* Functions are registered with better-sqlite3 to provide native-speed operations
* directly within SQL queries.
*
* These functions are used by:
* - Fuzzy search fallback (edit_distance)
* - Regular expression matching (regex_match)
*/
import type { Database } from "better-sqlite3";
import log from "../log.js";
/**
* Configuration for fuzzy search operations
*/
const FUZZY_CONFIG = {
MAX_EDIT_DISTANCE: 2,
MIN_TOKEN_LENGTH: 3,
MAX_STRING_LENGTH: 1000, // Performance guard for edit distance
} as const;
/**
* Interface for registering a custom SQL function
*/
interface SQLiteFunction {
name: string;
implementation: (...args: any[]) => any;
options?: {
deterministic?: boolean;
varargs?: boolean;
directOnly?: boolean;
};
}
/**
* Manages registration and lifecycle of custom SQLite functions
*/
export class SqliteFunctionsService {
private static instance: SqliteFunctionsService | null = null;
private registered = false;
private functions: SQLiteFunction[] = [];
private constructor() {
// Initialize the function definitions
this.initializeFunctions();
}
/**
* Get singleton instance of the service
*/
static getInstance(): SqliteFunctionsService {
if (!SqliteFunctionsService.instance) {
SqliteFunctionsService.instance = new SqliteFunctionsService();
}
return SqliteFunctionsService.instance;
}
/**
* Initialize all custom function definitions
*/
private initializeFunctions(): void {
// Bind all methods to preserve 'this' context
this.functions = [
{
name: "edit_distance",
implementation: this.editDistance.bind(this),
options: {
deterministic: true,
varargs: true // Changed to true to handle variable arguments
}
},
{
name: "regex_match",
implementation: this.regexMatch.bind(this),
options: {
deterministic: true,
varargs: true // Changed to true to handle variable arguments
}
}
];
}
/**
* Register all custom functions with the database connection
*
* @param db The better-sqlite3 database connection
* @returns true if registration was successful, false otherwise
*/
registerFunctions(db: Database): boolean {
if (this.registered) {
log.info("SQLite custom functions already registered");
return true;
}
try {
// Test if the database connection is valid first
// This will throw if the database is closed
db.pragma("user_version");
log.info("Registering SQLite custom functions...");
let successCount = 0;
for (const func of this.functions) {
try {
db.function(func.name, func.options || {}, func.implementation);
log.info(`Registered SQLite function: ${func.name}`);
successCount++;
} catch (error) {
log.error(`Failed to register SQLite function ${func.name}: ${error}`);
// Continue registering other functions even if one fails
}
}
// Only mark as registered if at least some functions were registered
if (successCount > 0) {
this.registered = true;
log.info(`SQLite custom functions registration completed (${successCount}/${this.functions.length})`);
return true;
} else {
log.error("No SQLite functions could be registered");
return false;
}
} catch (error) {
log.error(`Failed to register SQLite custom functions: ${error}`);
return false;
}
}
/**
* Unregister all custom functions (for cleanup/testing)
* Note: better-sqlite3 doesn't provide a way to unregister functions,
* so this just resets the internal state
*/
unregister(): void {
this.registered = false;
}
/**
* Check if functions are currently registered
*/
isRegistered(): boolean {
return this.registered;
}
// ===== Function Implementations =====
/**
* Calculate Levenshtein edit distance between two strings
* Optimized with early termination and single-array approach
*
* SQLite will pass 2 or 3 arguments:
* - 2 args: str1, str2 (uses default maxDistance)
* - 3 args: str1, str2, maxDistance
*
* @returns Edit distance or maxDistance + 1 if exceeded
*/
private editDistance(...args: any[]): number {
// Handle variable arguments from SQLite
let str1: string | null | undefined = args[0];
let str2: string | null | undefined = args[1];
let maxDistance: number = args.length > 2 ? args[2] : FUZZY_CONFIG.MAX_EDIT_DISTANCE;
// Handle null/undefined inputs
if (!str1 || typeof str1 !== 'string') str1 = '';
if (!str2 || typeof str2 !== 'string') str2 = '';
// Validate and sanitize maxDistance
if (typeof maxDistance !== 'number' || !Number.isFinite(maxDistance)) {
maxDistance = FUZZY_CONFIG.MAX_EDIT_DISTANCE;
} else {
// Ensure it's a positive integer
maxDistance = Math.max(0, Math.floor(maxDistance));
}
const len1 = str1.length;
const len2 = str2.length;
// Performance guard for very long strings
if (len1 > FUZZY_CONFIG.MAX_STRING_LENGTH || len2 > FUZZY_CONFIG.MAX_STRING_LENGTH) {
return Math.abs(len1 - len2) <= maxDistance ? Math.abs(len1 - len2) : maxDistance + 1;
}
// Early termination: length difference exceeds max
if (Math.abs(len1 - len2) > maxDistance) {
return maxDistance + 1;
}
// Handle edge cases
if (len1 === 0) return len2 <= maxDistance ? len2 : maxDistance + 1;
if (len2 === 0) return len1 <= maxDistance ? len1 : maxDistance + 1;
// Single-array optimization for memory efficiency
let previousRow = Array.from({ length: len2 + 1 }, (_, i) => i);
let currentRow = new Array(len2 + 1);
for (let i = 1; i <= len1; i++) {
currentRow[0] = i;
let minInRow = i;
for (let j = 1; j <= len2; j++) {
const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
currentRow[j] = Math.min(
previousRow[j] + 1, // deletion
currentRow[j - 1] + 1, // insertion
previousRow[j - 1] + cost // substitution
);
if (currentRow[j] < minInRow) {
minInRow = currentRow[j];
}
}
// Early termination: minimum distance in row exceeds threshold
if (minInRow > maxDistance) {
return maxDistance + 1;
}
// Swap arrays for next iteration
[previousRow, currentRow] = [currentRow, previousRow];
}
const result = previousRow[len2];
return result <= maxDistance ? result : maxDistance + 1;
}
/**
* Test if a string matches a JavaScript regular expression
*
* SQLite will pass 2 or 3 arguments:
* - 2 args: text, pattern (uses default flags 'i')
* - 3 args: text, pattern, flags
*
* @returns 1 if match, 0 if no match, null on error
*/
private regexMatch(...args: any[]): number | null {
// Handle variable arguments from SQLite
let text: string | null | undefined = args[0];
let pattern: string | null | undefined = args[1];
let flags: string = args.length > 2 ? args[2] : 'i';
if (!text || !pattern) {
return 0;
}
if (typeof text !== 'string' || typeof pattern !== 'string') {
return null;
}
try {
// Validate flags
const validFlags = ['i', 'g', 'm', 's', 'u', 'y'];
const flagsArray = (flags || '').split('');
if (!flagsArray.every(f => validFlags.includes(f))) {
flags = 'i'; // Fall back to case-insensitive
}
const regex = new RegExp(pattern, flags);
return regex.test(text) ? 1 : 0;
} catch (error) {
// Invalid regex pattern
log.error(`Invalid regex pattern in SQL: ${pattern} - ${error}`);
return null;
}
}
}
// Export singleton instance getter
export function getSqliteFunctionsService(): SqliteFunctionsService {
return SqliteFunctionsService.getInstance();
}
/**
* Initialize SQLite custom functions with the given database connection
* This should be called once during application startup after the database is opened
*
* @param db The better-sqlite3 database connection
* @returns true if successful, false otherwise
*/
export function initializeSqliteFunctions(db: Database): boolean {
const service = getSqliteFunctionsService();
return service.registerFunctions(db);
}

View File

@@ -14,6 +14,7 @@ import ws from "./ws.js";
import becca_loader from "../becca/becca_loader.js";
import entity_changes from "./entity_changes.js";
import config from "./config.js";
import { initializeSqliteFunctions } from "./search/sqlite_functions.js";
const dbOpts: Database.Options = {
nativeBinding: process.env.BETTERSQLITE3_NATIVE_PATH || undefined
@@ -49,12 +50,33 @@ function rebuildIntegrationTestDatabase(dbPath?: string) {
// This allows a database that is read normally but is kept in memory and discards all modifications.
dbConnection = buildIntegrationTestDatabase(dbPath);
statementCache = {};
// Re-register custom SQLite functions after rebuilding the database
try {
initializeSqliteFunctions(dbConnection);
} catch (error) {
log.error(`Failed to re-initialize SQLite custom functions after rebuild: ${error}`);
}
}
if (!process.env.TRILIUM_INTEGRATION_TEST) {
dbConnection.pragma("journal_mode = WAL");
}
// Initialize custom SQLite functions for search operations
// This must happen after the database connection is established
try {
const functionsRegistered = initializeSqliteFunctions(dbConnection);
if (functionsRegistered) {
log.info("SQLite custom search functions initialized successfully");
} else {
log.info("SQLite custom search functions initialization failed - search will use fallback methods");
}
} catch (error) {
log.error(`Failed to initialize SQLite custom functions: ${error}`);
// Continue without custom functions - triggers will use LOWER() as fallback
}
const LOG_ALL_QUERIES = false;
type Params = any;
@@ -367,6 +389,10 @@ function disableSlowQueryLogging<T>(cb: () => T) {
}
}
function getDbConnection(): DatabaseType {
return dbConnection;
}
export default {
insert,
replace,
@@ -434,5 +460,6 @@ export default {
fillParamList,
copyDatabase,
disableSlowQueryLogging,
rebuildIntegrationTestDatabase
rebuildIntegrationTestDatabase,
getDbConnection
};

View File

@@ -67,6 +67,21 @@ async function initDbConnection() {
PRIMARY KEY (tmpID)
);`)
// Register SQLite search functions after database is ready
try {
const { getSqliteFunctionsService } = await import("./search/sqlite_functions.js");
const functionsService = getSqliteFunctionsService();
const db = sql.getDbConnection();
if (functionsService.registerFunctions(db)) {
log.info("SQLite search functions registered successfully");
} else {
log.info("SQLite search functions registration skipped (already registered)");
}
} catch (error) {
log.error(`Failed to register SQLite search functions: ${error}`);
}
dbReady.resolve();
}

View File

@@ -1 +1,8 @@
{}
{
"get-started": {
"title": "Loslegen",
"desktop_title": "Die Desktop-App herunterladen (v{{version}})",
"architecture": "Architektur:",
"older_releases": "Ältere Releases anzeigen"
}
}

View File

@@ -2,7 +2,7 @@
"get-started": {
"title": "Commencer",
"desktop_title": "Télécharger l'application de bureau (v{{version}})",
"architecture": "Architecture:",
"architecture": "Architecture :",
"older_releases": "Voir les versions plus anciennes",
"server_title": "Configurer un serveur pour accéder à plusieurs appareils"
},
@@ -41,7 +41,17 @@
"note_types": {
"text_title": "Notes de texte",
"text_description": "Les notes sont éditées à l'aide d'un éditeur visuel (WYSIWYG) prenant en charge les tableaux, les images, les expressions mathématiques et les blocs de code avec coloration syntaxique. Formatez rapidement le texte grâce à une syntaxe de type Markdown ou à des commandes slash.",
"code_title": "Notes de code"
"code_title": "Notes de code",
"code_description": "De grands échantillons de code source ou de scripts utilisent un éditeur dédié, avec une coloration syntaxique pour de nombreux langages de programmation et avec différents thèmes de couleurs.",
"file_title": "Notes de fichier",
"file_description": "Intégrez des fichiers multimédias tels que des PDF, des images, des vidéos avec un aperçu intégré à l'application.",
"canvas_title": "Canvas",
"canvas_description": "Agencez formes, images et textes sur une surface infinie grâce à la même technologie qu'excalidraw.com. Idéal pour les diagrammes, les croquis et la planification visuelle.",
"mermaid_title": "Diagrammes Mermaid",
"mermaid_description": "Créez des diagrammes tels que des organigrammes, des diagrammes de classes et de séquences, des diagrammes de Gantt et bien d'autres, en utilisant la syntaxe Mermaid.",
"mindmap_title": "Carte mentale",
"mindmap_description": "Organisez vos pensées visuellement ou faites une séance de brainstorming.",
"others_list": "et autres : <0>carte de notes</0>, <1>carte de relations</1>, <2>recherches enregistrées</2>, <3>note de rendu</3> et <4>vues Web</4>."
},
"faq": {
"database_question": "Où sont les données stockées?",
@@ -64,7 +74,8 @@
"get_started": "Commencer"
},
"components": {
"link_learn_more": "En savoir plus..."
"link_learn_more": "En savoir plus...",
"list_with_screenshot_alt": "Capture d'écran de la fonctionnalité sélectionnée"
},
"support_us": {
"financial_donations_title": "Dons financiers",
@@ -72,7 +83,8 @@
"financial_donations_cta": "Envisagez de soutenir le développeur principal (<Link>eliandoran</Link>) de l'application via :",
"github_sponsors": "Sponsors GitHub",
"paypal": "PayPal",
"buy_me_a_coffee": "Offrez-moi un café"
"buy_me_a_coffee": "Offrez-moi un café",
"title": "Soutenez-nous"
},
"contribute": {
"title": "Autres façons de contribuer",
@@ -137,5 +149,44 @@
"description": "Notes Trilium hébergées sur PikaPods, un service payant pour un accès et une gestion simplifiés. Non affilié directement à l'équipe Trilium.",
"download_pikapod": "Installé sur PikaPods",
"download_triliumcc": "Voir également trilium.cc"
},
"extensibility_benefits": {
"title": "Partage et extensibilité",
"import_export_title": "Import/export",
"import_export_description": "Interagissez facilement avec d'autres applications utilisant les formats Markdown, ENEX, OML.",
"share_title": "Partager des notes sur le Web",
"share_description": "Si vous disposez d'un serveur, vous pouvez l'utiliser pour partager un sous-ensemble de vos notes avec d'autres personnes.",
"scripting_title": "Scripts avancés",
"scripting_description": "Créez vos propres intégrations dans Trilium avec des widgets personnalisés ou une logique côté serveur.",
"api_title": "REST API",
"api_description": "Interagissez avec Trilium par programmation à l'aide de son API REST intégrée."
},
"collections": {
"calendar_title": "Calendrier",
"calendar_description": "Organisez vos événements personnels ou professionnels grâce à un calendrier compatible avec les événements d'une journée ou de plusieurs jours. Visualisez vos événements en un coup d'œil grâce aux vues hebdomadaire, mensuelle et annuelle. Ajoutez ou déplacez facilement des événements.",
"table_title": "Tableau",
"table_description": "Affichez et modifiez les informations relatives aux notes dans une structure tabulaire, avec différents types de colonnes (texte, nombre, cases à cocher, date et heure, liens, couleurs) et la prise en charge des relations. Vous pouvez également afficher les notes sous forme d'arborescence à l'intérieur du tableau.",
"board_title": "Tableau de bord",
"board_description": "Organisez vos tâches ou l'état de vos projets dans un tableau Kanban avec un moyen simple de créer de nouveaux éléments et colonnes et de modifier simplement leur état en les faisant glisser sur le tableau.",
"geomap_title": "Géocarte",
"geomap_description": "Planifiez vos vacances ou marquez vos points d'intérêt directement sur une carte géographique grâce à des marqueurs personnalisables. Affichez les traces GPX enregistrées pour suivre vos itinéraires."
},
"download_now": {
"text": "Télécharger maintenant. ",
"platform_big": "v{{version}} pour {{platform}}",
"platform_small": "pour {{platform}}",
"linux_big": "v{{version}} pour Linux",
"linux_small": "pour Linux",
"more_platforms": "Plus de plateformes et de configuration de serveur"
},
"footer": {
"copyright_and_the": " et le ",
"copyright_community": "communauté"
},
"social_buttons": {
"github": "GitHub",
"github_discussions": "Discussions GitHub",
"matrix": "Matrix",
"reddit": "Reddit"
}
}

View File

@@ -1 +1,50 @@
{}
{
"get-started": {
"title": "Почати",
"desktop_title": "Завантажити програму для ПК (v{{version}})",
"architecture": "Архітектура:",
"older_releases": "Дивитися старіші випуски",
"server_title": "Налаштуйте сервер для доступу на кількох пристроях"
},
"hero_section": {
"title": "Упорядкуйте свої думки. Створіть свою особисту базу знань.",
"subtitle": "Trilium — це рішення з відкритим кодом для ведення нотаток та організації особистої бази знань. Використовуйте його локально на своєму робочому столі або синхронізуйте зі своїм власним сервером, щоб мати свої нотатки під рукою, де б ви не були.",
"get_started": "Почати",
"github": "GitHub",
"dockerhub": "Docker Hub",
"screenshot_alt": "Знімок екрана програми Trilium Notes для ПК"
},
"organization_benefits": {
"title": "Організація",
"note_structure_title": "Структура нотатки",
"note_structure_description": "Нотатки можна впорядковувати ієрархічно. Немає потреби в папках, оскільки кожна нотатка може містити піднотатки. Одну нотатку можна додати в кілька місць в ієрархії.",
"attributes_title": "Мітки та зв'язки нотаток",
"attributes_description": "Використовуйте зв'язки між нотатками або додавайте мітки для легкої категоризації. Використовуйте підвищені атрибути для введення структурованої інформації, яку можна використовувати в таблицях, на дошках.",
"hoisting_title": "Робочі області та хостинг",
"hoisting_description": "Легко розділяйте особисті нотатки та робочі, групуючи їх у робочій області, що фокусує ваше дерево нотаток на відображенні лише певного набору нотаток."
},
"productivity_benefits": {
"title": "Продуктивність та безпека",
"revisions_title": "Ревізії нотаток",
"revisions_content": "Нотатки періодично зберігаються у фоновому режимі, а ревізії можна використовувати для перегляду або скасування випадкових змін. Ревізії також можна створювати на вимогу.",
"sync_title": "Синхронізація",
"sync_content": "Використовуйте власний або хмарний екземпляр, щоб легко синхронізувати нотатки на кількох пристроях та отримувати до них доступ з мобільного телефону за допомогою PWA.",
"protected_notes_title": "Захищені нотатки",
"protected_notes_content": "Захистіть конфіденційну особисту інформацію, зашифрувавши нотатки та заблокувавши їх за сеансом, захищеним паролем.",
"jump_to_title": "Швидкий пошук і команди",
"jump_to_content": "Швидко переходьте до нотаток або команд інтерфейсу користувача в ієрархії, шукаючи їх за назвою, з нечітким зіставленням для врахування друкарських помилок або незначних відмінностей.",
"search_title": "Потужний пошук",
"search_content": "Або шукайте текст усередині нотаток та звузьте пошук, відфільтрувавши за батьківською нотаткою чи за глибиною.",
"web_clipper_title": "Web-кліпер",
"web_clipper_content": "Зберіть веб-сторінки (або скріншоти) та розмістіть їх безпосередньо в Trilium за допомогою розширення браузера Web Clipper."
},
"note_types": {
"text_title": "Текстові нотатки",
"text_description": "Нотатки редагуються за допомогою візуального (WYSIWYG) редактора з підтримкою таблиць, зображень, математичних виразів, блоків коду з підсвічуванням синтаксису. Швидко форматуйте текст, використовуючи синтаксис, подібний до Markdown, або використовуючи команди зі слеш-рисками.",
"code_title": "Нотатки з кодом",
"code_description": "Великі зразки вихідного коду або скриптів використовують спеціальний редактор із підсвічуванням синтаксису для багатьох мов програмування та різними колірними темами.",
"file_title": "Файлові нотатки",
"file_description": "Вбудовуйте мультимедійні файли, такі як PDF-файли, зображення, відео, з попереднім переглядом у програмі.",
"canvas_title": "Полотно"
}
}

View File

@@ -13,5 +13,12 @@
"github": "Github",
"dockerhub": "Kho Docker",
"screenshot_alt": "Ảnh chụp màn hình ứng dụng Trilium Notes (desktop)"
},
"organization_benefits": {
"title": "Tổ chức",
"note_structure_title": "Cấu trúc ghi chú",
"note_structure_description": "Ghi chú có thể được sắp xếp theo thứ bậc. Không cần thư mục, vì mỗi ghi chú có thể chứa các ghi chú phụ. Một ghi chú có thể được thêm vào nhiều vị trí trong hệ thống phân cấp.",
"attributes_title": "Các nhãn ghi chú và các mối quan hệ",
"attributes_description": "Sử dụng mối quan hệ giữa các ghi chú hoặc thêm nhãn để phân loại dễ dàng. Sử dụng các thuộc tính được khuyến khích để nhập thông tin có cấu trúc có thể được sử dụng trong bảng, bảng biểu."
}
}

2
docs/README-ar.md vendored
View File

@@ -33,7 +33,7 @@ quick overview:
<a href="https://triliumnext.github.io/Docs/Wiki/screenshot-tour"><img src="./docs/app.png" alt="Trilium Screenshot" width="1000"></a>
## ⏬ Download
## ⬇️ تنزيل
- [Latest release](https://github.com/TriliumNext/Trilium/releases/latest)
stable version, recommended for most users.
- [Nightly build](https://github.com/TriliumNext/Trilium/releases/tag/nightly)

149
docs/README-uk.md vendored
View File

@@ -11,103 +11,104 @@
# Trilium Notes
![GitHub Sponsors](https://img.shields.io/github/sponsors/eliandoran)
![LiberaPay patrons](https://img.shields.io/liberapay/patrons/ElianDoran)\
![Спонсори GitHub](https://img.shields.io/github/sponsors/eliandoran)
![Користувачі LiberaPay](https://img.shields.io/liberapay/patrons/ElianDoran)\
![Docker Pulls](https://img.shields.io/docker/pulls/triliumnext/trilium)
![GitHub Downloads (all assets, all
releases)](https://img.shields.io/github/downloads/triliumnext/trilium/total)\
![Завантаження GitHub (всі ресурси, всі
релізи)](https://img.shields.io/github/downloads/triliumnext/trilium/total)\
[![RelativeCI](https://badges.relative-ci.com/badges/Di5q7dz9daNDZ9UXi0Bp?branch=develop)](https://app.relative-ci.com/projects/Di5q7dz9daNDZ9UXi0Bp)
[![Translation
status](https://hosted.weblate.org/widget/trilium/svg-badge.svg)](https://hosted.weblate.org/engage/trilium/)
[![Статус
перекладу](https://hosted.weblate.org/widget/trilium/svg-badge.svg)](https://hosted.weblate.org/engage/trilium/)
[English](./README.md) | [Chinese (Simplified)](./docs/README-ZH_CN.md) |
[Chinese (Traditional)](./docs/README-ZH_TW.md) | [Russian](./docs/README-ru.md)
| [Japanese](./docs/README-ja.md) | [Italian](./docs/README-it.md) |
[Spanish](./docs/README-es.md)
Trilium Notes is a free and open-source, cross-platform hierarchical note taking
application with focus on building large personal knowledge bases.
Trilium Notes — це безкоштовний кросплатформний ієрархічний додаток для ведення
нотаток з відкритим кодом, орієнтований на створення великих персональних баз
знань.
See [screenshots](https://triliumnext.github.io/Docs/Wiki/screenshot-tour) for
quick overview:
Див. [скріншоти](https://triliumnext.github.io/Docs/Wiki/screenshot-tour) для
швидкого перегляду:
<a href="https://triliumnext.github.io/Docs/Wiki/screenshot-tour"><img src="./docs/app.png" alt="Trilium Screenshot" width="1000"></a>
## ⏬ Download
## ⏬ Завантажити
- [Latest release](https://github.com/TriliumNext/Trilium/releases/latest)
stable version, recommended for most users.
стабільна версія, рекомендована для більшості користувачів.
- [Nightly build](https://github.com/TriliumNext/Trilium/releases/tag/nightly)
unstable development version, updated daily with the latest features and
fixes.
нестабільна версія для розробників, щодня оновлюється найновішими функціями та
виправленнями.
## 📚 Documentation
## 📚 Документація
**Visit our comprehensive documentation at
**Відвідайте нашу вичерпну документацію за адресою
[docs.triliumnotes.org](https://docs.triliumnotes.org/)**
Our documentation is available in multiple formats:
- **Online Documentation**: Browse the full documentation at
Наша документація доступна в кількох форматах:
- **Онлайн-документація**: Перегляньте повну документацію на сайті
[docs.triliumnotes.org](https://docs.triliumnotes.org/)
- **In-App Help**: Press `F1` within Trilium to access the same documentation
directly in the application
- **GitHub**: Navigate through the [User
Guide](./docs/User%20Guide/User%20Guide/) in this repository
- **Довідка в додатку**: Натисніть `F1` у Trilium, щоб отримати доступ до тієї ж
документації безпосередньо в додатку
- **GitHub**: Перегляд [Посібника
користувача](./docs/User%20Guide/User%20Guide/) у цьому репозиторії
### Quick Links
- [Getting Started Guide](https://docs.triliumnotes.org/)
- [Installation
Instructions](./docs/User%20Guide/User%20Guide/Installation%20&%20Setup/Server%20Installation.md)
- [Docker
Setup](./docs/User%20Guide/User%20Guide/Installation%20&%20Setup/Server%20Installation/1.%20Installing%20the%20server/Using%20Docker.md)
- [Upgrading
### Швидкі посилання
- [Посібник із початку роботи](https://docs.triliumnotes.org/)
- [Інструкції з
встановлення](./docs/User%20Guide/User%20Guide/Installation%20&%20Setup/Server%20Installation.md)
- [Налаштування
Docker](./docs/User%20Guide/User%20Guide/Installation%20&%20Setup/Server%20Installation/1.%20Installing%20the%20server/Using%20Docker.md)
- [Оновлення
TriliumNext](./docs/User%20Guide/User%20Guide/Installation%20%26%20Setup/Upgrading%20TriliumNext.md)
- [Basic Concepts and
Features](./docs/User%20Guide/User%20Guide/Basic%20Concepts%20and%20Features/Notes.md)
- [Patterns of Personal Knowledge
Base](https://triliumnext.github.io/Docs/Wiki/patterns-of-personal-knowledge)
- [Основні поняття та
функції](./docs/User%20Guide/User%20Guide/Basic%20Concepts%20and%20Features/Notes.md)
- [Шаблони особистої бази
знань](https://triliumnext.github.io/Docs/Wiki/patterns-of-personal-knowledge)
## 🎁 Features
## 🎁 Можливості
* Notes can be arranged into arbitrarily deep tree. Single note can be placed
into multiple places in the tree (see
[cloning](https://triliumnext.github.io/Docs/Wiki/cloning-notes))
* Rich WYSIWYG note editor including e.g. tables, images and
[math](https://triliumnext.github.io/Docs/Wiki/text-notes) with markdown
[autoformat](https://triliumnext.github.io/Docs/Wiki/text-notes#autoformat)
* Support for editing [notes with source
code](https://triliumnext.github.io/Docs/Wiki/code-notes), including syntax
highlighting
* Fast and easy [navigation between
notes](https://triliumnext.github.io/Docs/Wiki/note-navigation), full text
search and [note
hoisting](https://triliumnext.github.io/Docs/Wiki/note-hoisting)
* Seamless [note
versioning](https://triliumnext.github.io/Docs/Wiki/note-revisions)
* Note [attributes](https://triliumnext.github.io/Docs/Wiki/attributes) can be
used for note organization, querying and advanced
[scripting](https://triliumnext.github.io/Docs/Wiki/scripts)
* UI available in English, German, Spanish, French, Romanian, and Chinese
(simplified and traditional)
* Direct [OpenID and TOTP
integration](./docs/User%20Guide/User%20Guide/Installation%20%26%20Setup/Server%20Installation/Multi-Factor%20Authentication.md)
for more secure login
* [Synchronization](https://triliumnext.github.io/Docs/Wiki/synchronization)
with self-hosted sync server
* there's a [3rd party service for hosting synchronisation
server](https://trilium.cc/paid-hosting)
* [Sharing](https://triliumnext.github.io/Docs/Wiki/sharing) (publishing) notes
to public internet
* Strong [note
encryption](https://triliumnext.github.io/Docs/Wiki/protected-notes) with
per-note granularity
* Sketching diagrams, based on [Excalidraw](https://excalidraw.com/) (note type
"canvas")
* [Relation maps](https://triliumnext.github.io/Docs/Wiki/relation-map) and
[link maps](https://triliumnext.github.io/Docs/Wiki/link-map) for visualizing
notes and their relations
* Mind maps, based on [Mind Elixir](https://docs.mind-elixir.com/)
* [Geo maps](./docs/User%20Guide/User%20Guide/Note%20Types/Geo%20Map.md) with
location pins and GPX tracks
* Нотатки можна розташувати в дерево довільної глибини. Одну нотатку можна
розмістити в кількох місцях дерева (див.
[клонування](https://triliumnext.github.io/Docs/Wiki/cloning-notes))
* Багатий WYSIWYG-редактор нотаток, включаючи, наприклад, таблиці, зображення та
[математику](https://triliumnext.github.io/Docs/Wiki/text-notes) з markdown
[автоформат](https://triliumnext.github.io/Docs/Wiki/text-notes#autoformat)
* Підтримка редагування [нотатки з вихідним
кодом](https://triliumnext.github.io/Docs/Wiki/code-notes), включаючи
підсвічування синтаксису
* Швидка та проста [навігація між
нотатками](https://triliumnext.github.io/Docs/Wiki/note-navigation),
повнотекстовий пошук та [хостінг
нотаток](https://triliumnext.github.io/Docs/Wiki/note-hoisting)
* Безшовне [керування версіями
нотаток](https://triliumnext.github.io/Docs/Wiki/note-revisions)
* [Атрибути](https://triliumnext.github.io/Docs/Wiki/attributes) нотатки можна
використовувати для організації нотаток, запитів та розширеного
[сриптінгу](https://triliumnext.github.io/Docs/Wiki/scripts)
* Інтерфейс користувача доступний англійською, німецькою, іспанською,
французькою, румунською та китайською (спрощеною та традиційною) мовами
* Пряма [OpenID та TOTP
інтеграція](./docs/User%20Guide/User%20Guide/Installation%20%26%20Setup/Server%20Installation/Multi-Factor%20Authentication.md)
для безпечнішого входу
* [Синхронізація](https://triliumnext.github.io/Docs/Wiki/synchronization) із
власним сервером синхронізації
* існує [сторонній сервіс для розміщення сервера
синхронізації](https://trilium.cc/paid-hosting)
* [Спільне використання](https://triliumnext.github.io/Docs/Wiki/sharing)
(публікація) нотаток у загальнодоступному інтернеті
* Надійне [шифрування
нотаток](https://triliumnext.github.io/Docs/Wiki/protected-notes) з
деталізацією для кожної нотатки
* Створення ескізних схем на основі [Excalidraw](https://excalidraw.com/) (тип
нотатки "полотно")
* [Карти зв'язків](https://triliumnext.github.io/Docs/Wiki/relation-map) та
[карти посилань](https://triliumnext.github.io/Docs/Wiki/link-map) для
візуалізації нотаток та їх зв'язків
* Інтелект-карти, засновані на [Mind Elixir](https://docs.mind-elixir.com/)
* [Геокарти](./docs/User%20Guide/User%20Guide/Note%20Types/Geo%20Map.md) з
географічними позначками та GPX-треками
* [Scripting](https://triliumnext.github.io/Docs/Wiki/scripts) - see [Advanced
showcases](https://triliumnext.github.io/Docs/Wiki/advanced-showcases)
* [REST API](https://triliumnext.github.io/Docs/Wiki/etapi) for automation

14
docs/README-vi.md vendored
View File

@@ -33,12 +33,14 @@ Xem [ảnh chụp màn hình](https://triliumnext.github.io/Docs/Wiki/screenshot
<a href="https://triliumnext.github.io/Docs/Wiki/screenshot-tour"><img src="./docs/app.png" alt="Trilium Screenshot" width="1000"></a>
## ⏬ Download
- [Latest release](https://github.com/TriliumNext/Trilium/releases/latest)
stable version, recommended for most users.
- [Nightly build](https://github.com/TriliumNext/Trilium/releases/tag/nightly)
unstable development version, updated daily with the latest features and
fixes.
## ⏬ Tải xuống
- [Bản phát hành mới
nhất](https://github.com/TriliumNext/Trilium/releases/latest) phiên bản ổn
định, được khuyên dùng cho hầu hết người dùng.
- [Bản dựng
nightly](https://github.com/TriliumNext/Trilium/releases/tag/nightly) phiên
bản phát triển kém ổn định, được cập nhật hàng ngày với các tính năng mới nhất
và sửa lỗi.
## 📚 Tài Liệu