Image Viewer

Allows viewing full image without leaving the page

当前为 2022-05-02 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Image Viewer
  3. // @description Allows viewing full image without leaving the page
  4. // @namespace https://github.com/nikolay-borzov
  5. // @version 1.1.9
  6. // @author nikolay-borzov
  7. // @license MIT
  8. // @icon https://raw.githubusercontent.com/nikolay-borzov/user-scripts/master/image-viewer/icon.png
  9. // @homepageURL https://github.com/nikolay-borzov/user-scripts
  10. // @homepage https://github.com/nikolay-borzov/user-scripts
  11. // @supportURL https://github.com/nikolay-borzov/user-scripts/issues
  12. // @include *
  13. // @connect www.imagebam.com
  14. // @connect imagevenue.com
  15. // @connect www.turboimagehost.com
  16. // @connect fastpic.ru
  17. // @connect radikal.ru
  18. // @run-at document-start
  19. // @grant GM_addStyle
  20. // @grant GM_xmlhttpRequest
  21. // @grant GM.xmlHttpRequest
  22. // @grant GM_setValue
  23. // @grant GM.setValue
  24. // @grant GM_getValue
  25. // @grant GM.getValue
  26. // @grant GM_registerMenuCommand
  27. // ==/UserScript==
  28.  
  29. ;(function () {
  30. 'use strict'
  31.  
  32. /* global Bliss */
  33. // eslint-disable-next-line
  34. !(function(){function t(e,n,i){return n=void 0===n?1:n,i=i||n+1,i-n<=1?function(){if(arguments.length<=n||"string"===r.type(arguments[n]))return e.apply(this,arguments);var t,i=arguments[n];for(var o in i){var s=Array.prototype.slice.call(arguments);s.splice(n,1,o,i[o]),t=e.apply(this,s);}return t}:t(t(e,n+1,i),n,i-1)}function e(t,r,i){var o=n(i);if("string"===o){var s=Object.getOwnPropertyDescriptor(r,i);!s||s.writable&&s.configurable&&s.enumerable&&!s.get&&!s.set?t[i]=r[i]:(delete t[i],Object.defineProperty(t,i,s));}else if("array"===o)i.forEach(function(n){n in r&&e(t,r,n);});else for(var a in r)i&&("regexp"===o&&!i.test(a)||"function"===o&&!i.call(r,a))||e(t,r,a);return t}function n(t){if(null===t)return "null";if(void 0===t)return "undefined";var e=(Object.prototype.toString.call(t).match(/^\[object\s+(.*?)\]$/)[1]||"").toLowerCase();return "number"==e&&isNaN(t)?"nan":e}var r=self.Bliss=e(function(t,e){return 2==arguments.length&&!e||!t?null:"string"===r.type(t)?(e||document).querySelector(t):t||null},self.Bliss);e(r,{extend:e,overload:t,type:n,property:r.property||"_",listeners:self.WeakMap?new WeakMap:new Map,original:{addEventListener:(self.EventTarget||Node).prototype.addEventListener,removeEventListener:(self.EventTarget||Node).prototype.removeEventListener},sources:{},noop:function(){},$:function(t,e){return t instanceof Node||t instanceof Window?[t]:2!=arguments.length||e?Array.prototype.slice.call("string"==typeof t?(e||document).querySelectorAll(t):t||[]):[]},defined:function(){for(var t=0;t<arguments.length;t++)if(void 0!==arguments[t])return arguments[t]},create:function(t,e){return t instanceof Node?r.set(t,e):(1===arguments.length&&("string"===r.type(t)?e={}:(e=t,t=e.tag,e=r.extend({},e,function(t){return "tag"!==t}))),r.set(document.createElement(t||"div"),e))},each:function(t,e,n){n=n||{};for(var r in t)n[r]=e.call(t,r,t[r]);return n},ready:function(t,e,n){if("function"!=typeof t||e||(e=t,t=void 0),t=t||document,e&&("loading"!==t.readyState?e():r.once(t,"DOMContentLoaded",function(){e();})),!n)return new Promise(function(e){r.ready(t,e,!0);})},Class:function(t){var e,n=["constructor","extends","abstract","static"].concat(Object.keys(r.classProps)),i=t.hasOwnProperty("constructor")?t.constructor:r.noop;2==arguments.length?(e=arguments[0],t=arguments[1]):(e=function(){if(this.constructor.__abstract&&this.constructor===e)throw new Error("Abstract classes cannot be directly instantiated.");e["super"]&&e["super"].apply(this,arguments),i.apply(this,arguments);},e["super"]=t["extends"]||null,e.prototype=r.extend(Object.create(e["super"]?e["super"].prototype:Object),{constructor:e}),e.prototype["super"]=e["super"]?e["super"].prototype:null,e.__abstract=!!t["abstract"]);var o=function(t){return this.hasOwnProperty(t)&&n.indexOf(t)===-1};if(t["static"]){r.extend(e,t["static"],o);for(var s in r.classProps)s in t["static"]&&r.classProps[s](e,t["static"][s]);}r.extend(e.prototype,t,o);for(var s in r.classProps)s in t&&r.classProps[s](e.prototype,t[s]);return e},classProps:{lazy:t(function(t,e,n){return Object.defineProperty(t,e,{get:function(){var t=n.call(this);return Object.defineProperty(this,e,{value:t,configurable:!0,enumerable:!0,writable:!0}),t},set:function(t){Object.defineProperty(this,e,{value:t,configurable:!0,enumerable:!0,writable:!0});},configurable:!0,enumerable:!0}),t}),live:t(function(t,e,n){return "function"===r.type(n)&&(n={set:n}),Object.defineProperty(t,e,{get:function(){var t=this["_"+e],r=n.get&&n.get.call(this,t);return void 0!==r?r:t},set:function(t){var r=this["_"+e],i=n.set&&n.set.call(this,t,r);this["_"+e]=void 0!==i?i:t;},configurable:n.configurable,enumerable:n.enumerable}),t})},include:function(){var t=arguments[arguments.length-1],e=2===arguments.length&&arguments[0],n=document.createElement("script");return e?Promise.resolve():new Promise(function(e,i){r.set(n,{async:!0,onload:function(){e(),n.parentNode&&n.parentNode.removeChild(n);},onerror:function(){i();},src:t,inside:document.head});})},fetch:function(t,n){if(!t)throw new TypeError("URL parameter is mandatory and cannot be "+t);var i=e({url:new URL(t,location),data:"",method:"GET",headers:{},xhr:new XMLHttpRequest},n);i.method=i.method.toUpperCase(),r.hooks.run("fetch-args",i),"GET"===i.method&&i.data&&(i.url.search+=i.data),document.body.setAttribute("data-loading",i.url),i.xhr.open(i.method,i.url.href,i.async!==!1,i.user,i.password);for(var o in n)if("upload"===o)i.xhr.upload&&"object"==typeof n[o]&&r.extend(i.xhr.upload,n[o]);else if(o in i.xhr)try{i.xhr[o]=n[o];}catch(s){self.console&&console.error(s);}var a=Object.keys(i.headers).map(function(t){return t.toLowerCase()});"GET"!==i.method&&a.indexOf("content-type")===-1&&i.xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");for(var c in i.headers)void 0!==i.headers[c]&&i.xhr.setRequestHeader(c,i.headers[c]);var u=new Promise(function(t,e){i.xhr.onload=function(){document.body.removeAttribute("data-loading"),0===i.xhr.status||i.xhr.status>=200&&i.xhr.status<300||304===i.xhr.status?t(i.xhr):e(r.extend(Error(i.xhr.statusText),{xhr:i.xhr,get status(){return this.xhr.status}}));},i.xhr.onerror=function(){document.body.removeAttribute("data-loading"),e(r.extend(Error("Network Error"),{xhr:i.xhr}));},i.xhr.ontimeout=function(){document.body.removeAttribute("data-loading"),e(r.extend(Error("Network Timeout"),{xhr:i.xhr}));},i.xhr.send("GET"===i.method?null:i.data);});return u.xhr=i.xhr,u},value:function(t){var e="string"!==r.type(t);return r.$(arguments).slice(+e).reduce(function(t,e){return t&&t[e]},e?t:self)}}),r.Hooks=new r.Class({add:function(t,e,n){if("string"==typeof arguments[0])(Array.isArray(t)?t:[t]).forEach(function(t){this[t]=this[t]||[],e&&this[t][n?"unshift":"push"](e);},this);else for(var t in arguments[0])this.add(t,arguments[0][t],arguments[1]);},run:function(t,e){this[t]=this[t]||[],this[t].forEach(function(t){t.call(e&&e.context?e.context:e,e);});}}),r.hooks=new r.Hooks;r.property;r.Element=function(t){this.subject=t,this.data={},this.bliss={};},r.Element.prototype={set:t(function(t,e){t in r.setProps?r.setProps[t].call(this,e):t in this?this[t]=e:this.setAttribute(t,e);},0),transition:function(t,e){return e=+e||400,new Promise(function(n,i){if("transition"in this.style){var o=r.extend({},this.style,/^transition(Duration|Property)$/);r.style(this,{transitionDuration:(e||400)+"ms",transitionProperty:Object.keys(t).join(", ")}),r.once(this,"transitionend",function(){clearTimeout(s),r.style(this,o),n(this);});var s=setTimeout(n,e+50,this);r.style(this,t);}else r.style(this,t),n(this);}.bind(this))},fire:function(t,e){var n=document.createEvent("HTMLEvents");return n.initEvent(t,!0,!0),this.dispatchEvent(r.extend(n,e))},bind:t(function(t,e){if(arguments.length>1&&("function"===r.type(e)||e.handleEvent)){var n=e;e="object"===r.type(arguments[2])?arguments[2]:{capture:!!arguments[2]},e.callback=n;}var i=r.listeners.get(this)||{};t.trim().split(/\s+/).forEach(function(t){if(t.indexOf(".")>-1){t=t.split(".");var n=t[1];t=t[0];}i[t]=i[t]||[],0===i[t].filter(function(t){return t.callback===e.callback&&t.capture==e.capture}).length&&i[t].push(r.extend({className:n},e)),r.original.addEventListener.call(this,t,e.callback,e);},this),r.listeners.set(this,i);},0),unbind:t(function(t,e){if(e&&("function"===r.type(e)||e.handleEvent)){var n=e;e=arguments[2];}"boolean"==r.type(e)&&(e={capture:e}),e=e||{},e.callback=e.callback||n;var i=r.listeners.get(this);(t||"").trim().split(/\s+/).forEach(function(t){if(t.indexOf(".")>-1){t=t.split(".");var n=t[1];t=t[0];}if(t&&e.callback)return r.original.removeEventListener.call(this,t,e.callback,e.capture);if(i)for(var o in i)if(!t||o===t)for(var s,a=0;s=i[o][a];a++)n&&n!==s.className||e.callback&&e.callback!==s.callback||!!e.capture!=!!s.capture||(i[o].splice(a,1),r.original.removeEventListener.call(this,o,s.callback,s.capture),a--);},this);},0)},r.setProps={style:function(t){for(var e in t)e in this.style?this.style[e]=t[e]:this.style.setProperty(e,t[e]);},attributes:function(t){for(var e in t)this.setAttribute(e,t[e]);},properties:function(t){r.extend(this,t);},events:function(t){if(1!=arguments.length||!t||!t.addEventListener)return r.bind.apply(this,[this].concat(r.$(arguments)));var e=this;if(r.listeners){var n=r.listeners.get(t);for(var i in n)n[i].forEach(function(t){r.bind(e,i,t.callback,t.capture);});}for(var o in t)0===o.indexOf("on")&&(this[o]=t[o]);},once:t(function(t,e){var n=this,i=function(){return r.unbind(n,t,i),e.apply(n,arguments)};r.bind(this,t,i,{once:!0});},0),delegate:t(function(t,e,n){r.bind(this,t,function(t){t.target.closest(e)&&n.call(this,t);});},0,2),contents:function(t){(t||0===t)&&(Array.isArray(t)?t:[t]).forEach(function(t){var e=r.type(t);/^(string|number)$/.test(e)?t=document.createTextNode(t+""):"object"===e&&(t=r.create(t)),t instanceof Node&&this.appendChild(t);},this);},inside:function(t){t&&t.appendChild(this);},before:function(t){t&&t.parentNode.insertBefore(this,t);},after:function(t){t&&t.parentNode.insertBefore(this,t.nextSibling);},start:function(t){t&&t.insertBefore(this,t.firstChild);},around:function(t){t&&t.parentNode&&r.before(this,t),this.appendChild(t);}},r.Array=function(t){this.subject=t;},r.Array.prototype={all:function(t){var e=r.$(arguments).slice(1);return this[t].apply(this,e)}},r.add=t(function(t,e,n,i){n=r.extend({$:!0,element:!0,array:!0},n),"function"==r.type(e)&&(!n.element||t in r.Element.prototype&&i||(r.Element.prototype[t]=function(){return this.subject&&r.defined(e.apply(this.subject,arguments),this.subject)}),!n.array||t in r.Array.prototype&&i||(r.Array.prototype[t]=function(){var t=arguments;return this.subject.map(function(n){return n&&r.defined(e.apply(n,t),n)})}),n.$&&(r.sources[t]=r[t]=e,(n.array||n.element)&&(r[t]=function(){var e=[].slice.apply(arguments),i=e.shift(),o=n.array&&Array.isArray(i)?"Array":"Element";return r[o].prototype[t].apply({subject:i},e)})));},0),r.add(r.Array.prototype,{element:!1}),r.add(r.Element.prototype),r.add(r.setProps),r.add(r.classProps,{element:!1,array:!1});var i=document.createElement("_");r.add(r.extend({},HTMLElement.prototype,function(t){return "function"===r.type(i[t])}),null,!0);}());
  35.  
  36. // eslint-disable-next-line
  37. const $ = Bliss;
  38. // eslint-disable-next-line
  39. const $$ = Bliss.$;
  40.  
  41. function hasOwnProperty(object, property) {
  42. return Object.prototype.hasOwnProperty.call(object, property)
  43. }
  44.  
  45. function getGMPolyfillMethod(methodName) {
  46. const GM_METHOD_MAP = {
  47. getValue: 'GM_getValue',
  48. setValue: 'GM_setValue',
  49. openInTab: 'GM_openInTab',
  50. }
  51.  
  52. if (hasOwnProperty(GM_METHOD_MAP, methodName)) {
  53. return GM !== undefined && methodName in GM
  54. ? GM[methodName]
  55. : function (...arguments_) {
  56. return new Promise((resolve, reject) => {
  57. try {
  58. resolve(window[GM_METHOD_MAP[methodName]](...arguments_))
  59. } catch (error) {
  60. reject(error)
  61. }
  62. })
  63. }
  64. }
  65. }
  66.  
  67. const addStyle =
  68. 'GM_addStyle' in window
  69. ? GM_addStyle // eslint-disable-line camelcase
  70. : (css) => {
  71. const head = document.querySelectorAll('head')[0]
  72.  
  73. if (head) {
  74. const style = document.createElement('style')
  75.  
  76. style.innerHTML = css
  77. head.append(style)
  78.  
  79. return css
  80. }
  81. }
  82.  
  83. let request$1
  84.  
  85. function getRequest() {
  86. if (!request$1) {
  87. const xmlHttpRequest =
  88. GM !== undefined && 'xmlHttpRequest' in GM
  89. ? GM.xmlHttpRequest
  90. : GM_xmlhttpRequest // eslint-disable-line camelcase
  91.  
  92. request$1 = function (url, { method = 'GET' } = {}) {
  93. return new Promise((resolve, reject) => {
  94. xmlHttpRequest({
  95. url,
  96. method,
  97. onload: resolve,
  98. onerror: reject,
  99. })
  100. })
  101. }
  102. }
  103.  
  104. return request$1
  105. }
  106.  
  107. let store$1
  108.  
  109. const getStore = () => {
  110. if (!store$1) {
  111. store$1 = {
  112. get: getGMPolyfillMethod('getValue'),
  113. set: getGMPolyfillMethod('setValue'),
  114. }
  115. }
  116.  
  117. return store$1
  118. }
  119.  
  120. const request = getRequest()
  121.  
  122. async function getURLFromPage(link, extractor) {
  123. const html = await getPageHtml(link.url)
  124.  
  125. const match = extractor.imageURLRegExp?.exec(html)
  126.  
  127. let url
  128.  
  129. if (match) {
  130. url = match.groups ? match.groups.url : match[1]
  131. }
  132.  
  133. if (!url) {
  134. console.warn(`[image-viewer] Unable to get URL from page ${link.url}`)
  135. }
  136.  
  137. return url
  138. }
  139.  
  140. async function getPageHtml(pageURL) {
  141. const response = await request(pageURL)
  142.  
  143. return response.responseText
  144. }
  145.  
  146. const fastpic = {
  147. name: 'FastPic',
  148. linkRegExp: /^http.?:\/\/fastpic\.ru\/view/,
  149.  
  150. imageURLRegExp: /src="(?<url>[^"]+)" class="image img-fluid"/,
  151. getURL: getURLFromPage,
  152. }
  153.  
  154. const URL_PARTS_REGEXP = /i(\d+).+big(\/\d+\/\d+\/).+\/([^/]+)$/
  155.  
  156. const fastpicDirect = {
  157. name: 'FastPic (direct link)',
  158. linkRegExp: /fastpic\.ru\/big/,
  159.  
  160. async getURL(link) {
  161. let hostLink = link.url
  162.  
  163. if (hostLink.includes('?')) {
  164. const urlObject = new URL(hostLink)
  165. const parameters = new URLSearchParams(urlObject.search)
  166.  
  167. for (const parameter of parameters.values()) {
  168. if (fastpicDirect.linkRegExp.test(parameter)) {
  169. hostLink = parameter
  170. break
  171. }
  172. }
  173. }
  174.  
  175. const [, index, date, filename] = URL_PARTS_REGEXP.exec(hostLink)
  176.  
  177. const url = `https://fastpic.ru/view/${index}${date}${filename}.html`
  178.  
  179. return fastpic.getURL({ ...link, url }, fastpic)
  180. },
  181. }
  182.  
  183. const imagebam = {
  184. name: 'ImageBam',
  185. linkRegExp: /^http:\/\/www\.imagebam\.com\/image/,
  186. imageURLRegExp: /property="og:image" content="([^"]*)"/,
  187. getURL: getURLFromPage,
  188. }
  189.  
  190. const DATE_PATTERN = /(\d{4})\.(\d{2})\.(\d{2})/
  191.  
  192. const imageban = {
  193. name: 'ImageBan.ru',
  194. linkRegExp: /\/\/imageban\.ru\/show/,
  195.  
  196. async getURL(link) {
  197. return link.thumbnailURL
  198. .replace('thumbs', 'out')
  199. .replace(DATE_PATTERN, '$1/$2/$3')
  200. },
  201. }
  202.  
  203. const imagebanDirect = {
  204. name: 'ImageBan.ru (direct link)',
  205. linkRegExp: /imageban\.ru\/out/,
  206.  
  207. async getURL(link) {
  208. return link.url
  209. },
  210. }
  211.  
  212. const imagetwist = {
  213. name: 'ImageTwist',
  214. linkRegExp: /imagetwist\.com/,
  215.  
  216. async getURL(link) {
  217. const imageName = link.url.split('/').pop()?.replace('.html', '')
  218. const extension = imageName?.split('.').pop()
  219. const imageUrl = link.thumbnailURL
  220. .replace('/th/', '/i/')
  221. .slice(0, -(extension?.length ?? 0))
  222.  
  223. return `${imageUrl}${extension}/${imageName}`
  224. },
  225. }
  226.  
  227. const HOST_REPLACE_REG_EXP = /(picturelol|picshick|imageshimage)/
  228.  
  229. const imagetwistBased = {
  230. name: 'ImageTwist based (legacy)',
  231. hosts: ['Picturelol.com', 'PicShick.com', 'Imageshimage.com'],
  232. linkRegExp: /^https?:\/\/(picturelol|picshick|imageshimage)\.com/,
  233.  
  234. async getURL(link) {
  235. const imageName = link.url.split('/').pop()
  236. const imageUrl = link.thumbnailURL
  237. .replace('/th/', '/i/')
  238. .replace(HOST_REPLACE_REG_EXP, 'imagetwist')
  239.  
  240. return `${imageUrl}/${imageName}`
  241. },
  242. }
  243.  
  244. const imagevenueLegacy = {
  245. name: 'ImageVenue.com',
  246.  
  247. linkRegExp: /(imagevenue.com\/img.php|www.imagevenue.com\/\\w+$)/,
  248. imageURLRegExp: /data-toggle="full">\W*<img src="(?<url>[^"]*)/im,
  249.  
  250. getURL: getURLFromPage,
  251. }
  252.  
  253. const imgadult = {
  254. name: 'ImgAdult.com',
  255. linkRegExp: /^https:\/\/imgadult\.com/,
  256.  
  257. async getURL(link) {
  258. return link.thumbnailURL.replace('/small/', '/big/')
  259. },
  260. }
  261.  
  262. const imgbb = {
  263. name: 'imgbb.com',
  264. linkRegExp: /^https:\/\/ibb\.co/,
  265.  
  266. async getURL(link) {
  267. return link.thumbnailURL.replace('//thumb', '//image')
  268. },
  269. }
  270.  
  271. const imgbox = {
  272. name: 'imgbox.com',
  273. linkRegExp: /^http:\/\/imgbox\.com/,
  274.  
  275. async getURL(link) {
  276. return link.thumbnailURL.replace('/thumbs', '/images').replace('_t', '_o')
  277. },
  278. }
  279.  
  280. const imgbum = {
  281. name: 'imgbum.net',
  282. linkRegExp: /^http:\/\/imgbum\.net/,
  283.  
  284. async getURL(link) {
  285. return link.thumbnailURL.replace('-thumb', '')
  286. },
  287. }
  288.  
  289. const imgchilibum = {
  290. name: 'imgchilibum.ru',
  291. linkRegExp: /^http:\/\/imgchilibum\.ru\/v/,
  292.  
  293. async getURL(link) {
  294. return link.thumbnailURL.replace('_s/', '_b/')
  295. },
  296. }
  297.  
  298. const imgdrive = {
  299. name: 'ImgDrive.net',
  300. linkRegExp: /^https:\/\/imgdrive\.net/,
  301.  
  302. async getURL(link) {
  303. return link.thumbnailURL.replace('small', 'big')
  304. },
  305. }
  306.  
  307. const imgtaxi = {
  308. name: 'imgtaxi.com',
  309. linkRegExp: /^https:\/\/imgtaxi\.com/,
  310.  
  311. async getURL(link) {
  312. return link.thumbnailURL
  313. .replace('/small/', '/big/')
  314. .replace('/small-medium/', '/big/')
  315. },
  316. }
  317.  
  318. const imx = {
  319. name: 'IMX.to',
  320. linkRegExp: /^https:\/\/imx\.to/,
  321.  
  322. async getURL(link) {
  323. return link.thumbnailURL.replace('/imx', '/i.imx').replace('/u/t/', '/i/')
  324. },
  325. }
  326.  
  327. const lostpic = {
  328. name: 'Lostpic.net',
  329. linkRegExp: /^http:\/\/lostpic\.net/,
  330.  
  331. async getURL(link) {
  332. return link.thumbnailURL.replace('.th', '').replace('http:', 'https:')
  333. },
  334. }
  335.  
  336. const moneyPic = {
  337. name: 'money-pic.ru',
  338. linkRegExp: /^http:\/\/money-pic\.ru/,
  339.  
  340. async getURL(link) {
  341. return link.thumbnailURL.replace('-thumb', '')
  342. },
  343. }
  344.  
  345. const nikapic = {
  346. name: 'nikapic.ru',
  347. linkRegExp: /^http:\/\/nikapic\.ru/,
  348.  
  349. async getURL(link) {
  350. return link.thumbnailURL.replace('/small/', '/big/')
  351. },
  352. }
  353.  
  354. const picage = {
  355. name: 'picage.ru',
  356. linkRegExp: /^http:\/\/picage\.ru/,
  357.  
  358. async getURL(link) {
  359. return link.thumbnailURL
  360. .replace('picage', 'pic4you')
  361. .replace('-thumb', '')
  362. },
  363. }
  364.  
  365. const piccash = {
  366. name: 'PicCash.net',
  367. linkRegExp: /^http:\/\/piccash\.net\//,
  368.  
  369. async getURL(link) {
  370. return link.thumbnailURL.replace('_thumb', '_full').replace('-thumb', '')
  371. },
  372. }
  373.  
  374. const HOST_REPLACE_REG_EX$1 =
  375. /(freescreens\.ru|imgclick\.ru|picclick\.ru|payforpic\.ru|picforall\.ru)/
  376.  
  377. const picforall = {
  378. name: 'PicForAll.ru',
  379. hosts: [
  380. 'freescreens.ru',
  381. 'imgclick.ru',
  382. 'picclick.ru',
  383. 'payforpic.ru',
  384. 'picforall.ru',
  385. ],
  386. linkRegExp:
  387. /^http:\/\/(freescreens\.ru|imgclick\.ru|picclick\.ru|payforpic\.ru|picforall\.ru)/,
  388.  
  389. async getURL(link) {
  390. return link.thumbnailURL
  391. .replace(HOST_REPLACE_REG_EX$1, 'picpic.online')
  392. .replace('-thumb', '')
  393. },
  394. }
  395.  
  396. const HOST_REPLACE_REG_EX =
  397. /(iceimg\.net|pixsense\.net|vestimage\.site|chaosimg\.site)/
  398.  
  399. const pixsense = {
  400. name: 'PixSense',
  401. hosts: [
  402. 'www.iceimg.net',
  403. 'www.pixsense.net',
  404. 'www.vestimage.site',
  405. 'www.chaosimg.site',
  406. ],
  407. linkRegExp:
  408. /^http:\/\/www\.(iceimg\.net|pixsense\.net|vestimage\.site|chaosimg\.site)/,
  409.  
  410. async getURL(link) {
  411. return link.thumbnailURL
  412. .replace(HOST_REPLACE_REG_EX, 'fortstore.net')
  413. .replace('small-', '')
  414. .replace('/small/', '/big/')
  415. },
  416. }
  417.  
  418. const radikal = {
  419. name: 'Radikal.ru',
  420. linkRegExp: /https?:\/\/.\.radikal\.ru\//,
  421.  
  422. async getURL(link) {
  423. return link.url
  424. },
  425. }
  426.  
  427. const radikalLegacy = {
  428. name: 'Radikal.ru (legacy)',
  429. linkRegExp: /^http:\/\/radikal\.ru\//,
  430. imageURLRegExp: /id="imgFullSize" src="(?<url>[^"]+)"/,
  431. getURL: getURLFromPage,
  432. }
  433.  
  434. const stuffed = {
  435. name: 'stuffed.ru',
  436. linkRegExp: /^http:\/\/stuffed\.ru/,
  437.  
  438. async getURL(link) {
  439. return link.thumbnailURL.replace('-thumb', '')
  440. },
  441. }
  442.  
  443. const turboimagehost = {
  444. name: 'TurboImageHost',
  445. linkRegExp: /^https:\/\/www\.turboimagehost\.com\/p/,
  446. imageURLRegExp: /property="og:image" content="([^"]*)"/,
  447. getURL: getURLFromPage,
  448. }
  449.  
  450. const vfl = {
  451. name: 'VFL.ru',
  452. linkRegExp: /^http:\/\/vfl\.ru/,
  453.  
  454. async getURL(link) {
  455. return link.thumbnailURL.replace('_s', '')
  456. },
  457. }
  458.  
  459. const xxxscreens = {
  460. name: 'XXXScreens.com',
  461. linkRegExp: /^http:\/\/xxxscreens\.com/,
  462.  
  463. async getURL(link) {
  464. return link.thumbnailURL.replace('small/', 'big/')
  465. },
  466. }
  467.  
  468. const hostExtractors = /* #__PURE__ */ Object.freeze({
  469. __proto__: null,
  470. fastpic,
  471. fastpicDirect,
  472. imagebam,
  473. imageban,
  474. imagebanDirect,
  475. imagetwist,
  476. imagetwistBased,
  477. imagevenueLegacy,
  478. imgadult,
  479. imgbb,
  480. imgbox,
  481. imgbum,
  482. imgchilibum,
  483. imgdrive,
  484. imgtaxi,
  485. imx,
  486. lostpic,
  487. moneyPic,
  488. nikapic,
  489. picage,
  490. piccash,
  491. picforall,
  492. pixsense,
  493. radikal,
  494. radikalLegacy,
  495. stuffed,
  496. turboimagehost,
  497. vfl,
  498. xxxscreens,
  499. })
  500.  
  501. let extractorsActive = []
  502.  
  503. const extractors = Object.values(hostExtractors).filter(Boolean)
  504.  
  505. const extractorsByName = extractors.reduce((result, extractor) => {
  506. result[extractor.name] = extractor
  507.  
  508. return result
  509. }, {})
  510.  
  511. const urlExtractor = {
  512. getImageHostsMetadata() {
  513. const result = extractors.map(({ name, hosts }) => ({
  514. name,
  515. description: hosts ? hosts.join(', ') : '',
  516. }))
  517.  
  518. return sortCaseInsensitive(result, ({ name }) => name)
  519. },
  520.  
  521. getImageURL(link) {
  522. const extractor = extractorsByName[link.host]
  523.  
  524. return extractor.getURL(link, extractor)
  525. },
  526.  
  527. getHostNameMatcher(enabledHosts) {
  528. extractorsActive = extractors.filter((extractor) =>
  529. enabledHosts.includes(extractor.name)
  530. )
  531.  
  532. let previousExtractor
  533.  
  534. return (url) => {
  535. if (previousExtractor && previousExtractor.linkRegExp.test(url)) {
  536. return previousExtractor.name
  537. }
  538.  
  539. const extractor = extractorsActive.find((extractor) =>
  540. extractor.linkRegExp.test(url)
  541. )
  542.  
  543. if (extractor) {
  544. previousExtractor = extractor
  545.  
  546. return extractor.name
  547. }
  548. }
  549. },
  550. }
  551.  
  552. function sortCaseInsensitive(items, getValue) {
  553. return items
  554. .map((value, index) => ({ index, value: getValue(value).toLowerCase() }))
  555. .sort((a, b) => {
  556. if (a.value > b.value) {
  557. return 1
  558. }
  559. if (a.value < b.value) {
  560. return -1
  561. }
  562.  
  563. return 0
  564. })
  565. .map((m) => items[m.index])
  566. }
  567.  
  568. const store = getStore()
  569.  
  570. const CLASSES$1 = {
  571. open: 'iv-config-form--open',
  572. }
  573.  
  574. let configMenu
  575. const currentHost = unsafeWindow.location.host
  576.  
  577. async function initHostConfig() {
  578. const config = await getHostConfig()
  579.  
  580. const handler = () => showMenu(config)
  581.  
  582. // eslint-disable-next-line camelcase
  583. if (typeof GM_registerMenuCommand !== 'undefined') {
  584. GM_registerMenuCommand('Image Viewer Settings', handler)
  585. } else {
  586. unsafeWindow.imageViewer = {
  587. settings: handler,
  588. }
  589. }
  590.  
  591. return config
  592. }
  593.  
  594. async function getHostConfig() {
  595. const hosts = urlExtractor.getImageHostsMetadata()
  596.  
  597. const storedConfig = await store.get(currentHost, { hosts: {} })
  598. const enabledHosts = []
  599.  
  600. for (const host of hosts) {
  601. const id = host.name
  602. const isEnabled = id in storedConfig.hosts ? storedConfig.hosts[id] : true
  603.  
  604. host.isEnabled = isEnabled
  605. storedConfig.hosts[id] = isEnabled
  606.  
  607. if (isEnabled) {
  608. enabledHosts.push(id)
  609. }
  610. }
  611.  
  612. storedConfig.hosts = hosts.reduce((result, host) => {
  613. result[host.name] = host.isEnabled
  614.  
  615. return result
  616. }, {})
  617.  
  618. return {
  619. hosts,
  620. storedConfig,
  621. enabledHosts,
  622. }
  623. }
  624.  
  625. function showMenu(config) {
  626. createMenuElement(config).classList.add(CLASSES$1.open)
  627. }
  628.  
  629. function createMenuElement(config) {
  630. if (configMenu) {
  631. return configMenu
  632. }
  633.  
  634. const rows = config.hosts.map((host) => createConfigMenuRow(host))
  635.  
  636. configMenu = $.create('div', {
  637. id: 'iv-config-form',
  638. className: 'iv-config-form',
  639. contents: [
  640. createMenuHeader(),
  641. {
  642. tag: 'div',
  643. className: 'iv-config-form__options',
  644. contents: rows,
  645. },
  646. ],
  647. delegate: {
  648. change: {
  649. '.js-iv-config-checkbox': ({ target: { value, checked } }) =>
  650. updateHostConfig(config.storedConfig, value, checked),
  651. },
  652. },
  653. })
  654.  
  655. document.body.append(configMenu)
  656.  
  657. return configMenu
  658. }
  659.  
  660. function createConfigMenuRow(host) {
  661. return $.create('label', {
  662. className: 'iv-config-form__label',
  663. title: host.description,
  664. contents: [
  665. {
  666. tag: 'input',
  667. type: 'checkbox',
  668. className: 'iv-config-form__checkbox js-iv-config-checkbox',
  669. checked: host.isEnabled,
  670. value: host.name,
  671. },
  672. host.name,
  673. ],
  674. })
  675. }
  676.  
  677. function createMenuHeader() {
  678. const closeButton = $.create('a', {
  679. href: '#',
  680. title: 'Close',
  681. className: `iv-icon-button iv-icon-button--small iv-icon iv-icon--type-close`,
  682. events: {
  683. click: (event) => {
  684. event.preventDefault()
  685. configMenu.classList.remove(CLASSES$1.open)
  686. },
  687. },
  688. })
  689.  
  690. return {
  691. tag: 'div',
  692. className: 'iv-config-form__header',
  693. contents: [
  694. {
  695. tag: 'span',
  696. className: 'iv-config-form__header-title',
  697. contents: `Settings for ${currentHost}`,
  698. },
  699. closeButton,
  700. ],
  701. }
  702. }
  703.  
  704. function updateHostConfig(config, hostName, isEnabled) {
  705. config.hosts[hostName] = isEnabled
  706. store.set(currentHost, config)
  707. }
  708.  
  709. const css_248z =
  710. "@keyframes spin{0%{transform:translate(-50%,-50%) rotate(0deg)}to{transform:translate(-50%,-50%) rotate(1turn)}}.iv-icon{position:relative}.iv-icon:after,.iv-image-link img:after{background-position:50%;background-repeat:no-repeat;background-size:contain;content:\"\";height:100%;left:50%;position:absolute;top:50%;transform:translate(-50%,-50%);width:100%;z-index:2}.iv-icon--hover:after{opacity:0;transition:opacity .35s ease}.iv-icon--hover:hover:after{opacity:1}.iv-icon--size-button:after{height:50px;width:50px}.iv-icon--type-loading:after{animation:spin 1s linear infinite;background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff'%3E%3Cpath d='M12 4V2A10 10 0 0 0 2 12h2a8 8 0 0 1 8-8z'/%3E%3C/svg%3E\")!important;opacity:1}.iv-icon--type-zoom:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg fill='%23fff' height='24' width='24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'/%3E%3Cpath d='M0 0h24v24H0V0z' fill='none'/%3E%3Cpath d='M12 10h-2v2H9v-2H7V9h2V7h1v2h2v1z'/%3E%3C/svg%3E\")}.iv-icon--type-next:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg fill='%23fff' height='24' width='24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z'/%3E%3Cpath d='M0 0h24v24H0z' fill='none'/%3E%3C/svg%3E\")}.iv-icon--type-previous:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg fill='%23fff' height='24' width='24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z'/%3E%3Cpath d='M0 0h24v24H0z' fill='none'/%3E%3C/svg%3E\")}.iv-icon--type-close:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg fill='%23fff' height='24' width='24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'/%3E%3Cpath d='M0 0h24v24H0z' fill='none'/%3E%3C/svg%3E\")}.iv-icon--type-expand:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff'%3E%3Cpath d='M5 5h5v2H7v3H5V5m9 0h5v5h-2V7h-3V5m3 9h2v5h-5v-2h3v-3m-7 3v2H5v-5h2v3h3z'/%3E%3C/svg%3E\")}.iv-icon--type-shrink:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff'%3E%3Cpath d='M14 14h5v2h-3v3h-2v-5m-9 0h5v5H8v-3H5v-2m3-9h2v5H5V8h3V5m11 3v2h-5V5h2v3h3z'/%3E%3C/svg%3E\")}.iv-icon--type-image-broken:after,.iv-image-link img:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff'%3E%3Cpath d='M21 5v6.59l-3-3.01-4 4.01-4-4-4 4-3-3.01V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2m-3 6.42 3 3.01V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-6.58l3 2.99 4-4 4 4'/%3E%3C/svg%3E\")}.iv-image-link{border:1px solid rgba(0,0,0,.2);box-shadow:1px 1px 3px rgba(0,0,0,.5);display:inline-flex;margin:3px;min-height:50px;min-width:50px;padding:4px;vertical-align:top}.iv-image-link img{margin:0}.iv-image-link>:not(img){align-items:center;display:flex;justify-content:center;width:100%}.iv-image-link:before{background-color:rgba(0,0,0,.5);bottom:4px;content:\"\";left:4px;opacity:0;position:absolute;right:4px;top:4px;transition:opacity .35s ease;z-index:1}.iv-image-link.iv-icon--type-loading:before,.iv-image-link:hover:before{opacity:1}.iv-image-link img:after,.iv-image-link img:before{content:\"\";position:absolute}.iv-image-link img:before{background-color:rgba(0,0,0,.2);height:100%;left:0;top:0;width:100%}.iv-image-link img:after{height:35px;width:35px;z-index:0}.iv-image-view{background-color:rgba(0,0,0,.8);color:#fff;display:none;flex-direction:column;height:0;opacity:0;transition:opacity .35s ease-out;user-select:none}.iv-image-view--open body,html.iv-image-view--open{overflow:hidden}.iv-image-view--open .iv-image-view{bottom:0;display:flex;height:auto;left:0;opacity:1;position:fixed;right:0;top:0;z-index:3}.iv-image-view--single .single-hide{visibility:hidden}.iv-image-view__footer,.iv-image-view__header{background-color:rgba(0,0,0,.8);display:flex}.iv-image-view__footer-wrapper,.iv-image-view__header-wrapper{z-index:2}.iv-image-view__header-wrapper{box-shadow:0 3px 7px rgba(0,0,0,.7)}.iv-image-view__footer-wrapper{box-shadow:0 -3px 7px rgba(0,0,0,.7)}.iv-image-view__header{justify-content:space-between}.iv-image-view__footer{justify-content:center}.iv-image-view__body{display:flex;height:100%;overflow:auto;position:relative}.iv-image-view__body::-webkit-scrollbar{width:20px}.iv-image-view__body::-webkit-scrollbar-thumb{background-color:rgba(0,0,0,.8)}.iv-image-view__body::-webkit-scrollbar-track{background-color:hsla(0,0%,100%,.8)}.iv-thumbnail-wrapper{display:flex;height:100%;left:0;position:absolute;top:0;width:100%;z-index:0}.iv-image-view__number{align-items:center;display:flex;font-size:18px;padding:0 40px}.iv-image-view__backdrop{height:100%;left:0;position:fixed;top:0;width:100%;z-index:1}.iv-image,.iv-thumbnail{margin:auto;max-height:100%;max-width:100%;object-fit:contain}.iv-image{opacity:1;transition:opacity .35s ease-out;z-index:2}.iv-thumbnail{filter:blur(5px)}.iv-icon--type-error .iv-image,.iv-image-view__image--loading .iv-image,.iv-image-view__image--thumbnail .iv-image{opacity:0}.iv-image-view__image--thumbnail .iv-thumbnail-wrapper{z-index:2}.iv-image-view--full-height .iv-image,.iv-image-view--full-height .iv-thumbnail{cursor:grab;max-height:none}.iv-image-view--full-height .iv-image--grabbing{cursor:grabbing}.iv-icon-button{height:50px;transition:all .35s ease-out;width:50px}.iv-icon-button--small{height:25px;width:25px}.iv-icon-button+.iv-icon-button{margin-left:5px}.iv-icon-button:hover{background-color:hsla(0,0%,100%,.1)}.iv-icon-button--active,.iv-icon-button:active{background-color:hsla(0,0%,100%,.2)}.iv-config-form{background-color:rgba(0,0,0,.85);color:#fff;display:none;flex-direction:column;height:50%;left:10px;max-width:500px;padding:10px;top:10px;width:50%}.iv-config-form--open{display:flex;position:fixed;z-index:3}.iv-config-form__header{align-items:center;display:flex;padding:10px}.iv-config-form__header-title{flex-grow:1}.iv-config-form__options{display:flex;flex-flow:column wrap;flex-grow:1;overflow:auto}.iv-config-form__label{align-items:center;display:flex;flex:0 0 auto;margin:0;padding:10px;transition:all .35s ease-out}.iv-config-form__label:hover{background-color:hsla(0,0%,100%,.15)}.iv-config-form__checkbox{margin:0 5px 0 0!important}"
  711.  
  712. const CLASSES = {
  713. imageLink: 'js-image-link',
  714. imageLinkZoom: 'iv-icon--type-zoom',
  715. imageLinkHover: 'iv-icon--hover',
  716. brokenImage: 'iv-icon--type-image-broken',
  717. loadingIcon: 'iv-icon--type-loading',
  718. loading: 'iv-image-view__image--loading',
  719. thumbnail: 'iv-image-view__image--thumbnail',
  720. open: 'iv-image-view--open',
  721. single: 'iv-image-view--single',
  722. fullHeight: 'iv-image-view--full-height',
  723. iconExpand: 'iv-icon--type-expand',
  724. iconShrink: 'iv-icon--type-shrink',
  725. grabbing: 'iv-image--grabbing',
  726. buttonActive: 'iv-icon-button--active',
  727. }
  728.  
  729. const SELECTORS = {
  730. imageLink: `.${CLASSES.imageLink}`,
  731. }
  732.  
  733. const EMPTY_SRC =
  734. 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEAAAAALAAAAAABAAEAAAI='
  735.  
  736. const TRANSITION_DURATION = 350
  737.  
  738. function initViewer(enabledHosts) {
  739. addStyle(css_248z)
  740.  
  741. const container = $('body')
  742.  
  743. const linkClasses = [
  744. CLASSES.imageLink,
  745. 'iv-image-link',
  746. 'iv-icon',
  747. 'iv-icon--hover',
  748. CLASSES.imageLinkZoom,
  749. 'iv-icon--size-button',
  750. ]
  751.  
  752. const getHostName = urlExtractor.getHostNameMatcher(enabledHosts)
  753.  
  754. const imagesWithLinks = $$('a > img, a > var', container)
  755. .map((img) => ({
  756. link: img.parentElement,
  757. thumbnailUrl: img.src || img.title,
  758. }))
  759. .filter(({ link }) => link.href)
  760.  
  761. for (const { link, thumbnailUrl } of imagesWithLinks) {
  762. const hostName = getHostName(link.href)
  763.  
  764. if (hostName) {
  765. link.dataset.ivHost = hostName
  766. link.dataset.ivThumbnail = thumbnailUrl
  767. link.classList.add(...linkClasses)
  768. }
  769. }
  770.  
  771. $.delegate(container, 'click', SELECTORS.imageLink, events.linkClick)
  772. }
  773.  
  774. const elements = {
  775. container: undefined,
  776. image: undefined,
  777. imageThumbnail: undefined,
  778. imageContainer: undefined,
  779. imageNumber: undefined,
  780. imageTotal: undefined,
  781. buttons: {
  782. next: undefined,
  783. previous: undefined,
  784. close: undefined,
  785. toggleFullHeight: undefined,
  786. },
  787. }
  788.  
  789. const state = {
  790. isFirstClick: true,
  791. isOpened: false,
  792. currentLink: undefined,
  793. linksSet: [],
  794. isSingle: false,
  795. getCurrentLinkIndex() {
  796. return this.currentLink === undefined
  797. ? -1
  798. : this.linksSet.indexOf(this.currentLink)
  799. },
  800. getLastLinkIndex() {
  801. return this.linksSet.length - 1
  802. },
  803. dragPosition: 0,
  804. dragging: false,
  805. }
  806.  
  807. const image = {
  808. async show(link) {
  809. const container = elements.container
  810. const img = elements.image
  811. const thumbnail = elements.imageThumbnail
  812.  
  813. state.currentLink = link
  814.  
  815. if (state.isSingle) {
  816. container.classList.add(CLASSES.single)
  817. } else {
  818. container.classList.remove(CLASSES.single)
  819. elements.imageNumber.textContent = (
  820. state.getCurrentLinkIndex() + 1
  821. ).toString()
  822. }
  823.  
  824. if (!state.isOpened) {
  825. document.documentElement.classList.add(CLASSES.open)
  826. state.isOpened = true
  827. }
  828.  
  829. img.src = EMPTY_SRC
  830.  
  831. if (link.classList.contains(CLASSES.brokenImage)) {
  832. container.classList.add(CLASSES.brokenImage)
  833.  
  834. return
  835. }
  836.  
  837. container.classList.remove(CLASSES.brokenImage)
  838.  
  839. container.classList.add(CLASSES.loading, CLASSES.loadingIcon)
  840.  
  841. const isSizeKnown = !!link.dataset.ivWidth
  842. const thumbnailURL = link.dataset.ivThumbnail
  843.  
  844. if (!thumbnailURL || !link.dataset.ivHost) {
  845. throw new Error(
  846. '[image-viewer] Either thumbnail URL or host is not set'
  847. )
  848. }
  849.  
  850. if (isSizeKnown) {
  851. thumbnail.width = Number(link.dataset.ivWidth)
  852. thumbnail.src = thumbnailURL
  853.  
  854. container.classList.add(CLASSES.thumbnail)
  855. }
  856.  
  857. let imageURL = link.dataset.ivImgUrl
  858.  
  859. if (!imageURL) {
  860. imageURL = await urlExtractor.getImageURL({
  861. url: link.href,
  862. thumbnailURL,
  863. host: link.dataset.ivHost,
  864. })
  865.  
  866. if (!imageURL) {
  867. image.markAsBroken(link)
  868.  
  869. return
  870. }
  871.  
  872. link.dataset.ivImgUrl = imageURL
  873. }
  874.  
  875. try {
  876. await image.preload(
  877. imageURL,
  878. isSizeKnown ? undefined : image.setThumbnailSize
  879. )
  880.  
  881. img.src = imageURL
  882.  
  883. container.classList.remove(
  884. CLASSES.thumbnail,
  885. CLASSES.loading,
  886. CLASSES.loadingIcon
  887. )
  888.  
  889. setTimeout(image.hideThumbnail, TRANSITION_DURATION)
  890. } catch {
  891. link.classList.remove(CLASSES.imageLink)
  892. image.markAsBroken(link)
  893.  
  894. $.attributes(link, { target: '_blank' })
  895. }
  896. },
  897.  
  898. preload(url, onSizeGet) {
  899. return new Promise((resolve, reject) => {
  900. const imageObject = new Image()
  901.  
  902. imageObject.addEventListener('load', () => resolve())
  903. imageObject.addEventListener('error', reject)
  904.  
  905. imageObject.src = url
  906.  
  907. if (onSizeGet) {
  908. image.getSize(imageObject).then(onSizeGet)
  909. }
  910. })
  911. },
  912.  
  913. getSize(img) {
  914. return new Promise((resolve) => {
  915. const intervalId = setInterval(() => {
  916. if (img.naturalWidth) {
  917. clearInterval(intervalId)
  918. resolve({ width: img.naturalWidth, isLoaded: img.complete })
  919. }
  920. }, 10)
  921. })
  922. },
  923.  
  924. setThumbnailSize({ width, isLoaded }) {
  925. if (!state.currentLink) {
  926. throw new Error('[image-viewer] currentLink is not set')
  927. }
  928.  
  929. const thumbnailURL = state.currentLink.dataset.ivThumbnail
  930.  
  931. if (!thumbnailURL) {
  932. throw new Error('[image-viewer] Thumbnail URL is not set')
  933. }
  934.  
  935. elements.imageThumbnail.width = width
  936. elements.imageThumbnail.src = thumbnailURL
  937.  
  938. if (!isLoaded) {
  939. elements.container.classList.add(CLASSES.thumbnail)
  940. }
  941.  
  942. state.currentLink.dataset.ivWidth = width.toString()
  943. },
  944.  
  945. hideThumbnail() {
  946. elements.imageThumbnail.removeAttribute('width')
  947. elements.imageThumbnail.src = EMPTY_SRC
  948. },
  949.  
  950. hide() {
  951. document.documentElement.classList.remove(CLASSES.open)
  952. state.isOpened = false
  953. state.currentLink = undefined
  954. elements.image.src = EMPTY_SRC
  955. events.keyboard.unbind()
  956. },
  957.  
  958. next() {
  959. const currentIndex = state.getCurrentLinkIndex()
  960. const newIndex =
  961. currentIndex < state.getLastLinkIndex() ? currentIndex + 1 : 0
  962.  
  963. image.show(state.linksSet[newIndex])
  964. },
  965.  
  966. previous() {
  967. const currentIndex = state.getCurrentLinkIndex()
  968. const newIndex =
  969. currentIndex === 0 ? state.getLastLinkIndex() : currentIndex - 1
  970.  
  971. image.show(state.linksSet[newIndex])
  972. },
  973.  
  974. toggleFullHeight() {
  975. elements.container.classList.toggle(CLASSES.fullHeight)
  976. elements.buttons.toggleFullHeight.classList.toggle(CLASSES.iconExpand)
  977. elements.buttons.toggleFullHeight.classList.toggle(CLASSES.iconShrink)
  978. },
  979.  
  980. markAsBroken(link) {
  981. elements.container.classList.replace(
  982. CLASSES.loadingIcon,
  983. CLASSES.brokenImage
  984. )
  985. elements.container.classList.remove(CLASSES.loading)
  986. link.classList.replace(CLASSES.imageLinkZoom, CLASSES.brokenImage)
  987. },
  988. }
  989.  
  990. const events = {
  991. linkClick(event) {
  992. event.preventDefault()
  993.  
  994. if (state.isFirstClick) {
  995. create.viewContainer()
  996. state.isFirstClick = false
  997. }
  998.  
  999. const link = event.target
  1000.  
  1001. state.linksSet = $$(SELECTORS.imageLink, link.parentElement ?? undefined)
  1002. state.isSingle = state.linksSet.length === 1
  1003.  
  1004. if (!state.isSingle) {
  1005. elements.imageTotal.textContent = state.linksSet.length.toString()
  1006. }
  1007.  
  1008. events.keyboard.bind()
  1009.  
  1010. image.show(link)
  1011. },
  1012.  
  1013. keyboard: {
  1014. bind() {
  1015. document.addEventListener('keydown', events.keyboard.handler, true)
  1016. },
  1017. unbind() {
  1018. document.removeEventListener('keydown', events.keyboard.handler, true)
  1019. },
  1020.  
  1021. handler(event) {
  1022. if (event.defaultPrevented || event.repeat) {
  1023. return
  1024. }
  1025.  
  1026. switch (event.key) {
  1027. case 'ArrowRight':
  1028. image.next()
  1029. break
  1030.  
  1031. case 'ArrowLeft':
  1032. image.previous()
  1033. break
  1034.  
  1035. case 'Escape':
  1036. image.hide()
  1037. break
  1038.  
  1039. case ' ':
  1040. image.toggleFullHeight()
  1041. break
  1042.  
  1043. default:
  1044. return
  1045. }
  1046.  
  1047. event.preventDefault()
  1048. },
  1049. },
  1050.  
  1051. mouse(event) {
  1052. switch (event.type) {
  1053. case 'mousedown':
  1054. state.dragging = true
  1055. state.dragPosition = event.clientY
  1056. elements.image.classList.add(CLASSES.grabbing)
  1057. break
  1058.  
  1059. case 'mousemove':
  1060. if (state.dragging) {
  1061. elements.imageContainer.scrollTop -=
  1062. event.clientY - state.dragPosition
  1063. state.dragPosition = event.clientY
  1064. }
  1065. break
  1066.  
  1067. case 'mouseup':
  1068.  
  1069. // fall through
  1070. case 'mouseout':
  1071. state.dragging = false
  1072. elements.image.classList.remove(CLASSES.grabbing)
  1073. break
  1074.  
  1075. case 'dblclick':
  1076. image.toggleFullHeight()
  1077. break
  1078.  
  1079. default:
  1080. return
  1081. }
  1082.  
  1083. event.preventDefault()
  1084. },
  1085. }
  1086.  
  1087. const create = {
  1088. viewContainer() {
  1089. elements.container = $.create('div', {
  1090. className: 'iv-image-view iv-icon iv-icon--size-button',
  1091. contents: [
  1092. create.viewContainerHeader(),
  1093. create.viewContainerBody(),
  1094. create.viewContainerFooter(),
  1095. ],
  1096. })
  1097.  
  1098. document.body.append(elements.container)
  1099. },
  1100.  
  1101. viewContainerBody() {
  1102. elements.image = $.create('img', {
  1103. className: 'iv-image',
  1104. events: {
  1105. 'mousedown mouseup mousemove mouseout dblclick': events.mouse,
  1106. },
  1107. })
  1108.  
  1109. elements.imageThumbnail = $.create('img', {
  1110. className: 'iv-thumbnail',
  1111. })
  1112.  
  1113. elements.imageContainer = $.create('div', {
  1114. className: 'iv-image-view__body',
  1115. contents: [
  1116. {
  1117. tag: 'div',
  1118. className: 'iv-image-view__backdrop',
  1119. events: {
  1120. click: image.hide,
  1121. },
  1122. },
  1123. {
  1124. tag: 'div',
  1125. className: 'iv-thumbnail-wrapper',
  1126. contents: elements.imageThumbnail,
  1127. },
  1128. elements.image,
  1129. ],
  1130. })
  1131.  
  1132. return elements.imageContainer
  1133. },
  1134.  
  1135. viewContainerHeader() {
  1136. elements.imageNumber = document.createElement('span')
  1137. elements.imageTotal = document.createElement('span')
  1138. const imageNumber = $.create('div', {
  1139. className: 'iv-image-view__number single-hide',
  1140. contents: [elements.imageNumber, '/', elements.imageTotal],
  1141. })
  1142.  
  1143. elements.buttons.close = create.toolbarButton(
  1144. 'Close (Esc)',
  1145. 'close',
  1146. image.hide
  1147. )
  1148.  
  1149. return {
  1150. tag: 'div',
  1151. className: 'iv-image-view__header-wrapper',
  1152. contents: {
  1153. tag: 'div',
  1154. className: 'iv-image-view__header',
  1155. contents: [imageNumber, elements.buttons.close],
  1156. },
  1157. }
  1158. },
  1159.  
  1160. viewContainerFooter() {
  1161. const buttons = elements.buttons
  1162.  
  1163. buttons.previous = create.toolbarButton(
  1164. 'Previous (←)',
  1165. 'previous',
  1166. image.previous,
  1167. 'single-hide'
  1168. )
  1169. buttons.toggleFullHeight = create.toolbarButton(
  1170. 'Toggle full height (Space)',
  1171. 'expand',
  1172. image.toggleFullHeight
  1173. )
  1174. buttons.next = create.toolbarButton(
  1175. 'Next (→)',
  1176. 'next',
  1177. image.next,
  1178. 'single-hide'
  1179. )
  1180.  
  1181. return {
  1182. tag: 'div',
  1183. className: 'iv-image-view__footer-wrapper',
  1184. contents: {
  1185. tag: 'div',
  1186. className: 'iv-image-view__footer',
  1187. contents: [buttons.previous, buttons.toggleFullHeight, buttons.next],
  1188. },
  1189. }
  1190. },
  1191.  
  1192. toolbarButton(title, icon, handler, className = '') {
  1193. return $.create('a', {
  1194. href: '#',
  1195. title,
  1196. className: `iv-icon-button iv-icon iv-icon--type-${icon} ${className}`,
  1197. events: {
  1198. click: (event) => {
  1199. event.preventDefault()
  1200. handler()
  1201. },
  1202. },
  1203. })
  1204. },
  1205. }
  1206.  
  1207. $.ready().then(async () => {
  1208. const hostConfig = await initHostConfig()
  1209.  
  1210. initViewer(hostConfig.enabledHosts)
  1211. })
  1212. })()