@docusaurus/plugin-pwa 2.0.0-beta.fbdeefcac → 2.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.d.ts +10 -0
- package/lib/index.js +164 -0
- package/lib/options.d.ts +9 -0
- package/lib/options.js +46 -0
- package/lib/registerSw.d.ts +18 -0
- package/lib/registerSw.js +186 -0
- package/lib/renderReloadPopup.d.ts +8 -0
- package/lib/renderReloadPopup.js +22 -0
- package/lib/sw.d.ts +7 -0
- package/lib/sw.js +111 -0
- package/lib/theme/PwaReloadPopup/index.d.ts +9 -0
- package/{src → lib}/theme/PwaReloadPopup/index.js +0 -4
- package/lib/theme/PwaReloadPopup/styles.module.css +39 -0
- package/package.json +35 -19
- package/src/deps.d.ts +15 -0
- package/src/{index.js → index.ts} +72 -45
- package/src/{pluginOptionSchema.js → options.ts} +17 -8
- package/src/plugin-pwa.d.ts +88 -0
- package/src/registerSw.ts +237 -0
- package/src/{renderReloadPopup.js → renderReloadPopup.tsx} +7 -5
- package/src/{sw.js → sw.ts} +36 -44
- package/src/theme/PwaReloadPopup/index.tsx +59 -0
- package/src/types.d.ts +8 -0
- package/src/registerSw.js +0 -303
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
import type { LoadContext, Plugin } from '@docusaurus/types';
|
|
8
|
+
import type { PluginOptions } from '@docusaurus/plugin-pwa';
|
|
9
|
+
export default function pluginPWA(context: LoadContext, options: PluginOptions): Plugin<void>;
|
|
10
|
+
export { validateOptions } from './options';
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
4
|
+
*
|
|
5
|
+
* This source code is licensed under the MIT license found in the
|
|
6
|
+
* LICENSE file in the root directory of this source tree.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.validateOptions = void 0;
|
|
10
|
+
const tslib_1 = require("tslib");
|
|
11
|
+
const path_1 = tslib_1.__importDefault(require("path"));
|
|
12
|
+
const webpack_1 = tslib_1.__importDefault(require("webpack"));
|
|
13
|
+
const terser_webpack_plugin_1 = tslib_1.__importDefault(require("terser-webpack-plugin"));
|
|
14
|
+
const workbox_build_1 = require("workbox-build");
|
|
15
|
+
const utils_1 = require("@docusaurus/utils");
|
|
16
|
+
const utils_2 = require("@docusaurus/core/lib/webpack/utils");
|
|
17
|
+
const LogPlugin_1 = tslib_1.__importDefault(require("@docusaurus/core/lib/webpack/plugins/LogPlugin"));
|
|
18
|
+
const theme_translations_1 = require("@docusaurus/theme-translations");
|
|
19
|
+
const isProd = process.env.NODE_ENV === 'production';
|
|
20
|
+
function getSWBabelLoader() {
|
|
21
|
+
return {
|
|
22
|
+
loader: 'babel-loader',
|
|
23
|
+
options: {
|
|
24
|
+
babelrc: false,
|
|
25
|
+
configFile: false,
|
|
26
|
+
presets: [
|
|
27
|
+
[
|
|
28
|
+
require.resolve('@babel/preset-env'),
|
|
29
|
+
{
|
|
30
|
+
useBuiltIns: 'entry',
|
|
31
|
+
corejs: '3',
|
|
32
|
+
// See https://twitter.com/jeffposnick/status/1280223070876315649
|
|
33
|
+
targets: 'chrome >= 56',
|
|
34
|
+
},
|
|
35
|
+
],
|
|
36
|
+
],
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function pluginPWA(context, options) {
|
|
41
|
+
const { outDir, baseUrl, i18n: { currentLocale }, } = context;
|
|
42
|
+
const { debug, offlineModeActivationStrategies, injectManifestConfig, pwaHead, swCustom, swRegister, } = options;
|
|
43
|
+
return {
|
|
44
|
+
name: 'docusaurus-plugin-pwa',
|
|
45
|
+
getThemePath() {
|
|
46
|
+
return '../lib/theme';
|
|
47
|
+
},
|
|
48
|
+
getTypeScriptThemePath() {
|
|
49
|
+
return '../src/theme';
|
|
50
|
+
},
|
|
51
|
+
getClientModules() {
|
|
52
|
+
return isProd && swRegister ? [swRegister] : [];
|
|
53
|
+
},
|
|
54
|
+
getDefaultCodeTranslationMessages() {
|
|
55
|
+
return (0, theme_translations_1.readDefaultCodeTranslationMessages)({
|
|
56
|
+
locale: currentLocale,
|
|
57
|
+
name: 'plugin-pwa',
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
configureWebpack(config) {
|
|
61
|
+
if (!isProd) {
|
|
62
|
+
return {};
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
plugins: [
|
|
66
|
+
new webpack_1.default.EnvironmentPlugin({
|
|
67
|
+
PWA_DEBUG: debug,
|
|
68
|
+
PWA_SERVICE_WORKER_URL: path_1.default.posix.resolve(`${config.output?.publicPath || '/'}`, 'sw.js'),
|
|
69
|
+
PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES: offlineModeActivationStrategies,
|
|
70
|
+
}),
|
|
71
|
+
],
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
injectHtmlTags() {
|
|
75
|
+
const headTags = [];
|
|
76
|
+
if (isProd) {
|
|
77
|
+
pwaHead.forEach(({ tagName, ...attributes }) => {
|
|
78
|
+
['href', 'content'].forEach((attribute) => {
|
|
79
|
+
const attributeValue = attributes[attribute];
|
|
80
|
+
if (!attributeValue) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const attributePath = !!path_1.default.extname(attributeValue) && attributeValue;
|
|
84
|
+
if (attributePath && !attributePath.startsWith(baseUrl)) {
|
|
85
|
+
attributes[attribute] = (0, utils_1.normalizeUrl)([baseUrl, attributeValue]);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
return headTags.push({
|
|
89
|
+
tagName,
|
|
90
|
+
attributes,
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
return { headTags };
|
|
95
|
+
},
|
|
96
|
+
async postBuild(props) {
|
|
97
|
+
if (!isProd) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const swSourceFileTest = /\.m?js$/;
|
|
101
|
+
const swWebpackConfig = {
|
|
102
|
+
entry: require.resolve('./sw.js'),
|
|
103
|
+
output: {
|
|
104
|
+
path: outDir,
|
|
105
|
+
filename: 'sw.js',
|
|
106
|
+
publicPath: baseUrl,
|
|
107
|
+
},
|
|
108
|
+
target: 'webworker',
|
|
109
|
+
mode: debug ? 'development' : 'production',
|
|
110
|
+
devtool: debug ? 'source-map' : false,
|
|
111
|
+
optimization: {
|
|
112
|
+
splitChunks: false,
|
|
113
|
+
minimize: !debug,
|
|
114
|
+
// See https://developers.google.com/web/tools/workbox/guides/using-bundlers#webpack
|
|
115
|
+
minimizer: debug
|
|
116
|
+
? []
|
|
117
|
+
: [
|
|
118
|
+
new terser_webpack_plugin_1.default({
|
|
119
|
+
test: swSourceFileTest,
|
|
120
|
+
}),
|
|
121
|
+
],
|
|
122
|
+
},
|
|
123
|
+
plugins: [
|
|
124
|
+
new webpack_1.default.EnvironmentPlugin({
|
|
125
|
+
// Fallback value required with Webpack 5
|
|
126
|
+
PWA_SW_CUSTOM: swCustom ?? '',
|
|
127
|
+
}),
|
|
128
|
+
new LogPlugin_1.default({
|
|
129
|
+
name: 'Service Worker',
|
|
130
|
+
color: 'red',
|
|
131
|
+
}),
|
|
132
|
+
],
|
|
133
|
+
module: {
|
|
134
|
+
rules: [
|
|
135
|
+
{
|
|
136
|
+
test: swSourceFileTest,
|
|
137
|
+
exclude: /node_modules/,
|
|
138
|
+
use: getSWBabelLoader(),
|
|
139
|
+
},
|
|
140
|
+
],
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
await (0, utils_2.compile)([swWebpackConfig]);
|
|
144
|
+
const swDest = path_1.default.resolve(props.outDir, 'sw.js');
|
|
145
|
+
await (0, workbox_build_1.injectManifest)({
|
|
146
|
+
...injectManifestConfig,
|
|
147
|
+
globPatterns: [
|
|
148
|
+
'**/*.{js,json,css,html}',
|
|
149
|
+
'**/*.{png,jpg,jpeg,gif,svg,ico}',
|
|
150
|
+
'**/*.{woff,woff2,eot,ttf,otf}',
|
|
151
|
+
// @ts-expect-error: internal API?
|
|
152
|
+
...(workbox_build_1.injectManifest.globPatterns ?? []),
|
|
153
|
+
],
|
|
154
|
+
// Those attributes are not overrideable
|
|
155
|
+
swDest,
|
|
156
|
+
swSrc: swDest,
|
|
157
|
+
globDirectory: props.outDir,
|
|
158
|
+
});
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
exports.default = pluginPWA;
|
|
163
|
+
var options_1 = require("./options");
|
|
164
|
+
Object.defineProperty(exports, "validateOptions", { enumerable: true, get: function () { return options_1.validateOptions; } });
|
package/lib/options.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
import type { OptionValidationContext } from '@docusaurus/types';
|
|
8
|
+
import type { PluginOptions } from '@docusaurus/plugin-pwa';
|
|
9
|
+
export declare function validateOptions({ validate, options, }: OptionValidationContext<PluginOptions, PluginOptions>): PluginOptions;
|
package/lib/options.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
4
|
+
*
|
|
5
|
+
* This source code is licensed under the MIT license found in the
|
|
6
|
+
* LICENSE file in the root directory of this source tree.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.validateOptions = void 0;
|
|
10
|
+
const utils_validation_1 = require("@docusaurus/utils-validation");
|
|
11
|
+
const DEFAULT_OPTIONS = {
|
|
12
|
+
debug: false,
|
|
13
|
+
offlineModeActivationStrategies: [
|
|
14
|
+
'appInstalled',
|
|
15
|
+
'queryString',
|
|
16
|
+
'standalone',
|
|
17
|
+
],
|
|
18
|
+
injectManifestConfig: {},
|
|
19
|
+
pwaHead: [],
|
|
20
|
+
swCustom: undefined,
|
|
21
|
+
swRegister: './registerSw.js',
|
|
22
|
+
};
|
|
23
|
+
const optionsSchema = utils_validation_1.Joi.object({
|
|
24
|
+
debug: utils_validation_1.Joi.bool().default(DEFAULT_OPTIONS.debug),
|
|
25
|
+
offlineModeActivationStrategies: utils_validation_1.Joi.array()
|
|
26
|
+
.items(utils_validation_1.Joi.string()
|
|
27
|
+
.valid('appInstalled', 'queryString', 'standalone', 'mobile', 'saveData', 'always')
|
|
28
|
+
.required())
|
|
29
|
+
.default(DEFAULT_OPTIONS.offlineModeActivationStrategies),
|
|
30
|
+
injectManifestConfig: utils_validation_1.Joi.object().default(DEFAULT_OPTIONS.injectManifestConfig),
|
|
31
|
+
pwaHead: utils_validation_1.Joi.array()
|
|
32
|
+
.items(utils_validation_1.Joi.object({ tagName: utils_validation_1.Joi.string().required() }).unknown().required())
|
|
33
|
+
.default(DEFAULT_OPTIONS.pwaHead),
|
|
34
|
+
swCustom: utils_validation_1.Joi.string(),
|
|
35
|
+
swRegister: utils_validation_1.Joi.alternatives()
|
|
36
|
+
.try(utils_validation_1.Joi.string(), utils_validation_1.Joi.bool().valid(false))
|
|
37
|
+
.default(DEFAULT_OPTIONS.swRegister),
|
|
38
|
+
// @ts-expect-error: forbidden
|
|
39
|
+
reloadPopup: utils_validation_1.Joi.any().forbidden().messages({
|
|
40
|
+
'any.unknown': 'The reloadPopup option is removed in favor of swizzling. See https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-pwa#customizing-reload-popup for how to customize the reload popup using swizzling.',
|
|
41
|
+
}),
|
|
42
|
+
});
|
|
43
|
+
function validateOptions({ validate, options, }) {
|
|
44
|
+
return validate(optionsSchema, options);
|
|
45
|
+
}
|
|
46
|
+
exports.validateOptions = validateOptions;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
declare global {
|
|
8
|
+
interface Navigator {
|
|
9
|
+
getInstalledRelatedApps: () => Promise<{
|
|
10
|
+
platform: string;
|
|
11
|
+
}[]>;
|
|
12
|
+
connection?: {
|
|
13
|
+
effectiveType: string;
|
|
14
|
+
saveData: boolean;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
|
|
8
|
+
import { createStorageSlot } from '@docusaurus/theme-common';
|
|
9
|
+
// First: read the env variables (provided by Webpack)
|
|
10
|
+
/* eslint-disable prefer-destructuring */
|
|
11
|
+
const PWA_SERVICE_WORKER_URL = process.env.PWA_SERVICE_WORKER_URL;
|
|
12
|
+
const PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES = process.env
|
|
13
|
+
.PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES;
|
|
14
|
+
const PWA_DEBUG = process.env.PWA_DEBUG;
|
|
15
|
+
/* eslint-enable prefer-destructuring */
|
|
16
|
+
const MAX_MOBILE_WIDTH = 996;
|
|
17
|
+
const AppInstalledEventFiredStorage = createStorageSlot('docusaurus.pwa.event.appInstalled.fired');
|
|
18
|
+
function debugLog(msg, obj) {
|
|
19
|
+
if (PWA_DEBUG) {
|
|
20
|
+
if (typeof obj === 'undefined') {
|
|
21
|
+
console.log(`[Docusaurus-PWA][registerSw]: ${msg}`);
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
console.log(`[Docusaurus-PWA][registerSw]: ${msg}`, obj);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
async function clearRegistrations() {
|
|
29
|
+
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
30
|
+
debugLog('will unregister all service workers', { registrations });
|
|
31
|
+
await Promise.all(registrations.map((registration) => registration
|
|
32
|
+
.unregister()
|
|
33
|
+
.then((result) => debugLog('unregister service worker', { registration, result }))));
|
|
34
|
+
debugLog('unregistered all service workers', { registrations });
|
|
35
|
+
window.location.reload();
|
|
36
|
+
}
|
|
37
|
+
/*
|
|
38
|
+
As of 2021:
|
|
39
|
+
It is complicated and not very reliable to detect an app is actually installed.
|
|
40
|
+
https://stackoverflow.com/questions/51735869/check-if-user-has-already-installed-pwa-to-homescreen-on-chrome
|
|
41
|
+
|
|
42
|
+
- appinstalled event is not in the spec anymore and seems to not fire? https://firt.dev/pwa-2021#less-capabilities-%E2%98%B9%EF%B8%8F
|
|
43
|
+
- getInstalledRelatedApps() is only supported in recent Chrome and does not seem to reliable either https://github.com/WICG/get-installed-related-apps
|
|
44
|
+
- display-mode: standalone is not exactly the same concept, but looks like a decent fallback https://petelepage.com/blog/2019/07/is-my-pwa-installed/
|
|
45
|
+
*/
|
|
46
|
+
function getIsAppInstalledEventFired() {
|
|
47
|
+
return AppInstalledEventFiredStorage.get() === 'true';
|
|
48
|
+
}
|
|
49
|
+
async function getIsAppInstalledRelatedApps() {
|
|
50
|
+
if (!('getInstalledRelatedApps' in window.navigator)) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
const relatedApps = await navigator.getInstalledRelatedApps();
|
|
54
|
+
return relatedApps.some((app) => app.platform === 'webapp');
|
|
55
|
+
}
|
|
56
|
+
function isStandaloneDisplayMode() {
|
|
57
|
+
return window.matchMedia('(display-mode: standalone)').matches;
|
|
58
|
+
}
|
|
59
|
+
const OfflineModeActivationStrategiesImplementations = {
|
|
60
|
+
always: () => true,
|
|
61
|
+
mobile: () => window.innerWidth <= MAX_MOBILE_WIDTH,
|
|
62
|
+
saveData: () => !!navigator.connection?.saveData,
|
|
63
|
+
appInstalled: () => getIsAppInstalledEventFired() || getIsAppInstalledRelatedApps(),
|
|
64
|
+
standalone: () => isStandaloneDisplayMode(),
|
|
65
|
+
queryString: () => new URLSearchParams(window.location.search).get('offlineMode') === 'true',
|
|
66
|
+
};
|
|
67
|
+
async function getActiveStrategies() {
|
|
68
|
+
const activeStrategies = await Promise.all(PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES.map((strategyName) => Promise.resolve(OfflineModeActivationStrategiesImplementations[strategyName]()).then((isActive) => (isActive ? strategyName : undefined))));
|
|
69
|
+
return activeStrategies.filter(Boolean);
|
|
70
|
+
}
|
|
71
|
+
async function getIsOfflineModeEnabled() {
|
|
72
|
+
const activeStrategies = await getActiveStrategies();
|
|
73
|
+
const enabled = activeStrategies.length > 0;
|
|
74
|
+
debugLog(enabled
|
|
75
|
+
? 'offline mode enabled, because of activation strategies'
|
|
76
|
+
: 'offline mode disabled, because none of the offlineModeActivationStrategies could be used', {
|
|
77
|
+
activeStrategies,
|
|
78
|
+
availableStrategies: PWA_OFFLINE_MODE_ACTIVATION_STRATEGIES,
|
|
79
|
+
});
|
|
80
|
+
return enabled;
|
|
81
|
+
}
|
|
82
|
+
function createServiceWorkerUrl(params) {
|
|
83
|
+
const paramsQueryString = JSON.stringify(params);
|
|
84
|
+
const url = `${PWA_SERVICE_WORKER_URL}?params=${encodeURIComponent(paramsQueryString)}`;
|
|
85
|
+
debugLog('service worker url', { url, params });
|
|
86
|
+
return url;
|
|
87
|
+
}
|
|
88
|
+
async function registerSW() {
|
|
89
|
+
const [{ Workbox }, offlineMode] = await Promise.all([
|
|
90
|
+
import('workbox-window'),
|
|
91
|
+
getIsOfflineModeEnabled(),
|
|
92
|
+
]);
|
|
93
|
+
const url = createServiceWorkerUrl({ offlineMode, debug: PWA_DEBUG });
|
|
94
|
+
const wb = new Workbox(url);
|
|
95
|
+
const sendSkipWaiting = () => wb.messageSW({ type: 'SKIP_WAITING' });
|
|
96
|
+
const handleServiceWorkerWaiting = () => {
|
|
97
|
+
debugLog('handleServiceWorkerWaiting');
|
|
98
|
+
// Immediately load new service worker when files aren't cached
|
|
99
|
+
if (!offlineMode) {
|
|
100
|
+
return sendSkipWaiting();
|
|
101
|
+
}
|
|
102
|
+
return import('./renderReloadPopup.js').then(({ renderReloadPopup }) => renderReloadPopup({
|
|
103
|
+
onReload() {
|
|
104
|
+
wb.addEventListener('controlling', () => {
|
|
105
|
+
window.location.reload();
|
|
106
|
+
});
|
|
107
|
+
sendSkipWaiting();
|
|
108
|
+
},
|
|
109
|
+
}));
|
|
110
|
+
};
|
|
111
|
+
// Update the current service worker when the next one has finished
|
|
112
|
+
// installing and transitions to waiting state.
|
|
113
|
+
wb.addEventListener('waiting', (event) => {
|
|
114
|
+
debugLog('event waiting', { event });
|
|
115
|
+
void handleServiceWorkerWaiting();
|
|
116
|
+
});
|
|
117
|
+
// Update current service worker if the next one finishes installing and
|
|
118
|
+
// moves to waiting state in another tab.
|
|
119
|
+
// @ts-expect-error: not present in the API typings anymore
|
|
120
|
+
wb.addEventListener('externalwaiting', (event) => {
|
|
121
|
+
debugLog('event externalwaiting', { event });
|
|
122
|
+
void handleServiceWorkerWaiting();
|
|
123
|
+
});
|
|
124
|
+
const registration = await wb.register();
|
|
125
|
+
if (registration) {
|
|
126
|
+
if (registration.active) {
|
|
127
|
+
debugLog('registration.active', { registration });
|
|
128
|
+
}
|
|
129
|
+
if (registration.installing) {
|
|
130
|
+
debugLog('registration.installing', { registration });
|
|
131
|
+
}
|
|
132
|
+
if (registration.waiting) {
|
|
133
|
+
debugLog('registration.waiting', { registration });
|
|
134
|
+
// Update service worker if the next one is already in the waiting
|
|
135
|
+
// state. This happens when the user doesn't click on `reload` in
|
|
136
|
+
// the popup.
|
|
137
|
+
await handleServiceWorkerWaiting();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
// TODO these events still works in chrome but have been removed from the spec
|
|
142
|
+
// in 2019! See https://github.com/w3c/manifest/pull/836
|
|
143
|
+
function addLegacyAppInstalledEventsListeners() {
|
|
144
|
+
debugLog('addLegacyAppInstalledEventsListeners');
|
|
145
|
+
window.addEventListener('appinstalled', (event) => {
|
|
146
|
+
debugLog('event appinstalled', { event });
|
|
147
|
+
AppInstalledEventFiredStorage.set('true');
|
|
148
|
+
debugLog("AppInstalledEventFiredStorage.set('true')");
|
|
149
|
+
// After the app is installed, we register a service worker with the path
|
|
150
|
+
// `/sw?enabled`. Since the previous service worker was `/sw`, it'll be
|
|
151
|
+
// treated as a new one. The previous registration will need to be
|
|
152
|
+
// cleared, otherwise the reload popup will show.
|
|
153
|
+
void clearRegistrations();
|
|
154
|
+
});
|
|
155
|
+
// TODO this event still works in chrome but has been removed from the spec
|
|
156
|
+
// in 2019!!!
|
|
157
|
+
window.addEventListener('beforeinstallprompt', (event) => {
|
|
158
|
+
debugLog('event beforeinstallprompt', { event });
|
|
159
|
+
// TODO instead of default browser install UI, show custom docusaurus
|
|
160
|
+
// prompt?
|
|
161
|
+
// event.preventDefault();
|
|
162
|
+
const appInstalledEventFired = AppInstalledEventFiredStorage.get();
|
|
163
|
+
debugLog('AppInstalledEventFiredStorage.get()', { appInstalledEventFired });
|
|
164
|
+
if (appInstalledEventFired) {
|
|
165
|
+
AppInstalledEventFiredStorage.del();
|
|
166
|
+
debugLog('AppInstalledEventFiredStorage.del()');
|
|
167
|
+
// After uninstalling the app, if the user doesn't clear all data, then
|
|
168
|
+
// the previous service worker will continue serving cached files. We
|
|
169
|
+
// need to clear registrations and reload, otherwise the popup shows.
|
|
170
|
+
void clearRegistrations();
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
debugLog('legacy appinstalled and beforeinstallprompt event listeners installed');
|
|
174
|
+
}
|
|
175
|
+
/*
|
|
176
|
+
Init code to run on the client!
|
|
177
|
+
*/
|
|
178
|
+
if (ExecutionEnvironment.canUseDOM) {
|
|
179
|
+
debugLog('debug mode enabled');
|
|
180
|
+
if ('serviceWorker' in navigator) {
|
|
181
|
+
// First: add the listeners asap/synchronously
|
|
182
|
+
addLegacyAppInstalledEventsListeners();
|
|
183
|
+
// Then try to register the SW using lazy/dynamic imports
|
|
184
|
+
registerSW().catch((e) => console.error('registerSW failed', e));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
import type { Props } from '@theme/PwaReloadPopup';
|
|
8
|
+
export declare function renderReloadPopup(props: Props): Promise<void>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
import React from 'react';
|
|
8
|
+
import ReactDOM from 'react-dom';
|
|
9
|
+
const POPUP_CONTAINER_ID = 'pwa-popup-container';
|
|
10
|
+
const getContainer = () => document.getElementById(POPUP_CONTAINER_ID);
|
|
11
|
+
const createContainer = () => {
|
|
12
|
+
const container = document.createElement('div');
|
|
13
|
+
container.id = POPUP_CONTAINER_ID;
|
|
14
|
+
document.body.appendChild(container);
|
|
15
|
+
return container;
|
|
16
|
+
};
|
|
17
|
+
export function renderReloadPopup(props) {
|
|
18
|
+
const container = getContainer() ?? createContainer();
|
|
19
|
+
return import('@theme/PwaReloadPopup').then(({ default: ReloadPopup }) => {
|
|
20
|
+
ReactDOM.render(<ReloadPopup {...props}/>, container);
|
|
21
|
+
});
|
|
22
|
+
}
|
package/lib/sw.d.ts
ADDED
package/lib/sw.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
/* eslint-disable no-restricted-globals */
|
|
8
|
+
import { PrecacheController } from 'workbox-precaching';
|
|
9
|
+
function parseSwParams() {
|
|
10
|
+
const params = JSON.parse(new URLSearchParams(self.location.search).get('params'));
|
|
11
|
+
if (params.debug) {
|
|
12
|
+
console.log('[Docusaurus-PWA][SW]: Service Worker params:', params);
|
|
13
|
+
}
|
|
14
|
+
return params;
|
|
15
|
+
}
|
|
16
|
+
// Doc advises against dynamic imports in SW
|
|
17
|
+
// https://developers.google.com/web/tools/workbox/guides/using-bundlers#code_splitting_and_dynamic_imports
|
|
18
|
+
// https://twitter.com/sebastienlorber/status/1280155204575518720
|
|
19
|
+
// but looks it's working fine as it's inlined by webpack, need to double check
|
|
20
|
+
async function runSWCustomCode(params) {
|
|
21
|
+
if (process.env.PWA_SW_CUSTOM) {
|
|
22
|
+
const customSW = await import(process.env.PWA_SW_CUSTOM);
|
|
23
|
+
if (typeof customSW.default === 'function') {
|
|
24
|
+
customSW.default(params);
|
|
25
|
+
}
|
|
26
|
+
else if (params.debug) {
|
|
27
|
+
console.warn('[Docusaurus-PWA][SW]: swCustom should have a default export function');
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Gets different possible variations for a request URL. Similar to
|
|
33
|
+
* https://git.io/JvixK
|
|
34
|
+
*/
|
|
35
|
+
function getPossibleURLs(url) {
|
|
36
|
+
const urlObject = new URL(url, self.location.href);
|
|
37
|
+
if (urlObject.origin !== self.location.origin) {
|
|
38
|
+
return [];
|
|
39
|
+
}
|
|
40
|
+
// Ignore search params and hash
|
|
41
|
+
urlObject.search = '';
|
|
42
|
+
urlObject.hash = '';
|
|
43
|
+
return [
|
|
44
|
+
// /blog.html
|
|
45
|
+
urlObject.href,
|
|
46
|
+
// /blog/ => /blog/index.html
|
|
47
|
+
// /blog => /blog/index.html
|
|
48
|
+
`${urlObject.href}${urlObject.pathname.endsWith('/') ? '' : '/'}index.html`,
|
|
49
|
+
];
|
|
50
|
+
}
|
|
51
|
+
(async () => {
|
|
52
|
+
const params = parseSwParams();
|
|
53
|
+
// eslint-disable-next-line no-underscore-dangle
|
|
54
|
+
const precacheManifest = self.__WB_MANIFEST;
|
|
55
|
+
const controller = new PrecacheController({
|
|
56
|
+
// Safer to turn this true?
|
|
57
|
+
fallbackToNetwork: true,
|
|
58
|
+
});
|
|
59
|
+
if (params.offlineMode) {
|
|
60
|
+
controller.addToCacheList(precacheManifest);
|
|
61
|
+
if (params.debug) {
|
|
62
|
+
console.log('[Docusaurus-PWA][SW]: addToCacheList', { precacheManifest });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
await runSWCustomCode(params);
|
|
66
|
+
self.addEventListener('install', (event) => {
|
|
67
|
+
if (params.debug) {
|
|
68
|
+
console.log('[Docusaurus-PWA][SW]: install event', { event });
|
|
69
|
+
}
|
|
70
|
+
event.waitUntil(controller.install(event));
|
|
71
|
+
});
|
|
72
|
+
self.addEventListener('activate', (event) => {
|
|
73
|
+
if (params.debug) {
|
|
74
|
+
console.log('[Docusaurus-PWA][SW]: activate event', { event });
|
|
75
|
+
}
|
|
76
|
+
event.waitUntil(controller.activate(event));
|
|
77
|
+
});
|
|
78
|
+
self.addEventListener('fetch', async (event) => {
|
|
79
|
+
if (params.offlineMode) {
|
|
80
|
+
const requestURL = event.request.url;
|
|
81
|
+
const possibleURLs = getPossibleURLs(requestURL);
|
|
82
|
+
for (const possibleURL of possibleURLs) {
|
|
83
|
+
const cacheKey = controller.getCacheKeyForURL(possibleURL);
|
|
84
|
+
if (cacheKey) {
|
|
85
|
+
const cachedResponse = caches.match(cacheKey);
|
|
86
|
+
if (params.debug) {
|
|
87
|
+
console.log('[Docusaurus-PWA][SW]: serving cached asset', {
|
|
88
|
+
requestURL,
|
|
89
|
+
possibleURL,
|
|
90
|
+
possibleURLs,
|
|
91
|
+
cacheKey,
|
|
92
|
+
cachedResponse,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
event.respondWith(cachedResponse);
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
self.addEventListener('message', async (event) => {
|
|
102
|
+
if (params.debug) {
|
|
103
|
+
console.log('[Docusaurus-PWA][SW]: message event', { event });
|
|
104
|
+
}
|
|
105
|
+
const type = event.data?.type;
|
|
106
|
+
if (type === 'SKIP_WAITING') {
|
|
107
|
+
// lib def bug, see https://github.com/microsoft/TypeScript/issues/14877
|
|
108
|
+
self.skipWaiting();
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
})();
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
/// <reference types="react" />
|
|
8
|
+
import type { Props } from '@theme/PwaReloadPopup';
|
|
9
|
+
export default function PwaReloadPopup({ onReload }: Props): JSX.Element | false;
|
|
@@ -4,16 +4,12 @@
|
|
|
4
4
|
* This source code is licensed under the MIT license found in the
|
|
5
5
|
* LICENSE file in the root directory of this source tree.
|
|
6
6
|
*/
|
|
7
|
-
|
|
8
7
|
import React, {useState} from 'react';
|
|
9
8
|
import clsx from 'clsx';
|
|
10
9
|
import Translate, {translate} from '@docusaurus/Translate';
|
|
11
|
-
|
|
12
10
|
import styles from './styles.module.css';
|
|
13
|
-
|
|
14
11
|
export default function PwaReloadPopup({onReload}) {
|
|
15
12
|
const [isVisible, setIsVisible] = useState(true);
|
|
16
|
-
|
|
17
13
|
return (
|
|
18
14
|
isVisible && (
|
|
19
15
|
<div className={clsx('alert', 'alert--secondary', styles.popup)}>
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the MIT license found in the
|
|
5
|
+
* LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
.popup {
|
|
9
|
+
position: fixed;
|
|
10
|
+
bottom: 16px;
|
|
11
|
+
right: 16px;
|
|
12
|
+
width: 344px;
|
|
13
|
+
display: flex;
|
|
14
|
+
align-items: center;
|
|
15
|
+
justify-content: space-between;
|
|
16
|
+
z-index: 999;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
.popup p {
|
|
20
|
+
margin: 0;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
@media screen and (max-width: 500px) {
|
|
24
|
+
.popup {
|
|
25
|
+
width: 100%;
|
|
26
|
+
bottom: 0;
|
|
27
|
+
right: 0;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
.buttonContainer {
|
|
32
|
+
display: flex;
|
|
33
|
+
align-items: center;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
.buttonContainer :global(.close) {
|
|
37
|
+
margin: 0;
|
|
38
|
+
padding: 0;
|
|
39
|
+
}
|