[web] Move all DOM creation to DomManager (flutter/engine#48123)

- `FlutterViewEmbedder` doesn't create the DOM tree anymore (instead, `DomManager` does).
- `DomManager` only creates the DOM tree (with styles) but doesn't insert it into the document.
- `EngineFlutterView` takes the root element from `DomManager` and inserts it into the document.
- We finally can now create multiple Flutter views, each with its own DOM tree.

cc @yjbanov since I'm making a few changes that probably conflict with your semantics changes.

Part of https://github.com/flutter/flutter/issues/134443
Part of https://github.com/flutter/flutter/issues/137447
This commit is contained in:
Mouad Debbar
2023-11-17 11:45:23 -05:00
committed by GitHub
parent cbd9e7a1fa
commit 360c454b63
6 changed files with 257 additions and 275 deletions

View File

@@ -2,7 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/src/engine/safe_browser_api.dart';
import 'package:ui/ui.dart' as ui;
import '../engine.dart' show buildMode, renderer;
@@ -12,9 +11,7 @@ import 'dom.dart';
import 'keyboard_binding.dart';
import 'platform_dispatcher.dart';
import 'pointer_binding.dart';
import 'semantics.dart';
import 'text_editing/text_editing.dart';
import 'view_embedder/dom_manager.dart';
import 'view_embedder/style_manager.dart';
import 'window.dart';
@@ -42,35 +39,13 @@ class FlutterViewEmbedder {
reset();
}
/// The element that contains the [sceneElement].
///
/// This element is created and inserted in the HTML DOM once. It is never
/// removed or moved. However the [sceneElement] may be replaced inside it.
///
/// This element is inserted after the [semanticsHostElement] so that
/// platform views take precedence in DOM event handling.
DomElement get sceneHostElement => _sceneHostElement;
late DomElement _sceneHostElement;
DomElement get _sceneHostElement => window.dom.sceneHost;
/// A child element of body outside the shadowroot that hosts
/// global resources such svg filters and clip paths when using webkit.
DomElement? _resourcesHost;
/// The element that contains the semantics tree.
///
/// This element is created and inserted in the HTML DOM once. It is never
/// removed or moved.
///
/// Render semantics inside the glasspane for proper focus and event
/// handling. If semantics is behind the glasspane, the phone will disable
/// focusing by touch, only by tabbing around the UI. If semantics is in
/// front of glasspane, then DOM event won't bubble up to the glasspane so
/// it can forward events to the framework.
///
/// This element is inserted before the [semanticsHostElement] so that
/// platform views take precedence in DOM event handling.
DomElement get semanticsHostElementDEPRECATED => _semanticsHostElement;
late DomElement _semanticsHostElement;
DomElement get _semanticsHostElement => window.dom.semanticsHost;
/// The last scene element rendered by the [render] method.
DomElement? get sceneElement => _sceneElement;
@@ -88,27 +63,8 @@ class FlutterViewEmbedder {
}
}
/// The element that captures input events, such as pointer events.
///
/// If semantics is enabled this element also contains the semantics DOM tree,
/// which captures semantics input events. The semantics DOM tree must be a
/// child of the glass pane element so that events bubble up to the glass pane
/// if they are not handled by semantics.
DomElement get flutterViewElementDEPRECATED => _flutterViewElement;
late DomElement _flutterViewElement;
DomElement get glassPaneElementDEPRECATED => _glassPaneElement;
late DomElement _glassPaneElement;
/// The shadow root of the [glassPaneElement], which contains the whole Flutter app.
DomShadowRoot get glassPaneShadowDEPRECATED => _glassPaneShadow;
late DomShadowRoot _glassPaneShadow;
DomElement get textEditingHostNodeDEPRECATED => _textEditingHostNode;
late DomElement _textEditingHostNode;
DomElement get announcementsHostDEPRECATED => _announcementsHost;
late DomElement _announcementsHost;
DomElement get _flutterViewElement => window.dom.rootElement;
DomShadowRoot get _glassPaneShadow => window.dom.renderingHost;
void reset() {
// How was the current renderer selected?
@@ -127,77 +83,9 @@ class FlutterViewEmbedder {
},
);
// Create and inject the [_glassPaneElement].
_flutterViewElement = domDocument.createElement(DomManager.flutterViewTagName);
_glassPaneElement = domDocument.createElement(DomManager.glassPaneTagName);
// This must be attached to the DOM now, so the engine can create a host
// node (ShadowDOM or a fallback) next.
//
// The embeddingStrategy will take care of cleaning up the glassPane on hot
// restart.
window.embeddingStrategy.attachGlassPane(_flutterViewElement);
_flutterViewElement.appendChild(_glassPaneElement);
if (getJsProperty<Object?>(_glassPaneElement, 'attachShadow') == null) {
throw UnsupportedError('ShadowDOM is not supported in this browser.');
}
// Create a [HostNode] under the glass pane element, and attach everything
// there, instead of directly underneath the glass panel.
final DomShadowRoot shadowRoot = _glassPaneElement.attachShadow(<String, dynamic>{
'mode': 'open',
// This needs to stay false to prevent issues like this:
// - https://github.com/flutter/flutter/issues/85759
'delegatesFocus': false,
});
_glassPaneShadow = shadowRoot;
StyleManager.attachGlobalStyles(
node: shadowRoot,
styleId: 'flt-internals-stylesheet',
styleNonce: configuration.nonce,
cssSelectorPrefix: '',
);
_textEditingHostNode =
createTextEditingHostNode(_flutterViewElement, configuration.nonce);
_sceneHostElement = domDocument.createElement(DomManager.sceneHostTagName);
StyleManager.styleSceneHost(
_sceneHostElement,
debugShowSemanticsNodes: configuration.debugShowSemanticsNodes,
);
renderer.reset(this);
_semanticsHostElement = domDocument.createElement(DomManager.semanticsHostTagName);
StyleManager.styleSemanticsHost(
_semanticsHostElement,
window.devicePixelRatio,
);
final DomElement accessibilityPlaceholder = EngineSemanticsOwner
.instance.semanticsHelper
.prepareAccessibilityPlaceholder();
_announcementsHost = createDomElement(DomManager.announcementsHostTagName);
shadowRoot.append(accessibilityPlaceholder);
shadowRoot.append(_sceneHostElement);
shadowRoot.append(_announcementsHost);
// The semantic host goes last because hit-test order-wise it must be
// first. If semantics goes under the scene host, platform views will
// obscure semantic elements.
//
// You may be wondering: wouldn't semantics obscure platform views and
// make then not accessible? At least with some careful planning, that
// should not be the case. The semantics tree makes all of its non-leaf
// elements transparent. This way, if a platform view appears among other
// interactive Flutter widgets, as long as those widgets do not intersect
// with the platform view, the platform view will be reachable.
_flutterViewElement.appendChild(_semanticsHostElement);
// TODO(mdebbar): Move these to `engine/initialization.dart`.
KeyboardBinding.initInstance();
PointerBinding.initInstance(
@@ -294,20 +182,3 @@ FlutterViewEmbedder ensureFlutterViewEmbedderInitialized() {
ensureImplicitViewInitialized();
return _flutterViewEmbedder ??= FlutterViewEmbedder();
}
/// Creates a node to host text editing elements and applies a stylesheet
/// to Flutter nodes that exist outside of the shadowDOM.
DomElement createTextEditingHostNode(DomElement root, String? nonce) {
StyleManager.attachGlobalStyles(
node: root,
styleId: 'flt-text-editing-stylesheet',
styleNonce: nonce,
cssSelectorPrefix: DomManager.flutterViewTagName,
);
final DomElement domElement =
domDocument.createElement('flt-text-editing-host');
root.appendChild(domElement);
return domElement;
}

View File

@@ -4,8 +4,11 @@
import 'package:ui/ui.dart' as ui;
import '../configuration.dart';
import '../dom.dart';
import '../embedder.dart';
import '../safe_browser_api.dart';
import '../semantics/semantics.dart';
import 'style_manager.dart';
/// Manages DOM elements and the DOM structure for a [ui.FlutterView].
///
@@ -19,24 +22,111 @@ import '../embedder.dart';
/// | | |
/// | | +- <flt-semantics-placeholder>
/// | | |
/// | | +- <flt-scene-host>
/// | | +- [sceneHost] <flt-scene-host>
/// | | | |
/// | | | +- <flt-scene>
/// | | |
/// | | +- [announcementsHost] <flt-announcement-host>
/// | | |
/// | | +- <style>
/// | |
/// | +- ...platform views
/// |
/// +- [textEditingHost] <text-editing-host>
/// +- [textEditingHost] <flt-text-editing-host>
/// | |
/// | +- ...text fields
/// |
/// +- [semanticsHost] <semantics-host>
/// |
/// +- ...semantics nodes
/// +- [semanticsHost] <flt-semantics-host>
/// | |
/// | +- ...semantics nodes
/// |
/// +- <style>
///
class DomManager {
DomManager.fromFlutterViewEmbedderDEPRECATED(this._embedder);
factory DomManager({required double devicePixelRatio}) {
final DomElement rootElement = domDocument.createElement(DomManager.flutterViewTagName);
final DomElement platformViewsHost = domDocument.createElement(DomManager.glassPaneTagName);
final DomShadowRoot renderingHost = _attachShadowRoot(platformViewsHost);
final DomElement sceneHost = domDocument.createElement(DomManager.sceneHostTagName);
final DomElement textEditingHost = domDocument.createElement(DomManager.textEditingHostTagName);
final DomElement semanticsHost = domDocument.createElement(DomManager.semanticsHostTagName);
final DomElement announcementsHost = createDomElement(DomManager.announcementsHostTagName);
// Root element children.
rootElement.appendChild(platformViewsHost);
rootElement.appendChild(textEditingHost);
// The semantic host goes last because hit-test order-wise it must be
// first. If semantics goes under the scene host, platform views will
// obscure semantic elements.
//
// You may be wondering: wouldn't semantics obscure platform views and
// make then not accessible? At least with some careful planning, that
// should not be the case. The semantics tree makes all of its non-leaf
// elements transparent. This way, if a platform view appears among other
// interactive Flutter widgets, as long as those widgets do not intersect
// with the platform view, the platform view will be reachable.
rootElement.appendChild(semanticsHost);
// Rendering host (shadow root) children.
// TODO(yjbanov): In a multi-view world, we may want to have a separate
// semantics owner for each view.
// https://github.com/flutter/flutter/issues/137445
final DomElement accessibilityPlaceholder = EngineSemanticsOwner
.instance.semanticsHelper
.prepareAccessibilityPlaceholder();
renderingHost.append(accessibilityPlaceholder);
renderingHost.append(sceneHost);
renderingHost.append(announcementsHost);
// Styling.
StyleManager.attachGlobalStyles(
node: rootElement,
styleId: 'flt-text-editing-stylesheet',
styleNonce: configuration.nonce,
cssSelectorPrefix: DomManager.flutterViewTagName,
);
StyleManager.attachGlobalStyles(
node: renderingHost,
styleId: 'flt-internals-stylesheet',
styleNonce: configuration.nonce,
cssSelectorPrefix: '',
);
StyleManager.styleSceneHost(
sceneHost,
debugShowSemanticsNodes: configuration.debugShowSemanticsNodes,
);
StyleManager.styleSemanticsHost(
semanticsHost,
devicePixelRatio,
);
return DomManager._(
rootElement: rootElement,
platformViewsHost: platformViewsHost,
renderingHost: renderingHost,
sceneHost: sceneHost,
textEditingHost: textEditingHost,
semanticsHost: semanticsHost,
announcementsHost: announcementsHost,
);
}
DomManager._({
required this.rootElement,
required this.platformViewsHost,
required this.renderingHost,
required this.sceneHost,
required this.textEditingHost,
required this.semanticsHost,
required this.announcementsHost,
});
/// The tag name for the Flutter View root element.
static const String flutterViewTagName = 'flutter-view';
@@ -47,38 +137,59 @@ class DomManager {
/// The tag name for the scene host.
static const String sceneHostTagName = 'flt-scene-host';
/// The tag name for the text editing host.
static const String textEditingHostTagName = 'flt-text-editing-host';
/// The tag name for the semantics host.
static const String semanticsHostTagName = 'flt-semantics-host';
/// The tag name for the accessibility announcements host.
static const String announcementsHostTagName = 'flt-announcement-host';
final FlutterViewEmbedder _embedder;
/// The root DOM element for the entire Flutter View.
///
/// This is where input events are captured, such as pointer events.
///
/// If semantics is enabled, this element also contains the semantics DOM tree,
/// which captures semantics input events.
DomElement get rootElement => _embedder.flutterViewElementDEPRECATED;
final DomElement rootElement;
/// Hosts all platform view elements.
DomElement get platformViewsHost => _embedder.glassPaneElementDEPRECATED;
final DomElement platformViewsHost;
/// Hosts all rendering elements and canvases.
DomShadowRoot get renderingHost => _embedder.glassPaneShadowDEPRECATED;
final DomShadowRoot renderingHost;
/// Hosts the <flt-scene> element.
///
/// This element is created and inserted in the HTML DOM once. It is never
/// removed or moved. However the <flt-scene> inside of it may be replaced.
final DomElement sceneHost;
/// Hosts all text editing elements.
DomElement get textEditingHost => _embedder.textEditingHostNodeDEPRECATED;
final DomElement textEditingHost;
/// Hosts the semantics tree.
///
/// This element is in front of the [renderingHost] and [platformViewsHost].
/// Otherwise, the phone will disable focusing by touch, only by tabbing
/// around the UI.
DomElement get semanticsHost => _embedder.semanticsHostElementDEPRECATED;
final DomElement semanticsHost;
/// This is where accessibility announcements are inserted.
DomElement get announcementsHost => _embedder.announcementsHostDEPRECATED;
final DomElement announcementsHost;
}
DomShadowRoot _attachShadowRoot(DomElement element) {
assert(
getJsProperty<Object?>(element, 'attachShadow') != null,
'ShadowDOM is not supported in this browser.',
);
return element.attachShadow(<String, dynamic>{
'mode': 'open',
// This needs to stay false to prevent issues like this:
// - https://github.com/flutter/flutter/issues/85759
'delegatesFocus': false,
});
}

View File

@@ -2,11 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@JS()
library window;
import 'dart:async';
import 'dart:js_interop';
import 'dart:typed_data';
import 'package:meta/meta.dart';
@@ -16,7 +12,6 @@ import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../engine.dart' show DimensionsProvider, registerHotRestartListener, renderer;
import 'display.dart';
import 'dom.dart';
import 'embedder.dart';
import 'mouse/context_menu.dart';
import 'mouse/cursor.dart';
import 'navigation/history.dart';
@@ -59,7 +54,12 @@ base class EngineFlutterView implements ui.FlutterView {
// by the public `EngineFlutterView` constructor).
DomElement? hostElement,
) : embeddingStrategy = EmbeddingStrategy.create(hostElement: hostElement),
_dimensionsProvider = DimensionsProvider.create(hostElement: hostElement);
_dimensionsProvider = DimensionsProvider.create(hostElement: hostElement) {
platformDispatcher.registerView(this);
// The embeddingStrategy will take care of cleaning up the rootElement on
// hot restart.
embeddingStrategy.attachGlassPane(dom.rootElement);
}
@override
final int viewId;
@@ -87,8 +87,7 @@ base class EngineFlutterView implements ui.FlutterView {
late final ContextMenu contextMenu = ContextMenu(dom.rootElement);
late final DomManager dom =
DomManager.fromFlutterViewEmbedderDEPRECATED(flutterViewEmbedder);
late final DomManager dom = DomManager(devicePixelRatio: devicePixelRatio);
late final PlatformViewMessageHandler platformViewMessageHandler =
PlatformViewMessageHandler(platformViewsContainer: dom.platformViewsHost);
@@ -168,7 +167,6 @@ final class _EngineFlutterViewImpl extends EngineFlutterView {
super.platformDispatcher,
super.hostElement,
) : super._() {
platformDispatcher.registerView(this);
registerHotRestartListener(() {
// TODO(harryterkelsen): What should we do about this in multi-view?
renderer.clearFragmentProgramCache();
@@ -184,7 +182,6 @@ final class EngineFlutterWindow extends EngineFlutterView implements ui.Singleto
super.platformDispatcher,
super.hostElement,
) : super._() {
platformDispatcher.registerView(this);
if (ui_web.isCustomUrlStrategySet) {
_browserHistory = createHistoryForExistingState(ui_web.urlStrategy);
}

View File

@@ -1,10 +1,6 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@JS()
library embedder_test; // We need this to mess with the ShadowDOM.
import 'dart:js_interop';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
@@ -47,15 +43,6 @@ void testMain() {
// TODO(ferhat): https://github.com/flutter/flutter/issues/46638
skip: browserEngine == BrowserEngine.firefox);
test('accesibility placeholder is attached after creation', () {
final FlutterViewEmbedder embedder = FlutterViewEmbedder();
expect(
embedder.glassPaneShadowDEPRECATED.querySelectorAll('flt-semantics-placeholder'),
isNotEmpty,
);
});
test('should add/remove global resource', () {
final FlutterViewEmbedder embedder = FlutterViewEmbedder();
final DomHTMLDivElement resource = createDomHTMLDivElement();
@@ -66,84 +53,4 @@ void testMain() {
embedder.removeResource(resource);
expect(resourceRoot.childNodes.length, 0);
});
test('hide placeholder text for textfield', () {
final FlutterViewEmbedder embedder = FlutterViewEmbedder();
final DomHTMLInputElement regularTextField = createDomHTMLInputElement();
regularTextField.placeholder = 'Now you see me';
embedder.addResource(regularTextField);
regularTextField.focus();
DomCSSStyleDeclaration? style = domWindow.getComputedStyle(
embedder.glassPaneShadowDEPRECATED.querySelector('input')!,
'::placeholder');
expect(style, isNotNull);
expect(style.opacity, isNot('0'));
final DomHTMLInputElement textField = createDomHTMLInputElement();
textField.placeholder = 'Now you dont';
textField.classList.add('flt-text-editing');
embedder.addResource(textField);
textField.focus();
style = domWindow.getComputedStyle(
embedder.glassPaneShadowDEPRECATED.querySelector('input.flt-text-editing')!,
'::placeholder');
expect(style, isNotNull);
expect(style.opacity, '0');
}, skip: browserEngine != BrowserEngine.firefox);
group('Shadow root', () {
late FlutterViewEmbedder embedder;
setUp(() {
embedder = FlutterViewEmbedder();
});
tearDown(() {
embedder.glassPaneElementDEPRECATED.remove();
});
test('throws when shadowDom is not available', () {
final dynamic oldAttachShadow = attachShadow;
expect(oldAttachShadow, isNotNull);
attachShadow = null; // Break ShadowDOM
expect(() => FlutterViewEmbedder(), throwsUnsupportedError);
attachShadow = oldAttachShadow; // Restore ShadowDOM
});
test('Initializes and attaches a shadow root', () {
expect(domInstanceOfString(embedder.glassPaneShadowDEPRECATED, 'ShadowRoot'), isTrue);
expect(embedder.glassPaneShadowDEPRECATED.host, embedder.glassPaneElementDEPRECATED);
expect(embedder.glassPaneShadowDEPRECATED, embedder.glassPaneElementDEPRECATED.shadowRoot);
// The shadow root should be initialized with correct parameters.
expect(embedder.glassPaneShadowDEPRECATED.mode, 'open');
if (browserEngine != BrowserEngine.firefox &&
browserEngine != BrowserEngine.webkit) {
// Older versions of Safari and Firefox don't support this flag yet.
// See: https://caniuse.com/mdn-api_shadowroot_delegatesfocus
expect(embedder.glassPaneShadowDEPRECATED.delegatesFocus, isFalse);
}
});
test('Attaches a stylesheet to the shadow root', () {
final DomElement? style =
embedder.glassPaneShadowDEPRECATED.querySelector('#flt-internals-stylesheet');
expect(style, isNotNull);
expect(style!.tagName, equalsIgnoringCase('style'));
expect(style.parentNode, embedder.glassPaneShadowDEPRECATED);
});
});
}
@JS('Element.prototype.attachShadow')
external JSAny? get _attachShadow;
dynamic get attachShadow => _attachShadow?.toObjectShallow;
@JS('Element.prototype.attachShadow')
external set _attachShadow(JSAny? x);
set attachShadow(Object? x) => _attachShadow = x?.toJSAnyShallow;

View File

@@ -23,8 +23,6 @@ DateTime _testTime = DateTime(2018, 12, 17);
EngineSemanticsOwner semantics() => EngineSemanticsOwner.instance;
DomShadowRoot get renderingHost =>
EnginePlatformDispatcher.instance.implicitView!.dom.renderingHost;
DomElement get platformViewsHost =>
EnginePlatformDispatcher.instance.implicitView!.dom.platformViewsHost;
@@ -226,14 +224,14 @@ void _testEngineSemanticsOwner() {
});
test('placeholder enables semantics', () async {
flutterViewEmbedder.reset(); // triggers `autoEnableOnTap` to be called
final DomManager domManager = DomManager(devicePixelRatio: 3.0);
expect(semantics().semanticsEnabled, isFalse);
// Synthesize a click on the placeholder.
final DomElement placeholder =
renderingHost.querySelector('flt-semantics-placeholder')!;
domManager.renderingHost.querySelector('flt-semantics-placeholder')!;
expect(placeholder.isConnected, isTrue);
expect(domManager.renderingHost.contains(placeholder), isTrue);
final DomRect rect = placeholder.getBoundingClientRect();
placeholder.dispatchEvent(createDomMouseEvent('click', <Object?, Object?>{
@@ -243,12 +241,12 @@ void _testEngineSemanticsOwner() {
// On mobile semantics is enabled asynchronously.
if (isMobile) {
while (placeholder.isConnected!) {
while (domManager.renderingHost.contains(placeholder)) {
await Future<void>.delayed(const Duration(milliseconds: 50));
}
}
expect(semantics().semanticsEnabled, isTrue);
expect(placeholder.isConnected, isFalse);
expect(domManager.renderingHost.contains(placeholder), isFalse);
});
test('accessibilityFeatures copyWith function works', () {
@@ -319,7 +317,7 @@ void _testEngineSemanticsOwner() {
});
test('auto-enables semantics', () async {
flutterViewEmbedder.reset(); // triggers `autoEnableOnTap` to be called
final DomManager domManager = DomManager(devicePixelRatio: 3.0);
expect(semantics().semanticsEnabled, isFalse);
expect(
EnginePlatformDispatcher
@@ -327,9 +325,7 @@ void _testEngineSemanticsOwner() {
isFalse);
final DomElement placeholder =
renderingHost.querySelector('flt-semantics-placeholder')!;
expect(placeholder.isConnected, isTrue);
domManager.renderingHost.querySelector('flt-semantics-placeholder')!;
// Sending a semantics update should auto-enable engine semantics.
final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder();
@@ -343,7 +339,7 @@ void _testEngineSemanticsOwner() {
isTrue);
// The placeholder should be removed
expect(placeholder.isConnected, isFalse);
expect(domManager.renderingHost.contains(placeholder), isFalse);
});
void renderSemantics({String? label, String? tooltip, Set<ui.SemanticsFlag> flags = const <ui.SemanticsFlag>{}}) {

View File

@@ -2,28 +2,128 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@JS()
library dom_manager_test; // We need this to mess with the ShadowDOM.
import 'dart:js_interop';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import '../../common/matchers.dart';
void main() {
internalBootstrapBrowserTest(() => doTests);
}
void doTests() {
group('DomManager', () {
test('fromFlutterViewEmbedderDEPRECATED', () {
ensureImplicitViewInitialized();
final FlutterViewEmbedder embedder = FlutterViewEmbedder();
final DomManager domManager =
DomManager.fromFlutterViewEmbedderDEPRECATED(embedder);
test('DOM tree looks right', () {
final DomManager domManager = DomManager(devicePixelRatio: 3.0);
expect(domManager.rootElement, embedder.flutterViewElementDEPRECATED);
expect(domManager.renderingHost, embedder.glassPaneShadowDEPRECATED);
expect(domManager.platformViewsHost, embedder.glassPaneElementDEPRECATED);
expect(domManager.textEditingHost, embedder.textEditingHostNodeDEPRECATED);
expect(domManager.semanticsHost, embedder.semanticsHostElementDEPRECATED);
expect(domManager.announcementsHost, embedder.announcementsHostDEPRECATED);
// Check tag names.
expect(domManager.rootElement.tagName, equalsIgnoringCase(DomManager.flutterViewTagName));
expect(domManager.platformViewsHost.tagName, equalsIgnoringCase(DomManager.glassPaneTagName));
expect(domManager.textEditingHost.tagName, equalsIgnoringCase(DomManager.textEditingHostTagName));
expect(domManager.semanticsHost.tagName, equalsIgnoringCase(DomManager.semanticsHostTagName));
expect(domManager.announcementsHost.tagName, equalsIgnoringCase(DomManager.announcementsHostTagName));
// Check parent-child relationships.
final List<DomElement> rootChildren = domManager.rootElement.children.toList();
expect(rootChildren.length, 4);
expect(rootChildren[0], domManager.platformViewsHost);
expect(rootChildren[1], domManager.textEditingHost);
expect(rootChildren[2], domManager.semanticsHost);
expect(rootChildren[3].tagName, equalsIgnoringCase('style'));
final List<DomElement> shadowChildren = domManager.renderingHost.childNodes.cast<DomElement>().toList();
expect(shadowChildren.length, 4);
expect(shadowChildren[0].tagName, equalsIgnoringCase('flt-semantics-placeholder'));
expect(shadowChildren[1], domManager.sceneHost);
expect(shadowChildren[2], domManager.announcementsHost);
expect(shadowChildren[3].tagName, equalsIgnoringCase('style'));
});
test('hide placeholder text for textfield', () {
final DomManager domManager = DomManager(devicePixelRatio: 3.0);
domDocument.body!.append(domManager.rootElement);
final DomHTMLInputElement regularTextField = createDomHTMLInputElement();
regularTextField.placeholder = 'Now you see me';
domManager.rootElement.appendChild(regularTextField);
regularTextField.focus();
DomCSSStyleDeclaration? style = domWindow.getComputedStyle(
domManager.rootElement.querySelector('input')!,
'::placeholder');
expect(style, isNotNull);
expect(style.opacity, isNot('0'));
final DomHTMLInputElement textField = createDomHTMLInputElement();
textField.placeholder = 'Now you dont';
textField.classList.add('flt-text-editing');
domManager.rootElement.appendChild(textField);
textField.focus();
style = domWindow.getComputedStyle(
domManager.rootElement.querySelector('input.flt-text-editing')!,
'::placeholder');
expect(style, isNotNull);
expect(style.opacity, '0');
domManager.rootElement.remove();
// For some reason, only Firefox is able to correctly compute styles for
// the `::placeholder` pseudo-element.
}, skip: browserEngine != BrowserEngine.firefox);
});
group('Shadow root', () {
test('throws when shadowDom is not available', () {
final dynamic oldAttachShadow = attachShadow;
expect(oldAttachShadow, isNotNull);
attachShadow = null; // Break ShadowDOM
expect(() => DomManager(devicePixelRatio: 3.0), throwsAssertionError);
attachShadow = oldAttachShadow; // Restore ShadowDOM
});
test('Initializes and attaches a shadow root', () {
final DomManager domManager = DomManager(devicePixelRatio: 3.0);
expect(domInstanceOfString(domManager.renderingHost, 'ShadowRoot'), isTrue);
expect(domManager.renderingHost.host, domManager.platformViewsHost);
expect(domManager.renderingHost, domManager.platformViewsHost.shadowRoot);
// The shadow root should be initialized with correct parameters.
expect(domManager.renderingHost.mode, 'open');
if (browserEngine != BrowserEngine.firefox &&
browserEngine != BrowserEngine.webkit) {
// Older versions of Safari and Firefox don't support this flag yet.
// See: https://caniuse.com/mdn-api_shadowroot_delegatesfocus
expect(domManager.renderingHost.delegatesFocus, isFalse);
}
});
test('Attaches a stylesheet to the shadow root', () {
final DomManager domManager = DomManager(devicePixelRatio: 3.0);
final DomElement? style =
domManager.renderingHost.querySelector('#flt-internals-stylesheet');
expect(style, isNotNull);
expect(style!.tagName, equalsIgnoringCase('style'));
expect(style.parentNode, domManager.renderingHost);
});
});
}
@JS('Element.prototype.attachShadow')
external JSAny? get _attachShadow;
dynamic get attachShadow => _attachShadow?.toObjectShallow;
@JS('Element.prototype.attachShadow')
external set _attachShadow(JSAny? x);
set attachShadow(Object? x) => _attachShadow = x?.toJSAnyShallow;