Skip to content

Commit 0748e48

Browse files
[web] Report env(safe-area-inset-*) as FlutterView.viewPadding (flutter#191647)
# [web] Report `env(safe-area-inset-*)` as `FlutterView.viewPadding` ## The problem `SafeArea` does nothing on the web. On an iPhone running the app as a standalone PWA, content sits under the notch, the Dynamic Island and the home indicator, and `MediaQuery.paddingOf(context)` is `EdgeInsets.zero` on every browser. The issue has been open since 2021, and the workaround that everybody in the thread reaches for — adding `<meta name="viewport" content="..., viewport-fit=cover">` to `index.html` — has no effect. Issue: flutter#84833 ## Root cause There are two independent causes, and fixing either one alone leaves the bug in place. **1. The engine deletes the app's opt-in.** `FullPageEmbeddingStrategy._applyViewportMeta()` (`engine/src/flutter/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/full_page_embedding_strategy.dart:70`) runs `querySelectorAll('meta[name="viewport"]')`, calls `remove()` on every match (line 86), and appends its own tag with a hard-coded `content = 'width=device-width, initial-scale=1.0, maximum-scale=5.0'` (line 96). There is no `viewport-fit` in it. So an app that wrote `viewport-fit=cover` in its `index.html` has that descriptor deleted during bootstrap, WebKit reverts to keeping the viewport inside the safe area, and `env(safe-area-inset-*)` correctly reports that there is nothing to inset. This is why every workaround in the thread fails. **2. Nothing ever reads `env(safe-area-inset-*)`.** Grepping `safe-area|safeAreaInset|viewport-fit|viewportFit` across `engine/src/flutter/lib/web_ui/lib/` returns no matches before this change. `EngineFlutterView.viewPadding` (`window.dart:264`) and `EngineFlutterView.padding` (`window.dart:270`) both read a `final ViewConfiguration _viewConfiguration = const ViewConfiguration();` (`window.dart:97`) that is never reassigned, so they are permanently `ui.ViewPadding.zero`. Only `viewInsets` works, because it is backed by a mutable field that `_computeOnScreenKeyboardInsets` (`window.dart:363`) updates through `DimensionsProvider.computeKeyboardInsets`. ## Reproduction Measured on an iPhone simulator, `devicePixelRatio` 3, UA `Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.1 Mobile/15E148 Safari/604.1`. Two pages were served side by side from the same origin: a plain HTML control that declares `viewport-fit=cover` and reads `env(safe-area-inset-*)` out of `getComputedStyle`, and a Flutter app whose `index.html` declares the same tag and which additionally reports `MediaQuery.viewPaddingOf` / `paddingOf`. Both declare `apple-mobile-web-app-status-bar-style=black-translucent`. Each was read in a Safari tab and as a standalone add-to-home-screen PWA, in both orientations. 11 configurations were recorded in all, from 997 samples; the four below are the ones the argument rests on. **The Flutter app was built with Flutter 3.44.6 stable**, not with this branch, so the engine tag quoted in row 3 is the one that release writes. Current `main` writes `maximum-scale=5.0` and no `user-scalable` descriptor. The difference is immaterial here: what matters is that neither carries a `viewport-fit`, and both remove the tag the app authored. | page | mode | orientation | `innerWidth` | viewport meta actually in the DOM | browser `env()` T/R/B/L | `MediaQuery.viewPaddingOf` | |---|---|---|---|---|---|---| | control | tab | landscape | 874 | `…, viewport-fit=cover` *(author's)* | `0 / 62 / 20 / 62` | n/a | | control | PWA | portrait | 402 | `…, viewport-fit=cover` *(author's)* | `0 / 0 / 34 / 0` | n/a | | Flutter | tab | landscape | 750 | `width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no` *(`flt-viewport`)* | `0 / 0 / 20 / 0` | `zero` | | Flutter | PWA | portrait | 402 | *(`flt-viewport`, no `viewport-fit`)* | `0 / 0 / 0 / 0` | `zero` | Two things to read off this: * The `viewport-fit=cover` the app wrote is **not in the DOM** on the Flutter page. The tag that is there is the engine's, and it has no `viewport-fit`. That is cause 1, observed directly. * The viewport is correspondingly narrower — 750 against the control's 874 in the same orientation on the same device. The difference, 124, is exactly `62 + 62`, the left and right insets the control reports. The app is being laid out inside the safe area. `MediaQuery.viewPaddingOf` was `EdgeInsets.zero` in **all 997 readings taken from the Flutter page**, including the runs where the viewport meta tag was restored by hand so that the page *did* go full-bleed and `env()` *did* report `0 / 62 / 20 / 62`. That isolates cause 2: even with the browser reporting a safe area correctly, nothing in the engine reads it. **What has not been measured on device.** The numbers above are all pre-patch. The patched engine has unit coverage (below) but has not been run on a device or simulator, so this PR claims no measured post-patch `MediaQuery.padding`. `env(safe-area-inset-top)` was **zero in all 11 configurations**, including the two standalone-PWA ones, where there is no Safari chrome to explain it away. I don't have an account of why, so I'm not offering one: the top axis is simply uncovered on device and rests on unit tests. If a reviewer knows the configuration that produces a non-zero top inset in mobile WebKit, I'd like to measure it. An end-to-end confirmation that a `SafeArea` child moves is also still owed. Both are repeated under "Not covered". The same run also shows why the `env()` values cannot be passed through verbatim: with **no** `viewport-fit` anywhere, iOS Safari still reports `env(safe-area-inset-bottom) = 20px` (row 3 above). See "Backwards compatibility" below. ## What the fix does **Layer 1 — preserve the app's `viewport-fit`.** `_applyViewportMeta()` now reads the `viewport-fit` descriptor off the viewport meta tags it is about to remove and copies it into the tag it writes. Parsing lives in one new file, `view_embedder/viewport_fit.dart`, so that the side that reads a descriptor and the side that writes it can never drift apart. The resolution matches the browser's: * the **last** viewport meta tag of the page wins outright, including when it declares no `viewport-fit` (WebKit builds a fresh set of viewport arguments per tag, so descriptors that the last tag omits revert to their defaults); * `,`, `;` and whitespace are all accepted as descriptor separators, because browsers accept all three — `content="width=400;initial-scale=1"` is honoured by both Blink and WebKit; * the descriptor and its value are matched case-insensitively; * only `auto`, `contain` and `cover` are copied over, so nothing unknown can reach the tag the engine writes. Because the tag the engine writes carries the descriptor, the value also survives hot restart: the tag read at the start of `_applyViewportMeta()` on the next run is the `flt-viewport` tag left behind by the previous one. The "this tag will be replaced" warning now fires only when the engine's tag really does say less than the app's — it lists the descriptors being dropped — so following the template's own advice below no longer provokes a warning on every debug run. **Layer 2 — feed `env(safe-area-inset-*)` into the framework.** `DimensionsProvider` gains `computeSafeAreaInsets()`. `FullPageDimensionsProvider` implements it with a `display: none` probe element whose four paddings are `env(safe-area-inset-*, 0px)`; the browser substitutes `env()` at computed-value time, so `getComputedStyle` returns absolute lengths without the element ever being laid out or painted. Every declaration on the probe is written with `important` priority, so an ordinary `* { padding: 0 !important }` reset in the host page cannot silently zero the measurement. The probe is created up front, in the constructor, so reading the safe area is a pure measurement and never a DOM mutation in the middle of a frame; it is re-attached if the host page ever empties `<body>`, and removed in `close()`. **The insets are gated on the app's own opt-in.** `computeSafeAreaInsets()` returns `ViewPadding.zero` unless the viewport meta tag the engine wrote carries `viewport-fit=cover`, i.e. unless the app declared it in its `index.html`. The gate reads that tag back with `readViewportFit`, the same function that wrote it, so the two halves are not coupled through an exact spelling: changing how `_applyViewportMeta` joins its descriptors cannot silently switch the feature off. `EngineFlutterView.viewPadding` is now backed by those insets, computed lazily and recomputed by `_handleBrowserResize` on the same events that recompute the physical size. `padding` is `viewPadding` minus `viewInsets`, clamped at zero (`ViewPadding.minus`), which is the relationship the other platforms use: when the on-screen keyboard covers the bottom safe area, the bottom padding goes to zero. No framework-side change is needed — `MediaQuery.fromView` already reads `view.padding` and `view.viewPadding`. `systemGestureInsets` is deliberately left at zero. `env()` describes the parts of the viewport that the device obstructs, not the parts the system reserves for its own gestures, and browsers do not expose the latter. **Tooling.** `packages/flutter_tools/templates/app/web/index.html.tmpl` gains the tag, commented out, with an explanation, next to the guidance it already carries for `<base href>`. New projects are not opted in by default; the comment tells developers how to opt in. **Cleanup.** `ViewConfiguration.viewInsets`, `.viewPadding` and `.padding` (`platform_dispatcher.dart`) are removed. `viewInsets` was already dead, and the other two become dead with this change; `ViewConfiguration` is only ever instantiated as `const ViewConfiguration()`. ## Backwards compatibility The gate is what keeps this from being a breaking change, and it is there because the naive version is one. * **Apps that never declared `viewport-fit`** — including everything `flutter create` produces, since the web template ships no active viewport meta tag — are unchanged. The engine writes a byte-identical viewport meta tag, and `viewPadding`, `padding` and `MediaQuery.paddingOf` stay `zero`. This is not automatic. iOS Safari reports `env(safe-area-inset-bottom) = 20px` in landscape *with no `viewport-fit` at all*, so an implementation that simply forwarded `env()` would have given every existing Flutter web app on iOS an uninvited `bottom: 20` logical pixels, shrinking the child of every `SafeArea` in an app that asked for nothing. The `20px` is a measured reading (row 3 of the table above); the resulting layout shift is the arithmetic consequence, not a second measurement. `FullPageDimensionsProvider.computeSafeAreaInsets()` therefore returns zero unless the page opted in, and the doc comment on `DimensionsProvider.computeSafeAreaInsets` says so explicitly. * **Apps that declared `viewport-fit=cover` in their `index.html` do change**, and this is the fix working rather than a side effect. Today the engine deletes the descriptor, so those apps are laid out inside the safe area; after this change they are laid out full-bleed. On the device above, that is the difference between the Flutter page's 750 logical pixels and the control's 874 in the same orientation, and content that is *not* wrapped in a `SafeArea` moves under the cutout and the rounded corners. This population matters: `viewport-fit=cover` in `index.html` is the most repeated workaround in issue flutter#84833 itself and in five years of blog posts about it. Many authors added the tag, saw nothing happen, and never wrapped anything in `SafeArea`. For them this is a visible layout change. It is the behaviour the tag has always requested, and the tag is the app's own explicit opt-in, but it should be called out in the release notes and it is the reason the PR does not carry `Fixes flutter#84833` on its own. * **Embedded (`hostElement`) and multi-view apps** are untouched. `_applyViewportMeta` only exists in `FullPageEmbeddingStrategy`, and `CustomElementDimensionsProvider.computeSafeAreaInsets()` returns zero, so `padding == zero.minus(viewInsets) == zero` exactly as before. * **Browsers without `env()` support** degrade to zero rather than to `NaN`: an unsupported `env()` leaves the padding at its initial value, which reads back as `0px`. If the team would rather not move the `viewport-fit=cover` population in a single release, the cover pass-through in `_applyViewportMeta` is the one place to put a `FlutterConfiguration` flag; the rest of the change is inert without it. ## Tests 42 new unit tests, run with `felt test --browser chrome --compiler dart2js` over the whole `test/engine` directory. The engine suite goes from 1190 to 1232 passing, 14 skipped, no failures and no regressions. A new `viewport_fit_test.dart` covers the parser directly: every specification value, unknown values, a descriptor that merely *ends* in `viewport-fit`, `,` `;` and whitespace separators, `=` spacing, case-insensitivity, last-declaration-wins, and a round trip between what `ViewportFit` writes and what `readViewportFit` reads. `parseViewportContent` is held to the same tolerance, so the two functions cannot disagree about what a `content` attribute says. The rest extend the four existing suites: the descriptor surviving `_applyViewportMeta` in each of those spellings; the gate staying shut for `auto` and `contain`, which the engine preserves but which must not unlock the insets; the probe's structure, its `important` priority beating a `* { padding: 5px !important }` rule in the host page, its re-attachment and its removal on `close()`; `viewPadding` refreshed by a real `resize` event rather than only by `debugForceResize`, so `_handleBrowserResize` is covered; zero for an embedded view; and `ViewPadding.minus` at no, partial and full clamping. Two of them run a real `FullPageEmbeddingStrategy` over a page declaring `viewport-fit=cover`, hand the page it leaves behind to a real `FullPageDimensionsProvider`, and assert a non-zero result (and a zero one for the negative twin). That seam between the two halves of the fix is where a hand-written `content` string would have hidden a break. Two mutations were run to check the tests bite. Making the gate accept any `viewport-fit` rather than only `cover` fails the `auto`/`contain` test. Changing how `_applyViewportMeta` joins its descriptors from `', '` to `';'` leaves the provider suite green — which is the point of sharing the parser, and would not have been true of an earlier revision of this patch that matched the joined string exactly. ## Not covered, left for follow-up * **Embedded and multi-view apps still get zero.** The engine could derive their insets from the intersection of the host element's bounding rect with the page's `env()` values; there is a `TODO` on `CustomElementDimensionsProvider.computeSafeAreaInsets` for it. Issue flutter#84833 should stay open until that lands, which is why this PR references the issue rather than closing it. * **Safe-area changes that do not resize the viewport are not observed.** `_viewPadding` is refreshed only from `_handleBrowserResize`. On iOS the status bar grows during a call, screen recording or personal hotspot without changing the viewport size, so `env(safe-area-inset-top)` changes with no `resize` event. A `ResizeObserver` on a probe whose `top`/`left`/`width`/ `height` are the `env()` values would close this; the limitation is documented on both `DimensionsProvider.computeSafeAreaInsets` and `EngineFlutterView._viewPadding`. * **`viewport-fit` injected from JavaScript after bootstrap** is not re-read. `_applyViewportMeta` runs once, in the strategy's constructor. * **`systemGestureInsets`** stays zero; browsers do not expose the information. * **`env(safe-area-inset-top)` has unit coverage but no on-device coverage.** It was zero in all 11 measured configurations, standalone PWAs included, and I have no explanation for that. It should be measured on a configuration that does report a non-zero top inset before this ships. * **Docs.** A companion flutter/website change should document the `viewport-fit=cover` opt-in on the web display-modes/initialization page and add a web caveat to the `SafeArea` API docs. ## 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. Notes on the checklist: * On the breaking change policy: the change is gated so that no app that did not declare `viewport-fit=cover` sees any difference in `MediaQuery.padding`, `MediaQuery.viewPadding` or its viewport meta tag. Apps that did declare it move from a safe-area-contained layout to a full-bleed one, with the measured numbers above. `customer_testing` / flutter/tests should be run against this branch before landing, and if anything moves, a migration guide from the flutter/website template should land with it. * No Data Driven Fixes apply: there is no API rename or removal on the framework side. <!-- 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 [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: Mouad Debbar <[email protected]>
1 parent 974341b commit 0748e48

15 files changed

Lines changed: 947 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: 93 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,80 @@ 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. web_ui's `parseFloat` returns null wherever JavaScript's
159+
// returns NaN, so the `?? 0.0` covers anything a computed `padding-*`
160+
// could fail to parse as.
161+
return (parseFloat(probeStyle.getPropertyValue(property)) ?? 0.0) * devicePixelRatio;
162+
}
163+
164+
return ViewPadding(
165+
top: inset('padding-top'),
166+
right: inset('padding-right'),
167+
bottom: inset('padding-bottom'),
168+
left: inset('padding-left'),
169+
);
170+
}
171+
172+
// Whether the page is laid out underneath the parts of the screen that the
173+
// device obstructs, which is the only situation in which the app has to inset
174+
// its own content.
175+
//
176+
// The viewport meta tag written by `FullPageEmbeddingStrategy` is the
177+
// authority on this. It is the last viewport meta tag of the page, and it
178+
// carries over the `viewport-fit` that the app declared in its `index.html`,
179+
// if any. It is read back with the same function that wrote it, so that the
180+
// two sides cannot drift apart over the exact spelling of the descriptor.
181+
bool get _isFullBleed {
182+
final DomElement? viewportMeta = domDocument.head?.querySelector(
183+
'meta[name="viewport"][flt-viewport]',
184+
);
185+
return readViewportFit(viewportMeta?.getAttribute('content')) == ViewportFit.cover;
186+
}
187+
188+
// Creates the element that the `env(safe-area-inset-*)` values are read back
189+
// from.
190+
//
191+
// The browser resolves `env()` into an absolute length at computed-value
192+
// time, so the insets can be read back from the probe with `getComputedStyle`
193+
// even though the probe is `display: none`, and therefore never laid out nor
194+
// painted.
195+
static DomHTMLDivElement _createSafeAreaProbe() {
196+
final DomHTMLDivElement probe = createDomHTMLDivElement()
197+
..setAttribute('flt-safe-area-probe', '');
198+
// Every declaration is `important`, because an inline declaration that is
199+
// not loses to an `!important` rule of the app, and a stylesheet as ordinary
200+
// as `* { padding: 0 !important }` would then silently zero the measurement
201+
// (or, for `display`, put an element on the page that shouldn't be there).
202+
probe.style.setProperty('display', 'none', 'important');
203+
for (final side in <String>['top', 'right', 'bottom', 'left']) {
204+
probe.style.setProperty('padding-$side', 'env(safe-area-inset-$side, 0px)', 'important');
205+
}
206+
return probe;
207+
}
115208
}

‎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)