[devdocsgjs: 1/2] Backport upstream's service worker changes




commit 21708f248fdd9f65a9537a5872445a456927bf5d
Author: FeRD (Frank Dana) <ferdnyc gmail com>
Date:   Sat Oct 30 23:34:25 2021 +0000

    Backport upstream's service worker changes

 .gitignore                                         |   1 +
 Dockerfile                                         |   1 +
 Dockerfile-alpine                                  |   1 +
 Gemfile                                            |   9 ++-
 Gemfile.lock                                       |  20 +++--
 README.md                                          |  10 +--
 assets/javascripts/app/app.coffee                  |  19 +++--
 assets/javascripts/app/appcache.coffee             |  42 -----------
 assets/javascripts/app/config.coffee.erb           |   2 +
 assets/javascripts/app/serviceworker.coffee        |  49 +++++++++++++
 assets/javascripts/app/settings.coffee             |  33 +++++++++
 assets/javascripts/app/update_checker.coffee       |   6 +-
 assets/javascripts/lib/page.coffee                 |  20 ++++-
 assets/javascripts/models/doc.coffee               |   4 +-
 assets/javascripts/news.json                       |   4 +
 assets/javascripts/templates/error_tmpl.coffee     |  10 +--
 assets/javascripts/templates/notif_tmpl.coffee     |   6 ++
 .../javascripts/templates/pages/about_tmpl.coffee  |   3 +-
 .../templates/pages/offline_tmpl.coffee            |  13 +++-
 .../templates/pages/root_tmpl.coffee.erb           |   2 +-
 .../templates/pages/settings_tmpl.coffee           |   8 ++
 assets/javascripts/tracking.js                     |  50 +++++++------
 assets/javascripts/views/content/entry_page.coffee |   2 +-
 .../javascripts/views/content/settings_page.coffee |  21 +++---
 assets/javascripts/views/layout/document.coffee    |  12 +--
 assets/javascripts/views/layout/resizer.coffee     |  11 +--
 assets/javascripts/views/layout/settings.coffee    |  10 +--
 assets/stylesheets/application.css.scss            |   3 +-
 .../stylesheets/components/_environment.scss.erb   |   3 +
 assets/stylesheets/components/_notif.scss          |   4 +
 docs/maintainers.md                                |   2 +-
 lib/app.rb                                         |  52 ++++++++-----
 public/images/webapp-icon-192.png                  | Bin 0 -> 32187 bytes
 public/manifest.json                               |   6 ++
 test/app_test.rb                                   |  81 ---------------------
 views/app.erb                                      |  14 +---
 views/index.erb                                    |   5 +-
 views/manifest.erb                                 |  14 ----
 views/other.erb                                    |   5 +-
 views/service-worker.js.erb                        |  61 ++++++++++++++++
 views/unsupported.erb                              |   6 +-
 41 files changed, 351 insertions(+), 274 deletions(-)
---
diff --git a/.gitignore b/.gitignore
index 1060fcf0..f89ecb61 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
 .DS_Store
 .bundle
+log
 tmp
 public/assets
 public/fonts
diff --git a/Dockerfile b/Dockerfile
index 71ef52b1..596630bb 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -122,6 +122,7 @@ RUN for docset in appindicator301 appstreamglib10 atk10 atspi20 cairo10 \
 FROM docker.io/library/ruby:2.7.3-alpine
 
 ENV LANG=C.UTF-8
+ENV ENABLE_SERVICE_WORKER=true
 
 WORKDIR /devdocs
 
diff --git a/Dockerfile-alpine b/Dockerfile-alpine
index 5bd25afe..a5d993f7 100644
--- a/Dockerfile-alpine
+++ b/Dockerfile-alpine
@@ -1,6 +1,7 @@
 FROM ruby:2.6.0-alpine
 
 ENV LANG=C.UTF-8
+ENV ENABLE_SERVICE_WORKER=true
 
 WORKDIR /devdocs
 
diff --git a/Gemfile b/Gemfile
index cfa12ef2..95c0154d 100644
--- a/Gemfile
+++ b/Gemfile
@@ -3,12 +3,13 @@ ruby '2.7.3'
 
 gem 'rake'
 gem 'thor'
-gem 'pry', '~> 0.12.0'
+gem 'pry', '~> 0.14.0'
 gem 'activesupport', '~> 5.2', require: false
 gem 'yajl-ruby', require: false
 gem 'html-pipeline'
 gem 'typhoeus'
 gem 'nokogiri'
+gem 'terminal-table'
 
 group :app do
   gem 'rack'
@@ -22,6 +23,10 @@ group :app do
   gem 'browser'
   gem 'sass'
   gem 'coffee-script'
+  gem 'chunky_png'
+  gem 'sprockets-sass'
+  gem 'image_optim'
+  gem 'image_optim_pack', platforms: :ruby
 end
 
 group :production do
@@ -34,8 +39,6 @@ group :development do
 end
 
 group :docs do
-  gem 'image_optim'
-  gem 'image_optim_pack', platforms: :ruby
   gem 'progress_bar', require: false
   gem 'unix_utils', require: false
   gem 'tty-pager', require: false
diff --git a/Gemfile.lock b/Gemfile.lock
index f2b6710b..5b91e436 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -12,6 +12,7 @@ GEM
       erubi (>= 1.0.0)
       rack (>= 0.9.0)
     browser (2.5.3)
+    chunky_png (1.4.0)
     coderay (1.1.2)
     coffee-script (2.4.1)
       coffee-script-source
@@ -44,7 +45,7 @@ GEM
       image_optim (~> 0.19)
     image_size (2.0.0)
     in_threads (1.5.1)
-    method_source (0.9.2)
+    method_source (1.0.0)
     mini_portile2 (2.4.0)
     minitest (5.14.1)
     multi_json (1.13.1)
@@ -60,9 +61,9 @@ GEM
     progress_bar (1.3.0)
       highline (>= 1.6, < 3)
       options (~> 2.3.0)
-    pry (0.12.2)
-      coderay (~> 1.1.0)
-      method_source (~> 0.9.0)
+    pry (0.14.1)
+      coderay (~> 1.1)
+      method_source (~> 1.0)
     rack (2.2.3)
     rack-protection (2.0.5)
       rack
@@ -96,11 +97,15 @@ GEM
       rack (> 1, < 3)
     sprockets-helpers (1.2.1)
       sprockets (>= 2.2)
+    sprockets-sass (2.0.0.beta2)
+      sprockets (>= 2.0, < 4.0)
     strings (0.1.4)
       strings-ansi (~> 0.1.0)
       unicode-display_width (~> 1.4.0)
       unicode_utils (~> 1.4.0)
     strings-ansi (0.1.0)
+    terminal-table (3.0.2)
+      unicode-display_width (>= 1.1.1, < 3)
     thin (1.7.2)
       daemons (~> 1.0, >= 1.0.9)
       eventmachine (~> 1.0, >= 1.0.4)
@@ -133,6 +138,7 @@ DEPENDENCIES
   activesupport (~> 5.2)
   better_errors
   browser
+  chunky_png
   coffee-script
   erubi
   html-pipeline
@@ -143,7 +149,7 @@ DEPENDENCIES
   newrelic_rpm
   nokogiri
   progress_bar
-  pry (~> 0.12.0)
+  pry (~> 0.14.0)
   rack
   rack-ssl-enforcer
   rack-test
@@ -154,6 +160,8 @@ DEPENDENCIES
   sinatra-contrib
   sprockets
   sprockets-helpers
+  sprockets-sass
+  terminal-table
   thin
   thor
   tty-pager
@@ -164,7 +172,7 @@ DEPENDENCIES
   yajl-ruby
 
 RUBY VERSION
-   ruby 2.7.1p83
+   ruby 2.7.3p183
 
 BUNDLED WITH
    2.1.4
diff --git a/README.md b/README.md
index 81cb546e..cba762e8 100644
--- a/README.md
+++ b/README.md
@@ -73,14 +73,14 @@ The web app is all client-side JavaScript, written in [CoffeeScript](http://coff
 
 Many of the code's design decisions were driven by the fact that the app uses XHR to load content directly 
into the main frame. This includes stripping the original documents of most of their HTML markup (e.g. 
scripts and stylesheets) to avoid polluting the main frame, and prefixing all CSS class names with an 
underscore to prevent conflicts.
 
-Another driving factor is performance and the fact that everything happens in the browser. 
`applicationCache` (which comes with its own set of constraints) and `localStorage` are used to speed up the 
boot time, while memory consumption is kept in check by allowing the user to pick his/her own set of 
documentations. The search algorithm is kept simple because it needs to be fast even searching through 
100,000 strings.
+Another driving factor is performance and the fact that everything happens in the browser. A service worker 
(which comes with its own set of constraints) and `localStorage` are used to speed up the boot time, while 
memory consumption is kept in check by allowing the user to pick his/her own set of documentations. The 
search algorithm is kept simple because it needs to be fast even searching through 100,000 strings.
 
 DevDocs being a developer tool, the browser requirements are high:
 
 * Recent versions of Firefox, Chrome, or Opera
-* Safari 9.1+
-* Edge 16+
-* iOS 10+
+* Safari 11.1+
+* Edge 17+
+* iOS 11.3+
 
 This allows the code to take advantage of the latest DOM and HTML5 APIs and make developing DevDocs a lot 
more fun!
 
@@ -172,7 +172,7 @@ DevDocs's own documentation is available on the [wiki](https://github.com/freeCo
 * [Doc Browser](https://github.com/qwfy/doc-browser) is a native Linux app that supports DevDocs docsets
 * [GNOME Application](https://github.com/hardpixel/devdocs-desktop) GTK3 application with search integrated 
in headerbar
 * [macOS Application](https://github.com/dteoh/devdocs-macos)
-* [Android Application](https://github.com/Merith-TK/devdocs_webapp_kotlin) is a fully working, advanced 
WebView with AppCache enabled
+* [Android Application](https://github.com/Merith-TK/devdocs_webapp_kotlin) is a fully working, advanced 
WebView
 
 ## Copyright / License
 
diff --git a/assets/javascripts/app/app.coffee b/assets/javascripts/app/app.coffee
index ab67a92a..62e7b6b6 100644
--- a/assets/javascripts/app/app.coffee
+++ b/assets/javascripts/app/app.coffee
@@ -13,10 +13,12 @@
 
     @el = $('._app')
     @localStorage = new LocalStorageStore
-    @appCache = new app.AppCache if app.AppCache.isEnabled()
+    @serviceWorker = new app.ServiceWorker if app.ServiceWorker.isEnabled()
     @settings = new app.Settings
     @db = new app.DB()
 
+    @settings.initLayout()
+
     @docs = new app.collections.Docs
     @disabledDocs = new app.collections.Docs
     @entries = new app.collections.Entries
@@ -138,7 +140,10 @@
       @docs.sort()
       @initDoc(doc)
       @saveDocs()
-      _onSuccess()
+      if app.settings.get('autoInstall')
+        doc.install(_onSuccess, onError)
+      else
+        _onSuccess()
       return
 
     doc.load onSuccess, onError, writeCache: true
@@ -147,7 +152,7 @@
   saveDocs: ->
     @settings.setDocs(doc.slug for doc in @docs.all())
     @db.migrate()
-    @appCache?.updateInBackground()
+    @serviceWorker?.updateInBackground()
 
   welcomeBack: ->
     visitCount = @settings.get('count')
@@ -167,14 +172,14 @@
   reload: ->
     @docs.clearCache()
     @disabledDocs.clearCache()
-    if @appCache then @appCache.reload() else @reboot()
+    if @serviceWorker then @serviceWorker.reload() else @reboot()
     return
 
   reset: ->
     @localStorage.reset()
     @settings.reset()
     @db?.reset()
-    @appCache?.update()
+    @serviceWorker?.update()
     window.location = '/'
     return
 
@@ -193,9 +198,9 @@
     return
 
   indexHost: ->
-    # Can't load the index files from the host/CDN when applicationCache is
+    # Can't load the index files from the host/CDN when service worker is
     # enabled because it doesn't support caching URLs that use CORS.
-    @config[if @appCache and @settings.hasDocs() then 'index_path' else 'docs_origin']
+    @config[if @serviceWorker and @settings.hasDocs() then 'index_path' else 'docs_origin']
 
   onBootError: (args...) ->
     @trigger 'bootError'
diff --git a/assets/javascripts/app/config.coffee.erb b/assets/javascripts/app/config.coffee.erb
index ec26b697..dba368e0 100644
--- a/assets/javascripts/app/config.coffee.erb
+++ b/assets/javascripts/app/config.coffee.erb
@@ -13,3 +13,5 @@ app.config =
   version: <%= Time.now.to_i %>
   release: <%= Time.now.utc.httpdate.to_json %>
   mathml_stylesheet: '<%= App.cdn_origin %>/mathml.css'
+  service_worker_path: '/service-worker.js'
+  service_worker_enabled: <%= App.environment == :production || ENV['ENABLE_SERVICE_WORKER'] == 'true' %>
diff --git a/assets/javascripts/app/serviceworker.coffee b/assets/javascripts/app/serviceworker.coffee
new file mode 100644
index 00000000..40235566
--- /dev/null
+++ b/assets/javascripts/app/serviceworker.coffee
@@ -0,0 +1,49 @@
+class app.ServiceWorker
+  $.extend @prototype, Events
+
+  @isEnabled: ->
+    !!navigator.serviceWorker and app.config.service_worker_enabled
+
+  constructor: ->
+    @registration = null
+    @notifyUpdate = true
+
+    navigator.serviceWorker.register(app.config.service_worker_path, {scope: '/'})
+      .then(
+        (registration) => @updateRegistration(registration),
+        (error) -> console.error('Could not register service worker:', error)
+      )
+
+  update: ->
+    return unless @registration
+    @notifyUpdate = true
+    return @registration.update().catch(->)
+
+  updateInBackground: ->
+    return unless @registration
+    @notifyUpdate = false
+    return @registration.update().catch(->)
+
+  reload: ->
+    return @updateInBackground().then(() -> app.reboot())
+
+  updateRegistration: (registration) ->
+    @registration = registration
+    $.on @registration, 'updatefound', @onUpdateFound
+    return
+
+  onUpdateFound: =>
+    $.off @installingRegistration, 'statechange', @onStateChange() if @installingRegistration
+    @installingRegistration = @registration.installing
+    $.on @installingRegistration, 'statechange', @onStateChange
+    return
+
+  onStateChange: =>
+    if @installingRegistration and @installingRegistration.state == 'installed' and 
navigator.serviceWorker.controller
+      @installingRegistration = null
+      @onUpdateReady()
+    return
+
+  onUpdateReady: ->
+    @trigger 'updateready' if @notifyUpdate
+    return
diff --git a/assets/javascripts/app/settings.coffee b/assets/javascripts/app/settings.coffee
index 8d309c41..b2734dfe 100644
--- a/assets/javascripts/app/settings.coffee
+++ b/assets/javascripts/app/settings.coffee
@@ -5,11 +5,13 @@ class app.Settings
     'manualUpdate'
     'fastScroll'
     'arrowScroll'
+    'analyticsConsent'
     'docs'
     'dark'
     'layout'
     'size'
     'tips'
+    'autoInstall'
   ]
 
   INTERNAL_KEYS = [
@@ -19,6 +21,8 @@ class app.Settings
     'news'
   ]
 
+  LAYOUTS: ['_max-width', '_sidebar-hidden', '_native-scrollbars']
+
   @defaults:
     count: 0
     hideDisabled: false
@@ -26,6 +30,7 @@ class app.Settings
     news: 0
     manualUpdate: false
     schema: 1
+    analyticsConsent: false
 
   constructor: ->
     @store = new CookieStore
@@ -38,6 +43,7 @@ class app.Settings
   set: (key, value) ->
     @store.set(key, value)
     delete @cache[key]
+    @toggleDark(value) if key == 'dark'
     return
 
   del: (key) ->
@@ -63,6 +69,8 @@ class app.Settings
     return
 
   setLayout: (name, enable) ->
+    @toggleLayout(name, enable)
+
     layout = (@store.get('layout') || '').split(' ')
     $.arrayDelete(layout, '')
 
@@ -104,3 +112,28 @@ class app.Settings
     @store.reset()
     @cache = {}
     return
+
+  initLayout: ->
+    @toggleDark(@get('dark') is 1)
+    @toggleLayout(layout, @hasLayout(layout)) for layout in @LAYOUTS
+    @initSidebarWidth()
+    return
+
+  toggleDark: (enable) ->
+    classList = document.documentElement.classList
+    classList.toggle('_theme-default', !enable)
+    classList.toggle('_theme-dark', enable)
+    color = getComputedStyle(document.documentElement).getPropertyValue('--headerBackground').trim()
+    $('meta[name=theme-color]').setAttribute('content', color)
+    return
+
+  toggleLayout: (layout, enable) ->
+    classList = document.body.classList
+    classList.toggle(layout, enable) unless layout is '_sidebar-hidden'
+    classList.toggle('_overlay-scrollbars', $.overlayScrollbarsEnabled())
+    return
+
+  initSidebarWidth: ->
+    size = @get('size')
+    document.documentElement.style.setProperty('--sidebarWidth', size + 'px') if size
+    return
diff --git a/assets/javascripts/app/update_checker.coffee b/assets/javascripts/app/update_checker.coffee
index 5630b488..3558d6bc 100644
--- a/assets/javascripts/app/update_checker.coffee
+++ b/assets/javascripts/app/update_checker.coffee
@@ -3,13 +3,13 @@ class app.UpdateChecker
     @lastCheck = Date.now()
 
     $.on window, 'focus', @onFocus
-    app.appCache.on 'updateready', @onUpdateReady if app.appCache
+    app.serviceWorker?.on 'updateready', @onUpdateReady
 
     setTimeout @checkDocs, 0
 
   check: ->
-    if app.appCache
-      app.appCache.update()
+    if app.serviceWorker
+      app.serviceWorker.update()
     else
       ajax
         url: $('script[src*="application"]').getAttribute('src')
diff --git a/assets/javascripts/lib/page.coffee b/assets/javascripts/lib/page.coffee
index 5d3f6c88..7a5329f6 100644
--- a/assets/javascripts/lib/page.coffee
+++ b/assets/javascripts/lib/page.coffee
@@ -199,5 +199,23 @@ page.track = (fn) ->
   return
 
 track = ->
-  tracker.call() for tracker in trackers
+  return unless app.config.env == 'production'
+
+  consentGiven = Cookies.get('analyticsConsent')
+  consentAsked = Cookies.get('analyticsConsentAsked')
+
+  if consentGiven == '1'
+    tracker.call() for tracker in trackers
+  else if consentGiven == undefined and consentAsked == undefined
+    # Only ask for consent once per browser session
+    Cookies.set('analyticsConsentAsked', '1')
+
+    new app.views.Notif 'AnalyticsConsent', autoHide: null
+  return
+
+@resetAnalytics = ->
+  for cookie in document.cookie.split(/;\s?/)
+    name = cookie.split('=')[0]
+    if name[0] == '_' && name[1] != '_'
+      Cookies.expire(name)
   return
diff --git a/assets/javascripts/models/doc.coffee b/assets/javascripts/models/doc.coffee
index 2d5f7e4a..c51e13fa 100644
--- a/assets/javascripts/models/doc.coffee
+++ b/assets/javascripts/models/doc.coffee
@@ -142,4 +142,6 @@ class app.models.Doc extends app.Model
     return
 
   isOutdated: (status) ->
-    status and status.installed and @mtime isnt status.mtime
+    return false if not status
+    isInstalled = status.installed or app.settings.get('autoInstall')
+    isInstalled and @mtime isnt status.mtime
diff --git a/assets/javascripts/news.json b/assets/javascripts/news.json
index 32da738e..13a8329e 100644
--- a/assets/javascripts/news.json
+++ b/assets/javascripts/news.json
@@ -1,4 +1,8 @@
 [
+  [
+    "2021-10-29",
+    "Applied upstream changes to replace the AppCache with a Service Worker (which makes DevDocsGJS an 
installable PWA) and fixe layout preferences on Firefox."
+  ],
   [
     "2018-09-23",
     "New documentations: <a href=\"/puppeteer/\">Puppeteer</a> and <a 
href=\"/handlebars/\">Handlebars.js</a>"
diff --git a/assets/javascripts/templates/error_tmpl.coffee b/assets/javascripts/templates/error_tmpl.coffee
index c4bf40ec..9cca1f9d 100644
--- a/assets/javascripts/templates/error_tmpl.coffee
+++ b/assets/javascripts/templates/error_tmpl.coffee
@@ -12,8 +12,8 @@ app.templates.notFoundPage = ->
 
 app.templates.pageLoadError = ->
   error """ The page failed to load. """,
-        """ It may be missing from the server (try reloading the app) or you could be offline.<br>
-            If you keep seeing this, you're likely behind a proxy or firewall that blocks cross-domain 
requests. """,
+        """ It may be missing from the server (try reloading the app) or you could be offline (try <a 
href="/offline">installing the documentation for offline usage</a> when online again).<br>
+            If you're online and you keep seeing this, you're likely behind a proxy or firewall that blocks 
cross-domain requests. """,
         """ #{back} &middot; <a href="/##{location.pathname}" target="_top" class="_error-link">Reload</a>
             &middot; <a href="#" class="_error-link" data-retry>Retry</a> """
 
@@ -57,9 +57,9 @@ app.templates.unsupportedBrowser = """
     <p class="_fail-text">DevDocs is an API documentation browser which supports the following browsers:
     <ul class="_fail-list">
       <li>Recent versions of Firefox, Chrome, or Opera
-      <li>Safari 9.1+
-      <li>Edge 16+
-      <li>iOS 10+
+      <li>Safari 11.1+
+      <li>Edge 17+
+      <li>iOS 11.3+
     </ul>
     <p class="_fail-text">
       If you're unable to upgrade, we apologize.
diff --git a/assets/javascripts/templates/notif_tmpl.coffee b/assets/javascripts/templates/notif_tmpl.coffee
index 93611a5c..0821036e 100644
--- a/assets/javascripts/templates/notif_tmpl.coffee
+++ b/assets/javascripts/templates/notif_tmpl.coffee
@@ -68,3 +68,9 @@ app.templates.notifShare = ->
 app.templates.notifUpdateDocs = ->
   textNotif """ Documentation updates available. """,
             """ <a href="/offline">Install them</a> as soon as possible to avoid broken pages. """
+
+app.templates.notifAnalyticsConsent = ->
+  textNotif """ Tracking cookies """,
+            """ We would like to gather usage data about how DevDocs is used through Google Analytics and 
Gauges. We only collect anonymous traffic information.
+                 Please confirm if you accept our tracking cookies. You can always change your decision in 
the settings.
+                 <br><span class="_notif-right"><a href="#" data-behavior="accept-analytics">Accept</a> or 
<a href="#" data-behavior="decline-analytics">Decline</a></span> """
diff --git a/assets/javascripts/templates/pages/about_tmpl.coffee 
b/assets/javascripts/templates/pages/about_tmpl.coffee
index 48e00d3a..2b2dc5b6 100644
--- a/assets/javascripts/templates/pages/about_tmpl.coffee
+++ b/assets/javascripts/templates/pages/about_tmpl.coffee
@@ -81,7 +81,8 @@ app.templates.aboutPage = -> """
   <ul>
     <li><a href="https://devdocs.io";>devdocs.io</a> ("App") is operated by <a 
href="https://www.freecodecamp.org/";>freeCodeCamp</a> ("We").
     <li>We do not collect personal information through the app.
-    <li>We use Google Analytics, Gauges and Sentry to collect anonymous traffic information and improve the 
app.
+    <li>We use Google Analytics and Gauges to collect anonymous traffic information if you have given 
consent to this. You can change your decision in the <a href="/settings">settings</a>.
+    <li>We use Sentry to collect crash data and improve the app.
     <li>The app uses cookies to store user preferences.
     <li>By using the app, you signify your acceptance of this policy. If you do not agree to this policy, 
please do not use the app.
     <li>If you have any questions regarding privacy, please email <a href="mailto:privacy freecodecamp 
org">privacy freecodecamp org</a>.
diff --git a/assets/javascripts/templates/pages/offline_tmpl.coffee 
b/assets/javascripts/templates/pages/offline_tmpl.coffee
index a9a3c21c..bb9e06e8 100644
--- a/assets/javascripts/templates/pages/offline_tmpl.coffee
+++ b/assets/javascripts/templates/pages/offline_tmpl.coffee
@@ -25,8 +25,8 @@ app.templates.offlinePage = (docs) -> """
   <h2 class="_block-heading">Questions & Answers</h2>
   <dl>
     <dt>How does this work?
-    <dd>Each page is cached as a key-value pair in <a 
href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API";>IndexedDB</a> (downloaded from a single 
file).<br>
-        The app also uses <a 
href="https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache";>AppCache</a> and <a 
href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API";>localStorage</a> to cache the assets 
and index files.
+    <dd>Each page is cached as a key-value pair in <a 
href="https://devdocs.io/dom/indexeddb_api";>IndexedDB</a> (downloaded from a single file).<br>
+        The app also uses <a href="https://devdocs.io/dom/service_worker_api/using_service_workers";>Service 
Workers</a> and <a href="https://devdocs.io/dom/web_storage_api";>localStorage</a> to cache the assets and 
index files.
     <dt>Can I close the tab/browser?
     <dd>#{canICloseTheTab()}
     <dt>What if I don't update a documentation?
@@ -41,10 +41,15 @@ app.templates.offlinePage = (docs) -> """
 """
 
 canICloseTheTab = ->
-  if app.AppCache.isEnabled()
+  if app.ServiceWorker.isEnabled()
     """ Yes! Even offline, you can open a new tab, go to <a href="//devdocs.io">devdocs.io</a>, and 
everything will work as if you were online (provided you installed all the documentations you want to use 
beforehand). """
   else
-    """ No. AppCache isn't available in your browser (or is disabled), so loading <a 
href="//devdocs.io">devdocs.io</a> offline won't work.<br>
+    reason = "aren't available in your browser (or are disabled)"
+
+    if app.config.env != 'production'
+      reason = "are disabled in your development instance of DevDocs (enable them by setting the 
<code>ENABLE_SERVICE_WORKER</code> environment variable to <code>true</code>)"
+
+    """ No. Service Workers #{reason}, so loading <a href="//devdocs.io">devdocs.io</a> offline won't 
work.<br>
         The current tab will continue to function even when you go offline (provided you installed all the 
documentations beforehand). """
 
 app.templates.offlineDoc = (doc, status) ->
diff --git a/assets/javascripts/templates/pages/root_tmpl.coffee.erb 
b/assets/javascripts/templates/pages/root_tmpl.coffee.erb
index 286ddda3..af3d4f47 100644
--- a/assets/javascripts/templates/pages/root_tmpl.coffee.erb
+++ b/assets/javascripts/templates/pages/root_tmpl.coffee.erb
@@ -10,7 +10,7 @@ app.templates.intro = """
     <p>Thanks for downloading DevDocs. Here are a few things you should know:
     <ol class="_intro-list">
       <li>Your local version of DevDocs won't self-update. Unless you're modifying the code,
-          I&nbsp;recommend using the hosted version at <a href="https://devdocs.io";>devdocs.io</a>.
+          we&nbsp;recommend using the hosted version at <a href="https://devdocs.io";>devdocs.io</a>.
       <li>Run <code>thor docs:list</code> to see all available documentations.
       <li>Run <code>thor docs:download &lt;name&gt;</code> to download documentations.
       <li>Run <code>thor docs:download --installed</code> to update all downloaded documentations.
diff --git a/assets/javascripts/templates/pages/settings_tmpl.coffee 
b/assets/javascripts/templates/pages/settings_tmpl.coffee
index 1d439edb..d5cb0985 100644
--- a/assets/javascripts/templates/pages/settings_tmpl.coffee
+++ b/assets/javascripts/templates/pages/settings_tmpl.coffee
@@ -15,6 +15,14 @@ app.templates.settingsPage = (settings) -> """
         <input type="checkbox" form="settings" name="layout" value="_sidebar-hidden"#{if 
settings['_sidebar-hidden'] then ' checked' else ''}>Automatically hide and show the sidebar
         <small>Tip: drag the edge of the sidebar to resize it.</small>
       </label>
+      <label class="_settings-label">
+        <input type="checkbox" form="settings" name="autoInstall" value="_auto-install"#{if 
settings.autoInstall then ' checked' else ''}>Automatically download documentation for offline use
+        <small>Only enable this when bandwidth isn't a concern to you.</small>
+      </label>
+      <label class="_settings-label _hide-in-development">
+        <input type="checkbox" form="settings" name="analyticsConsent"#{if settings.analyticsConsent then ' 
checked' else ''}>Enable tracking cookies
+        <small>With this checked, we enable Google Analytics and Gauges to collect anonymous traffic 
information.</small>
+      </label>
     </div>
   </div>
 
diff --git a/assets/javascripts/tracking.js b/assets/javascripts/tracking.js
index ca05b218..10bc4127 100644
--- a/assets/javascripts/tracking.js
+++ b/assets/javascripts/tracking.js
@@ -1,28 +1,32 @@
 try {
-  if (app.config.env == 'production') {
-    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
-    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
-    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
-    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
-    ga('create', 'UA-5544833-12', 'devdocs.io');
-    page.track(function() {
-      ga('send', 'pageview', {
-        page: location.pathname + location.search + location.hash,
-        dimension1: app.router.context && app.router.context.doc && 
app.router.context.doc.slug_without_version
+  if (app.config.env === 'development') {
+    if (Cookies.get('analyticsConsent') === '1') {
+      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
+        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
+        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
+      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
+      ga('create', 'UA-5544833-12', 'devdocs.io');
+      page.track(function() {
+        ga('send', 'pageview', {
+          page: location.pathname + location.search + location.hash,
+          dimension1: app.router.context && app.router.context.doc && 
app.router.context.doc.slug_without_version
+        });
       });
-    });
 
-    page.track(function() {
-      if (window._gauges)
-        _gauges.push(['track']);
-      else
-        (function() {
-          var _gauges=_gauges||[];!function(){var a=document.createElement("script");
-          a.type="text/javascript",a.async=!0,a.id="gauges-tracker",
-          a.setAttribute("data-site-id","51c15f82613f5d7819000067"),
-          a.src="https://secure.gaug.es/track.js";var b=document.getElementsByTagName("script")[0];
-          b.parentNode.insertBefore(a,b)}();
-        })();
-    });
+      page.track(function() {
+        if (window._gauges)
+          _gauges.push(['track']);
+        else
+          (function() {
+            var _gauges=_gauges||[];!function(){var a=document.createElement("script");
+              a.type="text/javascript",a.async=!0,a.id="gauges-tracker",
+                a.setAttribute("data-site-id","51c15f82613f5d7819000067"),
+                a.src="https://secure.gaug.es/track.js";var b=document.getElementsByTagName("script")[0];
+              b.parentNode.insertBefore(a,b)}();
+          })();
+      });
+    } else {
+      resetAnalytics();
+    }
   }
 } catch(e) { }
diff --git a/assets/javascripts/views/content/entry_page.coffee 
b/assets/javascripts/views/content/entry_page.coffee
index beae4d77..d11291a3 100644
--- a/assets/javascripts/views/content/entry_page.coffee
+++ b/assets/javascripts/views/content/entry_page.coffee
@@ -123,7 +123,7 @@ class app.views.EntryPage extends app.View
     @render @tmpl('pageLoadError')
     @resetClass()
     @addClass @constructor.errorClass
-    app.appCache?.update()
+    app.serviceWorker?.update()
     return
 
   cache: ->
diff --git a/assets/javascripts/views/content/settings_page.coffee 
b/assets/javascripts/views/content/settings_page.coffee
index e39b17df..9ca606c6 100644
--- a/assets/javascripts/views/content/settings_page.coffee
+++ b/assets/javascripts/views/content/settings_page.coffee
@@ -1,7 +1,4 @@
 class app.views.SettingsPage extends app.View
-  LAYOUTS = ['_max-width', '_sidebar-hidden', '_native-scrollbars']
-  SIDEBAR_HIDDEN_LAYOUT = '_sidebar-hidden'
-
   @className: '_static'
 
   @events:
@@ -17,31 +14,31 @@ class app.views.SettingsPage extends app.View
     settings.dark = app.settings.get('dark')
     settings.smoothScroll = !app.settings.get('fastScroll')
     settings.arrowScroll = app.settings.get('arrowScroll')
-    settings[layout] = app.settings.hasLayout(layout) for layout in LAYOUTS
+    settings.autoInstall = app.settings.get('autoInstall')
+    settings.analyticsConsent = app.settings.get('analyticsConsent')
+    settings[layout] = app.settings.hasLayout(layout) for layout in app.settings.LAYOUTS
     settings
 
   getTitle: ->
     'Preferences'
 
   toggleDark: (enable) ->
-    html = document.documentElement
-    html.classList.toggle('_theme-default')
-    html.classList.toggle('_theme-dark')
     app.settings.set('dark', !!enable)
-    app.appCache?.updateInBackground()
     return
 
   toggleLayout: (layout, enable) ->
-    document.body.classList[if enable then 'add' else 'remove'](layout) unless layout is 
SIDEBAR_HIDDEN_LAYOUT
-    document.body.classList[if $.overlayScrollbarsEnabled() then 'add' else 'remove']('_overlay-scrollbars')
     app.settings.setLayout(layout, enable)
-    app.appCache?.updateInBackground()
     return
 
   toggleSmoothScroll: (enable) ->
     app.settings.set('fastScroll', !enable)
     return
 
+  toggleAnalyticsConsent: (enable) ->
+    app.settings.set('analyticsConsent', if enable then '1' else '0')
+    resetAnalytics() unless enable
+    return
+
   toggle: (name, enable) ->
     app.settings.set(name, enable)
     return
@@ -85,6 +82,8 @@ class app.views.SettingsPage extends app.View
         @toggleSmoothScroll input.checked
       when 'import'
         @import input.files[0], input
+      when 'analyticsConsent'
+        @toggleAnalyticsConsent input.checked
       else
         @toggle input.name, input.checked
     return
diff --git a/assets/javascripts/views/layout/document.coffee b/assets/javascripts/views/layout/document.coffee
index e3e2f5a7..c61c8441 100644
--- a/assets/javascripts/views/layout/document.coffee
+++ b/assets/javascripts/views/layout/document.coffee
@@ -75,9 +75,11 @@ class app.views.Document extends app.View
     return unless target.hasAttribute('data-behavior')
     $.stopEvent(event)
     switch target.getAttribute('data-behavior')
-      when 'back'         then history.back()
-      when 'reload'       then window.location.reload()
-      when 'reboot'       then app.reboot()
-      when 'hard-reload'  then app.reload()
-      when 'reset'        then app.reset() if confirm('Are you sure you want to reset DevDocs?')
+      when 'back'               then history.back()
+      when 'reload'             then window.location.reload()
+      when 'reboot'             then app.reboot()
+      when 'hard-reload'        then app.reload()
+      when 'reset'              then app.reset() if confirm('Are you sure you want to reset DevDocs?')
+      when 'accept-analytics'   then Cookies.set('analyticsConsent', '1') && app.reboot()
+      when 'decline-analytics'  then Cookies.set('analyticsConsent', '0') && app.reboot()
     return
diff --git a/assets/javascripts/views/layout/resizer.coffee b/assets/javascripts/views/layout/resizer.coffee
index 86bb46f5..5584bfbe 100644
--- a/assets/javascripts/views/layout/resizer.coffee
+++ b/assets/javascripts/views/layout/resizer.coffee
@@ -11,9 +11,6 @@ class app.views.Resizer extends app.View
   init: ->
     @el.setAttribute('draggable', 'true')
     @appendTo $('._app')
-
-    @style = $('style[data-resizer]')
-    @size = @style.getAttribute('data-size')
     return
 
   MIN = 260
@@ -24,15 +21,11 @@ class app.views.Resizer extends app.View
     return unless value > 0
     value = Math.min(Math.max(Math.round(value), MIN), MAX)
     newSize = "#{value}px"
-    @style.innerHTML = @style.innerHTML.replace(new RegExp(@size, 'g'), newSize)
-    @size = newSize
-    if save
-      app.settings.setSize(value)
-      app.appCache?.updateInBackground()
+    document.documentElement.style.setProperty('--sidebarWidth', newSize)
+    app.settings.setSize(value) if save
     return
 
   onDragStart: (event) =>
-    @style.removeAttribute('disabled')
     event.dataTransfer.effectAllowed = 'link'
     event.dataTransfer.setData('Text', '')
     $.on(window, 'dragover', @onDrag)
diff --git a/assets/javascripts/views/layout/settings.coffee b/assets/javascripts/views/layout/settings.coffee
index 7888118a..6941b9cd 100644
--- a/assets/javascripts/views/layout/settings.coffee
+++ b/assets/javascripts/views/layout/settings.coffee
@@ -25,7 +25,6 @@ class app.views.Settings extends app.View
     if super
       @render()
       document.body.classList.remove(SIDEBAR_HIDDEN_LAYOUT)
-      app.appCache?.on 'progress', @onAppCacheProgress
     return
 
   deactivate: ->
@@ -33,7 +32,6 @@ class app.views.Settings extends app.View
       @resetClass()
       @docPicker.detach()
       document.body.classList.add(SIDEBAR_HIDDEN_LAYOUT) if app.settings.hasLayout(SIDEBAR_HIDDEN_LAYOUT)
-      app.appCache?.off 'progress', @onAppCacheProgress
     return
 
   render: ->
@@ -52,7 +50,7 @@ class app.views.Settings extends app.View
         docs = @docPicker.getSelectedDocs()
         app.settings.setDocs(docs)
 
-      @saveBtn.textContent = if app.appCache then 'Downloading\u2026' else 'Saving\u2026'
+      @saveBtn.textContent = 'Saving\u2026'
       disabledDocs = new app.collections.Docs(doc for doc in app.docs.all() when docs.indexOf(doc.slug) is 
-1)
       disabledDocs.uninstall ->
         app.db.migrate()
@@ -83,9 +81,3 @@ class app.views.Settings extends app.View
       $.stopEvent(event)
       app.router.show '/'
     return
-
-  onAppCacheProgress: (event) =>
-    if event.lengthComputable
-      percentage = Math.round event.loaded * 100 / event.total
-      @saveBtn.textContent = "Downloading\u2026 (#{percentage}%)"
-    return
diff --git a/assets/stylesheets/application.css.scss b/assets/stylesheets/application.css.scss
index dc8e4041..3c47a142 100644
--- a/assets/stylesheets/application.css.scss
+++ b/assets/stylesheets/application.css.scss
@@ -30,7 +30,8 @@
         'components/path',
         'components/notice',
         'components/prism',
-        'components/mobile';
+        'components/mobile',
+        'components/environment';
 
 @import 'pages/simple',
         'pages/angular',
diff --git a/assets/stylesheets/components/_environment.scss.erb 
b/assets/stylesheets/components/_environment.scss.erb
new file mode 100644
index 00000000..5e2201c3
--- /dev/null
+++ b/assets/stylesheets/components/_environment.scss.erb
@@ -0,0 +1,3 @@
+._hide-in-development {
+  <%= App.environment != :production ? 'display: none;' : '' %>
+}
diff --git a/assets/stylesheets/components/_notif.scss b/assets/stylesheets/components/_notif.scss
index dd23c43a..f0880fdd 100644
--- a/assets/stylesheets/components/_notif.scss
+++ b/assets/stylesheets/components/_notif.scss
@@ -134,3 +134,7 @@
 
   ._notif-info { color: var(--textColorLight); }
 }
+
+._notif-right {
+  float: right;
+}
diff --git a/docs/maintainers.md b/docs/maintainers.md
index d994a0fd..357f0b94 100644
--- a/docs/maintainers.md
+++ b/docs/maintainers.md
@@ -84,7 +84,7 @@ In addition to the [publicly-documented commands](https://github.com/freeCodeCam
 
 Once docs have been uploaded via `thor docs:upload` (if applicable), deploying DevDocs is as simple as 
running `git push heroku master`. See [Heroku's documentation](https://devcenter.heroku.com/articles/git) for 
more information.
 
-- If you're deploying documentation updates, verify that the documentations work properly once the deploy is 
done (you will need to reload [devdocs.io](https://devdocs.io/) a couple times for the application cache to 
update and the new version to load).
+- If you're deploying documentation updates, verify that the documentations work properly once the deploy is 
done. Keep in mind that you'll need to wait a few seconds for the service worker to finish caching the new 
assets. You should see a "DevDocs has been updated" notification appear when the caching is done, after which 
you need to refresh the page to see the changes.
 - If you're deploying frontend changes, monitor [Sentry](https://sentry.io/devdocs/devdocs-js/) for new JS 
errors once the deploy is done.
 - If you're deploying server changes, monitor New Relic (accessible through [the Heroku 
dashboard](https://dashboard.heroku.com/apps/devdocs)) for Ruby exceptions and throughput or response time 
changes once the deploy is done.
 
diff --git a/lib/app.rb b/lib/app.rb
index 7d33ef16..d892b039 100644
--- a/lib/app.rb
+++ b/lib/app.rb
@@ -192,35 +192,47 @@ class App < Sinatra::Application
       request.query_string.empty? ? nil : "?#{request.query_string}"
     end
 
-    def manifest_asset_urls
-      @@manifest_asset_urls ||= [
+    def service_worker_asset_urls
+      @@service_worker_asset_urls ||= [
         javascript_path('application', asset_host: false),
         stylesheet_path('application'),
         image_path('docs-1.png'),
         image_path('docs-1 2x png'),
         image_path('docs-2.png'),
         image_path('docs-2 2x png'),
-        asset_path('docs.js')
-      ]
+        asset_path('docs.js'),
+        App.production? ? nil : javascript_path('debug'),
+      ].compact
     end
 
-    def app_size
-      @app_size ||= memoized_cookies['size'].nil? ? '20rem' : "#{memoized_cookies['size']}px"
-    end
+    # Returns a cache name for the service worker to use which changes if any of the assets changes
+    # When a manifest exist, this name is only created once based on the asset manifest because it never 
changes without a server restart
+    # If a manifest does not exist, it is created every time this method is called because the assets can 
change while the server is running
+    def service_worker_cache_name
+      if File.exist?(App.assets_manifest_path)
+        if defined?(@@service_worker_cache_name)
+          return @@service_worker_cache_name
+        end
 
-    def app_layout
-      memoized_cookies['layout']
-    end
+        digest = Sprockets::Manifest
+                   .new(nil, App.assets_manifest_path)
+                   .files
+                   .values
+                   .map {|file| file["digest"]}
+                   .join
 
-    def app_theme
-      @app_theme ||= memoized_cookies['dark'].nil? ? 'default' : 'dark'
-    end
+        return @@service_worker_cache_name ||= Digest::MD5.hexdigest(digest)
+      else
+        paths = App.sprockets
+                  .each_file
+                  .to_a
+                  .reject {|file| file.start_with?(App.docs_path)}
 
-    def dark_theme?
-      app_theme == 'dark'
+        return App.sprockets.pack_hexdigest(App.sprockets.files_digest(paths))
+      end
     end
 
-    def redirect_via_js(path) # courtesy of HTML5 App Cache
+    def redirect_via_js(path)
       response.set_cookie :initial_path, value: path, expires: Time.now + 15, path: '/'
       redirect '/', 302
     end
@@ -243,15 +255,15 @@ class App < Sinatra::Application
     end
   end
 
-  get '/manifest.appcache' do
-    content_type 'text/cache-manifest'
+  get '/service-worker.js' do
+    content_type 'application/javascript'
     expires 0, :'no-cache'
-    erb :manifest
+    erb :'service-worker.js'
   end
 
   get '/' do
     return redirect "/#q=#{params[:q]}" if params[:q]
-    return redirect '/' unless request.query_string.empty? # courtesy of HTML5 App Cache
+    return redirect '/' unless request.query_string.empty?
     response.headers['Content-Security-Policy'] = settings.csp if settings.csp
     erb :index
   end
diff --git a/public/images/webapp-icon-192.png b/public/images/webapp-icon-192.png
new file mode 100644
index 00000000..d1d1dd75
Binary files /dev/null and b/public/images/webapp-icon-192.png differ
diff --git a/public/manifest.json b/public/manifest.json
index 1faa5978..301c56d1 100644
--- a/public/manifest.json
+++ b/public/manifest.json
@@ -4,6 +4,7 @@
   "description": "API Documentation Browser",
   "start_url": "/",
   "display": "standalone",
+  "background_color": "#EEEEEE",
   "icons": [
     {
       "src": "/images/webapp-icon-32.png",
@@ -25,6 +26,11 @@
       "sizes": "128x128",
       "type": "image/png"
     },
+    {
+      "src": "/images/webapp-icon-192.png",
+      "sizes": "192x192",
+      "type": "image/png"
+    },
     {
       "src": "/images/webapp-icon-256.png",
       "sizes": "256x256",
diff --git a/test/app_test.rb b/test/app_test.rb
index 92a24acd..8e9e369b 100644
--- a/test/app_test.rb
+++ b/test/app_test.rb
@@ -43,35 +43,6 @@ class AppTest < MiniTest::Spec
       assert last_response.redirect?
       assert_equal 'https://example.org/', last_response['Location']
     end
-
-    it "sets default size" do
-      get '/'
-      assert_includes last_response.body, 'data-size="20rem"'
-    end
-
-    it "sets size from cookie" do
-      set_cookie('size=42')
-      get '/'
-      assert_includes last_response.body, 'data-size="42px"'
-    end
-
-    it "sets layout from cookie" do
-      set_cookie('layout=foo')
-      get '/'
-      assert_includes last_response.body, '<body class="foo">'
-    end
-
-    it "sets the <html> theme from cookie" do
-      get '/'
-      assert_match %r{<html [^>]*class="[^\"]*_theme-default}, last_response.body
-      refute_includes last_response.body, '_theme-dark'
-
-      set_cookie('dark=1')
-
-      get '/'
-      assert_match %r{<html [^>]*class="[^\"]*_theme-dark}, last_response.body
-      refute_includes last_response.body, '_theme-default'
-    end
   end
 
   describe "/[static-page]" do
@@ -106,58 +77,6 @@ class AppTest < MiniTest::Spec
     end
   end
 
-  describe "/manifest.appcache" do
-    it "works" do
-      get '/manifest.appcache'
-      assert last_response.ok?
-    end
-
-    it "works with cookie" do
-      set_cookie('docs=css/html~5')
-      get '/manifest.appcache'
-      assert last_response.ok?
-      assert_includes last_response.body, '/css/index.json?1420139788'
-      assert_includes last_response.body, '/html~5/index.json?1420139791'
-    end
-
-    it "ignores invalid docs in the cookie" do
-      set_cookie('docs=foo')
-      get '/manifest.appcache'
-      assert last_response.ok?
-      refute_includes last_response.body, 'foo'
-    end
-
-    it "has the word 'default' when no 'dark' cookie is set" do
-      get '/manifest.appcache'
-      assert_includes last_response.body, '# default'
-      refute_includes last_response.body, '# dark'
-    end
-
-    it "has the word 'dark' when the cookie is set" do
-      set_cookie('dark=1')
-      get '/manifest.appcache'
-      assert_includes last_response.body, '# dark'
-      refute_includes last_response.body, '# default'
-    end
-
-    it "sets default size" do
-      get '/manifest.appcache'
-      assert_includes last_response.body, '20rem'
-    end
-
-    it "sets size from cookie" do
-      set_cookie('size=42')
-      get '/manifest.appcache'
-      assert_includes last_response.body, '42px'
-    end
-
-    it "sets layout from cookie" do
-      set_cookie('layout=foo_layout')
-      get '/manifest.appcache'
-      assert_includes last_response.body, 'foo_layout'
-    end
-  end
-
   describe "/[doc]" do
     it "renders when the doc exists and isn't enabled" do
       set_cookie('docs=html~5')
diff --git a/views/app.erb b/views/app.erb
index 25cfae15..19a0352b 100644
--- a/views/app.erb
+++ b/views/app.erb
@@ -28,13 +28,7 @@
     </nav>
   </header>
   <section class="_sidebar" tabindex="-1">
-    <div class="_list" role="navigation">
-      <% unless @doc %>
-      <% App.docs.each do |slug, doc| %>
-      <a href="/<%= slug %>/" class="_list-item"><%= doc['full_name'] %></a>
-      <% end %>
-      <% end %>
-    </div>
+    <div class="_list" role="navigation"></div>
   </section>
   <div class="_container" role="document">
     <main class="_content _content-loading" role="main"></main>
@@ -63,9 +57,3 @@
     <symbol id="icon-external-link" viewBox="0 0 24 24"><path d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 
1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"/></symbol>
   </defs>
 </svg>
-<style data-size="<%= app_size %>" data-resizer>
-  ._container { margin-left: <%= app_size %>; }
-  ._header, ._list { width: <%= app_size %>; }
-  ._list-hover.clone { min-width: <%= app_size %>; }
-  ._notice, ._path, ._resizer { left: <%= app_size %>; }
-</style>
diff --git a/views/index.erb b/views/index.erb
index 5d0fb4a5..67ba9db7 100644
--- a/views/index.erb
+++ b/views/index.erb
@@ -1,5 +1,5 @@
 <!DOCTYPE html>
-<html<%= ' manifest="/manifest.appcache"' if App.production? %> prefix="og: http://ogp.me/ns#"; lang="en" 
class="_booting _theme-<%= app_theme %>">
+<html prefix="og: http://ogp.me/ns#"; lang="en" class="_booting">
 <head>
   <meta charset="utf-8">
   <meta name="viewport" 
content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,shrink-to-fit=no">
@@ -14,6 +14,7 @@
   <meta name="apple-mobile-web-app-capable" content="yes">
   <meta name="apple-mobile-web-app-status-bar-style" content="black">
   <meta name="format-detection" content="telephone=no">
+  <meta name="theme-color" content="#eee">
   <meta name="robots" content="noodp">
   <title>GNOME JavaScript Docs</title>
   <link rel="canonical" href="<%= canonical_origin %>">
@@ -32,7 +33,7 @@
   <link rel="mask-icon" href="<%= App.cdn_origin %>/images/webkit-mask-icon.svg" color="#398df0">
   <%= stylesheet_tag 'application' %>
 </head>
-<body<%= %( class="#{app_layout}") if app_layout %>>
+<body>
 <noscript class="_fail">DevDocs requires JavaScript to run.</noscript>
 <%= erb :app -%>
 <%= javascript_tag 'application', asset_host: false %>
diff --git a/views/other.erb b/views/other.erb
index ee9b8de1..45cab943 100644
--- a/views/other.erb
+++ b/views/other.erb
@@ -1,10 +1,11 @@
 <!DOCTYPE html>
-<html lang="en" class="_booting _theme-<%= app_theme %>">
+<html lang="en" class="_booting">
 <head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
   <% if doc_index_page? %><meta name="description" content="<%= @doc['name'] %> <%= @doc['release'] %> API 
documentation with instant search, offline support, keyboard shortcuts, mobile version, and more."><% else 
%><meta name="robots" content="noindex"><% end %>
   <meta name="format-detection" content="telephone=no">
+  <meta name="theme-color" content="#eee">
   <meta property="og:image" content="<%= App.cdn_origin %>/images/icon-320.png">
   <title>DevDocs<%= " &mdash; #{@doc['full_name']} documentation" if doc_index_page? %></title>
   <link rel="canonical" href="<%= canonical_origin %><%= request.path %>">
@@ -13,7 +14,7 @@
   <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="Search 
DevDocs">
   <%= stylesheet_tag 'application' %>
 </head>
-<body<%= %( class="#{app_layout}") if app_layout %> data-doc="<%= CGI::escape_html @doc.to_json %>">
+<body data-doc="<%= CGI::escape_html @doc.to_json %>">
 <noscript class="_fail">DevDocs requires JavaScript to run.</noscript>
 <%= erb :app -%>
 <%= javascript_tag 'application', asset_host: false %><% unless App.production? %>
diff --git a/views/service-worker.js.erb b/views/service-worker.js.erb
new file mode 100644
index 00000000..aa234c19
--- /dev/null
+++ b/views/service-worker.js.erb
@@ -0,0 +1,61 @@
+<%# The name of the cache to store responses in %>
+<%# If the cache name changes DevDocs is assumed to be updated %>
+const cacheName = '<%= service_worker_cache_name %>';
+
+<%# Url's to cache when the service worker is installed %>
+const urlsToCache = [
+  '/',
+  '/favicon.ico',
+  '/manifest.json',
+  '<%= service_worker_asset_urls.join "',\n  '" %>',
+  '<%= doc_index_urls.join "',\n  '" %>',
+];
+
+<%# Set-up the cache %>
+self.addEventListener('install', event => {
+  self.skipWaiting();
+
+  event.waitUntil(
+    caches.open(cacheName).then(cache => cache.addAll(urlsToCache)),
+  );
+});
+
+<%# Remove old caches %>
+self.addEventListener('activate', event => {
+  event.waitUntil((async () => {
+    const keys = await caches.keys();
+    const jobs = keys.map(key => key !== cacheName ? caches.delete(key) : Promise.resolve());
+    return Promise.all(jobs);
+  })());
+});
+
+<%# Handle HTTP requests %>
+self.addEventListener('fetch', event => {
+  event.respondWith((async () => {
+    const cachedResponse = await caches.match(event.request);
+    if (cachedResponse) return cachedResponse;
+
+    try {
+      const response = await fetch(event.request);
+
+      if (!response.ok) {
+        throw new Error(`The HTTP request failed with status code ${response.status}`);
+      }
+
+      return response;
+    } catch (err) {
+      const url = new URL(event.request.url);
+
+      <%# Attempt to return the index page from the cache if the user is visiting a url like 
devdocs.io/offline or devdocs.io/javascript/global_objects/array/find %>
+      <%# The index page will make sure the correct documentation or a proper offline page is shown  %>
+      const pathname = url.pathname;
+      const filename = pathname.substr(1 + pathname.lastIndexOf('/')).split(/\#|\?/g)[0];
+      if (url.origin === location.origin && !filename.includes('.')) {
+        const cachedIndex = await caches.match('/');
+        if (cachedIndex) return cachedIndex;
+      }
+
+      throw err;
+    }
+  })());
+});
diff --git a/views/unsupported.erb b/views/unsupported.erb
index a01b7c7e..6c1ded7e 100644
--- a/views/unsupported.erb
+++ b/views/unsupported.erb
@@ -11,9 +11,9 @@
     <p class="_fail-text">DevDocs is an API documentation browser which supports the following browsers:</p>
     <ul class="_fail-list">
       <li>Recent versions of Firefox, Chrome, or Opera</li>
-      <li>Safari 9.1+</li>
-      <li>Edge 16+</li>
-      <li>iOS 10+</li>
+      <li>Safari 11.1+</li>
+      <li>Edge 17+</li>
+      <li>iOS 11.3+</li>
     </ul>
     <p class="_fail-text">
       If you're unable to upgrade, we apologize.


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]