[web] Migrate Flutter Web DOM usage to JS static interop - 15. (flutter/engine#33247)

This commit is contained in:
joshualitt
2022-05-18 09:48:36 -07:00
committed by GitHub
parent c250714a4f
commit 7825001bb1
13 changed files with 133 additions and 60 deletions

View File

@@ -26,9 +26,9 @@ class AssetManager {
String? get _baseUrl {
return domWindow.document
.querySelectorAll('meta')
.where((Object? domNode) => domInstanceOfString(domNode,
.where((DomElement domNode) => domInstanceOfString(domNode,
'HTMLMetaElement'))
.map((Object? domNode) => domNode! as DomHTMLMetaElement)
.map((DomElement domNode) => domNode as DomHTMLMetaElement)
.firstWhereOrNull(
(DomHTMLMetaElement element) => element.name == 'assetBase')
?.content;

View File

@@ -296,7 +296,7 @@ class HtmlViewEmbedder {
_svgPathDefs!.querySelector('#sk_path_defs')!;
final List<DomElement> nodesToRemove = <DomElement>[];
final Set<String> oldDefs = _svgClipDefs[viewId]!;
for (final DomElement child in clipDefs.children.cast<DomElement>()) {
for (final DomElement child in clipDefs.children) {
if (oldDefs.contains(child.id)) {
nodesToRemove.add(child);
}
@@ -732,8 +732,7 @@ class HtmlViewEmbedder {
/// Deletes SVG clip paths, useful for tests.
void debugCleanupSvgClipPaths() {
_svgPathDefs?.children.cast<DomElement>().single
.children.cast<DomElement>().forEach(removeElement);
_svgPathDefs?.children.single.children.forEach(removeElement);
_svgClipDefs.clear();
}

View File

@@ -25,6 +25,8 @@ class DomWindow {}
extension DomWindowExtension on DomWindow {
external DomConsole get console;
external DomDocument get document;
external int? get innerHeight;
external int? get innerWidth;
external DomNavigator get navigator;
external DomPerformance get performance;
Future<Object?> fetch(String url) =>
@@ -60,13 +62,16 @@ class DomDocument {}
extension DomDocumentExtension on DomDocument {
external DomElement? querySelector(String selectors);
external /* List<Node> */ List<Object?> querySelectorAll(String selectors);
List<DomElement> querySelectorAll(String selectors) =>
js_util.callMethod<List<Object?>>(
this, 'querySelectorAll', <Object>[selectors]).cast<DomElement>();
DomElement createElement(String name, [Object? options]) =>
js_util.callMethod(this, 'createElement',
<Object>[name, if (options != null) options]) as DomElement;
external DomHTMLScriptElement? get currentScript;
external DomElement createElementNS(
String namespaceURI, String qualifiedName);
external DomText createTextNode(String data);
}
@JS()
@@ -142,6 +147,7 @@ extension DomNodeExtension on DomNode {
external DomNode removeChild(DomNode child);
external bool? get isConnected;
external DomNode cloneNode(bool? deep);
}
@JS()
@@ -151,9 +157,11 @@ class DomElement extends DomNode {}
DomElement createDomElement(String tag) => domDocument.createElement(tag);
extension DomElementExtension on DomElement {
external /* List<DomElement> */ List<Object?> get children;
List<DomElement> get children =>
js_util.getProperty<List<Object?>>(this, 'children').cast<DomElement>();
external String get id;
external set id(String id);
external String? get outerHTML;
external set spellcheck(bool? value);
external String get tagName;
external DomCSSStyleDeclaration get style;
@@ -161,7 +169,12 @@ extension DomElementExtension on DomElement {
external String? getAttribute(String attributeName);
external void prepend(DomNode node);
external DomElement? querySelector(String selectors);
List<DomElement> querySelectorAll(String selectors) =>
js_util.callMethod<List<Object?>>(
this, 'querySelectorAll', <Object>[selectors]).cast<DomElement>();
external void remove();
external void setAttribute(String name, Object value);
void appendText(String text) => append(createDomText(text));
}
@JS()
@@ -187,6 +200,24 @@ extension DomCSSStyleDeclarationExtension on DomCSSStyleDeclaration {
setProperty('background-color', value, '');
set pointerEvents(String value) => setProperty('pointer-events', value, '');
set filter(String value) => setProperty('filter', value, '');
set zIndex(String value) => setProperty('z-index', value, '');
set whiteSpace(String value) => setProperty('white-space', value, '');
set lineHeight(String value) => setProperty('line-height', value, '');
set textStroke(String value) => setProperty('-webkit-text-stroke', value, '');
set fontSize(String value) => setProperty('font-size', value, '');
set fontWeight(String value) => setProperty('font-weight', value, '');
set fontStyle(String value) => setProperty('font-style', value, '');
set fontFamily(String value) => setProperty('font-family', value, '');
set letterSpacing(String value) => setProperty('letter-spacing', value, '');
set wordSpacing(String value) => setProperty('word-spacing', value, '');
set textShadow(String value) => setProperty('text-shadow', value, '');
set textDecoration(String value) => setProperty('text-decoration', value, '');
set textDecorationColor(String value) =>
setProperty('text-decoration-color', value, '');
set fontFeatureSettings(String value) =>
setProperty('font-feature-settings', value, '');
set fontVariationSettings(String value) =>
setProperty('font-variation-settings', value, '');
String get width => getPropertyValue('width');
String get height => getPropertyValue('height');
String get position => getPropertyValue('position');
@@ -203,6 +234,21 @@ extension DomCSSStyleDeclarationExtension on DomCSSStyleDeclaration {
String get backgroundColor => getPropertyValue('background-color');
String get pointerEvents => getPropertyValue('pointer-events');
String get filter => getPropertyValue('filter');
String get zIndex => getPropertyValue('z-index');
String get whiteSpace => getPropertyValue('white-space');
String get lineHeight => getPropertyValue('line-height');
String get textStroke => getPropertyValue('-webkit-text-stroke');
String get fontSize => getPropertyValue('font-size');
String get fontWeight => getPropertyValue('font-weight');
String get fontStyle => getPropertyValue('font-style');
String get fontFamily => getPropertyValue('font-family');
String get letterSpacing => getPropertyValue('letter-spacing');
String get wordSpacing => getPropertyValue('word-spacing');
String get textShadow => getPropertyValue('text-shadow');
String get textDecorationColor => getPropertyValue('text-decoration-color');
String get fontFeatureSettings => getPropertyValue('font-feature-settings');
String get fontVariationSettings =>
getPropertyValue('font-variation-settings');
external String getPropertyValue(String property);
void setProperty(String propertyName, String value, [String? priority]) {
@@ -318,14 +364,30 @@ class DomCanvasRenderingContext2D {}
extension DomCanvasRenderingContext2DExtension on DomCanvasRenderingContext2D {
external Object? get fillStyle;
external set fillStyle(Object? style);
external DomCanvasGradient createLinearGradient(num x0, num y0, num x1, num
y1);
external set font(String value);
external set lineWidth(num? value);
external set strokeStyle(Object? value);
external void beginPath();
external void closePath();
external DomCanvasGradient createLinearGradient(
num x0, num y0, num x1, num y1);
external DomCanvasPattern? createPattern(Object image, String reptitionType);
external DomCanvasGradient createRadialGradient(num x0, num y0, num r0, num
x1, num y1, num r1);
external DomCanvasGradient createRadialGradient(
num x0, num y0, num r0, num x1, num y1, num r1);
external void drawImage(DomCanvasImageSource source, num destX, num destY);
external void fill();
external void fillRect(num x, num y, num width, num height);
void fillText(String text, num x, num y, [num? maxWidth]) =>
js_util.callMethod(this, 'fillText',
<Object>[text, x, y, if (maxWidth != null) maxWidth]);
external DomImageData getImageData(int x, int y, int sw, int sh);
external void lineTo(num x, num y);
external void moveTo(num x, num y);
external void save();
external void stroke();
external void rect(num x, num y, num width, num height);
external void resetTransform();
external void restore();
}
@JS()
@@ -374,6 +436,16 @@ extension DomXMLHttpRequestExtension on DomXMLHttpRequest {
@staticInterop
class DomResponse {}
@JS()
@staticInterop
class DomCharacterData extends DomNode {}
@JS()
@staticInterop
class DomText extends DomCharacterData {}
DomText createDomText(String data) => domDocument.createTextNode(data);
@JS()
@staticInterop
class DomException {

View File

@@ -10,6 +10,7 @@ import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'dom.dart';
import 'html/painting.dart';
import 'html/render_vertices.dart';
import 'text/canvas_paragraph.dart';
@@ -257,18 +258,18 @@ mixin SaveStackTracking on EngineCanvas {
}
}
html.Element drawParagraphElement(
DomElement drawParagraphElement(
CanvasParagraph paragraph,
ui.Offset offset, {
Matrix4? transform,
}) {
assert(paragraph.isLaidOut);
final html.HtmlElement paragraphElement = paragraph.toDomElement();
final DomHTMLElement paragraphElement = paragraph.toDomElement();
if (transform != null) {
setElementTransform(
paragraphElement,
paragraphElement as html.Element,
transformWithOffset(transform, offset).storage,
);
}

View File

@@ -12,6 +12,7 @@ import '../browser_detection.dart';
import '../canvas_pool.dart';
import '../canvaskit/color_filter.dart';
import '../color_filter.dart';
import '../dom.dart';
import '../engine_canvas.dart';
import '../frame_reference.dart';
import '../html_image_codec.dart';
@@ -962,7 +963,7 @@ class BitmapCanvas extends EngineCanvas {
}
final html.Element paragraphElement =
drawParagraphElement(paragraph, offset);
drawParagraphElement(paragraph, offset) as html.Element;
if (_canvasPool.isClipped) {
final List<html.Element> clipElements = _clipContent(
_canvasPool.clipStack!,
@@ -1011,7 +1012,8 @@ class BitmapCanvas extends EngineCanvas {
'Linear/Radial/SweepGradient not supported yet');
final Int32List? colors = vertices.colors;
final ui.VertexMode mode = vertices.mode;
final html.CanvasRenderingContext2D ctx = _canvasPool.context;
final DomCanvasRenderingContext2D ctx = _canvasPool.context as
DomCanvasRenderingContext2D;
if (colors == null &&
paint.style != ui.PaintingStyle.fill &&
paint.shader == null) {

View File

@@ -128,7 +128,7 @@ class DomCanvas extends EngineCanvas with SaveElementStackTracking {
void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) {
final html.Element paragraphElement = drawParagraphElement(
paragraph as CanvasParagraph, offset,
transform: currentTransform);
transform: currentTransform) as html.Element;
currentElement.append(paragraphElement);
}

View File

@@ -9,6 +9,7 @@ import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../browser_detection.dart';
import '../dom.dart';
import '../safe_browser_api.dart';
import '../util.dart';
import '../vector_math.dart';
@@ -72,7 +73,7 @@ void initWebGl() {
abstract class GlRenderer {
void drawVertices(
html.CanvasRenderingContext2D? context,
DomCanvasRenderingContext2D? context,
int canvasWidthInPixels,
int canvasHeightInPixels,
Matrix4 transform,
@@ -91,7 +92,7 @@ abstract class GlRenderer {
int widthInPixels,
int heightInPixels);
void drawHairline(html.CanvasRenderingContext2D? _ctx, Float32List positions);
void drawHairline(DomCanvasRenderingContext2D? _ctx, Float32List positions);
}
/// Treeshakeable backend for rendering webgl on canvas.
@@ -101,7 +102,7 @@ abstract class GlRenderer {
class _WebGlRenderer implements GlRenderer {
@override
void drawVertices(
html.CanvasRenderingContext2D? context,
DomCanvasRenderingContext2D? context,
int canvasWidthInPixels,
int canvasHeightInPixels,
Matrix4 transform,
@@ -299,7 +300,7 @@ class _WebGlRenderer implements GlRenderer {
context!.save();
context.resetTransform();
gl.drawImage(context, offsetX, offsetY);
gl.drawImage(context as html.CanvasRenderingContext2D, offsetX, offsetY);
context.restore();
}
@@ -446,7 +447,7 @@ class _WebGlRenderer implements GlRenderer {
@override
void drawHairline(
html.CanvasRenderingContext2D? _ctx, Float32List positions) {
DomCanvasRenderingContext2D? _ctx, Float32List positions) {
assert(positions != null); // ignore: unnecessary_null_comparison
final int pointCount = positions.length ~/ 2;
_ctx!.lineWidth = 1.0;

View File

@@ -3,8 +3,8 @@
// found in the LICENSE file.
import 'dart:async';
import 'dart:html' as html;
import '../dom.dart';
import '../platform_dispatcher.dart';
import 'bitmap_canvas.dart';
import 'dom_canvas.dart';
@@ -94,10 +94,10 @@ class DebugSurfaceStats {
}
}
html.CanvasRenderingContext2D? _debugSurfaceStatsOverlayCtx;
DomCanvasRenderingContext2D? _debugSurfaceStatsOverlayCtx;
void debugRepaintSurfaceStatsOverlay(PersistedScene scene) {
final int overlayWidth = html.window.innerWidth!;
final int overlayWidth = domWindow.innerWidth!;
const int rowHeight = 30;
const int rowCount = 4;
const int overlayHeight = rowHeight * rowCount;
@@ -110,7 +110,7 @@ void debugRepaintSurfaceStatsOverlay(PersistedScene scene) {
}
if (_debugSurfaceStatsOverlayCtx == null) {
final html.CanvasElement _debugSurfaceStatsOverlay = html.CanvasElement(
final DomCanvasElement _debugSurfaceStatsOverlay = createDomCanvasElement(
width: overlayWidth,
height: overlayHeight,
);
@@ -121,7 +121,7 @@ void debugRepaintSurfaceStatsOverlay(PersistedScene scene) {
..zIndex = '1000'
..opacity = '0.8';
_debugSurfaceStatsOverlayCtx = _debugSurfaceStatsOverlay.context2D;
html.document.body!.append(_debugSurfaceStatsOverlay);
domDocument.body!.append(_debugSurfaceStatsOverlay);
}
_debugSurfaceStatsOverlayCtx!
@@ -131,9 +131,9 @@ void debugRepaintSurfaceStatsOverlay(PersistedScene scene) {
..fill();
final double physicalScreenWidth =
html.window.innerWidth! * EnginePlatformDispatcher.browserDevicePixelRatio;
domWindow.innerWidth! * EnginePlatformDispatcher.browserDevicePixelRatio;
final double physicalScreenHeight =
html.window.innerHeight! * EnginePlatformDispatcher.browserDevicePixelRatio;
domWindow.innerHeight! * EnginePlatformDispatcher.browserDevicePixelRatio;
final double physicsScreenPixelCount =
physicalScreenWidth * physicalScreenHeight;
@@ -291,20 +291,19 @@ void debugPrintSurfaceStats(PersistedScene scene, int frameNumber) {
// A microtask will fire after the DOM is flushed, letting us probe into
// actual <canvas> tags.
scheduleMicrotask(() {
final List<html.Element> canvasElements =
html.document.querySelectorAll('canvas');
final List<DomElement> canvasElements = domDocument.querySelectorAll('canvas');
final StringBuffer canvasInfo = StringBuffer();
final int pixelCount = canvasElements
.cast<html.CanvasElement>()
.map<int>((html.CanvasElement e) {
.cast<DomCanvasElement>()
.map<int>((DomCanvasElement e) {
final int pixels = e.width! * e.height!;
canvasInfo.writeln(' - ${e.width!} x ${e.height!} = $pixels pixels');
return pixels;
}).fold(0, (int total, int pixels) => total + pixels);
final double physicalScreenWidth =
html.window.innerWidth! * EnginePlatformDispatcher.browserDevicePixelRatio;
domWindow.innerWidth! * EnginePlatformDispatcher.browserDevicePixelRatio;
final double physicalScreenHeight =
html.window.innerHeight! * EnginePlatformDispatcher.browserDevicePixelRatio;
domWindow.innerHeight! * EnginePlatformDispatcher.browserDevicePixelRatio;
final double physicsScreenPixelCount =
physicalScreenWidth * physicalScreenHeight;
final double screenPixelRatio = pixelCount / physicsScreenPixelCount;

View File

@@ -2,10 +2,9 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:html' as html;
import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../embedder.dart';
import '../html/bitmap_canvas.dart';
import '../profiler.dart';
@@ -136,28 +135,28 @@ class CanvasParagraph implements ui.Paragraph {
/// Generates a flat string computed from all the spans of the paragraph.
String toPlainText() => plainText;
html.HtmlElement? _cachedDomElement;
DomHTMLElement? _cachedDomElement;
/// Returns a DOM element that represents the entire paragraph and its
/// children.
///
/// Generates a new DOM element on every invocation.
html.HtmlElement toDomElement() {
DomHTMLElement toDomElement() {
assert(isLaidOut);
final html.HtmlElement? domElement = _cachedDomElement;
final DomHTMLElement? domElement = _cachedDomElement;
if (domElement == null) {
return _cachedDomElement ??= _createDomElement();
}
return domElement.clone(true) as html.HtmlElement;
return domElement.cloneNode(true) as DomHTMLElement;
}
html.HtmlElement _createDomElement() {
final html.HtmlElement rootElement =
html.document.createElement('flt-paragraph') as html.HtmlElement;
DomHTMLElement _createDomElement() {
final DomHTMLElement rootElement =
domDocument.createElement('flt-paragraph') as DomHTMLElement;
// 1. Set paragraph-level styles.
final html.CssStyleDeclaration cssStyle = rootElement.style;
final DomCSSStyleDeclaration cssStyle = rootElement.style;
cssStyle
..position = 'absolute'
// Prevent the browser from doing any line breaks in the paragraph. We want
@@ -166,7 +165,7 @@ class CanvasParagraph implements ui.Paragraph {
// 2. Append all spans to the paragraph.
html.HtmlElement? lastSpanElement;
DomHTMLElement? lastSpanElement;
final List<EngineLineMetrics> lines = computeLineMetrics();
for (int i = 0; i < lines.length; i++) {
@@ -179,7 +178,8 @@ class CanvasParagraph implements ui.Paragraph {
final RangeBox box = boxes[j++];
if (box is SpanBox) {
lastSpanElement = html.document.createElement('flt-span') as html.HtmlElement;
lastSpanElement = domDocument.createElement('flt-span') as
DomHTMLElement;
applyTextStyleToElement(
element: lastSpanElement,
style: box.span.style,
@@ -257,7 +257,7 @@ class CanvasParagraph implements ui.Paragraph {
}
}
void _positionSpanElement(html.Element element, EngineLineMetrics line, RangeBox box) {
void _positionSpanElement(DomElement element, EngineLineMetrics line, RangeBox box) {
final ui.Rect boxRect = box.toTextBox(line, forPainting: true).toRect();
element.style
..position = 'absolute'

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 'dart:html' as html;
import 'dart:math' as math;
import 'package:ui/ui.dart' as ui;
@@ -674,14 +673,14 @@ String fontWeightIndexToCss({int fontWeightIndex = 3}) {
/// If [isSpan] is true, the text element is a span within richtext and
/// should not assign effectiveFontFamily if fontFamily was not specified.
void applyTextStyleToElement({
required html.HtmlElement element,
required DomHTMLElement element,
required EngineTextStyle style,
bool isSpan = false,
}) {
assert(element != null); // ignore: unnecessary_null_comparison
assert(style != null); // ignore: unnecessary_null_comparison
bool updateDecoration = false;
final html.CssStyleDeclaration cssStyle = element.style;
final DomCSSStyleDeclaration cssStyle = element.style;
final ui.Color? color = style.foreground?.color ?? style.color;
if (style.foreground?.style == ui.PaintingStyle.stroke) {
@@ -699,18 +698,18 @@ void applyTextStyleToElement({
: 1.0 / ui.window.devicePixelRatio;
cssStyle.textStroke = '${adaptedWidth}px ${colorToCssString(color)}';
} else if (color != null) {
cssStyle.color = colorToCssString(color);
cssStyle.color = colorToCssString(color)!;
}
final ui.Color? background = style.background?.color;
if (background != null) {
cssStyle.backgroundColor = colorToCssString(background);
cssStyle.backgroundColor = colorToCssString(background)!;
}
final double? fontSize = style.fontSize;
if (fontSize != null) {
cssStyle.fontSize = '${fontSize.floor()}px';
}
if (style.fontWeight != null) {
cssStyle.fontWeight = fontWeightToCss(style.fontWeight);
cssStyle.fontWeight = fontWeightToCss(style.fontWeight)!;
}
if (style.fontStyle != null) {
cssStyle.fontStyle =
@@ -719,9 +718,9 @@ void applyTextStyleToElement({
// For test environment use effectiveFontFamily since we need to
// consistently use Ahem font.
if (isSpan && !ui.debugEmulateFlutterTesterEnvironment) {
cssStyle.fontFamily = canonicalizeFontFamily(style.fontFamily);
cssStyle.fontFamily = canonicalizeFontFamily(style.fontFamily)!;
} else {
cssStyle.fontFamily = canonicalizeFontFamily(style.effectiveFontFamily);
cssStyle.fontFamily = canonicalizeFontFamily(style.effectiveFontFamily)!;
}
if (style.letterSpacing != null) {
cssStyle.letterSpacing = '${style.letterSpacing}px';
@@ -744,7 +743,7 @@ void applyTextStyleToElement({
if (textDecoration != null) {
if (browserEngine == BrowserEngine.webkit) {
setElementStyle(
element as DomElement, '-webkit-text-decoration', textDecoration);
element, '-webkit-text-decoration', textDecoration);
} else {
cssStyle.textDecoration = textDecoration;
}

View File

@@ -117,7 +117,7 @@ void testMain() {
// Emulate WebGL context loss.
final DomCanvasElement canvas =
surface.htmlElement.children.single! as DomCanvasElement;
surface.htmlElement.children.single as DomCanvasElement;
final dynamic ctx = canvas.getContext('webgl2');
expect(ctx, isNotNull);
final dynamic loseContextExtension =

View File

@@ -495,7 +495,7 @@ TextStyle styleWithDefaults({
}
void expectOuterHtml(CanvasParagraph paragraph, String expected, {required bool ignorePositions}) {
String outerHtml = paragraph.toDomElement().outerHtml!;
String outerHtml = paragraph.toDomElement().outerHTML!;
if (ignorePositions) {
outerHtml = removeMeasurementInfo(outerHtml);
expected = removeMeasurementInfo(expected);

View File

@@ -225,7 +225,7 @@ Future<void> testMain() async {
paragraph.layout(const ParagraphConstraints(width: 800.0));
expect(paragraph.plainText, 'abcdef');
final List<Element> spans =
paragraph.toDomElement().querySelectorAll('flt-span');
paragraph.toDomElement().querySelectorAll('flt-span').cast<Element>();
expect(spans[0].style.fontFamily, 'Ahem, $fallback, sans-serif');
// The nested span here should not set it's family to default sans-serif.
expect(spans[1].style.fontFamily, 'Ahem, $fallback, sans-serif');