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

This commit is contained in:
joshualitt
2022-05-09 08:25:12 -07:00
committed by GitHub
parent 419f786227
commit 727d4bba71
10 changed files with 111 additions and 38 deletions

View File

@@ -1089,6 +1089,7 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/services/message_codec.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/services/message_codecs.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/services/serialization.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/shadow.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/svg.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/test_embedding.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/canvas_paragraph.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/font_collection.dart

View File

@@ -138,6 +138,7 @@ export 'engine/services/message_codec.dart';
export 'engine/services/message_codecs.dart';
export 'engine/services/serialization.dart';
export 'engine/shadow.dart';
export 'engine/svg.dart';
export 'engine/test_embedding.dart';
export 'engine/text/canvas_paragraph.dart';
export 'engine/text/font_collection.dart';

View File

@@ -2,9 +2,7 @@
// 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 'dart:svg' as svg;
import 'package:ui/ui.dart' as ui;
@@ -13,6 +11,7 @@ import '../configuration.dart';
import '../dom.dart';
import '../html/path_to_svg_clip.dart';
import '../platform_views/slots.dart';
import '../svg.dart';
import '../util.dart';
import '../vector_math.dart';
import '../window.dart';
@@ -293,16 +292,16 @@ class HtmlViewEmbedder {
/// be recomposited.
void _cleanUpClipDefs(int viewId) {
if (_svgClipDefs.containsKey(viewId)) {
final html.Element clipDefs =
final DomElement clipDefs =
_svgPathDefs!.querySelector('#sk_path_defs')!;
final List<html.Element> nodesToRemove = <html.Element>[];
final List<DomElement> nodesToRemove = <DomElement>[];
final Set<String> oldDefs = _svgClipDefs[viewId]!;
for (final html.Element child in clipDefs.children) {
for (final DomElement child in clipDefs.children.cast<DomElement>()) {
if (oldDefs.contains(child.id)) {
nodesToRemove.add(child);
}
}
for (final html.Element node in nodesToRemove) {
for (final DomElement node in nodesToRemove) {
node.remove();
}
_svgClipDefs[viewId]!.clear();
@@ -343,14 +342,14 @@ class HtmlViewEmbedder {
final CkPath path = CkPath();
path.addRRect(mutator.rrect!);
_ensureSvgPathDefs();
final html.Element pathDefs =
final DomElement pathDefs =
_svgPathDefs!.querySelector('#sk_path_defs')!;
_clipPathCount += 1;
final String clipId = 'svgClip$_clipPathCount';
final svg.ClipPathElement newClipPath = svg.ClipPathElement();
final SVGClipPathElement newClipPath = createSVGClipPathElement();
newClipPath.id = clipId;
newClipPath.append(
svg.PathElement()
createSVGPathElement()
..setAttribute('d', path.toSvgString()!));
pathDefs.append(newClipPath);
@@ -362,14 +361,14 @@ class HtmlViewEmbedder {
} else if (mutator.path != null) {
final CkPath path = mutator.path! as CkPath;
_ensureSvgPathDefs();
final html.Element pathDefs =
final DomElement pathDefs =
_svgPathDefs!.querySelector('#sk_path_defs')!;
_clipPathCount += 1;
final String clipId = 'svgClip$_clipPathCount';
final svg.ClipPathElement newClipPath = svg.ClipPathElement();
final SVGClipPathElement newClipPath = createSVGClipPathElement();
newClipPath.id = clipId;
newClipPath.append(
svg.PathElement()
createSVGPathElement()
..setAttribute('d', path.toSvgString()!));
pathDefs.append(newClipPath);
// Store the id of the node instead of [newClipPath] directly. For
@@ -413,7 +412,7 @@ class HtmlViewEmbedder {
int _clipPathCount = 0;
html.Element? _svgPathDefs;
DomElement? _svgPathDefs;
/// The nodes containing the SVG clip definitions needed to clip this view.
Map<int, Set<String>> _svgClipDefs = <int, Set<String>>{};
@@ -424,9 +423,9 @@ class HtmlViewEmbedder {
if (_svgPathDefs != null) {
return;
}
_svgPathDefs = kSvgResourceHeader.clone(false) as svg.SvgSvgElement;
_svgPathDefs!.append(svg.DefsElement()..id = 'sk_path_defs');
skiaSceneHost!.append(_svgPathDefs! as DomElement);
_svgPathDefs = kSvgResourceHeader.clone(false) as SVGElement;
_svgPathDefs!.append(createSVGDefsElement()..id = 'sk_path_defs');
skiaSceneHost!.append(_svgPathDefs!);
}
void submitFrame() {
@@ -733,11 +732,12 @@ class HtmlViewEmbedder {
/// Deletes SVG clip paths, useful for tests.
void debugCleanupSvgClipPaths() {
_svgPathDefs?.children.single.children.forEach(removeElement);
_svgPathDefs?.children.cast<DomElement>().single
.children.cast<DomElement>().forEach(removeElement);
_svgClipDefs.clear();
}
static void removeElement(html.Element element) {
static void removeElement(DomElement element) {
element.remove();
}

View File

@@ -4,11 +4,11 @@
import 'dart:async';
import 'dart:convert';
import 'dart:html' as html;
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../font_change_util.dart';
import '../platform_dispatcher.dart';
import '../util.dart';
@@ -487,7 +487,7 @@ Set<NotoFont> findMinimumFontsForCodeUnits(
final Set<NotoFont> minimumFonts = <NotoFont>{};
final List<NotoFont> bestFonts = <NotoFont>[];
final String language = html.window.navigator.language;
final String language = domWindow.navigator.language;
while (codeUnits.isNotEmpty) {
int maxCodeUnitsCovered = 0;
@@ -970,7 +970,7 @@ class NotoDownloader {
_debugActiveDownloadCount += 1;
}
final Future<ByteBuffer> result = httpFetch(url).then(
(html.Body fetchResult) => fetchResult
(DomResponse fetchResult) => fetchResult
.arrayBuffer()
.then<ByteBuffer>((dynamic x) => x as ByteBuffer));
if (assertionsEnabled) {
@@ -989,7 +989,7 @@ class NotoDownloader {
_debugActiveDownloadCount += 1;
}
final Future<String> result = httpFetch(url).then(
(html.Body response) =>
(DomResponse response) =>
response.text().then<String>((dynamic x) => x as String));
if (assertionsEnabled) {
result.whenComplete(() {

View File

@@ -3,10 +3,10 @@
// found in the LICENSE file.
import 'dart:convert';
import 'dart:html' as html;
import 'dart:typed_data';
import '../assets.dart';
import '../dom.dart';
import '../util.dart';
import 'canvaskit_api.dart';
import 'font_fallbacks.dart';
@@ -210,7 +210,7 @@ class SkiaFontCollection {
return actualFamily;
}
Future<ByteBuffer> _getArrayBuffer(html.Body fetchResult) {
Future<ByteBuffer> _getArrayBuffer(DomResponse fetchResult) {
return fetchResult
.arrayBuffer()
.then<ByteBuffer>((dynamic x) => x as ByteBuffer);

View File

@@ -22,6 +22,8 @@ extension DomWindowExtension on DomWindow {
external DomDocument get document;
external DomNavigator get navigator;
external DomPerformance get performance;
Future<Object?> fetch(String url) =>
js_util.promiseToFuture(js_util.callMethod(this, 'fetch', <String>[url]));
}
@JS('window')
@@ -34,6 +36,7 @@ class DomNavigator {}
extension DomNavigatorExtension on DomNavigator {
external int? get maxTouchPoints;
external String get vendor;
external String get language;
external String? get platform;
external String get userAgent;
}
@@ -46,6 +49,8 @@ extension DomDocumentExtension on DomDocument {
external /* List<Node> */ List<Object?> querySelectorAll(String selectors);
external DomElement createElement(String name, [dynamic options]);
external DomHTMLScriptElement? get currentScript;
external DomElement createElementNS(
String namespaceURI, String qualifiedName);
}
@JS()
@@ -54,6 +59,7 @@ class DomHTMLDocument extends DomDocument {}
extension DomHTMLDocumentExtension on DomHTMLDocument {
external DomHTMLHeadElement? get head;
external DomHTMLBodyElement? get body;
}
@JS('document')
@@ -97,6 +103,7 @@ extension DomNodeExtension on DomNode {
parent.removeChild(this);
}
}
external DomNode removeChild(DomNode child);
external bool? get isConnected;
}
@@ -105,14 +112,17 @@ extension DomNodeExtension on DomNode {
@staticInterop
class DomElement extends DomNode {}
DomElement createDomElement(String tag) =>
domDocument.createElement(tag);
DomElement createDomElement(String tag) => domDocument.createElement(tag);
extension DomElementExtension on DomElement {
external /* List<DomElement> */ List<Object?> get children;
external String get id;
external set id(String id);
external DomCSSStyleDeclaration get style;
external void append(DomNode node);
external String? getAttribute(String attributeName);
external void prepend(DomNode node);
external DomElement? querySelector(String selectors);
external void setAttribute(String name, Object value);
}
@@ -139,8 +149,8 @@ extension DomCSSStyleDeclarationExtension on DomCSSStyleDeclaration {
String get opacity => getPropertyValue('opacity');
external String getPropertyValue(String property);
external void setProperty(String propertyName, String value, [String
priority]);
external void setProperty(String propertyName, String value,
[String priority]);
}
@JS()
@@ -161,6 +171,10 @@ extension DomHTMLMetaElementExtension on DomHTMLMetaElement {
@staticInterop
class DomHTMLHeadElement extends DomHTMLElement {}
@JS()
@staticInterop
class DomHTMLBodyElement extends DomHTMLElement {}
@JS()
@staticInterop
class DomHTMLScriptElement extends DomHTMLElement {}
@@ -220,6 +234,21 @@ extension DomCanvasElementExtension on DomCanvasElement {
}
}
@JS()
@staticInterop
class DomResponse {}
extension DomResponseExtension on DomResponse {
Future<dynamic> arrayBuffer() =>
js_util.promiseToFuture(js_util.callMethod(this, 'arrayBuffer', <Object>[]));
Future<dynamic> json() =>
js_util.promiseToFuture(js_util.callMethod(this, 'json', <Object>[]));
Future<String> text() =>
js_util.promiseToFuture(js_util.callMethod(this, 'text', <Object>[]));
}
Object? domGetConstructor(String constructorName) =>
js_util.getProperty(domWindow, constructorName);

View File

@@ -0,0 +1,43 @@
// 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.
import 'package:js/js.dart';
import 'dom.dart';
@JS()
@staticInterop
class SVGElement extends DomElement {}
@JS()
@staticInterop
class SVGGraphicsElement extends SVGElement {}
@JS()
@staticInterop
class SVGClipPathElement extends SVGGraphicsElement {}
SVGClipPathElement createSVGClipPathElement() =>
domDocument.createElementNS('http://www.w3.org/2000/svg', 'clipPath')
as SVGClipPathElement;
@JS()
@staticInterop
class SVGDefsElement extends SVGGraphicsElement {}
SVGDefsElement createSVGDefsElement() =>
domDocument.createElementNS('http://www.w3.org/2000/svg', 'defs')
as SVGDefsElement;
@JS()
@staticInterop
class SVGGeometryElement extends SVGGraphicsElement {}
@JS()
@staticInterop
class SVGPathElement extends SVGGeometryElement {}
SVGPathElement createSVGPathElement() =>
domDocument.createElementNS('http://www.w3.org/2000/svg', 'path')
as SVGPathElement;

View File

@@ -12,6 +12,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 'vector_math.dart';
@@ -558,9 +559,9 @@ bool unsafeIsNull(dynamic object) {
}
/// A typed variant of [html.Window.fetch].
Future<html.Body> httpFetch(String url) async {
final dynamic result = await html.window.fetch(url);
return result as html.Body;
Future<DomResponse> httpFetch(String url) async {
final Object? result = await html.window.fetch(url);
return result! as DomResponse;
}
/// Extensions to [Map] that make it easier to treat it as a JSON object. The

View File

@@ -450,7 +450,7 @@ void _testForImageCodecs({required bool useBrowserImageDecoder}) {
});
test('Decode test images', () async {
final html.Body listingResponse = await httpFetch('/test_images/');
final DomResponse listingResponse = await httpFetch('/test_images/');
final List<String> testFiles = (await listingResponse.json() as List<dynamic>).cast<String>();
// Sanity-check the test file list. If suddenly test files are moved or
@@ -464,7 +464,7 @@ void _testForImageCodecs({required bool useBrowserImageDecoder}) {
expect(testFiles, contains(matches(RegExp(r'.*\.bmp'))));
for (final String testFile in testFiles) {
final html.Body imageResponse = await httpFetch('/test_images/$testFile');
final DomResponse imageResponse = await httpFetch('/test_images/$testFile');
final Uint8List imageData = (await imageResponse.arrayBuffer() as ByteBuffer).asUint8List();
final ui.Codec codec = await skiaInstantiateImageCodec(imageData);
expect(codec.frameCount, greaterThan(0));
@@ -480,7 +480,7 @@ void _testForImageCodecs({required bool useBrowserImageDecoder}) {
// Reproduces https://skbug.com/12721
test('decoded image can be read back from picture', () async {
final html.Body imageResponse = await httpFetch('/test_images/mandrill_128.png');
final DomResponse imageResponse = await httpFetch('/test_images/mandrill_128.png');
final Uint8List imageData = (await imageResponse.arrayBuffer() as ByteBuffer).asUint8List();
final ui.Codec codec = await skiaInstantiateImageCodec(imageData);
final ui.FrameInfo frame = await codec.getNextFrame();

View File

@@ -2,8 +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 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
@@ -20,9 +18,9 @@ void testMain() {
test('populates flt-renderer and flt-build-mode', () {
FlutterViewEmbedder();
expect(html.document.body!.attributes['flt-renderer'],
expect(domDocument.body!.getAttribute('flt-renderer'),
'canvaskit (requested explicitly)');
expect(html.document.body!.attributes['flt-build-mode'], 'debug');
expect(domDocument.body!.getAttribute('flt-build-mode'), 'debug');
});
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
}, skip: isIosSafari);