Line data Source code
1 : import 'dart:async';
2 : import 'dart:math' as math;
3 :
4 : import 'package:flutter/services.dart';
5 : import 'package:flutter/widgets.dart';
6 : import 'package:fossui/src/components/chip/foss_chip.dart';
7 : import 'package:fossui/src/components/select/foss_select.dart';
8 : import 'package:fossui/src/components/text_field/foss_text_field.dart';
9 : import 'package:fossui/src/foundation/foss_field_box.dart';
10 : import 'package:fossui/src/icons/foss_glyph.dart';
11 : import 'package:fossui/src/theme/theme.dart';
12 :
13 : part '_foss_combobox_field.dart';
14 : part '_foss_combobox_popup.dart';
15 : part '_foss_multi_combobox_field.dart';
16 : part 'foss_combobox_item.dart';
17 : part 'foss_combobox_style.dart';
18 :
19 : const double _disabledOpacity = 0.64;
20 : const double _iconSize = 18;
21 : const double _affixOpacity = 0.8;
22 : const double _popupOffset = 4;
23 : const double _popupMargin = 8;
24 : const double _popupMaxHeight = 368;
25 : const double _rowMinHeight = 32;
26 : const double _indicatorColumn = 16;
27 : const double _openScale = 0.96;
28 :
29 : // Minimum touch region for the trailing affixes. The region expands past the
30 : // small glyph without growing its visual footprint.
31 : const double _minHitTarget = 48;
32 :
33 : /// Default empty-state caption when a query matches nothing.
34 : const String _defaultEmptyText = 'No items found.';
35 :
36 : // The chips input text selection uses the ring color at a low alpha, and the
37 : // placeholder sits at 72% of the muted-foreground alpha.
38 : const double _focusRingOpacity = 0.24;
39 : const double _placeholderOpacity = 0.72;
40 :
41 : // The chips label tightens its line height to 18px against the 16px base, to
42 : // match the single-line field label.
43 : const double _labelLineHeight = 18 / 16;
44 :
45 : /// Default filter: a case-insensitive substring match of the query against the
46 : /// option label.
47 2 : bool _defaultFilter(String label, String query) =>
48 6 : label.toLowerCase().contains(query.toLowerCase());
49 :
50 : /// {@category Inputs}
51 : /// {@template foss.combobox.preview}
52 : /// <img src="https://fossui.org/components/combobox/overview/light.png"
53 : /// alt="FossCombobox, light theme" width="480"
54 : /// style="max-width:100%;height:auto" />
55 : /// <img src="https://fossui.org/components/combobox/overview/dark.png"
56 : /// alt="FossCombobox, dark theme" width="480"
57 : /// style="max-width:100%;height:auto" />
58 : ///
59 : /// See the [combobox documentation ↗](https://fossui.org/docs/components/combobox) or
60 : /// try it live in the
61 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/combobox/fosscombobox/playground).
62 : /// {@endtemplate}
63 : ///
64 : /// A text field whose dropdown filters a list of suggestions as you type.
65 : ///
66 : /// The value is the field string, reported through [onChanged]; picking a
67 : /// suggestion writes its text into the field. The [items] are hints, not a
68 : /// constraint, so the field accepts any typed value. There is no selection
69 : /// indicator and no multiple selection: for those, use [FossCombobox].
70 : ///
71 : /// Colors, type, and metrics come from `context.fossTheme`; pass a
72 : /// [FossComboboxStyle] to [style] for a one-off.
73 : ///
74 : /// {@macro foss.customize}
75 : ///
76 : /// See also [FossSelect] for selection without typing.
77 : ///
78 : /// ```dart
79 : /// FossAutocomplete(
80 : /// label: 'Fruit',
81 : /// hintText: 'Type to filter',
82 : /// items: const ['Apple', 'Banana', 'Cherry'],
83 : /// onChanged: (value) => setState(() => fruit = value),
84 : /// );
85 : /// ```
86 : class FossAutocomplete extends StatelessWidget {
87 : /// {@macro foss.combobox.preview}
88 : ///
89 : /// Creates an autocomplete over string [items].
90 2 : const FossAutocomplete({
91 : required this.items,
92 : this.controller,
93 : this.focusNode,
94 : this.size = FossTextFieldSize.md,
95 : this.label,
96 : this.hintText,
97 : this.errorText,
98 : this.enabled = true,
99 : this.showTrigger = false,
100 : this.showClear = false,
101 : this.startAddon,
102 : this.filter,
103 : this.onChanged,
104 : this.emptyText = _defaultEmptyText,
105 : this.style,
106 : super.key,
107 : });
108 :
109 : /// The suggestions to filter as the user types.
110 : final List<String> items;
111 :
112 : /// Holds the editable text. Created and disposed internally when null.
113 : final TextEditingController? controller;
114 :
115 : /// Manages keyboard focus. Created and disposed internally when null.
116 : final FocusNode? focusNode;
117 :
118 : /// The field height and type scale.
119 : final FossTextFieldSize size;
120 :
121 : /// Optional label rendered above the field.
122 : final String? label;
123 :
124 : /// Placeholder shown while the field is empty.
125 : final String? hintText;
126 :
127 : /// When non-null, marks the field invalid and recolors its border.
128 : final String? errorText;
129 :
130 : /// Whether the field accepts input. Disabled when false.
131 : final bool enabled;
132 :
133 : /// Whether to show the trailing chevron that opens the list. Hidden by
134 : /// default; the list also opens on focus and typing.
135 : final bool showTrigger;
136 :
137 : /// Whether to show a trailing clear button while the field is non-empty.
138 : final bool showClear;
139 :
140 : /// Optional leading widget, typically a search glyph. Icon-agnostic.
141 : final Widget? startAddon;
142 :
143 : /// Overrides the default case-insensitive substring match. Receives the
144 : /// option label and the current query.
145 : final bool Function(String label, String query)? filter;
146 :
147 : /// Called whenever the field text changes, including on a pick.
148 : final ValueChanged<String>? onChanged;
149 :
150 : /// Caption shown when the query matches no suggestion.
151 : final String emptyText;
152 :
153 : /// Per-instance overrides layered on the theme-resolved style.
154 : final FossComboboxStyle? style;
155 :
156 2 : @override
157 : Widget build(BuildContext context) {
158 2 : return _FossComboboxField<String>(
159 2 : options: [
160 4 : for (final item in items) FossComboboxItem(value: item, label: item),
161 : ],
162 2 : controller: controller,
163 2 : focusNode: focusNode,
164 2 : size: size,
165 2 : label: label,
166 2 : hintText: hintText,
167 2 : errorText: errorText,
168 2 : enabled: enabled,
169 2 : showTrigger: showTrigger,
170 2 : showClear: showClear,
171 2 : startAddon: startAddon,
172 : showIndicator: false,
173 2 : emptyText: emptyText,
174 2 : filter: filter ?? _defaultFilter,
175 1 : isSelected: (_) => false,
176 4 : onPick: (item) => onChanged?.call(item.label),
177 3 : onTextChanged: (text) => onChanged?.call(text),
178 2 : style: style,
179 : );
180 : }
181 : }
182 :
183 : /// {@category Inputs}
184 : /// {@macro foss.combobox.preview}
185 : ///
186 : /// A text field with a filtered dropdown of predefined items, each carrying a
187 : /// check when picked.
188 : ///
189 : /// Unlike [FossAutocomplete], the value is the selected item, not the raw text:
190 : /// pass [value] and rebuild on [onChanged]. Picking a row writes its label
191 : /// into the field and closes the popup. A null [onChanged] (or
192 : /// `enabled: false`) disables the field.
193 : ///
194 : /// {@macro foss.customize}
195 : ///
196 : /// See also [FossSelect] for selection without typing.
197 : ///
198 : /// ```dart
199 : /// FossCombobox<String>(
200 : /// label: 'Team',
201 : /// hintText: 'Search teams',
202 : /// value: team,
203 : /// onChanged: (v) => setState(() => team = v),
204 : /// items: const [
205 : /// FossComboboxItem(value: 'design', label: 'Design'),
206 : /// FossComboboxItem(value: 'eng', label: 'Engineering'),
207 : /// ],
208 : /// );
209 : /// ```
210 : class FossCombobox<T> extends StatelessWidget {
211 : /// {@macro foss.combobox.preview}
212 : ///
213 : /// Creates a single-select combobox over [items].
214 3 : const FossCombobox({
215 : required this.items,
216 : this.value,
217 : this.onChanged,
218 : this.focusNode,
219 : this.size = FossTextFieldSize.md,
220 : this.label,
221 : this.hintText,
222 : this.errorText,
223 : this.enabled = true,
224 : this.showClear = false,
225 : this.startAddon,
226 : this.filter,
227 : this.emptyText = _defaultEmptyText,
228 : this.style,
229 : super.key,
230 : });
231 :
232 : /// The options to choose from.
233 : final List<FossComboboxItem<T>> items;
234 :
235 : /// The picked value, or null when nothing is selected.
236 : final T? value;
237 :
238 : /// Called with the picked value when a row is chosen. A null callback
239 : /// disables the field.
240 : final ValueChanged<T?>? onChanged;
241 :
242 : /// Manages keyboard focus. Created and disposed internally when null.
243 : final FocusNode? focusNode;
244 :
245 : /// The field height and type scale.
246 : final FossTextFieldSize size;
247 :
248 : /// Optional label rendered above the field.
249 : final String? label;
250 :
251 : /// Placeholder shown while the field is empty.
252 : final String? hintText;
253 :
254 : /// When non-null, marks the field invalid and recolors its border.
255 : final String? errorText;
256 :
257 : /// Whether the field accepts input. Disabled when false or [onChanged] is
258 : /// null.
259 : final bool enabled;
260 :
261 : /// Whether to show a trailing clear button while a value is selected.
262 : final bool showClear;
263 :
264 : /// Optional leading widget, typically a search glyph. Icon-agnostic.
265 : final Widget? startAddon;
266 :
267 : /// Overrides the default case-insensitive substring match.
268 : final bool Function(String label, String query)? filter;
269 :
270 : /// Caption shown when the query matches no option.
271 : final String emptyText;
272 :
273 : /// Per-instance overrides layered on the theme-resolved style.
274 : final FossComboboxStyle? style;
275 :
276 3 : @override
277 : Widget build(BuildContext context) {
278 3 : return _FossComboboxField<T>(
279 3 : options: items,
280 3 : focusNode: focusNode,
281 3 : size: size,
282 3 : label: label,
283 3 : hintText: hintText,
284 3 : errorText: errorText,
285 6 : enabled: enabled && onChanged != null,
286 : showTrigger: true,
287 3 : showClear: showClear,
288 3 : startAddon: startAddon,
289 : showIndicator: true,
290 : resetOnBlur: true,
291 3 : initialText: _selectedLabel(),
292 3 : emptyText: emptyText,
293 3 : filter: filter ?? _defaultFilter,
294 6 : isSelected: (v) => v == value,
295 4 : onPick: (item) => onChanged?.call(item.value),
296 3 : onClear: () => onChanged?.call(null),
297 3 : style: style,
298 : );
299 : }
300 :
301 3 : String? _selectedLabel() {
302 6 : for (final item in items) {
303 12 : if (item.value == value) return item.label;
304 : }
305 : return null;
306 : }
307 : }
308 :
309 : /// {@category Inputs}
310 : /// {@macro foss.combobox.preview}
311 : ///
312 : /// A combobox that holds several picks at once, shown as removable chips.
313 : ///
314 : /// The value is the set of selected items ([values]); rebuild on [onChanged].
315 : /// Typing filters [items], picking toggles a chip and keeps the popup open, and
316 : /// Backspace on the empty input removes the last chip. A null [onChanged] (or
317 : /// `enabled: false`) disables the field.
318 : ///
319 : /// {@macro foss.customize}
320 : ///
321 : /// See also [FossSelect] for selection without typing.
322 : ///
323 : /// ```dart
324 : /// FossMultiCombobox<String>(
325 : /// label: 'Tags',
326 : /// hintText: 'Add tags',
327 : /// values: tags,
328 : /// onChanged: (v) => setState(() => tags = v),
329 : /// items: const [
330 : /// FossComboboxItem(value: 'design', label: 'Design'),
331 : /// FossComboboxItem(value: 'eng', label: 'Engineering'),
332 : /// ],
333 : /// );
334 : /// ```
335 : class FossMultiCombobox<T> extends StatelessWidget {
336 : /// {@macro foss.combobox.preview}
337 : ///
338 : /// Creates a multi-select combobox over [items].
339 3 : const FossMultiCombobox({
340 : required this.items,
341 : this.values = const {},
342 : this.onChanged,
343 : this.focusNode,
344 : this.size = FossTextFieldSize.md,
345 : this.label,
346 : this.hintText,
347 : this.errorText,
348 : this.enabled = true,
349 : this.startAddon,
350 : this.filter,
351 : this.emptyText = _defaultEmptyText,
352 : this.removeLabel = 'Remove',
353 : this.style,
354 : super.key,
355 : });
356 :
357 : /// The options to choose from.
358 : final List<FossComboboxItem<T>> items;
359 :
360 : /// The current picks.
361 : final Set<T> values;
362 :
363 : /// Called with the next set when a pick is toggled. A null callback disables
364 : /// the field.
365 : final ValueChanged<Set<T>>? onChanged;
366 :
367 : /// Manages keyboard focus. Created and disposed internally when null.
368 : final FocusNode? focusNode;
369 :
370 : /// The field height and type scale.
371 : final FossTextFieldSize size;
372 :
373 : /// Optional label rendered above the field.
374 : final String? label;
375 :
376 : /// Placeholder shown while no picks and the input is empty.
377 : final String? hintText;
378 :
379 : /// When non-null, marks the field invalid and recolors its border.
380 : final String? errorText;
381 :
382 : /// Whether the field accepts input. Disabled when false or [onChanged] is
383 : /// null.
384 : final bool enabled;
385 :
386 : /// Optional leading widget, typically a search glyph. Icon-agnostic.
387 : final Widget? startAddon;
388 :
389 : /// Overrides the default case-insensitive substring match.
390 : final bool Function(String label, String query)? filter;
391 :
392 : /// Caption shown when the query matches no option.
393 : final String emptyText;
394 :
395 : /// Accessible label for each chip's remove button.
396 : final String removeLabel;
397 :
398 : /// Per-instance overrides layered on the theme-resolved style.
399 : final FossComboboxStyle? style;
400 :
401 3 : @override
402 : Widget build(BuildContext context) {
403 3 : return _FossMultiComboboxField<T>(
404 3 : options: items,
405 3 : values: values,
406 3 : focusNode: focusNode,
407 3 : size: size,
408 3 : label: label,
409 3 : hintText: hintText,
410 3 : errorText: errorText,
411 6 : enabled: enabled && onChanged != null,
412 3 : startAddon: startAddon,
413 3 : emptyText: emptyText,
414 3 : removeLabel: removeLabel,
415 3 : filter: filter ?? _defaultFilter,
416 3 : onChanged: (next) => onChanged?.call(next),
417 3 : style: style,
418 : );
419 : }
420 : }
421 :
422 : /// Builds the popup and row appearance from the theme tokens for [size].
423 3 : _ComboboxVisuals _resolve(FossThemeData theme, FossTextFieldSize size) {
424 3 : final c = theme.colors;
425 : final textStyle = switch (size) {
426 3 : FossTextFieldSize.sm => theme.typography.sm,
427 9 : FossTextFieldSize.md => theme.typography.base,
428 3 : FossTextFieldSize.lg => theme.typography.base,
429 : };
430 3 : return _ComboboxVisuals(
431 3 : foreground: c.foreground,
432 3 : mutedForeground: c.mutedForeground,
433 6 : borderRadius: theme.radii.lg,
434 6 : rowRadius: theme.radii.sm,
435 : textStyle: textStyle,
436 : iconSize: _iconSize,
437 3 : popupColor: c.popover,
438 3 : popupBorderColor: c.border,
439 6 : popupShadow: theme.shadows.lg,
440 3 : highlightColor: c.accent,
441 3 : highlightForeground: c.accentForeground,
442 : );
443 : }
444 :
445 3 : _ComboboxVisuals _apply(_ComboboxVisuals base, FossComboboxStyle? override) {
446 : if (override == null) return base;
447 3 : return base.copyWith(
448 3 : borderRadius: override.borderRadius,
449 3 : textStyle: override.textStyle,
450 3 : popupBorderColor: override.borderColor,
451 : );
452 : }
453 :
454 : /// The resolved popup and row appearance. The input box styling stays inside
455 : /// the embedded [FossTextField]; this covers only the dropdown.
456 : @immutable
457 : class _ComboboxVisuals {
458 3 : const _ComboboxVisuals({
459 : required this.foreground,
460 : required this.mutedForeground,
461 : required this.borderRadius,
462 : required this.rowRadius,
463 : required this.textStyle,
464 : required this.iconSize,
465 : required this.popupColor,
466 : required this.popupBorderColor,
467 : required this.popupShadow,
468 : required this.highlightColor,
469 : required this.highlightForeground,
470 : });
471 :
472 : final Color foreground;
473 : final Color mutedForeground;
474 : final double borderRadius;
475 : final double rowRadius;
476 : final TextStyle textStyle;
477 : final double iconSize;
478 : final Color popupColor;
479 : final Color popupBorderColor;
480 : final List<BoxShadow> popupShadow;
481 : final Color highlightColor;
482 : final Color highlightForeground;
483 :
484 3 : _ComboboxVisuals copyWith({
485 : double? borderRadius,
486 : TextStyle? textStyle,
487 : Color? popupBorderColor,
488 3 : }) => _ComboboxVisuals(
489 3 : foreground: foreground,
490 3 : mutedForeground: mutedForeground,
491 2 : borderRadius: borderRadius ?? this.borderRadius,
492 3 : rowRadius: rowRadius,
493 3 : textStyle: textStyle ?? this.textStyle,
494 3 : iconSize: iconSize,
495 3 : popupColor: popupColor,
496 3 : popupBorderColor: popupBorderColor ?? this.popupBorderColor,
497 3 : popupShadow: popupShadow,
498 3 : highlightColor: highlightColor,
499 3 : highlightForeground: highlightForeground,
500 : );
501 : }
|