Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[service worker] start work on service worker util package #150

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/flutter_service_worker/CHANGELOG.md
@@ -0,0 +1,3 @@
## 0.0.1

* Initial release.
28 changes: 28 additions & 0 deletions packages/flutter_service_worker/LICENSE
@@ -0,0 +1,28 @@
Copyright 2020 The Chromium Authors. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
67 changes: 67 additions & 0 deletions packages/flutter_service_worker/README.md
@@ -0,0 +1,67 @@
## Flutter Service Worker

A collection of utility APIs for interacting with the Flutter service worker.


### Setup

The `init` method should be called in main to bootstrap the service worker API. This is safe
to call on non-web platforms.

```dart
void main() {
serviceWorkerApi.init();
runApp(MyApp());
}
```


### Detecting a new version

A service worker will cache the old application until the new application is downloaded and ready. To be notified when this occurs, listen to the `newVersionReady` future. You can then use `skipWaiting()` to
force-load the new version.

```dart

serviceWorkerApi.newVersionReady.whenComplete(() {
showNewVersionDialog().then((bool yes) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is this function?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

showNewVersionDialog() is an example function that you might implement with showDialog or some other flutter functionality. I will fill out these examples more so they reference only working flutter code

if (yes) {
serviceWorkerApi.skipWaiting();
}
})
});

```

### Prompting for user install

Some browsers allow displaying a notification to install the web application to home screens or start menus. This can be done by waiting for `installPromptReady` to resolve. Once this is done, `showInstallPrompt()` can be called in response to user input, which will display a prompt.

```dart
serviceWorkerApi.installPromptReady.whenComplete(() {
showVersionInstallDialog().then((bool yes) {
if (yes) {
serviceWorkerApi.showInstallPrompt();
}
});
})

```


### Offline cache

By default, the Flutter service worker will cache an only the application shell upfront, other resources are cached on-demand. The `downloadOffline` method will force the service worker to eagerly cache all resources to
prepare the application for offline support.


```dart
MaterialButton(
child: Text('DOWNLOAD OFFLINE'),
onPressed: () async {
serviceWorkerApi.downloadOffline().whenComplete(() {
showOfflineDownloadComplete();
});
}
)
```
64 changes: 64 additions & 0 deletions packages/flutter_service_worker/lib/flutter_service_worker.dart
@@ -0,0 +1,64 @@
// Copyright 2020 The Chromium 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 'src/_io_impl.dart' if (dart.library.js) 'src/_web_impl.dart';

/// An API for interacting with the service worker for application caching and
/// installation.
///
/// On platforms other than the web, this delegates to a no-op implementation.
///
/// See also:
///
/// * https://web.dev/customize-install/
abstract class ServiceWorkerApi {
/// Initialize the service worker API.
///
/// This method should be called immediately in main, before calling
/// [runApp].
void init();

/// A future that resolves when it is safe to call [showInstallPrompt].
///
/// If the application is not compatible with a service worker installation,
/// for example by running on http instead of https, then this future
/// will never resolve.
///
/// This installation prompt event is currently only supported on Chrome.
/// On other browsers this future will never resolve.
///
/// Not all browsers
Future<void> get installPromptReady;

/// Trigger a prompt that allows users to install their application to the
/// device/home screen location.
///
/// Returns a boolean that indicates whether the installation prompt was
/// accepted.
///
/// This installation prompt event is currently only supported on Chrome.
/// On other browsers [installPromptReady] will never resolve.
///
/// Throws a [StateError] if this function is called before [installPromptReady]
/// resolves, or if it is not called in response to a user initiated gesture.
Future<bool> showInstallPrompt();

/// A future that resolves when a new version of the application is ready.
Future<void> get newVersionReady;

/// If a new version is available, skip a waiting period and force the browser
/// to reload.
///
/// This operation is disruptive and should only be called if there are no
/// other user activities or in response to a prompt.
Future<void> skipWaiting();

/// For the service worker to cache all resources files for offline use.
Future<void> downloadOffline();
}

/// The singleton [ServiceWorkerApi] instance.
ServiceWorkerApi get serviceWorkerApi =>
_serviceWorkerApi ??= ServiceWorkerImpl();
ServiceWorkerApi _serviceWorkerApi;
35 changes: 35 additions & 0 deletions packages/flutter_service_worker/lib/src/_io_impl.dart
@@ -0,0 +1,35 @@
// Copyright 2020 The Chromium 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 'dart:async';

import '../flutter_service_worker.dart';

/// An unsupported implementation of the [ServiceWorkerApi] for non-web
/// platforms.
class ServiceWorkerImpl extends ServiceWorkerApi {
@override
Future<void> get installPromptReady => Completer<void>().future;

@override
void init() {}

@override
Future<bool> showInstallPrompt() {
throw UnsupportedError('showInstallPrompt is only supported on the web.');
}

@override
Future<void> get newVersionReady => Completer<void>().future;

@override
Future<void> skipWaiting() {
throw UnsupportedError('skipWaiting is only supported on the web.');
}

@override
Future<void> downloadOffline() {
throw UnsupportedError('downloadOffline is only supported on the web.');
}
}
109 changes: 109 additions & 0 deletions packages/flutter_service_worker/lib/src/_web_impl.dart
@@ -0,0 +1,109 @@
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

library _web_impl;

import 'dart:async';
import 'dart:html';
import 'dart:js';
import 'dart:js_util';

import '../flutter_service_worker.dart';

/// An implementation of the [ServiceWorkerApi] that delegates to the JS Window
/// object.
class ServiceWorkerImpl extends ServiceWorkerApi {
@override
void init() {
window.addEventListener('beforeinstallprompt', allowInterop((Object event) {
if (_installPromptReady.isCompleted) {
return;
}
_installPrompt = JsObject.fromBrowserObject(event)
..callMethod('preventDefault');
_installPromptReady.complete();
}));
window.navigator.serviceWorker.ready
.then((ServiceWorkerRegistration registration) {
if (registration.waiting != null) {
if (!_installPromptReady.isCompleted) {
_newVersionReady.complete();
}
}
if (registration.installing != null) {
_handleInstall(registration.installing);
}
registration.addEventListener('updatefound', (_) {
_handleInstall(registration.installing);
});
});
}

void _handleInstall(ServiceWorker serviceWorker) {
serviceWorker.addEventListener('statechange', (_) {
if (serviceWorker.state == 'installed') {
if (!_installPromptReady.isCompleted) {
_installPromptReady.complete();
}
}
});
}

final Completer<void> _installPromptReady = Completer<void>();
final Completer<void> _newVersionReady = Completer<void>();
JsObject _installPrompt;

@override
Future<void> get installPromptReady => _installPromptReady.future;

@override
Future<bool> showInstallPrompt() async {
assert(_installPrompt != null,
'The installation future needs to resolve before acceptInstallPrompt can be called');
if (_installPrompt == null) {
throw StateError('missing installPrompt');
}
try {
await promiseToFuture<void>(_installPrompt.callMethod('prompt'));
} catch (err) {
throw StateError(err.toString());
}
final String result =
await promiseToFuture(getProperty(_installPrompt, 'userChoice'));
return result == 'accepted';
}

@override
Future<void> get newVersionReady => _newVersionReady.future;

@override
Future<void> skipWaiting() async {
final ServiceWorkerRegistration registration =
await window.navigator.serviceWorker.ready;
bool refreshing = false;
registration.active.addEventListener('controllerchange', (_) {
if (refreshing) {
return;
}
refreshing = true;
window.location.reload();
});
registration.active.postMessage('skipWaiting');
}

@override
Future<void> downloadOffline() async {
final ServiceWorkerRegistration registration =
await window.navigator.serviceWorker.ready;
final Completer<void> completer = Completer<void>();
registration.active.addEventListener('message', (Event event) {
if (completer.isCompleted) {
return;
}
completer.complete();
});
registration.active.postMessage('downloadOffline');
await completer.future;
}
}
16 changes: 16 additions & 0 deletions packages/flutter_service_worker/pubspec.yaml
@@ -0,0 +1,16 @@
name: flutter_service_worker
description: Flutter package for integrating with the web Service Worker
homepage: https://github.com/flutter/packages/tree/master/packages/flutter_service_worker
version: 0.0.1
authors:
- Jonah Williams <jonahwilliams@google.com>

environment:
# The pub client defaults to an <2.0.0 sdk constraint which we need to explicitly overwrite.
sdk: ">=2.8.0 <3.0.0"

dependencies:
meta: 1.1.8

dev_dependencies:
test: 1.14.3
18 changes: 18 additions & 0 deletions packages/flutter_service_worker/test/web_test.dart
@@ -0,0 +1,18 @@
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

@TestOn('chrome')
import 'package:test/test.dart';
import 'package:flutter_service_worker/src/_web_impl.dart';

void main() {
test(
'throws an Error if showInstallPrompt is called before installPromptReady resolves',
() {
final ServiceWorkerImpl api = ServiceWorkerImpl()..init();

// Could be either assertion or StateError depending on mode.
expect(() => api.showInstallPrompt(), throwsA(isA<Error>()));
});
}