Preserve SelectableRegion scope across context menu rebuilds (#186553) <!-- Thanks for filing a pull request! Reviewers are typically assigned within a week of filing a request. To learn more about code review, see our documentation on Tree Hygiene: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md --> `SelectableRegion` conditionally wraps its selection subtree in `PlatformSelectableRegionContextMenu` on desktop web. When `BrowserContextMenu.enabled` changes, that wrapper can be removed while the existing root `SelectionContainer` is still registered, causing a replacement container to register before the old one unregisters. This keeps the selection status scope keyed from `SelectableRegionState`, so the selection subtree is reparented across the optional wrapper change instead of recreated. The browser regression covers enable/disable transitions with the widgets-layer test harness and current selection controls. Fixes #186459. Tests: - `../../bin/flutter test --no-pub --platform chrome test/widgets/selectable_region_context_menu_test.dart` - `./bin/flutter analyze --no-pub packages/flutter/lib/src/widgets/selectable_region.dart packages/flutter/test/widgets/selectable_region_context_menu_test.dart` - `./bin/dart format --output=none --set-exit-if-changed packages/flutter/test/widgets/selectable_region_context_menu_test.dart` - `git diff --check` ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. If this change needs to override an active code freeze, provide a comment explaining why. The code freeze workflow can be overridden by code reviewers. See pinned issues for any active code freezes with guidance. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
diff --git a/packages/flutter/lib/src/widgets/selectable_region.dart b/packages/flutter/lib/src/widgets/selectable_region.dart index ca7f777..fd52fc6 100644 --- a/packages/flutter/lib/src/widgets/selectable_region.dart +++ b/packages/flutter/lib/src/widgets/selectable_region.dart
@@ -448,6 +448,10 @@ final _SelectableRegionSelectionStatusNotifier _selectionStatusNotifier = _SelectableRegionSelectionStatusNotifier._(); + /// Preserves the selection status scope and root selection container when the + /// desktop web context menu wrapper is added or removed. + final GlobalKey _selectionStatusScopeKey = GlobalKey(debugLabel: 'selectionStatusScopeKey'); + @protected @override void initState() { @@ -1959,6 +1963,7 @@ Widget build(BuildContext context) { assert(debugCheckHasOverlay(context)); Widget result = SelectableRegionSelectionStatusScope._( + key: _selectionStatusScopeKey, selectionStatusNotifier: _selectionStatusNotifier, child: SelectionContainer(registrar: this, delegate: _selectionDelegate, child: widget.child), ); @@ -3516,6 +3521,7 @@ /// does not change. final class SelectableRegionSelectionStatusScope extends InheritedWidget { const SelectableRegionSelectionStatusScope._({ + super.key, required this.selectionStatusNotifier, required super.child, });
diff --git a/packages/flutter/test/widgets/selectable_region_context_menu_test.dart b/packages/flutter/test/widgets/selectable_region_context_menu_test.dart index bc4fccc..5298257 100644 --- a/packages/flutter/test/widgets/selectable_region_context_menu_test.dart +++ b/packages/flutter/test/widgets/selectable_region_context_menu_test.dart
@@ -14,6 +14,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:web/web.dart' as web; +import 'editable_text_tester.dart'; import 'web_platform_view_registry_utils.dart'; extension on web.HTMLCollection { @@ -43,11 +44,23 @@ fakePlatformViewRegistry = FakePlatformViewRegistry(); PlatformSelectableRegionContextMenu.debugOverrideRegisterViewFactory = fakePlatformViewRegistry.registerViewFactory; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.contextMenu, + (MethodCall call) { + // Just complete successfully, so that BrowserContextMenu thinks that + // the engine successfully received its call. + return Future<void>.value(); + }, + ); }); tearDown(() { PlatformSelectableRegionContextMenu.debugOverrideRegisterViewFactory = null; PlatformSelectableRegionContextMenu.debugResetRegistry(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.contextMenu, + null, + ); }); testWidgets('DOM element is set up correctly', (WidgetTester tester) async { @@ -429,6 +442,44 @@ expect(event.defaultPrevented, isTrue); } }, variant: _browserContextMenuEnabledVariants); + + // Regression test for https://github.com/flutter/flutter/issues/186459 + testWidgets('can rebuild SelectableRegion as browser context menu toggles', ( + WidgetTester tester, + ) async { + await BrowserContextMenu.enableContextMenu(); + addTearDown(BrowserContextMenu.enableContextMenu); + + late StateSetter rebuild; + await tester.pumpWidget( + TestWidgetsApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + rebuild = setState; + return SelectableRegion( + selectionControls: testTextSelectionHandleControls, + child: const Text('How are you?'), + ); + }, + ), + ), + ); + + await BrowserContextMenu.disableContextMenu(); + rebuild(() {}); + await tester.pump(); + expect(tester.takeException(), isNull); + + await BrowserContextMenu.enableContextMenu(); + rebuild(() {}); + await tester.pump(); + expect(tester.takeException(), isNull); + + await BrowserContextMenu.disableContextMenu(); + rebuild(() {}); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }, variant: _browserContextMenuEnabledVariants); } void removeAllStyleElements() {