From b872a27c4e5b23e7e8f7d9bf01d1ac66b43080ea Mon Sep 17 00:00:00 2001 From: Qun Cheng <36861262+QuncCccccc@users.noreply.github.com> Date: Tue, 10 Sep 2024 12:41:23 -0700 Subject: [PATCH] `CupertinoSlidingSegmentedControl` update (#152976) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR is to improve `CupertinoSlidingSegmentedControl` fidelity and add a new property `setEnabled` so that segments can be disabled now. Fidelity update includes: * small change on default thumb radius (Based on iOS 17 Figma file) * separator height (Based on the comparison with SegmentedControl example in Xcode) * segment min padding (Based on iOS 17 Figma file) * thumb scale alignment (Based on the comparison with SegmentedControl example in Xcode). If the thumb is on the first or last position in SegmentedControl, the alignment should be `Alignment.leftCenter` and `Alignment.rightCenter` respectively, assuming the text direction is left to right. For segments in middle, they should have center alignment as previously. * TextStyle update (Based on both the Figma file and the Xcode example) * Clipped thumb shadow if the shadow is outside of the segmented control (Based on the Xcode example) * Fixed the overall size shaking issue during segment switching on macOS and iOS
Alignment update demo https://github.com/user-attachments/assets/6de3986f-6810-4dc4-8688-f87120557d89
Comparison before and after Before: ![Screenshot 2024-08-08 at 1 42 57 PM](https://github.com/user-attachments/assets/fe2e49a8-4bbd-4d54-9aba-1f47ab9bd9d9) After: ![Screenshot 2024-08-08 at 1 43 50 PM](https://github.com/user-attachments/assets/d3292f74-8d04-40ed-ae72-bf2e9b1751a4)
Shaking issue Before: https://github.com/user-attachments/assets/910d1271-75ea-4cec-8666-24090f9d4fb0 After: https://github.com/user-attachments/assets/bc5ae3e1-600d-49a6-95d9-b1f5d1bd9f6d
The `disabledChildren` feature can be used to disable segments. The default disabled color comes from the inspection in the Xcode example.
Disabled feature demos Disabled segment cannot be highlighted: https://github.com/user-attachments/assets/70339364-23d5-41c7-b071-c7abe92abd62 `groupValue` can still be highlighted programmatically if it is disabled. ![Screenshot 2024-09-04 at 5 45 25 PM](https://github.com/user-attachments/assets/99d37903-3605-475f-b87a-ae118a23e94d)
--- .../cupertino/sliding_segmented_control.dart | 158 +++++- .../sliding_segmented_control_test.dart | 470 ++++++++++++++++-- 2 files changed, 553 insertions(+), 75 deletions(-) diff --git a/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart b/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart index 3d56616a24..281dd1886a 100644 --- a/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart +++ b/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart @@ -18,13 +18,17 @@ import 'package:flutter/widgets.dart'; import 'colors.dart'; // Extracted from https://developer.apple.com/design/resources/. +// Default values have been updated to match iOS 17 figma file: https://www.figma.com/community/file/1248375255495415511. // Minimum padding from edges of the segmented control to edges of // encompassing widget. const EdgeInsetsGeometry _kHorizontalItemPadding = EdgeInsets.symmetric(vertical: 2, horizontal: 3); +// The corner radius of the segmented control. +const Radius _kCornerRadius = Radius.circular(9); + // The corner radius of the thumb. -const Radius _kThumbRadius = Radius.circular(6.93); +const Radius _kThumbRadius = Radius.circular(7); // The amount of space by which to expand the thumb from the size of the currently // selected child. const EdgeInsets _kThumbInsets = EdgeInsets.symmetric(horizontal: 1); @@ -40,9 +44,9 @@ const CupertinoDynamicColor _kThumbColor = CupertinoDynamicColor.withBrightness( ); // The amount of space by which to inset each separator. -const EdgeInsets _kSeparatorInset = EdgeInsets.symmetric(vertical: 6); +const EdgeInsets _kSeparatorInset = EdgeInsets.symmetric(vertical: 5); const double _kSeparatorWidth = 1; -const Radius _kSeparatorRadius = Radius.circular(_kSeparatorWidth/2); +const Radius _kSeparatorRadius = Radius.circular(_kSeparatorWidth / 2); // The minimum scale factor of the thumb, when being pressed on for a sufficient // amount of time. @@ -50,7 +54,7 @@ const double _kMinThumbScale = 0.95; // The minimum horizontal distance between the edges of the separator and the // closest child. -const double _kSegmentMinPadding = 9.25; +const double _kSegmentMinPadding = 10; // The threshold value used in hasDraggedTooFar, for checking against the square // L2 distance from the location of the current drag pointer, to the closest @@ -59,17 +63,24 @@ const double _kSegmentMinPadding = 9.25; // Both the mechanism and the value are speculated. const double _kTouchYDistanceThreshold = 50.0 * 50.0; -// The corner radius of the segmented control. -// -// Inspected from iOS 13.2 simulator. -const double _kCornerRadius = 8; - // The minimum opacity of an unselected segment, when the user presses on the // segment and it starts to fadeout. // -// Inspected from iOS 13.2 simulator. +// Inspected from iOS 17.5 simulator. const double _kContentPressedMinOpacity = 0.2; +// Inspected from iOS 17.5 simulator. +const double _kFontSize = 13.0; + +// Inspected from iOS 17.5 simulator. +const FontWeight _kFontWeight = FontWeight.w500; + +// Inspected from iOS 17.5 simulator. +const FontWeight _kHighlightedFontWeight = FontWeight.w600; + +// Inspected from iOS 17.5 simulator +const Color _kDisabledContentColor = Color.fromARGB(115, 122, 122, 122); + // The spring animation used when the thumb changes its rect. final SpringSimulation _kThumbSpringAnimationSimulation = SpringSimulation( const SpringDescription(mass: 1, stiffness: 503.551, damping: 44.8799), @@ -91,19 +102,23 @@ class _Segment extends StatefulWidget { required this.pressed, required this.highlighted, required this.isDragging, + required this.enabled, + required this.segmentLocation, }) : super(key: key); final Widget child; final bool pressed; final bool highlighted; + final bool enabled; + final _SegmentLocation segmentLocation; // Whether the thumb of the parent widget (CupertinoSlidingSegmentedControl) // is currently being dragged. final bool isDragging; - bool get shouldFadeoutContent => pressed && !highlighted; - bool get shouldScaleContent => pressed && highlighted && isDragging; + bool get shouldFadeoutContent => pressed && !highlighted && enabled; + bool get shouldScaleContent => pressed && highlighted && isDragging && enabled; @override _SegmentState createState() => _SegmentState(); @@ -151,6 +166,12 @@ class _SegmentState extends State<_Segment> with TickerProviderStateMixin< @override Widget build(BuildContext context) { + final Alignment scaleAlignment = switch (widget.segmentLocation) { + _SegmentLocation.leftmost => Alignment.centerLeft, + _SegmentLocation.rightmost => Alignment.centerRight, + _SegmentLocation.inbetween => Alignment.center, + }; + return MetaData( // Expand the hitTest area of this widget. behavior: HitTestBehavior.opaque, @@ -164,10 +185,15 @@ class _SegmentState extends State<_Segment> with TickerProviderStateMixin< child: AnimatedDefaultTextStyle( style: DefaultTextStyle.of(context) .style - .merge(TextStyle(fontWeight: widget.highlighted ? FontWeight.w500 : FontWeight.normal)), + .merge(TextStyle( + fontWeight: widget.highlighted ? _kHighlightedFontWeight : _kFontWeight, + fontSize: _kFontSize, + color: widget.enabled ? null : _kDisabledContentColor, + )), duration: _kHighlightAnimationDuration, curve: Curves.ease, child: ScaleTransition( + alignment: scaleAlignment, scale: highlightPressScaleAnimation, child: widget.child, ), @@ -178,11 +204,12 @@ class _SegmentState extends State<_Segment> with TickerProviderStateMixin< // the same and will always be greater than equal to that of the // visible child (at index 0), to keep the size of the entire // SegmentedControl widget consistent throughout the animation. - Offstage( - child: DefaultTextStyle.merge( - style: const TextStyle(fontWeight: FontWeight.w500), - child: widget.child, + DefaultTextStyle.merge( + style: const TextStyle( + fontWeight: _kHighlightedFontWeight, + fontSize: _kFontSize, ), + child: widget.child ), ], ), @@ -321,6 +348,7 @@ class CupertinoSlidingSegmentedControl extends StatefulWidget super.key, required this.children, required this.onValueChanged, + this.disabledChildren = const {}, this.groupValue, this.thumbColor = _kThumbColor, this.padding = _kHorizontalItemPadding, @@ -341,6 +369,20 @@ class CupertinoSlidingSegmentedControl extends StatefulWidget /// The map must have more than one entry. final Map children; + /// The set of identifying keys that correspond to the segments that should be + /// disabled. + /// + /// Disabled children cannot be selected by dragging, but they can be selected + /// programmatically. For example, if the [groupValue] is set to a disabled + /// segment, the segment is still selected but the segment content looks disabled. + /// + /// If an enabled segment is selected by dragging gesture and becomes disabled + /// before dragging finishes, [onValueChanged] will be triggered when finger is + /// released and the disabled segment is selected. + /// + /// By default, all segments are selectable. + final Set disabledChildren; + /// The identifier of the widget that is currently selected. /// /// This must be one of the keys in the [Map] of [children]. @@ -499,11 +541,15 @@ class _SegmentedControlState extends State _startedOnSelectedSegment ?? false; + bool get isThumbDragging => (_startedOnSelectedSegment ?? false) && !_startedOnDisabledSegment; // Converts local coordinate to segments. T segmentForXPosition(double dx) { @@ -554,6 +600,7 @@ class _SegmentedControlState extends State extends State extends State extends State extends State extends State _SegmentLocation.leftmost, + TextDirection.ltr when index == widget.children.length - 1 => _SegmentLocation.rightmost, + TextDirection.rtl when index == widget.children.length - 1 => _SegmentLocation.leftmost, + TextDirection.rtl when index == 0 => _SegmentLocation.rightmost, + TextDirection.ltr || TextDirection.rtl => _SegmentLocation.inbetween, + }; children.add( Semantics( button: true, - onTap: () { widget.onValueChanged(entry.key); }, + onTap: () { + if (widget.disabledChildren.contains(entry.key)) { + return; + } + widget.onValueChanged(entry.key); + }, inMutuallyExclusiveGroup: true, selected: widget.groupValue == entry.key, child: MouseRegion( @@ -683,6 +756,8 @@ class _SegmentedControlState extends State extends State extends MultiChildRenderOb class _SegmentedControlContainerBoxParentData extends ContainerBoxParentData { } +enum _SegmentLocation { + leftmost, + rightmost, + inbetween; +} + // The behavior of a UISegmentedControl as observed on iOS 13.1: // // 1. Tap up inside events will set the current selected index to the index of the @@ -1131,6 +1215,9 @@ class _RenderSegmentedControl extends RenderBox void paint(PaintingContext context, Offset offset) { final List children = getChildrenAsList(); + // Children contains both segment and separator and the order is segment -> + // separator -> segment. So to paint separators, index should start from 1 and + // the step should be 2. for (int index = 1; index < childCount; index += 2) { _paintSeparator(context, offset, children[index]); } @@ -1164,8 +1251,24 @@ class _RenderSegmentedControl extends RenderBox final Rect unscaledThumbRect = state.thumbAnimatable?.evaluate(state.thumbController) ?? newThumbRect; currentThumbRect = unscaledThumbRect; + + final _SegmentLocation childLocation; + if (highlightedChildIndex == 0) { + childLocation = _SegmentLocation.leftmost; + } else if (highlightedChildIndex == children.length ~/ 2) { + childLocation = _SegmentLocation.rightmost; + } else { + childLocation = _SegmentLocation.inbetween; + } + + final double delta = switch (childLocation) { + _SegmentLocation.leftmost => unscaledThumbRect.width - unscaledThumbRect.width * thumbScale, + _SegmentLocation.rightmost => unscaledThumbRect.width * thumbScale - unscaledThumbRect.width, + _SegmentLocation.inbetween => 0, + }; + final Rect thumbRect = Rect.fromCenter( - center: unscaledThumbRect.center, + center: unscaledThumbRect.center - Offset(delta / 2, 0), width: unscaledThumbRect.width * thumbScale, height: unscaledThumbRect.height * thumbScale, ); @@ -1176,6 +1279,9 @@ class _RenderSegmentedControl extends RenderBox } for (int index = 0; index < children.length; index += 2) { + // Children contains both segment and separator and the order is segment -> + // separator -> segment. So to paint separators, indes should start from 0 and + // the step should be 2. _paintChild(context, offset, children[index]); } } diff --git a/packages/flutter/test/cupertino/sliding_segmented_control_test.dart b/packages/flutter/test/cupertino/sliding_segmented_control_test.dart index a5975b7741..c944406bac 100644 --- a/packages/flutter/test/cupertino/sliding_segmented_control_test.dart +++ b/packages/flutter/test/cupertino/sliding_segmented_control_test.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// reduced-test-set: +// This file is run as part of a reduced test set in CI on Mac and Windows +// machines. +@Tags(['reduced-test-set']) +library; import 'dart:collection'; import 'package:flutter/cupertino.dart'; @@ -274,7 +279,7 @@ void main() { DefaultTextStyle textStyle = tester.widget(find.widgetWithText(DefaultTextStyle, 'Child 1').first); - expect(textStyle.style.fontWeight, FontWeight.w500); + expect(textStyle.style.fontWeight, FontWeight.w600); await tester.tap(find.byIcon(const IconData(1))); await tester.pump(); @@ -283,7 +288,7 @@ void main() { textStyle = tester.widget(find.widgetWithText(DefaultTextStyle, 'Child 1').first); expect(groupValue, 1); - expect(textStyle.style.fontWeight, FontWeight.normal); + expect(textStyle.style.fontWeight, FontWeight.w500); }, ); @@ -395,6 +400,34 @@ void main() { expect(getHighlightedIndex(tester), null); }); + testWidgets('Disabled segment can be selected programmtically', (WidgetTester tester) async { + const Map children = { + 0: Text('Child 1'), + 1: Text('Child 2'), + 2: Text('Child 3'), + }; + + groupValue = 0; + await tester.pumpWidget( + StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return boilerplate( + builder: (BuildContext context) { + return CupertinoSlidingSegmentedControl( + children: children, + disabledChildren: const {0}, + groupValue: groupValue, + onValueChanged: defaultCallback, + ); + }, + ); + }, + ), + ); + + expect(getHighlightedIndex(tester), 0); + }); + testWidgets('Long press not-selected child interactions', (WidgetTester tester) async { const Map children = { 0: Text('Child 1'), @@ -538,7 +571,7 @@ void main() { // to each child equally. final double childWidth = (segmentedControl.size.width - 8) / 3; - expect(childWidth, 200.0 + 9.25 * 2); + expect(childWidth, 200.0 + 10 * 2); }); testWidgets('If proportionalWidth is true, the width of each segmented ' @@ -573,13 +606,13 @@ void main() { } final Size firstChildSize = getChildSize(0); - expect(firstChildSize.width, 50 + 9.25 * 2); + expect(firstChildSize.width, 50 + 10.0 * 2); final Size secondChildSize = getChildSize(1); - expect(secondChildSize.width, 100 + 9.25 * 2); + expect(secondChildSize.width, 100 + 10.0 * 2); final Size thirdChildSize = getChildSize(2); - expect(thirdChildSize.width, 70 + 9.25 * 2); + expect(thirdChildSize.width, 70 + 10.0 * 2); // Overall segment control width is the sum of the segment widths + horizontal paddings + 2 separator width. final RenderBox segmentedControl = tester.renderObject( @@ -622,25 +655,25 @@ void main() { } Size firstChildSize = getChildSize(0); - expect(firstChildSize.width, 200 + 9.25 * 2); + expect(firstChildSize.width, 200 + 10.0 * 2); Size secondChildSize = getChildSize(1); - expect(secondChildSize.width, 200 + 9.25 * 2); + expect(secondChildSize.width, 200 + 10.0 * 2); Size thirdChildSize = getChildSize(2); - expect(thirdChildSize.width, 200 + 9.25 * 2); + expect(thirdChildSize.width, 200 + 10.0 * 2); setState!(() { proportionalWidth = true; }); await tester.pump(); firstChildSize = getChildSize(0); - expect(firstChildSize.width, 50 + 9.25 * 2); + expect(firstChildSize.width, 50 + 10.0 * 2); secondChildSize = getChildSize(1); - expect(secondChildSize.width, 200 + 9.25 * 2); + expect(secondChildSize.width, 200 + 10.0 * 2); thirdChildSize = getChildSize(2); - expect(thirdChildSize.width, 70 + 9.25 * 2); + expect(thirdChildSize.width, 70 + 10.0 * 2); }); testWidgets('If proportionalWidth is true, the width of each segmented ' @@ -675,13 +708,13 @@ void main() { } Size firstChildSize = getChildSize(0); - expect(firstChildSize.width, 50 + 9.25 * 2); + expect(firstChildSize.width, 50 + 10.0 * 2); Size secondChildSize = getChildSize(1); - expect(secondChildSize.width, 100 + 9.25 * 2); + expect(secondChildSize.width, 100 + 10.0 * 2); Size thirdChildSize = getChildSize(2); - expect(thirdChildSize.width, 70 + 9.25 * 2); + expect(thirdChildSize.width, 70 + 10.0 * 2); setState!(() { children = { @@ -693,13 +726,13 @@ void main() { await tester.pump(); firstChildSize = getChildSize(0); - expect(firstChildSize.width, 0 + 9.25 * 2); + expect(firstChildSize.width, 0 + 10.0 * 2); secondChildSize = getChildSize(1); - expect(secondChildSize.width, 220 + 9.25 * 2); + expect(secondChildSize.width, 220 + 10.0 * 2); thirdChildSize = getChildSize(2); - expect(thirdChildSize.width, 170 + 9.25 * 2); + expect(thirdChildSize.width, 170 + 10.0 * 2); }); @@ -737,19 +770,19 @@ void main() { ); } - // Without constraints, the overall size should be 405.5: 50 + 100 + 200 - // + 9.25 * 6(horizontal padding). To fit in 194(allowed max width - padding), + // Without constraints, the overall size should be 410: 50 + 100 + 200 + // + 10.0 * 6(horizontal padding). To fit in 194(allowed max width - padding), // each segment width should scale down to original width * (194 - separator) / 413.5. final Size firstChildSize = getChildSize(0); const double maxAllowedTotal = 200 - 6 - 2; - const double originalTotal = 405.5; - expect(firstChildSize.width, (50 + 9.25 * 2) * maxAllowedTotal / originalTotal); + const double originalTotal = 410; + expect(firstChildSize.width, (50 + 10.0 * 2) * maxAllowedTotal / originalTotal); final Size secondChildSize = getChildSize(1); - expect(secondChildSize.width, (100 + 9.25 * 2) * maxAllowedTotal / originalTotal); + expect(secondChildSize.width, (100 + 10.0 * 2) * maxAllowedTotal / originalTotal); final Size thirdChildSize = getChildSize(2); - expect(thirdChildSize.width, (200 + 9.25 * 2) * maxAllowedTotal / originalTotal); + expect(thirdChildSize.width, (200 + 10.0 * 2) * maxAllowedTotal / originalTotal); }); testWidgets('If proportionalWidth is true and the overall segment control width ' @@ -786,19 +819,19 @@ void main() { ); } - // Without constraints, the overall size should be 155.5: 20 + 30 + 50 - // + 9.25 * 6(horizontal padding). To fit in 194(allowed max width - padding), + // Without constraints, the overall size should be 160.0: 20 + 30 + 50 + // + 10.0 * 6(horizontal padding). To fit in 194(allowed max width - padding), // each segment width should scale up to original width * (194 - separator) / 155.5. final Size firstChildSize = getChildSize(0); const double constraintsMinWidth = 200 - 6 - 2; - const double originalTotal = 155.5; - expect(firstChildSize.width, moreOrLessEquals((20 + 9.25 * 2) * constraintsMinWidth / originalTotal)); + const double originalTotal = 160.0; + expect(firstChildSize.width, moreOrLessEquals((20 + 10.0 * 2) * constraintsMinWidth / originalTotal)); final Size secondChildSize = getChildSize(1); - expect(secondChildSize.width, moreOrLessEquals((30 + 9.25 * 2) * constraintsMinWidth / originalTotal)); + expect(secondChildSize.width, moreOrLessEquals((30 + 10.0 * 2) * constraintsMinWidth / originalTotal)); final Size thirdChildSize = getChildSize(2); - expect(thirdChildSize.width, moreOrLessEquals((50 + 9.25 * 2) * constraintsMinWidth / originalTotal)); + expect(thirdChildSize.width, moreOrLessEquals((50 + 10.0 * 2) * constraintsMinWidth / originalTotal)); }); testWidgets('Width is finite in unbounded space', (WidgetTester tester) async { @@ -830,7 +863,7 @@ void main() { expect( segmentedControl.size.width, - 70 * 2 + 9.25 * 4 + 3 * 2 + 1, // 2 children + 4 child padding + 2 outer padding + 1 separator + 70 * 2 + 10.0 * 4 + 3 * 2 + 1, // 2 children + 4 child padding + 2 outer padding + 1 separator ); }); @@ -1042,13 +1075,13 @@ void main() { expect(groupValue, 0); final Rect firstChild = tester.getRect(find.ancestor(of: find.byWidget(children[0]!), matching: find.byType(MetaData))); - expect(firstChild.width, 50.0 + 9.25 * 2); + expect(firstChild.width, 50.0 + 10.0 * 2); final Rect secondChild = tester.getRect(find.ancestor(of: find.byWidget(children[1]!), matching: find.byType(MetaData))); - expect(secondChild.width, 0.0 + 9.25 * 2); + expect(secondChild.width, 0.0 + 10.0 * 2); final Rect thirdChild = tester.getRect(find.ancestor(of: find.byWidget(children[2]!), matching: find.byType(MetaData))); - expect(thirdChild.width, 100.0 + 9.25 * 2); + expect(thirdChild.width, 100.0 + 10.0 * 2); final Finder child0 = find.ancestor(of: find.byWidget(children[0]!), matching: find.byType(MetaData)); final Offset centerOfChild0 = tester.getCenter(child0); @@ -1163,18 +1196,30 @@ void main() { await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); - // The thumb shrinks but does not moves towards left. + // The thumb shrinks but does not moves towards left; the shrink alignment + // is Alignment.centerRight, with ltr text direction because "Child 2" is + // the trailing item. expect(currentThumbScale(tester), lessThan(1)); + double centerDelta = tester.getSize(find.text('Child 2')).width * (1 - currentThumbScale(tester)) / 2; expect( - currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center, - offsetMoreOrLessEquals(tester.getCenter(find.text('Child 2')), epsilon: 0.01), + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dy, + moreOrLessEquals(tester.getCenter(find.text('Child 2')).dy, epsilon: 0.01), + ); + expect( + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dx, + moreOrLessEquals(tester.getCenter(find.text('Child 2')).dx - centerDelta, epsilon: 0.01), ); await tester.pumpAndSettle(); expect(currentThumbScale(tester), moreOrLessEquals(0.95, epsilon: 0.01)); + centerDelta = tester.getSize(find.text('Child 2')).width * (1 - currentThumbScale(tester)); expect( - currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center, - offsetMoreOrLessEquals(tester.getCenter(find.text('Child 2')), epsilon: 0.01), + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dy, + moreOrLessEquals(tester.getCenter(find.text('Child 2')).dy, epsilon: 0.01), + ); + expect( + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dx, + moreOrLessEquals(tester.getCenter(find.text('Child 2')).dx - centerDelta / 2, epsilon: 0.01), ); // Drag to Child 1. @@ -1191,9 +1236,14 @@ void main() { await tester.pumpAndSettle(); expect(currentThumbScale(tester), moreOrLessEquals(0.95, epsilon: 0.01)); + centerDelta = tester.getSize(find.text('Child 1')).width * (1 - currentThumbScale(tester)); expect( - currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center, - offsetMoreOrLessEquals(tester.getCenter(find.text('Child 1')), epsilon: 0.01), + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dy, + moreOrLessEquals(tester.getCenter(find.text('Child 1')).dy, epsilon: 0.01), + ); + expect( + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dx, + moreOrLessEquals(tester.getCenter(find.text('Child 1')).dx + centerDelta / 2, epsilon: 0.01), ); await gesture.up(); @@ -1396,8 +1446,13 @@ void main() { // The ongoing drag gesture should veto the programmatic change. expect( - currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center, - offsetMoreOrLessEquals(tester.getCenter(find.text('A')), epsilon: 0.01), + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dy, + moreOrLessEquals(tester.getCenter(find.text('A')).dy, epsilon: 0.01), + ); + final double centerDelta = tester.getSize(find.text('A')).width * (1 - currentThumbScale(tester)) / 2; + expect( + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dx, + moreOrLessEquals(tester.getCenter(find.text('A')).dx + centerDelta, epsilon: 0.01), ); // Move the pointer to 'B'. The onValueChanged callback will be called but @@ -1417,6 +1472,108 @@ void main() { expect(callbackCalled, isFalse); }); + testWidgets('Disable "highlighted" segment during drag, highlight stays', (WidgetTester tester) async { + const Map children = { + 0: Text('A'), + 1: Text('B'), + 2: Text('C'), + }; + Set disabledChildren = {}; + await tester.pumpWidget( + boilerplate( + builder: (BuildContext context) { + return CupertinoSlidingSegmentedControl( + key: const ValueKey('Segmented Control'), + children: children, + disabledChildren: disabledChildren, + groupValue: groupValue, + onValueChanged: defaultCallback, + ); + }, + ), + ); + + // Start dragging. + final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('A'))); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + + // Move pointer to B. + await gesture.moveTo(tester.getCenter(find.text('B'))); + await tester.pumpAndSettle(); + + // Disable B. + setState!(() { disabledChildren = { 1 }; }); + await tester.pumpAndSettle(); + + // During dragging, we can still see the "highlighted" segment. + expect( + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center, + offsetMoreOrLessEquals(tester.getCenter(find.text('B')), epsilon: 0.01), + ); + + await gesture.up(); + + await tester.pump(); + await tester.pumpAndSettle(); + + // When dragging stops, highlight stays. + expect(getHighlightedIndex(tester), 1); + }); + + testWidgets('Disable "highlighted" segment during drag, onValueChanged is still called', (WidgetTester tester) async { + const Map children = { + 0: Text('A'), + 1: Text('B'), + 2: Text('C'), + }; + Set disabledChildren = {}; + + int callbackCalled = 0; + + void onValueChanged(int? newValue) { + callbackCalled += 1; + setState!(() { groupValue = newValue; }); + } + + await tester.pumpWidget( + boilerplate( + builder: (BuildContext context) { + return CupertinoSlidingSegmentedControl( + key: const ValueKey('Segmented Control'), + children: children, + disabledChildren: disabledChildren, + groupValue: groupValue, + onValueChanged: onValueChanged, + ); + }, + ), + ); + + // Start dragging. + final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('A'))); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + + // Drag to B. + await gesture.moveTo(tester.getCenter(find.text('B'))); + await tester.pump(); + await tester.pumpAndSettle(); + + // Disable B. + setState!(() { disabledChildren = { 1 }; }); + await tester.pumpAndSettle(); + + // Stop dragging. + await gesture.up(); + + await tester.pump(); + await tester.pumpAndSettle(); + + expect(getHighlightedIndex(tester), 1); + expect(callbackCalled, 1); + }); + testWidgets('Dragging out of bound does not cause out of range exception', (WidgetTester tester) async { const Map children = { 0: Text('A'), @@ -1446,8 +1603,8 @@ void main() { ); } - expect(getChildSize(0).width, 32.5); - expect(getChildSize(2).width, 60.5); + expect(getChildSize(0).width, 33.0); + expect(getChildSize(2).width, 59.0); // Start dragging. final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('A'))); @@ -1512,8 +1669,13 @@ void main() { await tester.pumpAndSettle(); expect( - currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center, - offsetMoreOrLessEquals(tester.getCenter(find.text('A')), epsilon: 0.01), + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dy, + moreOrLessEquals(tester.getCenter(find.text('A')).dy, epsilon: 0.01), + ); + double centerDelta = tester.getSize(find.text('A')).width * (1 - currentThumbScale(tester)) / 2; + expect( + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dx, + moreOrLessEquals(tester.getCenter(find.text('A')).dx + centerDelta, epsilon: 0.01), ); // A different drag. @@ -1522,8 +1684,13 @@ void main() { await tester.pumpAndSettle(); expect( - currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center, - offsetMoreOrLessEquals(tester.getCenter(find.text('A')), epsilon: 0.01), + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dy, + moreOrLessEquals(tester.getCenter(find.text('A')).dy, epsilon: 0.01), + ); + centerDelta = tester.getSize(find.text('A')).width * (1 - currentThumbScale(tester)) / 2; + expect( + currentUnscaledThumbRect(tester, useGlobalCoordinate: true).center.dx, + moreOrLessEquals(tester.getCenter(find.text('A')).dx + centerDelta, epsilon: 0.01), ); await gesture.up(); @@ -1755,4 +1922,209 @@ void main() { kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic, ); }); + + testWidgets('CupertinoSlidingSegmentedControl defaults - no selection', (WidgetTester tester) async { + const Map children = { + 0: Text('A'), + 1: Text('BB'), + 2: Text('CCCC'), + }; + + Widget buildSlidingSegmentedControl({ Brightness? brightness }) { + return CupertinoApp( + theme: CupertinoThemeData( + brightness: brightness ?? Brightness.light, + ), + home: CupertinoPageScaffold( + child: Center( + child: CupertinoSlidingSegmentedControl( + children: children, + onValueChanged: defaultCallback, + ), + ), + ) + ); + } + + // Light theme + await tester.pumpWidget(buildSlidingSegmentedControl()); + + await expectLater( + find.byType(CupertinoSlidingSegmentedControl), + matchesGoldenFile('cupertino_sliding_segmented_control.light_theme.png'), + ); + + // Dark theme + await tester.pumpWidget(buildSlidingSegmentedControl(brightness: Brightness.dark)); + + await expectLater( + find.byType(CupertinoSlidingSegmentedControl), + matchesGoldenFile('cupertino_sliding_segmented_control.dark_theme.png'), + ); + }); + + testWidgets('CupertinoSlidingSegmentedControl defaults - group value is not null', (WidgetTester tester) async { + const Map children = { + 0: Text('A'), + 1: Text('BB'), + 2: Text('CCCC'), + }; + + Widget buildSlidingSegmentedControl({ Brightness? brightness }) { + return CupertinoApp( + theme: CupertinoThemeData( + brightness: brightness ?? Brightness.light, + ), + home: CupertinoPageScaffold( + child: Center( + child: CupertinoSlidingSegmentedControl( + groupValue: 1, + children: children, + onValueChanged: defaultCallback, + ), + ), + ) + ); + } + + // Light theme + await tester.pumpWidget(buildSlidingSegmentedControl()); + + await expectLater( + find.byType(CupertinoSlidingSegmentedControl), + matchesGoldenFile('cupertino_sliding_segmented_control.with_selection.light_theme.png'), + ); + + // Dark theme + await tester.pumpWidget(buildSlidingSegmentedControl(brightness: Brightness.dark)); + + await expectLater( + find.byType(CupertinoSlidingSegmentedControl), + matchesGoldenFile('cupertino_sliding_segmented_control.with_selection.dark_theme.png'), + ); + }); + + testWidgets('CupertinoSlidingSegmentedControl defaults - disabled', (WidgetTester tester) async { + const Map children = { + 0: Text('A'), + 1: Text('BB'), + 2: Text('CCCC'), + }; + + Widget buildSlidingSegmentedControl({ Brightness? brightness }) { + return CupertinoApp( + theme: CupertinoThemeData( + brightness: brightness ?? Brightness.light, + ), + home: CupertinoPageScaffold( + child: Center( + child: CupertinoSlidingSegmentedControl( + disabledChildren: const { 0 }, + children: children, + onValueChanged: defaultCallback, + ), + ), + ) + ); + } + + // Light theme + await tester.pumpWidget(buildSlidingSegmentedControl()); + + await expectLater( + find.byType(CupertinoSlidingSegmentedControl), + matchesGoldenFile('cupertino_sliding_segmented_control.disabled.light_theme.png'), + ); + + // Dark theme + await tester.pumpWidget(buildSlidingSegmentedControl(brightness: Brightness.dark)); + + await expectLater( + find.byType(CupertinoSlidingSegmentedControl), + matchesGoldenFile('cupertino_sliding_segmented_control.disabled.dark_theme.png'), + ); + }); + + testWidgets('Segment can be disabled', (WidgetTester tester) async { + const Map children = { + 0: Text('A'), + 1: Text('BB'), + 2: Text('CCCC'), + }; + + groupValue = 1; + await tester.pumpWidget( + boilerplate( + builder: (BuildContext context) { + return CupertinoSlidingSegmentedControl( + disabledChildren: const { 0 }, + children: children, + groupValue: groupValue, + onValueChanged: defaultCallback, + ); + }, + ) + ); + + expect(getHighlightedIndex(tester), 1); + + // Tap disabled segment + await tester.tap(find.text('A')); + await tester.pumpAndSettle(); + + expect(getHighlightedIndex(tester), 1); // The highlighted index doesn't change + + // Tap enabled segment + await tester.tap(find.text('CCCC')); + await tester.pumpAndSettle(); + + expect(getHighlightedIndex(tester), 2); + + // Tap disabled segment + await tester.tap(find.text('A')); + await tester.pumpAndSettle(); + + expect(getHighlightedIndex(tester), 2); // The highlighted index doesn't change + }); + + testWidgets('Several segments can be disabled', (WidgetTester tester) async { + const Map children = { + 0: Text('A'), + 1: Text('BB'), + 2: Text('CCCC'), + }; + + int onValueChangedCalled = 0; + await tester.pumpWidget( + boilerplate( + builder: (BuildContext context) { + return CupertinoSlidingSegmentedControl( + disabledChildren: const { 0, 1, 2 }, + children: children, + groupValue: groupValue, + onValueChanged: (int? value) { + onValueChangedCalled += 1; + defaultCallback.call(value); + }, + ); + }, + ) + ); + + // All segments are disabled, so onValueChangedCalled should always be 0. + await tester.tap(find.text('A')); + await tester.pumpAndSettle(); + + expect(onValueChangedCalled, 0); + + await tester.tap(find.text('CCCC')); + await tester.pumpAndSettle(); + + expect(onValueChangedCalled, 0); + + await tester.tap(find.text('BB')); + await tester.pumpAndSettle(); + + expect(onValueChangedCalled, 0); + }); }