Skip to content

Commit 0a291d1

Browse files
committed
[web] Report env(safe-area-inset-*) as FlutterView.viewPadding
`SafeArea` has always been a no-op on the web because nothing ever fed the device safe area into the framework. Two things were missing. 1. `FullPageEmbeddingStrategy` removed every `<meta name="viewport">` on the page and wrote its own without `viewport-fit`. An app that opted into a full-bleed layout with `viewport-fit=cover` had that opt-in deleted at startup, and WebKit then kept laying the app out inside the safe area, so `env(safe-area-inset-*)` had nothing to report. This is why the workarounds in the issue never worked. The `viewport-fit` of the last viewport meta tag on the page, which is the one the browser itself honours, is now carried over to the tag that the engine writes, and, as a result, across hot restarts too. The "this tag will be replaced" warning now names the descriptors that are actually being dropped, and stays quiet when none are, so an app following the web template's advice no longer provokes a warning on every debug run. 2. Nothing in `web_ui` read `env(safe-area-inset-*)`. `DimensionsProvider` gains `computeSafeAreaInsets()`. `FullPageDimensionsProvider` implements it by reading the values back from a `display: none` probe element whose paddings are set to `env(...)`; the browser resolves `env()` at computed-value time, so no layout or paint is involved. `CustomElementDimensionsProvider` reports zero, because the host application is the one that positions an embedded view on the page. `EngineFlutterView.viewPadding` is now backed by those insets, computed lazily and recomputed on the same events that recompute the physical size, and `padding` is `viewPadding` minus `viewInsets`, clamped at zero, matching the other platforms: when the on-screen keyboard covers the bottom safe area, the bottom padding goes to zero. Parsing a `viewport-fit` descriptor lives in one new file, `view_embedder/viewport_fit.dart`, used both by the strategy that writes the tag and by the provider that reads it back, so that the two sides cannot drift apart over the exact spelling of a `content` attribute. The insets are only reported for a page that declared `viewport-fit=cover` itself. That is a stricter rule than the one the browser applies to `env()`: on an iPhone 17 Pro (iOS 18.7, WebKit 605.1.15, Safari 26.1) `env(safe-area-inset-bottom)` is `20px` in landscape whether or not the page is full-bleed, and passing that on would have moved the content of every existing Flutter web app on iOS, including the ones that ask for nothing. A page that never declared `viewport-fit` keeps a byte-identical viewport meta tag and a `viewPadding` of `ViewPadding.zero`, exactly as before this change. Apps that do declare `viewport-fit=cover` in their `index.html` change, and that is the point of the fix: the browser stops keeping them within the safe area. On the device above, a Flutter page in landscape reports `window.innerWidth` of 750 against 874 for a plain HTML control that declares the same tag, a difference of exactly the `62 + 62` of left and right inset the control reports. Content that is not wrapped in a `SafeArea` moves under the display cutout and the rounded corners, which is what `viewport-fit=cover` asks the browser for. The post-change behaviour is covered by unit tests; it has not been measured on a device, and `env(safe-area-inset-top)` was zero in every device reading taken, so the top axis in particular rests on unit coverage alone. The `flutter create` web template gains the tag, commented out, next to the guidance it already carries for `<base href>`. `systemGestureInsets` is deliberately left at zero. `env()` describes the parts of the viewport obstructed by the device, not the parts the system reserves for its own gestures, and browsers do not expose the latter. This covers full-page embeddings only. A view hosted in a custom element still reports zero, so the issue stays open for embedded and multi-view apps. See flutter#84833
1 parent 40b3290 commit 0a291d1

15 files changed

Lines changed: 934 additions & 34 deletions

File tree

‎engine/src/flutter/lib/web_ui/lib/src/engine.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ export 'engine/view_embedder/flutter_view_manager.dart';
174174
export 'engine/view_embedder/global_html_attributes.dart';
175175
export 'engine/view_embedder/hot_restart_cache_handler.dart';
176176
export 'engine/view_embedder/style_manager.dart';
177+
export 'engine/view_embedder/viewport_fit.dart';
177178
export 'engine/web_paragraph/bidi.dart';
178179
export 'engine/web_paragraph/code_unit_flags.dart';
179180
export 'engine/web_paragraph/debug.dart';

‎engine/src/flutter/lib/web_ui/lib/src/engine/dom.dart‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -831,6 +831,8 @@ extension type DomCSSStyleDeclaration._(JSObject _) implements JSObject {
831831

832832
external String getPropertyValue(String property);
833833

834+
external String getPropertyPriority(String property);
835+
834836
@JS('setProperty')
835837
external void _setProperty(String propertyName, String value, String priority);
836838
void setProperty(String propertyName, String value, [String? priority]) {

‎engine/src/flutter/lib/web_ui/lib/src/engine/platform_dispatcher.dart‎

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1882,10 +1882,7 @@ class ViewConfiguration {
18821882
this.view,
18831883
this.devicePixelRatio = 1.0,
18841884
this.visible = false,
1885-
this.viewInsets = ui.ViewPadding.zero as ViewPadding,
1886-
this.viewPadding = ui.ViewPadding.zero as ViewPadding,
18871885
this.systemGestureInsets = ui.ViewPadding.zero as ViewPadding,
1888-
this.padding = ui.ViewPadding.zero as ViewPadding,
18891886
this.gestureSettings = const ui.GestureSettings(),
18901887
this.displayFeatures = const <ui.DisplayFeature>[],
18911888
this.displayCornerRadii,
@@ -1895,10 +1892,7 @@ class ViewConfiguration {
18951892
EngineFlutterView? view,
18961893
double? devicePixelRatio,
18971894
bool? visible,
1898-
ViewPadding? viewInsets,
1899-
ViewPadding? viewPadding,
19001895
ViewPadding? systemGestureInsets,
1901-
ViewPadding? padding,
19021896
ui.GestureSettings? gestureSettings,
19031897
List<ui.DisplayFeature>? displayFeatures,
19041898
ui.DisplayCornerRadii? displayCornerRadii,
@@ -1907,10 +1901,7 @@ class ViewConfiguration {
19071901
view: view ?? this.view,
19081902
devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
19091903
visible: visible ?? this.visible,
1910-
viewInsets: viewInsets ?? this.viewInsets,
1911-
viewPadding: viewPadding ?? this.viewPadding,
19121904
systemGestureInsets: systemGestureInsets ?? this.systemGestureInsets,
1913-
padding: padding ?? this.padding,
19141905
gestureSettings: gestureSettings ?? this.gestureSettings,
19151906
displayFeatures: displayFeatures ?? this.displayFeatures,
19161907
displayCornerRadii: displayCornerRadii ?? this.displayCornerRadii,
@@ -1920,10 +1911,7 @@ class ViewConfiguration {
19201911
final EngineFlutterView? view;
19211912
final double devicePixelRatio;
19221913
final bool visible;
1923-
final ViewPadding viewInsets;
1924-
final ViewPadding viewPadding;
19251914
final ViewPadding systemGestureInsets;
1926-
final ViewPadding padding;
19271915
final ui.GestureSettings gestureSettings;
19281916
final List<ui.DisplayFeature> displayFeatures;
19291917
final ui.DisplayCornerRadii? displayCornerRadii;

‎engine/src/flutter/lib/web_ui/lib/src/engine/view_embedder/dimensions_provider/custom_element_dimensions_provider.dart‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,4 +99,19 @@ class CustomElementDimensionsProvider extends DimensionsProvider {
9999
ViewPadding computeKeyboardInsets(double physicalHeight, bool isEditingOnMobile) {
100100
return const ViewPadding(top: 0, right: 0, bottom: 0, left: 0);
101101
}
102+
103+
@override
104+
ViewPadding computeSafeAreaInsets() {
105+
// A view embedded in a custom element occupies a region of a page that is
106+
// laid out by the host application, so the engine doesn't presume to know
107+
// how (or even whether) that region overlaps the obstructions of the device
108+
// screen. Keeping the element clear of them, or padding it with the CSS
109+
// `env(safe-area-inset-*)` values, is up to the host application for now.
110+
//
111+
// TODO(diegolopezrm): Derive these from the intersection of the host
112+
// element with the `env(safe-area-inset-*)` values of the page, so that
113+
// `SafeArea` works the same way in an embedded view as it does in a
114+
// full-page one. https://github.com/flutter/flutter/issues/84833
115+
return const ViewPadding(top: 0, right: 0, bottom: 0, left: 0);
116+
}
102117
}

‎engine/src/flutter/lib/web_ui/lib/src/engine/view_embedder/dimensions_provider/dimensions_provider.dart‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,33 @@ abstract class DimensionsProvider {
5050
/// Returns the [ViewPadding] of the keyboard insets (if present).
5151
ViewPadding computeKeyboardInsets(double physicalHeight, bool isEditingOnMobile);
5252

53+
/// Returns the [ViewPadding] of the safe area insets (if any), in physical
54+
/// pixels.
55+
///
56+
/// The safe area is the part of the viewport that is not obstructed by the
57+
/// device itself: display cutouts, rounded corners, or a home indicator.
58+
///
59+
/// On the web these insets come from the CSS `env(safe-area-inset-*)`
60+
/// environment variables, and only apply to a page that opted into laying
61+
/// itself out underneath those obstructions, by declaring
62+
/// `viewport-fit=cover` in the viewport meta tag of its `index.html`. A page
63+
/// that didn't opt in is laid out within the safe area by the browser, and
64+
/// gets no insets. This is a stricter rule than what the browser
65+
/// applies to `env()` itself: iOS Safari reports a non-zero
66+
/// `env(safe-area-inset-bottom)` for the home indicator even for a viewport
67+
/// it keeps clear of it, and reporting that would move the content of apps
68+
/// that never asked for a full-bleed layout.
69+
///
70+
/// Only [FullPageDimensionsProvider] reports a non-zero value. A view that is
71+
/// embedded in a custom element is positioned by the host application, which
72+
/// is therefore the one that knows how that element overlaps the obstructions
73+
/// of the screen.
74+
///
75+
/// The value is only guaranteed to be up to date right after the view is
76+
/// resized. A change to the safe area that doesn't resize the viewport, such
77+
/// as the taller status bar that iOS shows during a call, isn't observed.
78+
ViewPadding computeSafeAreaInsets();
79+
5380
/// Returns a Stream with the changes to [ui.Size] (when cheap to get).
5481
///
5582
/// Currently this Stream always returns `null` measurements because the

‎engine/src/flutter/lib/web_ui/lib/src/engine/view_embedder/dimensions_provider/full_page_dimensions_provider.dart‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,15 @@
44

55
import 'dart:async';
66

7+
import 'package:meta/meta.dart';
78
import 'package:ui/src/engine/display.dart';
89
import 'package:ui/src/engine/dom.dart';
10+
import 'package:ui/src/engine/safe_browser_api.dart';
911
import 'package:ui/src/engine/window.dart';
1012
import 'package:ui/ui.dart' as ui show Size;
1113
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
1214

15+
import '../viewport_fit.dart';
1316
import 'dimensions_provider.dart';
1417

1518
/// This class provides the real-time dimensions of a "full page" viewport.
@@ -34,6 +37,12 @@ class FullPageDimensionsProvider extends DimensionsProvider {
3437
'resize',
3538
createDomEventListener(_onVisualViewportResize),
3639
);
40+
41+
// The probe goes on the page up front, so that reading the safe area later
42+
// is a pure measurement, and never a DOM mutation in the middle of a frame.
43+
// It is taken back off in `close()`, which the view calls when it is
44+
// disposed, including on hot restart.
45+
domDocument.body!.append(safeAreaProbe);
3746
}
3847

3948
late DomSubscription _domResizeSubscription;
@@ -51,11 +60,19 @@ class FullPageDimensionsProvider extends DimensionsProvider {
5160
_onResizeStreamController.add(null);
5261
}
5362

63+
/// The element that the `env(safe-area-inset-*)` values are read back from.
64+
///
65+
/// Exposed so that tests can put values in it that a desktop browser would
66+
/// never report on its own.
67+
@visibleForTesting
68+
final DomHTMLDivElement safeAreaProbe = _createSafeAreaProbe();
69+
5470
@override
5571
void close() {
5672
super.close();
5773
_domResizeSubscription.cancel();
5874
_onResizeStreamController.close();
75+
safeAreaProbe.remove();
5976
}
6077

6178
@override
@@ -112,4 +129,79 @@ class FullPageDimensionsProvider extends DimensionsProvider {
112129

113130
return ViewPadding(bottom: bottomPadding, left: 0, right: 0, top: 0);
114131
}
132+
133+
@override
134+
ViewPadding computeSafeAreaInsets() {
135+
if (!_isFullBleed) {
136+
// The page is laid out within the safe area, so there is nothing for the
137+
// app to inset itself by. Report zero rather than whatever `env()` says:
138+
// some browsers report a non-zero inset even for a viewport they keep
139+
// clear of the obstruction themselves, and taking that at face value
140+
// would move the content of apps that never opted into a full-bleed
141+
// layout. See https://github.com/flutter/flutter/issues/84833.
142+
return const ViewPadding(top: 0, right: 0, bottom: 0, left: 0);
143+
}
144+
145+
if (safeAreaProbe.isConnected != true) {
146+
// The host page owns <body>, and is free to empty it, e.g. to take a
147+
// custom loading indicator down. `getComputedStyle` of a detached element
148+
// resolves to nothing, so put the probe back before measuring it.
149+
domDocument.body!.append(safeAreaProbe);
150+
}
151+
152+
final double devicePixelRatio = EngineFlutterDisplay.instance.devicePixelRatio;
153+
final DomCSSStyleDeclaration probeStyle = domWindow.getComputedStyle(safeAreaProbe);
154+
155+
double inset(String property) {
156+
// A browser that doesn't understand `env()` leaves the padding at its
157+
// initial value, which reads back as `0px`, so there is no separate code
158+
// path for it. `parseFloat` only returns null for an empty string, which
159+
// can't happen for an element that is in the document.
160+
return (parseFloat(probeStyle.getPropertyValue(property)) ?? 0.0) * devicePixelRatio;
161+
}
162+
163+
return ViewPadding(
164+
top: inset('padding-top'),
165+
right: inset('padding-right'),
166+
bottom: inset('padding-bottom'),
167+
left: inset('padding-left'),
168+
);
169+
}
170+
171+
// Whether the page is laid out underneath the parts of the screen that the
172+
// device obstructs, which is the only situation in which the app has to inset
173+
// its own content.
174+
//
175+
// The viewport meta tag written by `FullPageEmbeddingStrategy` is the
176+
// authority on this. It is the last viewport meta tag of the page, and it
177+
// carries over the `viewport-fit` that the app declared in its `index.html`,
178+
// if any. It is read back with the same function that wrote it, so that the
179+
// two sides cannot drift apart over the exact spelling of the descriptor.
180+
bool get _isFullBleed {
181+
final DomElement? viewportMeta = domDocument.head?.querySelector(
182+
'meta[name="viewport"][flt-viewport]',
183+
);
184+
return readViewportFit(viewportMeta?.getAttribute('content')) == ViewportFit.cover;
185+
}
186+
187+
// Creates the element that the `env(safe-area-inset-*)` values are read back
188+
// from.
189+
//
190+
// The browser resolves `env()` into an absolute length at computed-value
191+
// time, so the insets can be read back from the probe with `getComputedStyle`
192+
// even though the probe is `display: none`, and therefore never laid out nor
193+
// painted.
194+
static DomHTMLDivElement _createSafeAreaProbe() {
195+
final DomHTMLDivElement probe = createDomHTMLDivElement()
196+
..setAttribute('flt-safe-area-probe', '');
197+
// Every declaration is `important`, because an inline declaration that is
198+
// not loses to an `!important` rule of the app, and a stylesheet as ordinary
199+
// as `* { padding: 0 !important }` would then silently zero the measurement
200+
// (or, for `display`, put an element on the page that shouldn't be there).
201+
probe.style.setProperty('display', 'none', 'important');
202+
for (final side in <String>['top', 'right', 'bottom', 'left']) {
203+
probe.style.setProperty('padding-$side', 'env(safe-area-inset-$side, 0px)', 'important');
204+
}
205+
return probe;
206+
}
115207
}

‎engine/src/flutter/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/full_page_embedding_strategy.dart‎

Lines changed: 83 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import 'package:ui/src/engine/util.dart';
77
import 'package:ui/ui.dart' as ui;
88

99
import '../hot_restart_cache_handler.dart' show registerElementForCleanup;
10+
import '../viewport_fit.dart';
1011
import 'embedding_strategy.dart';
1112

1213
/// An [EmbeddingStrategy] that takes over the whole web page.
@@ -68,35 +69,98 @@ class FullPageEmbeddingStrategy implements EmbeddingStrategy {
6869

6970
// Sets a meta viewport tag appropriate for Flutter Web in full screen.
7071
void _applyViewportMeta() {
71-
for (final DomElement viewportMeta in domDocument.head!.querySelectorAll(
72-
'meta[name="viewport"]',
73-
)) {
74-
assert(() {
75-
// Filter out the meta tag that the engine placed on the page. This is
76-
// to avoid UI flicker during hot restart. Hot restart will clean up the
77-
// old meta tag synchronously with the first post-restart frame.
78-
if (!viewportMeta.hasAttribute('flt-viewport')) {
79-
printWarning(
80-
'Found an existing <meta name="viewport"> tag. Flutter Web uses its own viewport '
81-
'configuration for better compatibility with Flutter. This tag will be replaced.',
82-
);
83-
}
84-
return true;
85-
}());
86-
viewportMeta.remove();
72+
final List<DomElement> existingMetas = domDocument.head!
73+
.querySelectorAll('meta[name="viewport"]')
74+
.toList();
75+
76+
// Carry the `viewport-fit` of the tags that are about to be removed over to
77+
// the tag that replaces them.
78+
//
79+
// `viewport-fit` is how an app tells the browser that it wants to draw
80+
// under display cutouts and rounded corners, and it is also what makes the
81+
// browser report non-zero `env(safe-area-inset-*)` values, which back
82+
// `ui.FlutterView.viewPadding`. Dropping it would leave apps with no way to
83+
// opt into a full-bleed layout, and would make `SafeArea` a no-op.
84+
// See https://github.com/flutter/flutter/issues/84833.
85+
//
86+
// The assignment is unconditional, so that the last tag on the page wins,
87+
// including when it declares no `viewport-fit` at all. That is how the
88+
// browser resolves several viewport meta tags: each one is parsed into a
89+
// fresh set of viewport arguments that replaces the previous one, so the
90+
// descriptors that the last tag omits go back to their defaults.
91+
//
92+
// This also preserves the value across hot restarts, because the tags being
93+
// read include the `flt-viewport` tag written by the previous run of the
94+
// engine.
95+
ViewportFit? viewportFit;
96+
for (final viewportMeta in existingMetas) {
97+
viewportFit = readViewportFit(viewportMeta.getAttribute('content'));
8798
}
8899

89-
// The meta viewport is always removed by the for method above, so we don't
90-
// need to do anything else here, other than create it again.
91100
// These viewport settings are chosen to be accessibility-friendly, notably,
92101
// `user-scalable=no` is not used to comply with WCAG 2 rules.
102+
final String content = <String>[
103+
'width=device-width',
104+
'initial-scale=1.0',
105+
'maximum-scale=5.0',
106+
if (viewportFit != null) viewportFit.descriptor,
107+
].join(', ');
108+
109+
assert(() {
110+
_warnAboutDroppedDescriptors(existingMetas, content);
111+
return true;
112+
}());
113+
114+
for (final viewportMeta in existingMetas) {
115+
viewportMeta.remove();
116+
}
117+
93118
final DomHTMLMetaElement viewportMeta = createDomHTMLMetaElement()
94119
..setAttribute('flt-viewport', '')
95120
..name = 'viewport'
96-
..content = 'width=device-width, initial-scale=1.0, maximum-scale=5.0';
121+
..content = content;
97122

98123
domDocument.head!.append(viewportMeta);
99124

125+
// This must remain the first `registerElementForCleanup` call of the boot
126+
// sequence. The first call is what sweeps the elements registered by the
127+
// previous run of the app off the page, and the tags read above are among
128+
// them.
100129
registerElementForCleanup(viewportMeta);
101130
}
131+
132+
// Warns about each tag in [existingMetas] that says something the tag the
133+
// engine is about to write, whose `content` is [content], does not.
134+
//
135+
// A page that only declares descriptors the engine writes anyway — which is
136+
// what the `flutter create` web template suggests, so that an app can opt
137+
// into a full-bleed layout — loses nothing by being replaced, and warning
138+
// about it would be telling developers off for following our own advice.
139+
static void _warnAboutDroppedDescriptors(List<DomElement> existingMetas, String content) {
140+
final Map<String, String> written = parseViewportContent(content);
141+
for (final viewportMeta in existingMetas) {
142+
// Skip the tag that the engine placed on the page on a previous run. It
143+
// is still here because hot restart cleans the old tag up synchronously
144+
// with the first post-restart frame.
145+
if (viewportMeta.hasAttribute('flt-viewport')) {
146+
continue;
147+
}
148+
final List<String> dropped =
149+
(parseViewportContent(viewportMeta.getAttribute('content')).entries
150+
.where(
151+
(MapEntry<String, String> descriptor) =>
152+
written[descriptor.key] != descriptor.value,
153+
)
154+
.map((MapEntry<String, String> descriptor) => descriptor.key)
155+
.toList())
156+
..sort();
157+
if (dropped.isNotEmpty) {
158+
printWarning(
159+
'Found an existing <meta name="viewport"> tag. Flutter Web uses its own viewport '
160+
'configuration for better compatibility with Flutter, so ${dropped.join(', ')} '
161+
'will be ignored. Its `viewport-fit`, if any, is preserved.',
162+
);
163+
}
164+
}
165+
}
102166
}

0 commit comments

Comments
 (0)