Line data Source code
1 : import 'package:flutter/services.dart';
2 : import 'package:flutter/widgets.dart';
3 : import 'package:fossui/src/foundation/foss_since.dart';
4 : import 'package:fossui/src/icons/foss_glyph.dart';
5 : import 'package:fossui/src/theme/theme.dart';
6 :
7 : part 'foss_rating_style.dart';
8 :
9 : // Fixed control geometry. An interactive mark pads out to the platform
10 : // tap-target floor, so an interactive row is wider than its glyphs while the
11 : // painted marks keep their size.
12 : const double _hitExtent = 48;
13 : const double _ringWidth = 2;
14 : const double _ringOffset = 1;
15 : const double _disabledOpacity = 0.64;
16 :
17 : /// Glyph box of a [FossRating], in logical pixels.
18 : ///
19 : /// The box is an icon extent rather than a text size, so it does not grow with
20 : /// the text scale and the row keeps its height.
21 : ///
22 : /// ```dart
23 : /// FossRating(value: 4, size: FossRatingSize.lg);
24 : /// ```
25 : @FossSince('0.1.3')
26 : enum FossRatingSize {
27 : /// Compact: 16 logical pixels, matching the inline icon step.
28 : sm,
29 :
30 : /// Default: 20 logical pixels.
31 : md,
32 :
33 : /// Prominent: 24 logical pixels.
34 : lg,
35 : }
36 :
37 : /// Granularity a [FossRating] snaps input to.
38 : ///
39 : /// Display is unaffected: a rating always paints the exact fraction it is
40 : /// given, so an average of 4.3 reads as 4.3 under either value.
41 : ///
42 : /// ```dart
43 : /// FossRating(
44 : /// value: 3.5,
45 : /// precision: FossRatingPrecision.half,
46 : /// onChanged: (v) {},
47 : /// );
48 : /// ```
49 : @FossSince('0.1.3')
50 : enum FossRatingPrecision {
51 : /// Input snaps to whole marks.
52 : full,
53 :
54 : /// Input snaps to halves.
55 : half,
56 : }
57 :
58 : /// {@category Inputs}
59 : /// {@template foss.rating.preview}
60 : /// <img src="https://fossui.org/components/rating/overview/light.png"
61 : /// alt="FossRating, light theme" width="480"
62 : /// style="max-width:100%;height:auto" />
63 : /// <img src="https://fossui.org/components/rating/overview/dark.png"
64 : /// alt="FossRating, dark theme" width="480"
65 : /// style="max-width:100%;height:auto" />
66 : ///
67 : /// See the [rating documentation ↗](https://fossui.org/docs/components/rating)
68 : /// or try it live in the
69 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/rating/fossrating/playground).
70 : /// {@endtemplate}
71 : ///
72 : /// A row of [count] star marks standing for [value], a [double] in `0..count`.
73 : ///
74 : /// One widget covers both jobs. Pass [onChanged] and the row takes a rating: a
75 : /// tap or a horizontal drag sets the value, arrow keys step it, and Home and
76 : /// End reach both ends. Leave [onChanged] null and the row is a read-only
77 : /// display that still announces its value, which is what an average needs.
78 : /// That is separate from `enabled: false`, an interactive row currently
79 : /// refusing input.
80 : ///
81 : /// [precision] snaps input to whole marks or to halves, and never affects
82 : /// display: the last filled mark is clipped to the exact fraction, so 4.3
83 : /// paints as 4.3. Supply [emptyIcon] and [filledIcon] to swap the marks for any
84 : /// icon set; both are clipped the same way, so a custom pair keeps the partial
85 : /// fill. Input never reaches 0, so a tap always registers as a rating. Colors
86 : /// and spacing come from `context.fossTheme`; pass a [FossRatingStyle] to
87 : /// [style] for a one-off.
88 : ///
89 : /// {@macro foss.customize}
90 : ///
91 : /// See also `FossSlider` for picking a continuous value from a range.
92 : ///
93 : /// ```dart
94 : /// FossRating(
95 : /// value: _score,
96 : /// precision: FossRatingPrecision.half,
97 : /// onChanged: (v) => setState(() => _score = v),
98 : /// semanticLabel: 'Overall rating',
99 : /// );
100 : /// ```
101 : @FossSince('0.1.3')
102 : class FossRating extends StatefulWidget {
103 : /// {@macro foss.rating.preview}
104 : ///
105 : /// Creates a rating at [value], out of [count] marks.
106 1 : const FossRating({
107 : required this.value,
108 : this.count = 5,
109 : this.onChanged,
110 : this.precision = FossRatingPrecision.full,
111 : this.size = FossRatingSize.md,
112 : this.enabled = true,
113 : this.emptyIcon,
114 : this.filledIcon,
115 : this.semanticLabel,
116 : this.style,
117 : super.key,
118 2 : }) : assert(count > 0, 'count must be positive');
119 :
120 : /// The current rating. Clamped into `0..count` when painted, so an
121 : /// out-of-range value reads as the nearest bound rather than throwing.
122 : final double value;
123 :
124 : /// How many marks the row draws. Defaults to 5.
125 : final int count;
126 :
127 : /// Called with the new rating on a tap, drag, or key press. A null callback
128 : /// makes the row a read-only display.
129 : final ValueChanged<double>? onChanged;
130 :
131 : /// Granularity input snaps to. Has no effect on display.
132 : final FossRatingPrecision precision;
133 :
134 : /// Glyph box of each mark.
135 : final FossRatingSize size;
136 :
137 : /// Whether an interactive row accepts input. A false value dims the row and
138 : /// announces it as disabled. It differs from a null [onChanged], which is a
139 : /// display rather than a blocked control.
140 : final bool enabled;
141 :
142 : /// The unfilled mark, sized to the [size] box and tinted with the empty
143 : /// color through the icon theme. Defaults to an outline star.
144 : final Widget? emptyIcon;
145 :
146 : /// The filled mark, sized to the [size] box, tinted with the filled color
147 : /// through the icon theme, and clipped for a partial mark. Defaults to a
148 : /// solid star.
149 : final Widget? filledIcon;
150 :
151 : /// Accessibility name for the control.
152 : final String? semanticLabel;
153 :
154 : /// Per-instance overrides layered on the theme-resolved style.
155 : final FossRatingStyle? style;
156 :
157 1 : @override
158 1 : State<FossRating> createState() => _FossRatingState();
159 : }
160 :
161 : class _FossRatingState extends State<FossRating> {
162 : final WidgetStatesController _states = WidgetStatesController();
163 : final GlobalKey _rowKey = GlobalKey();
164 :
165 3 : bool get _interactive => widget.onChanged != null;
166 :
167 4 : bool get _enabled => widget.enabled && _interactive;
168 :
169 4 : double get _count => widget.count.toDouble();
170 :
171 5 : double get _value => widget.value.clamp(0, _count);
172 :
173 3 : double get _step => switch (widget.precision) {
174 1 : FossRatingPrecision.full => 1.0,
175 1 : FossRatingPrecision.half => 0.5,
176 : };
177 :
178 1 : @override
179 : void dispose() {
180 2 : _states.dispose();
181 1 : super.dispose();
182 : }
183 :
184 : // Rounds a pointer position up onto the precision step, so the lower half of
185 : // a mark reads as the half and the upper half as the whole, then clamps into
186 : // `step..count`. Input never reaches 0: a tap on the first mark is a rating
187 : // of one, not a reset, so a stray tap cannot silently wipe a value.
188 1 : double _snap(double value) =>
189 8 : ((value / _step).ceil() * _step).clamp(_step, _count);
190 :
191 : // The step boundary above the value, capped at count, or null at the top. A
192 : // fractional value steps to its next boundary rather than past it.
193 1 : double? get _next {
194 7 : final next = ((_value / _step).floor() + 1) * _step;
195 6 : return _value < _count ? next.clamp(_step, _count) : null;
196 : }
197 :
198 : // The step boundary below the value, or null at or below the first step, so
199 : // a decrement never raises the value or clears it.
200 1 : double? get _previous {
201 7 : final previous = ((_value / _step).ceil() - 1) * _step;
202 2 : return previous >= _step ? previous : null;
203 : }
204 :
205 : // Maps a global pointer position to a snapped rating through the row's box,
206 : // so the maths respects the laid-out width and the reading direction. In an
207 : // interactive row every mark owns an equal slice of that width, hit box
208 : // included.
209 1 : double? _pointerToValue(Offset global) {
210 3 : final box = _rowKey.currentContext?.findRenderObject() as RenderBox?;
211 : if (box == null) return null;
212 2 : final width = box.size.width;
213 1 : if (width <= 0) return null;
214 2 : final dx = box.globalToLocal(global).dx;
215 3 : final ltr = Directionality.of(context) == TextDirection.ltr;
216 2 : final fromStart = (ltr ? dx : width - dx).clamp(0.0, width);
217 5 : return _snap(fromStart / (width / widget.count));
218 : }
219 :
220 1 : void _emit(double value) {
221 6 : if (value != widget.value) widget.onChanged?.call(value);
222 : }
223 :
224 1 : void _emitPointer(Offset global) {
225 2 : if (_pointerToValue(global) case final value?) _emit(value);
226 : }
227 :
228 1 : void _emitStep(double? value) {
229 1 : if (value != null) _emit(value);
230 : }
231 :
232 1 : Map<ShortcutActivator, Intent> _shortcuts(TextDirection direction) {
233 1 : final ltr = direction == TextDirection.ltr;
234 : const inc = _RatingIncrementIntent();
235 : const dec = _RatingDecrementIntent();
236 1 : return {
237 : const SingleActivator(LogicalKeyboardKey.arrowUp): inc,
238 : const SingleActivator(LogicalKeyboardKey.arrowDown): dec,
239 : const SingleActivator(LogicalKeyboardKey.arrowRight): ltr ? inc : dec,
240 : const SingleActivator(LogicalKeyboardKey.arrowLeft): ltr ? dec : inc,
241 : const SingleActivator(LogicalKeyboardKey.home): const _RatingMinIntent(),
242 : const SingleActivator(LogicalKeyboardKey.end): const _RatingMaxIntent(),
243 : };
244 : }
245 :
246 2 : Map<Type, Action<Intent>> get _actions => {
247 1 : _RatingIncrementIntent: CallbackAction<_RatingIncrementIntent>(
248 1 : onInvoke: (_) {
249 2 : _emitStep(_next);
250 : return null;
251 : },
252 : ),
253 1 : _RatingDecrementIntent: CallbackAction<_RatingDecrementIntent>(
254 1 : onInvoke: (_) {
255 2 : _emitStep(_previous);
256 : return null;
257 : },
258 : ),
259 1 : _RatingMinIntent: CallbackAction<_RatingMinIntent>(
260 1 : onInvoke: (_) {
261 2 : _emit(_step);
262 : return null;
263 : },
264 : ),
265 1 : _RatingMaxIntent: CallbackAction<_RatingMaxIntent>(
266 1 : onInvoke: (_) {
267 2 : _emit(_count);
268 : return null;
269 : },
270 : ),
271 : };
272 :
273 1 : @override
274 : Widget build(BuildContext context) {
275 7 : final v = _apply(_resolve(context.fossTheme, widget.size), widget.style);
276 1 : final direction = Directionality.of(context);
277 :
278 1 : final row = Row(
279 1 : key: _rowKey,
280 : mainAxisSize: MainAxisSize.min,
281 : // Interactive hit boxes abut, so the gap lives inside them and the
282 : // pointer maths can treat the row as equal slices.
283 2 : spacing: _interactive ? 0 : v.gap,
284 1 : children: [
285 4 : for (var i = 0; i < widget.count; i++)
286 4 : _mark(v, fill: (_value - i).clamp(0.0, 1.0)),
287 : ],
288 : );
289 :
290 1 : if (!_interactive) {
291 1 : return _hug(
292 1 : Semantics(
293 2 : label: widget.semanticLabel,
294 2 : value: _format(_value),
295 : child: row,
296 : ),
297 : );
298 : }
299 :
300 1 : Widget control = ListenableBuilder(
301 1 : listenable: _states,
302 4 : builder: (_, _) => _states.value.contains(WidgetState.focused)
303 1 : ? CustomPaint(
304 1 : foregroundPainter: _FocusRingPainter(
305 1 : color: v.ringColor,
306 1 : offsetColor: v.ringOffsetColor,
307 1 : radius: v.ringRadius,
308 : ),
309 : child: row,
310 : )
311 : : row,
312 : );
313 :
314 : // Input commits on release or once a horizontal drag wins, never on the
315 : // first contact, so a vertical scroll that starts on the row leaves the
316 : // value alone.
317 1 : control = GestureDetector(
318 : behavior: HitTestBehavior.opaque,
319 4 : onTapUp: _enabled ? (d) => _emitPointer(d.globalPosition) : null,
320 1 : onHorizontalDragStart: _enabled
321 3 : ? (d) => _emitPointer(d.globalPosition)
322 : : null,
323 1 : onHorizontalDragUpdate: _enabled
324 3 : ? (d) => _emitPointer(d.globalPosition)
325 : : null,
326 : child: control,
327 : );
328 :
329 1 : control = FocusableActionDetector(
330 1 : enabled: _enabled,
331 1 : mouseCursor: _enabled
332 : ? SystemMouseCursors.click
333 : : SystemMouseCursors.basic,
334 2 : shortcuts: _enabled ? _shortcuts(direction) : null,
335 2 : actions: _enabled ? _actions : null,
336 1 : onShowFocusHighlight: (value) =>
337 2 : _states.update(WidgetState.focused, value),
338 : child: control,
339 : );
340 :
341 1 : if (!_enabled) {
342 1 : control = Opacity(opacity: _disabledOpacity, child: control);
343 : }
344 :
345 : // Null at the bound the value cannot move past, which drops the action, so
346 : // a screen reader never announces an unchanged value at either end.
347 2 : final next = _enabled ? _next : null;
348 2 : final previous = _enabled ? _previous : null;
349 :
350 1 : return _hug(
351 1 : Semantics(
352 : slider: true,
353 1 : enabled: _enabled,
354 2 : label: widget.semanticLabel,
355 2 : value: _format(_value),
356 1 : increasedValue: next == null ? null : _format(next),
357 1 : decreasedValue: previous == null ? null : _format(previous),
358 2 : onIncrease: next == null ? null : () => _emit(next),
359 2 : onDecrease: previous == null ? null : () => _emit(previous),
360 : child: control,
361 : ),
362 : );
363 : }
364 :
365 : // Keeps the control at its content width even where the parent hands down a
366 : // tight one, as a list or a column does. Without this the row stretches, the
367 : // marks stay at the start, and the pointer maths reads slices that no longer
368 : // line up with them. The child is laid out loose, so it still hugs; the box
369 : // around it only fills what the parent insists on.
370 2 : Widget _hug(Widget child) => Align(
371 : alignment: AlignmentDirectional.centerStart,
372 : widthFactor: 1,
373 : heightFactor: 1,
374 : child: child,
375 : );
376 :
377 : // One mark: the empty layer with the filled layer clipped over it. The clip
378 : // and the stack both align directionally, so a partial mark fills from the
379 : // end under RTL without a second code path.
380 1 : Widget _mark(_RatingVisuals v, {required double fill}) {
381 1 : final glyph = Stack(
382 : alignment: AlignmentDirectional.centerStart,
383 1 : children: [
384 : // A full mark skips the empty layer: the outline strokes astride its
385 : // own path, so half of it would fringe the solid fill laid over it.
386 1 : if (fill < 1)
387 1 : _layer(
388 1 : v.glyphSize,
389 1 : v.emptyColor,
390 2 : widget.emptyIcon,
391 2 : StarGlyph(v.emptyColor),
392 : ),
393 1 : if (fill > 0)
394 1 : ClipRect(
395 1 : child: Align(
396 : alignment: AlignmentDirectional.centerStart,
397 : widthFactor: fill,
398 : // A null factor makes that axis take the incoming maximum, so the
399 : // height has to shrink-wrap explicitly or the mark grows tall.
400 : heightFactor: 1,
401 1 : child: _layer(
402 1 : v.glyphSize,
403 1 : v.filledColor,
404 2 : widget.filledIcon,
405 2 : StarGlyph(v.filledColor, filled: true),
406 : ),
407 : ),
408 : ),
409 : ],
410 : );
411 :
412 1 : return _interactive
413 1 : ? SizedBox(
414 : width: _hitExtent,
415 : height: _hitExtent,
416 1 : child: Center(child: glyph),
417 : )
418 : : glyph;
419 : }
420 :
421 : // One layer of a mark at the glyph box: the caller's icon when supplied,
422 : // otherwise the built-in star. A supplied icon takes the mark's color and box
423 : // from the icon theme, so an explicit color on it still wins, and is excluded
424 : // from the semantics tree so it does not announce once per mark.
425 1 : Widget _layer(double box, Color color, Widget? icon, FossGlyph fallback) =>
426 1 : SizedBox.square(
427 : dimension: box,
428 : child: icon == null
429 1 : ? FossGlyphIcon(fallback)
430 1 : : IconTheme.merge(
431 1 : data: IconThemeData(color: color, size: box),
432 1 : child: ExcludeSemantics(child: icon),
433 : ),
434 : );
435 :
436 3 : String _format(double value) => value == value.roundToDouble()
437 4 : ? '${value.toStringAsFixed(0)} of ${widget.count}'
438 4 : : '${value.toStringAsFixed(1)} of ${widget.count}';
439 : }
440 :
441 : class _RatingIncrementIntent extends Intent {
442 2 : const _RatingIncrementIntent();
443 : }
444 :
445 : class _RatingDecrementIntent extends Intent {
446 2 : const _RatingDecrementIntent();
447 : }
448 :
449 : class _RatingMinIntent extends Intent {
450 2 : const _RatingMinIntent();
451 : }
452 :
453 : class _RatingMaxIntent extends Intent {
454 2 : const _RatingMaxIntent();
455 : }
456 :
457 : /// Builds the default appearance for [size] from the theme tokens.
458 1 : _RatingVisuals _resolve(FossThemeData theme, FossRatingSize size) {
459 1 : final c = theme.colors;
460 : final (glyphSize, gap) = switch (size) {
461 3 : FossRatingSize.sm => (16.0, theme.spacing(0.5)),
462 3 : FossRatingSize.md => (20.0, theme.spacing(1)),
463 3 : FossRatingSize.lg => (24.0, theme.spacing(1)),
464 : };
465 1 : return _RatingVisuals(
466 1 : filledColor: c.primary,
467 1 : emptyColor: c.mutedForeground,
468 1 : ringColor: c.ring,
469 1 : ringOffsetColor: c.background,
470 2 : ringRadius: theme.radii.sm,
471 : glyphSize: glyphSize,
472 : gap: gap,
473 : );
474 : }
475 :
476 : /// Lays a per-instance [override] over the resolved [base], field by field.
477 1 : _RatingVisuals _apply(_RatingVisuals base, FossRatingStyle? override) {
478 : if (override == null) return base;
479 1 : return _RatingVisuals(
480 2 : filledColor: override.filledColor ?? base.filledColor,
481 2 : emptyColor: override.emptyColor ?? base.emptyColor,
482 1 : ringColor: base.ringColor,
483 1 : ringOffsetColor: base.ringOffsetColor,
484 1 : ringRadius: base.ringRadius,
485 1 : glyphSize: override.glyphSize ?? base.glyphSize,
486 1 : gap: override.gap ?? base.gap,
487 : );
488 : }
489 :
490 : /// The fully resolved, non-null appearance for one size. A [FossRatingStyle]
491 : /// override is laid over it by [_apply], so the widget reads only non-null
492 : /// fields. The ring stays token-driven and is not overridable per instance.
493 : @immutable
494 : class _RatingVisuals {
495 1 : const _RatingVisuals({
496 : required this.filledColor,
497 : required this.emptyColor,
498 : required this.ringColor,
499 : required this.ringOffsetColor,
500 : required this.ringRadius,
501 : required this.glyphSize,
502 : required this.gap,
503 : });
504 :
505 : final Color filledColor;
506 : final Color emptyColor;
507 : final Color ringColor;
508 : final Color ringOffsetColor;
509 : final double ringRadius;
510 : final double glyphSize;
511 : final double gap;
512 : }
513 :
514 : /// Paints the focus ring around the whole row: the house 2px ring in the `ring`
515 : /// role over a 1px offset in `background`, on superellipse corners.
516 : class _FocusRingPainter extends CustomPainter {
517 1 : const _FocusRingPainter({
518 : required this.color,
519 : required this.offsetColor,
520 : required this.radius,
521 : });
522 :
523 : final Color color;
524 : final Color offsetColor;
525 : final double radius;
526 :
527 1 : RSuperellipse _shape(Rect box, double grow) =>
528 1 : RSuperellipse.fromRectAndRadius(
529 1 : box.inflate(grow),
530 3 : Radius.circular(radius + grow),
531 : );
532 :
533 1 : @override
534 : void paint(Canvas canvas, Size size) {
535 1 : final box = Offset.zero & size;
536 : canvas
537 1 : ..drawRSuperellipse(
538 2 : _shape(box, _ringOffset / 2),
539 1 : Paint()
540 2 : ..color = offsetColor
541 1 : ..style = PaintingStyle.stroke
542 1 : ..strokeWidth = _ringOffset,
543 : )
544 1 : ..drawRSuperellipse(
545 3 : _shape(box, _ringOffset + _ringWidth / 2),
546 1 : Paint()
547 2 : ..color = color
548 1 : ..style = PaintingStyle.stroke
549 1 : ..strokeWidth = _ringWidth,
550 : );
551 : }
552 :
553 1 : @override
554 : bool shouldRepaint(_FocusRingPainter old) =>
555 3 : old.color != color ||
556 3 : old.offsetColor != offsetColor ||
557 3 : old.radius != radius;
558 : }
|