Line data Source code
1 : import 'package:flutter/widgets.dart';
2 : import 'package:fossui/src/foundation/foss_since.dart';
3 : import 'package:fossui/src/theme/theme.dart';
4 :
5 : part 'foss_list_tile_style.dart';
6 :
7 : const double _iconSize = 18;
8 : const double _disabledOpacity = 0.64;
9 :
10 : /// Minimum row height, the tap-target floor. A one-line row lands on it
11 : /// exactly; a second subtitle line grows past it.
12 : const double _minHeight = 48;
13 :
14 : const double _ringWidth = 2;
15 : const double _ringOffset = 1;
16 :
17 : const Color _transparent = Color(0x00000000);
18 :
19 : /// Fill opacity of the filled row under the pointer: the input color at 64%,
20 : /// composited so it lands darker than the 4% rest fill in both themes.
21 : const double _hoverFillOpacity = 0.64;
22 :
23 : /// The surface a [FossListTile] paints at rest.
24 : enum FossListTileVariant {
25 : /// Tinted, rounded surface of its own. The default: a row in a plain list
26 : /// reads as its own band without a separator.
27 : filled,
28 :
29 : /// Transparent at rest, so the row inherits the surface under it. Use inside
30 : /// a FossCard or any container that already paints, where a second
31 : /// rectangle would double-draw.
32 : plain,
33 : }
34 :
35 : /// {@category Layout}
36 : /// {@template foss.listTile.preview}
37 : /// <img src="https://fossui.org/components/list-tile/overview/light.png"
38 : /// alt="FossListTile, light theme" width="480"
39 : /// style="max-width:100%;height:auto" />
40 : /// <img src="https://fossui.org/components/list-tile/overview/dark.png"
41 : /// alt="FossListTile, dark theme" width="480"
42 : /// style="max-width:100%;height:auto" />
43 : ///
44 : /// See the [list tile documentation ↗](https://fossui.org/docs/components/list-tile)
45 : /// or try it live in the
46 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/list_tile/fosslisttile/playground).
47 : /// {@endtemplate}
48 : ///
49 : /// A row in a list: an optional [leading] widget, a [title] over an optional
50 : /// [subtitle], and an optional [trailing] widget. A settings screen or an
51 : /// account list is mostly this one row repeated.
52 : ///
53 : /// Only [title] is required, and every gap collapses with the slot it belongs
54 : /// to. By default the row paints its own tinted, rounded surface, so a plain
55 : /// list reads as a stack of bands; pass [FossListTileVariant.plain] for a row
56 : /// inside a FossCard, where a second rectangle would double-draw.
57 : ///
58 : /// Pass [onTap] to make the whole row one target, which adds hover, pressed,
59 : /// and keyboard activation; leaving it null keeps the row inert at full
60 : /// opacity. That is a different state from `enabled: false`, which dims the row
61 : /// and blocks it.
62 : ///
63 : /// Two rules govern an interactive [trailing] widget, such as a FossSwitch.
64 : /// The trailing widget wins its own hit area, so a tap on it never reaches
65 : /// [onTap]; wire the two to different callbacks. Focus lands on the row first
66 : /// and the trailing control second, which is the order assistive tech announces
67 : /// them.
68 : ///
69 : /// The tile draws no separator and carries no outer margin, so it stays a row
70 : /// rather than a card: space filled rows from the list, and put a
71 : /// FossSeparator between plain ones.
72 : ///
73 : /// {@macro foss.customize}
74 : ///
75 : /// See also FossCard for the surface a group of plain rows usually sits on.
76 : ///
77 : /// ```dart
78 : /// FossListTile(
79 : /// leading: const Icon(bellIcon),
80 : /// title: const Text('Notifications'),
81 : /// subtitle: const Text('Push and email'),
82 : /// trailing: FossSwitch(
83 : /// value: notify,
84 : /// onChanged: (v) => setState(() => notify = v),
85 : /// ),
86 : /// onTap: openNotificationSettings,
87 : /// );
88 : /// ```
89 : @FossSince('0.1.2')
90 : class FossListTile extends StatefulWidget {
91 : /// {@macro foss.listTile.preview}
92 : ///
93 : /// Creates a list row showing [title]. Every other slot is optional; a null
94 : /// [onTap] leaves the row inert rather than disabled.
95 1 : const FossListTile({
96 : required this.title,
97 : this.subtitle,
98 : this.variant = FossListTileVariant.filled,
99 : this.leading,
100 : this.trailing,
101 : this.onTap,
102 : this.enabled = true,
103 : this.semanticLabel,
104 : this.style,
105 : super.key,
106 : });
107 :
108 : /// The primary line, typically a [Text]. Color, weight, and type step are
109 : /// applied through `DefaultTextStyle`. Clamped to one line.
110 : final Widget title;
111 :
112 : /// The secondary line below [title], typically a [Text]. Clamped to two
113 : /// lines.
114 : final Widget? subtitle;
115 :
116 : /// The surface the row paints at rest. Defaults to
117 : /// [FossListTileVariant.filled]; pass [FossListTileVariant.plain] for a row
118 : /// that sits inside a container which already paints its own surface.
119 : final FossListTileVariant variant;
120 :
121 : /// A widget at the start of the row (an icon, an avatar), themed as an icon
122 : /// and rendered at its own size.
123 : final Widget? leading;
124 :
125 : /// A widget at the end of the row (a switch, a chevron, a badge). An
126 : /// interactive one keeps its own gestures and its own focus stop.
127 : final Widget? trailing;
128 :
129 : /// Called when the row is tapped or activated with Enter or Space. Null
130 : /// leaves the row inert: no hover, no cursor change, and no focus stop.
131 : ///
132 : /// A tap on an interactive [trailing] widget goes to that widget and does not
133 : /// call this.
134 : final VoidCallback? onTap;
135 :
136 : /// Whether the row is interactive. False dims it to 64% and blocks both the
137 : /// pointer and the keyboard.
138 : final bool enabled;
139 :
140 : /// Accessibility name announced instead of [title] and [subtitle], for a row
141 : /// whose visible text does not read well on its own.
142 : final String? semanticLabel;
143 :
144 : /// Per-instance overrides layered on the theme-resolved style.
145 : final FossListTileStyle? style;
146 :
147 1 : @override
148 1 : State<FossListTile> createState() => _FossListTileState();
149 : }
150 :
151 : class _FossListTileState extends State<FossListTile> {
152 : final WidgetStatesController _states = WidgetStatesController();
153 :
154 : /// Whether the row itself responds: it has a callback and is not disabled.
155 5 : bool get _interactive => widget.onTap != null && widget.enabled;
156 :
157 1 : @override
158 : void initState() {
159 1 : super.initState();
160 1 : _sync();
161 : }
162 :
163 1 : @override
164 : void didUpdateWidget(FossListTile oldWidget) {
165 1 : super.didUpdateWidget(oldWidget);
166 1 : _sync();
167 : }
168 :
169 : /// Mirrors the disabled flag into the state set and drops any live pointer or
170 : /// focus state with it. A row that stops responding mid-press never gets the
171 : /// matching release, so the highlight would otherwise stick.
172 1 : void _sync() {
173 4 : _states.update(WidgetState.disabled, !widget.enabled);
174 1 : if (_interactive) return;
175 1 : _states
176 1 : ..update(WidgetState.pressed, false)
177 1 : ..update(WidgetState.hovered, false)
178 1 : ..update(WidgetState.focused, false);
179 : }
180 :
181 1 : @override
182 : void dispose() {
183 2 : _states.dispose();
184 1 : super.dispose();
185 : }
186 :
187 3 : void _setPressed(bool value) => _states.update(WidgetState.pressed, value);
188 :
189 1 : @override
190 : Widget build(BuildContext context) {
191 1 : final theme = context.fossTheme;
192 6 : final visuals = _resolve(theme, widget.variant).merge(widget.style);
193 : // Built once per build and reused across state changes, so a hover or a
194 : // press repaints the fill without rebuilding the slots.
195 1 : final content = _content(visuals);
196 :
197 1 : return MergeSemantics(
198 1 : child: Semantics(
199 2 : button: widget.onTap != null,
200 4 : enabled: widget.onTap == null ? null : widget.enabled,
201 2 : label: widget.semanticLabel,
202 1 : child: FocusableActionDetector(
203 1 : enabled: _interactive,
204 1 : mouseCursor: _interactive
205 : ? SystemMouseCursors.click
206 : : MouseCursor.defer,
207 3 : onShowHoverHighlight: (v) => _states.update(WidgetState.hovered, v),
208 3 : onShowFocusHighlight: (v) => _states.update(WidgetState.focused, v),
209 1 : actions: <Type, Action<Intent>>{
210 1 : ActivateIntent: CallbackAction<ActivateIntent>(
211 1 : onInvoke: (_) {
212 3 : widget.onTap?.call();
213 : return null;
214 : },
215 : ),
216 : },
217 1 : child: GestureDetector(
218 : behavior: HitTestBehavior.opaque,
219 3 : onTap: _interactive ? widget.onTap : null,
220 3 : onTapDown: _interactive ? (_) => _setPressed(true) : null,
221 3 : onTapUp: _interactive ? (_) => _setPressed(false) : null,
222 3 : onTapCancel: _interactive ? () => _setPressed(false) : null,
223 1 : child: ListenableBuilder(
224 1 : listenable: _states,
225 2 : builder: (context, _) => _paint(visuals, content),
226 : ),
227 : ),
228 : ),
229 : ),
230 : );
231 : }
232 :
233 1 : Widget _paint(_TileVisuals visuals, Widget content) {
234 2 : final states = _states.value;
235 :
236 1 : Widget row = ConstrainedBox(
237 2 : constraints: BoxConstraints(minHeight: visuals.minHeight),
238 1 : child: DecoratedBox(
239 1 : decoration: ShapeDecoration(
240 2 : color: visuals.background.resolve(states),
241 2 : shape: RoundedSuperellipseBorder(borderRadius: visuals.radius),
242 : ),
243 2 : child: Padding(padding: visuals.padding, child: content),
244 : ),
245 : );
246 :
247 2 : if (!widget.enabled) {
248 1 : row = Opacity(opacity: _disabledOpacity, child: row);
249 : }
250 :
251 1 : return CustomPaint(
252 1 : foregroundPainter: states.contains(WidgetState.focused)
253 1 : ? _FocusRingPainter(
254 1 : color: visuals.ring,
255 1 : offsetColor: visuals.ringOffset,
256 1 : radius: visuals.radius,
257 : )
258 : : null,
259 : child: row,
260 : );
261 : }
262 :
263 : /// Builds the slot row. Each gap belongs to the slot next to it, so a
264 : /// title-only tile carries no stray spacing.
265 1 : Widget _content(_TileVisuals visuals) {
266 1 : final icon = IconThemeData(
267 1 : size: visuals.iconSize,
268 1 : color: visuals.iconColor,
269 : );
270 :
271 1 : Widget text = Column(
272 : crossAxisAlignment: CrossAxisAlignment.start,
273 : mainAxisSize: MainAxisSize.min,
274 1 : spacing: visuals.textGap,
275 1 : children: [
276 1 : DefaultTextStyle.merge(
277 1 : style: visuals.titleStyle,
278 : maxLines: 1,
279 : softWrap: false,
280 : overflow: TextOverflow.ellipsis,
281 2 : child: widget.title,
282 : ),
283 2 : if (widget.subtitle case final subtitle?)
284 1 : DefaultTextStyle.merge(
285 1 : style: visuals.subtitleStyle,
286 : maxLines: 2,
287 : overflow: TextOverflow.ellipsis,
288 : child: subtitle,
289 : ),
290 : ],
291 : );
292 :
293 : // A semantic label replaces the row's text rather than adding to it, so the
294 : // lines it stands in for are dropped from the tree.
295 2 : if (widget.semanticLabel != null) {
296 1 : text = ExcludeSemantics(child: text);
297 : }
298 :
299 1 : return Row(
300 1 : spacing: visuals.gap,
301 1 : children: [
302 2 : if (widget.leading case final leading?)
303 1 : IconTheme.merge(data: icon, child: leading),
304 : // The text column takes the slack, so a long title ellipsizes instead
305 : // of pushing the trailing slot off the row.
306 1 : Expanded(child: text),
307 2 : if (widget.trailing case final trailing?)
308 1 : IconTheme.merge(data: icon, child: trailing),
309 : ],
310 : );
311 : }
312 : }
313 :
314 : /// Composites [base] at [opacity] of its own alpha over a fixed [surface],
315 : /// baking an opaque color for the filled row's lit state.
316 1 : Color _overlay(Color base, double opacity, Color surface) =>
317 4 : Color.alphaBlend(base.withValues(alpha: base.a * opacity), surface);
318 :
319 : /// Builds the default appearance for a variant from the theme tokens.
320 1 : _TileVisuals _resolve(FossThemeData theme, FossListTileVariant variant) {
321 1 : final c = theme.colors;
322 1 : final sp = theme.spacing;
323 :
324 : // A filled row already sits at the 4% tint, so its lit state has to step
325 : // past it; a plain row is transparent and lights to that same 4%. Pressed
326 : // matches hover either way: a band this wide does not need a third step.
327 : final (rest, lit, radius) = switch (variant) {
328 1 : FossListTileVariant.filled => (
329 1 : c.accent,
330 3 : _overlay(c.input, _hoverFillOpacity, c.background),
331 2 : theme.radii.lg,
332 : ),
333 4 : FossListTileVariant.plain => (_transparent, c.accent, theme.radii.sm),
334 : };
335 :
336 1 : return _TileVisuals(
337 1 : background: WidgetStateProperty.resolveWith(
338 1 : (states) =>
339 1 : states.contains(WidgetState.hovered) ||
340 1 : states.contains(WidgetState.pressed)
341 : ? lit
342 : : rest,
343 : ),
344 3 : padding: EdgeInsets.symmetric(horizontal: sp(4), vertical: sp(3)),
345 1 : gap: sp(4),
346 1 : textGap: sp(1),
347 : minHeight: _minHeight,
348 2 : radius: BorderRadius.all(Radius.circular(radius)),
349 5 : titleStyle: theme.typography.base.semibold.copyWith(color: c.foreground),
350 4 : subtitleStyle: theme.typography.sm.copyWith(color: c.mutedForeground),
351 1 : iconColor: c.foreground,
352 : iconSize: _iconSize,
353 1 : ring: c.ring,
354 1 : ringOffset: c.background,
355 : );
356 : }
357 :
358 : /// The fully resolved, non-null appearance of one tile. A public
359 : /// [FossListTileStyle] override is laid over it by [merge], so the widget reads
360 : /// only non-null fields.
361 : @immutable
362 : class _TileVisuals {
363 1 : const _TileVisuals({
364 : required this.background,
365 : required this.padding,
366 : required this.gap,
367 : required this.textGap,
368 : required this.minHeight,
369 : required this.radius,
370 : required this.titleStyle,
371 : required this.subtitleStyle,
372 : required this.iconColor,
373 : required this.iconSize,
374 : required this.ring,
375 : required this.ringOffset,
376 : });
377 :
378 : final WidgetStateProperty<Color> background;
379 : final EdgeInsetsGeometry padding;
380 : final double gap;
381 : final double textGap;
382 : final double minHeight;
383 : final BorderRadius radius;
384 : final TextStyle titleStyle;
385 : final TextStyle subtitleStyle;
386 : final Color iconColor;
387 : final double iconSize;
388 : final Color ring;
389 : final Color ringOffset;
390 :
391 : /// Lays a per-instance [override] over this resolved base, field by field.
392 1 : _TileVisuals merge(FossListTileStyle? override) {
393 : if (override == null) return this;
394 1 : final radius = override.borderRadius;
395 1 : return _TileVisuals(
396 2 : background: override.backgroundColor ?? background,
397 2 : padding: override.padding ?? padding,
398 2 : gap: override.gap ?? gap,
399 1 : textGap: textGap,
400 2 : minHeight: override.minHeight ?? minHeight,
401 : radius: radius != null
402 2 : ? BorderRadius.all(Radius.circular(radius))
403 1 : : this.radius,
404 3 : titleStyle: titleStyle.merge(override.titleStyle),
405 3 : subtitleStyle: subtitleStyle.merge(override.subtitleStyle),
406 1 : iconColor: iconColor,
407 2 : iconSize: override.iconSize ?? iconSize,
408 1 : ring: ring,
409 1 : ringOffset: ringOffset,
410 : );
411 : }
412 : }
413 :
414 : /// Paints the focus ring: a 2px superellipse outset just past the row edge,
415 : /// with a 1px offset gap filled with [offsetColor] so the ring reads as
416 : /// detached, matching the corner shape rather than a circular arc.
417 : class _FocusRingPainter extends CustomPainter {
418 1 : const _FocusRingPainter({
419 : required this.color,
420 : required this.offsetColor,
421 : required this.radius,
422 : });
423 :
424 : final Color color;
425 : final Color offsetColor;
426 : final BorderRadius radius;
427 :
428 1 : RSuperellipse _shape(Rect box, double inflate, double grow) =>
429 1 : RSuperellipse.fromRectAndCorners(
430 1 : box.inflate(inflate),
431 5 : topLeft: Radius.circular(radius.topLeft.x + grow),
432 5 : topRight: Radius.circular(radius.topRight.x + grow),
433 5 : bottomLeft: Radius.circular(radius.bottomLeft.x + grow),
434 5 : bottomRight: Radius.circular(radius.bottomRight.x + grow),
435 : );
436 :
437 1 : @override
438 : void paint(Canvas canvas, Size size) {
439 1 : final box = Offset.zero & size;
440 : canvas
441 1 : ..drawRSuperellipse(
442 3 : _shape(box, _ringOffset / 2, _ringOffset / 2),
443 1 : Paint()
444 2 : ..color = offsetColor
445 1 : ..style = PaintingStyle.stroke
446 1 : ..strokeWidth = _ringOffset,
447 : )
448 1 : ..drawRSuperellipse(
449 5 : _shape(box, _ringOffset + _ringWidth / 2, _ringOffset + _ringWidth / 2),
450 1 : Paint()
451 2 : ..color = color
452 1 : ..style = PaintingStyle.stroke
453 1 : ..strokeWidth = _ringWidth,
454 : );
455 : }
456 :
457 1 : @override
458 : bool shouldRepaint(_FocusRingPainter old) =>
459 3 : old.color != color ||
460 3 : old.offsetColor != offsetColor ||
461 3 : old.radius != radius;
462 : }
|