Introduced ESLint for code style checks

This commit is contained in:
squidfunk
2016-09-30 13:29:45 +02:00
parent 02915210f4
commit 46f45bb8a9
31 changed files with 1245 additions and 536 deletions

View File

@@ -20,221 +20,313 @@
* IN THE SOFTWARE.
*/
'use strict';
/* ----------------------------------------------------------------------------
* Imports
* ------------------------------------------------------------------------- */
import FastClick from 'fastclick';
import Sidebar from './components/sidebar';
import ScrollSpy from './components/scrollspy';
import Expander from './components/expander';
import FastClick from "fastclick"
import lunr from "lunr"
// import Expander from "./components/expander"
import Sidebar from "./components/sidebar"
import ScrollSpy from "./components/scrollspy"
// import Search from './components/search';
/* ----------------------------------------------------------------------------
* Application
* ------------------------------------------------------------------------- */
/* Initialize application upon DOM ready */
document.addEventListener('DOMContentLoaded', function() {
'use strict';
document.addEventListener("DOMContentLoaded", () => {
/* Test for iOS */
Modernizr.addTest('ios', function() {
return !!navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
});
Modernizr.addTest("ios", () => {
return !!navigator.userAgent.match(/(iPad|iPhone|iPod)/g)
})
/* Test for web application context */
Modernizr.addTest('standalone', function() {
return !!navigator.standalone;
});
Modernizr.addTest("standalone", () => {
return !!navigator.standalone
})
/* Attack FastClick to mitigate 300ms delay on touch devices */
FastClick.attach(document.body);
FastClick.attach(document.body)
const width = window.matchMedia("(min-width: 1200px)")
var width = window.matchMedia("(min-width: 1200px)");
var handler = function() {
const sidebar = new Sidebar(".md-sidebar--primary")
const handler = function() {
if (width.matches) {
sidebar.listen();
sidebar.listen()
} else {
sidebar.unlisten();
sidebar.unlisten()
}
}
handler() // check listen!
var sidebar = new Sidebar('.md-sidebar--primary');
handler(); // check listen!
const toc = new Sidebar(".md-sidebar--secondary")
toc.listen()
var toc = new Sidebar('.md-sidebar--secondary');
toc.listen();
const spy =
new ScrollSpy(".md-sidebar--secondary .md-nav--secondary .md-nav__link")
spy.listen()
var spy = new ScrollSpy('.md-sidebar--secondary .md-nav--secondary .md-nav__link');
spy.listen();
window.addEventListener("resize", handler)
window.addEventListener('resize', handler);
const query = document.getElementById("query")
query.addEventListener("focus", () => {
document.querySelector(".md-search").classList.add("md-js__search--locked")
})
/* Intercept click on search mode toggle */
var offset = 0;
var toggle = document.getElementById('search');
toggle.addEventListener('click', function(e) {
var list = document.body.classList;
var lock = !matchMedia('only screen and (min-width: 960px)').matches;
let offset = 0
const toggle = document.getElementById("search")
toggle.addEventListener("click", ev => {
const list = document.body.classList
const lock = !matchMedia("only screen and (min-width: 960px)").matches
/* Exiting search mode */
if (list.contains('md-js__body--locked')) {
list.remove('md-js__body--locked');
if (list.contains("md-js__body--locked")) {
list.remove("md-js__body--locked")
/* Scroll to former position, but wait for 100ms to prevent flashes
on iOS. A short timeout seems to do the trick */
if (lock)
setTimeout(function() {
window.scrollTo(0, offset);
}, 100);
setTimeout(() => {
window.scrollTo(0, offset)
}, 100)
/* Entering search mode */
} else {
offset = window.scrollY;
offset = window.scrollY
/* First timeout: scroll to top after transition, to omit flickering */
if (lock)
setTimeout(function() {
window.scrollTo(0, 0);
}, 400);
setTimeout(() => {
window.scrollTo(0, 0)
}, 400)
/* Second timeout: Lock body after finishing transition and scrolling to
top and focus input field. Sadly, the focus event is not dispatched
on iOS Safari and there's nothing we can do about it. */
setTimeout(function() {
setTimeout(() => {
/* This additional check is necessary to handle fast subsequent clicks
on the toggle and the timeout to lock the body must be cancelled */
if (this.checked) {
if (ev.target.checked) {
if (lock)
list.add('md-js__body--locked');
setTimeout(function() {
document.getElementById('md-search').focus();
}, 200);
list.add("md-js__body--locked")
setTimeout(() => {
document.getElementById("md-search").focus()
}, 200)
}
}.bind(this), 450);
}, 450)
}
});
})
// var toc = new Sidebar('.md-sidebar--secondary');
// toc.listen();
var toggles = document.querySelectorAll('.md-nav__item--nested > .md-nav__link');
[].forEach.call(toggles, (toggle) => {
let nav = toggle.nextElementSibling;
const toggles =
document.querySelectorAll(".md-nav__item--nested > .md-nav__link");
[].forEach.call(toggles, togglex => {
const nav = togglex.nextElementSibling
// 1.
nav.style.maxHeight = nav.getBoundingClientRect().height + 'px';
nav.style.maxHeight = `${nav.getBoundingClientRect().height}px`
toggle.addEventListener('click', function () {
let first = nav.getBoundingClientRect().height;
togglex.addEventListener("click", () => {
const first = nav.getBoundingClientRect().height
if (first) {
console.log('closing');
nav.style.maxHeight = first + 'px'; // reset!
// console.log('closing');
nav.style.maxHeight = `${first}px` // reset!
requestAnimationFrame(() => {
nav.classList.add('md-nav--transitioning');
nav.style.maxHeight = '0px';
});
nav.classList.add("md-nav--transitioning")
nav.style.maxHeight = "0px"
})
} else {
console.log('opening');
// console.log('opening');
/* Toggle and read height */
nav.style.maxHeight = '';
nav.style.maxHeight = ""
nav.classList.add('md-nav--toggled');
let last = nav.getBoundingClientRect().height;
nav.classList.remove('md-nav--toggled');
nav.classList.add("md-nav--toggled")
const last = nav.getBoundingClientRect().height
nav.classList.remove("md-nav--toggled")
// Initial state
nav.style.maxHeight = '0px';
nav.style.maxHeight = "0px"
/* Enable animations */
requestAnimationFrame(() => {
nav.classList.add('md-nav--transitioning');
nav.style.maxHeight = last + 'px';
});
nav.classList.add("md-nav--transitioning")
nav.style.maxHeight = `${last}px`
})
}
});
})
// Capture the end with transitionend
nav.addEventListener('transitionend', function() {
this.classList.remove('md-nav--transitioning');
if (this.getBoundingClientRect().height > 0) {
this.style.maxHeight = '100%';
nav.addEventListener("transitionend", ev => {
ev.target.classList.remove("md-nav--transitioning")
if (ev.target.getBoundingClientRect().height > 0) {
ev.target.style.maxHeight = "100%"
}
});
});
// document.querySelector('[for="nav-3"]').addEventListener('click', function() {
// var el = document.querySelector('[for="nav-3"] + nav');
//
// // TODO: do via class and disable transforms!!!
// el.style.maxHeight = '100%'; // class !?
//
// var rect = el.getBoundingClientRect();
//
// console.log(rect);
//
// el.style.maxHeight = '0px';
// requestAnimationFrame(function() {
// el.classList.add('md-nav--transitioning');
// el.style.maxHeight = rect.height + 'px';
// });
//
// // Capture the end with transitionend
// el.addEventListener('transitionend', function() {
// el.classList.remove('md-nav--transitioning');
// });
// });
})
})
// setTimeout(function() {
fetch('https://api.github.com/repos/squidfunk/mkdocs-material')
.then(function(response) {
fetch("https://api.github.com/repos/squidfunk/mkdocs-material")
.then(response => {
return response.json()
}).then(function(data) {
var stars = data.stargazers_count;
var forks = data.forks_count;
})
.then(data => {
const stars = data.stargazers_count
const forks = data.forks_count
// store in session!!!
var lists = document.querySelectorAll('.md-source__facts');
[].forEach.call(lists, function(list) {
// list.innerHTML += '<li class="md-source__fact">' + stars + ' Stars</li>\n';
// list.innerHTML += '<li>' + forks + ' Forks</li>\n';
const lists = document.querySelectorAll(".md-source__facts"); // TODO 2x list in drawer and header
[].forEach.call(lists, list => {
var li = document.createElement('li');
li.className = 'md-source__fact md-source__fact--hidden';
li.innerText = stars + ' Stars';
list.appendChild(li);
let li = document.createElement("li")
li.className = "md-source__fact md-source__fact--hidden"
li.innerText = `${stars} Stars`
list.appendChild(li)
setTimeout(lix => {
lix.classList.remove("md-source__fact--hidden")
}, 100, li)
setTimeout(function(li) {
li.classList.remove('md-source__fact--hidden');
}, 100, li);
li = document.createElement("li")
li.className = "md-source__fact md-source__fact--hidden"
li.innerText = `${forks} Forks`
list.appendChild(li)
li = document.createElement('li');
li.className = 'md-source__fact md-source__fact--hidden';
li.innerText = forks + ' Forks';
list.appendChild(li);
setTimeout(function(li) {
li.classList.remove('md-source__fact--hidden');
}, 500, li);
setTimeout(lix => {
lix.classList.remove("md-source__fact--hidden")
}, 500, li)
})
// setTimeout(function() {
// li.classList.remove('md-source__fact--hidden');
// }, 100);
}).catch(function(ex) {
console.log('parsing failed', ex)
});
})
.catch(() => {
// console.log("parsing failed", ex)
})
// setTimeout(function() {
fetch("/mkdocs/search_index.json") // TODO: prepend BASE URL!!!
.then(response => {
return response.json()
})
.then(data => {
// console.log(data)
/* Create index */
const index = lunr(() => {
/* eslint-disable no-invalid-this, lines-around-comment */
this.field("title", {boost: 10})
this.field("text")
this.ref("location")
/* eslint-enable no-invalid-this, lines-around-comment */
})
/* Index articles */
const articles = {}
data.docs.forEach(article => {
// TODO: match for two whitespaces, then replace unnecessary whitespace after string
article.text = article.text.replace(/\s(\.,\:)\s/gi, (string, g1) => {
return `${g1} `
})
// TODO: window.baseUrl sucks...
article.location = window.baseUrl + article.location
articles[article.location] = article
index.add(article)
})
/* Register keyhandler to execute search on key up */
const queryx = document.getElementById("query")
queryx.addEventListener("keyup", () => {
const container = document.querySelector(".md-search-result__list")
while (container.firstChild)
container.removeChild(container.firstChild)
// /* Abort, if the query is empty */
// var bar = document.querySelector('.bar.search');
// if (!query.value.length) {
// while (meta.firstChild)
// meta.removeChild(meta.firstChild);
//
// /* Restore state */
// bar.classList.remove('non-empty');
// return;
// }
/* Show reset button */
// bar.classList.add('non-empty');
/* Execute search */
const results = index.search(query.value)
results.forEach(result => {
const article = articles[result.ref]
/* Create a link referring to the article */
const link = document.createElement("a")
link.classList.add("md-search-result__link")
link.href = article.location
// /* Create article container */
const li = document.createElement("li")
li.classList.add("md-search-result__item")
li.appendChild(link)
/* Create title element */
const title = document.createElement("div")
title.classList.add("md-search-result__title")
// article.title.split(//)
title.innerHTML = article.title
link.appendChild(title)
/* Create text element */
const text = document.createElement("p")
text.classList.add("md-search-result__description")
text.innerHTML = article.text // .truncate(140);
link.appendChild(text)
container.appendChild(li)
})
/* Show number of search results */
// var number = document.createElement('strong');
const meta = document.querySelector(".md-search-result__meta")
meta.innerHTML = `${results.length} search result${
results.length !== 1
? "s"
: ""}`
/* Update number */
// while (meta.firstChild)
// meta.removeChild(meta.firstChild);
// meta.appendChild(number);
})
// setTimeout(function() {
// li.classList.remove('md-source__fact--hidden');
// }, 100);
})
.catch(() => {
// console.log("parsing failed", ex)
})
// }, 1000);
});
})

View File

@@ -20,8 +20,6 @@
* IN THE SOFTWARE.
*/
'use strict';
/* ----------------------------------------------------------------------------
* Navigation expander
* ------------------------------------------------------------------------- */
@@ -35,59 +33,59 @@ class Expander {
* @param {(string|HTMLElement)} el - Selector or HTML element
*/
constructor(el) {
this.el_ = (typeof el === 'string') ? document.querySelector(el) : el;
this.el_ = (typeof el === "string")
? document.querySelector(el)
: el
/* Event listener */
this.handler_ = ev => {
this.update(ev);
};
};
this.update(ev)
}
}
/**
* Update state of expandable element
*
* @param {Event} ev - Event
* @return {void}
*/
update(ev) {
console.log("foo");
};
update() {}
/**
* Reset state of expandable element
*
* @return {void}
*/
reset() {
// this.el_.classList.remove('md-js__sidebar--locked');
// this.el_.style.height = '';
//
// /* Reset parameters */
// this.height_ = 0;
// this.locked_ = false;
};
reset() {}
/**
* Register listener for all relevant events
*
* @return {void}
*/
listen() {
['click'].forEach(name => {
window.addEventListener(name, this.handler_, false);
});
};
["click"].forEach(name => {
window.addEventListener(name, this.handler_, false)
})
}
/**
* Unregister listener for all relevant events
*
* @return {void}
*/
unlisten() {
['click'].forEach(name => {
window.removeEventListener(name, this.handler_, false);
});
["click"].forEach(name => {
window.removeEventListener(name, this.handler_, false)
})
/* Perform reset */
this.reset();
};
this.reset()
}
}
/* ----------------------------------------------------------------------------
* Exports
* ------------------------------------------------------------------------- */
export default Expander;
export default Expander

View File

@@ -20,8 +20,6 @@
* IN THE SOFTWARE.
*/
'use strict';
/* ----------------------------------------------------------------------------
* Sidebar scroll-spy
* ------------------------------------------------------------------------- */
@@ -35,87 +33,96 @@ class ScrollSpy {
* @param {(string|HTMLCollection)} el - Selector or HTML elements
*/
constructor(el) {
this.el_ = (typeof el === 'string') ? document.querySelectorAll(el) : el;
this.el_ = (typeof el === "string")
? document.querySelectorAll(el)
: el
/* Initialize index for currently active element */
this.index_ = 0;
this.offset_ = window.pageYOffset;
this.index_ = 0
this.offset_ = window.pageYOffset
/* Event listener */
this.handler_ = ev => {
this.update(ev);
};
this.update(ev)
}
}
/**
* Update state of sidebar and hash
*
* @param {Event} ev - Event
* @param {Event} ev - Event (omitted)
* @return {void}
*/
update(ev) {
update() {
/* Scroll direction is down */
if (this.offset_ <= window.pageYOffset) {
for (let i = this.index_ + 1; i < this.el_.length; i++) {
let anchor = document.querySelector(this.el_[i].hash); // TODO: improve performance by caching
const anchor = document.querySelector(this.el_[i].hash) // TODO: improve performance by caching
if (anchor.offsetTop <= window.pageYOffset) {
if (i > 0)
this.el_[i - 1].classList.add('md-nav__link--marked');
this.index_ = i;
this.el_[i - 1].classList.add("md-nav__link--marked")
this.index_ = i
} else {
break;
break
}
}
/* Scroll direction is up */
} else {
for (let i = this.index_; i >= 0; i--) {
let anchor = document.querySelector(this.el_[i].hash);
const anchor = document.querySelector(this.el_[i].hash)
if (anchor.offsetTop > window.pageYOffset) {
if (i > 0)
this.el_[i - 1].classList.remove('md-nav__link--marked');
this.el_[i - 1].classList.remove("md-nav__link--marked")
} else {
this.index_ = i;
break;
this.index_ = i
break
}
}
}
/* Remember current offset for next cycle */
this.offset_ = window.pageYOffset;
this.offset_ = window.pageYOffset
}
/**
* Reset state of sidebar
*
* @return {void}
*/
reset() {
[].forEach.call(this.el_, el => {
el.classList.remove('md-nav__link--marked');
});
el.classList.remove("md-nav__link--marked")
})
}
/**
* Register listener for all relevant events
*
* @return {void}
*/
listen() {
['scroll', 'resize', 'orientationchange'].forEach(name => {
window.addEventListener(name, this.handler_, false);
});
["scroll", "resize", "orientationchange"].forEach(name => {
window.addEventListener(name, this.handler_, false)
})
/* Initial update */
this.update();
this.update()
}
/**
* Unregister listener for all relevant events
*
* @return {void}
*/
unlisten() {
['scroll', 'resize', 'orientationchange'].forEach(name => {
window.removeEventListener(name, this.handler_, false);
});
["scroll", "resize", "orientationchange"].forEach(name => {
window.removeEventListener(name, this.handler_, false)
})
/* Perform reset */
this.reset();
this.reset()
}
}
@@ -123,4 +130,4 @@ class ScrollSpy {
* Exports
* ------------------------------------------------------------------------- */
export default ScrollSpy;
export default ScrollSpy

View File

@@ -0,0 +1,98 @@
/*
* Copyright (c) 2016 Martin Donath <martin.donath@squidfunk.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
"use strict"
/* ----------------------------------------------------------------------------
* Search
* ------------------------------------------------------------------------- */
class Search {
/**
* Constructor
*
* @constructor
* @param {(string|HTMLElement)} el - Selector or HTML element
*/
constructor(el) {
this.el_ = (typeof el === "string") ? document.querySelector(el) : el
/* Event listener */
this.handler_ = ev => {
this.update(ev)
}
}
/**
* Update state and height of sidebar
*
* @param {Event} ev - Event
* @return {void}
*/
update() {
}
/**
* Reset state and height of sidebar
*
* @return {void}
*/
reset() {
}
/**
* Register listener for all relevant events
*
* @return {void}
*/
listen() {
// ['scroll', 'resize', 'orientationchange'].forEach(name => {
// window.addEventListener(name, this.handler_, false);
// });
/* Initial update */
this.update()
}
/**
* Unregister listener for all relevant events
*
* @return {void}
*/
unlisten() {
// ['scroll', 'resize', 'orientationchange'].forEach(name => {
// window.removeEventListener(name, this.handler_, false);
// });
/* Perform reset */
this.reset()
}
}
/* ----------------------------------------------------------------------------
* Exports
* ------------------------------------------------------------------------- */
export default Search

View File

@@ -20,8 +20,6 @@
* IN THE SOFTWARE.
*/
'use strict';
/* ----------------------------------------------------------------------------
* Sidebar sticky-scroll handler
* ------------------------------------------------------------------------- */
@@ -35,101 +33,110 @@ class Sidebar {
* @param {(string|HTMLElement)} el - Selector or HTML element
*/
constructor(el) {
this.el_ = (typeof el === 'string') ? document.querySelector(el) : el;
this.el_ = (typeof el === "string")
? document.querySelector(el)
: el
/* Grab inner and outer container */
this.inner_ = this.el_.parentNode;
this.outer_ = this.el_.parentNode.parentNode;
this.inner_ = this.el_.parentNode
this.outer_ = this.el_.parentNode.parentNode
/* Initialize parameters */
this.height_ = 0;
this.locked_ = false;
this.height_ = 0
this.locked_ = false
/* Event listener */
this.handler_ = ev => {
this.update(ev);
};
};
this.update(ev)
}
}
/**
* Update state and height of sidebar
*
* @param {Event} ev - Event
* @return {void}
*/
update(ev) {
let bounds = this.inner_.getBoundingClientRect();
let parent = this.outer_.offsetTop;
update() {
const bounds = this.inner_.getBoundingClientRect()
const parent = this.outer_.offsetTop
/* Determine top and bottom offsets */
let top = bounds.top + window.pageYOffset,
bottom = bounds.bottom + window.pageYOffset;
const top = bounds.top + window.pageYOffset,
bottom = bounds.bottom + window.pageYOffset
/* Determine current y-offset at top and bottom of window */
let upper = window.pageYOffset,
lower = window.pageYOffset + window.innerHeight;
const upper = window.pageYOffset,
lower = window.pageYOffset + window.innerHeight
/* Calculate new bounds */
let offset = top - upper;
let height = window.innerHeight - Math.max(lower - bottom, 0)
- Math.max(offset, parent);
const offset = top - upper
const height = window.innerHeight - Math.max(lower - bottom, 0)
- Math.max(offset, parent)
/* If height changed, update element */
if (height != this.height_)
this.el_.style.height = (this.height_ = height) + 'px';
if (height !== this.height_)
this.el_.style.height = `${this.height_ = height}px`
/* Sidebar should be locked, as we're below parent offset */
if (offset < parent) {
if (!this.locked_) {
this.el_.classList.add('md-js__sidebar--locked');
this.locked_ = true;
this.el_.classList.add("md-js__sidebar--locked")
this.locked_ = true
}
/* Sidebar should be unlocked, if locked */
} else if (this.locked_) {
this.el_.classList.remove('md-js__sidebar--locked');
this.locked_ = false;
this.el_.classList.remove("md-js__sidebar--locked")
this.locked_ = false
}
};
}
/**
* Reset state and height of sidebar
*
* @return {void}
*/
reset() {
this.el_.classList.remove('md-js__sidebar--locked');
this.el_.style.height = '';
this.el_.classList.remove("md-js__sidebar--locked")
this.el_.style.height = ""
/* Reset parameters */
this.height_ = 0;
this.locked_ = false;
};
this.height_ = 0
this.locked_ = false
}
/**
* Register listener for all relevant events
*
* @return {void}
*/
listen() {
['scroll', 'resize', 'orientationchange'].forEach(name => {
window.addEventListener(name, this.handler_, false);
});
["scroll", "resize", "orientationchange"].forEach(name => {
window.addEventListener(name, this.handler_, false)
})
/* Initial update */
this.update();
};
this.update()
}
/**
* Unregister listener for all relevant events
*
* @return {void}
*/
unlisten() {
['scroll', 'resize', 'orientationchange'].forEach(name => {
window.removeEventListener(name, this.handler_, false);
});
["scroll", "resize", "orientationchange"].forEach(name => {
window.removeEventListener(name, this.handler_, false)
})
/* Perform reset */
this.reset();
};
this.reset()
}
}
/* ----------------------------------------------------------------------------
* Exports
* ------------------------------------------------------------------------- */
export default Sidebar;
export default Sidebar