Improve JS code style.

This commit is contained in:
Cotes Chung 2020-08-19 12:26:45 +08:00
parent a8f8bbaa1c
commit 9b35380849
11 changed files with 268 additions and 262 deletions

View file

@ -3,16 +3,16 @@ Reference: https://bootsnipp.com/snippets/featured/link-to-top-page
*/
$(window).scroll(function() {
if ($(this).scrollTop() > 50
&& $('#sidebar-trigger').css('display') == 'none') {
$('#back-to-top').fadeIn();
&& $("#sidebar-trigger").css("display") === "none") {
$("#back-to-top").fadeIn();
} else {
$('#back-to-top').fadeOut();
$("#back-to-top").fadeOut();
}
});
$(function() {
$('#back-to-top').click(function() {
$('body,html').animate({scrollTop: 0}, 800);
$("#back-to-top").click(function() {
$("body,html").animate({scrollTop: 0}, 800);
return false;
});
});

View file

@ -1,13 +1,16 @@
/*
* Copy current page url to clipboard.
* v2.1
* https://github.com/cotes2020/jekyll-theme-chirpy
* © 2020 Cotes Chung
* MIT License
*/
* Copy current page url to clipboard.
* v2.1
* https://github.com/cotes2020/jekyll-theme-chirpy
* © 2020 Cotes Chung
* MIT License
*/
function copyLink(url) {
if (!url || 0 === url.length)
if (!url || 0 === url.length) {
return;
}
url = window.location.href;
var $temp = $("<input>");
@ -17,4 +20,5 @@ function copyLink(url) {
$temp.remove();
alert("Link copied successfully!");
}

View file

@ -8,18 +8,18 @@
$(function() {
var btnSbTrigger = $('#sidebar-trigger');
var btnSearchTrigger = $('#search-trigger');
var btnCancel = $('#search-cancel');
var btnClear = $('#search-cleaner');
var btnSbTrigger = $("#sidebar-trigger");
var btnSearchTrigger = $("#search-trigger");
var btnCancel = $("#search-cancel");
var btnClear = $("#search-cleaner");
var main = $('#main');
var topbarTitle = $('#topbar-title');
var searchWrapper = $('#search-wrapper');
var resultWrapper = $('#search-result-wrapper');
var results = $('#search-results');
var input = $('#search-input');
var hints = $('#search-hints');
var main = $("#main");
var topbarTitle = $("#topbar-title");
var searchWrapper = $("#search-wrapper");
var resultWrapper = $("#search-result-wrapper");
var results = $("#search-results");
var input = $("#search-input");
var hints = $("#search-hints");
/*--- Actions in small screens (Sidebar unloaded) ---*/
@ -27,75 +27,76 @@ $(function() {
var scrollBlocker = (function() {
var offset = 0;
return {
block: function() {
block() {
offset = $(window).scrollTop();
},
release: function() {
$('html,body').scrollTop(offset);
release() {
$("html,body").scrollTop(offset);
},
getOffset: function() {
getOffset() {
return offset;
}
}
})();
};
}());
var mobileSearchBar = (function() {
return {
on: function() {
btnSbTrigger.addClass('unloaded');
topbarTitle.addClass('unloaded');
btnSearchTrigger.addClass('unloaded');
searchWrapper.addClass('d-flex');
btnCancel.addClass('loaded');
on() {
btnSbTrigger.addClass("unloaded");
topbarTitle.addClass("unloaded");
btnSearchTrigger.addClass("unloaded");
searchWrapper.addClass("d-flex");
btnCancel.addClass("loaded");
},
off: function() {
btnCancel.removeClass('loaded');
searchWrapper.removeClass('d-flex');
btnSbTrigger.removeClass('unloaded');
topbarTitle.removeClass('unloaded');
btnSearchTrigger.removeClass('unloaded');
off() {
btnCancel.removeClass("loaded");
searchWrapper.removeClass("d-flex");
btnSbTrigger.removeClass("unloaded");
topbarTitle.removeClass("unloaded");
btnSearchTrigger.removeClass("unloaded");
}
}
})();
};
}());
var resultSwitch = (function() {
var visable = false;
return {
on: function() {
on() {
if (!visable) {
resultWrapper.removeClass('unloaded');
main.addClass('hidden');
resultWrapper.removeClass("unloaded");
main.addClass("hidden");
visable = true;
scrollBlocker.block();
}
},
off: function() {
off() {
if (visable) {
results.empty();
if (hints.hasClass('unloaded')) {
hints.removeClass('unloaded');
if (hints.hasClass("unloaded")) {
hints.removeClass("unloaded");
}
resultWrapper.addClass('unloaded');
btnClear.removeClass('visable');
main.removeClass('hidden');
resultWrapper.addClass("unloaded");
btnClear.removeClass("visable");
main.removeClass("hidden");
input.val('');
input.val("");
visable = false;
scrollBlocker.release();
}
},
isVisable: function() {
isVisable() {
return visable;
}
}
})();
};
}());
function isMobileView() {
return btnCancel.hasClass('loaded');
return btnCancel.hasClass("loaded");
}
btnSearchTrigger.click(function() {
@ -110,45 +111,45 @@ $(function() {
});
input.focus(function() {
searchWrapper.addClass('input-focus');
searchWrapper.addClass("input-focus");
});
input.focusout(function() {
searchWrapper.removeClass('input-focus');
searchWrapper.removeClass("input-focus");
});
input.on('keyup', function(e) {
if (e.keyCode == 8 && input.val() == '') {
input.on("keyup", function(e) {
if (e.keyCode === 8 && input.val() === "") {
if (!isMobileView()) {
resultSwitch.off();
} else {
hints.removeClass('unloaded');
hints.removeClass("unloaded");
}
} else {
if (input.val() != '') {
if (input.val() !== "") {
resultSwitch.on();
if (!btnClear.hasClass('visible')) {
btnClear.addClass('visable');
if (!btnClear.hasClass("visible")) {
btnClear.addClass("visable");
}
if (isMobileView()) {
hints.addClass('unloaded');
hints.addClass("unloaded");
}
}
}
});
btnClear.on('click', function() {
input.val('');
btnClear.on("click", function() {
input.val("");
if (isMobileView()) {
hints.removeClass('unloaded');
hints.removeClass("unloaded");
results.empty();
} else {
resultSwitch.off();
}
input.focus();
btnClear.removeClass('visable');
btnClear.removeClass("visable");
});
});
});

View file

@ -11,24 +11,24 @@ $(function() {
var sidebarUtil = (function() {
const ATTR_DISPLAY = "sidebar-display";
var isExpanded = false;
var body = $('body');
var body = $("body");
return {
toggle: function() {
if (isExpanded == false) {
body.attr(ATTR_DISPLAY, '');
toggle() {
if (isExpanded === false) {
body.attr(ATTR_DISPLAY, "");
} else {
body.removeAttr(ATTR_DISPLAY);
}
isExpanded = !isExpanded;
}
}
};
})();
}());
$("#sidebar-trigger").click(sidebarUtil.toggle);
$('#mask').click(sidebarUtil.toggle);
$("#mask").click(sidebarUtil.toggle);
});

View file

@ -11,7 +11,47 @@ $(function() {
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var topbarHeight = $('#topbar-wrapper').outerHeight();
var topbarHeight = $("#topbar-wrapper").outerHeight();
function hasScrolled() {
var st = $(this).scrollTop();
/* Make sure they scroll more than delta */
if (Math.abs(lastScrollTop - st) <= delta) {
return;
}
if (st > lastScrollTop && st > topbarHeight) {
/* Scroll Down */
$("#topbar-wrapper").removeClass("topbar-down").addClass("topbar-up");
if ($("#toc-wrapper").length > 0) {
$("#toc-wrapper").removeClass("topbar-down");
}
if ($(".access").length > 0) {
$(".access").removeClass("topbar-down");
}
if ($("#search-input").is(":focus")) {
$("#search-input").blur(); /* remove focus */
}
} else {
/* Scroll Up */
if (st + $(window).height() < $(document).height()) {
$("#topbar-wrapper").removeClass("topbar-up").addClass("topbar-down");
if ($("#toc-wrapper").length > 0) {
$("#toc-wrapper").addClass("topbar-down");
}
if ($(".access").length > 0) {
$(".access").addClass("topbar-down");
}
}
}
lastScrollTop = st;
}
$(window).scroll(function(event) {
if ($("#topbar-title").is(":hidden")) { /* Not in small screens */
@ -26,42 +66,4 @@ $(function() {
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
/* Make sure they scroll more than delta */
if (Math.abs(lastScrollTop - st) <= delta)
return;
if (st > lastScrollTop && st > topbarHeight) {
/* Scroll Down */
$('#topbar-wrapper').removeClass('topbar-down').addClass('topbar-up');
if ( $('#toc-wrapper').length > 0) {
$('#toc-wrapper').removeClass('topbar-down');
}
if ( $('.access').length > 0) {
$('.access').removeClass('topbar-down');
}
if ($('#search-input').is(':focus')) {
$('#search-input').blur(); /* remove focus */
}
} else {
/* Scroll Up */
if (st + $(window).height() < $(document).height()) {
$('#topbar-wrapper').removeClass('topbar-up').addClass('topbar-down');
if ( $('#toc-wrapper').length > 0) {
$('#toc-wrapper').addClass('topbar-down');
}
if ( $('.access').length > 0) {
$('.access').addClass('topbar-down');
}
}
}
lastScrollTop = st;
}
});

View file

@ -13,9 +13,9 @@ $(function() {
$("div.post>h1").text().trim() : $("h1").text().trim();
if ($("#page-category").length || $("#page-tag").length) {
/* The title in Category or Tag page will be '<title> <count_of_posts>' */
/* The title in Category or Tag page will be "<title> <count_of_posts>" */
if (/\s/.test(title)) {
title = title.replace(/[0-9]/g, '').trim();
title = title.replace(/[0-9]/g, "").trim();
}
}
@ -29,19 +29,19 @@ $(function() {
}
if ($(this).scrollTop() >= 95) {
if ($("#topbar-title").text() != title) {
if ($("#topbar-title").text() !== title) {
$("#topbar-title").text(title);
}
} else {
if ($("#topbar-title").text() != DEFAULT) {
if ($("#topbar-title").text() !== DEFAULT) {
$("#topbar-title").text(DEFAULT);
}
}
});
/* Click title remove hover effect. */
$('#topbar-title').click(function() {
$('body,html').animate({scrollTop: 0}, 800);
$("#topbar-title").click(function() {
$("body,html").animate({scrollTop: 0}, 800);
});
});

View file

@ -7,26 +7,26 @@
*/
$(function() {
var child_prefix = "l_";
var parent_prefix = "h_";
var childPrefix = "l_";
var parentPrefix = "h_";
/* close up top-category */
$(".collapse").on("hide.bs.collapse", function() { /* Bootstrap collapse events. */
var parent_id = parent_prefix + $(this).attr('id').substring(child_prefix.length);
if (parent_id) {
$("#" + parent_id + " .far.fa-folder-open").attr("class", "far fa-folder fa-fw");
$("#" + parent_id + " i.fas").addClass("rotate");
$("#" + parent_id).removeClass("hide-border-bottom");
var parentId = parentPrefix + $(this).attr("id").substring(childPrefix.length);
if (parentId) {
$("#" + parentId + " .far.fa-folder-open").attr("class", "far fa-folder fa-fw");
$("#" + parentId + " i.fas").addClass("rotate");
$("#" + parentId).removeClass("hide-border-bottom");
}
});
/* expand the top category */
$(".collapse").on("show.bs.collapse", function() {
var parent_id = parent_prefix + $(this).attr('id').substring(child_prefix.length);
if (parent_id) {
$("#" + parent_id + " .far.fa-folder").attr("class", "far fa-folder-open fa-fw");
$("#" + parent_id + " i.fas").removeClass("rotate");
$("#" + parent_id).addClass("hide-border-bottom");
var parentId = parentPrefix + $(this).attr("id").substring(childPrefix.length);
if (parentId) {
$("#" + parentId + " .far.fa-folder").attr("class", "far fa-folder-open fa-fw");
$("#" + parentId + " i.fas").removeClass("rotate");
$("#" + parentId).addClass("hide-border-bottom");
}
});

View file

@ -11,84 +11,19 @@
* MIT License
*/
function countUp(min, max, destId) {
if (min < max) {
var numAnim = new CountUp(destId, min, max);
if (!numAnim.error) {
numAnim.start();
} else {
console.error(numAnim.error);
}
}
}
function countPV(path, rows) {
var count = 0;
if (rows !== undefined ) {
for (var i = 0; i < rows.length; ++i) {
var gaPath = rows[i][0];
if (gaPath == path) { /* path format see: site.permalink */
count += parseInt(rows[i][1]);
break;
}
}
}
return count;
}
function tacklePV(rows, path, elem, hasInit) {
var count = countPV(path, rows);
count = (count == 0 ? 1 : count);
if (!hasInit) {
elem.text(new Intl.NumberFormat().format(count));
} else {
var initCount = parseInt(elem.text().replace(/,/g, ''));
if (count > initCount) {
countUp(initCount, count, elem.attr('id'));
}
}
}
function displayPageviews(data) {
if (data === undefined) {
return;
}
var hasInit = getInitStatus();
var rows = data.rows; /* could be undefined */
if ($("#post-list").length > 0) { /* the Home page */
$(".post-preview").each(function() {
var path = $(this).children("div").children("h1").children("a").attr("href");
tacklePV(rows, path, $(this).find('.pageviews'), hasInit);
});
} else if ($(".post").length > 0) { /* the post */
var path = window.location.pathname;
tacklePV(rows, path, $('#pv'), hasInit);
}
}
var getInitStatus = (function() {
var getInitStatus = (function () {
var hasInit = false;
return function() {
return () => {
let ret = hasInit;
if (!hasInit) {
hasInit = true;
}
return ret;
}
})();
};
}());
var PvCache = (function() {
var PvCache = (function () {
const KEY_PV = "pv";
const KEY_CREATION = "pv_created_date";
const KEY_PV_SRC = "pv_source";
@ -107,26 +42,26 @@ var PvCache = (function() {
}
return {
getData: function() {
getData() {
return JSON.parse(localStorage.getItem(KEY_PV) );
},
saveOriginCache: function(pv) {
saveOriginCache(pv) {
set(KEY_PV, pv);
set(KEY_PV_SRC, Source.ORIGIN );
set(KEY_CREATION, new Date().toJSON() );
},
saveProxyCache: function(pv) {
saveProxyCache(pv) {
set(KEY_PV, pv);
set(KEY_PV_SRC, Source.PROXY );
set(KEY_CREATION, new Date().toJSON() );
},
isFromOrigin: function() {
return get(KEY_PV_SRC) == Source.ORIGIN;
isFromOrigin() {
return get(KEY_PV_SRC) === Source.ORIGIN;
},
isFromProxy: function() {
return get(KEY_PV_SRC) == Source.PROXY;
isFromProxy() {
return get(KEY_PV_SRC) === Source.PROXY;
},
isExpired: function() {
isExpired() {
if (PvCache.isFromOrigin() ) {
let date = new Date(get(KEY_CREATION));
date.setDate(date.getDate() + 1); /* update origin records every day */
@ -139,30 +74,110 @@ var PvCache = (function() {
}
return false;
},
getAllPagevies: function() {
getAllPagevies() {
return PvCache.getData().totalsForAllResults["ga:pageviews"];
},
newerThan: function(pv) {
newerThan(pv) {
return PvCache.getAllPagevies() > pv.totalsForAllResults["ga:pageviews"];
},
inspectKeys: function() {
if (localStorage.getItem(KEY_PV) == null
|| localStorage.getItem(KEY_PV_SRC) == null
|| localStorage.getItem(KEY_CREATION) == null) {
inspectKeys() {
if (localStorage.getItem(KEY_PV) === null
|| localStorage.getItem(KEY_PV_SRC) === null
|| localStorage.getItem(KEY_CREATION) === null) {
localStorage.clear();
}
}
};
})(); /* PvCache */
}()); /* PvCache */
function countUp(min, max, destId) {
if (min < max) {
var numAnim = new CountUp(destId, min, max);
if (!numAnim.error) {
numAnim.start();
} else {
console.error(numAnim.error);
}
}
}
function countPV(path, rows) {
var count = 0;
if (typeof rows !== "undefined" ) {
for (var i = 0; i < rows.length; ++i) {
var gaPath = rows[i][0];
if (gaPath === path) { /* path format see: site.permalink */
count += parseInt(rows[i][1], 10);
break;
}
}
}
return count;
}
function tacklePV(rows, path, elem, hasInit) {
var count = countPV(path, rows);
count = (count === 0 ? 1 : count);
if (!hasInit) {
elem.text(new Intl.NumberFormat().format(count));
} else {
var initCount = parseInt(elem.text().replace(/,/g, ""), 10);
if (count > initCount) {
countUp(initCount, count, elem.attr("id"));
}
}
}
function displayPageviews(data) {
if (typeof data === "undefined") {
return;
}
var hasInit = getInitStatus();
var rows = data.rows; /* could be undefined */
if ($("#post-list").length > 0) { /* the Home page */
$(".post-preview").each(function() {
var path = $(this).children("div").children("h1").children("a").attr("href");
tacklePV(rows, path, $(this).find(".pageviews"), hasInit);
});
} else if ($(".post").length > 0) { /* the post */
var path = window.location.pathname;
tacklePV(rows, path, $("#pv"), hasInit);
}
}
function fetchProxyPageviews() {
$.ajax({
type: "GET",
url: proxyEndpoint, /* see: /assets/js/_pv-config.js */
dataType: "jsonp",
jsonpCallback: "displayPageviews",
success: (data, textStatus, jqXHR) => {
PvCache.saveProxyCache(JSON.stringify(data));
},
error: (jqXHR, textStatus, errorThrown) => {
console.log("Failed to load pageviews from proxy server: " + errorThrown);
}
});
}
function fetchPageviews(fetchOrigin = true, filterOrigin = false) {
/* pvCacheEnabled see: /assets/js/_pv-config.js */
if (pvCacheEnabled && fetchOrigin) {
fetch('/assets/js/data/pageviews.json')
.then(response => response.json())
.then(data => {
fetch("/assets/js/data/pageviews.json")
.then((response) => response.json())
.then((data) => {
if (filterOrigin) {
if (PvCache.newerThan(data)) {
return;
@ -180,25 +195,9 @@ function fetchPageviews(fetchOrigin = true, filterOrigin = false) {
}
function fetchProxyPageviews() {
$.ajax({
type: 'GET',
url: proxyEndpoint, /* see: /assets/js/_pv-config.js */
dataType: 'jsonp',
jsonpCallback: "displayPageviews",
success: function(data, textStatus, jqXHR) {
PvCache.saveProxyCache(JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Failed to load pageviews from proxy server: " + errorThrown);
}
});
}
$(function() {
if ($('.pageviews').length > 0) {
if ($(".pageviews").length > 0) {
PvCache.inspectKeys();
let cache = PvCache.getData();

View file

@ -8,24 +8,28 @@
$(function() {
var toRefresh = $(".timeago").length;
var intervalId = void 0;
function timeago(iso, isLastmod) {
let now = new Date();
let past = new Date(iso);
if (past.getFullYear() != now.getFullYear()) {
if (past.getFullYear() !== now.getFullYear()) {
toRefresh -= 1;
return past.toLocaleString("en-US", {
year: 'numeric',
month: 'short',
day: 'numeric'
year: "numeric",
month: "short",
day: "numeric"
});
}
if (past.getMonth() != now.getMonth()) {
if (past.getMonth() !== now.getMonth()) {
toRefresh -= 1;
return past.toLocaleString("en-US", {
month: 'short',
day: 'numeric'
month: "short",
day: "numeric"
});
}
@ -47,37 +51,33 @@ $(function() {
return minute + " minute" + (minute > 1 ? "s" : "") + " ago";
}
return (isLastmod? "just" : "Just") + " now";
return (isLastmod ? "just" : "Just") + " now";
}
function updateTimeago() {
$(".timeago").each(function() {
if ($(this).children("i").length > 0) {
var basic = $(this).text();
var isLastmod = $(this).hasClass('lastmod');
var isLastmod = $(this).hasClass("lastmod");
var node = $(this).children("i");
var date = node.text(); /* ISO Date: 'YYYY-MM-DDTHH:MM:SSZ' */
var date = node.text(); /* ISO Date: "YYYY-MM-DDTHH:MM:SSZ" */
$(this).text(timeago(date, isLastmod));
$(this).append(node);
}
});
if (toRefresh == 0 && intervalId != undefined) {
clearInterval(intervalId); /* stop interval */
if (toRefresh === 0 && typeof intervalId !== "undefined") {
clearInterval(intervalId); /* stop interval */
}
return toRefresh;
}
var toRefresh = $(".timeago").length;
if (toRefresh == 0) {
if (toRefresh === 0) {
return;
}
if (updateTimeago() > 0) { /* run immediately */
var intervalId = setInterval(updateTimeago, 60000); /* run every minute */
intervalId = setInterval(updateTimeago, 60000); /* run every minute */
}
});
});

View file

@ -7,8 +7,8 @@
*/
$(function() {
if ($("#post-wrapper .post-content h1").length == 0
&& $("#post-wrapper .post-content h2").length == 0) {
if ($("#post-wrapper .post-content h1").length === 0
&& $("#post-wrapper .post-content h2").length === 0) {
$("#toc-wrapper").addClass("unloaded");
}
});

View file

@ -6,5 +6,5 @@
* MIT License
*/
$(function () {
$('[data-toggle="tooltip"]').tooltip();
$("[data-toggle=\"tooltip\"]").tooltip();
});