Image Viewer

Allows viewing full image without leaving the page

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

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