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/.slugignore b/.slugignore
index 6a7070f5..9daeafb9 100644
--- a/.slugignore
+++ b/.slugignore
@@ -1,2 +1 @@
-public/icons
-test
\ No newline at end of file
+test
diff --git a/.travis.yml b/.travis.yml
index e8d3d588..f3839425 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -9,3 +9,11 @@ before_script:
script:
- if [ "$TRAVIS_EVENT_TYPE" != "cron" ]; then bundle exec rake; fi
- if [ "$TRAVIS_EVENT_TYPE" = "cron" ]; then bundle exec thor updates:check --github-token $GH_TOKEN --upload; fi
+
+deploy:
+ provider: heroku
+ app: devdocs
+ on:
+ branch: master
+ api_key:
+ secure: "4p1klvWJZSOImzFcKOduILjP93hlOlAhceWlYMKS4tU+TCFE8qTBzdKdFPSCsCgjB+YR9pBss+L0lJpVVMjSwFHXqpKe6EeUSltO2k7DFHfW7kXLUM/L0AfqXz+YXk76XUyZMhvOEbldPfaMaj10e8vgDOQCSHABDyK/4CU+hnI="
diff --git a/Dockerfile b/Dockerfile
index 77443edd..420bd195 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,6 +1,7 @@
FROM ruby:2.6.0
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 5b8fae70..e3f75fce 100644
--- a/Gemfile
+++ b/Gemfile
@@ -22,6 +22,8 @@ group :app do
gem 'browser'
gem 'sass'
gem 'coffee-script'
+ gem 'chunky_png'
+ gem 'sprockets-sass'
end
group :production do
diff --git a/Gemfile.lock b/Gemfile.lock
index 3ed8570b..b7023a31 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.3.10)
coderay (1.1.2)
coffee-script (2.4.1)
coffee-script-source
@@ -96,6 +97,8 @@ 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)
@@ -134,6 +137,7 @@ DEPENDENCIES
activesupport (~> 5.2)
better_errors
browser
+ chunky_png
coffee-script
erubi
html-pipeline
@@ -156,6 +160,7 @@ DEPENDENCIES
sprockets
sprockets-helpers
terminal-table
+ sprockets-sass
thin
thor
tty-pager
diff --git a/README.md b/README.md
index 3c652e9f..630142d4 100644
--- a/README.md
+++ b/README.md
@@ -59,14 +59,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!
@@ -156,7 +156,7 @@ Contributions are welcome. Please read the [contributing guidelines](./.github/C
* [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/images/.gitignore b/assets/images/.gitignore
new file mode 100644
index 00000000..4a72ec74
--- /dev/null
+++ b/assets/images/.gitignore
@@ -0,0 +1 @@
+sprites/**/*
diff --git a/assets/images/docs-1.png b/assets/images/docs-1.png
deleted file mode 100644
index c5bfb6b8..00000000
Binary files a/assets/images/docs-1.png and /dev/null differ
diff --git a/assets/images/docs-1@2x.png b/assets/images/docs-1@2x.png
deleted file mode 100644
index 1f81ecd9..00000000
Binary files a/assets/images/docs-1@2x.png and /dev/null differ
diff --git a/assets/images/docs-2.png b/assets/images/docs-2.png
deleted file mode 100644
index bd9d44a8..00000000
Binary files a/assets/images/docs-2.png and /dev/null differ
diff --git a/assets/images/docs-2@2x.png b/assets/images/docs-2@2x.png
deleted file mode 100644
index 512ea7a5..00000000
Binary files a/assets/images/docs-2@2x.png and /dev/null differ
diff --git a/assets/javascripts/app/app.coffee b/assets/javascripts/app/app.coffee
index ab67a92a..1e230368 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'
@@ -252,7 +257,7 @@
matchMedia: !!window.matchMedia
insertAdjacentHTML: !!document.body.insertAdjacentHTML
defaultPrevented: document.createEvent('CustomEvent').defaultPrevented is false
- cssVariables: CSS.supports and CSS.supports('(--t: 0)')
+ cssVariables: !!CSS?.supports?('(--t: 0)')
for key, value of features when not value
Raven.captureMessage "unsupported/#{key}", level: 'info'
diff --git a/assets/javascripts/app/appcache.coffee b/assets/javascripts/app/appcache.coffee
deleted file mode 100644
index 235cae02..00000000
--- a/assets/javascripts/app/appcache.coffee
+++ /dev/null
@@ -1,42 +0,0 @@
-class app.AppCache
- $.extend @prototype, Events
-
- @isEnabled: ->
- try
- applicationCache and applicationCache.status isnt applicationCache.UNCACHED
- catch
-
- constructor: ->
- @cache = applicationCache
- @notifyUpdate = true
- @onUpdateReady() if @cache.status is @cache.UPDATEREADY
-
- $.on @cache, 'progress', @onProgress
- $.on @cache, 'updateready', @onUpdateReady
-
- update: ->
- @notifyUpdate = true
- @notifyProgress = true
- try @cache.update() catch
- return
-
- updateInBackground: ->
- @notifyUpdate = false
- @notifyProgress = false
- try @cache.update() catch
- return
-
- reload: ->
- $.on @cache, 'updateready noupdate error', -> app.reboot()
- @notifyUpdate = false
- @notifyProgress = true
- try @cache.update() catch
- return
-
- onProgress: (event) =>
- @trigger 'progress', event if @notifyProgress
- return
-
- onUpdateReady: =>
- @trigger 'updateready' if @notifyUpdate
- return
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..ba2f2647 100644
--- a/assets/javascripts/lib/page.coffee
+++ b/assets/javascripts/lib/page.coffee
@@ -199,5 +199,21 @@ page.track = (fn) ->
return
track = ->
- tracker.call() for tracker in trackers
+ 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] == '_'
+ Cookies.expire(name)
return
diff --git a/assets/javascripts/lib/util.coffee b/assets/javascripts/lib/util.coffee
index 058106fd..001b13de 100644
--- a/assets/javascripts/lib/util.coffee
+++ b/assets/javascripts/lib/util.coffee
@@ -352,6 +352,10 @@ isIE = null
$.isIE = ->
isIE ?= navigator.userAgent?.indexOf('MSIE') >= 0 || navigator.userAgent?.indexOf('rv:11.0') >= 0
+isChromeForAndroid = null
+$.isChromeForAndroid = ->
+ isChromeForAndroid ?= navigator.userAgent?.indexOf('Android') >= 0 && /Chrome\/([.0-9])+ Mobile/.test(navigator.userAgent)
+
isAndroid = null
$.isAndroid = ->
isAndroid ?= navigator.userAgent?.indexOf('Android') >= 0
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..a2d18a47 100644
--- a/assets/javascripts/news.json
+++ b/assets/javascripts/news.json
@@ -1,4 +1,8 @@
[
+ [
+ "2019-07-19",
+ "Replaced the AppCache with a Service Worker (which makes DevDocs an installable PWA) and fixed layout preferences on Firefox."
+ ],
[
"2018-09-23",
"New documentations: Puppeteer and Handlebars.js"
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.
- 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 installing the documentation for offline usage when online again).
+ If you're online and you keep seeing this, you're likely behind a proxy or firewall that blocks cross-domain requests. """,
""" #{back} · Reload
· Retry """
@@ -57,9 +57,9 @@ app.templates.unsupportedBrowser = """
DevDocs is an API documentation browser which supports the following browsers:
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. """,
""" Install them 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.
+
Accept or Decline """
diff --git a/assets/javascripts/templates/pages/about_tmpl.coffee b/assets/javascripts/templates/pages/about_tmpl.coffee
index 5d997403..e7b4cc80 100644
--- a/assets/javascripts/templates/pages/about_tmpl.coffee
+++ b/assets/javascripts/templates/pages/about_tmpl.coffee
@@ -73,7 +73,8 @@ app.templates.aboutPage = -> """
ENABLE_SERVICE_WORKER
environment variable to true
)"
+
+ """ No. Service Workers #{reason}, so loading devdocs.io offline won't work.Thanks for downloading DevDocs. Here are a few things you should know:
thor docs:list
to see all available documentations.
thor docs:download <name>
to download documentations.
thor docs:download --installed
to update all downloaded documentations.
@@ -39,7 +39,7 @@ app.templates.intro = """
Happy coding! diff --git a/assets/javascripts/templates/pages/settings_tmpl.coffee b/assets/javascripts/templates/pages/settings_tmpl.coffee index 1d439edb..94afe3df 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) -> """ Automatically hide and show the sidebar Tip: drag the edge of the sidebar to resize it. + + diff --git a/assets/javascripts/tracking.js b/assets/javascripts/tracking.js index ca05b218..a68ca493 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 === 'production') { + 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 02b98c7a..597dfe37 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/javascripts/views/search/search.coffee b/assets/javascripts/views/search/search.coffee index 8fab885c..7d05f0a0 100644 --- a/assets/javascripts/views/search/search.coffee +++ b/assets/javascripts/views/search/search.coffee @@ -30,6 +30,9 @@ class app.views.Search extends app.View .on 'results', @onResults .on 'end', @onEnd + @scope + .on 'change', @onScopeChange + app.on 'ready', @onReady $.on window, 'hashchange', @searchUrl $.on window, 'focus', @onWindowFocus @@ -138,6 +141,11 @@ class app.views.Search extends app.View $.stopEvent(event) return + onScopeChange: => + @value = '' + @onInput() + return + afterRoute: (name, context) => return if app.shortcuts.eventInProgress?.name is 'escape' @reset(true) if not context.init and app.router.isIndex() diff --git a/assets/javascripts/views/search/search_scope.coffee b/assets/javascripts/views/search/search_scope.coffee index 24de57ce..52ff753a 100644 --- a/assets/javascripts/views/search/search_scope.coffee +++ b/assets/javascripts/views/search/search_scope.coffee @@ -6,7 +6,9 @@ class app.views.SearchScope extends app.View tag: '._search-tag' @events: + click: 'onClick' keydown: 'onKeydown' + textInput: 'onTextInput' @routes: after: 'afterRoute' @@ -87,17 +89,33 @@ class app.views.SearchScope extends app.View @trigger 'change', null, previousDoc return + doScopeSearch: (event) => + @search @input.value[0...@input.selectionStart] + $.stopEvent(event) if @doc + return + + onClick: (event) => + if event.target is @tag + @reset() + $.stopEvent(event) + return + onKeydown: (event) => if event.which is 8 # backspace - if @doc and not @input.value - $.stopEvent(event) + if @doc and @input.selectionEnd is 0 @reset() - else if not @doc and @input.value + $.stopEvent(event) + else if not @doc and @input.value and not $.isChromeForAndroid() return if event.ctrlKey or event.metaKey or event.altKey or event.shiftKey if event.which is 9 or # tab (event.which is 32 and app.isMobile()) # space - @search @input.value[0...@input.selectionStart] - $.stopEvent(event) if @doc + @doScopeSearch(event) + return + + onTextInput: (event) => + return unless $.isChromeForAndroid() + if not @doc and @input.value and event.data == ' ' + @doScopeSearch(event) return extractHashValue: -> diff --git a/assets/javascripts/views/sidebar/sidebar.coffee b/assets/javascripts/views/sidebar/sidebar.coffee index c8dc52a6..f3ae3bd4 100644 --- a/assets/javascripts/views/sidebar/sidebar.coffee +++ b/assets/javascripts/views/sidebar/sidebar.coffee @@ -28,7 +28,7 @@ class app.views.Sidebar extends app.View app.on 'ready', @onReady - $.on document.documentElement, 'mouseleave', (event) => @display() if event.clientX < 10 + $.on document.documentElement, 'mouseleave', (event) => @display() unless event.clientX <= 0 $.on document.documentElement, 'mouseenter', => @resetDisplay(forceNoHover: false) return diff --git a/assets/stylesheets/application.css.scss b/assets/stylesheets/application.css.scss index 2a64e5c9..85d1134f 100644 --- a/assets/stylesheets/application.css.scss +++ b/assets/stylesheets/application.css.scss @@ -1,7 +1,6 @@ -//= depend_on docs-1.png -//= depend_on docs-1@2x.png -//= depend_on docs-2.png -//= depend_on docs-2@2x.png +//= depend_on sprites/docs.png +//= depend_on sprites/docs@2x.png +//= depend_on sprites/docs.json /*! * Copyright 2013-2019 Thibaut Courouble and other contributors diff --git a/assets/stylesheets/components/_header.scss b/assets/stylesheets/components/_header.scss index 5bae8901..e74830aa 100644 --- a/assets/stylesheets/components/_header.scss +++ b/assets/stylesheets/components/_header.scss @@ -215,5 +215,6 @@ color: var(--textColorLight); background: var(--searchTagBackground); border-radius: 2px; + cursor: pointer; @extend %truncate-text; } 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/assets/stylesheets/global/_icons.scss b/assets/stylesheets/global/_icons.scss deleted file mode 100644 index e7a805f4..00000000 --- a/assets/stylesheets/global/_icons.scss +++ /dev/null @@ -1,182 +0,0 @@ -%svg-icon { - display: inline-block; - vertical-align: top; - width: 1rem; - height: 1rem; - pointer-events: none; - fill: currentColor; -} - -%doc-icon { - content: ''; - display: block; - width: 1rem; - height: 1rem; - background-image: image-url('docs-1.png'); - background-size: 10rem 10rem; -} - -%doc-icon-2 { background-image: image-url('docs-2.png') !important; } - -@media (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 144dpi) { - %doc-icon { background-image: image-url('docs-1@2x.png'); } - %doc-icon-2 { background-image: image-url('docs-2@2x.png') !important; } -} - -html._theme-dark { - %darkIconFix { - filter: invert(100%) grayscale(100%); - -webkit-filter: invert(100%) grayscale(100%); - } -} - -._icon-jest:before { background-position: 0 0; } -._icon-liquid:before { background-position: -1rem 0; } -._icon-openjdk:before { background-position: -2rem 0; } -._icon-codeceptjs:before { background-position: -3rem 0; } -._icon-codeception:before { background-position: -4rem 0; } -._icon-sqlite:before { background-position: -5rem 0; @extend %darkIconFix !optional; } -._icon-async:before { background-position: -6rem 0; @extend %darkIconFix !optional; } -._icon-http:before { background-position: -7rem 0; @extend %darkIconFix !optional; } -._icon-jquery:before { background-position: -8rem 0; @extend %darkIconFix !optional; } -._icon-underscore:before { background-position: -9rem 0; @extend %darkIconFix !optional; } -._icon-html:before { background-position: 0 -1rem; } -._icon-css:before { background-position: -1rem -1rem; } -._icon-dom:before { background-position: -2rem -1rem; } -._icon-dom_events:before { background-position: -3rem -1rem; } -._icon-javascript:before { background-position: -4rem -1rem; } -._icon-backbone:before { background-position: -5rem -1rem; @extend %darkIconFix !optional; } -._icon-node:before, -._icon-node_lts:before { background-position: -6rem -1rem; } -._icon-sass:before { background-position: -7rem -1rem; } -._icon-less:before { background-position: -8rem -1rem; } -._icon-angularjs:before { background-position: -9rem -1rem; } -._icon-coffeescript:before { background-position: 0 -2rem; @extend %darkIconFix !optional; } -._icon-ember:before { background-position: -1rem -2rem; } -._icon-yarn:before { background-position: -2rem -2rem; } -._icon-immutable:before { background-position: -3rem -2rem; @extend %darkIconFix !optional; } -._icon-jqueryui:before { background-position: -4rem -2rem; } -._icon-jquerymobile:before { background-position: -5rem -2rem; } -._icon-lodash:before { background-position: -6rem -2rem; } -._icon-php:before { background-position: -7rem -2rem; } -._icon-ruby:before, -._icon-minitest:before { background-position: -8rem -2rem; } -._icon-rails:before { background-position: -9rem -2rem; } -._icon-python:before, -._icon-python2:before { background-position: 0 -3rem; } -._icon-git:before { background-position: -1rem -3rem; } -._icon-redis:before { background-position: -2rem -3rem; } -._icon-postgresql:before { background-position: -3rem -3rem; } -._icon-d3:before { background-position: -4rem -3rem; } -._icon-knockout:before { background-position: -5rem -3rem; } -._icon-moment:before { background-position: -6rem -3rem; @extend %darkIconFix !optional; } -._icon-c:before { background-position: -7rem -3rem; } -._icon-statsmodels:before { background-position: -8rem -3rem; } -._icon-yii:before, -._icon-yii1:before { background-position: -9rem -3rem; } -._icon-cpp:before { background-position: 0 -4rem; } -._icon-go:before { background-position: -1rem -4rem; } -._icon-express:before { background-position: -2rem -4rem; } -._icon-grunt:before { background-position: -3rem -4rem; } -._icon-rust:before { background-position: -4rem -4rem; @extend %darkIconFix !optional; } -._icon-laravel:before { background-position: -5rem -4rem; } -._icon-haskell:before { background-position: -6rem -4rem; } -._icon-requirejs:before { background-position: -7rem -4rem; } -._icon-chai:before { background-position: -8rem -4rem; } -._icon-sinon:before { background-position: -9rem -4rem; } -._icon-cordova:before { background-position: 0 -5rem; } -._icon-markdown:before { background-position: -1rem -5rem; @extend %darkIconFix !optional; } -._icon-django:before { background-position: -2rem -5rem; } -._icon-xslt_xpath:before { background-position: -3rem -5rem; } -._icon-nginx:before, -._icon-nginx_lua_module:before { background-position: -4rem -5rem; } -._icon-svg:before { background-position: -5rem -5rem; } -._icon-marionette:before { background-position: -6rem -5rem; } -._icon-jsdoc:before, -._icon-koa:before, -._icon-graphite:before, -._icon-mongoose:before { background-position: -7rem -5rem; } -._icon-phpunit:before { background-position: -8rem -5rem; } -._icon-nokogiri:before { background-position: -9rem -5rem; @extend %darkIconFix !optional; } -._icon-rethinkdb:before { background-position: 0 -6rem; } -._icon-react:before { background-position: -1rem -6rem; } -._icon-socketio:before { background-position: -2rem -6rem; } -._icon-modernizr:before { background-position: -3rem -6rem; } -._icon-bower:before { background-position: -4rem -6rem; } -._icon-fish:before { background-position: -5rem -6rem; @extend %darkIconFix !optional; } -._icon-scikit_image:before { background-position: -6rem -6rem; } -._icon-twig:before { background-position: -7rem -6rem; } -._icon-pandas:before { background-position: -8rem -6rem; } -._icon-scikit_learn:before { background-position: -9rem -6rem; } -._icon-bottle:before { background-position: 0 -7rem; } -._icon-docker:before { background-position: -1rem -7rem; } -._icon-cakephp:before { background-position: -2rem -7rem; } -._icon-lua:before { background-position: -3rem -7rem; @extend %darkIconFix !optional; } -._icon-clojure:before { background-position: -4rem -7rem; } -._icon-symfony:before { background-position: -5rem -7rem; } -._icon-mocha:before { background-position: -6rem -7rem; } -._icon-meteor:before { background-position: -7rem -7rem; @extend %darkIconFix !optional; } -._icon-npm:before { background-position: -8rem -7rem; } -._icon-apache_http_server:before { background-position: -9rem -7rem; } -._icon-drupal:before { background-position: 0 -8rem; } -._icon-webpack:before { background-position: -1rem -8rem; } -._icon-phaser:before { background-position: -2rem -8rem; } -._icon-vue:before { background-position: -3rem -8rem; } -._icon-opentsdb:before { background-position: -4rem -8rem; } -._icon-q:before { background-position: -5rem -8rem; } -._icon-crystal:before { background-position: -6rem -8rem; @extend %darkIconFix !optional; } -._icon-julia:before { background-position: -7rem -8rem; @extend %darkIconFix !optional; } -._icon-redux:before { background-position: -8rem -8rem; @extend %darkIconFix !optional; } -._icon-bootstrap:before { background-position: -9rem -8rem; } -._icon-react_native:before { background-position: 0 -9rem; } -._icon-phalcon:before { background-position: -1rem -9rem; } -._icon-matplotlib:before { background-position: -2rem -9rem; } -._icon-cmake:before { background-position: -3rem -9rem; } -._icon-elixir:before { background-position: -4rem -9rem; @extend %darkIconFix !optional; } -._icon-vagrant:before { background-position: -5rem -9rem; } -._icon-dojo:before { background-position: -6rem -9rem; } -._icon-flow:before { background-position: -7rem -9rem; } -._icon-relay:before { background-position: -8rem -9rem; } -._icon-phoenix:before { background-position: -9rem -9rem; } - -._icon-tcl_tk:before { background-position: 0 0; @extend %doc-icon-2; } -._icon-erlang:before { background-position: -1rem 0; @extend %doc-icon-2; } -._icon-chef:before { background-position: -2rem 0; @extend %doc-icon-2; } -._icon-ramda:before { background-position: -3rem 0; @extend %doc-icon-2; @extend %darkIconFix !optional; } -._icon-codeigniter:before { background-position: -4rem 0; @extend %doc-icon-2; @extend %darkIconFix !optional; } -._icon-influxdata:before { background-position: -5rem 0; @extend %doc-icon-2; @extend %darkIconFix !optional; } -._icon-tensorflow:before { background-position: -6rem 0; @extend %doc-icon-2; } -._icon-haxe:before { background-position: -7rem 0; @extend %doc-icon-2; } -._icon-ansible:before { background-position: -8rem 0; @extend %doc-icon-2; @extend %darkIconFix !optional; } -._icon-typescript:before { background-position: -9rem 0; @extend %doc-icon-2; } -._icon-browser_support_tables:before { background-position: 0rem -1rem; @extend %doc-icon-2; } -._icon-gnu_fortran:before { background-position: -1rem -1rem; @extend %doc-icon-2; } -._icon-gcc:before { background-position: -2rem -1rem; @extend %doc-icon-2; } -._icon-perl:before { background-position: -3rem -1rem; @extend %doc-icon-2; } -._icon-apache_pig:before { background-position: -4rem -1rem; @extend %doc-icon-2; } -._icon-numpy:before { background-position: -5rem -1rem; @extend %doc-icon-2; } -._icon-kotlin:before { background-position: -6rem -1rem; @extend %doc-icon-2; } -._icon-padrino:before { background-position: -7rem -1rem; @extend %doc-icon-2; } -._icon-angular:before { background-position: -8rem -1rem; @extend %doc-icon-2; } -._icon-love:before { background-position: -9rem -1rem; @extend %doc-icon-2; } -._icon-jasmine:before { background-position: 0 -2rem; @extend %doc-icon-2; } -._icon-pug:before { background-position: -1rem -2rem; @extend %doc-icon-2; } -._icon-electron:before { background-position: -2rem -2rem; @extend %doc-icon-2; } -._icon-falcon:before { background-position: -3rem -2rem; @extend %doc-icon-2; } -._icon-godot:before { background-position: -4rem -2rem; @extend %doc-icon-2; } -._icon-nim:before { background-position: -5rem -2rem; @extend %doc-icon-2; @extend %darkIconFix !optional; } -._icon-vulkan:before { background-position: -6rem -2rem; @extend %doc-icon-2; @extend %darkIconFix !optional; } -._icon-d:before { background-position: -7rem -2rem; @extend %doc-icon-2; } -._icon-bluebird:before { background-position: -8rem -2rem; @extend %doc-icon-2; } -._icon-eslint:before { background-position: -9rem -2rem; @extend %doc-icon-2; } -._icon-homebrew:before { background-position: 0 -3rem; @extend %doc-icon-2; } -._icon-jekyll:before { background-position: -1rem -3rem; @extend %doc-icon-2; } -._icon-babel:before { background-position: -2rem -3rem; @extend %doc-icon-2; } -._icon-leaflet:before { background-position: -3rem -3rem; @extend %doc-icon-2; } -._icon-terraform:before { background-position: -4rem -3rem; @extend %doc-icon-2; } -._icon-pygame:before { background-position: -5rem -3rem; @extend %doc-icon-2; } -._icon-bash:before { background-position: -6rem -3rem; @extend %doc-icon-2; } -._icon-dart:before { background-position: -7rem -3rem; @extend %doc-icon-2; } -._icon-qt:before { background-position: -8rem -3rem; @extend %doc-icon-2; } -._icon-puppeteer:before { background-position: -9rem -3rem; @extend %doc-icon-2; } -._icon-handlebars:before { background-position: 0 -4rem; @extend %doc-icon-2; @extend %darkIconFix !optional; } diff --git a/assets/stylesheets/global/_icons.scss.erb b/assets/stylesheets/global/_icons.scss.erb new file mode 100644 index 00000000..b2b22c22 --- /dev/null +++ b/assets/stylesheets/global/_icons.scss.erb @@ -0,0 +1,43 @@ +<% manifest = JSON.parse(File.read('assets/images/sprites/docs.json')) %> + +%svg-icon { + display: inline-block; + vertical-align: top; + width: 1rem; + height: 1rem; + pointer-events: none; + fill: currentColor; +} + +%doc-icon { + content: ''; + display: block; + width: 1rem; + height: 1rem; + background-image: image-url('sprites/docs.png'); + background-size: <%= manifest['icons_per_row'] %>rem <%= manifest['icons_per_row'] %>rem; +} + +@media (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 144dpi) { + %doc-icon { background-image: image-url('sprites/docs@2x.png'); } +} + +html._theme-dark { + %darkIconFix { + filter: invert(100%) grayscale(100%); + -webkit-filter: invert(100%) grayscale(100%); + } +} + +<%= + items = [] + + manifest['items'].each do |item| + rules = [] + rules << "background-position: -#{item['col']}rem -#{item['row']}rem;" + rules << "@extend %darkIconFix !optional;" if item['dark_icon_fix'] + items << "._icon-#{item['type']}:before { #{rules.join(' ')} }" + end + + items.join('') + %> diff --git a/docs/maintainers.md b/docs/maintainers.md index 1369816d..da7e910e 100644 --- a/docs/maintainers.md +++ b/docs/maintainers.md @@ -21,8 +21,7 @@ The process for updating docs is as follow: - Commit the changes (protip: use the `thor docs:commit` command documented below). - Optional: do more updates. - Run `thor docs:upload` (documented below). -- [Deploy the app](#deploying-devdocs) and verify that everything works in production. -- Push to GitHub. +- Push to GitHub to [deploy the app](#deploying-devdocs) and verify that everything works in production. - Run `thor docs:clean` (documented below). Note: changes to `public/docs/docs.json` should never be committed. This file reflects which documentations have been downloaded or generated locally, which is always none on a fresh `git clone`. @@ -82,13 +81,13 @@ In addition to the [publicly-documented commands](https://github.com/freeCodeCam ## Deploying DevDocs -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. +Once docs have been uploaded via `thor docs:upload` (if applicable), you can push to the DevDocs master branch (or merge the PR containing the updates). If the Travis build succeeds, the Heroku application will be deployed automatically. -- 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. -If any issue arises, run `heroku rollback` to rollback to the previous of the app (this can also be done via Heroku's UI). Note that this will not revert changes made to documentation files that were uploaded via `thor docs:upload`. Try and fix the issue as quickly as possible, then re-deploy the app. Reach out to other maintainers if you need help. +If any issue arises, run `heroku rollback` to rollback to the previous version of the app (this can also be done via Heroku's UI). Note that this will not revert changes made to documentation files that were uploaded via `thor docs:upload`. Try and fix the issue as quickly as possible, then re-deploy the app. Reach out to other maintainers if you need help. If this is your first deploy, make sure another maintainer is around to assist. diff --git a/lib/app.rb b/lib/app.rb index 32cac31b..a1ace892 100644 --- a/lib/app.rb +++ b/lib/app.rb @@ -37,6 +37,9 @@ class App < Sinatra::Application set :csp, false + require 'docs' + Docs.generate_manifest + Dir[docs_path, root.join(assets_prefix, '*/')].each do |path| sprockets.append_path(path) end @@ -50,6 +53,11 @@ class App < Sinatra::Application end configure :test, :development do + require 'thor' + load 'tasks/sprites.thor' + + SpritesCLI.new.invoke(:generate) + require 'active_support/per_thread_registry' require 'active_support/cache' sprockets.cache = ActiveSupport::Cache.lookup_store :file_store, root.join('tmp', 'cache', 'assets', environment.to_s) @@ -192,35 +200,45 @@ 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') - ] + image_path('sprites/docs.png'), + image_path('sprites/docs@2x.png'), + 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 +261,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/lib/docs/core/scrapers/file_scraper.rb b/lib/docs/core/scrapers/file_scraper.rb index 9d354631..72a99b99 100644 --- a/lib/docs/core/scrapers/file_scraper.rb +++ b/lib/docs/core/scrapers/file_scraper.rb @@ -29,7 +29,7 @@ module Docs def request_one(url) assert_source_directory_exists - Response.new read_file(url_to_path(url)), URL.parse(url) + Response.new read_file(File.join(source_directory, url_to_path(url))), URL.parse(url) end def request_all(urls) @@ -50,7 +50,7 @@ module Docs end def read_file(path) - File.read(File.join(source_directory, path)) + File.read(path) rescue instrument 'warn.doc', msg: "Failed to open file: #{path}" nil diff --git a/lib/tasks/assets.thor b/lib/tasks/assets.thor index c3a4caf5..e9de1b6f 100644 --- a/lib/tasks/assets.thor +++ b/lib/tasks/assets.thor @@ -14,6 +14,9 @@ class AssetsCLI < Thor option :keep, type: :numeric, default: 0, desc: 'Number of old assets to keep' option :verbose, type: :boolean def compile + load 'tasks/sprites.thor' + invoke 'sprites:generate', [], :remove_public_icons => true, :verbose => options[:verbose] + manifest.compile App.assets_compile manifest.clean(options[:keep]) if options[:clean] end diff --git a/lib/tasks/sprites.thor b/lib/tasks/sprites.thor new file mode 100644 index 00000000..ca4e33bf --- /dev/null +++ b/lib/tasks/sprites.thor @@ -0,0 +1,211 @@ +class SpritesCLI < Thor + def self.to_s + 'Sprites' + end + + def initialize(*args) + require 'docs' + require 'chunky_png' + require 'fileutils' + super + end + + desc 'generate [--remove-public-icons] [--verbose]', 'Generate the documentation icon spritesheets' + option :remove_public_icons, type: :boolean, desc: 'Remove public/icons after generating the spritesheets' + option :verbose, type: :boolean + def generate + items = get_items + items_with_icons = items.select {|item| item[:has_icons]} + items_without_icons = items.select {|item| !item[:has_icons]} + icons_per_row = Math.sqrt(items_with_icons.length).ceil + + bg_color = get_sidebar_background + + items_with_icons.each_with_index do |item, index| + item[:row] = (index / icons_per_row).floor + item[:col] = index - item[:row] * icons_per_row + + item[:icon_16] = get_icon(item[:path_16], 16) + item[:icon_32] = get_icon(item[:path_32], 32) + + item[:dark_icon_fix] = needs_dark_icon_fix(item[:icon_32], bg_color) + end + + log_details(items_with_icons, icons_per_row) + + generate_spritesheet(16, items_with_icons, 'assets/images/sprites/docs.png') {|item| item[:icon_16]} + generate_spritesheet(32, items_with_icons, 'assets/images/sprites/docs@2x.png') {|item| item[:icon_32]} + + # Add Mongoose's icon details to docs without custom icons + default_item = items_with_icons.find {|item| item[:type] == 'mongoose'} + items_without_icons.each do |item| + item[:row] = default_item[:row] + item[:col] = default_item[:col] + item[:dark_icon_fix] = default_item[:dark_icon_fix] + end + + save_manifest(items, icons_per_row, 'assets/images/sprites/docs.json') + + if options[:remove_public_icons] + logger.info('Removing public/icons') + FileUtils.rm_rf('public/icons') + end + end + + private + + def get_items + items = Docs.all.map do |doc| + base_path = "public/icons/docs/#{doc.slug}" + { + :type => doc.slug, + :path_16 => "#{base_path}/16.png", + :path_32 => "#{base_path}/16@2x.png" + } + end + + # Checking paths against an array of possible paths is faster than 200+ File.exist? calls + files = Dir.glob('public/icons/docs/**/*.png') + + items.each do |item| + item[:has_icons] = files.include?(item[:path_16]) && files.include?(item[:path_32]) + end + end + + def get_icon(path, max_size) + icon = ChunkyPNG::Image.from_file(path) + + # Check if the icon is too big + # If it is, resize the image without changing the aspect ratio + if icon.width > max_size || icon.height > max_size + ratio = icon.width.to_f / icon.height + new_width = (icon.width >= icon.height ? max_size : max_size * ratio).floor + new_height = (icon.width >= icon.height ? max_size / ratio : max_size).floor + + logger.warn("Icon #{path} is too big: max size is #{max_size} x #{max_size}, icon is #{icon.width} x #{icon.height}, resizing to #{new_width} x #{new_height}") + + icon.resample_nearest_neighbor!(new_width, new_height) + end + + icon + end + + def get_sidebar_background + # This is a hacky way to get the background color of the sidebar + # Unfortunately, it's not possible to get the value of a SCSS variable from a Thor task + # Because hard-coding the value is even worse, we extract it using some regex + path = 'assets/stylesheets/global/_variables-dark.scss' + regex = /--sidebarBackground:\s+([^;]+);/ + ChunkyPNG::Color.parse(File.read(path)[regex, 1]) + end + + def needs_dark_icon_fix(icon, bg_color) + # Determine whether the icon needs to be grayscaled if the user has enabled the dark theme + # The logic is roughly based on https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast + contrast = icon.pixels.select {|pixel| ChunkyPNG::Color.a(pixel) > 0}.map do |pixel| + get_contrast(bg_color, pixel) + end + + avg = contrast.reduce(:+) / contrast.size.to_f + avg < 3.5 + end + + def get_contrast(base, other) + # Calculating the contrast ratio as described in the WCAG 2.0: + # https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef + l1 = get_luminance(base) + 0.05 + l2 = get_luminance(other) + 0.05 + ratio = l1 / l2 + l2 > l1 ? 1 / ratio : ratio + end + + def get_luminance(color) + rgb = [ + ChunkyPNG::Color.r(color).to_f, + ChunkyPNG::Color.g(color).to_f, + ChunkyPNG::Color.b(color).to_f + ] + + # Calculating the relative luminance as described in the WCAG 2.0: + # https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef + + rgb.map! do |value| + value /= 255 + value < 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4 + end + + 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2] + end + + def generate_spritesheet(size, items_with_icons, output_path, &item_to_icon) + logger.info("Generating spritesheet #{output_path} with icons of size #{size} x #{size}") + + icons_per_row = Math.sqrt(items_with_icons.length).ceil + spritesheet = ChunkyPNG::Image.new(size * icons_per_row, size * icons_per_row) + + items_with_icons.each do |item| + icon = item_to_icon.call(item) + + # Calculate the base coordinates + base_x = item[:col] * size + base_y = item[:row] * size + + # Center the icon if it's not a perfect rectangle + x = base_x + ((size - icon.width) / 2).floor + y = base_y + ((size - icon.height) / 2).floor + + spritesheet.compose!(icon, x, y) + end + + FileUtils.mkdir_p(File.dirname(output_path)) + spritesheet.save(output_path) + end + + def save_manifest(items, icons_per_row, path) + logger.info("Saving spritesheet details to #{path}") + + FileUtils.mkdir_p(File.dirname(path)) + + # Only save the details that the scss file needs + manifest_items = items.map do |item| + { + :type => item[:type], + :row => item[:row], + :col => item[:col], + :dark_icon_fix => item[:dark_icon_fix] + } + end + + manifest = {:icons_per_row => icons_per_row, :items => manifest_items} + + File.open(path, 'w') do |f| + f.write(JSON.generate(manifest)) + end + end + + def log_details(items_with_icons, icons_per_row) + logger.debug("Amount of icons: #{items_with_icons.length}") + logger.debug("Amount of icons needing the dark icon fix: #{items_with_icons.count {|item| item[:dark_icon_fix]}}") + logger.debug("Amount of icons per row: #{icons_per_row}") + + max_type_length = items_with_icons.map {|item| item[:type].length}.max + border = "+#{'-' * (max_type_length + 2)}+#{'-' * 5}+#{'-' * 8}+#{'-' * 15}+" + + logger.debug(border) + logger.debug("| #{'Type'.ljust(max_type_length)} | Row | Column | Dark icon fix |") + logger.debug(border) + + items_with_icons.each do |item| + logger.debug("| #{item[:type].ljust(max_type_length)} | #{item[:row].to_s.ljust(3)} | #{item[:col].to_s.ljust(6)} | #{(item[:dark_icon_fix] ? 'Yes' : 'No').ljust(13)} |") + end + + logger.debug(border) + end + + def logger + @logger ||= Logger.new($stdout).tap do |logger| + logger.level = options[:verbose] ? Logger::DEBUG : Logger::INFO + logger.formatter = proc {|severity, datetime, progname, msg| "#{msg}\n"} + end + end +end diff --git a/public/docs/docs.json b/public/docs/docs.json deleted file mode 100644 index 0637a088..00000000 --- a/public/docs/docs.json +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/public/icons/docs-1.pxm b/public/icons/docs-1.pxm deleted file mode 100644 index d9418ee7..00000000 Binary files a/public/icons/docs-1.pxm and /dev/null differ diff --git a/public/icons/docs-1@2x.pxm b/public/icons/docs-1@2x.pxm deleted file mode 100644 index d2b97c84..00000000 Binary files a/public/icons/docs-1@2x.pxm and /dev/null differ diff --git a/public/icons/docs-2.pxm b/public/icons/docs-2.pxm deleted file mode 100644 index ba5ce1b5..00000000 Binary files a/public/icons/docs-2.pxm and /dev/null differ diff --git a/public/icons/docs-2@2x.pxm b/public/icons/docs-2@2x.pxm deleted file mode 100644 index 3c390953..00000000 Binary files a/public/icons/docs-2@2x.pxm and /dev/null differ diff --git a/public/icons/docs/bluebird/16@2x.png b/public/icons/docs/bluebird/16@2x.png index 9ffae075..64ad5903 100644 Binary files a/public/icons/docs/bluebird/16@2x.png and b/public/icons/docs/bluebird/16@2x.png differ 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, '
' - end - - it "sets the theme from cookie" do - get '/' - assert_match %r{]*class="[^\"]*_theme-default}, last_response.body - refute_includes last_response.body, '_theme-dark' - - set_cookie('dark=1') - - get '/' - assert_match %r{]*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/test/lib/docs/core/scrapers/file_scraper_test.rb b/test/lib/docs/core/scrapers/file_scraper_test.rb index 7d90d262..88b5e8d5 100644 --- a/test/lib/docs/core/scrapers/file_scraper_test.rb +++ b/test/lib/docs/core/scrapers/file_scraper_test.rb @@ -63,7 +63,7 @@ class FileScraperTest < MiniTest::Spec end it "reads a file" do - mock(scraper).read_file(path) + mock(scraper).read_file(File.join(ROOT_PATH, 'docs/scraper', path)) result end @@ -165,7 +165,7 @@ class FileScraperTest < MiniTest::Spec describe "#read_file" do let :result do - scraper.send :read_file, 'file' + scraper.send :read_file, File.join(ROOT_PATH, 'docs', 'scraper', 'file') end it "returns the file's content when the file exists in the source directory" do diff --git a/views/app.erb b/views/app.erb index 7cffabd0..ffaa1bf3 100644 --- a/views/app.erb +++ b/views/app.erb @@ -28,13 +28,7 @@DevDocs is an API documentation browser which supports the following browsers:
If you're unable to upgrade, we apologize.