-
Notifications
You must be signed in to change notification settings - Fork 534
/
Copy pathmulti_trigger_autocomplete.dart
484 lines (419 loc) · 15.4 KB
/
multi_trigger_autocomplete.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
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_portal/flutter_portal.dart';
import 'autocomplete_query.dart';
import 'autocomplete_trigger.dart';
/// The type of the Autocomplete callback which returns the widget that
/// contains the input [TextField] or [TextFormField].
///
/// See also:
///
/// * [RawAutocomplete.fieldViewBuilder], which is of this type.
typedef MultiTriggerAutocompleteFieldViewBuilder = Widget Function(
BuildContext context,
TextEditingController textEditingController,
FocusNode focusNode,
);
/// Positions the [AutocompleteTrigger] options around the [TextField] or
/// [TextFormField] that triggered the autocomplete.
enum OptionsAlignment {
/// Positions the options to the top of the field.
top,
/// Positions the options to the bottom of the field.
bottom,
/// Positions the options to the top left of the field.
topStart,
/// Positions the options to the top right of the field.
topEnd,
/// Positions the options to the bottom left of the field.
bottomStart,
/// Positions the options to the bottom right of the field.
bottomEnd;
Anchor _toAnchor({double? widthFactor = 1.0}) {
switch (this) {
case OptionsAlignment.top:
return Aligned(
widthFactor: widthFactor,
follower: Alignment.bottomCenter,
target: Alignment.topCenter,
);
case OptionsAlignment.bottom:
return Aligned(
widthFactor: widthFactor,
follower: Alignment.topCenter,
target: Alignment.bottomCenter,
);
case OptionsAlignment.topStart:
return Aligned(
widthFactor: widthFactor,
follower: Alignment.bottomLeft,
target: Alignment.topLeft,
);
case OptionsAlignment.topEnd:
return Aligned(
widthFactor: widthFactor,
follower: Alignment.bottomRight,
target: Alignment.topRight,
);
case OptionsAlignment.bottomStart:
return Aligned(
widthFactor: widthFactor,
follower: Alignment.topLeft,
target: Alignment.bottomLeft,
);
case OptionsAlignment.bottomEnd:
return Aligned(
widthFactor: widthFactor,
follower: Alignment.topRight,
target: Alignment.bottomRight,
);
}
}
}
/// A widget that provides a text field with autocomplete functionality.
class MultiTriggerAutocomplete extends StatefulWidget {
/// Create an instance of StreamAutocomplete.
///
/// [displayStringForOption], [optionsBuilder] and [optionsViewBuilder] must
/// not be null.
const MultiTriggerAutocomplete({
super.key,
required this.autocompleteTriggers,
this.fieldViewBuilder = _defaultFieldViewBuilder,
this.focusNode,
this.textEditingController,
this.initialValue,
this.optionsAlignment = OptionsAlignment.bottom,
this.optionsWidthFactor = 1.0,
this.debounceDuration = const Duration(milliseconds: 300),
}) : assert((focusNode == null) == (textEditingController == null)),
assert(
!(textEditingController != null && initialValue != null),
'textEditingController and initialValue cannot be simultaneously defined.',
);
/// The triggers that trigger autocomplete.
final Iterable<AutocompleteTrigger> autocompleteTriggers;
/// {@template flutter.widgets.RawAutocomplete.fieldViewBuilder}
/// Builds the field whose input is used to get the options.
///
/// Pass the provided [TextEditingController] to the field built here so that
/// RawAutocomplete can listen for changes.
/// {@endtemplate}
final MultiTriggerAutocompleteFieldViewBuilder fieldViewBuilder;
/// The [FocusNode] that is used for the text field.
///
/// {@template flutter.widgets.RawAutocomplete.split}
/// The main purpose of this parameter is to allow the use of a separate text
/// field located in another part of the widget tree instead of the text
/// field built by [fieldViewBuilder]. For example, it may be desirable to
/// place the text field in the AppBar and the options below in the main body.
///
/// When following this pattern, [fieldViewBuilder] can return
/// `SizedBox.shrink()` so that nothing is drawn where the text field would
/// normally be. A separate text field can be created elsewhere, and a
/// FocusNode and TextEditingController can be passed both to that text field
/// and to RawAutocomplete.
///
/// {@tool dartpad}
/// This examples shows how to create an autocomplete widget with the text
/// field in the AppBar and the results in the main body of the app.
///
/// ** See code in examples/api/lib/widgets/autocomplete/raw_autocomplete.focus_node.0.dart **
/// {@end-tool}
/// {@endtemplate}
///
/// If this parameter is not null, then [textEditingController] must also be
/// not null.
final FocusNode? focusNode;
/// The [TextEditingController] that is used for the text field.
///
/// If this parameter is not null, then [focusNode] must also be not null.
final TextEditingController? textEditingController;
/// {@template flutter.widgets.RawAutocomplete.initialValue}
/// The initial value to use for the text field.
/// {@endtemplate}
///
/// Setting the initial value does not notify [textEditingController]'s
/// listeners, and thus will not cause the options UI to appear.
///
/// This parameter is ignored if [textEditingController] is defined.
final TextEditingValue? initialValue;
/// The alignment of the options.
///
/// The default value is [MultiTriggerAutocompleteAlignment.below].
final OptionsAlignment optionsAlignment;
/// The width to make the options as a multiple of the width of the
/// field.
///
/// The default value is 1.0, which makes the options the same width
/// as the field.
final double? optionsWidthFactor;
/// The duration of the debounce period for the [TextEditingController].
///
/// The default value is [300ms].
final Duration debounceDuration;
static Widget _defaultFieldViewBuilder(
BuildContext context,
TextEditingController textEditingController,
FocusNode focusNode,
) {
return _MultiTriggerAutocompleteField(
focusNode: focusNode,
textEditingController: textEditingController,
);
}
/// Returns the nearest [StreamAutocomplete] ancestor of the given context.
static MultiTriggerAutocompleteState of(BuildContext context) {
final state =
context.findAncestorStateOfType<MultiTriggerAutocompleteState>();
assert(state != null, 'MultiTriggerAutocomplete not found');
return state!;
}
@override
MultiTriggerAutocompleteState createState() =>
MultiTriggerAutocompleteState();
}
class MultiTriggerAutocompleteState extends State<MultiTriggerAutocomplete> {
late TextEditingController _textEditingController;
late FocusNode _focusNode;
AutocompleteQuery? _currentQuery;
AutocompleteTrigger? _currentTrigger;
bool _hideOptions = false;
String _lastFieldText = '';
// True if the state indicates that the options should be visible.
bool get _shouldShowOptions {
return !_hideOptions &&
_focusNode.hasFocus &&
_currentQuery != null &&
_currentTrigger != null;
}
void acceptAutocompleteOption(
String option, {
bool keepTrigger = true,
}) {
if (option.isEmpty) return;
final query = _currentQuery;
final trigger = _currentTrigger;
if (query == null || trigger == null) return;
final querySelection = query.selection;
final text = _textEditingController.text;
var start = querySelection.baseOffset;
if (!keepTrigger) start -= 1;
final end = querySelection.extentOffset;
final alreadyContainsTriggerEnd =
text.substring(end).startsWith(trigger.triggerEnd);
// Having triggerEnd dismissing the auto-completion view.
if (!alreadyContainsTriggerEnd) option += trigger.triggerEnd;
var selectionOffset = start + option.length;
// In case the triggerEnd is already there, we need to move the cursor
// after the triggerEnd.
if (alreadyContainsTriggerEnd) selectionOffset += trigger.triggerEnd.length;
final newText = text.replaceRange(start, end, option);
final newSelection = TextSelection.collapsed(offset: selectionOffset);
_textEditingController.value = TextEditingValue(
text: newText,
selection: newSelection,
);
return closeOptions();
}
void closeOptions() {
final prevQuery = _currentQuery;
final prevTrigger = _currentTrigger;
if (prevQuery == null || prevTrigger == null) return;
_currentQuery = null;
_currentTrigger = null;
if (mounted) setState(() {});
}
void showOptions(
AutocompleteQuery query,
AutocompleteTrigger trigger,
) {
final prevQuery = _currentQuery;
final prevTrigger = _currentTrigger;
if (prevQuery == query && prevTrigger == trigger) return;
_currentQuery = query;
_currentTrigger = trigger;
if (mounted) setState(() {});
}
// Checks if there is any invoked autocomplete trigger and returns the
// one with has the longest trigger length along with the query that
// matches the current input.
_AutocompleteInvokedTriggerWithQuery? _getInvokedTriggerWithQuery(
TextEditingValue textEditingValue,
) {
final autocompleteTriggers = widget.autocompleteTriggers.toSet();
AutocompleteTrigger? finalTrigger;
AutocompleteQuery? finalQuery;
for (final autocompleteTrigger in autocompleteTriggers) {
final query = autocompleteTrigger.invokingTrigger(textEditingValue);
if (query != null &&
(finalTrigger == null ||
autocompleteTrigger.trigger.length >
finalTrigger.trigger.length)) {
finalTrigger = autocompleteTrigger;
finalQuery = query;
}
}
if (finalTrigger != null && finalQuery != null) {
return _AutocompleteInvokedTriggerWithQuery(finalTrigger, finalQuery);
}
return null;
}
Timer? _debounceTimer;
// Called when _textEditingController changes.
void _onChangedField() {
if (_debounceTimer?.isActive == true) _debounceTimer?.cancel();
_debounceTimer = Timer(widget.debounceDuration, () {
final textEditingValue = _textEditingController.value;
// If the content has not changed, then there is nothing to do.
if (textEditingValue.text == _lastFieldText) return;
// Make sure the options are no longer hidden if the content of the
// field changes.
_hideOptions = false;
_lastFieldText = textEditingValue.text;
// If the text field is empty, then there is no need to do anything.
if (textEditingValue.text.isEmpty) return closeOptions();
// If the text field is not empty, then we need to check if the
// text field contains a trigger.
final triggerWithQuery = _getInvokedTriggerWithQuery(textEditingValue);
// If the text field does not contain a trigger, then there is no need
// to do anything.
if (triggerWithQuery == null) return closeOptions();
// If the text field contains a trigger, then we need to open the
// portal.
final trigger = triggerWithQuery.trigger;
final query = triggerWithQuery.query;
return showOptions(query, trigger);
});
}
// Called when the field's FocusNode changes.
void _onChangedFocus() {
// Options should no longer be hidden when the field is re-focused.
_hideOptions = !_focusNode.hasFocus;
if (mounted) setState(() {});
}
// Handle a potential change in textEditingController by properly disposing of
// the old one and setting up the new one, if needed.
void _updateTextEditingController(
TextEditingController? old, TextEditingController? current) {
if ((old == null && current == null) || old == current) {
return;
}
if (old == null) {
_textEditingController.removeListener(_onChangedField);
_textEditingController.dispose();
_textEditingController = current!;
} else if (current == null) {
_textEditingController.removeListener(_onChangedField);
_textEditingController = TextEditingController();
} else {
_textEditingController.removeListener(_onChangedField);
_textEditingController = current;
}
_textEditingController.addListener(_onChangedField);
}
// Handle a potential change in focusNode by properly disposing of the old one
// and setting up the new one, if needed.
void _updateFocusNode(FocusNode? old, FocusNode? current) {
if ((old == null && current == null) || old == current) {
return;
}
if (old == null) {
_focusNode.removeListener(_onChangedFocus);
_focusNode.dispose();
_focusNode = current!;
} else if (current == null) {
_focusNode.removeListener(_onChangedFocus);
_focusNode = FocusNode();
} else {
_focusNode.removeListener(_onChangedFocus);
_focusNode = current;
}
_focusNode.addListener(_onChangedFocus);
}
@override
void initState() {
super.initState();
_textEditingController = widget.textEditingController ??
TextEditingController.fromValue(widget.initialValue);
_textEditingController.addListener(_onChangedField);
_focusNode = widget.focusNode ?? FocusNode();
_focusNode.addListener(_onChangedFocus);
}
@override
void didUpdateWidget(MultiTriggerAutocomplete oldWidget) {
super.didUpdateWidget(oldWidget);
_updateTextEditingController(
oldWidget.textEditingController,
widget.textEditingController,
);
_updateFocusNode(oldWidget.focusNode, widget.focusNode);
}
@override
void dispose() {
_textEditingController.removeListener(_onChangedField);
if (widget.textEditingController == null) {
_textEditingController.dispose();
}
_focusNode.removeListener(_onChangedFocus);
if (widget.focusNode == null) {
_focusNode.dispose();
}
_debounceTimer?.cancel();
_currentTrigger = null;
_currentQuery = null;
super.dispose();
}
@override
Widget build(BuildContext context) {
// Adding additional builder so that [MultiTriggerAutocomplete.of] works.
return Builder(
builder: (context) {
final anchor = widget.optionsAlignment._toAnchor(
widthFactor: widget.optionsWidthFactor,
);
final shouldShowOptions = _shouldShowOptions;
final optionViewBuilder = shouldShowOptions
? TextFieldTapRegion(
child: _currentTrigger!.optionsViewBuilder(
context,
_currentQuery!,
_textEditingController,
),
)
: null;
return PortalTarget(
anchor: anchor,
visible: shouldShowOptions,
portalFollower: optionViewBuilder,
child: widget.fieldViewBuilder(
context,
_textEditingController,
_focusNode,
),
);
},
);
}
}
class _AutocompleteInvokedTriggerWithQuery {
const _AutocompleteInvokedTriggerWithQuery(this.trigger, this.query);
final AutocompleteTrigger trigger;
final AutocompleteQuery query;
}
// The default Material-style Autocomplete text field.
class _MultiTriggerAutocompleteField extends StatelessWidget {
const _MultiTriggerAutocompleteField({
required this.focusNode,
required this.textEditingController,
});
final FocusNode focusNode;
final TextEditingController textEditingController;
@override
Widget build(BuildContext context) {
return TextFormField(
controller: textEditingController,
focusNode: focusNode,
);
}
}