├── .gitignore ├── CONTRIBUTING ├── LICENSE ├── README.md ├── app.js ├── package.json ├── pages ├── art-meets-dinner.html ├── bar-americain.html ├── brunch-at-balthazar.html ├── dinner-at-bulgari.html ├── index.html ├── roast-for-breakfast.html └── stop-for-a-scoop.html ├── scripts ├── _amp_loader.js ├── _analytics.js ├── _loading_bar.js ├── _notifications.js ├── _offline-page.js ├── _offline-styling.js ├── _refresh.js └── app_shell.js ├── service_worker ├── _analytics.js ├── _notifications.js ├── _request_store.js ├── _utilities.js └── service_worker.js ├── static ├── icon-192.png ├── logo-white.png └── manifest.json ├── styles ├── _notifications.scss ├── _shared.scss ├── app_shell.scss └── core.scss └── templates ├── app_shell.html ├── base.html ├── install_serviceworker.html └── offline.html /.gitignore: -------------------------------------------------------------------------------- 1 | logs 2 | *.log 3 | npm-debug.log* 4 | yarn-debug.log* 5 | yarn-error.log* 6 | .DS_Store 7 | 8 | pids 9 | *.pid 10 | *.seed 11 | *.pid.lock 12 | 13 | bower_components 14 | node_modules/ 15 | jspm_packages/ 16 | 17 | .npm 18 | .eslintcache 19 | *.tgz 20 | .env 21 | -------------------------------------------------------------------------------- /CONTRIBUTING: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution, 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult [GitHub Help] for more 22 | information on using pull requests. 23 | 24 | [GitHub Help]: https://help.github.com/articles/about-pull-requests/ 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AMP+PWA Demo for Blog and News Sites 2 | 3 | A simple, dependency-free blog that uses a 4 | [Progressive Web App](https://developers.google.com/web/progressive-web-apps/) 5 | (PWA) to show [Accelerated Mobile Pages](https://www.ampproject.org/) (AMP). 6 | __This is not an official Google product.__ 7 | 8 | 9 | ## Setup 10 | 11 | This project requires [Node.js](https://nodejs.org/en/download/) and [NPM](https://www.npmjs.com/). 12 | 13 | In the root of this repo, run `npm install` to download all dependencies, and 14 | then `npm start` to start the server. You can visit the site at 15 | [localhost:8080](http://localhost:8080). 16 | 17 | Note that this is just a _demo site_. Some features (e.g. push notifications) 18 | require a more complex backend that is not implemented here. 19 | 20 | 21 | ## Implementation Details 22 | 23 | Our site uses AMP and PWA to create a site that loads as fast as possible, while 24 | still allowing users to take advantage of some of the most recent web platform 25 | features like push notifications and offline browsing. 26 | 27 | The front end consists of three main components: 28 | 29 | - __AMP templates__: All pages are valid AMP pages. We'll only have to maintain 30 | a single set of templates (rather than a conventional version and a separate 31 | AMP version). 32 | - __[App Shell](https://developers.google.com/web/fundamentals/architecture/app-shell)__: 33 | This is an empty HTML page that contains some scripts to download content. 34 | - __[Service Worker](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers)__ 35 | 36 | The first pageview will always be an AMP page. If visitors are coming from 37 | Google search results, this page will be loaded directly from the [Google AMP 38 | cache](https://developers.google.com/amp/cache/overview). In the background, 39 | the AMP page will install the service worker, which in turn will cache the app 40 | shell page and some other resources. 41 | 42 | Any further pageview will be intercepted by the service worker. It returns the 43 | app shell, rather than the requested page, and the app shell will then load the 44 | actual content using AJAX. 45 | 46 | While the content shown inside the app shell is still valid AMP, we can now use 47 | custom JavaScript to add functionality that is not (yet) supported by AMP. Note 48 | however that this functionality will not be available on the first pageview, or 49 | in browsers that don't support service workers. The App Shell can also intercept 50 | link clicks and use the web history API to create a "single page app". 51 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | const fs = require('fs'); 19 | const path = require('path'); 20 | 21 | const express = require('express'); 22 | const nunjucks = require('nunjucks'); 23 | const rollup = require('rollup'); 24 | const sass = require('node-sass'); 25 | const closure = require('google-closure-compiler-js'); 26 | 27 | 28 | // ----------------------------------------------------------------------------- 29 | // Compile static assets, which are inlined in our HTML 30 | 31 | function compileCSS(path) { 32 | return Promise.resolve(sass.renderSync({ 33 | file: path, 34 | outputStyle: 'compressed' 35 | }).css); 36 | } 37 | 38 | function compileJS(path) { 39 | // Resolve imports using RollupJS, and convert to ES5 using Closure Compiler. 40 | return rollup.rollup({entry: path}) 41 | .then(bundle => bundle.generate({format: 'iife'}).code) 42 | .then(code => closure.compile({jsCode: [{src: code}]}).compiledCode); 43 | } 44 | 45 | const ASSETS = {}; 46 | 47 | ['styles/app_shell.scss', 'styles/core.scss', 48 | 'service_worker/service_worker.js', 'scripts/app_shell.js'].forEach(file => { 49 | let compile = (file.split('.')[1] == 'js') ? compileJS : compileCSS; 50 | compile(file).then(code => { ASSETS[file] = code; }); 51 | }); 52 | 53 | 54 | // ----------------------------------------------------------------------------- 55 | // Express App. 56 | 57 | const pages = fs.readdirSync('pages'); 58 | const app = express(); 59 | 60 | nunjucks.configure('.', {autoescape: true, express: app}); 61 | 62 | app.use(function(req, res, next) { 63 | res.locals.assets = ASSETS; 64 | res.locals.request = req; 65 | next(); 66 | }); 67 | 68 | app.use(express.static('static')); 69 | 70 | for (let p of pages) { 71 | let url = '/' + p.replace('.html', '').replace('index', ''); 72 | app.get(url, function(req, res) { res.render('pages/' + p); }); 73 | } 74 | 75 | app.get('/_/offline', function(req, res) { 76 | res.render('templates/offline.html'); 77 | }); 78 | 79 | app.get('/_/app_shell', function(req, res) { 80 | res.render('templates/app_shell.html'); 81 | }); 82 | 83 | app.get('/_/install_serviceworker', function(req, res) { 84 | res.render('templates/install_serviceworker.html'); 85 | }); 86 | 87 | app.get('/service_worker.js', function(req, res) { 88 | res.setHeader('content-type', 'text/javascript'); 89 | res.write(ASSETS['service_worker/service_worker.js']); 90 | res.end(); 91 | }); 92 | 93 | app.get('/_/latest_article', function(req, res) { 94 | // TODO(plegner) 95 | res.end(); 96 | }); 97 | 98 | app.get('/_/add_subscription', function(req, res) { 99 | // TODO(plegner) 100 | res.end(); 101 | }); 102 | 103 | app.get('/_/remove_subscription', function(req, res) { 104 | // TODO(plegner) 105 | res.end(); 106 | }); 107 | 108 | app.listen(8080, function() { 109 | console.log('The API server is running on port 8080.'); 110 | }); 111 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pwamp-demo", 3 | "version": "0.1.0", 4 | "description": "A simple, dependency-free blog that uses a Progressive Web App (PWA) to show Accellerated Mobile Pages (AMP).", 5 | "license": "Apache-2.0", 6 | "engines": { 7 | "node": ">=6.0" 8 | }, 9 | "scripts": { 10 | "start": "node app.js" 11 | }, 12 | "dependencies": { 13 | "express": "^4.14.0", 14 | "google-closure-compiler-js": "^20170124.0.0", 15 | "node-sass": "^4.5.0", 16 | "nunjucks": "^3.0.0", 17 | "rollup": "^0.41.4" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /pages/art-meets-dinner.html: -------------------------------------------------------------------------------- 1 | {% extends "../templates/base.html" %} 2 | 3 | {% set title = "Art meets Dinner at Sketch London" %} 4 | {% set description = "Part restaurant part terrifying art installation this a playground-esque restaurant in Mayfair mixes a peculiar experience with outstanding food." %} 5 | 6 | {% block page %} 7 | 8 |
9 | 10 |

Art meets Dinner at Sketch London

11 |

Ever wanted to know what it’s like to sit inside a giant egg, trying to go the loo, while geese squawk at you? Well welcome to sketch. Part restaurant part terrifying art installation this a playground-esque restaurant in Mayfair, created by Mourad Mazouz, mixes a peculiar experience with outstanding food.

12 |

sketch restaurant is formed of several rooms; a velvet-covered candy pink main room, an ostentatious oriental style private dining room, the masculine smoking-room style parlour, and the astonishingly decorated forest-like Glade Room.

13 |

We chose to have dinner in the main part of the restaurant, the Gallery Room. The candy pink velvet benches and small bistro tables are beautiful but more impressive are the collections of sketches lining every wall. All created by artist David Shrigley, they feature some very odd encounters, funny jokes, and just the downright absurd.

14 |

All the china in the restaurant features Shrigley illustrations too, it reminds me of the Edward Munkton Puccinos tableware and it’s pretty funny.

15 |

But what did I have to eat? Well, when I was given the option to order a whole mandarin duck I couldn’t really turn it down. A whole duck. Not to myself mind you, but even for two of us it was pretty large. And yes when they say duck they do mean the whole thing. They even present it to you before whisking it away to be carved up. This is probably some important etiquette thing but I’m obviously not posh enough to know about it and would rather they just bring you the duck on a plate ready to eat instead of teasing you with it before removing it for another few minutes to be carved.

16 |

All I can say is that the duck was delicious, but so was the wine, so at this stage I can’t really tell you how or why it was delicious, just that it was.

17 |

But the dessert is something that I’ll never forget.

18 |

When you were younger, did you imagine that being an adult meant you could eat whatever you want, whenever you wanted? What happens if you’d wanted sherbet mousse and popping candy with flying saucers for pudding in a fancy restaurant? Then you grew up and realised that these sorts of places only served boring (but tasty) desserts like cheeseboards and lemon tarts.

19 |

But not at sketch.

20 |

What we ordered was like a childhood dream. A plate of zingy sherbet mousse, decorated with flying saucers and sprinkled with popping candy and ice cream, all arrived in pastel colours of pink and yellow and orange. Oh and it was delicious. Don’t get me wrong I love a cheeseboard, but there’s something hilarious about ordering flying saucers for dessert.

21 |

Oh and about those goose eggs, have fun in the toilet as you sit inside your own personal pod with mood lighting and the sounds of geese squawking overhead…

22 |
23 | 24 |

Related Articles

25 |
26 | 27 | 28 |

Art meets Dinner at sketch London

29 |
30 | 31 | 32 |

Stop for a Scoop in Seven Dials

33 |
34 | 35 | 36 |

Roast for breakfast

37 |
38 |
39 | 40 | {% endblock %} 41 | -------------------------------------------------------------------------------- /pages/bar-americain.html: -------------------------------------------------------------------------------- 1 | {% extends "../templates/base.html" %} 2 | 3 | {% set title = "Prohibition style cocktails at Bar Americain" %} 4 | {% set description = "While Piccadilly Circus bustles above you, you can venture underground to the vast complex of dining hall, cocktail bar and cabaret theatre." %} 5 | 6 | {% block page %} 7 | 8 |
9 | 10 |

Prohibition style cocktails at Bar Americain

11 |

While Piccadilly Circus bustles above you, you can venture underground to the vast complex of dining hall, cocktail bar and cabaret theatre practically underneath the Eros statue. This Art Deco style bar, restaurant and music hall was originally the The Regent Palace Hotel, a trans-atlantic style opulent hotel built in 1915. It was revived in 2004 though restored faithfully. Now you can sip Aviators and Mint Juleps in the aerospace themed bar.

12 |

I first visited this bar after having dinner at Brasserie Zedel, part of the same complex previously the Regent Palace Hotel. I’m a big fan of cocktails and though the concise menu here is great I like to test out bar staff by requesting a few off-menu drinks. The bar staff here are fantastic and clearly know their stuff as no cocktail was too difficult, and they seemingly had every ingredient needed. This is the place to come if you want to enjoy some authentic, classic cocktails!

13 |

Served with every cocktail comes a little enamel tin of lovely chilli-coated popcorn, just the moreish snack to enjoy whilst sipping on whatever concoction you have requested from the tuxedoed barman. The bar is small, so gets densely packed quickly. But with a free cloakroom just across the entrance hall there’s no reason not to stand and wait for a table, or take a seat at the bar and enjoy watching the cocktails being expertly crafted. The whole bar is decorated with wood panelling, featuring inlaid pictures of biplanes, while the original features of the hotel from days past are proudly on display

14 |

While classics such as the Southside and Negroni are always popular, there are some interesting classics on the menu. I’m a fan of the Clover Club, a pre-prohibition cocktail from Philadelphia. Gin, lemon, raspberries, egg white & sugar seems like an odd combination but the sweet and tart raspberries work well with the gin and the raw egg gives a creamy, meringue-like taste. Plus, at Bar Americain you know it’ll be perfectly crafted!

15 |
16 | 17 |

Related Articles

18 |
19 | 20 | 21 |

Art meets Dinner at sketch London

22 |
23 | 24 | 25 |

Stop for a Scoop in Seven Dials

26 |
27 | 28 | 29 |

Roast for breakfast

30 |
31 |
32 | 33 | {% endblock %} 34 | -------------------------------------------------------------------------------- /pages/brunch-at-balthazar.html: -------------------------------------------------------------------------------- 1 | {% extends "../templates/base.html" %} 2 | 3 | {% set title = "Brunch at Balthazar" %} 4 | {% set description = "A New York style French brasserie in the heart of Covent Garden, Balthazar makes a great Saturday morning brunch spot." %} 5 | 6 | {% block page %} 7 | 8 |
9 | 10 |

Brunch at Balthazar

11 |

A New York style French brasserie in the heart of Covent Garden, Balthazar makes a great Saturday morning brunch spot, but be sure to book; with the busy tourist scene and shopping in Covent Garden this place is nearly always full by midday.

12 |

I visited Balthazar in March with a friend for a long, luxury brunch. Having become a fan of other French brasseries in the area, such as The Delaunay and Zedel, Balthazar had been high on my list to visit.

13 |

Housed in the old Royal Opera House Theatre Museum, Balthazar shares “The Flower Cellars” building with The London Film Museum (the permanent flower market was originally built for the Covent Garden flower sellers in 1870 and this space was used for storage).

14 |

Keen to keep in-style with the New York equivalent, founder Keith McNally has kept to the rustic, opulent decor we’ve come to expect of an art deco brasserie look. But what about the food…

15 |

Though the hot lunch dishes coming out to tables all around us looked fantastic, we opted to go for the brunch menu. The menu is concise, typically French but with some interesting surprises thrown in. I opted for the poached egg and avocado on toast, topped with tomato salsa, and was not disappointed. And of course, nobody looks out of place with a glass of mimosa at this stylish brasserie, even if it is 11am! The dish was delicious, perfect size for brunch and just the right size to enjoy over a long catch-up and a glass of mimosa. But there’s always room for pudding. We topped off our main course with a sharing hazlenut waffle dish, drizzled with maple syrup and fresh winter berries.

16 |
17 | 18 |

Related Articles

19 |
20 | 21 | 22 |

Art meets Dinner at sketch London

23 |
24 | 25 | 26 |

Stop for a Scoop in Seven Dials

27 |
28 | 29 | 30 |

Roast for breakfast

31 |
32 |
33 | 34 | {% endblock %} 35 | -------------------------------------------------------------------------------- /pages/dinner-at-bulgari.html: -------------------------------------------------------------------------------- 1 | {% extends "../templates/base.html" %} 2 | 3 | {% set title = "Budget dinner at Bulgari Hotel & Spa" %} 4 | {% set description = "Nothing better than a day out in Seven Dials with a stop for tasty ice-cream." %} 5 | 6 | {% block page %} 7 | 8 |
9 | 10 |

Budget dinner at Bulgari Hotel & Spa

11 |

Yes I did say “budget”. Rivea London is the Alain Ducasse restaurant at Bulgari Hotel in fancy Knightsbridge. If you want to impress someone without crying over the bill, then come here and enjoy the £26 set menu. Just make sure you settle the bill before your guest catches sight of it.

12 |

After a day in London watching Star Wars, four of us prepared to rock up to the Bulgari Hotel, but a quick panic when we realised how fancy this place might be meant a dash around the nearby Zara to buy proper shoes and a nice dress meant we were a little late. Feeling much more acceptable we sat down for the set menu.

13 |

There were plenty of options to choose from even for a small set menu, and no one was disappointed. The sommelier even provided a (probably quite cheap) bottle of wine for the meal, not quite the level of service you’d get from a similar priced meal at Pizza Express.

14 |

The meal even starts with a funny little “condiments test” where you’re given a dish of 9 different flavoursome condiments to enjoy with bread sticks. It was pretty fun trying to work out exactly what each flavour was, and finding your favourite (and then trying to knock your friends off the trail so they didn’t discover the tasty secret. “Try that orange one, this green one is horrible” as you steal all the fresh pesto for yourself).

15 |

The menu changes regularly but it’s a pretty tasty but classic mix of the sort of Italian/French fine dining you might expect of Ducasse. The crab and radish salad, though small, was very tasty indeed and everyone enjoyed a selection of different meat dishes for main. Of course there’s always the mystery of an unheard-of ingredient to try out. But while the food quality was of course excellent, there was nothing spectacular. The interior is exactly the sort of glossy hotel look one would expect from Bulgari and the food is similar – tasty, a bit flashy but really nothing that jumps out at you.

16 |

This would make a great place to bring a friend to impress, but if you want a bit of luxury there are other, more interesting places to eat in London. Maybe the a la carte menu has more to offer.

17 |
18 | 19 |

Related Articles

20 |
21 | 22 | 23 |

Art meets Dinner at sketch London

24 |
25 | 26 | 27 |

Stop for a Scoop in Seven Dials

28 |
29 | 30 | 31 |

Roast for breakfast

32 |
33 |
34 | 35 | {% endblock %} 36 | -------------------------------------------------------------------------------- /pages/index.html: -------------------------------------------------------------------------------- 1 | {% extends "../templates/base.html" %} 2 | 3 | {% set title = "The Daily Spoon" %} 4 | {% set description = "Reviews of London Restaurants" %} 5 | 6 | {% block page %} 7 |

TheDailySpoon

8 |
9 | 10 | 11 |

Art meets Dinner at sketch London

12 |
13 | 14 | 15 |

Prohibition style cocktails at Bar Americain

16 |
17 | 18 | 19 |

Brunch at Balthazar

20 |
21 | 22 | 23 |

Budget dinner at Bulgari Hotel & Spa

24 |
25 | 26 | 27 |

Stop for a Scoop in Seven Dials

28 |
29 | 30 | 31 |

Roast for breakfast

32 |
33 |
34 | {% endblock %} 35 | -------------------------------------------------------------------------------- /pages/roast-for-breakfast.html: -------------------------------------------------------------------------------- 1 | {% extends "../templates/base.html" %} 2 | 3 | {% set title = "Roast for breakfast" %} 4 | {% set description = "Roast, the restaurant above Borough Market famous for it’s Sunday servings now does an amazing breakfast feast." %} 5 | 6 | {% block page %} 7 | 8 |
9 | 10 |

Roast for breakfast

11 |

Not quite a roast beef dinner, but Roast, the restaurant above Borough Market famous for it’s Sunday servings now does an amazing breakfast feast that lives up to their fantastic dinners.

12 |

We went here for Kris’ birthday breakfast as I wanted to surprise him with a nice sit down meal, somewhere that felt a little “fancy” but still offered a tasty full breakfast.

13 |

Bucks fizz of course is always a good idea, especially at birthday brunch. This plus a nice iced coffee went perfectly with the gorgeous breakfast. There are a number of different options, not just full breakfasts, but all use British produce, some purchased from the market that sits just below you.

14 |

Roast is located in the Flower Hall that sits above Borough Market, with glass walls on nearly all sides so you can peer down at the goings-on in the market stalls. It’s a really interesting vantage point.

15 |

But the restaurant, despite it’s location amongst this brash and exciting part of London, is still quite refined. Crisp white tablecloths, smartly dressed waiters and a personal lift up the restaurant, so it’s still somewhere you can get dressed up to visit.

16 |

After seeing the open-plan kitchen and the huge carving blocks I decided this place was definitely worth a visit for dinner, as it did feel a little bit odd going to “Roast” and having breakfast. We booked ourselves in for a dinner straight away, but that’s for another review.

17 |

Oh and if you do fancy sampling the cuisine before you go to roast, they have a small stand in the market just below the restaurant selling roast baguettes, baps and more. Definitely a good option for a late lunch snack but I’d save that for a day when you haven’t filled yourself up on brekkie!

18 |
19 | 20 |

Related Articles

21 |
22 | 23 | 24 |

Art meets Dinner at sketch London

25 |
26 | 27 | 28 |

Stop for a Scoop in Seven Dials

29 |
30 | 31 | 32 |

Roast for breakfast

33 |
34 |
35 | 36 | {% endblock %} 37 | -------------------------------------------------------------------------------- /pages/stop-for-a-scoop.html: -------------------------------------------------------------------------------- 1 | {% extends "../templates/base.html" %} 2 | 3 | {% set title = "Stop for a Scoop in Seven Dials" %} 4 | {% set description = "Nothing better than a day out in Seven Dials with a stop for tasty ice-cream." %} 5 | 6 | {% block page %} 7 | 8 |
9 | 10 |

Stop for a Scoop in Seven Dials

11 |

Nothing better than a day out in Seven Dials with a stop for tasty ice-cream. Scoop, a small Italian gelato and dessert shop sells some of the best ice cream in London, that’s my personal opinion but also one shared with Time Out magazine who rated it 5 stars!

12 |

The orange-fronted cafe is on Shorts Gardens so just nearby to all the shops and bars around the Seven Dials area, perfect for a quick drop-in. And I do seem to find myself dropping in here with friends often, mainly for their gorgeous Amarena gelato (a creamy gelato mixed with a syrupy cherry coulis and crushed sweet cherries. It’s amazing, if you see Amarena anywhere you have got to try it!) Though I’m a big fan of their dulce de leche too.

13 |

I’ve also recently learnt that Scoop is now available on Deliveroo so you can get tasty gelato sent direct to your home or office, or maybe the park for a picnic? It would certainly make for a more interesting delivery if you’re hosting a lunch meeting than boring soggy sandwiches.

14 |

Scoop also sells a range of yummy looking crepe dishes, cakes, coffees and more. Though I must admit I’ve never been able to tear myself away from the ice cream to try any of their other desserts, their coffee is really delicious and much better than some of the highstreet chains nearby. So it’s worth popping in for a quick coffee too.

15 |

There is sometimes a queue at the front of the shop on particularly busy days but don’t let it put you off, it’s still well worth waiting – the ice cream will taste even sweeter.

16 |
17 | 18 |

Related Articles

19 |
20 | 21 | 22 |

Art meets Dinner at sketch London

23 |
24 | 25 | 26 |

Stop for a Scoop in Seven Dials

27 |
28 | 29 | 30 |

Roast for breakfast

31 |
32 |
33 | 34 | {% endblock %} 35 | -------------------------------------------------------------------------------- /scripts/_amp_loader.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | const CONTAINER = document.querySelector('#body'); 19 | let AMP_DOC = null; 20 | let PENDING_REQUEST = null; 21 | 22 | /** 23 | * Fetches an AMP document and inserts it into the CONTAINER element. 24 | * @param {string} url 25 | * @returns {Promise} 26 | */ 27 | export function loadAmpDoc(url) { 28 | // Cancel any pending requests. 29 | let canceled = false; 30 | if (PENDING_REQUEST) { PENDING_REQUEST(); } 31 | PENDING_REQUEST = function() { canceled = true; }; 32 | 33 | // Trigger a custom event to indicate start of navigation. 34 | document.dispatchEvent(new CustomEvent('start-navigate')); 35 | 36 | fetch(url, {credentials: 'include'}) 37 | .then(response => response.text()) 38 | .then(text => { 39 | // Don't proceed if another request was started. 40 | if (canceled) return; 41 | 42 | // Create a new element on which to attach the shadow DOM. 43 | let ampContainer = document.createElement('div'); 44 | 45 | // Parse the AMP document and attach it to the shadow DOM. 46 | let doc = (new DOMParser()).parseFromString(text, 'text/html'); 47 | let ampDoc = window.AMP.attachShadowDoc(ampContainer, doc, url); 48 | 49 | // Find (inside the shadow root, for browsers that support it), 50 | // or (a child node, for browsers without shadow DOM). 51 | let ampShadow = ampContainer.shadowRoot || ampContainer; 52 | let ampBody = ampShadow.querySelector('body, amp-body'); 53 | 54 | // Trigger a custom event, and pass the new AMP body element. 55 | // TODO(plegner) Memory leak when ampBody is deleted! 56 | let event = new CustomEvent('navigate', {detail: {body: ampBody}}); 57 | document.dispatchEvent(event); 58 | 59 | // Close and remove the previous AMP doc. 60 | if (AMP_DOC) AMP_DOC.close(); 61 | CONTAINER.textContent = ''; 62 | window.scrollTo(0, 0); 63 | 64 | // Attach the AMP document and update the page title. 65 | document.title = doc.title || ''; 66 | CONTAINER.appendChild(ampContainer); 67 | AMP_DOC = ampDoc; 68 | }); 69 | } 70 | -------------------------------------------------------------------------------- /scripts/_analytics.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | window.addEventListener('beforeinstallprompt', function(event) { 19 | if (!window.ga) return; 20 | 21 | ga('send', 'event', 'PWA', 'Homescreen banner shown'); 22 | event.userChoice.then(function(choiceResult) { 23 | // choiceResult.outcome is either 'accepted' or 'dismissed'. 24 | ga('send', 'event', 'PWA', 'Homescreen banner ' + choiceResult.outcome); 25 | }); 26 | }); 27 | 28 | // Register sync callback to replay offline analytics when reconnecting. 29 | navigator.serviceWorker.ready.then(function(sw) { 30 | return sw.sync.register('analytics'); 31 | }); 32 | -------------------------------------------------------------------------------- /scripts/_loading_bar.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | const BAR = document.querySelector('#loading-bar'); 19 | const SPEED = 250; 20 | let STATUS = 0; 21 | 22 | function setProgress(n) { 23 | STATUS = n; 24 | 25 | let p = (Math.min(n, 1) - 1) * 100; 26 | BAR.style.transform = 'translate(' + p + '%, 0)'; 27 | BAR.style.transition = 'all ' + SPEED + 'ms linear'; 28 | BAR.offsetWidth; // Repaint! 29 | } 30 | 31 | document.addEventListener('start-navigate', function() { 32 | BAR.style.display = 'block'; 33 | BAR.style.transition = 'all 0 linear'; 34 | BAR.style.transform = 'translateX(-100%)'; 35 | BAR.offsetWidth; // Repaint! 36 | 37 | setProgress(0.1); 38 | 39 | /** 40 | * Slowly increment the progress of the bar, so that users know 41 | * something is happening. 42 | */ 43 | function increment() { 44 | setTimeout(function() { 45 | if (STATUS >= 0.9) return; 46 | setProgress(STATUS + Math.pow(12, 1 - STATUS) / 100); 47 | increment(); 48 | }, SPEED) 49 | } 50 | increment(); 51 | }); 52 | 53 | document.addEventListener('navigate', function() { 54 | BAR.style.opacity = 0; 55 | setProgress(1); 56 | setTimeout(() => { 57 | BAR.style.display = 'none'; 58 | BAR.style.opacity = 1; 59 | }, SPEED); 60 | }); 61 | -------------------------------------------------------------------------------- /scripts/_notifications.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | const WELCOME_NOTIFICATION = { 19 | title: 'You’ll now get notifications!', 20 | body: 'We’ll let you know about latest articles on The Daily Spoon.' + 21 | 'You can unsubscribe any time.', 22 | icon: '/logo-white.png' 23 | }; 24 | 25 | const BANNER_COOKIE = 'hide_notifications'; 26 | const WELCOME_COOKIE = 'welcome_notification'; 27 | const COOKIE_AGE = 60 * 60 * 24 * 30; // 30 days. 28 | 29 | const TOGGLE = document.querySelector('#notifications-toggle'); 30 | const BANNER = document.querySelector('#notifications-banner'); 31 | const ERROR = document.querySelector('#notifications-error'); 32 | 33 | // We only support notifications in Chrome (excluding Chrome on iOS) 34 | const SUPPORTS_NOTIFICATIONS = window.chrome && !window.opr && !window.opera; 35 | 36 | // Only show the banner on second pageview, and if it hasn't been dismissed. 37 | const SHOW_BANNER = document.cookie.indexOf(BANNER_COOKIE) < 0 && 38 | document.referrer && 39 | new URL(document.referrer).origin == location.origin; 40 | 41 | /** 42 | * Gets the GCM id from a subscription object. 43 | * @param {PushSubscription} subscription The subscription object. 44 | * @returns {string} The GCM id. 45 | */ 46 | function getGCMId(subscription) { 47 | var endpointSections = subscription.endpoint.split('/'); 48 | return endpointSections[endpointSections.length - 1]; 49 | } 50 | 51 | 52 | navigator.serviceWorker.ready.then(function(sw) { 53 | // Some old Chrome versions support service workers but no notifications. 54 | if (!sw.pushManager) return; 55 | 56 | let enabled = false; 57 | 58 | // Check if there is an existing subscription. 59 | sw.pushManager.getSubscription({userVisibleOnly: true}).then(function(sub) { 60 | if (sub) { 61 | // Already subscribed, update UI. 62 | TOGGLE.classList.add('enabled'); 63 | enabled = true; 64 | } else if (SHOW_BANNER) { 65 | // Not yet subscribed, show banner after 5 seconds. 66 | setTimeout(function() { 67 | BANNER.classList.add('visible'); 68 | if (window.ga) ga('send', 'event', 'PWA', 'Notifications banner shown'); 69 | }, 5000); 70 | } 71 | }); 72 | 73 | BANNER.querySelector('.primary').addEventListener('click', function() { 74 | if (window.ga) ga('send', 'event', 'PWA', 'Notifications banner accepted'); 75 | subscribe(); 76 | }); 77 | 78 | BANNER.querySelector('.secondary').addEventListener('click', function() { 79 | if (window.ga) ga('send', 'event', 'PWA', 'Notifications banner dismissed'); 80 | hideBanner(); 81 | }); 82 | 83 | TOGGLE.style.display = 'block'; 84 | TOGGLE.addEventListener('click', function() { 85 | if (enabled) { 86 | unsubscribe(); 87 | } else { 88 | subscribe(); 89 | } 90 | }); 91 | 92 | ERROR.querySelector('button').addEventListener('click', function() { 93 | ERROR.classList.remove('visible'); 94 | }); 95 | 96 | /** 97 | * Hides the subscribe to notifications banner and sets a cookie. 98 | */ 99 | function hideBanner() { 100 | document.cookie = BANNER_COOKIE + '=y;max-age=' + COOKIE_AGE + ';path=/'; 101 | BANNER.classList.remove('visible'); 102 | } 103 | 104 | /** 105 | * Subscribe the user to push notifications. 106 | */ 107 | function subscribe() { 108 | enabled = true; 109 | TOGGLE.classList.add('enabled'); 110 | hideBanner(); 111 | 112 | sw.pushManager.subscribe({userVisibleOnly: true}) 113 | .then(sub => fetch('/_/add_subscription/?gcm_id=' + getGCMId(sub))) 114 | .then(function() { 115 | // Send welcome notification. 116 | if (document.cookie.indexOf(WELCOME_COOKIE) >= 0) return; 117 | document.cookie = WELCOME_COOKIE + '=y;max-age=' + 118 | COOKIE_AGE + ';path=/'; 119 | sw.showNotification(WELCOME_NOTIFICATION.title, { 120 | body: WELCOME_NOTIFICATION.body, 121 | icon: WELCOME_NOTIFICATION.icon 122 | }); 123 | }) 124 | .catch(function() { 125 | // User has disabled notifications in their browser. 126 | enabled = false; 127 | TOGGLE.classList.remove('enabled'); 128 | ERROR.classList.add('visible'); 129 | }); 130 | } 131 | 132 | /** 133 | * Unsubscribe the user from push notifications. 134 | */ 135 | function unsubscribe() { 136 | enabled = false; 137 | TOGGLE.classList.remove('enabled'); 138 | hideBanner(); 139 | 140 | sw.pushManager.getSubscription().then(function(sub) { 141 | if (sub) { 142 | sub.unsubscribe(); 143 | fetch('/_/remove_subscription/?gcm_id=' + getGCMId(sub)); 144 | } 145 | }); 146 | } 147 | }); 148 | -------------------------------------------------------------------------------- /scripts/_offline-page.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | document.addEventListener('navigate', function(e) { 19 | 20 | // Show a button that sends a push notification when the page is available. 21 | const notifyButton = document.querySelector('.notify-article'); 22 | if (window.Notification && notifyButton) { 23 | notifyButton.style.display = 'inline-block'; 24 | notifyButton.addEventListener('click', function() { 25 | window.Notification.requestPermission().then(function(result) { 26 | if (result == 'granted') { 27 | navigator.serviceWorker.ready.then(function(sw) { 28 | sw.sync.register('notifyarticle:' + location.pathname); 29 | notifyBtn.textContent = 'Waiting…'; 30 | }); 31 | } 32 | }); 33 | // TODO(plegner) Automatically refresh the page when the article is ready 34 | // and you're still here. 35 | }); 36 | } 37 | 38 | // Show a list of all available articles. 39 | const cachedArticles = document.querySelector('.cached-articles'); 40 | if (cachedArticles) { 41 | window.caches.open('app-cache') 42 | .then(cache => cache.keys()) 43 | .then(urls => { 44 | for (let u of urls.slice(0, 8)) { 45 | // TODO(plegner) Get title and image for every article. 46 | cachedArticles.innerHTML += `Article Title` 47 | } 48 | }); 49 | } 50 | 51 | }); 52 | -------------------------------------------------------------------------------- /scripts/_offline-styling.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | // Note: these events don't work on desktop! 19 | window.addEventListener('online', function() { 20 | document.body.classList.remove('offline'); 21 | }); 22 | 23 | window.addEventListener('offline', function() { 24 | document.body.classList.add('offline'); 25 | }); 26 | 27 | 28 | document.addEventListener('navigate', function(e) { 29 | // Strict equality check for browsers which don't support navigator.onLine. 30 | if (navigator.onLine === false) { 31 | e.detail.body.classList.add('offline', 'offline-initial'); 32 | } 33 | 34 | /** 35 | * Removes the .offline-disable class from links which are cached. 36 | */ 37 | function checkCachedLinks() { 38 | let elements = e.detail.body.querySelectorAll('.offline-disable'); 39 | [].slice.call(elements).forEach(function(el) { 40 | caches.match(el.href).then(function(response) { 41 | if (response) { 42 | el.classList.remove('offline-disable'); 43 | } 44 | }); 45 | }); 46 | } 47 | 48 | window.addEventListener('online', function() { 49 | e.detail.body.classList.remove('offline'); 50 | 51 | // Retry loading all broken images when coming back online. 52 | // Note that this also works for , which creates an child. 53 | e.detail.body.querySelectorAll('img').forEach(function(img) { 54 | img.setAttribute('src', img.src); 55 | }); 56 | }); 57 | 58 | window.addEventListener('offline', function() { 59 | checkCachedLinks(); // Some links might have been cached since last time. 60 | e.detail.body.classList.add('offline'); 61 | }); 62 | 63 | checkCachedLinks(); 64 | 65 | /** 66 | * Prefetch the first five links on the page. 67 | */ 68 | function prefetchLinks() { 69 | console.log('[SW] Prefetch related articles.'); 70 | let links = e.detail.body.querySelectorAll('a.precache'); 71 | for (let i = 0; i < links.length && i < 5; ++i) { 72 | fetch(links[i].href, {credentials: 'include'}); 73 | } 74 | } 75 | 76 | // Prefetch articles when a new service worker claims this page... 77 | navigator.serviceWorker.addEventListener('controllerchange', prefetchLinks); 78 | 79 | // ... or if there already is an activated service worker. 80 | navigator.serviceWorker.ready.then(function(registration) { 81 | if (registration.active) prefetchLinks(); 82 | }); 83 | 84 | }); 85 | -------------------------------------------------------------------------------- /scripts/_refresh.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import {loadAmpDoc} from './_amp_loader'; 19 | 20 | const BANNER = document.querySelector('#refresh-banner'); 21 | const REFRESH_BUTTON = BANNER.querySelector('button'); 22 | 23 | // Show a banner that notifies users if they are viewing an outdated page, 24 | // and allows them to refresh the page. 25 | navigator.serviceWorker.addEventListener('message', function(event) { 26 | console.log('[SW] Client received message:' + event.data); 27 | if (event.data == 'sw-backgroundsync') { 28 | BANNER.classList.add('visible'); 29 | } 30 | }); 31 | 32 | REFRESH_BUTTON.addEventListener('click', function() { 33 | BANNER.classList.remove('visible'); 34 | loadAmpDoc(window.location); 35 | }); 36 | -------------------------------------------------------------------------------- /scripts/app_shell.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import {loadAmpDoc} from './_amp_loader'; 19 | import './_analytics'; 20 | import './_loading_bar'; 21 | import './_notifications'; 22 | import './_offline-page'; 23 | import './_offline-styling'; 24 | import './_refresh'; 25 | 26 | 27 | /** 28 | * Event handler for click events on , to intercept all link clicks. 29 | * @param e 30 | */ 31 | function interceptLinkClick(e) { 32 | if (e.defaultPrevented || e.button) return; 33 | if (e.metaKey) return; 34 | 35 | let a = event.target; 36 | while (a && (a.tagName != 'A' || !a.href)) { 37 | a = a.parentElement; 38 | } 39 | if (!a) return; 40 | 41 | if (new URL(a.href).origin === window.location.origin) { 42 | console.debug('[PWAMP] Intercept click:', a.href); 43 | e.preventDefault(); 44 | window.history.pushState(null, '', a.href); 45 | loadAmpDoc(a.href); 46 | } 47 | } 48 | 49 | document.addEventListener('DOMContentLoaded', function() { 50 | loadAmpDoc(window.location); 51 | }); 52 | 53 | window.addEventListener('popstate', function() { 54 | console.debug('[PWAMP] Popstate:', window.location.pathname); 55 | loadAmpDoc(window.location); 56 | }); 57 | 58 | document.addEventListener('navigate', function(e) { 59 | e.detail.body.addEventListener('click', interceptLinkClick); 60 | }); 61 | document.body.addEventListener('click', interceptLinkClick); 62 | -------------------------------------------------------------------------------- /service_worker/_analytics.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import RequestStore from './_request_store'; 19 | import {parseQueryString} from './_utilities'; 20 | 21 | const GA_HOST = 'www.google-analytics.com'; 22 | const GA_COLLECT_PATH = '/collect'; 23 | const ANALYTICS_STORE = new RequestStore('analytics-store', 1); 24 | 25 | /** 26 | * If users visit the site while offline, we trigger this additional GA event, 27 | * to track the number of offline pageviews. 28 | */ 29 | const OFFLINE_EVENT_URL = `https://www.google-analytics.com/collect?v=1&t=event&ex=SetIsOffline&ea=Yes&ni=1`; 30 | 31 | 32 | /** 33 | * Gets modified GA URL with queueTime GET parameter. 34 | * @param {string} url The original GA request URL. 35 | * @param {number} time UNIX timestamp of the original request, in ms. 36 | * @returns {Promise} The URL to report the event, including the queue time. 37 | */ 38 | function getDelayedUrl(url, time) { 39 | let newUrl = new URL(url); 40 | let queueTime = Date.now() - time; 41 | newUrl.search += (newUrl.search ? '&' : '?') + 'qt=' + queueTime; 42 | return newUrl.href; 43 | } 44 | 45 | /** 46 | * Replays stored Google Analytics requests. 47 | * @returns {Promise} 48 | */ 49 | function replayGARequest() { 50 | return ANALYTICS_STORE.getAll().then(requests => { 51 | let promise = Promise.resolve(); 52 | for (let url of Object.keys(requests)) { 53 | promise = promise.then(() => { 54 | let requestUrl = getDelayedUrl(url, requests[url]); 55 | console.log('Replaying Google Analytics request:', requestUrl); 56 | return fetch(requestUrl).then(() => ANALYTICS_STORE.remove(url)); 57 | }); 58 | } 59 | return promise; 60 | }); 61 | } 62 | 63 | /** 64 | * Replay GA events immediately, and when receiving sync.offlineAnalytics event. 65 | */ 66 | replayGARequest(); 67 | self.addEventListener('sync', function(event) { 68 | if (event.tag == 'analytics') { 69 | console.log('[SW] Handle sync event: analytics'); 70 | return event.waitUntil(replayGARequest()); 71 | } 72 | }); 73 | 74 | self.addEventListener('fetch', function(event) { 75 | let url = new URL(event.request.url); 76 | let queryParams = parseQueryString(url.search); 77 | 78 | // Only intercept requests to Google Analytics. 79 | if (url.hostname != GA_HOST || url.pathname != GA_COLLECT_PATH) return; 80 | 81 | // Make the request, or store it in our cache if it fails. 82 | return event.respondWith(fetch(event.request).catch(() => { 83 | console.log('[SW] Adding GA call to IDB:', url.href); 84 | ANALYTICS_STORE.add(url.href); 85 | 86 | // For pageview events, also add a new custom 'SetIsGPOffline' event. 87 | if (queryParams.t == 'pageview') { 88 | let queryString = `&cid=${queryParams.cid}&tid=${queryParams.tic}`; 89 | ANALYTICS_STORE.add(OFFLINE_EVENT_URL + queryString); 90 | } 91 | })); 92 | }); 93 | -------------------------------------------------------------------------------- /service_worker/_notifications.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import { loadCacheFirst } from './_utilities'; 19 | 20 | const LATEST_ARTICLE = '/_/latest_article'; 21 | 22 | 23 | /** 24 | * For simplicity, we send notifications without payload. That means we need to 25 | * get the notification data (from NOTIFICATIONS_PAGE), before we can show 26 | * anything. We also precache the article before showing a notification. 27 | */ 28 | self.addEventListener('push', function(event) { 29 | event.waitUntil(self.registration.pushManager.getSubscription() 30 | .then(() => fetch(LATEST_ARTICLE)) 31 | .then(response => response.json()) 32 | .then(notification => { 33 | return loadCacheFirst(notification.url) 34 | .then(() => self.registration.showNotification(notification.title, { 35 | body: notification.body, 36 | icon: notification.icon, 37 | data: {url: notification.url} 38 | })); 39 | })); 40 | }); 41 | 42 | /** 43 | * When clicking a notification, we need to manually close it and open the link. 44 | */ 45 | self.addEventListener('notificationclick', function(event) { 46 | event.notification.close(); 47 | event.waitUntil(clients.openWindow(event.notification.data.url)); 48 | }); 49 | -------------------------------------------------------------------------------- /service_worker/_request_store.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | export default class RequestStore { 19 | 20 | /** 21 | * @param {string} name Name of the IndexedDB. 22 | * @param {number} version Version of the IndexedDB. 23 | */ 24 | constructor(name, version) { 25 | this.name = name; 26 | this.version = version; 27 | this.store = 'store'; 28 | this.db = null; 29 | } 30 | 31 | /** 32 | * Returns instance of IndexedDB database. The result is cached. 33 | * @private 34 | * @returns {Promise} 35 | */ 36 | getDB_() { 37 | return new Promise((resolve, reject) => { 38 | 39 | // Use cached instance if available. 40 | if (this.db) resolve(this.db); 41 | 42 | // Open (and create, if necessary) IDBDatabase. 43 | let request = indexedDB.open(this.name, this.version); 44 | request.onupgradeneeded = (event => { 45 | let db = event.target.result; 46 | let objectStore = db.createObjectStore(this.store, {keyPath: 'url'}); 47 | objectStore.createIndex('time', 'time', {unique: false}); 48 | }); 49 | 50 | request.onsuccess = (event => { 51 | this.db = event.target.result; 52 | resolve(this.db); 53 | }); 54 | 55 | request.onerror = reject; 56 | }); 57 | } 58 | 59 | /** 60 | * Helper function to initialise an objectStore transaction. 61 | * @private 62 | * @param {Function} fn which takes objectStore as an argument and returns 63 | * the final value with which the promise should be resolved. 64 | * @returns {Promise} 65 | */ 66 | transaction_(fn) { 67 | return this.getDB_().then(db => { 68 | return new Promise((resolve, reject) => { 69 | let transaction = db.transaction([this.store], 'readwrite'); 70 | let objectStore = transaction.objectStore(this.store); 71 | let response = fn(objectStore); 72 | transaction.oncomplete = function(e) { resolve(response || e); }; 73 | transaction.onerror = reject; 74 | }); 75 | }); 76 | } 77 | 78 | /** 79 | * Helper function to initialise and loop over an objectStore cursor. 80 | * @private 81 | * @param {IDBObjectStore} objectStore for which to create a cursor. 82 | * @param {Function} fn which is called for every item in the object store. 83 | */ 84 | cursor_(objectStore, fn) { 85 | objectStore.openCursor().onsuccess = (event => { 86 | let cursor = event.target.result; 87 | if (cursor) { 88 | fn(cursor.value); 89 | cursor.continue(); 90 | } 91 | }); 92 | } 93 | 94 | /** 95 | * @param {string} url A new URL to be added to the IDB store. 96 | * @returns {Promise} 97 | */ 98 | add(url) { 99 | return this.transaction_(objectStore => { 100 | objectStore.put({url, time: Date.now()}); 101 | }); 102 | } 103 | 104 | /** 105 | * @param {string} url A URL to be removed from the IDB store. 106 | * @returns {Promise} 107 | */ 108 | remove(url) { 109 | return this.transaction_(objectStore => { objectStore.delete(url); }); 110 | } 111 | 112 | /** 113 | * @returns {Promise} Retrieves all urls currently in the IDB store. 114 | */ 115 | getAll() { 116 | return this.transaction_(objectStore => { 117 | let urls = {}; 118 | this.cursor_(objectStore, obj => { urls[obj.url] = obj.time; }); 119 | return urls; 120 | }); 121 | } 122 | 123 | /** 124 | * Removes all URLs currently in the IDB store. 125 | * @returns {Promise} 126 | */ 127 | removeAll() { 128 | return this.transaction_(objectStore => { 129 | this.cursor_(objectStore, obj => { objectStore.delete(obj.url); }); 130 | }); 131 | } 132 | 133 | /** 134 | * Removes all URLs which are older than a specified time. 135 | * @param {number} maxAge 136 | * @returns {Promise} that resolves with a list of URLs that were removed. 137 | */ 138 | expireOldEntries(maxAge) { 139 | return this.transaction_(objectStore => { 140 | let now = Date.now(); 141 | let urls = []; 142 | 143 | let index = objectStore.index('time'); 144 | this.cursor_(index, obj => { 145 | if (now - maxAge > obj.time) { 146 | urls.push(obj.url); 147 | objectStore.delete(obj.url); 148 | } 149 | }); 150 | 151 | return urls; 152 | }); 153 | } 154 | 155 | /** 156 | * Limits the total number of URLs stored in IDB. 157 | * @param {number} maxEntries 158 | * @returns {Promise} that resolves with a list of URLs that were removed. 159 | */ 160 | expireExtraEntries(maxEntries) { 161 | return this.transaction_(objectStore => { 162 | let urls = []; 163 | 164 | let index = objectStore.index('time'); 165 | let countRequest = index.count(); 166 | countRequest.onsuccess = () => { 167 | let initialCount = countRequest.result; 168 | 169 | this.cursor_(index, obj => { 170 | if (initialCount - urls.length > maxEntries) { 171 | urls.push(obj.url); 172 | objectStore.delete(obj.url); 173 | } 174 | }); 175 | }; 176 | 177 | return urls; 178 | }); 179 | } 180 | 181 | } 182 | -------------------------------------------------------------------------------- /service_worker/_utilities.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import RequestStore from './_request_store' 19 | 20 | const CACHE_NAME = 'app-cache'; 21 | const CACHE_STORE = new RequestStore(CACHE_NAME, 1); 22 | const CACHE_MAX_AGE = 60 * 60 * 24 * 60; // 60 days. 23 | const CACHE_MAX_ENTRIES = 120; 24 | 25 | 26 | /** 27 | * Parses query string of URL. This is needed because URL.searchParams is not 28 | * supported by many browsers. 29 | * @param {string} search The query string of the URL, with leading '?'. 30 | * @returns {object} The URL query parameters and values. 31 | */ 32 | export function parseQueryString(search) { 33 | let queryParams = {}; 34 | for (let paramString of search.substring(1).split('&')) { 35 | let [key, ...values] = paramString.split('='); 36 | queryParams[key] = decodeURIComponent(values.join('=')); 37 | } 38 | return queryParams; 39 | } 40 | 41 | /** 42 | * Removes UTM tracking params from a URL. This is necessary to prevent these 43 | * parameters from poisoning the cache. 44 | * @param {string} urlStr 45 | * @returns {string} The url, with tracking parameters removed. 46 | */ 47 | function removeTrackingParams(urlStr) { 48 | let url = new URL(urlStr, self.location); 49 | url.search = url.search 50 | .slice(1) // Skip leading '?'. 51 | .split('&') 52 | .filter(q => q && !q.startsWith('utm_')) 53 | .join('&'); 54 | return url.href; 55 | } 56 | 57 | /** 58 | * @param {string} url 59 | * @returns {Promise} Whether the URL has been cached. 60 | */ 61 | function findInCache(url) { 62 | url = removeTrackingParams(url); 63 | return caches.open(CACHE_NAME).then(cache => cache.match(url)); 64 | } 65 | 66 | /** 67 | * Asynchronously compares two responses, and sends a message to all clients 68 | * that are currently showing an outdated version (e.g. to display a warning). 69 | * @param {string} url 70 | * @param {Response} oldResponse 71 | * @param {Response} newResponse 72 | */ 73 | function updateClients(url, oldResponse, newResponse) { 74 | let textPromises = [oldResponse, newResponse].map(r => r.clone().text()); 75 | Promise.all(textPromises).then(texts => { 76 | if (texts[0] != texts[1]) { 77 | self.clients.matchAll().then(clients => { 78 | clients.forEach(client => { 79 | if (client.url == url) { 80 | client.postMessage('sw-backgroundsync'); 81 | } 82 | }); 83 | }); 84 | } 85 | }); 86 | } 87 | 88 | /** 89 | * Adds a new response into the cache, and update all active clients that are 90 | * currently displaying an old version of the page. 91 | * @param {string} url 92 | * @param {Response} response 93 | * @returns {Promise} 94 | */ 95 | function addToCache(url, response) { 96 | CACHE_STORE.add(url).then(() => cleanupCache()); 97 | return caches.open(CACHE_NAME).then(cache => { 98 | return cache.match(url).then(oldResponse => { 99 | if (oldResponse) updateClients(url, oldResponse, response); 100 | console.log('[SW] Add to cache', url); 101 | return cache.put(url, response); 102 | }); 103 | }); 104 | } 105 | 106 | /** 107 | * Replacement for cache.add that includes credentials, only caches 108 | * successful responses, and performs additional cleanup. 109 | * @param {string} url 110 | * @returns {Promise} 111 | */ 112 | export function fetchAndCache(url) { 113 | url = removeTrackingParams(url); 114 | return fetch(url, {credentials: 'include'}).then(response => { 115 | if (response.status === 200) addToCache(url, response); 116 | return response.clone(); 117 | }); 118 | } 119 | 120 | /** 121 | * Fetches an external asset from NO-CORS domains, and adds it to the cache, 122 | * if it wasn't already cached. Note that no-cors mode means the response is 123 | * `opaque`, so that we can't check its status code. 124 | * @param {string} url to fetch and cache. 125 | * @returns {Promise} 126 | */ 127 | export function loadExternalCacheFirst(url) { 128 | let options = {credentials: 'include', mode: 'no-cors'}; 129 | return findInCache(url).then(asset => { 130 | return asset || fetch(url, options).then(response => { 131 | console.log('[SW] Add to cache', url); 132 | caches.open(CACHE_NAME).then(cache => cache.put(url, response)); 133 | }); 134 | }); 135 | } 136 | 137 | /** 138 | * Returns a url from cache, or fetches and adds it if it isn't there yet. 139 | * @param {string} url to load from cache. 140 | * @returns {Promise} 141 | */ 142 | export function loadCacheFirst(url) { 143 | return findInCache(url).then(response => response || fetchAndCache(url)); 144 | } 145 | 146 | /** 147 | * Returns an url from cache and updates it in the background (or fetches and 148 | * adds it to the cache if it doesn't already exist). 149 | * @param {string} url 150 | * @returns {Promise} 151 | */ 152 | export function loadCacheFirstAndUpdate(url) { 153 | let fromNetwork = fetchAndCache(url); 154 | return findInCache(url).then(fromCache => fromCache || fromNetwork); 155 | } 156 | 157 | /** 158 | * Asynchronously deletes all previous cache instances. 159 | */ 160 | export function removeOldCaches() { 161 | self.caches.keys().then(cacheNames => cacheNames.forEach(cacheName => { 162 | if (cacheName !== CACHE_NAME) { 163 | console.log('[SW] Delete old cache', cacheName); 164 | caches.open(cacheName).then(cache => cache.keys().then(urlsToDelete => { 165 | return Promise.all(urlsToDelete.map(url => CACHE_STORE.remove(url))); 166 | }).then(() => self.caches.delete(cacheName))); 167 | } 168 | })); 169 | } 170 | 171 | /** 172 | * Removes old and too many items from the IDB cache store and the app cache. 173 | * @return {Promise} 174 | */ 175 | function cleanupCache() { 176 | return caches.open(CACHE_NAME).then(cache => { 177 | return CACHE_STORE.expireOldEntries(CACHE_MAX_AGE) 178 | .then(urlsToDelete => Promise.all(urlsToDelete.map(cache.delete))) 179 | .then(() => CACHE_STORE.expireExtraEntries(CACHE_MAX_ENTRIES)) 180 | .then(urlsToDelete => Promise.all(urlsToDelete.map(cache.delete))) 181 | }); 182 | } 183 | -------------------------------------------------------------------------------- /service_worker/service_worker.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import './_notifications'; 19 | import './_analytics'; 20 | import { 21 | fetchAndCache, 22 | loadExternalCacheFirst, 23 | loadCacheFirst, 24 | loadCacheFirstAndUpdate, 25 | removeOldCaches 26 | } from './_utilities'; 27 | 28 | const APP_SHELL_PAGE = '/_/app_shell'; 29 | const OFFLINE_PAGE = '/_/offline/'; 30 | const PRECACHE = ['/', OFFLINE_PAGE]; 31 | 32 | 33 | self.addEventListener('install', function(event) { 34 | console.log('[SW] Install service worker.'); 35 | 36 | // Activate the service worker as soon as the app shell page is cached. 37 | event.waitUntil(loadCacheFirst(APP_SHELL_PAGE).then(() => { 38 | self.skipWaiting(); 39 | })); 40 | 41 | // Precache/update a few other non-essential urls asynchronously. 42 | PRECACHE.forEach(path => loadCacheFirst(path)); 43 | }); 44 | 45 | 46 | self.addEventListener('activate', function(event) { 47 | console.log('[SW] Activate service worker.'); 48 | 49 | // Activate the service worker and claim all open windows. 50 | let activationPromise = self.clients.claim(); 51 | event.waitUntil(activationPromise); 52 | 53 | // Precache the content of all open windows. It might not yet be in our cache, 54 | // if the window were opened before the service worker was installed. 55 | activationPromise.then(() => self.clients.matchAll().then(clients => { 56 | clients.forEach(client => { 57 | loadCacheFirst(client.url); 58 | }); 59 | })); 60 | 61 | // Remove all previous cache versions. 62 | removeOldCaches(); 63 | }); 64 | 65 | self.addEventListener('fetch', function(event) { 66 | let url = new URL(event.request.url); 67 | 68 | // We only intercept GET requests to the current domain.. 69 | if (event.request.method != 'GET' || url.host != location.host) return; 70 | 71 | // We don't certain intercept internal requests. 72 | if (url.pathname.startsWith('/_/')) return; 73 | 74 | // For AMP navigation requests, return the app shell but immediately start 75 | // loading/updating the requested cached page in the background. 76 | if (event.request.mode == 'navigate') { 77 | fetchAndCache(url.href); 78 | return event.respondWith(loadCacheFirst(APP_SHELL_PAGE)); 79 | } 80 | 81 | // These should only be AJAX requests made by the app shell. We immediately 82 | // return them from cache, if possible, and show the offline page as fallback. 83 | // We need to ensure that the offline page is returned with an error code. 84 | event.respondWith(loadCacheFirstAndUpdate(url.href) 85 | .catch(() => loadCacheFirst(OFFLINE_PAGE) 86 | .then(response => response.clone().text()) 87 | .then(text => new Response(text, { 88 | ok: false, 89 | status: 503, 90 | headers: {'content-type': 'text/html'} 91 | })) 92 | ) 93 | ); 94 | }); 95 | 96 | self.addEventListener('sync', function(event) { 97 | let [name, data] = event.tag.split(':'); 98 | if (name == 'notifyarticle') { 99 | console.log('[SW] Handle sync event:', event.tag); 100 | return event.waitUntil(fetchAndCache(data).then(function() { 101 | // TODO(plegner) Get article title, body and thumbnail for notification. 102 | self.registration.showNotification('Your article is ready!', { 103 | body: 'Body', 104 | icon: 'Icon', 105 | data: {url: location.origin + data} 106 | }); 107 | })); 108 | } 109 | }); 110 | -------------------------------------------------------------------------------- /static/icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/amp-pwa-demo/ba4dea5385d29ce32e858c4015f80db903d56980/static/icon-192.png -------------------------------------------------------------------------------- /static/logo-white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/amp-pwa-demo/ba4dea5385d29ce32e858c4015f80db903d56980/static/logo-white.png -------------------------------------------------------------------------------- /static/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "The Daily Spoon", 3 | "short_name": "DailySpoon", 4 | "icons": [{ 5 | "src": "/icon-192.png", 6 | "sizes": "192x192", 7 | "type": "image/png" 8 | }], 9 | "start_url": "/?homescreen=1", 10 | "display": "standalone", 11 | "background_color": "#3E4EB8", 12 | "theme_color": "#2F3BA2" 13 | } 14 | -------------------------------------------------------------------------------- /styles/_notifications.scss: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | #notifications-toggle { 19 | background: url('data:image/svg+xml,') no-repeat 10px 10px; 20 | cursor: pointer; 21 | display: none; // Overridden in JS if service workers are available. 22 | float: right; 23 | height: 44px; 24 | width: 44px; 25 | 26 | &.enabled { 27 | background-image: url('data:image/svg+xml,'); 28 | } 29 | } 30 | 31 | #notifications-banner, 32 | #notifications-error { 33 | background: white; 34 | bottom: 0; 35 | box-shadow: 0 0 20px 3px rgba(#000, .22); 36 | font-family: Roboto, sans-serif; 37 | left: 50%; 38 | max-width: 500px; 39 | padding: 16px; 40 | position: fixed; 41 | right: 0; 42 | text-align: right; 43 | transform: translate(-50%, calc(100% + 20px)); 44 | transition: padding .3s, transform .3s; 45 | width: 100%; 46 | z-index: 100; 47 | 48 | p { 49 | text-align: left; 50 | margin: 0 0 16px; 51 | } 52 | 53 | button { 54 | $action-color: #4285f5; 55 | 56 | background: transparent; 57 | border: 0; 58 | border-radius: 2px; 59 | color: $action-color; 60 | display: inline-block; 61 | font-family: inherit; 62 | font-weight: bold; 63 | height: 2.5em; 64 | padding: 0 1.5em; 65 | text-transform: uppercase; 66 | 67 | &.primary { 68 | background: $action-color; 69 | color: white; 70 | } 71 | } 72 | } 73 | 74 | html:not(.offline) #notifications-banner.visible, 75 | #notifications-error.visible { 76 | transform: translate(-50%, 0); 77 | } 78 | -------------------------------------------------------------------------------- /styles/_shared.scss: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | html, body { 19 | font-family: "Open Sans", Roboto, sans-serif; 20 | font-size: 16px; 21 | line-height: 1.6; 22 | margin: 0; 23 | } 24 | 25 | // This class is applied by if Open Sans doesn't load within 2s. 26 | .fonts-error { 27 | font-family: Roboto, sans-serif; 28 | } 29 | 30 | header { 31 | background: #fa5742; 32 | height: 44px; 33 | position: fixed; 34 | top: 0; 35 | width: 100%; 36 | z-index: 10; 37 | } 38 | 39 | .header-body { 40 | margin: 0 auto; 41 | max-width: 720px; 42 | width: 90%; 43 | } 44 | 45 | .logo { 46 | background: url('/logo-white.png') no-repeat 0 8px; 47 | background-size: 28px 28px; 48 | color: white; 49 | display: block; 50 | float: left; 51 | font-size: 20px; 52 | line-height: 44px; 53 | padding-left: 38px; 54 | text-decoration: none; 55 | } 56 | -------------------------------------------------------------------------------- /styles/app_shell.scss: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | @import 'shared'; 19 | @import 'notifications'; 20 | 21 | 22 | #refresh-banner { 23 | background-color: rgba(black, 90%); 24 | color: white; 25 | left: 0; 26 | padding: 8px 0; 27 | position: fixed; 28 | right: 0; 29 | text-align: center; 30 | top: 100vh; 31 | transition: transform .3s; 32 | z-index: 9999; 33 | 34 | button { 35 | background: rgba(white, 20%); 36 | border: 0; 37 | border-radius: 2px; 38 | color: black; 39 | cursor: pointer; 40 | font-size: 1em; 41 | margin-left: 12px; 42 | padding: 6px 12px; 43 | } 44 | 45 | &.visible { 46 | transform: translateY(-100%); 47 | } 48 | } 49 | 50 | #loading-bar { 51 | $bar-color: #4285f5; 52 | 53 | background: $bar-color; 54 | display: none; 55 | height: 3px; 56 | left: 0; 57 | position: fixed; 58 | top: 0; 59 | width: 100%; 60 | will-change: transform; 61 | z-index: 9999; 62 | 63 | &::after { 64 | content: ""; 65 | display: block; 66 | width: 120px; 67 | height: 3px; 68 | float: right; 69 | box-shadow: 0 0 8px 2px $bar-color; 70 | transform: rotate(3deg); 71 | transform-origin: right top; 72 | } 73 | } 74 | 75 | #offline-banner { 76 | background-color: #fff; 77 | bottom: 0; 78 | box-shadow: 0 0 2px rgba(#000, .14); 79 | color: #000; 80 | font-size: .75rem; 81 | left: 0; 82 | padding: 3px 0; 83 | position: fixed; 84 | right: 0; 85 | text-align: center; 86 | text-transform: uppercase; 87 | transition: transform .3s; 88 | transform: translateY(calc(100% + 2px)); 89 | z-index: 9999; 90 | 91 | .offline & { 92 | transform: none; 93 | } 94 | } 95 | 96 | .offline .offline-disable { 97 | -webkit-filter: grayscale(1); 98 | opacity: .38; 99 | pointer-events: none; 100 | } 101 | -------------------------------------------------------------------------------- /styles/core.scss: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | @import 'shared'; 19 | 20 | // The header is already added by the app shell, so we hide it in the shadow. 21 | .amp-shadow header { 22 | display: none; 23 | } 24 | 25 | main { 26 | margin: 120px auto; 27 | max-width: 90%; 28 | width: 720px; 29 | } 30 | 31 | amp-img { 32 | background: #eee; // Light grey placeholder for missing/loading images. 33 | } 34 | 35 | button { 36 | background: #fa5742; 37 | border: 0; 38 | border-radius: 2px; 39 | color: white; 40 | font-family: inherit; 41 | font-weight: bold; 42 | height: 2.5em; 43 | padding: 0 1.5em; 44 | } 45 | 46 | .other-articles { 47 | color: #fa5742; 48 | font-size: 20px; 49 | text-align: center; 50 | } 51 | 52 | .article-grid { 53 | display: flex; 54 | flex-wrap: wrap; 55 | justify-content: space-between; 56 | margin: -12px; 57 | } 58 | 59 | .article-grid a { 60 | padding: 12px; 61 | width: 220px; 62 | text-decoration: none; 63 | transition: opacity .1s; 64 | } 65 | 66 | .article-grid:hover a:not(:hover) { 67 | opacity: 0.5; 68 | } 69 | 70 | .article-grid h2 { 71 | color: black; 72 | font-size: 16px; 73 | } 74 | -------------------------------------------------------------------------------- /templates/app_shell.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | The Daily Spoon 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 | 21 |
22 |
23 |
24 | 25 |
26 | 27 |
28 |
Offline
29 |
30 | A new version of this page is available. 31 | 32 |
33 | 34 |
35 |

Would you like to get notifications for the latest articles and updates?

36 | 37 | 38 |
39 |
40 |

It appears that notifications are blocked for this site. Please check your browser settings.

41 | 42 |
43 | 44 | 45 | 46 | 47 | 48 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | {{ title }} 7 | 8 | 9 | 10 | 11 | {# Colours and Icons -#} 12 | 13 | 14 | 15 | 16 | {# iOS Web App Configuration -#} 17 | 18 | 19 | 20 | 21 | 22 | {# AMP Scripts -#} 23 | 24 | 25 | 26 | 27 | 28 | {# Share Metadata -#} 29 | 30 | 31 | 32 | 33 | 34 | 35 | {# TODO(plegner) AMP Structured Data -#} 36 | 37 | {# Fonts #} 38 | 39 | 40 | 41 | {# Styles -#} 42 | 43 | 44 | 45 | 46 | 47 | 48 | 61 | 62 |
63 |
{% block page %}{% endblock %}
64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /templates/install_serviceworker.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Install Service Worker 4 | 9 | -------------------------------------------------------------------------------- /templates/offline.html: -------------------------------------------------------------------------------- 1 | {% extends "../templates/base.html" %} 2 | 3 | {% set title = "The Daily Spoon" %} 4 | {% set description = "Reviews of London Restaurants" %} 5 | 6 | {% block page %} 7 |

You’re offline :(

8 |

Connect to the internet to view this page. We can also download it in the background and notify you when it is available.

9 | 10 | 11 |

Cached articles

12 |
13 | {% endblock %} 14 | --------------------------------------------------------------------------------