forked from flutter/devtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.dart
1568 lines (1362 loc) · 48.8 KB
/
search.dart
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
// Copyright 2020 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd.
import 'dart:async';
import 'dart:math';
import 'package:async/async.dart';
import 'package:devtools_app_shared/ui.dart';
import 'package:devtools_app_shared/utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:logging/logging.dart';
import '../primitives/trees.dart';
import '../primitives/utils.dart';
import '../ui/utils.dart';
import '../utils/utils.dart';
import 'colors.dart';
import 'common_widgets.dart';
// TODO(https://github.com/flutter/devtools/issues/5416): break this file up
// into managable pieces.
/// Top 10 matches to display in auto-complete overlay.
const defaultTopMatchesLimit = 10;
int topMatchesLimit = defaultTopMatchesLimit;
final _log = Logger('packages/devtools_app/lib/src/shared/ui/search');
mixin SearchControllerMixin<T extends SearchableDataMixin> {
final _searchNotifier = ValueNotifier<String>('');
final _searchInProgress = ValueNotifier<bool>(false);
/// Notify that the search has changed.
ValueListenable<String> get searchNotifier => _searchNotifier;
ValueListenable<bool> get searchInProgressNotifier => _searchInProgress;
CancelableOperation<void>? _searchOperation;
Timer? _searchDebounce;
set search(String value) {
final previousSearchValue = _searchNotifier.value;
final shouldSearchPreviousMatches =
previousSearchValue.isNotEmpty &&
value.caseInsensitiveContains(previousSearchValue);
_searchNotifier.value = value;
refreshSearchMatches(searchPreviousMatches: shouldSearchPreviousMatches);
}
set searchInProgress(bool searchInProgress) {
_searchInProgress.value = searchInProgress;
}
String get search => _searchNotifier.value;
bool get isSearchInProgress => _searchInProgress.value;
final _searchMatches = ValueNotifier<List<T>>([]);
ValueListenable<List<T>> get searchMatches => _searchMatches;
/// Delay to reduce the amount of search queries
/// Duration.zero (default) disables debounce
Duration? get debounceDelay => null;
/// Text field controller for the [SearchField] that this instance of
/// [SearchControllerMixin] controls.
SearchTextEditingController get searchTextFieldController =>
_searchTextFieldController!;
SearchTextEditingController? _searchTextFieldController;
/// Focus node for the [SearchField] that this instance of
/// [SearchControllerMixin] controls.
FocusNode? get searchFieldFocusNode => _searchFieldFocusNode;
FocusNode? _searchFieldFocusNode;
void refreshSearchMatches({bool searchPreviousMatches = false}) {
if (_searchNotifier.value.isNotEmpty) {
if (debounceDelay != null) {
_startDebounceTimer(
search,
searchPreviousMatches: searchPreviousMatches,
);
} else {
final matches = matchesForSearch(
_searchNotifier.value,
searchPreviousMatches: searchPreviousMatches,
);
_updateMatches(matches);
}
} else {
_updateMatches(<T>[]);
}
}
void _startDebounceTimer(
String search, {
required bool searchPreviousMatches,
}) {
searchInProgress = true;
if (_searchDebounce?.isActive ?? false) {
_searchDebounce!.cancel();
}
assert(debounceDelay != null);
_searchDebounce = Timer(
search.isEmpty ? Duration.zero : debounceDelay!,
() async {
// Abort any ongoing search operations and start a new one
try {
await _searchOperation?.cancel();
} catch (e, st) {
_log.shout(e, e, st);
}
searchInProgress = true;
// Start new search operation
final future = Future(() {
return matchesForSearch(
_searchNotifier.value,
searchPreviousMatches: searchPreviousMatches,
);
}).then((matches) {
searchInProgress = false;
_updateMatches(matches);
});
_searchOperation = CancelableOperation.fromFuture(future);
await _searchOperation!.value;
searchInProgress = false;
},
);
}
void _updateMatches(List<T> matches) {
for (final previousMatch in _searchMatches.value) {
previousMatch.isSearchMatch = false;
}
for (final newMatch in matches) {
newMatch.isSearchMatch = true;
}
if (matches.isEmpty) {
matchIndex.value = 0;
}
if (matches.isNotEmpty && matchIndex.value == 0) {
matchIndex.value = 1;
}
_searchMatches.value = matches;
_updateActiveSearchMatch();
}
final _activeSearchMatch = ValueNotifier<T?>(null);
ValueListenable<T?> get activeSearchMatch => _activeSearchMatch;
/// 1-based index used for displaying matches status text (e.g. "2 / 15")
final matchIndex = ValueNotifier<int>(0);
void previousMatch() {
var previousMatchIndex = matchIndex.value - 1;
if (previousMatchIndex < 1) {
previousMatchIndex = _searchMatches.value.length;
}
matchIndex.value = previousMatchIndex;
_updateActiveSearchMatch();
}
void nextMatch() {
var nextMatchIndex = matchIndex.value + 1;
if (nextMatchIndex > _searchMatches.value.length) {
nextMatchIndex = 1;
}
matchIndex.value = nextMatchIndex;
_updateActiveSearchMatch();
}
void _updateActiveSearchMatch() {
// [matchIndex] is 1-based. Subtract 1 for the 0-based list [searchMatches].
int activeMatchIndex = matchIndex.value - 1;
if (activeMatchIndex < 0) {
_activeSearchMatch.value?.isActiveSearchMatch = false;
_activeSearchMatch.value = null;
return;
}
if (searchMatches.value.isNotEmpty &&
activeMatchIndex >= searchMatches.value.length) {
activeMatchIndex = 0;
matchIndex.value = 1; // first item because [matchIndex] us 1-based
}
_activeSearchMatch.value?.isActiveSearchMatch = false;
_activeSearchMatch.value =
searchMatches.value[activeMatchIndex]..isActiveSearchMatch = true;
onMatchChanged(activeMatchIndex);
}
/// The data that should be searched through when [matchesForSearch] is
/// called.
///
/// If [matchesForSearch] is overridden in such a way that
/// [currentDataToSearchThrough] is not used, then this getter does not need
/// to be implemented.
Iterable<T> get currentDataToSearchThrough =>
throw UnimplementedError(
'Implement this getter in order to use the default'
' [matchesForSearch] behavior.',
);
/// Default search matching logic.
///
/// The use of this method requires both [currentDataToSearchThrough] and
/// [T.matchesSearchToken] to be implemented.
List<T> matchesForSearch(
String search, {
bool searchPreviousMatches = false,
}) {
if (search.isEmpty) return <T>[];
final regexSearch = RegExp(search, caseSensitive: false);
final matches = <T>[];
if (searchPreviousMatches) {
final previousMatches = searchMatches.value;
for (final previousMatch in previousMatches) {
if (previousMatch.matchesSearchToken(regexSearch)) {
matches.add(previousMatch);
}
}
} else {
final searchData = currentDataToSearchThrough;
for (final data in searchData) {
if (data.matchesSearchToken(regexSearch)) {
matches.add(data);
}
}
}
return matches;
}
/// Called when selected match index changes. Index is 0 based
// Subclasses provide a valid implementation.
// ignore: avoid-unused-parameters
void onMatchChanged(int index) {}
void resetSearch() {
_searchNotifier.value = '';
_searchTextFieldController?.clear();
refreshSearchMatches();
}
@mustCallSuper
void initSearch() {
_searchTextFieldController?.dispose();
_searchFieldFocusNode?.dispose();
_searchTextFieldController =
SearchTextEditingController()..text = _searchNotifier.value;
_searchFieldFocusNode = FocusNode(debugLabel: 'search-field');
}
@mustCallSuper
void disposeSearch() {
unawaited(_searchOperation?.cancel());
if (_searchDebounce?.isActive ?? false) {
_searchDebounce!.cancel();
}
_searchTextFieldController?.dispose();
_searchFieldFocusNode?.dispose();
_searchTextFieldController = null;
_searchFieldFocusNode = null;
}
}
class AutoComplete extends StatefulWidget {
/// [controller] AutoCompleteController to associate with this pop-up.
/// [searchFieldKey] global key of the TextField to associate with the
/// auto-complete.
/// [onTap] method to call when item in drop-down list is tapped.
/// [bottom] display drop-down below (true) the TextField or above (false)
/// the TextField.
const AutoComplete(
this.controller, {
super.key,
required this.searchFieldKey,
required this.onTap,
bool bottom = true, // If false placed above.
bool maxWidth = true,
}) : isBottom = bottom,
isMaxWidth = maxWidth;
final AutoCompleteSearchControllerMixin controller;
final GlobalKey searchFieldKey;
final SelectAutoComplete onTap;
final bool isBottom;
final bool isMaxWidth;
@override
AutoCompleteState createState() => AutoCompleteState();
}
class AutoCompleteState extends State<AutoComplete> with AutoDisposeMixin {
@override
void didChangeDependencies() {
super.didChangeDependencies();
final autoComplete = context.widget as AutoComplete;
final controller = autoComplete.controller;
final searchFieldKey = autoComplete.searchFieldKey;
final onTap = autoComplete.onTap;
final bottom = autoComplete.isBottom;
final isMaxWidth = autoComplete.isMaxWidth;
addAutoDisposeListener(controller.searchAutoCompleteNotifier, () {
controller.handleAutoCompleteOverlay(
context: context,
searchFieldKey: searchFieldKey,
onTap: onTap,
bottom: bottom,
maxWidth: isMaxWidth,
);
});
}
@override
Widget build(BuildContext context) {
final autoComplete = context.widget as AutoComplete;
final controller = autoComplete.controller;
final searchFieldKey = autoComplete.searchFieldKey;
final bottom = autoComplete.isBottom;
final isMaxWidth = autoComplete.isMaxWidth;
final searchAutoComplete = controller.searchAutoComplete;
final colorScheme = Theme.of(context).colorScheme;
final autoCompleteTextStyle = Theme.of(
context,
).regularTextStyle.copyWith(color: colorScheme.contrastTextColor);
final autoCompleteHighlightedTextStyle = Theme.of(
context,
).regularTextStyle.copyWith(fontWeight: FontWeight.bold);
final tileContents =
searchAutoComplete.value
.map(
(match) => _maybeHighlightMatchText(
match,
autoCompleteTextStyle,
autoCompleteHighlightedTextStyle,
),
)
.toList();
// When there are no tiles present, we don't need to display the
// auto complete list.
if (tileContents.isEmpty) return const SizedBox.shrink();
final tileEntryHeight =
tileContents.isEmpty
? 0.0
: calculateTextSpanHeight(tileContents.first) + denseSpacing;
// Find the searchField and place overlay below bottom of TextField and
// make overlay width of TextField. This is also we decide the height of
// the ListTile height, position above (if bottom is false).
final box = searchFieldKey.currentContext!.findRenderObject() as RenderBox;
// Compute to global coordinates.
final offset = box.localToGlobal(Offset.zero);
final areaHeight = offset.dy;
final maxAreaForPopup = areaHeight - tileEntryHeight;
// TODO(terry): Scrolling doesn't work so max popup height is also total
// matches to use.
topMatchesLimit =
min(
defaultTopMatchesLimit,
(maxAreaForPopup / tileEntryHeight) - 1, // zero based.
).truncate();
// Total tiles visible.
final totalTiles =
bottom
? searchAutoComplete.value.length
: (maxAreaForPopup / tileEntryHeight).truncateToDouble();
final autoCompleteTiles = <AutoCompleteTile>[];
final count = min(searchAutoComplete.value.length, totalTiles);
for (var index = 0; index < count; index++) {
final textSpan = tileContents[index];
autoCompleteTiles.add(
AutoCompleteTile(
index: index,
textSpan: textSpan,
controller: controller,
onTap: autoComplete.onTap,
highlightColor: colorScheme.autoCompleteHighlightColor,
defaultColor: colorScheme.defaultBackgroundColor,
),
);
}
// Compute the Y position of the popup (auto-complete list). Its bottom
// will be positioned at the top of the text field. Add 1 includes
// the TextField border.
final yCoord =
bottom ? 0.0 : -((count * tileEntryHeight) + box.size.height + 1);
final xCoord = controller.xPosition;
return Positioned(
key: searchAutoCompleteKey,
width:
isMaxWidth
? box.size.width
: AutoCompleteSearchControllerMixin.minPopupWidth,
height: count * tileEntryHeight,
child: CompositedTransformFollower(
link: controller.autoCompleteLayerLink,
showWhenUnlinked: false,
targetAnchor: Alignment.bottomLeft,
offset: Offset(xCoord, yCoord),
child: Material(
elevation: defaultElevation,
child: TextFieldTapRegion(
child: ListView(
padding: EdgeInsets.zero,
itemExtent: tileEntryHeight,
children: autoCompleteTiles,
),
),
),
),
);
}
TextSpan _maybeHighlightMatchText(
AutoCompleteMatch match,
TextStyle regularTextStyle,
TextStyle highlightedTextStyle,
) {
return match.transformAutoCompleteMatch<TextSpan>(
transformMatchedSegment:
(segment) => TextSpan(text: segment, style: highlightedTextStyle),
transformUnmatchedSegment:
(segment) => TextSpan(text: segment, style: regularTextStyle),
combineSegments:
(segments) => TextSpan(
text: segments.first.text,
style: segments.first.style,
children: segments.sublist(1),
),
);
}
}
class AutoCompleteTile extends StatelessWidget {
const AutoCompleteTile({
super.key,
required this.textSpan,
required this.index,
required this.controller,
required this.onTap,
required this.highlightColor,
required this.defaultColor,
});
final TextSpan textSpan;
final int index;
final AutoCompleteSearchControllerMixin controller;
final SelectAutoComplete onTap;
final Color highlightColor;
final Color defaultColor;
@override
Widget build(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
onHover: (_) {
controller.setCurrentHoveredIndexValue(index);
},
child: GestureDetector(
onTap: () {
final selected = textSpan.toPlainText();
controller.selectTheSearch = true;
controller.search = selected;
onTap(selected);
},
child: ValueListenableBuilder(
valueListenable: controller.currentHoveredIndex,
builder: (context, currentHoveredIndex, _) {
return Container(
color:
currentHoveredIndex == index ? highlightColor : defaultColor,
padding: const EdgeInsets.symmetric(horizontal: denseSpacing),
alignment: Alignment.centerLeft,
child: Text.rich(textSpan, maxLines: 1),
);
},
),
),
);
}
}
const searchAutoCompleteKeyName = 'SearchAutoComplete';
@visibleForTesting
final searchAutoCompleteKey = GlobalKey(debugLabel: searchAutoCompleteKeyName);
/// Parts of active editing for auto-complete.
class EditingParts {
EditingParts({
required this.activeWord,
required this.leftSide,
required this.rightSide,
});
final String activeWord;
final String leftSide;
final String rightSide;
bool get isField => leftSide.endsWith('.');
}
/// Parsing characters looking for valid names e.g.,
/// [ _ | a..z | A..Z ] [ _ | a..z | A..Z | 0..9 ]+
const asciiSpace = 32;
const ascii0 = 48;
const ascii9 = 57;
const asciiUnderscore = 95;
const asciiA = 65;
const asciiZ = 90;
const asciia = 97;
const asciiz = 122;
mixin AutoCompleteSearchControllerMixin on SearchControllerMixin {
final selectTheSearchNotifier = ValueNotifier<bool>(false);
bool get selectTheSearch => selectTheSearchNotifier.value;
/// Search is very dynamic, with auto-complete or programmatic searching,
/// setting the value to true will fire off searching.
set selectTheSearch(bool v) {
selectTheSearchNotifier.value = v;
}
final searchAutoComplete = ValueNotifier<List<AutoCompleteMatch>>([]);
ValueListenable<List<AutoCompleteMatch>> get searchAutoCompleteNotifier =>
searchAutoComplete;
/// Layer links autoComplete popup to the search TextField widget.
final autoCompleteLayerLink = LayerLink();
OverlayEntry? autoCompleteOverlay;
ValueListenable<int> get currentHoveredIndex => _currentHoveredIndex;
final _currentHoveredIndex = ValueNotifier<int>(0);
String? get currentHoveredText =>
searchAutoComplete.value.isNotEmpty
? searchAutoComplete.value[currentHoveredIndex.value].text
: null;
/// Last X position of caret in search field, used for pop-up position.
double xPosition = 0.0;
ValueListenable<String?> get currentSuggestion => _currentSuggestionNotifier;
final _currentSuggestionNotifier = ValueNotifier<String?>(null);
static const minPopupWidth = 300.0;
/// Key used to find the search text field for positioning the auto complete
/// overlay.
GlobalKey get searchFieldKey;
/// [FocusNode] for the keyboard listener responsible for handling auto
/// complete search.
FocusNode get autocompleteFocusNode => _autocompleteFocusNode!;
FocusNode? _autocompleteFocusNode;
@override
void initSearch() {
super.initSearch();
_autocompleteFocusNode?.dispose();
_autocompleteFocusNode = FocusNode(debugLabel: 'search-keyboard');
}
@override
void disposeSearch() {
_autocompleteFocusNode?.dispose();
_autocompleteFocusNode = null;
super.disposeSearch();
}
void setCurrentHoveredIndexValue(int index) {
_currentHoveredIndex.value = index;
}
void clearSearchAutoComplete() {
searchAutoComplete.value = [];
// Default index is 0.
setCurrentHoveredIndexValue(0);
}
void updateCurrentSuggestion(String activeWord) {
final hoveredText = currentHoveredText;
final suggestion = hoveredText?.substring(
min(activeWord.length, hoveredText.length),
);
if (suggestion == null || suggestion.isEmpty) {
clearCurrentSuggestion();
return;
}
_currentSuggestionNotifier.value = suggestion;
}
void clearCurrentSuggestion() {
_currentSuggestionNotifier.value = null;
}
/// [bottom] if false placed above TextField (search field).
/// [maxWidth] if true drop-down is width of TextField otherwise minPopupWidth.
OverlayEntry createAutoCompleteOverlay({
required GlobalKey searchFieldKey,
required SelectAutoComplete onTap,
bool bottom = true,
bool maxWidth = true,
}) {
return OverlayEntry(
builder: (context) {
return AutoComplete(
this,
searchFieldKey: searchFieldKey,
onTap: onTap,
bottom: bottom,
maxWidth: maxWidth,
);
},
);
}
void closeAutoCompleteOverlay() {
autoCompleteOverlay?.remove();
autoCompleteOverlay = null;
}
/// Helper setState callback when searchAutoCompleteNotifier changes, usage:
///
/// addAutoDisposeListener(controller.searchAutoCompleteNotifier, () {
/// setState(autoCompleteOverlaySetState(controller, context));
/// });
void handleAutoCompleteOverlay({
required BuildContext context,
required GlobalKey searchFieldKey,
required SelectAutoComplete onTap,
bool bottom = true,
bool maxWidth = true,
}) {
if (autoCompleteOverlay != null) {
closeAutoCompleteOverlay();
}
autoCompleteOverlay = createAutoCompleteOverlay(
searchFieldKey: searchFieldKey,
onTap: onTap,
bottom: bottom,
maxWidth: maxWidth,
);
Overlay.of(context).insert(autoCompleteOverlay!);
}
/// Until an expression parser, poor man's way of finding the parts for
/// auto-complete.
///
/// Returns the parts of the editing area e.g.,
///
/// caret
/// ↓
/// addOne.yName + 1000 + myChart.tra┃
/// |_____________________________|_|
/// ↑ ↑
/// leftSide activeWord
///
/// activeWord is "tra"
/// leftSide is "addOne.yName + 1000 + myChart."
/// rightSide is "". RightSide isNotEmpty if caret is not
/// at the end the end TxtField value. If the
/// caret is within the text e.g.,
///
/// caret
/// ↓
/// controller.cl┃ + 1000 + myChart.tra
///
/// activeWord is "cl"
/// leftSide is "controller."
/// rightSide is " + 1000 + myChart.tra"
static EditingParts activeEditingParts(
String editing,
TextSelection selection, {
bool handleFields = false,
}) {
String activeWord = '';
String leftSide = '';
String rightSide = '';
final startSelection = selection.start;
if (startSelection != -1 && startSelection == selection.end) {
final selectionValue = editing.substring(0, startSelection);
var lastSpaceIndex = selectionValue.lastIndexOf(handleFields ? '.' : ' ');
lastSpaceIndex = lastSpaceIndex >= 0 ? lastSpaceIndex + 1 : 0;
activeWord = selectionValue.substring(lastSpaceIndex, startSelection);
var variableStart = -1;
// Validate activeWord is really a word.
for (var index = activeWord.length - 1; index >= 0; index--) {
final char = activeWord.codeUnitAt(index);
if (char >= ascii0 && char <= ascii9) {
// Keep gobbling # assuming might be part of variable name.
continue;
} else if (char == asciiUnderscore ||
(char >= asciiA && char <= asciiZ) ||
(char >= asciia && char <= asciiz)) {
variableStart = index;
} else if (variableStart == -1) {
// Never had a variable start.
lastSpaceIndex += activeWord.length;
activeWord = selectionValue.substring(
lastSpaceIndex - 1,
startSelection - 1,
);
break;
} else {
lastSpaceIndex += variableStart;
activeWord = selectionValue.substring(lastSpaceIndex, startSelection);
break;
}
}
leftSide = selectionValue.substring(0, lastSpaceIndex);
rightSide = editing.substring(startSelection);
}
return EditingParts(
activeWord: activeWord,
leftSide: leftSide,
rightSide: rightSide,
);
}
void clearSearchField({bool force = false}) {
if (force || search.isNotEmpty) {
resetSearch();
closeAutoCompleteOverlay();
}
}
void updateSearchField({
required String newValue,
required int caretPosition,
}) {
searchTextFieldController
..text = newValue
..selection = TextSelection.collapsed(offset: caretPosition);
}
}
mixin SearchableMixin<T> {
List<T> searchMatches = [];
T? activeSearchMatch;
}
/// Callback when item in the drop-down list is selected.
typedef SelectAutoComplete = void Function(String selection);
/// Callback to handle highlighting item in the drop-down list.
typedef HighlightAutoComplete =
void Function(
AutoCompleteSearchControllerMixin controller,
bool directionDown,
);
/// Provided by clients to specify where the autocomplete overlay should be
/// positioned relative to the input text.
typedef OverlayXPositionBuilder =
double Function(String inputValue, TextStyle? inputStyle);
class SearchTextEditingController extends TextEditingController {
String? _suggestionText;
String? get suggestionText {
if (_suggestionText == null) return null;
if (selection.end < text.length) return null;
return _suggestionText;
}
set suggestionText(String? suggestionText) {
_suggestionText = suggestionText;
notifyListeners();
}
bool get isAtEnd => text.length <= selection.end;
@override
TextSpan buildTextSpan({
required BuildContext context,
TextStyle? style,
required bool withComposing,
}) {
if (suggestionText == null) {
// If no `suggestionText` is provided, use the default implementation of `buildTextSpan`
return super.buildTextSpan(
context: context,
style: style,
withComposing: withComposing,
);
}
return TextSpan(
children: [
TextSpan(text: text),
TextSpan(
text: suggestionText,
style: style?.copyWith(color: Theme.of(context).colorScheme.grey),
),
],
style: style,
);
}
}
/// Mixin for managing search field lifecycle.
///
/// This should be mixed into any [State] class that builds [SearchField] or
/// [AutoCompleteSearchField].
mixin SearchFieldMixin<T extends StatefulWidget>
on AutoDisposeMixin<T>, State<T> {
SearchControllerMixin get searchController;
@override
void initState() {
super.initState();
// ignore: avoid-unrelated-type-assertions, false positive.
if (this is ProvidedControllerMixin) {
// Controllers provided through package:provider will not be ready until
// [didChangeDependencies] is called, so ensure [searchController] is
// ready before calling [searchController.initSearch].
(this as ProvidedControllerMixin).callWhenControllerReady((_) {
searchController.initSearch();
});
} else {
searchController.initSearch();
}
}
@override
void dispose() {
searchController.disposeSearch();
super.dispose();
}
}
/// A stateful text field with search capability.
///
/// [_SearchFieldState] automatically handles the lifecycle of the search field
/// through the [SearchFieldMixin].
///
/// Use this widget for simple use cases where the elements initialized and
/// disposed in [SearchControllerMixin.initSearch] and
/// [SearchControllerMixin.disposeSearch] are not used outside of the context
/// of the search code.
///
/// If these elements need to be used by the widget state that builds the search
/// field, consider using [StatelessSearchField] instead and manually mixing in
/// [SearchFieldMixin] so that you can manage the lifecycle properly.
class SearchField<T extends SearchControllerMixin> extends StatefulWidget {
SearchField({
required this.searchController,
this.searchFieldEnabled = true,
this.shouldRequestFocus = false,
this.supportsNavigation = true,
this.onClose,
this.searchFieldWidth = defaultSearchFieldWidth,
double? searchFieldHeight,
int? maxLines = 1,
super.key,
}) : assert(maxLines != 0, "'maxLines' must not be 0"),
searchFieldHeight = searchFieldHeight ?? defaultTextFieldHeight,
_maxLines = maxLines;
final T searchController;
final double searchFieldWidth;
final double searchFieldHeight;
/// Whether the search text field should be enabled.
final bool searchFieldEnabled;
/// Whether the search text field should automatically request focus once it
/// is built.
final bool shouldRequestFocus;
/// Whether this search field includes navigation controls for traversing
/// search results.
final bool supportsNavigation;
/// Optional callback called when the search field suffix close action is
/// triggered.
final VoidCallback? onClose;
/// The maximum number of lines, by default one.
///
/// Can be set to null to remove the restriction; must not be zero.
final int? _maxLines;
@override
State<SearchField> createState() => _SearchFieldState();
}
class _SearchFieldState extends State<SearchField>
with AutoDisposeMixin, SearchFieldMixin {
@override
SearchControllerMixin get searchController => widget.searchController;
@override
Widget build(BuildContext context) {
final searchField = StatelessSearchField(
controller: searchController,
searchFieldEnabled: widget.searchFieldEnabled,
shouldRequestFocus: widget.shouldRequestFocus,
supportsNavigation: widget.supportsNavigation,
onClose: widget.onClose,
searchFieldHeight: widget.searchFieldHeight,
maxLines: widget._maxLines,
);
return widget._maxLines != 1
? searchField
: SizedBox(
width: widget.searchFieldWidth,
height: widget.searchFieldHeight,
child: searchField,
);
}
}
/// A stateless text field with search capability.
///
/// The widget that builds [StatelessSearchField] is responsible for mixing in
/// [SearchFieldMixin], which manages the search field lifecycle.
///
/// Use this widget for use cases where the default state management that
/// [SearchField] provides is not sufficient for the use case. This can be the
/// case when the elements initialized and disposed in
/// [SearchControllerMixin.initSearch] and [SearchControllerMixin.disposeSearch]
/// need to be accessed outside of the context of the search code.
class StatelessSearchField<T extends SearchableDataMixin>
extends StatelessWidget {
const StatelessSearchField({
super.key,
required this.controller,
required this.searchFieldEnabled,
required this.shouldRequestFocus,
this.searchFieldKey,
this.label,
this.decoration,
this.supportsNavigation = false,
this.onClose,
this.onChanged,
this.prefix,
this.suffix,
this.style,
this.searchFieldHeight,
int? maxLines = 1,
}) : assert(maxLines != 0, "'maxLines' must not be 0"),
_maxLines = maxLines;
final SearchControllerMixin<T> controller;
/// Whether the search text field should be enabled.
final bool searchFieldEnabled;
/// Whether the search text field should automatically request focus once it
/// is built.
final bool shouldRequestFocus;
/// Whether this search field includes navigation controls for traversing
/// search results.