You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
parallel-library/cps/static/js/kthoom.js

554 lines
17 KiB
JavaScript

/*
* kthoom.js
*
* Licensed under the MIT License
*
* Copyright(c) 2011 Google Inc.
* Copyright(c) 2011 antimatter15
7 years ago
*/
/* Reference Documentation:
* Web Workers: http://www.whatwg.org/specs/web-workers/current-work/
* Web Workers in Mozilla: https://developer.mozilla.org/En/Using_web_workers
* File API (FileReader): http://www.w3.org/TR/FileAPI/
* Typed Arrays: http://www.khronos.org/registry/typedarray/specs/latest/#6
*/
/* global screenfull */
if (window.opera) {
7 years ago
window.console.log = function(str) {
opera.postError(str);
};
}
7 years ago
var kthoom;
// gets the element with the given id
function getElem(id) {
7 years ago
if (document.documentElement.querySelector) {
// querySelector lookup
7 years ago
return document.body.querySelector("#" + id);
7 years ago
}
// getElementById lookup
return document.getElementById(id);
}
if (typeof window.kthoom === "undefined" ) {
7 years ago
kthoom = {};
}
// key codes
kthoom.Key = {
ESCAPE: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
A: 65, B: 66, C: 67, D: 68, E: 69, F: 70, G: 71, H: 72, I: 73, J: 74, K: 75, L: 76, M: 77,
N: 78, O: 79, P: 80, Q: 81, R: 82, S: 83, T: 84, U: 85, V: 86, W: 87, X: 88, Y: 89, Z: 90,
QUESTION_MARK: 191,
LEFT_SQUARE_BRACKET: 219,
RIGHT_SQUARE_BRACKET: 221
};
// global variables
var currentImage = 0;
var imageFiles = [];
var imageFilenames = [];
var totalImages = 0;
7 years ago
var settings = {
hflip: false,
vflip: false,
rotateTimes: 0,
fitMode: kthoom.Key.B,
7 years ago
theme: "light"
};
kthoom.saveSettings = function() {
localStorage.kthoomSettings = JSON.stringify(settings);
7 years ago
};
kthoom.loadSettings = function() {
7 years ago
try {
7 years ago
if (!localStorage.kthoomSettings) {
return;
7 years ago
}
$.extend(settings, JSON.parse(localStorage.kthoomSettings));
kthoom.setSettings();
7 years ago
} catch (err) {
alert("Error load settings");
7 years ago
}
};
kthoom.setSettings = function() {
// Set settings control values
$.each(settings, function(key, value) {
if (typeof value === "boolean") {
7 years ago
$("input[name=" + key + "]").prop("checked", value);
} else {
7 years ago
$("input[name=" + key + "]").val([value]);
}
});
};
7 years ago
// Stores an image filename and its data: URI.
kthoom.ImageFile = function(file) {
7 years ago
this.filename = file.filename;
7 years ago
this.dataURI = file.fileData;
7 years ago
this.data = file;
};
function loadFromArrayBuffer(ab) {
7 years ago
var f = [];
7 years ago
f.fileData = ab.content;
f.filename = ab.name;
// add any new pages based on the filename
if (imageFilenames.indexOf(f.filename) === -1) {
imageFilenames.push(f.filename);
imageFiles.push(new kthoom.ImageFile(f));
// add thumbnails to the TOC list
7 years ago
$("#thumbnails").append(
"<li>" +
"<a data-page='" + imageFiles.length + "'>" +
"<img src='" + imageFiles[imageFiles.length - 1].dataURI + "'/>" +
"<span>" + imageFiles.length + "</span>" +
"</a>" +
"</li>"
);
7 years ago
}
var percentage = ((ab.page + 1) / (ab.last + 1)) * 100;
updateProgress(percentage);
7 years ago
totalImages = ab.last + 1;
// display first page if we haven't yet
if (imageFiles.length === currentImage + 1) {
updatePage();
7 years ago
}
7 years ago
}
function scrollTocToActive() {
// Scroll to the thumbnail in the TOC on page change
$('#tocView').stop().animate({
scrollTop: $('#tocView a.active').position().top
}, 200);
}
function updatePage() {
$('.page').text((currentImage + 1 ) + "/" + totalImages);
// Mark the current page in the TOC
$('#tocView a[data-page]')
// Remove the currently active thumbnail
.removeClass('active')
// Find the new one
.filter('[data-page='+ (currentImage + 1) +']')
// Set it to active
.addClass('active');
scrollTocToActive();
updateProgress();
7 years ago
if (imageFiles[currentImage]) {
setImage(imageFiles[currentImage].dataURI);
} else {
7 years ago
setImage("loading");
7 years ago
}
7 years ago
$("body").toggleClass("dark-theme", settings.theme === "dark");
kthoom.setSettings();
kthoom.saveSettings();
}
function updateProgress(loadPercentage) {
// Set the load/unzip progress if it's passed in
if (loadPercentage) {
$("#progress .bar-load").css({ width: loadPercentage + "%" });
if (loadPercentage === 100) {
$("#progress")
.removeClass('loading')
.find(".load").text('');
}
}
// Set page progress bar
$("#progress .bar-read").css({ width: totalImages === 0 ? 0 : Math.round((currentImage + 1) / totalImages * 100) + "%"});
}
function setImage(url) {
7 years ago
var canvas = $("#mainImage")[0];
7 years ago
var x = $("#mainImage")[0].getContext("2d");
$("#mainText").hide();
if (url === "loading") {
7 years ago
updateScale(true);
canvas.width = innerWidth - 100;
canvas.height = 200;
x.fillStyle = "black";
7 years ago
x.textAlign = "center";
x.font = "24px sans-serif";
7 years ago
x.strokeStyle = "black";
7 years ago
x.fillText("Loading Page #" + (currentImage + 1), innerWidth / 2, 100);
7 years ago
} else {
if (url === "error") {
7 years ago
updateScale(true);
canvas.width = innerWidth - 100;
canvas.height = 200;
x.fillStyle = "black";
7 years ago
x.textAlign = "center";
x.font = "24px sans-serif";
7 years ago
x.strokeStyle = "black";
7 years ago
x.fillText("Unable to decompress image #" + (currentImage + 1), innerWidth / 2, 100);
} else {
if ($("body").css("scrollHeight") / innerHeight > 1) {
$("body").css("overflowY", "scroll");
7 years ago
}
var img = new Image();
img.onerror = function() {
canvas.width = innerWidth - 100;
canvas.height = 300;
updateScale(true);
x.fillStyle = "black";
x.font = "50px sans-serif";
x.strokeStyle = "black";
x.fillText("Page #" + (currentImage + 1) + " (" +
7 years ago
imageFiles[currentImage].filename + ")", innerWidth / 2, 100);
x.fillStyle = "black";
7 years ago
x.fillText("Is corrupt or not an image", innerWidth / 2, 200);
var xhr = new XMLHttpRequest();
if (/(html|htm)$/.test(imageFiles[currentImage].filename)) {
xhr.open("GET", url, true);
xhr.onload = function() {
$("#mainText").css("display", "");
$("#mainText").innerHTML("<iframe style=\"width:100%;height:700px;border:0\" src=\"data:text/html," + escape(xhr.responseText) + "\"></iframe>");
}
xhr.send(null);
} else if (!/(jpg|jpeg|png|gif)$/.test(imageFiles[currentImage].filename) && imageFiles[currentImage].data.uncompressedSize < 10 * 1024) {
xhr.open("GET", url, true);
xhr.onload = function() {
$("#mainText").css("display", "");
$("#mainText").innerText(xhr.responseText);
};
xhr.send(null);
}
};
img.onload = function() {
var h = img.height,
w = img.width,
sw = w,
sh = h;
settings.rotateTimes = (4 + settings.rotateTimes) % 4;
x.save();
if (settings.rotateTimes % 2 === 1) {
sh = w;
sw = h;
}
canvas.height = sh;
canvas.width = sw;
x.translate(sw / 2, sh / 2);
x.rotate(Math.PI / 2 * settings.rotateTimes);
x.translate(-w / 2, -h / 2);
if (settings.vflip) {
x.scale(1, -1);
x.translate(0, -h);
}
if (settings.hflip) {
x.scale(-1, 1);
x.translate(-w, 0);
}
canvas.style.display = "none";
scrollTo(0, 0);
x.drawImage(img, 0, 0);
updateScale(false);
7 years ago
canvas.style.display = "";
$("body").css("overflowY", "");
x.restore();
};
img.src = url;
}
7 years ago
}
}
function showPrevPage() {
7 years ago
currentImage--;
if (currentImage < 0) {
7 years ago
// Freeze on the current page.
currentImage++;
} else {
updatePage();
}
}
function showNextPage() {
7 years ago
currentImage++;
if (currentImage >= Math.max(totalImages, imageFiles.length)) {
7 years ago
// Freeze on the current page.
currentImage--;
} else {
updatePage();
}
}
function updateScale(clear) {
7 years ago
var mainImageStyle = getElem("mainImage").style;
mainImageStyle.width = "";
mainImageStyle.height = "";
mainImageStyle.maxWidth = "";
mainImageStyle.maxHeight = "";
var maxheight = innerHeight - 50;
if (!clear) {
7 years ago
switch (settings.fitMode) {
case kthoom.Key.B:
mainImageStyle.maxWidth = "100%";
mainImageStyle.maxHeight = maxheight + "px";
break;
case kthoom.Key.H:
mainImageStyle.height = maxheight + "px";
break;
case kthoom.Key.W:
mainImageStyle.width = "100%";
break;
default:
break;
}
7 years ago
}
7 years ago
$("#mainContent").css({maxHeight: maxheight + 5});
kthoom.setSettings();
7 years ago
kthoom.saveSettings();
}
function keyHandler(evt) {
var hasModifier = evt.ctrlKey || evt.shiftKey || evt.metaKey;
switch (evt.keyCode) {
7 years ago
case kthoom.Key.LEFT:
if (hasModifier) break;
showPrevPage();
7 years ago
break;
case kthoom.Key.RIGHT:
if (hasModifier) break;
showNextPage();
7 years ago
break;
case kthoom.Key.L:
if (hasModifier) break;
settings.rotateTimes--;
if (settings.rotateTimes < 0) {
settings.rotateTimes = 3;
7 years ago
}
updatePage();
break;
case kthoom.Key.R:
if (hasModifier) break;
settings.rotateTimes++;
if (settings.rotateTimes > 3) {
settings.rotateTimes = 0;
7 years ago
}
updatePage();
break;
case kthoom.Key.F:
if (hasModifier) break;
if (!settings.hflip && !settings.vflip) {
settings.hflip = true;
} else if (settings.hflip === true && settings.vflip === true) {
settings.vflip = false;
settings.hflip = false;
} else if (settings.hflip === true) {
settings.vflip = true;
settings.hflip = false;
} else if (settings.vflip === true) {
settings.hflip = true;
7 years ago
}
updatePage();
break;
case kthoom.Key.W:
if (hasModifier) break;
settings.fitMode = kthoom.Key.W;
updateScale(false);
7 years ago
break;
case kthoom.Key.H:
if (hasModifier) break;
settings.fitMode = kthoom.Key.H;
updateScale(false);
7 years ago
break;
case kthoom.Key.B:
if (hasModifier) break;
settings.fitMode = kthoom.Key.B;
updateScale(false);
7 years ago
break;
case kthoom.Key.N:
if (hasModifier) break;
settings.fitMode = kthoom.Key.N;
updateScale(false);
7 years ago
break;
case kthoom.Key.SPACE:
var container = $('#mainContent');
var atTop = container.scrollTop() === 0;
var atBottom = container.scrollTop() >= container[0].scrollHeight - container.height();
if (evt.shiftKey && atTop) {
evt.preventDefault();
// If it's Shift + Space and the container is at the top of the page
showPrevPage();
} else if (!evt.shiftKey && atBottom) {
evt.preventDefault();
// If you're at the bottom of the page and you only pressed space
showNextPage();
container.scrollTop(0);
}
break;
7 years ago
default:
//console.log('KeyCode', evt.keyCode);
7 years ago
break;
}
}
function ImageLoadCallback() {
var jso = this.response;
// Unable to decompress file, or no response from server
7 years ago
if (jso === null) {
setImage("error");
} else {
// IE 11 sometimes sees the response as a string
if (typeof jso !== "object") {
jso = JSON.parse(jso);
}
if (jso.page !== jso.last) {
this.open("GET", this.fileid + "/" + (jso.page + 1));
this.addEventListener("load", ImageLoadCallback);
this.send();
}
loadFromArrayBuffer(jso);
7 years ago
}
}
function init(fileid) {
var request = new XMLHttpRequest();
request.open("GET", fileid);
request.responseType = "json";
request.fileid = fileid.substring(0, fileid.length - 2);
request.addEventListener("load", ImageLoadCallback);
request.send();
document.body.className += /AppleWebKit/.test(navigator.userAgent) ? " webkit" : "";
kthoom.loadSettings();
7 years ago
updateScale(true);
$(document).keydown(keyHandler);
$(window).resize(function() {
updateScale(false);
});
7 years ago
// Open TOC menu
$("#slider").click(function() {
7 years ago
$("#sidebar").toggleClass("open");
$("#main").toggleClass("closed");
$(this).toggleClass("icon-menu icon-right");
// We need this in a timeout because if we call it during the CSS transition, IE11 shakes the page ¯\_(ツ)_/¯
setTimeout(function(){
// Focus on the TOC or the main content area, depending on which is open
$('#main:not(.closed) #mainContent, #sidebar.open #tocView').focus();
scrollTocToActive();
}, 500);
7 years ago
});
7 years ago
// Open Settings modal
$("#setting").click(function() {
7 years ago
$("#settings-modal").toggleClass("md-show");
});
7 years ago
// On Settings input change
$("#settings input").on("change", function() {
7 years ago
// Get either the checked boolean or the assigned value
var value = this.type === "checkbox" ? this.checked : this.value;
7 years ago
// If it's purely numeric, parse it to an integer
value = /^\d+$/.test(value) ? parseInt(value) : value;
7 years ago
settings[this.name] = value;
updatePage();
updateScale(false);
7 years ago
});
7 years ago
// Close modal
$(".closer, .overlay").click(function() {
7 years ago
$(".md-show").removeClass("md-show");
});
// TOC thumbnail pagination
$("#thumbnails").on("click", "a", function() {
7 years ago
currentImage = $(this).data("page") - 1;
updatePage();
});
// Fullscreen mode
if (typeof screenfull !== "undefined") {
7 years ago
$("#fullscreen").click(function() {
screenfull.toggle($("#container")[0]);
});
7 years ago
if (screenfull.raw) {
var $button = $("#fullscreen");
document.addEventListener(screenfull.raw.fullscreenchange, function() {
7 years ago
screenfull.isFullscreen
? $button.addClass("icon-resize-small").removeClass("icon-resize-full")
: $button.addClass("icon-resize-full").removeClass("icon-resize-small");
});
}
7 years ago
}
// Focus the scrollable area so that keyboard scrolling work as expected
$('#mainContent').focus();
$("#mainImage").click(function(evt) {
// Firefox does not support offsetX/Y so we have to manually calculate
// where the user clicked in the image.
var mainContentWidth = $("#mainContent").width();
var mainContentHeight = $("#mainContent").height();
var comicWidth = evt.target.clientWidth;
var comicHeight = evt.target.clientHeight;
var offsetX = (mainContentWidth - comicWidth) / 2;
var offsetY = (mainContentHeight - comicHeight) / 2;
7 years ago
var clickX = evt.offsetX ? evt.offsetX : (evt.clientX - offsetX);
var clickY = evt.offsetY ? evt.offsetY : (evt.clientY - offsetY);
// Determine if the user clicked/tapped the left side or the
// right side of the page.
var clickedPrev = false;
7 years ago
switch (settings.rotateTimes) {
case 0:
clickedPrev = clickX < (comicWidth / 2);
break;
case 1:
clickedPrev = clickY < (comicHeight / 2);
break;
case 2:
clickedPrev = clickX > (comicWidth / 2);
break;
case 3:
clickedPrev = clickY > (comicHeight / 2);
break;
}
if (clickedPrev) {
showPrevPage();
} else {
showNextPage();
}
});
}