From 85185167af412d0bfb299feee0eec2521ce480a6 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Thu, 5 Nov 2026 20:28:41 +0200 Subject: [PATCH 1/5] Dispose personal note editors and ignore selection-only draft changes --- .../widgets/inline_note_editor.dart | 30 +- .../widgets/personal_note_editor.dart | 58 +- .../widgets/personal_note_editor_dialog.dart | 23 +- .../personal_note_editor_lifecycle_test.dart | 590 ++++++++++++++++++ 4 files changed, 665 insertions(+), 36 deletions(-) create mode 100644 test/personal_notes/widgets/personal_note_editor_lifecycle_test.dart diff --git a/lib/personal_notes/widgets/inline_note_editor.dart b/lib/personal_notes/widgets/inline_note_editor.dart index d99652cb82..1ca15f71ce 100644 --- a/lib/personal_notes/widgets/inline_note_editor.dart +++ b/lib/personal_notes/widgets/inline_note_editor.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:flutter/foundation.dart' show ValueListenable; import 'package:flutter/material.dart'; import 'package:fluentui_system_icons/fluentui_system_icons.dart'; +import 'package:flutter_quill/flutter_quill.dart' as quill; import 'package:otzaria/personal_notes/models/personal_note.dart'; import 'package:otzaria/personal_notes/services/personal_note_draft_service.dart'; @@ -52,6 +53,7 @@ class InlineNoteEditor extends StatefulWidget { class _InlineNoteEditorState extends State { late final PersonalNoteEditorController _controller; late final PersonalNoteEditorResult _initialResult; + late final StreamSubscription _documentChanges; final FocusNode _focusNode = FocusNode(debugLabel: 'InlineNoteEditor'); final ScrollController _scrollController = ScrollController(); final PersonalNoteDraftService _draftService = PersonalNoteDraftService(); @@ -70,16 +72,20 @@ class _InlineNoteEditorState extends State { ? widget.initialFormat : (widget.note?.contentFormat ?? PersonalNoteContentFormat.plain), ); - // _initialResult מייצג את המצב ה"נקי" לפני עריכה — לא תוכן הטיוטה. - // כך _persistDraft לא ימחק את הטיוטה כשה-Quill מפעיל notifyListeners בהתחלה. + // משווים להערה השמורה, כדי שטיוטה משוחזרת תישאר שינוי שלא נשמר. final originalController = buildPersonalNoteEditorController( initialContent: widget.note?.content ?? '', initialFormat: widget.note?.contentFormat ?? PersonalNoteContentFormat.plain, ); - _initialResult = originalController.buildResult(); - originalController.quillController.dispose(); - _controller.quillController.addListener(_scheduleDraftSave); + try { + _initialResult = originalController.buildResult(); + } finally { + originalController.dispose(); + } + _documentChanges = _controller.quillController.changes.listen( + (_) => _scheduleDraftSave(), + ); widget.cancelRequest?.addListener(_handleCancelRequest); // autoFocus לא תמיד תופס בפאנל שנפתח דינמית: ה-post-frame עלול לקדום לסוף // אנימציית הפתיחה, ולכן ניסיון נוסף אחרי שהיא מסתיימת. @@ -105,9 +111,11 @@ class _InlineNoteEditorState extends State { void dispose() { _draftSaveTimer?.cancel(); _focusRetryTimer?.cancel(); - _controller.quillController.removeListener(_scheduleDraftSave); + unawaited(_documentChanges.cancel()); widget.cancelRequest?.removeListener(_handleCancelRequest); + // _persistDraft אוסף את התוכן לפני ה-await הראשון, גם לפני ה-debounce. unawaited(_persistDraft()); + _controller.dispose(); _focusNode.dispose(); _scrollController.dispose(); super.dispose(); @@ -130,6 +138,7 @@ class _InlineNoteEditorState extends State { } void _scheduleDraftSave() { + if (_isDone) return; _draftSaveTimer?.cancel(); _draftSaveTimer = Timer( const Duration(milliseconds: 250), @@ -181,9 +190,14 @@ class _InlineNoteEditorState extends State { if (_isDone) return; if (_hasUnsavedChanges()) { final decision = await showNoteDraftDecisionDialog(context); - if (decision == null || decision == NoteDraftDecision.cancel) return; + if (!mounted || + decision == null || + decision == NoteDraftDecision.cancel) { + return; + } if (decision == NoteDraftDecision.saveDraft) { await _persistDraft(); + if (!mounted) return; _isDone = true; widget.onCancel(); return; @@ -191,7 +205,7 @@ class _InlineNoteEditorState extends State { } _isDone = true; await _clearDraft(); - widget.onCancel(); + if (mounted) widget.onCancel(); } bool _hasUnsavedChanges() { diff --git a/lib/personal_notes/widgets/personal_note_editor.dart b/lib/personal_notes/widgets/personal_note_editor.dart index 9c85595fce..24c9822154 100644 --- a/lib/personal_notes/widgets/personal_note_editor.dart +++ b/lib/personal_notes/widgets/personal_note_editor.dart @@ -101,6 +101,7 @@ class PersonalNoteEditorResult { }); } +/// בעל בקר Quill והמסמך שלו; יוצר העורך משחרר אותם ב-[dispose]. class PersonalNoteEditorController { final quill.QuillController quillController; @@ -115,6 +116,8 @@ class PersonalNoteEditorController { contentFormat: PersonalNoteContentFormat.quillDelta, ); } + + void dispose() => quillController.dispose(); } class PersonalNoteEditorBody extends StatefulWidget { @@ -159,6 +162,15 @@ class _PersonalNoteEditorBodyState extends State { widget.focusNode.addListener(_handleFocusChange); } + @override + void didUpdateWidget(covariant PersonalNoteEditorBody oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.focusNode != widget.focusNode) { + oldWidget.focusNode.removeListener(_handleFocusChange); + widget.focusNode.addListener(_handleFocusChange); + } + } + @override void dispose() { _settleTimer?.cancel(); @@ -263,7 +275,7 @@ class _PersonalNoteEditorBodyState extends State { notes: widget.linkableNotes, ), ); - if (result == null) return; + if (!mounted || result == null) return; final controller = widget.controller.quillController; final selection = controller.selection; @@ -432,6 +444,38 @@ const _noteControllerConfig = quill.QuillControllerConfig( clipboardConfig: _noteClipboardConfig, ); +class _PersonalNoteQuillController extends quill.QuillController { + _PersonalNoteQuillController(quill.Document document) + : super( + document: document, + selection: const TextSelection.collapsed(offset: 0), + config: _noteControllerConfig, + ) { + // קריאת הלוח יכולה להסתיים אחרי סגירת העורך והמסמך שלו. + onReplaceText = (_, _, _) => !_disposed; + } + + bool _disposed = false; + + @override + Future clipboardPaste({VoidCallback? updateEditor}) async { + if (_disposed) return false; + // ignore: experimental_member_use + final handled = await super.clipboardPaste( + updateEditor: () { + if (!_disposed) updateEditor?.call(); + }, + ); + return !_disposed && handled; + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} + PersonalNoteEditorController buildPersonalNoteEditorController({ required String initialContent, required PersonalNoteContentFormat initialFormat, @@ -442,11 +486,7 @@ PersonalNoteEditorController buildPersonalNoteEditorController({ final decoded = jsonDecode(initialContent) as List; final document = quill.Document.fromJson(decoded); return PersonalNoteEditorController( - quillController: quill.QuillController( - document: document, - selection: const TextSelection.collapsed(offset: 0), - config: _noteControllerConfig, - ), + quillController: _PersonalNoteQuillController(document), ); } catch (_) {} } @@ -454,11 +494,7 @@ PersonalNoteEditorController buildPersonalNoteEditorController({ final document = quill.Document() ..insert(0, initialContent.trimRight().isEmpty ? '' : '$initialContent\n'); return PersonalNoteEditorController( - quillController: quill.QuillController( - document: document, - selection: const TextSelection.collapsed(offset: 0), - config: _noteControllerConfig, - ), + quillController: _PersonalNoteQuillController(document), ); } diff --git a/lib/personal_notes/widgets/personal_note_editor_dialog.dart b/lib/personal_notes/widgets/personal_note_editor_dialog.dart index 6901ed0f98..69af905b6c 100644 --- a/lib/personal_notes/widgets/personal_note_editor_dialog.dart +++ b/lib/personal_notes/widgets/personal_note_editor_dialog.dart @@ -50,7 +50,6 @@ class _PersonalNoteEditorDialogState extends State late final ScrollController _scrollController; late final PersonalNoteEditorResult _initialResult; final PersonalNoteDraftService _draftService = PersonalNoteDraftService(); - bool _hasUnsavedChanges = false; @override void initState() { @@ -61,28 +60,15 @@ class _PersonalNoteEditorDialogState extends State initialFormat: widget.initialContentFormat, ); _initialResult = _editorController.buildResult(); - _editorController.quillController.addListener(_checkForChanges); registerDialogFocusRestorer(_textFieldFocusNode); WidgetsBinding.instance.addPostFrameCallback((_) { - _textFieldFocusNode.requestFocus(); + if (mounted) _textFieldFocusNode.requestFocus(); }); } - void _checkForChanges() { - final current = _editorController.buildResult(); - final hasChanges = - current.contentPlain.trim() != _initialResult.contentPlain.trim() && - current.contentPlain.trim().isNotEmpty; - if (hasChanges != _hasUnsavedChanges) { - setState(() { - _hasUnsavedChanges = hasChanges; - }); - } - } - @override void dispose() { - _editorController.quillController.removeListener(_checkForChanges); + _editorController.dispose(); _textFieldFocusNode.dispose(); _cancelFocusNode.dispose(); _saveFocusNode.dispose(); @@ -91,11 +77,14 @@ class _PersonalNoteEditorDialogState extends State } Future _confirmClose() async { - if (!_hasUnsavedChanges) { + final current = _editorController.buildResult(); + if (current.content == _initialResult.content || + current.contentPlain.trim().isEmpty) { return true; } final result = await showNoteDraftDecisionDialog(context); + if (!mounted) return false; if (result == NoteDraftDecision.saveDraft) { await _saveDraftIfPossible(); diff --git a/test/personal_notes/widgets/personal_note_editor_lifecycle_test.dart b/test/personal_notes/widgets/personal_note_editor_lifecycle_test.dart new file mode 100644 index 0000000000..37a6993fec --- /dev/null +++ b/test/personal_notes/widgets/personal_note_editor_lifecycle_test.dart @@ -0,0 +1,590 @@ +import 'dart:async'; +import 'dart:convert'; + +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_quill/quill_delta.dart'; +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/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/personal_notes/widgets/personal_note_link_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 'package:otzaria/widgets/controls/action_buttons.dart'; + +import '../../test_helpers/memory_cache_provider.dart'; + +class _DraftCache extends MemoryCacheProvider { + int writes = 0; + int removals = 0; + Completer? writeGate; + Completer? removeGate; + + @override + Future setObject(String key, T? value) async { + final stored = super.setObject(key, value); + if (key.startsWith(PersonalNoteDraftService.keyPrefix)) { + writes++; + await writeGate?.future; + } + await stored; + } + + @override + Future remove(String key) async { + final removed = super.remove(key); + if (key.startsWith(PersonalNoteDraftService.keyPrefix)) { + removals++; + await removeGate?.future; + } + await removed; + } +} + +class _CountingDocument extends quill.Document { + _CountingDocument(super.data) : super.fromJson(); + + int deltaReads = 0; + + @override + Delta toDelta() { + deltaReads++; + return super.toDelta(); + } +} + +class _ObservableFocusNode extends FocusNode { + bool get listening => hasListeners; +} + +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), + ), + ), + ), +); + +PersonalNote _note() => PersonalNote( + id: 'note-1', + bookId: 'test-book', + lineNumber: 1, + lastKnownLineNumber: null, + status: PersonalNoteStatus.located, + content: jsonEncode([ + {'insert': 'טקסט קיים\n'}, + ]), + contentPlain: 'טקסט קיים', + contentFormat: PersonalNoteContentFormat.quillDelta, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), +); + +quill.QuillController _quill(WidgetTester tester) => + tester.widget(find.byType(quill.QuillEditor)).controller; + +Future _pumpInline( + WidgetTester tester, { + PersonalNote? note, + String initialContent = '', + ValueChanged? onSave, + VoidCallback? onCancel, +}) async { + await tester.pumpWidget( + _host( + InlineNoteEditor( + note: note, + bookId: 'test-book', + draftLineNumber: note == null ? 1 : null, + draftNoteId: note?.id, + initialContent: initialContent, + linkableNotes: const [], + onSave: onSave ?? (_) {}, + onCancel: onCancel ?? () {}, + ), + ), + ); + await tester.pumpAndSettle(); +} + +Future _openDialog( + WidgetTester tester, { + ValueChanged? onClosed, +}) async { + await tester.pumpWidget( + _host( + Builder( + builder: (context) => TextButton( + onPressed: () async { + final result = await showDialog( + context: context, + builder: (_) => PersonalNoteEditorDialog( + initialContent: _note().content, + initialContentFormat: PersonalNoteContentFormat.quillDelta, + bookId: 'test-book', + draftLineNumber: 1, + ), + ); + onClosed?.call(result); + }, + child: const Text('פתח'), + ), + ), + ), + ); + await tester.tap(find.text('פתח')); + await tester.pumpAndSettle(); +} + +Future _tapAction(WidgetTester tester, String label) async { + await tester.tap(find.widgetWithText(ActionButton, label).last); + await tester.pumpAndSettle(); +} + +void main() { + late _DraftCache cache; + final drafts = PersonalNoteDraftService(); + + setUp(() async { + cache = _DraftCache(); + await Settings.init(cacheProvider: cache); + }); + + testWidgets('תנועות סמן בדיאלוג אינן מעתיקות או מסריילות את המסמך', ( + tester, + ) async { + await _openDialog(tester); + final controller = _quill(tester); + final original = controller.document; + final document = _CountingDocument([ + for (var i = 0; i < 200; i++) + { + 'insert': 'שורה ארוכה לבדיקת בחירה ומחזור חיים $i\n', + 'attributes': {'bold': i.isEven}, + }, + ]); + controller.document = document; + await tester.pump(); + original.close(); + document.deltaReads = 0; + + for (var i = 0; i < 1000; i++) { + controller.updateSelection( + TextSelection.collapsed(offset: i % 100), + quill.ChangeSource.local, + ); + } + + expect(document.deltaReads, 0); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }); + + testWidgets('שינוי עיצוב בדיאלוג מציע טיוטה ו-undo מחזיר מצב נקי', ( + tester, + ) async { + await _openDialog(tester); + final controller = _quill(tester); + controller.formatText(0, 4, quill.Attribute.bold); + await tester.pump(); + await _tapAction(tester, 'ביטול'); + expect(find.text('שמור טיוטה'), findsOneWidget); + + await _tapAction(tester, 'ביטול'); + controller.undo(); + await tester.pump(); + await _tapAction(tester, 'ביטול'); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + expect(find.text('שמור טיוטה'), findsNothing); + }); + + testWidgets('redo של עיצוב בדיאלוג נשמר בטיוטה', (tester) async { + await _openDialog(tester); + final controller = _quill(tester); + controller.formatText(0, 4, quill.Attribute.bold); + controller.undo(); + controller.redo(); + await tester.pump(); + await _tapAction(tester, 'ביטול'); + await _tapAction(tester, 'שמור טיוטה'); + + final draft = await drafts.loadDraft(bookId: 'test-book', lineNumber: 1); + expect(draft?.content, contains('"bold":true')); + expect(draft?.contentPlain, 'טקסט קיים'); + }); + + testWidgets('בחירה בלבד בעורך הפנימי אינה כותבת או מוחקת טיוטה', ( + tester, + ) async { + await _pumpInline(tester, note: _note()); + cache.writes = cache.removals = 0; + final controller = _quill(tester); + for (var i = 0; i < 30; i++) { + controller.updateSelection( + TextSelection.collapsed(offset: i % 8), + quill.ChangeSource.local, + ); + await tester.pump(const Duration(milliseconds: 300)); + } + expect(cache.writes, 0); + expect(cache.removals, 0); + }); + + testWidgets('שינוי עיצוב ישיר, undo ו-redo מעדכנים טיוטה פנימית', ( + tester, + ) async { + await _pumpInline(tester, note: _note()); + final controller = _quill(tester); + controller.document.format(0, 4, quill.Attribute.bold); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect( + (await drafts.loadDraft(bookId: 'test-book', noteId: 'note-1'))?.content, + contains('"bold":true'), + ); + + controller.undo(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect( + await drafts.loadDraft(bookId: 'test-book', noteId: 'note-1'), + isNull, + ); + + controller.redo(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect( + (await drafts.loadDraft(bookId: 'test-book', noteId: 'note-1'))?.content, + contains('"bold":true'), + ); + }); + + testWidgets('הסרה עם אירוע שטרם נמסר שומרת צילום לפני שחרור הבקר', ( + tester, + ) async { + await _pumpInline(tester); + final controller = _quill(tester); + final gate = cache.writeGate = Completer(); + controller.document.insert(0, 'טיוטה אחרונה'); + await tester.pumpWidget(const SizedBox.shrink()); + + expect(controller.document.documentChangeObserver.isClosed, isTrue); + gate.complete(); + await tester.pump(); + expect( + (await drafts.loadDraft( + bookId: 'test-book', + lineNumber: 1, + ))?.contentPlain, + 'טיוטה אחרונה', + ); + await tester.pump(const Duration(seconds: 1)); + expect(tester.takeException(), isNull); + }); + + testWidgets('שמירה שאושרה מוסרת את התוכן גם כשהניקוי מסתיים לאחר הסרה', ( + tester, + ) async { + PersonalNoteEditorResult? saved; + await _pumpInline( + tester, + note: _note(), + onSave: (result) => saved = result, + ); + final gate = cache.removeGate = Completer(); + await tester.tap(find.widgetWithText(ActionButton, 'שמור')); + await tester.pump(); + await tester.pumpWidget(const SizedBox.shrink()); + gate.complete(); + await tester.pump(); + + expect(saved?.contentPlain, 'טקסט קיים'); + expect(tester.takeException(), isNull); + }); + + for (final save in [true, false]) { + testWidgets( + 'flush מושהה אינו מחזיר טיוטה אחרי ${save ? 'שמירה' : 'ביטול'}', + ( + tester, + ) async { + PersonalNoteEditorResult? saved; + var cancelled = false; + await _pumpInline( + tester, + note: _note(), + onSave: (result) => saved = result, + onCancel: () => cancelled = true, + ); + final gate = cache.writeGate = Completer(); + _quill(tester).replaceText( + 0, + 0, + 'שינוי ', + const TextSelection.collapsed(offset: 6), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(cache.writes, 1); + + if (save) { + await _tapAction(tester, 'שמור'); + expect(saved?.contentPlain, 'שינוי טקסט קיים'); + } else { + await _tapAction(tester, 'ביטול'); + await _tapAction(tester, 'סגור בלי לשמור'); + expect(cancelled, isTrue); + } + gate.complete(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect( + await drafts.loadDraft(bookId: 'test-book', noteId: 'note-1'), + isNull, + ); + }, + ); + } + + for (final dialog in [true, false]) { + for (final rich in [true, false]) { + testWidgets( + 'הדבקה ${rich ? 'מעוצבת' : 'רגילה'} שמסתיימת אחרי סגירת ' + '${dialog ? 'דיאלוג' : 'עורך פנימי'} מתבטלת', + (tester) async { + if (dialog) { + await _openDialog(tester); + } else { + await _pumpInline(tester, note: _note()); + } + final controller = _quill(tester); + if (rich) { + controller.formatText(0, 4, quill.Attribute.bold); + controller.updateSelection( + const TextSelection(baseOffset: 0, extentOffset: 4), + quill.ChangeSource.local, + ); + // ignore: experimental_member_use + controller.clipboardSelection(true); + await tester.pump(); + } + final before = controller.document.toDelta(); + final clipboard = Completer(); + var reads = 0; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.getData') { + reads++; + return clipboard.future; + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, null), + ); + var updated = 0; + // ignore: experimental_member_use + final paste = controller.clipboardPaste( + updateEditor: () => updated++, + ); + await tester.pump(); + expect(reads, 1); + await tester.pumpWidget(const SizedBox.shrink()); + clipboard.complete({'text': rich ? 'טקסט' : 'הדבקה חדשה'}); + await tester.pump(); + + expect(await paste, isFalse); + expect(updated, 0); + expect(controller.document.toDelta(), before); + expect(controller.document.documentChangeObserver.isClosed, isTrue); + expect(tester.takeException(), isNull); + }, + ); + } + } + + testWidgets('הדבקת מקלדת שהושלמה אחרי הסרה אינה גוללת את העורך הישן', ( + tester, + ) async { + await _pumpInline(tester, note: _note()); + final editor = tester.state( + find.byType(quill.QuillRawEditor), + ); + final clipboard = Completer(); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async => + call.method == 'Clipboard.getData' ? clipboard.future : null, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final paste = editor.pasteText(SelectionChangedCause.keyboard); + await tester.pump(); + await tester.pumpWidget(const SizedBox.shrink()); + clipboard.complete({'text': 'טקסט מהלוח'}); + await tester.pump(); + await paste; + expect(tester.takeException(), isNull); + }); + + testWidgets('גוף העורך מחליף listener של focus ומשאיר בעלות אצל היוצר', ( + tester, + ) async { + final first = _ObservableFocusNode(); + final second = _ObservableFocusNode(); + final focus = ValueNotifier(first); + final scroll = ScrollController(); + final controller = buildPersonalNoteEditorController( + initialContent: _note().content, + initialFormat: PersonalNoteContentFormat.quillDelta, + ); + addTearDown(first.dispose); + addTearDown(second.dispose); + addTearDown(focus.dispose); + addTearDown(scroll.dispose); + addTearDown(controller.quillController.dispose); + await tester.pumpWidget( + _host( + ValueListenableBuilder( + valueListenable: focus, + builder: (_, node, _) => PersonalNoteEditorBody( + controller: controller, + focusNode: node, + scrollController: scroll, + autofocus: false, + linkableNotes: const [], + ), + ), + ), + ); + focus.value = second; + await tester.pump(); + expect(first.listening, isFalse); + expect(second.listening, isTrue); + await tester.pumpWidget(const SizedBox.shrink()); + expect(second.listening, isFalse); + expect( + controller.quillController.document.documentChangeObserver.isClosed, + isFalse, + ); + }); + + testWidgets('תוצאת חלונית קישור אחרי הסרת העורך אינה משנה מסמך ששוחרר', ( + tester, + ) async { + final visible = ValueNotifier(true); + addTearDown(visible.dispose); + await tester.pumpWidget( + _host( + ValueListenableBuilder( + valueListenable: visible, + builder: (_, show, _) => show + ? InlineNoteEditor( + note: _note(), + bookId: 'test-book', + draftNoteId: 'note-1', + linkableNotes: const [], + onSave: (_) {}, + onCancel: () {}, + ) + : const SizedBox.shrink(), + ), + ), + ); + await tester.pumpAndSettle(); + final controller = _quill(tester); + final before = controller.document.toDelta(); + await tester.tap(find.byTooltip('הוסף קישור')); + await tester.pumpAndSettle(); + visible.value = false; + await tester.pumpAndSettle(); + Navigator.of( + tester.element(find.byType(PersonalNoteLinkDialog)), + ).pop( + const PersonalNoteLinkTarget(label: 'קישור', url: 'https://example.org'), + ); + await tester.pumpAndSettle(); + + expect(controller.document.toDelta(), before); + expect(tester.takeException(), isNull); + }); + + testWidgets('30 מחזורי דיאלוג משחררים את המסמך בשמירה ובביטול', ( + tester, + ) async { + var closedDocuments = 0; + final subscriptions = >[]; + addTearDown(() async { + for (final subscription in subscriptions) { + await subscription.cancel(); + } + }); + for (var cycle = 0; cycle < 30; cycle++) { + await _openDialog(tester); + final controller = _quill(tester); + subscriptions.add( + controller.changes.listen(null, onDone: () => closedDocuments++), + ); + if (cycle.isEven) { + await _tapAction(tester, 'שמור'); + } else { + await _tapAction(tester, 'ביטול'); + } + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + } + expect(closedDocuments, 30); + expect(tester.takeException(), isNull); + }); + + testWidgets('30 מחזורי עורך פנימי משחררים מסמך ושומרים טיוטה לפני debounce', ( + tester, + ) async { + var closedDocuments = 0; + final subscriptions = >[]; + addTearDown(() async { + for (final subscription in subscriptions) { + await subscription.cancel(); + } + }); + for (var cycle = 0; cycle < 30; cycle++) { + await _pumpInline(tester); + final controller = _quill(tester); + subscriptions.add( + controller.changes.listen(null, onDone: () => closedDocuments++), + ); + controller.document.insert(0, 'טיוטה $cycle'); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + expect( + (await drafts.loadDraft( + bookId: 'test-book', + lineNumber: 1, + ))?.contentPlain, + 'טיוטה $cycle', + ); + } + await tester.pump(const Duration(seconds: 1)); + expect(closedDocuments, 30); + expect(tester.takeException(), isNull); + }); +} From 57863c6044918deefd2f6007dc3f9affc5d5ac4a Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Thu, 5 Nov 2026 20:35:28 +0200 Subject: [PATCH 2/5] Verify editor focus ownership across repeated lifecycles --- .../personal_note_editor_lifecycle_test.dart | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/test/personal_notes/widgets/personal_note_editor_lifecycle_test.dart b/test/personal_notes/widgets/personal_note_editor_lifecycle_test.dart index 37a6993fec..8d37d4c4b3 100644 --- a/test/personal_notes/widgets/personal_note_editor_lifecycle_test.dart +++ b/test/personal_notes/widgets/personal_note_editor_lifecycle_test.dart @@ -60,7 +60,19 @@ class _CountingDocument extends quill.Document { } class _ObservableFocusNode extends FocusNode { - bool get listening => hasListeners; + final callbacks = []; + + @override + void addListener(VoidCallback listener) { + callbacks.add(listener); + super.addListener(listener); + } + + @override + void removeListener(VoidCallback listener) { + callbacks.remove(listener); + super.removeListener(listener); + } } Widget _host(Widget child) => RepositoryProvider( @@ -477,12 +489,15 @@ void main() { ), ), ); + // Body registers before its children. Quill also registers a separate + // anonymous listener whose lifetime ends when the owner disposes the node. + final bodyFocusListener = first.callbacks.first; focus.value = second; await tester.pump(); - expect(first.listening, isFalse); - expect(second.listening, isTrue); + expect(first.callbacks, isNot(contains(bodyFocusListener))); + expect(second.callbacks, contains(bodyFocusListener)); await tester.pumpWidget(const SizedBox.shrink()); - expect(second.listening, isFalse); + expect(second.callbacks, isNot(contains(bodyFocusListener))); expect( controller.quillController.document.documentChangeObserver.isClosed, isFalse, @@ -542,6 +557,9 @@ void main() { for (var cycle = 0; cycle < 30; cycle++) { await _openDialog(tester); final controller = _quill(tester); + final focusNode = tester + .widget(find.byType(quill.QuillEditor)) + .focusNode; subscriptions.add( controller.changes.listen(null, onDone: () => closedDocuments++), ); @@ -551,6 +569,7 @@ void main() { await _tapAction(tester, 'ביטול'); } expect(find.byType(PersonalNoteEditorDialog), findsNothing); + expect(() => focusNode.addListener(() {}), throwsFlutterError); } expect(closedDocuments, 30); expect(tester.takeException(), isNull); @@ -569,12 +588,16 @@ void main() { for (var cycle = 0; cycle < 30; cycle++) { await _pumpInline(tester); final controller = _quill(tester); + final focusNode = tester + .widget(find.byType(quill.QuillEditor)) + .focusNode; subscriptions.add( controller.changes.listen(null, onDone: () => closedDocuments++), ); controller.document.insert(0, 'טיוטה $cycle'); await tester.pumpWidget(const SizedBox.shrink()); await tester.pump(); + expect(() => focusNode.addListener(() {}), throwsFlutterError); expect( (await drafts.loadDraft( bookId: 'test-book', From 3bd85bf7741e16c04553b5904cf4051826d80b06 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Thu, 5 Nov 2026 21:50:43 +0200 Subject: [PATCH 3/5] =?UTF-8?q?=D7=94=D7=A2=D7=A8=D7=95=D7=AA=20=D7=90?= =?UTF-8?q?=D7=99=D7=A9=D7=99=D7=95=D7=AA:=20=D7=99=D7=A6=D7=99=D7=A8?= =?UTF-8?q?=D7=94=20=D7=95=D7=A9=D7=9E=D7=99=D7=A8=D7=94=20=D7=91=D7=98?= =?UTF-8?q?=D7=95=D7=97=D7=95=D7=AA,=20=D7=A2=D7=95=D7=92=D7=A0=D7=99=20PD?= =?UTF-8?q?F,=20=D7=9E=D7=99=D7=95=D7=9F=20=D7=95=D7=A7=D7=99=D7=A9=D7=95?= =?UTF-8?q?=D7=A8=D7=99=20Word?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ממשיך את מנגנון מחזור החיים של #4303 ומשלב אותו עם שמירה אסינכרונית, טיוטות ופתיחה לפי מצב חלונית ההערות. Refs #1501, #3721, #4105, #4142, #4251, #4252, #4292, #3957, #3516, #2519, #3260, #2531 --- lib/core/messages/notes_messages.dart | 17 + .../utils/pdf_personal_note_anchor.dart | 84 ++ lib/pdf_book/view/pdf_book_screen.dart | 458 ++++++++++- lib/pdf_book/view/pdf_commentary_panel.dart | 22 + .../bloc/personal_notes_bloc.dart | 18 +- .../bloc/personal_notes_event.dart | 26 +- .../bloc/personal_notes_state.dart | 28 + .../models/pdf_note_anchor.dart | 57 ++ lib/personal_notes/models/personal_note.dart | 17 + .../models/personal_notes_sort_order.dart | 48 ++ lib/personal_notes/personal_notes_system.dart | 1 + .../repository/personal_notes_repository.dart | 55 ++ .../services/personal_note_draft_service.dart | 87 +- .../personal_notes_import_export_service.dart | 40 +- .../services/personal_notes_service.dart | 118 ++- .../storage/personal_notes_database.dart | 35 +- .../utils/create_personal_note.dart | 131 +++ .../utils/note_collection_utils.dart | 7 +- .../utils/note_location_ref.dart | 8 +- .../utils/open_personal_notes_target.dart | 4 +- .../utils/personal_note_source_link.dart | 64 ++ .../utils/personal_notes_book_key.dart | 45 + .../utils/personal_notes_filter.dart | 27 +- .../view/personal_notes_screen.dart | 527 ++++++++---- .../widgets/inline_note_editor.dart | 170 +++- .../widgets/note_delta_preview.dart | 3 +- lib/personal_notes/widgets/note_tile.dart | 24 +- .../widgets/notes_search_header.dart | 22 +- .../widgets/personal_note_content_view.dart | 55 +- .../widgets/personal_note_editor.dart | 27 +- .../widgets/personal_note_editor_dialog.dart | 131 ++- .../widgets/personal_note_styles.dart | 23 + .../widgets/personal_notes_export_dialog.dart | 16 +- .../widgets/personal_notes_sidebar.dart | 271 ++++-- lib/printing/print_content_models.dart | 4 + lib/printing/word_export_service.dart | 71 +- lib/settings/services/backup_service.dart | 49 +- lib/tabs/bloc/tabs_bloc.dart | 5 + lib/tabs/models/pdf_tab.dart | 21 + lib/text_book/utils/note_inline_render.dart | 82 +- .../combined_view/combined_book_screen.dart | 57 +- .../view/page_shape/page_shape_screen.dart | 22 +- .../view/page_shape/simple_text_viewer.dart | 173 ++-- .../splited_view/splited_view_screen.dart | 39 +- .../strategies/combined_view_strategy.dart | 1 + .../view/strategies/split_view_strategy.dart | 1 + .../strategies/text_book_view_strategy.dart | 2 + lib/text_book/view/text_book_scaffold.dart | 3 + lib/text_book/view/text_book_screen.dart | 48 +- lib/utils/ui/context_menu_utils.dart | 64 +- test/pdf_book/pdf_book_tab_test.dart | 29 + .../pdf_personal_note_anchor_test.dart | 194 +++++ .../pdf_personal_note_viewer_test.dart | 338 ++++++++ .../personal_notes_visible_filter_test.dart | 61 ++ .../imported_delta_preview_test.dart | 27 +- .../note_delta_preview_test.dart | 21 + .../open_personal_notes_target_test.dart | 25 + ...l_note_content_view_context_menu_test.dart | 77 ++ .../personal_note_draft_service_test.dart | 301 +++++++ .../personal_notes_book_key_test.dart | 106 +++ .../personal_notes_manager_loading_test.dart | 774 ++++++++++++++++++ ...notes_paragraph_marker_selection_test.dart | 130 +++ .../personal_notes_pdf_point_test.dart | 371 +++++++++ .../personal_notes_screen_test.dart | 136 +-- .../personal_notes_sort_order_test.dart | 371 +++++++++ ...ersonal_notes_word_export_screen_test.dart | 327 ++++++++ .../personal_notes_word_export_test.dart | 113 ++- ...ersonal_notes_write_confirmation_test.dart | 323 ++++++++ .../storage/personal_notes_changes_test.dart | 7 +- .../storage/personal_notes_database_test.dart | 81 ++ .../widgets/create_personal_note_test.dart | 591 +++++++++++++ .../widgets/inline_note_editor_test.dart | 40 + .../widgets/note_tile_persistence_test.dart | 210 +++++ .../personal_notes_export_dialog_test.dart | 106 +++ .../personal_notes_sidebar_reveal_test.dart | 490 +++++++++++ test/printing/pdf_sheet_composer_test.dart | 11 + .../printing_screen_export_profile_test.dart | 13 +- .../printing/printing_screen_output_test.dart | 10 + .../word_export_source_links_test.dart | 585 +++++++++++++ .../services/backup_service_test.dart | 151 ++++ test/tabs/bloc/tabs_bloc_test.dart | 29 + .../utils/note_inline_render_test.dart | 101 ++- .../combined_book_screen_test.dart | 115 ++- .../combined_view_note_entry_test.dart | 1 + .../page_shape_screen_settings_test.dart | 56 +- .../page_shape/simple_text_viewer_test.dart | 211 +++-- .../continuous_line_interaction_test.dart | 32 +- ...ed_view_toggle_commentators_pane_test.dart | 48 +- windows/runner/flutter_window.cpp | 9 + 89 files changed, 8987 insertions(+), 942 deletions(-) create mode 100644 lib/pdf_book/utils/pdf_personal_note_anchor.dart create mode 100644 lib/personal_notes/models/pdf_note_anchor.dart create mode 100644 lib/personal_notes/models/personal_notes_sort_order.dart create mode 100644 lib/personal_notes/utils/create_personal_note.dart create mode 100644 lib/personal_notes/utils/personal_note_source_link.dart create mode 100644 lib/personal_notes/widgets/personal_note_styles.dart create mode 100644 test/pdf_book/pdf_personal_note_anchor_test.dart create mode 100644 test/pdf_book/pdf_personal_note_viewer_test.dart create mode 100644 test/personal_notes/personal_notes_manager_loading_test.dart create mode 100644 test/personal_notes/personal_notes_paragraph_marker_selection_test.dart create mode 100644 test/personal_notes/personal_notes_pdf_point_test.dart create mode 100644 test/personal_notes/personal_notes_sort_order_test.dart create mode 100644 test/personal_notes/personal_notes_word_export_screen_test.dart create mode 100644 test/personal_notes/personal_notes_write_confirmation_test.dart create mode 100644 test/personal_notes/widgets/create_personal_note_test.dart create mode 100644 test/personal_notes/widgets/note_tile_persistence_test.dart create mode 100644 test/personal_notes/widgets/personal_notes_export_dialog_test.dart create mode 100644 test/personal_notes/widgets/personal_notes_sidebar_reveal_test.dart create mode 100644 test/printing/word_export_source_links_test.dart diff --git a/lib/core/messages/notes_messages.dart b/lib/core/messages/notes_messages.dart index cabf57475b..86e072a760 100644 --- a/lib/core/messages/notes_messages.dart +++ b/lib/core/messages/notes_messages.dart @@ -4,9 +4,24 @@ abstract class NotesMessages { // ===== הערות אישיות ===== static const String emptyNoteNotSaved = 'ההערה ריקה, לא נשמרה'; static const String noteSaved = 'ההערה נשמרה בהצלחה'; + static const String noteSavedDraftCleanupFailed = + 'ההערה נשמרה, אך לא ניתן למחוק את הטיוטה הישנה'; + static String noteDraftUpdateError(Object error) => + 'שגיאה בעדכון טיוטת ההערה: $error'; static const String noteUpdated = 'ההערה עודכנה'; + static const String noteNoLongerExists = 'ההערה אינה קיימת עוד'; + static const String noteMovedToDifferentBook = + 'ההערה הועברה לספר אחר. יש לפתוח אותה מחדש לפני שמירה'; static const String noteDeleted = 'ההערה נמחקה'; static const String noteHasNoLocation = 'להערה הזו אין מיקום'; + static const String choosePdfNotePoint = 'לחץ על הנקודה הרצויה בעמוד להערה'; + static const String pdfNotePointUnavailable = + 'בחר נקודה בתוך עמוד שנטען במלואו'; + static const String pdfNoteLocationUnavailable = + 'לא ניתן להגיע למיקום ההערה במסמך הזה'; + static const String noteRepositioned = 'מיקום ההערה עודכן'; + static String noteRepositionFailed(Object error) => + 'שינוי מיקום ההערה נכשל: $error'; static const String libraryNotLoadedYet = 'הספרייה לא נטענה עדיין'; static const String backupCompleted = 'הגיבוי הושלם בהצלחה'; static const String textExportCompleted = 'הייצוא לטקסט הושלם בהצלחה'; @@ -14,6 +29,8 @@ abstract class NotesMessages { static String notesListLoadError(Object error) => 'שגיאה בטעינת רשימת ההערות: $error'; + static const String notesLoadIncomplete = + 'חלק מההערות לא נטענו. יש לנסות שוב לפני ייצוא.'; static String importFailed(Object error) => 'ייבוא ההערות נכשל: $error'; diff --git a/lib/pdf_book/utils/pdf_personal_note_anchor.dart b/lib/pdf_book/utils/pdf_personal_note_anchor.dart new file mode 100644 index 0000000000..5615d94923 --- /dev/null +++ b/lib/pdf_book/utils/pdf_personal_note_anchor.dart @@ -0,0 +1,84 @@ +import 'package:flutter/widgets.dart'; +import 'package:otzaria/personal_notes/models/pdf_note_anchor.dart'; +import 'package:pdfrx/pdfrx.dart'; + +/// עמודים שנראים בפועל, כולל קצה העמוד הבא בגלילה רציפה. +List visiblePdfNotePageNumbers({ + required List pageLayouts, + required Rect visibleRect, +}) => [ + for (var index = 0; index < pageLayouts.length; index++) + if (pageLayouts[index].overlaps(visibleRect)) index + 1, +]; + +/// ממיר תוצאת hit-test של pdfrx לנקודה שאינה תלויה בזום, בפריסה או בסיבוב. +/// ממדי העמוד ב-pdfrx מסובבים, ואילו נקודת ה-hit-test היא בקואורדינטות המקור. +PdfNoteAnchor? pdfNoteAnchorFromHit( + PdfPageHitTestResult? hit, { + String? documentId, +}) { + if (hit == null || !hit.page.isLoaded) return null; + final page = hit.page; + final swapped = page.rotation.index.isOdd; + final width = swapped ? page.height : page.width; + final height = swapped ? page.width : page.height; + if (!width.isFinite || !height.isFinite || width <= 0 || height <= 0) { + return null; + } + final x = hit.offset.x / width; + final y = hit.offset.y / height; + if (!x.isFinite || !y.isFinite) return null; + return PdfNoteAnchor( + pageNumber: page.pageNumber, + x: x.clamp(0.0, 1.0), + y: y.clamp(0.0, 1.0), + documentId: documentId, + ); +} + +/// ממיר נקודה שמורה לקואורדינטות הפריסה, כולל הסיבוב הנוכחי של העמוד. +Offset pdfNoteAnchorDocumentPosition( + PdfNoteAnchor anchor, { + required PdfPage page, + required Rect pageRect, +}) { + final swapped = page.rotation.index.isOdd; + final width = swapped ? page.height : page.width; + final height = swapped ? page.width : page.height; + return PdfPoint(anchor.x * width, anchor.y * height).toOffsetInDocument( + page: page, + pageRect: pageRect, + ); +} + +/// מרכז נקודה שמורה, בלי לשנות את הזום. ההורה מכין את נעילת הכפולה לפני הקריאה. +/// מחזיר false כשאי אפשר לנווט (מסמך נסגר, עמוד חסר או בקשה שהתיישנה). +Future navigateToPdfNoteAnchor( + PdfViewerController controller, + PdfNoteAnchor anchor, { + bool Function()? isActive, +}) async { + bool active() => controller.isReady && (isActive?.call() ?? true); + if (!active() || anchor.pageNumber > controller.pageCount) return false; + final document = controller.document; + var page = controller.pages[anchor.pageNumber - 1]; + if (!page.isLoaded) { + final loaded = await page.waitForLoaded( + timeout: const Duration(seconds: 10), + ); + if (loaded == null) return false; + page = loaded; + } + if (!active() || !identical(controller.document, document)) return false; + final pageLayouts = controller.layout.pageLayouts; + if (anchor.pageNumber > pageLayouts.length) return false; + final position = pdfNoteAnchorDocumentPosition( + anchor, + page: page, + pageRect: pageLayouts[anchor.pageNumber - 1], + ); + await controller.goTo(controller.calcMatrixFor(position)); + if (!active() || !identical(controller.document, document)) return false; + controller.setCurrentPageNumber(anchor.pageNumber); + return true; +} diff --git a/lib/pdf_book/view/pdf_book_screen.dart b/lib/pdf_book/view/pdf_book_screen.dart index 6334139e10..e72458823e 100644 --- a/lib/pdf_book/view/pdf_book_screen.dart +++ b/lib/pdf_book/view/pdf_book_screen.dart @@ -36,6 +36,7 @@ import 'package:otzaria/pdf_book/utils/pdf_color_filter.dart'; import 'package:otzaria/pdf_book/utils/pdf_font_fallback.dart'; import 'package:otzaria/pdf_book/utils/pdf_links_window.dart'; import 'package:otzaria/pdf_book/utils/pdf_plugin_menu_entries.dart'; +import 'package:otzaria/pdf_book/utils/pdf_personal_note_anchor.dart'; import 'package:otzaria/plugins/utils/plugin_context_menu_entries.dart'; import 'package:otzaria/pdf_book/utils/pdf_scroll_physics_provider.dart'; import 'package:otzaria/pdf_book/utils/pdf_text_selection_actions.dart'; @@ -70,9 +71,11 @@ import 'package:otzaria/plugins/services/plugin_in_book_search_service.dart'; import 'package:otzaria/tabs/models/external_book_matches.dart'; import 'package:otzaria/personal_notes/utils/personal_notes_book_key.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/services/personal_note_draft_service.dart'; +import 'package:otzaria/personal_notes/repository/personal_notes_repository.dart'; +import 'package:otzaria/personal_notes/storage/personal_notes_changes.dart'; +import 'package:otzaria/personal_notes/utils/create_personal_note.dart'; +import 'package:otzaria/personal_notes/utils/open_personal_notes_target.dart'; import 'package:otzaria/settings/settings_exports.dart'; import 'package:otzaria/text_display/models/text_display_slot.dart'; import 'package:otzaria/tabs/bloc/tabs_bloc.dart'; @@ -661,6 +664,19 @@ class _PdfBookScreenState extends State final GlobalKey _pdfViewportBoundaryKey = GlobalKey(); final _searchViewKey = GlobalKey(); final GlobalKey _pdfContextMenuKey = GlobalKey(); + final PersonalNotesRepository _personalNotesRepository = + PersonalNotesRepository(); + StreamSubscription? _personalNotesSubscription; + List _pdfPointNotes = const []; + int _pdfNotesLoadGeneration = 0; + int _pdfNoteNavigationGeneration = 0; + int _pdfDocumentSession = 0; + bool _personalNoteViewerReady = false; + bool _isChoosingPersonalNotePoint = false; + PersonalNote? _noteToReanchor; + PdfNoteAnchor? _focusedPersonalNoteAnchor; + List _lastVisiblePdfNotePages = const []; + bool _visiblePdfNotesRefreshScheduled = false; late final StreamSubscription _settingsSub; StreamSubscription? _libraryReloadSub; late final AnimationController _pageTurnController; @@ -1151,6 +1167,14 @@ class _PdfBookScreenState extends State // קיצור Ctrl+Shift+P: מעבר למהדורת הטקסט — אותה פעולה כמו כפתור הטקסט. _toggleTextViewListener = () => _handleTextButtonPress(context); widget.tab.toggleTextViewNotifier.addListener(_toggleTextViewListener); + widget.tab.personalNoteNavigationRequests.addListener( + _onPersonalNoteNavigationRequested, + ); + _personalNotesSubscription = PersonalNotesChanges.stream.listen((bookId) { + if (bookId == personalNotesBookKey(widget.tab.book)) { + unawaited(_loadPdfPointNotes()); + } + }); } /// מסמן ב-host את הלשונית הנבחרת. לשונית שנבחרה אוטומטית (ספר שנפתח מחיפוש) @@ -1472,6 +1496,8 @@ class _PdfBookScreenState extends State final selection = selectedText == null ? null : ReaderMenuSelection(selectedText); + // שומרים את נקודת הלחיצה לפני שהתפריט או עורך ההערה משנים את התצוגה. + final noteAnchor = _pdfNoteAnchorAtGlobalPosition(tapPosition); return buildPdfContextMenuEntries( commentatorChildren: commentatorChildren, @@ -1490,7 +1516,11 @@ class _PdfBookScreenState extends State onSearchAllBooks: () => _searchAllBooksFromSelection(selection), onCopySelection: () => unawaited(_copyPdfTextSelection()), onAddBookmark: () => _handleBookmarkPress(menuContext), - onAddNote: () => _handleAddNotePress(menuContext), + onAddNote: () => _handleAddNotePress( + menuContext, + anchor: noteAnchor, + selectedText: selectedText, + ), )..addAll( _pdfPluginEntries( menuContext, @@ -1700,7 +1730,9 @@ class _PdfBookScreenState extends State scrollByArrowKey: 25.0, // ברירת המחדל של pdfrx היא 0.2; 1.0 זז כמו גלגלת בספר טקסט. scrollByMouseWheel: 1.0, - textSelectionParams: PdfTextSelectionParams(enabled: !_isHandMode), + textSelectionParams: PdfTextSelectionParams( + enabled: !_isHandMode && !_isChoosingPersonalNotePoint, + ), // נעילת הציר מתבצעת ב-TrackpadPanRecognizer; PanAxis נועל גם אלכסונים. panAxis: PanAxis.free, interactionDelegateProvider: _scrollPhysicsProvider, @@ -1735,6 +1767,23 @@ class _PdfBookScreenState extends State } }, onGeneralTap: (tapContext, _, details) { + if (_isChoosingPersonalNotePoint && + details.type == PdfViewerGeneralTapType.tap) { + final hit = widget.tab.pdfViewerController.getPdfPageHitTestResult( + details.documentPosition, + useDocumentLayoutCoordinates: true, + ); + final anchor = pdfNoteAnchorFromHit( + hit, + documentId: pdfPersonalNoteDocumentId(widget.tab.book), + ); + if (anchor == null) { + UiSnack.show(NotesMessages.pdfNotePointUnavailable); + } else { + unawaited(_completePersonalNotePointSelection(anchor)); + } + return true; + } if (details.type == PdfViewerGeneralTapType.secondaryTap) { return true; } @@ -1779,7 +1828,9 @@ class _PdfBookScreenState extends State _viewerInputOverlay, _buildBookViewViewportMask(size), _buildBookViewStackDecoration(context, size), + if (_isChoosingPersonalNotePoint) _buildPersonalNotePointPrompt(), ], + pageOverlaysBuilder: _buildPersonalNoteMarkers, loadingBannerBuilder: (context, bytesDownloaded, totalBytes) => Center( child: CircularProgressIndicator( value: totalBytes != null ? bytesDownloaded / totalBytes : null, @@ -1798,6 +1849,19 @@ class _PdfBookScreenState extends State ? [textSearcher!.pageTextMatchPaintCallback] : null, onDocumentChanged: (document) async { + _personalNoteViewerReady = false; + _pdfDocumentSession++; + _pdfNoteNavigationGeneration++; + _focusedPersonalNoteAnchor = null; + final wasChoosingPoint = _isChoosingPersonalNotePoint; + _isChoosingPersonalNotePoint = false; + _noteToReanchor = null; + _isJumping = false; + if (wasChoosingPoint) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) setState(() {}); + }); + } _pdfTextSelectionActions.cancel(); if (document == null) { widget.tab.documentRef.value = null; @@ -1807,7 +1871,18 @@ class _PdfBookScreenState extends State } }, onViewerReady: (document, controller) async { - if (!mounted) return; + if (!mounted || + !controller.isReady || + !identical(controller.document, document)) { + return; + } + final session = ++_pdfDocumentSession; + bool currentSession() => + mounted && + session == _pdfDocumentSession && + controller.isReady && + identical(controller.document, document); + _personalNoteViewerReady = false; // Only grab focus if neither of the pane text-fields is focused. // Unconditional requestFocus() here stole focus from open search/nav fields. if (!_searchFieldFocusNode.hasFocus && @@ -1831,6 +1906,7 @@ class _PdfBookScreenState extends State final documentRef = controller.documentRef; widget.tab.documentRef.value = documentRef; + unawaited(_loadPdfPointNotes()); final totalPages = document.pages.length; final initialTargetPage = widget.tab.pageNumber.clamp(1, totalPages); widget.tab.pageNumber = initialTargetPage; @@ -1856,7 +1932,7 @@ class _PdfBookScreenState extends State ), ); - if (!mounted) return; + if (!currentSession()) return; // נבדק לפני כל await: אחריו גלילת המשתמש נראית כנחיתה שגויה ומוחזרת. final currentReadyPage = resolveReadyPdfPageNumber( isReady: controller.isReady, @@ -1868,25 +1944,29 @@ class _PdfBookScreenState extends State _isJumping = true; try { await WidgetsBinding.instance.endOfFrame; - if (mounted && controller.isReady) { + if (currentSession()) { await controller.goToPage( pageNumber: initialTargetPage, duration: Duration.zero, ); + if (!currentSession()) return; await Future.delayed(const Duration(milliseconds: 200)); } } finally { - _isJumping = false; - _initialPageNumber = null; + if (currentSession()) { + _isJumping = false; + _initialPageNumber = null; + } } } else { _initialPageNumber = null; } - if (!mounted) return; + if (!currentSession()) return; // בחירת המפרשים נטענת תמיד (לא תלוי ב-enablePerBookSettings); את הזום // מחיל LoadPerBookSettings בבלוק. final settings = await _loadPerBookSettings(); + if (!currentSession()) return; if (settings?.activeCommentators != null) { widget.tab.activeCommentators.clear(); widget.tab.activeCommentators.addAll(settings!.activeCommentators!); @@ -1898,18 +1978,20 @@ class _PdfBookScreenState extends State screenWidth: mounted ? readingLayoutWidthOf(context) : null, ); if (!shouldShowLeftPane) _runInitialSearchIfNeeded(); - if (mounted) { + if (currentSession()) { if (shouldShowLeftPane) { // נעוצה: חלונית לא נעוצה הייתה מכסה את הספר בהצללה כבר בפתיחה. widget.tab.pinLeftPane.value = true; _setLeftPaneVisibility(true); } else { WidgetsBinding.instance.addPostFrameCallback((_) { - if (mounted) { + if (currentSession()) { _pdfViewFocusNode.requestFocus(); } }); } + _personalNoteViewerReady = true; + _onPersonalNoteNavigationRequested(); } }, ); @@ -2025,6 +2107,12 @@ class _PdfBookScreenState extends State if (!hasFocus) _pdfTextSelectionActions.cancel(); }, onKeyEvent: (FocusNode node, KeyEvent event) { + if (event is KeyDownEvent && + event.logicalKey == LogicalKeyboardKey.escape && + _isChoosingPersonalNotePoint) { + _cancelPersonalNotePointSelection(); + return KeyEventResult.handled; + } if (event is KeyDownEvent) _pdfTextSelectionActions.cancel(); if ((event is KeyDownEvent || event is KeyRepeatEvent) && ShortcutHelper.matchesShortcut( @@ -4129,6 +4217,13 @@ class _PdfBookScreenState extends State @override void dispose() { + _pdfNotesLoadGeneration++; + _pdfNoteNavigationGeneration++; + _pdfDocumentSession++; + _personalNotesSubscription?.cancel(); + widget.tab.personalNoteNavigationRequests.removeListener( + _onPersonalNoteNavigationRequested, + ); _pdfTextSelectionActions.cancel(); WidgetsBinding.instance.removeObserver(this); _pageTurnController.stop(canceled: false); @@ -4251,6 +4346,7 @@ class _PdfBookScreenState extends State void _onPdfViewerControllerUpdate() async { if (!widget.tab.pdfViewerController.isReady) return; + _refreshVisiblePersonalNotePages(); // Keep adjacent-spread pre-renders warm so page-turn animations can // open the cached snapshot instantly without waiting on goToPage + tile @@ -4588,7 +4684,10 @@ class _PdfBookScreenState extends State return ValueListenableBuilder( valueListenable: widget.tab.pinLeftPane, builder: (context, isPinned, _) => NavSidePanel( - isOpen: showLeftPane, + isOpen: + showLeftPane && + (!_isChoosingPersonalNotePoint || + _leftPaneUsesPushLayout), isPinned: isPinned, alignment: AlignmentDirectional.centerEnd, paneWidth: leftPaneWidth, @@ -4599,7 +4698,14 @@ class _PdfBookScreenState extends State maxPaneWidth: 600, autoHandleResponsiveVisibility: false, onLayoutModeChanged: (usesPushLayout) { - _leftPaneUsesPushLayout = usesPushLayout; + if (_isChoosingPersonalNotePoint && + _leftPaneUsesPushLayout != usesPushLayout) { + setState( + () => _leftPaneUsesPushLayout = usesPushLayout, + ); + } else { + _leftPaneUsesPushLayout = usesPushLayout; + } }, onPaneWidthChanged: (nextWidth) { _draggedLeftPaneWidth = nextWidth; @@ -4619,7 +4725,10 @@ class _PdfBookScreenState extends State }, paneContent: _buildLeftPaneContent(showLeftPane), mainContent: AdaptiveSidePane( - isOpen: showRightPane, + isOpen: + showRightPane && + (!_isChoosingPersonalNotePoint || + _rightPaneUsesPushLayout), alignment: AlignmentDirectional.centerStart, paneWidth: rightPaneWidth, minMainContentWidth: 200, @@ -4629,7 +4738,14 @@ class _PdfBookScreenState extends State maxPaneWidth: 600, autoHandleResponsiveVisibility: false, onLayoutModeChanged: (usesPushLayout) { - _rightPaneUsesPushLayout = usesPushLayout; + if (_isChoosingPersonalNotePoint && + _rightPaneUsesPushLayout != usesPushLayout) { + setState( + () => _rightPaneUsesPushLayout = usesPushLayout, + ); + } else { + _rightPaneUsesPushLayout = usesPushLayout; + } }, onPaneWidthChanged: (nextWidth) { _draggedRightPaneWidth = nextWidth; @@ -5051,6 +5167,8 @@ class _PdfBookScreenState extends State // המפרשים אינם תנ"ך, ולכן החרגות התנ"ך אינן חלות עליהם. final policy = settingsState.textDisplayPolicy; return PdfCommentaryPanel( + onReanchorNote: _beginPersonalNoteReanchor, + visiblePdfPages: _visiblePersonalNotePages(), openFilterRequest: _openFilterRequest, tab: widget.tab, linksCount: widget.tab.links.length, @@ -5906,37 +6024,301 @@ class _PdfBookScreenState extends State return bestMatch?.title; } - Future _handleAddNotePress(BuildContext context) async { - final currentPage = widget.tab.pdfViewerController.isReady - ? (widget.tab.pdfViewerController.pageNumber ?? 1) - : 1; - // עיגון למספר השורה הלוגי בטקסט המקביל (כמו מפרשים/קישורים), כדי שכותרת - // ההערה והסינון לפי עמוד נוכחי יתאימו. בספרים ללא טקסט מקביל - // currentTextLineNumber שווה ממילא לעמוד הפיזי. - final anchorLine = widget.tab.currentTextLineNumber ?? currentPage; + List _visiblePersonalNotePages() { + final controller = widget.tab.pdfViewerController; + if (!controller.isReady) return const []; + final visible = visiblePdfNotePageNumbers( + pageLayouts: controller.layout.pageLayouts, + visibleRect: controller.visibleRect, + ); + if (!_isBookViewModeActive()) return visible; + final range = _spreadPageRangeFor( + _pageNumberNotifier.value ?? widget.tab.pageNumber, + ); + // בתצוגת ספר המסכה מסתירה כפולות אחרות, גם אם הן בתוך מלבן הצפיין. + return visible + .where( + (page) => page >= range.startPage && page < range.endPageExclusive, + ) + .toList(); + } + + void _refreshVisiblePersonalNotePages() { + final pages = _visiblePersonalNotePages(); + if (listEquals(pages, _lastVisiblePdfNotePages)) return; + _lastVisiblePdfNotePages = pages; + if (_visiblePdfNotesRefreshScheduled) return; + _visiblePdfNotesRefreshScheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _visiblePdfNotesRefreshScheduled = false; + if (mounted) _pageDataRevision.value++; + }); + } + + Future _loadPdfPointNotes() async { + final generation = ++_pdfNotesLoadGeneration; + try { + final notes = await _personalNotesRepository.loadStoredNotes( + personalNotesBookKey(widget.tab.book), + ); + if (!mounted || generation != _pdfNotesLoadGeneration) return; + setState(() { + _pdfPointNotes = notes + .where((note) => note.pdfAnchor != null && note.hasLocation) + .toList(); + }); + } catch (error) { + debugPrint('PDF note markers could not be refreshed: $error'); + } + } + + PdfNoteAnchor? _pdfNoteAnchorAtGlobalPosition(Offset position) { + final controller = widget.tab.pdfViewerController; + if (!controller.isReady) return null; + try { + final local = controller.globalToLocal(position); + if (local == null) return null; + return pdfNoteAnchorFromHit( + controller.getPdfPageHitTestResult( + local, + useDocumentLayoutCoordinates: false, + ), + documentId: pdfPersonalNoteDocumentId(widget.tab.book), + ); + } catch (_) { + return null; + } + } - final notesBloc = context.read(); + bool _personalNoteMatchesDocument(PdfNoteAnchor anchor) => + pdfPersonalNoteAnchorMatchesBook( + anchor, + widget.tab.book, + library: context.read()?.state.library, + ); - final draftService = PersonalNoteDraftService(); - final draft = await draftService.loadDraft( + Future _handleAddNotePress( + BuildContext context, { + PdfNoteAnchor? anchor, + String? selectedText, + }) async { + if (anchor == null) { + setState(() { + _noteToReanchor = null; + _isChoosingPersonalNotePoint = true; + }); + _pdfViewFocusNode.requestFocus(); + return; + } + final state = _bloc.state; + await createPersonalNote( + this.context, + isNotesPanelOpen: + state is PdfBookLoaded && + state.showRightPane && + _currentRightPaneTabIndex == _kPersonalNotesTabIndex, bookId: personalNotesBookKey(widget.tab.book), categoryId: widget.tab.book.categoryId, - lineNumber: anchorLine, + lineNumber: anchor.pageNumber, + referenceText: 'עמוד ${anchor.pageNumber}', + selectedText: selectedText, + pdfAnchor: anchor, + openNotesPanel: _openPersonalNotesPane, + repository: _personalNotesRepository, ); + } - if (!mounted) return; + Future _beginPersonalNoteReanchor(PersonalNote note) async { + setState(() { + _noteToReanchor = note; + _isChoosingPersonalNotePoint = true; + }); + _pdfViewFocusNode.requestFocus(); + } - notesBloc.add( - StartCreatingPersonalNote( - bookId: personalNotesBookKey(widget.tab.book), - lineNumber: anchorLine, - referenceText: 'עמוד $currentPage', - initialContent: draft?.content ?? '', - initialFormat: draft?.contentFormat ?? PersonalNoteContentFormat.plain, + void _cancelPersonalNotePointSelection() { + setState(() { + _noteToReanchor = null; + _isChoosingPersonalNotePoint = false; + }); + } + + Future _completePersonalNotePointSelection(PdfNoteAnchor anchor) async { + final note = _noteToReanchor; + _cancelPersonalNotePointSelection(); + if (note == null) { + await _handleAddNotePress(context, anchor: anchor); + return; + } + try { + await _personalNotesRepository.repositionNote( + bookId: note.bookId, + noteId: note.id, + categoryId: widget.tab.book.categoryId, + lineNumber: anchor.pageNumber, + pdfAnchor: anchor, + ); + if (!mounted) return; + setState(() => _focusedPersonalNoteAnchor = anchor); + UiSnack.showSuccess(NotesMessages.noteRepositioned); + } catch (error) { + if (mounted) UiSnack.showError(NotesMessages.noteRepositionFailed(error)); + } + } + + Widget _buildPersonalNotePointPrompt() => PositionedDirectional( + top: 12, + start: 12, + end: 12, + child: Center( + child: Card( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + child: Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 8, + children: [ + const Text(NotesMessages.choosePdfNotePoint), + ActionButton.ghost( + text: 'ביטול', + icon: FluentIcons.dismiss_24_regular, + onPressed: _cancelPersonalNotePointSelection, + ), + ], + ), + ), ), - ); + ), + ); - _openPersonalNotesPane(); + List _buildPersonalNoteMarkers( + BuildContext context, + Rect pageRect, + PdfPage page, + ) { + if (!page.isLoaded) return const []; + final colors = Theme.of(context).colorScheme; + return [ + for (final note in _pdfPointNotes) + if (note.pdfAnchor!.pageNumber == page.pageNumber && + _personalNoteMatchesDocument(note.pdfAnchor!)) + Builder( + builder: (context) { + final anchor = note.pdfAnchor!; + final offset = pdfNoteAnchorDocumentPosition( + anchor, + page: page, + pageRect: Offset.zero & pageRect.size, + ); + final selected = anchor == _focusedPersonalNoteAnchor; + void openNote() { + if (_isChoosingPersonalNotePoint) return; + setState(() => _focusedPersonalNoteAnchor = anchor); + _openPersonalNotesPane(); + final bloc = context.read(); + openPersonalNotesTarget( + bloc, + bookId: note.bookId, + categoryId: widget.tab.book.categoryId, + lineNumber: note.lineNumber!, + pdfAnchor: anchor, + ); + } + + return Positioned( + key: ValueKey('pdf-note-${note.id}'), + left: offset.dx - 12, + top: offset.dy - 12, + width: 24, + height: 24, + child: PdfOverlayInteractionRegion( + onTap: (_) { + if (_isChoosingPersonalNotePoint) return false; + openNote(); + return true; + }, + child: Semantics( + button: true, + label: note.contentPlain, + onTap: openNote, + child: DecoratedBox( + decoration: BoxDecoration( + color: selected + ? colors.primary + : colors.primaryContainer, + shape: BoxShape.circle, + border: Border.all(color: colors.primary, width: 2), + ), + child: Icon( + FluentIcons.note_24_regular, + size: 16, + color: selected + ? colors.onPrimary + : colors.onPrimaryContainer, + ), + ), + ), + ), + ); + }, + ), + ]; + } + + void _onPersonalNoteNavigationRequested() { + final controller = widget.tab.pdfViewerController; + if (!mounted || !_personalNoteViewerReady || !controller.isReady) return; + final anchor = widget.tab.takePersonalNoteNavigationRequest(); + if (anchor == null) return; + unawaited(_navigateToPersonalNoteAnchor(anchor)); + } + + Future _navigateToPersonalNoteAnchor(PdfNoteAnchor anchor) async { + final generation = ++_pdfNoteNavigationGeneration; + bool active() => mounted && generation == _pdfNoteNavigationGeneration; + final controller = widget.tab.pdfViewerController; + if (!_personalNoteMatchesDocument(anchor) || + anchor.pageNumber > controller.pageCount) { + UiSnack.showError(NotesMessages.pdfNoteLocationUnavailable); + return; + } + _rememberPdfLocation(); + try { + final state = _bloc.state; + final paneWasOpen = state is PdfBookLoaded && state.showRightPane; + _openPersonalNotesPane(); + openPersonalNotesTarget( + context.read(), + bookId: personalNotesBookKey(widget.tab.book), + categoryId: widget.tab.book.categoryId, + lineNumber: anchor.pageNumber, + pdfAnchor: anchor, + ); + if (!paneWasOpen) { + // פתיחת הפאנל משנה את רוחב המציג; מרכזים רק לאחר סיום ההנפשה. + await WidgetsBinding.instance.endOfFrame; + if (!active()) return; + await Future.delayed(AppTokens.animPanelSlide); + if (!active()) return; + await WidgetsBinding.instance.endOfFrame; + if (!active()) return; + } + await _goToPageWithSpreadLock(anchor.pageNumber, duration: Duration.zero); + if (!active()) return; + final navigated = await navigateToPdfNoteAnchor( + controller, + anchor, + isActive: active, + ); + if (!active()) return; + if (navigated) { + setState(() => _focusedPersonalNoteAnchor = anchor); + } else { + UiSnack.showError(NotesMessages.pdfNoteLocationUnavailable); + } + } catch (_) { + if (active()) UiSnack.showError(NotesMessages.pdfNoteLocationUnavailable); + } } Future _handlePrintPress(BuildContext context) async { diff --git a/lib/pdf_book/view/pdf_commentary_panel.dart b/lib/pdf_book/view/pdf_commentary_panel.dart index c70e6d2cf5..bbf40a62a5 100644 --- a/lib/pdf_book/view/pdf_commentary_panel.dart +++ b/lib/pdf_book/view/pdf_commentary_panel.dart @@ -55,6 +55,8 @@ import 'package:otzaria/book_common/utils/default_commentators.dart'; import 'package:otzaria/book_common/utils/link_anchor_markers.dart'; import 'package:otzaria/widgets/lists/commentators_selection_panel.dart'; import 'package:otzaria/personal_notes/utils/personal_notes_book_key.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/library/bloc/library_bloc.dart'; import 'package:otzaria/personal_notes/widgets/personal_notes_sidebar.dart'; import 'package:otzaria/settings/settings_exports.dart'; import 'package:otzaria/settings/services/per_book_settings_service.dart'; @@ -288,6 +290,8 @@ class PdfCommentaryPanel extends StatefulWidget { final Function(OpenedTab) openBookCallback; final double fontSize; final VoidCallback? onClose; + final Future Function(PersonalNote)? onReanchorNote; + final List? visiblePdfPages; final int? initialTabIndex; /// רוחב מרבי לרשימת המפרשים (הגדרת רוחב הטקסט); null = ללא הגבלה. @@ -350,6 +354,8 @@ class PdfCommentaryPanel extends StatefulWidget { required this.openBookCallback, required this.fontSize, this.onClose, + this.onReanchorNote, + this.visiblePdfPages, this.initialTabIndex, this.onTabChanged, this.openFilterRequest, @@ -1991,15 +1997,31 @@ class PdfCommentaryPanelState extends State Widget _buildNotesView() { final bookId = personalNotesBookKey(widget.tab.book); + final library = context.watch()?.state.library; + final uniquePdf = library == null + ? null + : findPdfBookForPersonalNotesKey(library, bookId); + final documentId = pdfPersonalNoteDocumentId(widget.tab.book); return PersonalNotesSidebar( key: ValueKey(bookId), bookId: bookId, categoryId: widget.tab.book.categoryId, isPdf: true, + pdfDocumentId: documentId, + includeUnidentifiedPdfAnchors: + uniquePdf != null && + pdfPersonalNoteDocumentId(uniquePdf) == documentId, pdfOutline: widget.tab.outline, + visiblePdfPages: widget.visiblePdfPages ?? [widget.tab.pageNumber], + onReanchorNote: widget.onReanchorNote, visibleLineIndices: _getVisibleLineIndicesForCurrentPage(), onNavigateToLine: (lineNumber, {note}) { + final anchor = note?.pdfAnchor; + if (anchor != null) { + widget.tab.requestPersonalNoteNavigation(anchor); + return; + } // lineNumber הוא מספר שורה לוגי — ממירים אותו לעמוד דרך ה-heading // הקרוב לפניו, ונופלים לפרשנות-עמוד-ישירה בספרים ללא headings. if (widget.tab.pdfHeadings != null) { diff --git a/lib/personal_notes/bloc/personal_notes_bloc.dart b/lib/personal_notes/bloc/personal_notes_bloc.dart index 9e68038c99..f2e7b10f48 100644 --- a/lib/personal_notes/bloc/personal_notes_bloc.dart +++ b/lib/personal_notes/bloc/personal_notes_bloc.dart @@ -121,8 +121,7 @@ class PersonalNotesBloc extends Bloc { filteredMissingNotes: isSameBook ? null : const [], searchQuery: isSameBook ? state.searchQuery : '', visibleLineIndices: isSameBook ? state.visibleLineIndices : [], - // איפוס בקשת פתיחת הערה, כדי שלא תיפתח אוטומטית הערה באותה שורה בספר החדש - clearExpandRequest: true, + clearExpandRequest: !isSameBook, ), ); @@ -161,7 +160,10 @@ class PersonalNotesBloc extends Bloc { sourceSelectedText: event.sourceSelectedText, sourceSelectionOffset: event.sourceSelectionOffset, punctuationHidden: event.punctuationHidden, - categoryId: state.categoryId, + pdfAnchor: event.pdfAnchor, + categoryId: + event.categoryId ?? + (event.bookId == state.bookId ? state.categoryId : null), ); _emitNotes(event.bookId, notes, emit, clearCreatingState: true); } catch (e) { @@ -221,7 +223,10 @@ class PersonalNotesBloc extends Bloc { bookId: event.bookId, noteId: event.noteId, lineNumber: event.lineNumber, - categoryId: state.categoryId, + pdfAnchor: event.pdfAnchor, + categoryId: + event.categoryId ?? + (event.bookId == state.bookId ? state.categoryId : null), ); _emitNotes(event.bookId, notes, emit); } catch (e) { @@ -236,6 +241,7 @@ class PersonalNotesBloc extends Bloc { emit( state.copyWith( expandRequestLineNumber: event.lineNumber, + expandRequestPdfAnchor: event.pdfAnchor, expandRequestToken: state.expandRequestToken + 1, ), ); @@ -248,7 +254,10 @@ class PersonalNotesBloc extends Bloc { emit( state.copyWith( isCreatingNewNote: true, + newNoteRequestToken: state.newNoteRequestToken + 1, + clearExpandRequest: true, clearNewNoteSourceSelection: true, + clearNewNotePdfAnchor: true, newNoteBookId: event.bookId, newNoteLineNumber: event.lineNumber, newNoteReferenceText: event.referenceText, @@ -257,6 +266,7 @@ class PersonalNotesBloc extends Bloc { newNoteSourceSelectedText: event.sourceSelectedText, newNoteSourceSelectionOffset: event.sourceSelectionOffset, newNotePunctuationHidden: event.punctuationHidden, + newNotePdfAnchor: event.pdfAnchor, newNoteInitialContent: event.initialContent, newNoteInitialFormat: event.initialFormat, ), diff --git a/lib/personal_notes/bloc/personal_notes_event.dart b/lib/personal_notes/bloc/personal_notes_event.dart index b5a7a14e27..416a58bbdc 100644 --- a/lib/personal_notes/bloc/personal_notes_event.dart +++ b/lib/personal_notes/bloc/personal_notes_event.dart @@ -19,6 +19,7 @@ class LoadPersonalNotes extends PersonalNotesEvent { class AddPersonalNote extends PersonalNotesEvent { final String bookId; + final int? categoryId; final int lineNumber; final String content; final String contentPlain; @@ -30,9 +31,11 @@ class AddPersonalNote extends PersonalNotesEvent { final String? sourceSelectedText; final int? sourceSelectionOffset; final bool punctuationHidden; + final PdfNoteAnchor? pdfAnchor; const AddPersonalNote({ required this.bookId, + this.categoryId, required this.lineNumber, required this.content, required this.contentPlain, @@ -42,11 +45,13 @@ class AddPersonalNote extends PersonalNotesEvent { this.sourceSelectedText, this.sourceSelectionOffset, this.punctuationHidden = false, + this.pdfAnchor, }); @override List get props => [ bookId, + categoryId, lineNumber, content, contentPlain, @@ -56,6 +61,7 @@ class AddPersonalNote extends PersonalNotesEvent { sourceSelectedText, sourceSelectionOffset, punctuationHidden, + pdfAnchor, ]; } @@ -98,26 +104,37 @@ class RepositionPersonalNote extends PersonalNotesEvent { final String bookId; final String noteId; final int lineNumber; + final PdfNoteAnchor? pdfAnchor; + final int? categoryId; const RepositionPersonalNote({ required this.bookId, required this.noteId, required this.lineNumber, + this.pdfAnchor, + this.categoryId, }); @override - List get props => [bookId, noteId, lineNumber]; + List get props => [ + bookId, + noteId, + lineNumber, + pdfAnchor, + categoryId, + ]; } /// בקשה להרחיב (לפתוח) את ההערות המשויכות לשורה [lineNumber] (1-based), /// גם אם ההגדרה היא "סגור כברירת מחדל". נשלח בלחיצה על סימון הערה inline. class RequestExpandNotesForLine extends PersonalNotesEvent { final int lineNumber; + final PdfNoteAnchor? pdfAnchor; - const RequestExpandNotesForLine(this.lineNumber); + const RequestExpandNotesForLine(this.lineNumber, {this.pdfAnchor}); @override - List get props => [lineNumber]; + List get props => [lineNumber, pdfAnchor]; } class StartCreatingPersonalNote extends PersonalNotesEvent { @@ -129,6 +146,7 @@ class StartCreatingPersonalNote extends PersonalNotesEvent { final String? sourceSelectedText; final int? sourceSelectionOffset; final bool punctuationHidden; + final PdfNoteAnchor? pdfAnchor; final String? initialContent; final PersonalNoteContentFormat? initialFormat; @@ -141,6 +159,7 @@ class StartCreatingPersonalNote extends PersonalNotesEvent { this.sourceSelectedText, this.sourceSelectionOffset, this.punctuationHidden = false, + this.pdfAnchor, this.initialContent, this.initialFormat, }); @@ -155,6 +174,7 @@ class StartCreatingPersonalNote extends PersonalNotesEvent { sourceSelectedText, sourceSelectionOffset, punctuationHidden, + pdfAnchor, initialContent, initialFormat, ]; diff --git a/lib/personal_notes/bloc/personal_notes_state.dart b/lib/personal_notes/bloc/personal_notes_state.dart index 0e11bfe063..5f15384287 100644 --- a/lib/personal_notes/bloc/personal_notes_state.dart +++ b/lib/personal_notes/bloc/personal_notes_state.dart @@ -20,11 +20,14 @@ class PersonalNotesState extends Equatable { // בקשת הרחבה של הערות לשורה מסוימת (לחיצה על סימון inline). // הטוקן עולה בכל בקשה כדי לאפשר הרחבה חוזרת גם אחרי כיווץ ידני. final int? expandRequestLineNumber; + final PdfNoteAnchor? expandRequestPdfAnchor; final int expandRequestToken; // יצירת הערה חדשה — הטיוטה מתויגת ב-[newNoteBookId], כי bookId הוא הספר // האחרון שנטענו לו הערות ולא בהכרח ספר הטיוטה. final bool isCreatingNewNote; + // בקשה זהה עדיין צריכה לחשוף עורך שנגלל מחוץ למסך. + final int newNoteRequestToken; final String? newNoteBookId; final int? newNoteLineNumber; final String? newNoteReferenceText; @@ -33,6 +36,7 @@ class PersonalNotesState extends Equatable { final String? newNoteSourceSelectedText; final int? newNoteSourceSelectionOffset; final bool newNotePunctuationHidden; + final PdfNoteAnchor? newNotePdfAnchor; final String? newNoteInitialContent; final PersonalNoteContentFormat? newNoteInitialFormat; @@ -49,8 +53,10 @@ class PersonalNotesState extends Equatable { this.showOnlyVisible = true, this.visibleLineIndices = const [], this.expandRequestLineNumber, + this.expandRequestPdfAnchor, this.expandRequestToken = 0, this.isCreatingNewNote = false, + this.newNoteRequestToken = 0, this.newNoteBookId, this.newNoteLineNumber, this.newNoteReferenceText, @@ -59,6 +65,7 @@ class PersonalNotesState extends Equatable { this.newNoteSourceSelectedText, this.newNoteSourceSelectionOffset, this.newNotePunctuationHidden = false, + this.newNotePdfAnchor, this.newNoteInitialContent, this.newNoteInitialFormat, }); @@ -76,8 +83,10 @@ class PersonalNotesState extends Equatable { showOnlyVisible = true, visibleLineIndices = const [], expandRequestLineNumber = null, + expandRequestPdfAnchor = null, expandRequestToken = 0, isCreatingNewNote = false, + newNoteRequestToken = 0, newNoteBookId = null, newNoteLineNumber = null, newNoteReferenceText = null, @@ -86,6 +95,7 @@ class PersonalNotesState extends Equatable { newNoteSourceSelectedText = null, newNoteSourceSelectionOffset = null, newNotePunctuationHidden = false, + newNotePdfAnchor = null, newNoteInitialContent = null, newNoteInitialFormat = null; @@ -102,8 +112,10 @@ class PersonalNotesState extends Equatable { bool? showOnlyVisible, List? visibleLineIndices, int? expandRequestLineNumber, + PdfNoteAnchor? expandRequestPdfAnchor, int? expandRequestToken, bool? isCreatingNewNote, + int? newNoteRequestToken, String? newNoteBookId, int? newNoteLineNumber, String? newNoteReferenceText, @@ -112,10 +124,12 @@ class PersonalNotesState extends Equatable { String? newNoteSourceSelectedText, int? newNoteSourceSelectionOffset, bool? newNotePunctuationHidden, + PdfNoteAnchor? newNotePdfAnchor, String? newNoteInitialContent, PersonalNoteContentFormat? newNoteInitialFormat, bool clearNewNoteData = false, bool clearNewNoteSourceSelection = false, + bool clearNewNotePdfAnchor = false, bool clearExpandRequest = false, }) { return PersonalNotesState( @@ -133,10 +147,16 @@ class PersonalNotesState extends Equatable { expandRequestLineNumber: clearExpandRequest ? null : (expandRequestLineNumber ?? this.expandRequestLineNumber), + expandRequestPdfAnchor: clearExpandRequest + ? null + : expandRequestLineNumber != null + ? expandRequestPdfAnchor + : (expandRequestPdfAnchor ?? this.expandRequestPdfAnchor), expandRequestToken: expandRequestToken ?? this.expandRequestToken, isCreatingNewNote: clearNewNoteData ? false : (isCreatingNewNote ?? this.isCreatingNewNote), + newNoteRequestToken: newNoteRequestToken ?? this.newNoteRequestToken, newNoteBookId: clearNewNoteData ? null : (newNoteBookId ?? this.newNoteBookId), @@ -165,6 +185,11 @@ class PersonalNotesState extends Equatable { newNotePunctuationHidden: clearNewNoteData ? false : (newNotePunctuationHidden ?? this.newNotePunctuationHidden), + newNotePdfAnchor: clearNewNoteData + ? null + : clearNewNotePdfAnchor + ? newNotePdfAnchor + : (newNotePdfAnchor ?? this.newNotePdfAnchor), newNoteInitialContent: clearNewNoteData ? null : (newNoteInitialContent ?? this.newNoteInitialContent), @@ -188,8 +213,10 @@ class PersonalNotesState extends Equatable { showOnlyVisible, visibleLineIndices, expandRequestLineNumber, + expandRequestPdfAnchor, expandRequestToken, isCreatingNewNote, + newNoteRequestToken, newNoteBookId, newNoteLineNumber, newNoteReferenceText, @@ -198,6 +225,7 @@ class PersonalNotesState extends Equatable { newNoteSourceSelectedText, newNoteSourceSelectionOffset, newNotePunctuationHidden, + newNotePdfAnchor, newNoteInitialContent, newNoteInitialFormat, ]; diff --git a/lib/personal_notes/models/pdf_note_anchor.dart b/lib/personal_notes/models/pdf_note_anchor.dart new file mode 100644 index 0000000000..65eb90c07e --- /dev/null +++ b/lib/personal_notes/models/pdf_note_anchor.dart @@ -0,0 +1,57 @@ +import 'package:equatable/equatable.dart'; + +/// נקודה יחסית בדף PDF לא מסובב; ראשית הצירים בפינה השמאלית התחתונה. +class PdfNoteAnchor extends Equatable { + final int pageNumber; + final double x; + final double y; + + /// מזהה מהדורת ה-PDF בתוך מקור הספר; אינו משנה את מפתח ההערות הוותיק. + final String? documentId; + + const PdfNoteAnchor({ + required this.pageNumber, + required this.x, + required this.y, + this.documentId, + }) : assert(pageNumber > 0), + assert(x >= 0 && x <= 1), + assert(y >= 0 && y <= 1), + assert(documentId == null || documentId.length > 0); + + factory PdfNoteAnchor.fromJson(Map json) { + final page = json['pageNumber']; + final x = json['x']; + final y = json['y']; + final documentId = json['documentId']; + if (page is! int || + page < 1 || + x is! num || + y is! num || + !x.isFinite || + !y.isFinite || + x < 0 || + x > 1 || + y < 0 || + y > 1 || + (documentId != null && (documentId is! String || documentId.isEmpty))) { + throw const FormatException('Invalid PDF note anchor'); + } + return PdfNoteAnchor( + pageNumber: page, + x: x.toDouble(), + y: y.toDouble(), + documentId: documentId as String?, + ); + } + + Map toJson() => { + 'pageNumber': pageNumber, + 'x': x, + 'y': y, + if (documentId != null) 'documentId': documentId, + }; + + @override + List get props => [pageNumber, x, y, documentId]; +} diff --git a/lib/personal_notes/models/personal_note.dart b/lib/personal_notes/models/personal_note.dart index a9f02e202b..cd73a0deb5 100644 --- a/lib/personal_notes/models/personal_note.dart +++ b/lib/personal_notes/models/personal_note.dart @@ -1,4 +1,7 @@ import 'package:equatable/equatable.dart'; +import 'package:otzaria/personal_notes/models/pdf_note_anchor.dart'; + +export 'pdf_note_anchor.dart'; /// Indicates whether a personal note currently has a valid location in the book. enum PersonalNoteStatus { @@ -51,6 +54,9 @@ class PersonalNote extends Equatable { /// מיקום תווי (offset) של סוף הביטוי בשורה הגולמית — רמז/fast-path. final int? anchorEnd; + /// מיקום פיזי ב-PDF, שאינו תלוי במיפוי לשורות של מהדורת הטקסט. + final PdfNoteAnchor? pdfAnchor; + /// If the note lost its anchor, we keep the previous line number for UI hints. final int? lastKnownLineNumber; @@ -84,6 +90,7 @@ class PersonalNote extends Equatable { this.anchorSuffix, this.anchorStart, this.anchorEnd, + this.pdfAnchor, required this.lastKnownLineNumber, required this.status, required this.content, @@ -105,6 +112,11 @@ class PersonalNote extends Equatable { anchorSuffix: json['anchorSuffix'] as String?, anchorStart: json['anchorStart'] as int?, anchorEnd: json['anchorEnd'] as int?, + pdfAnchor: json['pdfAnchor'] == null + ? null + : PdfNoteAnchor.fromJson( + Map.from(json['pdfAnchor'] as Map), + ), lastKnownLineNumber: json['lastKnownLineNumber'] as int?, status: PersonalNoteStatus.values.byName(json['status'] as String), content: json['content'] as String, @@ -130,6 +142,7 @@ class PersonalNote extends Equatable { 'anchorSuffix': anchorSuffix, 'anchorStart': anchorStart, 'anchorEnd': anchorEnd, + 'pdfAnchor': pdfAnchor?.toJson(), 'lastKnownLineNumber': lastKnownLineNumber, 'status': status.name, 'content': content, @@ -161,6 +174,8 @@ class PersonalNote extends Equatable { int? anchorStart, int? anchorEnd, bool clearAnchor = false, + PdfNoteAnchor? pdfAnchor, + bool clearPdfAnchor = false, int? lastKnownLineNumber, bool clearLastKnownLineNumber = false, PersonalNoteStatus? status, @@ -182,6 +197,7 @@ class PersonalNote extends Equatable { anchorSuffix: clearAnchor ? null : (anchorSuffix ?? this.anchorSuffix), anchorStart: clearAnchor ? null : (anchorStart ?? this.anchorStart), anchorEnd: clearAnchor ? null : (anchorEnd ?? this.anchorEnd), + pdfAnchor: clearPdfAnchor ? null : (pdfAnchor ?? this.pdfAnchor), lastKnownLineNumber: clearLastKnownLineNumber ? null : (lastKnownLineNumber ?? this.lastKnownLineNumber), @@ -205,6 +221,7 @@ class PersonalNote extends Equatable { anchorSuffix, anchorStart, anchorEnd, + pdfAnchor, lastKnownLineNumber, status, content, diff --git a/lib/personal_notes/models/personal_notes_sort_order.dart b/lib/personal_notes/models/personal_notes_sort_order.dart new file mode 100644 index 0000000000..c146918077 --- /dev/null +++ b/lib/personal_notes/models/personal_notes_sort_order.dart @@ -0,0 +1,48 @@ +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; + +enum PersonalNotesSortOrder { + bookLocation, + newestCreated, + oldestCreated, + lastUpdated; + + String get label => switch (this) { + bookLocation => 'לפי ספר ומיקום', + newestCreated => 'החדשות ביותר תחילה', + oldestCreated => 'הוותיקות ביותר תחילה', + lastUpdated => 'עודכנו לאחרונה', + }; + + bool get usesCreationDate => this == newestCreated || this == oldestCreated; + + int compare(PersonalNote a, PersonalNote b) { + final dateComparison = switch (this) { + bookLocation => 0, + newestCreated => b.createdAt.compareTo(a.createdAt), + oldestCreated => a.createdAt.compareTo(b.createdAt), + lastUpdated => b.updatedAt.compareTo(a.updatedAt), + }; + if (dateComparison != 0) return dateComparison; + final bookComparison = a.bookId.compareTo(b.bookId); + if (bookComparison != 0) return bookComparison; + final lineComparison = (a.lineNumber ?? 0).compareTo(b.lineNumber ?? 0); + if (lineComparison != 0) return lineComparison; + final createdComparison = a.createdAt.compareTo(b.createdAt); + if (createdComparison != 0) return createdComparison; + return a.id.compareTo(b.id); + } +} + +const _sortOrderKey = 'key-personal-notes-sort-order'; + +PersonalNotesSortOrder loadPersonalNotesSortOrder() { + final saved = Settings.getValue(_sortOrderKey); + return PersonalNotesSortOrder.values.firstWhere( + (order) => order.name == saved, + orElse: () => PersonalNotesSortOrder.bookLocation, + ); +} + +Future savePersonalNotesSortOrder(PersonalNotesSortOrder order) => + Settings.setValue(_sortOrderKey, order.name); diff --git a/lib/personal_notes/personal_notes_system.dart b/lib/personal_notes/personal_notes_system.dart index e800d33613..0063d2f078 100644 --- a/lib/personal_notes/personal_notes_system.dart +++ b/lib/personal_notes/personal_notes_system.dart @@ -9,6 +9,7 @@ export 'services/personal_notes_user_book_keys.dart'; export 'repository/personal_notes_repository.dart'; export 'storage/personal_notes_database.dart'; export 'utils/note_text_utils.dart'; +export 'utils/create_personal_note.dart'; export 'utils/open_personal_notes_target.dart'; export 'utils/personal_notes_book_key.dart'; export 'view/personal_notes_screen.dart'; diff --git a/lib/personal_notes/repository/personal_notes_repository.dart b/lib/personal_notes/repository/personal_notes_repository.dart index fb14158c30..d9b3d0da11 100644 --- a/lib/personal_notes/repository/personal_notes_repository.dart +++ b/lib/personal_notes/repository/personal_notes_repository.dart @@ -78,6 +78,7 @@ class PersonalNotesRepository { String? sourceSelectedText, int? sourceSelectionOffset, bool punctuationHidden = false, + PdfNoteAnchor? pdfAnchor, int? categoryId, }) async { final bookContent = await _loadBookContent(bookId, categoryId: categoryId); @@ -93,6 +94,39 @@ class PersonalNotesRepository { sourceSelectedText: sourceSelectedText, sourceSelectionOffset: sourceSelectionOffset, punctuationHidden: punctuationHidden, + pdfAnchor: pdfAnchor, + ); + } + + /// מסיים אחרי הכתיבה; המאזינים ל-PersonalNotesChanges מרעננים בנפרד. + 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 { + final bookContent = await _loadBookContent(bookId, categoryId: categoryId); + return _service.createNote( + bookId: bookId, + bookContent: bookContent, + lineNumber: lineNumber, + content: content, + contentPlain: contentPlain, + contentFormat: contentFormat, + selectedText: selectedText, + selectionColumn: selectionColumn, + sourceSelectedText: sourceSelectedText, + sourceSelectionOffset: sourceSelectionOffset, + punctuationHidden: punctuationHidden, + pdfAnchor: pdfAnchor, ); } @@ -115,6 +149,25 @@ class PersonalNotesRepository { ); } + Future persistNote({ + required String bookId, + required String noteId, + required String content, + required String contentPlain, + required PersonalNoteContentFormat contentFormat, + int? categoryId, + }) async { + final bookContent = await _loadBookContent(bookId, categoryId: categoryId); + return _service.persistNote( + bookId: bookId, + bookContent: bookContent, + noteId: noteId, + content: content, + contentPlain: contentPlain, + contentFormat: contentFormat, + ); + } + Future> deleteNote({ required String bookId, required String noteId, @@ -124,6 +177,7 @@ class PersonalNotesRepository { required String bookId, required String noteId, required int lineNumber, + PdfNoteAnchor? pdfAnchor, int? categoryId, }) async { final bookContent = await _loadBookContent(bookId, categoryId: categoryId); @@ -132,6 +186,7 @@ class PersonalNotesRepository { bookContent: bookContent, noteId: noteId, lineNumber: lineNumber, + pdfAnchor: pdfAnchor, ); } diff --git a/lib/personal_notes/services/personal_note_draft_service.dart b/lib/personal_notes/services/personal_note_draft_service.dart index c2bfa26053..9d260c262e 100644 --- a/lib/personal_notes/services/personal_note_draft_service.dart +++ b/lib/personal_notes/services/personal_note_draft_service.dart @@ -13,6 +13,7 @@ class PersonalNoteDraft { final int? lineNumber; final String? noteId; final String? referenceText; + final PdfNoteAnchor? pdfAnchor; const PersonalNoteDraft({ required this.content, @@ -22,6 +23,7 @@ class PersonalNoteDraft { this.lineNumber, this.noteId, this.referenceText, + this.pdfAnchor, }); Map toJson() => { @@ -32,6 +34,7 @@ class PersonalNoteDraft { 'lineNumber': lineNumber, 'noteId': noteId, 'referenceText': referenceText, + if (pdfAnchor != null) 'pdfAnchor': pdfAnchor!.toJson(), }; factory PersonalNoteDraft.fromJson(Map json) { @@ -47,6 +50,11 @@ class PersonalNoteDraft { lineNumber: json['lineNumber'] as int?, noteId: json['noteId'] as String?, referenceText: json['referenceText'] as String?, + pdfAnchor: json['pdfAnchor'] == null + ? null + : PdfNoteAnchor.fromJson( + Map.from(json['pdfAnchor'] as Map), + ), ); } } @@ -61,10 +69,18 @@ class PersonalNoteDraftService { int? categoryId, int? lineNumber, String? noteId, + PdfNoteAnchor? pdfAnchor, }) { assert((lineNumber == null) != (noteId == null)); final prefix = _bookPrefix(bookId, categoryId: categoryId); - return noteId != null ? '${prefix}note:$noteId' : '$prefix$lineNumber'; + if (noteId != null) return '${prefix}note:$noteId'; + if (pdfAnchor != null) { + final document = pdfAnchor.documentId == null + ? '' + : '${Uri.encodeComponent(pdfAnchor.documentId!)}:'; + return '${prefix}pdf:$document${pdfAnchor.pageNumber}:${pdfAnchor.x}:${pdfAnchor.y}'; + } + return '$prefix$lineNumber'; } String _bookPrefix(String bookId, {int? categoryId}) { @@ -88,14 +104,25 @@ class PersonalNoteDraftService { int? categoryId, int? lineNumber, String? noteId, + PdfNoteAnchor? pdfAnchor, }) async { final key = _key( bookId, categoryId: categoryId, lineNumber: lineNumber, noteId: noteId, + pdfAnchor: pdfAnchor, + ); + final draft = _readDraft(key); + if (noteId != null) return draft; + if (draft != null && draft.pdfAnchor == pdfAnchor) return draft; + if (pdfAnchor == null) return null; + + // טיוטה שנשמרה במפתח הישן של מספר השורה שייכת רק לנקודה שלה. + final legacyDraft = _readDraft( + _key(bookId, categoryId: categoryId, lineNumber: lineNumber), ); - return _readDraft(key); + return legacyDraft?.pdfAnchor == pdfAnchor ? legacyDraft : null; } Future saveDraft({ @@ -110,6 +137,7 @@ class PersonalNoteDraftService { categoryId: categoryId, lineNumber: lineNumber, noteId: noteId, + pdfAnchor: draft.pdfAnchor, ); final normalizedDraft = PersonalNoteDraft( content: draft.content, @@ -119,7 +147,33 @@ class PersonalNoteDraftService { lineNumber: lineNumber ?? draft.lineNumber, noteId: noteId ?? draft.noteId, referenceText: draft.referenceText, + pdfAnchor: draft.pdfAnchor, ); + if (noteId == null) { + // מפתח שורה ישן עשוי להכיל טיוטת נקודה. מעבירים אותה לפני כתיבת + // טיוטה חדשה לאותה שורה, כדי שגם טיוטת טקסט לא תדרוס אותה. + final legacyKey = _key( + bookId, + categoryId: categoryId, + lineNumber: lineNumber, + ); + final legacyDraft = _readDraft(legacyKey); + if (legacyDraft?.pdfAnchor != null) { + final pointKey = _key( + bookId, + categoryId: categoryId, + lineNumber: lineNumber, + pdfAnchor: legacyDraft!.pdfAnchor, + ); + if (_readDraft(pointKey) == null) { + await Settings.setValue( + pointKey, + jsonEncode(legacyDraft.toJson()), + ); + } + await Settings.setValue(legacyKey, null); + } + } await Settings.setValue(key, jsonEncode(normalizedDraft.toJson())); } @@ -128,19 +182,39 @@ class PersonalNoteDraftService { int? categoryId, int? lineNumber, String? noteId, + PdfNoteAnchor? pdfAnchor, }) async { final key = _key( bookId, categoryId: categoryId, lineNumber: lineNumber, noteId: noteId, + pdfAnchor: pdfAnchor, ); + if (noteId == null && + pdfAnchor == null && + _readDraft(key)?.pdfAnchor != null) { + 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); + } + } } Future loadLatestNewNoteDraft({ required String bookId, int? categoryId, + bool includePdfAnchors = true, + String? pdfDocumentId, + bool includeUnidentifiedPdfAnchors = true, }) async { final prefix = _bookPrefix(bookId, categoryId: categoryId); if (!Hive.isBoxOpen(HiveCache.keyName)) return null; @@ -158,6 +232,15 @@ class PersonalNoteDraftService { final draft = _readDraft(key); if (draft == null || draft.lineNumber == null) continue; + final anchor = draft.pdfAnchor; + if (anchor != null) { + if (!includePdfAnchors) continue; + if (anchor.documentId == null) { + if (!includeUnidentifiedPdfAnchors) continue; + } else if (anchor.documentId != pdfDocumentId) { + continue; + } + } if (latestDraft == null || draft.updatedAt.isAfter(latestDraft.updatedAt)) { latestDraft = draft; diff --git a/lib/personal_notes/services/personal_notes_import_export_service.dart b/lib/personal_notes/services/personal_notes_import_export_service.dart index 86666e8b65..1486727d2a 100644 --- a/lib/personal_notes/services/personal_notes_import_export_service.dart +++ b/lib/personal_notes/services/personal_notes_import_export_service.dart @@ -121,12 +121,11 @@ class PersonalNotesImportExportService { } } - /// בונה את בלוקי המסמך לייצוא וורד בתבנית חידושי תורה (issue #767): - /// כותרת לכל ספר, תת-כותרת לכל מיקום (פרק/דף) מתוך [locationRef], ואחריהן - /// גוף ההערה — בלי מספרי שורה ותאריכים. הערות ללא מיקום מקובצות בסוף הספר. + /// בונה כותרות ספר ומיקום וגופי הערות ל-Word; הערות ללא מיקום בסוף הספר. List buildWordExportBlocks({ required List notes, required String? Function(PersonalNote note) locationRef, + String? Function(PersonalNote note)? sourceLink, }) { final sorted = [...notes] ..sort((a, b) { @@ -134,12 +133,18 @@ class PersonalNotesImportExportService { if (byBook != 0) return byBook; int line(PersonalNote n) => n.hasLocation ? (n.lineNumber ?? 0) : 1 << 30; - return line(a).compareTo(line(b)); + final byLine = line(a).compareTo(line(b)); + if (byLine != 0) return byLine; + final byTime = a.hasLocation + ? a.createdAt.compareTo(b.createdAt) + : b.updatedAt.compareTo(a.updatedAt); + return byTime != 0 ? byTime : a.id.compareTo(b.id); }); final blocks = []; String? currentBook; String? currentRef; + String? currentSourceLink; for (final note in sorted) { final body = _noteWordBlocks(note); if (body.isEmpty) continue; @@ -147,6 +152,7 @@ class PersonalNotesImportExportService { if (note.bookId != currentBook) { currentBook = note.bookId; currentRef = null; + currentSourceLink = null; blocks.add( PrintBlock( kind: PrintBlockKind.heading, @@ -160,13 +166,17 @@ class PersonalNotesImportExportService { final refLabel = (ref?.isNotEmpty ?? false) ? ref : (note.hasLocation ? null : 'הערות ללא מיקום'); - if (refLabel != null && refLabel != currentRef) { + final link = note.hasLocation ? sourceLink?.call(note) : null; + if (refLabel != null && + (refLabel != currentRef || link != currentSourceLink)) { currentRef = refLabel; + currentSourceLink = link; blocks.add( PrintBlock( kind: PrintBlockKind.heading, headingLevel: 2, text: _escapeHtml(refLabel), + sourceLink: link, ), ); } @@ -176,7 +186,7 @@ class PersonalNotesImportExportService { return blocks; } - /// גוף הערה אחת כבלוקי טקסט, כשהדיבור-המתחיל (הטקסט שסומן) מודגש בראשה. + /// גוף הערה כבלוקי טקסט, כשהטקסט שסומן או כותרת ההערה מודגשים בראשה. List _noteWordBlocks(PersonalNote note) { final paragraphs = _noteHtmlParagraphs(note); while (paragraphs.isNotEmpty && paragraphs.last.trim().isEmpty) { @@ -184,7 +194,8 @@ class PersonalNotesImportExportService { } if (paragraphs.isEmpty) return const []; - final dibur = note.anchorText?.trim() ?? ''; + var dibur = note.anchorText?.trim() ?? ''; + if (dibur.isEmpty) dibur = note.displayTitle?.trim() ?? ''; if (dibur.isNotEmpty) { final needsPeriod = !RegExp(r'[.:,;!?]$').hasMatch(dibur); final suffix = needsPeriod ? '.' : ''; @@ -286,6 +297,7 @@ class PersonalNotesImportExportService { ( PersonalNote.fromJson(json as Map), json.containsKey('anchorText'), + json.containsKey('pdfAnchor'), ), ]; int inserted = 0; @@ -293,7 +305,7 @@ class PersonalNotesImportExportService { int skipped = 0; int duplicated = 0; - for (final (note, hasAnchorText) in notes) { + for (final (note, hasAnchorText, hasPdfAnchor) in notes) { final existing = await _database.getNote(note.id); if (existing == null) { @@ -324,7 +336,7 @@ class PersonalNotesImportExportService { note.displayTitle == existing.displayTitle && (note.hasLocation || note.lastKnownLineNumber == existing.lastKnownLineNumber); - final updatedNote = preserveAnchor + var updatedNote = preserveAnchor ? note .copyWith(clearAnchor: true) .copyWith( @@ -335,6 +347,16 @@ class PersonalNotesImportExportService { anchorEnd: existing.anchorEnd, ) : note; + if (!hasPdfAnchor && + existing.pdfAnchor != null && + note.bookId == existing.bookId && + note.lineNumber == existing.lineNumber && + note.displayTitle == existing.displayTitle && + note.status == existing.status && + (note.hasLocation || + note.lastKnownLineNumber == existing.lastKnownLineNumber)) { + updatedNote = updatedNote.copyWith(pdfAnchor: existing.pdfAnchor); + } await _database.updateNote(updatedNote); updated++; break; diff --git a/lib/personal_notes/services/personal_notes_service.dart b/lib/personal_notes/services/personal_notes_service.dart index b57a3c67ea..733f571f74 100644 --- a/lib/personal_notes/services/personal_notes_service.dart +++ b/lib/personal_notes/services/personal_notes_service.dart @@ -1,5 +1,6 @@ import 'dart:math'; +import 'package:otzaria/core/messages/notes_messages.dart'; import 'package:otzaria/personal_notes/models/personal_note.dart'; import 'package:otzaria/personal_notes/storage/personal_notes_database.dart'; import 'package:otzaria/personal_notes/utils/note_anchor_utils.dart'; @@ -56,13 +57,48 @@ class PersonalNotesService { String? sourceSelectedText, int? sourceSelectionOffset, bool punctuationHidden = false, + PdfNoteAnchor? pdfAnchor, + }) async { + await createNote( + bookId: bookId, + bookContent: bookContent, + lineNumber: lineNumber, + content: content, + contentPlain: contentPlain, + contentFormat: contentFormat, + selectedText: selectedText, + selectionColumn: selectionColumn, + sourceSelectedText: sourceSelectedText, + sourceSelectionOffset: sourceSelectionOffset, + punctuationHidden: punctuationHidden, + pdfAnchor: pdfAnchor, + ); + return _database.loadNotes(bookId); + } + + /// אישור השמירה תלוי בכתיבה בלבד; כשל ברענון אינו מצדיק הוספה חוזרת. + Future createNote({ + required String bookId, + required String bookContent, + 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, }) async { final lines = splitBookContentIntoLines(bookContent); // ספר ללא תוכן טקסטואלי (PDF): lineNumber הוא מספר עמוד ונשמר כפי שהוא, // אחרת כיווץ ל-1 היה מאחד את כל ההערות לעמוד הראשון. - final normalizedLineNumber = lines.isEmpty - ? max(1, lineNumber) - : lineNumber.clamp(1, lines.length); + final normalizedLineNumber = + pdfAnchor?.pageNumber ?? + (lines.isEmpty + ? max(1, lineNumber) + : lineNumber.clamp(1, lines.length)); // Use selectedText if provided, otherwise extract display text from the line // Always remove nikud and te'amim from the display title @@ -71,6 +107,8 @@ class PersonalNotesService { trimmedSelectedText != null && trimmedSelectedText.isNotEmpty; final displayTitle = hasSelection ? removeHebrewDiacritics(trimmedSelectedText) + : pdfAnchor != null + ? '' : extractDisplayTextFromLines( lines, normalizedLineNumber, @@ -84,7 +122,7 @@ class PersonalNotesService { String? anchorSuffix; int? anchorStart; int? anchorEnd; - if (hasSelection) { + if (hasSelection && lines.isNotEmpty && pdfAnchor == null) { final rawLine = lines[normalizedLineNumber - 1]; final computed = computeAnchorForSelection( rawLine: rawLine, @@ -118,6 +156,7 @@ class PersonalNotesService { anchorSuffix: anchorSuffix, anchorStart: anchorStart, anchorEnd: anchorEnd, + pdfAnchor: pdfAnchor, lastKnownLineNumber: null, status: PersonalNoteStatus.located, content: content.trimRight(), @@ -128,8 +167,7 @@ class PersonalNotesService { ); await _database.insertNote(newNote); - - return await _database.loadNotes(bookId); + return newNote; } Future> updateNote({ @@ -139,24 +177,49 @@ class PersonalNotesService { String? content, String? contentPlain, PersonalNoteContentFormat? contentFormat, + }) async { + await persistNote( + bookId: bookId, + bookContent: bookContent, + noteId: noteId, + content: content, + contentPlain: contentPlain, + contentFormat: contentFormat, + ); + return loadNotes(bookId: bookId, bookContent: bookContent); + } + + /// העריכה נשמרת לפני אישור הסגירה, בלי לחייב רענון של יתר הערות הספר. + Future persistNote({ + required String bookId, + required String bookContent, + required String noteId, + String? content, + String? contentPlain, + PersonalNoteContentFormat? contentFormat, }) 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 now = DateTime.now(); - final updatedNote = note.copyWith( - content: content?.trimRight() ?? note.content, - contentPlain: contentPlain?.trimRight() ?? note.contentPlain, - contentFormat: contentFormat ?? note.contentFormat, - updatedAt: now, + final updatedNote = _reconcileLocation( + note.copyWith( + content: content?.trimRight() ?? note.content, + contentPlain: contentPlain?.trimRight() ?? note.contentPlain, + contentFormat: contentFormat ?? note.contentFormat, + updatedAt: now, + ), + splitBookContentIntoLines(bookContent), + bookId, ); await _database.updateNote(updatedNote); - - // Reconcile all notes after update - return await loadNotes(bookId: bookId, bookContent: bookContent); + return updatedNote; } Future> deleteNote({ @@ -172,6 +235,7 @@ class PersonalNotesService { required String bookContent, required String noteId, required int lineNumber, + PdfNoteAnchor? pdfAnchor, }) async { final note = await _database.getNote(noteId); if (note == null) { @@ -181,14 +245,18 @@ class PersonalNotesService { final lines = splitBookContentIntoLines(bookContent); // ספר ללא תוכן טקסטואלי (PDF): lineNumber הוא מספר עמוד ונשמר כפי שהוא, // אחרת כיווץ ל-1 היה מאחד את כל ההערות לעמוד הראשון. - final normalizedLineNumber = lines.isEmpty - ? max(1, lineNumber) - : lineNumber.clamp(1, lines.length); - final newDisplayTitle = extractDisplayTextFromLines( - lines, - normalizedLineNumber, - excludeBookTitle: _bookTitle(bookId), - ); + final normalizedLineNumber = + pdfAnchor?.pageNumber ?? + (lines.isEmpty + ? max(1, lineNumber) + : lineNumber.clamp(1, lines.length)); + final newDisplayTitle = pdfAnchor != null + ? '' + : extractDisplayTextFromLines( + lines, + normalizedLineNumber, + excludeBookTitle: _bookTitle(bookId), + ); final now = DateTime.now(); final updatedNote = note.copyWith( @@ -196,6 +264,8 @@ class PersonalNotesService { displayTitle: newDisplayTitle, // מיקום ידני מחדש הופך את ההערה להערת-שורה-שלמה (אין עוד מילים מעוגנות). clearAnchor: true, + pdfAnchor: pdfAnchor, + clearPdfAnchor: pdfAnchor == null, clearLastKnownLineNumber: true, status: PersonalNoteStatus.located, updatedAt: now, @@ -213,7 +283,7 @@ class PersonalNotesService { ) { // ספר ללא תוכן טקסטואלי (PDF): אין שורות לעגן אליהן — ה-lineNumber הוא // מספר עמוד ונשאר תקף, בלי לסמן 'חסר'. - if (lines.isEmpty) { + if (lines.isEmpty || note.pdfAnchor != null) { return note; } diff --git a/lib/personal_notes/storage/personal_notes_database.dart b/lib/personal_notes/storage/personal_notes_database.dart index e2c5e077a8..6edf8ba3b2 100644 --- a/lib/personal_notes/storage/personal_notes_database.dart +++ b/lib/personal_notes/storage/personal_notes_database.dart @@ -1,9 +1,11 @@ import 'package:flutter/foundation.dart'; +import 'package:otzaria/core/messages/notes_messages.dart'; import 'package:otzaria/data/sqlite/sqlite3_api.dart'; import 'package:otzaria/core/app_paths.dart'; import 'package:otzaria/personal_notes/models/personal_note.dart'; import 'package:otzaria/personal_notes/storage/personal_notes_changes.dart'; +import 'package:otzaria/personal_notes/utils/note_collection_utils.dart'; import 'package:otzaria/migration/database/sqlite3_utils.dart'; /// מסד SQLite להערות אישיות, עם אינדקסים לפי ספר ושורה. @@ -21,6 +23,10 @@ class PersonalNotesDatabase { static const _columnAnchorSuffix = 'anchor_suffix'; static const _columnAnchorStart = 'anchor_start'; static const _columnAnchorEnd = 'anchor_end'; + static const _columnPdfPage = 'pdf_page'; + static const _columnPdfX = 'pdf_x'; + static const _columnPdfY = 'pdf_y'; + static const _columnPdfDocumentId = 'pdf_document_id'; static const _columnLastKnownLine = 'last_known_line'; static const _columnStatus = 'status'; static const _columnContent = 'content'; @@ -80,6 +86,10 @@ class PersonalNotesDatabase { $_columnAnchorSuffix TEXT, $_columnAnchorStart INTEGER, $_columnAnchorEnd INTEGER, + $_columnPdfPage INTEGER, + $_columnPdfX REAL, + $_columnPdfY REAL, + $_columnPdfDocumentId TEXT, $_columnLastKnownLine INTEGER, $_columnStatus TEXT NOT NULL, $_columnContent TEXT NOT NULL, @@ -110,6 +120,10 @@ class PersonalNotesDatabase { 'anchor_suffix': 'TEXT', 'anchor_start': 'INTEGER', 'anchor_end': 'INTEGER', + 'pdf_page': 'INTEGER', + 'pdf_x': 'REAL', + 'pdf_y': 'REAL', + 'pdf_document_id': 'TEXT', }; for (final entry in anchorColumns.entries) { @@ -125,10 +139,10 @@ class PersonalNotesDatabase { Future> loadNotes(String bookId) async { final db = await database; final maps = db.select( - 'SELECT * FROM $_tableNotes WHERE $_columnBookId = ? ORDER BY $_columnLineNumber ASC, $_columnUpdatedAt DESC', + 'SELECT * FROM $_tableNotes WHERE $_columnBookId = ?', [bookId], ).toMapList(); - return maps.map((map) => _noteFromMap(map)).toList(); + return sortPersonalNotes(maps.map((map) => _noteFromMap(map)).toList()); } /// Insert a new note @@ -153,7 +167,10 @@ class PersonalNotesDatabase { ...m.values, note.id, ]); - if (db.updatedRows > 0) _notifyChanges([note.bookId]); + if (db.updatedRows == 0) { + throw StateError(NotesMessages.noteNoLongerExists); + } + _notifyChanges([note.bookId]); } /// Delete a note @@ -334,6 +351,10 @@ class PersonalNotesDatabase { _columnAnchorSuffix: note.anchorSuffix, _columnAnchorStart: note.anchorStart, _columnAnchorEnd: note.anchorEnd, + _columnPdfPage: note.pdfAnchor?.pageNumber, + _columnPdfX: note.pdfAnchor?.x, + _columnPdfY: note.pdfAnchor?.y, + _columnPdfDocumentId: note.pdfAnchor?.documentId, _columnLastKnownLine: note.lastKnownLineNumber, _columnStatus: note.status.name, _columnContent: note.content, @@ -356,6 +377,14 @@ class PersonalNotesDatabase { anchorSuffix: map[_columnAnchorSuffix] as String?, anchorStart: map[_columnAnchorStart] as int?, anchorEnd: map[_columnAnchorEnd] as int?, + pdfAnchor: map[_columnPdfPage] == null + ? null + : PdfNoteAnchor.fromJson({ + 'pageNumber': map[_columnPdfPage], + 'x': map[_columnPdfX], + 'y': map[_columnPdfY], + 'documentId': map[_columnPdfDocumentId], + }), lastKnownLineNumber: map[_columnLastKnownLine] as int?, status: PersonalNoteStatus.values.byName(map[_columnStatus] as String), content: map[_columnContent] as String, diff --git a/lib/personal_notes/utils/create_personal_note.dart b/lib/personal_notes/utils/create_personal_note.dart new file mode 100644 index 0000000000..b3c08420c4 --- /dev/null +++ b/lib/personal_notes/utils/create_personal_note.dart @@ -0,0 +1,131 @@ +import 'package:fluentui_system_icons/fluentui_system_icons.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.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/widgets/personal_note_editor.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_editor_dialog.dart'; + +/// פותח עורך בחלונית הערות פעילה, או דיאלוג בלי לשנות את מצב החלוניות. +Future createPersonalNote( + BuildContext context, { + required bool isNotesPanelOpen, + required String bookId, + required int lineNumber, + String title = 'הערה חדשה', + int? categoryId, + String? referenceText, + String? selectedText, + int? selectionColumn, + String? sourceSelectedText, + int? sourceSelectionOffset, + bool punctuationHidden = false, + PdfNoteAnchor? pdfAnchor, + VoidCallback? openNotesPanel, + PersonalNotesRepository? repository, +}) async { + final bloc = context.read(); + final draft = await PersonalNoteDraftService().loadDraft( + bookId: bookId, + categoryId: categoryId, + lineNumber: lineNumber, + pdfAnchor: pdfAnchor, + ); + if (!context.mounted) return; + + if (isNotesPanelOpen) { + final notesBloc = bloc ?? context.read(); + if (openNotesPanel != null) { + openNotesPanel(); + // מעבר מהערות מפרש לספר הראשי מעדכן את יעד ה-sidebar. נותנים לו + // להשלים את ביטול העורך הקודם לפני הבקשה החדשה. + await WidgetsBinding.instance.endOfFrame; + if (!context.mounted) return; + } + if (notesBloc.state.bookId != bookId || + notesBloc.state.categoryId != categoryId) { + notesBloc.add(LoadPersonalNotes(bookId, categoryId: categoryId)); + } + notesBloc.add( + StartCreatingPersonalNote( + bookId: bookId, + lineNumber: lineNumber, + referenceText: referenceText, + selectedText: selectedText, + selectionColumn: selectionColumn, + sourceSelectedText: sourceSelectedText, + sourceSelectionOffset: sourceSelectionOffset, + punctuationHidden: punctuationHidden, + pdfAnchor: pdfAnchor, + initialContent: draft?.content ?? '', + initialFormat: draft?.contentFormat ?? PersonalNoteContentFormat.plain, + ), + ); + return; + } + + final notesRepository = repository ?? PersonalNotesRepository(); + await showDialog( + context: context, + builder: (_) => PersonalNoteEditorDialog( + title: title, + referenceText: referenceText, + icon: FluentIcons.note_add_24_regular, + bookId: bookId, + categoryId: categoryId, + draftLineNumber: lineNumber, + pdfAnchor: pdfAnchor, + initialContent: draft?.content ?? '', + initialContentFormat: + draft?.contentFormat ?? PersonalNoteContentFormat.plain, + linkableNotes: bloc?.state.bookId == bookId + ? [...bloc!.state.locatedNotes, ...bloc.state.missingNotes] + : const [], + onSave: (result) => notesRepository.createNote( + bookId: bookId, + lineNumber: lineNumber, + content: result.content, + contentPlain: result.contentPlain, + contentFormat: result.contentFormat, + selectedText: selectedText, + selectionColumn: selectionColumn, + sourceSelectedText: sourceSelectedText, + sourceSelectionOffset: sourceSelectionOffset, + punctuationHidden: punctuationHidden, + categoryId: categoryId, + pdfAnchor: pdfAnchor, + ), + ), + ); +} + +/// מצב החלונית בפועל, לקריאה בעת קיצור מקלדת מהמסך העוטף. +abstract interface class PersonalNotesPanelVisibility { + bool get isPersonalNotesPanelOpen; + + void revealPersonalNotesTarget( + String bookId, + int? categoryId, + int lineNumber, + ); +} + +/// תפריט מפרש יכול להופיע בכמה מסכי קריאה. משתמשים בפאנל של המסך הקרוב +/// בלבד, וקוראים את מצבו בעת הפעולה — גם אם כרטיס המפרש נשמר במטמון. +PersonalNotesPanelVisibility? findPersonalNotesPanel(BuildContext context) { + PersonalNotesPanelVisibility? panel; + context.visitAncestorElements((element) { + if (element is StatefulElement) { + final Object state = element.state; + if (state is PersonalNotesPanelVisibility) { + panel = state; + return false; + } + } + return true; + }); + return panel; +} diff --git a/lib/personal_notes/utils/note_collection_utils.dart b/lib/personal_notes/utils/note_collection_utils.dart index 3eacdebef8..28d2bf8371 100644 --- a/lib/personal_notes/utils/note_collection_utils.dart +++ b/lib/personal_notes/utils/note_collection_utils.dart @@ -2,7 +2,12 @@ import 'package:otzaria/personal_notes/models/personal_note.dart'; List sortPersonalNotes(List notes) { final located = notes.where((n) => n.hasLocation).toList() - ..sort((a, b) => a.lineNumber!.compareTo(b.lineNumber!)); + ..sort((a, b) { + final lineOrder = a.lineNumber!.compareTo(b.lineNumber!); + if (lineOrder != 0) return lineOrder; + final creationOrder = a.createdAt.compareTo(b.createdAt); + return creationOrder != 0 ? creationOrder : a.id.compareTo(b.id); + }); final missing = notes.where((n) => !n.hasLocation).toList() ..sort((a, b) => b.updatedAt.compareTo(a.updatedAt)); return [...located, ...missing]; diff --git a/lib/personal_notes/utils/note_location_ref.dart b/lib/personal_notes/utils/note_location_ref.dart index dfa9e99447..ee6148a193 100644 --- a/lib/personal_notes/utils/note_location_ref.dart +++ b/lib/personal_notes/utils/note_location_ref.dart @@ -25,14 +25,18 @@ String? personalNoteLocationRef( // ב-PDF הכתובת מחושבת ממספר עמוד ואינה תואמת לעוגן; כותרת (מילות הדף) כבר // מציינת את המיקום, ורק בלעדיה (PDF ללא טקסט) מציגים את הכתובת. - if (isPdf && (note.displayTitle?.isNotEmpty ?? false)) { + if (isPdf && + note.pdfAnchor == null && + (note.displayTitle?.isNotEmpty ?? false)) { return null; } String ref; if (isPdf) { if (pdfOutline == null) return null; - ref = referenceFromPageNumber(lineNumber, pdfOutline).trim(); + final page = note.pdfAnchor?.pageNumber ?? lineNumber; + ref = referenceFromPageNumber(page, pdfOutline).trim(); + if (ref.isEmpty && note.pdfAnchor != null) ref = 'עמוד $page'; } else { if (tableOfContents == null) return null; // lineNumber הוא 1-based ואילו אינדקס ה-TOC הוא 0-based. diff --git a/lib/personal_notes/utils/open_personal_notes_target.dart b/lib/personal_notes/utils/open_personal_notes_target.dart index 5578c330de..5294cd8ba5 100644 --- a/lib/personal_notes/utils/open_personal_notes_target.dart +++ b/lib/personal_notes/utils/open_personal_notes_target.dart @@ -1,5 +1,6 @@ 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/pdf_note_anchor.dart'; /// טוען ספר בלשונית ההערות ומבקש להרחיב את הערות השורה שנבחרה. void openPersonalNotesTarget( @@ -7,6 +8,7 @@ void openPersonalNotesTarget( required String bookId, required int lineNumber, int? categoryId, + PdfNoteAnchor? pdfAnchor, }) { if (bloc.state.showOnlyVisible) { bloc.add(const ToggleShowOnlyVisible()); @@ -15,5 +17,5 @@ void openPersonalNotesTarget( bloc.add(const UpdateSearchQuery('')); } bloc.add(LoadPersonalNotes(bookId, categoryId: categoryId)); - bloc.add(RequestExpandNotesForLine(lineNumber)); + bloc.add(RequestExpandNotesForLine(lineNumber, pdfAnchor: pdfAnchor)); } diff --git a/lib/personal_notes/utils/personal_note_source_link.dart b/lib/personal_notes/utils/personal_note_source_link.dart new file mode 100644 index 0000000000..c3ec3b07ce --- /dev/null +++ b/lib/personal_notes/utils/personal_note_source_link.dart @@ -0,0 +1,64 @@ +import 'package:otzaria/library/models/library.dart'; +import 'package:otzaria/models/books.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/utils/personal_notes_book_key.dart'; +import 'package:otzaria/utils/book_link_builder.dart'; + +/// עוגן פיזי שייך למהדורת ה-PDF גם כשיש ספר טקסט באותה כותרת. +Book? personalNoteSourceBook(Library library, PersonalNote note) => + note.pdfAnchor == null + ? findBookForPersonalNotesKey(library, note.bookId) + : findPdfBookForPersonalNotesKey( + library, + note.bookId, + documentId: note.pdfAnchor?.documentId, + ); + +/// קישור למיקום שמור בספר מזוהה. ב-PDF נדרשת רשימת המועמדים לקישור, +/// כי מזהה מסד עשוי להיות משותף לכמה מהדורות בעלות נתיבים שונים. +String? personalNoteSourceLink( + Book? book, + PersonalNote note, { + Iterable? pdfLinkCandidates, +}) { + if (book == null || + book.id == null || + book.id! <= 0 || + !note.hasLocation || + note.lineNumber! <= 0 || + personalNotesBookKey(book) != note.bookId) { + return null; + } + if (book is PdfBook) { + final targetDocument = pdfPersonalNoteDocumentId(book); + final documents = pdfLinkCandidates + ?.where( + (candidate) => + candidate.id == book.id && candidate.source == book.source, + ) + .map(pdfPersonalNoteDocumentId) + .toSet(); + if (documents == null || + documents.length != 1 || + documents.single != targetDocument) { + return null; + } + final documentId = note.pdfAnchor?.documentId; + if (documentId != null && documentId != targetDocument) { + return null; + } + return buildPdfPageLink( + book.id!, + note.pdfAnchor?.pageNumber ?? note.lineNumber!, + source: book.source, + ); + } + if (book is TextBook && note.pdfAnchor == null) { + return buildSectionLink( + book.id!, + note.lineNumber! - 1, + source: book.source, + ); + } + return null; +} diff --git a/lib/personal_notes/utils/personal_notes_book_key.dart b/lib/personal_notes/utils/personal_notes_book_key.dart index 46deb0b691..d5ba6e3770 100644 --- a/lib/personal_notes/utils/personal_notes_book_key.dart +++ b/lib/personal_notes/utils/personal_notes_book_key.dart @@ -1,6 +1,8 @@ import 'package:otzaria/library/models/library.dart'; import 'package:otzaria/models/book_source.dart'; import 'package:otzaria/models/books.dart'; +import 'package:otzaria/personal_notes/models/pdf_note_anchor.dart'; +import 'package:otzaria/data/book_identity.dart'; /// מפתח הספר של הערות אישיות. ספר רשמי ממופתח לפי הכותרת, כמו בהערות שכבר /// נשמרו; ספר אישי מקבל `title|user` וספר ממסד מצורף `title|db:`. @@ -97,6 +99,49 @@ TextBook? findTextBookForPersonalNotesKey(Library library, String key) { return document?.toTextBook(); } +/// מזהה מסמך בתוך מקורו. קובץ שאינו רשומת קטלוג מזוהה לפי נתיבו, כדי ששתי +/// מהדורות באותו שם בתיקיות שונות לא יקבלו זו את הערות הנקודה של זו. +String pdfPersonalNoteDocumentId(PdfBook book) { + return '${book.source.wireKey}|' + '${Uri.encodeComponent(BookIdentity.indexedFilePath(book))}'; +} + +/// מהדורת ה-PDF מאותו מקור. בלי מזהה מסמך מותר להסיק רק התאמה יחידה. +PdfBook? findPdfBookForPersonalNotesKey( + Library library, + String key, { + String? documentId, +}) { + final parsed = parsePersonalNotesBookKey(key); + final byIdentity = {}; + for (final book in _candidates( + library, + parsed.title, + parsed.source, + ).whereType()) { + final identity = pdfPersonalNoteDocumentId(book); + if (documentId == null || documentId == identity) { + byIdentity.putIfAbsent(identity, () => book); + } + } + return byIdentity.length == 1 ? byIdentity.values.single : null; +} + +bool pdfPersonalNoteAnchorMatchesBook( + PdfNoteAnchor anchor, + PdfBook book, { + Library? library, +}) { + final identity = pdfPersonalNoteDocumentId(book); + if (anchor.documentId != null) return anchor.documentId == identity; + if (library == null) return false; + final unique = findPdfBookForPersonalNotesKey( + library, + personalNotesBookKey(book), + ); + return unique != null && pdfPersonalNoteDocumentId(unique) == identity; +} + /// תוכן העניינים של ספר הטקסט ש-[key] מצביע עליו, או null כשאינו בספרייה. Future?> personalNotesBookToc(Library? library, String key) { final book = library == null diff --git a/lib/personal_notes/utils/personal_notes_filter.dart b/lib/personal_notes/utils/personal_notes_filter.dart index edd6a7f1a9..54843eb766 100644 --- a/lib/personal_notes/utils/personal_notes_filter.dart +++ b/lib/personal_notes/utils/personal_notes_filter.dart @@ -16,11 +16,30 @@ PersonalNotesFilterResult filterPersonalNotes({ required String searchQuery, required bool showOnlyVisible, required List visibleLineIndices, + bool isPdf = false, + List? visiblePdfPages, + String? pdfDocumentId, + bool includeUnidentifiedPdfAnchors = false, }) { - var filteredLocated = locatedNotes; - if (showOnlyVisible && visibleLineIndices.isNotEmpty) { + bool included(PersonalNote note) { + final anchor = note.pdfAnchor; + if (anchor == null) return true; + if (!isPdf) return false; + if (anchor.documentId == null) return includeUnidentifiedPdfAnchors; + return anchor.documentId == pdfDocumentId; + } + + var filteredLocated = locatedNotes.where(included).toList(); + if (showOnlyVisible && + (visibleLineIndices.isNotEmpty || visiblePdfPages != null)) { final visibleLines = visibleLineIndices.toSet(); - filteredLocated = locatedNotes.where((note) { + final pdfPages = visiblePdfPages?.toSet(); + filteredLocated = filteredLocated.where((note) { + final pdfAnchor = note.pdfAnchor; + if (isPdf && pdfAnchor != null && pdfPages != null) { + return pdfPages.contains(pdfAnchor.pageNumber); + } + if (visibleLines.isEmpty) return true; final lineNumber = note.lineNumber; return lineNumber != null && visibleLines.contains(lineNumber - 1); }).toList(); @@ -36,7 +55,7 @@ PersonalNotesFilterResult filterPersonalNotes({ var filteredMissing = []; if (!showOnlyVisible) { - filteredMissing = missingNotes; + filteredMissing = missingNotes.where(included).toList(); if (searchQuery.isNotEmpty) { final query = searchQuery.toLowerCase(); filteredMissing = filteredMissing.where((note) { diff --git a/lib/personal_notes/view/personal_notes_screen.dart b/lib/personal_notes/view/personal_notes_screen.dart index a4e8b5e002..4d21e58097 100644 --- a/lib/personal_notes/view/personal_notes_screen.dart +++ b/lib/personal_notes/view/personal_notes_screen.dart @@ -7,6 +7,7 @@ import 'package:flutter/services.dart'; import 'package:fluentui_system_icons/fluentui_system_icons.dart'; import 'package:otzaria_icons/otzaria_icons.dart'; import 'package:otzaria/widgets/misc/rtl_icon.dart'; +import 'package:otzaria/widgets/misc/app_popup_menu.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:otzaria/widgets/text/otzaria_search_field.dart'; @@ -16,19 +17,23 @@ 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/bloc/personal_notes_state.dart'; import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/models/personal_notes_sort_order.dart'; import 'package:otzaria/personal_notes/repository/personal_notes_repository.dart'; import 'package:otzaria/printing/word_export_service.dart'; import 'package:otzaria/utils/file/save_file_with_extension.dart'; import 'package:pdf/pdf.dart'; import 'package:otzaria/personal_notes/services/personal_notes_import_export_service.dart'; +import 'package:otzaria/personal_notes/services/personal_note_draft_service.dart'; import 'package:otzaria/personal_notes/services/personal_notes_user_book_keys.dart'; import 'package:otzaria/personal_notes/storage/personal_notes_database.dart'; +import 'package:otzaria/personal_notes/storage/personal_notes_changes.dart'; import 'package:otzaria/personal_notes/widgets/personal_note_content_view.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/personal_notes/widgets/personal_notes_export_dialog.dart'; import 'package:otzaria/personal_notes/utils/note_location_ref.dart'; import 'package:otzaria/personal_notes/utils/personal_notes_book_key.dart'; +import 'package:otzaria/personal_notes/utils/personal_note_source_link.dart'; import 'package:otzaria/library/bloc/library_bloc.dart'; import 'package:otzaria/library/bloc/library_state.dart'; import 'package:otzaria/library/models/library.dart'; @@ -36,8 +41,10 @@ import 'package:otzaria/models/books.dart'; import 'package:otzaria/widgets/lists/nav_tree_tile.dart'; import 'package:otzaria/widgets/feedback/tool_empty_state.dart'; import 'package:otzaria/utils/navigation/open_book.dart'; +import 'package:otzaria/utils/text/ref_helper.dart'; import 'package:otzaria/tabs/bloc/tabs_bloc.dart'; import 'package:otzaria/tabs/models/text_tab.dart'; +import 'package:otzaria/tabs/models/pdf_tab.dart'; import 'package:otzaria/text_book/bloc/text_book_event.dart'; import 'package:file_picker/file_picker.dart'; import 'package:otzaria/utils/file/file_picker_dialog_options.dart'; @@ -77,8 +84,10 @@ class _PersonalNotesManagerScreenState final Map _bookStates = {}; final Map _expansionState = {}; int _notesLoadGeneration = 0; - StreamSubscription? _notesLoadSubscription; - Completer? _notesLoadCompleter; + late final StreamSubscription _notesChangesSubscription; + bool _isLoadingNotes = true; + bool _isRefreshingChangedBooks = false; + final Set _changedBooks = {}; // קאש ל-TOC לכל ספר, לחישוב כתובת המיקום של ההערות. נטען עצלן פעם אחת. final Map?>> _tocFutureByBook = {}; bool _isNavigationVisible = true; @@ -91,105 +100,163 @@ class _PersonalNotesManagerScreenState double _navigationWidth = 250.0; // טווח תאריכים לסינון לפי תאריך עדכון ההערה. null = ללא סינון תאריכים. DateTimeRange? _dateRange; + late PersonalNotesSortOrder _sortOrder; @override void initState() { super.initState(); + _sortOrder = loadPersonalNotesSortOrder(); _repository = widget.repository ?? PersonalNotesRepository(); _importExportService = widget.importExportService ?? PersonalNotesImportExportService(); + _notesChangesSubscription = PersonalNotesChanges.stream.listen((bookId) { + _changedBooks.add(bookId); + unawaited(_refreshChangedBooks()); + }); _loadBooks(); } Future _loadBooks() async { - // בריענון - לא מציגים ספינר אם כבר יש ספרים - // בטעינה ראשונה - נשאר במצב טעינה - final isRefresh = _books.isNotEmpty; - - if (!isRefresh) { - setState(() { - _isLoadingBooks = true; - _booksError = null; - }); - } else if (_booksError != null) { - setState(() { - _booksError = null; - }); - } + final generation = ++_notesLoadGeneration; + setState(() { + _isLoadingBooks = _books.isEmpty; + _isLoadingNotes = true; + _booksError = null; + }); try { final books = await _repository.listBooksWithNotes(); - if (!mounted) return; + if (!mounted || generation != _notesLoadGeneration) return; setState(() { _books = books; _isLoadingBooks = false; _booksError = null; + final keys = books.map((book) => book.bookId).toSet(); + _bookStates.removeWhere((key, _) => !keys.contains(key)); }); - _scheduleNotesLoad(books); + await _loadNotesSequence(books, generation); } catch (e) { - if (!mounted) return; - if (_books.isEmpty) { - setState(() { - _booksError = e.toString(); - _isLoadingBooks = false; - }); - } else { + if (!mounted || generation != _notesLoadGeneration) return; + setState(() { + _booksError = e.toString(); + _isLoadingBooks = false; + }); + if (_books.isNotEmpty) { UiSnack.showError(NotesMessages.notesListLoadError(e)); } + } finally { + if (mounted && generation == _notesLoadGeneration) { + setState(() => _isLoadingNotes = false); + unawaited(_refreshChangedBooks()); + } } } - void _scheduleNotesLoad(List books) { - final generation = ++_notesLoadGeneration; - _cancelPendingNotesLoad(); - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted || generation != _notesLoadGeneration) return; - unawaited(_loadNotesSequence(books, generation)); - }); - } - - void _cancelPendingNotesLoad() { - final subscription = _notesLoadSubscription; - final completer = _notesLoadCompleter; - _notesLoadSubscription = null; - _notesLoadCompleter = null; - if (completer != null && !completer.isCompleted) completer.complete(); - if (subscription != null) unawaited(subscription.cancel()); - } - Future _loadNotesSequence( List books, int generation, ) async { - if (!mounted || generation != _notesLoadGeneration) return; - final bloc = context.read(); for (final book in books) { - if (generation != _notesLoadGeneration) return; - final completer = Completer(); - void completeLoad() { - if (!completer.isCompleted) completer.complete(); + if (!mounted || generation != _notesLoadGeneration) return; + try { + // הקורא טוען ספרים במקביל; מצב ה-BLoC המשותף אינו תור טעינה למנהל. + final notes = await _repository.loadNotes(book.bookId); + if (!mounted || generation != _notesLoadGeneration) return; + _storeBookNotes(book.bookId, notes); + } catch (error) { + if (!mounted || generation != _notesLoadGeneration) return; + setState(() { + _bookStates[book.bookId] = + (_bookStates[book.bookId] ?? const PersonalNotesState.initial()) + .copyWith( + bookId: book.bookId, + errorMessage: error.toString(), + ); + }); } + } + } - final subscription = bloc.stream.listen( - (state) { - if (state.bookId == book.bookId && !state.isLoading) completeLoad(); - }, - onError: (_, _) => completeLoad(), - onDone: completeLoad, + void _storeBookNotes(String bookId, List notes) { + setState(() { + _bookStates[bookId] = PersonalNotesState( + bookId: bookId, + isLoading: false, + locatedNotes: notes.where((note) => note.hasLocation).toList(), + missingNotes: notes.where((note) => !note.hasLocation).toList(), + errorMessage: null, ); - _notesLoadSubscription = subscription; - _notesLoadCompleter = completer; - bloc.add(LoadPersonalNotes(book.bookId)); - await completer.future; - if (identical(_notesLoadSubscription, subscription)) { - _notesLoadSubscription = null; - _notesLoadCompleter = null; + }); + } + + Future _refreshChangedBooks() async { + if (!mounted || + _isLoadingNotes || + _isRefreshingChangedBooks || + _changedBooks.isEmpty) { + return; + } + setState(() => _isRefreshingChangedBooks = true); + final generation = _notesLoadGeneration; + try { + while (_changedBooks.isNotEmpty) { + final changed = Set.of(_changedBooks); + _changedBooks.clear(); + for (final bookId in changed) { + try { + final notes = await _repository.loadStoredNotes(bookId); + if (!mounted) return; + if (generation != _notesLoadGeneration) { + _changedBooks.addAll(changed); + return; + } + _storeBookNotes(bookId, notes); + } catch (error) { + if (!mounted || generation != _notesLoadGeneration) return; + setState(() { + _bookStates[bookId] = + (_bookStates[bookId] ?? const PersonalNotesState.initial()) + .copyWith(bookId: bookId, errorMessage: error.toString()); + }); + } + } + final books = await _repository.listBooksWithNotes(); + if (!mounted) return; + if (generation != _notesLoadGeneration) { + _changedBooks.addAll(changed); + return; + } + setState(() { + _books = books; + _booksError = null; + final keys = books.map((book) => book.bookId).toSet(); + _bookStates.removeWhere((key, _) => !keys.contains(key)); + }); + } + } catch (error) { + if (mounted && generation == _notesLoadGeneration) { + setState(() => _booksError = error.toString()); + } + } finally { + if (mounted) { + setState(() => _isRefreshingChangedBooks = false); + if (_changedBooks.isNotEmpty && !_isLoadingNotes) { + unawaited(_refreshChangedBooks()); + } } - unawaited(subscription.cancel()); - if (!mounted || generation != _notesLoadGeneration) return; } } + bool get _hasNotesLoadError => + _booksError != null || + _bookStates.values.any((state) => state.errorMessage != null); + + bool get _canExportNotes => + !_isLoadingNotes && + !_isRefreshingChangedBooks && + _changedBooks.isEmpty && + !_hasNotesLoadError; + void _onFilterChanged(String? filter) { setState(() { _selectedFilter = filter; @@ -276,7 +343,7 @@ class _PersonalNotesManagerScreenState @override void dispose() { _notesLoadGeneration++; - _cancelPendingNotesLoad(); + unawaited(_notesChangesSubscription.cancel()); _searchController.dispose(); _searchQuery.dispose(); _searchFocusNode.dispose(); @@ -321,61 +388,57 @@ class _PersonalNotesManagerScreenState focusNode: _windowFocusNode, autofocus: true, onKeyEvent: _handleWindowKeyEvent, - child: BlocListener( - listener: (context, state) { - // Store the state for each book and trigger rebuild - if (state.bookId != null && !state.isLoading) { - setState(() { - _bookStates[state.bookId!] = state; - }); - - // If this is a new book (not in _books list), refresh the books list - final bookExists = _books.any( - (book) => book.bookId == state.bookId, - ); - if (!bookExists && - (state.locatedNotes.isNotEmpty || - state.missingNotes.isNotEmpty)) { - _loadBooks(); - } - } - }, - child: Column( - children: [ - // שורת כלים עליונה לכל רוחב העמוד - _buildTopBar(), - // תוכן העמוד - Expanded( - child: NavSidePanel( - isOpen: _isNavigationVisible, - alignment: AlignmentDirectional - .centerEnd, // ימין בעברית (RTL) - סרגל ניווט - mainContent: Column( - children: [ - if (_dateRange != null) _buildDateFilterBanner(), - Expanded( - child: ValueListenableBuilder( - valueListenable: _searchQuery, - builder: (context, _, _) => _buildAllNotesList(), - ), + child: Column( + children: [ + // שורת כלים עליונה לכל רוחב העמוד + _buildTopBar(), + if (_isLoadingNotes) const LinearProgressIndicator(), + if (_hasNotesLoadError) + Padding( + padding: const EdgeInsets.all(8), + child: Row( + children: [ + const Expanded( + child: Text(NotesMessages.notesLoadIncomplete), + ), + ActionButton.recommended( + text: 'נסה שוב', + onPressed: _loadBooks, + ), + ], + ), + ), + // תוכן העמוד + Expanded( + child: NavSidePanel( + isOpen: _isNavigationVisible, + alignment: AlignmentDirectional + .centerEnd, // ימין בעברית (RTL) - סרגל ניווט + mainContent: Column( + children: [ + if (_dateRange != null) _buildDateFilterBanner(), + Expanded( + child: ValueListenableBuilder( + valueListenable: _searchQuery, + builder: (context, _, _) => _buildAllNotesList(), ), - ], - ), - paneWidth: _navigationWidth, - minMainContentWidth: 320, - onClose: () => setState(() => _isNavigationVisible = false), - onOpen: () => setState(() => _isNavigationVisible = true), - isResizable: true, - minPaneWidth: 150, - maxPaneWidth: 500, - onPaneWidthChanged: (nextWidth) { - _navigationWidth = nextWidth; - }, - paneContent: _buildNotesTree(), + ), + ], ), + paneWidth: _navigationWidth, + minMainContentWidth: 320, + onClose: () => setState(() => _isNavigationVisible = false), + onOpen: () => setState(() => _isNavigationVisible = true), + isResizable: true, + minPaneWidth: 150, + maxPaneWidth: 500, + onPaneWidthChanged: (nextWidth) { + _navigationWidth = nextWidth; + }, + paneContent: _buildNotesTree(), ), - ], - ), + ), + ], ), ), ), @@ -407,6 +470,25 @@ class _PersonalNotesManagerScreenState onClear: () => _searchQuery.value = '', ), trailingItems: [ + AppTopBarItem( + widget: AppPopupMenuButton( + iconData: FluentIcons.arrow_sort_24_regular, + tooltip: 'מיון הערות', + highlighted: _sortOrder != PersonalNotesSortOrder.bookLocation, + initialValue: _sortOrder, + entries: [ + for (final order in PersonalNotesSortOrder.values) + AppMenuEntry(value: order, label: order.label), + ], + onSelected: (order) { + setState(() => _sortOrder = order); + unawaited(savePersonalNotesSortOrder(order)); + if (_contentScrollController.hasClients) { + _contentScrollController.jumpTo(0); + } + }, + ), + ), AppTopBarItem( widget: BarButton.icon( compact: isCompact, @@ -432,7 +514,7 @@ class _PersonalNotesManagerScreenState compact: isCompact, tooltip: 'גיבוי הערות', icon: FluentIcons.arrow_download_24_regular, - onPressed: _exportNotes, + onPressed: _canExportNotes ? _exportNotes : null, ), ), AppTopBarItem( @@ -440,7 +522,7 @@ class _PersonalNotesManagerScreenState compact: isCompact, tooltip: 'ייצוא לטקסט', icon: OtzariaIcons.document_download_24_regular, - onPressed: _exportNotesToText, + onPressed: _canExportNotes ? _exportNotesToText : null, ), ), AppTopBarItem( @@ -448,7 +530,7 @@ class _PersonalNotesManagerScreenState compact: isCompact, tooltip: 'ייצוא לוורד', icon: OtzariaIcons.document_word_24_regular, - onPressed: _exportNotesToWord, + onPressed: _canExportNotes ? _exportNotesToWord : null, ), ), AppTopBarItem( @@ -498,12 +580,14 @@ class _PersonalNotesManagerScreenState required Future Function(NotesExportSelection selection) buildBytes, }) async { + if (!_canExportNotes) return; if (!await verifySaferModePassword(context)) return; - if (!mounted) return; + if (!mounted || !_canExportNotes) return; + final exportSnapshot = _collectAllNotes(); final selection = await showDialog( context: context, builder: (context) => PersonalNotesExportDialog( - allNotes: _collectAllNotes(), + allNotes: exportSnapshot, title: title, confirmText: confirmText, ), @@ -575,23 +659,81 @@ class _PersonalNotesManagerScreenState Future _buildWordExport(NotesExportSelection selection) async { final fontFamily = context.read().state.fontFamily; + final library = context.read().state.library; + final pdfLinkCandidatesById = <(String, int), List>{}; + if (library != null) { + for (final book in library.getIndexableBooks().whereType()) { + if (book.id != null) { + pdfLinkCandidatesById + .putIfAbsent((book.source.wireKey, book.id!), () => []) + .add(book); + } + } + } - // כתובת המיקום (פרק/דף) לכל הערה נגזרת מתוכן העניינים של ספרה. final notesByBook = >{}; for (final note in selection.notes) { notesByBook.putIfAbsent(note.bookId, () => []).add(note); } final refByNoteId = {}; + final sourceLinkByNoteId = {}; for (final entry in notesByBook.entries) { - final toc = await _tocFor(entry.key); + if (!mounted) return null; + final book = library == null + ? null + : findBookForPersonalNotesKey(library, entry.key); + final pdfBooks = {}; + final dbRefByLine = >{}; for (final note in entry.value) { - refByNoteId[note.id] = personalNoteLocationRef( + if (!mounted) return null; + if (!note.hasLocation) continue; + final lineNumber = note.lineNumber!; + final sourceBook = note.pdfAnchor == null + ? book + : pdfBooks.putIfAbsent( + note.pdfAnchor?.documentId, + () => library == null + ? null + : findPdfBookForPersonalNotesKey( + library, + entry.key, + documentId: note.pdfAnchor?.documentId, + ), + ); + final link = personalNoteSourceLink( + sourceBook, note, - isPdf: false, - bookTitle: parsePersonalNotesBookKey(entry.key).title, - tableOfContents: toc, - includeBookTitle: false, + pdfLinkCandidates: sourceBook is PdfBook + ? pdfLinkCandidatesById[( + sourceBook.source.wireKey, + sourceBook.id, + )] + : null, ); + sourceLinkByNoteId[note.id] = link; + if (sourceBook is PdfBook || note.pdfAnchor != null) { + refByNoteId[note.id] = + 'עמוד ${note.pdfAnchor?.pageNumber ?? lineNumber}'; + continue; + } + // heRef כולל את כתובת השורה; תוכן העניינים עשוי להסתיים בפרק. + final dbRef = sourceBook is! TextBook || lineNumber < 1 + ? null + : await dbRefByLine.putIfAbsent( + lineNumber, + () => heRefFromDbLine(sourceBook, lineNumber - 1), + ); + if (!mounted) return null; + refByNoteId[note.id] = + dbRef ?? + personalNoteLocationRef( + note, + isPdf: false, + bookTitle: parsePersonalNotesBookKey(entry.key).title, + tableOfContents: await _tocFor(entry.key), + includeBookTitle: false, + ) ?? + (link == null ? null : 'שורה $lineNumber'); } } if (!mounted) return null; @@ -599,6 +741,7 @@ class _PersonalNotesManagerScreenState final blocks = _importExportService.buildWordExportBlocks( notes: selection.notes, locationRef: (note) => refByNoteId[note.id], + sourceLink: (note) => sourceLinkByNoteId[note.id], ); return WordExportService.createWordDocument( title: 'הערות אישיות', @@ -723,8 +866,10 @@ class _PersonalNotesManagerScreenState rootCategory, _getNotesCountForBook, ); - final totalNotesCount = - categoryCounts[rootCategory]! + _getMissingNotesCount(); + final totalNotesCount = _books.fold( + 0, + (sum, book) => sum + book.noteCount, + ); // שיטוח לרשימת שורות + ListView.builder (בנייה עצלה) — ספריית ההערות // דינמית ועלולה להיות ארוכה; בנייה מוקדמת של כל העץ הכבידה. @@ -1018,17 +1163,8 @@ class _PersonalNotesManagerScreenState .toList(); } - // Filter missing notes if not showing missing filter - final displayNotes = _selectedFilter == '__missing__' - ? filteredNotes - : filteredNotes; - - // Sort by book and line number - displayNotes.sort((a, b) { - final bookCompare = a.bookId.compareTo(b.bookId); - if (bookCompare != 0) return bookCompare; - return (a.note.lineNumber ?? 0).compareTo(b.note.lineNumber ?? 0); - }); + final displayNotes = filteredNotes + ..sort((a, b) => _sortOrder.compare(a.note, b.note)); if (displayNotes.isEmpty) { return const ToolEmptyState( @@ -1037,7 +1173,7 @@ class _PersonalNotesManagerScreenState ); } - // Group notes by book for headers - always show book names + // קיבוץ של ספרים סמוכים בלבד שומר על המיון הכרונולוגי בין כל הספרים. final groupedNotes = <_NotesGroup>[]; String? currentBookId; List<_NoteWithBook> currentGroup = []; @@ -1112,7 +1248,7 @@ class _PersonalNotesManagerScreenState ); } return FutureBuilder?>( - key: ValueKey((group.bookId, start)), + key: ValueKey((group.bookId, group.notes.first.note.id, start)), future: _tocFor(group.bookId), builder: (context, tocSnapshot) => Padding( padding: EdgeInsets.only(top: start == 0 ? 0 : spacing), @@ -1189,10 +1325,19 @@ class _PersonalNotesManagerScreenState List? tableOfContents, }) { final cs = Theme.of(context).colorScheme; - final hebrewDate = getHebrewDateFormattedAsString(note.updatedAt); + final displayedDate = + (_sortOrder.usesCreationDate ? note.createdAt : note.updatedAt) + .toLocal(); + final hebrewDate = getHebrewDateFormattedAsString(displayedDate); + final dateLabel = _sortOrder.usesCreationDate ? 'נכתב' : 'עודכן'; + final time = + '${displayedDate.hour.toString().padLeft(2, '0')}:' + '${displayedDate.minute.toString().padLeft(2, '0')}'; // שם הספר כבר מוצג ככותרת הקבוצה, לכן כאן מציגים רק את הדף/העמוד. final locationRef = isMissing ? null + : note.pdfAnchor != null + ? 'עמוד ${note.pdfAnchor!.pageNumber}' : personalNoteLocationRef( note, isPdf: false, @@ -1262,14 +1407,18 @@ class _PersonalNotesManagerScreenState runSpacing: 8, crossAxisAlignment: WrapCrossAlignment.center, children: [ - _InfoChip( - icon: OtzariaIcons.calendar_24_regular, - text: hebrewDate, - // גוון בהיר מזה של הכפתורים, כדי שהתאריך לא ייראה לחיץ. - backgroundColor: cs.secondaryContainer.withValues( - alpha: 0.45, + Tooltip( + message: '$dateLabel: $hebrewDate $time', + child: _InfoChip( + icon: OtzariaIcons.calendar_24_regular, + text: _sortOrder == PersonalNotesSortOrder.bookLocation + ? hebrewDate + : '$hebrewDate $time', + backgroundColor: cs.secondaryContainer.withValues( + alpha: 0.45, + ), + foregroundColor: cs.onSecondaryContainer, ), - foregroundColor: cs.onSecondaryContainer, ), if (isMissing && note.lastKnownLineNumber != null) _InfoChip( @@ -1297,7 +1446,9 @@ class _PersonalNotesManagerScreenState const SizedBox(height: 6), if (isMissing) SecondaryIconButton( - tooltip: 'מיקום מחדש', + tooltip: note.pdfAnchor != null + ? 'פתח PDF לשינוי המיקום' + : 'מיקום מחדש', icon: FluentIcons.location_24_regular, onPressed: () => _repositionMissing(note), ) @@ -1322,37 +1473,38 @@ class _PersonalNotesManagerScreenState } Future _editNote(PersonalNote note) async { - final result = await showDialog( + final library = context.read().state.library; + final categoryId = library == null + ? null + : personalNoteSourceBook(library, note)?.categoryId; + final draft = await PersonalNoteDraftService().loadDraft( + bookId: note.bookId, + categoryId: categoryId, + noteId: note.id, + ); + if (!mounted) return; + await showDialog( context: context, builder: (context) => PersonalNoteEditorDialog( title: 'ערוך הערה', - initialContent: note.content, - initialContentFormat: note.contentFormat, + initialContent: draft?.content ?? note.content, + initialContentFormat: draft?.contentFormat ?? note.contentFormat, referenceText: note.displayTitle, icon: FluentIcons.edit_24_regular, bookId: note.bookId, + categoryId: categoryId, + draftNoteId: note.id, linkableNotes: _collectAllNotes(), + onSave: (result) => _repository.persistNote( + bookId: note.bookId, + categoryId: categoryId, + noteId: note.id, + content: result.content, + contentPlain: result.contentPlain, + contentFormat: result.contentFormat, + ), ), ); - if (result == null) return; - - final trimmed = result.contentPlain.trim(); - if (trimmed.isEmpty) { - UiSnack.show(NotesMessages.emptyNoteNotSaved); - return; - } - - if (!mounted) return; - context.read().add( - UpdatePersonalNote( - bookId: note.bookId, - noteId: note.id, - content: result.content, - contentPlain: result.contentPlain, - contentFormat: result.contentFormat, - ), - ); - UiSnack.show(NotesMessages.noteUpdated); } Future _deleteNote(PersonalNote note) async { @@ -1377,6 +1529,10 @@ class _PersonalNotesManagerScreenState } Future _repositionMissing(PersonalNote note) async { + if (note.pdfAnchor != null) { + await _openNoteInBook(note); + return; + } final result = await showInputDialog( context: context, title: 'מיקום מחדש של הערה', @@ -1404,7 +1560,7 @@ class _PersonalNotesManagerScreenState } Future _openNoteInBook(PersonalNote note) async { - if (note.lineNumber == null) { + if (note.lineNumber == null && note.pdfAnchor == null) { UiSnack.show(NotesMessages.noteHasNoLocation); return; } @@ -1416,7 +1572,7 @@ class _PersonalNotesManagerScreenState return; } - final book = findBookForPersonalNotesKey(library, note.bookId); + final book = personalNoteSourceBook(library, note); if (book == null) { UiSnack.show( NotesMessages.bookNotFound( @@ -1426,6 +1582,23 @@ class _PersonalNotesManagerScreenState return; } + if (book is PdfBook) { + final coordinator = bookOpenCoordinatorOf(context); + final tab = + coordinator.buildTab( + book, + note.pdfAnchor?.pageNumber ?? note.lineNumber!, + '', + ignoreHistory: true, + ) + as PdfBookTab; + if (note.pdfAnchor case final anchor?) { + tab.requestPersonalNoteNavigation(anchor); + } + coordinator.openTab(tab, navigateToPositionIfReused: true); + return; + } + final lineIndex = (note.lineNumber! - 1).clamp(0, 1 << 30); final tabsBloc = context.read(); final previousSidebarTab = Settings.getValue( diff --git a/lib/personal_notes/widgets/inline_note_editor.dart b/lib/personal_notes/widgets/inline_note_editor.dart index 1ca15f71ce..7a71634e92 100644 --- a/lib/personal_notes/widgets/inline_note_editor.dart +++ b/lib/personal_notes/widgets/inline_note_editor.dart @@ -12,6 +12,7 @@ import 'package:otzaria/personal_notes/widgets/personal_note_editor.dart'; import 'package:otzaria/settings/services/safer_mode_guard.dart'; import 'package:otzaria/core/ui_snack.dart'; import 'package:otzaria/core/messages/notes_messages.dart'; +import 'package:otzaria/core/messages/text_book_messages.dart'; import 'package:otzaria/theme/app_surfaces.dart'; import 'package:otzaria/theme/app_tokens.dart'; import 'package:otzaria/widgets/controls/action_buttons.dart'; @@ -24,9 +25,11 @@ class InlineNoteEditor extends StatefulWidget { final String initialContent; final PersonalNoteContentFormat initialFormat; final int? draftLineNumber; + final PdfNoteAnchor? pdfAnchor; final String? draftNoteId; final List linkableNotes; - final ValueChanged onSave; + final PersonalNoteSaveCallback onSave; + final VoidCallback? onSaved; final VoidCallback onCancel; final ValueListenable? cancelRequest; @@ -39,9 +42,11 @@ class InlineNoteEditor extends StatefulWidget { this.initialContent = '', this.initialFormat = PersonalNoteContentFormat.plain, this.draftLineNumber, + this.pdfAnchor, this.draftNoteId, required this.linkableNotes, required this.onSave, + this.onSaved, required this.onCancel, this.cancelRequest, }); @@ -54,12 +59,15 @@ class _InlineNoteEditorState extends State { late final PersonalNoteEditorController _controller; late final PersonalNoteEditorResult _initialResult; late final StreamSubscription _documentChanges; + final GlobalKey _editorKey = GlobalKey(); final FocusNode _focusNode = FocusNode(debugLabel: 'InlineNoteEditor'); final ScrollController _scrollController = ScrollController(); final PersonalNoteDraftService _draftService = PersonalNoteDraftService(); Timer? _draftSaveTimer; Timer? _focusRetryTimer; bool _isDone = false; // מונע שמירת טיוטה אחרי שמירה/ביטול + bool _isSaving = false; + bool _isClosing = false; @override void initState() { @@ -72,7 +80,8 @@ class _InlineNoteEditorState extends State { ? widget.initialFormat : (widget.note?.contentFormat ?? PersonalNoteContentFormat.plain), ); - // משווים להערה השמורה, כדי שטיוטה משוחזרת תישאר שינוי שלא נשמר. + // _initialResult מייצג את המצב ה"נקי" לפני עריכה — לא תוכן הטיוטה. + // כך _persistDraft לא ימחק את הטיוטה כשה-Quill מפעיל notifyListeners בהתחלה. final originalController = buildPersonalNoteEditorController( initialContent: widget.note?.content ?? '', initialFormat: @@ -89,13 +98,25 @@ class _InlineNoteEditorState extends State { widget.cancelRequest?.addListener(_handleCancelRequest); // autoFocus לא תמיד תופס בפאנל שנפתח דינמית: ה-post-frame עלול לקדום לסוף // אנימציית הפתיחה, ולכן ניסיון נוסף אחרי שהיא מסתיימת. - WidgetsBinding.instance.addPostFrameCallback((_) { - if (mounted) _focusNode.requestFocus(); - }); + _scheduleFocusAfterLayout(); _focusRetryTimer = Timer(const Duration(milliseconds: 350), () { if (!mounted) return; - if (!_focusNode.hasFocus) _focusNode.requestFocus(); + if (!_focusNode.hasFocus) _scheduleFocusAfterLayout(); + }); + } + + void _scheduleFocusAfterLayout({bool retry = true}) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || _isSaving || _isDone) return; + final editor = _editorKey.currentState?.renderEditor; + if (editor != null && editor.attached && editor.hasSize) { + _focusNode.requestFocus(); + } else if (retry) { + // חשיפת פריט ברשימה וירטואלית נפרסת רק בפריים שאחרי jumpTo. + _scheduleFocusAfterLayout(retry: false); + } }); + WidgetsBinding.instance.ensureVisualUpdate(); } @override @@ -114,7 +135,7 @@ class _InlineNoteEditorState extends State { unawaited(_documentChanges.cancel()); widget.cancelRequest?.removeListener(_handleCancelRequest); // _persistDraft אוסף את התוכן לפני ה-await הראשון, גם לפני ה-debounce. - unawaited(_persistDraft()); + _persistDraftInBackground(); _controller.dispose(); _focusNode.dispose(); _scrollController.dispose(); @@ -122,19 +143,50 @@ class _InlineNoteEditorState extends State { } Future _handleSave() async { - // במצב סייפר, נדרוש סיסמה לפני שמירה - if (!await verifySaferModePassword(context) || !mounted) { - return; - } - + if (_isDone || _isSaving || _isClosing) return; final result = _controller.buildResult(); if (result.contentPlain.trim().isEmpty) { UiSnack.showError(NotesMessages.emptyNoteNotSaved); return; } - _isDone = true; - await _clearDraft(); - widget.onSave(result); + setState(() { + _isSaving = true; + _controller.quillController.readOnly = true; + }); + try { + if (!await verifySaferModePassword(context) || !mounted) return; + await widget.onSave(result); + _isDone = true; + _draftSaveTimer?.cancel(); + var clearedDraft = true; + try { + await _clearDraft(); + } catch (_) { + clearedDraft = false; + } + if (mounted) { + if (clearedDraft) { + UiSnack.showSuccess( + widget.note == null + ? NotesMessages.noteSaved + : NotesMessages.noteUpdated, + ); + } else { + UiSnack.showWarning(NotesMessages.noteSavedDraftCleanupFailed); + } + widget.onSaved?.call(); + } + } catch (error) { + if (mounted) UiSnack.showError(TextBookMessages.noteSaveError(error)); + } finally { + if (mounted && !_isDone) { + setState(() { + _isSaving = false; + _controller.quillController.readOnly = false; + }); + _scheduleFocusAfterLayout(); + } + } } void _scheduleDraftSave() { @@ -142,7 +194,15 @@ class _InlineNoteEditorState extends State { _draftSaveTimer?.cancel(); _draftSaveTimer = Timer( const Duration(milliseconds: 250), - () => unawaited(_persistDraft()), + _persistDraftInBackground, + ); + } + + void _persistDraftInBackground() { + unawaited( + _persistDraft().catchError((Object error) { + debugPrint('Personal note draft autosave failed: $error'); + }), ); } @@ -167,6 +227,7 @@ class _InlineNoteEditorState extends State { lineNumber: widget.draftLineNumber, noteId: widget.draftNoteId, referenceText: widget.referenceText ?? widget.note?.displayTitle, + pdfAnchor: widget.pdfAnchor ?? widget.note?.pdfAnchor, ), ); } @@ -183,29 +244,37 @@ class _InlineNoteEditorState extends State { categoryId: widget.categoryId, lineNumber: widget.draftLineNumber, noteId: widget.draftNoteId, + pdfAnchor: widget.pdfAnchor ?? widget.note?.pdfAnchor, ); } Future _handleCancel() async { - if (_isDone) return; - if (_hasUnsavedChanges()) { - final decision = await showNoteDraftDecisionDialog(context); - if (!mounted || - decision == null || - decision == NoteDraftDecision.cancel) { - return; - } - if (decision == NoteDraftDecision.saveDraft) { - await _persistDraft(); - if (!mounted) return; - _isDone = true; - widget.onCancel(); - return; + if (_isDone || _isSaving || _isClosing) return; + _isClosing = true; + try { + if (_hasUnsavedChanges()) { + final decision = await showNoteDraftDecisionDialog(context); + if (!mounted || + decision == null || + decision == NoteDraftDecision.cancel) { + return; + } + if (decision == NoteDraftDecision.saveDraft) { + await _persistDraft(); + if (!mounted) return; + _isDone = true; + widget.onCancel(); + return; + } } + await _clearDraft(); + _isDone = true; + if (mounted) widget.onCancel(); + } catch (error) { + if (mounted) UiSnack.showError(NotesMessages.noteDraftUpdateError(error)); + } finally { + _isClosing = false; } - _isDone = true; - await _clearDraft(); - if (mounted) widget.onCancel(); } bool _hasUnsavedChanges() { @@ -222,23 +291,36 @@ class _InlineNoteEditorState extends State { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - PersonalNoteEditorBody( - controller: _controller, - focusNode: _focusNode, - scrollController: _scrollController, - autofocus: true, - referenceText: widget.referenceText, - bookId: widget.bookId, - linkableNotes: widget.linkableNotes, - onSaveShortcut: _handleSave, + ExcludeFocus( + excluding: _isSaving, + child: AbsorbPointer( + absorbing: _isSaving, + child: PersonalNoteEditorBody( + controller: _controller, + editorKey: _editorKey, + focusNode: _focusNode, + scrollController: _scrollController, + autofocus: false, + referenceText: widget.referenceText, + bookId: widget.bookId, + linkableNotes: widget.linkableNotes, + onSaveShortcut: _handleSave, + ), + ), ), const SizedBox(height: AppTokens.spaceSM), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ - ActionButton.ghost(text: 'ביטול', onPressed: _handleCancel), + ActionButton.ghost( + text: 'ביטול', + onPressed: _isSaving ? null : _handleCancel, + ), const SizedBox(width: AppTokens.spaceSM), - ActionButton.recommended(text: 'שמור', onPressed: _handleSave), + ActionButton.recommended( + text: 'שמור', + onPressed: _isSaving ? null : _handleSave, + ), ], ), ], diff --git a/lib/personal_notes/widgets/note_delta_preview.dart b/lib/personal_notes/widgets/note_delta_preview.dart index 42fec8f2f0..00705c515e 100644 --- a/lib/personal_notes/widgets/note_delta_preview.dart +++ b/lib/personal_notes/widgets/note_delta_preview.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_quill/flutter_quill.dart' as quill; +import 'package:otzaria/personal_notes/widgets/personal_note_styles.dart'; /// מציג עיצובים נתמכים ב-RichText, לפי סגנונות Quill וללא קלט. class NoteDeltaPreview extends StatelessWidget { @@ -45,7 +46,7 @@ class NoteDeltaPreview extends StatelessWidget { @override Widget build(BuildContext context) { - final styles = quill.DefaultStyles.getInstance(context); + final styles = personalNoteStyles(context); final direction = Directionality.of(context); final children = [ for (final line in document.root.children.whereType()) diff --git a/lib/personal_notes/widgets/note_tile.dart b/lib/personal_notes/widgets/note_tile.dart index f6a8984172..d58ac8fb5f 100644 --- a/lib/personal_notes/widgets/note_tile.dart +++ b/lib/personal_notes/widgets/note_tile.dart @@ -10,7 +10,7 @@ import 'package:otzaria/personal_notes/widgets/inline_note_editor.dart'; class NoteTile extends StatefulWidget { final PersonalNote note; final VoidCallback? onTap; - final ValueChanged onSave; + final PersonalNoteSaveCallback onSave; final VoidCallback onDelete; final ValueChanged onLinkTap; final bool defaultExpanded; @@ -98,8 +98,16 @@ class _NoteTileState extends State { }); } - void _startInlineEdit() { + Future _startInlineEdit() async { + final draft = await _draftService.loadDraft( + bookId: widget.bookId, + categoryId: widget.categoryId, + noteId: widget.note.id, + ); + if (!mounted) return; setState(() { + _draftContent = draft?.content; + _draftFormat = draft?.contentFormat; _isExpanded = true; _isInlineEditing = true; }); @@ -115,9 +123,12 @@ class _NoteTileState extends State { _cancelRequest.value++; } - void _handleSave(PersonalNoteEditorResult result) { - widget.onSave(result); - _cancelInlineEdit(); + void _finishSave() { + setState(() { + _draftContent = null; + _draftFormat = null; + _isInlineEditing = false; + }); } @override @@ -144,7 +155,8 @@ class _NoteTileState extends State { initialFormat: _draftFormat ?? widget.note.contentFormat, draftNoteId: widget.note.id, linkableNotes: widget.linkableNotes, - onSave: _handleSave, + onSave: widget.onSave, + onSaved: _finishSave, onCancel: _cancelInlineEdit, cancelRequest: _cancelRequest, ), diff --git a/lib/personal_notes/widgets/notes_search_header.dart b/lib/personal_notes/widgets/notes_search_header.dart index 35bdfc167f..408b951be5 100644 --- a/lib/personal_notes/widgets/notes_search_header.dart +++ b/lib/personal_notes/widgets/notes_search_header.dart @@ -15,6 +15,9 @@ class NotesSearchHeader extends StatefulWidget { final int? categoryId; final bool isPdf; final List visibleLineIndices; + final List? visiblePdfPages; + final String? pdfDocumentId; + final bool includeUnidentifiedPdfAnchors; const NotesSearchHeader({ super.key, @@ -22,6 +25,9 @@ class NotesSearchHeader extends StatefulWidget { this.categoryId, this.isPdf = false, required this.visibleLineIndices, + this.visiblePdfPages, + this.pdfDocumentId, + this.includeUnidentifiedPdfAnchors = false, }); @override @@ -52,14 +58,28 @@ class _NotesSearchHeaderState extends State { Widget build(BuildContext context) { return BlocBuilder( builder: (context, state) { + final allNotes = filterPersonalNotes( + locatedNotes: state.locatedNotes, + missingNotes: state.missingNotes, + searchQuery: '', + showOnlyVisible: false, + visibleLineIndices: const [], + isPdf: widget.isPdf, + pdfDocumentId: widget.pdfDocumentId, + includeUnidentifiedPdfAnchors: widget.includeUnidentifiedPdfAnchors, + ); final totalNotes = - state.locatedNotes.length + state.missingNotes.length; + allNotes.locatedNotes.length + allNotes.missingNotes.length; final filtered = filterPersonalNotes( locatedNotes: state.locatedNotes, missingNotes: state.missingNotes, searchQuery: state.searchQuery, showOnlyVisible: state.showOnlyVisible, visibleLineIndices: widget.visibleLineIndices, + isPdf: widget.isPdf, + visiblePdfPages: widget.visiblePdfPages, + pdfDocumentId: widget.pdfDocumentId, + includeUnidentifiedPdfAnchors: widget.includeUnidentifiedPdfAnchors, ); final visibleNotes = filtered.locatedNotes.length + filtered.missingNotes.length; diff --git a/lib/personal_notes/widgets/personal_note_content_view.dart b/lib/personal_notes/widgets/personal_note_content_view.dart index f2cf91d30c..2e01978864 100644 --- a/lib/personal_notes/widgets/personal_note_content_view.dart +++ b/lib/personal_notes/widgets/personal_note_content_view.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'package:fluentui_system_icons/fluentui_system_icons.dart'; +import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_quill/flutter_quill.dart' as quill; @@ -9,6 +10,7 @@ import 'package:otzaria/core/ui_snack.dart'; import 'package:otzaria/personal_notes/models/personal_note.dart'; import 'package:otzaria/personal_notes/utils/note_link_detection.dart'; import 'package:otzaria/personal_notes/widgets/note_delta_preview.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_styles.dart'; import 'package:otzaria/widgets/dialogs/app_dialogs.dart'; import 'package:otzaria/widgets/misc/app_menu_exports.dart'; import 'package:otzaria/widgets/misc/app_selection_area.dart'; @@ -186,27 +188,44 @@ class _PersonalNoteContentViewState extends State { platform == TargetPlatform.android || platform == TargetPlatform.iOS; final useOwnMenu = widget.interactive && !hostHasOwnMenu && !useNativeTouchMenu; - Widget editor = quill.QuillEditor( - key: _editorKey, - controller: controller, - focusNode: _focusNode!, - scrollController: _scrollController!, - config: quill.QuillEditorConfig( - contextMenuBuilder: hostHasOwnMenu || useOwnMenu - ? (context, _) => const SizedBox.shrink() - : null, - autoFocus: false, - expands: false, - padding: EdgeInsets.zero, - showCursor: false, - enableInteractiveSelection: widget.interactive, - scrollable: false, - // בלי הרישום, Quill מוסיף https:// לפני otzaria:// בעת לחיצה. - customLinkPrefixes: const ['otzaria://', 'zayit://'], - onLaunchUrl: widget.onLinkTap, + Widget editor = Builder( + builder: (context) => quill.QuillEditor( + key: _editorKey, + controller: controller, + focusNode: _focusNode!, + scrollController: _scrollController!, + config: quill.QuillEditorConfig( + customStyles: personalNoteStyles(context), + contextMenuBuilder: hostHasOwnMenu || useOwnMenu + ? (context, _) => const SizedBox.shrink() + : null, + autoFocus: false, + expands: false, + padding: EdgeInsets.zero, + showCursor: false, + enableInteractiveSelection: widget.interactive, + scrollable: false, + // בלי הרישום, Quill מוסיף https:// לפני otzaria:// בעת לחיצה. + customLinkPrefixes: const ['otzaria://', 'zayit://'], + onLaunchUrl: widget.onLinkTap, + ), ), ); + if (widget.interactive) { + // Quill אינו מבקש פוקוס בגרירת בחירה בעכבר. בלעדיו Ctrl+C מגיע + // לקורא שהיה ממוקד קודם, אף שהבחירה המוצגת נמצאת בגוף ההערה. + editor = Listener( + onPointerUp: (event) { + if (event.kind == PointerDeviceKind.mouse && + !_focusNode!.hasFocus) { + _focusNode!.requestFocus(); + } + }, + child: editor, + ); + } + if (useOwnMenu) { editor = AppContextMenuRegion( menuBuilder: (_, _) { diff --git a/lib/personal_notes/widgets/personal_note_editor.dart b/lib/personal_notes/widgets/personal_note_editor.dart index 24c9822154..4d49aff236 100644 --- a/lib/personal_notes/widgets/personal_note_editor.dart +++ b/lib/personal_notes/widgets/personal_note_editor.dart @@ -10,6 +10,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_quill/flutter_quill.dart' as quill; import 'package:otzaria/personal_notes/models/personal_note.dart'; import 'package:otzaria/personal_notes/widgets/personal_note_link_dialog.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_styles.dart'; import 'package:otzaria/shortcuts/shortcut_helper.dart'; import 'package:otzaria/widgets/misc/app_menu_exports.dart'; @@ -101,6 +102,10 @@ class PersonalNoteEditorResult { }); } +/// ההשלמה מציינת שהכתיבה הצליחה; כשל משאיר את העורך פתוח עם הטיוטה. +typedef PersonalNoteSaveCallback = + FutureOr Function(PersonalNoteEditorResult result); + /// בעל בקר Quill והמסמך שלו; יוצר העורך משחרר אותם ב-[dispose]. class PersonalNoteEditorController { final quill.QuillController quillController; @@ -122,6 +127,7 @@ class PersonalNoteEditorController { class PersonalNoteEditorBody extends StatefulWidget { final PersonalNoteEditorController controller; + final GlobalKey? editorKey; final FocusNode focusNode; final ScrollController scrollController; final bool autofocus; @@ -130,10 +136,12 @@ class PersonalNoteEditorBody extends StatefulWidget { final List linkableNotes; final String? bookId; final VoidCallback? onSaveShortcut; + final VoidCallback? onCancelShortcut; const PersonalNoteEditorBody({ super.key, required this.controller, + this.editorKey, required this.focusNode, required this.scrollController, required this.autofocus, @@ -142,6 +150,7 @@ class PersonalNoteEditorBody extends StatefulWidget { this.hintText, this.bookId, this.onSaveShortcut, + this.onCancelShortcut, }); @override @@ -380,8 +389,7 @@ class _PersonalNoteEditorBodyState extends State { // Ctrl+Enter (במק Cmd+Enter) — קיצור השמירה המומלץ. ShortcutHelper.activatorFromShortcut('ctrl+enter')!: widget.onSaveShortcut!, - // Alt+Enter — לתאימות לאחור; ב-Windows הוא משמיע - // "דינג" מערכת, ולכן הקיצור הראשי הוא Ctrl+Enter. + // Alt+Enter — לתאימות לאחור. const SingleActivator( LogicalKeyboardKey.enter, alt: true, @@ -409,13 +417,26 @@ class _PersonalNoteEditorBodyState extends State { focusNode: widget.focusNode, scrollController: widget.scrollController, config: quill.QuillEditorConfig( + editorKey: widget.editorKey, + customStyles: personalNoteStyles(context), autoFocus: widget.autofocus, expands: false, padding: const EdgeInsets.all(12), placeholder: widget.hintText ?? 'כתוב כאן... (${ShortcutHelper.formatShortcutForDisplay('ctrl+enter')} לשמירה)', - customShortcuts: _rtlArrowShortcuts, + customShortcuts: widget.onCancelShortcut == null + ? _rtlArrowShortcuts + : { + ..._rtlArrowShortcuts, + // Quill דורס התאמת SingleActivator בקיצור המובנה. + // LogicalKeySet משמר את קדימות קיצור הסגירה. + LogicalKeySet( + LogicalKeyboardKey.escape, + ): VoidCallbackIntent( + widget.onCancelShortcut!, + ), + }, 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 69af905b6c..a5d8bb8c8e 100644 --- a/lib/personal_notes/widgets/personal_note_editor_dialog.dart +++ b/lib/personal_notes/widgets/personal_note_editor_dialog.dart @@ -2,6 +2,9 @@ import 'package:fluentui_system_icons/fluentui_system_icons.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:otzaria/core/focus_repository.dart'; +import 'package:otzaria/core/messages/notes_messages.dart'; +import 'package:otzaria/core/messages/text_book_messages.dart'; +import 'package:otzaria/core/ui_snack.dart'; import 'package:otzaria/personal_notes/models/personal_note.dart'; import 'package:otzaria/personal_notes/services/personal_note_draft_service.dart'; import 'package:otzaria/personal_notes/widgets/note_draft_decision_dialog.dart'; @@ -22,6 +25,9 @@ class PersonalNoteEditorDialog extends StatefulWidget { final int? categoryId; final List linkableNotes; final int? draftLineNumber; + final String? draftNoteId; + final PdfNoteAnchor? pdfAnchor; + final Future Function(PersonalNoteEditorResult)? onSave; const PersonalNoteEditorDialog({ super.key, @@ -34,6 +40,9 @@ class PersonalNoteEditorDialog extends StatefulWidget { this.categoryId, this.linkableNotes = const [], this.draftLineNumber, + this.draftNoteId, + this.pdfAnchor, + this.onSave, }); @override @@ -50,6 +59,8 @@ class _PersonalNoteEditorDialogState extends State late final ScrollController _scrollController; late final PersonalNoteEditorResult _initialResult; final PersonalNoteDraftService _draftService = PersonalNoteDraftService(); + bool _isSaving = false; + bool _isClosing = false; @override void initState() { @@ -92,6 +103,7 @@ class _PersonalNoteEditorDialogState extends State } if (result == NoteDraftDecision.discard) { + await _clearDraftIfPossible(); return true; } @@ -99,54 +111,96 @@ class _PersonalNoteEditorDialogState extends State } Future _handleCancel() async { - if (await _confirmClose()) { - if (mounted) { - Navigator.of(context).pop(); - } + if (_isSaving || _isClosing) return; + _isClosing = true; + try { + if (await _confirmClose() && mounted) Navigator.of(context).pop(); + } catch (error) { + if (mounted) UiSnack.showError(NotesMessages.noteDraftUpdateError(error)); + } finally { + _isClosing = false; } } - void _submit() async { - // במצב סייפר, נדרוש סיסמה לפני שמירה - if (!await verifySaferModePassword(context) || !mounted) { - return; - } - + Future _submit() async { + if (_isSaving || _isClosing) return; final result = _editorController.buildResult(); - if (result.contentPlain.trim().isEmpty) { - return; + if (result.contentPlain.trim().isEmpty) return; + setState(() { + _isSaving = true; + _editorController.quillController.readOnly = true; + }); + var completed = false; + try { + if (!await verifySaferModePassword(context) || !mounted) return; + await widget.onSave?.call(result); + if (widget.onSave == null) { + await _clearDraftIfPossible(); + } else { + // ההערה כבר נכתבה. כשל בניקוי טיוטה אינו כשל שמירה, ואסור + // להשאיר כפתור שמירה פעיל שייצור עותק נוסף של אותה הערה. + try { + await _clearDraftIfPossible(); + if (mounted) UiSnack.showSuccess(NotesMessages.noteSaved); + } catch (_) { + if (mounted) { + UiSnack.showWarning(NotesMessages.noteSavedDraftCleanupFailed); + } + } + } + completed = true; + if (mounted) Navigator.of(context).pop(result); + } catch (error) { + if (mounted) { + UiSnack.showError(TextBookMessages.noteSaveError(error)); + } + } finally { + if (mounted && !completed) { + setState(() { + _isSaving = false; + _editorController.quillController.readOnly = false; + }); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) _textFieldFocusNode.requestFocus(); + }); + } } - _clearDraftIfPossible(); - Navigator.of(context).pop(result); } Future _saveDraftIfPossible() async { final bookId = widget.bookId; - final lineNumber = widget.draftLineNumber; - if (bookId == null || lineNumber == null) return; + final noteId = widget.draftNoteId; + final lineNumber = noteId == null ? widget.draftLineNumber : null; + if (bookId == null || (lineNumber == null && noteId == null)) return; final result = _editorController.buildResult(); if (result.contentPlain.trim().isEmpty) return; await _draftService.saveDraft( bookId: bookId, categoryId: widget.categoryId, lineNumber: lineNumber, + noteId: noteId, draft: PersonalNoteDraft( content: result.content, contentPlain: result.contentPlain, contentFormat: result.contentFormat, updatedAt: DateTime.now(), + referenceText: widget.referenceText, + pdfAnchor: widget.pdfAnchor, ), ); } Future _clearDraftIfPossible() async { final bookId = widget.bookId; - final lineNumber = widget.draftLineNumber; - if (bookId == null || lineNumber == null) return; + final noteId = widget.draftNoteId; + final lineNumber = noteId == null ? widget.draftLineNumber : null; + if (bookId == null || (lineNumber == null && noteId == null)) return; await _draftService.clearDraft( bookId: bookId, categoryId: widget.categoryId, lineNumber: lineNumber, + noteId: noteId, + pdfAnchor: widget.pdfAnchor, ); } @@ -158,6 +212,11 @@ class _PersonalNoteEditorDialogState extends State return KeyEventResult.ignored; } + if (event.logicalKey == LogicalKeyboardKey.escape) { + _handleCancel(); + return KeyEventResult.handled; + } + // Ctrl+Enter (במק Cmd+Enter) / Alt+Enter (תאימות לאחור) - // שליחת הטופס מכל מקום if (ShortcutHelper.matchesShortcut(event, 'ctrl+enter') || @@ -191,12 +250,6 @@ class _PersonalNoteEditorDialogState extends State } } - // Escape - ביטול - if (event.logicalKey == LogicalKeyboardKey.escape) { - _handleCancel(); - return KeyEventResult.handled; - } - return KeyEventResult.ignored; }, child: PopScope( @@ -226,6 +279,7 @@ class _PersonalNoteEditorDialogState extends State title: widget.title, compact: true, onClose: _handleCancel, + closeEnabled: !_isSaving, ), Flexible( child: SingleChildScrollView( @@ -235,15 +289,22 @@ class _PersonalNoteEditorDialogState extends State AppTokens.spaceLG, 0, ), - child: PersonalNoteEditorBody( - controller: _editorController, - focusNode: _textFieldFocusNode, - scrollController: _scrollController, - autofocus: true, - referenceText: widget.referenceText, - bookId: widget.bookId, - linkableNotes: widget.linkableNotes, - onSaveShortcut: _submit, + child: ExcludeFocus( + excluding: _isSaving, + child: AbsorbPointer( + absorbing: _isSaving, + child: PersonalNoteEditorBody( + controller: _editorController, + focusNode: _textFieldFocusNode, + scrollController: _scrollController, + autofocus: true, + referenceText: widget.referenceText, + bookId: widget.bookId, + linkableNotes: widget.linkableNotes, + onSaveShortcut: _submit, + onCancelShortcut: _handleCancel, + ), + ), ), ), ), @@ -255,13 +316,13 @@ class _PersonalNoteEditorDialogState extends State ActionButton.neutral( focusNode: _cancelFocusNode, text: 'ביטול', - onPressed: _handleCancel, + onPressed: _isSaving ? null : _handleCancel, ), const SizedBox(width: AppTokens.spaceSM), ActionButton.recommended( focusNode: _saveFocusNode, text: 'שמור', - onPressed: _submit, + onPressed: _isSaving ? null : _submit, ), ], ), diff --git a/lib/personal_notes/widgets/personal_note_styles.dart b/lib/personal_notes/widgets/personal_note_styles.dart new file mode 100644 index 0000000000..4c190abbd1 --- /dev/null +++ b/lib/personal_notes/widgets/personal_note_styles.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_quill/flutter_quill.dart' as quill; + +/// ריווח משותף לעריכה ולתצוגה, בלי לשנות את העיצוב השמור בהערה. +quill.DefaultStyles personalNoteStyles(BuildContext context) { + final styles = quill.DefaultStyles.getInstance(context); + return styles.merge( + quill.DefaultStyles( + paragraph: styles.paragraph!.copyWith( + style: styles.paragraph!.style.copyWith(height: 1.5), + ), + lists: styles.lists!.copyWith( + style: styles.lists!.style.copyWith(height: 1.5), + ), + quote: styles.quote!.copyWith( + style: styles.quote!.style.copyWith(height: 1.5), + ), + placeHolder: styles.placeHolder!.copyWith( + style: styles.placeHolder!.style.copyWith(height: 1.5), + ), + ), + ); +} diff --git a/lib/personal_notes/widgets/personal_notes_export_dialog.dart b/lib/personal_notes/widgets/personal_notes_export_dialog.dart index a31d48d9a5..01096fa81d 100644 --- a/lib/personal_notes/widgets/personal_notes_export_dialog.dart +++ b/lib/personal_notes/widgets/personal_notes_export_dialog.dart @@ -188,14 +188,20 @@ class _PersonalNotesExportDialogState extends State { itemBuilder: (context, index) { final note = filteredNotes[index]; final selected = _manualSelection[note.id] ?? false; + final bookTitle = parsePersonalNotesBookKey( + note.bookId, + ).title; + final location = note.displayTitle?.trim(); + final title = + location == null || + location.isEmpty || + location == bookTitle + ? bookTitle + : '$bookTitle — $location'; return CheckboxListTile( shape: Border(bottom: listDialogRowDivider(context)), value: selected, - title: Text( - note.displayTitle?.isNotEmpty == true - ? note.displayTitle! - : note.bookId, - ), + title: Text(title), subtitle: Text( note.contentPlain, maxLines: 1, diff --git a/lib/personal_notes/widgets/personal_notes_sidebar.dart b/lib/personal_notes/widgets/personal_notes_sidebar.dart index b0a3d8e5db..7b77b4f050 100644 --- a/lib/personal_notes/widgets/personal_notes_sidebar.dart +++ b/lib/personal_notes/widgets/personal_notes_sidebar.dart @@ -21,6 +21,7 @@ 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/bloc/personal_notes_state.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_note_content_view.dart'; import 'package:otzaria/personal_notes/widgets/personal_note_editor.dart'; import 'package:otzaria/personal_notes/widgets/notes_search_header.dart'; @@ -37,12 +38,17 @@ import 'package:otzaria/settings/settings_exports.dart'; class PersonalNotesSidebar extends StatefulWidget { final String bookId; final int? categoryId; + final PersonalNotesRepository? repository; /// [note] — ההערה שאליה מנווטים, לגלילה אל המילים שעליהן נכתבה. final void Function(int lineNumber, {PersonalNote? note}) onNavigateToLine; final bool isPdf; final List? visibleLineIndices; + final List? visiblePdfPages; + final String? pdfDocumentId; + final bool includeUnidentifiedPdfAnchors; final int? focusLineNumber; + final Future Function(PersonalNote)? onReanchorNote; /// ה-outline של ה-PDF לחישוב כתובת המיקום של כל הערה. רלוונטי רק כש-[isPdf]. /// מועבר כ-listenable כי ה-outline עשוי להיטען אחרי בניית הפאנל. @@ -55,10 +61,15 @@ class PersonalNotesSidebar extends StatefulWidget { super.key, required this.bookId, this.categoryId, + this.repository, required this.onNavigateToLine, this.isPdf = false, this.visibleLineIndices, + this.visiblePdfPages, + this.pdfDocumentId, + this.includeUnidentifiedPdfAnchors = false, this.focusLineNumber, + this.onReanchorNote, this.pdfOutline, this.footer, }); @@ -72,9 +83,14 @@ class PersonalNotesSidebarState extends State @override bool get wantKeepAlive => true; final PersonalNoteDraftService _draftService = PersonalNoteDraftService(); + late final PersonalNotesRepository _notesRepository = + widget.repository ?? PersonalNotesRepository(); final ValueNotifier> _visibleLineIndices = ValueNotifier(const []); final ValueNotifier _newNoteCancelRequest = ValueNotifier(0); final ItemScrollController _itemScrollController = ItemScrollController(); + (String, int?, int)? _revealedExpansion; + (String, int?, int)? _revealedDraft; + int _revealGeneration = 0; @override void initState() { @@ -141,7 +157,9 @@ class PersonalNotesSidebarState extends State void didUpdateWidget(covariant PersonalNotesSidebar oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.bookId != widget.bookId || - oldWidget.categoryId != widget.categoryId) { + oldWidget.categoryId != widget.categoryId || + oldWidget.isPdf != widget.isPdf || + oldWidget.pdfDocumentId != widget.pdfDocumentId) { context.read().add(const CancelCreatingPersonalNote()); _loadTarget(); _restorePendingNewNoteDraftIfNeeded(); @@ -183,28 +201,40 @@ class PersonalNotesSidebarState extends State Future _restorePendingNewNoteDraftIfNeeded() async { final bloc = context.read(); + final bookId = widget.bookId; + final categoryId = widget.categoryId; + final pdfDocumentId = widget.pdfDocumentId; + final includeUnidentifiedPdfAnchors = widget.includeUnidentifiedPdfAnchors; + final isPdf = widget.isPdf; final draft = await _draftService.loadLatestNewNoteDraft( - bookId: widget.bookId, - categoryId: widget.categoryId, + bookId: bookId, + categoryId: categoryId, + includePdfAnchors: isPdf, + pdfDocumentId: pdfDocumentId, + includeUnidentifiedPdfAnchors: includeUnidentifiedPdfAnchors, ); - if (!mounted || draft == null || draft.lineNumber == null) { + if (!mounted || + widget.bookId != bookId || + widget.categoryId != categoryId || + widget.pdfDocumentId != pdfDocumentId || + widget.includeUnidentifiedPdfAnchors != includeUnidentifiedPdfAnchors || + widget.isPdf != isPdf || + draft == null || + draft.lineNumber == null) { return; } final currentState = bloc.state; - final sameDraftAlreadyLoaded = - currentState.isCreatingNewNote && - currentState.newNoteBookId == widget.bookId && - currentState.newNoteLineNumber == draft.lineNumber && - currentState.newNoteInitialContent == draft.content && - currentState.newNoteInitialFormat == draft.contentFormat; - if (sameDraftAlreadyLoaded) { + // ניווט או יצירה מפורשים גוברים על שחזור אוטומטי, גם אם הגיעו בזמן הטעינה. + if (widget.focusLineNumber != null || + currentState.expandRequestLineNumber != null || + currentState.isCreatingNewNote) { return; } bloc.add( StartCreatingPersonalNote( - bookId: widget.bookId, + bookId: bookId, lineNumber: draft.lineNumber!, referenceText: draft.referenceText, selectedText: currentState.newNoteSelectedText, @@ -212,6 +242,7 @@ class PersonalNotesSidebarState extends State sourceSelectedText: currentState.newNoteSourceSelectedText, sourceSelectionOffset: currentState.newNoteSourceSelectionOffset, punctuationHidden: currentState.newNotePunctuationHidden, + pdfAnchor: draft.pdfAnchor, initialContent: draft.content, initialFormat: draft.contentFormat, ), @@ -223,30 +254,26 @@ class PersonalNotesSidebarState extends State context.read().add(const CancelCreatingPersonalNote()); } - void _saveNewNote(PersonalNoteEditorResult result) { - final bloc = context.read(); - final lineNumber = bloc.state.newNoteLineNumber; - final selectedText = bloc.state.newNoteSelectedText; - final selectionColumn = bloc.state.newNoteSelectionColumn; - - if (lineNumber == null) return; - - bloc.add( - AddPersonalNote( - bookId: widget.bookId, - lineNumber: lineNumber, - content: result.content, - contentPlain: result.contentPlain, - contentFormat: result.contentFormat, - selectedText: selectedText?.trim(), - selectionColumn: selectionColumn, - sourceSelectedText: bloc.state.newNoteSourceSelectedText, - sourceSelectionOffset: bloc.state.newNoteSourceSelectionOffset, - punctuationHidden: bloc.state.newNotePunctuationHidden, - ), + Future _saveNewNote(PersonalNoteEditorResult result) async { + final state = context.read().state; + final lineNumber = state.newNoteLineNumber; + if (lineNumber == null || state.newNoteBookId != widget.bookId) { + throw StateError('מיקום ההערה אינו זמין'); + } + await _notesRepository.createNote( + bookId: widget.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, + categoryId: widget.categoryId, ); - - UiSnack.showSuccess(NotesMessages.noteSaved); } @override @@ -254,7 +281,18 @@ class PersonalNotesSidebarState extends State super.build(context); final hasTextBookBloc = _hasTextBookBloc; - final child = BlocBuilder( + final child = BlocConsumer( + listenWhen: (previous, current) => + _isMyDraft(previous) && + _isMyDraft(current) && + previous.newNoteRequestToken != current.newNoteRequestToken, + listener: (context, state) { + if (_itemScrollController.isAttached) { + // חושפים עורך קיים לפני בנייתו מחדש: Quill מעדכן IME בסוף הפריים, + // גם כשפריט שמור מחוץ למסך עדיין לא קיבל פריסה חדשה. + _itemScrollController.jumpTo(index: 0); + } + }, buildWhen: (previous, current) { // מעבר ישיר בין טיוטות של ספרים צריך לרענן את שתי החלוניות. final wasMyDraft = @@ -287,6 +325,10 @@ class PersonalNotesSidebarState extends State categoryId: widget.categoryId, isPdf: widget.isPdf, visibleLineIndices: visibleLineIndices, + visiblePdfPages: widget.visiblePdfPages, + pdfDocumentId: widget.pdfDocumentId, + includeUnidentifiedPdfAnchors: + widget.includeUnidentifiedPdfAnchors, ), const Divider(height: 1), Expanded( @@ -437,13 +479,18 @@ class PersonalNotesSidebarState extends State searchQuery: state.searchQuery, showOnlyVisible: state.showOnlyVisible, visibleLineIndices: visibleLineIndices, + isPdf: widget.isPdf, + visiblePdfPages: widget.visiblePdfPages, + pdfDocumentId: widget.pdfDocumentId, + includeUnidentifiedPdfAnchors: widget.includeUnidentifiedPdfAnchors, ); // רשימה משותפת לכל הכרטיסים: העתקה לכל כרטיס ריבועית במספר ההערות. final linkableNotes = [...state.locatedNotes, ...state.missingNotes]; final items = []; // הטיוטה מזוהה לפי newNoteBookId; state.bookId הוא הספר האחרון שנטען. - if (state.isCreatingNewNote && state.newNoteBookId == widget.bookId) { + final hasNewEditor = _isMyDraft(state); + if (hasNewEditor) { items.add(_buildNewNoteEditor(context, state)); } @@ -452,6 +499,7 @@ class PersonalNotesSidebarState extends State items.addAll( filtered.locatedNotes.map( (note) => NoteTile( + key: ValueKey(note.id), note: note, onTap: () => widget.onNavigateToLine(note.lineNumber!, note: note), onSave: (result) => _saveInline(context, note, result), @@ -464,14 +512,14 @@ class PersonalNotesSidebarState extends State tableOfContents: tableOfContents, pdfOutline: pdfOutline, ), - expandToken: note.lineNumber == state.expandRequestLineNumber + expandToken: _matchesExpansion(note, state) ? state.expandRequestToken : null, bookId: widget.bookId, categoryId: widget.categoryId, linkableNotes: linkableNotes, extraAction: IconButton( - tooltip: 'שנה שיוך לשורה נבחרת', + tooltip: widget.isPdf ? 'שנה מיקום בדף' : 'שנה שיוך לשורה נבחרת', icon: const Icon(FluentIcons.pin_24_regular, size: 18), iconSize: 18, padding: const EdgeInsets.all(8), @@ -503,13 +551,18 @@ class PersonalNotesSidebarState extends State items.addAll( filtered.missingNotes.map( (note) => NoteTile( + key: ValueKey(note.id), note: note, onTap: () => _reposition(context, note), onSave: (result) => _saveInline(context, note, result), onDelete: () => _confirmDelete(context, note), onLinkTap: (url) => _handleNoteLinkTap(context, url), defaultExpanded: defaultExpanded, + expandToken: _matchesExpansion(note, state) + ? state.expandRequestToken + : null, bookId: widget.bookId, + categoryId: widget.categoryId, linkableNotes: linkableNotes, backgroundColor: Theme.of( context, @@ -565,6 +618,12 @@ class PersonalNotesSidebarState extends State ); } + _revealRequestedItem( + state, + filtered.locatedNotes, + filtered.missingNotes, + hasNewEditor, + ); return ScrollablePositionedListScrollbar( scrollController: _itemScrollController, itemCount: items.length, @@ -576,6 +635,77 @@ class PersonalNotesSidebarState extends State ); } + bool _matchesExpansion(PersonalNote note, PersonalNotesState state) { + if (state.expandRequestPdfAnchor case final anchor?) { + return note.pdfAnchor == anchor; + } + return note.lineNumber == state.expandRequestLineNumber && + state.expandRequestLineNumber != null; + } + + void _revealRequestedItem( + PersonalNotesState state, + List locatedNotes, + List missingNotes, + bool hasNewEditor, + ) { + final generation = ++_revealGeneration; + if (state.isLoading) return; + final expansion = ( + widget.bookId, + widget.categoryId, + state.expandRequestToken, + ); + final draft = hasNewEditor + ? (widget.bookId, widget.categoryId, state.newNoteRequestToken) + : null; + if (draft == null) _revealedDraft = null; + final revealExpansion = + state.expandRequestLineNumber != null && + expansion != _revealedExpansion; + final revealDraft = + !revealExpansion && draft != null && draft != _revealedDraft; + if (!revealDraft && !revealExpansion) return; + var noteIndex = locatedNotes.indexWhere( + (note) => _matchesExpansion(note, state), + ); + if (noteIndex < 0) { + final missingIndex = missingNotes.indexWhere( + (note) => _matchesExpansion(note, state), + ); + if (missingIndex >= 0) { + // כשיש גם הערות ממוקמות, כותרת ההערות החסרות תופסת פריט נוסף. + noteIndex = + locatedNotes.length + + (locatedNotes.isNotEmpty ? 1 : 0) + + missingIndex; + } + } + if (!revealDraft && noteIndex < 0) return; + final index = revealDraft ? 0 : noteIndex + (hasNewEditor ? 1 : 0); + + // הפריט עשוי להיות מחוץ למסך או להגיע מטעינה אסינכרונית; גוללים אחרי הבנייה. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || + generation != _revealGeneration || + !_itemScrollController.isAttached) { + return; + } + final current = context.read().state; + if (!identical(current, state) || + widget.bookId != expansion.$1 || + widget.categoryId != expansion.$2 || + (revealDraft + ? draft == _revealedDraft + : expansion == _revealedExpansion)) { + return; + } + _itemScrollController.jumpTo(index: index); + _revealedExpansion = expansion; + _revealedDraft = draft; + }); + } + Widget _buildNewNoteEditor(BuildContext context, PersonalNotesState state) { return InlineNoteEditorCard( icon: FluentIcons.note_add_24_regular, @@ -585,11 +715,12 @@ class PersonalNotesSidebarState extends State // דרך העורך, כדי שישאל על שינויים שלא נשמרו (issue #1303). onCancelPressed: () => _newNoteCancelRequest.value++, editor: InlineNoteEditor( - key: ValueKey( - 'new-note-${state.newNoteLineNumber}-' - '${state.newNoteInitialFormat?.name}-' - '${state.newNoteInitialContent.hashCode}', - ), + key: ValueKey(( + widget.bookId, + widget.categoryId, + state.newNoteLineNumber, + state.newNotePdfAnchor, + )), referenceText: state.newNoteReferenceText, bookId: widget.bookId, categoryId: widget.categoryId, @@ -597,29 +728,45 @@ class PersonalNotesSidebarState extends State initialFormat: state.newNoteInitialFormat ?? PersonalNoteContentFormat.plain, draftLineNumber: state.newNoteLineNumber, + pdfAnchor: state.newNotePdfAnchor, linkableNotes: [...state.locatedNotes, ...state.missingNotes], cancelRequest: _newNoteCancelRequest, onSave: _saveNewNote, + onSaved: () { + final current = context.read().state; + if (current.newNoteRequestToken == state.newNoteRequestToken && + current.newNoteBookId == widget.bookId) { + _cancelNewNote(); + } + }, onCancel: _cancelNewNote, ), ); } - void _saveInline( - BuildContext context, + bool _isMyDraft(PersonalNotesState state) { + if (!state.isCreatingNewNote || state.newNoteBookId != widget.bookId) { + return false; + } + final anchor = state.newNotePdfAnchor; + if (anchor == null) return true; + if (!widget.isPdf) return false; + if (anchor.documentId == null) return widget.includeUnidentifiedPdfAnchors; + return anchor.documentId == widget.pdfDocumentId; + } + + Future _saveInline( + BuildContext _, PersonalNote note, PersonalNoteEditorResult result, - ) { - if (!mounted) return; - if (result.contentPlain.trim().isEmpty) return; - context.read().add( - UpdatePersonalNote( - bookId: widget.bookId, - noteId: note.id, - content: result.content, - contentPlain: result.contentPlain, - contentFormat: result.contentFormat, - ), + ) async { + await _notesRepository.persistNote( + bookId: widget.bookId, + noteId: note.id, + content: result.content, + contentPlain: result.contentPlain, + contentFormat: result.contentFormat, + categoryId: widget.categoryId, ); } @@ -643,6 +790,10 @@ class PersonalNotesSidebarState extends State } Future _reposition(BuildContext context, PersonalNote note) async { + if (widget.onReanchorNote case final reanchor?) { + await reanchor(note); + return; + } final bloc = context.read(); final result = await showInputDialog( context: context, @@ -665,6 +816,7 @@ class PersonalNotesSidebarState extends State bookId: widget.bookId, noteId: note.id, lineNumber: newLine, + categoryId: widget.categoryId, ), ); } @@ -680,6 +832,7 @@ class PersonalNotesSidebarState extends State bookId: widget.bookId, noteId: note.id, lineNumber: selectedLineNumber, + categoryId: widget.categoryId, ), ); UiSnack.show(NotesMessages.noteAssignedToLine(selectedLineNumber)); @@ -690,6 +843,10 @@ class PersonalNotesSidebarState extends State PersonalNote note, int? selectedLineNumber, ) async { + if (widget.onReanchorNote case final reanchor?) { + await reanchor(note); + return; + } final bloc = context.read(); if (selectedLineNumber != null) { final choice = await showSelectionDialog( diff --git a/lib/printing/print_content_models.dart b/lib/printing/print_content_models.dart index 1829883b1f..adfdf9a158 100644 --- a/lib/printing/print_content_models.dart +++ b/lib/printing/print_content_models.dart @@ -29,12 +29,14 @@ class PrintBlock { final String text; final int? headingLevel; final List footnotes; + final String? sourceLink; const PrintBlock({ required this.kind, required this.text, this.headingLevel, this.footnotes = const [], + this.sourceLink, }); Map toJson() { @@ -43,6 +45,7 @@ class PrintBlock { 'text': text, 'headingLevel': headingLevel, 'footnotes': footnotes.map((footnote) => footnote.toJson()).toList(), + if (sourceLink != null) 'sourceLink': sourceLink, }; } @@ -52,6 +55,7 @@ class PrintBlock { kind: PrintBlockKind.values.byName(json['kind']! as String), text: json['text'] as String? ?? '', headingLevel: json['headingLevel'] as int?, + sourceLink: json['sourceLink'] as String?, footnotes: footnotesJson .whereType>() .map(PrintFootnote.fromJson) diff --git a/lib/printing/word_export_service.dart b/lib/printing/word_export_service.dart index 650d2c6eab..848c4d4aba 100644 --- a/lib/printing/word_export_service.dart +++ b/lib/printing/word_export_service.dart @@ -23,6 +23,7 @@ class WordExportService { } final footnotes = <_WordFootnote>[]; + final hyperlinks = {}; final basePt = fontSize ?? 13.0; final fontName = _wordFontNames[fontFamily] ?? fontFamily; @@ -38,6 +39,7 @@ class WordExportService { title: title, blocks: blocks, footnotes: footnotes, + hyperlinks: hyperlinks, format: format, isLandscape: isLandscape, pageMargin: pageMargin, @@ -58,7 +60,12 @@ class WordExportService { ..addFile(xmlFile('word/footnotes.xml', _buildFootnotesXml(footnotes))) ..addFile(xmlFile('word/header1.xml', _buildHeaderXml(title))) ..addFile(xmlFile('word/footer1.xml', _footerXml)) - ..addFile(xmlFile('word/_rels/document.xml.rels', _documentRelsXml)); + ..addFile( + xmlFile( + 'word/_rels/document.xml.rels', + _buildDocumentRelsXml(hyperlinks), + ), + ); final bytes = ZipEncoder().encode(archive); return Uint8List.fromList(bytes); @@ -68,6 +75,7 @@ class WordExportService { required String title, required List blocks, required List<_WordFootnote> footnotes, + required Map hyperlinks, required PdfPageFormat format, required bool isLandscape, required double pageMargin, @@ -85,7 +93,15 @@ class WordExportService { ..write(_paragraphXml('', 'BodyRtl', basePt)); for (final block in blocks) { - body.write(_paragraphForBlock(block, footnotes, basePt)); + final sourceLink = block.sourceLink; + final linkId = + sourceLink == null || sourceLink.isEmpty || block.text.trim().isEmpty + ? null + : hyperlinks.putIfAbsent( + sourceLink, + () => 'rId${hyperlinks.length + 6}', + ); + body.write(_paragraphForBlock(block, footnotes, basePt, linkId)); } body.write(''' @@ -130,6 +146,7 @@ class WordExportService { PrintBlock block, List<_WordFootnote> footnotes, double basePt, + String? linkId, ) { final text = block.text.trimRight(); if (text.isEmpty) { @@ -145,6 +162,7 @@ class WordExportService { basePt, footnotes: block.footnotes, registry: footnotes, + linkId: linkId, ); case PrintBlockKind.text: final headingMatch = _headingWrapper.firstMatch(text.trim()); @@ -156,6 +174,7 @@ class WordExportService { basePt, footnotes: block.footnotes, registry: footnotes, + linkId: linkId, ); } return _paragraphXml( @@ -164,13 +183,19 @@ class WordExportService { basePt, footnotes: block.footnotes, registry: footnotes, + linkId: linkId, ); case PrintBlockKind.commentaryTitle: - return _paragraphXml(text, 'CommentaryHeading', basePt); + return _paragraphXml(text, 'CommentaryHeading', basePt, linkId: linkId); case PrintBlockKind.commentaryGroupTitle: - return _paragraphXml(text, 'CommentarySubheading', basePt); + return _paragraphXml( + text, + 'CommentarySubheading', + basePt, + linkId: linkId, + ); case PrintBlockKind.commentary: - return _paragraphXml(text, 'CommentaryBody', basePt); + return _paragraphXml(text, 'CommentaryBody', basePt, linkId: linkId); } } @@ -180,6 +205,7 @@ class WordExportService { double basePt, { List footnotes = const [], List<_WordFootnote>? registry, + String? linkId, }) { if (text.isEmpty) { return ''' @@ -199,9 +225,13 @@ class WordExportService { ${_paragraphPropertiesXml(styleId)} '''); + if (linkId != null) { + buffer.write(''); + } for (final run in _parseInlineRuns(text)) { - buffer.write(_runXml(run, basePt)); + buffer.write(_runXml(run, basePt, hyperlink: linkId != null)); } + if (linkId != null) buffer.write(''); for (final footnote in footnotes) { if (registry == null) continue; @@ -265,12 +295,18 @@ class WordExportService { return runs; } - static String _runXml(_InlineRun run, double basePt) { + static String _runXml( + _InlineRun run, + double basePt, { + bool hyperlink = false, + }) { if (run.isBreak) { return ''; } final style = run.style; - final props = StringBuffer(''); + final props = StringBuffer(); + if (hyperlink) props.write(''); + props.write(''); if (style.bold) props.write(''); if (style.italic) props.write(''); if (style.underline) props.write(''); @@ -367,6 +403,21 @@ class WordExportService { .replaceAll('"', '"') .replaceAll("'", '''); } + + static String _buildDocumentRelsXml(Map hyperlinks) { + final links = StringBuffer(); + for (final entry in hyperlinks.entries) { + links.write( + '', + ); + } + return _documentRelsXml.replaceFirst( + '', + '$links', + ); + } } const String _contentTypesXml = @@ -491,6 +542,10 @@ String _buildStylesXml({ + + + + diff --git a/lib/settings/services/backup_service.dart b/lib/settings/services/backup_service.dart index c3c413bd3c..8ec51f5a70 100644 --- a/lib/settings/services/backup_service.dart +++ b/lib/settings/services/backup_service.dart @@ -1269,8 +1269,9 @@ class BackupService { counts.history += added; } - /// מפתח העיגון שנוכחותו מעידה שהגיבוי יודע לבטא עיגון להערה. + /// נוכחות המפתחות מבחינה בין גיבוי ישן לבין הסרה מפורשת של סוג העוגן. static const String _noteAnchorKey = 'anchorText'; + static const String _notePdfAnchorKey = 'pdfAnchor'; /// Restore notes to SQLite database. /// @@ -1298,13 +1299,21 @@ class BackupService { try { final json = noteData as Map; var note = PersonalNote.fromJson(json); - if (!json.containsKey(_noteAnchorKey)) { + final missingWordAnchor = !json.containsKey(_noteAnchorKey); + final missingPdfAnchor = !json.containsKey(_notePdfAnchorKey); + if (missingWordAnchor || missingPdfAnchor) { note = await _restoreNoteAnchoredAsBefore( database, note, pendingNote: toWrite[note.id], + preserveWordAnchor: missingWordAnchor, + preservePdfAnchor: missingPdfAnchor, ); - if (!note.isWordAnchored) anchorlessNotes++; + } + if (missingWordAnchor && + !note.isWordAnchored && + note.pdfAnchor == null) { + anchorlessNotes++; } if (counts != null) { // בייבוא ממזג אין לדרוס הערה מקומית או ממתינה חדשה יותר. @@ -1347,17 +1356,35 @@ class BackupService { PersonalNotesDatabase database, PersonalNote note, { PersonalNote? pendingNote, + required bool preserveWordAnchor, + required bool preservePdfAnchor, }) async { try { final existing = pendingNote ?? await database.getNote(note.id); - if (existing == null || !existing.isWordAnchored) return note; - return note.copyWith( - anchorText: existing.anchorText, - anchorPrefix: existing.anchorPrefix, - anchorSuffix: existing.anchorSuffix, - anchorStart: existing.anchorStart, - anchorEnd: existing.anchorEnd, - ); + if (existing == null) return note; + var restored = note; + if (preserveWordAnchor && existing.isWordAnchored) { + restored = restored.copyWith( + anchorText: existing.anchorText, + anchorPrefix: existing.anchorPrefix, + anchorSuffix: existing.anchorSuffix, + anchorStart: existing.anchorStart, + anchorEnd: existing.anchorEnd, + ); + } + // אותו כלל כמו בייבוא ממנהל ההערות: שדה חסר אינו מבטל נקודה מקומית, + // אך שינוי המקור או המיקום אינו רשאי להוריש את העוגן הישן. + if (preservePdfAnchor && + existing.pdfAnchor != null && + note.bookId == existing.bookId && + note.lineNumber == existing.lineNumber && + note.displayTitle == existing.displayTitle && + note.status == existing.status && + (note.hasLocation || + note.lastKnownLineNumber == existing.lastKnownLineNumber)) { + restored = restored.copyWith(pdfAnchor: existing.pdfAnchor); + } + return restored; } catch (e) { _logger.warning('Failed to preserve anchor for note ${note.id}: $e'); return note; diff --git a/lib/tabs/bloc/tabs_bloc.dart b/lib/tabs/bloc/tabs_bloc.dart index a0b071dc0d..4c262f1bb6 100644 --- a/lib/tabs/bloc/tabs_bloc.dart +++ b/lib/tabs/bloc/tabs_bloc.dart @@ -870,6 +870,11 @@ class TabsBloc extends Bloc { // עדכון pageNumber בטאב כך שיישמר ל-restore עתידי וכך שאם המסך עוד // לא הצטרף ל-controller, הטעינה הבאה תיפתח בעמוד הנכון. targetPdf.pageNumber = targetPage; + final noteAnchor = incomingTab.takePersonalNoteNavigationRequest(); + if (noteAnchor != null) { + targetPdf.requestPersonalNoteNavigation(noteAnchor); + return; + } if (targetPdf.pdfViewerController.isReady) { targetPdf.pdfViewerController.goToPage(pageNumber: targetPage); } diff --git a/lib/tabs/models/pdf_tab.dart b/lib/tabs/models/pdf_tab.dart index 7f58a4c8a6..f1abbeae41 100644 --- a/lib/tabs/models/pdf_tab.dart +++ b/lib/tabs/models/pdf_tab.dart @@ -13,6 +13,7 @@ import 'package:otzaria/settings/engine/app_settings_store.dart'; import 'package:otzaria/search/models/search_configuration.dart'; import 'package:otzaria/settings/services/per_book_settings_service.dart'; import 'package:otzaria/utils/ui/reading_left_pane_policy.dart'; +import 'package:otzaria/personal_notes/models/pdf_note_anchor.dart'; /// כרטיסיית קורא PDF עם מצב המשתמש ובקר התצוגה שלה. class PdfBookTab extends OpenedTab { @@ -31,6 +32,25 @@ class PdfBookTab extends OpenedTab { PdfViewerController pdfViewerController = PdfViewerController(); final navigationHistory = PdfLocationHistory(); + PdfNoteAnchor? _pendingPersonalNoteAnchor; + final ValueNotifier _personalNoteNavigationRequests = ValueNotifier(0); + + /// בקשות לעוגן פיזי, גם כשאותה נקודה נפתחת שוב בכרטיסייה קיימת. + ValueListenable get personalNoteNavigationRequests => + _personalNoteNavigationRequests; + + /// נשמר בזיכרון עד שהצפיין מוכן; אינו משוחזר עם היסטוריית הכרטיסיות. + void requestPersonalNoteNavigation(PdfNoteAnchor anchor) { + _pendingPersonalNoteAnchor = anchor; + _personalNoteNavigationRequests.value++; + } + + PdfNoteAnchor? takePersonalNoteNavigationRequest() { + final anchor = _pendingPersonalNoteAnchor; + _pendingPersonalNoteAnchor = null; + return anchor; + } + /// האם הדפים הנראים רחבים מהתצוגה, כך שנדרשת הזזה אופקית. /// סטייה בתוך השוליים אינה זום; סבילות של פיקסל מונעת שגיאות עיגול. bool get canPanHorizontally { @@ -257,6 +277,7 @@ class PdfBookTab extends OpenedTab { /// Cleanup when the tab is disposed @override void dispose() { + _personalNoteNavigationRequests.dispose(); searchController.dispose(); outline.dispose(); documentRef.dispose(); diff --git a/lib/text_book/utils/note_inline_render.dart b/lib/text_book/utils/note_inline_render.dart index e263c58b38..b2ec109ffe 100644 --- a/lib/text_book/utils/note_inline_render.dart +++ b/lib/text_book/utils/note_inline_render.dart @@ -62,33 +62,18 @@ String buildAnnotatedLineHtml({ // ההערה מדלגת על כל קיים — למניעת מקונן. final linkSpans = _anchorElementSpans(rawLine); - final ranges = []; - final hex = _colorToHex(underlineColor); - // color: currentcolor (ולא inherit) — flutter_widget_from_html לא מפרש - // inherit, וההצהרה הייתה נזרקת כך שטקסט ההערה נצבע בצבע ה-primary של - // קישורים (ברירת המחדל של תגית ). currentcolor כן נתמך ומשאיר את - // צבע הטקסט הרגיל — וכך הערה (קו מקווקו, צבע רגיל) נבדלת מקישור - // (קו מלא, צבע primary). - final openTag = - ''; + final boundaries = <({int offset, String id, bool opening})>[]; - void addNoteSpan(int start, int end) { + void addNoteSpan(int start, int end, String id) { for (final gap in _subtractSpans(start, end, linkSpans)) { - ranges.add( - HtmlWrapRange( - start: gap[0], - end: gap[1], - openTag: openTag, - closeTag: '', - ), - ); + boundaries.add((offset: gap[0], id: id, opening: true)); + boundaries.add((offset: gap[1], id: id, opening: false)); } } for (final note in notesForLine) { + if (note.pdfAnchor != null) continue; if (note.isWordAnchored) { final range = locateAnchor( rawLine: rawLine, @@ -102,18 +87,71 @@ String buildAnnotatedLineHtml({ final expanded = replaceHolyNames ? _expandToHolyName(rawLine, range) : range; - addNoteSpan(expanded.start, expanded.end); + addNoteSpan(expanded.start, expanded.end, note.id); continue; } // לא נמצא הביטוי — נופלים לסימון כל השורה. } // הערת-שורה-שלמה (או נפילה מאיתור כושל): סימון כל השורה. - addNoteSpan(0, rawLine.length); + addNoteSpan(0, rawLine.length, note.id); } + boundaries.sort((a, b) { + final offsetOrder = a.offset.compareTo(b.offset); + if (offsetOrder != 0) return offsetOrder; + return (a.opening ? 1 : 0).compareTo(b.opening ? 1 : 0); + }); + final ranges = []; + final activeIds = {}; + var cursor = 0; + for (final boundary in boundaries) { + if (cursor < boundary.offset && activeIds.isNotEmpty) { + final ids = activeIds + .map((id) => '&id=${Uri.encodeComponent(id)}') + .join(); + ranges.add( + HtmlWrapRange( + start: cursor, + end: boundary.offset, + // currentcolor שומר את צבע הטקסט; inherit אינו נתמך ברינדור ה-HTML. + openTag: + '', + closeTag: '', + ), + ); + } + if (boundary.opening) { + activeIds.add(boundary.id); + } else { + activeIds.remove(boundary.id); + } + cursor = boundary.offset; + } return wrapHtmlRanges(rawLine, ranges); } +/// מחזיר רק הערות של העוגן; קישור ישן בלי מזהים ממשיך להציג את הערות השורה. +List personalNotesForPreview( + String url, + Iterable notes, +) { + final uri = Uri.tryParse(url); + if (uri == null || uri.scheme != 'otzaria' || uri.host != 'note') return []; + final line = int.tryParse(uri.queryParameters['line'] ?? ''); + if (line == null || line < 0) return []; + final ids = uri.queryParametersAll['id']?.toSet(); + return notes + .where( + (note) => + note.pdfAnchor == null && + note.lineNumber == line + 1 && + (ids == null || ids.contains(note.id)), + ) + .toList(); +} + NoteAnchorRange _expandToHolyName(String rawLine, NoteAnchorRange range) { var start = range.start; var end = range.end; diff --git a/lib/text_book/view/combined_view/combined_book_screen.dart b/lib/text_book/view/combined_view/combined_book_screen.dart index f6c5e9f851..e735a8c91e 100644 --- a/lib/text_book/view/combined_view/combined_book_screen.dart +++ b/lib/text_book/view/combined_view/combined_book_screen.dart @@ -180,10 +180,6 @@ List buildCombinedViewContextMenuLinksForParagraph({ queriedLinks: queriedLinks, ); -@visibleForTesting -bool shouldShowPersonalNotePreview({required bool isPersonalNotesTabActive}) => - !isPersonalNotesTabActive; - /// מחזירה האם לשורה [index] יש מפרשים להצגה במצב "מפרשים מתחת". /// /// מתחשבת גם במפרש ההערות הוירטואלי ([kNotesCommentatorTitle]): אם הוא @@ -642,13 +638,6 @@ class _CombinedViewState extends State { _handleNumberedNoteMarkerHover(url, globalPosition); return; } - if (url.startsWith('otzaria://note') && - !shouldShowPersonalNotePreview( - isPersonalNotesTabActive: - widget.isPersonalNotesTabActive?.call() ?? false, - )) { - return; - } LinkPreviewOverlay.cancelScheduledHide(AppWindowKeys.of(context)); _cancelPendingAnchorHover(); @@ -713,16 +702,10 @@ class _CombinedViewState extends State { } if (url.startsWith('otzaria://note')) { - final line = int.tryParse( - Uri.tryParse(url)?.queryParameters['line'] ?? '', + final notes = personalNotesForPreview( + url, + context.read().state.locatedNotes, ); - if (line == null) return; - final notes = context - .read() - .state - .locatedNotes - .where((note) => note.lineNumber == line + 1) - .toList(); if (notes.isEmpty) return; LinkPreviewOverlay.showContent( context, @@ -1840,34 +1823,20 @@ class _CombinedViewState extends State { ) : null; - // טען טיוטה אם קיימת - final draftService = PersonalNoteDraftService(); - final draft = await draftService.loadDraft( + await createPersonalNote( + context, + isNotesPanelOpen: widget.isPersonalNotesTabActive?.call() ?? false, bookId: personalNotesBookKey(widget.tab.book), categoryId: widget.tab.book.categoryId, lineNumber: currentIndex + 1, + referenceText: referenceText, + selectedText: selectedText?.trim(), + selectionColumn: source.column, + sourceSelectedText: sourceSelection?.text, + sourceSelectionOffset: sourceSelection?.offset, + punctuationHidden: state.removePunctuation, + openNotesPanel: widget.onOpenPersonalNotes, ); - - if (!mounted) return; - - // שלח event לפתיחת מצב יצירה בסיידבר - context.read().add( - StartCreatingPersonalNote( - bookId: personalNotesBookKey(widget.tab.book), - lineNumber: currentIndex + 1, - referenceText: referenceText, - selectedText: selectedText?.trim(), - selectionColumn: source.column, - sourceSelectedText: sourceSelection?.text, - sourceSelectionOffset: sourceSelection?.offset, - punctuationHidden: state.removePunctuation, - initialContent: draft?.content ?? '', - initialFormat: draft?.contentFormat ?? PersonalNoteContentFormat.plain, - ), - ); - - // פתח את חלונית ההערות - widget.onOpenPersonalNotes?.call(); } /// טיפול בלחיצה על סימון הערה אישית inline: מדגיש את השורה ופותח את החלונית. diff --git a/lib/text_book/view/page_shape/page_shape_screen.dart b/lib/text_book/view/page_shape/page_shape_screen.dart index df5d19c86c..914b9a0388 100644 --- a/lib/text_book/view/page_shape/page_shape_screen.dart +++ b/lib/text_book/view/page_shape/page_shape_screen.dart @@ -60,9 +60,11 @@ import 'package:otzaria/data/data_providers/book_database_resolver.dart'; import 'package:otzaria/data/data_providers/sqlite_data_provider.dart'; import 'package:otzaria/data/data_providers/library_provider_manager.dart'; import 'package:otzaria/personal_notes/bloc/personal_notes_bloc.dart'; +import 'package:otzaria/personal_notes/utils/create_personal_note.dart'; import 'package:otzaria/personal_notes/models/personal_note.dart'; import 'package:otzaria/personal_notes/bloc/personal_notes_state.dart'; import 'package:otzaria/personal_notes/repository/personal_notes_repository.dart'; +import 'package:otzaria/personal_notes/utils/open_personal_notes_target.dart'; import 'package:otzaria/text_book/models/book_notes.dart'; import 'package:otzaria/text_book/repository/book_notes_repository.dart'; import 'package:otzaria/personal_notes/widgets/commentary_notes_section.dart'; @@ -112,7 +114,8 @@ class PageShapeScreen extends StatefulWidget { State createState() => _PageShapeScreenState(); } -class _PageShapeScreenState extends State { +class _PageShapeScreenState extends State + implements PersonalNotesPanelVisibility { String? _leftCommentator; String? _rightCommentator; String? _bottomCommentator; @@ -123,6 +126,10 @@ class _PageShapeScreenState extends State { bool _applyTextMaxWidth = PageShapeSettingsManager.getApplyTextMaxWidth(); bool _isLeftSidebarOpen = false; int _leftSidebarTabIndex = 0; + + @override + bool get isPersonalNotesPanelOpen => + _isLeftSidebarOpen && _leftSidebarTabIndex == kNotesTabIndex; String? _notesBookIdOverride; int? _notesCategoryIdOverride; int? _notesFocusLineNumber; @@ -896,7 +903,20 @@ class _PageShapeScreenState extends State { String bookId, int? categoryId, int lineNumber, + ) => revealPersonalNotesTarget(bookId, categoryId, lineNumber); + + @override + void revealPersonalNotesTarget( + String bookId, + int? categoryId, + int lineNumber, ) { + openPersonalNotesTarget( + context.read(), + bookId: bookId, + categoryId: categoryId, + lineNumber: lineNumber, + ); if (!_isLeftSidebarOpen) _reanchorMainText(); setState(() { _notesBookIdOverride = bookId; diff --git a/lib/text_book/view/page_shape/simple_text_viewer.dart b/lib/text_book/view/page_shape/simple_text_viewer.dart index 35e4f56c9b..c9048f1151 100644 --- a/lib/text_book/view/page_shape/simple_text_viewer.dart +++ b/lib/text_book/view/page_shape/simple_text_viewer.dart @@ -345,38 +345,6 @@ int resolvePageShapeNavigationBaseIndex({ return selectedIndex ?? 0; } -/// שומרת הערת מפרש דרך ה-repository, ממפה את תוצאת העורך לקריאת `addNote`. -/// -/// מופרדת לפונקציה עצמאית כדי לאפשר בדיקה ישירה של מיפוי הפרמטרים (ה-`bookId` -/// של המפרש, מספר השורה והתוכן) ללא תלות ב-UI של עורך ה-Quill. -@visibleForTesting -Future saveCommentaryNoteToRepository({ - required PersonalNotesRepository repository, - required String bookId, - required int lineNumber, - required PersonalNoteEditorResult result, - String? selectedText, - int? selectionColumn, - String? sourceSelectedText, - int? sourceSelectionOffset, - bool punctuationHidden = false, - int? categoryId, -}) { - return repository.addNote( - bookId: bookId, - lineNumber: lineNumber, - content: result.content, - contentPlain: result.contentPlain, - contentFormat: result.contentFormat, - selectedText: selectedText, - selectionColumn: selectionColumn, - sourceSelectedText: sourceSelectedText, - sourceSelectionOffset: sourceSelectionOffset, - punctuationHidden: punctuationHidden, - categoryId: categoryId, - ); -} - /// סמן הבחירה מצויר בריפוד הימני של הרשימה, מחוץ לטקסט. const _readerListPadding = EdgeInsets.all(4); @@ -783,9 +751,6 @@ class _SimpleTextViewerState extends State { _handleNumberedNoteMarkerHover(url, globalPosition); return; } - if (url.startsWith('otzaria://note') && widget.isPersonalNotesTabActive) { - return; - } LinkPreviewOverlay.cancelScheduledHide(AppWindowKeys.of(context)); _cancelPendingPreview(); final bloc = context.read(); @@ -852,16 +817,10 @@ class _SimpleTextViewerState extends State { } if (url.startsWith('otzaria://note')) { - final line = int.tryParse( - Uri.tryParse(url)?.queryParameters['line'] ?? '', + final notes = personalNotesForPreview( + url, + context.read().state.locatedNotes, ); - if (line == null) return; - final notes = context - .read() - .state - .locatedNotes - .where((note) => note.lineNumber == line + 1) - .toList(); if (notes.isEmpty) return; LinkPreviewOverlay.showContent( context, @@ -1166,7 +1125,10 @@ class _SimpleTextViewerState extends State { final state = context.read().state; if (state is TextBookLoaded) { context.read().add( - LoadPersonalNotes(personalNotesBookKey(state.book)), + LoadPersonalNotes( + personalNotesBookKey(state.book), + categoryId: state.book.categoryId, + ), ); } }); @@ -2399,10 +2361,8 @@ class _SimpleTextViewerState extends State { ? utils.removeVolwels(selectedText!.trim()) : widget.content[index]; - // הערה שנוצרת מתוך מפרש (לא הטקסט הראשי) חייבת להישמר תחת ספר המפרש - // עצמו, עם מספר השורה המקומי בתוך תוכן המפרש. הסיידבר של צורת הדף קשור - // תמיד לספר הראשי, לכן אי אפשר להשתמש בו — פותחים דיאלוג עצמאי ושומרים - // ישירות דרך ה-repository, בלי לשבש את ה-PersonalNotesBloc של הספר הראשי. + // הערת מפרש שייכת לספר המפרש ולשורה המקומית שלו, גם כשהעורך נפתח + // בחלונית הערות שכבר פעילה עבור הספר הראשי. if (!widget.isMainText && widget.bookTitle != null) { await _createCommentaryNote( bookTitle: widget.bookTitle!, @@ -2417,40 +2377,37 @@ class _SimpleTextViewerState extends State { return; } - // טען טיוטה אם קיימת - final draftService = PersonalNoteDraftService(); - final draft = await draftService.loadDraft( + await createPersonalNote( + context, + isNotesPanelOpen: widget.isPersonalNotesTabActive, bookId: personalNotesBookKey(state.book), categoryId: state.book.categoryId, lineNumber: index + 1, - ); - - if (!mounted) return; - - // שלח event לפתיחת מצב יצירה בסיידבר - context.read().add( - StartCreatingPersonalNote( - bookId: personalNotesBookKey(state.book), - lineNumber: index + 1, - referenceText: referenceText, - selectedText: selectedText?.trim(), - selectionColumn: source.column, - sourceSelectedText: mappedSelection?.text, - sourceSelectionOffset: mappedSelection?.offset, - punctuationHidden: state.removePunctuation, - initialContent: draft?.content ?? '', - initialFormat: draft?.contentFormat ?? PersonalNoteContentFormat.plain, - ), + referenceText: referenceText, + selectedText: selectedText?.trim(), + selectionColumn: source.column, + sourceSelectedText: mappedSelection?.text, + sourceSelectionOffset: mappedSelection?.offset, + punctuationHidden: state.removePunctuation, + repository: widget.notesRepository, + openNotesPanel: widget.onOpenSidebarTab == null + ? null + : () => widget.onOpenSidebarTab!(kNotesTabIndex), ); } /// טיפול בלחיצה על סימון הערה אישית inline: מדגיש את השורה ופותח את החלונית. void _onInlineNoteTap(int lineIndex) { - context.read().add(UpdateSelectedIndex(lineIndex)); - context.read().add(HighlightLine(lineIndex)); - // פותחים את ההערה עצמה בחלונית, גם אם מוגדר "סגור כברירת מחדל". - context.read().add( - RequestExpandNotesForLine(lineIndex + 1), + final bloc = context.read(); + final state = bloc.state; + if (state is! TextBookLoaded) return; + bloc.add(UpdateSelectedIndex(lineIndex)); + bloc.add(HighlightLine(lineIndex)); + openPersonalNotesTarget( + context.read(), + bookId: personalNotesBookKey(state.book), + categoryId: state.book.categoryId, + lineNumber: lineIndex + 1, ); if (widget.onOpenSidebarTab != null) { widget.onOpenSidebarTab!(kNotesTabIndex); @@ -2467,12 +2424,7 @@ class _SimpleTextViewerState extends State { : bookTitle; } - /// יצירת הערה על מפרש (בצורת הדף) — נשמרת תחת ספר המפרש עצמו. - /// - /// [bookTitle] - שם ספר המפרש (למשל "רש"י") - /// [lineNumber] - מספר השורה המקומי בתוך תוכן המפרש (1-based) - /// [referenceText] - טקסט הייחוס המוצג בכותרת ההערה - /// [selectedText] - הטקסט שסומן, אם קיים + /// הערת מפרש נשמרת תחת ספר המפרש ומספר השורה המקומי שלו (1-based). Future _createCommentaryNote({ required String bookTitle, required int lineNumber, @@ -2486,51 +2438,28 @@ class _SimpleTextViewerState extends State { final notesKey = _commentaryNotesKey(bookTitle); final categoryId = widget.reportBook?.categoryId; - // טען טיוטה קיימת (אם יש) כדי לתמוך בשחזור טקסט לא שמור — כמו במסלול הרגיל. - final draftService = PersonalNoteDraftService(); - final draft = await draftService.loadDraft( + final panel = findPersonalNotesPanel(context); + final openTarget = + widget.onOpenCommentaryPersonalNote ?? panel?.revealPersonalNotesTarget; + await createPersonalNote( + context, + isNotesPanelOpen: + panel?.isPersonalNotesPanelOpen ?? widget.isPersonalNotesTabActive, + title: 'הערה חדשה - $bookTitle', bookId: notesKey, categoryId: categoryId, lineNumber: lineNumber, + referenceText: referenceText, + selectedText: selectedText, + selectionColumn: selectionColumn, + sourceSelectedText: sourceSelectedText, + sourceSelectionOffset: sourceSelectionOffset, + punctuationHidden: punctuationHidden, + repository: widget.notesRepository, + openNotesPanel: openTarget == null + ? null + : () => openTarget(notesKey, categoryId, lineNumber), ); - - if (!mounted) return; - - final result = await showDialog( - context: context, - builder: (dialogContext) => PersonalNoteEditorDialog( - title: 'הערה חדשה - $bookTitle', - referenceText: referenceText, - icon: FluentIcons.note_add_24_regular, - bookId: notesKey, - categoryId: categoryId, - // draftLineNumber מאפשר לדיאלוג לשמור/לנקות טיוטה בעת סגירה. - draftLineNumber: lineNumber, - initialContent: draft?.content ?? '', - initialContentFormat: - draft?.contentFormat ?? PersonalNoteContentFormat.plain, - ), - ); - - if (result == null || result.contentPlain.trim().isEmpty) return; - - try { - await saveCommentaryNoteToRepository( - repository: widget.notesRepository ?? PersonalNotesRepository(), - bookId: notesKey, - lineNumber: lineNumber, - result: result, - selectedText: selectedText, - selectionColumn: selectionColumn, - sourceSelectedText: sourceSelectedText, - sourceSelectionOffset: sourceSelectionOffset, - punctuationHidden: punctuationHidden, - categoryId: categoryId, - ); - if (mounted) UiSnack.showSuccess(TextBookMessages.noteSaved); - } catch (e) { - if (mounted) UiSnack.showError(TextBookMessages.noteSaveError(e)); - } } int? _sourceIndex(int? index) => diff --git a/lib/text_book/view/splited_view/splited_view_screen.dart b/lib/text_book/view/splited_view/splited_view_screen.dart index 3ebf4fb96e..1a76a88168 100644 --- a/lib/text_book/view/splited_view/splited_view_screen.dart +++ b/lib/text_book/view/splited_view/splited_view_screen.dart @@ -4,6 +4,9 @@ import 'package:otzaria/plugins/view/plugin_text_reader.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:otzaria/search/models/search_configuration.dart'; import 'package:otzaria/settings/engine/app_settings_store.dart'; +import 'package:otzaria/personal_notes/bloc/personal_notes_bloc.dart'; +import 'package:otzaria/personal_notes/utils/create_personal_note.dart'; +import 'package:otzaria/personal_notes/utils/open_personal_notes_target.dart'; import 'package:otzaria/personal_notes/utils/personal_notes_book_key.dart'; import 'package:otzaria/settings/settings_exports.dart'; import 'package:otzaria/tabs/models/tab.dart'; @@ -55,7 +58,8 @@ class SplitedViewScreen extends StatefulWidget { State createState() => _SplitedViewScreenState(); } -class _SplitedViewScreenState extends State { +class _SplitedViewScreenState extends State + implements PersonalNotesPanelVisibility { bool _paneOpen = false; // פתיחה אוטומטית של פאנל המפרשים מתבצעת פעם אחת בלבד לכל טעינת מסך. bool _didAutoOpenCommentary = false; @@ -63,6 +67,10 @@ class _SplitedViewScreenState extends State { // מונח החיפוש להדגשה בטאב המפרשים (התוצאה שנחתה בהערה). late final ValueNotifier _searchHighlightNotifier; int? _currentTabIndex; + + @override + bool get isPersonalNotesPanelOpen => + _paneOpen && _currentTabIndex == kNotesTabIndex; String? _notesBookIdOverride; int? _notesCategoryIdOverride; int? _notesFocusLineNumber; @@ -138,6 +146,9 @@ class _SplitedViewScreenState extends State { setState(() { _paneOpen = true; _currentTabIndex = kNotesTabIndex; + _notesBookIdOverride = null; + _notesCategoryIdOverride = null; + _notesFocusLineNumber = null; }); } @@ -372,12 +383,28 @@ class _SplitedViewScreenState extends State { } void _openCommentaryPersonalNote(Link link, int lineNumber) { + final bookId = personalNotesBookKeyFor( + utils.getTitleFromPath(link.path2), + link.targetSource, + ); + revealPersonalNotesTarget(bookId, link.targetCategoryId, lineNumber); + } + + @override + void revealPersonalNotesTarget( + String bookId, + int? categoryId, + int lineNumber, + ) { + openPersonalNotesTarget( + context.read(), + bookId: bookId, + categoryId: categoryId, + lineNumber: lineNumber, + ); setState(() { - _notesBookIdOverride = personalNotesBookKeyFor( - utils.getTitleFromPath(link.path2), - link.targetSource, - ); - _notesCategoryIdOverride = link.targetCategoryId; + _notesBookIdOverride = bookId; + _notesCategoryIdOverride = categoryId; _notesFocusLineNumber = lineNumber; _paneOpen = true; _currentTabIndex = kNotesTabIndex; diff --git a/lib/text_book/view/strategies/combined_view_strategy.dart b/lib/text_book/view/strategies/combined_view_strategy.dart index 0fa304d921..511cf289ad 100644 --- a/lib/text_book/view/strategies/combined_view_strategy.dart +++ b/lib/text_book/view/strategies/combined_view_strategy.dart @@ -9,6 +9,7 @@ class CombinedViewStrategyImpl extends TextBookViewStrategy { @override Widget buildView(BuildContext context, TextBookViewConfig config) { return SplitedViewScreen( + key: config.splitViewKey, content: config.content, openBookCallback: config.openBookCallback, searchTextController: config.searchTextController, diff --git a/lib/text_book/view/strategies/split_view_strategy.dart b/lib/text_book/view/strategies/split_view_strategy.dart index 0e0d053d67..10754c1492 100644 --- a/lib/text_book/view/strategies/split_view_strategy.dart +++ b/lib/text_book/view/strategies/split_view_strategy.dart @@ -9,6 +9,7 @@ class SplitViewStrategyImpl extends TextBookViewStrategy { @override Widget buildView(BuildContext context, TextBookViewConfig config) { return SplitedViewScreen( + key: config.splitViewKey, content: config.content, openBookCallback: config.openBookCallback, searchTextController: config.searchTextController, diff --git a/lib/text_book/view/strategies/text_book_view_strategy.dart b/lib/text_book/view/strategies/text_book_view_strategy.dart index 556c55c751..fe89eb4c52 100644 --- a/lib/text_book/view/strategies/text_book_view_strategy.dart +++ b/lib/text_book/view/strategies/text_book_view_strategy.dart @@ -13,6 +13,7 @@ class TextBookViewConfig { final TextBookTab tab; final int? initialSidebarTabIndex; final Key? pageShapeKey; + final Key? splitViewKey; final GlobalKey? pageShapePrintBoundaryKey; final ValueNotifier? pageShapeSidebarTabNotifier; @@ -30,6 +31,7 @@ class TextBookViewConfig { required this.tab, this.initialSidebarTabIndex, this.pageShapeKey, + this.splitViewKey, this.pageShapePrintBoundaryKey, this.pageShapeSidebarTabNotifier, this.pageShapeOpenSettingsNotifier, diff --git a/lib/text_book/view/text_book_scaffold.dart b/lib/text_book/view/text_book_scaffold.dart index bed8140516..5e0b2d4157 100644 --- a/lib/text_book/view/text_book_scaffold.dart +++ b/lib/text_book/view/text_book_scaffold.dart @@ -19,6 +19,7 @@ class TextBookScaffold extends StatelessWidget { final TextBookTab tab; final int? initialSidebarTabIndex; final Key? pageShapeKey; // מפתח עבור PageShapeScreen + final Key? splitViewKey; final GlobalKey? pageShapePrintBoundaryKey; // מפתח עבור צילום למסמך הדפסה final ValueNotifier? pageShapeSidebarTabNotifier; @@ -37,6 +38,7 @@ class TextBookScaffold extends StatelessWidget { required this.tab, this.initialSidebarTabIndex, this.pageShapeKey, + this.splitViewKey, this.pageShapePrintBoundaryKey, this.pageShapeSidebarTabNotifier, this.pageShapeOpenSettingsNotifier, @@ -62,6 +64,7 @@ class TextBookScaffold extends StatelessWidget { tab: tab, initialSidebarTabIndex: initialSidebarTabIndex, pageShapeKey: pageShapeKey, + splitViewKey: splitViewKey, pageShapePrintBoundaryKey: pageShapePrintBoundaryKey, pageShapeSidebarTabNotifier: pageShapeSidebarTabNotifier, pageShapeOpenSettingsNotifier: pageShapeOpenSettingsNotifier, diff --git a/lib/text_book/view/text_book_screen.dart b/lib/text_book/view/text_book_screen.dart index 418e380e43..86d5059bd7 100644 --- a/lib/text_book/view/text_book_screen.dart +++ b/lib/text_book/view/text_book_screen.dart @@ -244,7 +244,8 @@ class _TextBookViewerBlocState extends State double? _pinchStartFontSize; // Key עבור PageShapeScreen - final Key _pageShapeKey = UniqueKey(); + final GlobalKey _pageShapeKey = GlobalKey(); + final GlobalKey _splitViewKey = GlobalKey(); // בדיקת הכותרות החלופיות מסתיימת אחרי הבנייה ומשנה את מספר הלשוניות; בלי // מפתח גלובלי לשונית החיפוש נבנית מאפס ומה שהוקלד בה עד אז אובד (issue #1263). @@ -1076,6 +1077,13 @@ class _TextBookViewerBlocState extends State context.read().add(const ToggleSplitView(true)); } + bool _isPersonalNotesPanelOpen(TextBookLoaded state) { + final Object? paneState = + (state.showPageShapeView ? _pageShapeKey : _splitViewKey).currentState; + return paneState is PersonalNotesPanelVisibility && + paneState.isPersonalNotesPanelOpen; + } + void _openLeftPaneTab(int index, {String? searchText}) { context.read().add(const ToggleLeftPane(true)); @@ -1374,6 +1382,7 @@ class _TextBookViewerBlocState extends State openSearchFromToolbar: _openSearchFromToolbar, openNotesForCurrentView: () => _openPersonalNotesForCurrentView(state), + isNotesPanelOpen: _isPersonalNotesPanelOpen(state), selectedTextForNote: _selectedTextForSearch, selectedLineForNote: _selectedLineForNote, selectedColumnForNote: _selectedColumnForNote, @@ -2789,6 +2798,7 @@ class _TextBookViewerBlocState extends State } }, pageShapeKey: _pageShapeKey, + splitViewKey: _splitViewKey, pageShapePrintBoundaryKey: _pageShapePrintBoundaryKey, pageShapeSidebarTabNotifier: _pageShapeSidebarTabNotifier, pageShapeOpenSettingsNotifier: _pageShapeOpenSettingsNotifier, @@ -3024,6 +3034,7 @@ bool _handleGlobalKeyEvent( TextBookTab tab, { required VoidCallback openSearchFromToolbar, required VoidCallback openNotesForCurrentView, + required bool isNotesPanelOpen, String? selectedTextForNote, int? selectedLineForNote, int? selectedColumnForNote, @@ -3138,6 +3149,7 @@ bool _handleGlobalKeyEvent( state, currentLine: tab.index, openNotesForCurrentView: openNotesForCurrentView, + isNotesPanelOpen: isNotesPanelOpen, selectedText: selectedTextForNote, selectedLineIndex: selectedLineForNote, selectionColumn: selectedColumnForNote, @@ -3533,6 +3545,7 @@ Future _addNoteFromKeyboard( TextBookLoaded state, { required int currentLine, required VoidCallback openNotesForCurrentView, + required bool isNotesPanelOpen, String? selectedText, int? selectedLineIndex, int? selectionColumn, @@ -3567,33 +3580,20 @@ Future _addNoteFromKeyboard( ) : null; - // טען טיוטה אם קיימת - final draftService = PersonalNoteDraftService(); - final draft = await draftService.loadDraft( + await createPersonalNote( + context, + isNotesPanelOpen: isNotesPanelOpen, bookId: personalNotesBookKey(state.book), categoryId: state.book.categoryId, lineNumber: currentIndex + 1, + referenceText: referenceText, + selectedText: hasSelection ? trimmedSelection : null, + selectionColumn: hasSelection ? selectionColumn : null, + sourceSelectedText: sourceSelection?.text, + sourceSelectionOffset: sourceSelection?.offset, + punctuationHidden: state.removePunctuation, + openNotesPanel: openNotesForCurrentView, ); - - if (!context.mounted) return; - - // שלח event לפתיחת מצב יצירה בסיידבר - context.read().add( - StartCreatingPersonalNote( - bookId: personalNotesBookKey(state.book), - lineNumber: currentIndex + 1, - referenceText: referenceText, - selectedText: hasSelection ? trimmedSelection : null, - selectionColumn: hasSelection ? selectionColumn : null, - sourceSelectedText: sourceSelection?.text, - sourceSelectionOffset: sourceSelection?.offset, - punctuationHidden: state.removePunctuation, - initialContent: draft?.content ?? '', - initialFormat: draft?.contentFormat ?? PersonalNoteContentFormat.plain, - ), - ); - - openNotesForCurrentView(); } // [EDITING DISABLED] diff --git a/lib/utils/ui/context_menu_utils.dart b/lib/utils/ui/context_menu_utils.dart index e76e445b27..069957e3b7 100644 --- a/lib/utils/ui/context_menu_utils.dart +++ b/lib/utils/ui/context_menu_utils.dart @@ -28,7 +28,6 @@ import 'package:otzaria/text_book/bloc/text_book_state.dart'; import 'package:otzaria/text_book/view/error_report_dialog.dart'; import 'package:otzaria/text_display/text_display_exports.dart'; import 'package:otzaria/widgets/misc/link_context_menu_entry.dart'; -import 'package:otzaria/core/messages/text_book_messages.dart'; import 'package:otzaria/utils/text/text_manipulation.dart' as utils; import 'package:otzaria/utils/text/copy_utils.dart'; import 'package:otzaria/settings/settings_exports.dart'; @@ -288,30 +287,6 @@ class ContextMenuUtils { ? utils.removeVolwels(selectedText!) : utils.stripHtmlIfNeeded(rawContent); final notesKey = personalNotesBookKeyFor(bookTitle, link.targetSource); - final draftService = PersonalNoteDraftService(); - final draft = await draftService.loadDraft( - bookId: notesKey, - categoryId: link.targetCategoryId, - lineNumber: link.index2, - ); - if (!context.mounted) return; - - final result = await showDialog( - context: context, - builder: (_) => PersonalNoteEditorDialog( - title: 'הערה חדשה - $bookTitle', - referenceText: referenceText, - icon: FluentIcons.note_add_24_regular, - bookId: notesKey, - categoryId: link.targetCategoryId, - draftLineNumber: link.index2, - initialContent: draft?.content ?? '', - initialContentFormat: - draft?.contentFormat ?? PersonalNoteContentFormat.plain, - ), - ); - if (result == null || result.contentPlain.trim().isEmpty) return; - final sourceSelection = selectedText?.isNotEmpty == true ? mapPersonalNoteSourceSelection( bookId: notesKey, @@ -322,24 +297,27 @@ class ContextMenuUtils { ) : null; - try { - await PersonalNotesRepository().addNote( - bookId: notesKey, - lineNumber: link.index2, - content: result.content, - contentPlain: result.contentPlain, - contentFormat: result.contentFormat, - selectedText: selectedText, - sourceSelectedText: sourceSelection?.text, - sourceSelectionOffset: sourceSelection?.offset, - categoryId: link.targetCategoryId, - ); - if (context.mounted) UiSnack.showSuccess(TextBookMessages.noteSaved); - } catch (e) { - if (context.mounted) { - UiSnack.showError(TextBookMessages.noteSaveError(e)); - } - } + final panel = findPersonalNotesPanel(context); + await createPersonalNote( + context, + isNotesPanelOpen: panel?.isPersonalNotesPanelOpen ?? false, + title: 'הערה חדשה - $bookTitle', + bookId: notesKey, + categoryId: link.targetCategoryId, + lineNumber: link.index2, + referenceText: referenceText, + selectedText: selectedText, + sourceSelectedText: sourceSelection?.text, + sourceSelectionOffset: sourceSelection?.offset, + punctuationHidden: displayProfile.removePunctuation, + openNotesPanel: panel == null + ? null + : () => panel.revealPersonalNotesTarget( + notesKey, + link.targetCategoryId, + link.index2, + ), + ); } /// ממפה מפרש ([link] + תוכנו [rawContent]) לפרמטרי דיווח הטעות: הדיווח מופנה diff --git a/test/pdf_book/pdf_book_tab_test.dart b/test/pdf_book/pdf_book_tab_test.dart index c93d4a4afa..92fbd3b2da 100644 --- a/test/pdf_book/pdf_book_tab_test.dart +++ b/test/pdf_book/pdf_book_tab_test.dart @@ -28,6 +28,35 @@ void main() { await Settings.init(cacheProvider: MemorySettingsCache()); }); + test('בקשת נקודת הערה ממתינה לצפיין ונצרכת פעם אחת, גם באותה נקודה שוב', () { + final tab = _tab(); + addTearDown(tab.dispose); + const anchor = PdfNoteAnchor(pageNumber: 5, x: .25, y: .8); + var requests = 0; + tab.personalNoteNavigationRequests.addListener(() => requests++); + tab.requestPersonalNoteNavigation(anchor); + expect(requests, 1); + expect(tab.takePersonalNoteNavigationRequest(), anchor); + expect(tab.takePersonalNoteNavigationRequest(), isNull); + tab.requestPersonalNoteNavigation(anchor); + expect(requests, 2); + expect(tab.takePersonalNoteNavigationRequest(), anchor); + }); + + test('בקשת נקודת הערה אינה נשמרת בסשן או בהעתקת כרטיסייה', () { + final tab = _tab(); + addTearDown(tab.dispose); + const anchor = PdfNoteAnchor(pageNumber: 5, x: .25, y: .8); + tab.requestPersonalNoteNavigation(anchor); + final clone = tab.clone() as PdfBookTab; + final restored = PdfBookTab.fromJson(tab.toJson()); + addTearDown(clone.dispose); + addTearDown(restored.dispose); + expect(clone.takePersonalNoteNavigationRequest(), isNull); + expect(restored.takePersonalNoteNavigationRequest(), isNull); + expect(tab.takePersonalNoteNavigationRequest(), anchor); + }); + group('הכרעת הזזה אופקית לפי רוחב הדפים הנראים', () { late PdfBookTab tab; late _GeometryController controller; diff --git a/test/pdf_book/pdf_personal_note_anchor_test.dart b/test/pdf_book/pdf_personal_note_anchor_test.dart new file mode 100644 index 0000000000..8c91a6b1e0 --- /dev/null +++ b/test/pdf_book/pdf_personal_note_anchor_test.dart @@ -0,0 +1,194 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/pdf_book/utils/pdf_personal_note_anchor.dart'; +import 'package:otzaria/personal_notes/models/pdf_note_anchor.dart'; +import 'package:pdfrx/pdfrx.dart'; + +class _Page extends Fake implements PdfPage { + _Page(this.pageNumber, this.rotation, {this.isLoaded = true}); + + @override + final int pageNumber; + @override + final PdfPageRotation rotation; + @override + final bool isLoaded; + @override + double get width => rotation.index.isOdd ? 400 : 200; + @override + double get height => rotation.index.isOdd ? 200 : 400; +} + +class _Document extends Fake implements PdfDocument {} + +class _Controller extends PdfViewerController { + _Controller(this.pages, this.layout); + + @override + bool isReady = true; + @override + final List pages; + @override + int get pageCount => pages.length; + @override + final PdfPageLayout layout; + @override + PdfDocument document = _Document(); + @override + double get currentZoom => 2.75; + + Offset? destination; + double? usedZoom; + int? selectedPage; + + @override + Matrix4 calcMatrixFor(Offset position, {double? zoom, Size? viewSize}) { + destination = position; + usedZoom = zoom ?? currentZoom; + return Matrix4.identity(); + } + + @override + Future goTo( + Matrix4? destination, { + Duration duration = const Duration(milliseconds: 200), + }) async {} + + @override + void setCurrentPageNumber(int pageNumber) => selectedPage = pageNumber; +} + +void main() { + const anchor = PdfNoteAnchor(pageNumber: 2, x: .25, y: .75); + + test('גלילה רציפה כוללת גם עמוד סמוך שנראה חלקית', () { + const pages = [ + Rect.fromLTWH(10, 10, 200, 400), + Rect.fromLTWH(10, 420, 200, 400), + Rect.fromLTWH(10, 830, 200, 400), + ]; + expect( + visiblePdfNotePageNumbers( + pageLayouts: pages, + visibleRect: const Rect.fromLTWH(10, 300, 200, 200), + ), + [1, 2], + ); + expect( + visiblePdfNotePageNumbers( + pageLayouts: pages, + visibleRect: const Rect.fromLTWH(10, 425, 200, 390), + ), + [2], + ); + expect( + visiblePdfNotePageNumbers( + pageLayouts: pages, + visibleRect: const Rect.fromLTWH(10, 411, 200, 8), + ), + isEmpty, + ); + }); + + test('נקודה נשמרת בממדים המקוריים בכל ארבעת הסיבובים', () { + const expectedOffsets = [ + Offset(50, 100), + Offset(300, 50), + Offset(150, 300), + Offset(100, 150), + ]; + for (final rotation in PdfPageRotation.values) { + final page = _Page(2, rotation); + final uiPoint = expectedOffsets[rotation.index]; + final saved = pdfNoteAnchorFromHit( + PdfPageHitTestResult( + page: page, + offset: uiPoint.toPdfPoint(page: page), + ), + ); + expect(saved, anchor, reason: 'rotation ${rotation.index}'); + for (final scale in [.5, 1.0, 3.0]) { + final pageRect = Rect.fromLTWH( + 725, + 40, + page.width * scale, + page.height * scale, + ); + final restored = pdfNoteAnchorDocumentPosition( + saved!, + page: page, + pageRect: pageRect, + ); + expect( + restored, + Offset(725, 40) + uiPoint * scale, + reason: 'rotation ${rotation.index}, scale $scale', + ); + } + } + }); + + test('hit-test שומר את עמוד הלחיצה בכפולה ולא את עמוד הבקר', () { + final rightPage = _Page(3, PdfPageRotation.none); + expect( + pdfNoteAnchorFromHit( + PdfPageHitTestResult( + page: rightPage, + offset: const PdfPoint(50, 300), + ), + )?.pageNumber, + 3, + ); + }); + + test('עמוד שממדיו עדיין משוערים אינו מייצר עוגן שגוי', () { + expect( + pdfNoteAnchorFromHit( + PdfPageHitTestResult( + page: _Page(2, PdfPageRotation.none, isLoaded: false), + offset: const PdfPoint(50, 300), + ), + ), + isNull, + ); + expect(pdfNoteAnchorFromHit(null), isNull); + }); + + test('ניווט חוזר למקום בכפולה ושומר זום בלי להתבסס על שורת טקסט', () async { + final controller = _Controller( + [_Page(1, PdfPageRotation.none), _Page(2, PdfPageRotation.none)], + PdfPageLayout( + pageLayouts: const [ + Rect.fromLTWH(0, 0, 400, 800), + Rect.fromLTWH(420, 0, 400, 800), + ], + documentSize: const Size(820, 800), + ), + ); + expect(await navigateToPdfNoteAnchor(controller, anchor), isTrue); + expect(controller.destination, const Offset(520, 200)); + expect(controller.usedZoom, 2.75); + expect(controller.selectedPage, 2); + }); + + test('בקשה מבוטלת או עמוד שאינו קיים אינם מנווטים למקום אחר', () async { + final controller = _Controller( + [_Page(1, PdfPageRotation.none)], + PdfPageLayout( + pageLayouts: const [Rect.fromLTWH(0, 0, 200, 400)], + documentSize: const Size(200, 400), + ), + ); + expect(await navigateToPdfNoteAnchor(controller, anchor), isFalse); + expect( + await navigateToPdfNoteAnchor( + controller, + const PdfNoteAnchor(pageNumber: 1, x: .5, y: .5), + isActive: () => false, + ), + isFalse, + ); + expect(controller.destination, isNull); + expect(controller.selectedPage, isNull); + }); +} diff --git a/test/pdf_book/pdf_personal_note_viewer_test.dart b/test/pdf_book/pdf_personal_note_viewer_test.dart new file mode 100644 index 0000000000..9d8d4e5f0d --- /dev/null +++ b/test/pdf_book/pdf_personal_note_viewer_test.dart @@ -0,0 +1,338 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +// ignore: depend_on_referenced_packages +import 'package:material_ui/material_ui.dart' as mui; +import 'package:otzaria/core/app_paths.dart'; +import 'package:otzaria/models/book_source.dart'; +import 'package:otzaria/models/books.dart'; +import 'package:otzaria/pdf_book/bloc/pdf_book_bloc.dart'; +import 'package:otzaria/pdf_book/bloc/pdf_book_state.dart'; +import 'package:otzaria/pdf_book/utils/pdf_personal_note_anchor.dart'; +import 'package:otzaria/pdf_book/view/pdf_book_screen.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/storage/personal_notes_database.dart'; +import 'package:otzaria/personal_notes/utils/personal_notes_book_key.dart'; +import 'package:otzaria/personal_notes/widgets/note_tile.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_event.dart'; +import 'package:otzaria/settings/engine/settings_repository.dart'; +import 'package:otzaria/settings/engine/settings_state.dart'; +import 'package:otzaria/settings/services/per_book_settings_service.dart'; +import 'package:otzaria/tabs/bloc/tabs_bloc.dart'; +import 'package:otzaria/tabs/bloc/tabs_state.dart'; +import 'package:otzaria/tabs/models/pdf_tab.dart'; +import 'package:otzaria/tabs/tabs_repository.dart'; +import 'package:otzaria/tour/bloc/tour_cubit.dart'; +import 'package:otzaria/widgets/layout/adaptive_side_pane.dart'; +import 'package:pdf/pdf.dart' show PdfPageFormat; +import 'package:pdf/widgets.dart' as pw; +import 'package:pdfrx/pdfrx.dart'; + +import '../test_helpers/memory_cache_provider.dart'; + +class _NotesRepository extends PersonalNotesRepository { + @override + Future> loadNotes(String bookId, {int? categoryId}) => + PersonalNotesDatabase.instance.loadNotes(bookId); +} + +class _TabsRepository implements TabsRepository { + @override + dynamic noSuchMethod(Invocation invocation) { + if (invocation.memberName == #loadTabs) return []; + if (invocation.memberName == #loadCurrentTabIndex) return 0; + return Future.value(); + } +} + +class _SettingsBloc extends Bloc + implements SettingsBloc { + _SettingsBloc() : super(SettingsState.initial()) { + on((_, _) {}); + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('plugins.flutter.io/path_provider'); + final database = PersonalNotesDatabase.instance; + final originalModulePath = Pdfrx.pdfiumModulePath; + late Directory directory; + + setUp(() async { + await Settings.init(cacheProvider: MemoryCacheProvider()); + await database.close(); + directory = Directory.systemTemp.createTempSync('otzaria-pdf-notes-'); + AppPaths.debugOverrideDataRootPath(directory.path); + await Settings.setValue( + SettingsRepository.keyDatabasesPath, + '${directory.path}/databases', + ); + final module = Platform.isWindows + ? 'pdfium.dll' + : Platform.isMacOS + ? 'libpdfium.dylib' + : 'libpdfium.so'; + Pdfrx.pdfiumModulePath = File( + 'build/native_assets/${Platform.operatingSystem}/$module', + ).absolute.path; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (_) async => directory.path); + }); + + tearDown(() async { + await database.close(); + AppPaths.debugOverrideDataRootPath(null); + await Settings.setValue(SettingsRepository.keyDatabasesPath, ''); + Pdfrx.pdfiumModulePath = originalModulePath; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + directory.deleteSync(recursive: true); + }); + + Future settle(WidgetTester tester, int rounds) async { + for (var i = 0; i < rounds; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 10)), + ); + await tester.pump(const Duration(milliseconds: 20)); + } + } + + Future pumpUntil(WidgetTester tester, bool Function() condition) async { + for (var i = 0; i < 200 && !condition(); i++) { + await settle(tester, 1); + } + expect(condition(), isTrue); + } + + testWidgets('PDF אמיתי: ניווט, זהות, זום ובחירת נקודה בפאנל צר', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1200, 800)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + final file = File('${directory.path}/book.pdf'); + final book = PdfBook( + id: 12, + title: 'ספר בדיקה', + path: file.path, + source: BookSource.user, + ); + final other = PdfBook( + id: 12, + title: book.title, + path: '${directory.path}/another/book.pdf', + source: BookSource.user, + ); + final anchor = PdfNoteAnchor( + pageNumber: 2, + x: .35, + y: .65, + documentId: pdfPersonalNoteDocumentId(book), + ); + final otherAnchor = PdfNoteAnchor( + pageNumber: 2, + x: .6, + y: .5, + documentId: pdfPersonalNoteDocumentId(other), + ); + final key = personalNotesBookKey(book); + PersonalNote note(String id, PdfNoteAnchor point) => PersonalNote( + id: id, + bookId: key, + lineNumber: point.pageNumber, + lastKnownLineNumber: null, + pdfAnchor: point, + status: PersonalNoteStatus.located, + content: 'תוכן $id', + contentPlain: 'תוכן $id', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), + ); + await tester.runAsync(() async { + await pdfrxFlutterInitialize(); + final pdf = pw.Document(); + for (var i = 0; i < 3; i++) { + pdf.addPage( + pw.Page( + pageFormat: const PdfPageFormat(400, 500), + build: (_) => pw.Text('${i + 1}'), + ), + ); + } + await file.writeAsBytes(await pdf.save()); + await database.insertNote(note('current', anchor)); + await database.insertNote(note('other-document', otherAnchor)); + }); + final tab = PdfBookTab( + book: book, + pageNumber: 1, + requiresStableLayout: true, + )..requestPersonalNoteNavigation(anchor); + final slowSettings = Completer(); + unawaited( + PerBookSettings.runLockedForKey( + PerBookSettings.bookKey(book), + () => slowSettings.future, + ), + ); + final tabs = TabsBloc(repository: _TabsRepository()); + // ignore: invalid_use_of_visible_for_testing_member + tabs.emit(TabsState(tabs: [tab], currentTabIndex: 0)); + final settings = _SettingsBloc(); + final notes = PersonalNotesBloc(repository: _NotesRepository()); + final tour = TourCubit(); + addTearDown(tabs.close); + addTearDown(settings.close); + addTearDown(notes.close); + addTearDown(tour.close); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: const [ + mui.DefaultMaterialLocalizations.delegate, + ], + home: MultiBlocProvider( + providers: [ + BlocProvider.value(value: settings), + BlocProvider.value(value: tabs), + BlocProvider.value(value: notes), + BlocProvider.value(value: tour), + ], + child: PdfBookScreen(tab: tab), + ), + ), + ); + final controller = tab.pdfViewerController; + await pumpUntil(tester, () => controller.isReady); + await settle(tester, 5); + final params = tester.widget(find.byType(PdfViewer)).params; + // הסשן הראשון מחכה להגדרות כאשר מתקבל document-change. ההמשך הישן + // אינו רשאי לפתוח פאנל או לצרוך את הבקשה השמורה עבור הסשן הבא. + params.onDocumentChanged!(null); + slowSettings.complete(); + await settle(tester, 30); + expect(notes.state.expandRequestPdfAnchor, isNull); + expect(tab.takePersonalNoteNavigationRequest(), anchor); + tab.requestPersonalNoteNavigation(anchor); + params.onViewerReady!(controller.document, controller); + await pumpUntil( + tester, + () => + find.byType(PersonalNotesSidebar).evaluate().isNotEmpty && + notes.state.expandRequestPdfAnchor == anchor, + ); + await settle(tester, 40); + + final pdfBloc = tester.element(find.byType(PdfViewer)).read(); + expect((pdfBloc.state as PdfBookLoaded).showRightPane, isTrue); + final marker = find.byKey(const ValueKey('pdf-note-current')); + expect(marker, findsOneWidget); + expect(find.byKey(const ValueKey('pdf-note-other-document')), findsNothing); + final tile = tester.widget(find.byKey(const ValueKey('current'))); + expect(tile.expandToken, notes.state.expandRequestToken); + expect(find.byKey(const ValueKey('other-document')), findsNothing); + + Offset documentPoint() => pdfNoteAnchorDocumentPosition( + anchor, + page: controller.pages[anchor.pageNumber - 1], + pageRect: controller.layout.pageLayouts[anchor.pageNumber - 1], + ); + void expectMarkerAtAnchor() { + final global = controller.documentToGlobal(documentPoint())!; + final center = tester.getCenter(marker); + expect(center.dx, closeTo(global.dx, 1)); + expect(center.dy, closeTo(global.dy, 1)); + expect(controller.visibleRect.contains(documentPoint()), isTrue); + } + + expectMarkerAtAnchor(); + final oldZoom = controller.currentZoom; + final zoom = controller.goTo( + controller.calcMatrixFor(documentPoint(), zoom: oldZoom * 1.5), + duration: Duration.zero, + ); + await settle(tester, 15); + await tester.runAsync(() => zoom); + expect(controller.currentZoom, greaterThan(oldZoom)); + expectMarkerAtAnchor(); + + await tester.binding.setSurfaceSize(const Size(420, 800)); + await settle(tester, 20); + AdaptiveSidePane notesPane() => tester.widget( + find.byWidgetPredicate( + (widget) => + widget is AdaptiveSidePane && + widget.alignment == AlignmentDirectional.centerStart, + ), + ); + Future beginReanchor() async { + final sidebar = tester.widget( + find.byType(PersonalNotesSidebar), + ); + await sidebar.onReanchorNote!(note('current', anchor)); + await settle(tester, 15); + // ההסתרה זמנית לתצוגה: ההחלטה על עורך inline נשארת לפי המצב הלוגי. + expect((pdfBloc.state as PdfBookLoaded).showRightPane, isTrue); + expect(notesPane().isOpen, isFalse); + } + + await beginReanchor(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await settle(tester, 15); + expect(notesPane().isOpen, isTrue); + await beginReanchor(); + final newAnchor = PdfNoteAnchor( + pageNumber: 2, + x: .45, + y: .6, + documentId: anchor.documentId, + ); + final newPosition = pdfNoteAnchorDocumentPosition( + newAnchor, + page: controller.pages[1], + pageRect: controller.layout.pageLayouts[1], + ); + final reposition = controller.goTo( + controller.calcMatrixFor(newPosition), + duration: Duration.zero, + ); + await settle(tester, 5); + await tester.runAsync(() => reposition); + await tester.tapAt(controller.documentToGlobal(newPosition)!); + await settle(tester, 30); + final stored = await tester.runAsync(() => database.loadNotes(key)); + final moved = stored!.singleWhere((note) => note.id == 'current'); + expect(moved.content, 'תוכן current'); + expect(moved.pdfAnchor!.documentId, anchor.documentId); + expect(moved.pdfAnchor!.pageNumber, 2); + expect(moved.pdfAnchor!.x, closeTo(.45, .00001)); + expect(moved.pdfAnchor!.y, closeTo(.6, .00001)); + expect(notesPane().isOpen, isTrue); + await beginReanchor(); + tester.widget(find.byType(PdfViewer)).params.onDocumentChanged!( + null, + ); + await settle(tester, 15); + expect( + notesPane().isOpen, + isTrue, + reason: 'החלפת מסמך מבטלת בחירת נקודה ומחזירה את הפאנל', + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await settle(tester, 10); + }); +} diff --git a/test/personal_notes/bloc/personal_notes_visible_filter_test.dart b/test/personal_notes/bloc/personal_notes_visible_filter_test.dart index 094a596996..37d746047a 100644 --- a/test/personal_notes/bloc/personal_notes_visible_filter_test.dart +++ b/test/personal_notes/bloc/personal_notes_visible_filter_test.dart @@ -6,6 +6,7 @@ import 'package:otzaria/personal_notes/bloc/personal_notes_event.dart'; import 'package:otzaria/personal_notes/bloc/personal_notes_state.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/utils/open_personal_notes_target.dart'; import '../../test_helpers/memory_cache_provider.dart'; @@ -135,6 +136,66 @@ void main() { }); group('טעינה מחדש שומרת על הסינון', () { + blocTest( + 'פתיחת יעד עם קטגוריה נשמרת גם כשהקורא נטען תחילה בלי קטגוריה', + build: buildBloc, + act: (bloc) async { + bloc.add(const LoadPersonalNotes(bookId)); + await bloc.stream.firstWhere((state) => !state.isLoading); + openPersonalNotesTarget( + bloc, + bookId: bookId, + categoryId: 9, + lineNumber: 50, + ); + await bloc.stream.firstWhere( + (state) => + !state.isLoading && + state.categoryId == 9 && + state.expandRequestLineNumber == 50, + ); + bloc.add(const LoadPersonalNotes(bookId, categoryId: 9)); + await bloc.stream.firstWhere((state) => !state.isLoading); + }, + verify: (bloc) { + expect(bloc.state.categoryId, 9); + expect(bloc.state.expandRequestLineNumber, 50); + }, + ); + + blocTest( + 'בקשת הרחבה נשמרת ברענון אותו ספר', + build: buildBloc, + act: (bloc) async { + bloc.add(const LoadPersonalNotes(bookId)); + await bloc.stream.firstWhere((state) => !state.isLoading); + bloc.add(const RequestExpandNotesForLine(50)); + bloc.add(const LoadPersonalNotes(bookId)); + await bloc.stream.firstWhere( + (state) => !state.isLoading && state.expandRequestToken == 1, + ); + }, + verify: (bloc) { + expect(bloc.state.expandRequestLineNumber, 50); + expect(bloc.state.expandRequestToken, 1); + }, + ); + + blocTest( + 'בקשת הרחבה אינה עוברת לספר אחר', + build: buildBloc, + act: (bloc) async { + bloc.add(const LoadPersonalNotes(bookId)); + await bloc.stream.firstWhere((state) => !state.isLoading); + bloc.add(const RequestExpandNotesForLine(50)); + bloc.add(const LoadPersonalNotes('ספר אחר')); + await bloc.stream.firstWhere( + (state) => !state.isLoading && state.bookId == 'ספר אחר', + ); + }, + verify: (bloc) => expect(bloc.state.expandRequestLineNumber, isNull), + ); + blocTest( 'רענון אותו ספר שומר את השורות הגלויות (אחרת הסינון היה נופל ' 'וכל הספר היה מוצג)', diff --git a/test/personal_notes/imported_delta_preview_test.dart b/test/personal_notes/imported_delta_preview_test.dart index 3a1d455af4..04427f2d0e 100644 --- a/test/personal_notes/imported_delta_preview_test.dart +++ b/test/personal_notes/imported_delta_preview_test.dart @@ -172,19 +172,20 @@ void main() { home: Directionality( textDirection: TextDirection.rtl, child: Scaffold( - body: UnconstrainedBox( - constrainedAxis: Axis.horizontal, - alignment: Alignment.topCenter, - child: SizedBox( - key: key, - width: 400, - child: PersonalNoteContentView( - note: note, - interactive: interactive, - maxPreviewChars: 280, - textStyle: const TextStyle( - fontSize: 12, - color: Color(0xff444444), + body: SingleChildScrollView( + child: Align( + alignment: Alignment.topCenter, + child: SizedBox( + key: key, + width: 400, + child: PersonalNoteContentView( + note: note, + interactive: interactive, + maxPreviewChars: 280, + textStyle: const TextStyle( + fontSize: 12, + color: Color(0xff444444), + ), ), ), ), diff --git a/test/personal_notes/note_delta_preview_test.dart b/test/personal_notes/note_delta_preview_test.dart index 4b65223496..caf6d5f624 100644 --- a/test/personal_notes/note_delta_preview_test.dart +++ b/test/personal_notes/note_delta_preview_test.dart @@ -128,6 +128,8 @@ void main() { fontSize: 12, height: 1.45, color: Color(0xFF444444), + fontFamily: 'serif', + fontWeight: FontWeight.w500, ), ), ), @@ -235,6 +237,25 @@ void main() { ); }); + testWidgets('תצוגה אינטראקטיבית וקלה יורשות את הגופן והצבע של ההערה', ( + tester, + ) async { + for (final interactive in [true, false]) { + await pump( + tester, + note([ + {'insert': 'הערה בעברית\n'}, + ]), + interactive: interactive, + ); + final style = renderedRuns(tester)['הערה בעברית']!; + expect(style.color, const Color(0xFF444444)); + expect(style.fontFamily, 'serif'); + expect(style.fontWeight, FontWeight.w500); + expect(style.height, 1.5); + } + }); + testWidgets('עיצוב, רשימות, ציטוט וקישורים זהים לעורך Quill', ( tester, ) async { diff --git a/test/personal_notes/open_personal_notes_target_test.dart b/test/personal_notes/open_personal_notes_target_test.dart index fa27206cae..63328f6df1 100644 --- a/test/personal_notes/open_personal_notes_target_test.dart +++ b/test/personal_notes/open_personal_notes_target_test.dart @@ -3,6 +3,7 @@ import 'package:flutter_test/flutter_test.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/bloc/personal_notes_state.dart'; +import 'package:otzaria/personal_notes/models/pdf_note_anchor.dart'; import 'package:otzaria/personal_notes/utils/open_personal_notes_target.dart'; class _RecordingPersonalNotesBloc @@ -42,4 +43,28 @@ void main() { expect(bloc.events[2], const LoadPersonalNotes('רש"י', categoryId: 9)); expect(bloc.events[3], const RequestExpandNotesForLine(7)); }); + + test('פתיחת PDF שומרת את הנקודה המדויקת בבקשת ההרחבה', () async { + final bloc = _RecordingPersonalNotesBloc( + const PersonalNotesState.initial().copyWith(showOnlyVisible: false), + ); + addTearDown(bloc.close); + const anchor = PdfNoteAnchor( + pageNumber: 7, + x: .2, + y: .8, + documentId: 'user|document.pdf', + ); + openPersonalNotesTarget( + bloc, + bookId: 'ספר בדיקה', + lineNumber: 7, + pdfAnchor: anchor, + ); + await Future.delayed(Duration.zero); + expect(bloc.events, [ + const LoadPersonalNotes('ספר בדיקה'), + const RequestExpandNotesForLine(7, pdfAnchor: anchor), + ]); + }); } diff --git a/test/personal_notes/personal_note_content_view_context_menu_test.dart b/test/personal_notes/personal_note_content_view_context_menu_test.dart index f9f8602b33..5944c0614b 100644 --- a/test/personal_notes/personal_note_content_view_context_menu_test.dart +++ b/test/personal_notes/personal_note_content_view_context_menu_test.dart @@ -10,6 +10,7 @@ import 'package:otzaria/personal_notes/models/personal_note.dart'; import 'package:otzaria/personal_notes/widgets/personal_note_content_view.dart'; import 'package:otzaria/widgets/misc/app_menu_exports.dart'; import 'package:otzaria/widgets/misc/app_selection_area.dart'; +import 'package:otzaria/widgets/text/selection_copy_shortcuts.dart'; /// issue #1271 — בתיבת הריחוף של הערה (עטופה ב-AppSelectionArea) לחיצה ימנית /// פתחה גם את תפריט ההעתקה של אוצריא וגם את תפריט Flutter של עורך ההערה. @@ -149,6 +150,82 @@ void main() { }); }); + // #3260: גרירה בתצוגת הקריאה של ההערה משאירה בחירה בלי פוקוס ב-Quill. + // לכן Ctrl+C הגיע לקורא, גם כשהטקסט המסומן היה בגוף ההערה. + for (final withSelectionArea in [false, true]) { + testWidgets( + 'Ctrl+C אחרי גרירה בהערה לא ממוקדת מעתיק אותה (מארח: $withSelectionArea)', + (tester) async { + await onPlatform(TargetPlatform.windows, () async { + final clipboardWrites = []; + mockClipboard(tester, clipboardWrites); + final readerFocus = FocusNode(); + addTearDown(readerFocus.dispose); + var readerCopies = 0; + final content = PersonalNoteContentView(note: note()); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Column( + children: [ + SelectionCopyShortcuts( + onCopy: () => readerCopies++, + child: SelectionArea( + focusNode: readerFocus, + child: const Text('טקסט הקורא'), + ), + ), + withSelectionArea + ? AppSelectionArea(child: content) + : content, + ], + ), + ), + ), + ); + readerFocus.requestFocus(); + await tester.pumpAndSettle(); + expect(readerFocus.hasFocus, isTrue); + final editor = tester.widget( + find.byType(quill.QuillEditor), + ); + expect(editor.focusNode.hasFocus, isFalse); + + final line = tester.getRect(find.text(noteText, findRichText: true)); + final gesture = await tester.startGesture( + line.centerLeft + const Offset(2, 0), + kind: PointerDeviceKind.mouse, + ); + await tester.pump(); + for (var step = 0; step < 5; step++) { + await gesture.moveBy(const Offset(6, 0)); + await tester.pump(); + } + await gesture.up(); + await tester.pumpAndSettle(); + final selectedText = editor.controller.getPlainText(); + expect(editor.controller.selection.isCollapsed, isFalse); + expect(selectedText, isNotEmpty); + expect(selectedText, isNot(noteText)); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyC); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); + + expect(readerCopies, 0, reason: 'הבחירה הפעילה נמצאת בהערה'); + expect(clipboardWrites.where((text) => text.isNotEmpty), [ + selectedText, + ]); + expect( + editor.controller.document.toPlainText().trimRight(), + noteText, + ); + }); + }, + ); + } + // עורך Quill אינו מדווח ל-SelectionArea, ובלי רישום הבחירה "העתק" של תיבת // הריחוף נשאר מושבת (issue #1595). testWidgets('בתוך AppSelectionArea "העתק" מעתיק את הבחירה של Quill', ( diff --git a/test/personal_notes/personal_note_draft_service_test.dart b/test/personal_notes/personal_note_draft_service_test.dart index d20c15760e..c73e5b4f52 100644 --- a/test/personal_notes/personal_note_draft_service_test.dart +++ b/test/personal_notes/personal_note_draft_service_test.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/settings/engine/app_settings_store.dart'; @@ -135,4 +136,304 @@ void main() { expect(box.containsKey('personal_note_draft:ספר ג:5'), isFalse); expect(await service.loadDraft(bookId: 'ספר ג', lineNumber: 5), isNull); }); + + test('טיוטת PDF משמרת נקודה פיזית בשמירה ובשחזור האחרון', () async { + const anchor = PdfNoteAnchor(pageNumber: 12, x: .37, y: .82); + final service = PersonalNoteDraftService(); + await service.saveDraft( + bookId: 'מסמך בדיקה|user', + lineNumber: 12, + draft: PersonalNoteDraft( + content: 'טיוטה', + contentPlain: 'טיוטה', + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime.utc(2026, 1, 1), + lineNumber: 12, + pdfAnchor: anchor, + ), + ); + expect( + (await service.loadDraft( + bookId: 'מסמך בדיקה|user', + lineNumber: 12, + pdfAnchor: anchor, + ))!.pdfAnchor, + anchor, + ); + expect( + (await service.loadLatestNewNoteDraft( + bookId: 'מסמך בדיקה|user', + ))!.pdfAnchor, + anchor, + ); + }); + + test( + 'טיוטות בשתי נקודות באותו עמוד אינן דורסות או מוחקות זו את זו', + () async { + final service = PersonalNoteDraftService(); + const first = PdfNoteAnchor(pageNumber: 4, x: .2, y: .3); + const second = PdfNoteAnchor(pageNumber: 4, x: .7, y: .8); + for (final (anchor, content) in [ + (first, 'נקודה א'), + (second, 'נקודה ב'), + ]) { + await service.saveDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + draft: PersonalNoteDraft( + content: content, + contentPlain: content, + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime.utc(2026, 1, 1), + pdfAnchor: anchor, + ), + ); + } + expect( + (await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + pdfAnchor: first, + ))?.contentPlain, + 'נקודה א', + ); + expect( + (await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + pdfAnchor: second, + ))?.contentPlain, + 'נקודה ב', + ); + expect( + await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + ), + isNull, + ); + await service.clearDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + pdfAnchor: second, + ); + expect( + await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + pdfAnchor: second, + ), + isNull, + ); + expect( + (await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + pdfAnchor: first, + ))?.contentPlain, + 'נקודה א', + ); + }, + ); + + test('טיוטת נקודה במפתח ישן נטענת רק לאותו עוגן ומועברת בלי אובדן', () async { + final service = PersonalNoteDraftService(); + const anchor = PdfNoteAnchor(pageNumber: 4, x: .2, y: .3); + final legacy = PersonalNoteDraft( + content: 'טיוטה ישנה', + contentPlain: 'טיוטה ישנה', + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime.utc(2026, 1, 1), + lineNumber: 4, + pdfAnchor: anchor, + ); + await Settings.setValue( + 'personal_note_draft:מסמך בדיקה@7:4', + jsonEncode(legacy.toJson()), + ); + expect( + await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + ), + isNull, + ); + expect( + await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + pdfAnchor: const PdfNoteAnchor(pageNumber: 4, x: .8, y: .9), + ), + isNull, + ); + expect( + (await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + pdfAnchor: anchor, + ))?.contentPlain, + 'טיוטה ישנה', + ); + await service.clearDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + ); + await service.saveDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + draft: PersonalNoteDraft( + content: 'טיוטת טקסט', + contentPlain: 'טיוטת טקסט', + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime.utc(2026, 1, 2), + ), + ); + expect( + (await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + pdfAnchor: anchor, + ))?.contentPlain, + 'טיוטה ישנה', + ); + expect( + (await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + ))?.contentPlain, + 'טיוטת טקסט', + ); + }); + + test('טיוטות באותה נקודה במסמכים בעלי אותו שם נשמרות בנפרד', () async { + final service = PersonalNoteDraftService(); + const first = PdfNoteAnchor( + pageNumber: 4, + x: .2, + y: .3, + documentId: 'edition-a', + ); + const second = PdfNoteAnchor( + pageNumber: 4, + x: .2, + y: .3, + documentId: 'edition-b', + ); + for (final (anchor, content, day) in [ + (first, 'מסמך א', 1), + (second, 'מסמך ב', 2), + ]) { + await service.saveDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + draft: PersonalNoteDraft( + content: content, + contentPlain: content, + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime.utc(2026, 1, day), + pdfAnchor: anchor, + ), + ); + } + expect( + (await service.loadLatestNewNoteDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + pdfDocumentId: 'edition-a', + ))?.contentPlain, + 'מסמך א', + ); + expect( + (await service.loadLatestNewNoteDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + pdfDocumentId: 'edition-b', + ))?.contentPlain, + 'מסמך ב', + ); + await service.clearDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + pdfAnchor: second, + ); + expect( + (await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + pdfAnchor: first, + ))?.contentPlain, + 'מסמך א', + ); + expect( + await service.loadDraft( + bookId: 'מסמך בדיקה', + categoryId: 7, + lineNumber: 4, + pdfAnchor: second, + ), + isNull, + ); + }); + + test('שחזור אחרון שומר על ספר וקטגוריה ומאפשר להחריג נקודות PDF', () async { + final service = PersonalNoteDraftService(); + for (final (bookId, category, anchor, day, content) in [ + ('מסמך בדיקה|user', 7, null, 1, 'טקסט'), + ( + 'מסמך בדיקה|user', + 7, + const PdfNoteAnchor(pageNumber: 4, x: .2, y: .3), + 2, + 'נקודה', + ), + ('מסמך בדיקה|user', 8, null, 3, 'קטגוריה אחרת'), + ('מסמך בדיקה|other', 7, null, 4, 'מקור אחר'), + ]) { + await service.saveDraft( + bookId: bookId, + categoryId: category, + lineNumber: 4, + draft: PersonalNoteDraft( + content: content, + contentPlain: content, + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime.utc(2026, 1, day), + pdfAnchor: anchor, + ), + ); + } + expect( + (await service.loadLatestNewNoteDraft( + bookId: 'מסמך בדיקה|user', + categoryId: 7, + ))?.contentPlain, + 'נקודה', + ); + expect( + (await service.loadLatestNewNoteDraft( + bookId: 'מסמך בדיקה|user', + categoryId: 7, + includePdfAnchors: false, + ))?.contentPlain, + 'טקסט', + ); + }); } diff --git a/test/personal_notes/personal_notes_book_key_test.dart b/test/personal_notes/personal_notes_book_key_test.dart index 8a3dbf8feb..82aa4aa34e 100644 --- a/test/personal_notes/personal_notes_book_key_test.dart +++ b/test/personal_notes/personal_notes_book_key_test.dart @@ -2,6 +2,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/library/models/library.dart'; import 'package:otzaria/models/book_source.dart'; import 'package:otzaria/models/books.dart'; +import 'package:otzaria/personal_notes/models/pdf_note_anchor.dart'; import 'package:otzaria/personal_notes/utils/personal_notes_book_key.dart'; Library _library(List books) { @@ -22,6 +23,111 @@ Library _library(List books) { void main() { final attachedSource = BookSource.attached('lib-a'); + test('PDF עם id שאול וכותרת זהה מובחן לפי הקובץ', () { + final first = PdfBook(id: 1, title: 'מסמך', path: '/one/document.pdf'); + final second = PdfBook(id: 1, title: 'מסמך', path: '/two/document.pdf'); + final library = _library([first, second]); + final identity = pdfPersonalNoteDocumentId(second); + expect(identity, isNot(pdfPersonalNoteDocumentId(first))); + expect(findPdfBookForPersonalNotesKey(library, 'מסמך'), isNull); + expect( + findPdfBookForPersonalNotesKey(library, 'מסמך', documentId: identity), + same(second), + ); + final anchor = PdfNoteAnchor( + pageNumber: 3, + x: .4, + y: .7, + documentId: identity, + ); + expect( + pdfPersonalNoteAnchorMatchesBook(anchor, first, library: library), + isFalse, + ); + expect( + pdfPersonalNoteAnchorMatchesBook(anchor, second, library: library), + isTrue, + ); + }); + + test('עוגן ללא זהות נפתר רק ל-PDF יחיד, גם כשאותו ספר נמצא פעמיים בעץ', () { + final book = PdfBook(title: 'מסמך', path: '/one/document.pdf'); + final library = _library([book])..offTreeBooks = [book]; + const anchor = PdfNoteAnchor(pageNumber: 3, x: .4, y: .7); + expect(findPdfBookForPersonalNotesKey(library, 'מסמך'), same(book)); + expect( + pdfPersonalNoteAnchorMatchesBook(anchor, book, library: library), + isTrue, + ); + library.offTreeBooks = [PdfBook(title: 'מסמך', path: '/two/document.pdf')]; + expect(findPdfBookForPersonalNotesKey(library, 'מסמך'), isNull); + expect( + pdfPersonalNoteAnchorMatchesBook(anchor, book, library: library), + isFalse, + ); + }); + + test('זהות PDF מכבדת מקור ומזהה קטלוג חיצוני או מסד מצורף', () { + final official = PdfBook(title: 'מסמך', path: '/same.pdf'); + final user = PdfBook( + title: 'מסמך', + path: '/same.pdf', + source: BookSource.user, + ); + expect( + pdfPersonalNoteDocumentId(official), + isNot(pdfPersonalNoteDocumentId(user)), + ); + final first = PdfBook( + id: 3, + title: 'מסמך', + path: '/old.pdf', + source: attachedSource, + ); + final moved = PdfBook( + id: 3, + title: 'מסמך', + path: '/new.pdf', + source: attachedSource, + ); + expect(pdfPersonalNoteDocumentId(first), pdfPersonalNoteDocumentId(moved)); + final external = PdfBook( + title: 'מסמך', + path: '/old.pdf', + externalLibraryId: 'fixture:17', + ); + final externalMoved = PdfBook( + title: 'מסמך', + path: '/new.pdf', + externalLibraryId: 'fixture:17', + ); + expect( + pdfPersonalNoteDocumentId(external), + pdfPersonalNoteDocumentId(externalMoved), + ); + expect( + findPdfBookForPersonalNotesKey( + _library([moved]), + personalNotesBookKey(first), + documentId: pdfPersonalNoteDocumentId(first), + ), + same(moved), + ); + }); + + test('נתיב PDF שהוחלף אינו מנווט אוטומטית לקובץ אחר באותה כותרת', () { + final old = PdfBook(title: 'מסמך', path: '/old.pdf'); + final replacement = PdfBook(title: 'מסמך', path: '/replacement.pdf'); + expect( + findPdfBookForPersonalNotesKey( + _library([replacement]), + 'מסמך', + documentId: pdfPersonalNoteDocumentId(old), + ), + isNull, + ); + }); + test('title key never resolves to an attached book of the same title', () { final attached = TextBook(id: 1, title: 'book', source: attachedSource); final library = _library([attached]); diff --git a/test/personal_notes/personal_notes_manager_loading_test.dart b/test/personal_notes/personal_notes_manager_loading_test.dart new file mode 100644 index 0000000000..741fc8a84b --- /dev/null +++ b/test/personal_notes/personal_notes_manager_loading_test.dart @@ -0,0 +1,774 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:bloc_test/bloc_test.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.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/core/messages/notes_messages.dart'; +import 'package:otzaria/core/ui_snack.dart'; +import 'package:otzaria/core/windowing/dialog_owner.dart'; +import 'package:otzaria/library/bloc/library_bloc.dart'; +import 'package:otzaria/library/bloc/library_event.dart'; +import 'package:otzaria/library/bloc/library_state.dart'; +import 'package:otzaria/library/models/library.dart'; +import 'package:otzaria/models/books.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/storage/personal_notes_database.dart'; +import 'package:otzaria/personal_notes/view/personal_notes_screen.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_editor_dialog.dart'; +import 'package:otzaria/personal_notes/widgets/personal_notes_export_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 'package:otzaria/widgets/controls/bar_button.dart'; +// ignore: depend_on_referenced_packages +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +import '../test_helpers/memory_cache_provider.dart'; + +class _LibraryBloc extends MockBloc + implements LibraryBloc {} + +class _SourceBook extends TextBook { + _SourceBook() : super(id: 1, title: 'ספר א', categoryId: 47); + + @override + Future> get tableOfContents async => const []; +} + +class _ExportPicker extends FilePickerPlatform with MockPlatformInterfaceMixin { + Uint8List? bytes; + + @override + Future saveFile({ + required String fileName, + required Uint8List bytes, + String mimeType = 'application/octet-stream', + String? dialogTitle, + String? initialDirectory, + Function(FilePickerStatus)? onFileSaving, + WindowsOptions windowsOptions = const WindowsOptions(), + LinuxOptions linuxOptions = const LinuxOptions(), + WebOptions webOptions = const WebOptions(), + }) async { + this.bytes = bytes; + return null; + } +} + +PersonalNote _note(String bookId, String content) => PersonalNote( + id: 'note-$bookId', + bookId: bookId, + lineNumber: 1, + lastKnownLineNumber: null, + status: PersonalNoteStatus.located, + content: content, + contentPlain: content, + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), +); + +BookNotesInfo _book(String id) => BookNotesInfo( + bookId: id, + noteCount: 1, + lastUpdated: DateTime(2026), +); + +class _Repository extends PersonalNotesRepository { + _Repository(this.notes); + + final Map> notes; + bool delayLists = false; + bool delayFullNotes = false; + bool delayStoredNotes = false; + bool delayUpdates = false; + final updateRequests = >[]; + final updateTargets = <({String bookId, String noteId, int? categoryId})>[]; + final listRequests = >>[]; + final fullRequests = >>>{}; + final storedRequests = >>>{}; + final fullReads = []; + final storedReads = []; + int listReads = 0; + + @override + Future> listBooksWithNotes() { + listReads++; + if (delayLists) { + final request = Completer>(); + listRequests.add(request); + return request.future; + } + return Future.value([ + for (final entry in notes.entries) + if (entry.value.isNotEmpty) + BookNotesInfo( + bookId: entry.key, + noteCount: entry.value.length, + lastUpdated: DateTime(2026), + ), + ]); + } + + Future> _read( + String bookId, { + required bool delayed, + required Map>>> requests, + }) { + if (!delayed) return Future.value(List.of(notes[bookId] ?? const [])); + final request = Completer>(); + requests.putIfAbsent(bookId, () => []).add(request); + return request.future; + } + + @override + Future> loadNotes(String bookId, {int? categoryId}) { + fullReads.add(bookId); + return _read(bookId, delayed: delayFullNotes, requests: fullRequests); + } + + @override + Future> loadStoredNotes(String bookId) { + storedReads.add(bookId); + return _read(bookId, delayed: delayStoredNotes, requests: storedRequests); + } + + @override + Future persistNote({ + required String bookId, + required String noteId, + required String content, + required String contentPlain, + required PersonalNoteContentFormat contentFormat, + int? categoryId, + }) async { + updateTargets.add((bookId: bookId, noteId: noteId, categoryId: categoryId)); + if (delayUpdates) { + final request = Completer(); + updateRequests.add(request); + await request.future; + } + notes[bookId] = [ + for (final note in notes[bookId] ?? const []) + if (note.id == noteId) + note.copyWith( + content: content, + contentPlain: contentPlain, + contentFormat: contentFormat, + ) + else + note, + ]; + PersonalNotesChanges.notify(bookId); + return notes[bookId]!.singleWhere((note) => note.id == noteId); + } + + void completePending() { + for (final request in updateRequests) { + if (!request.isCompleted) request.complete(); + } + for (final request in listRequests) { + if (!request.isCompleted) request.complete(const []); + } + for (final requests in [fullRequests, storedRequests]) { + for (final bookRequests in requests.values) { + for (final request in bookRequests) { + if (!request.isCompleted) request.complete(const []); + } + } + } + } +} + +Future _pump(WidgetTester tester, [int count = 8]) async { + for (var i = 0; i < count; i++) { + await tester.pump(const Duration(milliseconds: 1)); + } +} + +void _expectExportEnabled(WidgetTester tester, bool enabled) { + for (final tooltip in ['גיבוי הערות', 'ייצוא לטקסט', 'ייצוא לוורד']) { + final button = tester.widget( + find.byWidgetPredicate( + (widget) => widget is BarButton && widget.tooltip == tooltip, + ), + ); + expect(button.onPressed != null, enabled, reason: tooltip); + } +} + +Future _mount( + WidgetTester tester, + _Repository repository, { + Library? library, +}) async { + tester.view.physicalSize = const Size(1600, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final notesBloc = PersonalNotesBloc(repository: repository); + final settingsRepository = SettingsRepository(); + final settingsBloc = SettingsBloc(repository: settingsRepository); + final libraryBloc = _LibraryBloc(); + whenListen( + libraryBloc, + const Stream.empty(), + initialState: LibraryState( + library: library ?? Library(categories: []), + isLoading: false, + ), + ); + addTearDown(() async { + UiSnack.hide(); + await tester.pumpWidget(const SizedBox.shrink()); + repository.completePending(); + await tester.pump(); + await notesBloc.close(); + await settingsBloc.close(); + await libraryBloc.close(); + }); + await tester.pumpWidget( + MultiBlocProvider( + providers: [ + RepositoryProvider.value(value: settingsRepository), + BlocProvider.value(value: settingsBloc), + BlocProvider.value(value: libraryBloc), + BlocProvider.value(value: notesBloc), + ], + child: MaterialApp( + navigatorKey: navigatorKey, + home: Scaffold( + body: PersonalNotesManagerScreen(repository: repository), + ), + ), + ), + ); + await _pump(tester); + return notesBloc; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + await Settings.init(cacheProvider: MemoryCacheProvider()); + }); + + testWidgets('manager completes while the shared reader loads another book', ( + tester, + ) async { + final noteA = _note('ספר א', 'תוכן מנהל א'); + final noteB = _note('ספר ב', 'תוכן קורא ב'); + final repository = _Repository({ + 'ספר א': [noteA], + 'ספר ב': [noteB], + })..delayFullNotes = true; + final reader = await _mount(tester, repository); + expect(repository.fullRequests['ספר א'], hasLength(1)); + + // The real restartable BLoC must remain free for a reader while A is pending. + reader.add(const LoadPersonalNotes('ספר ב', categoryId: 91)); + await _pump(tester); + repository.fullRequests['ספר ב']!.first.complete([noteB]); + await _pump(tester); + expect(reader.state.bookId, 'ספר ב'); + expect(reader.state.categoryId, 91); + + repository.fullRequests['ספר א']!.single.complete([noteA]); + await _pump(tester); + expect(find.text('תוכן מנהל א'), findsOneWidget); + _expectExportEnabled(tester, false); + expect(repository.fullRequests['ספר ב'], hasLength(2)); + repository.fullRequests['ספר ב']!.last.complete([noteB]); + await _pump(tester); + + expect(find.text('תוכן מנהל א'), findsOneWidget); + expect(find.text('תוכן קורא ב'), findsOneWidget); + expect(reader.state.bookId, 'ספר ב'); + expect(reader.state.categoryId, 91); + expect(reader.state.locatedNotes, [noteB]); + _expectExportEnabled(tester, true); + }); + + testWidgets('an older book-list response cannot replace a newer refresh', ( + tester, + ) async { + final repository = _Repository({ + 'ספר א': [_note('ספר א', 'תוכן ראשוני')], + 'ספר ג': [_note('ספר ג', 'תוכן רענון חדש')], + }); + await _mount(tester, repository); + repository.delayLists = true; + final readsBefore = repository.fullReads.length; + await tester.tap(find.byTooltip('רענן')); + await _pump(tester); + await tester.tap(find.byTooltip('רענן')); + await _pump(tester); + expect(repository.listRequests, hasLength(2)); + _expectExportEnabled(tester, false); + + repository.listRequests.last.complete([_book('ספר ג')]); + await _pump(tester); + expect(find.text('תוכן רענון חדש'), findsOneWidget); + expect(find.text('תוכן ראשוני'), findsNothing); + repository.listRequests.first.complete([_book('ספר א')]); + await _pump(tester); + + expect(find.text('תוכן רענון חדש'), findsOneWidget); + expect(find.text('תוכן ראשוני'), findsNothing); + expect(repository.fullReads.skip(readsBefore), ['ספר ג']); + _expectExportEnabled(tester, true); + }); + + testWidgets('late note completion from an older refresh is ignored', ( + tester, + ) async { + final old = _note('ספר א', 'תוכן מבקשה ישנה'); + final current = _note('ספר ב', 'תוכן מבקשה חדשה'); + final repository = _Repository({ + 'ספר א': [old], + })..delayFullNotes = true; + await _mount(tester, repository); + repository.notes + ..clear() + ..['ספר ב'] = [current]; + await tester.tap(find.byTooltip('רענן')); + await _pump(tester); + repository.fullRequests['ספר ב']!.single.complete([current]); + await _pump(tester); + repository.fullRequests['ספר א']!.single.complete([old]); + await _pump(tester); + + expect(find.text('תוכן מבקשה חדשה'), findsOneWidget); + expect(find.text('תוכן מבקשה ישנה'), findsNothing); + expect(repository.fullReads, ['ספר א', 'ספר ב']); + _expectExportEnabled(tester, true); + }); + + testWidgets( + 'storage changes update only affected books including create and delete', + ( + tester, + ) async { + final repository = _Repository({ + 'ספר א': [_note('ספר א', 'תוכן א ישן')], + 'ספר ב': [_note('ספר ב', 'תוכן ב יציב')], + }); + final reader = await _mount(tester, repository); + expect(repository.fullReads, ['ספר א', 'ספר ב']); + expect(reader.state.bookId, isNull); + + repository.notes['ספר א'] = [_note('ספר א', 'תוכן א מעודכן')]; + PersonalNotesChanges.notify('ספר א'); + await _pump(tester); + expect(find.text('תוכן א מעודכן'), findsOneWidget); + expect(find.text('תוכן א ישן'), findsNothing); + expect(find.text('תוכן ב יציב'), findsOneWidget); + expect(repository.fullReads, ['ספר א', 'ספר ב']); + expect(repository.storedReads, ['ספר א']); + + repository.notes['ספר ג'] = [_note('ספר ג', 'תוכן ספר חדש')]; + PersonalNotesChanges.notify('ספר ג'); + await _pump(tester); + expect(find.text('תוכן ספר חדש'), findsOneWidget); + expect(repository.fullReads, ['ספר א', 'ספר ב']); + expect(repository.storedReads, ['ספר א', 'ספר ג']); + + repository.notes.remove('ספר ג'); + PersonalNotesChanges.notify('ספר ג'); + await _pump(tester); + expect(find.text('תוכן ספר חדש'), findsNothing); + expect(find.text('ספר ג'), findsNothing); + expect(find.text('תוכן א מעודכן'), findsOneWidget); + expect(find.text('תוכן ב יציב'), findsOneWidget); + expect(repository.fullReads, ['ספר א', 'ספר ב']); + expect(repository.storedReads, ['ספר א', 'ספר ג', 'ספר ג']); + _expectExportEnabled(tester, true); + }, + ); + + testWidgets( + 'a storage change during the initial load is replayed afterward', + ( + tester, + ) async { + final old = _note('ספר א', 'לפני שינוי בזמן טעינה'); + final latest = _note('ספר א', 'אחרי שינוי בזמן טעינה'); + final repository = _Repository({ + 'ספר א': [old], + })..delayFullNotes = true; + await _mount(tester, repository); + repository.notes['ספר א'] = [latest]; + PersonalNotesChanges.notify('ספר א'); + await _pump(tester); + expect(repository.storedReads, isEmpty); + _expectExportEnabled(tester, false); + + repository.fullRequests['ספר א']!.single.complete([old]); + await _pump(tester); + expect(find.text('אחרי שינוי בזמן טעינה'), findsOneWidget); + expect(find.text('לפני שינוי בזמן טעינה'), findsNothing); + expect(repository.fullReads, ['ספר א']); + expect(repository.storedReads, ['ספר א']); + _expectExportEnabled(tester, true); + }, + ); + + testWidgets('another write during a stored-note refresh is not lost', ( + tester, + ) async { + final old = _note('ספר א', 'תוכן לפני שתי כתיבות'); + final first = _note('ספר א', 'תוכן כתיבה ראשונה'); + final last = _note('ספר א', 'תוכן כתיבה אחרונה'); + final repository = _Repository({ + 'ספר א': [old], + }); + await _mount(tester, repository); + repository.delayStoredNotes = true; + PersonalNotesChanges.notify('ספר א'); + await _pump(tester); + _expectExportEnabled(tester, false); + PersonalNotesChanges.notify('ספר א'); + await _pump(tester); + repository.storedRequests['ספר א']!.first.complete([first]); + await _pump(tester); + expect(repository.storedRequests['ספר א'], hasLength(2)); + _expectExportEnabled(tester, false); + repository.storedRequests['ספר א']!.last.complete([last]); + await _pump(tester); + expect(find.text('תוכן כתיבה אחרונה'), findsOneWidget); + expect(find.text('תוכן כתיבה ראשונה'), findsNothing); + expect(repository.fullReads, ['ספר א']); + _expectExportEnabled(tester, true); + }); + + testWidgets('manual refresh wins over an older stored-note response', ( + tester, + ) async { + final old = _note('ספר א', 'תוכן לפני רענון ידני'); + final latest = _note('ספר א', 'תוכן אחרי רענון ידני'); + final repository = _Repository({ + 'ספר א': [old], + }); + await _mount(tester, repository); + repository.delayStoredNotes = true; + PersonalNotesChanges.notify('ספר א'); + await _pump(tester); + repository.notes['ספר א'] = [latest]; + await tester.tap(find.byTooltip('רענן')); + await _pump(tester); + expect(find.text('תוכן אחרי רענון ידני'), findsOneWidget); + repository.storedRequests['ספר א']!.first.complete([old]); + await _pump(tester); + expect(find.text('תוכן אחרי רענון ידני'), findsOneWidget); + expect(find.text('תוכן לפני רענון ידני'), findsNothing); + expect(repository.storedRequests['ספר א'], hasLength(2)); + _expectExportEnabled(tester, false); + repository.storedRequests['ספר א']!.last.complete([latest]); + await _pump(tester); + _expectExportEnabled(tester, true); + }); + + testWidgets( + 'one failed book preserves its notes and does not block other books', + ( + tester, + ) async { + final oldA = _note('ספר א', 'תוכן א שנשמר לאחר כשל'); + final newB = _note('ספר ב', 'תוכן ב אחרי כשל א'); + final repository = _Repository({ + 'ספר א': [oldA], + 'ספר ב': [_note('ספר ב', 'תוכן ב קודם')], + }); + await _mount(tester, repository); + repository.delayFullNotes = true; + await tester.tap(find.byTooltip('רענן')); + await _pump(tester); + repository.fullRequests['ספר א']!.single.completeError( + StateError('fixture failure'), + ); + await _pump(tester); + expect(repository.fullRequests['ספר ב'], hasLength(1)); + repository.fullRequests['ספר ב']!.single.complete([newB]); + await _pump(tester); + + expect(find.text('תוכן א שנשמר לאחר כשל'), findsOneWidget); + expect(find.text('תוכן ב אחרי כשל א'), findsOneWidget); + expect(find.text(NotesMessages.notesLoadIncomplete), findsOneWidget); + _expectExportEnabled(tester, false); + + repository.delayFullNotes = false; + repository.notes['ספר ב'] = [newB]; + await tester.tap(find.text('נסה שוב')); + await _pump(tester); + expect(find.text('תוכן א שנשמר לאחר כשל'), findsOneWidget); + expect(find.text('תוכן ב אחרי כשל א'), findsOneWidget); + expect(find.text(NotesMessages.notesLoadIncomplete), findsNothing); + _expectExportEnabled(tester, true); + }, + ); + + testWidgets( + 'stored-note failure preserves data and prevents incomplete export', + ( + tester, + ) async { + final old = _note('ספר א', 'תוכן שמור לפני כשל רענון'); + final latest = _note('ספר א', 'תוכן שמור אחרי ניסיון חוזר'); + final repository = _Repository({ + 'ספר א': [old], + }); + await _mount(tester, repository); + repository.delayStoredNotes = true; + PersonalNotesChanges.notify('ספר א'); + await _pump(tester); + repository.storedRequests['ספר א']!.single.completeError( + StateError('fixture failure'), + ); + await _pump(tester); + expect(find.text('תוכן שמור לפני כשל רענון'), findsOneWidget); + expect(find.text(NotesMessages.notesLoadIncomplete), findsOneWidget); + _expectExportEnabled(tester, false); + + repository.notes['ספר א'] = [latest]; + await tester.tap(find.text('נסה שוב')); + await _pump(tester); + expect(find.text('תוכן שמור אחרי ניסיון חוזר'), findsOneWidget); + expect(find.text(NotesMessages.notesLoadIncomplete), findsNothing); + _expectExportEnabled(tester, true); + }, + ); + + testWidgets( + 'dispose ignores pending completion and unsubscribes from changes', + ( + tester, + ) async { + final repository = _Repository({ + 'ספר א': [_note('ספר א', 'תוכן מאוחר לאחר סגירה')], + 'ספר ב': [_note('ספר ב', 'תוכן נוסף')], + })..delayFullNotes = true; + await _mount(tester, repository); + await tester.pumpWidget(const SizedBox.shrink()); + repository.fullRequests['ספר א']!.single.complete( + repository.notes['ספר א'], + ); + PersonalNotesChanges.notify('ספר ב'); + await _pump(tester); + + expect(repository.fullReads, ['ספר א']); + expect(repository.storedReads, isEmpty); + expect(repository.listReads, 1); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'export keeps a complete snapshot across refresh before dialog build', + ( + tester, + ) async { + final noteA = _note('ספר א', 'תוכן א במועד פתיחת הייצוא'); + final noteB = _note('ספר ב', 'תוכן ב במועד פתיחת הייצוא'); + final repository = _Repository({ + 'ספר א': [noteA], + 'ספר ב': [noteB], + }); + final picker = _ExportPicker(); + final previousPicker = FilePickerPlatform.instance; + final previousOwner = DialogOwner.hwnd(); + FilePickerPlatform.instance = picker; + DialogOwner.mainWindowHwnd = 7; + addTearDown(() { + FilePickerPlatform.instance = previousPicker; + DialogOwner.mainWindowHwnd = previousOwner; + }); + await _mount(tester, repository); + BarButton button(String tooltip) => tester.widget( + find.byWidgetPredicate( + (widget) => widget is BarButton && widget.tooltip == tooltip, + ), + ); + final refresh = button('רענן').onPressed!; + button('גיבוי הערות').onPressed!(); + // Complete password verification and push the route without building it yet. + await tester.idle(); + expect(find.byType(PersonalNotesExportDialog), findsNothing); + + repository.delayFullNotes = true; + final updatedA = _note('ספר א', 'תוכן א לאחר פתיחת הייצוא'); + repository.notes + ..clear() + ..['ספר א'] = [updatedA] + ..['ספר ג'] = [_note('ספר ג', 'תוכן חדש שעדיין לא נטען')]; + refresh(); + await tester.idle(); + expect(repository.fullRequests['ספר א'], hasLength(1)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + final dialog = tester.widget( + find.byType(PersonalNotesExportDialog), + ); + expect(dialog.allNotes, [noteA, noteB]); + + repository.fullRequests['ספר א']!.single.complete([updatedA]); + await _pump(tester); + repository.fullRequests['ספר ג']!.single.completeError( + StateError('fixture failure while export dialog is open'), + ); + await _pump(tester); + expect(find.text(NotesMessages.notesLoadIncomplete), findsOneWidget); + _expectExportEnabled(tester, false); + + await tester.tap(find.text('גבה')); + await _pump(tester); + expect(picker.bytes, isNotNull); + final backup = + jsonDecode(utf8.decode(picker.bytes!)) as Map; + final exported = (backup['notes'] as List) + .map( + (value) => + PersonalNote.fromJson(Map.from(value as Map)), + ) + .toList(); + expect(exported, [noteA, noteB]); + }, + ); + + testWidgets( + 'manager edit waits for persistence and clears only that note draft', + ( + tester, + ) async { + final first = _note( + 'ספר א', + 'תוכן ראשון שמור', + ).copyWith(id: 'edit-first'); + final second = _note( + 'ספר א', + 'תוכן שני שמור', + ).copyWith(id: 'edit-second'); + final repository = _Repository({ + 'ספר א': [first, second], + })..delayUpdates = true; + final drafts = PersonalNoteDraftService(); + PersonalNoteDraft draft(String content) => PersonalNoteDraft( + content: content, + contentPlain: content, + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime(2026), + ); + await drafts.saveDraft( + bookId: first.bookId, + categoryId: 47, + noteId: first.id, + draft: draft('טיוטת עריכה ראשונה'), + ); + await drafts.saveDraft( + bookId: second.bookId, + categoryId: 47, + noteId: second.id, + draft: draft('טיוטת עריכה שנייה'), + ); + await drafts.saveDraft( + bookId: first.bookId, + categoryId: 47, + lineNumber: 1, + draft: draft('טיוטת הערה חדשה'), + ); + final reader = await _mount( + tester, + repository, + library: Library(categories: [])..books.add(_SourceBook()), + ); + reader.add(const LoadPersonalNotes('ספר קורא אחר', categoryId: 91)); + await _pump(tester); + await tester.tap(find.byTooltip('עריכה').first); + await tester.pumpAndSettle(); + final controller = tester + .widget(find.byType(quill.QuillEditor)) + .controller; + expect(controller.document.toPlainText().trim(), 'טיוטת עריכה ראשונה'); + const updated = 'תוכן עריכה מעודכן'; + controller.replaceText( + 0, + controller.document.length - 1, + updated, + TextSelection.collapsed(offset: updated.length), + ); + await tester.pump(); + await tester.tap(find.text('שמור')); + await _pump(tester); + expect(repository.updateRequests, hasLength(1)); + expect(find.byType(PersonalNoteEditorDialog), findsOneWidget); + expect(controller.readOnly, isTrue); + repository.updateRequests.first.completeError( + StateError('fixture write failure'), + ); + await _pump(tester); + expect(find.byType(PersonalNoteEditorDialog), findsOneWidget); + expect(controller.readOnly, isFalse); + expect(controller.document.toPlainText().trim(), updated); + expect( + (await drafts.loadDraft( + bookId: first.bookId, + categoryId: 47, + noteId: first.id, + ))?.contentPlain, + 'טיוטת עריכה ראשונה', + ); + + await tester.tap(find.text('שמור')); + await _pump(tester); + expect(repository.updateRequests, hasLength(2)); + repository.updateRequests.last.complete(); + await tester.pumpAndSettle(); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + expect( + repository.notes[first.bookId]!.first.contentPlain.trim(), + updated, + ); + expect(repository.updateTargets, [ + (bookId: first.bookId, noteId: first.id, categoryId: 47), + (bookId: first.bookId, noteId: first.id, categoryId: 47), + ]); + expect( + await drafts.loadDraft( + bookId: first.bookId, + categoryId: 47, + noteId: first.id, + ), + isNull, + ); + expect( + (await drafts.loadDraft( + bookId: second.bookId, + categoryId: 47, + noteId: second.id, + ))?.contentPlain, + 'טיוטת עריכה שנייה', + ); + expect( + (await drafts.loadDraft( + bookId: first.bookId, + categoryId: 47, + lineNumber: 1, + ))?.contentPlain, + 'טיוטת הערה חדשה', + ); + expect(reader.state.bookId, 'ספר קורא אחר'); + expect(reader.state.categoryId, 91); + UiSnack.hide(); + await tester.pump(); + }, + ); +} diff --git a/test/personal_notes/personal_notes_paragraph_marker_selection_test.dart b/test/personal_notes/personal_notes_paragraph_marker_selection_test.dart new file mode 100644 index 0000000000..0c7cb885bf --- /dev/null +++ b/test/personal_notes/personal_notes_paragraph_marker_selection_test.dart @@ -0,0 +1,130 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.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'; +import 'package:otzaria/personal_notes/utils/note_anchor_utils.dart'; +import 'package:otzaria/personal_notes/utils/personal_note_source_selection.dart'; +import 'package:otzaria/widgets/smart_text/render_settings.dart'; +import 'package:otzaria/widgets/smart_text/smart_text_widget.dart'; + +class _NotesDb extends Fake implements PersonalNotesDatabase { + final notes = []; + @override + Future insertNote(PersonalNote note) async => notes.add(note); + @override + Future> loadNotes(String bookId) async => + notes.where((note) => note.bookId == bookId).toList(); + @override + Future batchUpdateNotes(List updated) async { + for (final note in updated) { + final index = notes.indexWhere((existing) => existing.id == note.id); + notes[index] = note; + } + } +} + +void main() { + const html = + 'פתיחה ארוכה שנשברת לכמה שורות ברוחב צר לבדיקה' + ' {פ}
' + 'המשך הפסקה אחרי הסמן והרווח, ועוד מילים לסיום.'; + const settings = RenderSettings(fontSize: 20, lineHeight: 1.6); + + for (final forceHtml in [false, true]) { + testWidgets( + 'בחירה אמיתית חוצה סמן ו-BR שומרת עוגן (HtmlWidget=$forceHtml)', + (tester) async { + SmartTextWidget.debugForceHtmlWidget = forceHtml; + addTearDown(() => SmartTextWidget.debugForceHtmlWidget = false); + String? selected; + await tester.pumpWidget( + MaterialApp( + home: Directionality( + textDirection: TextDirection.rtl, + child: Align( + alignment: Alignment.topCenter, + child: SizedBox( + width: 180, + child: SelectionArea( + onSelectionChanged: (content) => + selected = content?.plainText, + child: const SmartTextWidget( + text: html, + settings: settings, + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + tester + .state(find.byType(SelectableRegion)) + .selectAll(SelectionChangedCause.keyboard); + await tester.pump(); + expect(selected, isNotNull); + expect(selected, contains('{פ}')); + expect(selected, contains('המשך הפסקה')); + + final fullSelection = selected!; + const partialEnding = 'אחרי הסמן'; + final partialSelection = fullSelection.substring( + fullSelection.indexOf('לבדיקה'), + fullSelection.indexOf(partialEnding) + partialEnding.length, + ); + PersonalNote? fullNote; + for (final (selection, isPartial) in [ + (fullSelection, false), + (partialSelection, true), + ]) { + final source = mapPersonalNoteSourceSelection( + bookId: 'ספר בדיקה', + lineIndex: 0, + rawLine: html, + settings: settings, + selectedText: selection, + ); + expect(source, isNotNull, reason: 'partial=$isPartial'); + final database = _NotesDb(); + final service = PersonalNotesService(database: database); + final saved = (await service.addNote( + bookId: 'ספר בדיקה', + bookContent: html, + lineNumber: 1, + selectedText: selection, + sourceSelectedText: source?.text, + sourceSelectionOffset: source?.offset, + content: 'תוכן הערה', + contentPlain: 'תוכן הערה', + contentFormat: PersonalNoteContentFormat.plain, + )).single; + expect(saved.isWordAnchored, isTrue, reason: 'partial=$isPartial'); + expect(saved.anchorText, normalizeAnchorText(source!.text)); + if (isPartial) { + expect(saved.anchorStart, greaterThan(0)); + expect(saved.anchorEnd, lessThan(fullNote!.anchorEnd!)); + } else { + fullNote = saved; + } + database.notes[0] = PersonalNote.fromJson(saved.toJson()); + final reopened = (await service.loadNotes( + bookId: 'ספר בדיקה', + bookContent: html, + )).single; + expect(reopened.status, PersonalNoteStatus.located); + expect(reopened.lineNumber, 1); + expect(reopened.anchorText, saved.anchorText); + final range = locateAnchor( + rawLine: html, + anchorText: reopened.anchorText!, + ); + expect(range, isNotNull); + expect(range!.start, saved.anchorStart); + expect(range.end, saved.anchorEnd); + } + }, + ); + } +} diff --git a/test/personal_notes/personal_notes_pdf_point_test.dart b/test/personal_notes/personal_notes_pdf_point_test.dart new file mode 100644 index 0000000000..ad31910866 --- /dev/null +++ b/test/personal_notes/personal_notes_pdf_point_test.dart @@ -0,0 +1,371 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/core/app_paths.dart'; +import 'package:otzaria/data/sqlite/sqlite3_api.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/services/personal_notes_import_export_service.dart'; +import 'package:otzaria/personal_notes/services/personal_notes_service.dart'; +import 'package:otzaria/personal_notes/storage/personal_notes_database.dart'; +import 'package:otzaria/personal_notes/utils/personal_notes_filter.dart'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; +import 'package:otzaria/settings/engine/settings_repository.dart'; + +import '../test_helpers/memory_cache_provider.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final database = PersonalNotesDatabase.instance; + final service = PersonalNotesService(database: database); + late Directory root; + const point = PdfNoteAnchor( + pageNumber: 47, + x: .21, + y: .78, + documentId: 'user|document.pdf', + ); + + PersonalNote note({String id = 'point', PdfNoteAnchor? anchor = point}) => + PersonalNote( + id: id, + bookId: 'מסמך בדיקה|user', + lineNumber: 47, + pdfAnchor: anchor, + lastKnownLineNumber: null, + status: PersonalNoteStatus.located, + content: 'תוכן הערה', + contentPlain: 'תוכן הערה', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime.utc(2026, 1, 1), + updatedAt: DateTime.utc(2026, 1, 2), + ); + + setUpAll(() async { + await Settings.init(cacheProvider: MemoryCacheProvider()); + }); + + setUp(() async { + await database.close(); + root = await Directory.systemTemp.createTemp('pdf_note_point_'); + AppPaths.debugOverrideDataRootPath(root.path); + await Settings.setValue( + SettingsRepository.keyDatabasesPath, + '${root.path}/databases', + ); + }); + + tearDown(() async { + await database.close(); + AppPaths.debugOverrideDataRootPath(null); + await Settings.setValue(SettingsRepository.keyDatabasesPath, ''); + await root.delete(recursive: true); + }); + + test('JSON ישן נשאר ללא נקודה; JSON חדש ו-copyWith משמרים אותה', () { + final old = note(anchor: null); + expect(old.toJson()['pdfAnchor'], isNull); + expect(old.toJson().containsKey('pdfAnchor'), isTrue); + final legacyJson = old.toJson()..remove('pdfAnchor'); + expect(PersonalNote.fromJson(legacyJson), old); + final saved = note(); + expect( + PersonalNote.fromJson(jsonDecode(jsonEncode(saved.toJson()))), + saved, + ); + expect(saved.copyWith(content: 'עריכה').pdfAnchor, point); + expect(saved.copyWith(clearPdfAnchor: true).pdfAnchor, isNull); + for (final invalid in [ + {'pageNumber': 0, 'x': .5, 'y': .5}, + {'pageNumber': 1, 'x': -1, 'y': .5}, + {'pageNumber': 1, 'x': .5, 'y': 2}, + {'pageNumber': 1, 'x': double.nan, 'y': .5}, + {'pageNumber': 1, 'x': .5}, + ]) { + expect(() => PdfNoteAnchor.fromJson(invalid), throwsFormatException); + } + }); + + test('מסד ישן מוסיף עמודות בלי לשנות הערות קיימות', () async { + final path = await AppPaths.resolveNotesDbPath('personal_notes.db'); + final legacy = sqlite3.open(path); + legacy.execute(''' + CREATE TABLE personal_notes ( + id TEXT PRIMARY KEY, book_id TEXT NOT NULL, line_number INTEGER, + display_title TEXT, last_known_line INTEGER, status TEXT NOT NULL, + content TEXT NOT NULL, content_plain TEXT NOT NULL DEFAULT '', + content_format TEXT NOT NULL DEFAULT 'plain', + created_at TEXT NOT NULL, updated_at TEXT NOT NULL + ) + '''); + legacy.execute(''' + INSERT INTO personal_notes + (id, book_id, line_number, status, content, content_plain, created_at, updated_at) + VALUES ('legacy', 'מסמך בדיקה|user', 47, 'located', 'ישן', 'ישן', + '2026-01-01T00:00:00.000Z', '2026-01-02T00:00:00.000Z') + '''); + legacy.close(); + + final before = (await database.loadNotes(note().bookId)).single; + expect(before.id, 'legacy'); + expect(before.lineNumber, 47); + expect(before.pdfAnchor, isNull); + await database.insertNote(note()); + await database.close(); + + final after = await database.loadNotes(note().bookId); + expect(after.singleWhere((item) => item.id == 'legacy'), before); + expect(after.singleWhere((item) => item.id == 'point'), note()); + expect( + (await database.database) + .select('PRAGMA table_info(personal_notes)') + .map((row) => row['name']), + containsAll(['pdf_page', 'pdf_x', 'pdf_y', 'pdf_document_id']), + ); + }); + + test( + 'בחירת PDF ללא טקסט נשמרת, ומקור טקסט מקביל אינו משנה את הנקודה', + () async { + final notes = await service.addNote( + bookId: note().bookId, + bookContent: '', + lineNumber: 999, + pdfAnchor: point, + selectedText: 'בחירה מתוך המסמך', + content: 'תוכן', + contentPlain: 'תוכן', + contentFormat: PersonalNoteContentFormat.plain, + ); + final saved = notes.single; + expect(saved.lineNumber, 47); + expect(saved.pdfAnchor, point); + expect(saved.anchorText, isNull); + expect(saved.displayTitle, 'בחירה מתוך המסמך'); + await database.close(); + final loaded = await service.loadNotes( + bookId: saved.bookId, + bookContent: 'טקסט אחר\nקצר יותר', + ); + expect(loaded.single, saved); + }, + ); + + test('PDF עם טקסט מקביל אינו משתמש במספר עמוד כבשורת טקסט', () async { + final notes = await service.addNote( + bookId: note().bookId, + bookContent: 'שורה ראשונה\nשורה שנייה', + lineNumber: 1, + pdfAnchor: point, + content: 'תוכן', + contentPlain: 'תוכן', + contentFormat: PersonalNoteContentFormat.plain, + ); + expect(notes.single.lineNumber, 47); + expect(notes.single.displayTitle, isEmpty); + expect(notes.single.status, PersonalNoteStatus.located); + }); + + test('עריכה ועיגון מחדש שומרים תוכן, מזהה וזמן יצירה', () async { + final saved = note(); + await database.insertNote(saved); + await service.updateNote( + bookId: saved.bookId, + bookContent: 'שורה', + noteId: saved.id, + content: 'עריכה', + contentPlain: 'עריכה', + ); + expect((await database.getNote(saved.id))!.pdfAnchor, point); + const moved = PdfNoteAnchor(pageNumber: 9, x: .85, y: .1); + await service.repositionNote( + bookId: saved.bookId, + bookContent: 'שורה', + noteId: saved.id, + lineNumber: 1, + pdfAnchor: moved, + ); + await database.close(); + final reloaded = (await database.getNote(saved.id))!; + expect(reloaded.pdfAnchor, moved); + expect(reloaded.lineNumber, 9); + expect(reloaded.contentPlain, 'עריכה'); + expect(reloaded.createdAt, saved.createdAt); + expect(reloaded.status, PersonalNoteStatus.located); + }); + + test('גיבוי וייבוא מחזירים יחד הערות ישנות ונקודות PDF', () async { + final saved = [note(), note(id: 'legacy', anchor: null)]; + await database.batchInsertNotes(saved); + final backup = PersonalNotesImportExportService(database: database); + final payload = backup.buildExport( + notes: await database.loadNotes(note().bookId), + ); + final file = File('${root.path}/backup.json'); + await file.writeAsString(jsonEncode(payload)); + for (final item in saved) { + await database.deleteNote(item.id); + } + final summary = await backup.importFromFile( + path: file.path, + strategy: NotesImportConflictStrategy.merge, + ); + expect(summary.inserted, 2); + await database.close(); + expect(await database.loadNotes(note().bookId), unorderedEquals(saved)); + }); + + test('גיבוי ישן משמר נקודה מקומית, ואילו null מפורש מסיר אותה', () async { + final original = note(); + final backup = PersonalNotesImportExportService(database: database); + await database.insertNote(original); + Future import(Map data) async { + final file = File('${root.path}/restore.json'); + await file.writeAsString( + jsonEncode({ + 'version': '2.0', + 'notes': [data], + }), + ); + await backup.importFromFile( + path: file.path, + strategy: NotesImportConflictStrategy.merge, + ); + } + + final legacy = + original + .copyWith( + content: 'עריכה ישנה', + contentPlain: 'עריכה ישנה', + updatedAt: DateTime.utc(2026, 2, 1), + ) + .toJson() + ..remove('pdfAnchor'); + await import(legacy); + expect((await database.getNote(original.id))!.pdfAnchor, point); + + final cleared = original.copyWith( + clearPdfAnchor: true, + updatedAt: DateTime.utc(2026, 3, 1), + ); + final payload = backup.buildExport(notes: [cleared]); + final data = (payload['notes'] as List).single as Map; + expect(data.containsKey('pdfAnchor'), isTrue); + expect(data['pdfAnchor'], isNull); + await import(data); + await database.close(); + expect((await database.getNote(original.id))!.pdfAnchor, isNull); + }); + + for (final lastKnown in [47, 48]) { + test('ייבוא PDF חסר משמר נקודה רק כשרמז המיקום זהה ($lastKnown)', () async { + final original = PersonalNote.fromJson({ + ...note().toJson(), + 'lineNumber': null, + 'status': PersonalNoteStatus.missing.name, + 'lastKnownLineNumber': 47, + }); + await database.insertNote(original); + final imported = + original + .copyWith( + content: 'תוכן מהגיבוי', + contentPlain: 'תוכן מהגיבוי', + updatedAt: DateTime.utc(2026, 2, 1), + ) + .toJson() + ..remove('pdfAnchor') + ..['lastKnownLineNumber'] = lastKnown; + final file = File('${root.path}/missing-pdf-backup.json'); + await file.writeAsString( + jsonEncode({ + 'version': '2.0', + 'notes': [imported], + }), + ); + final backup = PersonalNotesImportExportService(database: database); + final summary = await backup.importFromFile( + path: file.path, + strategy: NotesImportConflictStrategy.merge, + ); + final restored = (await database.getNote(original.id))!; + expect(summary.updated, 1); + expect(restored.content, 'תוכן מהגיבוי'); + expect(restored.lastKnownLineNumber, lastKnown); + expect(restored.pdfAnchor, lastKnown == 47 ? point : isNull); + }); + } + + test('סינון עמוד PDF אינו מתבלבל עם השורות הלוגיות או מהדורת הטקסט', () { + final pointNote = note().copyWith(lineNumber: 1); + final otherPage = + note( + id: 'other', + ).copyWith( + pdfAnchor: const PdfNoteAnchor( + pageNumber: 48, + x: .5, + y: .5, + documentId: 'user|document.pdf', + ), + ); + final textNote = note(id: 'text', anchor: null).copyWith(lineNumber: 1); + final notes = [pointNote, otherPage, textNote]; + final pdf = filterPersonalNotes( + locatedNotes: notes, + missingNotes: [], + searchQuery: '', + showOnlyVisible: true, + visibleLineIndices: [0], + isPdf: true, + pdfDocumentId: point.documentId, + visiblePdfPages: [47], + ); + expect(pdf.locatedNotes.map((n) => n.id), ['point', 'text']); + final text = filterPersonalNotes( + locatedNotes: notes, + missingNotes: [], + searchQuery: '', + showOnlyVisible: false, + visibleLineIndices: [], + ); + expect(text.locatedNotes, [textNote]); + }); + + test('שתי מהדורות PDF באותו key אינן רואות זו את נקודותיה של זו', () { + final first = note(); + final second = note( + id: 'second', + anchor: const PdfNoteAnchor( + pageNumber: 47, + x: .21, + y: .78, + documentId: 'user|second.pdf', + ), + ); + final unidentified = note( + id: 'unknown', + anchor: const PdfNoteAnchor(pageNumber: 47, x: .21, y: .78), + ); + final legacy = note(id: 'legacy', anchor: null); + List filtered(String identity, {bool includeUnknown = false}) => + filterPersonalNotes( + locatedNotes: [first, second, unidentified, legacy], + missingNotes: [], + searchQuery: '', + showOnlyVisible: false, + visibleLineIndices: [], + isPdf: true, + pdfDocumentId: identity, + includeUnidentifiedPdfAnchors: includeUnknown, + ).locatedNotes.map((note) => note.id).toList(); + expect(filtered('user|document.pdf'), ['point', 'legacy']); + expect(filtered('user|second.pdf'), ['second', 'legacy']); + expect(filtered('user|document.pdf', includeUnknown: true), [ + 'point', + 'unknown', + 'legacy', + ]); + }); +} diff --git a/test/personal_notes/personal_notes_screen_test.dart b/test/personal_notes/personal_notes_screen_test.dart index e74cc9a6d3..da0585cfd4 100644 --- a/test/personal_notes/personal_notes_screen_test.dart +++ b/test/personal_notes/personal_notes_screen_test.dart @@ -28,7 +28,6 @@ import 'package:otzaria/library/bloc/library_event.dart'; import 'package:otzaria/library/bloc/library_state.dart'; import 'package:otzaria/library/models/library.dart'; import 'package:otzaria/personal_notes/bloc/personal_notes_bloc.dart'; -import 'package:otzaria/personal_notes/bloc/personal_notes_state.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/storage/personal_notes_database.dart'; @@ -175,92 +174,6 @@ class RefreshingDelayedPersonalNotesRepository extends PersonalNotesRepository { } } -class TrackingPersonalNotesBloc extends PersonalNotesBloc { - TrackingPersonalNotesBloc({required super.repository}); - - int activeStreamSubscriptions = 0; - int canceledStreamSubscriptions = 0; - - @override - Stream get stream => _TrackingStream( - super.stream, - onListen: () => activeStreamSubscriptions++, - onCancel: () { - activeStreamSubscriptions--; - canceledStreamSubscriptions++; - }, - ); -} - -class _TrackingStream extends Stream { - _TrackingStream( - this.source, { - required this.onListen, - required this.onCancel, - }); - - final Stream source; - final void Function() onListen; - final void Function() onCancel; - - @override - StreamSubscription listen( - void Function(T event)? onData, { - Function? onError, - void Function()? onDone, - bool? cancelOnError, - }) { - onListen(); - return _TrackingSubscription( - source.listen( - onData, - onError: onError, - onDone: onDone, - cancelOnError: cancelOnError, - ), - onCancel, - ); - } -} - -class _TrackingSubscription implements StreamSubscription { - _TrackingSubscription(this.source, this.onCancel); - - final StreamSubscription source; - final void Function() onCancel; - bool _canceled = false; - - @override - Future cancel() { - if (!_canceled) { - _canceled = true; - onCancel(); - } - return source.cancel(); - } - - @override - void onData(void Function(T data)? handleData) => source.onData(handleData); - - @override - void onError(Function? handleError) => source.onError(handleError); - - @override - void onDone(void Function()? handleDone) => source.onDone(handleDone); - - @override - void pause([Future? resumeSignal]) => source.pause(resumeSignal); - - @override - void resume() => source.resume(); - - @override - bool get isPaused => source.isPaused; - - @override - Future asFuture([E? futureValue]) => source.asFuture(futureValue); -} - void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -705,7 +618,7 @@ void main() { await tester.pump(const Duration(seconds: 1)); }); - testWidgets('רענון מבטל מאזין תקוע ומתחיל רצף חדש', ( + testWidgets('רענון מציג תוצאות חדשות ומתעלם מתשובה ישנה שנתקעה', ( tester, ) async { BookNotesInfo book(String id) => BookNotesInfo( @@ -720,7 +633,19 @@ void main() { [book('ספר ג')], ], ); - final personalNotesBloc = TrackingPersonalNotesBloc( + PersonalNote note(String bookId, String content) => PersonalNote( + id: 'note-$bookId', + bookId: bookId, + lineNumber: 1, + lastKnownLineNumber: null, + status: PersonalNoteStatus.located, + content: content, + contentPlain: content, + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), + ); + final personalNotesBloc = PersonalNotesBloc( repository: repository, ); final settingsBloc = SettingsBloc(repository: SettingsRepository()); @@ -762,8 +687,6 @@ void main() { await tester.pump(); await tester.pump(); expect(repository.requests['ספר א'], hasLength(1)); - final cancellationsBeforeRefresh = - personalNotesBloc.canceledStreamSubscriptions; await tester.tap(find.byTooltip('רענן')); await tester.pump(); @@ -774,15 +697,24 @@ void main() { expect(repository.requests['ספר ב'], isNull); expect(repository.requests['ספר ג'], hasLength(1)); - expect( - personalNotesBloc.canceledStreamSubscriptions, - greaterThan(cancellationsBeforeRefresh), - ); - repository.requests['ספר א']!.single.complete(const []); - repository.requests['ספר ג']!.single.complete(const []); + repository.requests['ספר ג']!.single.complete([ + note('ספר ג', 'תוכן מרענון חדש'), + ]); + await tester.pumpAndSettle(); + expect(find.text('תוכן מרענון חדש'), findsOneWidget); + repository.requests['ספר א']!.single.complete([ + note('ספר א', 'תוכן מתשובה ישנה'), + ]); + await tester.pumpAndSettle(); + expect(find.text('תוכן מרענון חדש'), findsOneWidget); + expect(find.text('תוכן מתשובה ישנה'), findsNothing); + expect(repository.requests['ספר ב'], isNull); + expect(tester.takeException(), isNull); }); - testWidgets('dispose מבטל מאזין לטעינה שנתקעה', (tester) async { + testWidgets('dispose מתעלם מהשלמת טעינה שהמתינה בזמן סגירת המסך', ( + tester, + ) async { final repository = DelayedPersonalNotesRepository( books: [ BookNotesInfo( @@ -792,7 +724,7 @@ void main() { ), ], ); - final personalNotesBloc = TrackingPersonalNotesBloc( + final personalNotesBloc = PersonalNotesBloc( repository: repository, ); final settingsBloc = SettingsBloc(repository: SettingsRepository()); @@ -831,13 +763,15 @@ void main() { await tester.pump(); await tester.pump(); expect(repository.requests['ספר תקוע'], isNotNull); - expect(personalNotesBloc.activeStreamSubscriptions, greaterThan(0)); await tester.pumpWidget(const SizedBox.shrink()); await tester.pump(); - expect(personalNotesBloc.activeStreamSubscriptions, 0); repository.requests['ספר תקוע']!.complete(const []); + await tester.pump(); + await tester.pump(); + expect(tester.takeException(), isNull); + expect(repository.requests.keys, ['ספר תקוע']); }); Future pumpScreenWithManyNotes( diff --git a/test/personal_notes/personal_notes_sort_order_test.dart b/test/personal_notes/personal_notes_sort_order_test.dart new file mode 100644 index 0000000000..723d540e16 --- /dev/null +++ b/test/personal_notes/personal_notes_sort_order_test.dart @@ -0,0 +1,371 @@ +import 'package:bloc_test/bloc_test.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/library/bloc/library_bloc.dart'; +import 'package:otzaria/library/bloc/library_event.dart'; +import 'package:otzaria/library/bloc/library_state.dart'; +import 'package:otzaria/library/models/library.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/models/personal_notes_sort_order.dart'; +import 'package:otzaria/personal_notes/repository/personal_notes_repository.dart'; +import 'package:otzaria/personal_notes/storage/personal_notes_database.dart'; +import 'package:otzaria/personal_notes/view/personal_notes_screen.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_content_view.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/text/otzaria_search_field.dart'; + +import '../test_helpers/memory_cache_provider.dart'; + +class _LibraryBloc extends MockBloc + implements LibraryBloc {} + +PersonalNote _note( + String id, { + required String bookId, + required DateTime created, + DateTime? updated, + int? line = 1, + String? content, +}) => PersonalNote( + id: id, + bookId: bookId, + lineNumber: line, + lastKnownLineNumber: null, + status: line == null + ? PersonalNoteStatus.missing + : PersonalNoteStatus.located, + content: content ?? id, + contentPlain: content ?? id, + contentFormat: PersonalNoteContentFormat.plain, + createdAt: created, + updatedAt: updated ?? created, +); + +List _sortedIds( + List notes, + PersonalNotesSortOrder order, +) => ([...notes]..sort(order.compare)).map((note) => note.id).toList(); + +class _Repository extends PersonalNotesRepository { + _Repository(this.notes); + + final List notes; + + @override + Future> listBooksWithNotes() async => [ + for (final bookId in notes.map((note) => note.bookId).toSet()) + BookNotesInfo( + bookId: bookId, + noteCount: notes.where((note) => note.bookId == bookId).length, + lastUpdated: DateTime(2026), + ), + ]; + + @override + Future> loadNotes( + String bookId, { + int? categoryId, + }) async => notes.where((note) => note.bookId == bookId).toList(); +} + +Future _mount(WidgetTester tester, List notes) async { + tester.view.physicalSize = const Size(1600, 1400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final repository = _Repository(notes); + final notesBloc = PersonalNotesBloc(repository: repository); + final settingsBloc = SettingsBloc(repository: SettingsRepository()); + final libraryBloc = _LibraryBloc(); + whenListen( + libraryBloc, + const Stream.empty(), + initialState: LibraryState( + library: Library(categories: []), + isLoading: false, + ), + ); + addTearDown(() async { + await tester.pumpWidget(const SizedBox.shrink()); + await notesBloc.close(); + await settingsBloc.close(); + await libraryBloc.close(); + }); + await tester.pumpWidget( + MultiBlocProvider( + providers: [ + BlocProvider.value(value: settingsBloc), + BlocProvider.value(value: libraryBloc), + BlocProvider.value(value: notesBloc), + ], + child: MaterialApp( + home: Scaffold( + body: PersonalNotesManagerScreen(repository: repository), + ), + ), + ), + ); + await tester.pumpAndSettle(); +} + +List _visibleIds(WidgetTester tester) => tester + .widgetList(find.byType(PersonalNoteContentView)) + .map((view) => view.note.id) + .toList(); + +Future _selectOrder(WidgetTester tester, String label) async { + await tester.tap(find.byTooltip('מיון הערות')); + await tester.pumpAndSettle(); + await tester.tap(find.text(label)); + await tester.pumpAndSettle(); +} + +List _screenNotes() => [ + _note( + 'a-old', + bookId: 'ספר א', + created: DateTime(2026, 1, 1, 8), + updated: DateTime(2026, 1, 1, 13), + content: 'סימון ישן', + ), + _note( + 'a-new', + bookId: 'ספר א', + created: DateTime(2026, 1, 1, 11), + line: 2, + content: 'סימון חדש', + ), + _note( + 'b-middle', + bookId: 'ספר ב', + created: DateTime(2026, 1, 1, 10), + content: 'תוכן אחר', + ), +]; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + await Settings.init(cacheProvider: MemoryCacheProvider()); + }); + + group('Personal-note sort order', () { + test('creation order spans books and compares the entire timestamp', () { + final notes = [ + _note('a', bookId: 'ספר א', created: DateTime(2026, 1, 1, 9, 0, 1)), + _note('c', bookId: 'ספר ג', created: DateTime(2026, 1, 1, 9, 0, 2)), + _note( + 'b', + bookId: 'ספר ב', + created: DateTime(2026, 1, 1, 9, 0, 1, 500), + ), + _note('d', bookId: 'ספר ד', created: DateTime(2025, 12, 31, 23, 59)), + ]; + expect(_sortedIds(notes, PersonalNotesSortOrder.newestCreated), [ + 'c', + 'b', + 'a', + 'd', + ]); + expect(_sortedIds(notes, PersonalNotesSortOrder.oldestCreated), [ + 'd', + 'a', + 'b', + 'c', + ]); + }); + + test( + 'editing an old note affects updated order but not creation order', + () { + final notes = [ + _note( + 'old', + bookId: 'ספר א', + created: DateTime(2025), + updated: DateTime(2026, 1, 1, 18), + ), + _note('new', bookId: 'ספר ב', created: DateTime(2026, 1, 1, 10)), + ]; + expect(_sortedIds(notes, PersonalNotesSortOrder.newestCreated), [ + 'new', + 'old', + ]); + expect(_sortedIds(notes, PersonalNotesSortOrder.lastUpdated), [ + 'old', + 'new', + ]); + expect(PersonalNotesSortOrder.newestCreated.usesCreationDate, isTrue); + expect(PersonalNotesSortOrder.oldestCreated.usesCreationDate, isTrue); + expect(PersonalNotesSortOrder.lastUpdated.usesCreationDate, isFalse); + }, + ); + + test( + 'equal timestamps and missing locations keep a deterministic order', + () { + final date = DateTime(2026); + final notes = [ + _note('a-later-id', bookId: 'ספר א', created: date, line: 2), + _note('b', bookId: 'ספר ב', created: date), + _note('a-earlier-id', bookId: 'ספר א', created: date, line: 2), + _note('missing', bookId: 'ספר א', created: date, line: null), + _note('a-line-1', bookId: 'ספר א', created: date), + ]; + for (final order in PersonalNotesSortOrder.values) { + expect( + _sortedIds(notes, order), + ['missing', 'a-line-1', 'a-earlier-id', 'a-later-id', 'b'], + reason: order.name, + ); + } + }, + ); + + test('missing locations participate in global chronological order', () { + final notes = [ + _note('located', bookId: 'ספר א', created: DateTime(2026, 1, 1, 8)), + _note( + 'missing', + bookId: 'ספר ב', + created: DateTime(2026, 1, 1, 9), + line: null, + ), + ]; + expect(_sortedIds(notes, PersonalNotesSortOrder.newestCreated), [ + 'missing', + 'located', + ]); + }); + + test( + 'settings preserve every choice and recover from unknown values', + () async { + expect( + loadPersonalNotesSortOrder(), + PersonalNotesSortOrder.bookLocation, + ); + for (final order in PersonalNotesSortOrder.values) { + await savePersonalNotesSortOrder(order); + expect( + Settings.getValue('key-personal-notes-sort-order'), + order.name, + ); + expect(loadPersonalNotesSortOrder(), order); + } + await Settings.setValue( + 'key-personal-notes-sort-order', + 'removed-option', + ); + expect( + loadPersonalNotesSortOrder(), + PersonalNotesSortOrder.bookLocation, + ); + }, + ); + }); + + testWidgets('chronological menu order stays global and survives reopening', ( + tester, + ) async { + final notes = _screenNotes(); + await _mount(tester, notes); + expect(_visibleIds(tester), ['a-old', 'a-new', 'b-middle']); + await _selectOrder(tester, 'החדשות ביותר תחילה'); + expect(_visibleIds(tester), ['a-new', 'b-middle', 'a-old']); + expect(find.text('ספר א'), findsNWidgets(2)); + expect( + tester.getTopLeft(find.text('סימון חדש')).dy, + lessThan(tester.getTopLeft(find.text('תוכן אחר')).dy), + ); + expect( + tester.getTopLeft(find.text('תוכן אחר')).dy, + lessThan(tester.getTopLeft(find.text('סימון ישן')).dy), + ); + expect( + tester + .widgetList(find.byType(Tooltip)) + .any( + (tooltip) => + tooltip.message?.startsWith('נכתב:') == true && + tooltip.message!.endsWith('11:00'), + ), + isTrue, + ); + await tester.pumpWidget(const SizedBox.shrink()); + await _mount(tester, notes); + expect(_visibleIds(tester), ['a-new', 'b-middle', 'a-old']); + + await _selectOrder(tester, 'עודכנו לאחרונה'); + expect(_visibleIds(tester), ['a-old', 'a-new', 'b-middle']); + expect( + tester + .widgetList(find.byType(Tooltip)) + .any( + (tooltip) => + tooltip.message?.startsWith('עודכן:') == true && + tooltip.message!.endsWith('13:00'), + ), + isTrue, + ); + await _selectOrder(tester, 'הוותיקות ביותר תחילה'); + expect(_visibleIds(tester), ['a-old', 'b-middle', 'a-new']); + }); + + testWidgets( + 'search and missing-note filters retain the selected date order', + ( + tester, + ) async { + final notes = [ + ..._screenNotes(), + _note( + 'b-missing', + bookId: 'ספר ב', + created: DateTime(2026, 1, 1, 12), + line: null, + content: 'סימון ללא מיקום', + ), + ]; + await _mount(tester, notes); + await _selectOrder(tester, 'החדשות ביותר תחילה'); + expect(_visibleIds(tester), ['b-missing', 'a-new', 'b-middle', 'a-old']); + await tester.enterText( + find + .descendant( + of: find.byType(OtzariaSearchField), + matching: find.byType(TextField), + ) + .first, + 'סימון', + ); + await tester.pumpAndSettle(); + expect(_visibleIds(tester), ['b-missing', 'a-new', 'a-old']); + await tester.tap(find.text('הערות ללא מיקום')); + await tester.pumpAndSettle(); + expect(_visibleIds(tester), ['b-missing']); + expect( + loadPersonalNotesSortOrder(), + PersonalNotesSortOrder.newestCreated, + ); + }, + ); + + testWidgets('sorting menu fits a narrow screen and remains usable', ( + tester, + ) async { + await _mount(tester, _screenNotes()); + await tester.tap(find.byTooltip('הסתר ניווט')); + await tester.pumpAndSettle(); + tester.view.physicalSize = const Size(390, 844); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + await _selectOrder(tester, 'החדשות ביותר תחילה'); + expect(tester.takeException(), isNull); + expect(_visibleIds(tester), ['a-new', 'b-middle', 'a-old']); + }); +} diff --git a/test/personal_notes/personal_notes_word_export_screen_test.dart b/test/personal_notes/personal_notes_word_export_screen_test.dart new file mode 100644 index 0000000000..75f2d95886 --- /dev/null +++ b/test/personal_notes/personal_notes_word_export_screen_test.dart @@ -0,0 +1,327 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:archive/archive.dart'; +import 'package:bloc_test/bloc_test.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/core/app_paths.dart'; +import 'package:otzaria/core/windowing/dialog_owner.dart'; +import 'package:otzaria/data/data_providers/book_composite_key.dart'; +import 'package:otzaria/data/data_providers/library_provider.dart'; +import 'package:otzaria/data/data_providers/library_provider_manager.dart'; +import 'package:otzaria/data/data_providers/user_books_database_holder.dart'; +import 'package:otzaria/library/bloc/library_bloc.dart'; +import 'package:otzaria/library/bloc/library_event.dart'; +import 'package:otzaria/library/bloc/library_state.dart'; +import 'package:otzaria/library/models/library.dart'; +import 'package:otzaria/migration/database/daos/database.dart'; +import 'package:otzaria/migration/database/repository/seforim_repository.dart'; +import 'package:otzaria/models/book_source.dart'; +import 'package:otzaria/models/books.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/storage/personal_notes_database.dart'; +import 'package:otzaria/personal_notes/utils/personal_notes_book_key.dart'; +import 'package:otzaria/personal_notes/view/personal_notes_screen.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:xml/xml.dart'; +// ignore: depend_on_referenced_packages +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +import '../helpers/memory_settings_cache.dart'; + +class _LibraryBloc extends MockBloc + implements LibraryBloc {} + +class _NotesRepository extends PersonalNotesRepository { + final notes = [ + for (var line = 1; line <= 3; line++) + PersonalNote( + id: 'note-$line', + bookId: 'ספר בדיקה|user', + lineNumber: line, + displayTitle: 'כותרת $line', + lastKnownLineNumber: null, + status: PersonalNoteStatus.located, + content: 'תוכן $line', + contentPlain: 'תוכן $line', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), + ), + ]; + + @override + Future> listBooksWithNotes() async => [ + BookNotesInfo( + bookId: 'ספר בדיקה|user', + noteCount: notes.length, + lastUpdated: DateTime(2026), + ), + ]; + + @override + Future> loadNotes( + String bookId, { + int? categoryId, + }) async => notes; +} + +class _TocProvider implements LibraryProvider { + @override + Future?> getBookToc( + String title, + int categoryId, + String fileType, { + BookSource preferSource = BookSource.official, + }) async => [TocEntry(text: 'פרק א', index: 0, level: 1)]; + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class _ExportPicker extends FilePickerPlatform with MockPlatformInterfaceMixin { + Uint8List? bytes; + + @override + Future saveFile({ + required String fileName, + required Uint8List bytes, + String mimeType = 'application/octet-stream', + String? dialogTitle, + String? initialDirectory, + Function(FilePickerStatus)? onFileSaving, + WindowsOptions windowsOptions = const WindowsOptions(), + LinuxOptions linuxOptions = const LinuxOptions(), + WebOptions webOptions = const WebOptions(), + }) async { + this.bytes = bytes; + return null; + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory root; + + setUp(() async { + await Settings.init(cacheProvider: MemorySettingsCache()); + await UserBooksDatabaseHolder.instance.close(); + root = await Directory.systemTemp.createTemp('notes-word-location-'); + AppPaths.debugOverrideDataRootPath(root.path); + final db = MyDatabase.withPath( + await UserBooksDatabaseHolder.resolveDbPath(), + ); + await SeforimRepository(db).ensureInitialized(); + final raw = await db.database; + raw.execute( + "INSERT INTO book (id, categoryId, sourceId, title) " + "VALUES (1, 1, 1, 'ספר בדיקה')", + ); + for (final (index, ref) in [(0, 'א, א'), (1, 'א, ב'), (2, ' ')]) { + raw.execute( + 'INSERT INTO line (id, bookId, lineIndex, content, heRef) ' + 'VALUES (?, 1, ?, ?, ?)', + [index + 1, index, 'שורה $index', ref], + ); + } + db.close(); + // פתיחת הקובץ ואתחול המנוע צריכים להסתיים מחוץ לשעון המדומה של ה-widget. + await UserBooksDatabaseHolder.instance.repository; + final provider = _TocProvider(); + LibraryProviderManager.instance.seedMappingsForTesting( + mapping: { + BookCompositeKey.create( + title: 'ספר בדיקה', + categoryId: 1, + fileType: 'txt', + source: BookSource.user, + ): provider, + }, + providers: [provider], + ); + }); + + tearDown(() async { + LibraryProviderManager.instance.resetForTesting(); + await UserBooksDatabaseHolder.instance.close(); + AppPaths.debugOverrideDataRootPath(null); + await root.delete(recursive: true); + }); + + testWidgets('ייצוא משתמש בכתובת השורה המדויקת וב-TOC רק כגיבוי', ( + tester, + ) async { + tester.view.physicalSize = const Size(1600, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final picker = _ExportPicker(); + final previousPicker = FilePickerPlatform.instance; + final previousOwner = DialogOwner.hwnd(); + FilePickerPlatform.instance = picker; + DialogOwner.mainWindowHwnd = 7; + addTearDown(() { + FilePickerPlatform.instance = previousPicker; + DialogOwner.mainWindowHwnd = previousOwner; + }); + // Normal PDFs can borrow the text edition's ID; this cannot identify a PDF + // deep link when two different files share it. + final firstPdf = PdfBook( + id: 1, + title: 'ספר בדיקה', + path: '/fixture-first.pdf', + categoryId: 1, + source: BookSource.user, + ); + final secondPdf = PdfBook( + id: 1, + title: 'ספר בדיקה', + path: '/fixture-second.pdf', + categoryId: 1, + source: BookSource.user, + ); + final repository = _NotesRepository() + ..notes.add( + PersonalNote( + id: 'pdf-note', + bookId: 'ספר בדיקה|user', + lineNumber: 7, + lastKnownLineNumber: null, + status: PersonalNoteStatus.located, + pdfAnchor: PdfNoteAnchor( + pageNumber: 7, + x: 0.2, + y: 0.6, + documentId: pdfPersonalNoteDocumentId(firstPdf), + ), + content: 'תוכן PDF', + contentPlain: 'תוכן PDF', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), + ), + ); + final notesBloc = PersonalNotesBloc(repository: repository); + final settingsBloc = SettingsBloc(repository: SettingsRepository()); + final libraryBloc = _LibraryBloc(); + addTearDown(notesBloc.close); + addTearDown(settingsBloc.close); + addTearDown(libraryBloc.close); + whenListen( + libraryBloc, + const Stream.empty(), + initialState: LibraryState( + library: Library(categories: []) + ..books.add( + TextBook( + id: 1, + title: 'ספר בדיקה', + categoryId: 1, + source: BookSource.user, + ), + ) + ..books.addAll([firstPdf, secondPdf]), + isLoading: false, + ), + ); + await tester.pumpWidget( + MultiBlocProvider( + providers: [ + RepositoryProvider.value( + value: SettingsRepository(), + ), + BlocProvider.value(value: settingsBloc), + BlocProvider.value(value: libraryBloc), + BlocProvider.value(value: notesBloc), + ], + child: MaterialApp( + home: Scaffold( + body: PersonalNotesManagerScreen(repository: repository), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('ייצוא לוורד')); + await tester.pumpAndSettle(); + await tester.tap(find.text('ייצא')); + for (var i = 0; i < 100 && picker.bytes == null; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 10)), + ); + await tester.pump(); + } + expect(picker.bytes, isNotNull); + final archive = ZipDecoder().decodeBytes(picker.bytes!); + final document = utf8.decode( + archive.findFile('word/document.xml')!.content as List, + ); + expect(document, contains('א, א')); + expect(document, contains('א, ב')); + expect(document, contains('פרק א')); + const wordNamespace = + 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'; + const relationshipNamespace = + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'; + final relationships = XmlDocument.parse( + utf8.decode( + archive.findFile('word/_rels/document.xml.rels')!.content as List, + ), + ); + final linksById = { + for (final relationship in relationships.rootElement.childElements) + relationship.getAttribute('Id'): relationship, + }; + final links = XmlDocument.parse( + document, + ).findAllElements('hyperlink', namespaceUri: wordNamespace).toList(); + expect(links.map((link) => link.innerText), ['א, א', 'א, ב', 'פרק א']); + for (var index = 0; index < links.length; index++) { + final relationshipId = links[index].getAttribute( + 'id', + namespaceUri: relationshipNamespace, + ); + final relationship = linksById[relationshipId]; + expect(relationship, isNotNull); + expect(relationship!.getAttribute('TargetMode'), 'External'); + expect( + relationship.getAttribute('Type'), + '$relationshipNamespace/hyperlink', + ); + expect( + relationship.getAttribute('Target'), + 'otzaria://open/book/1?source=user&index=$index', + ); + expect( + (links[index].parent as XmlElement) + .findAllElements('pStyle', namespaceUri: wordNamespace) + .single + .getAttribute('val', namespaceUri: wordNamespace), + 'Heading2', + ); + } + final pdfHeading = XmlDocument.parse(document) + .findAllElements('p', namespaceUri: wordNamespace) + .singleWhere( + (paragraph) => + paragraph + .findAllElements('t', namespaceUri: wordNamespace) + .map((text) => text.innerText) + .join() == + 'עמוד 7', + ); + expect( + pdfHeading.findAllElements('hyperlink', namespaceUri: wordNamespace), + isEmpty, + ); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + }); +} diff --git a/test/personal_notes/personal_notes_word_export_test.dart b/test/personal_notes/personal_notes_word_export_test.dart index b3e62d4da7..0095c14536 100644 --- a/test/personal_notes/personal_notes_word_export_test.dart +++ b/test/personal_notes/personal_notes_word_export_test.dart @@ -15,6 +15,8 @@ PersonalNote _note({ String content = 'תוכן ההערה', String? contentPlain, PersonalNoteContentFormat contentFormat = PersonalNoteContentFormat.plain, + DateTime? createdAt, + DateTime? updatedAt, }) { return PersonalNote( id: id, @@ -27,8 +29,8 @@ PersonalNote _note({ content: content, contentPlain: contentPlain ?? content, contentFormat: contentFormat, - createdAt: DateTime(2025, 1, 1), - updatedAt: DateTime(2025, 3, 7), + createdAt: createdAt ?? DateTime(2025, 1, 1), + updatedAt: updatedAt ?? DateTime(2025, 3, 7), ); } @@ -113,6 +115,72 @@ void main() { expect(allText, isNot(contains('2025'))); }); + test('סדר היצירה נשמר באותה שורה ועריכה אינה מזיזה הערה', () { + final blocks = service.buildWordExportBlocks( + notes: [ + _note( + id: 'later', + bookId: 'ספר בדיקה', + lineNumber: 5, + content: 'מאוחרת', + createdAt: DateTime(2026, 2), + ), + _note( + id: 'same-time-b', + bookId: 'ספר בדיקה', + lineNumber: 5, + content: 'שנייה', + ), + _note( + id: 'same-time-a', + bookId: 'ספר בדיקה', + lineNumber: 5, + content: 'ראשונה', + updatedAt: DateTime(2026, 3), + ), + ], + locationRef: (_) => null, + ); + + expect( + blocks.where((b) => b.kind == PrintBlockKind.text).map((b) => b.text), + ['ראשונה', 'שנייה', 'מאוחרת'], + ); + }); + + test('חסרות מיקום נשארות אחרי הממוקמות ולפי העדכון האחרון', () { + final blocks = service.buildWordExportBlocks( + notes: [ + _note( + id: 'older', + bookId: 'ספר בדיקה', + status: PersonalNoteStatus.missing, + content: 'עדכון ישן', + createdAt: DateTime(2026, 2), + ), + _note( + id: 'newer', + bookId: 'ספר בדיקה', + status: PersonalNoteStatus.missing, + content: 'עדכון חדש', + updatedAt: DateTime(2026, 3), + ), + _note( + id: 'located', + bookId: 'ספר בדיקה', + lineNumber: 5, + content: 'ממוקמת', + ), + ], + locationRef: (_) => null, + ); + + expect( + blocks.where((b) => b.kind == PrintBlockKind.text).map((b) => b.text), + ['ממוקמת', 'עדכון חדש', 'עדכון ישן'], + ); + }); + test('הערות ללא מיקום מקובצות בסוף הספר תחת כותרת משלהן', () { final blocks = service.buildWordExportBlocks( notes: [ @@ -153,6 +221,47 @@ void main() { }); group('buildWordExportBlocks - דיבור המתחיל', () { + test('כותרת הערת שורה נשמרת כשאין בחירת מילים', () { + for (final anchor in [null, '', ' ']) { + final blocks = service.buildWordExportBlocks( + notes: [ + _note( + id: 'whole-line', + bookId: 'ספר בדיקה', + lineNumber: 5, + displayTitle: ' כותרת <שלמה> & מקור ', + anchorText: anchor, + content: 'תוכן ההערה', + ), + ], + locationRef: (_) => null, + ); + + expect( + blocks.last.text, + 'כותרת <שלמה> & מקור. תוכן ההערה', + ); + } + }); + + test('בחירת המילים עדיפה על כותרת התצוגה', () { + final blocks = service.buildWordExportBlocks( + notes: [ + _note( + id: 'selection', + bookId: 'ספר בדיקה', + lineNumber: 5, + displayTitle: 'כותרת שלמה', + anchorText: 'בחירה מדויקת', + content: 'תוכן ההערה', + ), + ], + locationRef: (_) => null, + ); + + expect(blocks.last.text, 'בחירה מדויקת. תוכן ההערה'); + }); + test('הטקסט שסומן נפתח מודגש עם נקודה בסוף', () { final blocks = service.buildWordExportBlocks( notes: [ diff --git a/test/personal_notes/personal_notes_write_confirmation_test.dart b/test/personal_notes/personal_notes_write_confirmation_test.dart new file mode 100644 index 0000000000..c85c4005e8 --- /dev/null +++ b/test/personal_notes/personal_notes_write_confirmation_test.dart @@ -0,0 +1,323 @@ +import 'dart:io'; +import 'dart:math'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/core/app_paths.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'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; +import 'package:otzaria/settings/engine/settings_repository.dart'; + +import '../test_helpers/memory_cache_provider.dart'; + +const _bookId = 'ספר בדיקת שמירה'; +const _bookContent = 'פתיחה\nמקטע מדויק לסימון\nסיום'; + +class _ControlledDatabase extends Fake implements PersonalNotesDatabase { + final notes = {}; + bool failReads = true; + bool failInsert = false; + int listReads = 0; + int inserts = 0; + int updates = 0; + + @override + Future> loadNotes(String bookId) async { + listReads++; + if (failReads) throw StateError('list refresh failed after the write'); + return notes.values.where((note) => note.bookId == bookId).toList(); + } + + @override + Future getNote(String id) async => notes[id]; + + @override + Future insertNote(PersonalNote note) async { + inserts++; + if (failInsert) throw StateError('insert failed'); + notes[note.id] = note; + } + + @override + Future updateNote(PersonalNote note) async { + updates++; + if (!notes.containsKey(note.id)) throw StateError('note no longer exists'); + notes[note.id] = note; + } + + @override + Future batchUpdateNotes(List changed) async { + for (final note in changed) { + await updateNote(note); + } + } +} + +class _DeleteBeforeUpdateDatabase extends Fake + implements PersonalNotesDatabase { + _DeleteBeforeUpdateDatabase(this.delegate); + + final PersonalNotesDatabase delegate; + + @override + Future getNote(String id) => delegate.getNote(id); + + @override + Future updateNote(PersonalNote note) async { + // A real concurrent deletion after persistNote read the original record. + await delegate.deleteNote(note.id); + await delegate.updateNote(note); + } +} + +PersonalNote _note({String bookId = _bookId}) => PersonalNote( + id: 'existing-note', + bookId: bookId, + lineNumber: 2, + lastKnownLineNumber: null, + status: PersonalNoteStatus.located, + content: 'תוכן קודם', + contentPlain: 'תוכן קודם', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026, 1, 1), + updatedAt: DateTime(2026, 1, 1), +); + +Future _create(PersonalNotesService service) => + service.createNote( + bookId: _bookId, + bookContent: _bookContent, + lineNumber: 2, + selectedText: 'מקטע מדויק', + content: 'תוכן חדש \n', + contentPlain: 'תוכן חדש \n', + contentFormat: PersonalNoteContentFormat.plain, + ); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + 'create confirms one committed write without reading the list', + () async { + final database = _ControlledDatabase(); + final service = PersonalNotesService( + database: database, + random: Random(1), + ); + + final created = await _create(service); + + expect(database.inserts, 1); + expect(database.listReads, 0); + expect(database.notes.values, [created]); + expect(created.bookId, _bookId); + expect(created.lineNumber, 2); + expect(created.contentPlain, 'תוכן חדש'); + expect(created.anchorText, 'מקטע מדויק'); + expect(created.createdAt, created.updatedAt); + + database.failReads = false; + expect(await database.loadNotes(_bookId), [created]); + }, + ); + + test( + 'an unsuccessful insert still fails and is never acknowledged', + () async { + final database = _ControlledDatabase()..failInsert = true; + final service = PersonalNotesService(database: database); + + await expectLater(_create(service), throwsStateError); + + expect(database.inserts, 1); + expect(database.notes, isEmpty); + expect(database.listReads, 0); + }, + ); + + test( + 'persist confirms and reconciles the edited note before the write', + () async { + final database = _ControlledDatabase(); + final service = PersonalNotesService( + database: database, + random: Random(1), + ); + final created = await _create(service); + final unrelated = _note().copyWith(id: 'unrelated-note'); + database.notes[unrelated.id] = unrelated; + + final updated = await service.persistNote( + bookId: _bookId, + bookContent: 'כותרת נוספת\n$_bookContent', + noteId: created.id, + content: 'תוכן ערוך\n', + contentPlain: 'תוכן ערוך\n', + contentFormat: PersonalNoteContentFormat.plain, + ); + + expect(database.updates, 1); + expect(database.listReads, 0); + expect(updated.id, created.id); + expect(updated.createdAt, created.createdAt); + expect(updated.contentPlain, 'תוכן ערוך'); + expect(updated.lineNumber, 3); + expect(updated.status, PersonalNoteStatus.located); + expect(database.notes[updated.id], updated); + expect(database.notes[unrelated.id], unrelated); + }, + ); + + test( + 'persist refuses an already deleted note instead of reporting success', + () async { + final database = _ControlledDatabase(); + final service = PersonalNotesService(database: database); + + await expectLater( + service.persistNote( + bookId: _bookId, + bookContent: _bookContent, + noteId: 'deleted-note', + content: 'תוכן ערוך', + ), + throwsStateError, + ); + + expect(database.updates, 0); + expect(database.listReads, 0); + expect(database.notes, isEmpty); + }, + ); + + test('persist refuses an id belonging to a different book', () async { + final database = _ControlledDatabase(); + final original = _note(bookId: 'ספר אחר'); + database.notes[original.id] = original; + final service = PersonalNotesService(database: database); + + await expectLater( + service.persistNote( + bookId: _bookId, + bookContent: _bookContent, + noteId: original.id, + content: 'תוכן ערוך', + ), + throwsStateError, + ); + + expect(database.updates, 0); + expect(database.listReads, 0); + expect(database.notes[original.id], original); + }); + + test( + 'compatibility add and update APIs still return refreshed lists', + () async { + final database = _ControlledDatabase()..failReads = false; + final existing = _note(); + database.notes[existing.id] = existing; + final service = PersonalNotesService( + database: database, + random: Random(1), + ); + + final added = await service.addNote( + bookId: _bookId, + bookContent: _bookContent, + lineNumber: 3, + content: 'הערה נוספת', + contentPlain: 'הערה נוספת', + contentFormat: PersonalNoteContentFormat.plain, + ); + expect(added, hasLength(2)); + expect(added.map((note) => note.id), contains(existing.id)); + final created = added.singleWhere((note) => note.id != existing.id); + + final updated = await service.updateNote( + bookId: _bookId, + bookContent: _bookContent, + noteId: created.id, + content: 'הערה נוספת מעודכנת', + contentPlain: 'הערה נוספת מעודכנת', + ); + expect(updated, hasLength(2)); + expect( + updated.singleWhere((note) => note.id == created.id).contentPlain, + 'הערה נוספת מעודכנת', + ); + expect(database.listReads, 2); + }, + ); + + group('real SQLite write confirmation', () { + final database = PersonalNotesDatabase.instance; + late Directory temporaryRoot; + + setUp(() async { + await Settings.init(cacheProvider: MemoryCacheProvider()); + await database.close(); + temporaryRoot = await Directory.systemTemp.createTemp( + 'note_write_confirmation_', + ); + AppPaths.debugOverrideDataRootPath(temporaryRoot.path); + await Settings.setValue( + SettingsRepository.keyDatabasesPath, + '${temporaryRoot.path}/databases', + ); + }); + + tearDown(() async { + await database.close(); + AppPaths.debugOverrideDataRootPath(null); + await Settings.setValue(SettingsRepository.keyDatabasesPath, ''); + await temporaryRoot.delete(recursive: true); + }); + + test( + 'an UPDATE after DELETE is rejected without a success notification', + () async { + final note = _note(); + await database.insertNote(note); + await database.deleteNote(note.id); + final revisionAfterDelete = database.revision.value; + + await expectLater( + database.updateNote(note.copyWith(content: 'תוכן שלא נשמר')), + throwsStateError, + ); + + expect(await database.getNote(note.id), isNull); + expect(database.revision.value, revisionAfterDelete); + }, + ); + + test( + 'persist also 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.persistNote( + bookId: note.bookId, + bookContent: _bookContent, + noteId: note.id, + content: 'תוכן ערוך', + contentPlain: 'תוכן ערוך', + ), + throwsStateError, + ); + + expect(await database.getNote(note.id), isNull); + expect(database.revision.value, revisionBeforeDelete + 1); + }, + ); + }); +} diff --git a/test/personal_notes/storage/personal_notes_changes_test.dart b/test/personal_notes/storage/personal_notes_changes_test.dart index 682d2f8106..34ebeb935e 100644 --- a/test/personal_notes/storage/personal_notes_changes_test.dart +++ b/test/personal_notes/storage/personal_notes_changes_test.dart @@ -90,8 +90,11 @@ void main() { expect(await delivered(), isEmpty); }); - test('עדכון הערה שאינה קיימת אינו מודיע', () async { - await db.updateNote(_note('missing', bookId: 'רש"י')); + test('עדכון הערה שאינה קיימת נדחה ואינו מודיע', () async { + await expectLater( + db.updateNote(_note('missing', bookId: 'רש"י')), + throwsStateError, + ); expect(await delivered(), isEmpty); }); diff --git a/test/personal_notes/storage/personal_notes_database_test.dart b/test/personal_notes/storage/personal_notes_database_test.dart index 4c6ce368ed..212a33d032 100644 --- a/test/personal_notes/storage/personal_notes_database_test.dart +++ b/test/personal_notes/storage/personal_notes_database_test.dart @@ -6,6 +6,7 @@ import 'package:otzaria/core/app_paths.dart'; import 'package:otzaria/data/sqlite/sqlite3_api.dart'; import 'package:otzaria/personal_notes/models/personal_note.dart'; import 'package:otzaria/personal_notes/storage/personal_notes_database.dart'; +import 'package:otzaria/personal_notes/utils/note_collection_utils.dart'; import 'package:otzaria/settings/engine/settings_repository.dart'; import '../../test_helpers/memory_cache_provider.dart'; @@ -100,6 +101,86 @@ void main() { expect(times, hasLength(9)); }); + test('הערות באותה שורה נשארות בסדר היצירה אחרי עריכה וטעינה מחדש', () async { + final first = PersonalNote( + id: 'first', + bookId: 'ספר בדיקה', + lineNumber: 2, + lastKnownLineNumber: 2, + status: PersonalNoteStatus.located, + content: 'ראשונה', + contentPlain: 'ראשונה', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026, 1, 1), + updatedAt: DateTime(2026, 1, 1), + ); + final second = first.copyWith( + id: 'second', + createdAt: DateTime(2026, 1, 2), + updatedAt: DateTime(2026, 1, 2), + ); + final third = second.copyWith(id: 'third'); + final earlierLine = third.copyWith(id: 'earlier-line', lineNumber: 1); + await database.batchInsertNotes([third, second, first, earlierLine]); + final expected = ['earlier-line', 'first', 'second', 'third']; + expect( + (await database.loadNotes(first.bookId)).map((note) => note.id), + expected, + ); + await database.updateNote(first.copyWith(updatedAt: DateTime(2026, 2, 1))); + await database.close(); + + final reloaded = await database.loadNotes(first.bookId); + expect(reloaded.map((note) => note.id), expected); + expect( + sortPersonalNotes(reloaded.reversed.toList()).map((note) => note.id), + expected, + ); + }); + + test('מיון תאריכים משווה רגעים בזמן ושומר חסרות מיקום בסדר עדכון', () async { + final instant = DateTime.utc(2026, 1, 1, 12); + final utcNote = PersonalNote( + id: 'a-utc', + bookId: 'ספר בדיקה', + lineNumber: 1, + lastKnownLineNumber: 1, + status: PersonalNoteStatus.located, + content: 'תוכן', + contentPlain: 'תוכן', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: instant, + updatedAt: instant, + ); + final localNote = utcNote.copyWith( + id: 'b-local', + createdAt: instant.toLocal(), + ); + final missing = utcNote.copyWith( + id: 'missing-old', + status: PersonalNoteStatus.missing, + clearLineNumber: true, + ); + final newerMissing = missing.copyWith( + id: 'missing-new', + updatedAt: instant.add(const Duration(hours: 1)), + ); + await database.batchInsertNotes([ + localNote, + missing, + newerMissing, + utcNote, + ]); + + final reloaded = await database.loadNotes(utcNote.bookId); + expect(reloaded.map((note) => note.id), [ + 'a-utc', + 'b-local', + 'missing-new', + 'missing-old', + ]); + }); + test('זמן עדכון פגום מדלג על השורה ולא מפיל את הספירה', () async { final db = await database.database; db.execute( diff --git a/test/personal_notes/widgets/create_personal_note_test.dart b/test/personal_notes/widgets/create_personal_note_test.dart new file mode 100644 index 0000000000..7200e356b3 --- /dev/null +++ b/test/personal_notes/widgets/create_personal_note_test.dart @@ -0,0 +1,591 @@ +import 'dart:async'; + +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/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/utils/create_personal_note.dart'; +import 'package:otzaria/personal_notes/widgets/inline_note_editor.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_editor_dialog.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 '../../test_helpers/memory_cache_provider.dart'; + +const _bookId = 'ספר בדיקה|user'; +const _categoryId = 37; +const _lineNumber = 4; +const _anchor = PdfNoteAnchor(pageNumber: 4, x: .25, y: .75); + +void main() { + late _FailingCache cache; + late _NotesRepository repository; + late _RecordingNotesBloc bloc; + var blocCreated = false; + late int panelOpenCalls; + final drafts = PersonalNoteDraftService(); + + setUp(() async { + cache = _FailingCache(); + await Settings.init(cacheProvider: cache); + repository = _NotesRepository(); + blocCreated = false; + panelOpenCalls = 0; + }); + + tearDown(() async { + if (blocCreated) await bloc.close(); + }); + + Future saveDraft(String content, {PdfNoteAnchor? anchor}) => + drafts.saveDraft( + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + draft: PersonalNoteDraft( + content: content, + contentPlain: content, + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime.utc(2026, 1, 1), + pdfAnchor: anchor, + ), + ); + + Future open( + WidgetTester tester, { + bool panelOpen = false, + PdfNoteAnchor? anchor, + bool retargetSidebar = false, + }) async { + if (!blocCreated) { + // הזרמים האסינכרוניים צריכים להירשם באזור הזמן של testWidgets. + bloc = _RecordingNotesBloc(repository); + blocCreated = true; + } + var sidebarBook = 'ספר אחר'; + bloc.add(LoadPersonalNotes(sidebarBook, categoryId: 99)); + await tester.pumpWidget( + RepositoryProvider( + create: (_) => SettingsRepository(), + child: MultiBlocProvider( + providers: [ + BlocProvider.value(value: bloc), + BlocProvider( + create: (context) => SettingsBloc( + repository: context.read(), + ), + ), + ], + child: MaterialApp( + home: Directionality( + textDirection: TextDirection.rtl, + child: Scaffold( + body: StatefulBuilder( + builder: (context, setState) => Row( + children: [ + TextButton( + onPressed: () => createPersonalNote( + context, + isNotesPanelOpen: panelOpen, + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + referenceText: 'מקור בדיקה', + selectedText: 'בחירה', + selectionColumn: 8, + sourceSelectedText: 'בְּחִירָה', + sourceSelectionOffset: 12, + punctuationHidden: true, + pdfAnchor: anchor, + repository: repository, + openNotesPanel: () { + panelOpenCalls++; + if (retargetSidebar) { + setState(() => sidebarBook = _bookId); + } + }, + ), + child: const Text('צור הערה'), + ), + if (retargetSidebar) + Expanded( + child: PersonalNotesSidebar( + bookId: sidebarBook, + repository: repository, + isPdf: anchor != null, + pdfDocumentId: anchor?.documentId, + includeUnidentifiedPdfAnchors: true, + categoryId: sidebarBook == _bookId + ? _categoryId + : 99, + onNavigateToLine: (_, {note}) {}, + ), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + bloc.received.clear(); + await tester.tap(find.text('צור הערה')); + await tester.pumpAndSettle(); + } + + quill.QuillEditor editor(WidgetTester tester) => + tester.widget(find.byType(quill.QuillEditor)); + + Future type(WidgetTester tester, String content) async { + editor(tester).controller.replaceText( + 0, + 0, + content, + TextSelection.collapsed(offset: content.length), + ); + await tester.pump(); + } + + Future pressAction(WidgetTester tester, String text) async { + await tester.tap(find.widgetWithText(ActionButton, text).last); + await tester.pumpAndSettle(); + } + + testWidgets('פאנל סגור פותח דיאלוג בלי לשנות יעד או מצב חלונית', ( + tester, + ) async { + await open(tester); + expect(find.byType(PersonalNoteEditorDialog), findsOneWidget); + expect(bloc.received.whereType(), isEmpty); + expect(bloc.state.bookId, 'ספר אחר'); + expect(panelOpenCalls, 0); + await pressAction(tester, 'ביטול'); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + expect(repository.writes, isEmpty); + expect(tester.takeException(), isNull); + }); + + testWidgets('שמירה בחלון צף משמרת ספר, קטגוריה, מקור בחירה ועוגן', ( + tester, + ) async { + await open(tester, anchor: _anchor); + await type(tester, 'הערת בדיקה'); + await pressAction(tester, 'שמור'); + final saved = repository.writes.single; + expect(saved.bookId, _bookId); + expect(saved.categoryId, _categoryId); + expect(saved.lineNumber, _lineNumber); + expect(saved.contentPlain, 'הערת בדיקה'); + expect(saved.contentFormat, PersonalNoteContentFormat.quillDelta); + expect(saved.selectedText, 'בחירה'); + expect(saved.selectionColumn, 8); + expect(saved.sourceSelectedText, 'בְּחִירָה'); + expect(saved.sourceSelectionOffset, 12); + expect(saved.punctuationHidden, isTrue); + expect(saved.pdfAnchor, _anchor); + expect(panelOpenCalls, 0); + expect(bloc.state.bookId, 'ספר אחר'); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('פאנל פתוח משחזר טיוטה בתוך החלונית ולא פותח דיאלוג', ( + tester, + ) async { + await saveDraft('תוכן טיוטה', anchor: _anchor); + await open(tester, panelOpen: true, anchor: _anchor); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + expect(panelOpenCalls, 1); + final event = bloc.received.whereType().single; + expect(event.bookId, _bookId); + expect(event.initialContent, 'תוכן טיוטה'); + expect(event.pdfAnchor, _anchor); + expect(event.sourceSelectionOffset, 12); + expect(bloc.state.bookId, _bookId); + expect(bloc.state.categoryId, _categoryId); + expect(bloc.state.isCreatingNewNote, isTrue); + expect(repository.writes, isEmpty); + }); + + testWidgets('Alt+Enter מתוך החלון הצף שומר פעם אחת בלי לשנות את התוכן', ( + tester, + ) async { + await open(tester); + await type(tester, 'שורה ראשונה\nשורה שנייה'); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pumpAndSettle(); + expect(repository.attempts, 1); + expect(repository.writes.single.contentPlain, 'שורה ראשונה\nשורה שנייה'); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('מעבר מהערות ספר אחר אינו מבטל את היצירה החדשה', (tester) async { + await open(tester, panelOpen: true, retargetSidebar: true); + expect(bloc.state.newNoteBookId, _bookId); + expect(bloc.state.isCreatingNewNote, isTrue); + expect(find.byType(InlineNoteEditor), findsOneWidget); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + }); + + testWidgets('נקודה חדשה באותו עמוד אינה טוענת או מוחקת טיוטה בנקודה אחרת', ( + tester, + ) async { + await saveDraft('טיוטה בנקודה א', anchor: _anchor); + const second = PdfNoteAnchor(pageNumber: 4, x: .8, y: .2); + await open(tester, anchor: second); + expect(editor(tester).controller.document.toPlainText().trim(), isEmpty); + await type(tester, 'הערה בנקודה ב'); + await pressAction(tester, 'שמור'); + expect(repository.writes.single.pdfAnchor, second); + expect( + (await drafts.loadDraft( + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + pdfAnchor: _anchor, + ))?.contentPlain, + 'טיוטה בנקודה א', + ); + }); + + testWidgets('החלפת נקודה בחלונית שומרת טיוטה ומתחילה עורך חדש', ( + tester, + ) async { + await open(tester, panelOpen: true, retargetSidebar: true, anchor: _anchor); + await type(tester, 'טיוטה בנקודה א'); + const second = PdfNoteAnchor(pageNumber: 4, x: .8, y: .2); + bloc.add( + const StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: _lineNumber, + pdfAnchor: second, + ), + ); + await tester.pumpAndSettle(); + expect(editor(tester).controller.document.toPlainText().trim(), isEmpty); + expect( + (await drafts.loadDraft( + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + pdfAnchor: _anchor, + ))?.contentPlain, + 'טיוטה בנקודה א', + ); + await type(tester, 'תוכן בנקודה ב'); + await pressAction(tester, 'שמור'); + expect(repository.writes.single.pdfAnchor, second); + expect(repository.writes.single.contentPlain, 'תוכן בנקודה ב'); + expect( + (await drafts.loadDraft( + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + pdfAnchor: _anchor, + ))?.contentPlain, + 'טיוטה בנקודה א', + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('כשל שמירה משאיר תוכן לעריכה וחוסם שמירה כפולה בזמן ההמתנה', ( + tester, + ) async { + final pending = Completer(); + repository.onAdd = () => pending.future; + await open(tester); + await type(tester, 'תוכן לשמירה חוזרת'); + editor(tester).controller.updateSelection( + const TextSelection(baseOffset: 0, extentOffset: 4), + quill.ChangeSource.local, + ); + final pendingContent = editor( + tester, + ).controller.document.toDelta().toJson(); + await pressAction(tester, 'שמור'); + expect(editor(tester).controller.readOnly, isTrue); + expect(repository.attempts, 1); + final boldIcon = find + .descendant( + of: find.byTooltip('מודגש'), + matching: find.byType(Icon), + ) + .first; + Focus.of(tester.element(boldIcon)).requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + expect( + editor(tester).controller.document.toDelta().toJson(), + pendingContent, + ); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pump(); + expect(repository.attempts, 1); + expect(find.byType(PersonalNoteEditorDialog), findsOneWidget); + repository.onAdd = null; + pending.completeError(StateError('storage unavailable')); + await tester.pumpAndSettle(); + expect(editor(tester).controller.readOnly, isFalse); + expect(editor(tester).focusNode.hasFocus, isTrue); + expect( + editor(tester).controller.document.toPlainText().trim(), + 'תוכן לשמירה חוזרת', + ); + expect(repository.writes, isEmpty); + await pressAction(tester, 'שמור'); + expect(repository.attempts, 2); + expect(repository.writes, hasLength(1)); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('כשל מחיקת טיוטה לאחר שמירה אינו מאפשר יצירת עותק נוסף', ( + tester, + ) async { + await saveDraft('טיוטה קיימת'); + await open(tester); + cache.failRemove = true; + await pressAction(tester, 'שמור'); + expect(repository.writes, hasLength(1)); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('כשל כתיבה בחלונית שומר טיוטה גם אחרי סגירה ופתיחה מחדש', ( + tester, + ) async { + final pending = Completer(); + repository.onAdd = () => pending.future; + await open(tester, panelOpen: true, retargetSidebar: true); + await type(tester, 'תוכן שנשמר אחרי ניסיון חוזר'); + await pressAction(tester, 'שמור'); + expect(editor(tester).controller.readOnly, isTrue); + expect(repository.attempts, 1); + expect( + tester + .widget(find.widgetWithText(ActionButton, 'שמור')) + .onPressed, + isNull, + ); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + expect(repository.attempts, 1); + pending.completeError(StateError('storage unavailable')); + await tester.pumpAndSettle(); + expect(bloc.state.isCreatingNewNote, isTrue); + expect(editor(tester).controller.readOnly, isFalse); + expect(repository.writes, isEmpty); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + expect( + (await drafts.loadDraft( + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + ))?.contentPlain, + 'תוכן שנשמר אחרי ניסיון חוזר', + ); + repository.onAdd = null; + await open(tester, panelOpen: true, retargetSidebar: true); + expect( + editor(tester).controller.document.toPlainText().trim(), + 'תוכן שנשמר אחרי ניסיון חוזר', + ); + await pressAction(tester, 'שמור'); + expect(repository.attempts, 2); + expect( + repository.writes.single.contentPlain, + 'תוכן שנשמר אחרי ניסיון חוזר', + ); + expect(bloc.state.isCreatingNewNote, isFalse); + expect( + await drafts.loadDraft( + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + ), + isNull, + ); + expect(tester.takeException(), isNull); + }); + + for (final discard in [false, true]) { + testWidgets( + 'כשל ${discard ? 'מחיקת' : 'שמירת'} טיוטה בסגירה משאיר את העורך', + (tester) async { + if (discard) await saveDraft('טיוטה קיימת'); + await open(tester, anchor: discard ? null : _anchor); + await type(tester, 'תוכן חדש '); + cache.failWrite = !discard; + cache.failRemove = discard; + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + await pressAction(tester, discard ? 'סגור בלי לשמור' : 'שמור טיוטה'); + expect(find.byType(PersonalNoteEditorDialog), findsOneWidget); + expect( + editor(tester).controller.document.toPlainText(), + contains('תוכן חדש'), + ); + expect(tester.takeException(), isNull); + cache.failWrite = false; + cache.failRemove = false; + await pressAction(tester, 'ביטול'); + await pressAction(tester, discard ? 'סגור בלי לשמור' : 'שמור טיוטה'); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + final draft = await drafts.loadDraft( + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + pdfAnchor: discard ? null : _anchor, + ); + if (discard) { + expect(draft, isNull); + } else { + expect(draft?.contentPlain, 'תוכן חדש'); + expect(draft?.pdfAnchor, _anchor); + expect(draft?.referenceText, 'מקור בדיקה'); + } + }, + ); + } + + testWidgets('שינוי עיצוב בלבד מבקש החלטה גם כש-Escape מגיע מתוך העורך', ( + tester, + ) async { + await saveDraft('תוכן מעוצב'); + await open(tester); + editor(tester).controller.formatText(0, 4, quill.Attribute.bold); + await tester.pump(); + editor(tester).focusNode.requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.text('ההערה לא נשמרה. לשמור טיוטה?'), findsOneWidget); + await pressAction(tester, 'שמור טיוטה'); + final draft = await drafts.loadDraft( + bookId: _bookId, + categoryId: _categoryId, + lineNumber: _lineNumber, + ); + expect(draft?.content, contains('"bold":true')); + expect(draft?.contentPlain, 'תוכן מעוצב'); + }); +} + +class _FailingCache extends MemoryCacheProvider { + bool failWrite = false; + bool failRemove = false; + + @override + Future setObject(String key, T? value) { + if (failWrite && key.startsWith(PersonalNoteDraftService.keyPrefix)) { + throw StateError('draft storage unavailable'); + } + return super.setObject(key, value); + } + + @override + Future remove(String key) { + if (failRemove && key.startsWith(PersonalNoteDraftService.keyPrefix)) { + throw StateError('draft storage unavailable'); + } + return super.remove(key); + } +} + +class _RecordingNotesBloc extends PersonalNotesBloc { + _RecordingNotesBloc(PersonalNotesRepository repository) + : super(repository: repository); + final received = []; + + @override + void onEvent(PersonalNotesEvent event) { + received.add(event); + super.onEvent(event); + } +} + +class _NotesRepository extends PersonalNotesRepository { + int attempts = 0; + Future Function()? onAdd; + final writes = []; + + @override + Future> loadNotes( + String bookId, { + int? categoryId, + }) async => []; + + @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 { + attempts++; + await onAdd?.call(); + writes.add( + AddPersonalNote( + bookId: bookId, + lineNumber: lineNumber, + content: content, + contentPlain: contentPlain, + contentFormat: contentFormat, + selectedText: selectedText, + selectionColumn: selectionColumn, + sourceSelectedText: sourceSelectedText, + sourceSelectionOffset: sourceSelectionOffset, + punctuationHidden: punctuationHidden, + pdfAnchor: pdfAnchor, + categoryId: categoryId, + ), + ); + final now = DateTime.utc(2026, 1, 1); + return PersonalNote( + id: 'created-${writes.length}', + bookId: bookId, + lineNumber: lineNumber, + lastKnownLineNumber: lineNumber, + status: PersonalNoteStatus.located, + content: content, + contentPlain: contentPlain, + contentFormat: contentFormat, + anchorText: selectedText, + pdfAnchor: pdfAnchor, + createdAt: now, + updatedAt: now, + ); + } +} diff --git a/test/personal_notes/widgets/inline_note_editor_test.dart b/test/personal_notes/widgets/inline_note_editor_test.dart index e0bbf3fb77..0b5eacd59f 100644 --- a/test/personal_notes/widgets/inline_note_editor_test.dart +++ b/test/personal_notes/widgets/inline_note_editor_test.dart @@ -1,8 +1,13 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_quill/flutter_quill.dart' as quill; import 'package:otzaria/settings/engine/app_settings_store.dart'; import 'package:otzaria/personal_notes/widgets/inline_note_editor.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_editor.dart'; +import 'package:otzaria/settings/engine/settings_bloc.dart'; +import 'package:otzaria/settings/engine/settings_repository.dart'; import '../../test_helpers/memory_cache_provider.dart'; void main() { @@ -12,6 +17,41 @@ void main() { await Settings.init(cacheProvider: MemoryCacheProvider()); }); + testWidgets('Alt+Enter בחלונית שומר פעם אחת בלי להוסיף ירידת שורה', ( + tester, + ) async { + final saved = []; + await tester.pumpWidget( + RepositoryProvider( + create: (_) => SettingsRepository(), + child: BlocProvider( + create: (context) => + SettingsBloc(repository: context.read()), + child: MaterialApp( + home: Scaffold( + body: InlineNoteEditor( + bookId: 'ספר בדיקה', + draftLineNumber: 4, + initialContent: 'שורה ראשונה\nשורה שנייה', + linkableNotes: const [], + onSave: saved.add, + onCancel: () {}, + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pumpAndSettle(); + expect(saved, hasLength(1)); + expect(saved.single.contentPlain, 'שורה ראשונה\nשורה שנייה'); + expect(tester.takeException(), isNull); + }); + testWidgets('InlineNoteEditor תופס פוקוס מיד בעלייה', (tester) async { // רגרסיה: בצורת הדף, פתיחת הערה חדשה לא תפסה פוקוס במצב הראשוני // (autoFocus של QuillEditor איבד את ה-race עם אנימציית הפאנל). diff --git a/test/personal_notes/widgets/note_tile_persistence_test.dart b/test/personal_notes/widgets/note_tile_persistence_test.dart new file mode 100644 index 0000000000..e46ff0655b --- /dev/null +++ b/test/personal_notes/widgets/note_tile_persistence_test.dart @@ -0,0 +1,210 @@ +import 'dart:async'; + +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/services/personal_note_draft_service.dart'; +import 'package:otzaria/personal_notes/widgets/inline_note_editor.dart'; +import 'package:otzaria/personal_notes/widgets/note_tile.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_editor.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'; + +PersonalNote _note() => PersonalNote( + id: 'existing-note', + bookId: 'ספר בדיקה', + lineNumber: 4, + lastKnownLineNumber: 4, + displayTitle: 'שורה 4', + status: PersonalNoteStatus.located, + content: 'תוכן קודם', + contentPlain: 'תוכן קודם', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026, 1, 1), + updatedAt: DateTime(2026, 1, 1), +); + +Widget _harness(PersonalNoteSaveCallback onSave) => RepositoryProvider( + create: (_) => SettingsRepository(), + child: BlocProvider( + create: (context) => + SettingsBloc(repository: context.read()), + child: MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: NoteTile( + note: _note(), + bookId: _note().bookId, + defaultExpanded: true, + linkableNotes: const [], + onSave: onSave, + onDelete: () {}, + onLinkTap: (_) {}, + ), + ), + ), + ), + ), +); + +quill.QuillController _controller(WidgetTester tester) => + tester.widget(find.byType(quill.QuillEditor)).controller; + +void _replaceContent(WidgetTester tester, String content) { + final controller = _controller(tester); + controller.replaceText( + 0, + controller.document.length - 1, + content, + TextSelection.collapsed(offset: content.length), + ); +} + +Future _openEditor(WidgetTester tester) async { + await tester.tap(find.byTooltip('עריכה')); + await tester.pumpAndSettle(); + expect(find.byType(InlineNoteEditor), findsOneWidget); +} + +Future _draft() => PersonalNoteDraftService().loadDraft( + bookId: _note().bookId, + noteId: _note().id, +); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + await Settings.init(cacheProvider: MemoryCacheProvider()); + }); + + testWidgets( + 'an edit waits for persistence and a failed save can be retried', + ( + tester, + ) async { + final requests = >[]; + final results = []; + Future save(PersonalNoteEditorResult result) { + results.add(result); + final request = Completer(); + requests.add(request); + return request.future; + } + + await tester.pumpWidget(_harness(save)); + await tester.pumpAndSettle(); + await _openEditor(tester); + const changed = 'תוכן ערוך שנשמר רק לאחר הצלחה'; + _replaceContent(tester, changed); + await tester.pump(); + await tester.tap(find.text('שמור')); + await tester.pump(); + + expect(results.single.contentPlain, changed); + expect(find.byType(InlineNoteEditor), findsOneWidget); + expect(_controller(tester).readOnly, isTrue); + + // Both the button and keyboard shortcut must honor the same pending save. + await tester.tap(find.text('שמור')); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.tap(find.byTooltip('ביטול')); + await tester.pump(); + expect(results, hasLength(1)); + expect(find.byType(InlineNoteEditor), findsOneWidget); + + requests.single.completeError(StateError('write failed')); + await tester.pumpAndSettle(); + expect(find.byType(InlineNoteEditor), findsOneWidget); + expect(_controller(tester).readOnly, isFalse); + expect(_controller(tester).document.toPlainText().trimRight(), changed); + await tester.pump(const Duration(milliseconds: 300)); + expect((await _draft())?.contentPlain, changed); + + await tester.tap(find.text('שמור')); + await tester.pump(); + expect(results, hasLength(2)); + expect(results.last.contentPlain, changed); + requests.last.complete(); + await tester.pumpAndSettle(); + + expect(find.byType(InlineNoteEditor), findsNothing); + expect(find.byTooltip('עריכה'), findsOneWidget); + expect(await _draft(), isNull); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('a failed edit restores its draft after the note is reopened', ( + tester, + ) async { + var attempts = 0; + Future save(PersonalNoteEditorResult result) async { + attempts++; + throw StateError('write failed'); + } + + await tester.pumpWidget(_harness(save)); + await tester.pumpAndSettle(); + await _openEditor(tester); + const changed = 'טיוטת עריכה לאחר כשל כתיבה'; + _replaceContent(tester, changed); + await tester.pump(); + await tester.tap(find.text('שמור')); + await tester.pumpAndSettle(); + expect(attempts, 1); + expect(find.byType(InlineNoteEditor), findsOneWidget); + + // Removal before the debounce elapses must also retain the unsaved edit. + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + expect((await _draft())?.contentPlain, changed); + await tester.pumpWidget(_harness(save)); + await tester.pumpAndSettle(); + + expect(find.byType(InlineNoteEditor), findsOneWidget); + expect(_controller(tester).document.toPlainText().trimRight(), changed); + expect(_controller(tester).readOnly, isFalse); + expect(attempts, 1); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'a pending edit can be removed without losing its draft on error', + ( + tester, + ) async { + final request = Completer(); + await tester.pumpWidget(_harness((_) => request.future)); + await tester.pumpAndSettle(); + await _openEditor(tester); + const changed = 'טיוטה בזמן כתיבה ממתינה'; + _replaceContent(tester, changed); + await tester.pump(); + await tester.tap(find.text('שמור')); + await tester.pump(); + expect(_controller(tester).readOnly, isTrue); + + await tester.pumpWidget(const SizedBox.shrink()); + request.completeError(StateError('late write failure')); + await tester.pumpAndSettle(); + expect((await _draft())?.contentPlain, changed); + expect(tester.takeException(), isNull); + + await tester.pumpWidget(_harness((_) {})); + await tester.pumpAndSettle(); + expect(find.byType(InlineNoteEditor), findsOneWidget); + expect(_controller(tester).document.toPlainText().trimRight(), changed); + expect(_controller(tester).readOnly, isFalse); + expect(tester.takeException(), isNull); + }, + ); +} diff --git a/test/personal_notes/widgets/personal_notes_export_dialog_test.dart b/test/personal_notes/widgets/personal_notes_export_dialog_test.dart new file mode 100644 index 0000000000..faad6c9e18 --- /dev/null +++ b/test/personal_notes/widgets/personal_notes_export_dialog_test.dart @@ -0,0 +1,106 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/widgets/personal_notes_export_dialog.dart'; + +PersonalNote _note(String id, String bookId, {String? displayTitle}) => + PersonalNote( + id: id, + bookId: bookId, + lineNumber: 69, + lastKnownLineNumber: null, + status: PersonalNoteStatus.located, + displayTitle: displayTitle, + content: 'בהמשך הגמרא', + contentPlain: 'בהמשך הגמרא', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), + ); + +Future _open( + WidgetTester tester, + List notes, { + ValueChanged? onExport, +}) async { + await tester.binding.setSurfaceSize(const Size(1200, 900)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + MaterialApp( + locale: const Locale('he', 'IL'), + localizationsDelegates: GlobalMaterialLocalizations.delegates, + supportedLocales: const [Locale('he', 'IL')], + home: Builder( + builder: (context) => TextButton( + onPressed: () async { + final result = await showDialog( + context: context, + builder: (_) => PersonalNotesExportDialog(allNotes: notes), + ); + onExport?.call(result); + }, + child: const Text('פתח ייצוא'), + ), + ), + ), + ); + await tester.tap(find.text('פתח ייצוא')); + await tester.pumpAndSettle(); + await tester.tap(find.text('בחירה ידנית')); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets( + 'manual export distinguishes the same page in different books', + (tester) async { + NotesExportSelection? selection; + await _open( + tester, + [ + _note('berakhot', 'ברכות|user', displayTitle: 'דף סט:'), + _note('shabbat', 'שבת|db:fixture', displayTitle: 'דף סט:'), + ], + onExport: (result) => selection = result, + ); + + expect(find.text('ברכות — דף סט:'), findsOneWidget); + expect(find.text('שבת — דף סט:'), findsOneWidget); + expect(find.textContaining('|user'), findsNothing); + expect(find.textContaining('|db:'), findsNothing); + await tester.tap(find.text('שבת — דף סט:')); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), 'ברכות'); + await tester.pumpAndSettle(); + expect(find.text('ברכות — דף סט:'), findsOneWidget); + expect(find.text('שבת — דף סט:'), findsNothing); + await tester.enterText(find.byType(TextField), ''); + await tester.pumpAndSettle(); + final selected = tester.widget( + find.widgetWithText(CheckboxListTile, 'שבת — דף סט:'), + ); + expect(selected.value, isTrue); + + await tester.tap(find.text('ייצא')); + await tester.pumpAndSettle(); + expect(selection!.notes.map((note) => note.id), ['shabbat']); + }, + ); + + testWidgets('manual export shows a readable book without a location title', ( + tester, + ) async { + await _open(tester, [ + _note('empty', 'ברכות|user', displayTitle: ' '), + _note('same-title', 'שבת|db:fixture', displayTitle: 'שבת'), + ]); + + expect(find.text('ברכות'), findsOneWidget); + expect(find.text('שבת'), findsOneWidget); + expect(find.textContaining('|user'), findsNothing); + expect(find.textContaining('|db:'), findsNothing); + expect(find.text('שבת — שבת'), 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 new file mode 100644 index 0000000000..d62f8bd9b0 --- /dev/null +++ b/test/personal_notes/widgets/personal_notes_sidebar_reveal_test.dart @@ -0,0 +1,490 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_quill/flutter_quill.dart' as quill; +import 'package:hive_ce/hive.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/utils/open_personal_notes_target.dart'; +import 'package:otzaria/personal_notes/widgets/inline_note_editor.dart'; +import 'package:otzaria/personal_notes/widgets/note_tile.dart'; +import 'package:otzaria/personal_notes/widgets/personal_notes_sidebar.dart'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; +import 'package:positioned_sliver_list/positioned_list.dart'; + +import '../../test_helpers/memory_cache_provider.dart'; + +const _bookId = 'ספר בדיקה'; + +class _NotesRepository extends PersonalNotesRepository { + final notes = List.generate( + 40, + (index) => PersonalNote( + id: 'note-${index + 1}', + bookId: _bookId, + lineNumber: index + 1, + displayTitle: 'הערה ${index + 1}', + lastKnownLineNumber: index + 1, + status: PersonalNoteStatus.located, + content: 'תוכן ${index + 1}', + contentPlain: 'תוכן ${index + 1}', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), + ), + ); + + @override + Future> loadNotes( + String bookId, { + int? categoryId, + }) async => notes; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + await Settings.init(cacheProvider: MemoryCacheProvider()); + }); + + Future pumpSidebar( + WidgetTester tester, { + int? focusLineNumber, + PersonalNotesBloc? notesBloc, + bool isPdf = false, + String? pdfDocumentId, + }) async { + final bloc = notesBloc ?? PersonalNotesBloc(repository: _NotesRepository()); + addTearDown(bloc.close); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.topRight, + child: SizedBox( + width: 400, + height: 400, + child: BlocProvider.value( + value: bloc, + child: PersonalNotesSidebar( + bookId: _bookId, + isPdf: isPdf, + pdfDocumentId: pdfDocumentId, + focusLineNumber: focusLineNumber, + onNavigateToLine: (_, {note}) {}, + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + return bloc; + } + + ItemScrollController controller(WidgetTester tester) => tester + .widget(find.byType(ScrollablePositionedList)) + .itemScrollController!; + + void expectVisible(WidgetTester tester, Finder finder) { + expect(finder, findsOneWidget); + final viewport = tester.getRect(find.byType(ScrollablePositionedList)); + expect(tester.getRect(finder).overlaps(viewport), isTrue); + } + + testWidgets('פתיחה ראשונה גוללת להערה רחוקה ומרחיבה אותה לאחר הטעינה', ( + tester, + ) async { + await pumpSidebar(tester, focusLineNumber: 35); + + expectVisible(tester, find.text('תוכן 35')); + expect(controller(tester).scrollController!.offset, greaterThan(0)); + expect(tester.takeException(), isNull); + }); + + testWidgets('עוגן PDF חסר נחשף אחרי כותרת וטופס, גם כשיש הערה באותו עמוד', ( + tester, + ) async { + const anchor = PdfNoteAnchor( + pageNumber: 5, + x: .2, + y: .7, + documentId: 'user|pdf-book', + ); + final repository = _NotesRepository(); + repository.notes.add( + PersonalNote( + id: 'missing-pdf-point', + bookId: _bookId, + lineNumber: null, + displayTitle: '', + lastKnownLineNumber: 5, + status: PersonalNoteStatus.missing, + content: 'תוכן עוגן חסר', + contentPlain: 'תוכן עוגן חסר', + contentFormat: PersonalNoteContentFormat.plain, + pdfAnchor: anchor, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), + ), + ); + final notesBloc = PersonalNotesBloc(repository: repository); + notesBloc.add(const LoadPersonalNotes(_bookId)); + await notesBloc.stream.firstWhere((state) => !state.isLoading); + notesBloc.add( + const StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: 2, + pdfAnchor: PdfNoteAnchor( + pageNumber: 2, + x: .1, + y: .3, + documentId: 'user|pdf-book', + ), + ), + ); + await notesBloc.stream.firstWhere((state) => state.isCreatingNewNote); + final bloc = await pumpSidebar( + tester, + notesBloc: notesBloc, + isPdf: true, + pdfDocumentId: anchor.documentId, + ); + + openPersonalNotesTarget( + bloc, + bookId: _bookId, + lineNumber: 5, + pdfAnchor: anchor, + ); + await tester.pumpAndSettle(); + + expectVisible(tester, find.text('תוכן עוגן חסר')); + final tile = tester.widget( + find.byKey(const ValueKey('missing-pdf-point')), + ); + expect(tile.expandToken, bloc.state.expandRequestToken); + expect(bloc.state.isCreatingNewNote, isTrue); + + // בקשת שורה רגילה מסירה את הזהות הקודמת, גם אם המספר זהה. + bloc.add(const RequestExpandNotesForLine(5)); + await tester.pumpAndSettle(); + expect(bloc.state.expandRequestPdfAnchor, isNull); + expectVisible(tester, find.text('תוכן 5')); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('לחיצה חוזרת גוללת שוב ליעד שנגלל החוצה ונפתח אחרי כיווץ', ( + tester, + ) async { + final bloc = await pumpSidebar(tester, focusLineNumber: 35); + final target = find.byWidgetPredicate( + (widget) => widget is NoteTile && widget.note.id == 'note-35', + ); + await tester.tap( + find.descendant(of: target, matching: find.byTooltip('סגור')), + ); + await tester.pumpAndSettle(); + controller(tester).jumpTo(index: 0); + await tester.pumpAndSettle(); + + bloc.add(const RequestExpandNotesForLine(35)); + await tester.pumpAndSettle(); + + expectVisible(tester, find.text('תוכן 35')); + expect(tester.takeException(), isNull); + }); + + testWidgets('יצירת הערה אחרי גלילה חושפת את העורך בראש הרשימה', ( + tester, + ) async { + final bloc = await pumpSidebar(tester); + controller(tester).jumpTo(index: 30); + await tester.pumpAndSettle(); + expect(controller(tester).scrollController!.offset, greaterThan(0)); + + bloc.add(const StartCreatingPersonalNote(bookId: _bookId, lineNumber: 36)); + await tester.pumpAndSettle(); + + expectVisible(tester, find.byType(InlineNoteEditor)); + // הכרטיס גבוה מהחלונית; הפוקוס עשוי לגלול שוב כדי לחשוף את אזור ההקלדה. + // נדרשת נראות מלאה של הקלט ופוקוס פעיל, ולא היסט פיקסלים פנימי מסוים. + final input = find.descendant( + of: find.byType(InlineNoteEditor), + matching: find.byType(quill.QuillEditor), + ); + 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(tester.widget(input).focusNode.hasFocus, isTrue); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('רענון רגיל אינו מחזיר את המשתמש ליעד שכבר נחשף', ( + tester, + ) async { + final bloc = await pumpSidebar(tester, focusLineNumber: 35); + controller(tester).jumpTo(index: 0); + await tester.pumpAndSettle(); + + bloc.add(const LoadPersonalNotes(_bookId)); + await tester.pumpAndSettle(); + + expect(controller(tester).scrollController!.offset, closeTo(0, 0.01)); + expect(tester.takeException(), isNull); + }); + + testWidgets('ניווט אחרון גובר על טיוטה פעילה גם בבנייה ראשונה של החלונית', ( + tester, + ) async { + final notesBloc = PersonalNotesBloc(repository: _NotesRepository()); + notesBloc.add(const LoadPersonalNotes(_bookId)); + await notesBloc.stream.firstWhere((state) => !state.isLoading); + notesBloc.add( + const StartCreatingPersonalNote(bookId: _bookId, lineNumber: 2), + ); + notesBloc.add(const RequestExpandNotesForLine(35)); + await notesBloc.stream.firstWhere( + (state) => state.expandRequestLineNumber == 35, + ); + final bloc = await pumpSidebar(tester, notesBloc: notesBloc); + + expectVisible(tester, find.text('תוכן 35')); + expect(bloc.state.isCreatingNewNote, isTrue); + bloc.add(const LoadPersonalNotes(_bookId)); + await tester.pumpAndSettle(); + expectVisible(tester, find.text('תוכן 35')); + + bloc.add( + const StartCreatingPersonalNote(bookId: _bookId, lineNumber: 2), + ); + await tester.pumpAndSettle(); + expectVisible(tester, find.byType(InlineNoteEditor)); + expect(bloc.state.expandRequestLineNumber, isNull); + expect(controller(tester).scrollController!.offset, closeTo(0, 0.01)); + await tester.pumpWidget(const SizedBox()); + }); + + for (final (selection, cancelFirst) in [ + ('בחירה שנייה', false), + ('בחירה ראשונה', false), + ('בחירה ראשונה', true), + ]) { + testWidgets( + 'בקשת יצירה חוזרת חושפת עורך שנגלל החוצה: $selection, ביטול קודם=$cancelFirst', + (tester) async { + final bloc = await pumpSidebar(tester); + bloc.add( + const StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: 2, + selectedText: 'בחירה ראשונה', + ), + ); + await tester.pumpAndSettle(); + controller(tester).jumpTo(index: 30); + await tester.pumpAndSettle(); + + if (cancelFirst) bloc.add(const CancelCreatingPersonalNote()); + bloc.add( + StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: 2, + selectedText: selection, + ), + ); + await tester.pumpAndSettle(); + + expectVisible(tester, find.byType(InlineNoteEditor)); + expect(controller(tester).scrollController!.offset, closeTo(0, 0.01)); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + } + + testWidgets('נקודת PDF חדשה מחליפה עורך מחוץ למסך ובקשה זהה משמרת אותו', ( + tester, + ) async { + const documentId = 'user|pdf-points'; + const first = PdfNoteAnchor( + pageNumber: 2, + x: .2, + y: .3, + documentId: documentId, + ); + const second = PdfNoteAnchor( + pageNumber: 2, + x: .8, + y: .7, + documentId: documentId, + ); + final bloc = await pumpSidebar( + tester, + isPdf: true, + pdfDocumentId: documentId, + ); + void request(PdfNoteAnchor anchor, {bool staleDraft = false}) => bloc.add( + StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: 2, + initialContent: staleDraft + ? '[{"insert":"טיוטה ישנה\\n"}]' + : 'תוכן התחלתי', + initialFormat: staleDraft + ? PersonalNoteContentFormat.quillDelta + : PersonalNoteContentFormat.plain, + pdfAnchor: anchor, + ), + ); + quill.QuillEditor editor() => tester.widget( + find.byType(quill.QuillEditor), + ); + + request(first); + await tester.pumpAndSettle(); + final firstController = editor().controller; + firstController.document.insert(0, 'נקודה א '); + await tester.pumpAndSettle(); + controller(tester).jumpTo(index: 30); + await tester.pumpAndSettle(); + + request(second); + await tester.pumpAndSettle(); + final secondController = editor().controller; + expect(identical(firstController, secondController), isFalse); + expect(secondController.document.toPlainText().trim(), 'תוכן התחלתי'); + expectVisible(tester, find.byType(quill.QuillEditor)); + expect( + (await PersonalNoteDraftService().loadDraft( + bookId: _bookId, + lineNumber: 2, + pdfAnchor: first, + ))?.contentPlain, + 'נקודה א תוכן התחלתי', + ); + expect(tester.takeException(), isNull); + + secondController.document.insert(0, 'נקודה ב '); + await tester.pumpAndSettle(); + controller(tester).jumpTo(index: 30); + await tester.pumpAndSettle(); + request(second, staleDraft: true); + await tester.pumpAndSettle(); + expect(identical(editor().controller, secondController), isTrue); + expect( + editor().controller.document.toPlainText().trim(), + 'נקודה ב תוכן התחלתי', + ); + expectVisible(tester, find.byType(InlineNoteEditor)); + expect(controller(tester).scrollController!.offset, closeTo(0, .01)); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + }); + + group('שחזור טיוטה שמורה', () { + final drafts = PersonalNoteDraftService(); + + setUp(() async { + // Hive אמיתי נדרש לסריקת box.keys; backend בזיכרון מאפשר גם לשמירה + // מתוך dispose להסתיים ב-fakeAsync, בלי כתיבת קובץ שממשיכה לאחר הבדיקה. + await Hive.openBox( + HiveCache.keyName, + bytes: Uint8List(0), + ); + await Settings.init(cacheProvider: HiveCache()); + await drafts.saveDraft( + bookId: _bookId, + lineNumber: 2, + draft: PersonalNoteDraft( + content: 'טיוטה שנשמרה', + contentPlain: 'טיוטה שנשמרה', + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime(2026), + lineNumber: 2, + ), + ); + }); + + tearDown(() async { + await Hive.close(); + }); + + testWidgets('פתיחת חלונית רגילה עדיין משחזרת את הטיוטה', (tester) async { + final bloc = await pumpSidebar(tester); + + expect(bloc.state.newNoteLineNumber, 2); + expect(bloc.state.newNoteInitialContent, 'טיוטה שנשמרה'); + expectVisible(tester, find.byType(InlineNoteEditor)); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + + expect( + (await drafts.loadDraft(bookId: _bookId, lineNumber: 2))?.contentPlain, + 'טיוטה שנשמרה', + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('ניווט מפורש אינו נגנב על ידי טיוטה שמורה בשורה אחרת', ( + tester, + ) async { + final bloc = await pumpSidebar(tester, focusLineNumber: 35); + + expectVisible(tester, find.text('תוכן 35')); + expect(bloc.state.isCreatingNewNote, isFalse); + expect( + (await drafts.loadDraft(bookId: _bookId, lineNumber: 2))?.content, + 'טיוטה שנשמרה', + ); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('יצירה מפורשת אינה מוחלפת בטיוטה שמורה של שורה אחרת', ( + tester, + ) async { + final notesBloc = PersonalNotesBloc(repository: _NotesRepository()); + notesBloc.add( + const StartCreatingPersonalNote( + bookId: _bookId, + lineNumber: 36, + initialContent: 'טיוטה נוכחית', + ), + ); + await notesBloc.stream.firstWhere((state) => state.isCreatingNewNote); + final bloc = await pumpSidebar(tester, notesBloc: notesBloc); + + expect(bloc.state.newNoteLineNumber, 36); + expect(bloc.state.newNoteInitialContent, 'טיוטה נוכחית'); + expectVisible(tester, find.byType(InlineNoteEditor)); + expect( + (await drafts.loadDraft(bookId: _bookId, lineNumber: 2))?.content, + 'טיוטה שנשמרה', + ); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + + expect( + (await drafts.loadDraft(bookId: _bookId, lineNumber: 36))?.contentPlain, + 'טיוטה נוכחית', + ); + expect( + (await drafts.loadDraft(bookId: _bookId, lineNumber: 2))?.contentPlain, + 'טיוטה שנשמרה', + ); + expect(tester.takeException(), isNull); + }); + }); +} diff --git a/test/printing/pdf_sheet_composer_test.dart b/test/printing/pdf_sheet_composer_test.dart index 2ae3adf198..a7069da60f 100644 --- a/test/printing/pdf_sheet_composer_test.dart +++ b/test/printing/pdf_sheet_composer_test.dart @@ -65,12 +65,23 @@ void main() { }); group('composePdfSheets', () { + final originalModulePath = Pdfrx.pdfiumModulePath; setUpAll(() async { + final moduleName = Platform.isWindows + ? 'pdfium.dll' + : Platform.isMacOS + ? 'libpdfium.dylib' + : 'libpdfium.so'; + Pdfrx.pdfiumModulePath = File( + 'build/native_assets/${Platform.operatingSystem}/$moduleName', + ).absolute.path; // Skips the path_provider lookup, which a plain test has no plugin for. Pdfrx.cacheDirectoryPath = Directory.systemTemp.path; await pdfrxFlutterInitialize(); }); + tearDownAll(() => Pdfrx.pdfiumModulePath = originalModulePath); + test('שני עמודים בגיליון נשארים טקסט, הראשון מימין', () async { final source = await PdfDocument.openData(await _numberedPdf(5)); addTearDown(source.dispose); diff --git a/test/printing/printing_screen_export_profile_test.dart b/test/printing/printing_screen_export_profile_test.dart index e65470fef1..f494c8b7c4 100644 --- a/test/printing/printing_screen_export_profile_test.dart +++ b/test/printing/printing_screen_export_profile_test.dart @@ -142,11 +142,14 @@ void main() { setUpAll(() async { await Settings.init(cacheProvider: MemorySettingsCache()); await Settings.setValue('key-print-destination', 1); - if (Platform.isMacOS) { - Pdfrx.pdfiumModulePath = File( - 'build/native_assets/macos/libpdfium.dylib', - ).absolute.path; - } + final moduleName = Platform.isWindows + ? 'pdfium.dll' + : Platform.isMacOS + ? 'libpdfium.dylib' + : 'libpdfium.so'; + Pdfrx.pdfiumModulePath = File( + 'build/native_assets/${Platform.operatingSystem}/$moduleName', + ).absolute.path; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(pathProviderChannel, (_) async => '/tmp'); }); diff --git a/test/printing/printing_screen_output_test.dart b/test/printing/printing_screen_output_test.dart index 11f3343fb0..2dc9b062cb 100644 --- a/test/printing/printing_screen_output_test.dart +++ b/test/printing/printing_screen_output_test.dart @@ -95,11 +95,20 @@ Future _settle(WidgetTester tester, Future future) async { void main() { const pathProviderChannel = MethodChannel('plugins.flutter.io/path_provider'); + final originalModulePath = Pdfrx.pdfiumModulePath; late PrintingPlatform originalPlatform; late Directory tempDir; setUpAll(() async { await Settings.init(cacheProvider: MemorySettingsCache()); + final moduleName = Platform.isWindows + ? 'pdfium.dll' + : Platform.isMacOS + ? 'libpdfium.dylib' + : 'libpdfium.so'; + Pdfrx.pdfiumModulePath = File( + 'build/native_assets/${Platform.operatingSystem}/$moduleName', + ).absolute.path; originalPlatform = PrintingPlatform.instance; tempDir = Directory.systemTemp.createTempSync('otzaria-print-output-'); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger @@ -110,6 +119,7 @@ void main() { }); tearDownAll(() { + Pdfrx.pdfiumModulePath = originalModulePath; PrintingPlatform.instance = originalPlatform; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(pathProviderChannel, null); diff --git a/test/printing/word_export_source_links_test.dart b/test/printing/word_export_source_links_test.dart new file mode 100644 index 0000000000..b54e972b4c --- /dev/null +++ b/test/printing/word_export_source_links_test.dart @@ -0,0 +1,585 @@ +import 'dart:convert'; + +import 'package:archive/archive.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/library/models/library.dart'; +import 'package:otzaria/models/book_source.dart'; +import 'package:otzaria/models/books.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/services/personal_notes_import_export_service.dart'; +import 'package:otzaria/personal_notes/utils/personal_note_source_link.dart'; +import 'package:otzaria/personal_notes/utils/personal_notes_book_key.dart'; +import 'package:otzaria/printing/print_content_models.dart'; +import 'package:otzaria/printing/word_export_service.dart'; +import 'package:pdf/pdf.dart'; +import 'package:xml/xml.dart'; + +const _wordNamespace = + 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'; +const _relationshipNamespace = + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'; + +PersonalNote _note( + String id, { + String bookId = 'ספר בדיקה', + int? lineNumber = 1, + PersonalNoteStatus status = PersonalNoteStatus.located, + PdfNoteAnchor? pdfAnchor, +}) => PersonalNote( + id: id, + bookId: bookId, + lineNumber: lineNumber, + lastKnownLineNumber: null, + status: status, + pdfAnchor: pdfAnchor, + content: 'תוכן $id', + contentPlain: 'תוכן $id', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), +); + +Archive _document(List blocks) => ZipDecoder().decodeBytes( + WordExportService.createWordDocument( + title: 'בדיקת קישורים', + blocks: blocks, + format: PdfPageFormat.a4, + isLandscape: false, + pageMargin: 20, + ), +); + +XmlDocument _xml(Archive archive, String path) { + final file = archive.findFile(path); + expect(file, isNotNull, reason: path); + return XmlDocument.parse(utf8.decode(file!.content as List)); +} + +List _hyperlinks(XmlDocument document) => document + .findAllElements('hyperlink', namespaceUri: _wordNamespace) + .toList(); + +Map _relationships(Archive archive) => { + for (final relationship in _xml( + archive, + 'word/_rels/document.xml.rels', + ).rootElement.childElements) + relationship.getAttribute('Id')!: relationship, +}; + +String? _target(XmlElement hyperlink, Map relationships) { + final id = hyperlink.getAttribute('id', namespaceUri: _relationshipNamespace); + expect(id, isNotNull); + expect(relationships, contains(id)); + final relationship = relationships[id]!; + expect( + relationship.getAttribute('Type'), + '$_relationshipNamespace/hyperlink', + ); + expect(relationship.getAttribute('TargetMode'), 'External'); + return relationship.getAttribute('Target'); +} + +void main() { + group('Word source-link metadata', () { + test('old block JSON remains unlinked and new metadata survives JSON', () { + final oldJson = { + 'kind': 'heading', + 'text': 'מיקום ישן', + 'headingLevel': 2, + 'footnotes': [ + {'text': 'הערת שוליים'}, + ], + }; + final oldBlock = PrintBlock.fromJson(oldJson); + expect(oldBlock.sourceLink, isNull); + expect(oldBlock.toJson(), oldJson); + + final linkedJson = { + ...oldJson, + 'sourceLink': 'otzaria://open/book/12?source=user&index=2', + }; + final roundTrip = PrintBlock.fromJson( + Map.from(jsonDecode(jsonEncode(linkedJson)) as Map), + ); + expect(roundTrip.toJson(), linkedJson); + expect(roundTrip.footnotes.single.text, 'הערת שוליים'); + }); + + test('DOCX links retain heading, inline styles, RTL, and footnotes', () { + const source = 'otzaria://open/book/12?source=user&index=2'; + final archive = _document(const [ + PrintBlock( + kind: PrintBlockKind.heading, + headingLevel: 2, + text: 'מיקום מודגש נטוי & טקסט', + sourceLink: source, + footnotes: [PrintFootnote(text: 'הערת שוליים נפרדת')], + ), + PrintBlock(kind: PrintBlockKind.text, text: 'תוכן הערה'), + ]); + final document = _xml(archive, 'word/document.xml'); + final link = _hyperlinks(document).single; + expect(_target(link, _relationships(archive)), source); + expect(link.innerText, 'מיקום מודגש נטוי & טקסט'); + final paragraph = link.parent as XmlElement; + expect(paragraph.name.local, 'p'); + expect(paragraph.childElements.first.name.local, 'pPr'); + expect( + paragraph + .findAllElements('pStyle', namespaceUri: _wordNamespace) + .single + .getAttribute('val', namespaceUri: _wordNamespace), + 'Heading2', + ); + for (final run in link.childElements) { + expect( + run.findAllElements('rtl', namespaceUri: _wordNamespace), + hasLength(1), + ); + expect( + run + .findAllElements('rStyle', namespaceUri: _wordNamespace) + .single + .getAttribute('val', namespaceUri: _wordNamespace), + 'Hyperlink', + ); + } + expect( + link.findAllElements('b', namespaceUri: _wordNamespace), + hasLength(1), + ); + expect( + link.findAllElements('bCs', namespaceUri: _wordNamespace), + hasLength(1), + ); + expect( + link.findAllElements('i', namespaceUri: _wordNamespace), + hasLength(1), + ); + expect( + link.findAllElements('iCs', namespaceUri: _wordNamespace), + hasLength(1), + ); + expect( + link.findAllElements('footnoteReference', namespaceUri: _wordNamespace), + isEmpty, + ); + expect( + paragraph.findAllElements( + 'footnoteReference', + namespaceUri: _wordNamespace, + ), + hasLength(1), + ); + final styles = _xml(archive, 'word/styles.xml'); + final hyperlinkStyle = styles + .findAllElements('style', namespaceUri: _wordNamespace) + .singleWhere( + (style) => + style.getAttribute('styleId', namespaceUri: _wordNamespace) == + 'Hyperlink', + ); + expect( + hyperlinkStyle.getAttribute('type', namespaceUri: _wordNamespace), + 'character', + ); + expect( + hyperlinkStyle.findAllElements('u', namespaceUri: _wordNamespace), + hasLength(1), + ); + expect( + _xml(archive, 'word/footnotes.xml').innerText, + contains('הערת שוליים נפרדת'), + ); + }); + + test( + 'relationship IDs are unique, reused, escaped, and local to export', + () { + const firstTarget = 'otzaria://open/book/7?index=2&label="A\''; + const secondTarget = 'otzaria://open/pdf/8?source=db%3Ademo&index=5'; + final archive = _document(const [ + PrintBlock( + kind: PrintBlockKind.heading, + text: 'א', + sourceLink: firstTarget, + ), + PrintBlock( + kind: PrintBlockKind.heading, + text: 'ב', + sourceLink: secondTarget, + ), + PrintBlock( + kind: PrintBlockKind.heading, + text: 'ג', + sourceLink: firstTarget, + ), + ]); + final relationships = _relationships(archive); + final allRelationships = _xml( + archive, + 'word/_rels/document.xml.rels', + ).rootElement.childElements; + expect(relationships.length, allRelationships.length); + expect( + relationships.keys, + containsAll(['rId1', 'rId2', 'rId3', 'rId4', 'rId5']), + ); + final links = _hyperlinks(_xml(archive, 'word/document.xml')); + expect( + links.map((link) => _target(link, relationships)), + [firstTarget, secondTarget, firstTarget], + ); + expect( + links.map( + (link) => + link.getAttribute('id', namespaceUri: _relationshipNamespace), + ), + ['rId6', 'rId7', 'rId6'], + ); + expect(relationships.length, 7); + + final next = _document(const [ + PrintBlock( + kind: PrintBlockKind.heading, + text: 'אחר', + sourceLink: secondTarget, + ), + ]); + expect(_relationships(next).length, 6); + expect( + _relationships(next)['rId6']!.getAttribute('Target'), + secondTarget, + ); + }, + ); + + test('unlinked and empty blocks create no hyperlink relationships', () { + final archive = _document(const [ + PrintBlock(kind: PrintBlockKind.heading, text: 'כותרת ללא קישור'), + PrintBlock(kind: PrintBlockKind.text, text: 'תוכן ללא קישור'), + PrintBlock( + kind: PrintBlockKind.heading, + text: 'קישור ריק', + sourceLink: '', + ), + PrintBlock( + kind: PrintBlockKind.heading, + text: ' ', + sourceLink: 'otzaria://open/book/1?index=0', + ), + ]); + expect(_hyperlinks(_xml(archive, 'word/document.xml')), isEmpty); + expect(_relationships(archive).length, 5); + }); + }); + + group('Personal-note export grouping', () { + test('identical labels group only notes at the same linked location', () { + final notes = [ + _note('c', lineNumber: 3), + _note('a', lineNumber: 2), + _note('b', lineNumber: 2), + _note('missing', lineNumber: null, status: PersonalNoteStatus.missing), + ]; + final blocks = PersonalNotesImportExportService().buildWordExportBlocks( + notes: notes, + locationRef: (_) => 'פרק & בדיקה', + sourceLink: (note) { + expect(note.hasLocation, isTrue); + return 'otzaria://open/book/7?index=${note.lineNumber! - 1}'; + }, + ); + final locations = blocks + .where((block) => block.headingLevel == 2) + .toList(); + expect(locations.map((block) => block.text), [ + 'פרק & בדיקה', + 'פרק & בדיקה', + 'הערות ללא מיקום', + ]); + expect(locations.map((block) => block.sourceLink), [ + 'otzaria://open/book/7?index=1', + 'otzaria://open/book/7?index=2', + null, + ]); + expect( + blocks + .where((block) => block.headingLevel != 2) + .every( + (block) => block.sourceLink == null, + ), + isTrue, + ); + final archive = _document(blocks); + expect( + _hyperlinks(_xml(archive, 'word/document.xml')).map( + (link) => _target(link, _relationships(archive)), + ), + ['otzaria://open/book/7?index=1', 'otzaria://open/book/7?index=2'], + ); + }); + + test('legacy export callback preserves label grouping without links', () { + final blocks = PersonalNotesImportExportService().buildWordExportBlocks( + notes: [_note('a'), _note('b', lineNumber: 2)], + locationRef: (_) => 'פרק משותף', + ); + expect(blocks.where((block) => block.headingLevel == 2), hasLength(1)); + expect(blocks.every((block) => block.sourceLink == null), isTrue); + }); + }); + + group('Personal-note source routing', () { + test( + 'PDF document identity chooses the correct edition and rejects ambiguity', + () { + final first = PdfBook(id: 31, title: 'ספר בדיקה', path: '/first.pdf'); + final second = PdfBook(id: 32, title: 'ספר בדיקה', path: '/second.pdf'); + final library = Library(categories: []) + ..books.addAll([first, second, TextBook(id: 33, title: 'ספר בדיקה')]); + final notes = [ + _note( + 'first', + pdfAnchor: PdfNoteAnchor( + pageNumber: 4, + x: 0.2, + y: 0.6, + documentId: pdfPersonalNoteDocumentId(first), + ), + ), + _note( + 'second', + lineNumber: 2, + pdfAnchor: PdfNoteAnchor( + pageNumber: 7, + x: 0.2, + y: 0.6, + documentId: pdfPersonalNoteDocumentId(second), + ), + ), + _note( + 'ambiguous', + lineNumber: 3, + pdfAnchor: const PdfNoteAnchor(pageNumber: 3, x: 0.2, y: 0.6), + ), + _note( + 'unavailable', + lineNumber: 4, + pdfAnchor: const PdfNoteAnchor( + pageNumber: 3, + x: 0.2, + y: 0.6, + documentId: 'unavailable-document', + ), + ), + ]; + expect(personalNoteSourceBook(library, notes[0]), same(first)); + expect(personalNoteSourceBook(library, notes[1]), same(second)); + expect( + personalNoteSourceLink( + first, + notes[1], + pdfLinkCandidates: [first, second], + ), + isNull, + ); + expect(personalNoteSourceBook(library, notes[2]), isNull); + expect(personalNoteSourceBook(library, notes[3]), isNull); + final blocks = PersonalNotesImportExportService().buildWordExportBlocks( + notes: notes, + locationRef: (note) => note.id, + sourceLink: (note) => personalNoteSourceLink( + personalNoteSourceBook(library, note), + note, + pdfLinkCandidates: [first, second], + ), + ); + final archive = _document(blocks); + expect( + _hyperlinks(_xml(archive, 'word/document.xml')).map( + (link) => _target(link, _relationships(archive)), + ), + ['otzaria://open/pdf/31?index=4', 'otzaria://open/pdf/32?index=7'], + ); + }, + ); + + test('borrowed PDF IDs cannot link two different documents to one URI', () { + final first = PdfBook(id: 40, title: 'ספר בדיקה', path: '/first.pdf'); + final second = PdfBook(id: 40, title: 'ספר בדיקה', path: '/second.pdf'); + final note = _note( + 'borrowed-id', + pdfAnchor: PdfNoteAnchor( + pageNumber: 5, + x: 0.2, + y: 0.6, + documentId: pdfPersonalNoteDocumentId(first), + ), + ); + final library = Library(categories: [])..books.addAll([first, second]); + expect(personalNoteSourceBook(library, note), same(first)); + expect(personalNoteSourceLink(first, note), isNull); + for (final candidates in >[ + [], + [second], + [first, second], + ]) { + expect( + personalNoteSourceLink(first, note, pdfLinkCandidates: candidates), + isNull, + ); + } + expect( + personalNoteSourceLink(first, note, pdfLinkCandidates: [first, first]), + 'otzaria://open/pdf/40?index=5', + ); + expect( + personalNoteSourceLink( + first, + note, + pdfLinkCandidates: [ + first, + PdfBook(id: 41, title: 'ספר בדיקה', path: '/second.pdf'), + PdfBook( + id: 40, + title: 'ספר בדיקה', + path: '/second.pdf', + source: BookSource.user, + ), + ], + ), + 'otzaria://open/pdf/40?index=5', + ); + }); + + for (final source in [ + BookSource.official, + BookSource.user, + BookSource.attached('fixture-db'), + ]) { + test('DOCX keeps exact text and PDF locations for ${source.wireKey}', () { + final text = TextBook(id: 21, title: 'ספר בדיקה', source: source); + final pdf = PdfBook( + id: 22, + title: 'ספר בדיקה', + path: '/fixture.pdf', + source: source, + ); + final library = Library(categories: [])..books.addAll([pdf, text]); + final textNote = _note('text', bookId: personalNotesBookKey(text)); + final pdfNote = _note( + 'pdf', + bookId: personalNotesBookKey(pdf), + lineNumber: 80, + pdfAnchor: const PdfNoteAnchor(pageNumber: 4, x: 0.2, y: 0.6), + ); + expect(personalNoteSourceBook(library, textNote), same(text)); + expect(personalNoteSourceBook(library, pdfNote), same(pdf)); + final sourceParameter = switch (source) { + OfficialBookSource() => '', + UserBookSource() => 'source=user&', + AttachedBookSource(:final slug) => 'source=db%3A$slug&', + }; + final expected = [ + 'otzaria://open/book/21?${sourceParameter}index=0', + 'otzaria://open/pdf/22?${sourceParameter}index=4', + ]; + final blocks = PersonalNotesImportExportService().buildWordExportBlocks( + notes: [textNote, pdfNote], + locationRef: (note) => 'מיקום ${note.id}', + sourceLink: (note) => personalNoteSourceLink( + personalNoteSourceBook(library, note), + note, + pdfLinkCandidates: [pdf], + ), + ); + final archive = _document(blocks); + expect( + _hyperlinks(_xml(archive, 'word/document.xml')).map( + (link) => _target(link, _relationships(archive)), + ), + expected, + ); + expect( + personalNoteSourceLink( + pdf, + _note( + 'legacy-pdf', + bookId: personalNotesBookKey(pdf), + lineNumber: 7, + ), + pdfLinkCandidates: [pdf], + ), + 'otzaria://open/pdf/22?${sourceParameter}index=7', + ); + }); + } + + test('same title in another source never supplies a target', () { + final official = TextBook(id: 1, title: 'ספר בדיקה'); + final user = TextBook(id: 1, title: 'ספר בדיקה', source: BookSource.user); + final attached = TextBook( + id: 1, + title: 'ספר בדיקה', + source: BookSource.attached('fixture-db'), + ); + final library = Library(categories: []) + ..books.addAll([user, attached, official]); + for (final book in [official, user, attached]) { + final note = _note('source', bookId: personalNotesBookKey(book)); + expect(personalNoteSourceBook(library, note), same(book)); + for (final other in [ + official, + user, + attached, + ].where((b) => b != book)) { + expect(personalNoteSourceLink(other, note), isNull); + } + } + expect( + personalNoteSourceBook(Library(categories: []), _note('unknown')), + isNull, + ); + expect(personalNoteSourceLink(null, _note('unknown')), isNull); + }); + + test('unresolved or invalid locations do not become first-line links', () { + final text = TextBook(id: 4, title: 'ספר בדיקה'); + final anchored = _note( + 'pdf-only', + pdfAnchor: const PdfNoteAnchor(pageNumber: 3, x: 0.5, y: 0.5), + ); + final textOnly = Library(categories: [])..books.add(text); + expect(personalNoteSourceBook(textOnly, anchored), isNull); + expect(personalNoteSourceLink(text, anchored), isNull); + expect( + personalNoteSourceLink(text, _note('other', bookId: 'ספר אחר')), + isNull, + ); + for (final id in [null, 0, -1]) { + expect( + personalNoteSourceLink( + TextBook(id: id, title: 'ספר בדיקה'), + _note('id'), + ), + isNull, + ); + } + for (final line in [null, 0, -1]) { + expect( + personalNoteSourceLink(text, _note('line', lineNumber: line)), + isNull, + ); + } + expect( + personalNoteSourceLink( + text, + _note('missing', status: PersonalNoteStatus.missing), + ), + isNull, + ); + }); + }); +} diff --git a/test/settings/services/backup_service_test.dart b/test/settings/services/backup_service_test.dart index 162acd9bfd..6de2c4527f 100644 --- a/test/settings/services/backup_service_test.dart +++ b/test/settings/services/backup_service_test.dart @@ -1420,6 +1420,157 @@ void main() { }); }); + group('שחזור הערות PDF — תאימות גיבוי ישן', () { + final database = PersonalNotesDatabase.instance; + const point = PdfNoteAnchor( + pageNumber: 7, + x: .2, + y: .8, + documentId: 'user|document.pdf', + ); + const importedPoint = PdfNoteAnchor( + pageNumber: 7, + x: .6, + y: .3, + documentId: 'user|another-document.pdf', + ); + + PersonalNote localNote({bool missing = false}) => PersonalNote( + id: 'pdf-note', + bookId: 'מסמך בדיקה|user', + lineNumber: missing ? null : 7, + displayTitle: 'מקור מסומן', + pdfAnchor: point, + lastKnownLineNumber: missing ? 7 : null, + status: missing ? PersonalNoteStatus.missing : PersonalNoteStatus.located, + content: 'תוכן מקומי', + contentPlain: 'תוכן מקומי', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime.utc(2026, 1, 1), + updatedAt: DateTime.utc(2026, 1, 1), + ); + + Map oldPayload({PersonalNote? original}) => + (original ?? localNote()) + .copyWith( + content: 'תוכן מהגיבוי', + contentPlain: 'תוכן מהגיבוי', + updatedAt: DateTime.utc(2026, 2, 1), + ) + .toJson() + ..remove('pdfAnchor'); + + Future restoreRows( + List> rows, + BackupImportMode mode, + ) async { + final file = File(p.join(tempDir.path, 'pdf_notes_backup.json')); + await file.writeAsString( + jsonEncode({ + 'version': '2.0', + 'includes': {'notes': true}, + 'notes': [ + for (final row in rows) + { + 'bookId': row['bookId'], + 'notes': [row], + }, + ], + }), + ); + return BackupService.restoreFromBackup(file.path, mode: mode); + } + + setUp(() async { + AppPaths.debugOverrideDataRootPath(tempDir.path); + await database.close(); + await database.insertNote(localNote()); + }); + + for (final mode in [BackupImportMode.replace, BackupImportMode.merge]) { + test( + 'pdfAnchor חסר משמר נקודה גם כש-anchorText קיים (${mode.name})', + () async { + final result = await restoreRows([oldPayload()], mode); + final restored = (await database.getNote('pdf-note'))!; + expect(restored.pdfAnchor, point); + expect(restored.content, 'תוכן מהגיבוי'); + expect(result.notesWithoutAnchor, 0); + }, + ); + + test('נקודה שנשמרה אינה מדווחת כאובדן עוגן (${mode.name})', () async { + final payload = oldPayload()..remove('anchorText'); + final result = await restoreRows([payload], mode); + expect((await database.getNote('pdf-note'))!.pdfAnchor, point); + expect(result.notesWithoutAnchor, 0); + }); + + test('pdfAnchor null מפורש מסיר את הנקודה (${mode.name})', () async { + final payload = oldPayload()..['pdfAnchor'] = null; + await restoreRows([payload], mode); + final restored = (await database.getNote('pdf-note'))!; + expect(restored.pdfAnchor, isNull); + expect(restored.content, 'תוכן מהגיבוי'); + }); + + test('נקודה מפורשת מהגיבוי גוברת על המקומית (${mode.name})', () async { + final payload = oldPayload()..['pdfAnchor'] = importedPoint.toJson(); + await restoreRows([payload], mode); + expect((await database.getNote('pdf-note'))!.pdfAnchor, importedPoint); + }); + + for (final (field, value) in <(String, Object)>[ + ('bookId', 'מסמך בדיקה'), + ('bookId', 'מסמך אחר|user'), + ('lineNumber', 8), + ('displayTitle', 'מקור שונה'), + ('status', PersonalNoteStatus.missing.name), + ]) { + test( + 'שינוי $field=$value אינו יורש נקודה מקומית (${mode.name})', + () async { + final payload = oldPayload()..[field] = value; + await restoreRows([payload], mode); + final restored = (await database.getNote('pdf-note'))!; + expect(restored.pdfAnchor, isNull); + expect(restored.content, 'תוכן מהגיבוי'); + }, + ); + } + + for (final lastKnown in [7, 8]) { + test('הערה חסרה משווה רמז מיקום $lastKnown (${mode.name})', () async { + final original = localNote(missing: true); + await database.insertNote(original); + final payload = oldPayload(original: original) + ..['lastKnownLineNumber'] = lastKnown; + await restoreRows([payload], mode); + final restored = (await database.getNote('pdf-note'))!; + expect(restored.lastKnownLineNumber, lastKnown); + expect(restored.pdfAnchor, lastKnown == 7 ? point : isNull); + }); + } + + for (final previousPoint in [importedPoint, null]) { + test( + 'כפילות בגיבוי משתמשת בנקודה הממתינה $previousPoint (${mode.name})', + () async { + final first = oldPayload()..['pdfAnchor'] = previousPoint?.toJson(); + final second = oldPayload() + ..['updatedAt'] = DateTime.utc(2026, 3, 1).toIso8601String() + ..['content'] = 'תוכן אחרון' + ..['contentPlain'] = 'תוכן אחרון'; + await restoreRows([first, second], mode); + final restored = (await database.getNote('pdf-note'))!; + expect(restored.pdfAnchor, previousPoint); + expect(restored.content, 'תוכן אחרון'); + }, + ); + } + } + }); + // ─── זיהוי סעיף הגדרות חלקי ──────────────────────────────────────────────── group('isPartialSettingsSection', () { final declaredOnly = { diff --git a/test/tabs/bloc/tabs_bloc_test.dart b/test/tabs/bloc/tabs_bloc_test.dart index 60fe7c736e..66691c2212 100644 --- a/test/tabs/bloc/tabs_bloc_test.dart +++ b/test/tabs/bloc/tabs_bloc_test.dart @@ -9,6 +9,7 @@ import 'package:otzaria/core/pre_close_registry.dart'; import 'package:otzaria/models/book_source.dart'; import 'package:otzaria/models/books.dart'; import 'package:otzaria/models/links.dart'; +import 'package:otzaria/personal_notes/models/pdf_note_anchor.dart'; import 'package:otzaria/search/models/search_configuration.dart'; import 'package:otzaria/tabs/bloc/tabs_bloc.dart'; import 'package:otzaria/tabs/bloc/tabs_event.dart'; @@ -447,6 +448,34 @@ void main() { }); for (final split in [false, true]) { + test('נקודת הערה ממתינה בקורא PDF קיים (split=$split)', () async { + final bloc = _newBloc(_FakeTabsRepository()); + final existing = PdfBookTab( + book: PdfBook(id: 42, title: 'מסמך PDF', path: 'points.pdf'), + pageNumber: 3, + ); + final OpenedTab top = split + ? CombinedTab( + rightTab: existing, + leftTab: _createTextTab('ספר נוסף', categoryId: 2), + ) + : existing; + bloc.add(AddTab(top)); + await bloc.stream.firstWhere((s) => s.tabs.length == 1); + const anchor = PdfNoteAnchor(pageNumber: 12, x: .2, y: .9); + final incoming = PdfBookTab( + book: PdfBook(id: 42, title: 'מסמך PDF', path: 'points.pdf'), + pageNumber: anchor.pageNumber, + )..requestPersonalNoteNavigation(anchor); + bloc.add(OpenOrFocusTab(incoming, navigateToPositionIfReused: true)); + await pumpEventQueue(); + + expect(bloc.state.tabs, hasLength(1)); + expect(existing.takePersonalNoteNavigationRequest(), anchor); + expect(existing.takePersonalNoteNavigationRequest(), isNull); + await _closeBlocAndAllowDeferredDispose(bloc); + }); + test( 'תוצאה גלובלית מעבירה בקשת מירכוז ל-PDF קיים (split=$split)', () async { diff --git a/test/text_book/utils/note_inline_render_test.dart b/test/text_book/utils/note_inline_render_test.dart index bbe38ec13a..7ba40d7f8d 100644 --- a/test/text_book/utils/note_inline_render_test.dart +++ b/test/text_book/utils/note_inline_render_test.dart @@ -13,6 +13,7 @@ import 'package:otzaria/widgets/smart_text/text_renderer_service.dart'; import 'package:otzaria/utils/text/text_manipulation.dart' show HolyNameStyle; PersonalNote _note({ + String id = 'n1', String? anchorText, String? anchorPrefix, String? anchorSuffix, @@ -21,7 +22,7 @@ PersonalNote _note({ }) { final now = DateTime(2026, 1, 1); return PersonalNote( - id: 'n1', + id: id, bookId: 'ספר', lineNumber: 1, displayTitle: anchorText, @@ -75,7 +76,7 @@ int _maxAnchorDepthOfWellFormed(String html) { void main() { const color = Color(0xFF1A2B3C); const noteOpen = - ''; const linkOpen = @@ -101,6 +102,23 @@ void main() { ); } + test('עוגן PDF אינו מסמן או מציג הערה בשורת טקסט בעלת אותו מספר', () { + final pdfNote = _note(id: 'pdf').copyWith( + pdfAnchor: const PdfNoteAnchor(pageNumber: 1, x: 0.25, y: 0.75), + ); + const raw = 'טקסט הבדיקה'; + expect(render(raw, notes: [pdfNote]), raw); + expect( + personalNotesForPreview('otzaria://note?line=0', [pdfNote]), + isEmpty, + ); + final textNote = _note(); + expect( + personalNotesForPreview('otzaria://note?line=0', [textNote, pdfNote]), + [textNote], + ); + }); + test('הערת מילים עוטפת רק את הביטוי בקישור otzaria://note', () { const raw = 'וַיֹּאמֶר יְהוָה אֶל מֹשֶׁה לֵּאמֹר'; final html = buildAnnotatedLineHtml( @@ -109,7 +127,7 @@ void main() { lineIndex0: 4, underlineColor: color, ); - expect(html.contains('href="otzaria://note?line=4"'), isTrue); + expect(html.contains('href="otzaria://note?line=4&id=n1"'), isTrue); expect(html.contains('#1a2b3c'), isTrue); // המילים שלפני הביטוי לא נמצאות בתוך תגית ה-. final aStart = html.indexOf(''), isTrue); }); @@ -195,6 +213,79 @@ void main() { expect(html, raw); }); + test( + 'עוגנים חופפים מציגים את ההערות של כל טווח בלבד, בלי קישורים מקוננים', + () { + final notes = [ + _note(id: 'first', anchorText: 'alpha beta'), + _note(id: 'second', anchorText: 'beta gamma'), + _note(id: 'whole'), + ]; + final html = buildAnnotatedLineHtml( + rawLine: 'alpha beta gamma', + notesForLine: notes, + lineIndex0: 0, + underlineColor: color, + ); + final links = RegExp( + r']*>([^<]+)', + ).allMatches(html).toList(); + expect(links.map((match) => match.group(2)), [ + 'alpha ', + 'beta', + ' gamma', + ]); + final expected = [ + ['first', 'whole'], + ['first', 'second', 'whole'], + ['second', 'whole'], + ]; + for (var i = 0; i < links.length; i++) { + expect( + personalNotesForPreview( + links[i].group(1)!, + notes, + ).map((note) => note.id), + expected[i], + ); + } + expect(_maxAnchorDepthOfWellFormed(html), 1); + }, + ); + + test('מזהה הערה מקודד עובר מהסימון לתצוגה בלי לכלול הערה אחרת', () { + final selected = _note(id: 'id &"<,?', anchorText: 'טווח'); + final notes = [selected, _note(id: 'other', anchorText: 'אחר')]; + final html = buildAnnotatedLineHtml( + rawLine: 'טווח אחר', + notesForLine: notes, + lineIndex0: 0, + underlineColor: color, + ); + final url = RegExp(r'href="([^"]+)"').firstMatch(html)!.group(1)!; + expect(personalNotesForPreview(url, notes), [selected]); + expect(_maxAnchorDepthOfWellFormed(html), 1); + }); + + test('קישורי שורה ישנים נתמכים ומזהה שגוי אינו מחזיר את כל הערות השורה', () { + final notes = [ + _note(id: 'first'), + _note(id: 'other').copyWith(lineNumber: 2), + ]; + expect(personalNotesForPreview('otzaria://note?line=0', notes), [ + notes.first, + ]); + expect( + personalNotesForPreview('otzaria://note?line=0&id=unknown', notes), + isEmpty, + ); + expect( + personalNotesForPreview('otzaria://note?line=1&id=first', notes), + isEmpty, + ); + expect(personalNotesForPreview('otzaria://note?line=bad', notes), isEmpty); + }); + test('הערת-שורה-שלמה לא בולעת קישור inline באותה שורה', () { const raw = 'אבגד הוזח טיכל'; // קישור inline על "הוזח" (אינדקסים 5..9). @@ -215,7 +306,7 @@ void main() { lineIndex0: 2, underlineColor: color, ); - expect(html.startsWith(''), isTrue); }); diff --git a/test/text_book/view/combined_view/combined_book_screen_test.dart b/test/text_book/view/combined_view/combined_book_screen_test.dart index c92e10a60e..67d355cf6d 100644 --- a/test/text_book/view/combined_view/combined_book_screen_test.dart +++ b/test/text_book/view/combined_view/combined_book_screen_test.dart @@ -14,6 +14,8 @@ import 'package:otzaria/plugins/view/plugin_correction_paragraph.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/bloc/personal_notes_state.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_content_view.dart'; import 'package:otzaria/settings/engine/settings_bloc.dart'; import 'package:otzaria/settings/engine/settings_event.dart'; import 'package:otzaria/settings/engine/settings_state.dart'; @@ -24,6 +26,7 @@ import 'package:otzaria/text_book/bloc/text_book_state.dart'; import 'package:otzaria/book_common/models/commentator_group.dart'; import 'package:otzaria/data/repository/text_book_repository.dart'; import 'package:otzaria/text_book/view/combined_view/combined_book_screen.dart'; +import 'package:otzaria/text_book/view/page_shape/simple_text_viewer.dart'; import 'package:otzaria/text_book/view/selection/enhanced_gesture_detector.dart'; import 'package:otzaria/text_book/view/selection/selection_sync_controller.dart'; import 'package:otzaria/text_book/view/widgets/continuous_reading_paragraph.dart'; @@ -638,21 +641,105 @@ void main() { }); }); - group('shouldShowPersonalNotePreview', () { - test('מציג תצוגה מקדימה כשטאב ההערות אינו פעיל', () { - expect( - shouldShowPersonalNotePreview(isPersonalNotesTabActive: false), - isTrue, - ); - }); - - test('לא מציג תצוגה מקדימה כשטאב ההערות פעיל', () { - expect( - shouldShowPersonalNotePreview(isPersonalNotesTabActive: true), - isFalse, + for (final pageShape in [false, true]) { + for (final notesTabActive in [false, true]) { + testWidgets( + 'ריחוף מציג רק הערות העוגן: צורת הדף=$pageShape, חלונית פתוחה=$notesTabActive', + (tester) async { + addTearDown(LinkPreviewOverlay.dismiss); + final loaded = _loadedState().copyWith( + content: const ['ראשונה שנייה'], + ); + final textBloc = _RecordingTextBookBloc(loaded); + final tab = TextBookTab( + book: loaded.book, + index: 0, + blocOverride: textBloc, + ); + addTearDown(tab.dispose); + PersonalNote note(String id, String anchor) => PersonalNote( + id: id, + bookId: loaded.book.title, + lineNumber: 1, + displayTitle: anchor, + anchorText: anchor, + lastKnownLineNumber: 1, + status: PersonalNoteStatus.located, + content: 'תוכן $id', + contentPlain: 'תוכן $id', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), + ); + final notes = [note('first', 'ראשונה'), note('second', 'שנייה')]; + final notesBloc = _TestPersonalNotesBloc( + const PersonalNotesState.initial().copyWith( + bookId: loaded.book.title, + locatedNotes: notes, + ), + ); + final settingsBloc = _TestSettingsBloc(SettingsState.initial()); + addTearDown(notesBloc.close); + addTearDown(settingsBloc.close); + await tester.pumpWidget( + MaterialApp( + home: MultiBlocProvider( + providers: [ + BlocProvider.value(value: textBloc), + BlocProvider.value(value: notesBloc), + BlocProvider.value(value: settingsBloc), + ], + child: Scaffold( + body: pageShape + ? SimpleTextViewer( + content: loaded.content, + fontSize: 18, + openBookCallback: (_) {}, + isMainText: true, + isPersonalNotesTabActive: notesTabActive, + ) + : CombinedView( + data: loaded.content, + tab: tab, + openBookCallback: (_) {}, + openLeftPaneTab: (_, {searchText}) {}, + textSize: 18, + showCommentaryAsExpansionTiles: false, + isPersonalNotesTabActive: () => notesTabActive, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final text = tester + .widgetList(find.byType(SmartTextWidget)) + .firstWhere((text) => text.text.contains('otzaria://note?')); + final urls = RegExp(r'href="([^"]+)"') + .allMatches(text.text) + .map((match) => match.group(1)!) + .where((url) => url.startsWith('otzaria://note?')) + .toList(); + expect(urls, hasLength(2)); + for (var i = 0; i < urls.length; i++) { + text.onAnchorHover!(urls[i], const Offset(100, 100)); + await tester.pump(const Duration(milliseconds: 279)); + expect(find.byType(PersonalNotesListView), findsNothing); + await tester.pump(const Duration(milliseconds: 2)); + await tester.pump(); + final preview = tester.widget( + find.byType(PersonalNotesListView), + ); + expect(preview.notes.map((note) => note.id), [notes[i].id]); + LinkPreviewOverlay.dismiss(); + await tester.pump(); + } + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, ); - }); - }); + } + } group('shouldShowOpenLinksPaneEntry', () { test('מחזירה true כשיש קישורים וטאב הקישורים אינו פעיל', () { diff --git a/test/text_book/view/combined_view/combined_view_note_entry_test.dart b/test/text_book/view/combined_view/combined_view_note_entry_test.dart index 14bcdaa115..01fb761d7d 100644 --- a/test/text_book/view/combined_view/combined_view_note_entry_test.dart +++ b/test/text_book/view/combined_view/combined_view_note_entry_test.dart @@ -458,6 +458,7 @@ Future<_Fixture> _pumpView( textSize: 18, showCommentaryAsExpansionTiles: true, onOpenPersonalNotes: () {}, + isPersonalNotesTabActive: () => true, onSelectedTextChanged: (text, line, column) { fixture.selectedText = text; fixture.selectedLine = line; diff --git a/test/text_book/view/page_shape/page_shape_screen_settings_test.dart b/test/text_book/view/page_shape/page_shape_screen_settings_test.dart index 90d4161d99..8a47f59b87 100644 --- a/test/text_book/view/page_shape/page_shape_screen_settings_test.dart +++ b/test/text_book/view/page_shape/page_shape_screen_settings_test.dart @@ -13,6 +13,7 @@ import 'package:otzaria/library/models/library.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/bloc/personal_notes_state.dart'; +import 'package:otzaria/personal_notes/widgets/commentary_notes_section.dart'; import 'package:otzaria/settings/engine/settings_bloc.dart'; import 'package:otzaria/settings/engine/settings_event.dart'; import 'package:otzaria/settings/engine/settings_state.dart'; @@ -23,6 +24,7 @@ import 'package:otzaria/book_common/models/commentator_group.dart'; import 'package:otzaria/text_book/view/page_shape/page_shape_screen.dart'; import 'package:otzaria/text_book/view/page_shape/page_shape_settings_panel.dart'; import 'package:otzaria/text_book/view/page_shape/utils/page_shape_settings_manager.dart'; +import 'package:otzaria/text_book/view/tabbed_commentary_panel.dart'; import 'package:otzaria/widgets/layout/context_overlay_panel.dart'; import 'package:otzaria/widgets/layout/floating_panel.dart'; import 'package:otzaria/widgets/misc/app_menu_exports.dart'; @@ -46,6 +48,7 @@ void main() { ValueNotifier openSettingsNotifier, { TextBookLoaded? loadedState, PageShapeDefaultsLoader? defaultsLoader, + ValueNotifier? sidebarTabNotifier, }) async { await tester.pumpWidget( MaterialApp( @@ -74,6 +77,7 @@ void main() { child: PageShapeScreen( openBookCallback: (_) {}, openSettingsNotifier: openSettingsNotifier, + sidebarTabNotifier: sidebarTabNotifier, defaultsLoader: defaultsLoader, ), ), @@ -83,6 +87,42 @@ void main() { await tester.pump(); } + testWidgets('לחיצה חוזרת על הערת מפרש מבקשת לחשוף אותה שוב', (tester) async { + final settingsRequest = ValueNotifier(0); + final sidebarRequest = ValueNotifier(null); + addTearDown(settingsRequest.dispose); + addTearDown(sidebarRequest.dispose); + await pumpScreen( + tester, + settingsRequest, + sidebarTabNotifier: sidebarRequest, + ); + sidebarRequest.value = kNotesTabIndex; + await tester.pumpAndSettle(); + final bloc = + tester.element(find.byType(PageShapeScreen)).read() + as _TestPersonalNotesBloc; + + void openNote() { + final panel = tester.widget( + find.byType(TabbedCommentaryPanel), + ); + (panel.notesFooter! as CommentaryNotesSection).onOpenNote( + 'מפרש בדיקה', + 7, + ); + } + + openNote(); + await tester.pumpAndSettle(); + bloc.events.clear(); + openNote(); + await tester.pumpAndSettle(); + + expect(bloc.events, contains(const LoadPersonalNotes('מפרש בדיקה'))); + expect(bloc.events, contains(const RequestExpandNotesForLine(7))); + }); + testWidgets( 'בקשת פתיחה דרך openSettingsNotifier פותחת את החלונית עם עדכון חי מחווט', (tester) async { @@ -749,9 +789,23 @@ class _TestPersonalNotesBloc extends Bloc implements PersonalNotesBloc { _TestPersonalNotesBloc(super.initialState) { - on((event, emit) {}); + on((event, emit) { + events.add(event); + if (event is LoadPersonalNotes) { + emit( + state.copyWith( + isLoading: true, + bookId: event.bookId, + categoryId: event.categoryId, + ), + ); + emit(state.copyWith(isLoading: false)); + } + }); } + final List events = []; + @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } diff --git a/test/text_book/view/page_shape/simple_text_viewer_test.dart b/test/text_book/view/page_shape/simple_text_viewer_test.dart index 640badad8b..814999e5a9 100644 --- a/test/text_book/view/page_shape/simple_text_viewer_test.dart +++ b/test/text_book/view/page_shape/simple_text_viewer_test.dart @@ -28,8 +28,8 @@ import 'package:otzaria/personal_notes/bloc/personal_notes_event.dart'; import 'package:otzaria/personal_notes/bloc/personal_notes_state.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_note_editor.dart'; import 'package:otzaria/personal_notes/widgets/personal_note_editor_dialog.dart'; +import 'package:otzaria/personal_notes/utils/create_personal_note.dart'; import 'package:otzaria/settings/engine/settings_bloc.dart'; import 'package:otzaria/settings/engine/settings_event.dart'; import 'package:otzaria/settings/engine/settings_state.dart'; @@ -550,7 +550,11 @@ void main() { testWidgets('סימון הערה inline מוזרק לטקסט ולחיצתו פותחת את טאב ההערות', ( tester, ) async { - final textBookBloc = _TestTextBookBloc(_loadedState()); + final textBookBloc = _TestTextBookBloc( + _loadedState().copyWith( + book: TextBook(title: 'ספר בדיקה', categoryId: 9), + ), + ); final personalNotesBloc = _TestPersonalNotesBloc( PersonalNotesState( isLoading: false, @@ -560,6 +564,8 @@ void main() { errorMessage: null, filteredLocatedNotes: [_note()], filteredMissingNotes: const [], + searchQuery: 'חיפוש קודם', + showOnlyVisible: true, ), ); final settingsBloc = _TestSettingsBloc(SettingsState.initial()); @@ -588,6 +594,12 @@ void main() { await tester.pumpAndSettle(); + expect( + personalNotesBloc.receivedEvents.whereType().single, + const LoadPersonalNotes('ספר בדיקה', categoryId: 9), + ); + personalNotesBloc.receivedEvents.clear(); + // הסימון מוזרק כקישור inline בטקסט הראשי (otzaria://note?line=0). final mainText = tester .widgetList(find.byType(SmartTextWidget)) @@ -599,6 +611,12 @@ void main() { await tester.pumpAndSettle(); expect(openedTab, kNotesTabIndex); + expect(personalNotesBloc.receivedEvents, [ + const ToggleShowOnlyVisible(), + const UpdateSearchQuery(''), + const LoadPersonalNotes('ספר בדיקה', categoryId: 9), + const RequestExpandNotesForLine(1), + ]); }); testWidgets('תיבת הערה מרחפת נסגרת כשקישור בה פותח טאב אחר (issue #2957)', ( @@ -1325,7 +1343,7 @@ void main() { }); testWidgets( - 'הוספת הערה ממפרש פותחת דיאלוג עצמאי ולא עוברת דרך הסיידבר של הספר הראשי', + 'הוספת הערה ממפרש כשחלונית ההערות סגורה פותחת דיאלוג עצמאי', (tester) async { // רגרסיה: בצורת הדף המפרש חולק את ה-TextBookBloc של הספר הראשי. הוספת הערה // ממפרש חייבת להישמר תחת ספר המפרש (דרך דיאלוג עצמאי), ולא לשלוח @@ -1501,43 +1519,97 @@ void main() { }, ); - test( - 'saveCommentaryNoteToRepository ממפה את תוצאת העורך לקריאת addNote', - () async { - final repo = _RecordingNotesRepository(); - - await saveCommentaryNoteToRepository( - repository: repo, - bookId: 'רש"י', - lineNumber: 2, - result: const PersonalNoteEditorResult( - content: 'דלתא', - contentPlain: 'תוכן ההערה', - contentFormat: PersonalNoteContentFormat.quillDelta, + for (final panelOpen in [false, true]) { + testWidgets('מפרש משתמש בפאנל הקרוב שפתוח=$panelOpen ומכוון לספר המפרש', ( + tester, + ) async { + final textBookBloc = _TestTextBookBloc(_loadedState()); + final notesBloc = _TestPersonalNotesBloc( + const PersonalNotesState.initial(), + ); + final settingsBloc = _TestSettingsBloc(SettingsState.initial()); + final targets = <(String, int?, int)>[]; + var outerCalls = 0; + addTearDown(textBookBloc.close); + addTearDown(notesBloc.close); + addTearDown(settingsBloc.close); + await tester.pumpWidget( + MaterialApp( + home: MultiBlocProvider( + providers: [ + BlocProvider.value(value: textBookBloc), + BlocProvider.value(value: notesBloc), + BlocProvider.value(value: settingsBloc), + ], + child: Scaffold( + body: _NotesPanelOwner( + isOpen: true, + onReveal: (_, _, _) => outerCalls++, + child: _NotesPanelOwner( + isOpen: panelOpen, + onReveal: (book, category, line) => + targets.add((book, category, line)), + child: SimpleTextViewer( + content: const ['שורת מפרש'], + fontSize: 18, + openBookCallback: (_) {}, + isMainText: false, + bookTitle: 'מפרש בדיקה', + reportBook: TextBook(title: 'מפרש בדיקה', categoryId: 42), + ), + ), + ), + ), + ), ), - selectedText: 'טקסט נבחר', - selectionColumn: 12, - punctuationHidden: true, - categoryId: 7, ); - - expect( - repo.addNoteCallCount, - 1, - reason: 'חייבת להתבצע קריאה אחת בדיוק ל-addNote', - ); - expect(repo.capturedBookId, 'רש"י', reason: 'ההערה נשמרת תחת ספר המפרש'); - expect(repo.capturedLineNumber, 2); - expect(repo.capturedContentPlain, 'תוכן ההערה'); - expect(repo.capturedCategoryId, 7); - expect( - repo.capturedSelectionColumn, - 12, - reason: 'רמז עמודת הבחירה מועבר לזיהוי המופע הנכון בטקסט חוזר', + await tester.pumpAndSettle(); + final region = tester.widget( + find.byType(AppContextMenuRegion).first, ); - expect(repo.capturedPunctuationHidden, isTrue); - }, - ); + final context = tester.element(find.byType(AppContextMenuRegion).first); + final entries = region.menuBuilder( + context, + tester.getCenter(find.byType(AppContextMenuRegion).first), + ); + entries + .singleWhere((entry) => entry.label?.trim() == 'הוסף הערה אישית') + .onTap!(); + await tester.pumpAndSettle(); + expect(outerCalls, 0); + if (panelOpen) { + expect(targets, [('מפרש בדיקה', 42, 1)]); + final request = notesBloc.receivedEvents + .whereType() + .single; + expect(request.bookId, 'מפרש בדיקה'); + expect(request.lineNumber, 1); + expect( + notesBloc.receivedEvents + .whereType() + .last + .categoryId, + 42, + ); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + } else { + expect(targets, isEmpty); + expect( + notesBloc.receivedEvents.whereType(), + isEmpty, + ); + final dialog = tester.widget( + find.byType(PersonalNoteEditorDialog), + ); + expect(dialog.bookId, 'מפרש בדיקה'); + expect(dialog.categoryId, 42); + expect(dialog.onSave, isNotNull); + await tester.tap(find.text('ביטול')); + await tester.pumpAndSettle(); + } + expect(tester.takeException(), isNull); + }); + } testWidgets('מפרש בצורת הדף מציג סימון הערה ופותח אותה בלחיצה', ( tester, @@ -3141,6 +3213,36 @@ void main() { }); } +class _NotesPanelOwner extends StatefulWidget { + const _NotesPanelOwner({ + required this.isOpen, + required this.onReveal, + required this.child, + }); + final bool isOpen; + final void Function(String, int?, int) onReveal; + final Widget child; + + @override + State<_NotesPanelOwner> createState() => _NotesPanelOwnerState(); +} + +class _NotesPanelOwnerState extends State<_NotesPanelOwner> + implements PersonalNotesPanelVisibility { + @override + bool get isPersonalNotesPanelOpen => widget.isOpen; + + @override + void revealPersonalNotesTarget( + String bookId, + int? categoryId, + int lineNumber, + ) => widget.onReveal(bookId, categoryId, lineNumber); + + @override + Widget build(BuildContext context) => widget.child; +} + Future<_SelectionEmittingTextBookBloc> _pumpMarkedViewer( WidgetTester tester, { String line = 'אמר רבי יוחנן הלכה', @@ -3354,41 +3456,6 @@ class _GatedContentProvider implements LibraryProvider { ) async => const {}; } -/// repository מדומה שמתעד את הקריאה ל-addNote בלי לגעת במערכת הקבצים. -class _RecordingNotesRepository extends PersonalNotesRepository { - String? capturedBookId; - int? capturedLineNumber; - String? capturedContentPlain; - int? capturedCategoryId; - int? capturedSelectionColumn; - bool? capturedPunctuationHidden; - int addNoteCallCount = 0; - - @override - Future> addNote({ - 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, - int? categoryId, - }) async { - addNoteCallCount++; - capturedBookId = bookId; - capturedLineNumber = lineNumber; - capturedContentPlain = contentPlain; - capturedCategoryId = categoryId; - capturedSelectionColumn = selectionColumn; - capturedPunctuationHidden = punctuationHidden; - return const []; - } -} - class _CommentaryNotesRepository extends PersonalNotesRepository { _CommentaryNotesRepository(this.notes); diff --git a/test/text_book/view/reader_line/continuous_line_interaction_test.dart b/test/text_book/view/reader_line/continuous_line_interaction_test.dart index ac1c6bf3bf..13eed49ac2 100644 --- a/test/text_book/view/reader_line/continuous_line_interaction_test.dart +++ b/test/text_book/view/reader_line/continuous_line_interaction_test.dart @@ -17,6 +17,7 @@ import 'package:otzaria/personal_notes/bloc/personal_notes_bloc.dart'; import 'package:otzaria/plugins/services/reader_section_sync_gate.dart'; import 'package:otzaria/personal_notes/bloc/personal_notes_event.dart'; import 'package:otzaria/personal_notes/bloc/personal_notes_state.dart'; +import 'package:otzaria/personal_notes/widgets/personal_note_editor_dialog.dart'; import 'package:otzaria/settings/engine/settings_bloc.dart'; import 'package:otzaria/settings/engine/settings_event.dart'; import 'package:otzaria/settings/engine/settings_state.dart'; @@ -72,6 +73,28 @@ void main() { for (final simple in [false, true]) { final screen = simple ? 'צורת הדף' : 'עיון'; + testWidgets('$screen: יצירת הערה כשחלונית ההערות סגורה פותחת דיאלוג', ( + tester, + ) async { + final h = await _pump(tester, simple: simple); + await _openMenuAt(tester, _textRect(tester, 'מילה', occurrence: 1)); + await tester.tap(find.text('הערה')); + await _pumpUntil( + tester, + () => find.byType(PersonalNoteEditorDialog).evaluate().isNotEmpty, + ); + final dialog = tester.widget( + find.byType(PersonalNoteEditorDialog), + ); + expect(dialog.bookId, 'ספר בדיקה'); + expect(dialog.draftLineNumber, 3); + expect(h.notes.received.whereType(), isEmpty); + expect(h.notesPanelOpenCalls, 0); + await tester.tap(find.text('ביטול')); + await tester.pumpAndSettle(); + expect(find.byType(PersonalNoteEditorDialog), findsNothing); + }); + testWidgets('$screen: לחיצה בתוך פסקה בוחרת את השורה שנלחצה', ( tester, ) async { @@ -417,7 +440,7 @@ void main() { }); testWidgets('עיון: הערה מהתפריט נוצרת לשורה שנלחצה', (tester) async { - final h = await _pump(tester, simple: false); + final h = await _pump(tester, simple: false, notesPanelOpen: true); await _openMenuAt(tester, _textRect(tester, 'מילה', occurrence: 1)); await tester.tap(find.text('הערה')); await _pumpUntil( @@ -566,6 +589,7 @@ class _Harness { final _TextBookBloc bloc; final _PersonalNotesBloc notes; final _BookmarkBloc bookmarks; + int notesPanelOpenCalls = 0; String? selectedText; int? selectedLine; } @@ -579,6 +603,7 @@ Future<_Harness> _pump( List toc = const [], SettingsState? settings, bool commentaryCards = false, + bool notesPanelOpen = false, TextBookLoaded Function(TextBookLoaded state)? adjust, }) async { book ??= TextBook(title: 'ספר בדיקה'); @@ -637,6 +662,8 @@ Future<_Harness> _pump( content: data, fontSize: 18, isMainText: true, + isPersonalNotesTabActive: notesPanelOpen, + onOpenSidebarTab: (_) => h.notesPanelOpenCalls++, openBookCallback: (_) {}, ) : CombinedView( @@ -645,7 +672,8 @@ Future<_Harness> _pump( openLeftPaneTab: (_, {searchText}) {}, textSize: 18, showCommentaryAsExpansionTiles: commentaryCards, - onOpenPersonalNotes: () {}, + onOpenPersonalNotes: () => h.notesPanelOpenCalls++, + isPersonalNotesTabActive: () => notesPanelOpen, onSelectedTextChanged: (text, line, _) { h.selectedText = text; h.selectedLine = line; diff --git a/test/text_book/view/splited_view_toggle_commentators_pane_test.dart b/test/text_book/view/splited_view_toggle_commentators_pane_test.dart index d3eec9c7da..7745dd7c06 100644 --- a/test/text_book/view/splited_view_toggle_commentators_pane_test.dart +++ b/test/text_book/view/splited_view_toggle_commentators_pane_test.dart @@ -3,6 +3,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:otzaria/settings/engine/app_settings_store.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/models/books.dart'; +import 'package:otzaria/models/book_source.dart'; import 'package:otzaria/models/links.dart'; import 'package:otzaria/personal_notes/bloc/personal_notes_bloc.dart'; import 'package:otzaria/personal_notes/bloc/personal_notes_event.dart'; @@ -28,11 +29,8 @@ import 'package:otzaria/widgets/navigation/panel_tab_header.dart'; import '../../test_helpers/memory_cache_provider.dart'; -/// טסט רגרסיה לטוגל חלונית המפרשים מקיצור המקלדת (issue #1161). -/// -/// בעבר נחסם הקיצור במצב "מפרשים מתחת" (`showSplitView: false`) תחת ההנחה -/// השגויה שהחלונית אינה רלוונטית במצב זה. בפועל, החלונית מציגה את לשונית -/// "סינון מפרשים" (בחירת מפרשים), והקיצור מאפשר לפתוח ולסגור אותה בנוחות. +/// טוגל חלונית המפרשים חייב לעבוד גם במצב "מפרשים מתחת", +/// שבו אותה חלונית משמשת לסינון ולבחירת מפרשים. void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -113,6 +111,42 @@ void main() { return tab; } + testWidgets('לחיצה חוזרת על הערת מפרש משמרת מקור ומבקשת חשיפה', ( + tester, + ) async { + final tab = await pumpSplitedView(tester, showSplitView: true); + tab.toggleCommentatorsPaneNotifier.value++; + await tester.pumpAndSettle(); + final bloc = + tester.element(find.byType(SplitedViewScreen)).read() + as _TestPersonalNotesBloc; + final link = Link( + heRef: 'מפרש בדיקה א', + index1: 1, + path2: 'מפרש בדיקה', + index2: 7, + connectionType: 'commentary', + targetSource: BookSource.user, + targetCategoryId: 9, + ); + + void openNote() => tester + .widget(find.byType(TabbedCommentaryPanel)) + .onOpenPersonalNote!(link, 7); + + openNote(); + await tester.pumpAndSettle(); + bloc.events.clear(); + openNote(); + await tester.pumpAndSettle(); + + expect( + bloc.events, + contains(const LoadPersonalNotes('מפרש בדיקה|user', categoryId: 9)), + ); + expect(bloc.events, contains(const RequestExpandNotesForLine(7))); + }); + group('קיצור מפרשים (toggleCommentatorsPaneNotifier) במצב "מפרשים מתחת"', () { testWidgets( 'פתיחה: יריית ה-notifier פותחת את החלונית בלשונית סינון/בחירת מפרשים', @@ -224,9 +258,11 @@ class _TestPersonalNotesBloc extends Bloc implements PersonalNotesBloc { _TestPersonalNotesBloc(super.initialState) { - on((event, emit) {}); + on((event, emit) => events.add(event)); } + final List events = []; + @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp index 3a7c326334..d4040cd53f 100644 --- a/windows/runner/flutter_window.cpp +++ b/windows/runner/flutter_window.cpp @@ -346,6 +346,13 @@ bool InstallDartViewHooks(HWND root) { constexpr UINT_PTR kFramelessSubclassId = 0x0F1F; +// Flutter מעביר WM_SYSCHAR ל-DefWindowProc גם כשהקיצור טופל ב-Dart. +// צורכים את בקשת התפריט של Alt+Enter כדי למנוע צפצוף, בלי לחסום את המקש. +bool IsAltEnterMenuCommand(UINT message, WPARAM command, LPARAM character) { + return message == WM_SYSCOMMAND && (command & 0xFFF0) == SC_KEYMENU && + character == L'\r'; +} + // כמו `IsWindows11OrGreater` של window_manager: ב-10 נשאר פס עליון של פיקסל. bool IsWindows11OrGreaterForFrame() { #pragma warning(push) @@ -377,6 +384,7 @@ void AdjustMaximizedClientRect(NCCALCSIZE_PARAMS* sz) { // בלי WS_THICKFRAME (מסך מלא של ה-engine) הכול עובר כרגיל. LRESULT CALLBACK FramelessViewProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam, UINT_PTR, DWORD_PTR) { + if (IsAltEnterMenuCommand(message, wparam, lparam)) return 0; const bool framed = (::GetWindowLongPtr(hwnd, GWL_STYLE) & WS_THICKFRAME) != 0; switch (message) { @@ -980,6 +988,7 @@ LRESULT FlutterWindow::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { + if (IsAltEnterMenuCommand(message, wparam, lparam)) return 0; // נשלחת רק לחלון הראשי: ל-Dart שלו יש את ה-Navigator להצעת הדיווח. if (message == hang_monitor::kMsgAppHangRecovered) { if (process_control_channel_) { From b5384d32d05266d073c9fa52a9214d74d3cecb25 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Thu, 5 Nov 2026 22:40:28 +0200 Subject: [PATCH 4/5] test(notes): exercise PDF hand mode through the viewer --- test/pdf_book/pdf_hand_mode_test.dart | 13 +--- .../pdf_personal_note_viewer_test.dart | 64 ++++++++++++++++++- 2 files changed, 64 insertions(+), 13 deletions(-) diff --git a/test/pdf_book/pdf_hand_mode_test.dart b/test/pdf_book/pdf_hand_mode_test.dart index 31fbef4a10..d282812217 100644 --- a/test/pdf_book/pdf_hand_mode_test.dart +++ b/test/pdf_book/pdf_hand_mode_test.dart @@ -1,4 +1,5 @@ // בדיקות למצב יד בצפיין ה-PDF (issue #916): גרירת עכבר גוללת במקום לסמן. +// החיווט ל-PdfViewer נבדק בזמן ריצה ב-pdf_personal_note_viewer_test.dart. import 'dart:io'; @@ -36,18 +37,6 @@ void main() { source = await sourceFile.readAsString(); }); - test('textSelectionParams כפוף למצב היד', () { - expect( - source.contains( - 'textSelectionParams: PdfTextSelectionParams(enabled: !_isHandMode)', - ), - isTrue, - reason: - 'סימון הטקסט חייב להיות מנוטרל כשמצב היד פעיל — ' - 'זה מה שמפנה את גרירת העכבר לגלילה של pdfrx.', - ); - }); - test('הבחירה נזכרת ברמת התוכנה ולא מתאפסת בפתיחת ספר', () { expect( source.contains( diff --git a/test/pdf_book/pdf_personal_note_viewer_test.dart b/test/pdf_book/pdf_personal_note_viewer_test.dart index 9d8d4e5f0d..0d779ea655 100644 --- a/test/pdf_book/pdf_personal_note_viewer_test.dart +++ b/test/pdf_book/pdf_personal_note_viewer_test.dart @@ -8,6 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; // ignore: depend_on_referenced_packages import 'package:material_ui/material_ui.dart' as mui; import 'package:otzaria/core/app_paths.dart'; +import 'package:otzaria/core/messages/notes_messages.dart'; import 'package:otzaria/models/book_source.dart'; import 'package:otzaria/models/books.dart'; import 'package:otzaria/pdf_book/bloc/pdf_book_bloc.dart'; @@ -118,7 +119,7 @@ void main() { expect(condition(), isTrue); } - testWidgets('PDF אמיתי: ניווט, זהות, זום ובחירת נקודה בפאנל צר', ( + testWidgets('PDF אמיתי: ניווט, זהות, זום, מצב יד ובחירת נקודה בפאנל צר', ( tester, ) async { await tester.binding.setSurfaceSize(const Size(1200, 800)); @@ -269,6 +270,51 @@ void main() { expect(controller.currentZoom, greaterThan(oldZoom)); expectMarkerAtAnchor(); + // בודקים את הפרמטרים שמקבל הצפיין בפועל אחרי פעולות במסך. + // כך שינוי ניסוח או פורמט בקוד המקור אינו משנה את הכיסוי של מצב היד. + void expectTextSelectionEnabled(bool enabled, {required String reason}) { + final viewer = tester.widget(find.byType(PdfViewer)); + expect( + viewer.params.textSelectionParams?.enabled, + enabled, + reason: reason, + ); + } + + expectTextSelectionEnabled( + true, + reason: 'סימון טקסט זמין כשמצב היד ובחירת נקודה כבויים', + ); + await tester.tap(find.byTooltip('מצב יד — גלילה בגרירת העכבר')); + await settle(tester, 5); + expectTextSelectionEnabled( + false, + reason: 'הפעלת מצב היד מפנה את גרירת העכבר לגלילה', + ); + final sidebar = tester.widget( + find.byType(PersonalNotesSidebar), + ); + await sidebar.onReanchorNote!(note('current', anchor)); + await settle(tester, 15); + expect(find.text(NotesMessages.choosePdfNotePoint), findsOneWidget); + expectTextSelectionEnabled( + false, + reason: 'בחירת נקודת הערה אינה מפעילה סימון טקסט במצב יד', + ); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await settle(tester, 15); + expect(find.text(NotesMessages.choosePdfNotePoint), findsNothing); + expectTextSelectionEnabled( + false, + reason: 'ביטול בחירת נקודה משאיר את מצב היד פעיל', + ); + await tester.tap(find.byTooltip('מצב יד פעיל — לחץ לחזרה לסימון טקסט')); + await settle(tester, 5); + expectTextSelectionEnabled( + true, + reason: 'כיבוי מצב היד מחזיר את סימון הטקסט', + ); + await tester.binding.setSurfaceSize(const Size(420, 800)); await settle(tester, 20); AdaptiveSidePane notesPane() => tester.widget( @@ -287,12 +333,20 @@ void main() { // ההסתרה זמנית לתצוגה: ההחלטה על עורך inline נשארת לפי המצב הלוגי. expect((pdfBloc.state as PdfBookLoaded).showRightPane, isTrue); expect(notesPane().isOpen, isFalse); + expectTextSelectionEnabled( + false, + reason: 'בחירת נקודת הערה מנטרלת סימון טקסט גם כשמצב היד כבוי', + ); } await beginReanchor(); await tester.sendKeyEvent(LogicalKeyboardKey.escape); await settle(tester, 15); expect(notesPane().isOpen, isTrue); + expectTextSelectionEnabled( + true, + reason: 'ביטול בחירת נקודה מחזיר סימון טקסט כשמצב היד כבוי', + ); await beginReanchor(); final newAnchor = PdfNoteAnchor( pageNumber: 2, @@ -321,6 +375,10 @@ void main() { expect(moved.pdfAnchor!.x, closeTo(.45, .00001)); expect(moved.pdfAnchor!.y, closeTo(.6, .00001)); expect(notesPane().isOpen, isTrue); + expectTextSelectionEnabled( + true, + reason: 'שמירת נקודת ההערה מחזירה סימון טקסט כשמצב היד כבוי', + ); await beginReanchor(); tester.widget(find.byType(PdfViewer)).params.onDocumentChanged!( null, @@ -331,6 +389,10 @@ void main() { isTrue, reason: 'החלפת מסמך מבטלת בחירת נקודה ומחזירה את הפאנל', ); + expectTextSelectionEnabled( + true, + reason: 'החלפת מסמך מבטלת את חסימת סימון הטקסט של בחירת נקודה', + ); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox.shrink()); await settle(tester, 10); From 4ca3b3fae256ecfb7bd543c2a7aa51023e7efa62 Mon Sep 17 00:00:00 2001 From: ypl <7353755@gmail.com> Date: Fri, 6 Nov 2026 07:10:12 +0200 Subject: [PATCH 5/5] =?UTF-8?q?=D7=AA=D7=A7=D7=9F=20=D7=A4=D7=A2=D7=95?= =?UTF-8?q?=D7=9C=D7=95=D7=AA=20=D7=9E=D7=A0=D7=94=D7=9C=20=D7=94=D7=94?= =?UTF-8?q?=D7=A2=D7=A8=D7=95=D7=AA=20=D7=95=D7=96=D7=94=D7=95=D7=AA=20PDF?= =?UTF-8?q?=20=D7=A0=D7=99=D7=99=D7=93=D7=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/core/messages/notes_messages.dart | 1 + lib/pdf_book/view/pdf_book_screen.dart | 13 +- lib/pdf_book/view/pdf_commentary_panel.dart | 1 + .../services/personal_note_draft_service.dart | 4 +- .../utils/personal_note_source_link.dart | 3 +- .../utils/personal_notes_book_key.dart | 65 ++- .../utils/personal_notes_filter.dart | 4 +- .../view/personal_notes_screen.dart | 29 +- .../widgets/notes_search_header.dart | 4 + .../widgets/personal_notes_sidebar.dart | 13 +- .../pdf_note_document_identity_test.dart | 378 ++++++++++++++++++ .../personal_note_draft_service_test.dart | 201 ++++++++++ .../personal_notes_manager_loading_test.dart | 103 ++++- ...ersonal_notes_word_export_screen_test.dart | 5 +- .../printing_screen_export_profile_test.dart | 3 +- test/test_helpers/capture_file_saves.dart | 26 ++ 16 files changed, 815 insertions(+), 38 deletions(-) create mode 100644 test/personal_notes/pdf_note_document_identity_test.dart create mode 100644 test/test_helpers/capture_file_saves.dart diff --git a/lib/core/messages/notes_messages.dart b/lib/core/messages/notes_messages.dart index 86e072a760..4ed219546a 100644 --- a/lib/core/messages/notes_messages.dart +++ b/lib/core/messages/notes_messages.dart @@ -13,6 +13,7 @@ abstract class NotesMessages { static const String noteMovedToDifferentBook = 'ההערה הועברה לספר אחר. יש לפתוח אותה מחדש לפני שמירה'; static const String noteDeleted = 'ההערה נמחקה'; + static String noteDeleteFailed(Object error) => 'מחיקת ההערה נכשלה: $error'; static const String noteHasNoLocation = 'להערה הזו אין מיקום'; static const String choosePdfNotePoint = 'לחץ על הנקודה הרצויה בעמוד להערה'; static const String pdfNotePointUnavailable = diff --git a/lib/pdf_book/view/pdf_book_screen.dart b/lib/pdf_book/view/pdf_book_screen.dart index e72458823e..dafacb9996 100644 --- a/lib/pdf_book/view/pdf_book_screen.dart +++ b/lib/pdf_book/view/pdf_book_screen.dart @@ -668,6 +668,7 @@ class _PdfBookScreenState extends State PersonalNotesRepository(); StreamSubscription? _personalNotesSubscription; List _pdfPointNotes = const []; + late final _pdfNoteDocumentIds = pdfPersonalNoteDocumentIds(widget.tab.book); int _pdfNotesLoadGeneration = 0; int _pdfNoteNavigationGeneration = 0; int _pdfDocumentSession = 0; @@ -6091,11 +6092,13 @@ class _PdfBookScreenState extends State } bool _personalNoteMatchesDocument(PdfNoteAnchor anchor) => - pdfPersonalNoteAnchorMatchesBook( - anchor, - widget.tab.book, - library: context.read()?.state.library, - ); + anchor.documentId != null + ? _pdfNoteDocumentIds.contains(anchor.documentId) + : pdfPersonalNoteAnchorMatchesBook( + anchor, + widget.tab.book, + library: context.read()?.state.library, + ); Future _handleAddNotePress( BuildContext context, { diff --git a/lib/pdf_book/view/pdf_commentary_panel.dart b/lib/pdf_book/view/pdf_commentary_panel.dart index bbf40a62a5..f1e961e7eb 100644 --- a/lib/pdf_book/view/pdf_commentary_panel.dart +++ b/lib/pdf_book/view/pdf_commentary_panel.dart @@ -2009,6 +2009,7 @@ class PdfCommentaryPanelState extends State categoryId: widget.tab.book.categoryId, isPdf: true, pdfDocumentId: documentId, + pdfDocumentIds: pdfPersonalNoteDocumentIds(widget.tab.book), includeUnidentifiedPdfAnchors: uniquePdf != null && pdfPersonalNoteDocumentId(uniquePdf) == documentId, diff --git a/lib/personal_notes/services/personal_note_draft_service.dart b/lib/personal_notes/services/personal_note_draft_service.dart index 9d260c262e..e0499f4649 100644 --- a/lib/personal_notes/services/personal_note_draft_service.dart +++ b/lib/personal_notes/services/personal_note_draft_service.dart @@ -214,6 +214,7 @@ class PersonalNoteDraftService { int? categoryId, bool includePdfAnchors = true, String? pdfDocumentId, + Set pdfDocumentIds = const {}, bool includeUnidentifiedPdfAnchors = true, }) async { final prefix = _bookPrefix(bookId, categoryId: categoryId); @@ -237,7 +238,8 @@ class PersonalNoteDraftService { if (!includePdfAnchors) continue; if (anchor.documentId == null) { if (!includeUnidentifiedPdfAnchors) continue; - } else if (anchor.documentId != pdfDocumentId) { + } else if (anchor.documentId != pdfDocumentId && + !pdfDocumentIds.contains(anchor.documentId)) { continue; } } diff --git a/lib/personal_notes/utils/personal_note_source_link.dart b/lib/personal_notes/utils/personal_note_source_link.dart index c3ec3b07ce..396202122e 100644 --- a/lib/personal_notes/utils/personal_note_source_link.dart +++ b/lib/personal_notes/utils/personal_note_source_link.dart @@ -44,7 +44,8 @@ String? personalNoteSourceLink( return null; } final documentId = note.pdfAnchor?.documentId; - if (documentId != null && documentId != targetDocument) { + if (documentId != null && + !pdfPersonalNoteDocumentIds(book).contains(documentId)) { return null; } return buildPdfPageLink( diff --git a/lib/personal_notes/utils/personal_notes_book_key.dart b/lib/personal_notes/utils/personal_notes_book_key.dart index d5ba6e3770..b2bf0a6369 100644 --- a/lib/personal_notes/utils/personal_notes_book_key.dart +++ b/lib/personal_notes/utils/personal_notes_book_key.dart @@ -1,3 +1,7 @@ +import 'package:otzaria/core/app_paths.dart'; +import 'package:path/path.dart' as p; +import 'package:otzaria/settings/engine/app_settings_store.dart'; +import 'package:otzaria/settings/engine/settings_repository.dart'; import 'package:otzaria/library/models/library.dart'; import 'package:otzaria/models/book_source.dart'; import 'package:otzaria/models/books.dart'; @@ -99,13 +103,57 @@ TextBook? findTextBookForPersonalNotesKey(Library library, String key) { return document?.toTextBook(); } -/// מזהה מסמך בתוך מקורו. קובץ שאינו רשומת קטלוג מזוהה לפי נתיבו, כדי ששתי -/// מהדורות באותו שם בתיקיות שונות לא יקבלו זו את הערות הנקודה של זו. +/// מזהה PDF נייד: מזהה קטלוג יציב, או נתיב יחסית לשורש הספרייה/הנתונים. +/// קובץ מחוץ לספרייה נשאר מזוהה לפי נתיבו המוחלט. String pdfPersonalNoteDocumentId(PdfBook book) { - return '${book.source.wireKey}|' - '${Uri.encodeComponent(BookIdentity.indexedFilePath(book))}'; + if ((book.externalLibraryId ?? '').isNotEmpty || + (book.source.isAttached && book.id != null)) { + return _legacyPdfDocumentId(book); + } + final libraryRoot = Settings.isInitialized + ? Settings.getValue(SettingsRepository.keyLibraryPath) + : null; + ({String scope, String path, int depth})? nearest; + for (final (scope, root) in [ + ('library', libraryRoot), + ('data', AppPaths.cachedDataRootPath), + ]) { + if (root == null || root.isEmpty) continue; + final paths = p.Context( + style: p.windows.isAbsolute(root) && !p.windows.isRootRelative(root) + ? p.Style.windows + : p.Style.posix, + ); + if (!paths.isAbsolute(root) || + !paths.isAbsolute(book.path) || + !paths.isWithin(root, book.path)) { + continue; + } + final segments = paths.split(paths.relative(book.path, from: root)); + // השורש הקרוב הוא בעל הקובץ, גם כששורש הספרייה ושורש הנתונים מקוננים. + if (nearest == null || segments.length < nearest.depth) { + nearest = ( + scope: scope, + path: segments.join('/'), + depth: segments.length, + ); + } + } + if (nearest != null) { + return '${book.source.wireKey}|v2:${nearest.scope}:${Uri.encodeComponent(nearest.path)}'; + } + return _legacyPdfDocumentId(book); } +String _legacyPdfDocumentId(PdfBook book) => + '${book.source.wireKey}|${Uri.encodeComponent(BookIdentity.indexedFilePath(book))}'; + +/// זהויות קודמות מתקבלות רק בנתיב הנוכחי, בלי לנחש מהדורה לפי שם קובץ. +Set pdfPersonalNoteDocumentIds(PdfBook book) => { + pdfPersonalNoteDocumentId(book), + _legacyPdfDocumentId(book), +}; + /// מהדורת ה-PDF מאותו מקור. בלי מזהה מסמך מותר להסיק רק התאמה יחידה. PdfBook? findPdfBookForPersonalNotesKey( Library library, @@ -120,7 +168,8 @@ PdfBook? findPdfBookForPersonalNotesKey( parsed.source, ).whereType()) { final identity = pdfPersonalNoteDocumentId(book); - if (documentId == null || documentId == identity) { + if (documentId == null || + (documentId == identity || documentId == _legacyPdfDocumentId(book))) { byIdentity.putIfAbsent(identity, () => book); } } @@ -132,9 +181,11 @@ bool pdfPersonalNoteAnchorMatchesBook( PdfBook book, { Library? library, }) { - final identity = pdfPersonalNoteDocumentId(book); - if (anchor.documentId != null) return anchor.documentId == identity; + if (anchor.documentId != null) { + return pdfPersonalNoteDocumentIds(book).contains(anchor.documentId); + } if (library == null) return false; + final identity = pdfPersonalNoteDocumentId(book); final unique = findPdfBookForPersonalNotesKey( library, personalNotesBookKey(book), diff --git a/lib/personal_notes/utils/personal_notes_filter.dart b/lib/personal_notes/utils/personal_notes_filter.dart index 54843eb766..54ea01d58b 100644 --- a/lib/personal_notes/utils/personal_notes_filter.dart +++ b/lib/personal_notes/utils/personal_notes_filter.dart @@ -19,6 +19,7 @@ PersonalNotesFilterResult filterPersonalNotes({ bool isPdf = false, List? visiblePdfPages, String? pdfDocumentId, + Set pdfDocumentIds = const {}, bool includeUnidentifiedPdfAnchors = false, }) { bool included(PersonalNote note) { @@ -26,7 +27,8 @@ PersonalNotesFilterResult filterPersonalNotes({ if (anchor == null) return true; if (!isPdf) return false; if (anchor.documentId == null) return includeUnidentifiedPdfAnchors; - return anchor.documentId == pdfDocumentId; + return anchor.documentId == pdfDocumentId || + pdfDocumentIds.contains(anchor.documentId); } var filteredLocated = locatedNotes.where(included).toList(); diff --git a/lib/personal_notes/view/personal_notes_screen.dart b/lib/personal_notes/view/personal_notes_screen.dart index 4d21e58097..54eddb72b1 100644 --- a/lib/personal_notes/view/personal_notes_screen.dart +++ b/lib/personal_notes/view/personal_notes_screen.dart @@ -13,8 +13,6 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:otzaria/widgets/text/otzaria_search_field.dart'; import 'package:otzaria/core/ui_snack.dart'; import 'package:otzaria/core/messages/notes_messages.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/bloc/personal_notes_state.dart'; import 'package:otzaria/personal_notes/models/personal_note.dart'; import 'package:otzaria/personal_notes/models/personal_notes_sort_order.dart'; @@ -1518,13 +1516,12 @@ class _PersonalNotesManagerScreenState if (shouldDelete == true) { if (!mounted) return; - context.read().add( - DeletePersonalNote( - bookId: note.bookId, - noteId: note.id, - ), - ); - UiSnack.show(NotesMessages.noteDeleted); + try { + await _repository.deleteNote(bookId: note.bookId, noteId: note.id); + if (mounted) UiSnack.show(NotesMessages.noteDeleted); + } catch (error) { + if (mounted) UiSnack.showError(NotesMessages.noteDeleteFailed(error)); + } } } @@ -1548,14 +1545,18 @@ class _PersonalNotesManagerScreenState if (newLine != null) { if (!mounted) return; - context.read().add( - RepositionPersonalNote( + try { + await _repository.repositionNote( bookId: note.bookId, noteId: note.id, lineNumber: newLine, - ), - ); - UiSnack.show(NotesMessages.noteMovedToLine(newLine)); + ); + if (mounted) UiSnack.show(NotesMessages.noteMovedToLine(newLine)); + } catch (error) { + if (mounted) { + UiSnack.showError(NotesMessages.noteRepositionFailed(error)); + } + } } } diff --git a/lib/personal_notes/widgets/notes_search_header.dart b/lib/personal_notes/widgets/notes_search_header.dart index 408b951be5..cf68ee468d 100644 --- a/lib/personal_notes/widgets/notes_search_header.dart +++ b/lib/personal_notes/widgets/notes_search_header.dart @@ -17,6 +17,7 @@ class NotesSearchHeader extends StatefulWidget { final List visibleLineIndices; final List? visiblePdfPages; final String? pdfDocumentId; + final Set pdfDocumentIds; final bool includeUnidentifiedPdfAnchors; const NotesSearchHeader({ @@ -27,6 +28,7 @@ class NotesSearchHeader extends StatefulWidget { required this.visibleLineIndices, this.visiblePdfPages, this.pdfDocumentId, + this.pdfDocumentIds = const {}, this.includeUnidentifiedPdfAnchors = false, }); @@ -66,6 +68,7 @@ class _NotesSearchHeaderState extends State { visibleLineIndices: const [], isPdf: widget.isPdf, pdfDocumentId: widget.pdfDocumentId, + pdfDocumentIds: widget.pdfDocumentIds, includeUnidentifiedPdfAnchors: widget.includeUnidentifiedPdfAnchors, ); final totalNotes = @@ -79,6 +82,7 @@ class _NotesSearchHeaderState extends State { isPdf: widget.isPdf, visiblePdfPages: widget.visiblePdfPages, pdfDocumentId: widget.pdfDocumentId, + pdfDocumentIds: widget.pdfDocumentIds, includeUnidentifiedPdfAnchors: widget.includeUnidentifiedPdfAnchors, ); final visibleNotes = diff --git a/lib/personal_notes/widgets/personal_notes_sidebar.dart b/lib/personal_notes/widgets/personal_notes_sidebar.dart index 7b77b4f050..fd46f42272 100644 --- a/lib/personal_notes/widgets/personal_notes_sidebar.dart +++ b/lib/personal_notes/widgets/personal_notes_sidebar.dart @@ -46,6 +46,7 @@ class PersonalNotesSidebar extends StatefulWidget { final List? visibleLineIndices; final List? visiblePdfPages; final String? pdfDocumentId; + final Set pdfDocumentIds; final bool includeUnidentifiedPdfAnchors; final int? focusLineNumber; final Future Function(PersonalNote)? onReanchorNote; @@ -67,6 +68,7 @@ class PersonalNotesSidebar extends StatefulWidget { this.visibleLineIndices, this.visiblePdfPages, this.pdfDocumentId, + this.pdfDocumentIds = const {}, this.includeUnidentifiedPdfAnchors = false, this.focusLineNumber, this.onReanchorNote, @@ -159,7 +161,8 @@ class PersonalNotesSidebarState extends State if (oldWidget.bookId != widget.bookId || oldWidget.categoryId != widget.categoryId || oldWidget.isPdf != widget.isPdf || - oldWidget.pdfDocumentId != widget.pdfDocumentId) { + oldWidget.pdfDocumentId != widget.pdfDocumentId || + !setEquals(oldWidget.pdfDocumentIds, widget.pdfDocumentIds)) { context.read().add(const CancelCreatingPersonalNote()); _loadTarget(); _restorePendingNewNoteDraftIfNeeded(); @@ -204,6 +207,7 @@ class PersonalNotesSidebarState extends State final bookId = widget.bookId; final categoryId = widget.categoryId; final pdfDocumentId = widget.pdfDocumentId; + final pdfDocumentIds = widget.pdfDocumentIds; final includeUnidentifiedPdfAnchors = widget.includeUnidentifiedPdfAnchors; final isPdf = widget.isPdf; final draft = await _draftService.loadLatestNewNoteDraft( @@ -211,12 +215,14 @@ class PersonalNotesSidebarState extends State categoryId: categoryId, includePdfAnchors: isPdf, pdfDocumentId: pdfDocumentId, + pdfDocumentIds: pdfDocumentIds, includeUnidentifiedPdfAnchors: includeUnidentifiedPdfAnchors, ); if (!mounted || widget.bookId != bookId || widget.categoryId != categoryId || widget.pdfDocumentId != pdfDocumentId || + !setEquals(widget.pdfDocumentIds, pdfDocumentIds) || widget.includeUnidentifiedPdfAnchors != includeUnidentifiedPdfAnchors || widget.isPdf != isPdf || draft == null || @@ -327,6 +333,7 @@ class PersonalNotesSidebarState extends State visibleLineIndices: visibleLineIndices, visiblePdfPages: widget.visiblePdfPages, pdfDocumentId: widget.pdfDocumentId, + pdfDocumentIds: widget.pdfDocumentIds, includeUnidentifiedPdfAnchors: widget.includeUnidentifiedPdfAnchors, ), @@ -482,6 +489,7 @@ class PersonalNotesSidebarState extends State isPdf: widget.isPdf, visiblePdfPages: widget.visiblePdfPages, pdfDocumentId: widget.pdfDocumentId, + pdfDocumentIds: widget.pdfDocumentIds, includeUnidentifiedPdfAnchors: widget.includeUnidentifiedPdfAnchors, ); // רשימה משותפת לכל הכרטיסים: העתקה לכל כרטיס ריבועית במספר ההערות. @@ -752,7 +760,8 @@ class PersonalNotesSidebarState extends State if (anchor == null) return true; if (!widget.isPdf) return false; if (anchor.documentId == null) return widget.includeUnidentifiedPdfAnchors; - return anchor.documentId == widget.pdfDocumentId; + return anchor.documentId == widget.pdfDocumentId || + widget.pdfDocumentIds.contains(anchor.documentId); } Future _saveInline( diff --git a/test/personal_notes/pdf_note_document_identity_test.dart b/test/personal_notes/pdf_note_document_identity_test.dart new file mode 100644 index 0000000000..47e810492b --- /dev/null +++ b/test/personal_notes/pdf_note_document_identity_test.dart @@ -0,0 +1,378 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/core/app_paths.dart'; +import 'package:otzaria/library/models/library.dart'; +import 'package:otzaria/models/books.dart'; +import 'package:otzaria/models/book_source.dart'; +import 'package:otzaria/personal_notes/models/personal_note.dart'; +import 'package:otzaria/personal_notes/utils/personal_notes_book_key.dart'; +import 'package:otzaria/personal_notes/utils/personal_note_source_link.dart'; +import 'package:otzaria/personal_notes/utils/personal_notes_filter.dart'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; +import 'package:otzaria/settings/engine/settings_repository.dart'; + +import '../test_helpers/memory_cache_provider.dart'; + +Library _library(List books) { + final category = Category( + title: 'root', + description: '', + shortDescription: '', + order: 0, + subCategories: [], + books: books, + parent: null, + ); + final library = Library(categories: [category]); + category.parent = library; + return library; +} + +PersonalNote _note(PdfBook book) => PersonalNote( + id: 'note', + bookId: personalNotesBookKey(book), + lineNumber: 2, + pdfAnchor: PdfNoteAnchor( + pageNumber: 2, + x: .35, + y: .65, + documentId: pdfPersonalNoteDocumentId(book), + ), + lastKnownLineNumber: null, + status: PersonalNoteStatus.located, + content: 'תוכן', + contentPlain: 'תוכן', + contentFormat: PersonalNoteContentFormat.plain, + createdAt: DateTime(2026), + updatedAt: DateTime(2026), +); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUp(() { + AppPaths.debugOverrideDataRootPath(null); + return Settings.init(cacheProvider: MemoryCacheProvider()); + }); + tearDown(() => AppPaths.debugOverrideDataRootPath(null)); + + for (final source in [BookSource.official, BookSource.user]) { + test( + 'PDF notes survive moving the library and JSON restore (${source.wireKey})', + () async { + await Settings.setValue( + SettingsRepository.keyLibraryPath, + r'C:\old\library', + ); + final old = PdfBook( + id: 42, + title: 'ספר', + path: r'C:\old\library\nested\ספר.pdf', + source: source, + ); + final saved = _note(old); + final restored = PersonalNote.fromJson( + jsonDecode(jsonEncode(saved.toJson())) as Map, + ); + await Settings.setValue( + SettingsRepository.keyLibraryPath, + '/new/library', + ); + final moved = PdfBook( + id: 42, + title: old.title, + path: '/new/library/nested/ספר.pdf', + source: source, + ); + expect(pdfPersonalNoteDocumentId(moved), saved.pdfAnchor!.documentId); + expect( + personalNoteSourceBook(_library([moved]), restored), + same(moved), + ); + expect( + filterPersonalNotes( + locatedNotes: [restored], + missingNotes: [], + searchQuery: '', + showOnlyVisible: false, + visibleLineIndices: [], + isPdf: true, + pdfDocumentId: pdfPersonalNoteDocumentId(moved), + ).locatedNotes, + [restored], + ); + }, + ); + } + + for (final source in [BookSource.official, BookSource.user]) { + test( + 'full relative subdirectories distinguish PDFs with a borrowed id (${source.wireKey})', + () async { + await Settings.setValue(SettingsRepository.keyLibraryPath, '/library'); + final first = PdfBook( + id: 1, + title: 'ספר', + path: '/library/one/ספר.pdf', + source: source, + ); + final second = PdfBook( + id: 1, + title: 'ספר', + path: '/library/two/ספר.pdf', + source: source, + ); + expect( + pdfPersonalNoteDocumentId(first), + isNot(pdfPersonalNoteDocumentId(second)), + ); + expect( + personalNoteSourceBook(_library([first, second]), _note(first)), + same(first), + ); + expect( + pdfPersonalNoteAnchorMatchesBook(_note(first).pdfAnchor!, second), + isFalse, + ); + }, + ); + } + + test( + 'outside-library paths never alias a managed relative document', + () async { + await Settings.setValue(SettingsRepository.keyLibraryPath, '/library'); + final managed = PdfBook(title: 'ספר', path: '/library/one/ספר.pdf'); + final outside = PdfBook(title: 'ספר', path: '/one/ספר.pdf'); + final prefixSibling = PdfBook( + title: 'ספר', + path: '/library-other/one/ספר.pdf', + ); + expect( + pdfPersonalNoteDocumentId(managed), + isNot(pdfPersonalNoteDocumentId(outside)), + ); + expect( + pdfPersonalNoteDocumentId(managed), + isNot(pdfPersonalNoteDocumentId(prefixSibling)), + ); + }, + ); + + test( + 'source-scoped ids separate same-title personal PDFs and preserve external identities', + () { + final first = PdfBook( + id: 1, + title: 'ספר', + path: '/one.pdf', + source: BookSource.user, + ); + final second = PdfBook( + id: 2, + title: 'ספר', + path: '/two.pdf', + source: BookSource.user, + ); + expect( + pdfPersonalNoteDocumentId(first), + isNot(pdfPersonalNoteDocumentId(second)), + ); + final external = PdfBook( + id: 1, + title: 'ספר', + path: '/one.pdf', + source: BookSource.user, + externalLibraryId: 'external:7', + ); + final moved = PdfBook( + id: 2, + title: 'ספר', + path: '/two.pdf', + source: BookSource.user, + externalLibraryId: 'external:7', + ); + expect( + pdfPersonalNoteDocumentId(external), + pdfPersonalNoteDocumentId(moved), + ); + expect( + pdfPersonalNoteDocumentId(external), + isNot(pdfPersonalNoteDocumentId(first)), + ); + }, + ); + test( + 'Windows forward-slash drive and UNC roots keep portable relative identity', + () async { + for (final root in ['C:/library', r'\\server\share\library']) { + await Settings.setValue(SettingsRepository.keyLibraryPath, root); + final original = PdfBook(title: 'ספר', path: '$root/one/ספר.pdf'); + final identity = pdfPersonalNoteDocumentId(original); + await Settings.setValue( + SettingsRepository.keyLibraryPath, + '/new/library', + ); + expect( + identity, + pdfPersonalNoteDocumentId( + PdfBook(title: 'ספר', path: '/new/library/one/ספר.pdf'), + ), + ); + } + }, + ); + + test( + 'legacy current-path identities retain navigation, links, and filtering without guessing moved paths', + () async { + await Settings.setValue(SettingsRepository.keyLibraryPath, '/library'); + for (final source in [BookSource.official, BookSource.user]) { + final book = PdfBook( + id: 42, + title: 'ספר', + path: '/library/one/ספר.pdf', + source: source, + ); + final legacy = '${source.wireKey}|${Uri.encodeComponent(book.path)}'; + final note = _note(book).copyWith( + pdfAnchor: PdfNoteAnchor( + pageNumber: 2, + x: .35, + y: .65, + documentId: legacy, + ), + ); + expect(personalNoteSourceBook(_library([book]), note), same(book)); + expect(pdfPersonalNoteAnchorMatchesBook(note.pdfAnchor!, book), isTrue); + expect( + personalNoteSourceLink(book, note, pdfLinkCandidates: [book]), + isNotNull, + ); + expect( + filterPersonalNotes( + locatedNotes: [note], + missingNotes: [], + searchQuery: '', + showOnlyVisible: false, + visibleLineIndices: [], + isPdf: true, + pdfDocumentId: pdfPersonalNoteDocumentId(book), + pdfDocumentIds: pdfPersonalNoteDocumentIds(book), + ).locatedNotes, + [note], + ); + final replacement = PdfBook( + id: 42, + title: 'ספר', + path: '/library/two/ספר.pdf', + source: source, + ); + expect(personalNoteSourceBook(_library([replacement]), note), isNull); + } + }, + ); + test( + 'POSIX roots remain case sensitive and preserve literal backslashes', + () async { + await Settings.setValue(SettingsRepository.keyLibraryPath, '/library'); + final inside = PdfBook(title: 'ספר', path: '/library/one/ספר.pdf'); + final outside = PdfBook(title: 'ספר', path: '/Library/one/ספר.pdf'); + expect(pdfPersonalNoteDocumentId(inside), startsWith('o|v2:library:')); + expect( + pdfPersonalNoteDocumentId(outside), + isNot(startsWith('o|v2:library:')), + ); + final slash = PdfBook(title: 'ספר', path: '/library/one/two/ספר.pdf'); + final backslash = PdfBook( + title: 'ספר', + path: r'/library/one\two/ספר.pdf', + ); + expect( + pdfPersonalNoteDocumentId(backslash), + 'o|v2:library:${Uri.encodeComponent(r'one\two/ספר.pdf')}', + ); + expect( + pdfPersonalNoteDocumentId(backslash), + isNot(pdfPersonalNoteDocumentId(slash)), + ); + }, + ); + test( + 'imported personal PDF keeps identity when the data root moves across platforms', + () async { + AppPaths.debugOverrideDataRootPath(r'C:\profile\otzaria'); + final old = PdfBook( + id: 42, + title: 'ספר', + path: r'C:\profile\otzaria\הספרים שלי\one\ספר.pdf', + source: BookSource.user, + ); + final saved = PersonalNote.fromJson( + jsonDecode(jsonEncode(_note(old).toJson())) as Map, + ); + expect(saved.pdfAnchor!.documentId, startsWith('u|v2:data:')); + AppPaths.debugOverrideDataRootPath('/new/profile/otzaria'); + final moved = PdfBook( + id: 42, + title: 'ספר', + path: '/new/profile/otzaria/הספרים שלי/one/ספר.pdf', + source: BookSource.user, + ); + final other = PdfBook( + id: 42, + title: 'ספר', + path: '/new/profile/otzaria/הספרים שלי/two/ספר.pdf', + source: BookSource.user, + ); + expect(pdfPersonalNoteDocumentId(moved), saved.pdfAnchor!.documentId); + expect( + personalNoteSourceBook(_library([moved, other]), saved), + same(moved), + ); + expect( + pdfPersonalNoteAnchorMatchesBook(saved.pdfAnchor!, other), + isFalse, + ); + }, + ); + + test( + 'nested roots retain the more specific namespace when either root is relocated', + () async { + await Settings.setValue( + SettingsRepository.keyLibraryPath, + '/data/library', + ); + AppPaths.debugOverrideDataRootPath('/data'); + final libraryBook = PdfBook( + title: 'ספר', + path: '/data/library/one/ספר.pdf', + ); + final libraryId = pdfPersonalNoteDocumentId(libraryBook); + expect(libraryId, startsWith('o|v2:library:')); + await Settings.setValue( + SettingsRepository.keyLibraryPath, + '/elsewhere/library', + ); + expect( + pdfPersonalNoteDocumentId( + PdfBook(title: 'ספר', path: '/elsewhere/library/one/ספר.pdf'), + ), + libraryId, + ); + await Settings.setValue(SettingsRepository.keyLibraryPath, '/library'); + AppPaths.debugOverrideDataRootPath('/library/data'); + final dataBook = PdfBook(title: 'ספר', path: '/library/data/one/ספר.pdf'); + final dataId = pdfPersonalNoteDocumentId(dataBook); + expect(dataId, startsWith('o|v2:data:')); + AppPaths.debugOverrideDataRootPath('/elsewhere/data'); + expect( + pdfPersonalNoteDocumentId( + PdfBook(title: 'ספר', path: '/elsewhere/data/one/ספר.pdf'), + ), + dataId, + ); + }, + ); +} diff --git a/test/personal_notes/personal_note_draft_service_test.dart b/test/personal_notes/personal_note_draft_service_test.dart index c73e5b4f52..efe1d753d0 100644 --- a/test/personal_notes/personal_note_draft_service_test.dart +++ b/test/personal_notes/personal_note_draft_service_test.dart @@ -1,6 +1,11 @@ import 'dart:convert'; import 'dart:io'; +import 'package:otzaria/models/books.dart'; +import 'package:otzaria/models/book_source.dart'; +import 'package:otzaria/settings/engine/settings_repository.dart'; +import 'package:otzaria/personal_notes/utils/personal_notes_book_key.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/core/app_paths.dart'; import 'package:otzaria/settings/engine/app_settings_store.dart'; import 'package:hive_ce/hive.dart'; import 'package:otzaria/data/data_providers/hive_data_provider.dart'; @@ -20,6 +25,7 @@ void main() { }); tearDown(() async { + AppPaths.debugOverrideDataRootPath(null); await Hive.close(); await tempDir.delete(recursive: true); }); @@ -436,4 +442,199 @@ void main() { 'טקסט', ); }); + test( + 'portable PDF draft survives a root change through exact and latest lookup', + () async { + final service = PersonalNoteDraftService(); + for (final source in [BookSource.official, BookSource.user]) { + await Settings.setValue( + SettingsRepository.keyLibraryPath, + r'C:\old\library', + ); + final old = PdfBook( + id: 42, + title: 'ספר', + path: r'C:\old\library\one\ספר.pdf', + source: source, + ); + final anchor = PdfNoteAnchor( + pageNumber: 2, + x: .3, + y: .7, + documentId: pdfPersonalNoteDocumentId(old), + ); + final bookId = personalNotesBookKey(old); + await service.saveDraft( + bookId: bookId, + lineNumber: 2, + draft: PersonalNoteDraft( + content: 'טיוטה ניידת', + contentPlain: 'טיוטה ניידת', + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime(2026), + lineNumber: 2, + pdfAnchor: anchor, + ), + ); + await Settings.setValue( + SettingsRepository.keyLibraryPath, + '/new/library', + ); + final moved = PdfBook( + id: 42, + title: 'ספר', + path: '/new/library/one/ספר.pdf', + source: source, + ); + final movedAnchor = PdfNoteAnchor( + pageNumber: 2, + x: .3, + y: .7, + documentId: pdfPersonalNoteDocumentId(moved), + ); + final exact = await service.loadDraft( + bookId: bookId, + lineNumber: 2, + pdfAnchor: movedAnchor, + ); + final latest = await service.loadLatestNewNoteDraft( + bookId: bookId, + pdfDocumentId: movedAnchor.documentId, + pdfDocumentIds: pdfPersonalNoteDocumentIds(moved), + ); + expect(exact?.contentPlain, 'טיוטה ניידת'); + expect(latest?.contentPlain, 'טיוטה ניידת'); + expect(exact?.pdfAnchor, anchor); + await service.clearDraft( + bookId: bookId, + lineNumber: 2, + pdfAnchor: movedAnchor, + ); + expect( + await service.loadLatestNewNoteDraft( + bookId: bookId, + pdfDocumentId: movedAnchor.documentId, + ), + isNull, + ); + } + }, + ); + + test( + 'legacy current-path PDF draft restores through exact and accepted latest identities', + () async { + final service = PersonalNoteDraftService(); + await Settings.setValue(SettingsRepository.keyLibraryPath, '/library'); + final book = PdfBook( + id: 42, + title: 'ספר', + path: '/library/one/ספר.pdf', + source: BookSource.user, + ); + final anchor = PdfNoteAnchor( + pageNumber: 2, + x: .3, + y: .7, + documentId: 'u|${Uri.encodeComponent(book.path)}', + ); + await service.saveDraft( + bookId: 'ספר|user', + lineNumber: 2, + draft: PersonalNoteDraft( + content: 'טיוטה קודמת', + contentPlain: 'טיוטה קודמת', + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime(2026), + lineNumber: 2, + pdfAnchor: anchor, + ), + ); + final latest = await service.loadLatestNewNoteDraft( + bookId: 'ספר|user', + pdfDocumentId: pdfPersonalNoteDocumentId(book), + pdfDocumentIds: pdfPersonalNoteDocumentIds(book), + ); + expect(latest?.pdfAnchor, anchor); + expect( + (await service.loadDraft( + bookId: 'ספר|user', + lineNumber: 2, + pdfAnchor: latest!.pdfAnchor, + ))?.contentPlain, + 'טיוטה קודמת', + ); + final other = PdfBook( + id: 43, + title: 'ספר', + path: '/library/two/ספר.pdf', + source: BookSource.user, + ); + expect( + await service.loadLatestNewNoteDraft( + bookId: 'ספר|user', + pdfDocumentId: pdfPersonalNoteDocumentId(other), + pdfDocumentIds: pdfPersonalNoteDocumentIds(other), + ), + isNull, + ); + }, + ); + test('imported PDF draft restores after moving the data root', () async { + final service = PersonalNoteDraftService(); + AppPaths.debugOverrideDataRootPath('/old/profile'); + final old = PdfBook( + id: 42, + title: 'ספר', + path: '/old/profile/הספרים שלי/nested/ספר.pdf', + source: BookSource.user, + ); + final anchor = PdfNoteAnchor( + pageNumber: 2, + x: .3, + y: .7, + documentId: pdfPersonalNoteDocumentId(old), + ); + await service.saveDraft( + bookId: 'ספר|user', + lineNumber: 2, + draft: PersonalNoteDraft( + content: 'טיוטת ספר מיובא', + contentPlain: 'טיוטת ספר מיובא', + contentFormat: PersonalNoteContentFormat.plain, + updatedAt: DateTime(2026), + lineNumber: 2, + pdfAnchor: anchor, + ), + ); + AppPaths.debugOverrideDataRootPath('/new/profile'); + final moved = PdfBook( + id: 42, + title: 'ספר', + path: '/new/profile/הספרים שלי/nested/ספר.pdf', + source: BookSource.user, + ); + final movedAnchor = PdfNoteAnchor( + pageNumber: 2, + x: .3, + y: .7, + documentId: pdfPersonalNoteDocumentId(moved), + ); + expect( + (await service.loadDraft( + bookId: 'ספר|user', + lineNumber: 2, + pdfAnchor: movedAnchor, + ))?.contentPlain, + 'טיוטת ספר מיובא', + ); + expect( + (await service.loadLatestNewNoteDraft( + bookId: 'ספר|user', + pdfDocumentId: movedAnchor.documentId, + pdfDocumentIds: pdfPersonalNoteDocumentIds(moved), + ))?.contentPlain, + 'טיוטת ספר מיובא', + ); + }); } diff --git a/test/personal_notes/personal_notes_manager_loading_test.dart b/test/personal_notes/personal_notes_manager_loading_test.dart index 741fc8a84b..57eaa2402f 100644 --- a/test/personal_notes/personal_notes_manager_loading_test.dart +++ b/test/personal_notes/personal_notes_manager_loading_test.dart @@ -34,6 +34,7 @@ import 'package:otzaria/widgets/controls/bar_button.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import '../test_helpers/memory_cache_provider.dart'; +import '../test_helpers/capture_file_saves.dart'; class _LibraryBloc extends MockBloc implements LibraryBloc {} @@ -256,6 +257,45 @@ Future _mount( return notesBloc; } +class _MutationRepository extends _Repository { + _MutationRepository(super.notes); + final pendingWrite = Completer(); + final targets = <({String bookId, String noteId, int? line})>[]; + + Future> _write( + String bookId, + String noteId, + int? line, + ) async { + targets.add((bookId: bookId, noteId: noteId, line: line)); + await pendingWrite.future; + notes[bookId] = [ + for (final note in notes[bookId] ?? []) + if (note.id != noteId) + note + else if (line != null) + note.copyWith(lineNumber: line, status: PersonalNoteStatus.located), + ]; + PersonalNotesChanges.notify(bookId); + return notes[bookId]!; + } + + @override + Future> deleteNote({ + required String bookId, + required String noteId, + }) => _write(bookId, noteId, null); + + @override + Future> repositionNote({ + required String bookId, + required String noteId, + required int lineNumber, + PdfNoteAnchor? pdfAnchor, + int? categoryId, + }) => _write(bookId, noteId, lineNumber); +} + void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -584,12 +624,10 @@ void main() { 'ספר ב': [noteB], }); final picker = _ExportPicker(); - final previousPicker = FilePickerPlatform.instance; final previousOwner = DialogOwner.hwnd(); - FilePickerPlatform.instance = picker; + captureFileSaves(picker, (bytes) => picker.bytes = bytes); DialogOwner.mainWindowHwnd = 7; addTearDown(() { - FilePickerPlatform.instance = previousPicker; DialogOwner.mainWindowHwnd = previousOwner; }); await _mount(tester, repository); @@ -771,4 +809,63 @@ void main() { await tester.pump(); }, ); + for (final reposition in [false, true]) { + for (final fail in [false, true]) { + testWidgets( + 'manager ${reposition ? "repositions" : "deletes"} only after confirmed write (failure: $fail)', + (tester) async { + var note = _note('ספר א', 'תוכן פעולת מנהל'); + if (reposition) { + note = note.copyWith( + clearLineNumber: true, + status: PersonalNoteStatus.missing, + ); + } + final repository = _MutationRepository({ + 'ספר א': [note], + }); + final reader = await _mount(tester, repository); + await tester.pumpAndSettle(); + expect(reader.state.bookId, isNull); + 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 _pump(tester); + expect(repository.targets, [ + (bookId: note.bookId, noteId: note.id, line: reposition ? 3 : null), + ]); + final success = reposition + ? NotesMessages.noteMovedToLine(3) + : NotesMessages.noteDeleted; + expect(find.text(success), findsNothing); + expect(repository.notes[note.bookId], [note]); + reader.add(const LoadPersonalNotes('ספר קורא אחר', categoryId: 91)); + await _pump(tester); + if (fail) { + repository.pendingWrite.completeError(StateError('כתיבה נדחתה')); + } else { + repository.pendingWrite.complete(); + } + await tester.pumpAndSettle(); + expect(reader.state.bookId, 'ספר קורא אחר'); + if (fail) { + expect(repository.notes[note.bookId], [note]); + expect(find.text(success), findsNothing); + expect(find.textContaining('כתיבה נדחתה'), findsOneWidget); + } else { + expect(find.text(success), findsOneWidget); + if (reposition) { + expect(repository.notes[note.bookId]!.single.lineNumber, 3); + } else { + expect(repository.notes[note.bookId], isEmpty); + } + } + await tester.pump(const Duration(seconds: 10)); + }, + ); + } + } } diff --git a/test/personal_notes/personal_notes_word_export_screen_test.dart b/test/personal_notes/personal_notes_word_export_screen_test.dart index 75f2d95886..1c446040c0 100644 --- a/test/personal_notes/personal_notes_word_export_screen_test.dart +++ b/test/personal_notes/personal_notes_word_export_screen_test.dart @@ -32,6 +32,7 @@ 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:xml/xml.dart'; +import '../test_helpers/capture_file_saves.dart'; // ignore: depend_on_referenced_packages import 'package:plugin_platform_interface/plugin_platform_interface.dart'; @@ -163,12 +164,10 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final picker = _ExportPicker(); - final previousPicker = FilePickerPlatform.instance; final previousOwner = DialogOwner.hwnd(); - FilePickerPlatform.instance = picker; + captureFileSaves(picker, (bytes) => picker.bytes = bytes); DialogOwner.mainWindowHwnd = 7; addTearDown(() { - FilePickerPlatform.instance = previousPicker; DialogOwner.mainWindowHwnd = previousOwner; }); // Normal PDFs can borrow the text edition's ID; this cannot identify a PDF diff --git a/test/printing/printing_screen_export_profile_test.dart b/test/printing/printing_screen_export_profile_test.dart index f494c8b7c4..5546817abc 100644 --- a/test/printing/printing_screen_export_profile_test.dart +++ b/test/printing/printing_screen_export_profile_test.dart @@ -29,6 +29,7 @@ import 'package:xml/xml.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import '../helpers/memory_settings_cache.dart'; +import '../test_helpers/capture_file_saves.dart'; class _MockSettingsBloc extends MockBloc implements SettingsBloc {} @@ -76,7 +77,7 @@ Future _exportWord( tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final picker = _CapturingFilePicker(); - FilePickerPlatform.instance = picker; + captureFileSaves(picker, (bytes) => picker.bytes = bytes); final settingsBloc = _MockSettingsBloc(); whenListen( settingsBloc, diff --git a/test/test_helpers/capture_file_saves.dart b/test/test_helpers/capture_file_saves.dart new file mode 100644 index 0000000000..05fae52cb6 --- /dev/null +++ b/test/test_helpers/capture_file_saves.dart @@ -0,0 +1,26 @@ +import 'dart:io'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// ב-macOS הבורר בבעלות חלון נוצר בנפרד ועוקף את ה-instance המשותף. +void captureFileSaves( + FilePickerPlatform picker, + void Function(Uint8List bytes) onSave, +) { + final previous = FilePickerPlatform.instance; + FilePickerPlatform.instance = picker; + addTearDown(() => FilePickerPlatform.instance = previous); + if (!Platform.isMacOS) return; + const channel = MethodChannel('miguelruivo.flutter.plugins.filepicker'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'save') { + onSave(Uint8List.fromList((call.arguments['bytes'] as List).cast())); + } + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); +}