Skip to content

Commit 9cb9f6b

Browse files
authored
[tool] Fix flutter.js regression with hot-reload on promise-based init. (#110805)
1 parent 822f6e3 commit 9cb9f6b

File tree

5 files changed

+217
-6
lines changed

5 files changed

+217
-6
lines changed

packages/flutter_tools/lib/src/web/file_generators/flutter_js.dart

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,8 @@ _flutter.loader = null;
205205
this._didCreateEngineInitializerResolve(engineInitializer);
206206
// Remove the resolver after the first time, so Flutter Web can hot restart.
207207
this._didCreateEngineInitializerResolve = null;
208+
// Make the engine revert to "auto" initialization on hot restart.
209+
delete _flutter.loader.didCreateEngineInitializer;
208210
}
209211
if (typeof this._onEntrypointLoaded === "function") {
210212
this._onEntrypointLoaded(engineInitializer);

packages/flutter_tools/test/integration.shard/test_data/hot_reload_project.dart

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import '../test_utils.dart';
66
import 'project.dart';
77

88
class HotReloadProject extends Project {
9+
HotReloadProject({super.indexHtml});
10+
911
@override
1012
final String pubspec = '''
1113
name: test

packages/flutter_tools/test/integration.shard/test_data/project.dart

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// found in the LICENSE file.
44

55
import 'package:file/file.dart';
6+
import 'package:flutter_tools/src/web/file_generators/flutter_js.dart';
67

78
import '../test_utils.dart';
89
import 'deferred_components_config.dart';
@@ -19,6 +20,11 @@ const String _kDefaultHtml = '''
1920
''';
2021

2122
abstract class Project {
23+
/// Creates a flutter Project for testing.
24+
///
25+
/// If passed, `indexHtml` is used as the contents of the web/index.html file.
26+
Project({this.indexHtml = _kDefaultHtml});
27+
2228
late Directory dir;
2329

2430
String get pubspec;
@@ -29,6 +35,13 @@ abstract class Project {
2935

3036
Uri get mainDart => Uri.parse('package:test/main.dart');
3137

38+
/// The contents for the index.html file of this `Project`.
39+
///
40+
/// Defaults to [_kDefaultHtml] via the Project constructor.
41+
///
42+
/// (Used by [HotReloadProject].)
43+
final String indexHtml;
44+
3245
Future<void> setUpIn(Directory dir) async {
3346
this.dir = dir;
3447
writeFile(fileSystem.path.join(dir.path, 'pubspec.yaml'), pubspec);
@@ -45,7 +58,11 @@ abstract class Project {
4558
writeFile(fileSystem.path.join(dir.path, '.dart_tool', 'flutter_gen', 'flutter_gen.dart'), generatedFile);
4659
}
4760
deferredComponents?.setUpIn(dir);
48-
writeFile(fileSystem.path.join(dir.path, 'web', 'index.html'), _kDefaultHtml);
61+
62+
// Setup for different flutter web initializations
63+
writeFile(fileSystem.path.join(dir.path, 'web', 'index.html'), indexHtml);
64+
writeFile(fileSystem.path.join(dir.path, 'web', 'flutter.js'), generateFlutterJsFile());
65+
writeFile(fileSystem.path.join(dir.path, 'web', 'flutter_service_worker.js'), '');
4966
writePackages(dir.path);
5067
await getPackages(dir.path);
5168
}

packages/flutter_tools/test/web.shard/hot_reload_web_test.dart

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,22 @@ import '../integration.shard/test_driver.dart';
1111
import '../integration.shard/test_utils.dart';
1212
import '../src/common.dart';
1313

14-
void main() {
14+
import 'test_data/hot_reload_index_html_samples.dart';
15+
16+
void main() async {
17+
await _testProject(HotReloadProject()); // default
18+
await _testProject(HotReloadProject(indexHtml: indexHtmlFlutterJsCallback), name: 'flutter.js (callback)');
19+
await _testProject(HotReloadProject(indexHtml: indexHtmlFlutterJsPromisesFull), name: 'flutter.js (promises)');
20+
await _testProject(HotReloadProject(indexHtml: indexHtmlFlutterJsPromisesShort), name: 'flutter.js (promises, short)');
21+
await _testProject(HotReloadProject(indexHtml: indexHtmlNoFlutterJs), name: 'No flutter.js');
22+
}
23+
24+
Future<void> _testProject(HotReloadProject project, {String name = 'Default'}) async {
1525
late Directory tempDir;
16-
final HotReloadProject project = HotReloadProject();
1726
late FlutterRunTestDriver flutter;
1827

28+
final String testName = 'Hot reload (index.html: $name)';
29+
1930
setUp(() async {
2031
tempDir = createResolvedTempDirectorySync('hot_reload_test.');
2132
await project.setUpIn(tempDir);
@@ -28,12 +39,12 @@ void main() {
2839
tryToDelete(tempDir);
2940
});
3041

31-
testWithoutContext('hot restart works without error', () async {
42+
testWithoutContext('$testName: hot restart works without error', () async {
3243
await flutter.run(chrome: true, additionalCommandArgs: <String>['--verbose', '--web-renderer=html']);
3344
await flutter.hotRestart();
3445
});
3546

36-
testWithoutContext('newly added code executes during hot restart', () async {
47+
testWithoutContext('$testName: newly added code executes during hot restart', () async {
3748
final Completer<void> completer = Completer<void>();
3849
final StreamSubscription<String> subscription = flutter.stdout.listen((String line) {
3950
if (line.contains('(((((RELOAD WORKED)))))')) {
@@ -50,7 +61,7 @@ void main() {
5061
}
5162
});
5263

53-
testWithoutContext('newly added code executes during hot restart - canvaskit', () async {
64+
testWithoutContext('$testName: newly added code executes during hot restart - canvaskit', () async {
5465
final Completer<void> completer = Completer<void>();
5566
final StreamSubscription<String> subscription = flutter.stdout.listen((String line) {
5667
if (line.contains('(((((RELOAD WORKED)))))')) {
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
// This file contains a bunch of different index.html "styles" that can be written
6+
// by Flutter Web users.
7+
// This should be somewhat kept in sync with the different index.html files present
8+
// in `flutter/dev/integration_tests/web/web`.
9+
// @see https://github.com/flutter/flutter/tree/master/dev/integration_tests/web/web
10+
11+
/// index_with_flutterjs_entrypoint_loaded.html
12+
String indexHtmlFlutterJsCallback = _generateFlutterJsIndexHtml('''
13+
window.addEventListener('load', function(ev) {
14+
// Download main.dart.js
15+
_flutter.loader.loadEntrypoint({
16+
onEntrypointLoaded: onEntrypointLoaded,
17+
serviceWorker: {
18+
serviceWorkerVersion: serviceWorkerVersion,
19+
}
20+
});
21+
// Once the entrypoint is ready, do things!
22+
async function onEntrypointLoaded(engineInitializer) {
23+
const appRunner = await engineInitializer.initializeEngine();
24+
appRunner.runApp();
25+
}
26+
});
27+
''');
28+
29+
/// index_with_flutterjs_short.html
30+
String indexHtmlFlutterJsPromisesShort = _generateFlutterJsIndexHtml('''
31+
window.addEventListener('load', function(ev) {
32+
// Download main.dart.js
33+
_flutter.loader.loadEntrypoint({
34+
serviceWorker: {
35+
serviceWorkerVersion: serviceWorkerVersion,
36+
}
37+
}).then(function(engineInitializer) {
38+
return engineInitializer.autoStart();
39+
});
40+
});
41+
''');
42+
43+
/// index_with_flutterjs.html
44+
String indexHtmlFlutterJsPromisesFull = _generateFlutterJsIndexHtml('''
45+
window.addEventListener('load', function(ev) {
46+
// Download main.dart.js
47+
_flutter.loader.loadEntrypoint({
48+
serviceWorker: {
49+
serviceWorkerVersion: serviceWorkerVersion,
50+
}
51+
}).then(function(engineInitializer) {
52+
return engineInitializer.initializeEngine();
53+
}).then(function(appRunner) {
54+
return appRunner.runApp();
55+
});
56+
});
57+
''');
58+
59+
/// index_without_flutterjs.html
60+
String indexHtmlNoFlutterJs = '''
61+
<!DOCTYPE HTML>
62+
<!-- Copyright 2014 The Flutter Authors. All rights reserved.
63+
Use of this source code is governed by a BSD-style license that can be
64+
found in the LICENSE file. -->
65+
<html>
66+
<head>
67+
<meta charset="UTF-8">
68+
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
69+
70+
<title>Web Test</title>
71+
<!-- iOS meta tags & icons -->
72+
<meta name="apple-mobile-web-app-capable" content="yes">
73+
<meta name="apple-mobile-web-app-status-bar-style" content="black">
74+
<meta name="apple-mobile-web-app-title" content="Web Test">
75+
<link rel="manifest" href="manifest.json">
76+
</head>
77+
<body>
78+
<!-- This script installs service_worker.js to provide PWA functionality to
79+
application. For more information, see:
80+
https://developers.google.com/web/fundamentals/primers/service-workers -->
81+
<script>
82+
var serviceWorkerVersion = null;
83+
var scriptLoaded = false;
84+
function loadMainDartJs() {
85+
if (scriptLoaded) {
86+
return;
87+
}
88+
scriptLoaded = true;
89+
var scriptTag = document.createElement('script');
90+
scriptTag.src = 'main.dart.js';
91+
scriptTag.type = 'application/javascript';
92+
document.body.append(scriptTag);
93+
}
94+
95+
if ('serviceWorker' in navigator) {
96+
// Service workers are supported. Use them.
97+
window.addEventListener('load', function () {
98+
// Wait for registration to finish before dropping the <script> tag.
99+
// Otherwise, the browser will load the script multiple times,
100+
// potentially different versions.
101+
var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
102+
navigator.serviceWorker.register(serviceWorkerUrl)
103+
.then((reg) => {
104+
function waitForActivation(serviceWorker) {
105+
serviceWorker.addEventListener('statechange', () => {
106+
if (serviceWorker.state == 'activated') {
107+
console.log('Installed new service worker.');
108+
loadMainDartJs();
109+
}
110+
});
111+
}
112+
if (!reg.active && (reg.installing || reg.waiting)) {
113+
// No active web worker and we have installed or are installing
114+
// one for the first time. Simply wait for it to activate.
115+
waitForActivation(reg.installing ?? reg.waiting);
116+
} else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
117+
// When the app updates the serviceWorkerVersion changes, so we
118+
// need to ask the service worker to update.
119+
console.log('New service worker available.');
120+
reg.update();
121+
waitForActivation(reg.installing);
122+
} else {
123+
// Existing service worker is still good.
124+
console.log('Loading app from service worker.');
125+
loadMainDartJs();
126+
}
127+
});
128+
129+
// If service worker doesn't succeed in a reasonable amount of time,
130+
// fallback to plaint <script> tag.
131+
setTimeout(() => {
132+
if (!scriptLoaded) {
133+
console.warn(
134+
'Failed to load app from service worker. Falling back to plain <script> tag.',
135+
);
136+
loadMainDartJs();
137+
}
138+
}, 4000);
139+
});
140+
} else {
141+
// Service workers not supported. Just drop the <script> tag.
142+
loadMainDartJs();
143+
}
144+
</script>
145+
</body>
146+
</html>
147+
''';
148+
149+
// Generates the scaffolding of an index.html file, with a configurable `initScript`.
150+
String _generateFlutterJsIndexHtml(String initScript) => '''
151+
<!DOCTYPE HTML>
152+
<!-- Copyright 2014 The Flutter Authors. All rights reserved.
153+
Use of this source code is governed by a BSD-style license that can be
154+
found in the LICENSE file. -->
155+
<html>
156+
<head>
157+
<meta charset="UTF-8">
158+
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
159+
160+
<title>Integration test. App load with flutter.js and onEntrypointLoaded API</title>
161+
<!-- iOS meta tags & icons -->
162+
<meta name="apple-mobile-web-app-capable" content="yes">
163+
<meta name="apple-mobile-web-app-status-bar-style" content="black">
164+
<meta name="apple-mobile-web-app-title" content="Web Test">
165+
<link rel="manifest" href="manifest.json">
166+
<script>
167+
// The value below is injected by flutter build, do not touch.
168+
var serviceWorkerVersion = null;
169+
</script>
170+
<!-- This script adds the flutter initialization JS code -->
171+
<script src="flutter.js" defer></script>
172+
</head>
173+
<body>
174+
<script>
175+
$initScript
176+
</script>
177+
</body>
178+
</html>
179+
''';

0 commit comments

Comments
 (0)