diff --git a/lib/common/navigation/app_bars/notes/notes_app_bar.dart b/lib/common/navigation/app_bars/notes/notes_app_bar.dart index fb491478..a1b4967e 100644 --- a/lib/common/navigation/app_bars/notes/notes_app_bar.dart +++ b/lib/common/navigation/app_bars/notes/notes_app_bar.dart @@ -19,6 +19,18 @@ import '../../../preferences/watched_preferences.dart'; import '../../../widgets/notes/note_tile.dart'; import '../../../widgets/placeholders/empty_placeholder.dart'; +/// How long the search waits for the user to stop typing. +const _searchDebounce = Duration(milliseconds: 300); + +/// The minimum number of characters of a search. +const _searchMinimumLength = 2; + +/// The number of searches started, to skip the outdated ones. +var _searchGeneration = 0; + +/// The latest search started. +Future>? _latestSearch; + /// Notes list and bin's app bar. /// /// Contains: @@ -96,8 +108,34 @@ class NotesAppBar extends ConsumerWidget { } /// Searches for the notes that match the [search]. + /// + /// The search waits for the user to stop typing for [_searchDebounce] and needs at least [_searchMinimumLength] + /// characters. If a newer search starts meanwhile, the results of the newer one are returned instead, so that the + /// results of an outdated search never replace the ones of the current text. Future> searchNotes(String? search) async { - if (search == null || search.isEmpty) { + final generation = ++_searchGeneration; + final searchFuture = _search(search, generation); + _latestSearch = searchFuture; + + Future> latestSearch; + List results; + do { + latestSearch = _latestSearch!; + results = await latestSearch; + } while (latestSearch != _latestSearch); + + return results; + } + + /// Performs the search of the [search] if it's still the latest one (its [generation]) after the debounce. + Future> _search(String? search, int generation) async { + if (search == null || search.trim().length < _searchMinimumLength) { + return []; + } + + await Future.delayed(_searchDebounce); + + if (generation != _searchGeneration) { return []; } diff --git a/lib/common/widgets/notes/note_tile.dart b/lib/common/widgets/notes/note_tile.dart index 782d8930..e2fb9f90 100644 --- a/lib/common/widgets/notes/note_tile.dart +++ b/lib/common/widgets/notes/note_tile.dart @@ -1,3 +1,5 @@ +import 'dart:math'; + import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:gap/gap.dart'; @@ -26,6 +28,12 @@ import 'dismissible/available_dismissible.dart'; import 'dismissible/deleted_dismissible.dart'; import 'note_tile_labels_list.dart'; +/// In the search view, the offset of the first match from which the content preview starts near it. +const _searchPreviewMaximumOffset = 80; + +/// In the search view, the number of characters shown before the first match when the preview starts near it. +const _searchPreviewContext = 30; + /// List tile that displays the main info about a note. /// /// A custom `ListTile` widget is created because the default one doesn't allow not displaying a title. @@ -191,6 +199,37 @@ class _NoteTileState extends ConsumerState { toggleSelectNote(ref, note: widget.note); } + /// Returns the content preview to show in the search view for the [search]. + /// + /// If the first match of the [search] is too far for the preview, the preview starts a few characters before it, + /// so that the match is visible and highlighted. + String searchPreview(String search) { + final preview = widget.note.contentPreview; + final lowerPreview = preview.toLowerCase(); + + final indexes = search + .toLowerCase() + .split(' ') + .where((word) => word.isNotEmpty) + .map((word) => lowerPreview.indexOf(word)) + .where((index) => index >= 0); + + if (indexes.isEmpty) { + return preview; + } + + final firstMatch = indexes.reduce(min); + + if (firstMatch < _searchPreviewMaximumOffset) { + return preview; + } + + final lineStart = preview.lastIndexOf('\n', firstMatch) + 1; + final start = max(lineStart, firstMatch - _searchPreviewContext); + + return '…${preview.substring(start)}'; + } + @override Widget build(BuildContext context) { final showTitlesOnly = PreferenceKey.showTitlesOnly.preferenceOrDefault; @@ -278,7 +317,7 @@ class _NoteTileState extends ConsumerState { if (showContent) widget.search != null ? SubstringHighlight( - text: widget.note.contentPreview, + text: searchPreview(widget.search!), terms: widget.search?.split(' '), maxLines: maximumContentPreviewLines, overflow: TextOverflow.ellipsis, diff --git a/lib/models/note/index/note_index.dart b/lib/models/note/index/note_index.dart deleted file mode 100644 index 9c4b6157..00000000 --- a/lib/models/note/index/note_index.dart +++ /dev/null @@ -1,51 +0,0 @@ -import 'package:json_annotation/json_annotation.dart'; - -import '../note.dart'; - -part 'note_index.g.dart'; - -/// Notes search index. -@JsonSerializable() -class NoteIndex { - /// The isar ID of the note. - final int id; - - /// Whether the note is deleted. - final bool deleted; - - /// Whether the note is archived. - final bool archived; - - /// The title of the note. - final String title; - - /// The content of the note as plain text. - final String content; - - /// The labels of the note. - final List labels; - - /// A search index for a note, allowing to search through its [title] and [content] - /// and filter on whether it is [deleted], [archived] what [labels] it has. - const NoteIndex({ - required this.id, - required this.deleted, - required this.archived, - required this.title, - required this.content, - required this.labels, - }); - - /// Creates a [NoteIndex] from a [Note]. - factory NoteIndex.fromNote(Note note) => NoteIndex( - id: note.isarId, - deleted: note.deleted, - archived: note.archived, - title: note.title, - content: note.contentAsText, - labels: note.labelsNamesVisibleSorted, - ); - - /// Returns this [NoteIndex] as JSON. - Map toJson() => _$NoteIndexToJson(this); -} diff --git a/lib/services/database_service.dart b/lib/services/database_service.dart index 9ff7345b..1b0cd1b8 100644 --- a/lib/services/database_service.dart +++ b/lib/services/database_service.dart @@ -20,20 +20,31 @@ class DatabaseService { DatabaseService._internal(); + /// The schemas of the collections of the database. + static const schemas = [ + NoteSchema, + PlainTextNoteSchema, + RichTextNoteSchema, + MarkdownNoteSchema, + ChecklistNoteSchema, + LabelSchema, + ]; + + /// The name of the database. + static const databaseName = 'materialnotes'; + /// Isar database instance. late final Isar database; + /// The directory of the database. + late final String databaseDirectory; + /// Ensures the service is initialized. Future ensureInitialized() async { - final databaseName = 'materialnotes'; - final databaseDirectory = (await getApplicationDocumentsDirectory()).path; + databaseDirectory = (await getApplicationDocumentsDirectory()).path; // Initialize the database - database = await Isar.open( - [NoteSchema, PlainTextNoteSchema, RichTextNoteSchema, MarkdownNoteSchema, ChecklistNoteSchema, LabelSchema], - name: databaseName, - directory: databaseDirectory, - ); + database = await Isar.open(schemas, name: databaseName, directory: databaseDirectory); // Initialize the models services await LabelsService().ensureInitialized(); diff --git a/lib/services/notes/notes_search.dart b/lib/services/notes/notes_search.dart new file mode 100644 index 00000000..6eb2a306 --- /dev/null +++ b/lib/services/notes/notes_search.dart @@ -0,0 +1,220 @@ +import 'dart:convert'; +import 'dart:isolate'; + +import 'package:fleather/fleather.dart'; +import 'package:isar_community/isar.dart'; + +import '../../models/label/label.dart'; +import '../../models/note/note.dart'; +import '../../models/note/types/note_type.dart'; +import '../database_service.dart'; + +/// A note found by a search, identified by its [type] (its collection) and its [isarId]. +typedef SearchResult = ({NoteType type, int isarId}); + +/// The parameters of a search, sent to the isolate that performs it. +typedef SearchParameters = ({ + String databaseName, + String databaseDirectory, + List words, + bool archived, + bool deleted, + String? label, + bool lockNote, + bool lockLabel, + int limit, +}); + +/// The notes found by a search: all the ones whose title matches every word, then at most a limit of the ones whose +/// content does. +typedef SearchResults = ({List titleMatches, List contentMatches}); + +/// Searches the notes matching the [parameters] in a new isolate, so that the search doesn't freeze the interface. +/// +/// Top-level function, so that the closure sent to the isolate only captures the [parameters]. +Future searchNotesInIsolate(SearchParameters parameters) { + return Isolate.run(() => searchNotesInDatabase(parameters)); +} + +/// Searches the notes matching the [parameters], in an isolate that opens its own instance of the database. +/// +/// A note matches when each word starts a word of its title, or is contained in its content. The content of the notes +/// that require an authentication is never searched, so that the results never reveal what they contain. +/// +/// Only returns the identifiers of the notes, so that the notes are loaded by the main isolate. +Future searchNotesInDatabase(SearchParameters parameters) async { + final openedInstance = Isar.getInstance(parameters.databaseName); + final database = + openedInstance ?? + await Isar.open( + DatabaseService.schemas, + name: parameters.databaseName, + directory: parameters.databaseDirectory, + inspector: false, + ); + + try { + final words = parameters.words; + final archived = parameters.archived; + final deleted = parameters.deleted; + final label = parameters.label; + + // One query per collection, on the titles only or on the titles and the contents + final fetchers = <_Fetch>[ + ({required bool titleOnly, required int offset, required int limit}) => database.plainTextNotes + .filter() + .archivedEqualTo(archived) + .deletedEqualTo(deleted) + .optional(label != null, (q) => q.labels((q2) => q2.nameEqualTo(label!))) + .allOf( + words, + (q, word) => q.group( + (q2) => titleOnly + ? q2.titleIndexedElementStartsWith(word) + : q2.titleIndexedElementStartsWith(word).or().contentContains(word, caseSensitive: false), + ), + ) + .offset(offset) + .limit(limit) + .findAll(), + ({required bool titleOnly, required int offset, required int limit}) => database.markdownNotes + .filter() + .archivedEqualTo(archived) + .deletedEqualTo(deleted) + .optional(label != null, (q) => q.labels((q2) => q2.nameEqualTo(label!))) + .allOf( + words, + (q, word) => q.group( + (q2) => titleOnly + ? q2.titleIndexedElementStartsWith(word) + : q2.titleIndexedElementStartsWith(word).or().contentContains(word, caseSensitive: false), + ), + ) + .offset(offset) + .limit(limit) + .findAll(), + ({required bool titleOnly, required int offset, required int limit}) => database.richTextNotes + .filter() + .archivedEqualTo(archived) + .deletedEqualTo(deleted) + .optional(label != null, (q) => q.labels((q2) => q2.nameEqualTo(label!))) + .allOf( + words, + (q, word) => q.group( + (q2) => titleOnly + ? q2.titleIndexedElementStartsWith(word) + : q2.titleIndexedElementStartsWith(word).or().contentContains(word, caseSensitive: false), + ), + ) + .offset(offset) + .limit(limit) + .findAll(), + ({required bool titleOnly, required int offset, required int limit}) => database.checklistNotes + .filter() + .archivedEqualTo(archived) + .deletedEqualTo(deleted) + .optional(label != null, (q) => q.labels((q2) => q2.nameEqualTo(label!))) + .allOf( + words, + (q, word) => q.group( + (q2) => titleOnly + ? q2.titleIndexedElementStartsWith(word) + : q2.titleIndexedElementStartsWith(word).or().textsElementContains(word, caseSensitive: false), + ), + ) + .offset(offset) + .limit(limit) + .findAll(), + ]; + + final titleMatches = []; + final contentMatches = []; + final limit = parameters.limit; + + // First all the notes whose title matches, with the index of the titles, as before the search in the contents + for (final fetch in fetchers) { + final notes = await fetch(titleOnly: true, offset: 0, limit: _noLimit); + titleMatches.addAll(notes.map((note) => (type: note.type, isarId: note.isarId))); + } + + // Then at most [limit] notes whose content matches, by batches so that only the needed notes are read. The + // candidates are checked in Dart, to skip the content of the locked notes and the JSON syntax of the rich text notes + final titleMatchesIds = titleMatches.toSet(); + for (final fetch in fetchers) { + for (var offset = 0; contentMatches.length < limit; offset += _batchSize) { + final candidates = await fetch(titleOnly: false, offset: offset, limit: _batchSize); + + for (final note in candidates) { + final result = (type: note.type, isarId: note.isarId); + + if (contentMatches.length >= limit) { + break; + } + + if (titleMatchesIds.contains(result) || !_contentMatches(note, words, parameters)) { + continue; + } + + contentMatches.add(result); + } + + if (candidates.length < _batchSize) { + break; + } + } + } + + return (titleMatches: titleMatches, contentMatches: contentMatches); + } finally { + // Close the instance opened by this isolate + if (openedInstance == null) { + await database.close(); + } + } +} + +/// Returns the content of the [note] in which to search. +/// +/// For a rich text note, it's the text of the document rather than its JSON, or the raw content if it can't be decoded +/// (the logger of the main isolate isn't available here). +String _searchableContent(Note note) { + switch (note) { + case final RichTextNote note: + try { + return ParchmentDocument.fromJson(jsonDecode(note.content) as List).toPlainText(); + } catch (_) { + return note.content; + } + case final ChecklistNote note: + return note.texts.join('\n'); + case final PlainTextNote note: + return note.content; + case final MarkdownNote note: + return note.content; + } +} + +/// The limit of a query that returns all its results. +const _noLimit = 1 << 30; + +/// The number of candidates read at once when searching the contents. +const _batchSize = 50; + +/// Fetches the notes of one collection matching the words of a search, on the titles only if [titleOnly]. +typedef _Fetch = Future> Function({required bool titleOnly, required int offset, required int limit}); + +/// Returns whether the [note] matches each of the [words] in its title or its content. +/// +/// The content of a note that requires an authentication is never searched. +bool _contentMatches(Note note, List words, SearchParameters parameters) { + final requiresAuthentication = + (parameters.lockNote && note.locked) || (parameters.lockLabel && note.labels.any((label) => label.locked)); + if (requiresAuthentication) { + return false; + } + + final titleWords = note.titleIndexed; + final content = _searchableContent(note).toLowerCase(); + + return words.every((word) => titleWords.any((titleWord) => titleWord.startsWith(word)) || content.contains(word)); +} diff --git a/lib/services/notes/notes_service.dart b/lib/services/notes/notes_service.dart index 5c960d26..5946de28 100644 --- a/lib/services/notes/notes_service.dart +++ b/lib/services/notes/notes_service.dart @@ -1,3 +1,4 @@ +import 'package:collection/collection.dart'; import 'package:is_first_run/is_first_run.dart'; import 'package:isar_community/isar.dart'; @@ -5,10 +6,13 @@ import '../../common/constants/constants.dart'; import '../../common/constants/environment.dart'; import '../../common/constants/labels.dart'; import '../../common/constants/notes.dart'; +import '../../common/preferences/preference_key.dart'; import '../../models/label/label.dart'; import '../../models/note/note.dart'; import '../../models/note/note_status.dart'; +import '../../models/note/types/note_type.dart'; import '../database_service.dart'; +import 'notes_search.dart'; /// Service for the notes database. /// @@ -139,57 +143,57 @@ class NotesService { ]; } - /// Returns all the notes with the [notesStatus] that match the [search]. + /// The maximum number of notes returned by a search because of their content (all the title matches are returned). + static const searchLimit = 50; + + /// Returns the notes with the [notesStatus] that match the [search]: all the title matches, then at most + /// [searchLimit] content matches. + /// + /// A note matches when each word of the [search] starts a word of its title, or is contained in its content (except + /// for the notes that require an authentication). The notes whose title matches come first. /// /// If [label] is set, the search should be performed on the notes that have that label. + /// + /// The search runs in an isolate, so that it doesn't freeze the interface. The notes are loaded here by their IDs. Future> search(String search, NoteStatus notesStatus, String? label) async { - final searchWords = Isar.splitWords(search.toLowerCase()); + final words = Isar.splitWords(search.toLowerCase()); + + if (words.isEmpty) { + return []; + } + + final SearchParameters parameters = ( + databaseName: DatabaseService.databaseName, + databaseDirectory: DatabaseService().databaseDirectory, + words: words, + archived: notesStatus == NoteStatus.archived, + deleted: notesStatus == NoteStatus.deleted, + label: label, + lockNote: PreferenceKey.lockNote.preferenceOrDefault, + lockLabel: PreferenceKey.lockLabel.preferenceOrDefault, + limit: searchLimit, + ); - final statusArchivedFilter = notesStatus == NoteStatus.archived; - final statusDeletedFilter = notesStatus == NoteStatus.deleted; + final results = await searchNotesInIsolate(parameters); return [ - ...await (_plainTextNotes - .filter() - .archivedEqualTo(statusArchivedFilter) - .deletedEqualTo(statusDeletedFilter) - .optional(label != null, (q) => q.labels((q2) => q2.nameEqualTo(label!))) - .allOf( - searchWords, - (q, word) => q.group((q2) => q2.titleIndexedElementStartsWith(word)), - ) - .findAll()), - ...await (_markdownNotes - .filter() - .archivedEqualTo(statusArchivedFilter) - .deletedEqualTo(statusDeletedFilter) - .optional(label != null, (q) => q.labels((q2) => q2.nameEqualTo(label!))) - .allOf( - searchWords, - (q, word) => q.group((q2) => q2.titleIndexedElementStartsWith(word)), - ) - .findAll()), - ...await (_richTextNotes - .filter() - .archivedEqualTo(statusArchivedFilter) - .deletedEqualTo(statusDeletedFilter) - .optional(label != null, (q) => q.labels((q2) => q2.nameEqualTo(label!))) - .allOf( - searchWords, - (q, word) => q.group((q2) => q2.titleIndexedElementStartsWith(word)), - ) - .findAll()), - ...await (_checklistNotes - .filter() - .archivedEqualTo(statusArchivedFilter) - .deletedEqualTo(statusDeletedFilter) - .optional(label != null, (q) => q.labels((q2) => q2.nameEqualTo(label!))) - .allOf( - searchWords, - (q, word) => q.group((q2) => q2.titleIndexedElementStartsWith(word)), - ) - .findAll()), + ...(await _getAllByResults(results.titleMatches)).sorted(), + ...(await _getAllByResults(results.contentMatches)).sorted(), + ]; + } + + /// Returns the notes of the search [results], from their collection. + Future> _getAllByResults(List results) async { + List ids(NoteType type) => results.where((result) => result.type == type).map((r) => r.isarId).toList(); + + final notes = [ + ...await _plainTextNotes.getAll(ids(NoteType.plainText)), + ...await _markdownNotes.getAll(ids(NoteType.markdown)), + ...await _richTextNotes.getAll(ids(NoteType.richText)), + ...await _checklistNotes.getAll(ids(NoteType.checklist)), ]; + + return notes.nonNulls.toList(); } /// Puts the [note] in the database.