Minor modifications

This commit is contained in:
Sébastien Lucas 2013-10-15 16:07:41 +02:00
parent 0dda0052e3
commit 3343a65335

754
util.js
View file

@ -1,378 +1,378 @@
// util.js // util.js
// copyright Sébastien Lucas // copyright Sébastien Lucas
// https://github.com/seblucas/cops // https://github.com/seblucas/cops
/*global LRUCache */ /*global LRUCache */
var templatePage, templateBookDetail, templateMain, templateSuggestion, currentData, before, filterList; var templatePage, templateBookDetail, templateMain, templateSuggestion, currentData, before, filterList;
if (typeof LRUCache!='undefined') { if (typeof LRUCache != 'undefined') {
var cache = new LRUCache(30); var cache = new LRUCache(30);
} }
var DEBUG = false; var DEBUG = false;
var isPushStateEnabled = window.history && window.history.pushState && window.history.replaceState && var isPushStateEnabled = window.history && window.history.pushState && window.history.replaceState &&
// pushState isn't reliable on iOS until 5. // pushState isn't reliable on iOS until 5.
!navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/); !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/);
function debug_log(text) { function debug_log(text) {
if ( DEBUG ) { if ( DEBUG ) {
console.log(text); console.log(text);
} }
} }
/*exported updateCookie */ /*exported updateCookie */
function updateCookie (id) { function updateCookie (id) {
if($(id).prop('pattern') && !$(id).val().match(new RegExp ($(id).prop('pattern')))) { if ($(id).prop('pattern') && !$(id).val().match(new RegExp ($(id).prop('pattern')))) {
return; return;
} }
var name = $(id).attr('id'); var name = $(id).attr('id');
var value = $(id).val (); var value = $(id).val ();
$.cookie(name, value, { expires: 365 }); $.cookie(name, value, { expires: 365 });
} }
/*exported updateCookieFromCheckbox */ /*exported updateCookieFromCheckbox */
function updateCookieFromCheckbox (id) { function updateCookieFromCheckbox (id) {
var name = $(id).attr('id'); var name = $(id).attr('id');
if ((/^style/).test (name)) { if ((/^style/).test (name)) {
name = "style"; name = "style";
} }
if ($(id).is(":checked")) if ($(id).is(":checked"))
{ {
if ($(id).is(':radio')) { if ($(id).is(':radio')) {
$.cookie(name, $(id).val (), { expires: 365 }); $.cookie(name, $(id).val (), { expires: 365 });
} else { } else {
$.cookie(name, '1', { expires: 365 }); $.cookie(name, '1', { expires: 365 });
} }
} }
else else
{ {
$.cookie(name, '0', { expires: 365 }); $.cookie(name, '0', { expires: 365 });
} }
} }
function elapsed () { function elapsed () {
var elapsedTime = new Date () - before; var elapsedTime = new Date () - before;
return "Elapsed : " + elapsedTime; return "Elapsed : " + elapsedTime;
} }
function retourMail(data, textStatus, jqXHR ) { function retourMail(data, textStatus, jqXHR ) {
$("#mailButton :first-child").removeClass ("icon-spinner icon-spin").addClass ("icon-envelope"); $("#mailButton :first-child").removeClass ("icon-spinner icon-spin").addClass ("icon-envelope");
alert (data); alert (data);
} }
/*exported sendToMailAddress */ /*exported sendToMailAddress */
function sendToMailAddress (component, dataid) { function sendToMailAddress (component, dataid) {
var email = $.cookie ('email'); var email = $.cookie ('email');
if (!$.cookie ('email')) { if (!$.cookie ('email')) {
email = window.prompt (currentData.c.i18n.customizeEmail, ""); email = window.prompt (currentData.c.i18n.customizeEmail, "");
$.cookie ('email', email, { expires: 365 }); $.cookie ('email', email, { expires: 365 });
} }
var url = 'sendtomail.php'; var url = 'sendtomail.php';
if (currentData.databaseId) { if (currentData.databaseId) {
url = url + '?db=' + currentData.databaseId; url = url + '?db=' + currentData.databaseId;
} }
$("#mailButton :first-child").removeClass ("icon-envelope").addClass ("icon-spinner icon-spin"); $("#mailButton :first-child").removeClass ("icon-envelope").addClass ("icon-spinner icon-spin");
$.ajax ({'url': url, 'type': 'post', 'data': { 'data': dataid, 'email': email }, 'success': retourMail}); $.ajax ({'url': url, 'type': 'post', 'data': { 'data': dataid, 'email': email }, 'success': retourMail});
} }
function str_format () { function str_format () {
var s = arguments[0]; var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) { for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm"); var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]); s = s.replace(reg, arguments[i + 1]);
} }
return s; return s;
} }
function isDefined(x) { function isDefined(x) {
var undefinedVar; var undefinedVar;
return x !== undefinedVar; return x !== undefinedVar;
} }
function getCurrentOption (option) { function getCurrentOption (option) {
if (!$.cookie (option)) { if (!$.cookie (option)) {
if (currentData && currentData.c && currentData.c.config && currentData.c.config [option]) { if (currentData && currentData.c && currentData.c.config && currentData.c.config [option]) {
return currentData.c.config [option]; return currentData.c.config [option];
} }
} }
return $.cookie (option); return $.cookie (option);
} }
/*exported htmlspecialchars */ /*exported htmlspecialchars */
function htmlspecialchars(str) { function htmlspecialchars(str) {
return String(str) return String(str)
.replace(/&/g, '&amp;') .replace(/&/g, '&amp;')
.replace(/"/g, '&quot;') .replace(/"/g, '&quot;')
.replace(/'/g, '&#39;') .replace(/'/g, '&#39;')
.replace(/</g, '&lt;') .replace(/</g, '&lt;')
.replace(/>/g, '&gt;'); .replace(/>/g, '&gt;');
} }
/************************************************ /************************************************
* All functions needed to filter the book list by tags * All functions needed to filter the book list by tags
************************************************ ************************************************
*/ */
function getTagList () { function getTagList () {
var tagList = {}; var tagList = {};
$(".se").each (function(){ $(".se").each (function(){
if ($(this).parents (".filtered").length > 0) { return; } if ($(this).parents (".filtered").length > 0) { return; }
var taglist = $(this).text(); var taglist = $(this).text();
var tagarray = taglist.split (","); var tagarray = taglist.split (",");
for (var i in tagarray) { for (var i in tagarray) {
var tag = tagarray [i].replace(/^\s+/g,'').replace(/\s+$/g,''); var tag = tagarray [i].replace(/^\s+/g,'').replace(/\s+$/g,'');
tagList [tag] = 1; tagList [tag] = 1;
} }
}); });
return tagList; return tagList;
} }
function doFilter () { function doFilter () {
$(".books").removeClass("filtered"); $(".books").removeClass("filtered");
if (jQuery.isEmptyObject(filterList)) { if (jQuery.isEmptyObject(filterList)) {
updateFilters (); updateFilters ();
return; return;
} }
$(".se").each (function(){ $(".se").each (function(){
var taglist = ", " + $(this).text() + ", "; var taglist = ", " + $(this).text() + ", ";
var toBeFiltered = false; var toBeFiltered = false;
for (var filter in filterList) { for (var filter in filterList) {
var onlyThisTag = filterList [filter]; var onlyThisTag = filterList [filter];
filter = ', ' + filter + ', '; filter = ', ' + filter + ', ';
var myreg = new RegExp (filter); var myreg = new RegExp (filter);
if (myreg.test (taglist)) { if (myreg.test (taglist)) {
if (onlyThisTag === false) { if (onlyThisTag === false) {
toBeFiltered = true; toBeFiltered = true;
} }
} else { } else {
if (onlyThisTag === true) { if (onlyThisTag === true) {
toBeFiltered = true; toBeFiltered = true;
} }
} }
} }
if (toBeFiltered) { $(this).parents (".books").addClass ("filtered"); } if (toBeFiltered) { $(this).parents (".books").addClass ("filtered"); }
}); });
updateFilters (); updateFilters ();
} }
function updateFilters () { function updateFilters () {
var tagList = getTagList (); var tagList = getTagList ();
// If there is already some filters then let's prepare to update the list // If there is already some filters then let's prepare to update the list
$("#filter ul li").each (function () { $("#filter ul li").each (function () {
var text = $(this).text (); var text = $(this).text ();
if (isDefined (tagList [text]) || $(this).attr ('class')) { if (isDefined (tagList [text]) || $(this).attr ('class')) {
tagList [text] = 0; tagList [text] = 0;
} else { } else {
tagList [text] = -1; tagList [text] = -1;
} }
}); });
// Update the filter -1 to remove, 1 to add, 0 already there // Update the filter -1 to remove, 1 to add, 0 already there
for (var tag in tagList) { for (var tag in tagList) {
var tagValue = tagList [tag]; var tagValue = tagList [tag];
if (tagValue === -1) { if (tagValue === -1) {
$("#filter ul li:contains('" + tag + "')").remove(); $("#filter ul li:contains('" + tag + "')").remove();
} }
if (tagValue === 1) { if (tagValue === 1) {
$("#filter ul").append ("<li>" + tag + "</li>"); $("#filter ul").append ("<li>" + tag + "</li>");
} }
} }
$("#filter ul").append ("<li>_CLEAR_</li>"); $("#filter ul").append ("<li>_CLEAR_</li>");
// Sort the list alphabetically // Sort the list alphabetically
$('#filter ul li').sortElements(function(a, b){ $('#filter ul li').sortElements(function(a, b){
return $(a).text() > $(b).text() ? 1 : -1; return $(a).text() > $(b).text() ? 1 : -1;
}); });
} }
function handleFilterEvents () { function handleFilterEvents () {
$("#filter ul").on ("click", "li", function(){ $("#filter ul").on ("click", "li", function(){
var filter = $(this).text (); var filter = $(this).text ();
if (filter === "_CLEAR_") { if (filter === "_CLEAR_") {
filterList = {}; filterList = {};
$("#filter ul li").removeClass ("filter-exclude"); $("#filter ul li").removeClass ("filter-exclude");
$("#filter ul li").removeClass ("filter-include"); $("#filter ul li").removeClass ("filter-include");
doFilter (); doFilter ();
return; return;
} }
switch ($(this).attr("class")) { switch ($(this).attr("class")) {
case "filter-include" : case "filter-include" :
$(this).attr("class", "filter-exclude"); $(this).attr("class", "filter-exclude");
filterList [filter] = false; filterList [filter] = false;
break; break;
case "filter-exclude" : case "filter-exclude" :
$(this).removeClass ("filter-exclude"); $(this).removeClass ("filter-exclude");
delete filterList [filter]; delete filterList [filter];
break; break;
default : default :
$(this).attr("class", "filter-include"); $(this).attr("class", "filter-include");
filterList [filter] = true; filterList [filter] = true;
break; break;
} }
doFilter (); doFilter ();
}); });
} }
/************************************************ /************************************************
* Functions to handle Ajax navigation * Functions to handle Ajax navigation
************************************************ ************************************************
*/ */
function navigateTo (url) { function navigateTo (url) {
$("h1").append (" <i class='icon-spinner icon-spin'></i>"); $("h1").append (" <i class='icon-spinner icon-spin'></i>");
before = new Date (); before = new Date ();
var jsonurl = url.replace ("index", "getJSON"); var jsonurl = url.replace ("index", "getJSON");
var cachedData = cache.get (jsonurl); var cachedData = cache.get (jsonurl);
if (cachedData) { if (cachedData) {
history.pushState(jsonurl, "", url); history.pushState(jsonurl, "", url);
updatePage (cachedData); updatePage (cachedData);
} else { } else {
$.getJSON(jsonurl, function(data) { $.getJSON(jsonurl, function(data) {
history.pushState(jsonurl, "", url); history.pushState(jsonurl, "", url);
cache.put (jsonurl, data); cache.put (jsonurl, data);
updatePage (data); updatePage (data);
}); });
} }
} }
function updatePage (data) { function updatePage (data) {
var result; var result;
filterList = {}; filterList = {};
data.c = currentData.c; data.c = currentData.c;
if (false && $("section").length && currentData.isPaginated === 0 && data.isPaginated === 0) { if (false && $("section").length && currentData.isPaginated === 0 && data.isPaginated === 0) {
// Partial update (for now disabled) // Partial update (for now disabled)
debug_log ("Partial update"); debug_log ("Partial update");
result = templateMain (data); result = templateMain (data);
$("h1").html (data.title); $("h1").html (data.title);
$("section").html (result); $("section").html (result);
} else { } else {
// Full update // Full update
result = templatePage (data); result = templatePage (data);
$("body").html (result); $("body").html (result);
} }
document.title = data.title; document.title = data.title;
currentData = data; currentData = data;
setTimeout( function() { $("input[name=query]").focus(); }, 500 ); setTimeout( function() { $("input[name=query]").focus(); }, 500 );
debug_log (elapsed ()); debug_log (elapsed ());
if ($.cookie('toolbar') === '1') { $("#tool").show (); } if ($.cookie('toolbar') === '1') { $("#tool").show (); }
if (currentData.containsBook === 1) { if (currentData.containsBook === 1) {
$("#sortForm").show (); $("#sortForm").show ();
if (getCurrentOption ("html_tag_filter") === "1") { if (getCurrentOption ("html_tag_filter") === "1") {
$("#filter ul").empty (); $("#filter ul").empty ();
updateFilters (); updateFilters ();
handleFilterEvents (); handleFilterEvents ();
} }
} else { } else {
$("#sortForm").hide (); $("#sortForm").hide ();
} }
} }
/*exported handleLinks */ /*exported handleLinks */
function handleLinks () { function handleLinks () {
$("body").on ("click", "a[href^='index']", link_Clicked); $("body").on ("click", "a[href^='index']", link_Clicked);
$("body").on ("submit", "#searchForm", search_Submitted); $("body").on ("submit", "#searchForm", search_Submitted);
$("body").on ("click", "#sort", function(){ $("body").on ("click", "#sort", function(){
$('.books').sortElements(function(a, b){ $('.books').sortElements(function(a, b){
var test = 1; var test = 1;
if ($("#sortorder").val() === "desc") if ($("#sortorder").val() === "desc")
{ {
test = -1; test = -1;
} }
return $(a).find ("." + $("#sortchoice").val()).text() > $(b).find ("." + $("#sortchoice").val()).text() ? test : -test; return $(a).find ("." + $("#sortchoice").val()).text() > $(b).find ("." + $("#sortchoice").val()).text() ? test : -test;
}); });
}); });
$("body").on ("click", ".headright", function(){ $("body").on ("click", ".headright", function(){
if ($("#tool").is(":hidden")) { if ($("#tool").is(":hidden")) {
$("#tool").slideDown("slow"); $("#tool").slideDown("slow");
$("input[name=query]").focus(); $("input[name=query]").focus();
$.cookie('toolbar', '1', { expires: 365 }); $.cookie('toolbar', '1', { expires: 365 });
} else { } else {
$("#tool").slideUp(); $("#tool").slideUp();
$.removeCookie('toolbar'); $.removeCookie('toolbar');
} }
}); });
$("body").magnificPopup({ $("body").magnificPopup({
delegate: '.fancycover', // child items selector, by clicking on it popup will open delegate: '.fancycover', // child items selector, by clicking on it popup will open
type: 'image', type: 'image',
gallery:{enabled:true, preload: [0,2]}, gallery:{enabled:true, preload: [0,2]},
disableOn: function() { disableOn: function() {
if( getCurrentOption ("use_fancyapps") === "1" ) { if( getCurrentOption ("use_fancyapps") === "1" ) {
return true; return true;
} }
return false; return false;
} }
}); });
} }
function link_Clicked (event) { function link_Clicked (event) {
var currentLink = $(this); var currentLink = $(this);
if (!isPushStateEnabled || if (!isPushStateEnabled ||
currentData.page === "19") { currentData.page === "19") {
return; return;
} }
event.preventDefault(); event.preventDefault();
var url = currentLink.attr('href'); var url = currentLink.attr('href');
if ($(".mfp-ready").length) if ($(".mfp-ready").length)
{ {
$.magnificPopup.close(); $.magnificPopup.close();
} }
// The bookdetail / about should be displayed in a lightbox // The bookdetail / about should be displayed in a lightbox
if (getCurrentOption ("use_fancyapps") === "1" && if (getCurrentOption ("use_fancyapps") === "1" &&
(currentLink.hasClass ("fancydetail") || currentLink.hasClass ("fancyabout"))) { (currentLink.hasClass ("fancydetail") || currentLink.hasClass ("fancyabout"))) {
before = new Date (); before = new Date ();
var jsonurl = url.replace ("index", "getJSON"); var jsonurl = url.replace ("index", "getJSON");
$.getJSON(jsonurl, function(data) { $.getJSON(jsonurl, function(data) {
data.c = currentData.c; data.c = currentData.c;
var detail = ""; var detail = "";
if (data.page === "16") { if (data.page === "16") {
detail = data.fullhtml; detail = data.fullhtml;
} else { } else {
detail = templateBookDetail (data); detail = templateBookDetail (data);
} }
$.magnificPopup.open({ $.magnificPopup.open({
items: { items: {
src: detail, src: detail,
type: 'inline' type: 'inline'
} }
}); });
debug_log (elapsed ()); debug_log (elapsed ());
}); });
return; return;
} }
navigateTo (url); navigateTo (url);
} }
function search_Submitted (event) { function search_Submitted (event) {
if (!isPushStateEnabled || if (!isPushStateEnabled ||
currentData.page === "19") { currentData.page === "19") {
return; return;
} }
event.preventDefault(); event.preventDefault();
var url = str_format ("index.php?page=9&current={0}&query={1}&db={2}", currentData.page, $("input[name=query]").val (), currentData.databaseId); var url = str_format ("index.php?page=9&current={0}&query={1}&db={2}", currentData.page, $("input[name=query]").val (), currentData.databaseId);
navigateTo (url); navigateTo (url);
} }
window.onpopstate = function(event) { window.onpopstate = function(event) {
before = new Date (); before = new Date ();
var data = cache.get (event.state); var data = cache.get (event.state);
updatePage (data); updatePage (data);
}; };
$(document).keydown(function(e){ $(document).keydown(function(e){
if (e.keyCode === 37 && $("#prevLink").length > 0) { if (e.keyCode === 37 && $("#prevLink").length > 0) {
navigateTo ($("#prevLink").attr('href')); navigateTo ($("#prevLink").attr('href'));
} }
if (e.keyCode === 39 && $("#nextLink").length > 0) { if (e.keyCode === 39 && $("#nextLink").length > 0) {
navigateTo ($("#nextLink").attr('href')); navigateTo ($("#nextLink").attr('href'));
} }
}); });