Skip to content

Commit 9d98366

Browse files
authored
Fix web context-menu client lifecycle in SelectableRegion (flutter#189587)
On web, `PlatformSelectableRegionContextMenu._activeClient` — the static `SelectionContainerDelegate` that the right-click `mousedown` listener reads — can end up pointing at a detached or disposed delegate, because of three lifecycle defects: 1. `detach` has an inverted condition — `if (_activeClient != client) { _activeClient = null; }`. Detaching the active client leaves it registered, while detaching an unrelated client wipes another region's registration. 2. `SelectableRegionState._handleFocusChanged` calls `attach` unconditionally at the end of the method, so a region that just lost focus is immediately re-registered. 3. `SelectableRegionState.dispose` never detaches, so the static can keep pointing at a disposed delegate. Together these produce a crash on web when the user right-clicks during a route transition: the listener calls `getTransformTo(null)` on the stale delegate and hits `"getTransformTo cannot be called before SelectionContainer is laid out"` (`selection_container.dart:303`). We hit this in a production web app. This PR flips the `detach` condition, moves the re-attach into the focused branch, and detaches in `dispose` before disposing the delegate. It also adds a `@visibleForTesting` `debugActiveClient` getter, mirroring the existing `debugOverrideRegisterViewFactory` pattern, since the delegate is otherwise unobservable from tests. Three new browser tests in `selectable_region_context_menu_test.dart` isolate the defects; each is red before the fix and green after it. A follow-up commit hardens the detach paths against `BrowserContextMenu.enabled` changing at runtime. Attach stays gated on the full dynamic check, but the focus-loss and dispose detach paths now gate on `kIsWeb` alone, so a delegate attached while the menu was enabled is still detached after the menu is disabled. This is safe because `detach` is identity-selective: calling it for a never-attached delegate is a no-op. Two more browser tests cover unfocus and disposal after `BrowserContextMenu.disableContextMenu()`, bringing it to five lifecycle tests, each red before its fix and green after. Fixes flutter#189575 ## 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. <!-- 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/ [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
1 parent ec81c5f commit 9d98366

4 files changed

Lines changed: 284 additions & 4 deletions

File tree

‎packages/flutter/lib/src/widgets/_platform_selectable_region_context_menu_io.dart‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,12 @@ class PlatformSelectableRegionContextMenu extends StatelessWidget {
4040
/// Detaches the `client` from the platform-appropriate selection context menus.
4141
static void detach(SelectionContainerDelegate client) => throw UnimplementedError();
4242

43+
/// The client currently attached to the [PlatformSelectableRegionContextMenu].
44+
///
45+
/// This should only be used for testing.
46+
@visibleForTesting
47+
static SelectionContainerDelegate? get debugActiveClient => throw UnimplementedError();
48+
4349
/// Override this to provide a custom implementation of `ui_web.platformViewRegistry.registerViewFactory`.
4450
///
4551
/// This should only be used for testing.

‎packages/flutter/lib/src/widgets/_platform_selectable_region_context_menu_web.dart‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,13 +56,19 @@ class PlatformSelectableRegionContextMenu extends StatelessWidget {
5656

5757
/// See `_platform_selectable_region_context_menu_io.dart`.
5858
static void detach(SelectionContainerDelegate client) {
59-
if (_activeClient != client) {
59+
if (_activeClient == client) {
6060
_activeClient = null;
6161
}
6262
}
6363

6464
static SelectionContainerDelegate? _activeClient;
6565

66+
/// The client currently attached to the [PlatformSelectableRegionContextMenu].
67+
///
68+
/// This should only be used for testing.
69+
@visibleForTesting
70+
static SelectionContainerDelegate? get debugActiveClient => _activeClient;
71+
6672
// Keeps track if this widget has already registered its view factories or not.
6773
static String? _registeredViewType;
6874

‎packages/flutter/lib/src/widgets/selectable_region.dart‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -525,7 +525,11 @@ class SelectableRegionState extends State<SelectableRegion>
525525

526526
void _handleFocusChanged() {
527527
if (!_focusNode.hasFocus) {
528-
if (_webContextMenuEnabled) {
528+
if (kIsWeb) {
529+
// Detach regardless of the current (dynamic) _webContextMenuEnabled
530+
// value: the browser context menu may have been disabled after this
531+
// delegate attached, and detach is a no-op for a client that was
532+
// never the active one.
529533
PlatformSelectableRegionContextMenu.detach(_selectionDelegate);
530534
}
531535
if (SchedulerBinding.instance.lifecycleState == AppLifecycleState.resumed) {
@@ -540,8 +544,7 @@ class SelectableRegionState extends State<SelectableRegion>
540544
_selectionStatusNotifier.value = SelectableRegionSelectionStatus.changing;
541545
_finalizeSelectableRegionStatus();
542546
}
543-
}
544-
if (_webContextMenuEnabled) {
547+
} else if (_webContextMenuEnabled) {
545548
PlatformSelectableRegionContextMenu.attach(_selectionDelegate);
546549
}
547550
}
@@ -1935,6 +1938,9 @@ class SelectableRegionState extends State<SelectableRegion>
19351938
void dispose() {
19361939
_selectable?.removeListener(_updateSelectionStatus);
19371940
_selectable?.pushHandleLayers(null, null);
1941+
if (kIsWeb) {
1942+
PlatformSelectableRegionContextMenu.detach(_selectionDelegate);
1943+
}
19381944
_selectionDelegate.dispose();
19391945
_selectionStatusNotifier.dispose();
19401946
// In case dispose was triggered before gesture end, remove the magnifier

‎packages/flutter/test/widgets/selectable_region_context_menu_test.dart‎

Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
@TestOn('browser') // This file contains web-only library.
66
library;
77

8+
import 'dart:js_interop';
9+
810
import 'package:flutter/foundation.dart';
911
import 'package:flutter/rendering.dart';
1012
import 'package:flutter/services.dart';
@@ -142,6 +144,266 @@ void main() {
142144
expect((selectWordEvent.globalPosition.dy - 300).abs() < precisionErrorTolerance, isTrue);
143145
}, variant: _browserContextMenuEnabledVariants);
144146

147+
// Regression test for https://github.com/flutter/flutter/issues/189575.
148+
testWidgets('right click does not dispatch event to previous stale client after losing focus', (
149+
WidgetTester tester,
150+
) async {
151+
final int currentViewId = platformViewsRegistry.getNextPlatformViewId();
152+
final focusNode = FocusNode();
153+
addTearDown(focusNode.dispose);
154+
final spy = UniqueKey();
155+
await tester.pumpWidget(
156+
TestWidgetsApp(
157+
home: SelectableRegion(
158+
focusNode: focusNode,
159+
selectionControls: emptyTextSelectionControls,
160+
child: SelectionSpy(key: spy),
161+
),
162+
),
163+
);
164+
final element = fakePlatformViewRegistry.getViewById(currentViewId + 1) as web.HTMLElement;
165+
expect(element, isNotNull);
166+
focusNode.requestFocus();
167+
await tester.pump();
168+
focusNode.unfocus();
169+
await tester.pump();
170+
final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(
171+
find.byKey(spy),
172+
);
173+
renderSelectionSpy.events.clear();
174+
// Before the fix, losing focus re-attached the client instead of
175+
// detaching it, so the right click below dispatched a
176+
// SelectWordSelectionEvent to the stale, no-longer-focused client.
177+
element.dispatchEvent(
178+
web.MouseEvent('mousedown', web.MouseEventInit(button: 2, clientX: 200, clientY: 300)),
179+
);
180+
expect(renderSelectionSpy.events, isEmpty);
181+
}, variant: _browserContextMenuEnabledVariants);
182+
183+
testWidgets('right click after the SelectableRegion is disposed does not crash', (
184+
WidgetTester tester,
185+
) async {
186+
final int currentViewId = platformViewsRegistry.getNextPlatformViewId();
187+
final focusNode = FocusNode();
188+
addTearDown(focusNode.dispose);
189+
await tester.pumpWidget(
190+
TestWidgetsApp(
191+
home: SelectableRegion(
192+
focusNode: focusNode,
193+
selectionControls: emptyTextSelectionControls,
194+
child: const SelectionSpy(),
195+
),
196+
),
197+
);
198+
final element = fakePlatformViewRegistry.getViewById(currentViewId + 1) as web.HTMLElement;
199+
expect(element, isNotNull);
200+
focusNode.requestFocus();
201+
await tester.pump();
202+
expect(PlatformSelectableRegionContextMenu.debugActiveClient, isNotNull);
203+
204+
// Removing the SelectableRegion disposes its state without ever
205+
// losing focus on the externally-owned focus node, so only the
206+
// dispose-time detach can clear the static reference.
207+
await tester.pumpWidget(const TestWidgetsApp(home: SizedBox.shrink()));
208+
209+
// Before the fix, the static active-client pointer outlived the
210+
// disposed delegate, so this right click reached into its defunct
211+
// render context and crashed instead of being a no-op.
212+
web.Event? capturedError;
213+
final JSExportedDartFunction onWindowError = (web.Event event) {
214+
capturedError = event;
215+
}.toJS;
216+
web.window.addEventListener('error', onWindowError);
217+
addTearDown(() => web.window.removeEventListener('error', onWindowError));
218+
element.dispatchEvent(
219+
web.MouseEvent('mousedown', web.MouseEventInit(button: 2, clientX: 200, clientY: 300)),
220+
);
221+
expect(tester.takeException(), isNull);
222+
expect(capturedError, isNull, reason: 'window reported an uncaught error: $capturedError');
223+
}, variant: _browserContextMenuEnabledVariants);
224+
225+
testWidgets('detach only clears the active client when detaching the active client', (
226+
WidgetTester tester,
227+
) async {
228+
final focusNodeA = FocusNode();
229+
final focusNodeB = FocusNode();
230+
addTearDown(focusNodeA.dispose);
231+
addTearDown(focusNodeB.dispose);
232+
233+
await tester.pumpWidget(
234+
TestWidgetsApp(
235+
home: Column(
236+
children: <Widget>[
237+
SizedBox(
238+
height: 100,
239+
child: SelectableRegion(
240+
focusNode: focusNodeA,
241+
selectionControls: emptyTextSelectionControls,
242+
child: const SelectionSpy(),
243+
),
244+
),
245+
SizedBox(
246+
height: 100,
247+
child: SelectableRegion(
248+
focusNode: focusNodeB,
249+
selectionControls: emptyTextSelectionControls,
250+
child: const SelectionSpy(),
251+
),
252+
),
253+
],
254+
),
255+
),
256+
);
257+
258+
focusNodeA.requestFocus();
259+
await tester.pump();
260+
final SelectionContainerDelegate delegateA =
261+
PlatformSelectableRegionContextMenu.debugActiveClient!;
262+
263+
focusNodeB.requestFocus();
264+
await tester.pump();
265+
final SelectionContainerDelegate delegateB =
266+
PlatformSelectableRegionContextMenu.debugActiveClient!;
267+
expect(delegateB, isNot(same(delegateA)));
268+
269+
// Detaching a client that is not the active client must not clear
270+
// the active client.
271+
PlatformSelectableRegionContextMenu.detach(delegateA);
272+
expect(PlatformSelectableRegionContextMenu.debugActiveClient, same(delegateB));
273+
274+
// Detaching the active client must clear it.
275+
PlatformSelectableRegionContextMenu.detach(delegateB);
276+
expect(PlatformSelectableRegionContextMenu.debugActiveClient, isNull);
277+
}, variant: _browserContextMenuEnabledVariants);
278+
279+
testWidgets('losing focus detaches the client and does not reattach it', (
280+
WidgetTester tester,
281+
) async {
282+
final focusNode = FocusNode();
283+
addTearDown(focusNode.dispose);
284+
285+
await tester.pumpWidget(
286+
TestWidgetsApp(
287+
home: SelectableRegion(
288+
focusNode: focusNode,
289+
selectionControls: emptyTextSelectionControls,
290+
child: const SelectionSpy(),
291+
),
292+
),
293+
);
294+
295+
focusNode.requestFocus();
296+
await tester.pump();
297+
expect(PlatformSelectableRegionContextMenu.debugActiveClient, isNotNull);
298+
299+
focusNode.unfocus();
300+
await tester.pump();
301+
302+
expect(PlatformSelectableRegionContextMenu.debugActiveClient, isNull);
303+
}, variant: _browserContextMenuEnabledVariants);
304+
305+
testWidgets('disposing a SelectableRegion detaches its client from the context menu', (
306+
WidgetTester tester,
307+
) async {
308+
final focusNode = FocusNode();
309+
addTearDown(focusNode.dispose);
310+
311+
await tester.pumpWidget(
312+
TestWidgetsApp(
313+
home: SelectableRegion(
314+
focusNode: focusNode,
315+
selectionControls: emptyTextSelectionControls,
316+
child: const SelectionSpy(),
317+
),
318+
),
319+
);
320+
321+
focusNode.requestFocus();
322+
await tester.pump();
323+
expect(PlatformSelectableRegionContextMenu.debugActiveClient, isNotNull);
324+
325+
// Removing the SelectableRegion disposes its state without ever
326+
// losing focus on the externally-owned focus node, so only the
327+
// dispose-time detach can clear the static reference.
328+
await tester.pumpWidget(const TestWidgetsApp(home: SizedBox.shrink()));
329+
330+
expect(PlatformSelectableRegionContextMenu.debugActiveClient, isNull);
331+
}, variant: _browserContextMenuEnabledVariants);
332+
333+
group('when the browser context menu is disabled after attaching', () {
334+
setUp(() async {
335+
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
336+
SystemChannels.contextMenu,
337+
(MethodCall call) => Future<void>.value(),
338+
);
339+
});
340+
341+
tearDown(() async {
342+
await BrowserContextMenu.enableContextMenu();
343+
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
344+
SystemChannels.contextMenu,
345+
null,
346+
);
347+
});
348+
349+
testWidgets('losing focus still detaches the client', (WidgetTester tester) async {
350+
final focusNode = FocusNode();
351+
addTearDown(focusNode.dispose);
352+
353+
await tester.pumpWidget(
354+
TestWidgetsApp(
355+
home: SelectableRegion(
356+
focusNode: focusNode,
357+
selectionControls: emptyTextSelectionControls,
358+
child: const SelectionSpy(),
359+
),
360+
),
361+
);
362+
363+
focusNode.requestFocus();
364+
await tester.pump();
365+
expect(PlatformSelectableRegionContextMenu.debugActiveClient, isNotNull);
366+
367+
// Disabling the browser context menu after the delegate attached
368+
// must not prevent the eventual detach: _webContextMenuEnabled is
369+
// re-evaluated dynamically and would otherwise report false here.
370+
await BrowserContextMenu.disableContextMenu();
371+
372+
focusNode.unfocus();
373+
await tester.pump();
374+
375+
expect(PlatformSelectableRegionContextMenu.debugActiveClient, isNull);
376+
}, variant: _browserContextMenuEnabledVariants);
377+
378+
testWidgets('disposing still detaches the client', (WidgetTester tester) async {
379+
final focusNode = FocusNode();
380+
addTearDown(focusNode.dispose);
381+
382+
await tester.pumpWidget(
383+
TestWidgetsApp(
384+
home: SelectableRegion(
385+
focusNode: focusNode,
386+
selectionControls: emptyTextSelectionControls,
387+
child: const SelectionSpy(),
388+
),
389+
),
390+
);
391+
392+
focusNode.requestFocus();
393+
await tester.pump();
394+
expect(PlatformSelectableRegionContextMenu.debugActiveClient, isNotNull);
395+
396+
await BrowserContextMenu.disableContextMenu();
397+
398+
// Removing the SelectableRegion disposes its state without ever
399+
// losing focus on the externally-owned focus node, so only the
400+
// dispose-time detach can clear the static reference.
401+
await tester.pumpWidget(const TestWidgetsApp(home: SizedBox.shrink()));
402+
403+
expect(PlatformSelectableRegionContextMenu.debugActiveClient, isNull);
404+
}, variant: _browserContextMenuEnabledVariants);
405+
});
406+
145407
// Regression test for https://github.com/flutter/flutter/issues/157579
146408
testWidgets('prevents default action of mousedown events', (WidgetTester tester) async {
147409
final int currentViewId = platformViewsRegistry.getNextPlatformViewId();

0 commit comments

Comments
 (0)