diff --git a/lib/pdf_book/view/pdf_book_screen.dart b/lib/pdf_book/view/pdf_book_screen.dart index eafc55baae..97fd233292 100644 --- a/lib/pdf_book/view/pdf_book_screen.dart +++ b/lib/pdf_book/view/pdf_book_screen.dart @@ -6171,7 +6171,7 @@ class _PdfBookScreenState extends State return; } try { - await _personalNotesRepository.repositionNote( + await _personalNotesRepository.moveNote( bookId: note.bookId, noteId: note.id, categoryId: widget.tab.book.categoryId, diff --git a/lib/personal_notes/bloc/personal_notes_bloc.dart b/lib/personal_notes/bloc/personal_notes_bloc.dart index f2e7b10f48..a13f937248 100644 --- a/lib/personal_notes/bloc/personal_notes_bloc.dart +++ b/lib/personal_notes/bloc/personal_notes_bloc.dart @@ -251,10 +251,18 @@ class PersonalNotesBloc extends Bloc { StartCreatingPersonalNote event, Emitter emit, ) { + final isSameSession = + state.isCreatingNewNote && + state.newNoteBookId == event.bookId && + state.newNoteLineNumber == event.lineNumber && + state.newNotePdfAnchor == event.pdfAnchor; emit( state.copyWith( isCreatingNewNote: true, newNoteRequestToken: state.newNoteRequestToken + 1, + newNoteSessionToken: isSameSession + ? state.newNoteSessionToken + : state.newNoteSessionToken + 1, clearExpandRequest: true, clearNewNoteSourceSelection: true, clearNewNotePdfAnchor: true, @@ -277,6 +285,14 @@ class PersonalNotesBloc extends Bloc { CancelCreatingPersonalNote event, Emitter emit, ) { + // השלמת כתיבה ישנה אינה מבטלת יצירה חדשה שכבר ממתינה בתור האירועים. + if ((event.sessionToken != null && + event.sessionToken != state.newNoteSessionToken) || + (event.bookId != null && event.bookId != state.newNoteBookId) || + (event.lineNumber != null && + event.lineNumber != state.newNoteLineNumber)) { + return; + } emit(state.copyWith(clearNewNoteData: true)); } diff --git a/lib/personal_notes/bloc/personal_notes_event.dart b/lib/personal_notes/bloc/personal_notes_event.dart index 416a58bbdc..0cc357dfa5 100644 --- a/lib/personal_notes/bloc/personal_notes_event.dart +++ b/lib/personal_notes/bloc/personal_notes_event.dart @@ -181,7 +181,18 @@ class StartCreatingPersonalNote extends PersonalNotesEvent { } class CancelCreatingPersonalNote extends PersonalNotesEvent { - const CancelCreatingPersonalNote(); + final int? sessionToken; + final String? bookId; + final int? lineNumber; + + const CancelCreatingPersonalNote({ + this.sessionToken, + this.bookId, + this.lineNumber, + }); + + @override + List get props => [sessionToken, bookId, lineNumber]; } class UpdateSearchQuery extends PersonalNotesEvent { diff --git a/lib/personal_notes/bloc/personal_notes_state.dart b/lib/personal_notes/bloc/personal_notes_state.dart index 5f15384287..af60788740 100644 --- a/lib/personal_notes/bloc/personal_notes_state.dart +++ b/lib/personal_notes/bloc/personal_notes_state.dart @@ -28,6 +28,8 @@ class PersonalNotesState extends Equatable { final bool isCreatingNewNote; // בקשה זהה עדיין צריכה לחשוף עורך שנגלל מחוץ למסך. final int newNoteRequestToken; + // חשיפה חוזרת משמרת את היצירה; ביטול או מעבר מיקום מתחילים יצירה אחרת. + final int newNoteSessionToken; final String? newNoteBookId; final int? newNoteLineNumber; final String? newNoteReferenceText; @@ -57,6 +59,7 @@ class PersonalNotesState extends Equatable { this.expandRequestToken = 0, this.isCreatingNewNote = false, this.newNoteRequestToken = 0, + this.newNoteSessionToken = 0, this.newNoteBookId, this.newNoteLineNumber, this.newNoteReferenceText, @@ -87,6 +90,7 @@ class PersonalNotesState extends Equatable { expandRequestToken = 0, isCreatingNewNote = false, newNoteRequestToken = 0, + newNoteSessionToken = 0, newNoteBookId = null, newNoteLineNumber = null, newNoteReferenceText = null, @@ -116,6 +120,7 @@ class PersonalNotesState extends Equatable { int? expandRequestToken, bool? isCreatingNewNote, int? newNoteRequestToken, + int? newNoteSessionToken, String? newNoteBookId, int? newNoteLineNumber, String? newNoteReferenceText, @@ -157,6 +162,7 @@ class PersonalNotesState extends Equatable { ? false : (isCreatingNewNote ?? this.isCreatingNewNote), newNoteRequestToken: newNoteRequestToken ?? this.newNoteRequestToken, + newNoteSessionToken: newNoteSessionToken ?? this.newNoteSessionToken, newNoteBookId: clearNewNoteData ? null : (newNoteBookId ?? this.newNoteBookId), @@ -217,6 +223,7 @@ class PersonalNotesState extends Equatable { expandRequestToken, isCreatingNewNote, newNoteRequestToken, + newNoteSessionToken, newNoteBookId, newNoteLineNumber, newNoteReferenceText, diff --git a/lib/personal_notes/repository/personal_notes_repository.dart b/lib/personal_notes/repository/personal_notes_repository.dart index d9b3d0da11..24d507db0f 100644 --- a/lib/personal_notes/repository/personal_notes_repository.dart +++ b/lib/personal_notes/repository/personal_notes_repository.dart @@ -173,6 +173,10 @@ class PersonalNotesRepository { required String noteId, }) => _service.deleteNote(bookId: bookId, noteId: noteId); + /// מסיים לאחר המחיקה; המאזינים לשינויים מרעננים בנפרד. + Future removeNote({required String noteId}) => + _service.removeNote(noteId: noteId); + Future> repositionNote({ required String bookId, required String noteId, @@ -190,6 +194,23 @@ class PersonalNotesRepository { ); } + Future moveNote({ + required String bookId, + required String noteId, + required int lineNumber, + PdfNoteAnchor? pdfAnchor, + int? categoryId, + }) async { + final bookContent = await _loadBookContent(bookId, categoryId: categoryId); + return _service.moveNote( + bookId: bookId, + bookContent: bookContent, + noteId: noteId, + lineNumber: lineNumber, + pdfAnchor: pdfAnchor, + ); + } + /// תוכן הספר של מפתח ההערות [bookId], כפי שההערות מעוגנות אליו. Future loadBookContent(String bookId, {int? categoryId}) => _loadBookContent(bookId, categoryId: categoryId, refresh: true); diff --git a/lib/personal_notes/services/personal_note_draft_service.dart b/lib/personal_notes/services/personal_note_draft_service.dart index e0499f4649..c26c3a0cc7 100644 --- a/lib/personal_notes/services/personal_note_draft_service.dart +++ b/lib/personal_notes/services/personal_note_draft_service.dart @@ -64,6 +64,26 @@ class PersonalNoteDraftService { /// ההגדרות יחריג אותה — טיוטה היא תוכן הערה אישית, לא הגדרה. static const keyPrefix = 'personal_note_draft:'; + // גרסה לתחרות בין פעולות אסינכרוניות באותו תהליך; אינה חלק מהקובץ. + // מופעי שירות שונים חולקים מפתחות טיוטה, ולכן חולקים גם את הגרסאות. + static final _versions = {}; + static const _anyVersion = Object(); + + Object? draftVersion({ + required String bookId, + int? categoryId, + int? lineNumber, + String? noteId, + PdfNoteAnchor? pdfAnchor, + }) => + _versions[_key( + bookId, + categoryId: categoryId, + lineNumber: lineNumber, + noteId: noteId, + pdfAnchor: pdfAnchor, + )]; + String _key( String bookId, { int? categoryId, @@ -139,6 +159,7 @@ class PersonalNoteDraftService { noteId: noteId, pdfAnchor: draft.pdfAnchor, ); + final version = _versions[key] = Object(); final normalizedDraft = PersonalNoteDraft( content: draft.content, contentPlain: draft.contentPlain, @@ -157,6 +178,8 @@ class PersonalNoteDraftService { categoryId: categoryId, lineNumber: lineNumber, ); + final legacyVersion = _versions[legacyKey]; + final legacyRaw = Settings.getValue(legacyKey); final legacyDraft = _readDraft(legacyKey); if (legacyDraft?.pdfAnchor != null) { final pointKey = _key( @@ -171,10 +194,19 @@ class PersonalNoteDraftService { jsonEncode(legacyDraft.toJson()), ); } - await Settings.setValue(legacyKey, null); + if (identical(_versions[legacyKey], legacyVersion) && + Settings.getValue(legacyKey) == legacyRaw) { + await Settings.setValue(legacyKey, null); + } } } - await Settings.setValue(key, jsonEncode(normalizedDraft.toJson())); + // העברה ממפתח PDF ישן עשויה להמתין. כתיבה/ניקוי חדשים גוברים עליה. + if (identical(_versions[key], version)) { + await Settings.setValue( + key, + jsonEncode(normalizedDraft.toJson()), + ); + } } Future clearDraft({ @@ -183,6 +215,7 @@ class PersonalNoteDraftService { int? lineNumber, String? noteId, PdfNoteAnchor? pdfAnchor, + Object? expectedVersion = _anyVersion, }) async { final key = _key( bookId, @@ -191,21 +224,42 @@ class PersonalNoteDraftService { noteId: noteId, pdfAnchor: pdfAnchor, ); + if (!identical(expectedVersion, _anyVersion) && + !identical(_versions[key], expectedVersion)) { + return; + } + final version = _versions[key]; + final clearingVersion = _versions[key] = Object(); if (noteId == null && pdfAnchor == null && _readDraft(key)?.pdfAnchor != null) { + // ביטול כתיבת טקסט שממתינה להעברת PDF אינו מוחק את ה-PDF הישן. + _versions.remove(key); return; } - await Settings.setValue(key, null); - if (noteId == null && pdfAnchor != null) { - final legacyKey = _key( - bookId, - categoryId: categoryId, - lineNumber: lineNumber, - ); - if (_readDraft(legacyKey)?.pdfAnchor == pdfAnchor) { - await Settings.setValue(legacyKey, null); + final legacyKey = noteId == null && pdfAnchor != null + ? _key(bookId, categoryId: categoryId, lineNumber: lineNumber) + : null; + try { + // שתי המחיקות מתחילות לפני ההמתנה. כך writer חדש אינו פוגש + // PDF שכבר נוקה בנקודה אבל עדיין ממתין למחיקת המפתח הישן שלו. + await Future.wait([ + Settings.setValue(key, null), + if (legacyKey != null && _readDraft(legacyKey)?.pdfAnchor == pdfAnchor) + Settings.setValue(legacyKey, null), + ]); + // עורך שנפתח בזמן הניקוי מזהה שהצילום שלו כבר אינו טיוטה פעילה. + if (identical(_versions[key], clearingVersion)) _versions.remove(key); + } catch (_) { + // כשל מחיקה מאפשר ניסיון חוזר, בלי להחליף גרסה שנכתבה בינתיים. + if (identical(_versions[key], clearingVersion)) { + if (version == null) { + _versions.remove(key); + } else { + _versions[key] = version; + } } + rethrow; } } diff --git a/lib/personal_notes/services/personal_notes_service.dart b/lib/personal_notes/services/personal_notes_service.dart index 733f571f74..dd95eea4cd 100644 --- a/lib/personal_notes/services/personal_notes_service.dart +++ b/lib/personal_notes/services/personal_notes_service.dart @@ -226,20 +226,45 @@ class PersonalNotesService { required String bookId, required String noteId, }) async { - await _database.deleteNote(noteId); + await removeNote(noteId: noteId); return await _database.loadNotes(bookId); } + /// אישור המחיקה אינו תלוי בקריאת הרשימה שאחריה. + Future removeNote({required String noteId}) => + _database.deleteNote(noteId); + Future> repositionNote({ required String bookId, required String bookContent, required String noteId, required int lineNumber, PdfNoteAnchor? pdfAnchor, + }) async { + await moveNote( + bookId: bookId, + bookContent: bookContent, + noteId: noteId, + lineNumber: lineNumber, + pdfAnchor: pdfAnchor, + ); + return _database.loadNotes(bookId); + } + + /// מחזיר את ההערה לאחר כתיבת המיקום, בלי לטעון את יתר הערות הספר. + Future moveNote({ + required String bookId, + required String bookContent, + required String noteId, + required int lineNumber, + PdfNoteAnchor? pdfAnchor, }) async { final note = await _database.getNote(noteId); if (note == null) { - return await _database.loadNotes(bookId); + throw StateError(NotesMessages.noteNoLongerExists); + } + if (note.bookId != bookId) { + throw StateError(NotesMessages.noteMovedToDifferentBook); } final lines = splitBookContentIntoLines(bookContent); @@ -272,8 +297,7 @@ class PersonalNotesService { ); await _database.updateNote(updatedNote); - - return await _database.loadNotes(bookId); + return updatedNote; } PersonalNote _reconcileLocation( diff --git a/lib/personal_notes/view/personal_notes_screen.dart b/lib/personal_notes/view/personal_notes_screen.dart index 54eddb72b1..ca0dc1e850 100644 --- a/lib/personal_notes/view/personal_notes_screen.dart +++ b/lib/personal_notes/view/personal_notes_screen.dart @@ -1517,7 +1517,7 @@ class _PersonalNotesManagerScreenState if (shouldDelete == true) { if (!mounted) return; try { - await _repository.deleteNote(bookId: note.bookId, noteId: note.id); + await _repository.removeNote(noteId: note.id); if (mounted) UiSnack.show(NotesMessages.noteDeleted); } catch (error) { if (mounted) UiSnack.showError(NotesMessages.noteDeleteFailed(error)); @@ -1546,7 +1546,7 @@ class _PersonalNotesManagerScreenState if (newLine != null) { if (!mounted) return; try { - await _repository.repositionNote( + await _repository.moveNote( bookId: note.bookId, noteId: note.id, lineNumber: newLine, diff --git a/lib/personal_notes/widgets/inline_note_editor.dart b/lib/personal_notes/widgets/inline_note_editor.dart index 7a71634e92..493074e59c 100644 --- a/lib/personal_notes/widgets/inline_note_editor.dart +++ b/lib/personal_notes/widgets/inline_note_editor.dart @@ -29,6 +29,8 @@ class InlineNoteEditor extends StatefulWidget { final String? draftNoteId; final List linkableNotes; final PersonalNoteSaveCallback onSave; + + /// השלמה לוגית לאחר כתיבה וניקוי הטיוטה; עשויה להגיע אחרי הסרת העורך. final VoidCallback? onSaved; final VoidCallback onCancel; final ValueListenable? cancelRequest; @@ -58,11 +60,13 @@ class InlineNoteEditor extends StatefulWidget { class _InlineNoteEditorState extends State { late final PersonalNoteEditorController _controller; late final PersonalNoteEditorResult _initialResult; + late PersonalNoteEditorResult _draftResult; late final StreamSubscription _documentChanges; final GlobalKey _editorKey = GlobalKey(); final FocusNode _focusNode = FocusNode(debugLabel: 'InlineNoteEditor'); final ScrollController _scrollController = ScrollController(); final PersonalNoteDraftService _draftService = PersonalNoteDraftService(); + Object? _draftVersion; Timer? _draftSaveTimer; Timer? _focusRetryTimer; bool _isDone = false; // מונע שמירת טיוטה אחרי שמירה/ביטול @@ -72,6 +76,7 @@ class _InlineNoteEditorState extends State { @override void initState() { super.initState(); + _draftVersion = _currentDraftVersion(); _controller = buildPersonalNoteEditorController( initialContent: widget.initialContent.isNotEmpty ? widget.initialContent @@ -80,6 +85,7 @@ class _InlineNoteEditorState extends State { ? widget.initialFormat : (widget.note?.contentFormat ?? PersonalNoteContentFormat.plain), ); + _draftResult = _controller.buildResult(); // _initialResult מייצג את המצב ה"נקי" לפני עריכה — לא תוכן הטיוטה. // כך _persistDraft לא ימחק את הטיוטה כשה-Quill מפעיל notifyListeners בהתחלה. final originalController = buildPersonalNoteEditorController( @@ -145,6 +151,8 @@ class _InlineNoteEditorState extends State { Future _handleSave() async { if (_isDone || _isSaving || _isClosing) return; final result = _controller.buildResult(); + final onSave = widget.onSave; + final onSaved = widget.onSaved; if (result.contentPlain.trim().isEmpty) { UiSnack.showError(NotesMessages.emptyNoteNotSaved); return; @@ -155,7 +163,7 @@ class _InlineNoteEditorState extends State { }); try { if (!await verifySaferModePassword(context) || !mounted) return; - await widget.onSave(result); + await onSave(result); _isDone = true; _draftSaveTimer?.cancel(); var clearedDraft = true; @@ -174,8 +182,8 @@ class _InlineNoteEditorState extends State { } else { UiSnack.showWarning(NotesMessages.noteSavedDraftCleanupFailed); } - widget.onSaved?.call(); } + onSaved?.call(); } catch (error) { if (mounted) UiSnack.showError(TextBookMessages.noteSaveError(error)); } finally { @@ -209,12 +217,23 @@ class _InlineNoteEditorState extends State { Future _persistDraft() async { if (_isDone) return; final result = _controller.buildResult(); + // עורך ששוחזר בזמן כתיבה עשוי להיסגר לאחר שהמקור כבר נשמר ונוקה. + // תוכן חדש שלא הספיק ל-debounce עדיין נשמר, אך צילום ישן אינו מוחזר. + if (!identical(_draftVersion, _currentDraftVersion()) && + _matchesResult(_draftResult, result)) { + return; + } if (_matchesInitial(result) || result.contentPlain.trim().isEmpty) { + final clearedVersion = _draftVersion; + _draftResult = result; await _clearDraft(); + if (identical(_draftVersion, clearedVersion)) { + if (_currentDraftVersion() == null) _draftVersion = null; + } return; } - await _draftService.saveDraft( + final write = _draftService.saveDraft( bookId: widget.bookId, categoryId: widget.categoryId, lineNumber: widget.draftLineNumber, @@ -230,12 +249,22 @@ class _InlineNoteEditorState extends State { pdfAnchor: widget.pdfAnchor ?? widget.note?.pdfAnchor, ), ); + // saveDraft קובע את הגרסה לפני ה-await הראשון, גם כשכתיבת Hive ממתינה. + _draftVersion = _currentDraftVersion(); + _draftResult = result; + await write; } - bool _matchesInitial(PersonalNoteEditorResult result) { - return _initialResult.content.trimRight() == result.content.trimRight() && - _initialResult.contentPlain.trim() == result.contentPlain.trim() && - _initialResult.contentFormat == result.contentFormat; + bool _matchesInitial(PersonalNoteEditorResult result) => + _matchesResult(_initialResult, result); + + bool _matchesResult( + PersonalNoteEditorResult first, + PersonalNoteEditorResult second, + ) { + return first.content.trimRight() == second.content.trimRight() && + first.contentPlain.trim() == second.contentPlain.trim() && + first.contentFormat == second.contentFormat; } Future _clearDraft() { @@ -245,9 +274,18 @@ class _InlineNoteEditorState extends State { lineNumber: widget.draftLineNumber, noteId: widget.draftNoteId, pdfAnchor: widget.pdfAnchor ?? widget.note?.pdfAnchor, + expectedVersion: _draftVersion, ); } + Object? _currentDraftVersion() => _draftService.draftVersion( + bookId: widget.bookId, + categoryId: widget.categoryId, + lineNumber: widget.draftLineNumber, + noteId: widget.draftNoteId, + pdfAnchor: widget.pdfAnchor ?? widget.note?.pdfAnchor, + ); + Future _handleCancel() async { if (_isDone || _isSaving || _isClosing) return; _isClosing = true; diff --git a/lib/personal_notes/widgets/note_tile.dart b/lib/personal_notes/widgets/note_tile.dart index d58ac8fb5f..dd9ca13c29 100644 --- a/lib/personal_notes/widgets/note_tile.dart +++ b/lib/personal_notes/widgets/note_tile.dart @@ -124,6 +124,7 @@ class _NoteTileState extends State { } void _finishSave() { + if (!mounted) return; setState(() { _draftContent = null; _draftFormat = null; diff --git a/lib/personal_notes/widgets/personal_note_editor.dart b/lib/personal_notes/widgets/personal_note_editor.dart index 4d49aff236..a1726acb4c 100644 --- a/lib/personal_notes/widgets/personal_note_editor.dart +++ b/lib/personal_notes/widgets/personal_note_editor.dart @@ -4,6 +4,7 @@ import 'package:otzaria/theme/app_tokens.dart'; import 'package:fluentui_system_icons/fluentui_system_icons.dart'; import 'package:otzaria_icons/otzaria_icons.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -215,6 +216,55 @@ class _PersonalNoteEditorBodyState extends State { }); } + KeyEventResult? _handleEmptyLineBackspace(KeyEvent event, quill.Node? node) { + final controller = widget.controller.quillController; + if (controller.readOnly || + !controller.selection.isCollapsed || + node is! quill.Line || + node.length != 1) { + return null; + } + if (!kIsWeb && + defaultTargetPlatform == TargetPlatform.windows && + const SingleActivator( + LogicalKeyboardKey.backspace, + alt: true, + ).accepts(event, HardwareKeyboard.instance)) { + // מחיקה עד תחילת שורה ריקה היא טווח ריק. Quill מנסה לקרוא תיבת + // טקסט שאינה קיימת; בתחילת המסמך נשמר ניקוי עיצוב הבלוק שלו. + if (controller.selection.start == 0) { + final style = controller.document.collectStyle(0, 0); + final blockAttributes = controller + .getSelectionStyle() + .values + .where((attribute) => attribute.scope == quill.AttributeScope.block) + .toList(); + for (final attribute in blockAttributes) { + controller.formatSelection(quill.Attribute.clone(attribute, null)); + style.attributes.remove(attribute.key); + } + controller.forceToggledStyle(style); + } + return KeyEventResult.handled; + } + if (!const SingleActivator( + LogicalKeyboardKey.backspace, + ).accepts(event, HardwareKeyboard.instance)) { + return null; + } + final attributes = node.toDelta().last.attributes; + if (attributes?[quill.Attribute.list.key] == null) return null; + final indent = attributes?[quill.Attribute.indent.key] as int? ?? 0; + if (indent > 0) { + controller.indentSelection(false); + } else { + controller.formatSelection( + quill.Attribute.clone(quill.Attribute.list, null), + ); + } + return KeyEventResult.handled; + } + /// Quill מבקש תפריט גם בסיום גרירה בעכבר, ושם לא מציגים כלום; לחיצה ימנית /// פותחת את התפריט מהאזור. Widget _touchContextMenu( @@ -437,6 +487,8 @@ class _PersonalNoteEditorBodyState extends State { widget.onCancelShortcut!, ), }, + // ignore: experimental_member_use + onKeyPressed: _handleEmptyLineBackspace, contextMenuBuilder: _touchContextMenu, ), ), diff --git a/lib/personal_notes/widgets/personal_note_editor_dialog.dart b/lib/personal_notes/widgets/personal_note_editor_dialog.dart index a5d8bb8c8e..f951d94a6d 100644 --- a/lib/personal_notes/widgets/personal_note_editor_dialog.dart +++ b/lib/personal_notes/widgets/personal_note_editor_dialog.dart @@ -59,12 +59,14 @@ class _PersonalNoteEditorDialogState extends State late final ScrollController _scrollController; late final PersonalNoteEditorResult _initialResult; final PersonalNoteDraftService _draftService = PersonalNoteDraftService(); + Object? _draftVersion; bool _isSaving = false; bool _isClosing = false; @override void initState() { super.initState(); + _draftVersion = _currentDraftVersion(); _scrollController = ScrollController(); _editorController = buildPersonalNoteEditorController( initialContent: widget.initialContent, @@ -174,7 +176,7 @@ class _PersonalNoteEditorDialogState extends State if (bookId == null || (lineNumber == null && noteId == null)) return; final result = _editorController.buildResult(); if (result.contentPlain.trim().isEmpty) return; - await _draftService.saveDraft( + final write = _draftService.saveDraft( bookId: bookId, categoryId: widget.categoryId, lineNumber: lineNumber, @@ -188,6 +190,8 @@ class _PersonalNoteEditorDialogState extends State pdfAnchor: widget.pdfAnchor, ), ); + _draftVersion = _currentDraftVersion(); + await write; } Future _clearDraftIfPossible() async { @@ -201,6 +205,21 @@ class _PersonalNoteEditorDialogState extends State lineNumber: lineNumber, noteId: noteId, pdfAnchor: widget.pdfAnchor, + expectedVersion: _draftVersion, + ); + } + + Object? _currentDraftVersion() { + final bookId = widget.bookId; + final noteId = widget.draftNoteId; + final lineNumber = noteId == null ? widget.draftLineNumber : null; + if (bookId == null || (lineNumber == null && noteId == null)) return null; + return _draftService.draftVersion( + bookId: bookId, + categoryId: widget.categoryId, + lineNumber: lineNumber, + noteId: noteId, + pdfAnchor: widget.pdfAnchor, ); } diff --git a/lib/personal_notes/widgets/personal_notes_sidebar.dart b/lib/personal_notes/widgets/personal_notes_sidebar.dart index fd46f42272..94871c5fa7 100644 --- a/lib/personal_notes/widgets/personal_notes_sidebar.dart +++ b/lib/personal_notes/widgets/personal_notes_sidebar.dart @@ -260,24 +260,27 @@ class PersonalNotesSidebarState extends State context.read().add(const CancelCreatingPersonalNote()); } - Future _saveNewNote(PersonalNoteEditorResult result) async { - final state = context.read().state; - final lineNumber = state.newNoteLineNumber; - if (lineNumber == null || state.newNoteBookId != widget.bookId) { + Future _saveNewNote( + PersonalNoteEditorResult result, + PersonalNotesState request, + ) async { + final bookId = widget.bookId; + final lineNumber = request.newNoteLineNumber; + if (lineNumber == null || request.newNoteBookId != bookId) { throw StateError('מיקום ההערה אינו זמין'); } await _notesRepository.createNote( - bookId: widget.bookId, + bookId: bookId, lineNumber: lineNumber, content: result.content, contentPlain: result.contentPlain, contentFormat: result.contentFormat, - selectedText: state.newNoteSelectedText?.trim(), - selectionColumn: state.newNoteSelectionColumn, - sourceSelectedText: state.newNoteSourceSelectedText, - sourceSelectionOffset: state.newNoteSourceSelectionOffset, - punctuationHidden: state.newNotePunctuationHidden, - pdfAnchor: state.newNotePdfAnchor, + selectedText: request.newNoteSelectedText?.trim(), + selectionColumn: request.newNoteSelectionColumn, + sourceSelectedText: request.newNoteSourceSelectedText, + sourceSelectionOffset: request.newNoteSourceSelectionOffset, + punctuationHidden: request.newNotePunctuationHidden, + pdfAnchor: request.newNotePdfAnchor, categoryId: widget.categoryId, ); } @@ -715,6 +718,7 @@ class PersonalNotesSidebarState extends State } Widget _buildNewNoteEditor(BuildContext context, PersonalNotesState state) { + final bloc = context.read(); return InlineNoteEditorCard( icon: FluentIcons.note_add_24_regular, title: state.newNoteReferenceText != null @@ -726,6 +730,7 @@ class PersonalNotesSidebarState extends State key: ValueKey(( widget.bookId, widget.categoryId, + state.newNoteSessionToken, state.newNoteLineNumber, state.newNotePdfAnchor, )), @@ -739,12 +744,17 @@ class PersonalNotesSidebarState extends State pdfAnchor: state.newNotePdfAnchor, linkableNotes: [...state.locatedNotes, ...state.missingNotes], cancelRequest: _newNoteCancelRequest, - onSave: _saveNewNote, + onSave: (result) => _saveNewNote(result, state), onSaved: () { - final current = context.read().state; - if (current.newNoteRequestToken == state.newNoteRequestToken && - current.newNoteBookId == widget.bookId) { - _cancelNewNote(); + // ההשלמה שייכת לבקשה שנשמרה, גם אם הפאנל הוסר בזמן הכתיבה. + if (!bloc.isClosed) { + bloc.add( + CancelCreatingPersonalNote( + sessionToken: state.newNoteSessionToken, + bookId: state.newNoteBookId, + lineNumber: state.newNoteLineNumber, + ), + ); } }, onCancel: _cancelNewNote, @@ -844,7 +854,6 @@ class PersonalNotesSidebarState extends State categoryId: widget.categoryId, ), ); - UiSnack.show(NotesMessages.noteAssignedToLine(selectedLineNumber)); } Future _reanchorNote( diff --git a/lib/settings/l10n/settings_catalogs.g.dart b/lib/settings/l10n/settings_catalogs.g.dart index fd9f14ffe1..0761604da0 100644 --- a/lib/settings/l10n/settings_catalogs.g.dart +++ b/lib/settings/l10n/settings_catalogs.g.dart @@ -9,7 +9,6 @@ const Map> kSettingsCatalogs = { 'en': { ' אם הכרטיס יוסר, האפליקציה לא תוכל לגשת לספרים עד שיוחזר.\n\nשים לב: תיקיית האפליקציה שבכרטיס נספרת כמטמון של האפליקציה — "ניקוי מטמון" בהגדרות המכשיר ימחק ממנה את הספרייה.': ' If the SD card is removed, Otzaria will not be able to access the seforim until it is back.\n\nNote: the app folder on the card is counted as app cache — clearing the app\'s cache in the device settings will delete the library stored there.', '(לא חובה)': '(optional)', - '1. בחר את סוג השגיאה • 2. השתמש במספרים המוצגים למטה כשתתקשר': '1. Choose the error type. • 2. Use the numbers below when you call.', '12 בלילה': 'Midnight', 'Enter פותח את המקור המסומן, מקשי החצים מנווטים בין התוצאות': 'Enter opens the highlighted result; arrow keys move between results', '{cm} ס"מ': '{cm} cm', @@ -64,7 +63,6 @@ const Map> kSettingsCatalogs = { 'אותיות עבריות כלשהן לפני המילה, עד 3 (במילה קצרה עד 5), וגם מספר הערה צמוד (28שבת). רחב יותר מקידומות דקדוקיות.': 'Any Hebrew letters before the word, up to 3 (up to 5 for a short word), and also an attached footnote number (28שבת). Broader than grammatical prefixes.', 'אחסון פנימי': 'Internal storage', 'אחר': 'Other', - 'אי אפשר להתקדם... עדיין לא מילאתם בטופס...': 'Complete the required fields to continue.', 'איחוד טקסטים זהים': 'Merge identical texts', 'אימות סיסמה': 'Confirm the Password', 'אין': 'None', @@ -198,7 +196,6 @@ const Map> kSettingsCatalogs = { 'בחר מיקום מותאם אישית, או השתמש במיקום ברירת המחדל של האפליקציה': 'Pick a custom location, or use the system default Location', 'בחר מיקום עבור מאגר הספרים': 'Select where the seforim are kept', 'בחר מצב בהיר או כהה, צבע בסיסי לממשק ומצב תצוגה מלאה.': 'Pick a light or dark mode, a base color for Otzaria and full-screen mode.', - 'בחר סוג שגיאה:': 'Choose an error type:', 'בחר סיסמה': 'Choose a Password', 'בחר פעולה להוספת קיצור': 'Select an action to shortcut', 'בחר צבע בסיס': 'Select a System Color', @@ -221,7 +218,6 @@ const Map> kSettingsCatalogs = { 'בטקסט — מקטע; ב-PDF — עמוד': 'In text — a section; in PDF — a page', 'ביוגרפיות': 'Biographies', 'ביטול': 'Cancel', - 'ביטול הדיווח': 'Cancel report', 'ביטול הפעלה ברקע': 'Disable Background Activation', 'בייצוא ובהדפסה': 'When Exporting & Printing', 'בייצוא ובהדפסה|source': 'when exporting & printing', @@ -294,7 +290,6 @@ const Map> kSettingsCatalogs = { 'דחיה מהרשת': 'Block Network Access', 'די בהופעה של מילה אחת ממילות החיפוש.': 'One of the search words is enough.', 'דיווח אחרי קריסה או תקיעה': 'Report after a crash or hang', - 'דיווח דרך קו אוצריא': 'Report by Otzaria phone line', 'דיווח זהה לזה כבר נשלח ל{target} בעבר, ולכן לא נשלחה הודעה נוספת. הדיווח נקלט במערכת.': 'An identical report was already sent to {target}, so no additional message was sent. The report is recorded in the system.', 'דיווח חופשי': 'Free-text report', 'דיווח על טעות בספר': 'Report a book error', @@ -407,8 +402,6 @@ const Map> kSettingsCatalogs = { 'הוספת ספרים משלך לספרייה — TXT, PDF, Word, EPUB ועוד. כאן בוחרים קבצים, ולא תיקייה כמו במחשב': 'Add your own seforim to the library — TXT, PDF, Word, EPUB and more. Here you pick files, not a folder as on a computer', 'הוספת קישור ליומן חיצוני — האירועים מתרעננים אוטומטית בכל הפעלה': 'Add a link to an external calendar — events refresh automatically on every launch', 'הועבר לשליחה דרך עדכוני אוצריא': 'Handed over for sending via Otzaria Updates', - 'הועתק ללוח: {text}': 'Copied to clipboard: {text}', - 'הוראות לדיווח טלפוני:': 'Phone reporting instructions:', 'הורד': 'Download', 'הורד לשליחה במחשב מחובר': 'Download to Send From an Online Computer', 'הורד מחדש': 'Download Again', @@ -465,7 +458,6 @@ const Map> kSettingsCatalogs = { 'הטקסט ימלא את כל הרוחב הזמין': 'The text fills the full width available', 'הטקסט מכיל תו פגום (חצי מתו מורכב, כמו אימוג׳י שנקטע), ולכן לא ניתן לשלוח אותו כהצעה מדויקת. יש למחוק את התו או לשלוח דיווח חופשי.': 'The text contains an incomplete character, such as part of an emoji, and cannot be sent as an exact correction. Remove the character or send a free-text report.', 'הטקסט שנבחר': 'The Selected Text', - 'הטקסט שנבחר:': 'Selected text:', 'היברובוקס בלבד': 'HebrewBooks only', 'הידעת?': 'Did You Know?', 'היום בלוח יתחלף בזמן השקיעה של העיר הנבחרת': 'The date changes at Shkiah.', @@ -579,7 +571,6 @@ const Map> kSettingsCatalogs = { 'העתיקו כמה מילים כפי שהן בספר, ושוב כשהן מתוקנות': 'Quote a few words as they appear in the book, followed by the corrected version.', 'העתק': 'Copy', 'העתק טקסט': 'Copy text', - 'העתק מספר טלפון': 'Copy phone number', 'העתק נתיב': 'Copy Path', 'העתק נתיב...': 'Copy Path...', 'העתק פרטים': 'Copy Details', @@ -722,7 +713,6 @@ const Map> kSettingsCatalogs = { 'התקדמות האינדקס: {processed}/{total}': 'Indexing: {processed}/{total}', 'התקן': 'Install', 'התקן תוסף חדש': 'Install a new plugin', - 'התקשר': 'Call', 'התראות': 'Alerts', 'וי״ו קטיעא': 'Broken vav', 'זהו הצירוף הבסיסי — הוא נערך למעלה': 'This is the base combination — edit it above', @@ -795,7 +785,6 @@ const Map> kSettingsCatalogs = { 'חתימת הקריסה': 'Crash signature', 'טאבים — ספרים מרובים': 'Tabs — Multiple Seforim', 'טווח קרבה: {scope} · התאמת מילים: {mode}': 'Proximity: {scope} · Word matching: {mode}', - 'טוען נתוני דיווח...': 'Loading report details…', 'טוען ספרייה': 'Loading library', 'טוען...': 'Loading...', 'טורקיז': 'Teal', @@ -812,9 +801,7 @@ const Map> kSettingsCatalogs = { 'טען תיקיית תוסף': 'Load a plugin folder', 'טקסט': 'Text', 'טקסט המקור (לא ניתן לעריכה):': 'Original text (read only):', - 'טקסט חסר': 'Missing text', 'טקסט מוצע': 'Proposed text', - 'טקסט מיותר': 'Extra text', 'טרם נבחר מיקום': 'No Location Chosen Yet', 'י-ה-ו-ה יוצג כ-י-ק-ו-ק': 'The Divine Name is shown in a substituted spelling', 'ידוד': 'Y-Dalet-V-Dalet', @@ -955,14 +942,12 @@ const Map> kSettingsCatalogs = { 'לא ידוע': 'Unknown', 'לא יובאו עדיין קבצים. השתמש ב"ייבוא נתונים" כדי להוסיף.': 'No files imported yet. Use "Import Data" to add some.', 'לא ממוזגת': 'not merged', - 'לא נבחר': 'Not selected', 'לא נוסף דבר — כל מה שבקובץ כבר קיים במכשיר זה.': 'Nothing was added — everything in the file already exists on this device.', 'לא ניתן היה לאסוף מידע אבחון': 'Diagnostic information could not be collected', 'לא ניתן היה לקרוא את התמונה.': 'The image could not be read.', 'לא ניתן להתחבר למקור העדכונים': 'Could not reach the update source', 'לא ניתן לזהות את הספר לדיווח.': 'The book for this report could not be identified.', 'לא ניתן לטעון את הטיוטה. יש לסגור ולנסות לפתוח אותה שוב; התוכן השמור לא שונה.': 'The draft could not be loaded. Close the form and try opening it again; the saved content has not changed.', - 'לא ניתן לטעון את נתוני הדיווח:': 'Could not load report details:', 'לא ניתן למחוק את הסיסמה כשמצב סייפר פעיל': 'The password cannot be removed while Safer Mode is on', 'לא ניתן לעדכן את הטיוטה. נסו שוב.': 'The draft could not be updated. Please try again.', 'לא ניתן לפתוח': 'Cannot be opened', @@ -1044,7 +1029,6 @@ const Map> kSettingsCatalogs = { 'לפי אורך המילה: מ-4 אותיות, הבדל של אות אחת (החלפה, הוספה או השמטה); ב-3 אותיות, רק החלפת אות באות דומה (שבת ימצא שבט); במילה קצרה יותר, בלי. יחד עם "חלק ממילה" החיפוש רחב מאוד ואיטי יותר.': 'By word length: from 4 letters, one letter different (replaced, added or dropped); in 3 letters, only a letter replaced by a similar one (שבת finds שבט); in shorter words, none. Combined with "Partial word" the search is very broad and slower.', 'לפי המסורת': 'By tradition', 'לפי שפת מערכת ההפעלה': 'Use device language', - 'לפירוט נוסף, השאר הקלטה ברורה!': 'Leave a clear recording with any additional details.', 'לצרף את קובץ הקריסה (minidump)': 'Include the crash dump (minidump)', 'לצרף מידע אבחון על התוכנה והמערכת': 'Include program and system diagnostics', 'לצרף קטע מיומן השגיאות': 'Include an excerpt from the error log', @@ -1141,10 +1125,7 @@ const Map> kSettingsCatalogs = { 'מסך הקריאה': 'Reading View', 'מסכתות הבבלי ייפתחו במהדורת ה-PDF בדף המתאים, גם בפתיחה מהספרייה ובתצוגה המקדימה': 'Gemaros in PDF will open at the right daf, including from the library and the preview pane', 'מסכתות הבבלי ייפתחו במהדורת הטקסט (מהספרייה, מתוצאות חיפוש, מאיתור מקורות ומקישורים)': 'Gemaros will open in text format', - 'מספר גירסה': 'Version number', - 'מספר ספר': 'Book number', 'מספר קופה:': 'Fund number:', - 'מספר שגיאה': 'Error number', 'מספר שורה': 'Line number', 'מספר תוצאות': 'Number of Results', 'מעבד...': 'Working...', @@ -1253,7 +1234,6 @@ const Map> kSettingsCatalogs = { 'נתוני {name} עוד לא הותקנו.': 'The {name} data has not been installed yet.', 'נתוני {name} פגומים או אינם תואמים לגרסה זו. יש להוריד אותם מחדש.': 'The {name} data is damaged or does not match this version. Download it again.', 'נתוני {name} שהתקבלו אינם הגרסה הרשמית. יש להוריד אותם מחדש.': 'The {name} data received is not the official release. Download it again.', - 'נתוני הדיווח:': 'Report details:', 'נתוני החיפוש לגרסת הספרייה {version} עוד לא פורסמו. הם יורדו כשיתפרסמו.': 'Search data for library version {version} has not been published yet. It will be downloaded once it is.', 'נתוני משתמש': 'User Data', 'נתונים שהגיעו מקבצים אחרים יישארו. אפשר גם להשהות במקום למחוק.': 'Data from other files is kept. You can also pause the file instead of deleting it.', @@ -1456,7 +1436,6 @@ const Map> kSettingsCatalogs = { 'קבצים מיובאים': 'Imported Files', 'קבצים שאינם טקסט': 'Non-text files', 'קבצים שאינם טקסט — נקראים ישירות מהקבצים': 'Non-text files — read directly from the files', - 'קו אוצריא:': 'Otzaria phone line:', 'קובע כמה מילים יכולות להופיע בין מילות החיפוש. כאשר מוגדרים מרווחים ידניים בין מילים, השדה הזה מושבת.': 'Sets how many words may appear between the search words. When manual per-word spacing is set, this field is disabled.', 'קובע עד כמה מותר לתוצאה להיות שונה מהמילים שהוקלדו.': 'Sets how different a result may be from the typed words.', 'קובץ "<שם הקובץ>.כותרות.csv" ליד ספר טקסט מוסיף לו את לשונית "כותרות" (עמודות: מבנה, רמה, כותרת, שורה או טקסט). קובץ "גרסאות.csv" בתיקייה מאחד כמה קבצים לספר אחד (עמודות: ראשי, גרסה, שם). קובץ "<שם הספר>.links.csv" או "<שם הספר>_links.json" מוסיף קישורים. הקבצים נקלטים בסריקת התיקייה.': 'A ".כותרות.csv" file next to a text sefer adds a Headings tab to it (columns: מבנה, רמה, כותרת, שורה or טקסט). A "גרסאות.csv" file in the folder combines several files into one sefer (columns: ראשי, גרסה, שם). A ".links.csv" or "_links.json" file adds links. The files are picked up when the folder is scanned.', @@ -1531,9 +1510,6 @@ const Map> kSettingsCatalogs = { 'שגיאה בשליחת הדיווח.': 'The report could not be sent.', 'שגיאה בשליחת הדיווח: {error}': 'Could not send the report: {error}', 'שגיאות כתיב': 'Typo tolerance', - 'שגיאת כתיב': 'Spelling error', - 'שגיאת מקור': 'Source error', - 'שגיאת עיצוב': 'Formatting error', 'שולחנות עבודה': 'Workspaces', 'שום גיבוי לא נמחק': 'No backup is ever deleted', 'שורה {number}': 'Line {number}', @@ -1569,7 +1545,6 @@ const Map> kSettingsCatalogs = { 'שלח ישירות ל{target}': 'Send directly to {target}', 'שלח עכשיו': 'Send Now', 'שליחה ישירה לצוות אוצריא, כולל תור אוטומטי במצב אופליין.': 'Sent directly to Otzaria, with offline requests handled automatically when you reconnect.', - 'שליחת דיווח': 'Send report', 'שליחת דיווח תעזור לנו למצוא את הסיבה ולתקן אותה.': 'Sending a report helps us find the cause and fix it.', 'שליחת דיווחים שמורים - אוצריא': 'Send queued reports - Otzaria', 'שליחת התראת ניסיון כדי לוודא שהתראות המערכת פועלות': 'Send a trial notification to verify that system notifications are working', diff --git a/lib/settings/l10n/settings_en.arb b/lib/settings/l10n/settings_en.arb index 6420ab0287..55dab1c6d0 100644 --- a/lib/settings/l10n/settings_en.arb +++ b/lib/settings/l10n/settings_en.arb @@ -1492,11 +1492,7 @@ "הנוסח המתוקן": "Corrected text", "השינוי המוצע:": "Proposed change:", "לא נשלח ערך": "No value is sent", - "שליחת דיווח": "Send report", - "דיווח דרך קו אוצריא": "Report by Otzaria phone line", "דיווח על טעות בספר": "Report a book error", - "טוען נתוני דיווח...": "Loading report details…", - "לא ניתן לטעון את נתוני הדיווח:": "Could not load report details:", "שמירת הטיוטה נכשלה. התוכן עדיין בטופס; נסו שוב.": "The draft could not be saved. Your content is still in the form; please try again.", "השלכת הטיוטה נכשלה. נסו שוב.": "The draft could not be discarded. Please try again.", "לחץ כאן על מנת לתקן את הספר בעצמך": "Edit the book yourself", @@ -1541,22 +1537,7 @@ "הסתר את מה שיישלח": "Hide report preview", "הצג את מה שיישלח": "Preview what will be sent", "כתובת דוא\"ל": "Email address", - "נתוני הדיווח:": "Report details:", - "מספר גירסה": "Version number", - "מספר ספר": "Book number", "מספר שורה": "Line number", - "מספר שגיאה": "Error number", - "לא נבחר": "Not selected", - "קו אוצריא:": "Otzaria phone line:", - "העתק מספר טלפון": "Copy phone number", - "התקשר": "Call", - "לפירוט נוסף, השאר הקלטה ברורה!": "Leave a clear recording with any additional details.", - "הוראות לדיווח טלפוני:": "Phone reporting instructions:", - "1. בחר את סוג השגיאה • 2. השתמש במספרים המוצגים למטה כשתתקשר": "1. Choose the error type. • 2. Use the numbers below when you call.", - "הטקסט שנבחר:": "Selected text:", - "בחר סוג שגיאה:": "Choose an error type:", - "אי אפשר להתקדם... עדיין לא מילאתם בטופס...": "Complete the required fields to continue.", - "ביטול הדיווח": "Cancel report", "תמונה גדולה מ-{limit} MiB לא צורפה.": "An image larger than {limit} MiB was not attached.", "הגודל הכולל של הצרופות מוגבל ל-{limit} MiB.": "All attachments together are limited to {limit} MiB.", "ניתן לצרף עד {count} תמונות לדיווח.": "You can attach up to {count} images per report.", @@ -1642,13 +1623,7 @@ "השליחה לא הצליחה כרגע. הדיווח נשמר להמשך ויישלח אוטומטית ל{target} בניסיון הבא. ניתן לנהל את הדיווחים השמורים בהגדרות.": "Sending failed. The report was queued for another attempt to {target}. You can manage queued reports in Settings.", "שרת הדיווחים החזיר {status}. הדיווח לא נשמר להמשך כי נראה שיש בעיה קבועה בנתונים שנשלחו.": "The report server returned {status}. The data appears to need correction and was not queued for automatic retry.", "שרת הדיווחים החזיר {status}. הדיווח יישמר להמשך.": "The report server returned {status}. The report will be saved for another attempt.", - "שגיאת כתיב": "Spelling error", - "טקסט חסר": "Missing text", - "טקסט מיותר": "Extra text", - "שגיאת עיצוב": "Formatting error", - "שגיאת מקור": "Source error", "תוכנת הדואר נפתחה. הטיוטה נשמרה בהגדרות עד שתשלחו את הדיווח או תשליכו אותה במפורש.": "The email application opened. The draft remains in Settings until you send the report or explicitly discard it.", - "הועתק ללוח: {text}": "Copied to clipboard: {text}", "שגיאה בהעתקה ללוח": "Could not copy to the clipboard", "לא ניתן לפתוח את אפליקציית הטלפון": "Could not open the phone application", "שגיאה בפתיחת אפליקציית הטלפון": "Error opening the phone application", diff --git a/test/personal_notes/personal_note_draft_revision_test.dart b/test/personal_notes/personal_note_draft_revision_test.dart new file mode 100644 index 0000000000..36ddc13341 --- /dev/null +++ b/test/personal_notes/personal_note_draft_revision_test.dart @@ -0,0 +1,229 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/services/personal_note_draft_service.dart'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; + +import '../test_helpers/memory_cache_provider.dart'; + +class _DelayedDraftCache extends MemoryCacheProvider { + Completer? pointWriteGate; + Completer? removeGate; + bool gatedPointWrite = false; + bool failRemove = false; + + @override + Future setObject(String key, T? value) async { + final write = super.setObject(key, value); + if (pointWriteGate != null && key.contains(':pdf:') && !gatedPointWrite) { + gatedPointWrite = true; + await pointWriteGate!.future; + } + await write; + } + + @override + Future remove(String key) async { + if (failRemove) throw StateError('draft removal failed'); + final removal = super.remove(key); + await removeGate?.future; + await removal; + } +} + +void main() { + final first = PersonalNoteDraftService(); + final second = PersonalNoteDraftService(); + late _DelayedDraftCache cache; + late String bookId; + var sequence = 0; + const line = 4; + const point = PdfNoteAnchor(pageNumber: line, x: .2, y: .3); + + PersonalNoteDraft draft(String content, {PdfNoteAnchor? anchor}) => + PersonalNoteDraft( + content: content, + contentPlain: content, + contentFormat: PersonalNoteContentFormat.plain, + // אותו זמן גם בכתיבות שונות: ההגנה אינה תלויה בשעון או בתוכן. + updatedAt: DateTime.utc(2026), + lineNumber: line, + pdfAnchor: anchor, + ); + + Future legacyPdf() => Settings.setValue( + '${PersonalNoteDraftService.keyPrefix}$bookId:$line', + jsonEncode(draft('טיוטת PDF ישנה', anchor: point).toJson()), + ); + + Future write( + PersonalNoteDraftService service, + String content, { + PdfNoteAnchor? anchor, + }) => service.saveDraft( + bookId: bookId, + lineNumber: line, + draft: draft(content, anchor: anchor), + ); + + Future read({PdfNoteAnchor? anchor}) => first.loadDraft( + bookId: bookId, + lineNumber: line, + pdfAnchor: anchor, + ); + + Object? version({PdfNoteAnchor? anchor}) => first.draftVersion( + bookId: bookId, + lineNumber: line, + pdfAnchor: anchor, + ); + + setUp(() async { + cache = _DelayedDraftCache(); + bookId = 'draft-revision-${sequence++}'; + await Settings.init(cacheProvider: cache); + }); + + tearDown(() { + for (final gate in [cache.pointWriteGate, cache.removeGate]) { + if (gate != null && !gate.isCompleted) gate.complete(); + } + }); + + test( + 'conditional clear preserves a newer identical draft from another service', + () async { + await write(first, 'אותו תוכן'); + final savedVersion = version(); + await write(second, 'אותו תוכן'); + expect(identical(version(), savedVersion), isFalse); + await first.clearDraft( + bookId: bookId, + lineNumber: line, + expectedVersion: savedVersion, + ); + expect((await read())?.contentPlain, 'אותו תוכן'); + }, + ); + + test( + 'an absent revision is conditional while omitted revision clears explicitly', + () async { + await Settings.setValue( + '${PersonalNoteDraftService.keyPrefix}$bookId:$line', + jsonEncode(draft('טיוטה מתהליך קודם').toJson()), + ); + expect(version(), isNull); + await write(second, 'טיוטה חדשה'); + await first.clearDraft( + bookId: bookId, + lineNumber: line, + expectedVersion: null, + ); + expect((await read())?.contentPlain, 'טיוטה חדשה'); + await first.clearDraft(bookId: bookId, lineNumber: line); + expect(await read(), isNull); + }, + ); + + test( + 'clear during legacy migration cancels pending text without deleting PDF', + () async { + await legacyPdf(); + final gate = cache.pointWriteGate = Completer(); + final pending = write(first, 'טקסט שבוטל'); + expect(cache.gatedPointWrite, isTrue); + await second.clearDraft( + bookId: bookId, + lineNumber: line, + expectedVersion: version(), + ); + gate.complete(); + await pending; + + expect(await read(), isNull); + expect((await read(anchor: point))?.contentPlain, 'טיוטת PDF ישנה'); + }, + ); + + test( + 'old migration does not delete a newer text draft in the legacy key', + () async { + await legacyPdf(); + final gate = cache.pointWriteGate = Completer(); + final pending = write(first, 'טקסט ישן'); + expect(cache.gatedPointWrite, isTrue); + await write(second, 'טקסט חדש'); + gate.complete(); + await pending; + + expect((await read())?.contentPlain, 'טקסט חדש'); + expect((await read(anchor: point))?.contentPlain, 'טיוטת PDF ישנה'); + }, + ); + + test( + 'old migration preserves a newer PDF draft in the copied point key', + () async { + await legacyPdf(); + const anotherPoint = PdfNoteAnchor(pageNumber: line, x: .7, y: .8); + final gate = cache.pointWriteGate = Completer(); + final pending = write(first, 'נקודה אחרת', anchor: anotherPoint); + expect(cache.gatedPointWrite, isTrue); + await write(second, 'נקודה שהתעדכנה', anchor: point); + gate.complete(); + await pending; + + expect((await read(anchor: point))?.contentPlain, 'נקודה שהתעדכנה'); + expect((await read(anchor: anotherPoint))?.contentPlain, 'נקודה אחרת'); + expect(await read(), isNull); + }, + ); + + test( + 'delayed PDF cleanup cannot restore its legacy copy through a text writer', + () async { + await write(first, 'טיוטת PDF ישנה', anchor: point); + await legacyPdf(); + final gate = cache.removeGate = Completer(); + final cleanup = first.clearDraft( + bookId: bookId, + lineNumber: line, + pdfAnchor: point, + expectedVersion: version(anchor: point), + ); + // שתי המחיקות כבר נראות במטמון; רק אישור ה-flush מושהה. + expect(await read(anchor: point), isNull); + await write(second, 'טקסט חדש'); + gate.complete(); + await cleanup; + + expect((await read())?.contentPlain, 'טקסט חדש'); + expect(await read(anchor: point), isNull); + }, + ); + + test('a failed clear retains its revision for a later retry', () async { + await write(first, 'טיוטה למחיקה'); + final savedVersion = version(); + cache.failRemove = true; + await expectLater( + first.clearDraft( + bookId: bookId, + lineNumber: line, + expectedVersion: savedVersion, + ), + throwsStateError, + ); + expect(identical(version(), savedVersion), isTrue); + cache.failRemove = false; + await first.clearDraft( + bookId: bookId, + lineNumber: line, + expectedVersion: savedVersion, + ); + expect(await read(), isNull); + }); +} diff --git a/test/personal_notes/personal_notes_manager_loading_test.dart b/test/personal_notes/personal_notes_manager_loading_test.dart index 57eaa2402f..f14544c891 100644 --- a/test/personal_notes/personal_notes_manager_loading_test.dart +++ b/test/personal_notes/personal_notes_manager_loading_test.dart @@ -21,6 +21,7 @@ import 'package:otzaria/personal_notes/bloc/personal_notes_event.dart'; import 'package:otzaria/personal_notes/models/personal_note.dart'; import 'package:otzaria/personal_notes/repository/personal_notes_repository.dart'; import 'package:otzaria/personal_notes/services/personal_note_draft_service.dart'; +import 'package:otzaria/personal_notes/services/personal_notes_service.dart'; import 'package:otzaria/personal_notes/storage/personal_notes_changes.dart'; import 'package:otzaria/personal_notes/storage/personal_notes_database.dart'; import 'package:otzaria/personal_notes/view/personal_notes_screen.dart'; @@ -86,7 +87,7 @@ BookNotesInfo _book(String id) => BookNotesInfo( ); class _Repository extends PersonalNotesRepository { - _Repository(this.notes); + _Repository(this.notes, {super.service}); final Map> notes; bool delayLists = false; @@ -257,6 +258,87 @@ Future _mount( return notesBloc; } +class _ServiceMutationRepository extends _Repository { + _ServiceMutationRepository(super.notes, this._mutationService) + : super(service: _mutationService); + + final PersonalNotesService _mutationService; + static const _bookContent = 'first line\nsecond line\nthird line'; + + @override + Future> repositionNote({ + required String bookId, + required String noteId, + required int lineNumber, + PdfNoteAnchor? pdfAnchor, + int? categoryId, + }) => _mutationService.repositionNote( + bookId: bookId, + bookContent: _bookContent, + noteId: noteId, + lineNumber: lineNumber, + pdfAnchor: pdfAnchor, + ); + + @override + Future moveNote({ + required String bookId, + required String noteId, + required int lineNumber, + PdfNoteAnchor? pdfAnchor, + int? categoryId, + }) => _mutationService.moveNote( + bookId: bookId, + bookContent: _bookContent, + noteId: noteId, + lineNumber: lineNumber, + pdfAnchor: pdfAnchor, + ); +} + +class _MutationRefreshDatabase extends Fake implements PersonalNotesDatabase { + _MutationRefreshDatabase(this.notes); + + final Map> notes; + int writes = 0; + int listReads = 0; + + @override + Future> loadNotes(String bookId) async { + listReads++; + throw StateError('list refresh failed after the write'); + } + + @override + Future getNote(String noteId) async { + for (final bookNotes in notes.values) { + for (final note in bookNotes) { + if (note.id == noteId) return note; + } + } + return null; + } + + @override + Future deleteNote(String noteId) async { + final note = await getNote(noteId); + if (note == null) return; + notes[note.bookId]!.removeWhere((note) => note.id == noteId); + writes++; + PersonalNotesChanges.notify(note.bookId); + } + + @override + Future updateNote(PersonalNote updated) async { + final bookNotes = notes[updated.bookId]!; + final index = bookNotes.indexWhere((note) => note.id == updated.id); + if (index < 0) throw StateError('note no longer exists'); + bookNotes[index] = updated; + writes++; + PersonalNotesChanges.notify(updated.bookId); + } +} + class _MutationRepository extends _Repository { _MutationRepository(super.notes); final pendingWrite = Completer(); @@ -281,19 +363,24 @@ class _MutationRepository extends _Repository { } @override - Future> deleteNote({ - required String bookId, - required String noteId, - }) => _write(bookId, noteId, null); + Future removeNote({required String noteId}) async { + final bookId = notes.entries + .singleWhere((entry) => entry.value.any((note) => note.id == noteId)) + .key; + await _write(bookId, noteId, null); + } @override - Future> repositionNote({ + Future moveNote({ required String bookId, required String noteId, required int lineNumber, PdfNoteAnchor? pdfAnchor, int? categoryId, - }) => _write(bookId, noteId, lineNumber); + }) async { + final stored = await _write(bookId, noteId, lineNumber); + return stored.singleWhere((note) => note.id == noteId); + } } void main() { @@ -810,6 +897,52 @@ void main() { }, ); for (final reposition in [false, true]) { + testWidgets( + 'manager acknowledges ${reposition ? "reposition" : "delete"} without a post-write list read', + (tester) async { + var note = _note('ספר א', 'תוכן פעולת מנהל'); + if (reposition) { + note = note.copyWith( + clearLineNumber: true, + status: PersonalNoteStatus.missing, + ); + } + final notes = >{ + note.bookId: [note], + }; + final database = _MutationRefreshDatabase(notes); + final repository = _ServiceMutationRepository( + notes, + PersonalNotesService(database: database), + ); + final reader = await _mount(tester, repository); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip(reposition ? 'מיקום מחדש' : 'מחיקה')); + await tester.pumpAndSettle(); + if (reposition) { + await tester.enterText(find.byType(EditableText).last, '3'); + } + await tester.tap(find.text(reposition ? 'שמור' : 'מחק')); + await tester.pumpAndSettle(); + + final success = reposition + ? NotesMessages.noteMovedToLine(3) + : NotesMessages.noteDeleted; + expect(database.writes, 1); + expect(find.text(success), findsOneWidget); + expect(database.listReads, 0); + expect(find.textContaining('list refresh failed'), findsNothing); + expect(reader.state.bookId, isNull); + if (reposition) { + expect(notes[note.bookId]!.single.lineNumber, 3); + } else { + expect(notes[note.bookId], isEmpty); + } + await expectLater(database.loadNotes(note.bookId), throwsStateError); + await tester.pump(const Duration(seconds: 10)); + }, + ); + for (final fail in [false, true]) { testWidgets( 'manager ${reposition ? "repositions" : "deletes"} only after confirmed write (failure: $fail)', diff --git a/test/personal_notes/personal_notes_reposition_confirmation_test.dart b/test/personal_notes/personal_notes_reposition_confirmation_test.dart new file mode 100644 index 0000000000..2cf0393f5a --- /dev/null +++ b/test/personal_notes/personal_notes_reposition_confirmation_test.dart @@ -0,0 +1,93 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/core/messages/notes_messages.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/services/personal_notes_service.dart'; +import 'package:otzaria/personal_notes/storage/personal_notes_database.dart'; + +class _Database extends Fake implements PersonalNotesDatabase { + PersonalNote? note; + int updates = 0; + int listReads = 0; + + @override + Future getNote(String id) async => note; + + @override + Future updateNote(PersonalNote value) async { + updates++; + note = value; + } + + @override + Future> loadNotes(String bookId) async { + listReads++; + final value = note; + return value != null && value.bookId == bookId ? [value] : []; + } +} + +void main() { + test( + 'reposition refuses an already deleted note instead of reporting success', + () async { + final database = _Database(); + final service = PersonalNotesService(database: database); + + await expectLater( + service.repositionNote( + bookId: 'requested-book', + bookContent: 'first line\nsecond line', + noteId: 'removed-note', + lineNumber: 2, + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + NotesMessages.noteNoLongerExists, + ), + ), + ); + + expect(database.updates, 0); + expect(database.listReads, 0); + }, + ); + + test('reposition refuses an id belonging to a different book', () async { + final original = PersonalNote( + id: 'moved-note', + bookId: 'other-book', + lineNumber: 1, + lastKnownLineNumber: null, + status: PersonalNoteStatus.located, + content: 'retained content', + contentPlain: 'retained content', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), + ); + final database = _Database()..note = original; + final service = PersonalNotesService(database: database); + + await expectLater( + service.repositionNote( + bookId: 'requested-book', + bookContent: 'first line\nsecond line', + noteId: original.id, + lineNumber: 2, + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + NotesMessages.noteMovedToDifferentBook, + ), + ), + ); + + expect(database.note, original); + expect(database.updates, 0); + expect(database.listReads, 0); + }); +} diff --git a/test/personal_notes/personal_notes_repository_delete_test.dart b/test/personal_notes/personal_notes_repository_delete_test.dart index b737befa43..19f30de097 100644 --- a/test/personal_notes/personal_notes_repository_delete_test.dart +++ b/test/personal_notes/personal_notes_repository_delete_test.dart @@ -79,6 +79,14 @@ void main() { expect(files.textReads, 0); }); + test('מחיקה מאושרת אינה קוראת את תוכן הספר', () async { + await repository.removeNote(noteId: 'a'); + + expect(files.textReads, 0); + expect(await database.getNote('a'), isNull); + expect((await database.loadNotes(_bookId)).map((note) => note.id), ['b']); + }); + test('מחיקת הערה מחזירה את שאר הערות הספר', () async { final remaining = await repository.deleteNote( bookId: _bookId, diff --git a/test/personal_notes/personal_notes_write_confirmation_test.dart b/test/personal_notes/personal_notes_write_confirmation_test.dart index c85c4005e8..b0a8e18ea2 100644 --- a/test/personal_notes/personal_notes_write_confirmation_test.dart +++ b/test/personal_notes/personal_notes_write_confirmation_test.dart @@ -18,9 +18,12 @@ class _ControlledDatabase extends Fake implements PersonalNotesDatabase { final notes = {}; bool failReads = true; bool failInsert = false; + bool failDelete = false; + bool failUpdate = false; int listReads = 0; int inserts = 0; int updates = 0; + int deletes = 0; @override Future> loadNotes(String bookId) async { @@ -42,10 +45,18 @@ class _ControlledDatabase extends Fake implements PersonalNotesDatabase { @override Future updateNote(PersonalNote note) async { updates++; + if (failUpdate) throw StateError('update failed'); if (!notes.containsKey(note.id)) throw StateError('note no longer exists'); notes[note.id] = note; } + @override + Future deleteNote(String noteId) async { + deletes++; + if (failDelete) throw StateError('delete failed'); + notes.remove(noteId); + } + @override Future batchUpdateNotes(List changed) async { for (final note in changed) { @@ -65,7 +76,7 @@ class _DeleteBeforeUpdateDatabase extends Fake @override Future updateNote(PersonalNote note) async { - // A real concurrent deletion after persistNote read the original record. + // A real concurrent deletion after the service read the original record. await delegate.deleteNote(note.id); await delegate.updateNote(note); } @@ -252,6 +263,149 @@ void main() { }, ); + test('delete confirms a committed write without reading the list', () async { + final original = _note(); + final retained = original.copyWith(id: 'retained-note'); + final database = _ControlledDatabase() + ..notes[original.id] = original + ..notes[retained.id] = retained; + final service = PersonalNotesService(database: database); + + await service.removeNote(noteId: original.id); + + expect(database.deletes, 1); + expect(database.listReads, 0); + expect(database.notes.values, [retained]); + await expectLater(database.loadNotes(_bookId), throwsStateError); + expect(database.notes.values, [retained]); + }); + + test('a failed delete is not acknowledged', () async { + final original = _note(); + final database = _ControlledDatabase() + ..notes[original.id] = original + ..failDelete = true; + final service = PersonalNotesService(database: database); + + await expectLater( + service.removeNote(noteId: original.id), + throwsStateError, + ); + + expect(database.deletes, 1); + expect(database.listReads, 0); + expect(database.notes.values, [original]); + }); + + test( + 'reposition confirms a committed write without reading the list', + () async { + final database = _ControlledDatabase(); + final service = PersonalNotesService(database: database); + final original = await _create(service); + final retained = _note(); + database.notes[retained.id] = retained; + + final moved = await service.moveNote( + bookId: _bookId, + bookContent: _bookContent, + noteId: original.id, + lineNumber: 3, + ); + + expect(database.updates, 1); + expect(database.listReads, 0); + expect(database.notes[original.id], moved); + expect(database.notes[retained.id], retained); + expect(moved.lineNumber, 3); + expect(moved.status, PersonalNoteStatus.located); + expect(moved.anchorText, isNull); + expect(moved.createdAt, original.createdAt); + expect(moved.content, original.content); + await expectLater(database.loadNotes(_bookId), throwsStateError); + expect(database.notes[original.id], moved); + }, + ); + + test('a failed reposition is not acknowledged', () async { + final original = _note(); + final database = _ControlledDatabase() + ..notes[original.id] = original + ..failUpdate = true; + final service = PersonalNotesService(database: database); + + await expectLater( + service.moveNote( + bookId: _bookId, + bookContent: _bookContent, + noteId: original.id, + lineNumber: 3, + ), + throwsStateError, + ); + + expect(database.updates, 1); + expect(database.listReads, 0); + expect(database.notes.values, [original]); + }); + + test('compatibility mutations still return refreshed lists', () async { + final original = _note(); + final retained = original.copyWith(id: 'retained-note'); + final database = _ControlledDatabase() + ..failReads = false + ..notes[original.id] = original + ..notes[retained.id] = retained; + final service = PersonalNotesService(database: database); + + final moved = await service.repositionNote( + bookId: _bookId, + bookContent: _bookContent, + noteId: original.id, + lineNumber: 3, + ); + expect(moved, hasLength(2)); + expect(moved.singleWhere((note) => note.id == original.id).lineNumber, 3); + expect(moved, contains(retained)); + + final remaining = await service.deleteNote( + bookId: _bookId, + noteId: original.id, + ); + expect(remaining, [retained]); + expect(database.listReads, 2); + }); + + for (final reposition in [false, true]) { + test( + 'list-returning ${reposition ? "reposition" : "delete"} still reports a refresh failure', + () async { + final original = _note(); + final database = _ControlledDatabase()..notes[original.id] = original; + final service = PersonalNotesService(database: database); + + await expectLater( + reposition + ? service.repositionNote( + bookId: _bookId, + bookContent: _bookContent, + noteId: original.id, + lineNumber: 3, + ) + : service.deleteNote(bookId: _bookId, noteId: original.id), + throwsStateError, + ); + + expect(database.listReads, 1); + if (reposition) { + expect(database.notes[original.id]!.lineNumber, 3); + } else { + expect(database.notes, isEmpty); + } + }, + ); + } + group('real SQLite write confirmation', () { final database = PersonalNotesDatabase.instance; late Directory temporaryRoot; @@ -319,5 +473,30 @@ void main() { expect(database.revision.value, revisionBeforeDelete + 1); }, ); + + test( + 'reposition detects deletion between its initial read and UPDATE', + () async { + final note = _note(); + await database.insertNote(note); + final revisionBeforeDelete = database.revision.value; + final service = PersonalNotesService( + database: _DeleteBeforeUpdateDatabase(database), + ); + + await expectLater( + service.moveNote( + bookId: note.bookId, + bookContent: _bookContent, + noteId: note.id, + lineNumber: 3, + ), + throwsStateError, + ); + + expect(await database.getNote(note.id), isNull); + expect(database.revision.value, revisionBeforeDelete + 1); + }, + ); }); } diff --git a/test/personal_notes/widgets/personal_note_list_backspace_test.dart b/test/personal_notes/widgets/personal_note_list_backspace_test.dart new file mode 100644 index 0000000000..06dfe39032 --- /dev/null +++ b/test/personal_notes/widgets/personal_note_list_backspace_test.dart @@ -0,0 +1,486 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_quill/flutter_quill.dart' as quill; +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/widgets/inline_note_editor.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_editor.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_editor_dialog.dart'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; +import 'package:otzaria/settings/engine/settings_bloc.dart'; +import 'package:otzaria/settings/engine/settings_repository.dart'; + +import '../../test_helpers/memory_cache_provider.dart'; + +enum _Surface { inline, dialog } + +Widget _host(Widget child) => RepositoryProvider( + create: (_) => SettingsRepository(), + child: BlocProvider( + create: (context) => + SettingsBloc(repository: context.read()), + child: MaterialApp( + home: Directionality( + textDirection: TextDirection.rtl, + child: Scaffold(body: child), + ), + ), + ), +); + +Future _open( + WidgetTester tester, + List> delta, { + _Surface surface = _Surface.inline, +}) async { + final content = jsonEncode(delta); + await tester.pumpWidget( + _host( + surface == _Surface.inline + ? InlineNoteEditor( + bookId: 'list-backspace-test', + draftLineNumber: 1, + initialContent: content, + initialFormat: PersonalNoteContentFormat.quillDelta, + linkableNotes: const [], + onSave: (_) {}, + onCancel: () {}, + ) + : Builder( + builder: (context) => TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => Directionality( + textDirection: TextDirection.rtl, + child: PersonalNoteEditorDialog( + initialContent: content, + initialContentFormat: + PersonalNoteContentFormat.quillDelta, + ), + ), + ), + child: const Text('פתח'), + ), + ), + ), + ); + if (surface == _Surface.dialog) { + await tester.tap(find.text('פתח')); + } + await tester.pumpAndSettle(); + final editor = tester.widget( + find.byType(quill.QuillEditor), + ); + editor.focusNode.requestFocus(); + await tester.pumpAndSettle(); + return editor.controller; +} + +List> _list(String kind, {String second = ''}) => [ + {'insert': 'ראשון'}, + { + 'insert': '\n', + 'attributes': {'list': kind}, + }, + if (second.isNotEmpty) {'insert': second}, + { + 'insert': '\n', + 'attributes': {'list': kind}, + }, +]; + +Map _lineAttributes( + quill.QuillController controller, + int at, +) => controller.document.queryChild(at).node!.toDelta().last.attributes ?? {}; + +Future _select( + WidgetTester tester, + quill.QuillController controller, + TextSelection selection, +) async { + controller.updateSelection(selection, quill.ChangeSource.local); + await tester.pump(); +} + +Future _type( + WidgetTester tester, + quill.QuillController controller, + String text, +) async { + final selection = controller.selection; + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: controller.document.toPlainText().replaceRange( + selection.start, + selection.end, + text, + ), + selection: TextSelection.collapsed(offset: selection.start + text.length), + ), + ); + await tester.pump(); +} + +Future _press(WidgetTester tester, LogicalKeyboardKey key) async { + await tester.sendKeyEvent(key); + await tester.pump(); +} + +Future _close(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + expect(tester.takeException(), isNull); +} + +void _testOnWindows(String description, WidgetTesterCallback callback) { + testWidgets(description, (tester) async { + final previousPlatform = debugDefaultTargetPlatformOverride; + final previousErrorHandler = FlutterError.onError!; + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + FlutterError.onError = (details) { + // takeException below keeps the assertion strict; retain its original stack. + debugPrintSynchronously( + 'List keyboard error: ${details.exceptionAsString()}', + ); + debugPrintSynchronously(details.stack.toString()); + previousErrorHandler(details); + }; + try { + await callback(tester); + } finally { + FlutterError.onError = previousErrorHandler; + debugDefaultTargetPlatformOverride = previousPlatform; + } + }); +} + +void main() { + setUp(() async { + await Settings.init(cacheProvider: MemoryCacheProvider()); + }); + + for (final surface in _Surface.values) { + for (final kind in ['bullet', 'ordered']) { + _testOnWindows( + 'Backspace אחרי Enter יוצא מרשימת $kind ב-${surface.name}', + ( + tester, + ) async { + final controller = await _open(tester, [ + {'insert': 'ראשון'}, + { + 'insert': '\n', + 'attributes': {'list': kind}, + }, + ], surface: surface); + await _select( + tester, + controller, + const TextSelection.collapsed(offset: 5), + ); + await _type(tester, controller, '\n'); + expect(controller.document.toPlainText(), 'ראשון\n\n'); + expect( + controller.selection, + const TextSelection.collapsed(offset: 6), + ); + expect(_lineAttributes(controller, 6)['list'], kind); + + await _press(tester, LogicalKeyboardKey.backspace); + + expect(controller.document.toDelta().toJson(), [ + {'insert': 'ראשון'}, + { + 'insert': '\n', + 'attributes': {'list': kind}, + }, + {'insert': '\n'}, + ]); + expect( + controller.selection, + const TextSelection.collapsed(offset: 6), + ); + await _type(tester, controller, 'המשך'); + expect(controller.document.toPlainText(), 'ראשון\nהמשך\n'); + expect(_lineAttributes(controller, 6)['list'], isNull); + expect(_lineAttributes(controller, 0)['list'], kind); + await _close(tester); + }, + ); + } + } + + for (final kind in ['bullet', 'ordered']) { + _testOnWindows('Backspace ברשימת $kind מקוננת מוריד רמה ושומר עיצוב', ( + tester, + ) async { + final controller = await _open(tester, [ + { + 'insert': 'ראשון', + 'attributes': {'bold': true}, + }, + { + 'insert': '\n', + 'attributes': {'list': kind}, + }, + { + 'insert': '\n', + 'attributes': { + 'list': kind, + 'indent': 2, + 'align': 'right', + 'direction': 'rtl', + }, + }, + ]); + await _select( + tester, + controller, + const TextSelection.collapsed(offset: 6), + ); + for (final indent in [1, 0]) { + await _press(tester, LogicalKeyboardKey.backspace); + expect(_lineAttributes(controller, 6), { + 'list': kind, + if (indent > 0) 'indent': indent, + 'align': 'right', + 'direction': 'rtl', + }); + expect(controller.document.toPlainText(), 'ראשון\n\n'); + expect(controller.selection, const TextSelection.collapsed(offset: 6)); + } + await _press(tester, LogicalKeyboardKey.backspace); + expect(_lineAttributes(controller, 6), { + 'align': 'right', + 'direction': 'rtl', + }); + expect(controller.document.toPlainText(), 'ראשון\n\n'); + expect(controller.document.toDelta().first.attributes, {'bold': true}); + expect(_lineAttributes(controller, 0), {'list': kind}); + expect(controller.selection, const TextSelection.collapsed(offset: 6)); + await _close(tester); + }); + } + + _testOnWindows('פריט שאינו ריק שומר את מחיקת הטקסט הרגילה', (tester) async { + final controller = await _open(tester, _list('bullet', second: 'שני')); + await _select(tester, controller, const TextSelection.collapsed(offset: 7)); + await _press(tester, LogicalKeyboardKey.backspace); + expect(controller.document.toPlainText(), 'ראשון\nני\n'); + expect(controller.selection, const TextSelection.collapsed(offset: 6)); + expect(_lineAttributes(controller, 6)['list'], 'bullet'); + await _close(tester); + }); + + _testOnWindows('Backspace בתחילת פריט שאינו ריק עדיין ממזג שורות', ( + tester, + ) async { + final controller = await _open(tester, _list('bullet', second: 'שני')); + await _select(tester, controller, const TextSelection.collapsed(offset: 6)); + await _press(tester, LogicalKeyboardKey.backspace); + expect(controller.document.toPlainText(), 'ראשוןשני\n'); + expect(controller.selection, const TextSelection.collapsed(offset: 5)); + expect(_lineAttributes(controller, 0)['list'], 'bullet'); + await _close(tester); + }); + + _testOnWindows('בחירה שמתחילה בפריט ריק נמחקת כטקסט', (tester) async { + final controller = await _open(tester, _list('bullet')); + await _select( + tester, + controller, + const TextSelection(baseOffset: 6, extentOffset: 5), + ); + await _press(tester, LogicalKeyboardKey.backspace); + expect(controller.document.toPlainText(), 'ראשון\n'); + expect(controller.selection, const TextSelection.collapsed(offset: 5)); + expect(_lineAttributes(controller, 0)['list'], 'bullet'); + await _close(tester); + }); + + _testOnWindows('Delete קדימה בפריט ריק ממשיך למחוק קדימה', (tester) async { + final controller = await _open(tester, [ + ..._list('bullet'), + {'insert': 'אחרון'}, + { + 'insert': '\n', + 'attributes': {'list': 'bullet'}, + }, + ]); + await _select(tester, controller, const TextSelection.collapsed(offset: 6)); + await _press(tester, LogicalKeyboardKey.delete); + expect(controller.document.toPlainText(), 'ראשון\nאחרון\n'); + expect(controller.selection, const TextSelection.collapsed(offset: 6)); + expect(_lineAttributes(controller, 6)['list'], 'bullet'); + await _close(tester); + }); + + for (final modifier in [ + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.shiftLeft, + ]) { + _testOnWindows('${modifier.keyLabel}+Backspace אינו הופך פריט לפסקה', ( + tester, + ) async { + final controller = await _open(tester, _list('bullet')); + await _select( + tester, + controller, + const TextSelection.collapsed(offset: 6), + ); + final before = controller.document.toDelta(); + final selection = controller.selection; + await tester.sendKeyDownEvent(modifier); + await _press(tester, LogicalKeyboardKey.backspace); + await tester.sendKeyUpEvent(modifier); + expect( + _lineAttributes(controller, controller.selection.start)['list'], + 'bullet', + ); + if (modifier == LogicalKeyboardKey.altLeft) { + expect(controller.document.toDelta(), before); + expect(controller.selection, selection); + } + await _close(tester); + }); + } + + _testOnWindows('Alt+Backspace בפריט הראשון עדיין מסיר רשימה', (tester) async { + final controller = await _open(tester, [ + { + 'insert': '\n', + 'attributes': { + 'list': 'bullet', + 'indent': 2, + 'align': 'right', + 'direction': 'rtl', + }, + }, + ]); + await _select(tester, controller, const TextSelection.collapsed(offset: 0)); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await _press(tester, LogicalKeyboardKey.backspace); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + expect(controller.document.toDelta().toJson(), [ + {'insert': '\n'}, + ]); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + await _close(tester); + }); + + _testOnWindows('Alt+Backspace חוזר בפסקה ריקה אינו משנה תוכן', ( + tester, + ) async { + final controller = await _open(tester, [ + {'insert': '\n'}, + ]); + await _select(tester, controller, const TextSelection.collapsed(offset: 0)); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await _press(tester, LogicalKeyboardKey.backspace); + await _press(tester, LogicalKeyboardKey.backspace); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + expect(controller.document.toDelta().toJson(), [ + {'insert': '\n'}, + ]); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + await _close(tester); + }); + + _testOnWindows('פסקה ריקה אחרי רשימה עדיין נמחקת בלי לרשת רשימה', ( + tester, + ) async { + final controller = await _open(tester, [ + {'insert': 'ראשון'}, + { + 'insert': '\n', + 'attributes': {'list': 'bullet'}, + }, + {'insert': '\n'}, + ]); + await _select(tester, controller, const TextSelection.collapsed(offset: 6)); + await _press(tester, LogicalKeyboardKey.backspace); + expect(controller.document.toPlainText(), 'ראשון\n'); + expect(controller.selection, const TextSelection.collapsed(offset: 5)); + await _close(tester); + }); + + _testOnWindows('יציאה מרשימה נשמרת ב-undo וב-redo', (tester) async { + final controller = await _open(tester, _list('bullet')); + await _select(tester, controller, const TextSelection.collapsed(offset: 6)); + final before = controller.document.toDelta(); + await _press(tester, LogicalKeyboardKey.backspace); + final after = controller.document.toDelta(); + expect(controller.document.toPlainText(), 'ראשון\n\n'); + expect(_lineAttributes(controller, 6)['list'], isNull); + controller.undo(); + await tester.pump(); + expect(controller.document.toDelta(), before); + controller.redo(); + await tester.pump(); + expect(controller.document.toDelta(), after); + await _close(tester); + }); + + _testOnWindows('Backspace בפריט הראשון שומר יישור וכיווניות', (tester) async { + final controller = await _open(tester, [ + { + 'insert': '\n', + 'attributes': { + 'list': 'bullet', + 'align': 'right', + 'direction': 'rtl', + }, + }, + ]); + await _press(tester, LogicalKeyboardKey.backspace); + expect(_lineAttributes(controller, 0), { + 'align': 'right', + 'direction': 'rtl', + }); + expect(controller.document.toPlainText(), '\n'); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + await _close(tester); + }); + + _testOnWindows('מצב קריאה בלבד אינו משנה פריט ריק', (tester) async { + final owner = buildPersonalNoteEditorController( + initialContent: jsonEncode(_list('bullet')), + initialFormat: PersonalNoteContentFormat.quillDelta, + ); + final controller = owner.quillController + ..readOnly = true + ..updateSelection( + const TextSelection.collapsed(offset: 6), + quill.ChangeSource.local, + ); + final focus = FocusNode(); + final scroll = ScrollController(); + addTearDown(owner.dispose); + addTearDown(focus.dispose); + addTearDown(scroll.dispose); + await tester.pumpWidget( + _host( + PersonalNoteEditorBody( + controller: owner, + focusNode: focus, + scrollController: scroll, + autofocus: true, + linkableNotes: const [], + ), + ), + ); + await tester.pumpAndSettle(); + final before = controller.document.toDelta(); + await _press(tester, LogicalKeyboardKey.backspace); + expect(controller.document.toDelta(), before); + expect(controller.selection, const TextSelection.collapsed(offset: 6)); + await _close(tester); + }); +} diff --git a/test/personal_notes/widgets/personal_notes_draft_navigation_test.dart b/test/personal_notes/widgets/personal_notes_draft_navigation_test.dart new file mode 100644 index 0000000000..2eff37ee57 --- /dev/null +++ b/test/personal_notes/widgets/personal_notes_draft_navigation_test.dart @@ -0,0 +1,911 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_quill/flutter_quill.dart' as quill; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive_ce/hive.dart'; +import 'package:otzaria/core/messages/notes_messages.dart'; +import 'package:otzaria/core/ui_snack.dart'; +import 'package:otzaria/data/data_providers/hive_data_provider.dart'; +import 'package:otzaria/personal_notes/bloc/personal_notes_bloc.dart'; +import 'package:otzaria/personal_notes/bloc/personal_notes_event.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/repository/personal_notes_repository.dart'; +import 'package:otzaria/personal_notes/services/personal_note_draft_service.dart'; +import 'package:otzaria/personal_notes/storage/personal_notes_changes.dart'; +import 'package:otzaria/personal_notes/widgets/inline_note_editor.dart'; +import 'package:otzaria/personal_notes/widgets/personal_notes_sidebar.dart'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; +import 'package:otzaria/settings/engine/settings_bloc.dart'; +import 'package:otzaria/settings/engine/settings_repository.dart'; +import 'package:otzaria/widgets/controls/action_buttons.dart'; +import 'package:otzaria/widgets/layout/adaptive_side_pane.dart'; + +const _bookId = 'draft-navigation-book'; +const _categoryId = 17; +const _lineNumber = 4; + +class _DraftCache extends HiveCache { + Completer? removeGate; + bool failRemove = false; + int draftRemovals = 0; + + @override + Future remove(String key) async { + if (!key.startsWith(PersonalNoteDraftService.keyPrefix)) { + return super.remove(key); + } + draftRemovals++; + if (failRemove) throw StateError('draft cleanup failed'); + final removal = super.remove(key); + await removeGate?.future; + await removal; + } +} + +class _PendingRepository extends PersonalNotesRepository { + final notes = []; + Completer? pendingCreate; + int creates = 0; + + @override + Future> loadNotes( + String bookId, { + int? categoryId, + }) async => notes.where((note) => note.bookId == bookId).toList(); + + @override + Future> loadStoredNotes(String bookId) => + loadNotes(bookId); + + @override + Future createNote({ + required String bookId, + required int lineNumber, + required String content, + required String contentPlain, + required PersonalNoteContentFormat contentFormat, + String? selectedText, + int? selectionColumn, + String? sourceSelectedText, + int? sourceSelectionOffset, + bool punctuationHidden = false, + PdfNoteAnchor? pdfAnchor, + int? categoryId, + }) async { + creates++; + await pendingCreate?.future; + final now = DateTime.utc(2026, 1, 1); + final note = PersonalNote( + id: 'saved-${notes.length + 1}', + bookId: bookId, + lineNumber: lineNumber, + lastKnownLineNumber: lineNumber, + status: PersonalNoteStatus.located, + content: content, + contentPlain: contentPlain, + contentFormat: contentFormat, + anchorText: selectedText, + pdfAnchor: pdfAnchor, + createdAt: now, + updatedAt: now, + ); + notes.add(note); + PersonalNotesChanges.notify(bookId); + return note; + } +} + +class _NotesBloc extends PersonalNotesBloc { + _NotesBloc({required super.repository}); + + VoidCallback? beforeCancel; + + @override + void onEvent(PersonalNotesEvent event) { + super.onEvent(event); + if (event is CancelCreatingPersonalNote) { + final callback = beforeCancel; + beforeCancel = null; + callback?.call(); + } + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final drafts = PersonalNoteDraftService(); + late _DraftCache cache; + + setUp(() async { + // סריקת טיוטות משתמשת ב-box.keys, ולכן שירות הטיוטות ו-Hive אמיתיים. + await Hive.openBox(HiveCache.keyName, bytes: Uint8List(0)); + cache = _DraftCache(); + await Settings.init(cacheProvider: cache); + }); + + tearDown(Hive.close); + + Future< + ({ + _NotesBloc bloc, + _PendingRepository repository, + ValueNotifier visible, + }) + > + open( + WidgetTester tester, { + bool adaptivePane = false, + PdfNoteAnchor? pdfAnchor, + }) async { + await drafts.saveDraft( + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + draft: PersonalNoteDraft( + content: 'טיוטה מקורית', + contentPlain: 'טיוטה מקורית', + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime.utc(2026), + pdfAnchor: pdfAnchor, + ), + ); + final repository = _PendingRepository(); + // הרשמת זרמי BLoC באזור הזמן של testWidgets, לא ב-setUp. + final bloc = _NotesBloc(repository: repository); + final visible = ValueNotifier(true); + await tester.binding.setSurfaceSize(const Size(1000, 800)); + addTearDown(() async { + if (cache.removeGate case final gate? when !gate.isCompleted) { + gate.complete(); + } + if (repository.pendingCreate case final pending? + when !pending.isCompleted && repository.creates > 0) { + pending.completeError(StateError('test cleanup')); + await tester.pump(); + } + UiSnack.hide(); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + if (!bloc.isClosed) await bloc.close(); + visible.dispose(); + await tester.binding.setSurfaceSize(null); + }); + await tester.pumpWidget( + RepositoryProvider( + create: (_) => SettingsRepository(), + child: MultiBlocProvider( + providers: [ + BlocProvider.value(value: bloc), + BlocProvider( + create: (context) => SettingsBloc( + repository: context.read(), + ), + ), + ], + child: MaterialApp( + navigatorKey: navigatorKey, + locale: const Locale('he'), + supportedLocales: const [Locale('he'), Locale('en')], + localizationsDelegates: const [ + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + quill.FlutterQuillLocalizations.delegate, + ], + home: DefaultTabController( + length: 2, + child: Scaffold( + body: Column( + children: [ + const TabBar( + tabs: [ + Tab(text: 'הערות לבדיקה'), + Tab(text: 'חלונית אחרת'), + ], + ), + Expanded( + child: TabBarView( + children: [ + ValueListenableBuilder( + valueListenable: visible, + builder: (context, show, _) { + final sidebar = PersonalNotesSidebar( + bookId: _bookId, + categoryId: _categoryId, + isPdf: pdfAnchor != null, + pdfDocumentId: pdfAnchor?.documentId, + repository: repository, + onNavigateToLine: (_, {note}) {}, + ); + if (adaptivePane) { + return AdaptiveSidePane( + isOpen: show, + paneWidth: 600, + minMainContentWidth: 200, + onClose: () => visible.value = false, + mainContent: const SizedBox.expand(), + paneContent: sidebar, + ); + } + return show ? sidebar : const SizedBox.shrink(); + }, + ), + const Center(child: Text('תוכן חלונית אחרת')), + ], + ), + ), + ], + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(InlineNoteEditor), findsOneWidget); + return (bloc: bloc, repository: repository, visible: visible); + } + + quill.QuillController controller(WidgetTester tester) => tester + .widget(find.byType(quill.QuillEditor)) + .controller; + + Future replace(WidgetTester tester, String text) async { + final editor = controller(tester); + editor.replaceText( + 0, + editor.document.length - 1, + text, + TextSelection.collapsed(offset: text.length), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(); + } + + Future readDraft({PdfNoteAnchor? pdfAnchor}) => + drafts.loadDraft( + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + pdfAnchor: pdfAnchor, + ); + + Iterable draftKeys() => + Hive.box(HiveCache.keyName).keys.where( + (key) => key.toString().startsWith(PersonalNoteDraftService.keyPrefix), + ); + + testWidgets('tab navigation without Save keeps one live draft', ( + tester, + ) async { + final host = await open(tester); + await replace(tester, 'טקסט שנערך בלי שמירה'); + final originalController = controller(tester); + final token = host.bloc.state.newNoteRequestToken; + + for (var i = 0; i < 3; i++) { + await tester.tap(find.text('חלונית אחרת')); + await tester.pumpAndSettle(); + await tester.tap(find.text('הערות לבדיקה')); + await tester.pumpAndSettle(); + } + + expect(identical(controller(tester), originalController), isTrue); + expect( + controller(tester).document.toPlainText().trim(), + 'טקסט שנערך בלי שמירה', + ); + expect(host.bloc.state.newNoteRequestToken, token); + expect(host.repository.creates, 0); + expect(host.repository.notes, isEmpty); + expect(draftKeys(), hasLength(1)); + expect((await readDraft())?.contentPlain, 'טקסט שנערך בלי שמירה'); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'save completed after panel removal does not reopen a duplicate', + ( + tester, + ) async { + final host = await open(tester); + final pending = host.repository.pendingCreate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.creates, 1); + host.visible.value = false; + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + pending.complete(); + await tester.pumpAndSettle(); + host.visible.value = true; + await tester.pumpAndSettle(); + + expect(host.repository.notes, hasLength(1)); + expect(host.repository.notes.single.contentPlain, 'טיוטה מקורית'); + expect(await readDraft(), isNull); + expect(host.bloc.state.isCreatingNewNote, isFalse); + expect(find.byType(InlineNoteEditor), findsNothing); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('adaptive pane hide and show without Save keeps one live draft', ( + tester, + ) async { + final host = await open(tester, adaptivePane: true); + await replace(tester, 'טיוטה בזמן סגירת חלונית'); + final originalController = controller(tester); + final token = host.bloc.state.newNoteRequestToken; + for (var i = 0; i < 3; i++) { + host.visible.value = false; + await tester.pumpAndSettle(); + host.visible.value = true; + await tester.pumpAndSettle(); + } + + expect(identical(controller(tester), originalController), isTrue); + expect(host.bloc.state.newNoteRequestToken, token); + expect(host.repository.creates, 0); + expect(host.repository.notes, isEmpty); + expect((await readDraft())?.contentPlain, 'טיוטה בזמן סגירת חלונית'); + expect(draftKeys(), hasLength(1)); + expect(tester.takeException(), isNull); + }); + + testWidgets('late save keeps a newer draft at the same location', ( + tester, + ) async { + final host = await open(tester); + final pending = host.repository.pendingCreate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.creates, 1); + host.visible.value = false; + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + host.bloc.add(const CancelCreatingPersonalNote()); + host.bloc.add( + const StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: _lineNumber, + initialContent: 'בקשה חדשה', + ), + ); + await tester.pump(); + final newToken = host.bloc.state.newNoteRequestToken; + host.visible.value = true; + await tester.pump(); + await replace(tester, 'טיוטה חדשה באותה שורה'); + expect((await readDraft())?.contentPlain, 'טיוטה חדשה באותה שורה'); + pending.complete(); + await tester.pumpAndSettle(); + + expect(host.repository.notes, hasLength(1)); + expect(host.bloc.state.newNoteRequestToken, newToken); + expect(host.bloc.state.isCreatingNewNote, isTrue); + expect( + controller(tester).document.toPlainText().trim(), + 'טיוטה חדשה באותה שורה', + ); + expect((await readDraft())?.contentPlain, 'טיוטה חדשה באותה שורה'); + expect(draftKeys(), hasLength(1)); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'restoring the panel while save is pending does not revive the draft', + ( + tester, + ) async { + final host = await open(tester); + final oldController = controller(tester); + final pending = host.repository.pendingCreate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.creates, 1); + host.visible.value = false; + await tester.pump(); + host.visible.value = true; + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(identical(controller(tester), oldController), isFalse); + pending.complete(); + await tester.pumpAndSettle(); + + expect(host.repository.notes, hasLength(1)); + expect(host.bloc.state.isCreatingNewNote, isFalse); + expect(find.byType(InlineNoteEditor), findsNothing); + expect(await readDraft(), isNull); + expect(draftKeys(), isEmpty); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('restored editor preserves new typing before its debounce', ( + tester, + ) async { + final host = await open(tester); + final pending = host.repository.pendingCreate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.creates, 1); + host.visible.value = false; + await tester.pump(); + host.visible.value = true; + await tester.pump(); + final editor = controller(tester); + editor.replaceText( + 0, + editor.document.length - 1, + 'תוספת שטרם נשמרה בטיוטה', + const TextSelection.collapsed(offset: 0), + ); + pending.complete(); + await tester.pumpAndSettle(); + + expect(host.repository.notes.single.contentPlain, 'טיוטה מקורית'); + expect((await readDraft())?.contentPlain, 'תוספת שטרם נשמרה בטיוטה'); + expect(draftKeys(), hasLength(1)); + expect(tester.takeException(), isNull); + }); + + testWidgets('mounted save confirms success after delayed draft cleanup', ( + tester, + ) async { + final host = await open(tester); + final gate = cache.removeGate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.notes, hasLength(1)); + expect(cache.draftRemovals, 1); + expect(host.bloc.state.isCreatingNewNote, isTrue); + gate.complete(); + await tester.pumpAndSettle(); + + expect(find.text(NotesMessages.noteSaved), findsOneWidget); + expect(host.bloc.state.isCreatingNewNote, isFalse); + expect(find.byType(InlineNoteEditor), findsNothing); + UiSnack.hide(); + await tester.pump(); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'mounted save reports cleanup failure and completes its request', + ( + tester, + ) async { + final host = await open(tester); + cache.failRemove = true; + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pumpAndSettle(); + + expect(host.repository.notes, hasLength(1)); + expect( + find.text(NotesMessages.noteSavedDraftCleanupFailed), + findsOneWidget, + ); + expect(host.bloc.state.isCreatingNewNote, isFalse); + expect(find.byType(InlineNoteEditor), findsNothing); + expect((await readDraft())?.contentPlain, 'טיוטה מקורית'); + UiSnack.hide(); + await tester.pump(); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'restoring the panel during draft cleanup does not revive the draft', + ( + tester, + ) async { + final host = await open(tester); + final gate = cache.removeGate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.notes, hasLength(1)); + expect(cache.draftRemovals, 1); + host.visible.value = false; + await tester.pump(); + host.visible.value = true; + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.byType(InlineNoteEditor), findsOneWidget); + gate.complete(); + await tester.pumpAndSettle(); + + expect(host.repository.notes, hasLength(1)); + expect(host.bloc.state.isCreatingNewNote, isFalse); + expect(find.byType(InlineNoteEditor), findsNothing); + expect(await readDraft(), isNull); + expect(draftKeys(), isEmpty); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('queued creation survives completion of the preceding save', ( + tester, + ) async { + final host = await open(tester); + final pending = host.repository.pendingCreate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.creates, 1); + host.bloc.beforeCancel = () => host.bloc.add( + const StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: 8, + initialContent: 'יצירה שהמתינה בתור', + ), + ); + pending.complete(); + await tester.pumpAndSettle(); + + expect(host.repository.notes, hasLength(1)); + expect(host.bloc.state.isCreatingNewNote, isTrue); + expect(host.bloc.state.newNoteLineNumber, 8); + expect( + controller(tester).document.toPlainText().trim(), + 'יצירה שהמתינה בתור', + ); + UiSnack.hide(); + await tester.pump(); + expect(tester.takeException(), isNull); + }); + + testWidgets('save failure after removal preserves its recoverable draft', ( + tester, + ) async { + final host = await open(tester); + final pending = host.repository.pendingCreate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.creates, 1); + host.visible.value = false; + await tester.pump(); + pending.completeError(StateError('storage unavailable')); + await tester.pumpAndSettle(); + + expect(host.repository.notes, isEmpty); + expect((await readDraft())?.contentPlain, 'טיוטה מקורית'); + expect(draftKeys(), hasLength(1)); + expect(tester.takeException(), isNull); + }); + + testWidgets('save can finish after its notes bloc has closed', ( + tester, + ) async { + final host = await open(tester); + final pending = host.repository.pendingCreate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.creates, 1); + await tester.pumpWidget(const SizedBox.shrink()); + var closeCompleted = false; + unawaited( + host.bloc.close().then((_) { + closeCompleted = true; + }), + ); + // Stream cancellation crosses the real and fake async zones. Drain both + // while keeping the actual note write suspended throughout closure. + for (var i = 0; i < 100 && !closeCompleted; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 10)), + ); + await tester.pump(); + } + expect(closeCompleted, isTrue); + expect(host.bloc.isClosed, isTrue); + expect(pending.isCompleted, isFalse); + pending.complete(); + await tester.pumpAndSettle(); + + expect(host.repository.notes, hasLength(1)); + expect(await readDraft(), isNull); + expect(tester.takeException(), isNull); + }); + + group('creation session', () { + for (final pdfAnchor in [ + null, + const PdfNoteAnchor( + pageNumber: _lineNumber, + x: .2, + y: .7, + documentId: 'user|draft-navigation-pdf', + ), + ]) { + testWidgets( + 'repeated ${pdfAnchor == null ? 'text' : 'PDF'} request during save closes the saved editor', + (tester) async { + final host = await open(tester, pdfAnchor: pdfAnchor); + await replace(tester, 'תוכן שנערך לפני השמירה'); + final originalController = controller(tester); + final token = host.bloc.state.newNoteRequestToken; + final pending = host.repository.pendingCreate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.creates, 1); + expect(originalController.readOnly, isTrue); + + host.bloc.add( + StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: _lineNumber, + initialContent: 'בקשה חוזרת עם תוכן ישן', + pdfAnchor: pdfAnchor == null + ? null + : PdfNoteAnchor( + pageNumber: pdfAnchor.pageNumber, + x: pdfAnchor.x, + y: pdfAnchor.y, + documentId: pdfAnchor.documentId, + ), + ), + ); + await tester.pumpAndSettle(); + expect(host.bloc.state.newNoteRequestToken, greaterThan(token)); + expect(identical(controller(tester), originalController), isTrue); + expect( + controller(tester).document.toPlainText().trim(), + 'תוכן שנערך לפני השמירה', + ); + + pending.complete(); + await tester.pumpAndSettle(); + + expect(host.repository.notes, hasLength(1)); + expect( + host.repository.notes.single.contentPlain, + 'תוכן שנערך לפני השמירה', + ); + expect(host.repository.notes.single.pdfAnchor, pdfAnchor); + expect(host.bloc.state.isCreatingNewNote, isFalse); + expect(find.byType(InlineNoteEditor), findsNothing); + expect(await readDraft(pdfAnchor: pdfAnchor), isNull); + expect(draftKeys(), isEmpty); + UiSnack.hide(); + await tester.pump(); + expect(tester.takeException(), isNull); + }, + ); + } + + testWidgets('queued same-location request closes the saved editor', ( + tester, + ) async { + final host = await open(tester); + final pending = host.repository.pendingCreate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.creates, 1); + host.bloc.beforeCancel = () => host.bloc.add( + const StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: _lineNumber, + initialContent: 'בקשה חוזרת שהמתינה בתור', + ), + ); + + pending.complete(); + await tester.pumpAndSettle(); + + expect(host.repository.notes, hasLength(1)); + expect(host.bloc.state.isCreatingNewNote, isFalse); + expect(find.byType(InlineNoteEditor), findsNothing); + expect(await readDraft(), isNull); + expect(draftKeys(), isEmpty); + UiSnack.hide(); + await tester.pump(); + expect(tester.takeException(), isNull); + }); + + for (final processRequest in [false, true]) { + testWidgets( + 'save before rebuild ${processRequest ? 'after' : 'before'} the repeated request reaches the bloc', + (tester) async { + final host = await open(tester); + final originalController = controller(tester); + final token = host.bloc.state.newNoteRequestToken; + final save = tester + .widget( + find.widgetWithText(ActionButton, 'שמור'), + ) + .onPressed!; + final pending = host.repository.pendingCreate = Completer(); + host.bloc.add( + const StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: _lineNumber, + initialContent: 'בקשה חוזרת לפני הבנייה', + ), + ); + if (processRequest) await tester.idle(); + expect( + host.bloc.state.newNoteRequestToken, + processRequest ? greaterThan(token) : token, + ); + expect(identical(controller(tester), originalController), isTrue); + + // מפעילים את הכפתור הקיים בלי לבנות מחדש את ה-callback שלו. + save(); + await tester.pump(); + expect(host.repository.creates, 1); + pending.complete(); + await tester.pumpAndSettle(); + + expect(host.repository.notes, hasLength(1)); + expect(host.repository.notes.single.contentPlain, 'טיוטה מקורית'); + expect(host.bloc.state.isCreatingNewNote, isFalse); + expect(find.byType(InlineNoteEditor), findsNothing); + expect(await readDraft(), isNull); + UiSnack.hide(); + await tester.pump(); + expect(tester.takeException(), isNull); + }, + ); + } + + for (final typeBeforeClosing in [false, true]) { + testWidgets( + 'cancel and restart in one frame preserves ${typeBeforeClosing ? 'typing before debounce' : 'new initial content'} after the old save', + (tester) async { + final host = await open(tester); + final originalController = controller(tester); + final pending = host.repository.pendingCreate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + expect(host.repository.creates, 1); + + // בקשת יצירה משחזרת initialContent משירות הטיוטות. + await drafts.saveDraft( + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + draft: PersonalNoteDraft( + content: 'תוכן של יצירה חדשה', + contentPlain: 'תוכן של יצירה חדשה', + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime.utc(2026, 1, 2), + ), + ); + host.bloc.add(const CancelCreatingPersonalNote()); + host.bloc.add( + const StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: _lineNumber, + initialContent: 'תוכן של יצירה חדשה', + ), + ); + await tester.pump(); + final newController = controller(tester); + expect(identical(newController, originalController), isFalse); + expect(newController.readOnly, isFalse); + expect( + newController.document.toPlainText().trim(), + 'תוכן של יצירה חדשה', + ); + + final expectedDraft = typeBeforeClosing + ? 'תוכן חדש שטרם עבר השהיה' + : 'תוכן של יצירה חדשה'; + if (typeBeforeClosing) { + newController.replaceText( + 0, + newController.document.length - 1, + expectedDraft, + TextSelection.collapsed(offset: expectedDraft.length), + ); + } + pending.complete(); + await tester.pump(); + await tester.idle(); + expect(host.repository.notes, hasLength(1)); + expect(host.repository.notes.single.contentPlain, 'טיוטה מקורית'); + expect(host.bloc.state.isCreatingNewNote, isTrue); + expect(identical(controller(tester), newController), isTrue); + expect(newController.readOnly, isFalse); + expect( + tester + .widget(find.widgetWithText(ActionButton, 'שמור')) + .onPressed, + isNotNull, + ); + + host.visible.value = false; + await tester.pump(); + await tester.idle(); + + expect((await readDraft())?.contentPlain, expectedDraft); + expect(draftKeys(), hasLength(1)); + // חושפים את הטיוטה שנכתבה, בלי להישען על תוכן בקשת היצירה הקודמת. + host.bloc.add(const CancelCreatingPersonalNote()); + await tester.pump(); + host.visible.value = true; + await tester.pumpAndSettle(); + expect(controller(tester).readOnly, isFalse); + expect( + controller(tester).document.toPlainText().trim(), + expectedDraft, + ); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pumpAndSettle(); + + expect(host.repository.notes.map((note) => note.contentPlain), [ + 'טיוטה מקורית', + expectedDraft, + ]); + expect(host.bloc.state.isCreatingNewNote, isFalse); + expect(find.byType(InlineNoteEditor), findsNothing); + expect(await readDraft(), isNull); + UiSnack.hide(); + await tester.pump(); + expect(tester.takeException(), isNull); + }, + ); + } + + testWidgets('repeated request keeps a failed save editable for retry', ( + tester, + ) async { + final host = await open(tester); + await replace(tester, 'תוכן לניסיון חוזר'); + final originalController = controller(tester); + final pending = host.repository.pendingCreate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + host.bloc.add( + const StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: _lineNumber, + initialContent: 'בקשה חוזרת בזמן שמירה', + ), + ); + await tester.pump(); + pending.completeError(StateError('storage unavailable')); + await tester.pumpAndSettle(); + + expect(host.repository.notes, isEmpty); + expect(host.bloc.state.isCreatingNewNote, isTrue); + expect(identical(controller(tester), originalController), isTrue); + expect(originalController.readOnly, isFalse); + expect((await readDraft())?.contentPlain, 'תוכן לניסיון חוזר'); + expect( + tester + .widget(find.widgetWithText(ActionButton, 'שמור')) + .onPressed, + isNotNull, + ); + expect( + tester + .widget(find.widgetWithText(ActionButton, 'ביטול')) + .onPressed, + isNotNull, + ); + + host.repository.pendingCreate = null; + UiSnack.hide(); + await tester.pump(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pumpAndSettle(); + + expect(host.repository.creates, 2); + expect(host.repository.notes, hasLength(1)); + expect(host.repository.notes.single.contentPlain, 'תוכן לניסיון חוזר'); + expect(host.bloc.state.isCreatingNewNote, isFalse); + expect(find.byType(InlineNoteEditor), findsNothing); + expect(await readDraft(), isNull); + UiSnack.hide(); + await tester.pump(); + expect(tester.takeException(), isNull); + }); + }); +} diff --git a/test/personal_notes/widgets/personal_notes_sidebar_mutation_confirmation_test.dart b/test/personal_notes/widgets/personal_notes_sidebar_mutation_confirmation_test.dart new file mode 100644 index 0000000000..f455417089 --- /dev/null +++ b/test/personal_notes/widgets/personal_notes_sidebar_mutation_confirmation_test.dart @@ -0,0 +1,126 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_quill/flutter_quill.dart' + show FlutterQuillLocalizations; +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/core/messages/notes_messages.dart'; +import 'package:otzaria/core/ui_snack.dart'; +import 'package:otzaria/personal_notes/bloc/personal_notes_bloc.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/repository/personal_notes_repository.dart'; +import 'package:otzaria/personal_notes/widgets/personal_notes_sidebar.dart'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; + +import '../../test_helpers/memory_cache_provider.dart'; + +class _PendingRepository extends PersonalNotesRepository { + final note = PersonalNote( + id: 'note', + bookId: 'ספר בדיקה', + lineNumber: 1, + lastKnownLineNumber: null, + status: PersonalNoteStatus.located, + content: 'תוכן ההערה', + contentPlain: 'תוכן ההערה', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), + ); + final pendingWrite = Completer>(); + final targets = <({String bookId, String noteId, int lineNumber})>[]; + + @override + Future> loadNotes( + String bookId, { + int? categoryId, + }) async => [note]; + + @override + Future> loadStoredNotes(String bookId) async => [note]; + + @override + Future> repositionNote({ + required String bookId, + required String noteId, + required int lineNumber, + PdfNoteAnchor? pdfAnchor, + int? categoryId, + }) { + targets.add((bookId: bookId, noteId: noteId, lineNumber: lineNumber)); + return pendingWrite.future; + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + await Settings.init(cacheProvider: MemoryCacheProvider()); + }); + + testWidgets('sidebar does not announce a failed reposition as successful', ( + tester, + ) async { + final repository = _PendingRepository(); + final bloc = PersonalNotesBloc(repository: repository); + addTearDown(() async { + if (repository.targets.isNotEmpty && + !repository.pendingWrite.isCompleted) { + repository.pendingWrite.completeError(StateError('test cleanup')); + } + UiSnack.hide(); + await tester.pumpWidget(const SizedBox.shrink()); + await bloc.close(); + }); + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigatorKey, + locale: const Locale('he'), + supportedLocales: const [Locale('he'), Locale('en')], + localizationsDelegates: const [ + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + FlutterQuillLocalizations.delegate, + ], + home: Scaffold( + body: BlocProvider.value( + value: bloc, + child: PersonalNotesSidebar( + bookId: repository.note.bookId, + repository: repository, + visibleLineIndices: const [0], + onNavigateToLine: (_, {note}) {}, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('שנה שיוך לשורה נבחרת')); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(EditableText).last, '3'); + await tester.tap(find.text('שמור')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + final success = NotesMessages.noteAssignedToLine(3); + final announcedBeforeWrite = find.text(success).evaluate().isNotEmpty; + + repository.pendingWrite.completeError(StateError('שיוך נדחה')); + await tester.pumpAndSettle(); + + expect(repository.targets, [ + ( + bookId: repository.note.bookId, + noteId: repository.note.id, + lineNumber: 3, + ), + ]); + expect(announcedBeforeWrite, isFalse); + expect(find.textContaining('שיוך נדחה'), findsOneWidget); + expect(find.text(success), findsNothing); + }); +} diff --git a/test/personal_notes/widgets/personal_notes_sidebar_reveal_test.dart b/test/personal_notes/widgets/personal_notes_sidebar_reveal_test.dart index d62f8bd9b0..0d310fea51 100644 --- a/test/personal_notes/widgets/personal_notes_sidebar_reveal_test.dart +++ b/test/personal_notes/widgets/personal_notes_sidebar_reveal_test.dart @@ -293,6 +293,9 @@ void main() { ), ); await tester.pumpAndSettle(); + final originalController = tester + .widget(find.byType(quill.QuillEditor)) + .controller; controller(tester).jumpTo(index: 30); await tester.pumpAndSettle(); @@ -307,7 +310,24 @@ void main() { await tester.pumpAndSettle(); expectVisible(tester, find.byType(InlineNoteEditor)); - expect(controller(tester).scrollController!.offset, closeTo(0, 0.01)); + final input = find.descendant( + of: find.byType(InlineNoteEditor), + matching: find.byType(quill.QuillEditor), + ); + final editor = tester.widget(input); + expect(identical(editor.controller, originalController), !cancelFirst); + if (cancelFirst) { + // יצירה חדשה מבקשת פוקוס וגוללת את הקלט לתצוגה גם בכרטיס גבוה. + final viewport = tester.getRect( + find.byType(ScrollablePositionedList), + ); + final inputRect = tester.getRect(input); + expect(inputRect.top, greaterThanOrEqualTo(viewport.top - 1)); + expect(inputRect.bottom, lessThanOrEqualTo(viewport.bottom + 1)); + expect(editor.focusNode.hasFocus, isTrue); + } else { + expect(controller(tester).scrollController!.offset, closeTo(0, 0.01)); + } expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); },