Line data Source code
1 : part of 'foss_combobox.dart';
2 :
3 : /// The chips input, anchored popup, filtering, and dismiss handling behind
4 : /// [FossMultiCombobox]. Reuses the single field's popup, rows, and layout; only
5 : /// the anchor differs (a wrapping chips field instead of a `FossTextField`).
6 : class _FossMultiComboboxField<T> extends StatefulWidget {
7 3 : const _FossMultiComboboxField({
8 : required this.options,
9 : required this.values,
10 : required this.size,
11 : required this.enabled,
12 : required this.emptyText,
13 : required this.removeLabel,
14 : required this.filter,
15 : required this.onChanged,
16 : this.focusNode,
17 : this.label,
18 : this.hintText,
19 : this.errorText,
20 : this.startAddon,
21 : this.style,
22 : super.key,
23 : });
24 :
25 : final List<FossComboboxItem<T>> options;
26 : final Set<T> values;
27 : final FossTextFieldSize size;
28 : final bool enabled;
29 : final String emptyText;
30 : final String removeLabel;
31 : final bool Function(String label, String query) filter;
32 : final ValueChanged<Set<T>> onChanged;
33 : final FocusNode? focusNode;
34 : final String? label;
35 : final String? hintText;
36 : final String? errorText;
37 : final Widget? startAddon;
38 : final FossComboboxStyle? style;
39 :
40 3 : @override
41 : State<_FossMultiComboboxField<T>> createState() =>
42 3 : _FossMultiComboboxFieldState<T>();
43 : }
44 :
45 : class _FossMultiComboboxFieldState<T> extends State<_FossMultiComboboxField<T>>
46 : with
47 : SingleTickerProviderStateMixin,
48 : _ComboboxPopup<T, _FossMultiComboboxField<T>> {
49 : final TextEditingController _controller = TextEditingController();
50 :
51 : late FocusNode _focusNode;
52 : FocusNode? _ownedFocusNode;
53 :
54 3 : @override
55 : void initState() {
56 3 : super.initState();
57 13 : _focusNode = widget.focusNode ?? (_ownedFocusNode = FocusNode());
58 9 : _focusNode.addListener(_onFocusChanged);
59 9 : _controller.addListener(_onTextChanged);
60 : }
61 :
62 2 : @override
63 : void didUpdateWidget(_FossMultiComboboxField<T> oldWidget) {
64 2 : super.didUpdateWidget(oldWidget);
65 8 : if (widget.focusNode == oldWidget.focusNode) return;
66 3 : (oldWidget.focusNode ?? _ownedFocusNode)?.removeListener(_onFocusChanged);
67 1 : _ownedFocusNode?.dispose();
68 2 : final provided = widget.focusNode;
69 : if (provided != null) {
70 1 : _ownedFocusNode = null;
71 1 : _focusNode = provided;
72 : } else {
73 3 : _focusNode = _ownedFocusNode = FocusNode();
74 : }
75 3 : _focusNode.addListener(_onFocusChanged);
76 : }
77 :
78 3 : @override
79 : void dispose() {
80 9 : _focusNode.removeListener(_onFocusChanged);
81 3 : _controller
82 6 : ..removeListener(_onTextChanged)
83 3 : ..dispose();
84 6 : _ownedFocusNode?.dispose();
85 3 : super.dispose();
86 : }
87 :
88 1 : @override
89 2 : bool get popupEnabled => widget.enabled;
90 :
91 1 : @override
92 : List<FossComboboxItem<T>> get filteredOptions {
93 2 : final query = _controller.text;
94 3 : if (query.isEmpty) return widget.options;
95 1 : return [
96 2 : for (final o in widget.options)
97 5 : if (widget.filter(o.label, query)) o,
98 : ];
99 : }
100 :
101 1 : @override
102 2 : int initialHighlight() => _firstEnabled(filteredOptions);
103 :
104 1 : @override
105 1 : void onActivate(FossComboboxItem<T> item) => _toggle(item);
106 :
107 6 : List<FossComboboxItem<T>> get _chips => [
108 6 : for (final o in widget.options)
109 15 : if (widget.values.contains(o.value)) o,
110 : ];
111 :
112 1 : void _onFocusChanged() {
113 2 : if (_focusNode.hasFocus) {
114 1 : _openPopup();
115 : } else {
116 1 : _closePopup();
117 : }
118 : }
119 :
120 2 : void _onTextChanged() => _resetHighlight();
121 :
122 1 : void _toggle(FossComboboxItem<T> item) {
123 1 : if (!item.enabled) return;
124 3 : final next = Set<T>.of(widget.values);
125 4 : if (!next.remove(item.value)) next.add(item.value);
126 2 : _controller.clear();
127 3 : widget.onChanged(next);
128 2 : _focusNode.requestFocus();
129 : }
130 :
131 1 : void _removeLast() {
132 1 : final chips = _chips;
133 1 : if (chips.isEmpty) return;
134 9 : widget.onChanged(Set<T>.of(widget.values)..remove(chips.last.value));
135 : }
136 :
137 : // The shared popup keys plus Backspace, which removes the last chip when the
138 : // input is empty.
139 1 : KeyEventResult _onKey(FocusNode node, KeyEvent event) {
140 1 : final result = _handlePopupKey(event);
141 1 : if (result != KeyEventResult.ignored) return result;
142 1 : if (event is! KeyUpEvent &&
143 2 : event.logicalKey == LogicalKeyboardKey.backspace &&
144 3 : _controller.text.isEmpty) {
145 1 : _removeLast();
146 : return KeyEventResult.handled;
147 : }
148 : return KeyEventResult.ignored;
149 : }
150 :
151 3 : @override
152 : Widget build(BuildContext context) {
153 3 : final theme = context.fossTheme;
154 18 : final v = _apply(_resolve(theme, widget.size), widget.style);
155 :
156 3 : final field = Column(
157 : mainAxisSize: MainAxisSize.min,
158 : crossAxisAlignment: CrossAxisAlignment.start,
159 3 : children: [
160 7 : if (widget.label case final label?) ...[
161 1 : Opacity(
162 2 : opacity: widget.enabled ? 1 : _disabledOpacity,
163 1 : child: Text(
164 : label,
165 4 : style: theme.typography.base.medium.copyWith(
166 2 : color: theme.colors.foreground,
167 : height: _labelLineHeight,
168 : ),
169 : ),
170 : ),
171 3 : SizedBox(height: theme.spacing(2)),
172 : ],
173 3 : OverlayPortal(
174 3 : controller: _portal,
175 3 : overlayChildBuilder: _buildOverlay,
176 3 : child: TextFieldTapRegion(
177 3 : child: Focus(
178 : canRequestFocus: false,
179 : skipTraversal: true,
180 3 : onKeyEvent: _onKey,
181 3 : child: Semantics(
182 3 : expanded: _open,
183 3 : child: KeyedSubtree(
184 3 : key: _anchorKey,
185 3 : child: _shell(theme, v),
186 : ),
187 : ),
188 : ),
189 : ),
190 : ),
191 8 : if (widget.errorText case final error?) ...[
192 6 : SizedBox(height: theme.spacing(2)),
193 2 : Semantics(
194 : liveRegion: true,
195 2 : child: Text(
196 : error,
197 6 : style: theme.typography.xs.copyWith(
198 4 : color: theme.colors.destructiveForeground,
199 : ),
200 : ),
201 : ),
202 : ],
203 : ],
204 : );
205 :
206 : return field;
207 : }
208 :
209 3 : Widget _shell(FossThemeData theme, _ComboboxVisuals v) {
210 3 : final colors = theme.colors;
211 9 : final m = fieldMetrics(theme, widget.size);
212 6 : final style = widget.style;
213 6 : final hasError = widget.errorText != null;
214 :
215 3 : return ListenableBuilder(
216 12 : listenable: Listenable.merge([_focusNode, _controller]),
217 3 : builder: (context, _) {
218 3 : final box = FossFieldBox(
219 6 : enabled: widget.enabled,
220 : hasError: hasError,
221 8 : focused: _focusNode.hasFocus && widget.enabled,
222 1 : background: style?.backgroundColor ?? m.fill,
223 4 : borderColor: style?.borderColor ?? colors.input,
224 3 : ringColor: colors.ring,
225 3 : destructiveColor: colors.destructive,
226 1 : borderRadius: style?.borderRadius ?? m.radius,
227 : minHeight: m.minHeight,
228 7 : shadow: style?.shadow ?? theme.shadows.xs,
229 3 : isDark: colors.isDark,
230 : // Fill the available width like the single-line field, whose editable
231 : // expands. The chips carry their own height, so a small vertical
232 : // inset keeps them off the border once the field grows past one run.
233 3 : child: SizedBox(
234 : width: double.infinity,
235 3 : child: Padding(
236 3 : padding: EdgeInsets.symmetric(
237 : horizontal: m.padX,
238 6 : vertical: theme.spacing(1),
239 : ),
240 3 : child: _wrap(theme, v),
241 : ),
242 : ),
243 : );
244 :
245 6 : if (!widget.enabled) return box;
246 2 : return GestureDetector(
247 : behavior: HitTestBehavior.opaque,
248 4 : onTap: _focusNode.requestFocus,
249 : child: box,
250 : );
251 : },
252 : );
253 : }
254 :
255 3 : Widget _wrap(FossThemeData theme, _ComboboxVisuals v) {
256 3 : final colors = theme.colors;
257 3 : final chips = _chips;
258 : final showPlaceholder =
259 8 : chips.isEmpty && _controller.text.isEmpty && widget.hintText != null;
260 :
261 3 : return Wrap(
262 6 : spacing: theme.spacing(1),
263 6 : runSpacing: theme.spacing(1),
264 : crossAxisAlignment: WrapCrossAlignment.center,
265 : runAlignment: WrapAlignment.center,
266 3 : children: [
267 6 : if (widget.startAddon case final addon?)
268 1 : IconTheme.merge(
269 1 : data: IconThemeData(
270 1 : size: v.iconSize,
271 5 : color: v.foreground.withValues(alpha: v.foreground.a * 0.8),
272 : ),
273 : child: addon,
274 : ),
275 3 : for (final item in chips)
276 3 : FossChip(
277 6 : label: Text(item.label),
278 : size: FossChipSize.sm,
279 6 : removeLabel: widget.removeLabel,
280 6 : enabled: widget.enabled,
281 2 : onRemove: () => _toggle(item),
282 : ),
283 3 : SizedBox(
284 : width: 140,
285 3 : child: Stack(
286 : alignment: AlignmentDirectional.centerStart,
287 3 : children: [
288 : if (showPlaceholder)
289 1 : IgnorePointer(
290 1 : child: Text(
291 2 : widget.hintText ?? '',
292 : maxLines: 1,
293 : overflow: TextOverflow.ellipsis,
294 : textHeightBehavior: const TextHeightBehavior(
295 : leadingDistribution: TextLeadingDistribution.even,
296 : ),
297 2 : style: v.textStyle.copyWith(
298 2 : color: colors.mutedForeground.withValues(
299 3 : alpha: colors.mutedForeground.a * _placeholderOpacity,
300 : ),
301 : ),
302 : ),
303 : ),
304 3 : EditableText(
305 3 : controller: _controller,
306 3 : focusNode: _focusNode,
307 6 : readOnly: !widget.enabled,
308 9 : style: v.textStyle.copyWith(color: v.foreground),
309 3 : cursorColor: colors.foreground,
310 3 : backgroundCursorColor: colors.mutedForeground,
311 6 : selectionColor: colors.ring.withValues(
312 : alpha: _focusRingOpacity,
313 : ),
314 : cursorOpacityAnimates: true,
315 2 : onSubmitted: (_) => _activateHighlighted(),
316 : textHeightBehavior: const TextHeightBehavior(
317 : leadingDistribution: TextLeadingDistribution.even,
318 : ),
319 : ),
320 : ],
321 : ),
322 : ),
323 : ],
324 : );
325 : }
326 :
327 1 : @override
328 : Widget buildPopupSurface(BuildContext context) {
329 1 : final theme = context.fossTheme;
330 6 : final v = _apply(_resolve(theme, widget.size), widget.style);
331 1 : final options = filteredOptions;
332 : final Widget body;
333 1 : if (options.isEmpty) {
334 1 : body = Padding(
335 3 : padding: EdgeInsets.all(theme.spacing(2)),
336 1 : child: Text(
337 2 : widget.emptyText,
338 : textAlign: TextAlign.center,
339 3 : style: v.textStyle.copyWith(color: v.mutedForeground),
340 : ),
341 : );
342 : } else {
343 1 : body = ListView(
344 : shrinkWrap: true,
345 3 : padding: EdgeInsets.all(theme.spacing(1)),
346 1 : children: [
347 3 : for (var i = 0; i < options.length; i++)
348 1 : _ComboRow<T>(
349 1 : item: options[i],
350 : theme: theme,
351 : visuals: v,
352 : showIndicator: true,
353 5 : selected: widget.values.contains(options[i].value),
354 2 : highlighted: i == _highlight,
355 2 : onEnter: () => _highlightRow(i),
356 3 : onTap: () => _toggle(options[i]),
357 : ),
358 : ],
359 : );
360 : }
361 :
362 1 : return _popupChrome(v, body);
363 : }
364 : }
365 :
366 : /// A removable chip in the chips field: a label plus a trailing remove button.
|