Repository navigation
Expand file tree
/
Copy pathlinks_list_view.dart
More file actions
1071 lines (996 loc) · 42.8 KB
/
Copy pathlinks_list_view.dart
File metadata and controls
1071 lines (996 loc) · 42.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'package:otzaria_icons/otzaria_icons.dart';
import 'package:flutter/material.dart';
import 'package:otzaria/theme/app_fonts.dart';
import 'package:otzaria/theme/app_tokens.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:otzaria/widgets/misc/expanding_chevron.dart';
import 'package:otzaria/widgets/misc/app_menu_exports.dart';
import 'package:otzaria/widgets/misc/middle_click_open.dart';
import 'package:otzaria/models/link_types.dart';
import 'package:otzaria/models/links.dart';
import 'package:otzaria/services/commentary_service.dart';
import 'package:otzaria/services/target_line_links_service.dart';
import 'package:otzaria/settings/settings_exports.dart';
import 'package:otzaria/tabs/models/tab.dart';
import 'package:otzaria/book_common/utils/commentary_search_utils.dart';
import 'package:otzaria/book_common/utils/link_anchor_markers.dart';
import 'package:otzaria/tools/dictionary/widgets/laaz_commentary_subblock.dart';
import 'package:otzaria/widgets/feedback/app_future_builder.dart';
import 'package:otzaria/widgets/feedback/otzaria_empty_state.dart';
import 'package:otzaria/widgets/lists/filter_chips_widget.dart';
import 'package:otzaria/utils/navigation/talmud_bavli_open_format.dart';
import 'package:otzaria/text_display/models/text_display_profile.dart';
import 'package:otzaria/utils/text/text_manipulation.dart' as utils;
import 'package:otzaria/utils/ui/context_menu_utils.dart';
import 'package:otzaria/widgets/text/otzaria_search_field.dart';
import 'package:otzaria/widgets/text/rtl_selection_shortcuts.dart';
import 'package:otzaria/widgets/text/selection_copy_shortcuts.dart';
import 'package:otzaria/widgets/commentary/panel_anchor_links.dart';
import 'package:otzaria/widgets/smart_text/smart_text.dart';
import 'package:otzaria/text_book/view/selection/selection_sync_controller.dart';
import 'package:otzaria/book_common/selection/selection_hit_test.dart';
import 'package:otzaria/widgets/feedback/scrollable_positioned_list_scrollbar.dart';
import 'package:positioned_sliver_list/positioned_list.dart';
@visibleForTesting
RenderSettings buildSelectedLinkRenderSettings({
required SettingsState settingsState,
required TextDisplayProfile displayProfile,
required String searchText,
}) {
return RenderSettings.fromProfile(
displayProfile,
searchText: searchText,
fontSize: settingsState.commentatorsFontSize,
fontFamily: settingsState.commentatorsFontFamily,
fontWeight: settingsState.commentatorsFontBold ? FontWeight.bold : null,
lineHeight: settingsState.lineHeight,
justifyText: true,
// חייב להתאים ל-partialWordMatch של הסינון, אחרת קישור נכנס לרשימה
// בלי שההתאמה שהכניסה אותו מודגשת בו.
partialWordHighlight: true,
);
}
String _selectedLinkBookKey(Link link) =>
'${link.targetSource.wireKey}_${link.targetCategoryId ?? ''}_${link.targetBookId ?? ''}';
@visibleForTesting
String buildSelectedLinkContentKey(Link link) {
final target = _selectedLinkBookKey(link);
return '${link.path2}_${link.index2}_$target';
}
@visibleForTesting
String buildSelectedLinkInstanceKey(Link link) {
final target = _selectedLinkBookKey(link);
return '${link.path2}_${link.index1}_${link.index2}_${link.index2End ?? ''}_${link.heRef}_${link.start}_${link.end}_${link.connectionType}_$target';
}
/// זהות קטע היעד, כולל המסד והספר, בלי שורת המקור (index1).
@visibleForTesting
String buildSelectedLinkTargetKey(Link link) {
final target = _selectedLinkBookKey(link);
return '${link.path2}_${link.index2}_${link.index2End ?? ''}_${link.start}_${link.end}_${link.connectionType}_${link.targetFileType ?? ''}_$target';
}
/// מסיר קישורים כפולים לאותו קטע-יעד. הקטע המוצג פורש כמה שורות מקור, ואותו
/// קטע-יעד מקושר לעיתים מכמה מהן — בלי המיזוג הוא מופיע ברשימה כמה פעמים.
List<Link> dedupeLinksByTarget(List<Link> links) {
final seen = <String>{};
return links
.where((link) => seen.add(buildSelectedLinkTargetKey(link)))
.toList();
}
@visibleForTesting
String buildSelectedLinksSearchKey({
required String searchQuery,
required bool searchInContent,
required List<Link> links,
Set<String> selectedLinkTypes = const {},
}) {
// רשימה אינה משתנה אחרי שנבנתה, ולכן הקלדה אינה גוזרת שוב את מפתחות כולה.
final linksSignature = _linksSignatures[links] ??= links
.map(buildSelectedLinkInstanceKey)
.join('|');
// סדר יציב — Set.toString() אינו מבטיח סדר, ומפתח מתחלף היה מרענן לשווא.
final typesSignature = (selectedLinkTypes.toList()..sort()).join(',');
return '${searchQuery}_$searchInContent|$typesSignature|$linksSignature';
}
final _linksSignatures = Expando<String>('linksSignature');
/// מפתחות צ׳יפי הסינון של [links], בסדר התצוגה. סוג בעל תווית משמעותית מקבל
/// צ׳יפ משלו; שאר הסוגים ([LinkTypes.eraGroupedTypes]) מקובצים לפי דור ספר
/// היעד. הסדר: סוגים ייעודיים (לפי [_typeChipOrder]) ואז דורות לפי סדר הדורות.
@visibleForTesting
List<String> buildLinkChipKeys(List<Link> links, {String? openBookTitle}) {
final keys = <String>{};
for (final link in links) {
keys.addAll(
CommentaryService.linkChipKeys(link, openBookTitle: openBookTitle),
);
}
return keys.toList()..sort((a, b) {
final eraA = CommentaryService.eraFromChipKey(a);
final eraB = CommentaryService.eraFromChipKey(b);
// דורות תמיד אחרי הסוגים הייעודיים.
if ((eraA == null) != (eraB == null)) return eraA == null ? -1 : 1;
if (eraA != null) return eraA.order.compareTo(eraB!.order);
final indexA = _typeChipOrder.indexOf(a);
final indexB = _typeChipOrder.indexOf(b);
if (indexA != indexB) {
if (indexA == -1) return 1;
if (indexB == -1) return -1;
return indexA.compareTo(indexB);
}
return a.compareTo(b);
});
}
/// הבחירה האפקטיבית: רק מפתחות שקיימים בצ׳יפים. בחירה שאין לה אף צ׳יפ קיים
/// (הגדרה שנשמרה כשמפתחות הצ׳יפים היו אחרים) מוחזרת כריקה = הצג הכל.
@visibleForTesting
Set<String> effectiveSelectedLinkTypes({
required Set<String> selectedTypes,
required List<String> availableKeys,
}) {
if (selectedTypes.isEmpty) return const {};
final available = availableKeys.toSet();
return selectedTypes.where(available.contains).toSet();
}
/// חתימת הכותרות שדורותיהן נטענו. גרסת המטמון נכללת כי אחרי `clearEraCache`
/// הכותרות זהות אך המטמון ריק, וטעינה מחדש נדרשת.
@visibleForTesting
String buildEraPreloadSignature(Set<String> titles) =>
'${CommentaryService.eraCacheVersion}|${(titles.toList()..sort()).join('|')}';
/// קישורי ההפניה שמהם נבנים הצ׳יפים — כל קישורי חלון הקריאה, לא רק הנראים,
/// כדי ששורת הצ׳יפים לא תקפוץ בדפדוף והבחירה לא תתאפס.
@visibleForTesting
List<Link> chipSourceLinks(List<Link> links) => links
.where(
(link) =>
!LinkTypes.isDependentTextLink(link.connectionType) &&
link.start == null &&
link.end == null,
)
.toList();
@visibleForTesting
const Key linkTypeChipsRowKey = Key('link_type_chips_row');
@visibleForTesting
const Key linkEraChipsRowKey = Key('link_era_chips_row');
/// מפתחות הצ׳יפים מפוצלים לשני צירי המיון: `types` (סוג הקישור) ו-`eras`
/// (דור המחבר). הסדר בתוך כל ציר נשמר כפי שהתקבל.
@visibleForTesting
({List<String> types, List<String> eras}) splitChipKeysByAxis(
List<String> keys,
) {
final types = <String>[];
final eras = <String>[];
for (final key in keys) {
(LinkTypes.isEraKey(key) ? eras : types).add(key);
}
return (types: types, eras: eras);
}
/// הבחירה השמורה החדשה אחרי לחיצה על צ׳יפ. הצ׳יפים מציגים רק את הבחירה
/// האפקטיבית, ולכן מחילים את הדלתא על הבחירה השמורה המלאה — אחרת כל מפתח
/// שאינו קיים כרגע היה נמחק.
@visibleForTesting
Set<String> applyChipSelectionDelta({
required Set<String> savedTypes,
required Set<String> effectiveTypes,
required Set<String> newSelection,
}) {
final added = newSelection.difference(effectiveTypes);
final removed = effectiveTypes.difference(newSelection);
return savedTypes.union(added).difference(removed);
}
/// סדר הצ׳יפים של הסוגים הייעודיים. סוג שאינו כאן מוצג אחריהם, אלפביתית.
const List<String> _typeChipOrder = [
// SOURCE הוא ספר הבסיס שממנו נפתח המפרש — המידע הישיר ביותר לקטע הנלמד.
LinkTypes.source,
LinkTypes.einMishpat,
LinkTypes.sifreiMitzvot,
LinkTypes.mesoratHashas,
LinkTypes.mishnahInTalmud,
LinkTypes.quotation,
LinkTypes.law,
LinkTypes.liturgy,
LinkTypes.summary,
LinkTypes.footnotes,
LinkTypes.allusion,
LinkTypes.altToc,
// אחרון שבסוגים — חוצץ בין הסוגים הייעודיים לצ׳יפי הדורות שאחריהם.
LinkTypes.onBookKey,
];
/// רשימת הקישורים (לא-מפרשים) של הקטע המוצג: צ׳יפי סינון לפי סוג ודור,
/// חיפוש בכותרת ובתוכן, ורינדור ב-[SmartTextWidget].
///
/// חסר-תלות ב-`TextBookBloc` בכוונה — הנתונים נכנסים כפרמטרים והשינויים
/// יוצאים בקולבקים, כדי שגם חלונית ה-PDF (שאין בה BLoC של טקסט) תציג את
/// אותה רשימה בדיוק. ראה [SelectedLineLinksView] למתאם של כרטיסיית הטקסט.
class LinksListView extends StatefulWidget {
/// הקישורים להצגה ברשימה — הקטע הנראה, ללא קישורי-תווים (inline).
final List<Link> links;
/// כל קישורי חלון הקריאה. מהם נבנים הצ׳יפים, כדי שצ׳יפ לא ייעלם בדפדוף
/// ושהבחירה לא תתאפס.
final List<Link> chipSourceLinks;
/// שם הספר הפתוח — לתווית צ׳יפ "על <הספר>".
final String openBookTitle;
/// הבחירה השמורה של סוגי הקישורים (ריקה = הצג הכל).
final Set<String> selectedLinkTypes;
final ValueChanged<Set<String>> onSelectedLinkTypesChanged;
final Function(OpenedTab) openBookCallback;
final double fontSize;
/// פרופיל התצוגה שחל על תוכן הקישורים.
final TextDisplayProfile displayProfile;
/// פרופיל ערוץ ההעתקה; null = כמו התצוגה.
final TextDisplayProfile? copyDisplayProfile;
final SelectionSyncController? selectionSyncController;
/// מזהה התוכן המוצג; שינויו מאפס גלילה ובחירה אך משמר חיפוש וסינון.
final Object? contentScopeKey;
/// ההודעה כשאין קישורים כלל.
final String emptyMessage;
const LinksListView({
super.key,
required this.links,
required this.chipSourceLinks,
required this.openBookTitle,
required this.selectedLinkTypes,
required this.onSelectedLinkTypesChanged,
required this.openBookCallback,
required this.fontSize,
required this.displayProfile,
this.copyDisplayProfile,
this.selectionSyncController,
this.contentScopeKey,
this.emptyMessage = 'לא נמצאו קישורים לקטע הנבחר',
});
@override
State<LinksListView> createState() => _LinksListViewState();
}
class _LinksListViewState extends State<LinksListView> {
final TextEditingController _searchController = TextEditingController();
final ItemScrollController _itemScrollController = ItemScrollController();
String _searchQuery = '';
final Map<String, Future<String>> _contentCache = {};
final Set<String> _failedContentKeys = {};
// תוצאת ה-Future שב-_contentCache, ולא link.loadedContent: המפתח כאן אינו
// כולל את סוף הטווח, והמטמון הזה אינו מתנקה ברענון מסד.
final Map<String, String> _loadedContent = {};
final Map<String, bool> _expanded = {};
bool _searchInContent = false;
Future<List<Link>>? _filteredLinksFuture;
String _lastSearchKey = '';
Object? _lastSearchInputs;
List<Link>? _dedupedSource;
List<Link> _dedupedLinks = const [];
List<Link>? _sortedSource;
int _sortedEraVersion = -1;
List<Link> _sortedLinks = const [];
List<Link>? _searchTextsSource;
List<(String, String)> _searchTexts = const [];
final Set<String> _linksWithSearchResults = {}; // קישורים עם תוצאות חיפוש
String? _savedSelectedText; // טקסט נבחר לתפריט הקשר
bool _anchorHandledTap = false;
Link? _savedSelectedLink; // ה-link שממנו נבחר הטקסט
final Object _selectionOwner = Object();
int _selectionRevision = 0;
String _preloadedEraTitles = '';
int _eraGeneration = 0;
List<Link>? _cachedChipLinksSource;
String? _cachedChipCountsBookTitle;
int _cachedChipCountsEraGeneration = -1;
List<String> _cachedChipKeys = const [];
@override
void initState() {
super.initState();
widget.selectionSyncController?.addListener(_handleExternalSelectionChange);
}
@override
void dispose() {
widget.selectionSyncController?.removeListener(
_handleExternalSelectionChange,
);
_searchController.dispose();
super.dispose();
}
@override
void didUpdateWidget(covariant LinksListView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.selectionSyncController != widget.selectionSyncController) {
oldWidget.selectionSyncController?.removeListener(
_handleExternalSelectionChange,
);
widget.selectionSyncController?.addListener(
_handleExternalSelectionChange,
);
}
if (oldWidget.contentScopeKey != widget.contentScopeKey) {
widget.selectionSyncController?.clear(_selectionOwner);
_savedSelectedText = null;
_savedSelectedLink = null;
_selectionRevision++;
final contentScopeKey = widget.contentScopeKey;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted ||
widget.contentScopeKey != contentScopeKey ||
!_itemScrollController.isAttached) {
return;
}
_itemScrollController.jumpTo(index: 0);
});
}
}
void _handleExternalSelectionChange() {
final controller = widget.selectionSyncController;
if (controller == null || !mounted) {
return;
}
final shouldClear = shouldClearSelectionOnExternalChange(
activeOwner: controller.activeOwner,
selfOwner: _selectionOwner,
hasOwnSelection: _savedSelectedText != null,
);
if (!shouldClear) {
return;
}
// כאן הניקוי כן נעשה בהחלפת מפתח: הרשימה מרנדרת SelectionArea לכל קישור
// מורחב, ולכן אין GlobalKey יחיד לפנות אליו. ההריסה בטוחה — אין כאן אזור
// בחירה מקונן שאפשר להרוס לו את הבחירה.
setState(() {
_selectionRevision++;
_savedSelectedText = null;
_savedSelectedLink = null;
});
}
@override
Widget build(BuildContext context) {
final links = _dedupedFor(widget.links);
final openBookTitle = widget.openBookTitle;
final chipKeys = _chipKeysFor(widget.chipSourceLinks, openBookTitle);
final effectiveTypes = effectiveSelectedLinkTypes(
selectedTypes: widget.selectedLinkTypes,
availableKeys: chipKeys,
);
final chipAxes = splitChipKeysByAxis(chipKeys);
String chipLabel(String key) =>
CommentaryService.chipKeyLabel(key, openBookTitle: openBookTitle);
return Column(
children: [
// שדה חיפוש
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
OtzariaSearchField(
controller: _searchController,
hintText: 'חפש בתוך הקישורים המוצגים...',
icon: OtzariaIcons.search_in_titles_24_regular,
onClear: () => setState(() => _searchQuery = ''),
onChanged: (value) {
setState(() {
_searchQuery = value;
});
},
),
if (_searchQuery.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Row(
children: [
Checkbox(
value: _searchInContent,
onChanged: (value) {
setState(() {
_searchInContent = value ?? false;
});
},
),
const Text('חפש גם בתוכן הקישורים'),
],
),
),
],
),
),
if (chipKeys.length > 1) ...[
Padding(
padding: const EdgeInsets.fromLTRB(
AppTokens.spaceSM,
0,
AppTokens.spaceSM,
AppTokens.spaceXS,
),
// Wrap ולא Row: שני הצירים מתאחדים לשורה אחת רק כשיש רוחב לשניהם,
// אחרת כל ציר יורד לשורה משלו. הריווח האנכי מגיע מריפוד הקבוצה.
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: AppTokens.spaceMD,
runSpacing: 0,
children: [
if (chipAxes.types.isNotEmpty)
_buildChipGroup(
key: linkTypeChipsRowKey,
keys: chipAxes.types,
savedTypes: widget.selectedLinkTypes,
effectiveTypes: effectiveTypes,
chipLabel: chipLabel,
),
if (chipAxes.eras.isNotEmpty)
_buildChipGroup(
key: linkEraChipsRowKey,
keys: chipAxes.eras,
savedTypes: widget.selectedLinkTypes,
effectiveTypes: effectiveTypes,
chipLabel: chipLabel,
),
],
),
),
const SizedBox(height: AppTokens.spaceSM),
],
// תוכן הקישורים
Expanded(
child: _buildLinksList(links, effectiveTypes, openBookTitle),
),
],
);
}
/// קבוצת צ׳יפים של ציר מיון אחד. הדלתא מחושבת מול הבחירה האפקטיבית של
/// *הקבוצה בלבד* — אחרת מפתחות הציר השני היו נחשבים כמי שהוסרו ונמחקים.
Widget _buildChipGroup({
required List<String> keys,
required Set<String> savedTypes,
required Set<String> effectiveTypes,
required String Function(String key) chipLabel,
required Key key,
}) {
final rowKeys = keys.toSet();
final rowSelected = effectiveTypes.intersection(rowKeys);
return compactFilterChips(
key: key,
items: keys,
selected: rowSelected.toList(),
labelBuilder: chipLabel,
onSelectionChanged: (selected) => widget.onSelectedLinkTypesChanged(
applyChipSelectionDelta(
savedTypes: savedTypes,
effectiveTypes: rowSelected,
newSelection: selected.toSet(),
),
),
);
}
/// הרשימה מתחלפת עם הקטע בלבד; הרחבת פריט או הקלדה אינן גוזרות מחדש את
/// מפתחות היעד של כל הקישורים.
List<Link> _dedupedFor(List<Link> links) {
if (!identical(_dedupedSource, links)) {
_dedupedSource = links;
_dedupedLinks = dedupeLinksByTarget(links);
}
return _dedupedLinks;
}
/// צ׳יפי הסינון של כל קישורי החלון, ממומשים לפי זהות הרשימה. `copyWith`
/// מעביר את `links` באותה הפניה בגלילה, ולכן זהות היא מפתח נכון וזול.
List<String> _chipKeysFor(List<Link> stateLinks, String openBookTitle) {
// התחממות מטמון הדורות משנה מפתחות צ׳יפים, ולכן היא חלק ממפתח המימוש.
if (identical(_cachedChipLinksSource, stateLinks) &&
_cachedChipCountsBookTitle == openBookTitle &&
_cachedChipCountsEraGeneration == _eraGeneration) {
return _cachedChipKeys;
}
final chipLinks = chipSourceLinks(stateLinks);
_ensureErasPreloaded(chipLinks);
_cachedChipLinksSource = stateLinks;
_cachedChipCountsBookTitle = openBookTitle;
_cachedChipCountsEraGeneration = _eraGeneration;
_cachedChipKeys = buildLinkChipKeys(
chipLinks,
openBookTitle: openBookTitle,
);
return _cachedChipKeys;
}
/// מטמון הדורות נקרא סינכרונית ב-build; בלי טעינה מוקדמת כל הקישורים ייפלו
/// לצ׳יפ "ספרים נוספים". הטעינה אסינכרונית ומרעננת את ה-build בסיומה.
void _ensureErasPreloaded(List<Link> links) {
final eraLinks = links
.where((link) => LinkTypes.isEraGroupedType(link.connectionType))
.toList();
final titles = eraLinks
.map((link) => utils.getTitleFromPath(link.path2))
.toSet();
if (titles.isEmpty) return;
final signature = buildEraPreloadSignature(titles);
if (_preloadedEraTitles == signature) return;
_preloadedEraTitles = signature;
CommentaryService.preloadErasForLinks(eraLinks).then((_) {
// בחירת שורה מהירה מייתרת טעינה קודמת — rebuild מיותר.
if (mounted && _preloadedEraTitles == signature) {
setState(() => _eraGeneration++);
}
});
}
/// פותח את יעד הקישור בכרטיסייה חדשה (טקסט או PDF, לפי תבנית הפתיחה).
Future<void> _navigateToLink(Link link) =>
openLinkTarget(link, (tab) => widget.openBookCallback(tab));
Widget _buildLinksList(
List<Link> links,
Set<String> selectedTypes,
String? openBookTitle,
) {
if (links.isEmpty) {
return _buildEmptyMessage(widget.emptyMessage);
}
// קבוצה ריקה = הצג הכל. כמה צ׳יפים נבחרים = איחוד, ולכן די בחיתוך אחד.
final typeFilteredLinks = selectedTypes.isEmpty
? links
: links
.where(
(link) => CommentaryService.linkChipKeys(
link,
openBookTitle: openBookTitle,
).any(selectedTypes.contains),
)
.toList();
// הצ׳יפים נבנים מקישורי כל חלון הקריאה בעוד הרשימה מציגה את הקטע הנראה
// בלבד, ולכן צ׳יפ שנבחר עשוי לא להתאים לאף קישור כאן.
if (typeFilteredLinks.isEmpty) {
return _buildEmptyMessage('לא נמצאו קישורים מהסוגים שנבחרו');
}
// אותם קלטים בדיוק נותנים אותו מפתח; בלי הבדיקה כל בנייה מחשבת מפתח לכל קישור.
final searchInputs = (
_searchQuery,
_searchInContent,
typeFilteredLinks,
selectedTypes,
);
if (searchInputs != _lastSearchInputs) {
_lastSearchInputs = searchInputs;
final searchKey = buildSelectedLinksSearchKey(
searchQuery: _searchQuery,
searchInContent: _searchInContent,
links: typeFilteredLinks,
selectedLinkTypes: selectedTypes,
);
// Future חדש רק כשהחיפוש השתנה, גם כשהרשימה עצמה הוחלפה.
if (_lastSearchKey != searchKey) {
_lastSearchKey = searchKey;
_filteredLinksFuture = _filterLinksAsync(typeFilteredLinks);
}
}
return AppFutureBuilder<List<Link>>(
future: _filteredLinksFuture,
builder: (context, data) {
final filteredLinks = data;
if (filteredLinks.isEmpty) {
return _buildEmptyMessage('לא נמצאו קישורים התואמים לחיפוש');
}
return ScrollablePositionedListScrollbar(
scrollController: _itemScrollController,
itemCount: filteredLinks.length,
child: ScrollablePositionedList.builder(
itemScrollController: _itemScrollController,
// נבנית מחדש בכל קטע ואין בה scrollTo, ולכן די בחצי מסך. רשימות הקריאה
// צריכות יותר, כדי ש-scrollTo ליעד קרוב יגיע בגלילה חלקה.
cacheExtentScreens: 0.5,
itemCount: filteredLinks.length,
itemBuilder: (context, index) {
final link = filteredLinks[index];
return _buildExpansionTile(link);
},
),
);
},
);
}
Widget _buildEmptyMessage(String message) {
return OtzariaEmptyState(
isCompact: true,
icon: OtzariaIcons.links_24_regular,
title: message,
);
}
/// סדר הדורות אינו תלוי בשאילתה: ממיינים פעם אחת לרשימה ולא בכל הקשה.
Future<List<Link>> _sortedByEra(List<Link> links) async {
if (links.length <= 1) return links;
final eraVersion = CommentaryService.eraCacheVersion;
if (identical(links, _sortedSource) && eraVersion == _sortedEraVersion) {
return _sortedLinks;
}
await CommentaryService.preloadErasForLinks(links);
// מיון ללא דורות הוא זמני. בלי await בין המיון לבדיקה, שניהם רואים
// אותו מטמון גם כשפאנל אחר משלים טעינת דורות במקביל.
final sorted = CommentaryService.sortLinksByEraSync(links);
if (eraVersion == CommentaryService.eraCacheVersion &&
CommentaryService.hasCachedErasForLinks(links)) {
_sortedSource = links;
_sortedEraVersion = eraVersion;
_sortedLinks = sorted;
}
return sorted;
}
/// הכותרת ושם הספר של כל קישור, מוקטנים — פעם אחת לרשימה ממוינת.
List<(String, String)> _searchTextsFor(List<Link> sortedLinks) {
if (!identical(sortedLinks, _searchTextsSource)) {
_searchTextsSource = sortedLinks;
_searchTexts = [
for (final link in sortedLinks)
(
link.heRef.toLowerCase(),
utils.getTitleFromPath(link.path2).toLowerCase(),
),
];
}
return _searchTexts;
}
// פונקציה אסינכרונית לסינון הקישורים עם חיפוש בתוכן
Future<List<Link>> _filterLinksAsync(List<Link> links) async {
_linksWithSearchResults.clear(); // איפוס רשימת הקישורים עם תוצאות
// מיון הקישורים לפי סדר הדורות (כמו במפרשים)
final sortedLinks = await _sortedByEra(links);
if (_searchQuery.isEmpty) {
return sortedLinks;
}
final query = _searchQuery.toLowerCase();
final searchTexts = _searchTextsFor(sortedLinks);
final filteredLinks = <Link>[];
for (var i = 0; i < sortedLinks.length; i++) {
final link = sortedLinks[i];
final (title, bookTitle) = searchTexts[i];
// חיפוש בכותרת ושם הספר
if (title.contains(query) || bookTitle.contains(query)) {
filteredLinks.add(link);
continue;
}
// חיפוש בתוכן אם הופעל
if (_searchInContent) {
String content;
try {
content = await link.content;
} catch (_) {
content = '';
}
// אותו מונה של חיפוש המפרשים: מתעלם מניקוד ומפיסוק כמו כל משטחי
// החיפוש, ותואם את ההדגשה ש-SmartTextWidget מרנדר על אותו תוכן.
// הפענוח קודם לספירה — ` ` בין מילים היה חוסם ביטוי שהמשתמש רואה
// כרווח רגיל.
final matches = countCommentarySearchMatches(
content: utils.stripHtmlIfNeeded(content),
query: _searchQuery,
displayProfile: widget.displayProfile,
partialWordMatch: true,
);
if (matches > 0) {
final instanceKey = buildSelectedLinkInstanceKey(link);
filteredLinks.add(link);
_linksWithSearchResults.add(instanceKey); // מסמן שיש תוצאות בתוכן
_cacheLinkContent(buildSelectedLinkContentKey(link), link);
// פותח אוטומטית את הקישור הראשון עם תוצאות
if (_linksWithSearchResults.length == 1) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
setState(() {
_expanded[instanceKey] = true;
});
}
});
}
}
}
}
return filteredLinks;
}
Widget _buildExpansionTile(Link link) {
final instanceKey = buildSelectedLinkInstanceKey(link);
final contentKey = buildSelectedLinkContentKey(link);
final restoredExpanded =
PageStorage.maybeOf(context)?.readState(
context,
identifier: instanceKey,
)
as bool?;
final isExpanded = _expanded[instanceKey] ?? restoredExpanded ?? false;
return ExpansionTile(
key: PageStorageKey(instanceKey),
initiallyExpanded: isExpanded,
maintainState: true,
showTrailingIcon: false,
// ברירת המחדל של ExpansionTile היא גבול עליון *וגם* תחתון בעובי 1.0
// לוגי — קו כפול בין שני פריטים פתוחים. תחתון בלבד בעובי 0 (hairline),
// כעובי ה-Divider שבפאנל המפרשים.
shape: Border(
bottom: BorderSide(color: Theme.of(context).dividerColor, width: 0),
),
leading: ExpandingChevron(
isExpanded: isExpanded,
style: ExpandingChevronStyle.tree,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
title: BlocBuilder<SettingsBloc, SettingsState>(
builder: (context, settingsState) {
String displayTitle = utils.getTitleFromPath(link.path2);
if (settingsState.replaceHolyNames) {
displayTitle = utils.replaceHolyNames(
displayTitle,
style: settingsState.holyNameStyle,
);
}
return Text(
displayTitle,
style: TextStyle(
fontSize: settingsState.commentatorsFontSize - 2,
fontWeight: FontWeight.bold,
fontVariations: AppFonts.boldFontVariations(
settingsState.commentatorsFontFamily,
),
fontFamily: AppFonts.renderFontFamily(
settingsState.commentatorsFontFamily,
),
),
);
},
),
subtitle: BlocBuilder<SettingsBloc, SettingsState>(
builder: (context, settingsState) {
// קישור עם עוגן-מילה: אות הסימון שבגוף הטקסט מוצגת לפני ההפניה.
var markerPrefix = '';
if (link.anchorStart != null) {
final markerText = anchorMarkerText(link);
if (markerText != null) markerPrefix = '$markerText ';
}
final rawFallback = settingsState.replaceHolyNames
? utils.replaceHolyNames(
link.fallbackDisplayReference,
style: settingsState.holyNameStyle,
)
: link.fallbackDisplayReference;
if (!isExpanded) {
return Text(
markerPrefix + rawFallback,
style: TextStyle(
fontSize: settingsState.commentatorsFontSize - 4,
fontWeight: FontWeight.normal,
fontFamily: AppFonts.renderFontFamily(
settingsState.commentatorsFontFamily,
),
color: Theme.of(context).colorScheme.onSurface.withAlpha(128),
),
);
}
return FutureBuilder<String>(
future: link.displayReference,
initialData: rawFallback,
builder: (context, snapshot) {
String displaySubtitle =
markerPrefix + (snapshot.data ?? rawFallback);
if (settingsState.replaceHolyNames) {
displaySubtitle = utils.replaceHolyNames(
displaySubtitle,
style: settingsState.holyNameStyle,
);
}
return Text(
displaySubtitle,
style: TextStyle(
fontSize: settingsState.commentatorsFontSize - 4,
fontWeight: FontWeight.normal,
fontFamily: AppFonts.renderFontFamily(
settingsState.commentatorsFontFamily,
),
color: Theme.of(context).colorScheme.onSurface.withAlpha(128),
),
);
},
);
},
),
onExpansionChanged: (isExpanded) {
// כשל נשאר מוצג עד פתיחה מפורשת נוספת, בלי לולאת retry ברקע.
if (isExpanded &&
(!_contentCache.containsKey(contentKey) ||
_failedContentKeys.contains(contentKey))) {
_cacheLinkContent(contentKey, link);
}
// עדכון מצב ההרחבה עם setState בטוח - דוחה עד אחרי הבנייה
if (_expanded[instanceKey] != isExpanded) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
setState(() {
_expanded[instanceKey] = isExpanded;
});
}
});
}
},
children: [
if (isExpanded)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 8.0,
),
child: AppFutureBuilder<String>(
future: _contentCache[contentKey],
// קישור פתוח שנבנה מחדש בגלילה: שלד טעינה מקצר אותו לפריים אחד,
// והגדילה אחריו דוחפת את הרשימה.
initialData: _loadedContent[contentKey],
builder: (context, content) => _buildLinkContent(content, link),
errorBuilder: (context, error) =>
BlocBuilder<SettingsBloc, SettingsState>(
builder: (context, settingsState) {
return Text(
'שגיאה בטעינת התוכן: $error',
style: TextStyle(
color: Theme.of(context).colorScheme.error,
fontSize: settingsState.commentatorsFontSize,
),
);
},
),
),
),
],
);
}
void _cacheLinkContent(String key, Link link) {
final pending = link.content;
_failedContentKeys.remove(key);
_loadedContent.remove(key);
_contentCache[key] = pending;
void failed() {
if (identical(_contentCache[key], pending)) _failedContentKeys.add(key);
}
// פינוי מיידי היה מציג future=null אם הכשל הקדים את פריים ההרחבה.
pending.then<void>((value) {
if (identical(_contentCache[key], pending)) _loadedContent[key] = value;
if (value.startsWith('שגיאה')) failed();
}, onError: (Object _) => failed());
}
Widget _buildLinkContent(String content, Link link) {
if (content.isEmpty) {
return BlocBuilder<SettingsBloc, SettingsState>(
builder: (context, settingsState) {
return Text(
'אין תוכן זמין',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface.withAlpha(150),
fontSize: settingsState.commentatorsFontSize,
),
);
},
);
}
// יירוט Ctrl+C ממוקם *מעל* ה-SelectionArea — שם מנגנון ה-override של
// CopySelectionTextIntent מאתר אותו (מתחתיו הוא נשאר בלתי-נראה).
return SelectionCopyShortcuts(
onCopy: () => ContextMenuUtils.copyFormattedText(
context: context,
savedSelectedText: _savedSelectedText,
fontSize: widget.fontSize,
link: _savedSelectedLink,
),
child: RtlSelectionShortcuts(
child: SelectionArea(
key: ValueKey(
'selected_link_${buildSelectedLinkInstanceKey(link)}_$_selectionRevision',
),
contextMenuBuilder: (context, selectableRegionState) {
return const SizedBox.shrink();
},
onSelectionChanged: (selection) {
// עדכון מעקב כיוון הגרירה (ל-RtlSelectionShortcuts).
trackRtlSelection(selection?.plainText);
// שינוי בחירה זמני בזמן priming — לא לעבד.
if (rtlSelectionPriming) return;
if (selection != null && selection.plainText.isNotEmpty) {
widget.selectionSyncController?.activate(_selectionOwner);
_savedSelectedText = selection.plainText;
_savedSelectedLink = link;
} else if (selection == null ||
selection.plainText.trim().isEmpty) {
widget.selectionSyncController?.clear(_selectionOwner);
_savedSelectedText = null;
_savedSelectedLink = null;
}
},
child: AppContextMenuRegion(
// ריחוף מקדים את טעינת קישורי קטע היעד, כדי שהתפריט ייבנה עם
// נתונים מוכנים. הלחיצה הימנית מכסה מגע/עט, שאין בהם ריחוף.
onHoverEnter: () =>
TargetLineLinksService.instance.prefetchOnHover(link),
onSecondaryTapDown: (_) =>
TargetLineLinksService.instance.prefetch(link),
// לחיצה ימנית על הטקסט המסומן בפועל לא תשחרר את הבחירה (התנהגות ברירת
// המחדל של SelectableRegion ב-Windows); לחיצה על חלק לא-מסומן מבטלת
// כרגיל. הבחירה מנוהלת ע"י SelectionArea פר-קישור, לכן מחשבים את קטע
// הבחירה ישירות מול הפסקה שעליה לחצו.
shouldPreserveSelectionOnSecondaryTap: (globalPosition) {
final selected = _savedSelectedText;
if (selected == null || selected.isEmpty) return false;
final root = context.findRenderObject();
if (root == null) return true; // סלחני
return clickIsOnSelectionWithinArea(
root: root,
globalPosition: globalPosition,
selectedText: selected,
) ??
true; // לא הוכרע — סלחני
},
menuBuilder: (menuCtx, _) =>
ContextMenuUtils.buildCommentaryContextMenu(
context: menuCtx,
link: link,
openBookCallback: widget.openBookCallback,
fontSize: widget.fontSize,
displayProfile: widget.displayProfile,
copyDisplayProfile: widget.copyDisplayProfile,
savedSelectedText: _savedSelectedText,
onNavigateToLink: _navigateToLink,
onCopySelected: () => ContextMenuUtils.copyFormattedText(
context: menuCtx,
savedSelectedText: _savedSelectedText,
fontSize: widget.fontSize,
link: _savedSelectedLink,