// ==UserScript==
// @name E HENTAI VIEW ENHANCE
// @name:zh-CN E绅士阅读强化
// @namespace https://github.com/MapoMagpie/eh-view-enhance
// @version 4.4.12
// @author MapoMagpie
// @description Manga Viewer + Downloader, Focus on experience and low load on the site. Support: e-hentai.org | exhentai.org | pixiv.net | 18comic.vip | nhentai.net | hitomi.la | rule34.xxx | danbooru.donmai.us | gelbooru.com
// @description:zh-CN 漫画阅读 + 下载器,注重体验和对站点的负载控制。支持:e-hentai.org | exhentai.org | pixiv.net | 18comic.vip | nhentai.net | hitomi.la | rule34.xxx | danbooru.donmai.us | gelbooru.com
// @license MIT
// @icon https://exhentai.org/favicon.ico
// @supportURL https://github.com/MapoMagpie/eh-view-enhance/issues
// @match https://exhentai.org/*
// @match https://e-hentai.org/*
// @match http://exhentai55ld2wyap5juskbm67czulomrouspdacjamjeloj7ugjbsad.onion/*
// @match https://nhentai.net/*
// @match https://steamcommunity.com/id/*/screenshots*
// @match https://hitomi.la/*
// @match https://www.pixiv.net/*
// @match https://yande.re/*
// @match https://rokuhentai.com/*
// @match https://18comic.org/*
// @match https://18comic.vip/*
// @match https://18-comicfreedom.xyz/*
// @match https://rule34.xxx/*
// @match https://imhentai.xxx/*
// @match https://danbooru.donmai.us/*
// @match https://gelbooru.com/*
// @connect exhentai.org
// @connect e-hentai.org
// @connect hath.network
// @connect exhentai55ld2wyap5juskbm67czulomrouspdacjamjeloj7ugjbsad.onion
// @connect nhentai.net
// @connect hitomi.la
// @connect akamaihd.net
// @connect i.pximg.net
// @connect ehgt.org
// @connect yande.re
// @connect 18comic.org
// @connect 18comic.vip
// @connect 18-comicfreedom.xyz
// @connect rule34.xxx
// @connect imhentai.xxx
// @connect donmai.us
// @connect gelbooru.com
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @downloadURL none
// ==/UserScript==
(function () {
'use strict';
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
// src/native/alias.ts
var _GM_getValue = /* @__PURE__ */ (() => typeof GM_getValue != "undefined" ? GM_getValue : void 0)();
var _GM_setValue = /* @__PURE__ */ (() => typeof GM_setValue != "undefined" ? GM_setValue : void 0)();
var _GM_xmlhttpRequest = /* @__PURE__ */ (() => typeof GM_xmlhttpRequest != "undefined" ? GM_xmlhttpRequest : void 0)();
function defaultConf() {
const screenWidth = window.screen.width;
const colCount = screenWidth > 2500 ? 7 : screenWidth > 1900 ? 6 : 5;
return {
backgroundImage: `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAfElEQVR42mP8z/CfCgIwDEgwAIAL0Fq3MDD5iQcn0/BgDpDAn0/AvywA4kUEZ7gUkXBoAM5gUQUaJ6eClOyBjALcAAAAASUVORK5CYII=`,
colCount,
readMode: "pagination",
autoLoad: true,
fetchOriginal: false,
restartIdleLoader: 2e3,
threads: 3,
downloadThreads: 4,
timeout: 10,
version: VERSION,
debug: true,
first: true,
reversePages: false,
pageHelperAbTop: "unset",
pageHelperAbLeft: "20px",
pageHelperAbBottom: "20px",
pageHelperAbRight: "unset",
imgScale: 0,
stickyMouse: "disable",
autoPageInterval: 5e3,
autoPlay: false,
filenameTemplate: "{number}-{title}",
preventScrollPageTime: 100,
archiveVolumeSize: 1200,
convertTo: "GIF",
autoCollapsePanel: true,
minifyPageHelper: "inBigMode",
keyboards: { inBigImageMode: {}, inFullViewGrid: {}, inMain: {} },
excludeURLs: [],
muted: false,
volume: 50,
disableCssAnimation: true,
mcInSites: ["18comic"],
paginationIMGCount: 1,
hitomiFormat: "auto",
autoOpen: false,
autoLoadInBackground: true
};
}
const VERSION = "4.4.0";
const CONFIG_KEY = "ehvh_cfg_";
function getStorageMethod() {
if (typeof _GM_getValue === "function" && typeof _GM_setValue === "function") {
return {
setItem: (key, value) => _GM_setValue(key, value),
getItem: (key) => _GM_getValue(key)
};
} else if (typeof localStorage !== "undefined") {
return {
setItem: (key, value) => localStorage.setItem(key, value),
getItem: (key) => localStorage.getItem(key)
};
} else {
throw new Error("No supported storage method found");
}
}
const storage = getStorageMethod();
function getConf() {
let cfgStr = storage.getItem(CONFIG_KEY);
if (cfgStr) {
let cfg2 = JSON.parse(cfgStr);
if (cfg2.version === VERSION) {
return confHealthCheck(cfg2);
}
}
let cfg = defaultConf();
saveConf(cfg);
return cfg;
}
function confHealthCheck(cf) {
let changed = false;
const defa = defaultConf();
const keys = Object.keys(defa);
keys.forEach((key) => {
if (cf[key] === void 0) {
cf[key] = defa[key];
changed = true;
}
});
["pageHelperAbTop", "pageHelperAbLeft", "pageHelperAbBottom", "pageHelperAbRight"].forEach((key) => {
if (cf[key] !== "unset") {
let pos = parseInt(cf[key]);
const screenLimit = key.endsWith("Right") || key.endsWith("Left") ? window.screen.width : window.screen.height;
if (isNaN(pos) || pos < 5 || pos > screenLimit) {
cf[key] = "5px";
changed = true;
}
}
});
if (!["pagination", "continuous"].includes(cf.readMode)) {
cf.readMode = "pagination";
changed = true;
}
if (changed) {
saveConf(cf);
}
return cf;
}
function saveConf(c) {
storage.setItem(CONFIG_KEY, JSON.stringify(c));
}
const conf = getConf();
const ConfigItems = [
{ key: "colCount", typ: "number" },
{ key: "threads", typ: "number" },
{ key: "downloadThreads", typ: "number" },
{ key: "paginationIMGCount", typ: "number" },
{ key: "timeout", typ: "number" },
{ key: "preventScrollPageTime", typ: "number" },
{ key: "autoPageInterval", typ: "number" },
{ key: "fetchOriginal", typ: "boolean", gridColumnRange: [1, 6] },
{ key: "autoLoad", typ: "boolean", gridColumnRange: [6, 11] },
{ key: "reversePages", typ: "boolean", gridColumnRange: [1, 6] },
{ key: "autoPlay", typ: "boolean", gridColumnRange: [6, 11] },
{ key: "autoLoadInBackground", typ: "boolean", gridColumnRange: [1, 6] },
{ key: "autoOpen", typ: "boolean", gridColumnRange: [6, 11] },
{ key: "disableCssAnimation", typ: "boolean", gridColumnRange: [1, 11] },
{ key: "autoCollapsePanel", typ: "boolean", gridColumnRange: [1, 11] },
{
key: "readMode",
typ: "select",
options: [
{ value: "pagination", display: "Pagination" },
{ value: "continuous", display: "Continuous" }
]
},
{
key: "stickyMouse",
typ: "select",
options: [
{ value: "enable", display: "Enable" },
{ value: "reverse", display: "Reverse" },
{ value: "disable", display: "Disable" }
]
},
{
key: "minifyPageHelper",
typ: "select",
options: [
{ value: "always", display: "Always" },
{ value: "inBigMode", display: "InBigMode" },
{ value: "never", display: "Never" }
]
},
{
key: "hitomiFormat",
typ: "select",
options: [
{ value: "auto", display: "Auto" },
{ value: "avif", display: "Avif" },
{ value: "webp", display: "Webp" },
{ value: "jxl", display: "Jxl" }
],
displayInSite: /hitomi.la\//
}
];
function evLog(level, msg, ...info) {
if (level === "debug" && !conf.debug)
return;
if (level === "error") {
console.warn((/* @__PURE__ */ new Date()).toLocaleString(), "EHVP:" + msg, ...info);
} else {
console.info((/* @__PURE__ */ new Date()).toLocaleString(), "EHVP:" + msg, ...info);
}
}
class EventManager {
events;
constructor() {
this.events = /* @__PURE__ */ new Map();
}
emit(id, ...args) {
if (!["imf-download-state-change"].includes(id)) {
evLog("debug", "event bus emitted: ", id);
}
const cbs = this.events.get(id);
if (cbs) {
cbs.forEach((cb) => cb(...args));
}
}
subscribe(id, cb) {
evLog("info", "event bus subscribed: ", id);
const cbs = this.events.get(id);
if (cbs) {
cbs.push(cb);
} else {
this.events.set(id, [cb]);
}
}
reset() {
this.events = /* @__PURE__ */ new Map();
}
}
const EBUS = new EventManager();
class Debouncer {
tids;
mode;
lastExecTime;
constructor(mode) {
this.tids = {};
this.lastExecTime = Date.now();
this.mode = mode || "debounce";
}
addEvent(id, event, timeout) {
if (this.mode === "throttle") {
const now = Date.now();
if (now - this.lastExecTime >= timeout) {
this.lastExecTime = now;
event();
}
} else if (this.mode === "debounce") {
window.clearTimeout(this.tids[id]);
this.tids[id] = window.setTimeout(event, timeout);
}
}
}
const HOST_REGEX = /\/\/([^\/]*)\//;
function xhrWapper(url, respType, cb, timeout) {
return _GM_xmlhttpRequest({
method: "GET",
url,
timeout: timeout || 0,
responseType: respType,
nocache: false,
revalidate: false,
// fetch: false,
headers: {
"Host": HOST_REGEX.exec(url)?.[1] || window.location.host,
// "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:106.0) Gecko/20100101 Firefox/106.0",
"Accept": "image/avif,image/webp,*/*",
// "Accept-Language": "en-US,en;q=0.5",
// "Accept-Encoding": "gzip, deflate, br",
// "Connection": "keep-alive",
"Referer": window.location.href,
// "Sec-Fetch-Dest": "image",
// "Sec-Fetch-Mode": "no-cors",
// "Sec-Fetch-Site": "cross-site",
"Cache-Control": "public, max-age=2592000, immutable"
},
...cb
}).abort;
}
function fetchImage(url) {
return new Promise((resolve, reject) => {
xhrWapper(url, "blob", {
onload: (response) => resolve(response.response),
onerror: (error) => reject(error)
}, 10 * 1e3);
});
}
var FetchState = /* @__PURE__ */ ((FetchState2) => {
FetchState2[FetchState2["FAILED"] = 0] = "FAILED";
FetchState2[FetchState2["URL"] = 1] = "URL";
FetchState2[FetchState2["DATA"] = 2] = "DATA";
FetchState2[FetchState2["DONE"] = 3] = "DONE";
return FetchState2;
})(FetchState || {});
class IMGFetcher {
node;
originURL;
stage = 1 /* URL */;
tryTimes = 0;
lock = false;
/// 0: not rendered, 1: rendered tumbinal, 2: rendered big image
rendered = 0;
data;
contentType;
blobUrl;
downloadState;
downloadBar;
timeoutId;
matcher;
chapterIndex;
constructor(root, matcher, chapterIndex) {
this.node = root;
this.node.onclick = () => EBUS.emit("imf-on-click", this);
this.downloadState = { total: 100, loaded: 0, readyState: 0 };
this.matcher = matcher;
this.chapterIndex = chapterIndex;
}
create() {
return this.node.create();
}
// 刷新下载状态
setDownloadState(newState) {
this.downloadState = { ...this.downloadState, ...newState };
this.node.progress(this.downloadState);
EBUS.emit("imf-download-state-change");
}
async start(index) {
if (this.lock)
return;
this.lock = true;
try {
this.node.changeStyle("fetching");
await this.fetchImage();
this.node.changeStyle("fetched");
EBUS.emit("imf-on-finished", index, true, this);
} catch (error) {
this.node.changeStyle("failed");
evLog("error", `IMG-FETCHER ERROR:`, error);
this.stage = 0 /* FAILED */;
EBUS.emit("imf-on-finished", index, false, this);
} finally {
this.lock = false;
}
}
retry() {
if (this.stage !== 3 /* DONE */) {
this.node.changeStyle();
this.stage = 1 /* URL */;
}
}
async fetchImage() {
this.tryTimes = 0;
while (this.tryTimes < 3) {
switch (this.stage) {
case 0 /* FAILED */:
case 1 /* URL */:
let meta = await this.fetchOriginMeta();
if (meta !== null) {
this.originURL = meta.url;
if (meta.title) {
this.node.title = meta.title;
if (this.node.imgElement) {
this.node.imgElement.title = meta.title;
}
}
this.stage = 2 /* DATA */;
} else {
this.tryTimes++;
}
break;
case 2 /* DATA */:
const ret = await this.fetchImageData();
if (ret !== null) {
[this.data, this.contentType] = ret;
[this.data, this.contentType] = await this.matcher.processData(this.data, this.contentType, this.originURL);
this.blobUrl = URL.createObjectURL(new Blob([this.data], { type: this.contentType }));
this.node.onloaded(this.blobUrl, this.contentType);
if (this.rendered === 2) {
this.node.render();
}
this.stage = 3 /* DONE */;
} else {
this.stage = 1 /* URL */;
this.tryTimes++;
}
break;
case 3 /* DONE */:
return;
}
}
throw new Error(`Fetch image failed, reach max try times, current stage: ${this.stage}`);
}
async fetchOriginMeta() {
try {
const meta = await this.matcher.fetchOriginMeta(this.node.href, this.tryTimes > 0, this.chapterIndex);
if (!meta) {
evLog("error", "Fetch URL failed, the URL is empty");
return null;
}
return meta;
} catch (error) {
evLog("error", `Fetch URL error:`, error);
return null;
}
}
async fetchImageData() {
try {
const data = await this.fetchBigImage();
if (data == null) {
throw new Error(`Data is null, image url:${this.originURL}`);
}
return data.arrayBuffer().then((buffer) => [new Uint8Array(buffer), data.type]);
} catch (error) {
evLog("error", `Fetch image data error:`, error);
return null;
}
}
render() {
switch (this.rendered) {
case 0:
case 1:
this.node.render();
this.rendered = 2;
if (this.stage === 3 /* DONE */)
this.node.changeStyle("fetched");
break;
}
}
unrender() {
if (this.rendered === 1 || this.rendered === 0)
return;
this.rendered = 1;
this.node.unrender();
}
async fetchBigImage() {
if (this.originURL?.startsWith("blob:")) {
return await fetch(this.originURL).then((resp) => resp.blob());
}
const imgFetcher = this;
return new Promise(async (resolve, reject) => {
const debouncer = new Debouncer();
let abort;
const timeout = () => {
debouncer.addEvent("XHR_TIMEOUT", () => {
reject("timeout");
abort();
}, conf.timeout * 1e3);
};
abort = xhrWapper(imgFetcher.originURL, "blob", {
onload: function(response) {
let data = response.response;
if (data.type === "text/html") {
console.error("warn: fetch big image data type is not blob: ", data);
}
try {
imgFetcher.setDownloadState({ readyState: response.readyState });
} catch (error) {
evLog("error", "warn: fetch big image data onload setDownloadState error:", error);
}
resolve(data);
},
onerror: function(response) {
reject(`error:${response.error}, response:${response.response}`);
},
onprogress: function(response) {
imgFetcher.setDownloadState({ total: response.total, loaded: response.loaded, readyState: response.readyState });
timeout();
},
onloadstart: function() {
imgFetcher.setDownloadState(imgFetcher.downloadState);
}
});
timeout();
});
}
}
const lang = navigator.language;
const i18nIndex = lang.startsWith("zh") ? 1 : 0;
class I18nValue extends Array {
constructor(...value) {
super(...value);
}
get() {
return this[i18nIndex];
}
}
const keyboardCustom = {
inMain: {
"open-full-view-grid": new I18nValue("Enter Read Mode", "进入阅读模式")
},
inBigImageMode: {
"step-image-prev": new I18nValue("Go Prev Image", "切换到上一张图片"),
"step-image-next": new I18nValue("Go Next Image", "切换到下一张图片"),
"exit-big-image-mode": new I18nValue("Exit Big Image Mode", "退出大图模式"),
"step-to-first-image": new I18nValue("Go First Image", "跳转到第一张图片"),
"step-to-last-image": new I18nValue("Go Last Image", "跳转到最后一张图片"),
"scale-image-increase": new I18nValue("Increase Image Scale", "放大图片"),
"scale-image-decrease": new I18nValue("Decrease Image Scale", "缩小图片"),
"scroll-image-up": new I18nValue("Scroll Image Up (Please Keep Default Keys)", "向上滚动图片 (请保留默认按键)"),
"scroll-image-down": new I18nValue("Scroll Image Down (Please Keep Default Keys)", "向下滚动图片 (请保留默认按键)")
},
inFullViewGrid: {
"open-big-image-mode": new I18nValue("Enter Big Image Mode", "进入大图阅读模式"),
"pause-auto-load-temporarily": new I18nValue("Pause Auto Load Temporarily", "临时停止自动加载"),
"exit-full-view-grid": new I18nValue("Exit Read Mode", "退出阅读模式"),
"columns-increase": new I18nValue("Increase Columns ", "增加每行数量"),
"columns-decrease": new I18nValue("Decrease Columns ", "减少每行数量"),
"back-chapters-selection": new I18nValue("Back to Chapters Selection", "返回章节选择")
}
};
const i18n = {
imageScale: new I18nValue("SCALE", "缩放"),
download: new I18nValue("DL", "下载"),
config: new I18nValue("CONF", "配置"),
backChapters: new I18nValue("Chapters", "章节"),
autoPagePlay: new I18nValue("PLAY", "播放"),
autoPagePause: new I18nValue("PAUSE", "暂停"),
autoPlay: new I18nValue("Auto Page", "自动翻页"),
autoPlayTooltip: new I18nValue("Auto Page when entering the big image readmode.", "当阅读大图时,开启自动播放模式。"),
preventScrollPageTime: new I18nValue("Flip Page Time", "滚动翻页时间"),
preventScrollPageTimeTooltip: new I18nValue("In Read Mode:Single Page, when scrolling through the content, prevent immediate page flipping when reaching the bottom, improve the reading experience. Set to 0 to disable this feature, measured in milliseconds.", "在单页阅读模式下,滚动浏览时,阻止滚动到底部时立即翻页,提升阅读体验。设置为0时则为禁用此功能,单位为毫秒。"),
collapse: new I18nValue("FOLD", "收起"),
colCount: new I18nValue("Columns", "每行数量"),
readMode: new I18nValue("Read Mode", "阅读模式"),
autoPageInterval: new I18nValue("Auto Page Interval", "自动翻页间隔"),
autoPageIntervalTooltip: new I18nValue("Use the mouse wheel on Input box to adjust the interval time.", "在输入框上使用鼠标滚轮快速修改间隔时间"),
readModeTooltip: new I18nValue("Switch to the next picture when scrolling, otherwise read continuously", "滚动时切换到下一张图片,否则连续阅读"),
threads: new I18nValue("PreloadThreads", "最大同时加载"),
threadsTooltip: new I18nValue("Max Preload Threads", "大图浏览时,每次滚动到下一张时,预加载的图片数量,大于1时体现为越看加载的图片越多,将提升浏览体验。"),
downloadThreads: new I18nValue("DownloadThreads", "最大同时下载"),
downloadThreadsTooltip: new I18nValue("Max Download Threads, suggest: <5", "下载模式下,同时加载的图片数量,建议小于等于5"),
timeout: new I18nValue("Timeout(second)", "超时时间(秒)"),
fetchOriginal: new I18nValue("Raw Image", "最佳质量"),
autoLoad: new I18nValue("Auto Load", "自动加载"),
autoLoadTooltip: new I18nValue("", "进入本脚本的浏览模式后,即使不浏览也会一张接一张的加载图片。直至所有图片加载完毕。"),
fetchOriginalTooltip: new I18nValue("enable will download the original source, cost more traffic and quotas", "启用后,将加载未经过压缩的原档文件,下载打包后的体积也与画廊所标体积一致。 注意:这将消耗更多的流量与配额,请酌情启用。"),
forceDownload: new I18nValue("Take Loaded", "强制下载已加载的"),
downloadStart: new I18nValue("Start Download", "开始下载"),
downloading: new I18nValue("Downloading...", "下载中..."),
downloadFailed: new I18nValue("Failed(Retry)", "下载失败(重试)"),
downloaded: new I18nValue("Downloaded", "下载完成"),
packaging: new I18nValue("Packaging...", "打包中..."),
reversePages: new I18nValue("Reverse Pages", "反向翻页"),
reversePagesTooltip: new I18nValue("Clicking on the side navigation, if enable then reverse paging, which is a reading style similar to Japanese manga where pages are read from right to left.", "点击侧边导航时,是否反向翻页,反向翻页类似日本漫画那样的从右到左的阅读方式。"),
autoCollapsePanel: new I18nValue("Auto Fold Control Panel", "自动收起控制面板"),
autoCollapsePanelTooltip: new I18nValue("When the mouse is moved out of the control panel, the control panel will automatically fold. If disabled, the display of the control panel can only be toggled through the button on the control bar.", "当鼠标移出控制面板时,自动收起控制面板。禁用此选项后,只能通过控制栏上的按钮切换控制面板的显示。"),
disableCssAnimation: new I18nValue("Disable Animation", "禁用动画"),
disableCssAnimationTooltip: new I18nValue("Valid after refreshing the page", "刷新页面后生效"),
stickyMouse: new I18nValue("Sticky Mouse", "黏糊糊鼠标"),
stickyMouseTooltip: new I18nValue("In non-continuous reading mode, scroll a single image automatically by moving the mouse.", "非连续阅读模式下,通过鼠标移动来自动滚动单张图片。"),
minifyPageHelper: new I18nValue("Minify Control Bar", "最小化控制栏"),
minifyPageHelperTooltip: new I18nValue("Minify Control Bar", "最小化控制栏"),
paginationIMGCount: new I18nValue("Images Per Page", "每页图片数量"),
paginationIMGCountTooltip: new I18nValue("In Pagination Read mode, the number of images displayed on each page", "在翻页阅读模式下,每页展示的图片数量"),
hitomiFormat: new I18nValue("Hitomi Image Format", "Hitomi 图片格式"),
hitomiFormatTooltip: new I18nValue("In Hitomi, Fetch images by the format. if Auto then try Avif > Jxl > Webp, Requires Refresh", "在Hitomi中的源图格式。 如果是Auto,则优先获取Avif > Jxl > Webp,修改后需要刷新生效。"),
autoOpen: new I18nValue("Auto Open", "自动展开"),
autoOpenTooltip: new I18nValue("Automatically open after the gallery page is loaded", "进入画廊页面后,自动展开阅读视图。"),
autoLoadInBackground: new I18nValue("Keep Loading", "后台加载"),
autoLoadInBackgroundTooltip: new I18nValue("Keep Auto-Loading after the tab loses focus", "当标签页失去焦点后保持自动加载。"),
dragToMove: new I18nValue("Drag to Move", "拖动移动"),
originalCheck: new I18nValue("Enable RawImage Transient", "未启用最佳质量图片,点击此处临时开启最佳质量"),
showHelp: new I18nValue("Help", "帮助"),
showKeyboard: new I18nValue("Keyboard", "快捷键"),
showExcludes: new I18nValue("Excludes", "站点排除"),
letUsStar: new I18nValue("Let's Star", "点星"),
help: new I18nValue(`
GUIDE:
If you are browsing E-Hentai, please click Here to switch to Lager thumbnail mode for clearer thumbnails. (need login e-hentai)
Click ⋖📖⋗ from left-bottom corner, entry reading.
Just a monment, all thumbnail will exhibited in grid, click one of thumbnails into big image mode.
You can use the mouse middle-click on a thumbnail to open the href of the image in new tab.
Image quality:For e-hentai,you can enable control-bar > CONF > Image Raw, which will directly download the uploaded original uncompressed images, but it will consume more quotas. Generally, the compressed files provided by E-Hentai are already clear enough.
Big image:click thumbnail image, into big image mode, use mouse wheel switch to next or prev
Keyboard:
Scale Image
mouse right + wheel or -/=
Open Image(In thumbnails)
Enter
Exit Image(In big mode)
Enter/Esc
Open Specific Page(In thumbnails)
Input number(no echo) + Enter
Switch Page
→/←
Scroll Image
↑/↓/Space
Toggle Auto Load
p
Download:You can click on the download button in the download panel to quickly load all the images. You can still continue browsing the images. Downloading and viewing large images are integrated, and you can click on Download Loaded in the download panel to save the images at any time.
Feedback:
Click
Issue
to provide feedback on issues, Give me a star if you like this script.
Star
`;
fullViewGrid.innerHTML = HTML_STRINGS;
const styleSheel = loadStyleSheel();
if (!conf.disableCssAnimation) {
toggleAnimationStyle(conf.disableCssAnimation);
}
return {
root: fullViewGrid,
fullViewGrid: q("#ehvp-nodes-container", fullViewGrid),
// root element
bigImageFrame: q("#big-img-frame", fullViewGrid),
// page helper
pageHelper: q("#p-helper", fullViewGrid),
// config button in pageHelper
configPanelBTN: q("#config-panel-btn", fullViewGrid),
// config panel mouse leave event
configPanel: q("#config-panel", fullViewGrid),
// download button in pageHelper
downloaderPanelBTN: q("#downloader-panel-btn", fullViewGrid),
// download panel mouse leave event
downloaderPanel: q("#downloader-panel", fullViewGrid),
collapseBTN: q("#collapse-btn", fullViewGrid),
gate: q("#ehvp-gate-icon", fullViewGrid),
currPageElement: q("#p-curr-page", fullViewGrid),
totalPageElement: q("#p-total", fullViewGrid),
finishedElement: q("#p-finished", fullViewGrid),
showGuideElement: q("#show-guide-element", fullViewGrid),
showKeyboardCustomElement: q("#show-keyboard-custom-element", fullViewGrid),
showExcludeURLElement: q("#show-exclude-url-element", fullViewGrid),
imgLandLeft: q("#img-land-left", fullViewGrid),
imgLandRight: q("#img-land-right", fullViewGrid),
imgScaleBar: q("#img-scale-bar", fullViewGrid),
autoPageBTN: q("#auto-page-btn", fullViewGrid),
pageLoading: q("#page-loading", fullViewGrid),
downloaderCanvas: q("#downloader-canvas", fullViewGrid),
downloadTabDashboard: q("#download-tab-dashboard", fullViewGrid),
downloadTabChapters: q("#download-tab-chapters", fullViewGrid),
downloadDashboard: q("#download-dashboard", fullViewGrid),
downloadChapters: q("#download-chapters", fullViewGrid),
downloadNotice: q("#download-notice", fullViewGrid),
downloadBTNForce: q("#download-force", fullViewGrid),
downloadBTNStart: q("#download-start", fullViewGrid),
styleSheel
};
}
function addEventListeners(events, HTML, BIFM, DL) {
HTML.configPanelBTN.addEventListener("click", () => events.togglePanelEvent("config"));
HTML.downloaderPanelBTN.addEventListener("click", () => {
events.togglePanelEvent("downloader");
DL.check();
});
function collapsePanel(key) {
const elements = { "config": HTML.configPanel, "downloader": HTML.downloaderPanel };
conf.autoCollapsePanel && events.collapsePanelEvent(elements[key], key);
}
HTML.configPanel.addEventListener("mouseleave", () => collapsePanel("config"));
HTML.configPanel.addEventListener("blur", () => collapsePanel("config"));
HTML.downloaderPanel.addEventListener("mouseleave", () => collapsePanel("downloader"));
HTML.downloaderPanel.addEventListener("blur", () => collapsePanel("downloader"));
HTML.pageHelper.addEventListener("mouseover", () => events.abortMouseleavePanelEvent());
HTML.pageHelper.addEventListener("mouseleave", () => ["config", "downloader"].forEach((k) => collapsePanel(k)));
ConfigItems.forEach((item) => {
switch (item.typ) {
case "number":
q(`#${item.key}MinusBTN`, HTML.root).addEventListener("click", () => events.modNumberConfigEvent(item.key, "minus"));
q(`#${item.key}AddBTN`, HTML.root).addEventListener("click", () => events.modNumberConfigEvent(item.key, "add"));
q(`#${item.key}Input`, HTML.root).addEventListener("wheel", (event) => {
event.preventDefault();
if (event.deltaY < 0) {
events.modNumberConfigEvent(item.key, "add");
} else if (event.deltaY > 0) {
events.modNumberConfigEvent(item.key, "minus");
}
});
break;
case "boolean":
q(`#${item.key}Checkbox`, HTML.root).addEventListener("click", () => events.modBooleanConfigEvent(item.key));
break;
case "select":
q(`#${item.key}Select`, HTML.root).addEventListener("change", () => events.modSelectConfigEvent(item.key));
break;
}
});
HTML.collapseBTN.addEventListener("click", () => events.main(false));
HTML.gate.addEventListener("click", () => events.main(true));
const debouncer = new Debouncer();
HTML.fullViewGrid.addEventListener("scroll", () => debouncer.addEvent("FULL-VIEW-SCROLL-EVENT", events.scrollEvent, 400));
HTML.fullViewGrid.addEventListener("click", events.hiddenFullViewGridEvent);
HTML.currPageElement.addEventListener("wheel", (event) => BIFM.stepNext(event.deltaY > 0 ? "next" : "prev", parseInt(event.target.textContent ?? "") - 1));
document.addEventListener("keydown", (event) => events.keyboardEvent(event));
HTML.fullViewGrid.addEventListener("keydown", (event) => {
events.fullViewGridKeyBoardEvent(event);
event.stopPropagation();
});
HTML.bigImageFrame.addEventListener("keydown", (event) => {
events.bigImageFrameKeyBoardEvent(event);
event.stopPropagation();
});
HTML.imgLandLeft.addEventListener("click", (event) => {
BIFM.stepNext(conf.reversePages ? "next" : "prev");
event.stopPropagation();
});
HTML.imgLandRight.addEventListener("click", (event) => {
BIFM.stepNext(conf.reversePages ? "prev" : "next");
event.stopPropagation();
});
HTML.showGuideElement.addEventListener("click", events.showGuideEvent);
HTML.showKeyboardCustomElement.addEventListener("click", events.showKeyboardCustomEvent);
HTML.showExcludeURLElement.addEventListener("click", events.showExcludeURLEvent);
dragElement(HTML.pageHelper, q("#dragHub", HTML.pageHelper), events.modPageHelperPostion);
}
class PageHelper {
html;
chapterIndex = 0;
constructor(html, getChapter) {
this.html = html;
EBUS.subscribe("pf-change-chapter", (index) => {
this.chapterIndex = index;
const [total, finished] = (() => {
const queue = getChapter(index)?.queue;
if (!queue)
return [0, 0];
const finished2 = queue.filter((imf) => imf.stage === FetchState.DONE).length;
return [finished2, queue.length];
})();
this.setPageState({ finished: finished.toString(), total: total.toString(), current: "1" });
});
EBUS.subscribe("bifm-on-show", () => this.minify(true, "bigImageFrame"));
EBUS.subscribe("bifm-on-hidden", () => this.minify(false, "bigImageFrame"));
EBUS.subscribe("ifq-do", (index, imf) => {
if (imf.chapterIndex !== this.chapterIndex)
return;
const queue = getChapter(this.chapterIndex)?.queue;
if (!queue)
return;
this.setPageState({ current: (index + 1).toString() });
if (imf.stage !== FetchState.DONE) {
this.setFetchState("fetching");
}
});
EBUS.subscribe("ifq-on-finished-report", (index, queue) => {
if (queue.chapterIndex !== this.chapterIndex)
return;
this.setPageState({ finished: queue.finishedIndex.size.toString() });
evLog("info", `No.${index + 1} Finished,Current index at No.${queue.currIndex + 1}`);
if (queue[queue.currIndex].stage === FetchState.DONE) {
this.setFetchState("fetched");
}
});
EBUS.subscribe("pf-on-appended", (total, _ifs, done) => {
this.setPageState({ total: `${total}${done ? "" : ".."}` });
});
html.currPageElement.addEventListener("click", (event) => {
const ele = event.target;
const index = parseInt(ele.textContent || "1") - 1;
const queue = getChapter(this.chapterIndex)?.queue;
if (!queue || !queue[index])
return;
EBUS.emit("imf-on-click", queue[index]);
});
}
setFetchState(state) {
if (state === "fetching") {
this.html.pageHelper.classList.add("p-helper-fetching");
} else {
this.html.pageHelper.classList.remove("p-helper-fetching");
}
}
setPageState({ total, current, finished }) {
if (total !== void 0) {
this.html.totalPageElement.textContent = total;
}
if (current !== void 0) {
this.html.currPageElement.textContent = current;
}
if (finished !== void 0) {
this.html.finishedElement.textContent = finished;
}
}
minify(ok, level) {
switch (conf.minifyPageHelper) {
case "inBigMode":
if (level === "fullViewGrid") {
return;
}
break;
case "always":
if (level === "bigImageFrame") {
return;
}
break;
case "never":
this.html.pageHelper.classList.remove("p-minify");
return;
}
if (ok) {
this.html.pageHelper.classList.add("p-minify");
} else {
this.html.pageHelper.classList.remove("p-minify");
}
}
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
var hammer = {exports: {}};
/*! Hammer.JS - v2.0.7 - 2016-04-22
* http://hammerjs.github.io/
*
* Copyright (c) 2016 Jorik Tangelder;
* Licensed under the MIT license */
(function (module) {
(function(window, document, exportName, undefined$1) {
var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
var TEST_ELEMENT = document.createElement('div');
var TYPE_FUNCTION = 'function';
var round = Math.round;
var abs = Math.abs;
var now = Date.now;
/**
* set a timeout with a given scope
* @param {Function} fn
* @param {Number} timeout
* @param {Object} context
* @returns {number}
*/
function setTimeoutContext(fn, timeout, context) {
return setTimeout(bindFn(fn, context), timeout);
}
/**
* if the argument is an array, we want to execute the fn on each entry
* if it aint an array we don't want to do a thing.
* this is used by all the methods that accept a single and array argument.
* @param {*|Array} arg
* @param {String} fn
* @param {Object} [context]
* @returns {Boolean}
*/
function invokeArrayArg(arg, fn, context) {
if (Array.isArray(arg)) {
each(arg, context[fn], context);
return true;
}
return false;
}
/**
* walk objects and arrays
* @param {Object} obj
* @param {Function} iterator
* @param {Object} context
*/
function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length !== undefined$1) {
i = 0;
while (i < obj.length) {
iterator.call(context, obj[i], i, obj);
i++;
}
} else {
for (i in obj) {
obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
}
}
}
/**
* wrap a method with a deprecation warning and stack trace
* @param {Function} method
* @param {String} name
* @param {String} message
* @returns {Function} A new function wrapping the supplied method.
*/
function deprecate(method, name, message) {
var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
return function() {
var e = new Error('get-stack-trace');
var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
.replace(/^\s+at\s+/gm, '')
.replace(/^Object.\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
var log = window.console && (window.console.warn || window.console.log);
if (log) {
log.call(window.console, deprecationMessage, stack);
}
return method.apply(this, arguments);
};
}
/**
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} target
* @param {...Object} objects_to_assign
* @returns {Object} target
*/
var assign;
if (typeof Object.assign !== 'function') {
assign = function assign(target) {
if (target === undefined$1 || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined$1 && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
} else {
assign = Object.assign;
}
/**
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} dest
* @param {Object} src
* @param {Boolean} [merge=false]
* @returns {Object} dest
*/
var extend = deprecate(function extend(dest, src, merge) {
var keys = Object.keys(src);
var i = 0;
while (i < keys.length) {
if (!merge || (merge && dest[keys[i]] === undefined$1)) {
dest[keys[i]] = src[keys[i]];
}
i++;
}
return dest;
}, 'extend', 'Use `assign`.');
/**
* merge the values from src in the dest.
* means that properties that exist in dest will not be overwritten by src
* @param {Object} dest
* @param {Object} src
* @returns {Object} dest
*/
var merge = deprecate(function merge(dest, src) {
return extend(dest, src, true);
}, 'merge', 'Use `assign`.');
/**
* simple class inheritance
* @param {Function} child
* @param {Function} base
* @param {Object} [properties]
*/
function inherit(child, base, properties) {
var baseP = base.prototype,
childP;
childP = child.prototype = Object.create(baseP);
childP.constructor = child;
childP._super = baseP;
if (properties) {
assign(childP, properties);
}
}
/**
* simple function bind
* @param {Function} fn
* @param {Object} context
* @returns {Function}
*/
function bindFn(fn, context) {
return function boundFn() {
return fn.apply(context, arguments);
};
}
/**
* let a boolean value also be a function that must return a boolean
* this first item in args will be used as the context
* @param {Boolean|Function} val
* @param {Array} [args]
* @returns {Boolean}
*/
function boolOrFn(val, args) {
if (typeof val == TYPE_FUNCTION) {
return val.apply(args ? args[0] || undefined$1 : undefined$1, args);
}
return val;
}
/**
* use the val2 when val1 is undefined
* @param {*} val1
* @param {*} val2
* @returns {*}
*/
function ifUndefined(val1, val2) {
return (val1 === undefined$1) ? val2 : val1;
}
/**
* addEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function addEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.addEventListener(type, handler, false);
});
}
/**
* removeEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function removeEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.removeEventListener(type, handler, false);
});
}
/**
* find if a node is in the given parent
* @method hasParent
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @return {Boolean} found
*/
function hasParent(node, parent) {
while (node) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
/**
* small indexOf wrapper
* @param {String} str
* @param {String} find
* @returns {Boolean} found
*/
function inStr(str, find) {
return str.indexOf(find) > -1;
}
/**
* split string on whitespace
* @param {String} str
* @returns {Array} words
*/
function splitStr(str) {
return str.trim().split(/\s+/g);
}
/**
* find if a array contains the object using indexOf or a simple polyFill
* @param {Array} src
* @param {String} find
* @param {String} [findByKey]
* @return {Boolean|Number} false when not found, or the index
*/
function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
var i = 0;
while (i < src.length) {
if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
return i;
}
i++;
}
return -1;
}
}
/**
* convert array-like objects to real arrays
* @param {Object} obj
* @returns {Array}
*/
function toArray(obj) {
return Array.prototype.slice.call(obj, 0);
}
/**
* unique array with objects based on a key (like 'id') or just by the array's value
* @param {Array} src [{id:1},{id:2},{id:1}]
* @param {String} [key]
* @param {Boolean} [sort=False]
* @returns {Array} [{id:1},{id:2}]
*/
function uniqueArray(src, key, sort) {
var results = [];
var values = [];
var i = 0;
while (i < src.length) {
var val = key ? src[i][key] : src[i];
if (inArray(values, val) < 0) {
results.push(src[i]);
}
values[i] = val;
i++;
}
if (sort) {
if (!key) {
results = results.sort();
} else {
results = results.sort(function sortUniqueArray(a, b) {
return a[key] > b[key];
});
}
}
return results;
}
/**
* get the prefixed property
* @param {Object} obj
* @param {String} property
* @returns {String|Undefined} prefixed
*/
function prefixed(obj, property) {
var prefix, prop;
var camelProp = property[0].toUpperCase() + property.slice(1);
var i = 0;
while (i < VENDOR_PREFIXES.length) {
prefix = VENDOR_PREFIXES[i];
prop = (prefix) ? prefix + camelProp : property;
if (prop in obj) {
return prop;
}
i++;
}
return undefined$1;
}
/**
* get a unique id
* @returns {number} uniqueId
*/
var _uniqueId = 1;
function uniqueId() {
return _uniqueId++;
}
/**
* get the window object of an element
* @param {HTMLElement} element
* @returns {DocumentView|Window}
*/
function getWindowForElement(element) {
var doc = element.ownerDocument || element;
return (doc.defaultView || doc.parentWindow || window);
}
var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
var SUPPORT_TOUCH = ('ontouchstart' in window);
var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined$1;
var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
var INPUT_TYPE_TOUCH = 'touch';
var INPUT_TYPE_PEN = 'pen';
var INPUT_TYPE_MOUSE = 'mouse';
var INPUT_TYPE_KINECT = 'kinect';
var COMPUTE_INTERVAL = 25;
var INPUT_START = 1;
var INPUT_MOVE = 2;
var INPUT_END = 4;
var INPUT_CANCEL = 8;
var DIRECTION_NONE = 1;
var DIRECTION_LEFT = 2;
var DIRECTION_RIGHT = 4;
var DIRECTION_UP = 8;
var DIRECTION_DOWN = 16;
var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
var PROPS_XY = ['x', 'y'];
var PROPS_CLIENT_XY = ['clientX', 'clientY'];
/**
* create new input type manager
* @param {Manager} manager
* @param {Function} callback
* @returns {Input}
* @constructor
*/
function Input(manager, callback) {
var self = this;
this.manager = manager;
this.callback = callback;
this.element = manager.element;
this.target = manager.options.inputTarget;
// smaller wrapper around the handler, for the scope and the enabled state of the manager,
// so when disabled the input events are completely bypassed.
this.domHandler = function(ev) {
if (boolOrFn(manager.options.enable, [manager])) {
self.handler(ev);
}
};
this.init();
}
Input.prototype = {
/**
* should handle the inputEvent data and trigger the callback
* @virtual
*/
handler: function() { },
/**
* bind the events
*/
init: function() {
this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
},
/**
* unbind the events
*/
destroy: function() {
this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
}
};
/**
* create new input type manager
* called by the Manager constructor
* @param {Hammer} manager
* @returns {Input}
*/
function createInputInstance(manager) {
var Type;
var inputClass = manager.options.inputClass;
if (inputClass) {
Type = inputClass;
} else if (SUPPORT_POINTER_EVENTS) {
Type = PointerEventInput;
} else if (SUPPORT_ONLY_TOUCH) {
Type = TouchInput;
} else if (!SUPPORT_TOUCH) {
Type = MouseInput;
} else {
Type = TouchMouseInput;
}
return new (Type)(manager, inputHandler);
}
/**
* handle input events
* @param {Manager} manager
* @param {String} eventType
* @param {Object} input
*/
function inputHandler(manager, eventType, input) {
var pointersLen = input.pointers.length;
var changedPointersLen = input.changedPointers.length;
var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));
var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));
input.isFirst = !!isFirst;
input.isFinal = !!isFinal;
if (isFirst) {
manager.session = {};
}
// source event is the normalized value of the domEvents
// like 'touchstart, mouseup, pointerdown'
input.eventType = eventType;
// compute scale, rotation etc
computeInputData(manager, input);
// emit secret event
manager.emit('hammer.input', input);
manager.recognize(input);
manager.session.prevInput = input;
}
/**
* extend the data with some usable properties like scale, rotate, velocity etc
* @param {Object} manager
* @param {Object} input
*/
function computeInputData(manager, input) {
var session = manager.session;
var pointers = input.pointers;
var pointersLength = pointers.length;
// store the first input to calculate the distance and direction
if (!session.firstInput) {
session.firstInput = simpleCloneInputData(input);
}
// to compute scale and rotation we need to store the multiple touches
if (pointersLength > 1 && !session.firstMultiple) {
session.firstMultiple = simpleCloneInputData(input);
} else if (pointersLength === 1) {
session.firstMultiple = false;
}
var firstInput = session.firstInput;
var firstMultiple = session.firstMultiple;
var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
var center = input.center = getCenter(pointers);
input.timeStamp = now();
input.deltaTime = input.timeStamp - firstInput.timeStamp;
input.angle = getAngle(offsetCenter, center);
input.distance = getDistance(offsetCenter, center);
computeDeltaXY(session, input);
input.offsetDirection = getDirection(input.deltaX, input.deltaY);
var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
input.overallVelocityX = overallVelocity.x;
input.overallVelocityY = overallVelocity.y;
input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y;
input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length >
session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers);
computeIntervalInputData(session, input);
// find the correct target
var target = manager.element;
if (hasParent(input.srcEvent.target, target)) {
target = input.srcEvent.target;
}
input.target = target;
}
function computeDeltaXY(session, input) {
var center = input.center;
var offset = session.offsetDelta || {};
var prevDelta = session.prevDelta || {};
var prevInput = session.prevInput || {};
if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
prevDelta = session.prevDelta = {
x: prevInput.deltaX || 0,
y: prevInput.deltaY || 0
};
offset = session.offsetDelta = {
x: center.x,
y: center.y
};
}
input.deltaX = prevDelta.x + (center.x - offset.x);
input.deltaY = prevDelta.y + (center.y - offset.y);
}
/**
* velocity is calculated every x ms
* @param {Object} session
* @param {Object} input
*/
function computeIntervalInputData(session, input) {
var last = session.lastInterval || input,
deltaTime = input.timeStamp - last.timeStamp,
velocity, velocityX, velocityY, direction;
if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined$1)) {
var deltaX = input.deltaX - last.deltaX;
var deltaY = input.deltaY - last.deltaY;
var v = getVelocity(deltaTime, deltaX, deltaY);
velocityX = v.x;
velocityY = v.y;
velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
direction = getDirection(deltaX, deltaY);
session.lastInterval = input;
} else {
// use latest velocity info if it doesn't overtake a minimum period
velocity = last.velocity;
velocityX = last.velocityX;
velocityY = last.velocityY;
direction = last.direction;
}
input.velocity = velocity;
input.velocityX = velocityX;
input.velocityY = velocityY;
input.direction = direction;
}
/**
* create a simple clone from the input used for storage of firstInput and firstMultiple
* @param {Object} input
* @returns {Object} clonedInputData
*/
function simpleCloneInputData(input) {
// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers = [];
var i = 0;
while (i < input.pointers.length) {
pointers[i] = {
clientX: round(input.pointers[i].clientX),
clientY: round(input.pointers[i].clientY)
};
i++;
}
return {
timeStamp: now(),
pointers: pointers,
center: getCenter(pointers),
deltaX: input.deltaX,
deltaY: input.deltaY
};
}
/**
* get the center of all the pointers
* @param {Array} pointers
* @return {Object} center contains `x` and `y` properties
*/
function getCenter(pointers) {
var pointersLength = pointers.length;
// no need to loop when only one touch
if (pointersLength === 1) {
return {
x: round(pointers[0].clientX),
y: round(pointers[0].clientY)
};
}
var x = 0, y = 0, i = 0;
while (i < pointersLength) {
x += pointers[i].clientX;
y += pointers[i].clientY;
i++;
}
return {
x: round(x / pointersLength),
y: round(y / pointersLength)
};
}
/**
* calculate the velocity between two points. unit is in px per ms.
* @param {Number} deltaTime
* @param {Number} x
* @param {Number} y
* @return {Object} velocity `x` and `y`
*/
function getVelocity(deltaTime, x, y) {
return {
x: x / deltaTime || 0,
y: y / deltaTime || 0
};
}
/**
* get the direction between two points
* @param {Number} x
* @param {Number} y
* @return {Number} direction
*/
function getDirection(x, y) {
if (x === y) {
return DIRECTION_NONE;
}
if (abs(x) >= abs(y)) {
return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
}
return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
}
/**
* calculate the absolute distance between two points
* @param {Object} p1 {x, y}
* @param {Object} p2 {x, y}
* @param {Array} [props] containing x and y keys
* @return {Number} distance
*/
function getDistance(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]],
y = p2[props[1]] - p1[props[1]];
return Math.sqrt((x * x) + (y * y));
}
/**
* calculate the angle between two coordinates
* @param {Object} p1
* @param {Object} p2
* @param {Array} [props] containing x and y keys
* @return {Number} angle
*/
function getAngle(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]],
y = p2[props[1]] - p1[props[1]];
return Math.atan2(y, x) * 180 / Math.PI;
}
/**
* calculate the rotation degrees between two pointersets
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} rotation
*/
function getRotation(start, end) {
return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
}
/**
* calculate the scale factor between two pointersets
* no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} scale
*/
function getScale(start, end) {
return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
}
var MOUSE_INPUT_MAP = {
mousedown: INPUT_START,
mousemove: INPUT_MOVE,
mouseup: INPUT_END
};
var MOUSE_ELEMENT_EVENTS = 'mousedown';
var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
/**
* Mouse events input
* @constructor
* @extends Input
*/
function MouseInput() {
this.evEl = MOUSE_ELEMENT_EVENTS;
this.evWin = MOUSE_WINDOW_EVENTS;
this.pressed = false; // mousedown state
Input.apply(this, arguments);
}
inherit(MouseInput, Input, {
/**
* handle mouse events
* @param {Object} ev
*/
handler: function MEhandler(ev) {
var eventType = MOUSE_INPUT_MAP[ev.type];
// on start we want to have the left mouse button down
if (eventType & INPUT_START && ev.button === 0) {
this.pressed = true;
}
if (eventType & INPUT_MOVE && ev.which !== 1) {
eventType = INPUT_END;
}
// mouse must be down
if (!this.pressed) {
return;
}
if (eventType & INPUT_END) {
this.pressed = false;
}
this.callback(this.manager, eventType, {
pointers: [ev],
changedPointers: [ev],
pointerType: INPUT_TYPE_MOUSE,
srcEvent: ev
});
}
});
var POINTER_INPUT_MAP = {
pointerdown: INPUT_START,
pointermove: INPUT_MOVE,
pointerup: INPUT_END,
pointercancel: INPUT_CANCEL,
pointerout: INPUT_CANCEL
};
// in IE10 the pointer types is defined as an enum
var IE10_POINTER_TYPE_ENUM = {
2: INPUT_TYPE_TOUCH,
3: INPUT_TYPE_PEN,
4: INPUT_TYPE_MOUSE,
5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
};
var POINTER_ELEMENT_EVENTS = 'pointerdown';
var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';
// IE10 has prefixed support, and case-sensitive
if (window.MSPointerEvent && !window.PointerEvent) {
POINTER_ELEMENT_EVENTS = 'MSPointerDown';
POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
}
/**
* Pointer events input
* @constructor
* @extends Input
*/
function PointerEventInput() {
this.evEl = POINTER_ELEMENT_EVENTS;
this.evWin = POINTER_WINDOW_EVENTS;
Input.apply(this, arguments);
this.store = (this.manager.session.pointerEvents = []);
}
inherit(PointerEventInput, Input, {
/**
* handle mouse events
* @param {Object} ev
*/
handler: function PEhandler(ev) {
var store = this.store;
var removePointer = false;
var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
var isTouch = (pointerType == INPUT_TYPE_TOUCH);
// get index of the event in the store
var storeIndex = inArray(store, ev.pointerId, 'pointerId');
// start and mouse must be down
if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
if (storeIndex < 0) {
store.push(ev);
storeIndex = store.length - 1;
}
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
removePointer = true;
}
// it not found, so the pointer hasn't been down (so it's probably a hover)
if (storeIndex < 0) {
return;
}
// update the event in the store
store[storeIndex] = ev;
this.callback(this.manager, eventType, {
pointers: store,
changedPointers: [ev],
pointerType: pointerType,
srcEvent: ev
});
if (removePointer) {
// remove from the store
store.splice(storeIndex, 1);
}
}
});
var SINGLE_TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';
/**
* Touch events input
* @constructor
* @extends Input
*/
function SingleTouchInput() {
this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
this.started = false;
Input.apply(this, arguments);
}
inherit(SingleTouchInput, Input, {
handler: function TEhandler(ev) {
var type = SINGLE_TOUCH_INPUT_MAP[ev.type];
// should we handle the touch events?
if (type === INPUT_START) {
this.started = true;
}
if (!this.started) {
return;
}
var touches = normalizeSingleTouches.call(this, ev, type);
// when done, reset the started state
if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
this.started = false;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
}
});
/**
* @this {TouchInput}
* @param {Object} ev
* @param {Number} type flag
* @returns {undefined|Array} [all, changed]
*/
function normalizeSingleTouches(ev, type) {
var all = toArray(ev.touches);
var changed = toArray(ev.changedTouches);
if (type & (INPUT_END | INPUT_CANCEL)) {
all = uniqueArray(all.concat(changed), 'identifier', true);
}
return [all, changed];
}
var TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
/**
* Multi-user touch events input
* @constructor
* @extends Input
*/
function TouchInput() {
this.evTarget = TOUCH_TARGET_EVENTS;
this.targetIds = {};
Input.apply(this, arguments);
}
inherit(TouchInput, Input, {
handler: function MTEhandler(ev) {
var type = TOUCH_INPUT_MAP[ev.type];
var touches = getTouches.call(this, ev, type);
if (!touches) {
return;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
}
});
/**
* @this {TouchInput}
* @param {Object} ev
* @param {Number} type flag
* @returns {undefined|Array} [all, changed]
*/
function getTouches(ev, type) {
var allTouches = toArray(ev.touches);
var targetIds = this.targetIds;
// when there is only one touch, the process can be simplified
if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
targetIds[allTouches[0].identifier] = true;
return [allTouches, allTouches];
}
var i,
targetTouches,
changedTouches = toArray(ev.changedTouches),
changedTargetTouches = [],
target = this.target;
// get target touches from touches
targetTouches = allTouches.filter(function(touch) {
return hasParent(touch.target, target);
});
// collect touches
if (type === INPUT_START) {
i = 0;
while (i < targetTouches.length) {
targetIds[targetTouches[i].identifier] = true;
i++;
}
}
// filter changed touches to only contain touches that exist in the collected target ids
i = 0;
while (i < changedTouches.length) {
if (targetIds[changedTouches[i].identifier]) {
changedTargetTouches.push(changedTouches[i]);
}
// cleanup removed touches
if (type & (INPUT_END | INPUT_CANCEL)) {
delete targetIds[changedTouches[i].identifier];
}
i++;
}
if (!changedTargetTouches.length) {
return;
}
return [
// merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
changedTargetTouches
];
}
/**
* Combined touch and mouse input
*
* Touch has a higher priority then mouse, and while touching no mouse events are allowed.
* This because touch devices also emit mouse events while doing a touch.
*
* @constructor
* @extends Input
*/
var DEDUP_TIMEOUT = 2500;
var DEDUP_DISTANCE = 25;
function TouchMouseInput() {
Input.apply(this, arguments);
var handler = bindFn(this.handler, this);
this.touch = new TouchInput(this.manager, handler);
this.mouse = new MouseInput(this.manager, handler);
this.primaryTouch = null;
this.lastTouches = [];
}
inherit(TouchMouseInput, Input, {
/**
* handle mouse and touch events
* @param {Hammer} manager
* @param {String} inputEvent
* @param {Object} inputData
*/
handler: function TMEhandler(manager, inputEvent, inputData) {
var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH),
isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);
if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
return;
}
// when we're in a touch event, record touches to de-dupe synthetic mouse event
if (isTouch) {
recordTouches.call(this, inputEvent, inputData);
} else if (isMouse && isSyntheticEvent.call(this, inputData)) {
return;
}
this.callback(manager, inputEvent, inputData);
},
/**
* remove the event listeners
*/
destroy: function destroy() {
this.touch.destroy();
this.mouse.destroy();
}
});
function recordTouches(eventType, eventData) {
if (eventType & INPUT_START) {
this.primaryTouch = eventData.changedPointers[0].identifier;
setLastTouch.call(this, eventData);
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
setLastTouch.call(this, eventData);
}
}
function setLastTouch(eventData) {
var touch = eventData.changedPointers[0];
if (touch.identifier === this.primaryTouch) {
var lastTouch = {x: touch.clientX, y: touch.clientY};
this.lastTouches.push(lastTouch);
var lts = this.lastTouches;
var removeLastTouch = function() {
var i = lts.indexOf(lastTouch);
if (i > -1) {
lts.splice(i, 1);
}
};
setTimeout(removeLastTouch, DEDUP_TIMEOUT);
}
}
function isSyntheticEvent(eventData) {
var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY;
for (var i = 0; i < this.lastTouches.length; i++) {
var t = this.lastTouches[i];
var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);
if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
return true;
}
}
return false;
}
var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined$1;
// magical touchAction value
var TOUCH_ACTION_COMPUTE = 'compute';
var TOUCH_ACTION_AUTO = 'auto';
var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
var TOUCH_ACTION_NONE = 'none';
var TOUCH_ACTION_PAN_X = 'pan-x';
var TOUCH_ACTION_PAN_Y = 'pan-y';
var TOUCH_ACTION_MAP = getTouchActionProps();
/**
* Touch Action
* sets the touchAction property or uses the js alternative
* @param {Manager} manager
* @param {String} value
* @constructor
*/
function TouchAction(manager, value) {
this.manager = manager;
this.set(value);
}
TouchAction.prototype = {
/**
* set the touchAction value on the element or enable the polyfill
* @param {String} value
*/
set: function(value) {
// find out the touch-action by the event handlers
if (value == TOUCH_ACTION_COMPUTE) {
value = this.compute();
}
if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
}
this.actions = value.toLowerCase().trim();
},
/**
* just re-set the touchAction value
*/
update: function() {
this.set(this.manager.options.touchAction);
},
/**
* compute the value for the touchAction property based on the recognizer's settings
* @returns {String} value
*/
compute: function() {
var actions = [];
each(this.manager.recognizers, function(recognizer) {
if (boolOrFn(recognizer.options.enable, [recognizer])) {
actions = actions.concat(recognizer.getTouchAction());
}
});
return cleanTouchActions(actions.join(' '));
},
/**
* this method is called on each input cycle and provides the preventing of the browser behavior
* @param {Object} input
*/
preventDefaults: function(input) {
var srcEvent = input.srcEvent;
var direction = input.offsetDirection;
// if the touch action did prevented once this session
if (this.manager.session.prevented) {
srcEvent.preventDefault();
return;
}
var actions = this.actions;
var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];
if (hasNone) {
//do not prevent defaults if this is a tap gesture
var isTapPointer = input.pointers.length === 1;
var isTapMovement = input.distance < 2;
var isTapTouchTime = input.deltaTime < 250;
if (isTapPointer && isTapMovement && isTapTouchTime) {
return;
}
}
if (hasPanX && hasPanY) {
// `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
return;
}
if (hasNone ||
(hasPanY && direction & DIRECTION_HORIZONTAL) ||
(hasPanX && direction & DIRECTION_VERTICAL)) {
return this.preventSrc(srcEvent);
}
},
/**
* call preventDefault to prevent the browser's default behavior (scrolling in most cases)
* @param {Object} srcEvent
*/
preventSrc: function(srcEvent) {
this.manager.session.prevented = true;
srcEvent.preventDefault();
}
};
/**
* when the touchActions are collected they are not a valid value, so we need to clean things up. *
* @param {String} actions
* @returns {*}
*/
function cleanTouchActions(actions) {
// none
if (inStr(actions, TOUCH_ACTION_NONE)) {
return TOUCH_ACTION_NONE;
}
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
// if both pan-x and pan-y are set (different recognizers
// for different directions, e.g. horizontal pan but vertical swipe?)
// we need none (as otherwise with pan-x pan-y combined none of these
// recognizers will work, since the browser would handle all panning
if (hasPanX && hasPanY) {
return TOUCH_ACTION_NONE;
}
// pan-x OR pan-y
if (hasPanX || hasPanY) {
return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
}
// manipulation
if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
return TOUCH_ACTION_MANIPULATION;
}
return TOUCH_ACTION_AUTO;
}
function getTouchActionProps() {
if (!NATIVE_TOUCH_ACTION) {
return false;
}
var touchMap = {};
var cssSupports = window.CSS && window.CSS.supports;
['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function(val) {
// If css.supports is not supported but there is native touch-action assume it supports
// all values. This is the case for IE 10 and 11.
touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true;
});
return touchMap;
}
/**
* Recognizer flow explained; *
* All recognizers have the initial state of POSSIBLE when a input session starts.
* The definition of a input session is from the first input until the last input, with all it's movement in it. *
* Example session for mouse-input: mousedown -> mousemove -> mouseup
*
* On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
* which determines with state it should be.
*
* If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
* POSSIBLE to give it another change on the next cycle.
*
* Possible
* |
* +-----+---------------+
* | |
* +-----+-----+ |
* | | |
* Failed Cancelled |
* +-------+------+
* | |
* Recognized Began
* |
* Changed
* |
* Ended/Recognized
*/
var STATE_POSSIBLE = 1;
var STATE_BEGAN = 2;
var STATE_CHANGED = 4;
var STATE_ENDED = 8;
var STATE_RECOGNIZED = STATE_ENDED;
var STATE_CANCELLED = 16;
var STATE_FAILED = 32;
/**
* Recognizer
* Every recognizer needs to extend from this class.
* @constructor
* @param {Object} options
*/
function Recognizer(options) {
this.options = assign({}, this.defaults, options || {});
this.id = uniqueId();
this.manager = null;
// default is enable true
this.options.enable = ifUndefined(this.options.enable, true);
this.state = STATE_POSSIBLE;
this.simultaneous = {};
this.requireFail = [];
}
Recognizer.prototype = {
/**
* @virtual
* @type {Object}
*/
defaults: {},
/**
* set options
* @param {Object} options
* @return {Recognizer}
*/
set: function(options) {
assign(this.options, options);
// also update the touchAction, in case something changed about the directions/enabled state
this.manager && this.manager.touchAction.update();
return this;
},
/**
* recognize simultaneous with an other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
recognizeWith: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
return this;
}
var simultaneous = this.simultaneous;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (!simultaneous[otherRecognizer.id]) {
simultaneous[otherRecognizer.id] = otherRecognizer;
otherRecognizer.recognizeWith(this);
}
return this;
},
/**
* drop the simultaneous link. it doesnt remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
dropRecognizeWith: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
delete this.simultaneous[otherRecognizer.id];
return this;
},
/**
* recognizer can only run when an other is failing
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
requireFailure: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
return this;
}
var requireFail = this.requireFail;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (inArray(requireFail, otherRecognizer) === -1) {
requireFail.push(otherRecognizer);
otherRecognizer.requireFailure(this);
}
return this;
},
/**
* drop the requireFailure link. it does not remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
dropRequireFailure: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
var index = inArray(this.requireFail, otherRecognizer);
if (index > -1) {
this.requireFail.splice(index, 1);
}
return this;
},
/**
* has require failures boolean
* @returns {boolean}
*/
hasRequireFailures: function() {
return this.requireFail.length > 0;
},
/**
* if the recognizer can recognize simultaneous with an other recognizer
* @param {Recognizer} otherRecognizer
* @returns {Boolean}
*/
canRecognizeWith: function(otherRecognizer) {
return !!this.simultaneous[otherRecognizer.id];
},
/**
* You should use `tryEmit` instead of `emit` directly to check
* that all the needed recognizers has failed before emitting.
* @param {Object} input
*/
emit: function(input) {
var self = this;
var state = this.state;
function emit(event) {
self.manager.emit(event, input);
}
// 'panstart' and 'panmove'
if (state < STATE_ENDED) {
emit(self.options.event + stateStr(state));
}
emit(self.options.event); // simple 'eventName' events
if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...)
emit(input.additionalEvent);
}
// panend and pancancel
if (state >= STATE_ENDED) {
emit(self.options.event + stateStr(state));
}
},
/**
* Check that all the require failure recognizers has failed,
* if true, it emits a gesture event,
* otherwise, setup the state to FAILED.
* @param {Object} input
*/
tryEmit: function(input) {
if (this.canEmit()) {
return this.emit(input);
}
// it's failing anyway
this.state = STATE_FAILED;
},
/**
* can we emit?
* @returns {boolean}
*/
canEmit: function() {
var i = 0;
while (i < this.requireFail.length) {
if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
return false;
}
i++;
}
return true;
},
/**
* update the recognizer
* @param {Object} inputData
*/
recognize: function(inputData) {
// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone = assign({}, inputData);
// is is enabled and allow recognizing?
if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
this.reset();
this.state = STATE_FAILED;
return;
}
// reset when we've reached the end
if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
this.state = STATE_POSSIBLE;
}
this.state = this.process(inputDataClone);
// the recognizer has recognized a gesture
// so trigger an event
if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
this.tryEmit(inputDataClone);
}
},
/**
* return the state of the recognizer
* the actual recognizing happens in this method
* @virtual
* @param {Object} inputData
* @returns {Const} STATE
*/
process: function(inputData) { }, // jshint ignore:line
/**
* return the preferred touch-action
* @virtual
* @returns {Array}
*/
getTouchAction: function() { },
/**
* called when the gesture isn't allowed to recognize
* like when another is being recognized or it is disabled
* @virtual
*/
reset: function() { }
};
/**
* get a usable string, used as event postfix
* @param {Const} state
* @returns {String} state
*/
function stateStr(state) {
if (state & STATE_CANCELLED) {
return 'cancel';
} else if (state & STATE_ENDED) {
return 'end';
} else if (state & STATE_CHANGED) {
return 'move';
} else if (state & STATE_BEGAN) {
return 'start';
}
return '';
}
/**
* direction cons to string
* @param {Const} direction
* @returns {String}
*/
function directionStr(direction) {
if (direction == DIRECTION_DOWN) {
return 'down';
} else if (direction == DIRECTION_UP) {
return 'up';
} else if (direction == DIRECTION_LEFT) {
return 'left';
} else if (direction == DIRECTION_RIGHT) {
return 'right';
}
return '';
}
/**
* get a recognizer by name if it is bound to a manager
* @param {Recognizer|String} otherRecognizer
* @param {Recognizer} recognizer
* @returns {Recognizer}
*/
function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
var manager = recognizer.manager;
if (manager) {
return manager.get(otherRecognizer);
}
return otherRecognizer;
}
/**
* This recognizer is just used as a base for the simple attribute recognizers.
* @constructor
* @extends Recognizer
*/
function AttrRecognizer() {
Recognizer.apply(this, arguments);
}
inherit(AttrRecognizer, Recognizer, {
/**
* @namespace
* @memberof AttrRecognizer
*/
defaults: {
/**
* @type {Number}
* @default 1
*/
pointers: 1
},
/**
* Used to check if it the recognizer receives valid input, like input.distance > 10.
* @memberof AttrRecognizer
* @param {Object} input
* @returns {Boolean} recognized
*/
attrTest: function(input) {
var optionPointers = this.options.pointers;
return optionPointers === 0 || input.pointers.length === optionPointers;
},
/**
* Process the input and return the state for the recognizer
* @memberof AttrRecognizer
* @param {Object} input
* @returns {*} State
*/
process: function(input) {
var state = this.state;
var eventType = input.eventType;
var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
var isValid = this.attrTest(input);
// on cancel input and we've recognized before, return STATE_CANCELLED
if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
return state | STATE_CANCELLED;
} else if (isRecognized || isValid) {
if (eventType & INPUT_END) {
return state | STATE_ENDED;
} else if (!(state & STATE_BEGAN)) {
return STATE_BEGAN;
}
return state | STATE_CHANGED;
}
return STATE_FAILED;
}
});
/**
* Pan
* Recognized when the pointer is down and moved in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
function PanRecognizer() {
AttrRecognizer.apply(this, arguments);
this.pX = null;
this.pY = null;
}
inherit(PanRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof PanRecognizer
*/
defaults: {
event: 'pan',
threshold: 10,
pointers: 1,
direction: DIRECTION_ALL
},
getTouchAction: function() {
var direction = this.options.direction;
var actions = [];
if (direction & DIRECTION_HORIZONTAL) {
actions.push(TOUCH_ACTION_PAN_Y);
}
if (direction & DIRECTION_VERTICAL) {
actions.push(TOUCH_ACTION_PAN_X);
}
return actions;
},
directionTest: function(input) {
var options = this.options;
var hasMoved = true;
var distance = input.distance;
var direction = input.direction;
var x = input.deltaX;
var y = input.deltaY;
// lock to axis?
if (!(direction & options.direction)) {
if (options.direction & DIRECTION_HORIZONTAL) {
direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
hasMoved = x != this.pX;
distance = Math.abs(input.deltaX);
} else {
direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
hasMoved = y != this.pY;
distance = Math.abs(input.deltaY);
}
}
input.direction = direction;
return hasMoved && distance > options.threshold && direction & options.direction;
},
attrTest: function(input) {
return AttrRecognizer.prototype.attrTest.call(this, input) &&
(this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
},
emit: function(input) {
this.pX = input.deltaX;
this.pY = input.deltaY;
var direction = directionStr(input.direction);
if (direction) {
input.additionalEvent = this.options.event + direction;
}
this._super.emit.call(this, input);
}
});
/**
* Pinch
* Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
* @constructor
* @extends AttrRecognizer
*/
function PinchRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(PinchRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof PinchRecognizer
*/
defaults: {
event: 'pinch',
threshold: 0,
pointers: 2
},
getTouchAction: function() {
return [TOUCH_ACTION_NONE];
},
attrTest: function(input) {
return this._super.attrTest.call(this, input) &&
(Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
},
emit: function(input) {
if (input.scale !== 1) {
var inOut = input.scale < 1 ? 'in' : 'out';
input.additionalEvent = this.options.event + inOut;
}
this._super.emit.call(this, input);
}
});
/**
* Press
* Recognized when the pointer is down for x ms without any movement.
* @constructor
* @extends Recognizer
*/
function PressRecognizer() {
Recognizer.apply(this, arguments);
this._timer = null;
this._input = null;
}
inherit(PressRecognizer, Recognizer, {
/**
* @namespace
* @memberof PressRecognizer
*/
defaults: {
event: 'press',
pointers: 1,
time: 251, // minimal time of the pointer to be pressed
threshold: 9 // a minimal movement is ok, but keep it low
},
getTouchAction: function() {
return [TOUCH_ACTION_AUTO];
},
process: function(input) {
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTime = input.deltaTime > options.time;
this._input = input;
// we only allow little movement
// and we've reached an end event, so a tap is possible
if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
this.reset();
} else if (input.eventType & INPUT_START) {
this.reset();
this._timer = setTimeoutContext(function() {
this.state = STATE_RECOGNIZED;
this.tryEmit();
}, options.time, this);
} else if (input.eventType & INPUT_END) {
return STATE_RECOGNIZED;
}
return STATE_FAILED;
},
reset: function() {
clearTimeout(this._timer);
},
emit: function(input) {
if (this.state !== STATE_RECOGNIZED) {
return;
}
if (input && (input.eventType & INPUT_END)) {
this.manager.emit(this.options.event + 'up', input);
} else {
this._input.timeStamp = now();
this.manager.emit(this.options.event, this._input);
}
}
});
/**
* Rotate
* Recognized when two or more pointer are moving in a circular motion.
* @constructor
* @extends AttrRecognizer
*/
function RotateRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(RotateRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof RotateRecognizer
*/
defaults: {
event: 'rotate',
threshold: 0,
pointers: 2
},
getTouchAction: function() {
return [TOUCH_ACTION_NONE];
},
attrTest: function(input) {
return this._super.attrTest.call(this, input) &&
(Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
}
});
/**
* Swipe
* Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
function SwipeRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(SwipeRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof SwipeRecognizer
*/
defaults: {
event: 'swipe',
threshold: 10,
velocity: 0.3,
direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
pointers: 1
},
getTouchAction: function() {
return PanRecognizer.prototype.getTouchAction.call(this);
},
attrTest: function(input) {
var direction = this.options.direction;
var velocity;
if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
velocity = input.overallVelocity;
} else if (direction & DIRECTION_HORIZONTAL) {
velocity = input.overallVelocityX;
} else if (direction & DIRECTION_VERTICAL) {
velocity = input.overallVelocityY;
}
return this._super.attrTest.call(this, input) &&
direction & input.offsetDirection &&
input.distance > this.options.threshold &&
input.maxPointers == this.options.pointers &&
abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
},
emit: function(input) {
var direction = directionStr(input.offsetDirection);
if (direction) {
this.manager.emit(this.options.event + direction, input);
}
this.manager.emit(this.options.event, input);
}
});
/**
* A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
* between the given interval and position. The delay option can be used to recognize multi-taps without firing
* a single tap.
*
* The eventData from the emitted event contains the property `tapCount`, which contains the amount of
* multi-taps being recognized.
* @constructor
* @extends Recognizer
*/
function TapRecognizer() {
Recognizer.apply(this, arguments);
// previous time and center,
// used for tap counting
this.pTime = false;
this.pCenter = false;
this._timer = null;
this._input = null;
this.count = 0;
}
inherit(TapRecognizer, Recognizer, {
/**
* @namespace
* @memberof PinchRecognizer
*/
defaults: {
event: 'tap',
pointers: 1,
taps: 1,
interval: 300, // max time between the multi-tap taps
time: 250, // max time of the pointer to be down (like finger on the screen)
threshold: 9, // a minimal movement is ok, but keep it low
posThreshold: 10 // a multi-tap can be a bit off the initial position
},
getTouchAction: function() {
return [TOUCH_ACTION_MANIPULATION];
},
process: function(input) {
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTouchTime = input.deltaTime < options.time;
this.reset();
if ((input.eventType & INPUT_START) && (this.count === 0)) {
return this.failTimeout();
}
// we only allow little movement
// and we've reached an end event, so a tap is possible
if (validMovement && validTouchTime && validPointers) {
if (input.eventType != INPUT_END) {
return this.failTimeout();
}
var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
this.pTime = input.timeStamp;
this.pCenter = input.center;
if (!validMultiTap || !validInterval) {
this.count = 1;
} else {
this.count += 1;
}
this._input = input;
// if tap count matches we have recognized it,
// else it has began recognizing...
var tapCount = this.count % options.taps;
if (tapCount === 0) {
// no failing requirements, immediately trigger the tap event
// or wait as long as the multitap interval to trigger
if (!this.hasRequireFailures()) {
return STATE_RECOGNIZED;
} else {
this._timer = setTimeoutContext(function() {
this.state = STATE_RECOGNIZED;
this.tryEmit();
}, options.interval, this);
return STATE_BEGAN;
}
}
}
return STATE_FAILED;
},
failTimeout: function() {
this._timer = setTimeoutContext(function() {
this.state = STATE_FAILED;
}, this.options.interval, this);
return STATE_FAILED;
},
reset: function() {
clearTimeout(this._timer);
},
emit: function() {
if (this.state == STATE_RECOGNIZED) {
this._input.tapCount = this.count;
this.manager.emit(this.options.event, this._input);
}
}
});
/**
* Simple way to create a manager with a default set of recognizers.
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
function Hammer(element, options) {
options = options || {};
options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
return new Manager(element, options);
}
/**
* @const {string}
*/
Hammer.VERSION = '2.0.7';
/**
* default settings
* @namespace
*/
Hammer.defaults = {
/**
* set if DOM events are being triggered.
* But this is slower and unused by simple implementations, so disabled by default.
* @type {Boolean}
* @default false
*/
domEvents: false,
/**
* The value for the touchAction property/fallback.
* When set to `compute` it will magically set the correct value based on the added recognizers.
* @type {String}
* @default compute
*/
touchAction: TOUCH_ACTION_COMPUTE,
/**
* @type {Boolean}
* @default true
*/
enable: true,
/**
* EXPERIMENTAL FEATURE -- can be removed/changed
* Change the parent input target element.
* If Null, then it is being set the to main element.
* @type {Null|EventTarget}
* @default null
*/
inputTarget: null,
/**
* force an input class
* @type {Null|Function}
* @default null
*/
inputClass: null,
/**
* Default recognizer setup when calling `Hammer()`
* When creating a new Manager these will be skipped.
* @type {Array}
*/
preset: [
// RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
[RotateRecognizer, {enable: false}],
[PinchRecognizer, {enable: false}, ['rotate']],
[SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}],
[PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']],
[TapRecognizer],
[TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']],
[PressRecognizer]
],
/**
* Some CSS properties can be used to improve the working of Hammer.
* Add them to this method and they will be set when creating a new Manager.
* @namespace
*/
cssProps: {
/**
* Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userSelect: 'none',
/**
* Disable the Windows Phone grippers when pressing an element.
* @type {String}
* @default 'none'
*/
touchSelect: 'none',
/**
* Disables the default callout shown when you touch and hold a touch target.
* On iOS, when you touch and hold a touch target such as a link, Safari displays
* a callout containing information about the link. This property allows you to disable that callout.
* @type {String}
* @default 'none'
*/
touchCallout: 'none',
/**
* Specifies whether zooming is enabled. Used by IE10>
* @type {String}
* @default 'none'
*/
contentZooming: 'none',
/**
* Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userDrag: 'none',
/**
* Overrides the highlight color shown when the user taps a link or a JavaScript
* clickable element in iOS. This property obeys the alpha value, if specified.
* @type {String}
* @default 'rgba(0,0,0,0)'
*/
tapHighlightColor: 'rgba(0,0,0,0)'
}
};
var STOP = 1;
var FORCED_STOP = 2;
/**
* Manager
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
function Manager(element, options) {
this.options = assign({}, Hammer.defaults, options || {});
this.options.inputTarget = this.options.inputTarget || element;
this.handlers = {};
this.session = {};
this.recognizers = [];
this.oldCssProps = {};
this.element = element;
this.input = createInputInstance(this);
this.touchAction = new TouchAction(this, this.options.touchAction);
toggleCssProps(this, true);
each(this.options.recognizers, function(item) {
var recognizer = this.add(new (item[0])(item[1]));
item[2] && recognizer.recognizeWith(item[2]);
item[3] && recognizer.requireFailure(item[3]);
}, this);
}
Manager.prototype = {
/**
* set options
* @param {Object} options
* @returns {Manager}
*/
set: function(options) {
assign(this.options, options);
// Options that need a little more setup
if (options.touchAction) {
this.touchAction.update();
}
if (options.inputTarget) {
// Clean up existing event listeners and reinitialize
this.input.destroy();
this.input.target = options.inputTarget;
this.input.init();
}
return this;
},
/**
* stop recognizing for this session.
* This session will be discarded, when a new [input]start event is fired.
* When forced, the recognizer cycle is stopped immediately.
* @param {Boolean} [force]
*/
stop: function(force) {
this.session.stopped = force ? FORCED_STOP : STOP;
},
/**
* run the recognizers!
* called by the inputHandler function on every movement of the pointers (touches)
* it walks through all the recognizers and tries to detect the gesture that is being made
* @param {Object} inputData
*/
recognize: function(inputData) {
var session = this.session;
if (session.stopped) {
return;
}
// run the touch-action polyfill
this.touchAction.preventDefaults(inputData);
var recognizer;
var recognizers = this.recognizers;
// this holds the recognizer that is being recognized.
// so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
// if no recognizer is detecting a thing, it is set to `null`
var curRecognizer = session.curRecognizer;
// reset when the last recognizer is recognized
// or when we're in a new session
if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
curRecognizer = session.curRecognizer = null;
}
var i = 0;
while (i < recognizers.length) {
recognizer = recognizers[i];
// find out if we are allowed try to recognize the input for this one.
// 1. allow if the session is NOT forced stopped (see the .stop() method)
// 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
// that is being recognized.
// 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
// this can be setup with the `recognizeWith()` method on the recognizer.
if (session.stopped !== FORCED_STOP && ( // 1
!curRecognizer || recognizer == curRecognizer || // 2
recognizer.canRecognizeWith(curRecognizer))) { // 3
recognizer.recognize(inputData);
} else {
recognizer.reset();
}
// if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
// current active recognizer. but only if we don't already have an active recognizer
if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
curRecognizer = session.curRecognizer = recognizer;
}
i++;
}
},
/**
* get a recognizer by its event name.
* @param {Recognizer|String} recognizer
* @returns {Recognizer|Null}
*/
get: function(recognizer) {
if (recognizer instanceof Recognizer) {
return recognizer;
}
var recognizers = this.recognizers;
for (var i = 0; i < recognizers.length; i++) {
if (recognizers[i].options.event == recognizer) {
return recognizers[i];
}
}
return null;
},
/**
* add a recognizer to the manager
* existing recognizers with the same event name will be removed
* @param {Recognizer} recognizer
* @returns {Recognizer|Manager}
*/
add: function(recognizer) {
if (invokeArrayArg(recognizer, 'add', this)) {
return this;
}
// remove existing
var existing = this.get(recognizer.options.event);
if (existing) {
this.remove(existing);
}
this.recognizers.push(recognizer);
recognizer.manager = this;
this.touchAction.update();
return recognizer;
},
/**
* remove a recognizer by name or instance
* @param {Recognizer|String} recognizer
* @returns {Manager}
*/
remove: function(recognizer) {
if (invokeArrayArg(recognizer, 'remove', this)) {
return this;
}
recognizer = this.get(recognizer);
// let's make sure this recognizer exists
if (recognizer) {
var recognizers = this.recognizers;
var index = inArray(recognizers, recognizer);
if (index !== -1) {
recognizers.splice(index, 1);
this.touchAction.update();
}
}
return this;
},
/**
* bind event
* @param {String} events
* @param {Function} handler
* @returns {EventEmitter} this
*/
on: function(events, handler) {
if (events === undefined$1) {
return;
}
if (handler === undefined$1) {
return;
}
var handlers = this.handlers;
each(splitStr(events), function(event) {
handlers[event] = handlers[event] || [];
handlers[event].push(handler);
});
return this;
},
/**
* unbind event, leave emit blank to remove all handlers
* @param {String} events
* @param {Function} [handler]
* @returns {EventEmitter} this
*/
off: function(events, handler) {
if (events === undefined$1) {
return;
}
var handlers = this.handlers;
each(splitStr(events), function(event) {
if (!handler) {
delete handlers[event];
} else {
handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
}
});
return this;
},
/**
* emit event to the listeners
* @param {String} event
* @param {Object} data
*/
emit: function(event, data) {
// we also want to trigger dom events
if (this.options.domEvents) {
triggerDomEvent(event, data);
}
// no handlers, so skip it all
var handlers = this.handlers[event] && this.handlers[event].slice();
if (!handlers || !handlers.length) {
return;
}
data.type = event;
data.preventDefault = function() {
data.srcEvent.preventDefault();
};
var i = 0;
while (i < handlers.length) {
handlers[i](data);
i++;
}
},
/**
* destroy the manager and unbinds all events
* it doesn't unbind dom events, that is the user own responsibility
*/
destroy: function() {
this.element && toggleCssProps(this, false);
this.handlers = {};
this.session = {};
this.input.destroy();
this.element = null;
}
};
/**
* add/remove the css properties as defined in manager.options.cssProps
* @param {Manager} manager
* @param {Boolean} add
*/
function toggleCssProps(manager, add) {
var element = manager.element;
if (!element.style) {
return;
}
var prop;
each(manager.options.cssProps, function(value, name) {
prop = prefixed(element.style, name);
if (add) {
manager.oldCssProps[prop] = element.style[prop];
element.style[prop] = value;
} else {
element.style[prop] = manager.oldCssProps[prop] || '';
}
});
if (!add) {
manager.oldCssProps = {};
}
}
/**
* trigger dom event
* @param {String} event
* @param {Object} data
*/
function triggerDomEvent(event, data) {
var gestureEvent = document.createEvent('Event');
gestureEvent.initEvent(event, true, true);
gestureEvent.gesture = data;
data.target.dispatchEvent(gestureEvent);
}
assign(Hammer, {
INPUT_START: INPUT_START,
INPUT_MOVE: INPUT_MOVE,
INPUT_END: INPUT_END,
INPUT_CANCEL: INPUT_CANCEL,
STATE_POSSIBLE: STATE_POSSIBLE,
STATE_BEGAN: STATE_BEGAN,
STATE_CHANGED: STATE_CHANGED,
STATE_ENDED: STATE_ENDED,
STATE_RECOGNIZED: STATE_RECOGNIZED,
STATE_CANCELLED: STATE_CANCELLED,
STATE_FAILED: STATE_FAILED,
DIRECTION_NONE: DIRECTION_NONE,
DIRECTION_LEFT: DIRECTION_LEFT,
DIRECTION_RIGHT: DIRECTION_RIGHT,
DIRECTION_UP: DIRECTION_UP,
DIRECTION_DOWN: DIRECTION_DOWN,
DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
DIRECTION_VERTICAL: DIRECTION_VERTICAL,
DIRECTION_ALL: DIRECTION_ALL,
Manager: Manager,
Input: Input,
TouchAction: TouchAction,
TouchInput: TouchInput,
MouseInput: MouseInput,
PointerEventInput: PointerEventInput,
TouchMouseInput: TouchMouseInput,
SingleTouchInput: SingleTouchInput,
Recognizer: Recognizer,
AttrRecognizer: AttrRecognizer,
Tap: TapRecognizer,
Pan: PanRecognizer,
Swipe: SwipeRecognizer,
Pinch: PinchRecognizer,
Rotate: RotateRecognizer,
Press: PressRecognizer,
on: addEventListeners,
off: removeEventListeners,
each: each,
merge: merge,
extend: extend,
assign: assign,
inherit: inherit,
bindFn: bindFn,
prefixed: prefixed
});
// this prevents errors when Hammer is loaded in the presence of an AMD
// style loader but by script tag, not by the loader.
var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line
freeGlobal.Hammer = Hammer;
if (typeof undefined$1 === 'function' && undefined$1.amd) {
undefined$1(function() {
return Hammer;
});
} else if (module.exports) {
module.exports = Hammer;
} else {
window[exportName] = Hammer;
}
})(window, document, 'Hammer');
} (hammer));
var hammerExports = hammer.exports;
const Hammer = /*@__PURE__*/getDefaultExportFromCjs(hammerExports);
function onMouse(ele, callback, signal) {
ele.addEventListener("mousedown", (event) => {
const { left } = ele.getBoundingClientRect();
const mouseMove = (event2) => {
const xInProgress = event2.clientX - left;
const percent = Math.round(xInProgress / ele.clientWidth * 100);
callback(percent);
};
mouseMove(event);
ele.addEventListener("mousemove", mouseMove);
ele.addEventListener("mouseup", () => {
ele.removeEventListener("mousemove", mouseMove);
}, { once: true });
ele.addEventListener("mouseleave", () => {
ele.removeEventListener("mousemove", mouseMove);
}, { once: true });
}, { signal });
}
const PLAY_ICON = ``;
const PAUSE_ICON = ``;
const VOLUME_ICON = ``;
const MUTED_ICON = ``;
class VideoControl {
ui;
context = /* @__PURE__ */ new Map();
paused = false;
abortController;
constructor(root) {
this.ui = this.create(root);
this.flushUI();
}
show() {
this.ui.root.hidden = false;
}
hidden() {
this.ui.root.hidden = true;
}
create(root) {
const ui = document.createElement("div");
ui.classList.add("bifm-vid-ctl");
ui.innerHTML = `
00:00/10:00
`;
root.appendChild(ui);
return {
root: ui,
playBTN: q("#bifm-vid-ctl-play", ui),
volumeBTN: q("#bifm-vid-ctl-mute", ui),
volumeProgress: q("#bifm-vid-ctl-volume", ui),
progress: q("#bifm-vid-ctl-pg", ui),
time: q("#bifm-vid-ctl-time", ui),
duration: q("#bifm-vid-ctl-duration", ui)
};
}
flushUI(state, onlyState) {
let { value, max } = state ? { value: state.time, max: state.duration } : { value: 0, max: 10 };
const percent = value / max * 100;
this.ui.progress.firstElementChild.style.width = `${percent}%`;
this.ui.time.textContent = secondsToTime(value);
this.ui.duration.textContent = secondsToTime(max);
if (onlyState)
return;
this.ui.playBTN.innerHTML = this.paused ? PLAY_ICON : PAUSE_ICON;
this.ui.volumeBTN.innerHTML = conf.muted ? MUTED_ICON : VOLUME_ICON;
this.ui.volumeProgress.firstElementChild.style.width = `${conf.volume || 30}%`;
}
attach(element) {
evLog("info", "attach video control");
this.detach();
this.show();
this.abortController = new AbortController();
let state = this.context.get(element.src);
if (!state) {
state = { time: element.currentTime, duration: element.duration };
this.context.set(element.src, state);
} else {
element.currentTime = state.time;
}
this.flushUI(state);
element.addEventListener("timeupdate", (event) => {
const ele = event.target;
if (!state)
return;
state.time = ele.currentTime;
this.flushUI(state, true);
}, { signal: this.abortController.signal });
element.onwaiting = () => evLog("debug", "onwaiting");
element.loop = true;
element.muted = conf.muted || false;
element.volume = (conf.volume || 30) / 100;
if (!this.paused) {
element.play();
}
let elementID = element.id;
if (!elementID) {
elementID = "vid-" + Math.random().toString(36).slice(2);
element.id = elementID;
}
this.ui.playBTN.addEventListener("click", () => {
const vid = document.querySelector(`#${elementID}`);
if (vid) {
this.paused = !this.paused;
if (this.paused) {
vid.pause();
} else {
vid.play();
}
this.flushUI(this.context.get(vid.src));
}
}, { signal: this.abortController.signal });
this.ui.volumeBTN.addEventListener("click", () => {
const vid = document.querySelector(`#${elementID}`);
if (vid) {
conf.muted = !conf.muted;
vid.muted = conf.muted;
saveConf(conf);
this.flushUI(this.context.get(vid.src));
}
}, { signal: this.abortController.signal });
onMouse(this.ui.progress, (percent) => {
const vid = document.querySelector(`#${elementID}`);
if (vid) {
vid.currentTime = vid.duration * (percent / 100);
const state2 = this.context.get(vid.src);
state2.time = vid.currentTime;
this.flushUI(state2);
}
}, this.abortController.signal);
onMouse(this.ui.volumeProgress, (percent) => {
const vid = document.querySelector(`#${elementID}`);
if (vid) {
conf.volume = percent;
saveConf(conf);
vid.volume = conf.volume / 100;
this.flushUI(this.context.get(vid.src));
}
}, this.abortController.signal);
}
detach() {
this.abortController?.abort();
this.abortController = void 0;
this.flushUI();
}
}
function secondsToTime(seconds) {
const min = Math.floor(seconds / 60).toString().padStart(2, "0");
const sec = Math.floor(seconds % 60).toString().padStart(2, "0");
return `${min}:${sec}`;
}
class BigImageFrameManager {
frame;
lockInit;
lastMouse;
fragment;
// image decode will take a while, so cache it to fragment
elements = { next: [], curr: [], prev: [] };
imgScaleBar;
debouncer;
throttler;
callbackOnWheel;
hammer;
preventStep = { fin: false };
visible = false;
html;
frameScrollAbort;
vidController;
chapterIndex = 0;
getChapter;
constructor(HTML, getChapter) {
this.html = HTML;
this.frame = HTML.bigImageFrame;
this.fragment = new DocumentFragment();
this.imgScaleBar = HTML.imgScaleBar;
this.debouncer = new Debouncer();
this.throttler = new Debouncer("throttle");
this.lockInit = false;
this.getChapter = getChapter;
this.resetStickyMouse();
this.initFrame();
this.initImgScaleBar();
this.initImgScaleStyle();
this.initHammer();
EBUS.subscribe("pf-change-chapter", (index) => this.chapterIndex = Math.max(0, index));
EBUS.subscribe("imf-on-click", (imf) => this.show(imf));
EBUS.subscribe("imf-on-finished", (index, success, imf) => {
if (imf.chapterIndex !== this.chapterIndex)
return;
if (!this.visible || !success)
return;
const elements = [
...this.elements.curr.map((e, i) => ({ img: e, eleIndex: i, key: "curr" })),
...this.elements.prev.map((e, i) => ({ img: e, eleIndex: i, key: "prev" })),
...this.elements.next.map((e, i) => ({ img: e, eleIndex: i, key: "next" })),
...this.getMediaNodes().map((e, i) => ({ img: e, eleIndex: i, key: "" }))
];
const ret = elements.find((o) => index === parseIndex(o.img));
if (!ret)
return;
let { img, eleIndex, key } = ret;
if (imf.contentType?.startsWith("video")) {
const vid = this.newMediaNode(index, imf);
if (["curr", "prev", "next"].includes(key)) {
this.elements[key][eleIndex] = vid;
}
img.replaceWith(vid);
img.remove();
return;
}
img.setAttribute("src", imf.blobUrl);
});
new AutoPage(this, HTML.autoPageBTN);
}
initHammer() {
this.hammer = new Hammer(this.frame, {
// touchAction: "auto",
recognizers: [
[Hammer.Swipe, { direction: Hammer.DIRECTION_ALL, enable: false }]
]
});
this.hammer.on("swipe", (ev) => {
ev.preventDefault();
if (conf.readMode === "pagination") {
switch (ev.direction) {
case Hammer.DIRECTION_LEFT:
this.stepNext(conf.reversePages ? "prev" : "next");
break;
case Hammer.DIRECTION_UP:
this.stepNext("next");
break;
case Hammer.DIRECTION_RIGHT:
this.stepNext(conf.reversePages ? "next" : "prev");
break;
case Hammer.DIRECTION_DOWN:
this.stepNext("prev");
break;
}
}
});
}
resetStickyMouse() {
this.lastMouse = void 0;
}
flushImgScaleBar() {
q("#img-scale-status", this.imgScaleBar).innerHTML = `${conf.imgScale}%`;
q("#img-scale-progress-inner", this.imgScaleBar).style.width = `${conf.imgScale}%`;
}
initFrame() {
this.frame.addEventListener("wheel", (event) => this.onWheel(event, true));
this.frame.addEventListener("click", (event) => this.hidden(event));
this.frame.addEventListener("contextmenu", (event) => event.preventDefault());
const debouncer = new Debouncer("throttle");
this.frame.addEventListener("mousemove", (event) => {
debouncer.addEvent("BIG-IMG-MOUSE-MOVE", () => {
if (this.lastMouse)
this.stickyMouse(event, this.lastMouse);
this.lastMouse = { x: event.clientX, y: event.clientY };
}, 5);
});
}
initImgScaleBar() {
q("#img-increase-btn", this.imgScaleBar).addEventListener("click", () => this.scaleBigImages(1, 5));
q("#img-decrease-btn", this.imgScaleBar).addEventListener("click", () => this.scaleBigImages(-1, 5));
q("#img-scale-reset-btn", this.imgScaleBar).addEventListener("click", () => this.resetScaleBigImages());
const progress = q("#img-scale-progress", this.imgScaleBar);
onMouse(progress, (percent) => this.scaleBigImages(0, 0, percent));
}
hidden(event) {
if (event && event.target && event.target.tagName === "SPAN")
return;
this.visible = false;
EBUS.emit("bifm-on-hidden");
this.html.fullViewGrid.focus();
this.frameScrollAbort?.abort();
this.frame.classList.add("big-img-frame-collapse");
this.debouncer.addEvent("TOGGLE-CHILDREN", () => this.resetElements(), 200);
}
show(imf) {
this.visible = true;
this.frame.classList.remove("big-img-frame-collapse");
this.frame.focus();
this.frameScrollAbort = new AbortController();
this.frame.addEventListener("scroll", () => this.onScroll(), { signal: this.frameScrollAbort.signal });
this.debouncer.addEvent("TOGGLE-CHILDREN-D", () => imf.chapterIndex === this.chapterIndex && this.setNow(imf), 100);
EBUS.emit("bifm-on-show");
}
setNow(imf, oriented) {
if (this.visible) {
this.resetStickyMouse();
this.initElements(imf, oriented);
} else {
const queue = this.getChapter(this.chapterIndex).queue;
const index = queue.indexOf(imf);
if (index === -1)
return;
EBUS.emit("ifq-do", index, imf, oriented || "next");
}
}
initElements(imf, oriented = "next") {
this.resetPreventStep();
const queue = this.getChapter(this.chapterIndex).queue;
const index = queue.indexOf(imf);
if (index === -1)
return;
if (conf.readMode === "continuous") {
this.resetElements();
this.elements.curr[0] = this.newMediaNode(index, imf);
this.frame.appendChild(this.elements.curr[0]);
this.tryExtend();
this.hammer?.get("swipe").set({ enable: false });
} else {
this.balanceElements(index, queue, oriented);
this.placeElements();
this.checkFrameOverflow();
this.hammer?.get("swipe").set({ enable: true });
}
EBUS.emit("ifq-do", index, imf, oriented);
this.elements.curr[0]?.scrollIntoView();
}
placeElements() {
this.removeMediaNode();
this.elements.curr.forEach((element) => this.frame.appendChild(element));
this.elements.prev.forEach((element) => this.fragment.appendChild(element));
this.elements.next.forEach((element) => this.fragment.appendChild(element));
const vid = this.elements.curr[0];
if (vid && vid instanceof HTMLVideoElement) {
if (vid.paused)
this.tryPlayVideo(vid);
}
}
balanceElements(index, queue, oriented) {
const indices = { prev: [], curr: [], next: [] };
for (let i = 0; i < conf.paginationIMGCount; i++) {
const prevIndex = i + index - conf.paginationIMGCount;
const currIndex = i + index;
const nextIndex = i + index + conf.paginationIMGCount;
if (prevIndex > -1)
indices.prev.push(prevIndex);
if (currIndex > -1 && currIndex < queue.length)
indices.curr.push(currIndex);
if (nextIndex < queue.length)
indices.next.push(nextIndex);
}
console.log("balanceElements", indices);
if (oriented === "next") {
this.elements.prev = this.elements.curr;
this.elements.curr = this.elements.next;
this.elements.next = [];
} else {
this.elements.next = this.elements.curr;
this.elements.curr = this.elements.prev;
this.elements.prev = [];
}
Object.entries(indices).forEach(([k, indexRange]) => {
const elements = this.elements[k];
if (elements.length > indexRange.length) {
elements.splice(indexRange.length, elements.length - indexRange.length).forEach((ele) => ele.remove());
}
for (let j = 0; j < indexRange.length; j++) {
if (indexRange[j] === parseIndex(elements[j]))
continue;
if (elements[j])
elements[j].remove();
elements[j] = this.newMediaNode(indexRange[j], queue[indexRange[j]]);
}
});
}
resetElements() {
this.elements = { prev: [], curr: [], next: [] };
this.fragment.childNodes.forEach((child) => child.remove());
this.removeMediaNode();
}
removeMediaNode() {
this.vidController?.detach();
this.vidController?.hidden();
this.getMediaNodes().forEach((ele) => {
if (ele instanceof HTMLVideoElement) {
ele.pause();
}
ele.remove();
});
}
getMediaNodes() {
const list = Array.from(this.frame.querySelectorAll("img, video"));
let last = 0;
for (const ele of list) {
const index = parseIndex(ele);
if (index < last) {
throw new Error("BIFM: getMediaNodes: list is not ordered by d-index");
}
last = index;
}
return list;
}
stepNext(oriented, current) {
let index = current !== void 0 ? current : this.elements.curr[0] ? parseInt(this.elements.curr[0].getAttribute("d-index")) : void 0;
if (index === void 0 || isNaN(index))
return;
const queue = this.getChapter(this.chapterIndex)?.queue;
if (!queue || queue.length === 0)
return;
index = oriented === "next" ? index + conf.paginationIMGCount : index - conf.paginationIMGCount;
if (index < -conf.paginationIMGCount)
index = queue.length - 1;
if (!queue[index])
return;
this.setNow(queue[index], oriented);
}
// isMouse: onWheel triggered by mousewheel, if not, means by keyboard control
onWheel(event, isMouse, preventCallback) {
if (!preventCallback)
this.callbackOnWheel?.(event);
if (event.buttons === 2) {
event.preventDefault();
this.scaleBigImages(event.deltaY > 0 ? -1 : 1, 5);
return;
}
if (conf.readMode === "continuous")
return;
const oriented = event.deltaY > 0 ? "next" : "prev";
if (conf.stickyMouse === "disable") {
if (!this.isReachedBoundary(oriented))
return;
if (isMouse && this.tryPreventStep())
return;
}
event.preventDefault();
this.stepNext(oriented);
}
onScroll() {
if (conf.readMode === "continuous") {
this.consecutive();
}
}
resetPreventStep(fin) {
this.preventStep.ani?.cancel();
this.preventStep.ele?.remove();
this.preventStep = { fin: fin ?? false };
}
// prevent scroll to next page while mouse scrolling;
tryPreventStep() {
if (!conf.imgScale || conf.imgScale === 0 || conf.preventScrollPageTime === 0) {
return false;
}
if (this.preventStep.fin) {
this.resetPreventStep();
return false;
} else {
if (!this.preventStep.ele) {
const lockEle = document.createElement("div");
lockEle.style.width = "100vw";
lockEle.style.position = "fixed";
lockEle.style.display = "flex";
lockEle.style.justifyContent = "center";
lockEle.style.bottom = "0px";
lockEle.innerHTML = `