diff --git a/.editorconfig b/.editorconfig index 73db316c..03c17bf8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,3 +6,6 @@ indent_style = space indent_size = 2 insert_final_newline = true trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index d1f848bd..d2317ab5 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -24,12 +24,12 @@ Want to contribute? Great. Please review the following guidelines carefully and ## Requesting new features 1. Search for similar feature requests; someone may have already requested it. -2. Make sure your feature fits DevDocs's [vision](https://github.com/freeCodeCamp/devdocs/blob/master/README.md#vision). +2. Make sure your feature fits DevDocs's [vision](../README.md#vision). 3. Provide a clear and detailed explanation of the feature and why it's important to add it. ## Requesting new documentations -Please don't open issues to request new documentations. +Please don't open issues to request new documentations. Use the [Trello board](https://trello.com/b/6BmTulfx/devdocs-documentation) where everyone can vote. ## Contributing code and features @@ -44,7 +44,7 @@ Use the [Trello board](https://trello.com/b/6BmTulfx/devdocs-documentation) wher ## Contributing new documentations -See the [wiki](https://github.com/freeCodeCamp/devdocs/wiki) to learn how to add new documentations. +See the [`docs` folder](https://github.com/freeCodeCamp/devdocs/tree/master/docs) to learn how to add new documentations. **Important:** the documentation's license must permit alteration, redistribution and commercial use, and the documented software must be released under an open source license. Feel free to get in touch if you're not sure if a documentation meets those requirements. 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/.travis.yml b/.travis.yml index d5e5a6aa..0e64a76a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,3 +5,11 @@ cache: bundler before_script: - gem update --system - gem install bundler + +deploy: + provider: heroku + app: devdocs + on: + branch: master + api_key: + secure: "4p1klvWJZSOImzFcKOduILjP93hlOlAhceWlYMKS4tU+TCFE8qTBzdKdFPSCsCgjB+YR9pBss+L0lJpVVMjSwFHXqpKe6EeUSltO2k7DFHfW7kXLUM/L0AfqXz+YXk76XUyZMhvOEbldPfaMaj10e8vgDOQCSHABDyK/4CU+hnI=" diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..26f8ab09 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,2 @@ + +> Our Code of Conduct is available here: 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/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..0df55970 --- /dev/null +++ b/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,11 @@ +If you’re adding a new scraper, please ensure that you have: + +- [ ] Tested the scraper on a local copy of DevDocs +- [ ] Ensured that the docs are styled similarly to other docs on DevDocs + +- [ ] Added these files to the public/icons/*your_scraper_name*/ directory: + - [ ] `16.png`: a 16×16 pixel icon for the doc + - [ ] `16@2x.png`: a 32×32 pixel icon for the doc + - [ ] `SOURCE`: A text file containing the URL to the page the image can be found on or the URL of the original image itself + + diff --git a/README.md b/README.md index 837b07ad..630142d4 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Keep track of development news: * Watch the repository on [GitHub](https://github.com/freeCodeCamp/devdocs/subscription) * Follow [@DevDocs](https://twitter.com/DevDocs) on Twitter -**Table of Contents:** [Quick Start](#quick-start) · [Vision](#vision) · [App](#app) · [Scraper](#scraper) · [Commands](#available-commands) · [Contributing](#contributing) · [License](#copyright--license) · [Questions?](#questions) +**Table of Contents:** [Quick Start](#quick-start) · [Vision](#vision) · [App](#app) · [Scraper](#scraper) · [Commands](#available-commands) · [Contributing](#contributing) · [Documentation](#documentation) · [Plugins and Extensions](#plugins-and-extensions) · [License](#copyright--license) · [Questions?](#questions) ## Quick Start @@ -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! @@ -83,12 +83,13 @@ Modifications made to each document include: * replacing all external (not scraped) URLs with their fully qualified counterpart * replacing all internal (scraped) URLs with their unqualified and relative counterpart * adding content, such as a title and link to the original document +* ensuring correct syntax highlighting using [Prism](http://prismjs.com/) These modifications are applied via a set of filters using the [HTML::Pipeline](https://github.com/jch/html-pipeline) library. Each scraper includes filters specific to itself, one of which is tasked with figuring out the pages' metadata. The end result is a set of normalized HTML partials and two JSON files (index + offline data). Because the index files are loaded separately by the [app](#app) following the user's preferences, the scraper also creates a JSON manifest file containing information about the documentations currently available on the system (such as their name, version, update date, etc.). -More information about scrapers and filters is available on the [wiki](https://github.com/freeCodeCamp/devdocs/wiki). +More information about [scrapers](./docs/scraper-reference.md) and [filters](./docs/filter-reference.md) is available in the `docs` folder. ## Available Commands @@ -128,15 +129,40 @@ If multiple versions of Ruby are installed on your system, commands must be run ## Contributing -Contributions are welcome. Please read the [contributing guidelines](https://github.com/freeCodeCamp/devdocs/blob/master/.github/CONTRIBUTING.md). - -DevDocs's own documentation is available on the [wiki](https://github.com/freeCodeCamp/devdocs/wiki). +Contributions are welcome. Please read the [contributing guidelines](./.github/CONTRIBUTING.md). + +## Documentation + +* [Adding documentations to DevDocs](./docs/adding-docs.md) +* [Scraper Reference](./docs/scraper-reference.md) +* [Filter Reference](./docs/filter-reference.md) +* [Maintainers’ Guide](./docs/maintainers.md) + +## Plugins and Extensions + +* [Chrome web app](https://chrome.google.com/webstore/detail/devdocs/mnfehgbmkapmjnhcnbodoamcioleeooe) +* [Ubuntu Touch app](https://uappexplorer.com/app/devdocsunofficial.berkes) +* [Sublime Text plugin](https://sublime.wbond.net/packages/DevDocs) +* [Atom plugin](https://atom.io/packages/devdocs) +* [Brackets extension](https://github.com/gruehle/dev-docs-viewer) +* [Fluid](http://fluidapp.com) for turning DevDocs into a real OS X app +* [GTK shell / Vim integration](https://github.com/naquad/devdocs-shell) +* [Emacs lookup](https://github.com/skeeto/devdocs-lookup) +* [Alfred Workflow](https://github.com/yannickglt/alfred-devdocs) +* [Vim search plugin with Devdocs in its defaults](https://github.com/waiting-for-dev/vim-www) Just set `let g:www_shortcut_engines = { 'devdocs': ['Devdocs', 'dd'] }` to have a `:Devdocs` command and a `dd` mapping. +* [Visual Studio Code plugin](https://marketplace.visualstudio.com/items?itemName=akfish.vscode-devdocs ) (1) +* [Visual Studio Code plugin](https://marketplace.visualstudio.com/items?itemName=deibit.devdocs) (2) +* [Desktop application](https://github.com/egoist/devdocs-desktop) +* [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 ## Copyright / License Copyright 2013-2019 Thibaut Courouble and [other contributors](https://github.com/freeCodeCamp/devdocs/graphs/contributors) -This software is licensed under the terms of the Mozilla Public License v2.0. See the [COPYRIGHT](https://github.com/freeCodeCamp/devdocs/blob/master/COPYRIGHT) and [LICENSE](https://github.com/freeCodeCamp/devdocs/blob/master/LICENSE) files. +This software is licensed under the terms of the Mozilla Public License v2.0. See the [COPYRIGHT](./COPYRIGHT) and [LICENSE](./LICENSE) files. Please do not use the name DevDocs to endorse or promote products derived from this software without the maintainers' permission, except as may be necessary to comply with the notice/attribution requirements. diff --git a/assets/javascripts/app/app.coffee b/assets/javascripts/app/app.coffee index ab67a92a..f92e296c 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 @@ -147,7 +149,7 @@ saveDocs: -> @settings.setDocs(doc.slug for doc in @docs.all()) @db.migrate() - @appCache?.updateInBackground() + @serviceWorker?.updateInBackground() welcomeBack: -> visitCount = @settings.get('count') @@ -167,14 +169,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 +195,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 +254,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 ca7ccbc6..a03d0b5e 100644 --- a/assets/javascripts/app/settings.coffee +++ b/assets/javascripts/app/settings.coffee @@ -20,6 +20,8 @@ class app.Settings 'news' ] + LAYOUTS: ['_max-width', '_sidebar-hidden', '_native-scrollbars'] + @defaults: count: 0 hideDisabled: false @@ -40,6 +42,7 @@ class app.Settings set: (key, value) -> @store.set(key, value) delete @cache[key] + @toggleDark(value) if key == 'dark' return del: (key) -> @@ -65,6 +68,8 @@ class app.Settings return setLayout: (name, enable) -> + @toggleLayout(name, enable) + layout = (@store.get('layout') || '').split(' ') $.arrayDelete(layout, '') @@ -106,3 +111,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/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/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:

  • Recent versions of Firefox, Chrome, or Opera -
  • Safari 9.1+ -
  • Edge 16+ -
  • iOS 10+ +
  • Safari 11.1+ +
  • Edge 17+ +
  • iOS 11.3+

If you're unable to upgrade, we apologize. 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) -> """

Questions & Answers

How does this work? -
Each page is cached as a key-value pair in IndexedDB (downloaded from a single file).
- The app also uses AppCache and localStorage to cache the assets and index files. +
Each page is cached as a key-value pair in IndexedDB (downloaded from a single file).
+ The app also uses Service Workers and localStorage to cache the assets and index files.
Can I close the tab/browser?
#{canICloseTheTab()}
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 devdocs.io, 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 devdocs.io offline won't work.
+ 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 ENABLE_SERVICE_WORKER environment variable to true)" + + """ No. Service Workers #{reason}, so loading devdocs.io offline won't work.
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 7adce7fd..714e0e20 100644 --- a/assets/javascripts/templates/pages/root_tmpl.coffee.erb +++ b/assets/javascripts/templates/pages/root_tmpl.coffee.erb @@ -8,7 +8,7 @@ app.templates.intro = """

Thanks for downloading DevDocs. Here are a few things you should know:

  1. Your local version of DevDocs won't self-update. Unless you're modifying the code, - I recommend using the hosted version at devdocs.io. + we recommend using the hosted version at devdocs.io.
  2. Run thor docs:list to see all available documentations.
  3. Run thor docs:download <name> to download documentations.
  4. Run thor docs:download --installed to update all downloaded documentations. @@ -39,7 +39,7 @@ app.templates.intro = """
  5. DevDocs works offline, on mobile, and can be installed on Chrome.
  6. For the latest news, follow @DevDocs.
  7. DevDocs is free and open source. - +
  8. And if you're new to coding, check out freeCodeCamp's open source curriculum.

Happy coding! 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 ed574097..21de111a 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: @@ -18,25 +15,18 @@ class app.views.SettingsPage extends app.View settings.smoothScroll = !app.settings.get('fastScroll') settings.arrowScroll = app.settings.get('arrowScroll') settings.analyticsConsent = app.settings.get('analyticsConsent') - settings[layout] = app.settings.hasLayout(layout) for layout in LAYOUTS + 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) -> 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/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/docs/adding-docs.md b/docs/adding-docs.md new file mode 100644 index 00000000..dfc96cb1 --- /dev/null +++ b/docs/adding-docs.md @@ -0,0 +1,23 @@ +Adding a documentation may look like a daunting task but once you get the hang of it, it's actually quite simple. Don't hesitate to ask for help [in Gitter](https://gitter.im/FreeCodeCamp/DevDocs) if you ever get stuck. + +**Note:** please read the [contributing guidelines](../.github/CONTRIBUTING.md) before submitting a new documentation. + +1. Create a subclass of `Docs::UrlScraper` or `Docs::FileScraper` in the `lib/docs/scrapers/` directory. Its name should be the [PascalCase](http://api.rubyonrails.org/classes/String.html#method-i-camelize) equivalent of the filename (e.g. `my_doc` → `MyDoc`) +2. Add the appropriate class attributes and filter options (see the [Scraper Reference](./scraper-reference.md) page). +3. Check that the scraper is listed in `thor docs:list`. +4. Create filters specific to the scraper in the `lib/docs/filters/[my_doc]/` directory and add them to the class's [filter stacks](./scraper-reference.md#filter-stacks). You may create any number of filters but will need at least the following two: + * A [`CleanHtml`](./filter-reference.md#cleanhtmlfilter) filter whose task is to clean the HTML markup (e.g. adding `id` attributes to headings) and remove everything superfluous and/or nonessential. + * An [`Entries`](./filter-reference.md#entriesfilter) filter whose task is to determine the pages' metadata (the list of entries, each with a name, type and path). + The [Filter Reference](./filter-reference.md) page has all the details about filters. +5. Using the `thor docs:page [my_doc] [path]` command, check that the scraper works properly. Files will appear in the `public/docs/[my_doc]/` directory (but not inside the app as the command doesn't touch the index). `path` in this case refers to either the remote path (if using `UrlScraper`) or the local path (if using `FileScraper`). +6. Generate the full documentation using the `thor docs:generate [my_doc] --force` command. Additionally, you can use the `--verbose` option to see which files are being created/updated/deleted (useful to see what changed since the last run), and the `--debug` option to see which URLs are being requested and added to the queue (useful to pin down which page adds unwanted URLs to the queue). +7. Start the server, open the app, enable the documentation, and see how everything plays out. +8. Tweak the scraper/filters and repeat 5) and 6) until the pages and metadata are ok. +9. To customize the pages' styling, create an SCSS file in the `assets/stylesheets/pages/` directory and import it in both `application.css.scss` AND `application-dark.css.scss`. Both the file and CSS class should be named `_[type]` where [type] is equal to the scraper's `type` attribute (documentations with the same type share the same custom CSS and JS). Setting the type to `simple` will apply the general styling rules in `assets/stylesheets/pages/_simple.scss`, which can be used for documentations where little to no CSS changes are needed. +10. To add syntax highlighting or execute custom JavaScript on the pages, create a file in the `assets/javascripts/views/pages/` directory (take a look at the other files to see how it works). +11. Add the documentation's icon in the `public/icons/docs/[my_doc]/` directory, in both 16x16 and 32x32-pixels formats. It'll be added to the icon spritesheet after your pull request is merged. +12. Add the documentation's copyright details to the list in `assets/javascripts/templates/pages/about_tmpl.coffee`. This is the data shown in the table on the [about](https://devdocs.io/about) page, and is ordered alphabetically. Simply copying an existing item, placing it in the right slot and updating the values to match the new scraper will do the job. + +If the documentation includes more than a few hundreds pages and is available for download, try to scrape it locally (e.g. using `FileScraper`). It'll make the development process much faster and avoids putting too much load on the source site. (It's not a problem if your scraper is coupled to your local setup, just explain how it works in your pull request.) + +Finally, try to document your scraper and filters' behavior as much as possible using comments (e.g. why some URLs are ignored, HTML markup removed, metadata that way, etc.). It'll make updating the documentation much easier. diff --git a/docs/filter-reference.md b/docs/filter-reference.md new file mode 100644 index 00000000..f5c74c66 --- /dev/null +++ b/docs/filter-reference.md @@ -0,0 +1,224 @@ +**Table of contents:** + +* [Overview](#overview) +* [Instance methods](#instance-methods) +* [Core filters](#core-filters) +* [Custom filters](#custom-filters) + - [CleanHtmlFilter](#cleanhtmlfilter) + - [EntriesFilter](#entriesfilter) + +## Overview + +Filters use the [HTML::Pipeline](https://github.com/jch/html-pipeline) library. They take an HTML string or [Nokogiri](http://nokogiri.org/) node as input, optionally perform modifications and/or extract information from it, and then outputs the result. Together they form a pipeline where each filter hands its output to the next filter's input. Every documentation page passes through this pipeline before being copied on the local filesystem. + +Filters are subclasses of the [`Docs::Filter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/core/filter.rb) class and require a `call` method. A basic implementation looks like this: + +```ruby +module Docs + class CustomFilter < Filter + def call + doc + end + end +end +``` + +Filters which manipulate the Nokogiri node object (`doc` and related methods) are _HTML filters_ and must not manipulate the HTML string (`html`). Vice-versa, filters which manipulate the string representation of the document are _text filters_ and must not manipulate the Nokogiri node object. The two types are divided into two stacks within the scrapers. These stacks are then combined into a pipeline that calls the HTML filters before the text filters (more details [here](./scraper-reference.md#filter-stacks)). This is to avoid parsing the document multiple times. + +The `call` method must return either `doc` or `html`, depending on the type of filter. + +## Instance methods + +* `doc` [Nokogiri::XML::Node] + The Nokogiri representation of the container element. + See [Nokogiri's API docs](http://www.rubydoc.info/github/sparklemotion/nokogiri/Nokogiri/XML/Node) for the list of available methods. + +* `html` [String] + The string representation of the container element. + +* `context` [Hash] **(frozen)** + The scraper's `options` along with a few additional keys: `:base_url`, `:root_url`, `:root_page` and `:url`. + +* `result` [Hash] + Used to store the page's metadata and pass back information to the scraper. + Possible keys: + + - `:path` — the page's normalized path + - `:store_path` — the path where the page will be stored (equal to `:path` with `.html` at the end) + - `:internal_urls` — the list of distinct internal URLs found within the page + - `:entries` — the [`Entry`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/core/models/entry.rb) objects to add to the index + +* `css`, `at_css`, `xpath`, `at_xpath` + Shortcuts for `doc.css`, `doc.xpath`, etc. + +* `base_url`, `current_url`, `root_url` [Docs::URL] + Shortcuts for `context[:base_url]`, `context[:url]`, and `context[:root_url]` respectively. + +* `root_path` [String] + Shortcut for `context[:root_path]`. + +* `subpath` [String] + The sub-path from the base URL of the current URL. + _Example: if `base_url` equals `example.com/docs` and `current_url` equals `example.com/docs/file?raw`, the returned value is `/file`._ + +* `slug` [String] + The `subpath` removed of any leading slash or `.html` extension. + _Example: if `subpath` equals `/dir/file.html`, the returned value is `dir/file`._ + +* `root_page?` [Boolean] + Returns `true` if the current page is the root page. + +* `initial_page?` [Boolean] + Returns `true` if the current page is the root page or its subpath is one of the scraper's `initial_paths`. + +## Core filters + +* [`ContainerFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/container.rb) — changes the root node of the document (remove everything outside) +* [`CleanHtmlFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/clean_html.rb) — removes HTML comments, `