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

Offline mode and web app manifest #486

Merged
merged 23 commits into from
Nov 28, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
210 changes: 141 additions & 69 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,12 @@
"devDependencies": {
"@magento/directive-parser": "^0.1.1",
"@magento/eslint-config": "^1.2.3",
"@storybook/addon-actions": "^3.4.2",
"@storybook/addons": "^3.4.6",
"@storybook/react": "^3.4.2",
"apollo-boost": "^0.1.20",
"apollo-cache-inmemory": "^1.3.9",
"apollo-cache-persist": "^0.1.1",
"apollo-client": "^2.4.5",
"apollo-link-context": "^1.0.9",
"apollo-server": "^2.0.5",
Expand Down
24 changes: 21 additions & 3 deletions packages/peregrine/src/Router/MagentoRouteHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,34 @@ export default class MagentoRouteHandler extends Component {
}
};

// TODO: Add the ability to customize the cache name
async addToCache(urls) {
const myCache = await window.caches.open(
`workbox-runtime-${location.origin}/`
);
await myCache.addAll(urls);
}

componentDidMount() {
mountedInstances.add(this);
this.getRouteComponent(this.props.location.pathname);
this.getRouteComponent();
}

componentDidUpdate() {
const { props, state } = this;
const { pathname } = props.location;
const isKnown = state.componentMap.has(pathname);

if (!isKnown) {
this.getRouteComponent(pathname);
// `NOTFOUND` component needs a unique id
// currently it is set to -1
const isNotFoundComponent = isKnown
? state.componentMap.get(pathname).id === -1
: false;

const shouldReloadRoute = isNotFoundComponent && navigator.onLine;

if (!isKnown || shouldReloadRoute) {
this.getRouteComponent();
}
}

Expand Down Expand Up @@ -88,6 +104,8 @@ export default class MagentoRouteHandler extends Component {
return;
}

this.addToCache([pathname]);

this.setState(({ componentMap }) => ({
componentMap: new Map(componentMap).set(pathname, {
RootComponent,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,48 @@ const urlResolverRes = (type, id) =>
}
});

const NotFoundManifest = {
NotFound: {
rootChunkID: -1,
rootModuleID: 100,
pageTypes: ['NOTFOUND']
}
};

const mockManifest = {
Category: {
rootChunkID: 2,
rootModuleID: 100,
pageTypes: ['CATEGORY']
},
Product: {
rootChunkID: 1,
rootModuleID: 99,
pageTypes: ['PRODUCT']
},
...NotFoundManifest
};

const cachedResponse = JSON.stringify({
'foo-bar.html': {
...JSON.parse(urlResolverRes('PRODUCT'))
}
});

const isOnline = _value => ({
get: () => _value,
set: v => (_value = v)
});

Object.defineProperty(navigator, 'onLine', isOnline(true));

function clearLocalStorage(item) {
localStorage.setItem(item, null);
}

beforeEach(() => {
navigator.onLine = true;
clearLocalStorage('urlResolve');
document.body.innerHTML = '';
resolveUnknownRoute.preloadDone = false;
fetch.resetMocks();
Expand All @@ -18,14 +59,67 @@ test('Preload path: resolves directly from preload element', async () => {
'<script type="application/json" id="url-resolver">{ "type": "PRODUCT", "id": "VA-123" }</script>';
const res = await resolveUnknownRoute({
route: 'foo-bar.html',
apiBase: 'https://store.com'
apiBase: 'https://example.com'
});
expect(res).toMatchObject({
type: 'PRODUCT',
id: 'VA-123'
});
});

test('returns NOTFOUND when offline and requested content is not in cache ', async () => {
navigator.onLine = false;

fetch.mockResponseOnce(JSON.stringify(mockManifest));
const res = await resolveUnknownRoute({
route: 'foo-bar.html',
apiBase: 'https://store.com',
__tmp_webpack_public_path__: 'https://dev-server.com/pub'
});

expect(res).toHaveProperty('id', NotFoundManifest.NotFound.rootChunkID);
});

test('stores response of urlResolver in cache', async () => {
fetch.mockResponseOnce(urlResolverRes('PRODUCT'));
fetch.mockResponseOnce(JSON.stringify(mockManifest));

const url = 'foo-bar.html';

await resolveUnknownRoute({
route: url,
apiBase: 'https://store.com',
__tmp_webpack_public_path__: 'https://dev-server.com/pub'
});

expect(localStorage.getItem('urlResolve')).not.toBeNull();
});

test('does not call fetchRoute when response is cached', async () => {
localStorage.setItem('urlResolve', cachedResponse);

fetch.mockResponseOnce(JSON.stringify(mockManifest));
await resolveUnknownRoute({
route: 'foo-bar.html',
apiBase: 'https://store.com',
__tmp_webpack_public_path__: 'https://dev-server.com/pub'
});

expect(fetch).toHaveBeenCalledTimes(0);
});

test('calls fetchRoute when response is not cached', async () => {
fetch.mockResponseOnce(urlResolverRes('PRODUCT'));
fetch.mockResponseOnce(JSON.stringify(mockManifest));
await resolveUnknownRoute({
route: 'foo-bar.html',
apiBase: 'https://store.com',
__tmp_webpack_public_path__: 'https://dev-server.com/pub'
});

expect(fetch).toHaveBeenCalledTimes(1);
});

test('urlResolver path: resolve using fetch to GraphQL after one preload', async () => {
fetch.mockResponseOnce(urlResolverRes('PRODUCT', 'VA-11'));
document.body.innerHTML =
Expand Down
43 changes: 41 additions & 2 deletions packages/peregrine/src/Router/resolveUnknownRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,37 @@ export default async function resolveUnknownRoute(opts) {
}

/**
* @description Calls the GraphQL API for results from the urlResolver query
* @description Checks if route is stored in localStorage, if not call `fetchRoute`
* @param {{ route: string, apiBase: string}} opts
* @returns {Promise<{type: "PRODUCT" | "CATEGORY" | "CMS_PAGE"}>}
*/
function remotelyResolveRoute(opts) {
let urlResolve = localStorage.getItem('urlResolve');
urlResolve = JSON.parse(urlResolve);

// If it exists in localStorage, use that value
// TODO: This can be handled by workbox once this issue is resolved in the
// graphql repo: https://github.com/magento/graphql-ce/issues/229
if ((urlResolve && urlResolve[opts.route]) || !navigator.onLine) {
if (urlResolve && urlResolve[opts.route]) {
return Promise.resolve(urlResolve[opts.route].data.urlResolver);
} else {
return Promise.resolve({
type: 'NOTFOUND',
id: -1
});
}
} else {
return fetchRoute(opts);
}
}

/**
* @description Calls the GraphQL API for results from the urlResolver query
* @param {{ route: string, apiBase: string}} opts
* @returns {Promise<{type: "PRODUCT" | "CATEGORY" | "CMS_PAGE"}>}
*/
function fetchRoute(opts) {
const url = new URL('/graphql', opts.apiBase);
return fetch(url, {
method: 'POST',
Expand All @@ -66,5 +92,18 @@ function remotelyResolveRoute(opts) {
})
})
.then(res => res.json())
.then(res => res.data.urlResolver);
.then(res => {
storeURLResolveResult(res, opts);
return res.data.urlResolver;
});
}

// TODO: This can be handled by workbox once this issue is resolved in the
// graphql repo: https://github.com/magento/graphql-ce/issues/229
function storeURLResolveResult(res, opts) {
const storedRoute = localStorage.getItem('urlResolve');
const item = JSON.parse(storedRoute) || {};

item[opts.route] = res;
localStorage.setItem('urlResolve', JSON.stringify(item));
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class ServiceWorkerPlugin {
ServiceWorkerPlugin.validateOptions('ServiceWorkerPlugin', config);
this.config = config;
}
applyWorkbox(compiler) {
applyGenerateSW(compiler) {
const config = {
// `globDirectory` and `globPatterns` must match at least 1 file
// otherwise workbox throws an error
Expand All @@ -28,25 +28,48 @@ class ServiceWorkerPlugin {
swDest: this.config.serviceWorkerFileName
};

if (this.config.runtimeCacheAssetPath) {
config.runtimeCaching = [
{
urlPattern: new RegExp(this.config.runtimeCacheAssetPath),
handler: 'staleWhileRevalidate'
}
];
if (this.config.runtimeCacheConfig) {
config.runtimeCaching = this.config.runtimeCacheConfig;
}
new WorkboxPlugin.GenerateSW(config).apply(compiler);
}

configureInjectManifest() {
let injectManifest;
if (this.config.injectManifestConfig) {
injectManifest = new WorkboxPlugin.InjectManifest(
this.config.injectManifestConfig
);
} else {
injectManifest = new WorkboxPlugin.InjectManifest({
swSrc: this.config.paths.src + '/sw.js',
swDest: this.config.paths.dest + '/sw.js'
});
}
return injectManifest;
}

applyInjectManifest(compiler) {
this.configureInjectManifest().apply(compiler);
}

apply(compiler) {
if (this.config.env.mode === 'development') {
// add a WriteFilePlugin to write out the service worker to the filesystem so it can be served by M2, even though it's under dev
if (this.config.enableServiceWorkerDebugging) {
if (
this.config.enableServiceWorkerDebugging &&
!this.config.injectManifest
) {
new WriteFileWebpackPlugin({
test: new RegExp(this.config.serviceWorkerFileName + '$'),
log: true
}).apply(compiler);
this.applyWorkbox(compiler);
this.applyGenerateSW(compiler);
} else if (
this.config.enableServiceWorkerDebugging &&
this.config.injectManifest
) {
this.applyInjectManifest(compiler);
} else {
// TODO: (feature) emit a structured { code, severity, resolution } object
// on Environment that might throw and might not
Expand All @@ -58,5 +81,13 @@ class ServiceWorkerPlugin {
this.applyWorkbox(compiler);
}
}

applyWorkbox(compiler) {
if (this.config.injectManifest) {
this.applyInjectManifest(compiler);
} else {
this.applyGenerateSW(compiler);
}
}
}
module.exports = ServiceWorkerPlugin;
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,34 @@ test('.apply generates and writes out a serviceworker when enableServiceWorkerDe
})
);
});

test('.apply uses `InjectManifest` when `injectManifest` is `true`', () => {
const injectManifestConfig = {
swSrc: 'path/to/sw',
swDest: 'path/to/dest'
};
const plugin = new ServiceWorkerPlugin({
env: {
mode: 'development'
},
enableServiceWorkerDebugging: true,
serviceWorkerFileName: 'sw.js',
injectManifest: true,
paths: {
output: 'path/to/assets'
},
injectManifestConfig
});

const fakeCompiler = {};
const workboxApply = jest.fn();
WorkboxPlugin.InjectManifest.mockImplementationOnce(() => ({
apply: workboxApply
}));

plugin.apply(fakeCompiler);

expect(WorkboxPlugin.InjectManifest).toHaveBeenCalledWith(
expect.objectContaining(injectManifestConfig)
);
});
Binary file removed packages/venia-concept/media/favicon.ico
Binary file not shown.
6 changes: 6 additions & 0 deletions packages/venia-concept/src/RootComponents/NotFound/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* @RootComponent
* description = 'Page to display when offline'
* pageTypes = NOTFOUND
*/
export { default } from './notFound';
10 changes: 10 additions & 0 deletions packages/venia-concept/src/RootComponents/NotFound/notFound.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.root {
padding: 1rem;
}

.title {
font-size: 1.5rem;
font-weight: 400;
margin: 0 0 1rem;
padding: 0.5rem;
}
28 changes: 28 additions & 0 deletions packages/venia-concept/src/RootComponents/NotFound/notFound.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import React, { Component } from 'react';
import classify from 'src/classify';
import defaultClasses from './notFound.css';

class NotFound extends Component {
// TODO: Should not be a default here, we just don't have
// the wiring in place to map route info down the tree (yet)
static defaultProps = {
id: 3
};

goBack() {
history.back();
}

render() {
const { classes } = this.props;

return (
<div className={classes.root}>
<h1> Offline! </h1>
<button onClick={this.goBack}> Go Back </button>
</div>
);
}
}

export default classify(defaultClasses)(NotFound);
Loading