diff --git a/CHANGELOG.md b/CHANGELOG.md index eb304f504..c0ebf15b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ 4chan XT uses a different user script namespace, so to migrate you need to export settings from 4chan X, and import them in XT. +### XT v2.2.3 (2023-11-08) + +- Fixed error when "Force Noscript Captcha" is enabled. + ### XT v2.2.2 (2023-10-29) - Fixed trying to get thread JSON from unsupported archives. diff --git a/builds/4chan-XT.meta.js b/builds/4chan-XT.meta.js index 5218d704d..50af18e38 100644 --- a/builds/4chan-XT.meta.js +++ b/builds/4chan-XT.meta.js @@ -1,6 +1,6 @@ // ==UserScript== // @name 4chan XT -// @version XT 2.2.2 +// @version XT 2.2.3 // @minGMVer 1.14 // @minFFVer 74 // @namespace 4chan-XT diff --git a/builds/4chan-XT.min.meta.js b/builds/4chan-XT.min.meta.js index 2e9f7a695..39057b4c3 100644 --- a/builds/4chan-XT.min.meta.js +++ b/builds/4chan-XT.min.meta.js @@ -1,6 +1,6 @@ // ==UserScript== // @name 4chan XT -// @version XT 2.2.2 +// @version XT 2.2.3 // @minGMVer 1.14 // @minFFVer 74 // @namespace 4chan-XT diff --git a/builds/4chan-XT.min.user.js b/builds/4chan-XT.min.user.js index 232f91629..63dff737f 100644 --- a/builds/4chan-XT.min.user.js +++ b/builds/4chan-XT.min.user.js @@ -1,6 +1,6 @@ // ==UserScript== // @name 4chan XT -// @version XT 2.2.2 +// @version XT 2.2.3 // @minGMVer 1.14 // @minFFVer 74 // @namespace 4chan-XT @@ -190,7 +190,7 @@ !function(){"use strict";var e={name:"4chan XT",path:"4chan-XT",fork:"TuxedoTako",page:"https://github.com/TuxedoTako/4chan-xt",downloads:"https://github.com/TuxedoTako/4chan-xt/releases",oldVersions:"https://raw.githubusercontent.com/ccd0/4chan-x/",faq:"https://github.com/ccd0/4chan-x/wiki/Frequently-Asked-Questions",captchaFAQ:"https://github.com/ccd0/4chan-x/wiki/Captcha-FAQ",cssGuide:"https://github.com/ccd0/4chan-x/wiki/Styling-Guide",license:"https://github.com/TuxedoTako/4chan-xt/blob/project-XT/LICENSE",changelog:"https://github.com/TuxedoTako/4chan-xt/blob/project-XT/CHANGELOG.md",issues:"https://github.com/TuxedoTako/4chan-xt/issues",newIssue:"https://github.com/TuxedoTako/4chan-xt/issues",newIssueMaxLength:8181,alternatives:"https://www.4chan-x.net/4chan_alternatives.html",appid:"lacclbnghgdicfifcamcmcnilckjamag",appidGecko:"4chan-x@4chan-x.net",chromeStoreID:"ohnjgmpcibpbafdlkimncjhflgedgpam",recaptchaKey:"6Ldp2bsSAAAAAAJ5uyx_lx34lJeEpTLVkP5k04qc",distBranch:"gh-pages", includes_only:["*://boards.4chan.org/*","*://sys.4chan.org/*","*://www.4chan.org/*","*://boards.4channel.org/*","*://sys.4channel.org/*","*://www.4channel.org/*","*://i.4cdn.org/*","*://is.4chan.org/*","*://is2.4chan.org/*","*://is.4channel.org/*","*://is2.4channel.org/*"],matches_only:["*://*.4chan.org/*","*://*.4channel.org/*","*://*.4cdn.org/*"], matches:["https://erischan.org/*","https://www.erischan.org/*","https://fufufu.moe/*","https://gnfos.com/*","https://himasugi.blog/*","https://www.himasugi.blog/*","https://kakashinenpo.com/*","https://www.kakashinenpo.com/*","https://kissu.moe/*","https://www.kissu.moe/*","https://lainchan.org/*","https://www.lainchan.org/*","https://merorin.com/*","https://ota-ch.com/*","https://www.ota-ch.com/*","https://ponyville.us/*","https://www.ponyville.us/*","https://smuglo.li/*","https://notso.smuglo.li/*","https://smugloli.net/*","https://smug.nepu.moe/*","https://sportschan.org/*","https://www.sportschan.org/*","https://sushigirl.us/*","https://www.sushigirl.us/*","https://tvch.moe/*"],matches_extra:[],exclude_matches:["*://www.4chan.org/advertise","*://www.4chan.org/advertise?*","*://www.4chan.org/donate","*://www.4chan.org/donate?*","*://www.4channel.org/advertise","*://www.4channel.org/advertise?*","*://www.4channel.org/donate","*://www.4channel.org/donate?*"], -grants:["GM_getValue","GM_setValue","GM_deleteValue","GM_listValues","GM_addValueChangeListener","GM_openInTab","GM_xmlhttpRequest","GM.getValue","GM.setValue","GM.deleteValue","GM.listValues","GM.openInTab","GM.xmlHttpRequest"],min:{chrome:"80",firefox:"74",greasemonkey:"1.14"}};const t=Object.create(null),o={VERSION:"XT 2.2.2",NAMESPACE:e.name,sites:Object.create(null),boards:Object.create(null)},n=function(){const e={"&":"&","'":"'",'"':""","<":"<",">":">"},t=/[&"'<>]/g,o=function(t){return e[t]},n=function(e){return e.toString().replace(t,o)};return n.cat=function(e){let t="";for(let o=0;o":">"},t=/[&"'<>]/g,o=function(t){return e[t]},n=function(e){return e.toString().replace(t,o)};return n.cat=function(e){let t="";for(let o=0;oArray.from(t.querySelectorAll(e)),p={init(){if(!("yotsuba"!==o.SITE.software||a.cookie.indexOf("pass_enabled=1")>=0)){ -if(!t["Force Noscript Captcha"]||!jt.jsEnabled)return t.captchaLanguage.trim()?["boards.4chan.org","boards.4channel.org"].includes(location.hostname)?Qe.onExists(i,"#captchaFormPart",(e=>Qe.onExists(e,'iframe[src^="https://www.google.com/recaptcha/"]',$e.replace.iframe))):Qe.onExists(i,'iframe[src^="https://www.google.com/recaptcha/"]',$e.replace.iframe):void 0;Qe.ready($e.replace.noscript)}},noscript(){let e,t,o;if(!(t=Qe("#g-recaptcha"))||!(e=Qe("noscript",t.parentNode)))return;const n=Qe.el("span",{id:"captcha-forced-noscript"});Qe.replace(e,n),Qe.rm(t);const a=function(){return n.innerHTML=e.textContent,$e.replace.iframe(Qe('iframe[src^="https://www.google.com/recaptcha/"]',n))};return(o=Qe("#togglePostFormLink a, #form-link"))?Qe.on(o,"click",a):a()},iframe(e){let o;if(o=t.captchaLanguage.trim()){const t=/[?&]hl=/.test(e.src)?e.src.replace(/([?&]hl=)[^&]*/,"$1"+encodeURIComponent(o)):e.src+`&hl=${encodeURIComponent(o)}`;e.src!==t&&(e.src=t)}}},g={init(){ +};e=Qe.getOwn(e,t.favicon);const o=h;let n=0;for(;e[n];)e[n]="data:image/png;base64,"+e[n++];return[o.unreadDead,o.unreadDeadY,o.unreadSFW,o.unreadSFWY,o.unreadNSFW,o.unreadNSFWY]=e,o.update()},update(){return this.isSFW?(this.unread=this.unreadSFW,this.unreadY=this.unreadSFWY):(this.unread=this.unreadNSFW,this.unreadY=this.unreadNSFWY)},SFW:"//s.4cdn.org/image/favicon-ws.ico",NSFW:"//s.4cdn.org/image/favicon.ico",dead:"data:image/gif;base64,R0lGODlhEAAQAKECAAAAAP8AAP///////yH5BAEKAAIALAAAAAAQABAAAAIvlI+pq+D9DAgUoFkPDlbs7lFZKIJOJJ3MyraoB14jFpOcVMpzrnF3OKlZYsMWowAAOw==",logo:"data:image/png;base64,R0lGODlhEAAQAJEAAAAAAP///9vb2////yH5BAEAAAMALAAAAAAQABAAAAIvnI+pq+D9DBAUoFkPFnbs7lFZKIJOJJ3MyraoB14jFpOcVMpzrnF3OKlZYsMWowAAOw=="};const u=(e,t=a.body)=>Array.from(t.querySelectorAll(e)),p={init(){ +"yotsuba"!==o.SITE.software||a.cookie.indexOf("pass_enabled=1")>=0||(t["Force Noscript Captcha"]&&jt.jsEnabled?Qe.ready(this.noscript):t.captchaLanguage.trim()&&(["boards.4chan.org","boards.4channel.org"].includes(location.hostname)?Qe.onExists(i,"#captchaFormPart",(e=>Qe.onExists(e,'iframe[src^="https://www.google.com/recaptcha/"]',this.iframe))):Qe.onExists(i,'iframe[src^="https://www.google.com/recaptcha/"]',this.iframe)))},noscript(){let e,t,o;if(!(t=Qe("#g-recaptcha"))||!(e=Qe("noscript",t.parentNode)))return;const n=Qe.el("span",{id:"captcha-forced-noscript"});Qe.replace(e,n),Qe.rm(t);const a=function(){n.innerHTML=e.textContent,this.iframe(Qe('iframe[src^="https://www.google.com/recaptcha/"]',n))};(o=Qe("#togglePostFormLink a, #form-link"))?Qe.on(o,"click",a):a()},iframe(e){let o;if(o=t.captchaLanguage.trim()){const t=/[?&]hl=/.test(e.src)?e.src.replace(/([?&]hl=)[^&]*/,"$1"+encodeURIComponent(o)):e.src+`&hl=${encodeURIComponent(o)}`;e.src!==t&&(e.src=t)}}},g={init(){ if(a.cookie.indexOf("pass_enabled=1")>=0)return;if(!(this.isEnabled=!!Qe("#t-root")||!Qe.id("postForm")))return;const e=Qe.el("div",{className:"captcha-root"});return this.nodes={root:e},Qe.addClass(je.nodes.el,"has-captcha","captcha-t"),Qe.after(je.nodes.com.parentNode,e)},moreNeeded(){},getThread(){let e;const t=o.BOARD.ID;return e="new"===je.posts[0].thread?"0":""+je.posts[0].thread,{boardID:t,threadID:e}},setup(e){if(this.isEnabled)return this.nodes.container||(this.nodes.container=Qe.el("div",{className:"captcha-container"}),Qe.prepend(this.nodes.root,this.nodes.container),g.currentThread=g.getThread(),Qe.global((function(){const e=document.querySelector("#qr .captcha-container");return window.TCaptcha.init(e,this.boardID,+this.threadID),window.TCaptcha.setErrorCb((e=>window.dispatchEvent(new CustomEvent("CreateNotification",{detail:{type:"warning",content:""+e}}))))}),g.currentThread)),e?Qe("#t-resp").focus():void 0},destroy(){ if(this.isEnabled&&this.nodes.container)return Qe.global((()=>window.TCaptcha.destroy())),Qe.rm(this.nodes.container),delete this.nodes.container},updateThread(){if(!this.isEnabled)return;const{boardID:e,threadID:t}=g.currentThread||{},o=g.getThread();return o.boardID!==e||o.threadID!==t?(g.destroy(),g.setup()):void 0},getOne(){let e,t={};if(this.nodes.container)for(var o of["t-response","t-challenge"])t[o]=Qe(`[name='${o}']`,this.nodes.container).value;return t["t-response"]||(e=Qe("#t-msg"))&&/Verification not required/i.test(e.textContent)||(t=null),t},setUsed(){if(this.isEnabled)return this.nodes.container?Qe.global((()=>window.TCaptcha.clearChallenge())):void 0},occupied(){return!!this.nodes.container}},f=(e,t)=>{let o=0,n=null,a=null,i=null;const r=function(){return o=Date.now(),t.apply(a,i)};return function(){return i=arguments,a=this,oObject.create(null);m.clone=function(e){if("object"!=typeof e||null===e)return e ;if(e instanceof Array){const t=[];for(let o=0,n=e.length;om.clone(JSON.parse(e));const b=1e3,A=6e4,v=36e5,w=24*v,x=window.GM_xmlhttpRequest?"userscript":"crx";class y{static initClass(){this.keys=["hiddenThreads","hiddenPosts","lastReadPosts","yourPosts","watchedThreads","watcherLastModified","customTitles"]}constructor(e,o,n){if(this.changes=[],this.onSync=this.onSync.bind(this),this.key=e,this.initData(t[this.key]),Qe.sync(this.key,this.onSync),n||this.clean(),o){var i=()=>(Qe.off(a,"4chanXInitFinished",i),this.sync=o);Qe.on(a,"4chanXInitFinished",i)}}initData(e){let t;if(this.data=e,this.data.boards){let e;({boards:t,lastChecked:e}=this.data),this.data["4chan.org"]={boards:t,lastChecked:e},delete this.data.boards,delete this.data.lastChecked}return this.data[o.SITE.ID]||(this.data[o.SITE.ID]={boards:m()})}save(e,t){return e(),this.changes.push(e), diff --git a/builds/4chan-XT.min.user.js.map b/builds/4chan-XT.min.user.js.map index a51ecdcf3..1b8e9eece 100644 --- a/builds/4chan-XT.min.user.js.map +++ b/builds/4chan-XT.min.user.js.map @@ -1 +1 @@ -{"version":3,"file":"4chan-XT.min.user.js","sources":["../../../../src/globals/globals.ts","../src/classes/Callbacks.js","../src/config/Config.js","../src/Monitoring/Favicon.js","../src/platform/$$.js","../src/Posting/Captcha.replace.js","../src/Posting/Captcha.t.js","../../../../src/platform/helpers.ts","../src/classes/DataBoard.js","../../../../src/classes/SimpleDict.ts","../../../../src/classes/Thread.ts","../src/classes/CatalogThread.js","../src/General/UI.js","../src/Miscellaneous/Nav.js","../src/Images/ImageHost.js","../src/Images/Volume.js","../src/Images/ImageCommon.js","../../../../src/Images/Audio.ts","../../../../src/Images/ImageExpand.ts","../../../../src/classes/Post.ts","../src/Menu/Menu.js","../src/Filtering/Recursive.js","../src/Filtering/PostHiding.js","../src/Miscellaneous/RelativeDates.js","../src/General/BoardConfig.js","../../../../src/classes/Board.ts","../src/Posting/PostRedirect.js","../src/Miscellaneous/ExpandComment.js","../src/Quotelinks/QuoteYou.js","../src/classes/RandomAccessList.js","../src/Monitoring/Unread.js","../src/Miscellaneous/ExpandThread.js","../src/Monitoring/UnreadIndex.js","../src/Monitoring/ThreadWatcher.js","../../../../src/globals/jsx.ts","../../../../src/Archive/Parse.ts","../../../../src/classes/Fetcher.ts","../src/Quotelinks/QuotePreview.js","../src/General/Index.js","../src/Filtering/ThreadHiding.js","../../../../src/General/Settings/SettingsHtml.tsx","../../../../src/css/style.ts","../../../../src/css/CSS.ts","../src/Miscellaneous/CustomCSS.js","../src/site/SW.tinyboard.js","../../../../src/Miscellaneous/PassMessage/PassMessageHtml.tsx","../src/Miscellaneous/PassMessage.js","../src/Miscellaneous/Report.js","../src/Posting/PostSuccessful.js","../../../../src/site/SW.yotsuba.tsx","../../../../src/site/SW.yotsuba.Build/PostInfoHtml.tsx","../../../../src/site/SW.yotsuba.Build/FileHtml.tsx","../../../../src/site/SW.yotsuba.Build/CatalogThreadHtml.tsx","../src/site/SW.js","../../../../src/Miscellaneous/FileInfo.tsx","../../../../src/Miscellaneous/Time.ts","../src/Monitoring/ReplyPruning.js","../src/Quotelinks/QuoteThreading.js","../../../../src/Monitoring/ThreadUpdater.ts","../../../../src/General/Settings.tsx","../src/Images/FappeTyme.js","../src/Images/Sauce.js","../src/Images/Gallery.js","../src/Linkification/Embedding.js","../src/Miscellaneous/Keybinds.js","../src/Posting/Captcha.js","../src/Posting/QR.js","../src/platform/CrossOrigin.js","../../../../src/platform/$.ts","../src/General/Get.js","../../../../src/Filtering/Filter.ts","../src/site/Site.js","../src/Miscellaneous/CatalogLinks.js","../src/General/Header.js","../src/classes/Notice.js","../../../../src/Archive/Redirect.ts","../src/classes/CatalogThreadNative.js","../src/Filtering/Anonymize.js","../src/Images/ImageHover.js","../src/Images/ImageLoader.js","../src/Images/Metadata.js","../src/Images/RevealSpoilers.js","../src/Linkification/Linkify.js","../src/Menu/ArchiveLink.js","../src/Menu/CopyTextLink.js","../src/Menu/DeleteLink.js","../src/Menu/DownloadLink.js","../src/Menu/ReportLink.js","../src/Miscellaneous/AntiAutoplay.js","../src/Miscellaneous/Banner.js","../src/Miscellaneous/Flash.js","../src/Miscellaneous/Fourchan.js","../src/Miscellaneous/IDColor.js","../src/Miscellaneous/IDHighlight.js","../src/Miscellaneous/IDPostCount.js","../src/Miscellaneous/ModContact.js","../src/Miscellaneous/NormalizeURL.js","../src/Miscellaneous/PostJumper.js","../src/Miscellaneous/PSA.js","../src/Miscellaneous/PSAHiding.js","../src/Miscellaneous/RemoveSpoilers.js","../src/Miscellaneous/ThreadLinks.js","../src/Miscellaneous/Tinyboard.js","../src/Monitoring/MarkNewIPs.js","../src/Monitoring/ThreadStats.js","../src/Posting/PassLink.js","../src/Quotelinks/QuoteInline.js","../src/Quotelinks/QuoteBacklink.js","../src/Quotelinks/QuoteCT.js","../src/Quotelinks/QuoteOP.js","../src/Quotelinks/Quotify.js","../src/General/Polyfill.js","../../../../src/Archive/RestoreDeletedFromArchive.ts","../src/main/Main.js","../src/Quotelinks/QuoteStrikeThrough.js"],"sourcesContent":[null,"import Main from \"../main/Main\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS206: Consider reworking classes to avoid initClass\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nexport default class Callbacks {\r\n static initClass() {\r\n this.Post = new Callbacks('Post');\r\n this.Thread = new Callbacks('Thread');\r\n this.CatalogThread = new Callbacks('Catalog Thread');\r\n this.CatalogThreadNative = new Callbacks('Catalog Thread');\r\n }\r\n\r\n constructor(type) {\r\n this.type = type;\r\n this.keys = [];\r\n }\r\n\r\n push({name, cb}) {\r\n if (!this[name]) { this.keys.push(name); }\r\n return this[name] = cb;\r\n }\r\n\r\n execute(node, keys=this.keys, force=false) {\r\n let errors;\r\n if (node.callbacksExecuted && !force) { return; }\r\n node.callbacksExecuted = true;\r\n for (var name of keys) {\r\n try {\r\n this[name]?.call(node);\r\n } catch (err) {\r\n if (!errors) { errors = []; }\r\n errors.push({\r\n message: ['\"', name, '\" crashed on node ', this.type, ' No.', node.ID, ' (', node.board, ').'].join(''),\r\n error: err,\r\n html: node.nodes?.root?.outerHTML\r\n });\r\n }\r\n }\r\n\r\n if (errors) { return Main.handleErrors(errors); }\r\n }\r\n}\r\nCallbacks.initClass();\r\n","import userCss from './user.css';\r\nimport banners from './banners.json';\r\nimport meta from '../../package.json';\r\n\r\nconst Config = {\r\n main: {\r\n 'Miscellaneous': {\r\n 'Redirect to HTTPS': [\r\n true,\r\n 'Redirect to the HTTPS version of 4chan.'\r\n ],\r\n 'JSON Index': [\r\n true,\r\n 'Replace the original board index with one supporting searching, sorting, infinite scrolling, and a catalog mode.'\r\n ],\r\n [`Use ${meta.name} Catalog`]: [\r\n true,\r\n `Link to ${meta.name}'s catalog instead of the native 4chan one.`,\r\n 1\r\n ],\r\n 'Index Refresh Notifications': [\r\n false,\r\n 'Show a notice at the top of the page when the index is refreshed.',\r\n 1\r\n ],\r\n 'Follow Cursor': [\r\n true,\r\n 'Image Hover and Quote Preview move with the mouse cursor.'\r\n ],\r\n 'Open Threads in New Tab': [\r\n false,\r\n `Make links to threads in the index / ${meta.name} catalog open in a new tab.`\r\n ],\r\n 'External Catalog': [\r\n false,\r\n 'Link to external catalog instead of the internal one.'\r\n ],\r\n 'Catalog Links': [\r\n false,\r\n 'Add toggle link in header menu to turn Navigation links into links to each board\\'s catalog.'\r\n ],\r\n 'Announcement Hiding': [\r\n true,\r\n 'Add button to hide 4chan announcements.'\r\n ],\r\n 'Desktop Notifications': [\r\n true,\r\n `Enables desktop notifications across various ${meta.name} features.`\r\n ],\r\n '404 Redirect': [\r\n true,\r\n 'Redirect dead threads and images to the archives.'\r\n ],\r\n 'Archive Report': [\r\n true,\r\n 'Enable reporting posts to supported archives.'\r\n ],\r\n 'Exempt Archives from Encryption': [\r\n false,\r\n 'Permit loading content from, and warningless redirects to, HTTP-only archives from HTTPS pages.'\r\n ],\r\n 'Keybinds': [\r\n true,\r\n 'Bind actions to keyboard shortcuts.'\r\n ],\r\n 'Time Formatting': [\r\n true,\r\n 'Localize and format timestamps.'\r\n ],\r\n 'Relative Post Dates': [\r\n true,\r\n 'Display dates like \"3 minutes ago\". Tooltip shows the timestamp.'\r\n ],\r\n 'Relative Date Title': [\r\n true,\r\n 'Show Relative Post Date only when hovering over dates.',\r\n 1\r\n ],\r\n 'Comment Expansion': [\r\n true,\r\n 'Expand comments that are too long to display on the index. Not applicable with JSON Index.'\r\n ],\r\n 'File Info Formatting': [\r\n true,\r\n 'Reformat the file information.'\r\n ],\r\n 'Thread Expansion': [\r\n true,\r\n 'Add buttons to expand threads.'\r\n ],\r\n 'Index Navigation': [\r\n false,\r\n 'Add buttons to navigate between threads.'\r\n ],\r\n 'Reply Navigation': [\r\n false,\r\n 'Add buttons to navigate to top / bottom of thread.'\r\n ],\r\n 'Unique ID and Capcode Navigation': [\r\n false,\r\n 'Add buttons to navigate to posts having the same unique ID or capcode.'\r\n ],\r\n 'Custom Board Titles': [\r\n true,\r\n 'Allow editing of the board title and subtitle by ctrl/\\u2318+clicking them.'\r\n ],\r\n 'Persistent Custom Board Titles': [\r\n false,\r\n 'Force custom board titles to be persistent, even if the board titles are updated.',\r\n 1\r\n ],\r\n 'Show Updated Notifications': [\r\n true,\r\n `Show notifications when ${meta.name} is successfully updated.`\r\n ],\r\n 'Color User IDs': [\r\n true,\r\n 'Assign unique colors to user IDs on boards that use them'\r\n ],\r\n 'Count Posts by ID': [\r\n true,\r\n 'Display number of posts in the thread when hovering over an ID.'\r\n ],\r\n 'Remove Spoilers': [\r\n false,\r\n 'Remove all spoilers in text.'\r\n ],\r\n 'Reveal Spoilers': [\r\n false,\r\n 'Indicate spoilers if Remove Spoilers is enabled, or make the text appear hovered if Remove Spoiler is disabled.'\r\n ],\r\n 'Normalize URL': [\r\n true,\r\n 'Rewrite the URL of the current page, removing slugs and excess slashes, and changing /res/ to /thread/.'\r\n ],\r\n 'Work around CORB Bug': [\r\n true,\r\n 'Leave this checked until your garbage browser is fixed.'\r\n ],\r\n 'Disable Autoplaying Sounds': [\r\n false,\r\n 'Prevent sounds on the page from autoplaying.'\r\n ],\r\n 'Disable Native Extension': [\r\n true,\r\n `${meta.name} is NOT designed to work with the native extension.`\r\n ],\r\n 'Enable Native Flash Embedding': [\r\n true,\r\n 'Activate the native extension\\'s Flash embedding if the native extension is disabled.'\r\n ]\r\n },\r\n\r\n 'Linkification': {\r\n 'Linkify': [\r\n true,\r\n 'Convert text into links where applicable.'\r\n ],\r\n 'Link Title': [\r\n true,\r\n 'Replace the link of a supported site with its actual title.',\r\n 1\r\n ],\r\n 'Cover Preview': [\r\n true,\r\n 'Show preview of supported links on hover.',\r\n 1\r\n ],\r\n 'Embedding': [\r\n true,\r\n 'Embed supported services. Note: Some services don\\'t work on HTTPS.',\r\n 1\r\n ],\r\n 'Auto-embed': [\r\n false,\r\n 'Auto-embed Linkify Embeds.',\r\n 2\r\n ],\r\n 'Floating Embeds': [\r\n false,\r\n 'Embed content in a frame that remains in place when the page is scrolled.',\r\n 2\r\n ]\r\n },\r\n\r\n 'Filtering': {\r\n 'Anonymize': [\r\n false,\r\n 'Make everyone Anonymous.'\r\n ],\r\n 'Filter': [\r\n true,\r\n 'Self-moderation placebo.'\r\n ],\r\n 'Filtered Backlinks': [\r\n false,\r\n 'When enabled, shows backlinks to filtered posts with a line-through decoration. Otherwise, hides the backlinks.',\r\n 1\r\n ],\r\n 'Filter in Native Catalog': [\r\n true,\r\n 'Apply 4chan X filters in native catalog.',\r\n 1\r\n ],\r\n 'MD5 Quick Filter Notifications': [\r\n true,\r\n 'Show notification when quick filtering MD5s using the button or keybind.',\r\n 1\r\n ],\r\n 'Recursive Hiding': [\r\n true,\r\n 'Hide replies of hidden posts, recursively.'\r\n ],\r\n 'Thread Hiding Buttons': [\r\n true,\r\n 'Add buttons to hide entire threads.'\r\n ],\r\n 'Reply Hiding Buttons': [\r\n true,\r\n 'Add buttons to hide single replies.'\r\n ],\r\n 'Stubs': [\r\n true,\r\n 'Show stubs of hidden threads / replies.'\r\n ]\r\n },\r\n\r\n 'Images and Videos': {\r\n 'Image Expansion': [\r\n true,\r\n 'Expand images / videos.'\r\n ],\r\n 'Image Hover': [\r\n true,\r\n 'Show full image / video on mouseover.'\r\n ],\r\n 'Image Hover in Catalog': [\r\n true,\r\n `Show full image / video on mouseover in ${meta.name} catalog.`\r\n ],\r\n 'Gallery': [\r\n true,\r\n 'Adds a simple and cute image gallery. Has more options in the gallery menu.'\r\n ],\r\n 'Fullscreen Gallery': [\r\n false,\r\n 'Open gallery in fullscreen mode.',\r\n 1\r\n ],\r\n 'PDF in Gallery': [\r\n false,\r\n 'Show PDF files in gallery.',\r\n 1\r\n ],\r\n 'Sauce': [\r\n true,\r\n 'Add sauce links to images.'\r\n ],\r\n 'WEBM Metadata': [\r\n true,\r\n 'Add link to fetch title metadata from webm videos.'\r\n ],\r\n 'Reveal Spoiler Thumbnails': [\r\n false,\r\n 'Replace spoiler thumbnails with the original image.'\r\n ],\r\n 'Replace GIF': [\r\n false,\r\n 'Replace gif thumbnails with the actual image.'\r\n ],\r\n 'Replace JPG': [\r\n false,\r\n 'Replace jpg thumbnails with the actual image.'\r\n ],\r\n 'Replace PNG': [\r\n false,\r\n 'Replace png thumbnails with the actual image.'\r\n ],\r\n 'Replace WEBM': [\r\n false,\r\n 'Replace webm, mp4, and ogv thumbnails with the actual video. Probably will degrade browser performance ;)'\r\n ],\r\n 'Image Prefetching': [\r\n true,\r\n 'Add a shortcut icon to the header to turn on image preloading.'\r\n ],\r\n 'Fappe Tyme': [\r\n true,\r\n 'Hide posts without images when header menu item is checked. *hint* *hint*'\r\n ],\r\n 'Werk Tyme': [\r\n true,\r\n 'Hide all post images when header menu item is checked.'\r\n ],\r\n 'Autoplay': [\r\n true,\r\n 'Videos begin playing immediately when opened.'\r\n ],\r\n 'Restart when Opened': [\r\n false,\r\n 'Restart GIFs and WebMs when you hover over or expand them.'\r\n ],\r\n 'Show Controls': [\r\n true,\r\n 'Show controls on videos expanded inline.'\r\n ],\r\n 'Click Passthrough': [\r\n false,\r\n 'Clicks on videos trigger your browser\\'s default behavior. Videos can be contracted with button / dragging to the left.',\r\n 1\r\n ],\r\n 'Allow Sound': [\r\n true,\r\n 'Open videos with the sound unmuted.'\r\n ],\r\n 'Mouse Wheel Volume': [\r\n true,\r\n 'Adjust volume of videos with the mouse wheel over the thumbnail/filename/gallery.'\r\n ],\r\n 'Loop in New Tab': [\r\n true,\r\n 'Loop videos opened in their own tabs.'\r\n ],\r\n 'Volume in New Tab': [\r\n true,\r\n `Apply ${meta.name} mute and volume settings to videos opened in their own tabs.`\r\n ],\r\n 'Enable sound posts': [\r\n true,\r\n 'Enable loading audio from [sound=] file names. This audio is fetched from third parties.'\r\n ],\r\n },\r\n\r\n 'Menu': {\r\n 'Menu': [\r\n true,\r\n 'Add a drop-down menu to posts.'\r\n ],\r\n 'Report Link': [\r\n true,\r\n 'Add a report link to the menu.',\r\n 1\r\n ],\r\n 'Copy Text Link': [\r\n true,\r\n 'Add a link to copy the post\\'s text.',\r\n 1\r\n ],\r\n 'Thread Hiding Link': [\r\n true,\r\n 'Add a link to hide entire threads.',\r\n 1\r\n ],\r\n 'Reply Hiding Link': [\r\n true,\r\n 'Add a link to hide single replies.',\r\n 1\r\n ],\r\n 'Delete Link': [\r\n true,\r\n 'Add post and image deletion links to the menu.',\r\n 1\r\n ],\r\n 'Archive Link': [\r\n true,\r\n 'Add an archive link to the menu.',\r\n 1\r\n ],\r\n 'Edit Link': [\r\n true,\r\n 'Add a link to edit the image in Tegaki, /i/\\'s painting program. Requires Quick Reply.',\r\n 1\r\n ],\r\n 'Download Link': [\r\n false,\r\n 'Add a download with original filename link to the menu.',\r\n 1\r\n ]\r\n },\r\n\r\n 'Monitoring': {\r\n 'Thread Updater': [\r\n true,\r\n 'Fetch and insert new replies. Has more options in the header menu and the \"Advanced\" tab.'\r\n ],\r\n 'Unread Count': [\r\n true,\r\n 'Show the unread posts count in the tab title.'\r\n ],\r\n 'Quoted Title': [\r\n false,\r\n 'Change the page title to reflect you\\'ve been quoted.',\r\n 1\r\n ],\r\n 'Hide Unread Count at (0)': [\r\n false,\r\n 'Hide the unread posts count in the tab title when it reaches 0.',\r\n 1\r\n ],\r\n 'Unread Favicon': [\r\n true,\r\n 'Show a different favicon when there are unread posts.'\r\n ],\r\n 'Unread Line': [\r\n true,\r\n 'Show a line to distinguish read posts from unread ones.'\r\n ],\r\n 'Remember Last Read Post': [\r\n true,\r\n 'Remember how far you\\'ve read after you close the thread.'\r\n ],\r\n 'Scroll to Last Read Post': [\r\n true,\r\n 'Scroll back to the last read post when reopening a thread.',\r\n 1\r\n ],\r\n 'Unread Line in Index': [\r\n false,\r\n 'Show a line between read and unread posts in threads in the index.',\r\n 1\r\n ],\r\n 'Remove Thread Excerpt': [\r\n false,\r\n 'Replace the excerpt of the thread in the tab title with the board title.'\r\n ],\r\n 'Thread Stats': [\r\n true,\r\n 'Display reply and image count.'\r\n ],\r\n 'IP Count in Stats': [\r\n true,\r\n 'Display the unique IP count in the thread stats.',\r\n 1\r\n ],\r\n 'Page Count in Stats': [\r\n true,\r\n 'Display the page count in the thread stats.',\r\n 1\r\n ],\r\n 'Updater and Stats in Header': [\r\n true,\r\n 'Places the thread updater and thread stats in the header instead of floating them.'\r\n ],\r\n 'Thread Watcher': [\r\n true,\r\n 'Bookmark threads. Has more options in the thread watcher menu.'\r\n ],\r\n 'Fixed Thread Watcher': [\r\n true,\r\n 'Makes the thread watcher scroll with the page.',\r\n 1\r\n ],\r\n 'Persistent Thread Watcher': [\r\n false,\r\n 'The thread watcher will be visible when the page is loaded.',\r\n 1\r\n ],\r\n 'Mark New IPs': [\r\n false,\r\n 'Label each post from a new IP with the thread\\'s current IP count.'\r\n ],\r\n 'Reply Pruning': [\r\n true,\r\n 'Add option in header menu to hide old replies in long threads. Activated by default in stickies.'\r\n ],\r\n 'Prune All Threads': [\r\n false,\r\n 'Activate Reply Pruning by default in all threads.',\r\n 1\r\n ]\r\n },\r\n\r\n 'Posting and Captchas': {\r\n 'Quick Reply': [\r\n true,\r\n 'All-in-one form to reply, create threads, automate dumping and more.'\r\n ],\r\n 'Persistent QR': [\r\n false,\r\n 'The Quick reply won\\'t disappear after posting.',\r\n 1\r\n ],\r\n 'Auto Hide QR': [\r\n true,\r\n 'Automatically hide the quick reply when posting.',\r\n 2\r\n ],\r\n 'Open Post in New Tab': [\r\n true,\r\n 'Open new threads in a new tab, and open replies in a new tab if you\\'re not already in the thread.',\r\n 1\r\n ],\r\n 'Remember QR Size': [\r\n false,\r\n 'Remember the size of the Quick reply.',\r\n 1\r\n ],\r\n 'Remember Spoiler': [\r\n false,\r\n 'Remember the spoiler state, instead of resetting after posting.',\r\n 1\r\n ],\r\n 'Randomize Filename': [\r\n false,\r\n 'Set the filename to a random timestamp within the past year. Disabled on /f/.',\r\n 1\r\n ],\r\n 'Show New Thread Option in Threads': [\r\n true,\r\n 'Show the option to post a new / different thread from inside a thread.',\r\n 1\r\n ],\r\n 'Show Upload Progress': [\r\n true,\r\n 'Track progress of file uploads as percentage in submit button.',\r\n 1\r\n ],\r\n 'Cooldown': [\r\n true,\r\n 'Indicate the remaining time before posting again.',\r\n 1\r\n ],\r\n 'Posting Success Notifications': [\r\n true,\r\n 'Show notifications on successful post creation or file uploading.',\r\n 1\r\n ],\r\n 'Auto-load captcha': [\r\n false,\r\n 'Automatically load the captcha in the QR even if your post is empty.',\r\n 1\r\n ],\r\n 'Post on Captcha Completion': [\r\n false,\r\n 'Submit the post immediately when the captcha is completed.',\r\n 1\r\n ],\r\n 'Force Noscript Captcha': [\r\n false,\r\n 'Use the non-Javascript fallback captcha even if Javascript is enabled.'\r\n ],\r\n 'Pass Link': [\r\n false,\r\n 'Add a 4chan Pass login link to the bottom of the page.'\r\n ]\r\n },\r\n\r\n 'Quote Links': {\r\n 'Quote Backlinks': [\r\n true,\r\n 'Add quote backlinks.'\r\n ],\r\n 'OP Backlinks': [\r\n true,\r\n 'Add backlinks to the OP.',\r\n 1\r\n ],\r\n 'Bottom Backlinks': [\r\n false,\r\n 'Place backlinks at the bottom of posts.',\r\n 1\r\n ],\r\n 'Quote Inlining': [\r\n true,\r\n 'Inline quoted post on click.'\r\n ],\r\n 'Inline Cross-thread Quotes Only': [\r\n false,\r\n 'Don\\'t inline quote links when the posts are visible in the thread.',\r\n 1\r\n ],\r\n 'Quote Hash Navigation': [\r\n false,\r\n 'Include an extra link after quotes for autoscrolling to quoted posts.',\r\n 1\r\n ],\r\n 'Forward Hiding': [\r\n true,\r\n 'Hide original posts of inlined backlinks.',\r\n 1\r\n ],\r\n 'Quote Previewing': [\r\n true,\r\n 'Show quoted post on hover.'\r\n ],\r\n 'Quote Highlighting': [\r\n true,\r\n 'Highlight the previewed post.',\r\n 1\r\n ],\r\n 'Resurrect Quotes': [\r\n true,\r\n 'Link dead quotes to the archives, and support inlining/previewing of archive links like quote links.'\r\n ],\r\n 'Remember Your Posts': [\r\n true,\r\n 'Remember your posting history.'\r\n ],\r\n 'Mark Quotes of You': [\r\n true,\r\n 'Add \\'(You)\\' to quotes linking to your posts.',\r\n 1\r\n ],\r\n 'Highlight Posts Quoting You': [\r\n true,\r\n 'Highlights any posts that contain a quote to your post.',\r\n 1\r\n ],\r\n 'Highlight Own Posts': [\r\n true,\r\n 'Highlights own posts.',\r\n 1\r\n ],\r\n 'Mark OP Quotes': [\r\n true,\r\n 'Add \\'(OP)\\' to OP quotes.'\r\n ],\r\n 'Mark Cross-thread Quotes': [\r\n true,\r\n 'Add \\'(Cross-thread)\\' to cross-threads quotes.'\r\n ],\r\n 'Quote Threading': [\r\n true,\r\n 'Add option in header menu to thread conversations.'\r\n ]\r\n }\r\n },\r\n\r\n imageExpansion: {\r\n 'Fit width': [\r\n true,\r\n ''\r\n ],\r\n 'Fit height': [\r\n false,\r\n ''\r\n ],\r\n 'Scroll into view': [\r\n true,\r\n 'Scroll down when expanding images to bring the full image into view.'\r\n ],\r\n 'Expand spoilers': [\r\n true,\r\n 'Expand all images along with spoilers.'\r\n ],\r\n 'Expand videos': [\r\n true,\r\n 'Expand all images also expands videos.'\r\n ],\r\n 'Expand from here': [\r\n false,\r\n 'Expand all images only from current position to thread end.'\r\n ],\r\n 'Expand thread only': [\r\n false,\r\n 'In index, expand all images only within the current thread.'\r\n ],\r\n 'Advance on contract': [\r\n false,\r\n 'Advance to next post when contracting an expanded image.'\r\n ]\r\n },\r\n\r\n gallery: {\r\n 'Hide Thumbnails': [\r\n false\r\n ],\r\n 'Fit Width': [ // 'Fit width' (lowercase W) belongs to Image Expansion. Engine limitations, heh.\r\n true\r\n ],\r\n 'Fit Height': [\r\n true\r\n ],\r\n 'Stretch to Fit': [\r\n false\r\n ],\r\n 'Scroll to Post': [\r\n true\r\n ],\r\n 'Slide Delay': [\r\n 6.0\r\n ]\r\n },\r\n\r\n 'Default Volume': 1.0,\r\n\r\n threadWatcher: {\r\n 'Current Board': [\r\n false,\r\n 'Only show watched threads from the current board.'\r\n ],\r\n 'Auto Update Thread Watcher': [\r\n true,\r\n 'Periodically check status of watched threads.'\r\n ],\r\n 'Auto Watch': [\r\n true,\r\n 'Automatically watch threads you start.'\r\n ],\r\n 'Auto Watch Reply': [\r\n true,\r\n 'Automatically watch threads you reply to.'\r\n ],\r\n 'Auto Prune': [\r\n false,\r\n 'Automatically remove dead threads.'\r\n ],\r\n 'Show Page': [\r\n true,\r\n 'Show what page watched threads are on.'\r\n ],\r\n 'Show Unread Count': [\r\n true,\r\n 'Show number of unread posts in watched threads.'\r\n ],\r\n 'Show Site Prefix': [\r\n true,\r\n 'When multiple sites are shown in the thread watcher, add a prefix to board names to distinguish them.'\r\n ],\r\n 'Require OP Quote Link': [\r\n false,\r\n 'For purposes of thread watcher highlighting, only consider posts with a quote link to the OP as replies to the OP.'\r\n ]\r\n },\r\n\r\n filter: {\r\n general: '',\r\n\r\n postID: `\\\r\n# Highlight dubs on [s4s]:\r\n#/(\\\\d)\\\\1$/;highlight;top:no;boards:s4s\\\r\n`,\r\n\r\n name: `\\\r\n# Filter any namefags:\r\n#/^(?!Anonymous$)/\\\r\n`,\r\n\r\n uniqueID: `\\\r\n# Filter a specific ID:\r\n#/Txhvk1Tl/\\\r\n`,\r\n\r\n tripcode: `\\\r\n# Filter any tripfag\r\n#/^!/\\\r\n`,\r\n\r\n capcode: `\\\r\n# Set a custom class for mods:\r\n#/Mod$/;highlight:mod;op:yes\r\n# Set a custom class for admins:\r\n#/Admin$/;highlight:admin;op:yes\\\r\n`,\r\n\r\n pass: `\\\r\n# Filter anyone using since4pass:\r\n#/./\\\r\n`,\r\n\r\n email: '',\r\n\r\n subject: `\\\r\n# Filter Generals on /v/:\r\n#/general/i;boards:v;op:only\\\r\n`,\r\n\r\n comment: `\\\r\n# Filter Stallman copypasta on /g/:\r\n#/what you\\'re refer+ing to as linux/i;boards:g\r\n# Filter posts with 20 or more quote links:\r\n#/(?:>>\\\\d(?:(?!>>\\\\d)[^])*){20}/\r\n# Filter posts like T H I S / H / I / S:\r\n#/^>?\\\\s?\\\\w\\\\s?(\\\\w)\\\\s?(\\\\w)\\\\s?(\\\\w).*$[\\\\s>]+\\\\1[\\\\s>]+\\\\2[\\\\s>]+\\\\3/im\\\r\n`,\r\n\r\n flag: '',\r\n filename: '',\r\n dimensions: `\\\r\n# Highlight potential wallpapers:\r\n#/1920x1080/;op:yes;highlight;top:no;boards:w,wg\\\r\n`,\r\n\r\n filesize: '',\r\n\r\n MD5: ''\r\n },\r\n\r\n sauces: `\\\r\n# Known filename formats:\r\nhttps://www.pixiv.net/member_illust.php?mode=medium&illust_id=%$1;regexp:/^(\\\\d+)_p\\\\d+/\r\njavascript:void(open(\"https://www.deviantart.com/\"+%$1.replace(/_/g,\"-\")+\"/art/\"+parseInt(%$2,36)));regexp:/^\\\\w+_by_(\\\\w+)[_-]d([\\\\da-z]{6})\\\\b/\r\nhttps://imgur.com/%$1;regexp:/^(?![a-zA-Z][a-z]{6})(?![A-Z]{7})(?!\\\\d{7})([\\\\da-zA-Z]{7})(?: \\\\(\\\\d+\\\\))?\\\\.\\\\w+$/\r\nhttps://flickr.com/photo.gne?id=%$1;regexp:/^(\\\\d+)_[\\\\da-f]{10}(?:_\\\\w)*\\\\b/\r\nhttps://www.facebook.com/photo.php?fbid=%$1;regexp:/^\\\\d+_(\\\\d+)_\\\\d+_[no]\\\\b/\r\n\r\n# Reverse image search:\r\nhttps://www.google.com/searchbyimage?sbisrc=4chanx&image_url=%IMG&safe=off\r\nhttps://yandex.com/images/search?rpt=imageview&url=%IMG\r\n#//tineye.com/search?url=%IMG\r\n#//www.bing.com/images/search?q=imgurl:%IMG&view=detailv2&iss=sbi#enterInsights\r\n#https://lens.google.com/uploadbyurl?url=%IMG;text:lens\r\n\r\n# Specialized reverse image search:\r\n//iqdb.org/?url=%IMG\r\nhttps://trace.moe/?auto&url=%IMG;text:wait\r\n#//3d.iqdb.org/?url=%IMG\r\n#//saucenao.com/search.php?url=%IMG\r\n\r\n# \"View Same\" in archives:\r\nhttp://eye.swfchan.com/search/?q=%name;types:swf\r\n#https://desuarchive.org/_/search/image/%sMD5/\r\n#https://archive.4plebs.org/_/search/image/%sMD5/\r\n#https://boards.fireden.net/_/search/image/%sMD5/\r\n#https://foolz.fireden.net/_/search/image/%sMD5/\r\n\r\n# Other tools:\r\n#http://exif.regex.info/exif.cgi?imgurl=%URL\r\n#//imgops.com/start?url=%URL;types:gif,jpg,png\r\n#//www.gif-explode.com/%URL;types:gif\\\r\n`,\r\n\r\n FappeT: {\r\n werk: false\r\n },\r\n\r\n 'Custom CSS': true,\r\n\r\n Index: {\r\n 'Index Mode': 'paged',\r\n 'Previous Index Mode': 'paged',\r\n 'Index Size': 'small',\r\n 'Show Replies': [true, 'Show replies in the index, and also in the catalog if \"Catalog hover expand\" is checked.'],\r\n 'Catalog Hover Expand': [false, 'Expand the comment and show more details when you hover over a thread in the catalog.'],\r\n 'Catalog Hover Toggle': [true, 'Turn \"Catalog hover expand\" on and off by clicking in the catalog.'],\r\n 'Pin Watched Threads': [false, 'Move watched threads to the start of the index.'],\r\n 'Anchor Hidden Threads': [true, 'Move hidden threads to the end of the index.'],\r\n 'Refreshed Navigation': [false, 'Refresh index when navigating through pages.']\r\n },\r\n\r\n Header: {\r\n 'Fixed Header': true,\r\n 'Header auto-hide': false,\r\n 'Header auto-hide on scroll': false,\r\n 'Bottom Header': false,\r\n 'Centered links': false,\r\n 'Header catalog links': false,\r\n 'Bottom Board List': true,\r\n 'Shortcut Icons': true,\r\n 'Custom Board Navigation': true\r\n },\r\n\r\n archives: {\r\n archiveLists: 'https://4chenz.github.io/archives.json/archives.json',\r\n lastarchivecheck: 0,\r\n archiveAutoUpdate: true\r\n },\r\n\r\n externalCatalogURLs: `\\\r\n//catalog.neet.tv/%board/;boards:4chan.org:3,a,adv,an,asp,biz,c,cgl,ck,cm,co,diy,f,fa,fit,g,gd,his,i,int,jp,k,lgbt,lit,m,mlp,mu,n,news,o,out,p,po,pol,s4s,sci,sp,tg,toy,trv,tv,v,vg,vip,vp,vr,w,wg,wsg,wsr,x\\\r\n`,\r\n\r\n boardnav: `\\\r\n[ toggle-all ]\r\n[current-index-text:\"Index\"\r\ncurrent-catalog-text:\"Catalog\"\r\ncurrent-expired-text:\"Expired\"\r\ncurrent-archive-text:\"Archive\"]\r\n[external-text:\"FAQ\",\"${meta.name}\"]\\\r\n`,\r\n\r\n QR: {\r\n 'QR.personas': `\\\r\n#options:\"sage\";boards:jp;always\\\r\n`,\r\n sjisPreview: false\r\n },\r\n\r\n jsWhitelist: `\\\r\nhttp://s.4cdn.org\r\nhttps://s.4cdn.org\r\nhttp://www.google.com\r\nhttps://www.google.com\r\nhttps://www.gstatic.com\r\nhttp://cdn.mathjax.org\r\nhttps://cdn.mathjax.org\r\nhttps://cdnjs.cloudflare.com\r\nhttps://hcaptcha.com\r\nhttps://*.hcaptcha.com\r\n'self'\r\n'unsafe-inline'\r\n'unsafe-eval'\\\r\n`,\r\n\r\n captchaLanguage: '',\r\n\r\n time: '%m/%d/%y(%a)%H:%M:%S',\r\n timeLocale: '',\r\n\r\n backlink: '>>%id',\r\n\r\n pastedname: 'file',\r\n\r\n fileInfo: '%l %d (%p%s, %r%g)',\r\n\r\n favicon: 'ferongr',\r\n\r\n usercss: userCss,\r\n\r\n hotkeys: {\r\n // QR & Options\r\n 'Toggle board list': [\r\n 'Ctrl+b',\r\n 'Toggle the full board list.'\r\n ],\r\n 'Toggle header': [\r\n 'Shift+h',\r\n 'Toggle the auto-hide option of the header.'\r\n ],\r\n 'Open empty QR': [\r\n 'q',\r\n 'Open QR without post number inserted.'\r\n ],\r\n 'Open QR': [\r\n 'Shift+q',\r\n 'Open QR with post number inserted.'\r\n ],\r\n 'Open settings': [\r\n 'Alt+o',\r\n 'Open Settings.'\r\n ],\r\n 'Close': [\r\n 'Esc',\r\n 'Close dialogs or notifications.'\r\n ],\r\n 'Spoiler tags': [\r\n 'Ctrl+s',\r\n 'Insert spoiler tags.'\r\n ],\r\n 'Code tags': [\r\n 'Alt+c',\r\n 'Insert code tags.'\r\n ],\r\n 'Eqn tags': [\r\n 'Alt+e',\r\n 'Insert eqn tags.'\r\n ],\r\n 'Math tags': [\r\n 'Alt+m',\r\n 'Insert math tags.'\r\n ],\r\n 'SJIS tags': [\r\n 'Alt+a',\r\n 'Insert SJIS tags.'\r\n ],\r\n 'Toggle sage': [\r\n 'Alt+s',\r\n 'Toggle sage in options field.'\r\n ],\r\n 'Toggle Cooldown': [\r\n 'Alt+Comma',\r\n 'Toggle custom cooldown timer.'\r\n ],\r\n 'Post from URL': [\r\n 'Alt+l',\r\n 'Post from URL.'\r\n ],\r\n 'Add new post': [\r\n 'Alt+n',\r\n 'Add new post to the QR dump list.'\r\n ],\r\n 'Submit QR': [\r\n 'Ctrl+Enter',\r\n 'Submit post.'\r\n ],\r\n // Thread related\r\n 'Watch': [\r\n 'w',\r\n 'Watch thread.'\r\n ],\r\n 'Update': [\r\n 'r',\r\n 'Update the thread / refresh the index.'\r\n ],\r\n 'Update thread watcher': [\r\n 'Shift+r',\r\n 'Manually refresh thread watcher.'\r\n ],\r\n 'Toggle thread watcher': [\r\n 't',\r\n 'Toggle visibility of thread watcher.'\r\n ],\r\n 'Toggle threading': [\r\n 'Shift+t',\r\n 'Toggle threading.'\r\n ],\r\n 'Mark thread read': [\r\n 'Ctrl+0',\r\n 'Mark thread read from index (requires \"Unread Line in Index\").'\r\n ],\r\n // Images\r\n 'Expand image': [\r\n 'Shift+e',\r\n 'Expand selected image.'\r\n ],\r\n 'Expand images': [\r\n 'e',\r\n 'Expand all images.'\r\n ],\r\n 'Open Gallery': [\r\n 'g',\r\n 'Opens the gallery.'\r\n ],\r\n 'Next Gallery Image': [\r\n 'Right',\r\n 'Go to the next image in gallery mode.'\r\n ],\r\n 'Previous Gallery Image': [\r\n 'Left',\r\n 'Go to the previous image in gallery mode.'\r\n ],\r\n 'Advance Gallery': [\r\n 'Enter',\r\n 'Go to next image or, if Autoplay is off, play video.'\r\n ],\r\n 'Pause': [\r\n 'p',\r\n 'Pause/play videos in the gallery.'\r\n ],\r\n 'Slideshow': [\r\n 'Ctrl+Right',\r\n 'Toggle the gallery slideshow mode.'\r\n ],\r\n 'Rotate image clockwise': [\r\n 'Shift+Right',\r\n 'Rotate image clockwise in gallery.'\r\n ],\r\n 'Rotate image anticlockwise': [\r\n 'Shift+Left',\r\n 'Rotate image anticlockwise in gallery.'\r\n ],\r\n 'Download Gallery Image': [\r\n 'Shift+j',\r\n 'Download current image in gallery.'\r\n ],\r\n 'fappeTyme': [\r\n 'f',\r\n 'Toggle Fappe Tyme.'\r\n ],\r\n 'werkTyme': [\r\n 'Shift+w',\r\n 'Toggle Werk Tyme.'\r\n ],\r\n // Board Navigation\r\n 'Front page': [\r\n '1',\r\n 'Jump to front page.'\r\n ],\r\n 'Open front page': [\r\n 'Shift+1',\r\n 'Open front page in a new tab.'\r\n ],\r\n 'Next page': [\r\n 'Ctrl+Right',\r\n 'Jump to the next page.'\r\n ],\r\n 'Previous page': [\r\n 'Ctrl+Left',\r\n 'Jump to the previous page.'\r\n ],\r\n 'Paged mode': [\r\n 'Alt+1',\r\n 'Open the index in paged mode.'\r\n ],\r\n 'Infinite scrolling mode': [\r\n 'Alt+2',\r\n 'Open the index in infinite scrolling mode.'\r\n ],\r\n 'All pages mode': [\r\n 'Alt+3',\r\n 'Open the index in all threads mode.'\r\n ],\r\n 'Open catalog': [\r\n 'Shift+c',\r\n 'Open the catalog of the current board.'\r\n ],\r\n 'Search form': [\r\n 'Ctrl+Alt+s',\r\n 'Focus the search field on the board index.'\r\n ],\r\n 'Cycle sort type': [\r\n 'Alt+x',\r\n 'Cycle through index sort types.'\r\n ],\r\n // Thread Navigation\r\n 'Next thread': [\r\n 'Ctrl+Down',\r\n 'See next thread.'\r\n ],\r\n 'Previous thread': [\r\n 'Ctrl+Up',\r\n 'See previous thread.'\r\n ],\r\n 'Expand thread': [\r\n 'Ctrl+e',\r\n 'Expand thread.'\r\n ],\r\n 'Open thread': [\r\n 'o',\r\n 'Open thread in current tab.'\r\n ],\r\n 'Open thread tab': [\r\n 'Shift+o',\r\n 'Open thread in new tab.'\r\n ],\r\n // Reply Navigation\r\n 'Next reply': [\r\n 'j',\r\n 'Select next reply.'\r\n ],\r\n 'Previous reply': [\r\n 'k',\r\n 'Select previous reply.'\r\n ],\r\n 'Deselect reply': [\r\n 'Shift+d',\r\n 'Deselect reply.'\r\n ],\r\n 'Hide': [\r\n 'x',\r\n 'Hide thread.'\r\n ],\r\n 'Quick Filter MD5': [\r\n '5',\r\n 'Add the MD5 of the selected image to the filter list.'\r\n ],\r\n 'Previous Post Quoting You': [\r\n 'Alt+Up',\r\n 'Scroll to the previous post that quotes you.'\r\n ],\r\n 'Next Post Quoting You': [\r\n 'Alt+Down',\r\n 'Scroll to the next post that quotes you.'\r\n ]\r\n },\r\n\r\n updater: {\r\n checkbox: {\r\n 'Beep': [\r\n false,\r\n 'Beep on new post to completely read thread.'\r\n ],\r\n 'Beep Quoting You': [\r\n false,\r\n 'Beep on new post quoting you.'\r\n ],\r\n 'Auto Scroll': [\r\n false,\r\n 'Scroll updated posts into view. Only enabled at bottom of page.'\r\n ],\r\n 'Bottom Scroll': [\r\n false,\r\n 'Always scroll to the bottom, not the first new post. Useful for event threads.'\r\n ],\r\n 'Scroll BG': [\r\n false,\r\n 'Auto-scroll background tabs.'\r\n ],\r\n 'Auto Update': [\r\n true,\r\n 'Automatically fetch new posts.'\r\n ],\r\n 'Optional Increase': [\r\n false,\r\n 'Increase the intervals between updates on threads without new posts.'\r\n ]\r\n },\r\n 'Interval': 5\r\n },\r\n\r\n customCooldown: 0,\r\n customCooldownEnabled: true,\r\n\r\n 'Thread Quotes': false,\r\n\r\n 'Max Replies': 1000,\r\n\r\n 'Autohiding Scrollbar': false,\r\n\r\n position: {\r\n 'embedding.position': 'top: 50px; right: 0px;',\r\n 'thread-stats.position': 'bottom: 0px; right: 0px;',\r\n 'updater.position': 'bottom: 0px; left: 0px;',\r\n 'thread-watcher.position': 'top: 50px; left: 0px;',\r\n 'qr.position': 'top: 50px; right: 0px;'\r\n },\r\n\r\n fourchanImageHost: 'i.4cdn.org',\r\n\r\n hiddenPSAList: [{}],\r\n\r\n knownBanners: banners.join(','),\r\n\r\n passMessageClosed: false,\r\n\r\n 'Prerequest Captcha': false,\r\n\r\n 'PSAseen': [[]]\r\n};\r\nexport default Config;\r\n","import ferongr_unreadDead from './Favicon/ferongr.unreadDead.png';\r\nimport ferongr_unreadDeadY from './Favicon/ferongr.unreadDeadY.png';\r\nimport ferongr_unreadSFW from './Favicon/ferongr.unreadSFW.png';\r\nimport ferongr_unreadSFWY from './Favicon/ferongr.unreadSFWY.png';\r\nimport ferongr_unreadNSFW from './Favicon/ferongr.unreadNSFW.png';\r\nimport ferongr_unreadNSFWY from './Favicon/ferongr.unreadNSFWY.png';\r\nimport xat_unreadDead from './Favicon/xat-.unreadDead.png';\r\nimport xat_unreadDeadY from './Favicon/xat-.unreadDeadY.png';\r\nimport xat_unreadSFW from './Favicon/xat-.unreadSFW.png';\r\nimport xat_unreadSFWY from './Favicon/xat-.unreadSFWY.png';\r\nimport xat_unreadNSFW from './Favicon/xat-.unreadNSFW.png';\r\nimport xat_unreadNSFWY from './Favicon/xat-.unreadNSFWY.png';\r\nimport Mayhem_unreadDead from './Favicon/Mayhem.unreadDead.png';\r\nimport Mayhem_unreadDeadY from './Favicon/Mayhem.unreadDeadY.png';\r\nimport Mayhem_unreadSFW from './Favicon/Mayhem.unreadSFW.png';\r\nimport Mayhem_unreadSFWY from './Favicon/Mayhem.unreadSFWY.png';\r\nimport Mayhem_unreadNSFW from './Favicon/Mayhem.unreadNSFW.png';\r\nimport Mayhem_unreadNSFWY from './Favicon/Mayhem.unreadNSFWY.png';\r\nimport fourChanJS_unreadDead from './Favicon/4chanJS.unreadDead.png';\r\nimport fourChanJS_unreadDeadY from './Favicon/4chanJS.unreadDeadY.png';\r\nimport fourChanJS_unreadSFW from './Favicon/4chanJS.unreadSFW.png';\r\nimport fourChanJS_unreadSFWY from './Favicon/4chanJS.unreadSFWY.png';\r\nimport fourChanJS_unreadNSFW from './Favicon/4chanJS.unreadNSFW.png';\r\nimport fourChanJS_unreadNSFWY from './Favicon/4chanJS.unreadNSFWY.png';\r\nimport Original_unreadDead from './Favicon/Original.unreadDead.png';\r\nimport Original_unreadDeadY from './Favicon/Original.unreadDeadY.png';\r\nimport Original_unreadSFW from './Favicon/Original.unreadSFW.png';\r\nimport Original_unreadSFWY from './Favicon/Original.unreadSFWY.png';\r\nimport Original_unreadNSFW from './Favicon/Original.unreadNSFW.png';\r\nimport Original_unreadNSFWY from './Favicon/Original.unreadNSFWY.png';\r\nimport Metro_unreadDead from './Favicon/Metro.unreadDead.png';\r\nimport Metro_unreadDeadY from './Favicon/Metro.unreadDeadY.png';\r\nimport Metro_unreadSFW from './Favicon/Metro.unreadSFW.png';\r\nimport Metro_unreadSFWY from './Favicon/Metro.unreadSFWY.png';\r\nimport Metro_unreadNSFW from './Favicon/Metro.unreadNSFW.png';\r\nimport Metro_unreadNSFWY from './Favicon/Metro.unreadNSFWY.png';\r\nimport dead from './Favicon/dead.gif';\r\nimport empty from './Favicon/empty.gif';\r\nimport $ from '../platform/$';\r\nimport { Conf, d } from '../globals/globals';\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\n\r\nvar Favicon = {\r\n init() {\r\n return $.asap((() => d.head && (Favicon.el = $('link[rel=\"shortcut icon\"]', d.head))), Favicon.initAsap);\r\n },\r\n\r\n set(status) {\r\n Favicon.status = status;\r\n if (Favicon.el) {\r\n Favicon.el.href = Favicon[status];\r\n // `favicon.href = href` doesn't work on Firefox.\r\n return $.add(d.head, Favicon.el);\r\n }\r\n },\r\n\r\n initAsap() {\r\n Favicon.el.type = 'image/x-icon';\r\n const {href} = Favicon.el;\r\n Favicon.isSFW = /ws\\.ico$/.test(href);\r\n Favicon.default = href;\r\n Favicon.switch();\r\n if (Favicon.status) {\r\n return Favicon.set(Favicon.status);\r\n }\r\n },\r\n\r\n switch() {\r\n let items = {\r\n ferongr: [\r\n ferongr_unreadDead,\r\n ferongr_unreadDeadY,\r\n ferongr_unreadSFW,\r\n ferongr_unreadSFWY,\r\n ferongr_unreadNSFW,\r\n ferongr_unreadNSFWY,\r\n ],\r\n 'xat-': [\r\n xat_unreadDead,\r\n xat_unreadDeadY,\r\n xat_unreadSFW,\r\n xat_unreadSFWY,\r\n xat_unreadNSFW,\r\n xat_unreadNSFWY,\r\n ],\r\n Mayhem: [\r\n Mayhem_unreadDead,\r\n Mayhem_unreadDeadY,\r\n Mayhem_unreadSFW,\r\n Mayhem_unreadSFWY,\r\n Mayhem_unreadNSFW,\r\n Mayhem_unreadNSFWY,\r\n ],\r\n '4chanJS': [\r\n fourChanJS_unreadDead,\r\n fourChanJS_unreadDeadY,\r\n fourChanJS_unreadSFW,\r\n fourChanJS_unreadSFWY,\r\n fourChanJS_unreadNSFW,\r\n fourChanJS_unreadNSFWY,\r\n ],\r\n Original: [\r\n Original_unreadDead,\r\n Original_unreadDeadY,\r\n Original_unreadSFW,\r\n Original_unreadSFWY,\r\n Original_unreadNSFW,\r\n Original_unreadNSFWY,\r\n ],\r\n 'Metro': [\r\n Metro_unreadDead,\r\n Metro_unreadDeadY,\r\n Metro_unreadSFW,\r\n Metro_unreadSFWY,\r\n Metro_unreadNSFW,\r\n Metro_unreadNSFWY,\r\n ]\r\n };\r\n items = $.getOwn(items, Conf['favicon']);\r\n\r\n const f = Favicon;\r\n const t = 'data:image/png;base64,';\r\n let i = 0;\r\n while (items[i]) {\r\n items[i] = t + items[i++];\r\n }\r\n\r\n [f.unreadDead, f.unreadDeadY, f.unreadSFW, f.unreadSFWY, f.unreadNSFW, f.unreadNSFWY] = items;\r\n return f.update();\r\n },\r\n\r\n update() {\r\n if (this.isSFW) {\r\n this.unread = this.unreadSFW;\r\n return this.unreadY = this.unreadSFWY;\r\n } else {\r\n this.unread = this.unreadNSFW;\r\n return this.unreadY = this.unreadNSFWY;\r\n }\r\n },\r\n\r\n SFW: '//s.4cdn.org/image/favicon-ws.ico',\r\n NSFW: '//s.4cdn.org/image/favicon.ico',\r\n dead: `data:image/gif;base64,${dead}`,\r\n logo: `data:image/png;base64,${empty}`,\r\n};\r\nexport default Favicon;\r\n","import { d } from \"../globals/globals\";\r\n\r\nconst $$ = (selector, root = d.body) => Array.from(root.querySelectorAll(selector));\r\nexport default $$;\r\n","import { g, Conf, doc, d } from \"../globals/globals\";\r\nimport Main from \"../main/Main\";\r\nimport $ from \"../platform/$\";\r\nimport Captcha from \"./Captcha\";\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nconst CaptchaReplace = {\r\n init() {\r\n if ((g.SITE.software !== 'yotsuba') || (d.cookie.indexOf('pass_enabled=1') >= 0)) { return; }\r\n\r\n if (Conf['Force Noscript Captcha'] && Main.jsEnabled) {\r\n $.ready(Captcha.replace.noscript);\r\n return;\r\n }\r\n\r\n if (Conf['captchaLanguage'].trim()) {\r\n if (['boards.4chan.org', 'boards.4channel.org'].includes(location.hostname)) {\r\n return $.onExists(doc, '#captchaFormPart', node => $.onExists(node, 'iframe[src^=\"https://www.google.com/recaptcha/\"]', Captcha.replace.iframe));\r\n } else {\r\n return $.onExists(doc, 'iframe[src^=\"https://www.google.com/recaptcha/\"]', Captcha.replace.iframe);\r\n }\r\n }\r\n },\r\n\r\n noscript() {\r\n let noscript, original, toggle;\r\n if (!((original = $('#g-recaptcha')) && (noscript = $('noscript', original.parentNode)))) { return; }\r\n const span = $.el('span',\r\n {id: 'captcha-forced-noscript'});\r\n $.replace(noscript, span);\r\n $.rm(original);\r\n const insert = function() {\r\n span.innerHTML = noscript.textContent;\r\n return Captcha.replace.iframe($('iframe[src^=\"https://www.google.com/recaptcha/\"]', span));\r\n };\r\n if (toggle = $('#togglePostFormLink a, #form-link')) {\r\n return $.on(toggle, 'click', insert);\r\n } else {\r\n return insert();\r\n }\r\n },\r\n\r\n iframe(iframe) {\r\n let lang;\r\n if (lang = Conf['captchaLanguage'].trim()) {\r\n const src = /[?&]hl=/.test(iframe.src) ?\r\n iframe.src.replace(/([?&]hl=)[^&]*/, '$1' + encodeURIComponent(lang))\r\n :\r\n iframe.src + `&hl=${encodeURIComponent(lang)}`;\r\n if (iframe.src !== src) { iframe.src = src; }\r\n }\r\n }\r\n};\r\nexport default CaptchaReplace;\r\n","import { d, g } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\nimport QR from \"./QR\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nconst CaptchaT = {\r\n init() {\r\n if (d.cookie.indexOf('pass_enabled=1') >= 0) { return; }\r\n if (!(this.isEnabled = !!$('#t-root') || !$.id('postForm'))) { return; }\r\n\r\n const root = $.el('div', {className: 'captcha-root'});\r\n this.nodes = {root};\r\n\r\n $.addClass(QR.nodes.el, 'has-captcha', 'captcha-t');\r\n return $.after(QR.nodes.com.parentNode, root);\r\n },\r\n\r\n moreNeeded() {\r\n },\r\n\r\n getThread() {\r\n let threadID;\r\n const boardID = g.BOARD.ID;\r\n if (QR.posts[0].thread === 'new') {\r\n threadID = '0';\r\n } else {\r\n threadID = '' + QR.posts[0].thread;\r\n }\r\n return {boardID, threadID};\r\n },\r\n\r\n setup(focus) {\r\n if (!this.isEnabled) { return; }\r\n\r\n if (!this.nodes.container) {\r\n this.nodes.container = $.el('div', {className: 'captcha-container'});\r\n $.prepend(this.nodes.root, this.nodes.container);\r\n CaptchaT.currentThread = CaptchaT.getThread();\r\n $.global(function() {\r\n const el = document.querySelector('#qr .captcha-container');\r\n window.TCaptcha.init(el, this.boardID, +this.threadID);\r\n return window.TCaptcha.setErrorCb(err => window.dispatchEvent(new CustomEvent('CreateNotification', {detail: {\r\n type: 'warning',\r\n content: '' + err\r\n }})\r\n ));\r\n }\r\n , CaptchaT.currentThread);\r\n }\r\n\r\n if (focus) {\r\n return $('#t-resp').focus();\r\n }\r\n },\r\n\r\n destroy() {\r\n if (!this.isEnabled || !this.nodes.container) { return; }\r\n $.global(() => window.TCaptcha.destroy());\r\n $.rm(this.nodes.container);\r\n return delete this.nodes.container;\r\n },\r\n\r\n updateThread() {\r\n if (!this.isEnabled) { return; }\r\n const {boardID, threadID} = (CaptchaT.currentThread || {});\r\n const newThread = CaptchaT.getThread();\r\n if ((newThread.boardID !== boardID) || (newThread.threadID !== threadID)) {\r\n CaptchaT.destroy();\r\n return CaptchaT.setup();\r\n }\r\n },\r\n\r\n getOne() {\r\n let el;\r\n let response = {};\r\n if (this.nodes.container) {\r\n for (var key of ['t-response', 't-challenge']) {\r\n response[key] = $(`[name='${key}']`, this.nodes.container).value;\r\n }\r\n }\r\n if (!response['t-response'] && !((el = $('#t-msg')) && /Verification not required/i.test(el.textContent))) {\r\n response = null;\r\n }\r\n return response;\r\n },\r\n\r\n setUsed() {\r\n if (!this.isEnabled) { return; }\r\n if (this.nodes.container) {\r\n return $.global(() => window.TCaptcha.clearChallenge());\r\n }\r\n },\r\n\r\n occupied() {\r\n return !!this.nodes.container;\r\n }\r\n};\r\nexport default CaptchaT;\r\n",null,"import { Conf, d, g } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\nimport { dict, HOUR } from \"../platform/helpers\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS104: Avoid inline assignments\r\n * DS206: Consider reworking classes to avoid initClass\r\n * DS207: Consider shorter variations of null checks\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nexport default class DataBoard {\r\n static initClass() {\r\n this.keys = ['hiddenThreads', 'hiddenPosts', 'lastReadPosts', 'yourPosts', 'watchedThreads', 'watcherLastModified', 'customTitles'];\r\n }\r\n\r\n constructor(key, sync, dontClean) {\r\n this.changes = [];\r\n this.onSync = this.onSync.bind(this);\r\n this.key = key;\r\n this.initData(Conf[this.key]);\r\n $.sync(this.key, this.onSync);\r\n if (!dontClean) { this.clean(); }\r\n if (!sync) { return; }\r\n // Chrome also fires the onChanged callback on the current tab,\r\n // so we only start syncing when we're ready.\r\n var init = () => {\r\n $.off(d, '4chanXInitFinished', init);\r\n return this.sync = sync;\r\n };\r\n $.on(d, '4chanXInitFinished', init);\r\n }\r\n\r\n initData(data) {\r\n let boards;\r\n this.data = data;\r\n if (this.data.boards) {\r\n let lastChecked;\r\n ({boards, lastChecked} = this.data);\r\n this.data['4chan.org'] = {boards, lastChecked};\r\n delete this.data.boards;\r\n delete this.data.lastChecked;\r\n }\r\n return this.data[g.SITE.ID] || (this.data[g.SITE.ID] = { boards: dict() });\r\n }\r\n\r\n save(change, cb) {\r\n change();\r\n this.changes.push(change);\r\n return $.get(this.key, { boards: dict() }, items => {\r\n if (!this.changes.length) { return; }\r\n const needSync = ((items[this.key].version || 0) > (this.data.version || 0));\r\n if (needSync) {\r\n this.initData(items[this.key]);\r\n for (change of this.changes) { change(); }\r\n }\r\n this.changes = [];\r\n this.data.version = (this.data.version || 0) + 1;\r\n return $.set(this.key, this.data, () => {\r\n if (needSync) { this.sync?.(); }\r\n return cb?.();\r\n });\r\n });\r\n }\r\n\r\n forceSync(cb) {\r\n return $.get(this.key, { boards: dict() }, items => {\r\n if ((items[this.key].version || 0) > (this.data.version || 0)) {\r\n this.initData(items[this.key]);\r\n for (var change of this.changes) { change(); }\r\n this.sync?.();\r\n }\r\n return cb?.();\r\n });\r\n }\r\n\r\n delete({siteID, boardID, threadID, postID}, cb) {\r\n if (!siteID) { siteID = g.SITE.ID; }\r\n if (!this.data[siteID]) { return; }\r\n return this.save(() => {\r\n if (postID) {\r\n if (!this.data[siteID].boards[boardID]?.[threadID]) { return; }\r\n delete this.data[siteID].boards[boardID][threadID][postID];\r\n return this.deleteIfEmpty({siteID, boardID, threadID});\r\n } else if (threadID) {\r\n if (!this.data[siteID].boards[boardID]) { return; }\r\n delete this.data[siteID].boards[boardID][threadID];\r\n return this.deleteIfEmpty({siteID, boardID});\r\n } else {\r\n return delete this.data[siteID].boards[boardID];\r\n }\r\n }\r\n , cb);\r\n }\r\n\r\n deleteIfEmpty({siteID, boardID, threadID}) {\r\n if (!this.data[siteID]) { return; }\r\n if (threadID) {\r\n if (!Object.keys(this.data[siteID].boards[boardID][threadID]).length) {\r\n delete this.data[siteID].boards[boardID][threadID];\r\n return this.deleteIfEmpty({siteID, boardID});\r\n }\r\n } else if (!Object.keys(this.data[siteID].boards[boardID]).length) {\r\n return delete this.data[siteID].boards[boardID];\r\n }\r\n }\r\n\r\n set(data, cb) {\r\n return this.save(() => {\r\n return this.setUnsafe(data);\r\n }\r\n , cb);\r\n }\r\n\r\n setUnsafe({siteID, boardID, threadID, postID, val}) {\r\n if (!siteID) { siteID = g.SITE.ID; }\r\n if (!this.data[siteID]) { this.data[siteID] = { boards: dict() }; }\r\n if (postID !== undefined) {\r\n let base;\r\n return (((base = this.data[siteID].boards[boardID] || (this.data[siteID].boards[boardID] = dict())))[threadID] || (base[threadID] = dict()))[postID] = val;\r\n } else if (threadID !== undefined) {\r\n return (this.data[siteID].boards[boardID] || (this.data[siteID].boards[boardID] = dict()))[threadID] = val;\r\n } else {\r\n return this.data[siteID].boards[boardID] = val;\r\n }\r\n }\r\n\r\n extend({siteID, boardID, threadID, postID, val}, cb) {\r\n return this.save(() => {\r\n const oldVal = this.get({ siteID, boardID, threadID, postID, defaultValue: dict() });\r\n for (var key in val) {\r\n var subVal = val[key];\r\n if (typeof subVal === 'undefined') {\r\n delete oldVal[key];\r\n } else {\r\n oldVal[key] = subVal;\r\n }\r\n }\r\n return this.setUnsafe({siteID, boardID, threadID, postID, val: oldVal});\r\n }\r\n , cb);\r\n }\r\n\r\n setLastChecked(key='lastChecked') {\r\n return this.save(() => {\r\n return this.data[key] = Date.now();\r\n });\r\n }\r\n\r\n get({siteID, boardID, threadID, postID, defaultValue}) {\r\n let board, val;\r\n if (!siteID) { siteID = g.SITE.ID; }\r\n if (board = this.data[siteID]?.boards[boardID]) {\r\n let thread;\r\n if (threadID == null) {\r\n if (postID != null) {\r\n for (thread = 0; thread < board.length; thread++) {\r\n var ID = board[thread];\r\n if (postID in thread) {\r\n val = thread[postID];\r\n break;\r\n }\r\n }\r\n } else {\r\n val = board;\r\n }\r\n } else if (thread = board[threadID]) {\r\n val = (postID != null) ?\r\n thread[postID]\r\n :\r\n thread;\r\n }\r\n }\r\n return val || defaultValue;\r\n }\r\n\r\n clean() {\r\n let boardID, middle;\r\n const siteID = g.SITE.ID;\r\n for (boardID in this.data[siteID].boards) {\r\n var val = this.data[siteID].boards[boardID];\r\n this.deleteIfEmpty({siteID, boardID});\r\n }\r\n const now = Date.now();\r\n if (now - (2 * HOUR) >= ((middle = this.data[siteID].lastChecked || 0)) || middle > now) {\r\n this.data[siteID].lastChecked = now;\r\n for (boardID in this.data[siteID].boards) {\r\n this.ajaxClean(boardID);\r\n }\r\n }\r\n }\r\n\r\n ajaxClean(boardID) {\r\n const that = this;\r\n const siteID = g.SITE.ID;\r\n const threadsList = g.SITE.urls.threadsListJSON?.({siteID, boardID});\r\n if (!threadsList) { return; }\r\n return $.cache(threadsList, function() {\r\n if (this.status !== 200) { return; }\r\n const archiveList = g.SITE.urls.archiveListJSON?.({siteID, boardID});\r\n if (!archiveList) { return that.ajaxCleanParse(boardID, this.response); }\r\n const response1 = this.response;\r\n return $.cache(archiveList, function() {\r\n if ((this.status !== 200) && (!!g.SITE.archivedBoardsKnown || (this.status !== 404))) { return; }\r\n return that.ajaxCleanParse(boardID, response1, this.response);\r\n });\r\n });\r\n }\r\n\r\n ajaxCleanParse(boardID, response1, response2) {\r\n let board, ID;\r\n const siteID = g.SITE.ID;\r\n if (!(board = this.data[siteID].boards[boardID])) { return; }\r\n const threads = dict();\r\n if (response1) {\r\n for (var page of response1) {\r\n for (var thread of page.threads) {\r\n ID = thread.no;\r\n if (ID in board) { threads[ID] = board[ID]; }\r\n }\r\n }\r\n }\r\n if (response2) {\r\n for (ID of response2) {\r\n if (ID in board) { threads[ID] = board[ID]; }\r\n }\r\n }\r\n this.data[siteID].boards[boardID] = threads;\r\n this.deleteIfEmpty({siteID, boardID});\r\n return $.set(this.key, this.data);\r\n }\r\n\r\n onSync(data) {\r\n if ((data.version || 0) <= (this.data.version || 0)) { return; }\r\n this.initData(data);\r\n return this.sync?.();\r\n }\r\n}\r\nDataBoard.initClass();\r\n",null,null,"import $ from \"../platform/$\";\r\n\r\nexport default class CatalogThread {\r\n toString() { return this.ID; }\r\n\r\n constructor(root, thread) {\r\n this.thread = thread;\r\n this.ID = this.thread.ID;\r\n this.board = this.thread.board;\r\n const {post} = this.thread.OP.nodes;\r\n this.nodes = {\r\n root,\r\n thumb: $('.catalog-thumb', post),\r\n icons: $('.catalog-icons', post),\r\n postCount: $('.post-count', post),\r\n fileCount: $('.file-count', post),\r\n pageCount: $('.page-count', post),\r\n replies: null\r\n };\r\n this.thread.catalogView = this;\r\n }\r\n}\r\n","import { Conf, d, doc } from \"../globals/globals\";\r\nimport Main from \"../main/Main\";\r\nimport $ from \"../platform/$\";\r\nimport $$ from \"../platform/$$\";\r\nimport Header from \"./Header\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS206: Consider reworking classes to avoid initClass\r\n * DS207: Consider shorter variations of null checks\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nconst dialog = function(id, properties) {\r\n const el = $.el('div', {\r\n className: 'dialog',\r\n id\r\n }\r\n );\r\n $.extend(el, properties);\r\n el.style.cssText = Conf[`${id}.position`];\r\n\r\n const move = $('.move', el);\r\n $.on(move, 'touchstart mousedown', dragstart);\r\n for (var child of move.children) {\r\n if (!child.tagName) { continue; }\r\n $.on(child, 'touchstart mousedown', e => e.stopPropagation());\r\n }\r\n\r\n return el;\r\n};\r\n\r\nvar Menu = (function() {\r\n let currentMenu = undefined;\r\n let lastToggledButton = undefined;\r\n Menu = class Menu {\r\n static initClass() {\r\n currentMenu = null;\r\n lastToggledButton = null;\r\n }\r\n\r\n constructor(type) {\r\n // XXX AddMenuEntry event is deprecated\r\n this.setPosition = this.setPosition.bind(this);\r\n this.close = this.close.bind(this);\r\n this.keybinds = this.keybinds.bind(this);\r\n this.onFocus = this.onFocus.bind(this);\r\n this.addEntry = this.addEntry.bind(this);\r\n this.type = type;\r\n $.on(d, 'AddMenuEntry', ({detail}) => {\r\n if (detail.type !== this.type) { return; }\r\n delete detail.open;\r\n return this.addEntry(detail);\r\n });\r\n this.entries = [];\r\n }\r\n\r\n makeMenu() {\r\n const menu = $.el('div', {\r\n className: 'dialog',\r\n id: 'menu',\r\n tabIndex: 0\r\n }\r\n );\r\n menu.dataset.type = this.type;\r\n $.on(menu, 'click', e => e.stopPropagation());\r\n $.on(menu, 'keydown', this.keybinds);\r\n return menu;\r\n }\r\n\r\n toggle(e, button, data) {\r\n e.preventDefault();\r\n e.stopPropagation();\r\n\r\n if (currentMenu) {\r\n // Close if it's already opened.\r\n // Reopen if we clicked on another button.\r\n const previousButton = lastToggledButton;\r\n currentMenu.close();\r\n if (previousButton === button) { return; }\r\n }\r\n\r\n if (!this.entries.length) { return; }\r\n return this.open(button, data);\r\n }\r\n\r\n open(button, data) {\r\n let entry;\r\n const menu = (this.menu = this.makeMenu());\r\n currentMenu = this;\r\n lastToggledButton = button;\r\n\r\n this.entries.sort((first, second) => first.order - second.order);\r\n\r\n for (entry of this.entries) {\r\n this.insertEntry(entry, menu, data);\r\n }\r\n\r\n $.addClass(lastToggledButton, 'active');\r\n\r\n $.on(d, 'click CloseMenu', this.close);\r\n $.on(d, 'scroll', this.setPosition);\r\n $.on(window, 'resize', this.setPosition);\r\n $.after(button, menu);\r\n\r\n this.setPosition();\r\n\r\n entry = $('.entry', menu);\r\n // We've removed flexbox, so we don't use order anymore.\r\n // while prevEntry = @findNextEntry entry, -1\r\n // entry = prevEntry\r\n this.focus(entry);\r\n\r\n return menu.focus();\r\n }\r\n\r\n setPosition() {\r\n const mRect = this.menu.getBoundingClientRect();\r\n const bRect = lastToggledButton.getBoundingClientRect();\r\n const bTop = window.scrollY + bRect.top;\r\n const bLeft = window.scrollX + bRect.left;\r\n const cHeight = doc.clientHeight;\r\n const cWidth = doc.clientWidth;\r\n const [top, bottom] = (bRect.top + bRect.height + mRect.height) < cHeight ?\r\n [`${bRect.bottom}px`, '']\r\n :\r\n ['', `${cHeight - bRect.top}px`];\r\n const [left, right] = (bRect.left + mRect.width) < cWidth ?\r\n [`${bRect.left}px`, '']\r\n :\r\n ['', `${cWidth - bRect.right}px`];\r\n $.extend(this.menu.style, {top, right, bottom, left});\r\n return this.menu.classList.toggle('left', right);\r\n }\r\n\r\n insertEntry(entry, parent, data) {\r\n let submenu;\r\n if (typeof entry.open === 'function') {\r\n try {\r\n if (!entry.open(data)) { return; }\r\n } catch (err) {\r\n Main.handleErrors({\r\n message: `Error in building the ${this.type} menu.`,\r\n error: err\r\n });\r\n return;\r\n }\r\n }\r\n $.add(parent, entry.el);\r\n\r\n if (!entry.subEntries) { return; }\r\n if (submenu = $('.submenu', entry.el)) {\r\n // Reset sub menu, remove irrelevant entries.\r\n $.rm(submenu);\r\n }\r\n submenu = $.el('div',\r\n {className: 'dialog submenu'});\r\n for (var subEntry of entry.subEntries) {\r\n this.insertEntry(subEntry, submenu, data);\r\n }\r\n $.add(entry.el, submenu);\r\n }\r\n\r\n close() {\r\n $.rm(this.menu);\r\n delete this.menu;\r\n $.rmClass(lastToggledButton, 'active');\r\n currentMenu = null;\r\n lastToggledButton = null;\r\n $.off(d, 'click scroll CloseMenu', this.close);\r\n $.off(d, 'scroll', this.setPosition);\r\n return $.off(window, 'resize', this.setPosition);\r\n }\r\n\r\n findNextEntry(entry, direction) {\r\n const entries = [...entry.parentNode.children];\r\n entries.sort((first, second) => first.style.order - second.style.order);\r\n return entries[entries.indexOf(entry) + direction];\r\n }\r\n\r\n keybinds(e) {\r\n let subEntry;\r\n let next, submenu;\r\n let entry = $('.focused', this.menu);\r\n while ((subEntry = $('.focused', entry))) {\r\n entry = subEntry;\r\n }\r\n\r\n switch (e.keyCode) {\r\n case 27: // Esc\r\n lastToggledButton.focus();\r\n this.close();\r\n break;\r\n case 13: case 32: // Enter, Space\r\n entry.click();\r\n break;\r\n case 38: // Up\r\n if (next = this.findNextEntry(entry, -1)) {\r\n this.focus(next);\r\n }\r\n break;\r\n case 40: // Down\r\n if (next = this.findNextEntry(entry, +1)) {\r\n this.focus(next);\r\n }\r\n break;\r\n case 39: // Right\r\n if ((submenu = $('.submenu', entry)) && (next = submenu.firstElementChild)) {\r\n let nextPrev;\r\n while ((nextPrev = this.findNextEntry(next, -1))) {\r\n next = nextPrev;\r\n }\r\n this.focus(next);\r\n }\r\n break;\r\n case 37: // Left\r\n if (next = $.x('parent::*[contains(@class,\"submenu\")]/parent::*', entry)) {\r\n this.focus(next);\r\n }\r\n break;\r\n default:\r\n return;\r\n }\r\n\r\n e.preventDefault();\r\n return e.stopPropagation();\r\n }\r\n\r\n onFocus(e) {\r\n e.stopPropagation();\r\n return this.focus(e.target);\r\n }\r\n\r\n focus(entry) {\r\n let focused, submenu;\r\n while ((focused = $.x('parent::*/child::*[contains(@class,\"focused\")]', entry))) {\r\n $.rmClass(focused, 'focused');\r\n }\r\n for (focused of $$('.focused', entry)) {\r\n $.rmClass(focused, 'focused');\r\n }\r\n $.addClass(entry, 'focused');\r\n\r\n // Submenu positioning.\r\n if (!(submenu = $('.submenu', entry))) { return; }\r\n const sRect = submenu.getBoundingClientRect();\r\n const eRect = entry.getBoundingClientRect();\r\n const cHeight = doc.clientHeight;\r\n const cWidth = doc.clientWidth;\r\n const [top, bottom] = (eRect.top + sRect.height) < cHeight ?\r\n ['0px', 'auto']\r\n :\r\n ['auto', '0px'];\r\n const [left, right] = (eRect.right + sRect.width) < (cWidth - 150) ?\r\n ['100%', 'auto']\r\n :\r\n ['auto', '100%'];\r\n const {style} = submenu;\r\n style.top = top;\r\n style.bottom = bottom;\r\n style.left = left;\r\n return style.right = right;\r\n }\r\n\r\n addEntry(entry) {\r\n this.parseEntry(entry);\r\n return this.entries.push(entry);\r\n }\r\n\r\n parseEntry(entry) {\r\n const {el, subEntries} = entry;\r\n $.addClass(el, 'entry');\r\n $.on(el, 'focus mouseover', this.onFocus);\r\n el.style.order = entry.order || 100;\r\n if (!subEntries) { return; }\r\n $.addClass(el, 'has-submenu');\r\n for (var subEntry of subEntries) {\r\n this.parseEntry(subEntry);\r\n }\r\n }\r\n };\r\n Menu.initClass();\r\n return Menu;\r\n})();\r\n\r\nexport var dragstart = function (e) {\r\n let isTouching;\r\n if ((e.type === 'mousedown') && (e.button !== 0)) { return; } // not LMB\r\n // prevent text selection\r\n e.preventDefault();\r\n if (isTouching = e.type === 'touchstart') {\r\n e = e.changedTouches[e.changedTouches.length - 1];\r\n }\r\n // distance from pointer to el edge is constant; calculate it here.\r\n const el = $.x('ancestor::div[contains(@class,\"dialog\")][1]', this);\r\n const rect = el.getBoundingClientRect();\r\n const screenHeight = doc.clientHeight;\r\n const screenWidth = doc.clientWidth;\r\n const o = {\r\n id: el.id,\r\n style: el.style,\r\n dx: e.clientX - rect.left,\r\n dy: e.clientY - rect.top,\r\n height: screenHeight - rect.height,\r\n width: screenWidth - rect.width,\r\n screenHeight,\r\n screenWidth,\r\n isTouching\r\n };\r\n\r\n [o.topBorder, o.bottomBorder] = Conf['Header auto-hide'] || !Conf['Fixed Header'] ?\r\n [0, 0]\r\n : Conf['Bottom Header'] ?\r\n [0, Header.bar.getBoundingClientRect().height]\r\n :\r\n [Header.bar.getBoundingClientRect().height, 0];\r\n\r\n if (isTouching) {\r\n o.identifier = e.identifier;\r\n o.move = touchmove.bind(o);\r\n o.up = touchend.bind(o);\r\n $.on(d, 'touchmove', o.move);\r\n return $.on(d, 'touchend touchcancel', o.up);\r\n } else { // mousedown\r\n o.move = drag.bind(o);\r\n o.up = dragend.bind(o);\r\n $.on(d, 'mousemove', o.move);\r\n return $.on(d, 'mouseup', o.up);\r\n }\r\n};\r\n\r\nexport var touchmove = function (e) {\r\n for (var touch of e.changedTouches) {\r\n if (touch.identifier === this.identifier) {\r\n drag.call(this, touch);\r\n return;\r\n }\r\n }\r\n};\r\n\r\nexport var drag = function (e) {\r\n const {clientX, clientY} = e;\r\n\r\n let left = clientX - this.dx;\r\n left = left < 10 ?\r\n 0\r\n : (this.width - left) < 10 ?\r\n ''\r\n :\r\n ((left / this.screenWidth) * 100) + '%';\r\n\r\n let top = clientY - this.dy;\r\n top = top < (10 + this.topBorder) ?\r\n this.topBorder + 'px'\r\n : (this.height - top) < (10 + this.bottomBorder) ?\r\n ''\r\n :\r\n ((top / this.screenHeight) * 100) + '%';\r\n\r\n const right = left === '' ?\r\n 0\r\n :\r\n '';\r\n\r\n const bottom = top === '' ?\r\n this.bottomBorder + 'px'\r\n :\r\n '';\r\n\r\n const {style} = this;\r\n style.left = left;\r\n style.right = right;\r\n style.top = top;\r\n return style.bottom = bottom;\r\n};\r\n\r\nexport var touchend = function (e) {\r\n for (var touch of e.changedTouches) {\r\n if (touch.identifier === this.identifier) {\r\n dragend.call(this);\r\n return;\r\n }\r\n }\r\n};\r\n\r\nexport var dragend = function () {\r\n if (this.isTouching) {\r\n $.off(d, 'touchmove', this.move);\r\n $.off(d, 'touchend touchcancel', this.up);\r\n } else { // mouseup\r\n $.off(d, 'mousemove', this.move);\r\n $.off(d, 'mouseup', this.up);\r\n }\r\n return $.set(`${this.id}.position`, this.style.cssText);\r\n};\r\n\r\nconst hoverstart = function ({ root, el, latestEvent, endEvents, height, width, cb, noRemove }) {\r\n const rect = root.getBoundingClientRect();\r\n const o = {\r\n root,\r\n el,\r\n style: el.style,\r\n isImage: ['IMG', 'VIDEO'].includes(el.nodeName),\r\n cb,\r\n endEvents,\r\n latestEvent,\r\n clientHeight: doc.clientHeight,\r\n clientWidth: doc.clientWidth,\r\n height,\r\n width,\r\n noRemove,\r\n clientX: (rect.left + rect.right) / 2,\r\n clientY: (rect.top + rect.bottom) / 2\r\n };\r\n o.hover = hover.bind(o);\r\n o.hoverend = hoverend.bind(o);\r\n\r\n o.hover(o.latestEvent);\r\n new MutationObserver(function() {\r\n if (el.parentNode) { return o.hover(o.latestEvent); }\r\n }).observe(el, {childList: true});\r\n\r\n $.on(root, endEvents, o.hoverend);\r\n if ($.x('ancestor::div[contains(@class,\"inline\")][1]', root)) {\r\n $.on(d, 'keydown', o.hoverend);\r\n }\r\n $.on(root, 'mousemove', o.hover);\r\n\r\n // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=674955\r\n o.workaround = function(e) { if (!root.contains(e.target)) { return o.hoverend(e); } };\r\n return $.on(doc, 'mousemove', o.workaround);\r\n};\r\n\r\nhoverstart.padding = 25;\r\n\r\nexport var hover = function (e) {\r\n this.latestEvent = e;\r\n const height = (this.height || this.el.offsetHeight) + hoverstart.padding;\r\n const width = (this.width || this.el.offsetWidth);\r\n const {clientX, clientY} = Conf['Follow Cursor'] ? e : this;\r\n\r\n const top = this.isImage ?\r\n Math.max(0, (clientY * (this.clientHeight - height)) / this.clientHeight)\r\n :\r\n Math.max(0, Math.min(this.clientHeight - height, clientY - 120));\r\n\r\n let threshold = this.clientWidth / 2;\r\n if (!this.isImage) { threshold = Math.max(threshold, this.clientWidth - 400); }\r\n let marginX = (clientX <= threshold ? clientX : this.clientWidth - clientX) + 45;\r\n if (this.isImage) { marginX = Math.min(marginX, this.clientWidth - width); }\r\n marginX += 'px';\r\n const [left, right] = clientX <= threshold ? [marginX, ''] : ['', marginX];\r\n\r\n const {style} = this;\r\n style.top = top + 'px';\r\n style.left = left;\r\n return style.right = right;\r\n};\r\n\r\nexport var hoverend = function (e) {\r\n if (((e.type === 'keydown') && (e.keyCode !== 13)) || (e.target.nodeName === \"TEXTAREA\")) { return; }\r\n if (!this.noRemove) { $.rm(this.el); }\r\n $.off(this.root, this.endEvents, this.hoverend);\r\n $.off(d, 'keydown', this.hoverend);\r\n $.off(this.root, 'mousemove', this.hover);\r\n // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=674955\r\n $.off(doc, 'mousemove', this.workaround);\r\n if (this.cb) { return this.cb.call(this); }\r\n};\r\n\r\nexport const checkbox = function (name, text, checked) {\r\n if (checked == null) { checked = Conf[name]; }\r\n const label = $.el('label');\r\n const input = $.el('input', {type: 'checkbox', name, checked});\r\n $.add(label, [input, $.tn(` ${text}`)]);\r\n return label;\r\n};\r\n\r\nconst UI = {\r\n dialog,\r\n Menu,\r\n hover: hoverstart,\r\n checkbox\r\n};\r\nexport default UI;\r\n","import Get from \"../General/Get\";\r\nimport Header from \"../General/Header\";\r\nimport { g, Conf, d, doc } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\nimport $$ from \"../platform/$$\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar Nav = {\r\n init() {\r\n switch (g.VIEW) {\r\n case 'index':\r\n if (!Conf['Index Navigation']) { return; }\r\n break;\r\n case 'thread':\r\n if (!Conf['Reply Navigation']) { return; }\r\n break;\r\n default:\r\n return;\r\n }\r\n\r\n const span = $.el('span',\r\n {id: 'navlinks'});\r\n const prev = $.el('a', {\r\n textContent: '▲',\r\n href: 'javascript:;'\r\n }\r\n );\r\n const next = $.el('a', {\r\n textContent: '▼',\r\n href: 'javascript:;'\r\n }\r\n );\r\n\r\n $.on(prev, 'click', this.prev);\r\n $.on(next, 'click', this.next);\r\n\r\n $.add(span, [prev, $.tn(' '), next]);\r\n var append = function() {\r\n $.off(d, '4chanXInitFinished', append);\r\n return $.add(d.body, span);\r\n };\r\n return $.on(d, '4chanXInitFinished', append);\r\n },\r\n\r\n prev() {\r\n if (g.VIEW === 'thread') {\r\n return window.scrollTo(0, 0);\r\n } else {\r\n return Nav.scroll(-1);\r\n }\r\n },\r\n\r\n next() {\r\n if (g.VIEW === 'thread') {\r\n return window.scrollTo(0, d.body.scrollHeight);\r\n } else {\r\n return Nav.scroll(+1);\r\n }\r\n },\r\n\r\n getThread() {\r\n if (g.VIEW === 'thread') { return g.threads.get(`${g.BOARD}.${g.THREADID}`).nodes.root; }\r\n if ($.hasClass(doc, 'catalog-mode')) { return; }\r\n for (var threadRoot of $$(g.SITE.selectors.thread)) {\r\n var thread = Get.threadFromRoot(threadRoot);\r\n if (thread.isHidden && !thread.stub) { continue; }\r\n if (Header.getTopOf(threadRoot) >= -threadRoot.getBoundingClientRect().height) { // not scrolled past\r\n return threadRoot;\r\n }\r\n }\r\n },\r\n\r\n scroll(delta) {\r\n let next;\r\n d.activeElement?.blur();\r\n let thread = Nav.getThread();\r\n if (!thread) { return; }\r\n const axis = delta === +1 ?\r\n 'following'\r\n :\r\n 'preceding';\r\n if (next = $.x(`${axis}-sibling::${g.SITE.xpath.thread}[not(@hidden)][1]`, thread)) {\r\n // Unless we're not at the beginning of the current thread,\r\n // and thus wanting to move to beginning,\r\n // or we're above the first thread and don't want to skip it.\r\n const top = Header.getTopOf(thread);\r\n if (((delta === +1) && (top < 5)) || ((delta === -1) && (top > -5))) { thread = next; }\r\n }\r\n // Add extra space to the end of the page if necessary so that all threads can be selected by keybinds.\r\n const extra = (Header.getTopOf(thread) + doc.clientHeight) - d.body.getBoundingClientRect().bottom;\r\n if (extra > 0) { d.body.style.marginBottom = `${extra}px`; }\r\n\r\n Header.scrollTo(thread);\r\n\r\n if ((extra > 0) && !Nav.haveExtra) {\r\n Nav.haveExtra = true;\r\n return $.on(d, 'scroll', Nav.removeExtra);\r\n }\r\n },\r\n\r\n removeExtra() {\r\n const extra = doc.clientHeight - d.body.getBoundingClientRect().bottom;\r\n if (extra > 0) {\r\n return d.body.style.marginBottom = `${extra}px`;\r\n } else {\r\n d.body.style.marginBottom = '';\r\n delete Nav.haveExtra;\r\n return $.off(d, 'scroll', Nav.removeExtra);\r\n }\r\n }\r\n};\r\nexport default Nav;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport { Conf, g } from \"../globals/globals\";\r\nimport $$ from \"../platform/$$\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar ImageHost = {\r\n init() {\r\n if ((!(this.useFaster = /\\S/.test(Conf['fourchanImageHost']))) || (g.SITE.software !== 'yotsuba') || !['index', 'thread'].includes(g.VIEW)) { return; }\r\n return Callbacks.Post.push({\r\n name: 'Image Host Rewriting',\r\n cb: this.node\r\n });\r\n },\r\n\r\n suggestions: ['i.4cdn.org', 'is2.4chan.org'],\r\n\r\n host() {\r\n return Conf['fourchanImageHost'].trim() || 'i.4cdn.org';\r\n },\r\n flashHost() {\r\n return 'i.4cdn.org';\r\n },\r\n thumbHost() {\r\n return 'i.4cdn.org';\r\n },\r\n test(hostname) {\r\n return (hostname === 'i.4cdn.org') || ImageHost.regex.test(hostname);\r\n },\r\n\r\n regex: /^is\\d*\\.4chan(?:nel)?\\.org$/,\r\n\r\n node() {\r\n if (this.isClone) { return; }\r\n const host = ImageHost.host();\r\n if (this.file && ImageHost.test(this.file.url.split('/')[2]) && !/\\.swf$/.test(this.file.url)) {\r\n this.file.link.hostname = host;\r\n if (this.file.thumbLink) { this.file.thumbLink.hostname = host; }\r\n this.file.url = this.file.link.href;\r\n }\r\n return ImageHost.fixLinks($$('a', this.nodes.comment));\r\n },\r\n\r\n fixLinks(links) {\r\n for (var link of links) {\r\n if (ImageHost.test(link.hostname) && !/\\.swf$/.test(link.pathname)) {\r\n var host = ImageHost.host();\r\n if (link.hostname !== host) { link.hostname = host; }\r\n }\r\n }\r\n }\r\n};\r\nexport default ImageHost;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport Config from \"../config/Config\";\r\nimport Header from \"../General/Header\";\r\nimport UI from \"../General/UI\";\r\nimport { g, Conf, E } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar Volume = {\r\n init() {\r\n if (!['index', 'thread'].includes(g.VIEW) ||\r\n (!Conf['Image Expansion'] && !Conf['Image Hover'] && !Conf['Image Hover in Catalog'] && !Conf['Gallery'])) { return; }\r\n\r\n $.sync('Allow Sound', function(x) {\r\n Conf['Allow Sound'] = x;\r\n if (Volume.inputs) Volume.inputs.unmute.checked = x;\r\n });\r\n\r\n $.sync('Default Volume', function(x) {\r\n Conf['Default Volume'] = x;\r\n if (Volume.inputs) Volume.inputs.volume.value = x;\r\n });\r\n\r\n if (Conf['Mouse Wheel Volume']) {\r\n Callbacks.Post.push({\r\n name: 'Mouse Wheel Volume',\r\n cb: this.node\r\n });\r\n }\r\n\r\n if (g.SITE.noAudio?.(g.BOARD)) { return; }\r\n\r\n if (Conf['Mouse Wheel Volume']) {\r\n Callbacks.CatalogThread.push({\r\n name: 'Mouse Wheel Volume',\r\n cb: this.catalogNode\r\n });\r\n }\r\n\r\n const unmuteEntry = UI.checkbox('Allow Sound', 'Allow Sound');\r\n unmuteEntry.title = Config.main['Images and Videos']['Allow Sound'][1];\r\n\r\n const volumeEntry = $.el('label',\r\n {title: 'Default volume for videos.'});\r\n $.extend(volumeEntry,\r\n {innerHTML: \" Volume\"});\r\n\r\n this.inputs = {\r\n unmute: unmuteEntry.firstElementChild,\r\n volume: volumeEntry.firstElementChild\r\n };\r\n\r\n $.on(this.inputs.unmute, 'change', $.cb.checked);\r\n $.on(this.inputs.volume, 'change', $.cb.value);\r\n\r\n Header.menu.addEntry({el: unmuteEntry, order: 200});\r\n return Header.menu.addEntry({el: volumeEntry, order: 201});\r\n },\r\n\r\n setup(video) {\r\n video.muted = !Conf['Allow Sound'];\r\n video.volume = Conf['Default Volume'];\r\n return $.on(video, 'volumechange', Volume.change);\r\n },\r\n\r\n change() {\r\n const {muted, volume} = this;\r\n const items = {\r\n 'Allow Sound': !muted,\r\n 'Default Volume': volume\r\n };\r\n for (var key in items) {\r\n var val = items[key];\r\n if (Conf[key] === val) {\r\n delete items[key];\r\n }\r\n }\r\n $.set(items);\r\n $.extend(Conf, items);\r\n if (Volume.inputs) {\r\n Volume.inputs.unmute.checked = !muted;\r\n return Volume.inputs.volume.value = volume;\r\n }\r\n },\r\n\r\n node() {\r\n if (g.SITE.noAudio?.(this.board)) { return; }\r\n for (var file of this.files) {\r\n if (file.isVideo) {\r\n if (file.thumb) { $.on(file.thumb, 'wheel', Volume.wheel.bind(Header.hover)); }\r\n $.on(($('.file-info', file.text) || file.link), 'wheel', Volume.wheel.bind(file.thumbLink));\r\n }\r\n }\r\n },\r\n\r\n catalogNode() {\r\n const file = this.thread.OP.files[0];\r\n if (!file?.isVideo) { return; }\r\n return $.on(this.nodes.thumb, 'wheel', Volume.wheel.bind(Header.hover));\r\n },\r\n\r\n wheel(e) {\r\n let el;\r\n if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) { return; }\r\n if (!(el = $('video:not([data-md5])', this))) { return; }\r\n if (el.muted || !$.hasAudio(el)) { return; }\r\n let volume = el.volume + 0.1;\r\n if (e.deltaY < 0) { volume *= 1.1; }\r\n if (e.deltaY > 0) { volume /= 1.1; }\r\n el.volume = $.minmax(volume - 0.1, 0, 1);\r\n return e.preventDefault();\r\n }\r\n};\r\nexport default Volume;\r\n","import Redirect from \"../Archive/Redirect\";\r\nimport Notice from \"../classes/Notice\";\r\nimport { g, Conf, d } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\nimport CrossOrigin from \"../platform/CrossOrigin\";\r\nimport ImageHost from \"./ImageHost\";\r\nimport Volume from \"./Volume\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS104: Avoid inline assignments\r\n * DS204: Change includes calls to have a more natural evaluation order\r\n * DS207: Consider shorter variations of null checks\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar ImageCommon = {\r\n // Pause and mute video in preparation for removing the element from the document.\r\n pause(video) {\r\n if (video.nodeName !== 'VIDEO') { return; }\r\n video.pause();\r\n $.off(video, 'volumechange', Volume.change);\r\n return video.muted = true;\r\n },\r\n\r\n rewind(el) {\r\n if (el.nodeName === 'VIDEO') {\r\n if (el.readyState >= el.HAVE_METADATA) { return el.currentTime = 0; }\r\n } else if (/\\.gif$/.test(el.src)) {\r\n return $.queueTask(() => el.src = el.src);\r\n }\r\n },\r\n\r\n pushCache(el) {\r\n ImageCommon.cache = el;\r\n return $.on(el, 'error', ImageCommon.cacheError);\r\n },\r\n\r\n popCache() {\r\n const el = ImageCommon.cache;\r\n $.off(el, 'error', ImageCommon.cacheError);\r\n delete ImageCommon.cache;\r\n return el;\r\n },\r\n\r\n cacheError() {\r\n if (ImageCommon.cache === this) { return delete ImageCommon.cache; }\r\n },\r\n\r\n decodeError(file, fileObj) {\r\n let message;\r\n if (file.error?.code !== MediaError.MEDIA_ERR_DECODE) { return false; }\r\n if (!(message = $('.warning', fileObj.thumb.parentNode))) {\r\n message = $.el('div', {className: 'warning'});\r\n $.after(fileObj.thumb, message);\r\n }\r\n message.textContent = 'Error: Corrupt or unplayable video';\r\n return true;\r\n },\r\n\r\n isFromArchive(file) {\r\n return (g.SITE.software === 'yotsuba') && !ImageHost.test(file.src.split('/')[2]);\r\n },\r\n\r\n error(file, post, fileObj, delay, cb) {\r\n let timeoutID;\r\n const src = fileObj.url.split('/');\r\n let url = null;\r\n if ((g.SITE.software === 'yotsuba') && Conf['404 Redirect']) {\r\n url = Redirect.to('file', {\r\n boardID: post.board.ID,\r\n filename: src[src.length - 1]\r\n });\r\n }\r\n if (!url || !Redirect.securityCheck(url)) { url = null; }\r\n\r\n if ((post.isDead || fileObj.isDead) && !ImageCommon.isFromArchive(file)) { return cb(url); }\r\n\r\n if (delay != null) { timeoutID = setTimeout((() => cb(url)), delay); }\r\n if (post.isDead || fileObj.isDead) { return; }\r\n const redirect = function() {\r\n if (!ImageCommon.isFromArchive(file)) {\r\n if (delay != null) { clearTimeout(timeoutID); }\r\n return cb(url);\r\n }\r\n };\r\n\r\n const threadJSON = g.SITE.urls.threadJSON?.(post);\r\n if (!threadJSON) { return; }\r\n var parseJSON = function(isArchiveURL) {\r\n let needle, postObj;\r\n if (this.status === 404) {\r\n let archivedThreadJSON;\r\n if (!isArchiveURL && (archivedThreadJSON = g.SITE.urls.archivedThreadJSON?.(post))) {\r\n $.ajax(archivedThreadJSON, {onloadend() { return parseJSON.call(this, true); }});\r\n } else {\r\n post.kill(!post.isClone, fileObj.index);\r\n }\r\n }\r\n if (this.status !== 200) { return redirect(); }\r\n for (postObj of this.response.posts) {\r\n if (postObj.no === post.ID) { break; }\r\n }\r\n if (postObj.no !== post.ID) {\r\n post.kill();\r\n return redirect();\r\n } else if ((needle = fileObj.docIndex, g.SITE.Build.parseJSON(postObj, post.board).filesDeleted.includes(needle))) {\r\n post.kill(true);\r\n return redirect();\r\n } else {\r\n return url = fileObj.url;\r\n }\r\n };\r\n return $.ajax(threadJSON, {onloadend() { return parseJSON.call(this); }});\r\n },\r\n\r\n // Add controls, but not until the mouse is moved over the video.\r\n addControls(video) {\r\n var handler = function() {\r\n $.off(video, 'mouseover', handler);\r\n // Hacky workaround for Firefox forever-loading bug for very short videos\r\n const t = new Date().getTime();\r\n return $.asap((() => ($.engine !== 'gecko') || ((video.readyState >= 3) && (video.currentTime <= Math.max(0.1, (video.duration - 0.5)))) || (new Date().getTime() >= (t + 1000))), () => video.controls = true);\r\n };\r\n return $.on(video, 'mouseover', handler);\r\n },\r\n\r\n // XXX Estimate whether clicks are on the video controls and should be ignored.\r\n onControls(e) {\r\n return (Conf['Show Controls'] && Conf['Click Passthrough'] && (e.target.nodeName === 'VIDEO')) ||\r\n (e.target.controls && ((e.target.getBoundingClientRect().bottom - e.clientY) < 35));\r\n },\r\n\r\n download(e) {\r\n if (this.protocol === 'blob:') { return true; }\r\n e.preventDefault();\r\n const {href, download} = this;\r\n return CrossOrigin.file(href, function(blob) {\r\n if (blob) {\r\n const a = $.el('a', {\r\n href: URL.createObjectURL(blob),\r\n download,\r\n hidden: true\r\n }\r\n );\r\n $.add(d.body, a);\r\n a.click();\r\n return $.rm(a);\r\n } else {\r\n return new Notice('warning', `Could not download ${href}`, 20);\r\n }\r\n });\r\n }\r\n};\r\nexport default ImageCommon;\r\n",null,null,null,"import Callbacks from \"../classes/Callbacks\";\r\nimport UI from \"../General/UI\";\r\nimport { g, Conf } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar Menu = {\r\n init() {\r\n if (!['index', 'thread'].includes(g.VIEW) || !Conf['Menu']) { return; }\r\n\r\n this.button = $.el('a', {\r\n className: 'menu-button',\r\n href: 'javascript:;'\r\n }\r\n );\r\n\r\n $.extend(this.button, {textContent: \"🞃\"});\r\n\r\n this.menu = new UI.Menu('post');\r\n Callbacks.Post.push({\r\n name: 'Menu',\r\n cb: this.node\r\n });\r\n\r\n return Callbacks.CatalogThread.push({\r\n name: 'Menu',\r\n cb: this.catalogNode\r\n });\r\n },\r\n\r\n node() {\r\n if (this.isClone) {\r\n const button = $('.menu-button', this.nodes.info);\r\n $.rmClass(button, 'active');\r\n $.rm($('.dialog', this.nodes.info));\r\n Menu.makeButton(this, button);\r\n return;\r\n }\r\n return $.add(this.nodes.info, Menu.makeButton(this));\r\n },\r\n\r\n catalogNode() {\r\n return $.after(this.nodes.icons, Menu.makeButton(this.thread.OP));\r\n },\r\n\r\n makeButton(post, button) {\r\n if (!button) { button = Menu.button.cloneNode(true); }\r\n $.on(button, 'click', function(e) {\r\n return Menu.menu.toggle(e, this, post);\r\n });\r\n return button;\r\n }\r\n};\r\nexport default Menu;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport { g } from \"../globals/globals\";\r\nimport { dict } from \"../platform/helpers\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar Recursive = {\r\n recursives: dict(),\r\n init() {\r\n if (!['index', 'thread'].includes(g.VIEW)) { return; }\r\n return Callbacks.Post.push({\r\n name: 'Recursive',\r\n cb: this.node\r\n });\r\n },\r\n\r\n node() {\r\n if (this.isClone || this.isFetchedQuote) { return; }\r\n for (var quote of this.quotes) {\r\n var obj;\r\n if ((obj = Recursive.recursives[quote])) {\r\n for (var i = 0; i < obj.recursives.length; i++) {\r\n var recursive = obj.recursives[i];\r\n recursive(this, ...obj.args[i]);\r\n }\r\n }\r\n }\r\n },\r\n\r\n add(recursive, post, ...args) {\r\n const obj = Recursive.recursives[post.fullID] || (Recursive.recursives[post.fullID] = {\r\n recursives: [],\r\n args: []\r\n });\r\n obj.recursives.push(recursive);\r\n return obj.args.push(args);\r\n },\r\n\r\n rm(recursive, post) {\r\n let obj;\r\n if (!(obj = Recursive.recursives[post.fullID])) { return; }\r\n for (let i = 0; i < obj.recursives.length; i++) {\r\n var rec = obj.recursives[i];\r\n if (rec === recursive) {\r\n obj.recursives.splice(i, 1);\r\n obj.args.splice(i, 1);\r\n }\r\n }\r\n },\r\n\r\n apply(recursive, post, ...args) {\r\n const {fullID} = post;\r\n return g.posts.forEach(function(post) {\r\n if (post.quotes.includes(fullID)) {\r\n return recursive(post, ...args);\r\n }\r\n });\r\n }\r\n};\r\nexport default Recursive;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport DataBoard from \"../classes/DataBoard\";\r\nimport Get from \"../General/Get\";\r\nimport UI from \"../General/UI\";\r\nimport { g, Conf, doc } from \"../globals/globals\";\r\nimport Menu from \"../Menu/Menu\";\r\nimport $ from \"../platform/$\";\r\nimport Recursive from \"./Recursive\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS207: Consider shorter variations of null checks\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar PostHiding = {\r\n init() {\r\n if (!['index', 'thread'].includes(g.VIEW) || (!Conf['Reply Hiding Buttons'] && !(Conf['Menu'] && Conf['Reply Hiding Link']))) { return; }\r\n\r\n if (Conf['Reply Hiding Buttons']) {\r\n $.addClass(doc, \"reply-hide\");\r\n }\r\n\r\n this.db = new DataBoard('hiddenPosts');\r\n return Callbacks.Post.push({\r\n name: 'Reply Hiding',\r\n cb: this.node\r\n });\r\n },\r\n\r\n isHidden(boardID, threadID, postID) {\r\n return !!(PostHiding.db && PostHiding.db.get({boardID, threadID, postID}));\r\n },\r\n\r\n node() {\r\n let data, sa;\r\n if (!this.isReply || this.isClone || this.isFetchedQuote) { return; }\r\n\r\n if (data = PostHiding.db.get({boardID: this.board.ID, threadID: this.thread.ID, postID: this.ID})) {\r\n if (data.thisPost) {\r\n PostHiding.hide(this, data.makeStub, data.hideRecursively);\r\n } else {\r\n Recursive.apply(PostHiding.hide, this, data.makeStub, true);\r\n Recursive.add(PostHiding.hide, this, data.makeStub, true);\r\n }\r\n }\r\n\r\n if (!Conf['Reply Hiding Buttons']) { return; }\r\n\r\n const button = PostHiding.makeButton(this, 'hide');\r\n if (sa = g.SITE.selectors.sideArrows) {\r\n const sideArrows = $(sa, this.nodes.root);\r\n $.replace(sideArrows.firstChild, button);\r\n return sideArrows.className = 'replacedSideArrows';\r\n } else {\r\n return $.prepend(this.nodes.info, button);\r\n }\r\n },\r\n\r\n menu: {\r\n init() {\r\n if (!['index', 'thread'].includes(g.VIEW) || !Conf['Menu'] || !Conf['Reply Hiding Link']) { return; }\r\n\r\n // Hide\r\n let div = $.el('div', {\r\n className: 'hide-reply-link',\r\n textContent: 'Hide'\r\n }\r\n );\r\n\r\n let apply = $.el('a', {\r\n textContent: 'Apply',\r\n href: 'javascript:;'\r\n }\r\n );\r\n $.on(apply, 'click', PostHiding.menu.hide);\r\n\r\n let thisPost = UI.checkbox('thisPost', 'This post', true);\r\n let replies = UI.checkbox('replies', 'Hide replies', Conf['Recursive Hiding']);\r\n const makeStub = UI.checkbox('makeStub', 'Make stub', Conf['Stubs']);\r\n\r\n Menu.menu.addEntry({\r\n el: div,\r\n order: 20,\r\n open(post) {\r\n if (!post.isReply || post.isClone || post.isHidden) {\r\n return false;\r\n }\r\n PostHiding.menu.post = post;\r\n return true;\r\n },\r\n subEntries: [\r\n {el: apply}\r\n ,\r\n {el: thisPost}\r\n ,\r\n {el: replies}\r\n ,\r\n {el: makeStub}\r\n ]});\r\n\r\n // Show\r\n div = $.el('div', {\r\n className: 'show-reply-link',\r\n textContent: 'Show'\r\n }\r\n );\r\n\r\n apply = $.el('a', {\r\n textContent: 'Apply',\r\n href: 'javascript:;'\r\n }\r\n );\r\n $.on(apply, 'click', PostHiding.menu.show);\r\n\r\n thisPost = UI.checkbox('thisPost', 'This post', false);\r\n replies = UI.checkbox('replies', 'Show replies', false);\r\n const hideStubLink = $.el('a', {\r\n textContent: 'Hide stub',\r\n href: 'javascript:;'\r\n }\r\n );\r\n $.on(hideStubLink, 'click', PostHiding.menu.hideStub);\r\n\r\n Menu.menu.addEntry({\r\n el: div,\r\n order: 20,\r\n open(post) {\r\n let data;\r\n if (!post.isReply || post.isClone || !post.isHidden) {\r\n return false;\r\n }\r\n if (!(data = PostHiding.db.get({boardID: post.board.ID, threadID: post.thread.ID, postID: post.ID}))) {\r\n return false;\r\n }\r\n PostHiding.menu.post = post;\r\n thisPost.firstChild.checked = post.isHidden;\r\n replies.firstChild.checked = (data?.hideRecursively != null) ? data.hideRecursively : Conf['Recursive Hiding'];\r\n return true;\r\n },\r\n subEntries: [\r\n {el: apply}\r\n ,\r\n {el: thisPost}\r\n ,\r\n {el: replies}\r\n ]});\r\n\r\n return Menu.menu.addEntry({\r\n el: hideStubLink,\r\n order: 15,\r\n open(post) {\r\n let data;\r\n if (!post.isReply || post.isClone || !post.isHidden) {\r\n return false;\r\n }\r\n if (!(data = PostHiding.db.get({boardID: post.board.ID, threadID: post.thread.ID, postID: post.ID}))) {\r\n return false;\r\n }\r\n return PostHiding.menu.post = post;\r\n }\r\n });\r\n },\r\n\r\n hide() {\r\n const parent = this.parentNode;\r\n const thisPost = $('input[name=thisPost]', parent).checked;\r\n const replies = $('input[name=replies]', parent).checked;\r\n const makeStub = $('input[name=makeStub]', parent).checked;\r\n const {post} = PostHiding.menu;\r\n if (thisPost) {\r\n PostHiding.hide(post, makeStub, replies);\r\n } else if (replies) {\r\n Recursive.apply(PostHiding.hide, post, makeStub, true);\r\n Recursive.add(PostHiding.hide, post, makeStub, true);\r\n } else {\r\n return;\r\n }\r\n PostHiding.saveHiddenState(post, true, thisPost, makeStub, replies);\r\n return $.event('CloseMenu');\r\n },\r\n\r\n show() {\r\n let data;\r\n const parent = this.parentNode;\r\n const thisPost = $('input[name=thisPost]', parent).checked;\r\n const replies = $('input[name=replies]', parent).checked;\r\n const {post} = PostHiding.menu;\r\n if (thisPost) {\r\n PostHiding.show(post, replies);\r\n } else if (replies) {\r\n Recursive.apply(PostHiding.show, post, true);\r\n Recursive.rm(PostHiding.hide, post, true);\r\n } else {\r\n return;\r\n }\r\n if (data = PostHiding.db.get({boardID: post.board.ID, threadID: post.thread.ID, postID: post.ID})) {\r\n PostHiding.saveHiddenState(post, !(thisPost && replies), !thisPost, data.makeStub, !replies);\r\n }\r\n return $.event('CloseMenu');\r\n },\r\n hideStub() {\r\n let data;\r\n const {post} = PostHiding.menu;\r\n if (data = PostHiding.db.get({boardID: post.board.ID, threadID: post.thread.ID, postID: post.ID})) {\r\n PostHiding.show(post, data.hideRecursively);\r\n PostHiding.hide(post, false, data.hideRecursively);\r\n PostHiding.saveHiddenState(post, true, true, false, data.hideRecursively);\r\n }\r\n $.event('CloseMenu');\r\n }\r\n },\r\n\r\n makeButton(post, type) {\r\n const span = $.el('span', {\r\n textContent: type === 'hide' ? '➖︎' : '➕︎',\r\n });\r\n const a = $.el('a', {\r\n className: `${type}-reply-button`,\r\n href: 'javascript:;'\r\n }\r\n );\r\n $.add(a, span);\r\n $.on(a, 'click', PostHiding.toggle);\r\n return a;\r\n },\r\n\r\n saveHiddenState(post, isHiding, thisPost, makeStub, hideRecursively) {\r\n const data = {\r\n boardID: post.board.ID,\r\n threadID: post.thread.ID,\r\n postID: post.ID\r\n };\r\n if (isHiding) {\r\n data.val = {\r\n thisPost: thisPost !== false, // undefined -> true\r\n makeStub,\r\n hideRecursively\r\n };\r\n return PostHiding.db.set(data);\r\n } else {\r\n return PostHiding.db.delete(data);\r\n }\r\n },\r\n\r\n toggle() {\r\n const post = Get.postFromNode(this);\r\n PostHiding[(post.isHidden ? 'show' : 'hide')](post);\r\n return PostHiding.saveHiddenState(post, post.isHidden);\r\n },\r\n\r\n hide(post, makeStub=Conf['Stubs'], hideRecursively=Conf['Recursive Hiding']) {\r\n if (post.isHidden) { return; }\r\n post.isHidden = true;\r\n\r\n if (hideRecursively) {\r\n Recursive.apply(PostHiding.hide, post, makeStub, true);\r\n Recursive.add(PostHiding.hide, post, makeStub, true);\r\n }\r\n\r\n for (var quotelink of Get.allQuotelinksLinkingTo(post)) {\r\n $.addClass(quotelink, 'filtered');\r\n }\r\n\r\n if (!makeStub) {\r\n post.nodes.root.hidden = true;\r\n return;\r\n }\r\n\r\n const a = PostHiding.makeButton(post, 'show');\r\n $.add(a, $.tn(` ${post.info.nameBlock}`));\r\n post.nodes.stub = $.el('div',\r\n {className: 'stub'});\r\n $.add(post.nodes.stub, a);\r\n if (Conf['Menu']) {\r\n $.add(post.nodes.stub, Menu.makeButton(post));\r\n }\r\n return $.prepend(post.nodes.root, post.nodes.stub);\r\n },\r\n\r\n show(post, showRecursively=Conf['Recursive Hiding']) {\r\n if (post.nodes.stub) {\r\n $.rm(post.nodes.stub);\r\n delete post.nodes.stub;\r\n } else {\r\n post.nodes.root.hidden = false;\r\n }\r\n post.isHidden = false;\r\n if (showRecursively) {\r\n Recursive.apply(PostHiding.show, post, true);\r\n Recursive.rm(PostHiding.hide, post);\r\n }\r\n for (var quotelink of Get.allQuotelinksLinkingTo(post)) {\r\n $.rmClass(quotelink, 'filtered');\r\n }\r\n }\r\n};\r\nexport default PostHiding;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport Post from \"../classes/Post\";\r\nimport Index from \"../General/Index\";\r\nimport { g, Conf, d, doc } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\nimport { DAY, HOUR, MINUTE, SECOND } from \"../platform/helpers\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS205: Consider reworking code to avoid use of IIFEs\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar RelativeDates = {\r\n INTERVAL: 30000,\r\n\r\n init() {\r\n if (\r\n (['index', 'thread', 'archive'].includes(g.VIEW) && Conf['Relative Post Dates'] && !Conf['Relative Date Title']) ||\r\n Index.enabled\r\n ) {\r\n this.flush();\r\n $.on(d, 'visibilitychange PostsInserted', this.flush);\r\n }\r\n\r\n if (Conf['Relative Post Dates']) {\r\n return Callbacks.Post.push({\r\n name: 'Relative Post Dates',\r\n cb: this.node\r\n });\r\n }\r\n },\r\n\r\n node() {\r\n if (!this.info.date) { return; }\r\n const dateEl = this.nodes.date;\r\n if (Conf['Relative Date Title']) {\r\n $.on(dateEl, 'mouseover', () => RelativeDates.hover(this));\r\n return;\r\n }\r\n if (this.isClone) { return; }\r\n\r\n // Show original absolute time as tooltip so users can still know exact times\r\n // Since \"Time Formatting\" runs its `node` before us, the title tooltip will\r\n // pick up the user-formatted time instead of 4chan time when enabled.\r\n dateEl.title = dateEl.textContent;\r\n\r\n return RelativeDates.update(this);\r\n },\r\n\r\n // diff is milliseconds from now.\r\n relative(diff, now, date, abbrev) {\r\n let number;\r\n let unit = (() => {\r\n if ((number = (diff / DAY)) >= 1) {\r\n const years = now.getFullYear() - date.getFullYear();\r\n let months = now.getMonth() - date.getMonth();\r\n const days = now.getDate() - date.getDate();\r\n if (years > 1) {\r\n number = years - ((months < 0) || ((months === 0) && (days < 0)));\r\n return 'year';\r\n } else if ((years === 1) && ((months > 0) || ((months === 0) && (days >= 0)))) {\r\n number = years;\r\n return 'year';\r\n } else if ((months = months + (12*years)) > 1) {\r\n number = months - (days < 0);\r\n return 'month';\r\n } else if ((months === 1) && (days >= 0)) {\r\n number = months;\r\n return 'month';\r\n } else {\r\n return 'day';\r\n }\r\n } else if ((number = (diff / HOUR)) >= 1) {\r\n return 'hour';\r\n } else if ((number = (diff / MINUTE)) >= 1) {\r\n return 'minute';\r\n } else {\r\n // prevent \"-1 seconds ago\"\r\n number = Math.max(0, diff) / SECOND;\r\n return 'second';\r\n }\r\n })();\r\n\r\n const rounded = Math.round(number);\r\n\r\n if (abbrev) {\r\n unit = unit === 'month' ? 'mo' : unit[0];\r\n } else {\r\n if (rounded !== 1) { unit += 's'; } // pluralize\r\n }\r\n\r\n if (abbrev) { return `${rounded}${unit}`; } else { return `${rounded} ${unit} ago`; }\r\n },\r\n\r\n // Changing all relative dates as soon as possible incurs many annoying\r\n // redraws and scroll stuttering. Thus, sacrifice accuracy for UX/CPU economy,\r\n // and perform redraws when the DOM is otherwise being manipulated (and scroll\r\n // stuttering won't be noticed), falling back to INTERVAL while the page\r\n // is visible.\r\n //\r\n // Each individual dateTime element will add its update() function to the stale list\r\n // when it is to be called.\r\n stale: [],\r\n flush() {\r\n // No point in changing the dates until the user sees them.\r\n if (d.hidden) { return; }\r\n\r\n const now = new Date();\r\n for (var data of RelativeDates.stale) { RelativeDates.update(data, now); }\r\n RelativeDates.stale = [];\r\n\r\n // Reset automatic flush.\r\n clearTimeout(RelativeDates.timeout);\r\n return RelativeDates.timeout = setTimeout(RelativeDates.flush, RelativeDates.INTERVAL);\r\n },\r\n\r\n hover(post) {\r\n const {\r\n date\r\n } = post.info;\r\n const now = new Date();\r\n const diff = now - date;\r\n return post.nodes.date.title = RelativeDates.relative(diff, now, date);\r\n },\r\n\r\n // `update()`, when called from `flush()`, updates the elements,\r\n // and re-calls `setOwnTimeout()` to re-add `data` to the stale list later.\r\n update(data, now) {\r\n let abbrev, date;\r\n const isPost = data instanceof Post;\r\n if (isPost) {\r\n ({\r\n date\r\n } = data.info);\r\n abbrev = false;\r\n } else {\r\n date = new Date(+data.dataset.utc);\r\n abbrev = !!data.dataset.abbrev;\r\n }\r\n if (!now) { now = new Date(); }\r\n const diff = now - date;\r\n const relative = RelativeDates.relative(diff, now, date, abbrev);\r\n if (isPost) {\r\n for (var singlePost of [data].concat(data.clones)) {\r\n singlePost.nodes.date.firstChild.textContent = relative;\r\n }\r\n } else {\r\n data.firstChild.textContent = relative;\r\n }\r\n return RelativeDates.setOwnTimeout(diff, data);\r\n },\r\n\r\n setOwnTimeout(diff, data) {\r\n const delay = diff < MINUTE ?\r\n SECOND - ((diff + (SECOND / 2)) % SECOND)\r\n : diff < HOUR ?\r\n MINUTE - ((diff + (MINUTE / 2)) % MINUTE)\r\n : diff < DAY ?\r\n HOUR - ((diff + (HOUR / 2)) % HOUR)\r\n :\r\n DAY - ((diff + (DAY / 2)) % DAY);\r\n return setTimeout(RelativeDates.markStale, delay, data);\r\n },\r\n\r\n markStale(data) {\r\n if (RelativeDates.stale.includes(data)) { return; } // We can call RelativeDates.update() multiple times.\r\n if (data instanceof Post && !g.posts.get(data.fullID)) { return; } // collected post.\r\n if (data instanceof Element && !doc.contains(data)) { return; } // removed catalog reply.\r\n return RelativeDates.stale.push(data);\r\n }\r\n};\r\nexport default RelativeDates;\r\n","import Notice from \"../classes/Notice\";\r\nimport { g, Conf } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\nimport { dict, HOUR } from \"../platform/helpers\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS104: Avoid inline assignments\r\n * DS205: Consider reworking code to avoid use of IIFEs\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar BoardConfig = {\r\n cbs: [],\r\n\r\n init() {\r\n let middle;\r\n if (g.SITE.software !== 'yotsuba') { return; }\r\n const now = Date.now();\r\n if (now - (2 * HOUR) >= ((middle = Conf['boardConfig'].lastChecked || 0)) || middle > now) {\r\n return $.ajax(`${location.protocol}//a.4cdn.org/boards.json`,\r\n {onloadend: this.load});\r\n } else {\r\n const {boards} = Conf['boardConfig'];\r\n return this.set(boards);\r\n }\r\n },\r\n\r\n load() {\r\n let boards;\r\n if ((this.status === 200) && this.response && this.response.boards) {\r\n boards = dict();\r\n for (var board of this.response.boards) {\r\n boards[board.board] = board;\r\n }\r\n $.set('boardConfig', {boards, lastChecked: Date.now()});\r\n } else {\r\n ({boards} = Conf['boardConfig']);\r\n const err = (() => { switch (this.status) {\r\n case 0: return 'Connection Error';\r\n case 200: return 'Invalid Data';\r\n default: return `Error ${this.statusText} (${this.status})`;\r\n } })();\r\n new Notice('warning', `Failed to load board configuration. ${err}`, 20);\r\n }\r\n return BoardConfig.set(boards);\r\n },\r\n\r\n set(boards) {\r\n this.boards = boards;\r\n for (var ID in g.boards) {\r\n var board = g.boards[ID];\r\n board.config = this.boards[ID] || {};\r\n }\r\n for (var cb of this.cbs) {\r\n $.queueTask(cb);\r\n }\r\n },\r\n\r\n ready(cb) {\r\n if (this.boards) {\r\n return cb();\r\n } else {\r\n return this.cbs.push(cb);\r\n }\r\n },\r\n\r\n sfwBoards(sfw) {\r\n return (() => {\r\n const result = [];\r\n const object = this.boards || Conf['boardConfig'].boards;\r\n for (var board in object) {\r\n var data = object[board];\r\n if (!!data.ws_board === sfw) {\r\n result.push(board);\r\n }\r\n }\r\n return result;\r\n })();\r\n },\r\n\r\n isSFW(board) {\r\n return !!(this.boards || Conf['boardConfig'].boards)[board]?.ws_board;\r\n },\r\n\r\n domain(board) {\r\n return `boards.${BoardConfig.isSFW(board) ? '4channel' : '4chan'}.org`;\r\n },\r\n\r\n isArchived(board) {\r\n // assume archive exists if no data available to prevent cleaning of archived threads\r\n const data = (this.boards || Conf['boardConfig'].boards)[board];\r\n return !data || data.is_archived;\r\n },\r\n\r\n noAudio(boardID) {\r\n if (g.SITE.software !== 'yotsuba') { return false; }\r\n const boards = this.boards || Conf['boardConfig'].boards;\r\n return boards && boards[boardID] && !boards[boardID].webm_audio;\r\n },\r\n\r\n title(boardID) {\r\n return (this.boards || Conf['boardConfig'].boards)?.[boardID]?.title || '';\r\n }\r\n};\r\nexport default BoardConfig;\r\n",null,"import { d } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nconst PostRedirect = {\r\n init() {\r\n return $.on(d, 'QRPostSuccessful', e => {\r\n if (!e.detail.redirect) { return; }\r\n this.event = e;\r\n this.delays = 0;\r\n return $.queueTask(() => {\r\n if ((e === this.event) && (this.delays === 0)) {\r\n return location.href = e.detail.redirect;\r\n }\r\n });\r\n });\r\n },\r\n\r\n delays: 0,\r\n\r\n delay() {\r\n if (!this.event) { return null; }\r\n const e = this.event;\r\n this.delays++;\r\n return () => {\r\n if (e !== this.event) { return; }\r\n this.delays--;\r\n if (this.delays === 0) {\r\n return location.href = e.detail.redirect;\r\n }\r\n };\r\n }\r\n};\r\nexport default PostRedirect;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport Get from \"../General/Get\";\r\nimport { g, Conf } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\nimport $$ from \"../platform/$$\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar ExpandComment = {\r\n init() {\r\n if ((g.VIEW !== 'index') || !Conf['Comment Expansion'] || Conf['JSON Index']) { return; }\r\n\r\n return Callbacks.Post.push({\r\n name: 'Comment Expansion',\r\n cb: this.node\r\n });\r\n },\r\n\r\n node() {\r\n let a;\r\n if (a = $('.abbr > a:not([onclick])', this.nodes.comment)) {\r\n return $.on(a, 'click', ExpandComment.cb);\r\n }\r\n },\r\n\r\n callbacks: [],\r\n\r\n cb(e) {\r\n e.preventDefault();\r\n return ExpandComment.expand(Get.postFromNode(this));\r\n },\r\n\r\n expand(post) {\r\n let a;\r\n if (post.nodes.longComment && !post.nodes.longComment.parentNode) {\r\n $.replace(post.nodes.shortComment, post.nodes.longComment);\r\n post.nodes.comment = post.nodes.longComment;\r\n return;\r\n }\r\n if (!(a = $('.abbr > a', post.nodes.comment))) { return; }\r\n a.textContent = `Post No.${post} Loading...`;\r\n return $.cache(g.SITE.urls.threadJSON({boardID: post.boardID, threadID: post.threadID}), function() { return ExpandComment.parse(this, a, post); });\r\n },\r\n\r\n contract(post) {\r\n if (!post.nodes.shortComment) { return; }\r\n const a = $('.abbr > a', post.nodes.shortComment);\r\n a.textContent = 'here';\r\n $.replace(post.nodes.longComment, post.nodes.shortComment);\r\n return post.nodes.comment = post.nodes.shortComment;\r\n },\r\n\r\n parse(req, a, post) {\r\n let postObj, spoilerRange;\r\n const {status} = req;\r\n if (![200, 304].includes(status)) {\r\n a.textContent = status ? `Error ${req.statusText} (${status})` : 'Connection Error';\r\n return;\r\n }\r\n\r\n const {\r\n posts\r\n } = req.response;\r\n if (spoilerRange = posts[0].custom_spoiler) {\r\n g.SITE.Build.spoilerRange[g.BOARD] = spoilerRange;\r\n }\r\n\r\n for (postObj of posts) {\r\n if (postObj.no === post.ID) { break; }\r\n }\r\n if (postObj.no !== post.ID) {\r\n a.textContent = `Post No.${post} not found.`;\r\n return;\r\n }\r\n\r\n const {comment} = post.nodes;\r\n const clone = comment.cloneNode(false);\r\n clone.innerHTML = postObj.com;\r\n // Fix pathnames\r\n for (var quote of $$('.quotelink', clone)) {\r\n var href = quote.getAttribute('href');\r\n if (href[0] === '/') { continue; } // Cross-board quote, or board link\r\n if (href[0] === '#') {\r\n quote.href = `${a.pathname.split(/\\/+/).splice(0,4).join('/')}${href}`;\r\n } else {\r\n quote.href = `${a.pathname.split(/\\/+/).splice(0,3).join('/')}/${href}`;\r\n }\r\n }\r\n post.nodes.shortComment = comment;\r\n $.replace(comment, clone);\r\n post.nodes.comment = (post.nodes.longComment = clone);\r\n post.parseComment();\r\n post.parseQuotes();\r\n\r\n for (var callback of ExpandComment.callbacks) {\r\n callback.call(post);\r\n }\r\n }\r\n};\r\nexport default ExpandComment;;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport DataBoard from \"../classes/DataBoard\";\r\nimport Notice from \"../classes/Notice\";\r\nimport Get from \"../General/Get\";\r\nimport Header from \"../General/Header\";\r\nimport { Conf, d, doc, g } from \"../globals/globals\";\r\nimport Menu from \"../Menu/Menu\";\r\nimport ExpandComment from \"../Miscellaneous/ExpandComment\";\r\nimport $ from \"../platform/$\";\r\nimport $$ from \"../platform/$$\";\r\nimport PostRedirect from \"../Posting/PostRedirect\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar QuoteYou = {\r\n init() {\r\n if (!Conf['Remember Your Posts']) { return; }\r\n\r\n this.db = new DataBoard('yourPosts');\r\n $.sync('Remember Your Posts', enabled => Conf['Remember Your Posts'] = enabled);\r\n $.on(d, 'QRPostSuccessful', function(e) {\r\n const cb = PostRedirect.delay();\r\n return $.get('Remember Your Posts', Conf['Remember Your Posts'], function(items) {\r\n if (!items['Remember Your Posts']) { return; }\r\n const {boardID, threadID, postID} = e.detail;\r\n return QuoteYou.db.set({boardID, threadID, postID, val: true}, cb);\r\n });\r\n });\r\n\r\n if (!['index', 'thread', 'archive'].includes(g.VIEW)) { return; }\r\n\r\n if (Conf['Highlight Own Posts']) {\r\n $.addClass(doc, 'highlight-own');\r\n }\r\n\r\n if (Conf['Highlight Posts Quoting You']) {\r\n $.addClass(doc, 'highlight-you');\r\n }\r\n\r\n if (Conf['Comment Expansion']) {\r\n ExpandComment.callbacks.push(this.node);\r\n }\r\n\r\n // \\u00A0 is nbsp\r\n this.mark = $.el('span', {\r\n textContent: '\\u00A0(You)',\r\n className: 'qmark-you'\r\n }\r\n );\r\n Callbacks.Post.push({\r\n name: 'Mark Quotes of You',\r\n cb: this.node\r\n });\r\n\r\n return QuoteYou.menu.init();\r\n },\r\n\r\n isYou(post) {\r\n return !!QuoteYou.db?.get({\r\n boardID: post.boardID,\r\n threadID: post.threadID,\r\n postID: post.ID\r\n });\r\n },\r\n\r\n node() {\r\n if (this.isClone) { return; }\r\n\r\n if (QuoteYou.isYou(this)) {\r\n $.addClass(this.nodes.root, 'yourPost');\r\n }\r\n\r\n // Stop there if there's no quotes in that post.\r\n if (!this.quotes.length) { return; }\r\n\r\n for (var quotelink of this.nodes.quotelinks) {\r\n if (QuoteYou.db.get(Get.postDataFromLink(quotelink))) {\r\n if (Conf['Mark Quotes of You']) { $.add(quotelink, QuoteYou.mark.cloneNode(true)); }\r\n $.addClass(quotelink, 'you');\r\n $.addClass(this.nodes.root, 'quotesYou');\r\n }\r\n }\r\n },\r\n\r\n menu: {\r\n init() {\r\n const label = $.el('label',\r\n {className: 'toggle-you'}\r\n ,\r\n {innerHTML: ' You'});\r\n const input = $('input', label);\r\n $.on(input, 'change', QuoteYou.menu.toggle);\r\n return Menu.menu?.addEntry({\r\n el: label,\r\n order: 80,\r\n open(post) {\r\n QuoteYou.menu.post = (post.origin || post);\r\n input.checked = QuoteYou.isYou(post);\r\n return true;\r\n }\r\n });\r\n },\r\n\r\n toggle() {\r\n const {post} = QuoteYou.menu;\r\n const data = {boardID: post.board.ID, threadID: post.thread.ID, postID: post.ID, val: true};\r\n if (this.checked) {\r\n QuoteYou.db.set(data);\r\n } else {\r\n QuoteYou.db.delete(data);\r\n }\r\n for (var clone of [post].concat(post.clones)) {\r\n clone.nodes.root.classList.toggle('yourPost', this.checked);\r\n }\r\n for (var quotelink of Get.allQuotelinksLinkingTo(post)) {\r\n if (this.checked) {\r\n if (Conf['Mark Quotes of You']) { $.add(quotelink, QuoteYou.mark.cloneNode(true)); }\r\n } else {\r\n $.rm($('.qmark-you', quotelink));\r\n }\r\n quotelink.classList.toggle('you', this.checked);\r\n if ($.hasClass(quotelink, 'quotelink')) {\r\n var quoter = Get.postFromNode(quotelink).nodes.root;\r\n quoter.classList.toggle('quotesYou', !!$('.quotelink.you', quoter));\r\n }\r\n }\r\n }\r\n },\r\n\r\n cb: {\r\n seek(type) {\r\n let highlighted, post;\r\n let result;\r\n const {highlight} = g.SITE.classes;\r\n if (highlighted = $(`.${highlight}`)) { $.rmClass(highlighted, highlight); }\r\n\r\n if (!QuoteYou.lastRead || !doc.contains(QuoteYou.lastRead) || !$.hasClass(QuoteYou.lastRead, 'quotesYou')) {\r\n if (!(post = (QuoteYou.lastRead = $('.quotesYou')))) {\r\n new Notice('warning', 'No posts are currently quoting you, loser.', 20);\r\n return;\r\n }\r\n if (QuoteYou.cb.scroll(post)) { return; }\r\n } else {\r\n post = QuoteYou.lastRead;\r\n }\r\n\r\n const str = `${type}::div[contains(@class,'quotesYou')]`;\r\n\r\n while (post = (result = $.X(str, post)).snapshotItem(type === 'preceding' ? result.snapshotLength - 1 : 0)) {\r\n if (QuoteYou.cb.scroll(post)) { return; }\r\n }\r\n\r\n const posts = $$('.quotesYou');\r\n return QuoteYou.cb.scroll(posts[type === 'following' ? 0 : posts.length - 1]);\r\n },\r\n\r\n scroll(root) {\r\n const post = Get.postFromRoot(root);\r\n if (!post.nodes.post.getBoundingClientRect().height) {\r\n return false;\r\n } else {\r\n QuoteYou.lastRead = root;\r\n location.href = Get.url('post', post);\r\n Header.scrollTo(post.nodes.post);\r\n if (post.isReply) {\r\n const sel = `${g.SITE.selectors.postContainer}${g.SITE.selectors.highlightable.reply}`;\r\n let node = post.nodes.root;\r\n if (!node.matches(sel)) { node = $(sel, node); }\r\n $.addClass(node, g.SITE.classes.highlight);\r\n }\r\n return true;\r\n }\r\n }\r\n }\r\n};\r\nexport default QuoteYou;\r\n","/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nexport default class RandomAccessList {\r\n constructor(items) {\r\n this.length = 0;\r\n if (items) { for (var item of items) { this.push(item); } }\r\n }\r\n\r\n push(data) {\r\n let item;\r\n let {ID} = data;\r\n if (!ID) { ID = data.id; }\r\n if (this[ID]) { return; }\r\n const {last} = this;\r\n this[ID] = (item = {\r\n prev: last,\r\n next: null,\r\n data,\r\n ID\r\n });\r\n item.prev = last;\r\n this.last = last ?\r\n (last.next = item)\r\n :\r\n (this.first = item);\r\n return this.length++;\r\n }\r\n\r\n before(root, item) {\r\n if ((item.next === root) || (item === root)) { return; }\r\n\r\n this.rmi(item);\r\n\r\n const {prev} = root;\r\n root.prev = item;\r\n item.next = root;\r\n item.prev = prev;\r\n if (prev) {\r\n return prev.next = item;\r\n } else {\r\n return this.first = item;\r\n }\r\n }\r\n\r\n after(root, item) {\r\n if ((item.prev === root) || (item === root)) { return; }\r\n\r\n this.rmi(item);\r\n\r\n const {next} = root;\r\n root.next = item;\r\n item.prev = root;\r\n item.next = next;\r\n if (next) {\r\n return next.prev = item;\r\n } else {\r\n return this.last = item;\r\n }\r\n }\r\n\r\n prepend(item) {\r\n const {first} = this;\r\n if ((item === first) || !this[item.ID]) { return; }\r\n this.rmi(item);\r\n item.next = first;\r\n if (first) {\r\n first.prev = item;\r\n } else {\r\n this.last = item;\r\n }\r\n this.first = item;\r\n return delete item.prev;\r\n }\r\n\r\n shift() {\r\n return this.rm(this.first.ID);\r\n }\r\n\r\n order() {\r\n let item;\r\n const order = [(item = this.first)];\r\n while ((item = item.next)) { order.push(item); }\r\n return order;\r\n }\r\n\r\n rm(ID) {\r\n const item = this[ID];\r\n if (!item) { return; }\r\n delete this[ID];\r\n this.length--;\r\n this.rmi(item);\r\n delete item.next;\r\n return delete item.prev;\r\n }\r\n\r\n rmi(item) {\r\n const {prev, next} = item;\r\n if (prev) {\r\n prev.next = next;\r\n } else {\r\n this.first = next;\r\n }\r\n if (next) {\r\n return next.prev = prev;\r\n } else {\r\n return this.last = prev;\r\n }\r\n }\r\n}\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport DataBoard from \"../classes/DataBoard\";\r\nimport RandomAccessList from \"../classes/RandomAccessList\";\r\nimport Get from \"../General/Get\";\r\nimport Header from \"../General/Header\";\r\nimport { g, Conf, d } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\nimport { debounce, SECOND } from \"../platform/helpers\";\r\nimport QuoteYou from \"../Quotelinks/QuoteYou\";\r\nimport Favicon from \"./Favicon\";\r\nimport ThreadWatcher from \"./ThreadWatcher\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS207: Consider shorter variations of null checks\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar Unread = {\r\n init() {\r\n if ((g.VIEW !== 'thread') || (\r\n !Conf['Unread Count'] &&\r\n !Conf['Unread Favicon'] &&\r\n !Conf['Unread Line'] &&\r\n !Conf['Remember Last Read Post'] &&\r\n !Conf['Desktop Notifications'] &&\r\n !Conf['Quote Threading']\r\n )) { return; }\r\n\r\n if (Conf['Remember Last Read Post']) {\r\n $.sync('Remember Last Read Post', enabled => Conf['Remember Last Read Post'] = enabled);\r\n this.db = new DataBoard('lastReadPosts', this.sync);\r\n }\r\n\r\n this.hr = $.el('hr', {\r\n id: 'unread-line',\r\n className: 'unread-line'\r\n }\r\n );\r\n this.posts = new Set();\r\n this.postsQuotingYou = new Set();\r\n this.order = new RandomAccessList();\r\n this.position = null;\r\n\r\n Callbacks.Thread.push({\r\n name: 'Unread',\r\n cb: this.node\r\n });\r\n\r\n return Callbacks.Post.push({\r\n name: 'Unread',\r\n cb: this.addPost\r\n });\r\n },\r\n\r\n node() {\r\n Unread.thread = this;\r\n Unread.title = d.title;\r\n Unread.lastReadPost = Unread.db?.get({\r\n boardID: this.board.ID,\r\n threadID: this.ID\r\n }) || 0;\r\n Unread.readCount = 0;\r\n for (var ID of this.posts.keys) { if (+ID <= Unread.lastReadPost) { Unread.readCount++; } }\r\n $.one(d, '4chanXInitFinished', Unread.ready);\r\n $.on(d, 'PostsInserted', Unread.onUpdate);\r\n $.on(d, 'ThreadUpdate', function(e) { if (e.detail[404]) { return Unread.update(); } });\r\n const resetLink = $.el('a', {\r\n href: 'javascript:;',\r\n className: 'unread-reset',\r\n textContent: 'Mark all unread'\r\n }\r\n );\r\n $.on(resetLink, 'click', Unread.reset);\r\n return Header.menu.addEntry({\r\n el: resetLink,\r\n order: 70\r\n });\r\n },\r\n\r\n ready() {\r\n if (Conf['Remember Last Read Post'] && Conf['Scroll to Last Read Post']) { Unread.scroll(); }\r\n Unread.setLine(true);\r\n Unread.read();\r\n Unread.update();\r\n $.on(d, 'scroll visibilitychange', Unread.read);\r\n if (Conf['Unread Line']) { return $.on(d, 'visibilitychange', Unread.setLine); }\r\n },\r\n\r\n positionPrev() {\r\n if (Unread.position) { return Unread.position.prev; } else { return Unread.order.last; }\r\n },\r\n\r\n scroll() {\r\n // Let the header's onload callback handle it.\r\n let hash;\r\n if ((hash = location.hash.match(/\\d+/)) && hash[0] in Unread.thread.posts) { return; }\r\n\r\n let position = Unread.positionPrev();\r\n while (position) {\r\n var {bottom} = position.data.nodes;\r\n if (!bottom.getBoundingClientRect().height) {\r\n // Don't try to scroll to posts with display: none\r\n position = position.prev;\r\n } else {\r\n Header.scrollToIfNeeded(bottom, true);\r\n break;\r\n }\r\n }\r\n },\r\n\r\n reset() {\r\n if (Unread.lastReadPost == null) { return; }\r\n\r\n Unread.posts = new Set();\r\n Unread.postsQuotingYou = new Set();\r\n Unread.order = new RandomAccessList();\r\n Unread.position = null;\r\n Unread.lastReadPost = 0;\r\n Unread.readCount = 0;\r\n Unread.thread.posts.forEach(post => Unread.addPost.call(post));\r\n\r\n $.forceSync('Remember Last Read Post');\r\n if (Conf['Remember Last Read Post'] && (!Unread.thread.isDead || Unread.thread.isArchived)) {\r\n Unread.db.set({\r\n boardID: Unread.thread.board.ID,\r\n threadID: Unread.thread.ID,\r\n val: 0\r\n });\r\n }\r\n\r\n Unread.updatePosition();\r\n Unread.setLine();\r\n return Unread.update();\r\n },\r\n\r\n sync() {\r\n if (Unread.lastReadPost == null) { return; }\r\n const lastReadPost = Unread.db.get({\r\n boardID: Unread.thread.board.ID,\r\n threadID: Unread.thread.ID,\r\n defaultValue: 0\r\n });\r\n if (Unread.lastReadPost >= lastReadPost) { return; }\r\n Unread.lastReadPost = lastReadPost;\r\n\r\n const postIDs = Unread.thread.posts.keys;\r\n for (let i = Unread.readCount, end = postIDs.length; i < end; i++) {\r\n var ID = +postIDs[i];\r\n if (!Unread.thread.posts.get(ID).isFetchedQuote) {\r\n if (ID > Unread.lastReadPost) { break; }\r\n Unread.posts.delete(ID);\r\n Unread.postsQuotingYou.delete(ID);\r\n }\r\n Unread.readCount++;\r\n }\r\n\r\n Unread.updatePosition();\r\n Unread.setLine();\r\n return Unread.update();\r\n },\r\n\r\n addPost() {\r\n if (this.isFetchedQuote || this.isClone) return;\r\n Unread.order.push(this);\r\n if ((this.ID <= Unread.lastReadPost) || this.isHidden || QuoteYou.isYou(this)) return;\r\n Unread.posts.add((Unread.posts.last = this.ID));\r\n Unread.addPostQuotingYou(this);\r\n return Unread.position != null ? Unread.position : (Unread.position = Unread.order[this.ID]);\r\n },\r\n\r\n addPostQuotingYou(post) {\r\n for (var quotelink of post.nodes.quotelinks) {\r\n if (QuoteYou.db?.get(Get.postDataFromLink(quotelink))) {\r\n Unread.postsQuotingYou.add((Unread.postsQuotingYou.last = post.ID));\r\n Unread.openNotification(post);\r\n return;\r\n }\r\n }\r\n },\r\n\r\n openNotification(post, predicate=' replied to you') {\r\n if (!Header.areNotificationsEnabled) { return; }\r\n const notif = new Notification(`${post.info.nameBlock}${predicate}`, {\r\n body: post.commentDisplay(),\r\n icon: Favicon.logo\r\n }\r\n );\r\n notif.onclick = function() {\r\n Header.scrollToIfNeeded(post.nodes.bottom, true);\r\n return window.focus();\r\n };\r\n return notif.onshow = () => setTimeout(() => notif.close()\r\n , 7 * SECOND);\r\n },\r\n\r\n onUpdate() {\r\n return $.queueTask(function() { // ThreadUpdater may scroll immediately after inserting posts\r\n Unread.setLine();\r\n Unread.read();\r\n return Unread.update();\r\n });\r\n },\r\n\r\n readSinglePost(post) {\r\n const {ID} = post;\r\n if (!Unread.posts.has(ID)) { return; }\r\n Unread.posts.delete(ID);\r\n Unread.postsQuotingYou.delete(ID);\r\n Unread.updatePosition();\r\n Unread.saveLastReadPost();\r\n return Unread.update();\r\n },\r\n\r\n read: debounce(100, function(e) {\r\n // Update the lastReadPost when hidden posts are added to the thread.\r\n if (!Unread.posts.size && (Unread.readCount !== Unread.thread.posts.keys.length)) {\r\n Unread.saveLastReadPost();\r\n }\r\n\r\n if (d.hidden || !Unread.posts.size) { return; }\r\n\r\n let count = 0;\r\n while (Unread.position) {\r\n var {ID, data} = Unread.position;\r\n var {bottom} = data.nodes;\r\n if (!!bottom.getBoundingClientRect().height && // post has been hidden\r\n (Header.getBottomOf(bottom) <= -1)) { break; } // post is completely read\r\n count++;\r\n Unread.posts.delete(ID);\r\n Unread.postsQuotingYou.delete(ID);\r\n Unread.position = Unread.position.next;\r\n }\r\n\r\n if (!count) { return; }\r\n Unread.updatePosition();\r\n Unread.saveLastReadPost();\r\n if (e) { return Unread.update(); }\r\n }),\r\n\r\n updatePosition() {\r\n while (Unread.position && !Unread.posts.has(Unread.position.ID)) {\r\n Unread.position = Unread.position.next;\r\n }\r\n },\r\n\r\n saveLastReadPost: debounce(2 * SECOND, function() {\r\n let ID;\r\n $.forceSync('Remember Last Read Post');\r\n if (!Conf['Remember Last Read Post'] || !Unread.db) { return; }\r\n const postIDs = Unread.thread.posts.keys;\r\n for (let i = Unread.readCount, end = postIDs.length; i < end; i++) {\r\n ID = +postIDs[i];\r\n if (!Unread.thread.posts.get(ID).isFetchedQuote) {\r\n if (Unread.posts.has(ID)) { break; }\r\n Unread.lastReadPost = ID;\r\n }\r\n Unread.readCount++;\r\n }\r\n if (Unread.thread.isDead && !Unread.thread.isArchived) { return; }\r\n return Unread.db.set({\r\n boardID: Unread.thread.board.ID,\r\n threadID: Unread.thread.ID,\r\n val: Unread.lastReadPost\r\n });\r\n }),\r\n\r\n setLine(force) {\r\n if (!Conf['Unread Line']) { return; }\r\n if (Unread.hr.hidden || d.hidden || (force === true)) {\r\n const oldPosition = Unread.linePosition;\r\n if (Unread.linePosition = Unread.positionPrev()) {\r\n if (Unread.linePosition !== oldPosition) {\r\n let node = Unread.linePosition.data.nodes.bottom;\r\n if (node.nextSibling?.tagName === 'BR') { node = node.nextSibling; }\r\n $.after(node, Unread.hr);\r\n }\r\n } else {\r\n $.rm(Unread.hr);\r\n }\r\n }\r\n return Unread.hr.hidden = Unread.linePosition === Unread.order.last;\r\n },\r\n\r\n update() {\r\n const count = Unread.posts.size;\r\n const countQuotingYou = Unread.postsQuotingYou.size;\r\n\r\n if (Conf['Unread Count']) {\r\n const titleQuotingYou = Conf['Quoted Title'] && countQuotingYou ? '(!) ' : '';\r\n const titleCount = count || !Conf['Hide Unread Count at (0)'] ? `(${count}) ` : '';\r\n const titleDead = Unread.thread.isDead ?\r\n Unread.title.replace('-', (Unread.thread.isArchived ? '- Archived -' : '- 404 -'))\r\n :\r\n Unread.title;\r\n d.title = `${titleQuotingYou}${titleCount}${titleDead}`;\r\n }\r\n\r\n Unread.saveThreadWatcherCount();\r\n\r\n if (Conf['Unread Favicon'] && (g.SITE.software === 'yotsuba')) {\r\n const {isDead} = Unread.thread;\r\n return Favicon.set((\r\n countQuotingYou ?\r\n (isDead ? 'unreadDeadY' : 'unreadY')\r\n : count ?\r\n (isDead ? 'unreadDead' : 'unread')\r\n :\r\n (isDead ? 'dead' : 'default')\r\n )\r\n );\r\n }\r\n },\r\n\r\n saveThreadWatcherCount: debounce(2 * SECOND, function() {\r\n $.forceSync('Remember Last Read Post');\r\n if (Conf['Remember Last Read Post'] && (!Unread.thread.isDead || Unread.thread.isArchived)) {\r\n let posts;\r\n const quotingYou = !Conf['Require OP Quote Link'] && QuoteYou.isYou(Unread.thread.OP) ? Unread.posts : Unread.postsQuotingYou;\r\n if (!quotingYou.size) {\r\n quotingYou.last = 0;\r\n } else if (!quotingYou.has(quotingYou.last)) {\r\n quotingYou.last = 0;\r\n posts = Unread.thread.posts.keys;\r\n for (let i = posts.length - 1; i >= 0; i--) {\r\n if (quotingYou.has(+posts[i])) {\r\n quotingYou.last = posts[i];\r\n break;\r\n }\r\n }\r\n }\r\n return ThreadWatcher.update(g.SITE.ID, Unread.thread.board.ID, Unread.thread.ID, {\r\n last: Unread.thread.lastPost,\r\n isDead: Unread.thread.isDead,\r\n isArchived: Unread.thread.isArchived,\r\n unread: Unread.posts.size,\r\n quotingYou: (quotingYou.last || 0)\r\n }\r\n );\r\n }\r\n })\r\n};\r\nexport default Unread;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport Post from \"../classes/Post\";\r\nimport Get from \"../General/Get\";\r\nimport Index from \"../General/Index\";\r\nimport { g, Conf, d } from \"../globals/globals\";\r\nimport Main from \"../main/Main\";\r\nimport $ from \"../platform/$\";\r\nimport $$ from \"../platform/$$\";\r\nimport { dict } from \"../platform/helpers\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar ExpandThread = {\r\n statuses: dict(),\r\n init() {\r\n if (!((g.VIEW === 'index') && Conf['Thread Expansion'])) { return; }\r\n if (Conf['JSON Index']) {\r\n return $.on(d, 'IndexRefreshInternal', this.onIndexRefresh);\r\n } else {\r\n return Callbacks.Thread.push({\r\n name: 'Expand Thread',\r\n cb() { return ExpandThread.setButton(this); }\r\n });\r\n }\r\n },\r\n\r\n setButton(thread) {\r\n let a;\r\n if (!(thread.nodes.root && (a = $('.summary', thread.nodes.root)))) { return; }\r\n a.textContent = g.SITE.Build.summaryText('+', ...a.textContent.match(/\\d+/g));\r\n a.style.cursor = 'pointer';\r\n return $.on(a, 'click', ExpandThread.cbToggle);\r\n },\r\n \r\n disconnect(refresh) {\r\n if ((g.VIEW === 'thread') || !Conf['Thread Expansion']) { return; }\r\n for (var threadID in ExpandThread.statuses) {\r\n var oldReq;\r\n var status = ExpandThread.statuses[threadID];\r\n if (oldReq = status.req) {\r\n delete status.req;\r\n oldReq.abort();\r\n }\r\n delete ExpandThread.statuses[threadID];\r\n }\r\n\r\n if (!refresh) { return $.off(d, 'IndexRefreshInternal', this.onIndexRefresh); }\r\n },\r\n\r\n onIndexRefresh() {\r\n ExpandThread.disconnect(true);\r\n return g.BOARD.threads.forEach(thread => ExpandThread.setButton(thread));\r\n },\r\n\r\n cbToggle(e) {\r\n if ($.modifiedClick(e)) { return; }\r\n e.preventDefault();\r\n return ExpandThread.toggle(Get.threadFromNode(this));\r\n },\r\n\r\n cbToggleBottom(e) {\r\n if ($.modifiedClick(e)) { return; }\r\n e.preventDefault();\r\n const thread = Get.threadFromNode(this);\r\n $.rm(this); // remove before fixing bottom of thread position\r\n const {bottom} = thread.nodes.root.getBoundingClientRect();\r\n ExpandThread.toggle(thread);\r\n return window.scrollBy(0, (thread.nodes.root.getBoundingClientRect().bottom - bottom));\r\n },\r\n\r\n toggle(thread) {\r\n let a;\r\n if (!(thread.nodes.root && (a = $('.summary', thread.nodes.root)))) { return; }\r\n if (thread.ID in ExpandThread.statuses) {\r\n return ExpandThread.contract(thread, a, thread.nodes.root);\r\n } else {\r\n return ExpandThread.expand(thread, a);\r\n }\r\n },\r\n\r\n expand(thread, a) {\r\n let status;\r\n ExpandThread.statuses[thread] = (status = {});\r\n a.textContent = g.SITE.Build.summaryText('...', ...a.textContent.match(/\\d+/g));\r\n status.req = $.cache(g.SITE.urls.threadJSON({boardID: thread.board.ID, threadID: thread.ID}), function() {\r\n if (this !== status.req) { return; } // aborted\r\n delete status.req;\r\n return ExpandThread.parse(this, thread, a);\r\n });\r\n return status.numReplies = $$(g.SITE.selectors.replyOriginal, thread.nodes.root).length;\r\n },\r\n\r\n contract(thread, a, threadRoot) {\r\n let oldReq;\r\n const status = ExpandThread.statuses[thread];\r\n delete ExpandThread.statuses[thread];\r\n if (oldReq = status.req) {\r\n delete status.req;\r\n oldReq.abort();\r\n if (a) { a.textContent = g.SITE.Build.summaryText('+', ...a.textContent.match(/\\d+/g)); }\r\n return;\r\n }\r\n\r\n let replies = $$('.thread > .replyContainer', threadRoot);\r\n if (status.numReplies) { replies = replies.slice(0, (-status.numReplies)); }\r\n let postsCount = 0;\r\n let filesCount = 0;\r\n for (var reply of replies) {\r\n // rm clones\r\n if (Conf['Quote Inlining']) { var inlined;\r\n while ((inlined = $('.inlined', reply))) { inlined.click(); } }\r\n postsCount++;\r\n if ('file' in Get.postFromRoot(reply)) { filesCount++; }\r\n $.rm(reply);\r\n }\r\n if (Index.enabled) { // otherwise handled by Main.addPosts\r\n $.event('PostsRemoved', null, a.parentNode);\r\n }\r\n a.textContent = g.SITE.Build.summaryText('+', postsCount, filesCount);\r\n return $.rm($('.summary-bottom', threadRoot));\r\n },\r\n\r\n parse(req, thread, a) {\r\n let root;\r\n if (![200, 304].includes(req.status)) {\r\n a.textContent = req.status ? `Error ${req.statusText} (${req.status})` : 'Connection Error';\r\n return;\r\n }\r\n\r\n g.SITE.Build.spoilerRange[thread.board] = req.response.posts[0].custom_spoiler;\r\n\r\n const posts = [];\r\n const postsRoot = [];\r\n let filesCount = 0;\r\n for (var postData of req.response.posts) {\r\n var post;\r\n if (postData.no === thread.ID) { continue; }\r\n if ((post = thread.posts.get(postData.no)) && !post.isFetchedQuote) {\r\n if ('file' in post) { filesCount++; }\r\n ({root} = post.nodes);\r\n postsRoot.push(root);\r\n continue;\r\n }\r\n root = g.SITE.Build.postFromObject(postData, thread.board.ID);\r\n post = new Post(root, thread, thread.board);\r\n if ('file' in post) { filesCount++; }\r\n posts.push(post);\r\n postsRoot.push(root);\r\n }\r\n Main.callbackNodes('Post', posts);\r\n $.after(a, postsRoot);\r\n $.event('PostsInserted', null, a.parentNode);\r\n\r\n const postsCount = postsRoot.length;\r\n a.textContent = g.SITE.Build.summaryText('-', postsCount, filesCount);\r\n\r\n if (root) {\r\n const a2 = a.cloneNode(true);\r\n a2.classList.add('summary-bottom');\r\n $.on(a2, 'click', ExpandThread.cbToggleBottom);\r\n return $.after(root, a2);\r\n }\r\n }\r\n};\r\nexport default ExpandThread;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport DataBoard from \"../classes/DataBoard\";\r\nimport Get from \"../General/Get\";\r\nimport Header from \"../General/Header\";\r\nimport Index from \"../General/Index\";\r\nimport { g, Conf, d } from \"../globals/globals\";\r\nimport ExpandThread from \"../Miscellaneous/ExpandThread\";\r\nimport $ from \"../platform/$\";\r\nimport { dict } from \"../platform/helpers\";\r\nimport QuoteYou from \"../Quotelinks/QuoteYou\";\r\nimport ThreadWatcher from \"./ThreadWatcher\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS205: Consider reworking code to avoid use of IIFEs\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar UnreadIndex = {\r\n lastReadPost: dict(),\r\n hr: dict(),\r\n markReadLink: dict(),\r\n\r\n init() {\r\n if ((g.VIEW !== 'index') || !Conf['Remember Last Read Post'] || !Conf['Unread Line in Index']) { return; }\r\n\r\n this.enabled = true;\r\n this.db = new DataBoard('lastReadPosts', this.sync);\r\n\r\n Callbacks.Thread.push({\r\n name: 'Unread Line in Index',\r\n cb: this.node\r\n });\r\n\r\n $.on(d, 'IndexRefreshInternal', this.onIndexRefresh);\r\n return $.on(d, 'PostsInserted PostsRemoved', this.onPostsInserted);\r\n },\r\n\r\n node() {\r\n UnreadIndex.lastReadPost[this.fullID] = UnreadIndex.db.get({\r\n boardID: this.board.ID,\r\n threadID: this.ID\r\n }) || 0;\r\n if (!Index.enabled) { // let onIndexRefresh handle JSON Index\r\n return UnreadIndex.update(this);\r\n }\r\n },\r\n\r\n onIndexRefresh(e) {\r\n if (e.detail.isCatalog) { return; }\r\n return (() => {\r\n const result = [];\r\n for (var threadID of e.detail.threadIDs) {\r\n var thread = g.threads.get(threadID);\r\n result.push(UnreadIndex.update(thread));\r\n }\r\n return result;\r\n })();\r\n },\r\n\r\n onPostsInserted(e) {\r\n if (e.target === Index.root) { return; } // onIndexRefresh handles this case\r\n const thread = Get.threadFromNode(e.target);\r\n if (!thread || (thread.nodes.root !== e.target)) { return; }\r\n const wasVisible = !!UnreadIndex.hr[thread.fullID]?.parentNode;\r\n UnreadIndex.update(thread);\r\n if (Conf['Scroll to Last Read Post'] && (e.type === 'PostsInserted') && !wasVisible && !!UnreadIndex.hr[thread.fullID]?.parentNode) {\r\n return Header.scrollToIfNeeded(UnreadIndex.hr[thread.fullID], true);\r\n }\r\n },\r\n\r\n sync() {\r\n return g.threads.forEach(function(thread) {\r\n const lastReadPost = UnreadIndex.db.get({\r\n boardID: thread.board.ID,\r\n threadID: thread.ID\r\n }) || 0;\r\n if (lastReadPost !== UnreadIndex.lastReadPost[thread.fullID]) {\r\n UnreadIndex.lastReadPost[thread.fullID] = lastReadPost;\r\n if (thread.nodes.root?.parentNode) {\r\n return UnreadIndex.update(thread);\r\n }\r\n }\r\n });\r\n },\r\n\r\n update(thread) {\r\n let divider;\r\n const lastReadPost = UnreadIndex.lastReadPost[thread.fullID];\r\n let repliesShown = 0;\r\n let repliesRead = 0;\r\n let firstUnread = null;\r\n thread.posts.forEach(function(post) {\r\n if (post.isReply && thread.nodes.root.contains(post.nodes.root)) {\r\n repliesShown++;\r\n if (post.ID <= lastReadPost) {\r\n return repliesRead++;\r\n } else if ((!firstUnread || (post.ID < firstUnread.ID)) && !post.isHidden && !QuoteYou.isYou(post)) {\r\n return firstUnread = post;\r\n }\r\n }\r\n });\r\n\r\n let hr = UnreadIndex.hr[thread.fullID];\r\n if (firstUnread && (repliesRead || ((lastReadPost === thread.OP.ID) && (!$(g.SITE.selectors.summary, thread.nodes.root) || thread.ID in ExpandThread.statuses)))) {\r\n if (!hr) {\r\n hr = (UnreadIndex.hr[thread.fullID] = $.el('hr',\r\n {className: 'unread-line'}));\r\n }\r\n $.before(firstUnread.nodes.root, hr);\r\n } else {\r\n $.rm(hr);\r\n }\r\n\r\n const hasUnread = repliesShown ?\r\n firstUnread || !repliesRead\r\n : Index.enabled ?\r\n thread.lastPost > lastReadPost\r\n :\r\n thread.OP.ID > lastReadPost;\r\n thread.nodes.root.classList.toggle('unread-thread', hasUnread);\r\n\r\n let link = UnreadIndex.markReadLink[thread.fullID];\r\n if (!link) {\r\n link = (UnreadIndex.markReadLink[thread.fullID] = $.el('a', {\r\n className: 'unread-mark-read brackets-wrap',\r\n href: 'javascript:;',\r\n textContent: 'Mark Read'\r\n }\r\n ));\r\n $.on(link, 'click', UnreadIndex.markRead);\r\n }\r\n if (divider = $(g.SITE.selectors.threadDivider, thread.nodes.root)) { // divider inside thread as in Tinyboard\r\n return $.before(divider, link);\r\n } else {\r\n return $.add(thread.nodes.root, link);\r\n }\r\n },\r\n\r\n markRead() {\r\n const thread = Get.threadFromNode(this);\r\n UnreadIndex.lastReadPost[thread.fullID] = thread.lastPost;\r\n UnreadIndex.db.set({\r\n boardID: thread.board.ID,\r\n threadID: thread.ID,\r\n val: thread.lastPost\r\n });\r\n $.rm(UnreadIndex.hr[thread.fullID]);\r\n thread.nodes.root.classList.remove('unread-thread');\r\n return ThreadWatcher.update(g.SITE.ID, thread.board.ID, thread.ID, {\r\n last: thread.lastPost,\r\n unread: 0,\r\n quotingYou: 0\r\n }\r\n );\r\n }\r\n};\r\nexport default UnreadIndex;\r\n","import ThreadWatcherPage from './ThreadWatcher/ThreadWatcher.html';\r\nimport $ from \"../platform/$\";\r\nimport Board from '../classes/Board';\r\nimport Callbacks from '../classes/Callbacks';\r\nimport DataBoard from '../classes/DataBoard';\r\nimport Thread from '../classes/Thread';\r\nimport Filter from '../Filtering/Filter';\r\nimport Main from '../main/Main';\r\nimport $$ from '../platform/$$';\r\nimport Config from '../config/Config';\r\nimport CrossOrigin from '../platform/CrossOrigin';\r\nimport PostRedirect from '../Posting/PostRedirect';\r\nimport QuoteYou from '../Quotelinks/QuoteYou';\r\nimport Unread from './Unread';\r\nimport UnreadIndex from './UnreadIndex';\r\nimport Header from '../General/Header';\r\nimport Index from '../General/Index';\r\nimport { Conf, d, doc, g } from '../globals/globals';\r\nimport Menu from '../Menu/Menu';\r\nimport UI from '../General/UI';\r\nimport Get from '../General/Get';\r\nimport { dict, HOUR, MINUTE } from '../platform/helpers';\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS104: Avoid inline assignments\r\n * DS207: Consider shorter variations of null checks\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\n\r\nvar ThreadWatcher = {\r\n init() {\r\n let sc;\r\n if (!(this.enabled = Conf['Thread Watcher'])) { return; }\r\n\r\n this.shortcut = (sc = $.el('a', {\r\n id: 'watcher-link',\r\n textContent: '👁︎',\r\n title: 'Thread Watcher',\r\n href: 'javascript:;',\r\n }\r\n ));\r\n\r\n this.db = new DataBoard('watchedThreads', this.refresh, true);\r\n this.dbLM = new DataBoard('watcherLastModified', null, true);\r\n this.dialog = UI.dialog('thread-watcher', { innerHTML: ThreadWatcherPage });\r\n this.status = $('#watcher-status', this.dialog);\r\n this.list = this.dialog.lastElementChild;\r\n this.refreshButton = $('.refresh', this.dialog);\r\n this.closeButton = $('.move > .close', this.dialog);\r\n this.unreaddb = Unread.db || UnreadIndex.db || new DataBoard('lastReadPosts');\r\n this.unreadEnabled = Conf['Remember Last Read Post'];\r\n\r\n $.on(d, 'QRPostSuccessful', this.cb.post);\r\n $.on(sc, 'click', this.toggleWatcher);\r\n $.on(this.refreshButton, 'click', this.buttonFetchAll);\r\n $.on(this.closeButton, 'click', this.toggleWatcher);\r\n\r\n this.menu.addHeaderMenuEntry();\r\n $.onExists(doc, 'body', this.addDialog);\r\n\r\n switch (g.VIEW) {\r\n case 'index':\r\n $.on(d, 'IndexUpdate', this.cb.onIndexUpdate);\r\n break;\r\n case 'thread':\r\n $.on(d, 'ThreadUpdate', this.cb.onThreadRefresh);\r\n break;\r\n }\r\n\r\n if (Conf['Fixed Thread Watcher']) {\r\n $.addClass(doc, 'fixed-watcher');\r\n }\r\n if (!Conf['Persistent Thread Watcher']) {\r\n $.addClass(ThreadWatcher.shortcut, 'disabled');\r\n this.dialog.hidden = true;\r\n }\r\n\r\n Header.addShortcut('watcher', sc, 510);\r\n\r\n ThreadWatcher.initLastModified();\r\n ThreadWatcher.fetchAuto();\r\n $.on(window, 'visibilitychange focus', () => $.queueTask(ThreadWatcher.fetchAuto));\r\n\r\n if (Conf['Menu'] && Index.enabled) {\r\n Menu.menu.addEntry({\r\n el: $.el('a', {\r\n href: 'javascript:;',\r\n className: 'has-shortcut-text'\r\n }\r\n , {innerHTML: 'Alt+click'}),\r\n order: 6,\r\n open({thread}) {\r\n if (Conf['Index Mode'] !== 'catalog') { return false; }\r\n this.el.firstElementChild.textContent = ThreadWatcher.isWatched(thread) ?\r\n 'Unwatch'\r\n :\r\n 'Watch';\r\n if (this.cb) { $.off(this.el, 'click', this.cb); }\r\n this.cb = function() {\r\n $.event('CloseMenu');\r\n return ThreadWatcher.toggle(thread);\r\n };\r\n $.on(this.el, 'click', this.cb);\r\n return true;\r\n }\r\n });\r\n }\r\n\r\n if (!['index', 'thread'].includes(g.VIEW)) { return; }\r\n\r\n Callbacks.Post.push({\r\n name: 'Thread Watcher',\r\n cb: this.node\r\n });\r\n return Callbacks.CatalogThread.push({\r\n name: 'Thread Watcher',\r\n cb: this.catalogNode\r\n });\r\n },\r\n\r\n isWatched(thread) {\r\n return !!ThreadWatcher.db?.get({boardID: thread.board.ID, threadID: thread.ID});\r\n },\r\n\r\n isWatchedRaw(boardID, threadID) {\r\n return !!ThreadWatcher.db?.get({boardID, threadID});\r\n },\r\n\r\n setToggler(toggler, isWatched) {\r\n toggler.classList.toggle('watched', isWatched);\r\n return toggler.title = `${isWatched ? 'Unwatch' : 'Watch'} Thread`;\r\n },\r\n\r\n node() {\r\n let toggler;\r\n if (this.isReply) { return; }\r\n if (this.isClone) {\r\n toggler = $('.watch-thread-link', this.nodes.info);\r\n } else {\r\n toggler = $.el('a', {\r\n href: 'javascript:;',\r\n className: 'watch-thread-link'\r\n }\r\n );\r\n $.before($('input', this.nodes.info), toggler);\r\n }\r\n const siteID = g.SITE.ID;\r\n const boardID = this.board.ID;\r\n const threadID = this.thread.ID;\r\n const data = ThreadWatcher.db.get({siteID, boardID, threadID});\r\n ThreadWatcher.setToggler(toggler, !!data);\r\n $.on(toggler, 'click', ThreadWatcher.cb.toggle);\r\n // Add missing excerpt for threads added by Auto Watch\r\n if (data && (data.excerpt == null)) {\r\n return $.queueTask(() => {\r\n return ThreadWatcher.update(siteID, boardID, threadID, {excerpt: Get.threadExcerpt(this.thread)});\r\n });\r\n }\r\n },\r\n\r\n catalogNode() {\r\n if (ThreadWatcher.isWatched(this.thread)) { $.addClass(this.nodes.root, 'watched'); }\r\n return $.on(this.nodes.root, 'mousedown click', e => {\r\n if ((e.button !== 0) || !e.altKey) { return; }\r\n if (e.type === 'click') { ThreadWatcher.toggle(this.thread); }\r\n return e.preventDefault();\r\n });\r\n }, // Also on mousedown to prevent highlighting thumbnail in Firefox.\r\n\r\n addDialog() {\r\n if (!Main.isThisPageLegit()) { return; }\r\n ThreadWatcher.build();\r\n return $.prepend(d.body, ThreadWatcher.dialog);\r\n },\r\n\r\n toggleWatcher() {\r\n $.toggleClass(ThreadWatcher.shortcut, 'disabled');\r\n return ThreadWatcher.dialog.hidden = !ThreadWatcher.dialog.hidden;\r\n },\r\n\r\n cb: {\r\n openAll() {\r\n if ($.hasClass(this, 'disabled')) { return; }\r\n for (var a of $$('a.watcher-link', ThreadWatcher.list)) {\r\n $.open(a.href);\r\n }\r\n return $.event('CloseMenu');\r\n },\r\n openUnread() {\r\n if ($.hasClass(this, 'disabled')) { return; }\r\n for (var a of $$('.replies-unread > a.watcher-link', ThreadWatcher.list)) {\r\n $.open(a.href);\r\n }\r\n return $.event('CloseMenu');\r\n },\r\n openDeads() {\r\n if ($.hasClass(this, 'disabled')) { return; }\r\n for (var a of $$('.dead-thread > a.watcher-link', ThreadWatcher.list)) {\r\n $.open(a.href);\r\n }\r\n return $.event('CloseMenu');\r\n },\r\n pruneDeads() {\r\n if ($.hasClass(this, 'disabled')) { return; }\r\n for (var {siteID, boardID, threadID, data} of ThreadWatcher.getAll()) {\r\n if (data.isDead) {\r\n ThreadWatcher.db.delete({siteID, boardID, threadID});\r\n }\r\n }\r\n ThreadWatcher.refresh();\r\n return $.event('CloseMenu');\r\n },\r\n dismiss() {\r\n for (var {siteID, boardID, threadID, data} of ThreadWatcher.getAll()) {\r\n if (data.quotingYou) {\r\n ThreadWatcher.update(siteID, boardID, threadID, {dismiss: data.quotingYou || 0});\r\n }\r\n }\r\n return $.event('CloseMenu');\r\n },\r\n toggle() {\r\n const {thread} = Get.postFromNode(this);\r\n return ThreadWatcher.toggle(thread);\r\n },\r\n rm() {\r\n const {siteID} = this.parentNode.dataset;\r\n const [boardID, threadID] = this.parentNode.dataset.fullID.split('.');\r\n return ThreadWatcher.rm(siteID, boardID, +threadID);\r\n },\r\n post(e) {\r\n const {boardID, threadID, postID} = e.detail;\r\n const cb = PostRedirect.delay();\r\n if (postID === threadID) {\r\n if (Conf['Auto Watch']) {\r\n return ThreadWatcher.addRaw(boardID, threadID, {}, cb);\r\n }\r\n } else if (Conf['Auto Watch Reply']) {\r\n return ThreadWatcher.add((g.threads.get(boardID + '.' + threadID) || new Thread(threadID, g.boards[boardID] || new Board(boardID))), cb);\r\n }\r\n },\r\n onIndexUpdate(e) {\r\n const {db} = ThreadWatcher;\r\n const siteID = g.SITE.ID;\r\n const boardID = g.BOARD.ID;\r\n let nKilled = 0;\r\n for (var threadID in db.data[siteID].boards[boardID]) {\r\n // Don't prune threads that have yet to appear in index.\r\n var data = db.data[siteID].boards[boardID][threadID];\r\n if (!data?.isDead && !e.detail.threads.includes(`${boardID}.${threadID}`)) {\r\n if (!e.detail.threads.some(fullID => +fullID.split('.')[1] > threadID)) { continue; }\r\n if (Conf['Auto Prune'] || !(data && (typeof data === 'object'))) { // corrupt data\r\n db.delete({boardID, threadID});\r\n nKilled++;\r\n } else {\r\n ThreadWatcher.fetchStatus({siteID, boardID, threadID, data});\r\n }\r\n }\r\n }\r\n if (nKilled) { return ThreadWatcher.refresh(); }\r\n },\r\n onThreadRefresh(e) {\r\n const thread = g.threads.get(e.detail.threadID);\r\n if (!e.detail[404] || !ThreadWatcher.isWatched(thread)) { return; }\r\n // Update dead status.\r\n return ThreadWatcher.add(thread);\r\n }\r\n },\r\n\r\n requests: [],\r\n fetched: 0,\r\n\r\n fetch(url, {siteID, force}, args, cb) {\r\n if (ThreadWatcher.requests.length === 0) {\r\n ThreadWatcher.status.textContent = '...';\r\n $.addClass(ThreadWatcher.refreshButton, 'spin');\r\n }\r\n const onloadend = function() {\r\n if (this.finished) { return; }\r\n this.finished = true;\r\n ThreadWatcher.fetched++;\r\n if (ThreadWatcher.fetched === ThreadWatcher.requests.length) {\r\n ThreadWatcher.clearRequests();\r\n } else {\r\n ThreadWatcher.status.textContent = `${Math.round((ThreadWatcher.fetched / ThreadWatcher.requests.length) * 100)}%`;\r\n }\r\n return cb.apply(this, args);\r\n };\r\n const ajax = siteID === g.SITE.ID ? $.ajax : CrossOrigin.ajax;\r\n if (force) {\r\n delete $.lastModified.ThreadWatcher?.[url];\r\n }\r\n const req = $.whenModified(\r\n url,\r\n 'ThreadWatcher',\r\n onloadend,\r\n { timeout: MINUTE, ajax }\r\n );\r\n return ThreadWatcher.requests.push(req);\r\n },\r\n\r\n clearRequests() {\r\n ThreadWatcher.requests = [];\r\n ThreadWatcher.fetched = 0;\r\n ThreadWatcher.status.textContent = '';\r\n return $.rmClass(ThreadWatcher.refreshButton, 'spin');\r\n },\r\n\r\n abort() {\r\n delete ThreadWatcher.syncing;\r\n for (var req of ThreadWatcher.requests) {\r\n if (!req.finished) {\r\n req.finished = true;\r\n req.abort();\r\n }\r\n }\r\n return ThreadWatcher.clearRequests();\r\n },\r\n\r\n initLastModified() {\r\n const lm = ($.lastModified['ThreadWatcher'] || ($.lastModified['ThreadWatcher'] = dict()));\r\n for (var siteID in ThreadWatcher.dbLM.data) {\r\n var boards = ThreadWatcher.dbLM.data[siteID];\r\n for (var boardID in boards.boards) {\r\n var data = boards.boards[boardID];\r\n if (ThreadWatcher.db.get({siteID, boardID})) {\r\n for (var url in data) {\r\n var date = data[url];\r\n lm[url] = date;\r\n }\r\n } else {\r\n ThreadWatcher.dbLM.delete({siteID, boardID});\r\n }\r\n }\r\n }\r\n },\r\n\r\n fetchAuto() {\r\n let middle;\r\n clearTimeout(ThreadWatcher.timeout);\r\n if (!Conf['Auto Update Thread Watcher']) { return; }\r\n const {db} = ThreadWatcher;\r\n const interval = Conf['Show Page'] || (ThreadWatcher.unreadEnabled && Conf['Show Unread Count']) ? 5 * MINUTE : 2 * HOUR;\r\n const now = Date.now();\r\n if ((now - interval >= ((middle = db.data.lastChecked || 0)) || middle > now) && !d.hidden && !!d.hasFocus()) {\r\n ThreadWatcher.fetchAllStatus(interval);\r\n }\r\n return ThreadWatcher.timeout = setTimeout(ThreadWatcher.fetchAuto, interval);\r\n },\r\n\r\n buttonFetchAll() {\r\n if (ThreadWatcher.syncing || ThreadWatcher.requests.length) {\r\n return ThreadWatcher.abort();\r\n } else {\r\n return ThreadWatcher.fetchAllStatus();\r\n }\r\n },\r\n\r\n fetchAllStatus(interval=0) {\r\n ThreadWatcher.status.textContent = '...';\r\n $.addClass(ThreadWatcher.refreshButton, 'spin');\r\n ThreadWatcher.syncing = true;\r\n const dbs = [ThreadWatcher.db, ThreadWatcher.unreaddb, QuoteYou.db].filter(x => x);\r\n let n = 0;\r\n return dbs.map((dbi) =>\r\n dbi.forceSync(function() {\r\n if ((++n) === dbs.length) {\r\n let middle;\r\n if (!ThreadWatcher.syncing) { return; } // aborted\r\n delete ThreadWatcher.syncing;\r\n if (0 > (middle = Date.now() - (ThreadWatcher.db.data.lastChecked || 0)) || middle >= interval) { // not checked in another tab\r\n // XXX On vichan boards, last_modified field of threads.json does not account for sage posts.\r\n // Occasionally check replies field of catalog.json to find these posts.\r\n let middle1;\r\n const {db} = ThreadWatcher;\r\n const now = Date.now();\r\n const deep = !(now - (2 * HOUR) < ((middle1 = db.data.lastChecked2 || 0)) && middle1 <= now);\r\n const boards = ThreadWatcher.getAll(true);\r\n for (var board of boards) {\r\n ThreadWatcher.fetchBoard(board, deep);\r\n }\r\n db.setLastChecked();\r\n if (deep) { db.setLastChecked('lastChecked2'); }\r\n }\r\n if (ThreadWatcher.fetched === ThreadWatcher.requests.length) {\r\n return ThreadWatcher.clearRequests();\r\n }\r\n }\r\n }));\r\n },\r\n\r\n fetchBoard(board, deep) {\r\n if (!board.some(thread => !thread.data.isDead)) { return; }\r\n let force = false;\r\n for (var thread of board) {\r\n var {data} = thread;\r\n if (!data.isDead && (data.last !== -1)) {\r\n if (Conf['Show Page'] && (data.page == null)) { force = true; }\r\n if ((data.modified == null)) { force = (thread.force = true); }\r\n }\r\n }\r\n const {siteID, boardID} = board[0];\r\n const site = g.sites[siteID];\r\n if (!site) { return; }\r\n const urlF = deep && site.threadModTimeIgnoresSage ? 'catalogJSON' : 'threadsListJSON';\r\n const url = site.urls[urlF]?.({siteID, boardID});\r\n if (!url) { return; }\r\n return ThreadWatcher.fetch(url, {siteID, force}, [board, url], ThreadWatcher.parseBoard);\r\n },\r\n\r\n parseBoard(board, url) {\r\n let page, thread;\r\n if (this.status !== 200) { return; }\r\n const {siteID, boardID} = board[0];\r\n const lmDate = this.getResponseHeader('Last-Modified');\r\n ThreadWatcher.dbLM.extend({siteID, boardID, val: $.item(url, lmDate)});\r\n const threads = dict();\r\n let pageLength = 0;\r\n let nThreads = 0;\r\n let oldest = null;\r\n try {\r\n pageLength = this.response[0]?.threads.length || 0;\r\n for (let i = 0; i < this.response.length; i++) {\r\n page = this.response[i];\r\n for (var item of page.threads) {\r\n threads[item.no] = {\r\n page: i + 1,\r\n index: nThreads,\r\n modified: item.last_modified,\r\n replies: item.replies\r\n };\r\n nThreads++;\r\n if ((oldest == null) || (item.no < oldest)) {\r\n oldest = item.no;\r\n }\r\n }\r\n }\r\n } catch (error) {\r\n for (thread of board) {\r\n ThreadWatcher.fetchStatus(thread);\r\n }\r\n }\r\n for (thread of board) {\r\n var {threadID, data} = thread;\r\n if (threads[threadID]) {\r\n var index, modified, replies;\r\n ({page, index, modified, replies} = threads[threadID]);\r\n if (Conf['Show Page']) {\r\n var lastPage = g.sites[siteID].isPrunedByAge?.({siteID, boardID}) ?\r\n threadID === oldest\r\n :\r\n index >= (nThreads - pageLength);\r\n ThreadWatcher.update(siteID, boardID, threadID, {page, lastPage});\r\n }\r\n if (ThreadWatcher.unreadEnabled && Conf['Show Unread Count']) {\r\n if ((modified !== data.modified) || ((replies != null) && (replies !== data.replies))) {\r\n (thread.newData || (thread.newData = {})).modified = modified;\r\n ThreadWatcher.fetchStatus(thread);\r\n }\r\n }\r\n } else {\r\n ThreadWatcher.fetchStatus(thread);\r\n }\r\n }\r\n },\r\n\r\n fetchStatus(thread) {\r\n const {siteID, boardID, threadID, data, force} = thread;\r\n const url = g.sites[siteID]?.urls.threadJSON?.({siteID, boardID, threadID});\r\n if (!url) { return; }\r\n if (data.isDead && !force) { return; }\r\n if (data.last === -1) { return; } // 404 or no JSON API\r\n return ThreadWatcher.fetch(url, {siteID, force}, [thread], ThreadWatcher.parseStatus);\r\n },\r\n\r\n parseStatus(thread, isArchiveURL) {\r\n let isDead, last;\r\n let {siteID, boardID, threadID, data, newData, force} = thread;\r\n const site = g.sites[siteID];\r\n if ((this.status === 200) && this.response) {\r\n let isArchived;\r\n last = this.response.posts[this.response.posts.length-1].no;\r\n const replies = this.response.posts.length-1;\r\n isDead = (isArchived = !!(this.response.posts[0].archived || isArchiveURL));\r\n if (isDead && Conf['Auto Prune']) {\r\n ThreadWatcher.rm(siteID, boardID, threadID);\r\n return;\r\n }\r\n\r\n if ((last === data.last) && (isDead === data.isDead) && (isArchived === data.isArchived)) { return; }\r\n\r\n const lastReadPost = ThreadWatcher.unreaddb.get({siteID, boardID, threadID, defaultValue: 0});\r\n let unread = data.unread || 0;\r\n let quotingYou = data.quotingYou || 0;\r\n const youOP = !!QuoteYou.db?.get({siteID, boardID, threadID, postID: threadID});\r\n\r\n for (var postObj of this.response.posts) {\r\n if ((postObj.no <= (data.last || 0)) || (postObj.no <= lastReadPost)) { continue; }\r\n if (QuoteYou.db?.get({siteID, boardID, threadID, postID: postObj.no})) { continue; }\r\n\r\n var quotesYou = false;\r\n if (!Conf['Require OP Quote Link'] && youOP) {\r\n quotesYou = true;\r\n } else if (QuoteYou.db && postObj.com) {\r\n var match;\r\n var regexp = site.regexp.quotelinkHTML;\r\n regexp.lastIndex = 0;\r\n while (match = regexp.exec(postObj.com)) {\r\n if (QuoteYou.db.get({\r\n siteID,\r\n boardID: match[1] ? encodeURIComponent(match[1]) : boardID,\r\n threadID: match[2] || threadID,\r\n postID: match[3] || match[2] || threadID\r\n })) {\r\n quotesYou = true;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (!unread || (!quotingYou && quotesYou)) {\r\n if (Filter.isHidden(site.Build.parseJSON(postObj, {siteID, boardID}))) { continue; }\r\n }\r\n\r\n unread++;\r\n if (quotesYou) { quotingYou = postObj.no; }\r\n }\r\n\r\n if (!newData) { newData = {}; }\r\n $.extend(newData, {last, replies, isDead, isArchived, unread, quotingYou});\r\n return ThreadWatcher.update(siteID, boardID, threadID, newData);\r\n\r\n } else if (this.status === 404) {\r\n const archiveURL = g.sites[siteID]?.urls.archivedThreadJSON?.({siteID, boardID, threadID});\r\n if (!isArchiveURL && archiveURL) {\r\n return ThreadWatcher.fetch(archiveURL, {siteID, force}, [thread, true], ThreadWatcher.parseStatus);\r\n } else if (site.mayLackJSON && (data.last == null)) {\r\n return ThreadWatcher.update(siteID, boardID, threadID, {last: -1});\r\n } else {\r\n return ThreadWatcher.update(siteID, boardID, threadID, {isDead: true});\r\n }\r\n }\r\n },\r\n\r\n getAll(groupByBoard) {\r\n const all = [];\r\n for (var siteID in ThreadWatcher.db.data) {\r\n var boards = ThreadWatcher.db.data[siteID];\r\n for (var boardID in boards.boards) {\r\n var cont;\r\n var threads = boards.boards[boardID];\r\n if (Conf['Current Board'] && ((siteID !== g.SITE.ID) || (boardID !== g.BOARD.ID))) {\r\n continue;\r\n }\r\n if (groupByBoard) {\r\n all.push((cont = []));\r\n }\r\n for (var threadID in threads) {\r\n var data = threads[threadID];\r\n if (data && (typeof data === 'object')) {\r\n (groupByBoard ? cont : all).push({siteID, boardID, threadID, data});\r\n }\r\n }\r\n }\r\n }\r\n return all;\r\n },\r\n\r\n makeLine(siteID, boardID, threadID, data) {\r\n let page;\r\n const x = $.el('a', {\r\n textContent: '✕',\r\n href: 'javascript:;'\r\n }\r\n );\r\n $.on(x, 'click', ThreadWatcher.cb.rm);\r\n\r\n let {excerpt, isArchived} = data;\r\n if (!excerpt) { excerpt = `/${boardID}/ - No.${threadID}`; }\r\n if (Conf['Show Site Prefix']) { excerpt = ThreadWatcher.prefixes[siteID] + excerpt; }\r\n\r\n const link = $.el('a', {\r\n href: g.sites[siteID]?.urls.thread({siteID, boardID, threadID}, isArchived) || '',\r\n title: excerpt,\r\n className: 'watcher-link'\r\n }\r\n );\r\n\r\n if (Conf['Show Page'] && (data.page != null)) {\r\n page = $.el('span', {\r\n textContent: `[${data.page}]`,\r\n className: 'watcher-page'\r\n }\r\n );\r\n $.add(link, page);\r\n }\r\n\r\n if (ThreadWatcher.unreadEnabled && Conf['Show Unread Count'] && (data.unread != null)) {\r\n const count = $.el('span', {\r\n textContent: `(${data.unread})`,\r\n className: 'watcher-unread'\r\n }\r\n );\r\n $.add(link, count);\r\n }\r\n\r\n const title = $.el('span', {\r\n textContent: excerpt,\r\n className: 'watcher-title'\r\n }\r\n );\r\n $.add(link, title);\r\n\r\n const div = $.el('div');\r\n const fullID = `${boardID}.${threadID}`;\r\n div.dataset.fullID = fullID;\r\n div.dataset.siteID = siteID;\r\n if ((g.VIEW === 'thread') && (fullID === `${g.BOARD}.${g.THREADID}`)) { $.addClass(div, 'current'); }\r\n if (data.isDead) { $.addClass(div, 'dead-thread'); }\r\n if (Conf['Show Page']) {\r\n if (data.lastPage) { $.addClass(div, 'last-page'); }\r\n if (data.page != null) { div.dataset.page = data.page; }\r\n }\r\n if (ThreadWatcher.unreadEnabled && Conf['Show Unread Count']) {\r\n if (data.unread === 0) { $.addClass(div, 'replies-read'); }\r\n if (data.unread) { $.addClass(div, 'replies-unread'); }\r\n if ((data.quotingYou || 0) > (data.dismiss || 0)) { $.addClass(div, 'replies-quoting-you'); }\r\n }\r\n $.add(div, [x, $.tn(' '), link]);\r\n return div;\r\n },\r\n\r\n setPrefixes(threads) {\r\n const prefixes = dict();\r\n for (var {siteID} of threads) {\r\n if (siteID in prefixes) { continue; }\r\n var len = 0;\r\n var prefix = '';\r\n var conflicts = Object.keys(prefixes);\r\n while (conflicts.length > 0) {\r\n len++;\r\n prefix = siteID.slice(0, len);\r\n var conflicts2 = [];\r\n for (var siteID2 of conflicts) {\r\n if (siteID2.slice(0, len) === prefix) {\r\n conflicts2.push(siteID2);\r\n } else if (prefixes[siteID2].length < len) {\r\n prefixes[siteID2] = siteID2.slice(0, len);\r\n }\r\n }\r\n conflicts = conflicts2;\r\n }\r\n prefixes[siteID] = prefix;\r\n }\r\n return ThreadWatcher.prefixes = prefixes;\r\n },\r\n\r\n build() {\r\n const nodes = [];\r\n const threads = ThreadWatcher.getAll();\r\n ThreadWatcher.setPrefixes(threads);\r\n for (var {siteID, boardID, threadID, data} of threads) {\r\n // Add missing excerpt for threads added by Auto Watch\r\n var thread;\r\n if ((data.excerpt == null) && (siteID === g.SITE.ID) && (thread = g.threads.get(`${boardID}.${threadID}`)) && thread.OP) {\r\n ThreadWatcher.db.extend({boardID, threadID, val: {excerpt: Get.threadExcerpt(thread)}});\r\n }\r\n nodes.push(ThreadWatcher.makeLine(siteID, boardID, threadID, data));\r\n }\r\n const {list} = ThreadWatcher;\r\n $.rmAll(list);\r\n $.add(list, nodes);\r\n\r\n return ThreadWatcher.refreshIcon();\r\n },\r\n\r\n refresh() {\r\n ThreadWatcher.build();\r\n\r\n g.threads.forEach(function(thread) {\r\n const isWatched = ThreadWatcher.isWatched(thread);\r\n if (thread.OP) {\r\n for (var post of [thread.OP, ...thread.OP.clones]) {\r\n var toggler;\r\n if (toggler = $('.watch-thread-link', post.nodes.info)) {\r\n ThreadWatcher.setToggler(toggler, isWatched);\r\n }\r\n }\r\n }\r\n if (thread.catalogView) { return thread.catalogView.nodes.root.classList.toggle('watched', isWatched); }\r\n });\r\n\r\n if (Conf['Pin Watched Threads']) {\r\n return $.event('SortIndex', {deferred: Conf['Index Mode'] !== 'catalog'});\r\n }\r\n },\r\n\r\n refreshIcon() {\r\n for (var className of ['replies-unread', 'replies-quoting-you']) {\r\n ThreadWatcher.shortcut.classList.toggle(className, !!$(`.${className}`, ThreadWatcher.dialog));\r\n }\r\n },\r\n\r\n update(siteID, boardID, threadID, newData) {\r\n let data, key, line, val;\r\n if (!(data = ThreadWatcher.db?.get({siteID, boardID, threadID}))) { return; }\r\n if (newData.isDead && Conf['Auto Prune']) {\r\n ThreadWatcher.rm(siteID, boardID, threadID);\r\n return;\r\n }\r\n if (newData.isDead || (newData.last === -1)) {\r\n for (key of ['isArchived', 'page', 'lastPage', 'unread', 'quotingyou']) {\r\n if (!(key in newData)) {\r\n newData[key] = undefined;\r\n }\r\n }\r\n }\r\n if ((newData.last != null) && (newData.last < data.last)) {\r\n newData.modified = undefined;\r\n }\r\n let n = 0;\r\n for (key in newData) { val = newData[key]; if (data[key] !== val) { n++; } }\r\n if (!n) { return; }\r\n ThreadWatcher.db.extend({siteID, boardID, threadID, val: newData});\r\n if (line = $(`#watched-threads > [data-site-i-d='${siteID}'][data-full-i-d='${boardID}.${threadID}']`, ThreadWatcher.dialog)) {\r\n const newLine = ThreadWatcher.makeLine(siteID, boardID, threadID, data);\r\n $.replace(line, newLine);\r\n return ThreadWatcher.refreshIcon();\r\n } else {\r\n return ThreadWatcher.refresh();\r\n }\r\n },\r\n\r\n set404(boardID, threadID, cb) {\r\n let data;\r\n if (!(data = ThreadWatcher.db?.get({boardID, threadID}))) { return cb(); }\r\n if (Conf['Auto Prune']) {\r\n ThreadWatcher.db.delete({boardID, threadID});\r\n return cb();\r\n }\r\n if (data.isDead && !((data.isArchived != null) || (data.page != null) || (data.lastPage != null) || (data.unread != null) || (data.quotingYou != null))) { return cb(); }\r\n return ThreadWatcher.db.extend({boardID, threadID, val: {isDead: true, isArchived: undefined, page: undefined, lastPage: undefined, unread: undefined, quotingYou: undefined}}, cb);\r\n },\r\n\r\n toggle(thread) {\r\n const siteID = g.SITE.ID;\r\n const boardID = thread.board.ID;\r\n const threadID = thread.ID;\r\n if (ThreadWatcher.db.get({boardID, threadID})) {\r\n return ThreadWatcher.rm(siteID, boardID, threadID);\r\n } else {\r\n return ThreadWatcher.add(thread);\r\n }\r\n },\r\n\r\n add(thread, cb) {\r\n const data = {};\r\n const siteID = g.SITE.ID;\r\n const boardID = thread.board.ID;\r\n const threadID = thread.ID;\r\n if (thread.isDead) {\r\n if (Conf['Auto Prune'] && ThreadWatcher.db.get({boardID, threadID})) {\r\n ThreadWatcher.rm(siteID, boardID, threadID, cb);\r\n return;\r\n }\r\n data.isDead = true;\r\n }\r\n if (thread.OP) { data.excerpt = Get.threadExcerpt(thread); }\r\n return ThreadWatcher.addRaw(boardID, threadID, data, cb);\r\n },\r\n\r\n addRaw(boardID, threadID, data, cb) {\r\n const oldData = ThreadWatcher.db.get({ boardID, threadID, defaultValue: dict() });\r\n delete oldData.last;\r\n delete oldData.modified;\r\n $.extend(oldData, data);\r\n ThreadWatcher.db.set({boardID, threadID, val: oldData}, cb);\r\n ThreadWatcher.refresh();\r\n const thread = {siteID: g.SITE.ID, boardID, threadID, data, force: true};\r\n if (Conf['Show Page'] && !data.isDead) {\r\n return ThreadWatcher.fetchBoard([thread]);\r\n } else if (ThreadWatcher.unreadEnabled && Conf['Show Unread Count']) {\r\n return ThreadWatcher.fetchStatus(thread);\r\n }\r\n },\r\n\r\n rm(siteID, boardID, threadID, cb) {\r\n ThreadWatcher.db.delete({siteID, boardID, threadID}, cb);\r\n return ThreadWatcher.refresh();\r\n },\r\n\r\n menu: {\r\n init() {\r\n if (!Conf['Thread Watcher']) { return; }\r\n const menu = (this.menu = new UI.Menu('thread watcher'));\r\n $.on($('.menu-button', ThreadWatcher.dialog), 'click', function(e) {\r\n return menu.toggle(e, this, ThreadWatcher);\r\n });\r\n return this.addMenuEntries();\r\n },\r\n\r\n addHeaderMenuEntry() {\r\n if (g.VIEW !== 'thread') { return; }\r\n const entryEl = $.el('a',\r\n {href: 'javascript:;'});\r\n Header.menu.addEntry({\r\n el: entryEl,\r\n order: 60,\r\n open() {\r\n const [addClass, rmClass, text] = !!ThreadWatcher.db.get({boardID: g.BOARD.ID, threadID: g.THREADID}) ?\r\n ['unwatch-thread', 'watch-thread', 'Unwatch thread']\r\n :\r\n ['watch-thread', 'unwatch-thread', 'Watch thread'];\r\n $.addClass(entryEl, addClass);\r\n $.rmClass(entryEl, rmClass);\r\n entryEl.textContent = text;\r\n return true;\r\n }\r\n });\r\n return $.on(entryEl, 'click', () => ThreadWatcher.toggle(g.threads.get(`${g.BOARD}.${g.THREADID}`)));\r\n },\r\n\r\n addMenuEntries() {\r\n const entries = [];\r\n\r\n // `Open all` entry\r\n entries.push({\r\n text: 'Open all threads',\r\n cb: ThreadWatcher.cb.openAll,\r\n open() {\r\n this.el.classList.toggle('disabled', !ThreadWatcher.list.firstElementChild);\r\n return true;\r\n }\r\n });\r\n\r\n // `Open Unread` entry\r\n entries.push({\r\n text: 'Open unread threads',\r\n cb: ThreadWatcher.cb.openUnread,\r\n open() {\r\n this.el.classList.toggle('disabled', !$('.replies-unread', ThreadWatcher.list));\r\n return true;\r\n }\r\n });\r\n\r\n // `Open dead threads` entry\r\n entries.push({\r\n text: 'Open dead threads',\r\n cb: ThreadWatcher.cb.openDeads,\r\n open() {\r\n this.el.classList.toggle('disabled', !$('.dead-thread', ThreadWatcher.list));\r\n return true;\r\n }\r\n });\r\n\r\n // `Prune dead threads` entry\r\n entries.push({\r\n text: 'Prune dead threads',\r\n cb: ThreadWatcher.cb.pruneDeads,\r\n open() {\r\n this.el.classList.toggle('disabled', !$('.dead-thread', ThreadWatcher.list));\r\n return true;\r\n }\r\n });\r\n\r\n // `Dismiss posts quoting you` entry\r\n entries.push({\r\n text: 'Dismiss posts quoting you',\r\n title: 'Unhighlight the thread watcher icon and threads until there are new replies quoting you.',\r\n cb: ThreadWatcher.cb.dismiss,\r\n open() {\r\n this.el.classList.toggle('disabled', !$.hasClass(ThreadWatcher.shortcut, 'replies-quoting-you'));\r\n return true;\r\n }\r\n });\r\n\r\n for (var {text, title, cb, open} of entries) {\r\n var entry = {\r\n el: $.el('a', {\r\n textContent: text,\r\n href: 'javascript:;'\r\n }\r\n )\r\n };\r\n if (title) { entry.el.title = title; }\r\n $.on(entry.el, 'click', cb);\r\n entry.open = open.bind(entry);\r\n this.menu.addEntry(entry);\r\n }\r\n\r\n // Settings checkbox entries:\r\n for (var name in Config.threadWatcher) {\r\n var conf = Config.threadWatcher[name];\r\n this.addCheckbox(name, conf[1]);\r\n }\r\n\r\n },\r\n\r\n addCheckbox(name, desc) {\r\n const entry = {\r\n type: 'thread watcher',\r\n el: UI.checkbox(name, name.replace(' Thread Watcher', ''))\r\n };\r\n entry.el.title = desc;\r\n const input = entry.el.firstElementChild;\r\n if ((name === 'Show Unread Count') && !ThreadWatcher.unreadEnabled) {\r\n input.disabled = true;\r\n $.addClass(entry.el, 'disabled');\r\n entry.el.title += '\\n[Remember Last Read Post is disabled.]';\r\n }\r\n $.on(input, 'change', $.cb.checked);\r\n if (['Current Board', 'Show Page', 'Show Unread Count', 'Show Site Prefix'].includes(name)) { $.on(input, 'change', ThreadWatcher.refresh); }\r\n if (['Show Page', 'Show Unread Count', 'Auto Update Thread Watcher'].includes(name)) { $.on(input, 'change', ThreadWatcher.fetchAuto); }\r\n return this.menu.addEntry(entry);\r\n }\r\n }\r\n};\r\nexport default ThreadWatcher;\r\n",null,null,null,"import Callbacks from \"../classes/Callbacks\";\r\nimport Fetcher from \"../classes/Fetcher\";\r\nimport Get from \"../General/Get\";\r\nimport Header from \"../General/Header\";\r\nimport UI from \"../General/UI\";\r\nimport { Conf, d, doc, g } from \"../globals/globals\";\r\nimport ExpandComment from \"../Miscellaneous/ExpandComment\";\r\nimport $ from \"../platform/$\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar QuotePreview = {\r\n init() {\r\n if (!Conf['Quote Previewing']) { return; }\r\n\r\n if (g.VIEW === 'archive') {\r\n $.on(d, 'mouseover', function(e) {\r\n if ((e.target.nodeName === 'A') && $.hasClass(e.target, 'quotelink')) {\r\n return QuotePreview.mouseover.call(e.target, e);\r\n }\r\n });\r\n }\r\n\r\n if (!['index', 'thread'].includes(g.VIEW)) { return; }\r\n\r\n if (Conf['Comment Expansion']) {\r\n ExpandComment.callbacks.push(this.node);\r\n }\r\n\r\n return Callbacks.Post.push({\r\n name: 'Quote Previewing',\r\n cb: this.node\r\n });\r\n },\r\n\r\n node() {\r\n for (var link of this.nodes.quotelinks.concat([...this.nodes.backlinks], this.nodes.archivelinks)) {\r\n $.on(link, 'mouseover', QuotePreview.mouseover);\r\n }\r\n },\r\n\r\n mouseover(e) {\r\n let origin;\r\n if (($.hasClass(this, 'inlined') && !$.hasClass(doc, 'catalog-mode')) || !d.contains(this)) { return; }\r\n\r\n const {boardID, threadID, postID} = Get.postDataFromLink(this);\r\n\r\n const qp = $.el('div', {\r\n id: 'qp',\r\n className: 'dialog'\r\n }\r\n );\r\n\r\n $.add(Header.hover, qp);\r\n new Fetcher(boardID, threadID, postID, qp, Get.postFromNode(this));\r\n\r\n UI.hover({\r\n root: this,\r\n el: qp,\r\n latestEvent: e,\r\n endEvents: 'mouseout click',\r\n cb: QuotePreview.mouseout\r\n });\r\n\r\n if (Conf['Quote Highlighting'] && (origin = g.posts.get(`${boardID}.${postID}`))) {\r\n const posts = [origin].concat(origin.clones);\r\n // Remove the clone that's in the qp from the array.\r\n posts.pop();\r\n for (var post of posts) {\r\n $.addClass(post.nodes.post, 'qphl');\r\n }\r\n }\r\n },\r\n\r\n mouseout() {\r\n // Stop if it only contains text.\r\n let root;\r\n if (!(root = this.el.firstElementChild)) { return; }\r\n\r\n $.event('PostsRemoved', null, Header.hover);\r\n\r\n const clone = Get.postFromRoot(root);\r\n let post = clone.origin;\r\n post.rmClone(root.dataset.clone);\r\n\r\n if (!Conf['Quote Highlighting']) { return; }\r\n for (post of [post].concat(post.clones)) {\r\n $.rmClass(post.nodes.post, 'qphl');\r\n }\r\n }\r\n};\r\nexport default QuotePreview;\r\n","/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS205: Consider reworking code to avoid use of IIFEs\r\n * DS207: Consider shorter variations of null checks\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nimport Callbacks from '../classes/Callbacks';\r\nimport CatalogThread from '../classes/CatalogThread';\r\nimport Notice from '../classes/Notice';\r\nimport Post from '../classes/Post';\r\nimport Thread from '../classes/Thread';\r\nimport Config from '../config/Config';\r\nimport Filter from '../Filtering/Filter';\r\nimport PostHiding from '../Filtering/PostHiding';\r\nimport ThreadHiding from '../Filtering/ThreadHiding';\r\nimport Main from '../main/Main';\r\nimport CatalogLinks from '../Miscellaneous/CatalogLinks';\r\nimport RelativeDates from '../Miscellaneous/RelativeDates';\r\nimport ThreadWatcher from '../Monitoring/ThreadWatcher';\r\nimport $$ from '../platform/$$';\r\nimport $ from '../platform/$';\r\nimport QuotePreview from '../Quotelinks/QuotePreview';\r\nimport { c, Conf, d, doc, g } from '../globals/globals';\r\nimport Header from './Header';\r\nimport UI from './UI';\r\nimport Menu from '../Menu/Menu';\r\n\r\nimport NavLinksPage from './Index/NavLinks.html';\r\nimport PageList from './Index/PageList.html';\r\nimport BoardConfig from './BoardConfig';\r\nimport Get from './Get';\r\nimport { dict, SECOND } from '../platform/helpers';\r\n\r\nvar Index = {\r\n showHiddenThreads: false,\r\n changed: {},\r\n\r\n enabledOn({siteID, boardID}) {\r\n return Conf['JSON Index'] && (g.sites[siteID].software === 'yotsuba') && (boardID !== 'f');\r\n },\r\n\r\n init() {\r\n let input, inputs, name;\r\n if (g.VIEW !== 'index') { return; }\r\n\r\n // For IndexRefresh events\r\n $.one(d, '4chanXInitFinished', this.cb.initFinished);\r\n $.on(d, 'PostsInserted', this.cb.postsInserted);\r\n\r\n if (!this.enabledOn(g.BOARD)) { return; }\r\n\r\n this.enabled = true;\r\n\r\n Callbacks.Post.push({\r\n name: 'Index Page Numbers',\r\n cb: this.node\r\n });\r\n Callbacks.CatalogThread.push({\r\n name: 'Catalog Features',\r\n cb: this.catalogNode\r\n });\r\n\r\n this.search = history.state?.searched || '';\r\n if (history.state?.mode) {\r\n Conf['Index Mode'] = history.state?.mode;\r\n }\r\n this.currentSort = history.state?.sort;\r\n if (!this.currentSort) { this.currentSort = typeof Conf['Index Sort'] === 'object' ? (\r\n Conf['Index Sort'][g.BOARD.ID] || 'bump'\r\n ) : (\r\n Conf['Index Sort']\r\n ); }\r\n this.currentPage = this.getCurrentPage();\r\n this.processHash();\r\n\r\n $.addClass(doc, 'index-loading', `${Conf['Index Mode'].replace(/\\ /g, '-')}-mode`);\r\n $.on(window, 'popstate', this.cb.popstate);\r\n $.on(d, 'scroll', this.scroll);\r\n $.on(d, 'SortIndex', this.cb.resort);\r\n\r\n // Header refresh button\r\n this.button = $.el('a', {\r\n title: 'Refresh',\r\n href: 'javascript:;',\r\n textContent: '🗘'\r\n }\r\n );\r\n $.on(this.button, 'click', () => Index.update());\r\n Header.addShortcut('index-refresh', this.button, 590);\r\n\r\n // Header \"Index Navigation\" submenu\r\n const entries = [];\r\n this.inputs = (inputs = dict());\r\n for (name in Config.Index) {\r\n var arr = Config.Index[name];\r\n if (arr instanceof Array) {\r\n var label = UI.checkbox(name, `${name[0]}${name.slice(1).toLowerCase()}`);\r\n label.title = arr[1];\r\n entries.push({el: label});\r\n input = label.firstChild;\r\n $.on(input, 'change', $.cb.checked);\r\n inputs[name] = input;\r\n }\r\n }\r\n $.on(inputs['Show Replies'], 'change', this.cb.replies);\r\n $.on(inputs['Catalog Hover Expand'], 'change', this.cb.hover);\r\n $.on(inputs['Pin Watched Threads'], 'change', this.cb.resort);\r\n $.on(inputs['Anchor Hidden Threads'], 'change', this.cb.resort);\r\n\r\n const watchSettings = function(e) {\r\n if (input = $.getOwn(inputs, e.target.name)) {\r\n input.checked = e.target.checked;\r\n return $.event('change', null, input);\r\n }\r\n };\r\n $.on(d, 'OpenSettings', () => $.on($.id('fourchanx-settings'), 'change', watchSettings));\r\n\r\n const sortEntry = UI.checkbox('Per-Board Sort Type', 'Per-board sort type', (typeof Conf['Index Sort'] === 'object'));\r\n sortEntry.title = 'Set the sorting order of each board independently.';\r\n $.on(sortEntry.firstChild, 'change', this.cb.perBoardSort);\r\n entries.splice(3, 0, {el: sortEntry});\r\n\r\n Header.menu.addEntry({\r\n el: $.el('span',\r\n {textContent: 'Index Navigation'}),\r\n order: 100,\r\n subEntries: entries\r\n });\r\n\r\n // Navigation links at top of index\r\n this.navLinks = $.el('div', {className: 'navLinks json-index'});\r\n $.extend(this.navLinks, {innerHTML: NavLinksPage});\r\n $('.cataloglink a', this.navLinks).href = CatalogLinks.catalog();\r\n if (!BoardConfig.isArchived(g.BOARD.ID)) { $('.archlistlink', this.navLinks).hidden = true; }\r\n $.on($('#index-last-refresh a', this.navLinks), 'click', this.cb.refreshFront);\r\n\r\n // Search field\r\n this.searchInput = $('#index-search', this.navLinks);\r\n this.setupSearch();\r\n $.on(this.searchInput, 'input', this.onSearchInput);\r\n $.on($('#index-search-clear', this.navLinks), 'click', this.clearSearch);\r\n\r\n // Hidden threads toggle\r\n this.hideLabel = $('#hidden-label', this.navLinks);\r\n $.on($('#hidden-toggle a', this.navLinks), 'click', this.cb.toggleHiddenThreads);\r\n\r\n // Drop-down menus and reverse sort toggle\r\n this.selectRev = $('#index-rev', this.navLinks);\r\n this.selectMode = $('#index-mode', this.navLinks);\r\n this.selectSort = $('#index-sort', this.navLinks);\r\n this.selectSize = $('#index-size', this.navLinks);\r\n $.on(this.selectRev, 'change', this.cb.sort);\r\n $.on(this.selectMode, 'change', this.cb.mode);\r\n $.on(this.selectSort, 'change', this.cb.sort);\r\n $.on(this.selectSize, 'change', $.cb.value);\r\n $.on(this.selectSize, 'change', this.cb.size);\r\n for (var select of [this.selectMode, this.selectSize]) {\r\n select.value = Conf[select.name];\r\n }\r\n this.selectRev.checked = /-rev$/.test(Index.currentSort);\r\n this.selectSort.value = Index.currentSort.replace(/-rev$/, '');\r\n\r\n // Last Long Reply options\r\n this.lastLongOptions = $('#lastlong-options', this.navLinks);\r\n this.lastLongInputs = $$('input', this.lastLongOptions);\r\n this.lastLongThresholds = [0, 0];\r\n this.lastLongOptions.hidden = (this.selectSort.value !== 'lastlong');\r\n for (let i = 0; i < this.lastLongInputs.length; i++) {\r\n input = this.lastLongInputs[i];\r\n $.on(input, 'change', this.cb.lastLongThresholds);\r\n var tRaw = Conf[`Last Long Reply Thresholds ${i}`];\r\n input.value = (this.lastLongThresholds[i] =\r\n typeof tRaw === 'object' ? (tRaw[g.BOARD.ID] ?? 100) : tRaw);\r\n }\r\n\r\n // Thread container\r\n this.root = $.el('div', {className: 'board json-index'});\r\n $.on(this.root, 'click', this.cb.hoverToggle);\r\n this.cb.size();\r\n this.cb.hover();\r\n\r\n // Page list\r\n this.pagelist = $.el('div', {className: 'pagelist json-index'});\r\n $.extend(this.pagelist, {innerHTML: PageList});\r\n $('.cataloglink a', this.pagelist).href = CatalogLinks.catalog();\r\n $.on(this.pagelist, 'click', this.cb.pageNav);\r\n\r\n this.update(true);\r\n\r\n $.onExists(doc, 'title + *', () => d.title = d.title.replace(/\\ -\\ Page\\ \\d+/, ''));\r\n\r\n $.onExists(doc, '.board > .thread > .postContainer, .board + *', function() {\r\n let el;\r\n g.SITE.Build.hat = $('.board > .thread > img:first-child');\r\n if (g.SITE.Build.hat) {\r\n g.BOARD.threads.forEach(function(thread) {\r\n if (thread.nodes.root) {\r\n return $.prepend(thread.nodes.root, g.SITE.Build.hat.cloneNode(false));\r\n }\r\n });\r\n $.addClass(doc, 'hats-enabled');\r\n $.addStyle(`.catalog-thread::after {background-image: url(${g.SITE.Build.hat.src});}`);\r\n }\r\n\r\n const board = $('.board');\r\n $.replace(board, Index.root);\r\n if (Index.loaded) {\r\n $.event('PostsInserted', null, Index.root);\r\n }\r\n // Hacks:\r\n // - When removing an element from the document during page load,\r\n // its ancestors will still be correctly created inside of it.\r\n // - Creating loadable elements inside of an origin-less document\r\n // will not download them.\r\n // - Combine the two and you get a download canceller!\r\n // Does not work on Firefox unfortunately. bugzil.la/939713\r\n try {\r\n d.implementation.createDocument(null, null, null).appendChild(board);\r\n } catch (error) {}\r\n\r\n for (el of $$('.navLinks')) { $.rm(el); }\r\n $.rm($.id('ctrl-top'));\r\n const topNavPos = $.id('delform').previousElementSibling;\r\n $.before(topNavPos, $.el('hr'));\r\n $.before(topNavPos, Index.navLinks);\r\n const timeEl = $('#index-last-refresh time', Index.navLinks);\r\n if (timeEl.dataset.utc) { return RelativeDates.update(timeEl); }\r\n });\r\n\r\n return Main.ready(function() {\r\n let pagelist;\r\n if (pagelist = $('.pagelist')) {\r\n $.replace(pagelist, Index.pagelist);\r\n }\r\n return $.rmClass(doc, 'index-loading');\r\n });\r\n },\r\n\r\n scroll() {\r\n if (Index.req || !Index.liveThreadData || (Conf['Index Mode'] !== 'infinite') || (window.scrollY <= (doc.scrollHeight - (300 + window.innerHeight)))) { return; }\r\n if (Index.pageNum == null) { Index.pageNum = Index.currentPage; } // Avoid having to pushState to keep track of the current page\r\n\r\n const pageNum = ++Index.pageNum;\r\n if (pageNum > Index.pagesNum) { return Index.endNotice(); }\r\n\r\n const threadIDs = Index.threadsOnPage(pageNum);\r\n return Index.buildStructure(threadIDs);\r\n },\r\n\r\n endNotice: (function() {\r\n let notify = false;\r\n const reset = () => notify = false;\r\n return function() {\r\n if (notify) { return; }\r\n notify = true;\r\n new Notice('info', \"Last page reached.\", 2);\r\n return setTimeout(reset, 3 * SECOND);\r\n };\r\n })(),\r\n\r\n menu: {\r\n init() {\r\n if ((g.VIEW !== 'index') || !Conf['Menu'] || !Conf['Thread Hiding Link'] || !Index.enabledOn(g.BOARD)) { return; }\r\n\r\n return Menu.menu.addEntry({\r\n el: $.el('a', {\r\n href: 'javascript:;',\r\n className: 'has-shortcut-text'\r\n }\r\n , {innerHTML: \"Shift+click\"}),\r\n order: 20,\r\n open({thread}) {\r\n if (Conf['Index Mode'] !== 'catalog') { return false; }\r\n this.el.firstElementChild.textContent = thread.isHidden ?\r\n 'Unhide'\r\n :\r\n 'Hide';\r\n if (this.cb) { $.off(this.el, 'click', this.cb); }\r\n this.cb = function() {\r\n $.event('CloseMenu');\r\n return Index.toggleHide(thread);\r\n };\r\n $.on(this.el, 'click', this.cb);\r\n return true;\r\n }\r\n });\r\n }\r\n },\r\n\r\n node() {\r\n if (this.isReply || this.isClone || (Index.threadPosition[this.ID] == null)) { return; }\r\n return this.thread.setPage(Math.floor(Index.threadPosition[this.ID] / Index.threadsNumPerPage) + 1);\r\n },\r\n\r\n catalogNode() {\r\n return $.on(this.nodes.root, 'mousedown click', e => {\r\n if ((e.button !== 0) || !e.shiftKey) { return; }\r\n if (e.type === 'click') { Index.toggleHide(this.thread); }\r\n return e.preventDefault();\r\n });\r\n }, // Also on mousedown to prevent highlighting text.\r\n\r\n toggleHide(thread) {\r\n if (Index.showHiddenThreads) {\r\n ThreadHiding.show(thread);\r\n if (!ThreadHiding.db.get({boardID: thread.board.ID, threadID: thread.ID})) { return; }\r\n // Don't save when un-hiding filtered threads.\r\n } else {\r\n ThreadHiding.hide(thread);\r\n }\r\n return ThreadHiding.saveHiddenState(thread);\r\n },\r\n\r\n cycleSortType() {\r\n let i;\r\n const types = Index.selectSort.options.filter(option => !option.disabled);\r\n for (i = 0; i < types.length; i++) {\r\n var type = types[i];\r\n if (type.selected) { break; }\r\n }\r\n types[(i + 1) % types.length].selected = true;\r\n return $.event('change', null, Index.selectSort);\r\n },\r\n\r\n cb: {\r\n initFinished() {\r\n Index.initFinishedFired = true;\r\n return $.queueTask(() => Index.cb.postsInserted());\r\n },\r\n\r\n postsInserted() {\r\n if (!Index.initFinishedFired) { return; }\r\n let n = 0;\r\n g.posts.forEach(function(post) {\r\n if (!post.isFetchedQuote && !post.indexRefreshSeen && doc.contains(post.nodes.root)) {\r\n post.indexRefreshSeen = true;\r\n return n++;\r\n }\r\n });\r\n if (n) { return $.event('IndexRefresh'); }\r\n },\r\n\r\n toggleHiddenThreads() {\r\n $('#hidden-toggle a', Index.navLinks).textContent = (Index.showHiddenThreads = !Index.showHiddenThreads) ?\r\n 'Hide'\r\n :\r\n 'Show';\r\n Index.sort();\r\n return Index.buildIndex();\r\n },\r\n\r\n mode() {\r\n Index.pushState({mode: this.value});\r\n return Index.pageLoad(false);\r\n },\r\n\r\n sort() {\r\n const value = Index.selectRev.checked ? Index.selectSort.value + \"-rev\" : Index.selectSort.value;\r\n Index.pushState({sort: value});\r\n return Index.pageLoad(false);\r\n },\r\n\r\n resort(e) {\r\n Index.changed.order = true;\r\n if (!e?.detail?.deferred) { return Index.pageLoad(false); }\r\n },\r\n\r\n perBoardSort() {\r\n Conf['Index Sort'] = this.checked ? dict() : '';\r\n Index.saveSort();\r\n for (let i = 0; i < 2; i++) {\r\n Conf[`Last Long Reply Thresholds ${i}`] = this.checked ? dict() : '';\r\n Index.saveLastLongThresholds(i);\r\n }\r\n },\r\n\r\n lastLongThresholds() {\r\n const i = [...this.parentNode.children].indexOf(this);\r\n const value = +this.value;\r\n if (!Number.isFinite(value)) {\r\n this.value = Index.lastLongThresholds[i];\r\n return;\r\n }\r\n Index.lastLongThresholds[i] = value;\r\n Index.saveLastLongThresholds(i);\r\n Index.changed.order = true;\r\n return Index.pageLoad(false);\r\n },\r\n\r\n size(e) {\r\n if (Conf['Index Mode'] !== 'catalog') {\r\n $.rmClass(Index.root, 'catalog-small');\r\n $.rmClass(Index.root, 'catalog-large');\r\n } else if (Conf['Index Size'] === 'small') {\r\n $.addClass(Index.root, 'catalog-small');\r\n $.rmClass(Index.root, 'catalog-large');\r\n } else {\r\n $.addClass(Index.root, 'catalog-large');\r\n $.rmClass(Index.root, 'catalog-small');\r\n }\r\n if (e) { return Index.buildIndex(); }\r\n },\r\n\r\n replies() {\r\n return Index.buildIndex();\r\n },\r\n\r\n hover() {\r\n return doc.classList.toggle('catalog-hover-expand', Conf['Catalog Hover Expand']);\r\n },\r\n\r\n hoverToggle(e) {\r\n if (Conf['Catalog Hover Toggle'] && $.hasClass(doc, 'catalog-mode') && !$.modifiedClick(e) && !$.x('ancestor-or-self::a', e.target)) {\r\n let thread;\r\n const input = Index.inputs['Catalog Hover Expand'];\r\n input.checked = !input.checked;\r\n $.event('change', null, input);\r\n if (thread = Get.threadFromNode(e.target)) {\r\n Index.cb.catalogReplies.call(thread);\r\n return Index.cb.hoverAdjust.call(thread.OP.nodes);\r\n }\r\n }\r\n },\r\n\r\n popstate(e) {\r\n if (e?.state) {\r\n const {searched, mode, sort} = e.state;\r\n const page = Index.getCurrentPage();\r\n Index.setState({search: searched, mode, sort, page});\r\n return Index.pageLoad(false);\r\n } else {\r\n // page load or hash change\r\n const nCommands = Index.processHash();\r\n if (Conf['Refreshed Navigation'] && nCommands) {\r\n return Index.update();\r\n } else {\r\n return Index.pageLoad();\r\n }\r\n }\r\n },\r\n\r\n pageNav(e) {\r\n let a;\r\n if ($.modifiedClick(e)) { return; }\r\n switch (e.target.nodeName) {\r\n case 'BUTTON':\r\n e.target.blur();\r\n a = e.target.parentNode;\r\n break;\r\n case 'A':\r\n a = e.target;\r\n break;\r\n default:\r\n return;\r\n }\r\n if (a.textContent === 'Catalog') { return; }\r\n e.preventDefault();\r\n return Index.userPageNav(+a.pathname.split(/\\/+/)[2] || 1);\r\n },\r\n\r\n refreshFront() {\r\n Index.pushState({page: 1});\r\n return Index.update();\r\n },\r\n\r\n catalogReplies() {\r\n if (Conf['Show Replies'] && $.hasClass(doc, 'catalog-hover-expand') && !this.catalogView.nodes.replies) {\r\n return Index.buildCatalogReplies(this);\r\n }\r\n },\r\n\r\n hoverAdjust() {\r\n // Prevent hovered catalog threads from going offscreen.\r\n let x;\r\n if (!$.hasClass(doc, 'catalog-hover-expand')) { return; }\r\n const rect = this.post.getBoundingClientRect();\r\n if (x = $.minmax(0, -rect.left, doc.clientWidth - rect.right)) {\r\n const {style} = this.post;\r\n style.left = `${x}px`;\r\n style.right = `${-x}px`;\r\n return $.one(this.root, 'mouseleave', () => style.left = (style.right = null));\r\n }\r\n }\r\n },\r\n\r\n scrollToIndex() {\r\n // Scroll to navlinks, or top of board if navlinks are hidden.\r\n return Header.scrollToIfNeeded((Index.navLinks.getBoundingClientRect().height ? Index.navLinks : Index.root));\r\n },\r\n\r\n getCurrentPage() {\r\n return +window.location.pathname.split(/\\/+/)[2] || 1;\r\n },\r\n\r\n userPageNav(page) {\r\n Index.pushState({page});\r\n if (Conf['Refreshed Navigation']) {\r\n return Index.update();\r\n } else {\r\n return Index.pageLoad();\r\n }\r\n },\r\n\r\n hashCommands: {\r\n mode: {\r\n 'paged': 'paged',\r\n 'infinite-scrolling': 'infinite',\r\n 'infinite': 'infinite',\r\n 'all-threads': 'all pages',\r\n 'all-pages': 'all pages',\r\n 'catalog': 'catalog'\r\n },\r\n sort: {\r\n 'bump-order': 'bump',\r\n 'last-reply': 'lastreply',\r\n 'last-long-reply': 'lastlong',\r\n 'creation-date': 'birth',\r\n 'reply-count': 'replycount',\r\n 'file-count': 'filecount',\r\n 'posts-per-minute': 'activity'\r\n }\r\n },\r\n\r\n processHash() {\r\n // XXX https://bugzilla.mozilla.org/show_bug.cgi?id=483304\r\n let hash = location.href.match(/#.*/)?.[0] || '';\r\n const state =\r\n {replace: true};\r\n const commands = hash.slice(1).split('/');\r\n const leftover = [];\r\n for (var command of commands) {\r\n var mode, sort;\r\n if (mode = $.getOwn(Index.hashCommands.mode, command)) {\r\n state.mode = mode;\r\n } else if (command === 'index') {\r\n state.mode = Conf['Previous Index Mode'];\r\n state.page = 1;\r\n } else if (sort = $.getOwn(Index.hashCommands.sort, command.replace(/-rev$/, ''))) {\r\n state.sort = sort;\r\n if (/-rev$/.test(command)) { state.sort += '-rev'; }\r\n } else if (/^s=/.test(command)) {\r\n state.search = decodeURIComponent(command.slice(2)).replace(/\\+/g, ' ').trim();\r\n } else {\r\n leftover.push(command);\r\n }\r\n }\r\n hash = leftover.join('/');\r\n if (hash) { state.hash = `#${hash}`; }\r\n Index.pushState(state);\r\n return commands.length - leftover.length;\r\n },\r\n\r\n pushState(state) {\r\n let {search, hash, replace} = state;\r\n let pageBeforeSearch = history.state?.oldpage;\r\n if ((search != null) && (search !== Index.search)) {\r\n state.page = search ? 1 : (pageBeforeSearch || 1);\r\n if (!search) {\r\n pageBeforeSearch = undefined;\r\n } else if (!Index.search) {\r\n pageBeforeSearch = Index.currentPage;\r\n }\r\n }\r\n Index.setState(state);\r\n const pathname = Index.currentPage === 1 ? `/${g.BOARD}/` : `/${g.BOARD}/${Index.currentPage}`;\r\n if (!hash) { hash = ''; }\r\n return history[replace ? 'replaceState' : 'pushState']({\r\n mode: Conf['Index Mode'],\r\n sort: Index.currentSort,\r\n searched: Index.search,\r\n oldpage: pageBeforeSearch\r\n }\r\n , '', `${location.protocol}//${location.host}${pathname}${hash}`);\r\n },\r\n\r\n setState({search, mode, sort, page, hash}) {\r\n if ((search != null) && (search !== Index.search)) {\r\n Index.changed.search = true;\r\n Index.search = search;\r\n }\r\n if ((mode != null) && (mode !== Conf['Index Mode'])) {\r\n Index.changed.mode = true;\r\n Conf['Index Mode'] = mode;\r\n $.set('Index Mode', mode);\r\n if ((mode !== 'catalog') && (Conf['Previous Index Mode'] !== mode)) {\r\n Conf['Previous Index Mode'] = mode;\r\n $.set('Previous Index Mode', mode);\r\n }\r\n }\r\n if ((sort != null) && (sort !== Index.currentSort)) {\r\n Index.changed.sort = true;\r\n Index.currentSort = sort;\r\n Index.saveSort();\r\n }\r\n if (['all pages', 'catalog'].includes(Conf['Index Mode'])) { page = 1; }\r\n if ((page != null) && (page !== Index.currentPage)) {\r\n Index.changed.page = true;\r\n Index.currentPage = page;\r\n }\r\n if (hash != null) {\r\n return Index.changed.hash = true;\r\n }\r\n },\r\n\r\n savePerBoard(key, value) {\r\n if (typeof Conf[key] === 'object') {\r\n Conf[key][g.BOARD.ID] = value;\r\n } else {\r\n Conf[key] = value;\r\n }\r\n return $.set(key, Conf[key]);\r\n },\r\n\r\n saveSort() {\r\n return Index.savePerBoard('Index Sort', Index.currentSort);\r\n },\r\n\r\n saveLastLongThresholds(i) {\r\n return Index.savePerBoard(`Last Long Reply Thresholds ${i}`, Index.lastLongThresholds[i]);\r\n },\r\n\r\n pageLoad(scroll=true) {\r\n if (!Index.liveThreadData) { return; }\r\n let {threads, order, search, mode, sort, page, hash} = Index.changed;\r\n if (!threads) { threads = search; }\r\n if (!order) { order = sort; }\r\n if (threads || order) { Index.sort(); }\r\n if (threads) { Index.buildPagelist(); }\r\n if (search) { Index.setupSearch(); }\r\n if (mode) { Index.setupMode(); }\r\n if (sort) { Index.setupSort(); }\r\n if (threads || mode || page || order) { Index.buildIndex(); }\r\n if (threads || page) { Index.setPage(); }\r\n if (scroll && !hash) { Index.scrollToIndex(); }\r\n if (hash) { Header.hashScroll(); }\r\n return Index.changed = {};\r\n },\r\n\r\n setupMode() {\r\n for (var mode of ['paged', 'infinite', 'all pages', 'catalog']) {\r\n $[mode === Conf['Index Mode'] ? 'addClass' : 'rmClass'](doc, `${mode.replace(/\\ /g, '-')}-mode`);\r\n }\r\n Index.selectMode.value = Conf['Index Mode'];\r\n Index.cb.size();\r\n Index.showHiddenThreads = false;\r\n return $('#hidden-toggle a', Index.navLinks).textContent = 'Show';\r\n },\r\n\r\n setupSort() {\r\n Index.selectRev.checked = /-rev$/.test(Index.currentSort);\r\n Index.selectSort.value = Index.currentSort.replace(/-rev$/, '');\r\n return Index.lastLongOptions.hidden = (Index.selectSort.value !== 'lastlong');\r\n },\r\n\r\n getPagesNum() {\r\n if (Index.search) {\r\n return Math.ceil(Index.sortedThreadIDs.length / Index.threadsNumPerPage);\r\n } else {\r\n return Index.pagesNum;\r\n }\r\n },\r\n\r\n getMaxPageNum() {\r\n return Math.max(1, Index.getPagesNum());\r\n },\r\n\r\n buildPagelist() {\r\n const pagesRoot = $('.pages', Index.pagelist);\r\n const maxPageNum = Index.getMaxPageNum();\r\n if (pagesRoot.childElementCount !== maxPageNum) {\r\n const nodes = [];\r\n for (let i = 1, end = maxPageNum; i <= end; i++) {\r\n var a = $.el('a', {\r\n textContent: i,\r\n href: i === 1 ? './' : i\r\n }\r\n );\r\n nodes.push($.tn('['), a, $.tn('] '));\r\n }\r\n $.rmAll(pagesRoot);\r\n return $.add(pagesRoot, nodes);\r\n }\r\n },\r\n\r\n setPage() {\r\n let a, strong;\r\n const pageNum = Index.currentPage;\r\n const maxPageNum = Index.getMaxPageNum();\r\n const pagesRoot = $('.pages', Index.pagelist);\r\n\r\n // Previous/Next buttons\r\n const prev = pagesRoot.previousElementSibling.firstElementChild;\r\n const next = pagesRoot.nextElementSibling.firstElementChild;\r\n let href = Math.max(pageNum - 1, 1);\r\n prev.href = href === 1 ? './' : href;\r\n prev.firstElementChild.disabled = href === pageNum;\r\n href = Math.min(pageNum + 1, maxPageNum);\r\n next.href = href === 1 ? './' : href;\r\n next.firstElementChild.disabled = href === pageNum;\r\n\r\n // current page\r\n if (strong = $('strong', pagesRoot)) {\r\n if (+strong.textContent === pageNum) { return; }\r\n $.replace(strong, strong.firstChild);\r\n } else {\r\n strong = $.el('strong');\r\n }\r\n\r\n if (a = pagesRoot.children[pageNum - 1]) {\r\n $.before(a, strong);\r\n return $.add(strong, a);\r\n }\r\n },\r\n\r\n updateHideLabel() {\r\n if (!Index.hideLabel) { return; }\r\n let hiddenCount = 0;\r\n for (var threadID of Index.liveThreadIDs) {\r\n if (Index.isHidden(threadID)) {\r\n hiddenCount++;\r\n }\r\n }\r\n if (!hiddenCount) {\r\n Index.hideLabel.hidden = true;\r\n if (Index.showHiddenThreads) { Index.cb.toggleHiddenThreads(); }\r\n return;\r\n }\r\n Index.hideLabel.hidden = false;\r\n return $('#hidden-count', Index.navLinks).textContent = hiddenCount === 1 ?\r\n '1 hidden thread'\r\n :\r\n `${hiddenCount} hidden threads`;\r\n },\r\n\r\n update(firstTime) {\r\n let oldReq;\r\n if (oldReq = Index.req) {\r\n delete Index.req;\r\n oldReq.abort();\r\n }\r\n\r\n if (Conf['Index Refresh Notifications']) {\r\n // Optional notification for manual refreshes\r\n if (!Index.notice) { Index.notice = new Notice('info', 'Refreshing index...'); }\r\n if (!Index.nTimeout) { Index.nTimeout = setTimeout(() => {\r\n if (Index.notice) {\r\n Index.notice.el.lastElementChild.textContent += ' (disable JSON Index if this takes too long)';\r\n }\r\n }\r\n , 3 * SECOND); }\r\n } else {\r\n // Also display notice if Index Refresh is taking too long\r\n if (!Index.nTimeout) { Index.nTimeout = setTimeout(() => Index.notice || (Index.notice = new Notice('info', 'Refreshing index... (disable JSON Index if this takes too long)'))\r\n , 3 * SECOND); }\r\n }\r\n\r\n // Hard refresh in case of incomplete page load.\r\n if (!firstTime && (d.readyState !== 'loading') && !$('.board + *')) {\r\n location.reload();\r\n return;\r\n }\r\n\r\n Index.req = $.whenModified(\r\n g.SITE.urls.catalogJSON({boardID: g.BOARD.ID}),\r\n 'Index',\r\n Index.load\r\n );\r\n return $.addClass(Index.button, 'spin');\r\n },\r\n\r\n load() {\r\n let err;\r\n if (this !== Index.req) { return; } // aborted\r\n\r\n $.rmClass(Index.button, 'spin');\r\n const {notice, nTimeout} = Index;\r\n if (nTimeout) { clearTimeout(nTimeout); }\r\n delete Index.nTimeout;\r\n delete Index.req;\r\n delete Index.notice;\r\n\r\n if (![200, 304].includes(this.status)) {\r\n err = `Index refresh failed. ${this.status ? `Error ${this.statusText} (${this.status})` : 'Connection Error'}`;\r\n if (notice) {\r\n notice.setType('warning');\r\n notice.el.lastElementChild.textContent = err;\r\n setTimeout(notice.close, SECOND);\r\n } else {\r\n new Notice('warning', err, 1);\r\n }\r\n return;\r\n }\r\n\r\n try {\r\n if (this.status === 200) {\r\n Index.parse(this.response);\r\n } else if (this.status === 304) {\r\n Index.pageLoad();\r\n }\r\n } catch (error) {\r\n err = error;\r\n c.error(`Index failure: ${err.message}`, err.stack);\r\n if (notice) {\r\n notice.setType('error');\r\n notice.el.lastElementChild.textContent = 'Index refresh failed.';\r\n setTimeout(notice.close, SECOND);\r\n } else {\r\n new Notice('error', 'Index refresh failed.', 1);\r\n }\r\n return;\r\n }\r\n\r\n if (notice) {\r\n if (Conf['Index Refresh Notifications']) {\r\n notice.setType('success');\r\n notice.el.lastElementChild.textContent = 'Index refreshed!';\r\n setTimeout(notice.close, SECOND);\r\n } else {\r\n notice.close();\r\n }\r\n }\r\n\r\n const timeEl = $('#index-last-refresh time', Index.navLinks);\r\n timeEl.dataset.utc = Date.parse(this.getResponseHeader('Last-Modified'));\r\n return RelativeDates.update(timeEl);\r\n },\r\n\r\n parse(pages) {\r\n $.cleanCache(url => /^https?:\\/\\/a\\.4cdn\\.org\\//.test(url));\r\n Index.parseThreadList(pages);\r\n Index.changed.threads = true;\r\n return Index.pageLoad();\r\n },\r\n\r\n parseThreadList(pages) {\r\n Index.pagesNum = pages.length;\r\n Index.threadsNumPerPage = pages[0]?.threads.length || 1;\r\n Index.liveThreadData = pages.reduce(((arr, next) => arr.concat(next.threads)), []);\r\n Index.liveThreadIDs = Index.liveThreadData.map(data => data.no);\r\n Index.liveThreadDict = dict();\r\n Index.threadPosition = dict();\r\n Index.parsedThreads = dict();\r\n Index.replyData = dict();\r\n for (let i = 0; i < Index.liveThreadData.length; i++) {\r\n var obj, results;\r\n var data = Index.liveThreadData[i];\r\n Index.liveThreadDict[data.no] = data;\r\n Index.threadPosition[data.no] = i;\r\n Index.parsedThreads[data.no] = (obj = g.SITE.Build.parseJSON(data, g.BOARD));\r\n obj.filterResults = (results = Filter.test(obj));\r\n obj.isOnTop = results.top;\r\n obj.isHidden = results.hide || ThreadHiding.isHidden(obj.boardID, obj.threadID);\r\n if (data.last_replies) {\r\n for (var reply of data.last_replies) {\r\n Index.replyData[`${g.BOARD}.${reply.no}`] = reply;\r\n }\r\n }\r\n }\r\n if (Index.liveThreadData[0]) {\r\n g.SITE.Build.spoilerRange[g.BOARD.ID] = Index.liveThreadData[0].custom_spoiler;\r\n }\r\n g.BOARD.threads.forEach(function(thread) {\r\n if (!Index.liveThreadIDs.includes(thread.ID)) { return thread.collect(); }\r\n });\r\n $.event('IndexUpdate',\r\n {threads: ((Index.liveThreadIDs.map((ID) => `${g.BOARD}.${ID}`)))});\r\n },\r\n\r\n isHidden(threadID) {\r\n let thread;\r\n if ((thread = g.BOARD.threads.get(threadID)) && thread.OP && !thread.OP.isFetchedQuote) {\r\n return thread.isHidden;\r\n } else {\r\n return Index.parsedThreads[threadID].isHidden;\r\n }\r\n },\r\n\r\n isHiddenReply(threadID, replyData) {\r\n return PostHiding.isHidden(g.BOARD.ID, threadID, replyData.no) || Filter.isHidden(g.SITE.Build.parseJSON(replyData, g.BOARD));\r\n },\r\n\r\n buildThreads(threadIDs, isCatalog, withReplies) {\r\n let errors;\r\n const threads = [];\r\n const newThreads = [];\r\n let newPosts = [];\r\n for (var ID of threadIDs) {\r\n var opRoot, thread;\r\n try {\r\n var OP;\r\n var threadData = Index.liveThreadDict[ID];\r\n\r\n if (thread = g.BOARD.threads.get(ID)) {\r\n var isStale = (thread.json !== threadData) && (JSON.stringify(thread.json) !== JSON.stringify(threadData));\r\n if (isStale) {\r\n thread.setCount('post', threadData.replies + 1, threadData.bumplimit);\r\n thread.setCount('file', threadData.images + !!threadData.ext, threadData.imagelimit);\r\n thread.setStatus('Sticky', !!threadData.sticky);\r\n thread.setStatus('Closed', !!threadData.closed);\r\n }\r\n if (thread.catalogView) {\r\n $.rm(thread.catalogView.nodes.replies);\r\n thread.catalogView.nodes.replies = null;\r\n }\r\n } else {\r\n thread = new Thread(ID, g.BOARD);\r\n newThreads.push(thread);\r\n }\r\n var lastPost = threadData.last_replies && threadData.last_replies.length ? threadData.last_replies[threadData.last_replies.length - 1].no : ID;\r\n if (lastPost > thread.lastPost) { thread.lastPost = lastPost; }\r\n thread.json = threadData;\r\n threads.push(thread);\r\n\r\n if ((OP = thread.OP) && !OP.isFetchedQuote) {\r\n OP.setCatalogOP(isCatalog);\r\n thread.setPage(Math.floor(Index.threadPosition[ID] / Index.threadsNumPerPage) + 1);\r\n } else {\r\n var obj = Index.parsedThreads[ID];\r\n opRoot = g.SITE.Build.post(obj);\r\n OP = new Post(opRoot, thread, g.BOARD);\r\n OP.filterResults = obj.filterResults;\r\n newPosts.push(OP);\r\n }\r\n\r\n if (!isCatalog || !thread.nodes.root) {\r\n g.SITE.Build.thread(thread, threadData, withReplies);\r\n }\r\n } catch (err) {\r\n // Skip posts that we failed to parse.\r\n if (!errors) { errors = []; }\r\n errors.push({\r\n message: `Parsing of Thread No.${thread} failed. Thread will be skipped.`,\r\n error: err,\r\n html: opRoot?.outerHTML\r\n });\r\n }\r\n }\r\n if (errors) { Main.handleErrors(errors); }\r\n\r\n if (withReplies) {\r\n newPosts = newPosts.concat(Index.buildReplies(threads));\r\n }\r\n\r\n Main.callbackNodes('Thread', newThreads);\r\n Main.callbackNodes('Post', newPosts);\r\n Index.updateHideLabel();\r\n $.event('IndexRefreshInternal', {threadIDs: (threads.map((t) => t.fullID)), isCatalog});\r\n\r\n return threads;\r\n },\r\n\r\n buildReplies(threads) {\r\n let errors;\r\n const posts = [];\r\n for (var thread of threads) {\r\n var lastReplies;\r\n if (!(lastReplies = Index.liveThreadDict[thread.ID].last_replies)) { continue; }\r\n var nodes = [];\r\n for (var data of lastReplies) {\r\n var node, post;\r\n if ((post = thread.posts.get(data.no)) && !post.isFetchedQuote) {\r\n nodes.push(post.nodes.root);\r\n continue;\r\n }\r\n nodes.push(node = g.SITE.Build.postFromObject(data, thread.board.ID));\r\n try {\r\n posts.push(new Post(node, thread, thread.board));\r\n } catch (err) {\r\n // Skip posts that we failed to parse.\r\n if (!errors) { errors = []; }\r\n errors.push({\r\n message: `Parsing of Post No.${data.no} failed. Post will be skipped.`,\r\n error: err,\r\n html: node?.outerHTML\r\n });\r\n }\r\n }\r\n $.add(thread.nodes.root, nodes);\r\n }\r\n\r\n if (errors) { Main.handleErrors(errors); }\r\n return posts;\r\n },\r\n\r\n buildCatalogViews(threads) {\r\n const catalogThreads = [];\r\n for (var thread of threads) {\r\n if (!thread.catalogView) {\r\n var {ID} = thread;\r\n var page = Math.floor(Index.threadPosition[ID] / Index.threadsNumPerPage) + 1;\r\n var root = g.SITE.Build.catalogThread(thread, Index.liveThreadDict[ID], page);\r\n catalogThreads.push(new CatalogThread(root, thread));\r\n }\r\n }\r\n Main.callbackNodes('CatalogThread', catalogThreads);\r\n },\r\n\r\n sizeCatalogViews(threads) {\r\n // XXX When browsers support CSS3 attr(), use it instead.\r\n const size = Conf['Index Size'] === 'small' ? 150 : 250;\r\n for (var thread of threads) {\r\n var {thumb} = thread.catalogView.nodes;\r\n var {width, height} = thumb.dataset;\r\n if (!width) { continue; }\r\n var ratio = size / Math.max(width, height);\r\n thumb.style.width = (width * ratio) + 'px';\r\n thumb.style.height = (height * ratio) + 'px';\r\n }\r\n },\r\n\r\n buildCatalogReplies(thread) {\r\n let lastReplies;\r\n const {nodes} = thread.catalogView;\r\n if (!(lastReplies = Index.liveThreadDict[thread.ID].last_replies)) { return; }\r\n\r\n const replies = [];\r\n for (var data of lastReplies) {\r\n if (Index.isHiddenReply(thread.ID, data)) { continue; }\r\n var reply = g.SITE.Build.catalogReply(thread, data);\r\n RelativeDates.update($('time', reply));\r\n $.on($('.catalog-reply-preview', reply), 'mouseover', QuotePreview.mouseover);\r\n replies.push(reply);\r\n }\r\n\r\n nodes.replies = $.el('div', {className: 'catalog-replies'});\r\n $.add(nodes.replies, replies);\r\n $.add(thread.OP.nodes.post, nodes.replies);\r\n },\r\n\r\n sort() {\r\n let threadIDs;\r\n const {liveThreadIDs, liveThreadData} = Index;\r\n if (!liveThreadData) { return; }\r\n const tmp_time = new Date().getTime()/1000;\r\n const sortType = Index.currentSort.replace(/-rev$/, '');\r\n Index.sortedThreadIDs = (() => { switch (sortType) {\r\n case 'lastreply': case 'lastlong':\r\n var repliesAvailable = liveThreadData.some(thread => thread.last_replies?.length);\r\n var lastlong = function(thread) {\r\n if (!repliesAvailable) {\r\n return thread.last_modified;\r\n }\r\n const iterable = thread.last_replies || [];\r\n for (let i = iterable.length - 1; i >= 0; i--) {\r\n var r = iterable[i];\r\n if (Index.isHiddenReply(thread.no, r)) { continue; }\r\n if (sortType === 'lastreply') {\r\n return r;\r\n }\r\n var len = r.com ? g.SITE.Build.parseComment(r.com).replace(/[^a-z]/ig, '').length : 0;\r\n if (len >= Index.lastLongThresholds[+!!r.ext]) {\r\n return r;\r\n }\r\n }\r\n if (thread.omitted_posts && thread.last_replies?.length) { return thread.last_replies[0]; } else { return thread; }\r\n };\r\n var lastlongD = dict();\r\n for (var thread of liveThreadData) {\r\n lastlongD[thread.no] = lastlong(thread).no;\r\n }\r\n return [...liveThreadData].sort((a, b) => lastlongD[b.no] - lastlongD[a.no]).map(post => post.no);\r\n case 'bump': return liveThreadIDs;\r\n case 'birth': return [...liveThreadIDs ].sort((a, b) => b - a);\r\n case 'replycount': return [...liveThreadData].sort((a, b) => b.replies - a.replies).map(post => post.no);\r\n case 'filecount': return [...liveThreadData].sort((a, b) => b.images - a.images).map(post => post.no);\r\n case 'activity': return [...liveThreadData].sort((a, b) => ((tmp_time-a.time)/(a.replies+1)) - ((tmp_time-b.time)/(b.replies+1))).map(post => post.no);\r\n default: return liveThreadIDs;\r\n } })();\r\n if (/-rev$/.test(Index.currentSort)) {\r\n Index.sortedThreadIDs.reverse();\r\n }\r\n if (Index.search && (threadIDs = Index.querySearch(Index.search))) {\r\n Index.sortedThreadIDs = threadIDs;\r\n }\r\n // Sticky threads\r\n Index.sortOnTop(obj => obj.isSticky);\r\n // Highlighted threads\r\n Index.sortOnTop(obj => obj.isOnTop || (Conf['Pin Watched Threads'] && ThreadWatcher.isWatchedRaw(obj.boardID, obj.threadID)));\r\n // Non-hidden threads\r\n if (Conf['Anchor Hidden Threads']) { return Index.sortOnTop(obj => !Index.isHidden(obj.threadID)); }\r\n },\r\n\r\n sortOnTop(match) {\r\n const topThreads = [];\r\n const bottomThreads = [];\r\n for (var ID of Index.sortedThreadIDs) {\r\n (match(Index.parsedThreads[ID]) ? topThreads : bottomThreads).push(ID);\r\n }\r\n return Index.sortedThreadIDs = topThreads.concat(bottomThreads);\r\n },\r\n\r\n buildIndex() {\r\n let threadIDs;\r\n if (!Index.liveThreadData) { return; }\r\n switch (Conf['Index Mode']) {\r\n case 'all pages':\r\n threadIDs = Index.sortedThreadIDs;\r\n break;\r\n case 'catalog':\r\n threadIDs = Index.sortedThreadIDs.filter(ID => !Index.isHidden(ID) !== Index.showHiddenThreads);\r\n break;\r\n default:\r\n threadIDs = Index.threadsOnPage(Index.currentPage);\r\n }\r\n delete Index.pageNum;\r\n $.rmAll(Index.root);\r\n $.rmAll(Header.hover);\r\n if (Index.loaded && Index.root.parentNode) {\r\n $.event('PostsRemoved', null, Index.root);\r\n }\r\n if (Conf['Index Mode'] === 'catalog') {\r\n Index.buildCatalog(threadIDs);\r\n } else {\r\n Index.buildStructure(threadIDs);\r\n }\r\n },\r\n\r\n threadsOnPage(pageNum) {\r\n const nodesPerPage = Index.threadsNumPerPage;\r\n const offset = nodesPerPage * (pageNum - 1);\r\n return Index.sortedThreadIDs.slice(offset , offset + nodesPerPage);\r\n },\r\n\r\n buildStructure(threadIDs) {\r\n const threads = Index.buildThreads(threadIDs, false, Conf['Show Replies']);\r\n const nodes = [];\r\n for (var thread of threads) {\r\n nodes.push(thread.nodes.root, $.el('hr'));\r\n }\r\n $.add(Index.root, nodes);\r\n if (Index.root.parentNode) {\r\n $.event('PostsInserted', null, Index.root);\r\n }\r\n Index.loaded = true;\r\n },\r\n\r\n buildCatalog(threadIDs) {\r\n let i = 0;\r\n const n = threadIDs.length;\r\n let node0 = null;\r\n var fn = function() {\r\n if (node0 && !node0.parentNode) { return; } // Index.root cleared\r\n const j = (i > 0) && Index.root.parentNode ? n : i + 30;\r\n node0 = Index.buildCatalogPart(threadIDs.slice(i, j))[0];\r\n i = j;\r\n if (i < n) {\r\n return $.queueTask(fn);\r\n } else {\r\n if (Index.root.parentNode) {\r\n $.event('PostsInserted', null, Index.root);\r\n }\r\n return Index.loaded = true;\r\n }\r\n };\r\n fn();\r\n },\r\n\r\n buildCatalogPart(threadIDs) {\r\n const threads = Index.buildThreads(threadIDs, true);\r\n Index.buildCatalogViews(threads);\r\n Index.sizeCatalogViews(threads);\r\n const nodes = [];\r\n for (var thread of threads) {\r\n thread.OP.setCatalogOP(true);\r\n $.add(thread.catalogView.nodes.root, thread.OP.nodes.root);\r\n nodes.push(thread.catalogView.nodes.root);\r\n $.on(thread.catalogView.nodes.root, 'mouseenter', Index.cb.catalogReplies.bind(thread));\r\n $.on(thread.OP.nodes.root, 'mouseenter', Index.cb.hoverAdjust.bind(thread.OP.nodes));\r\n }\r\n $.add(Index.root, nodes);\r\n return nodes;\r\n },\r\n\r\n clearSearch() {\r\n Index.searchInput.value = '';\r\n Index.onSearchInput();\r\n return Index.searchInput.focus();\r\n },\r\n\r\n setupSearch() {\r\n Index.searchInput.value = Index.search;\r\n if (Index.search) {\r\n return Index.searchInput.dataset.searching = 1;\r\n } else {\r\n // XXX https://bugzilla.mozilla.org/show_bug.cgi?id=1021289\r\n return Index.searchInput.removeAttribute('data-searching');\r\n }\r\n },\r\n\r\n onSearchInput() {\r\n const search = Index.searchInput.value.trim();\r\n if (search === Index.search) { return; }\r\n Index.pushState({\r\n search,\r\n replace: !!search === !!Index.search\r\n });\r\n return Index.pageLoad(false);\r\n },\r\n\r\n querySearch(query) {\r\n let keywords, match;\r\n if (match = query.match(/^([\\w+]+):\\/(.*)\\/(\\w*)$/)) {\r\n let regexp;\r\n try {\r\n regexp = RegExp(match[2], match[3]);\r\n } catch (error) {\r\n return [];\r\n }\r\n return Index.sortedThreadIDs.filter(ID => regexp.test(Filter.values(match[1], Index.parsedThreads[ID]).join('\\n')));\r\n }\r\n if (!(keywords = query.toLowerCase().match(/\\S+/g))) { return; }\r\n return Index.sortedThreadIDs.filter(ID => Index.searchMatch(Index.parsedThreads[ID], keywords));\r\n },\r\n\r\n searchMatch(obj, keywords) {\r\n const {info, file} = obj;\r\n if (info.comment == null) { info.comment = g.SITE.Build.parseComment(info.commentHTML.innerHTML); }\r\n let text = [];\r\n for (var key of ['comment', 'subject', 'name', 'tripcode']) {\r\n if (key in info) { text.push(info[key]); }\r\n }\r\n if (file) { text.push(file.name); }\r\n text = text.join(' ').toLowerCase();\r\n for (var keyword of keywords) {\r\n if (-1 === text.indexOf(keyword)) { return false; }\r\n }\r\n return true;\r\n }\r\n};\r\nexport default Index;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport DataBoard from \"../classes/DataBoard\";\r\nimport Thread from \"../classes/Thread\";\r\nimport Index from \"../General/Index\";\r\nimport UI from \"../General/UI\";\r\nimport { g, Conf, d, doc } from \"../globals/globals\";\r\nimport Main from \"../main/Main\";\r\nimport Menu from \"../Menu/Menu\";\r\nimport $ from \"../platform/$\";\r\nimport $$ from \"../platform/$$\";\r\nimport { dict } from \"../platform/helpers\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar ThreadHiding = {\r\n init() {\r\n if (!['index', 'catalog'].includes(g.VIEW) || (!Conf['Thread Hiding Buttons'] && !(Conf['Menu'] && Conf['Thread Hiding Link']) && !Conf['JSON Index'])) { return; }\r\n this.db = new DataBoard('hiddenThreads');\r\n if (g.VIEW === 'catalog') { return this.catalogWatch(); }\r\n this.catalogSet(g.BOARD);\r\n $.on(d, 'IndexRefreshInternal', this.onIndexRefresh);\r\n if (Conf['Thread Hiding Buttons']) {\r\n $.addClass(doc, 'thread-hide');\r\n }\r\n return Callbacks.Post.push({\r\n name: 'Thread Hiding',\r\n cb: this.node\r\n });\r\n },\r\n\r\n catalogSet(board) {\r\n if (!$.hasStorage || (g.SITE.software !== 'yotsuba')) { return; }\r\n const hiddenThreads = ThreadHiding.db.get({\r\n boardID: board.ID,\r\n defaultValue: dict()\r\n });\r\n for (var threadID in hiddenThreads) { hiddenThreads[threadID] = true; }\r\n return localStorage.setItem(`4chan-hide-t-${board}`, JSON.stringify(hiddenThreads));\r\n },\r\n\r\n catalogWatch() {\r\n if (!$.hasStorage || (g.SITE.software !== 'yotsuba')) { return; }\r\n this.hiddenThreads = JSON.parse(localStorage.getItem(`4chan-hide-t-${g.BOARD}`)) || {};\r\n return Main.ready(() => // 4chan's catalog sets the style to \"display: none;\" when hiding or unhiding a thread.\r\n new MutationObserver(ThreadHiding.catalogSave).observe($.id('threads'), {\r\n attributes: true,\r\n subtree: true,\r\n attributeFilter: ['style']\r\n }));\r\n },\r\n\r\n catalogSave() {\r\n let threadID;\r\n const hiddenThreads2 = JSON.parse(localStorage.getItem(`4chan-hide-t-${g.BOARD}`)) || {};\r\n for (threadID in hiddenThreads2) {\r\n if (!$.hasOwn(ThreadHiding.hiddenThreads, threadID)) {\r\n ThreadHiding.db.set({\r\n boardID: g.BOARD.ID,\r\n threadID,\r\n val: {makeStub: Conf['Stubs']}});\r\n }\r\n }\r\n for (threadID in ThreadHiding.hiddenThreads) {\r\n if (!$.hasOwn(hiddenThreads2, threadID)) {\r\n ThreadHiding.db.delete({\r\n boardID: g.BOARD.ID,\r\n threadID\r\n });\r\n }\r\n }\r\n return ThreadHiding.hiddenThreads = hiddenThreads2;\r\n },\r\n\r\n isHidden(boardID, threadID) {\r\n return !!(ThreadHiding.db && ThreadHiding.db.get({boardID, threadID}));\r\n },\r\n\r\n node() {\r\n let data;\r\n if (this.isReply || this.isClone || this.isFetchedQuote) { return; }\r\n\r\n if (Conf['Thread Hiding Buttons']) {\r\n $.prepend(this.nodes.root, ThreadHiding.makeButton(this.thread, 'hide'));\r\n }\r\n\r\n if (data = ThreadHiding.db.get({boardID: this.board.ID, threadID: this.ID})) {\r\n return ThreadHiding.hide(this.thread, data.makeStub);\r\n }\r\n },\r\n\r\n onIndexRefresh() {\r\n return g.BOARD.threads.forEach(function(thread) {\r\n const {root} = thread.nodes;\r\n if (thread.isHidden && thread.stub && !root.contains(thread.stub)) {\r\n return ThreadHiding.makeStub(thread, root);\r\n }\r\n });\r\n },\r\n\r\n menu: {\r\n init() {\r\n if ((g.VIEW !== 'index') || !Conf['Menu'] || !Conf['Thread Hiding Link']) { return; }\r\n\r\n let div = $.el('div', {\r\n className: 'hide-thread-link',\r\n textContent: 'Hide'\r\n }\r\n );\r\n\r\n const apply = $.el('a', {\r\n textContent: 'Apply',\r\n href: 'javascript:;'\r\n }\r\n );\r\n $.on(apply, 'click', ThreadHiding.menu.hide);\r\n\r\n const makeStub = UI.checkbox('Stubs', 'Make stub');\r\n\r\n Menu.menu.addEntry({\r\n el: div,\r\n order: 20,\r\n open({thread, isReply}) {\r\n if (isReply || thread.isHidden || (Conf['JSON Index'] && (Conf['Index Mode'] === 'catalog'))) {\r\n return false;\r\n }\r\n ThreadHiding.menu.thread = thread;\r\n return true;\r\n },\r\n subEntries: [{el: apply}, {el: makeStub}]});\r\n\r\n div = $.el('a', {\r\n className: 'show-thread-link',\r\n textContent: 'Show',\r\n href: 'javascript:;'\r\n }\r\n );\r\n $.on(div, 'click', ThreadHiding.menu.show);\r\n\r\n Menu.menu.addEntry({\r\n el: div,\r\n order: 20,\r\n open({thread, isReply}) {\r\n if (isReply || !thread.isHidden || (Conf['JSON Index'] && (Conf['Index Mode'] === 'catalog'))) {\r\n return false;\r\n }\r\n ThreadHiding.menu.thread = thread;\r\n return true;\r\n }\r\n });\r\n\r\n const hideStubLink = $.el('a', {\r\n textContent: 'Hide stub',\r\n href: 'javascript:;'\r\n }\r\n );\r\n $.on(hideStubLink, 'click', ThreadHiding.menu.hideStub);\r\n\r\n return Menu.menu.addEntry({\r\n el: hideStubLink,\r\n order: 15,\r\n open({thread, isReply}) {\r\n if (isReply || !thread.isHidden || (Conf['JSON Index'] && (Conf['Index Mode'] === 'catalog'))) {\r\n return false;\r\n }\r\n return ThreadHiding.menu.thread = thread;\r\n }\r\n });\r\n },\r\n\r\n hide() {\r\n const makeStub = $('input', this.parentNode).checked;\r\n const {thread} = ThreadHiding.menu;\r\n ThreadHiding.hide(thread, makeStub);\r\n ThreadHiding.saveHiddenState(thread, makeStub);\r\n return $.event('CloseMenu');\r\n },\r\n\r\n show() {\r\n const {thread} = ThreadHiding.menu;\r\n ThreadHiding.show(thread);\r\n ThreadHiding.saveHiddenState(thread);\r\n return $.event('CloseMenu');\r\n },\r\n\r\n hideStub() {\r\n const {thread} = ThreadHiding.menu;\r\n ThreadHiding.show(thread);\r\n ThreadHiding.hide(thread, false);\r\n ThreadHiding.saveHiddenState(thread, false);\r\n $.event('CloseMenu');\r\n }\r\n },\r\n\r\n makeButton(thread, type) {\r\n const a = $.el('a', {\r\n className: `${type}-thread-button`,\r\n href: 'javascript:;'\r\n }\r\n );\r\n $.extend(a, {textContent: type === \"hide\" ? '➖︎' : '➕︎' });\r\n a.dataset.fullID = thread.fullID;\r\n $.on(a, 'click', ThreadHiding.toggle);\r\n return a;\r\n },\r\n\r\n makeStub(thread, root) {\r\n let summary, threadDivider;\r\n let numReplies = $$(g.SITE.selectors.replyOriginal, root).length;\r\n if (summary = $(g.SITE.selectors.summary, root)) { numReplies += +summary.textContent.match(/\\d+/); }\r\n\r\n const a = ThreadHiding.makeButton(thread, 'show');\r\n $.add(a, $.tn(` ${thread.OP.info.nameBlock} (${numReplies === 1 ? '1 reply' : `${numReplies} replies`})`));\r\n thread.stub = $.el('div',\r\n {className: 'stub'});\r\n if (Conf['Menu']) {\r\n $.add(thread.stub, [a, Menu.makeButton(thread.OP)]);\r\n } else {\r\n $.add(thread.stub, a);\r\n }\r\n $.prepend(root, thread.stub);\r\n\r\n // Prevent hiding of thread divider on sites that put it inside the thread\r\n if (threadDivider = $(g.SITE.selectors.threadDivider, root)) {\r\n return $.addClass(threadDivider, 'threadDivider');\r\n }\r\n },\r\n\r\n saveHiddenState(thread, makeStub) {\r\n if (thread.isHidden) {\r\n ThreadHiding.db.set({\r\n boardID: thread.board.ID,\r\n threadID: thread.ID,\r\n val: {makeStub}});\r\n } else {\r\n ThreadHiding.db.delete({\r\n boardID: thread.board.ID,\r\n threadID: thread.ID\r\n });\r\n }\r\n return ThreadHiding.catalogSet(thread.board);\r\n },\r\n\r\n toggle(thread) {\r\n if (!(thread instanceof Thread)) {\r\n thread = g.threads.get(this.dataset.fullID);\r\n }\r\n if (thread.isHidden) {\r\n ThreadHiding.show(thread);\r\n } else {\r\n ThreadHiding.hide(thread);\r\n }\r\n return ThreadHiding.saveHiddenState(thread);\r\n },\r\n\r\n hide(thread, makeStub=Conf['Stubs']) {\r\n if (thread.isHidden) { return; }\r\n const threadRoot = thread.nodes.root;\r\n thread.isHidden = true;\r\n Index.updateHideLabel();\r\n if (thread.catalogView && !Index.showHiddenThreads) {\r\n $.rm(thread.catalogView.nodes.root);\r\n $.event('PostsRemoved', null, Index.root);\r\n }\r\n\r\n if (!makeStub) { return threadRoot.hidden = true; }\r\n\r\n return ThreadHiding.makeStub(thread, threadRoot);\r\n },\r\n\r\n show(thread) {\r\n if (thread.stub) {\r\n $.rm(thread.stub);\r\n delete thread.stub;\r\n }\r\n const threadRoot = thread.nodes.root;\r\n threadRoot.hidden = (thread.isHidden = false);\r\n Index.updateHideLabel();\r\n if (thread.catalogView && Index.showHiddenThreads) {\r\n $.rm(thread.catalogView.nodes.root);\r\n return $.event('PostsRemoved', null, Index.root);\r\n }\r\n }\r\n};\r\nexport default ThreadHiding;\r\n",null,null,null,"import $ from \"../platform/$\";\r\nimport CSS from \"../css/CSS\";\r\nimport { Conf } from \"../globals/globals\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nconst CustomCSS = {\r\n init() {\r\n if (!Conf['Custom CSS']) { return; }\r\n return this.addStyle();\r\n },\r\n\r\n addStyle() {\r\n return this.style = $.addStyle(CSS.sub(Conf['usercss']), 'custom-css', '#fourchanx-css');\r\n },\r\n\r\n rmStyle() {\r\n if (this.style) {\r\n $.rm(this.style);\r\n return delete this.style;\r\n }\r\n },\r\n\r\n update() {\r\n if (!this.style) {\r\n return this.addStyle();\r\n }\r\n return this.style.textContent = CSS.sub(Conf['usercss']);\r\n }\r\n};\r\nexport default CustomCSS;\r\n","import { Conf, d } from \"../globals/globals\";\r\nimport Main from \"../main/Main\";\r\nimport $ from \"../platform/$\";\r\nimport $$ from \"../platform/$$\";\r\nimport { dict } from \"../platform/helpers\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nconst SWTinyboard = {\r\n isOPContainerThread: true,\r\n mayLackJSON: true,\r\n threadModTimeIgnoresSage: true,\r\n\r\n disabledFeatures: [\r\n 'Resurrect Quotes',\r\n 'Quick Reply Personas',\r\n 'Quick Reply',\r\n 'Cooldown',\r\n 'Report Link',\r\n 'Delete Link',\r\n 'Edit Link',\r\n 'Quote Inlining',\r\n 'Quote Previewing',\r\n 'Quote Backlinks',\r\n 'File Info Formatting',\r\n 'Image Expansion',\r\n 'Image Expansion (Menu)',\r\n 'Comment Expansion',\r\n 'Thread Expansion',\r\n 'Favicon',\r\n 'Quote Threading',\r\n 'Thread Updater',\r\n 'Banner',\r\n 'Flash Features',\r\n 'Reply Pruning'\r\n ],\r\n\r\n detect() {\r\n for (var script of $$('script:not([src])', d.head)) {\r\n var m;\r\n if (m = script.textContent.match(/\\bvar configRoot=(\".*?\")/)) {\r\n var properties = dict();\r\n try {\r\n var root = JSON.parse(m[1]);\r\n if (root[0] === '/') {\r\n properties.root = location.origin + root;\r\n } else if (/^https?:/.test(root)) {\r\n properties.root = root;\r\n }\r\n } catch (error) {}\r\n return properties;\r\n }\r\n }\r\n return false;\r\n },\r\n\r\n awaitBoard(cb) {\r\n let reactUI;\r\n if (reactUI = $.id('react-ui')) {\r\n const s = (this.selectors = Object.create(this.selectors));\r\n s.boardFor = {index: '.page-container'};\r\n s.thread = 'div[id^=\"thread_\"]';\r\n return Main.mounted(cb);\r\n } else {\r\n return cb();\r\n }\r\n },\r\n\r\n urls: {\r\n thread({siteID, boardID, threadID}, isArchived) {\r\n return `${Conf['siteProperties'][siteID]?.root || `http://${siteID}/`}${boardID}/${isArchived ? 'archive/' : ''}res/${threadID}.html`;\r\n },\r\n post({postID}) { return `#${postID}`; },\r\n index({siteID, boardID}) { return `${Conf['siteProperties'][siteID]?.root || `http://${siteID}/`}${boardID}/`; },\r\n catalog({siteID, boardID}) { return `${Conf['siteProperties'][siteID]?.root || `http://${siteID}/`}${boardID}/catalog.html`; },\r\n threadJSON({siteID, boardID, threadID}, isArchived) {\r\n const root = Conf['siteProperties'][siteID]?.root;\r\n if (root) { return `${root}${boardID}/${isArchived ? 'archive/' : ''}res/${threadID}.json`; } else { return ''; }\r\n },\r\n archivedThreadJSON(thread) {\r\n return SWTinyboard.urls.threadJSON(thread, true);\r\n },\r\n threadsListJSON({siteID, boardID}) {\r\n const root = Conf['siteProperties'][siteID]?.root;\r\n if (root) { return `${root}${boardID}/threads.json`; } else { return ''; }\r\n },\r\n archiveListJSON({siteID, boardID}) {\r\n const root = Conf['siteProperties'][siteID]?.root;\r\n if (root) { return `${root}${boardID}/archive/archive.json`; } else { return ''; }\r\n },\r\n catalogJSON({siteID, boardID}) {\r\n const root = Conf['siteProperties'][siteID]?.root;\r\n if (root) { return `${root}${boardID}/catalog.json`; } else { return ''; }\r\n },\r\n file({siteID, boardID}, filename) {\r\n return `${Conf['siteProperties'][siteID]?.root || `http://${siteID}/`}${boardID}/${filename}`;\r\n },\r\n thumb(board, filename) {\r\n return SWTinyboard.urls.file(board, filename);\r\n }\r\n },\r\n\r\n selectors: {\r\n board: 'form[name=\"postcontrols\"]',\r\n thread: 'input[name=\"board\"] ~ div[id^=\"thread_\"]',\r\n threadDivider: 'div[id^=\"thread_\"] > hr:last-child',\r\n summary: '.omitted',\r\n postContainer: 'div[id^=\"reply_\"]:not(.hidden)', // postContainer is thread for OP\r\n opBottom: '.op',\r\n replyOriginal: 'div[id^=\"reply_\"]:not(.hidden)',\r\n infoRoot: '.intro',\r\n info: {\r\n subject: '.subject',\r\n name: '.name',\r\n email: '.email',\r\n tripcode: '.trip',\r\n uniqueID: '.poster_id',\r\n capcode: '.capcode',\r\n flag: '.flag',\r\n date: 'time',\r\n nameBlock: 'label',\r\n quote: 'a[href*=\"#q\"]',\r\n reply: 'a[href*=\"/res/\"]:not([href*=\"#\"])'\r\n },\r\n icons: {\r\n isSticky: '.fa-thumb-tack',\r\n isClosed: '.fa-lock'\r\n },\r\n file: {\r\n text: '.fileinfo',\r\n link: '.fileinfo > a',\r\n thumb: 'a > .post-image'\r\n },\r\n thumbLink: '.file > a',\r\n multifile: '.files > .file',\r\n highlightable: {\r\n op: ' > .op',\r\n reply: '.reply',\r\n catalog: ' > .thread'\r\n },\r\n comment: '.body',\r\n spoiler: '.spoiler',\r\n quotelink: 'a[onclick*=\"highlightReply(\"]',\r\n catalog: {\r\n board: '#Grid',\r\n thread: '.mix',\r\n thumb: '.thread-image'\r\n },\r\n boardList: '.boardlist',\r\n boardListBottom: '.boardlist.bottom',\r\n styleSheet: '#stylesheet',\r\n psa: '.blotter',\r\n nav: {\r\n prev: '.pages > form > [value=Previous]',\r\n next: '.pages > form > [value=Next]'\r\n }\r\n },\r\n\r\n classes: {\r\n highlight: 'highlighted'\r\n },\r\n\r\n xpath: {\r\n thread: 'div[starts-with(@id,\"thread_\")]',\r\n postContainer: 'div[starts-with(@id,\"reply_\") or starts-with(@id,\"thread_\")]',\r\n replyContainer: 'div[starts-with(@id,\"reply_\")]'\r\n },\r\n\r\n regexp: {\r\n quotelink:\r\n new RegExp(`\\\r\n/\\\r\n([^/]+)\\\r\n/res/\\\r\n(\\\\d+)\\\r\n(?:\\\\.\\\\w+)?#\\\r\n(\\\\d+)\\\r\n$\\\r\n`),\r\n quotelinkHTML:\r\n /]*\\bhref=\"[^\"]*\\/([^\\/]+)\\/res\\/(\\d+)(?:\\.\\w+)?#(\\d+)\"/g\r\n },\r\n\r\n Build: {\r\n parseJSON(data, board) {\r\n const o = this.parseJSON(data, board);\r\n if (data.ext === 'deleted') {\r\n delete o.file;\r\n $.extend(o, {\r\n files: [],\r\n fileDeleted: true,\r\n filesDeleted: [0]\r\n });\r\n }\r\n if (data.extra_files) {\r\n let file;\r\n for (let i = 0; i < data.extra_files.length; i++) {\r\n var extra_file = data.extra_files[i];\r\n if (extra_file.ext === 'deleted') {\r\n o.filesDeleted.push(i);\r\n } else {\r\n file = this.parseJSONFile(data, board);\r\n o.files.push(file);\r\n }\r\n }\r\n if (o.files.length) {\r\n o.file = o.files[0];\r\n }\r\n }\r\n return o;\r\n },\r\n\r\n parseComment(html) {\r\n html = html\r\n .replace(//gi, '\\n')\r\n .replace(/<[^>]*>/g, '');\r\n return $.unescape(html);\r\n }\r\n },\r\n\r\n bgColoredEl() {\r\n return $.el('div', {className: 'post reply'});\r\n },\r\n\r\n isFileURL(url) {\r\n return /\\/src\\/[^\\/]+/.test(url.pathname);\r\n },\r\n\r\n preParsingFixes(board) {\r\n // fixes effects of unclosed link in announcement\r\n let broken;\r\n if (broken = $('a > input[name=\"board\"]', board)) {\r\n return $.before(broken.parentNode, broken);\r\n }\r\n },\r\n\r\n parseNodes(post, nodes) {\r\n // Add vichan's span.poster_id around the ID if not already present.\r\n let m;\r\n if (nodes.uniqueID) { return; }\r\n let text = '';\r\n let node = nodes.nameBlock.nextSibling;\r\n while (node && (node.nodeType === 3)) {\r\n text += node.textContent;\r\n node = node.nextSibling;\r\n }\r\n if (m = text.match(/(\\s*ID:\\s*)(\\S+)/)) {\r\n let uniqueID;\r\n nodes.info.normalize();\r\n let {nextSibling} = nodes.nameBlock;\r\n nextSibling = nextSibling.splitText(m[1].length);\r\n nextSibling.splitText(m[2].length);\r\n nodes.uniqueID = (uniqueID = $.el('span', {className: 'poster_id'}));\r\n $.replace(nextSibling, uniqueID);\r\n return $.add(uniqueID, nextSibling);\r\n }\r\n },\r\n\r\n parseDate(node) {\r\n let date = Date.parse(node.getAttribute('datetime')?.trim());\r\n if (!isNaN(date)) { return new Date(date); }\r\n date = Date.parse(node.textContent.trim() + ' UTC'); // e.g. onesixtwo.club\r\n if (!isNaN(date)) { return new Date(date); }\r\n return undefined;\r\n },\r\n\r\n parseFile(post, file) {\r\n let info, infoNode;\r\n const {text, link, thumb} = file;\r\n if ($.x(`ancestor::${this.xpath.postContainer}[1]`, text) !== post.nodes.root) { return false; } // file belongs to a reply\r\n if (!(infoNode = link.nextSibling?.textContent.includes('(') ? link.nextSibling : link.nextElementSibling)) { return false; }\r\n if (!(info = infoNode.textContent.match(/\\((.*,\\s*)?([\\d.]+ ?[KMG]?B).*\\)/))) { return false; }\r\n const nameNode = $('.postfilename', text);\r\n $.extend(file, {\r\n name: nameNode ? (nameNode.title || nameNode.textContent) : link.pathname.match(/[^/]*$/)[0],\r\n size: info[2],\r\n dimensions: info[0].match(/\\d+x\\d+/)?.[0]\r\n });\r\n if (thumb) {\r\n $.extend(file, {\r\n thumbURL: /\\/static\\//.test(thumb.src) && $.isImage(link.href) ? link.href : thumb.src,\r\n isSpoiler: /^Spoiler/i.test(info[1] || '') || (link.textContent === 'Spoiler Image')\r\n }\r\n );\r\n }\r\n return true;\r\n },\r\n\r\n isThumbExpanded(file) {\r\n // Detect old Tinyboard image expansion that changes src attribute on thumbnail.\r\n return $.hasClass(file.thumb.parentNode, 'expanded') || (file.thumb.parentNode.dataset.expanded === 'true');\r\n },\r\n\r\n isLinkified(link) {\r\n return /\\bnofollow\\b/.test(link.rel);\r\n },\r\n\r\n catalogPin(threadRoot) {\r\n return threadRoot.dataset.sticky = 'true';\r\n }\r\n};\r\nexport default SWTinyboard;\r\n",null,"import { Conf, d } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\nimport PassMessagePage from './PassMessage/PassMessageHtml';\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\n\r\nconst PassMessage = {\r\n init() {\r\n if (Conf['passMessageClosed']) { return; }\r\n const msg = $.el('div',\r\n {className: 'box-outer top-box'}\r\n ,\r\n PassMessagePage);\r\n msg.style.cssText = 'padding-bottom: 0;';\r\n const close = $('a', msg);\r\n $.on(close, 'click', function() {\r\n $.rm(msg);\r\n return $.set('passMessageClosed', true);\r\n });\r\n return $.ready(function() {\r\n let hd;\r\n if (hd = $.id('hd')) {\r\n return $.after(hd, msg);\r\n } else {\r\n return $.prepend(d.body, msg);\r\n }\r\n });\r\n }\r\n};\r\nexport default PassMessage;\r\n","import Redirect from \"../Archive/Redirect\";\r\nimport $ from \"../platform/$\";\r\nimport ReportPage from './Report/ArchiveReport.html';\r\nimport CSS from \"../css/CSS\";\r\nimport Captcha from \"../Posting/Captcha\";\r\nimport { Conf, d, g } from \"../globals/globals\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\n\r\nvar Report = {\r\n init() {\r\n let match;\r\n if (!(match = location.search.match(/\\bno=(\\d+)/))) { return; }\r\n Captcha.replace.init();\r\n this.postID = +match[1];\r\n return $.ready(this.ready);\r\n },\r\n\r\n ready() {\r\n $.addStyle(CSS.report);\r\n\r\n if (Conf['Archive Report']) { Report.archive(); }\r\n\r\n new MutationObserver(function() {\r\n Report.fit('iframe[src^=\"https://www.google.com/recaptcha/api2/frame\"]');\r\n return Report.fit('body');\r\n }).observe(d.body, {\r\n childList: true,\r\n attributes: true,\r\n subtree: true\r\n }\r\n );\r\n return Report.fit('body');\r\n },\r\n\r\n fit(selector) {\r\n let el;\r\n if (!((el = $(selector, doc)) && (getComputedStyle(el).visibility !== 'hidden'))) { return; }\r\n const dy = (el.getBoundingClientRect().bottom - doc.clientHeight) + 8;\r\n if (dy > 0) { return window.resizeBy(0, dy); }\r\n },\r\n\r\n archive() {\r\n let match, urls;\r\n if (!(urls = Redirect.report(g.BOARD.ID)).length) { return; }\r\n\r\n const form = $('form');\r\n const types = $.id('reportTypes');\r\n const message = $('h3');\r\n\r\n const fieldset = $.el('fieldset', {\r\n id: 'archive-report',\r\n hidden: true\r\n }\r\n ,\r\n { innerHTML: ReportPage });\r\n const enabled = $('#archive-report-enabled', fieldset);\r\n const reason = $('#archive-report-reason', fieldset);\r\n const submit = $('#archive-report-submit', fieldset);\r\n\r\n $.on(enabled, 'change', function() {\r\n return reason.disabled = !this.checked;\r\n });\r\n\r\n if (form && types) {\r\n fieldset.hidden = !$('[value=\"31\"]', types).checked;\r\n $.on(types, 'change', function(e) {\r\n fieldset.hidden = (e.target.value !== '31');\r\n return Report.fit('body');\r\n });\r\n $.after(types, fieldset);\r\n Report.fit('body');\r\n $.one(form, 'submit', function(e) {\r\n if (!fieldset.hidden && enabled.checked) {\r\n e.preventDefault();\r\n return Report.archiveSubmit(urls, reason.value, results => {\r\n this.action = '#archiveresults=' + encodeURIComponent(JSON.stringify(results));\r\n return this.submit();\r\n });\r\n }\r\n });\r\n } else if (message) {\r\n fieldset.hidden = /Report submitted!/.test(message.textContent);\r\n $.on(enabled, 'change', function() {\r\n return submit.hidden = !this.checked;\r\n });\r\n $.after(message, fieldset);\r\n $.on(submit, 'click', () => Report.archiveSubmit(urls, reason.value, Report.archiveResults));\r\n }\r\n\r\n if (match = location.hash.match(/^#archiveresults=(.*)$/)) {\r\n try {\r\n return Report.archiveResults(JSON.parse(decodeURIComponent(match[1])));\r\n } catch (error) {}\r\n }\r\n },\r\n\r\n archiveSubmit(urls, reason, cb) {\r\n const form = $.formData({\r\n board: g.BOARD.ID,\r\n num: Report.postID,\r\n reason\r\n });\r\n const results = [];\r\n for (var [name, url] of urls) {\r\n (function(name, url) {\r\n return $.ajax(url, {\r\n onloadend() {\r\n results.push([name, this.response || {error: ''}]);\r\n if (results.length === urls.length) {\r\n return cb(results);\r\n }\r\n },\r\n form\r\n });\r\n })(name, url);\r\n }\r\n },\r\n\r\n archiveResults(results) {\r\n const fieldset = $.id('archive-report');\r\n for (var [name, response] of results) {\r\n var line = $.el('h3',\r\n {className: 'archive-report-response'});\r\n if ('success' in response) {\r\n $.addClass(line, 'archive-report-success');\r\n line.textContent = `${name}: ${response.success}`;\r\n } else {\r\n $.addClass(line, 'archive-report-error');\r\n line.textContent = `${name}: ${response.error || 'Error reporting post.'}`;\r\n }\r\n if (fieldset) {\r\n $.before(fieldset, line);\r\n } else {\r\n $.add(d.body, line);\r\n }\r\n }\r\n }\r\n};\r\nexport default Report;\r\n","import DataBoard from \"../classes/DataBoard\";\r\nimport { Conf, d, g } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nconst PostSuccessful = {\r\n init() {\r\n if (!Conf['Remember Your Posts']) { return; }\r\n return $.ready(this.ready);\r\n },\r\n\r\n ready() {\r\n if (d.title !== 'Post successful!') { return; }\r\n\r\n let [_, threadID, postID] = $('h1').nextSibling.textContent.match(/thread:(\\d+),no:(\\d+)/);\r\n postID = +postID;\r\n threadID = +threadID || postID;\r\n\r\n const db = new DataBoard('yourPosts');\r\n return db.set({\r\n boardID: g.BOARD.ID,\r\n threadID,\r\n postID,\r\n val: true\r\n });\r\n }\r\n};\r\nexport default PostSuccessful;\r\n",null,null,null,null,"import SWTinyboard from \"./SW.tinyboard\";\r\nimport SWYotsuba from \"./SW.yotsuba\";\r\n\r\nconst SW = { tinyboard: SWTinyboard, yotsuba: SWYotsuba };\r\nexport default SW;\r\n",null,null,"import Callbacks from \"../classes/Callbacks\";\r\nimport Header from \"../General/Header\";\r\nimport UI from \"../General/UI\";\r\nimport { g, Conf, E, d } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\nimport QuoteThreading from \"../Quotelinks/QuoteThreading\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS104: Avoid inline assignments\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar ReplyPruning = {\r\n init() {\r\n if ((g.VIEW !== 'thread') || !Conf['Reply Pruning']) { return; }\r\n\r\n this.container = $.frag();\r\n\r\n this.summary = $.el('span', {\r\n hidden: true,\r\n className: 'summary'\r\n }\r\n );\r\n this.summary.style.cursor = 'pointer';\r\n $.on(this.summary, 'click', () => {\r\n this.inputs.enabled.checked = !this.inputs.enabled.checked;\r\n return $.event('change', null, this.inputs.enabled);\r\n });\r\n\r\n const label = UI.checkbox('Prune Replies', 'Show Last', Conf['Prune All Threads']);\r\n const el = $.el('span',\r\n {title: 'Maximum number of replies to show.'}\r\n ,\r\n {innerHTML: \" \"});\r\n $.prepend(el, label);\r\n\r\n this.inputs = {\r\n enabled: label.firstElementChild,\r\n replies: el.lastElementChild\r\n };\r\n\r\n this.setEnabled.call(this.inputs.enabled);\r\n $.on(this.inputs.enabled, 'change', this.setEnabled);\r\n $.on(this.inputs.replies, 'change', $.cb.value);\r\n\r\n Header.menu.addEntry({\r\n el,\r\n order: 190\r\n });\r\n\r\n return Callbacks.Thread.push({\r\n name: 'Reply Pruning',\r\n cb: this.node\r\n });\r\n },\r\n\r\n position: 0,\r\n hidden: 0,\r\n hiddenFiles: 0,\r\n total: 0,\r\n totalFiles: 0,\r\n\r\n setEnabled() {\r\n const other = QuoteThreading.input;\r\n if (this.checked && other?.checked) {\r\n other.checked = false;\r\n $.event('change', null, other);\r\n }\r\n return ReplyPruning.active = this.checked;\r\n },\r\n\r\n showIfHidden(id) {\r\n if (ReplyPruning.container && $(`#${id}`, ReplyPruning.container)) {\r\n ReplyPruning.inputs.enabled.checked = false;\r\n return $.event('change', null, ReplyPruning.inputs.enabled);\r\n }\r\n },\r\n\r\n node() {\r\n let middle;\r\n ReplyPruning.thread = this;\r\n\r\n if (this.isSticky) {\r\n ReplyPruning.active = (ReplyPruning.inputs.enabled.checked = true);\r\n if (QuoteThreading.input) {\r\n // Disable Quote Threading for this thread but don't save the setting.\r\n Conf['Thread Quotes'] = (QuoteThreading.input.checked = false);\r\n }\r\n }\r\n\r\n this.posts.forEach(function(post) {\r\n if (post.isReply) {\r\n ReplyPruning.total++;\r\n if (post.file) { return ReplyPruning.totalFiles++; }\r\n }\r\n });\r\n\r\n // If we're linked to a post that we would hide, don't hide the posts in the first place.\r\n if (\r\n ReplyPruning.active &&\r\n /^#p\\d+$/.test(location.hash) &&\r\n (1 <= (middle = this.posts.keys.indexOf(location.hash.slice(2))) && middle < 1 + Math.max(ReplyPruning.total - +Conf[\"Max Replies\"], 0))\r\n ) {\r\n ReplyPruning.active = (ReplyPruning.inputs.enabled.checked = false);\r\n }\r\n\r\n $.after(this.OP.nodes.root, ReplyPruning.summary);\r\n\r\n $.on(ReplyPruning.inputs.enabled, 'change', ReplyPruning.update);\r\n $.on(ReplyPruning.inputs.replies, 'change', ReplyPruning.update);\r\n $.on(d, 'ThreadUpdate', ReplyPruning.updateCount);\r\n $.on(d, 'ThreadUpdate', ReplyPruning.update);\r\n\r\n return ReplyPruning.update();\r\n },\r\n\r\n updateCount(e) {\r\n if (e.detail[404]) { return; }\r\n for (var fullID of e.detail.newPosts) {\r\n ReplyPruning.total++;\r\n if (g.posts.get(fullID).file) { ReplyPruning.totalFiles++; }\r\n }\r\n },\r\n\r\n update() {\r\n let boardTop, node, post;\r\n const hidden1 = ReplyPruning.hidden;\r\n const hidden2 = ReplyPruning.active ?\r\n Math.max(ReplyPruning.total - +Conf[\"Max Replies\"], 0)\r\n :\r\n 0;\r\n\r\n // Record position from bottom of document\r\n const oldPos = d.body.clientHeight - window.scrollY;\r\n\r\n const {posts} = ReplyPruning.thread;\r\n\r\n if (ReplyPruning.hidden < hidden2) {\r\n while ((ReplyPruning.hidden < hidden2) && (ReplyPruning.position < posts.keys.length)) {\r\n post = posts.get(posts.keys[ReplyPruning.position++]);\r\n if (post.isReply && !post.isFetchedQuote) {\r\n while ((node = ReplyPruning.summary.nextSibling) && (node !== post.nodes.root)) { $.add(ReplyPruning.container, node); }\r\n $.add(ReplyPruning.container, post.nodes.root);\r\n ReplyPruning.hidden++;\r\n if (post.file) { ReplyPruning.hiddenFiles++; }\r\n }\r\n }\r\n\r\n } else if (ReplyPruning.hidden > hidden2) {\r\n const frag = $.frag();\r\n while ((ReplyPruning.hidden > hidden2) && (ReplyPruning.position > 0)) {\r\n post = posts.get(posts.keys[--ReplyPruning.position]);\r\n if (post.isReply && !post.isFetchedQuote) {\r\n while ((node = ReplyPruning.container.lastChild) && (node !== post.nodes.root)) { $.prepend(frag, node); }\r\n $.prepend(frag, post.nodes.root);\r\n ReplyPruning.hidden--;\r\n if (post.file) { ReplyPruning.hiddenFiles--; }\r\n }\r\n }\r\n $.after(ReplyPruning.summary, frag);\r\n $.event('PostsInserted', null, ReplyPruning.summary.parentNode);\r\n }\r\n\r\n ReplyPruning.summary.textContent = ReplyPruning.active ?\r\n g.SITE.Build.summaryText('+', ReplyPruning.hidden, ReplyPruning.hiddenFiles)\r\n :\r\n g.SITE.Build.summaryText('-', ReplyPruning.total, ReplyPruning.totalFiles);\r\n ReplyPruning.summary.hidden = (ReplyPruning.total <= +Conf[\"Max Replies\"]);\r\n\r\n // Maintain position in thread when posts are added/removed above\r\n if ((hidden1 !== hidden2) && ((boardTop = Header.getTopOf($('.board'))) < 0)) {\r\n return window.scrollBy(0, Math.max(d.body.clientHeight - oldPos, window.scrollY + boardTop) - window.scrollY);\r\n }\r\n }\r\n};\r\nexport default ReplyPruning;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport RandomAccessList from \"../classes/RandomAccessList\";\r\nimport Header from \"../General/Header\";\r\nimport { Conf, d, g } from \"../globals/globals\";\r\nimport ReplyPruning from \"../Monitoring/ReplyPruning\";\r\nimport Unread from \"../Monitoring/Unread\";\r\nimport $ from \"../platform/$\";\r\nimport { dict } from \"../platform/helpers\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\n/*\r\n <3 aeosynth\r\n*/\r\n\r\nvar QuoteThreading = {\r\n init() {\r\n if (!Conf['Quote Threading'] || (g.VIEW !== 'thread')) { return; }\r\n\r\n this.controls = $.el('label',\r\n {innerHTML: \" Threading\"});\r\n\r\n this.threadNewLink = $.el('span', {\r\n className: 'brackets-wrap threadnewlink',\r\n hidden: true\r\n }\r\n );\r\n $.extend(this.threadNewLink, {innerHTML: \"Thread New Posts\"});\r\n\r\n this.input = $('input', this.controls);\r\n this.input.checked = Conf['Thread Quotes'];\r\n\r\n $.on(this.input, 'change', this.setEnabled);\r\n $.on(this.input, 'change', this.rethread);\r\n $.on(this.threadNewLink.firstElementChild, 'click', this.rethread);\r\n $.on(d, '4chanXInitFinished', () => { return this.ready = true; });\r\n\r\n Header.menu.addEntry(this.entry = {\r\n el: this.controls,\r\n order: 99\r\n }\r\n );\r\n\r\n Callbacks.Thread.push({\r\n name: 'Quote Threading',\r\n cb: this.setThread\r\n });\r\n\r\n return Callbacks.Post.push({\r\n name: 'Quote Threading',\r\n cb: this.node\r\n });\r\n },\r\n\r\n parent: dict(),\r\n children: dict(),\r\n inserted: dict(),\r\n\r\n toggleThreading() {\r\n return this.setThreadingState(!Conf['Thread Quotes']);\r\n },\r\n\r\n setThreadingState(enabled) {\r\n this.input.checked = enabled;\r\n this.setEnabled.call(this.input);\r\n return this.rethread.call(this.input);\r\n },\r\n\r\n setEnabled() {\r\n if (this.checked) {\r\n $.set('Prune All Threads', false);\r\n const other = ReplyPruning.inputs?.enabled;\r\n if (other?.checked) {\r\n other.checked = false;\r\n $.event('change', null, other);\r\n }\r\n }\r\n return $.cb.checked.call(this);\r\n },\r\n\r\n setThread() {\r\n QuoteThreading.thread = this;\r\n return $.asap((() => !Conf['Thread Updater'] || $('.navLinksBot > .updatelink')), function() {\r\n let navLinksBot;\r\n if (navLinksBot = $('.navLinksBot')) { return $.add(navLinksBot, [$.tn(' '), QuoteThreading.threadNewLink]); }\r\n });\r\n },\r\n\r\n node() {\r\n let parent;\r\n if (this.isFetchedQuote || this.isClone || !this.isReply) { return; }\r\n\r\n const parents = new Set();\r\n let lastParent = null;\r\n for (var quote of this.quotes) {\r\n if ((parent = g.posts.get(quote))) {\r\n if (!parent.isFetchedQuote && parent.isReply && (parent.ID < this.ID)) {\r\n parents.add(parent.ID);\r\n if (!lastParent || (parent.ID > lastParent.ID)) { lastParent = parent; }\r\n }\r\n }\r\n }\r\n\r\n if (!lastParent) { return; }\r\n\r\n let ancestor = lastParent;\r\n while ((ancestor = QuoteThreading.parent[ancestor.fullID])) {\r\n parents.delete(ancestor.ID);\r\n }\r\n\r\n if (parents.size === 1) {\r\n return QuoteThreading.parent[this.fullID] = lastParent;\r\n }\r\n },\r\n\r\n descendants(post) {\r\n let children;\r\n let posts = [post];\r\n if (children = QuoteThreading.children[post.fullID]) {\r\n for (var child of children) {\r\n posts = posts.concat(QuoteThreading.descendants(child));\r\n }\r\n }\r\n return posts;\r\n },\r\n\r\n insert(post) {\r\n let parent, x;\r\n if (!(\r\n Conf['Thread Quotes'] &&\r\n (parent = QuoteThreading.parent[post.fullID]) &&\r\n !QuoteThreading.inserted[post.fullID]\r\n )) { return false; }\r\n\r\n const descendants = QuoteThreading.descendants(post);\r\n if (!Unread.posts.has(parent.ID)) {\r\n if ((function() { for (var x of descendants) { if (Unread.posts.has(x.ID)) { return true; } } })()) {\r\n QuoteThreading.threadNewLink.hidden = false;\r\n return false;\r\n }\r\n }\r\n\r\n const {order} = Unread;\r\n const children = (QuoteThreading.children[parent.fullID] || (QuoteThreading.children[parent.fullID] = []));\r\n const threadContainer = parent.nodes.threadContainer || $.el('div', {className: 'threadContainer'});\r\n const nodes = [post.nodes.root];\r\n if (post.nodes.threadContainer) { nodes.push(post.nodes.threadContainer); }\r\n\r\n let i = children.length;\r\n for (let j = children.length - 1; j >= 0; j--) { var child = children[j]; if (child.ID >= post.ID) { i--; } }\r\n if (i !== children.length) {\r\n const next = children[i];\r\n for (x of descendants) { order.before(order[next.ID], order[x.ID]); }\r\n children.splice(i, 0, post);\r\n $.before(next.nodes.root, nodes);\r\n } else {\r\n let prev2;\r\n let prev = parent;\r\n while ((prev2 = QuoteThreading.children[prev.fullID]) && prev2.length) {\r\n prev = prev2[prev2.length-1];\r\n }\r\n for (let k = descendants.length - 1; k >= 0; k--) { x = descendants[k]; order.after(order[prev.ID], order[x.ID]); }\r\n children.push(post);\r\n $.add(threadContainer, nodes);\r\n }\r\n\r\n QuoteThreading.inserted[post.fullID] = true;\r\n\r\n if (!parent.nodes.threadContainer) {\r\n parent.nodes.threadContainer = threadContainer;\r\n $.addClass(parent.nodes.root, 'threadOP');\r\n $.after(parent.nodes.root, threadContainer);\r\n }\r\n\r\n return true;\r\n },\r\n\r\n rethread() {\r\n if (!QuoteThreading.ready) { return; }\r\n const {thread} = QuoteThreading;\r\n const {posts} = thread;\r\n\r\n QuoteThreading.threadNewLink.hidden = true;\r\n\r\n if (Conf['Thread Quotes']) {\r\n posts.forEach(QuoteThreading.insert);\r\n } else {\r\n const nodes = [];\r\n Unread.order = new RandomAccessList();\r\n QuoteThreading.inserted = dict();\r\n posts.forEach(function(post) {\r\n if (post.isFetchedQuote) { return; }\r\n Unread.order.push(post);\r\n if (post.isReply) { nodes.push(post.nodes.root); }\r\n if (QuoteThreading.children[post.fullID]) {\r\n delete QuoteThreading.children[post.fullID];\r\n $.rmClass(post.nodes.root, 'threadOP');\r\n $.rm(post.nodes.threadContainer);\r\n return delete post.nodes.threadContainer;\r\n }\r\n });\r\n $.add(thread.nodes.root, nodes);\r\n }\r\n\r\n Unread.position = Unread.order.first;\r\n Unread.updatePosition();\r\n Unread.setLine(true);\r\n Unread.read();\r\n return Unread.update();\r\n }\r\n};\r\nexport default QuoteThreading;\r\n",null,null,"import Callbacks from \"../classes/Callbacks\";\r\nimport Header from \"../General/Header\";\r\nimport UI from \"../General/UI\";\r\nimport { Conf, doc, g } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar FappeTyme = {\r\n init() {\r\n if ((!Conf['Fappe Tyme'] && !Conf['Werk Tyme']) || !['index', 'thread', 'archive'].includes(g.VIEW)) { return; }\r\n\r\n this.nodes = {};\r\n this.enabled = {\r\n fappe: false,\r\n werk: Conf['werk']\r\n };\r\n\r\n for (var type of [\"Fappe\", \"Werk\"]) {\r\n if (Conf[`${type} Tyme`]) {\r\n var lc = type.toLowerCase();\r\n var el = UI.checkbox(lc, `${type} Tyme`, false);\r\n el.title = `${type} Tyme`;\r\n\r\n this.nodes[lc] = el.firstElementChild;\r\n if (Conf[lc]) { this.set(lc, true); }\r\n $.on(this.nodes[lc], 'change', this.toggle.bind(this, lc));\r\n\r\n Header.menu.addEntry({\r\n el,\r\n order: 97\r\n });\r\n\r\n var indicator = $.el('span', {\r\n className: 'indicator',\r\n textContent: type[0],\r\n title: `${type} Tyme active`\r\n }\r\n );\r\n $.on(indicator, 'click', function() {\r\n const check = $.getOwn(FappeTyme.nodes, this.parentNode.id.replace('shortcut-', ''));\r\n check.checked = !check.checked;\r\n return $.event('change', null, check);\r\n });\r\n Header.addShortcut(lc, indicator, 410);\r\n }\r\n }\r\n\r\n if (Conf['Werk Tyme']) {\r\n $.sync('werk', this.set.bind(this, 'werk'));\r\n }\r\n\r\n Callbacks.Post.push({\r\n name: 'Fappe Tyme',\r\n cb: this.node\r\n });\r\n\r\n return Callbacks.CatalogThread.push({\r\n name: 'Werk Tyme',\r\n cb: this.catalogNode\r\n });\r\n },\r\n\r\n node() {\r\n return this.nodes.root.classList.toggle('noFile', !this.files.length);\r\n },\r\n\r\n catalogNode() {\r\n const file = this.thread.OP.files[0];\r\n if (!file) { return; }\r\n const filename = $.el('div', {\r\n textContent: file.name,\r\n className: 'werkTyme-filename'\r\n }\r\n );\r\n return $.add(this.nodes.thumb.parentNode, filename);\r\n },\r\n\r\n set(type, enabled) {\r\n this.enabled[type] = (this.nodes[type].checked = enabled);\r\n return $[`${enabled ? 'add' : 'rm'}Class`](doc, `${type}Tyme`);\r\n },\r\n\r\n toggle(type) {\r\n this.set(type, !this.enabled[type]);\r\n if (type === 'werk') { return $.cb.checked.call(this.nodes[type]); }\r\n }\r\n};\r\nexport default FappeTyme;\r\n","import Callbacks from \"../classes/Callbacks\";\r\nimport Notice from \"../classes/Notice\";\r\nimport Filter from \"../Filtering/Filter\";\r\nimport { g, Conf, doc } from \"../globals/globals\";\r\nimport $ from \"../platform/$\";\r\nimport { dict } from \"../platform/helpers\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS104: Avoid inline assignments\r\n * DS204: Change includes calls to have a more natural evaluation order\r\n * DS207: Consider shorter variations of null checks\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar Sauce = {\r\n init() {\r\n let link;\r\n if (!['index', 'thread'].includes(g.VIEW) || !Conf['Sauce']) { return; }\r\n $.addClass(doc, 'show-sauce');\r\n\r\n const links = [];\r\n for (link of Conf['sauces'].split('\\n')) {\r\n var linkData;\r\n if ((link[0] !== '#') && (linkData = this.parseLink(link))) {\r\n links.push(linkData);\r\n }\r\n }\r\n if (!links.length) { return; }\r\n\r\n this.links = links;\r\n this.link = $.el('a', {\r\n target: '_blank',\r\n className: 'sauce'\r\n }\r\n );\r\n return Callbacks.Post.push({\r\n name: 'Sauce',\r\n cb: this.node\r\n });\r\n },\r\n\r\n parseLink(link) {\r\n if (!(link = link.trim())) { return null; }\r\n const parts = dict();\r\n const iterable = link.split(/;(?=(?:text|boards|types|regexp|sandbox):?)/);\r\n for (let i = 0; i < iterable.length; i++) {\r\n var part = iterable[i];\r\n if (i === 0) {\r\n parts['url'] = part;\r\n } else {\r\n var m = part.match(/^(\\w*):?(.*)$/);\r\n parts[m[1]] = m[2];\r\n }\r\n }\r\n if (!parts['text']) { parts['text'] = parts['url'].match(/(\\w+)\\.\\w+\\//)?.[1] || '?'; }\r\n if ('boards' in parts) {\r\n parts['boards'] = Filter.parseBoards(parts['boards']);\r\n }\r\n if ('regexp' in parts) {\r\n try {\r\n let regexp;\r\n if (regexp = parts['regexp'].match(/^\\/(.*)\\/(\\w*)$/)) {\r\n parts['regexp'] = RegExp(regexp[1], regexp[2]);\r\n } else {\r\n parts['regexp'] = RegExp(parts['regexp']);\r\n }\r\n } catch (err) {\r\n new Notice('warning', [\r\n $.tn(\"Invalid regexp for Sauce link:\"),\r\n $.el('br'),\r\n $.tn(link),\r\n $.el('br'),\r\n $.tn(err.message)\r\n ], 60);\r\n return null;\r\n }\r\n }\r\n return parts;\r\n },\r\n\r\n createSauceLink(link, post, file) {\r\n let a, matches, needle;\r\n const ext = file.url.match(/[^.]*$/)[0];\r\n const parts = dict();\r\n $.extend(parts, link);\r\n\r\n if (!!parts['boards'] && !parts['boards'][`${post.siteID}/${post.boardID}`] && !parts['boards'][`${post.siteID}/*`]) { return null; }\r\n if (!!parts['types'] && (needle = ext, !parts['types'].split(',').includes(needle))) { return null; }\r\n if (!!parts['regexp'] && (!(matches = file.name.match(parts['regexp'])))) { return null; }\r\n\r\n const missing = [];\r\n for (var key of ['url', 'text']) {\r\n parts[key] = parts[key].replace(/%(T?URL|IMG|[sh]?MD5|board|name|%|semi|\\$\\d+)/g, function(orig, parameter) {\r\n let type;\r\n if (parameter[0] === '$') {\r\n if (!matches) { return orig; }\r\n type = matches[parameter.slice(1)] || '';\r\n } else {\r\n type = Sauce.formatters[parameter](post, file, ext);\r\n if ((type == null)) {\r\n missing.push(parameter);\r\n return '';\r\n }\r\n }\r\n\r\n if ((key === 'url') && !['%', 'semi'].includes(parameter)) {\r\n if (/^javascript:/i.test(parts['url'])) { type = JSON.stringify(type); }\r\n type = encodeURIComponent(type);\r\n }\r\n return type;\r\n });\r\n }\r\n\r\n if (g.SITE.areMD5sDeferred?.(post.board) && missing.length && !missing.filter(x => !/^.?MD5$/.test(x)).length) {\r\n a = Sauce.link.cloneNode(false);\r\n a.dataset.skip = '1';\r\n return a;\r\n }\r\n\r\n if (missing.length) { return null; }\r\n\r\n a = Sauce.link.cloneNode(false);\r\n a.href = parts['url'];\r\n a.textContent = parts['text'];\r\n if (/^javascript:/i.test(parts['url'])) { a.removeAttribute('target'); }\r\n return a;\r\n },\r\n\r\n node() {\r\n if (this.isClone) { return; }\r\n for (var file of this.files) {\r\n Sauce.file(this, file);\r\n }\r\n },\r\n\r\n file(post, file) {\r\n let link, node;\r\n const nodes = [];\r\n const skipped = [];\r\n for (link of Sauce.links) {\r\n if (node = Sauce.createSauceLink(link, post, file)) {\r\n nodes.push($.tn(' '), node);\r\n if (node.dataset.skip) { skipped.push([link, node]); }\r\n }\r\n }\r\n $.add(file.text, nodes);\r\n\r\n if (skipped.length) {\r\n var observer = new MutationObserver(function() {\r\n if (file.text.dataset.md5) {\r\n for ([link, node] of skipped) {\r\n var node2;\r\n if (node2 = Sauce.createSauceLink(link, post, file)) {\r\n $.replace(node, node2);\r\n }\r\n }\r\n return observer.disconnect();\r\n }\r\n });\r\n return observer.observe(file.text, {attributes: true});\r\n }\r\n },\r\n\r\n formatters: {\r\n TURL(post, file) { return file.thumbURL; },\r\n URL(post, file) { return file.url; },\r\n IMG(post, file, ext) { if (['gif', 'jpg', 'jpeg', 'png'].includes(ext)) { return file.url; } else { return file.thumbURL; } },\r\n MD5(post, file) { return file.MD5; },\r\n sMD5(post, file) { return file.MD5?.replace(/[+/=]/g, c => ({'+': '-', '/': '_', '=': ''})[c]); },\r\n hMD5(post, file) { if (file.MD5) { return (atob(file.MD5).map((c) => `0${c.charCodeAt(0).toString(16)}`.slice(-2))).join(''); } },\r\n board(post) { return post.board.ID; },\r\n name(post, file) { return file.name; },\r\n '%'() { return '%'; },\r\n semi() { return ';'; }\r\n }\r\n};\r\nexport default Sauce;\r\n","/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS205: Consider reworking code to avoid use of IIFEs\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nimport galleryPage from './Gallery/Gallery.html';\r\nimport $ from '../platform/$';\r\nimport Callbacks from '../classes/Callbacks';\r\nimport Notice from '../classes/Notice';\r\nimport Main from '../main/Main';\r\nimport Keybinds from '../Miscellaneous/Keybinds';\r\nimport $$ from '../platform/$$';\r\nimport ImageCommon from './ImageCommon';\r\nimport Sauce from './Sauce';\r\nimport Volume from './Volume';\r\nimport Header from '../General/Header';\r\nimport { Conf, d, doc, g } from '../globals/globals';\r\nimport UI from '../General/UI';\r\nimport Get from '../General/Get';\r\nimport { debounce, dict, SECOND } from '../platform/helpers';\r\n\r\nvar Gallery = {\r\n init() {\r\n if (!(this.enabled = Conf['Gallery'] && ['index', 'thread'].includes(g.VIEW))) { return; }\r\n\r\n this.delay = Conf['Slide Delay'];\r\n\r\n const el = $.el('a', {\r\n href: 'javascript:;',\r\n title: 'Gallery',\r\n textContent: '🖼︎',\r\n });\r\n\r\n $.on(el, 'click', this.cb.toggle);\r\n\r\n Header.addShortcut('gallery', el, 530);\r\n\r\n return Callbacks.Post.push({\r\n name: 'Gallery',\r\n cb: this.node\r\n });\r\n },\r\n\r\n node() {\r\n return (() => {\r\n const result = [];\r\n for (var file of this.files) {\r\n if (file.thumb) {\r\n if (Gallery.nodes) {\r\n Gallery.generateThumb(this, file);\r\n Gallery.nodes.total.textContent = Gallery.images.length;\r\n }\r\n\r\n if (!Conf['Image Expansion'] && ((g.SITE.software !== 'tinyboard') || !Main.jsEnabled)) {\r\n result.push($.on(file.thumbLink, 'click', Gallery.cb.image));\r\n } else {\r\n result.push(undefined);\r\n }\r\n }\r\n }\r\n return result;\r\n })();\r\n },\r\n\r\n build(image) {\r\n let dialog, thumb;\r\n const {cb} = Gallery;\r\n\r\n if (Conf['Fullscreen Gallery']) {\r\n $.one(d, 'fullscreenchange mozfullscreenchange webkitfullscreenchange', () => $.on(d, 'fullscreenchange mozfullscreenchange webkitfullscreenchange', cb.close));\r\n doc.mozRequestFullScreen?.();\r\n doc.webkitRequestFullScreen?.(Element.ALLOW_KEYBOARD_INPUT);\r\n }\r\n\r\n Gallery.images = [];\r\n const nodes = (Gallery.nodes = {});\r\n Gallery.fileIDs = dict();\r\n Gallery.slideshow = false;\r\n\r\n nodes.el = (dialog = $.el('div',\r\n {id: 'a-gallery'}));\r\n $.extend(dialog, {innerHTML: galleryPage });\r\n\r\n const object = {\r\n buttons: '.gal-buttons',\r\n frame: '.gal-image',\r\n name: '.gal-name',\r\n count: '.count',\r\n total: '.total',\r\n sauce: '.gal-sauce',\r\n thumbs: '.gal-thumbnails',\r\n next: '.gal-image a',\r\n current: '.gal-image img'\r\n };\r\n for (var key in object) { var value = object[key]; nodes[key] = $(value, dialog); }\r\n\r\n const menuButton = $('.menu-button', dialog);\r\n nodes.menu = new UI.Menu('gallery');\r\n\r\n $.on(nodes.frame, 'click', cb.blank);\r\n if (Conf['Mouse Wheel Volume']) { $.on(nodes.frame, 'wheel', Volume.wheel); }\r\n $.on(nodes.next, 'click', cb.click);\r\n $.on(nodes.name, 'click', ImageCommon.download);\r\n\r\n $.on($('.gal-prev', dialog), 'click', cb.prev);\r\n $.on($('.gal-next', dialog), 'click', cb.next);\r\n $.on($('.gal-start', dialog), 'click', cb.start);\r\n $.on($('.gal-stop', dialog), 'click', cb.stop);\r\n $.on($('.gal-close', dialog), 'click', cb.close);\r\n\r\n $.on(menuButton, 'click', function(e) {\r\n return nodes.menu.toggle(e, this, g);\r\n });\r\n\r\n for (var entry of Gallery.menu.createSubEntries()) {\r\n entry.order = 0;\r\n nodes.menu.addEntry(entry);\r\n }\r\n\r\n $.on(d, 'keydown', cb.keybinds);\r\n if (Conf['Keybinds']) { $.off(d, 'keydown', Keybinds.keydown); }\r\n\r\n $.on(window, 'resize', Gallery.cb.setHeight);\r\n\r\n for (var postThumb of $$(g.SITE.selectors.file.thumb)) {\r\n var post;\r\n if (!(post = Get.postFromNode(postThumb))) { continue; }\r\n for (var file of post.files) {\r\n if (file.thumb) {\r\n Gallery.generateThumb(post, file);\r\n // If no image to open is given, pick image we have scrolled to.\r\n if (!image && Gallery.fileIDs[`${post.fullID}.${file.index}`]) {\r\n var candidate = file.thumbLink;\r\n if ((Header.getTopOf(candidate) + candidate.getBoundingClientRect().height) >= 0) {\r\n image = candidate;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n $.addClass(doc, 'gallery-open');\r\n\r\n $.add(d.body, dialog);\r\n\r\n nodes.thumbs.scrollTop = 0;\r\n nodes.current.parentElement.scrollTop = 0;\r\n\r\n if (image) { thumb = $(`[href='${image.href}']`, nodes.thumbs); }\r\n if (!thumb) { thumb = Gallery.images[Gallery.images.length-1]; }\r\n if (thumb) { Gallery.open(thumb); }\r\n\r\n doc.style.overflow = 'hidden';\r\n return nodes.total.textContent = Gallery.images.length;\r\n },\r\n\r\n generateThumb(post, file) {\r\n if (post.isClone || post.isHidden) { return; }\r\n if (!file || !file.thumb || (!file.isImage && !file.isVideo && !Conf['PDF in Gallery'])) { return; }\r\n if (Gallery.fileIDs[`${post.fullID}.${file.index}`]) { return; }\r\n\r\n Gallery.fileIDs[`${post.fullID}.${file.index}`] = true;\r\n\r\n const thumb = $.el('a', {\r\n className: 'gal-thumb',\r\n href: file.url,\r\n target: '_blank',\r\n title: file.name\r\n }\r\n );\r\n\r\n thumb.dataset.id = Gallery.images.length;\r\n thumb.dataset.post = post.fullID;\r\n thumb.dataset.file = file.index;\r\n\r\n const thumbImg = file.thumb.cloneNode(false);\r\n thumbImg.style.cssText = '';\r\n $.add(thumb, thumbImg);\r\n\r\n $.on(thumb, 'click', Gallery.cb.open);\r\n\r\n Gallery.images.push(thumb);\r\n return $.add(Gallery.nodes.thumbs, thumb);\r\n },\r\n\r\n load(thumb, errorCB) {\r\n const ext = thumb.href.match(/\\w*$/);\r\n const elType = $.getOwn({'webm': 'video', 'mp4': 'video', 'ogv': 'video', 'pdf': 'iframe'}, ext) || 'img';\r\n const file = $.el(elType);\r\n $.extend(file.dataset, thumb.dataset);\r\n $.on(file, 'error', errorCB);\r\n file.src = thumb.href;\r\n return file;\r\n },\r\n\r\n open(thumb) {\r\n let el, file, post;\r\n const {nodes} = Gallery;\r\n const oldID = +nodes.current.dataset.id;\r\n const newID = +thumb.dataset.id;\r\n\r\n // Highlight, center selected thumbnail\r\n if (el = Gallery.images[oldID]) { $.rmClass(el, 'gal-highlight'); }\r\n $.addClass(thumb, 'gal-highlight');\r\n nodes.thumbs.scrollTop = (thumb.offsetTop + (thumb.offsetHeight/2)) - (nodes.thumbs.clientHeight/2);\r\n\r\n // Load image or use preloaded image\r\n if (Gallery.cache?.dataset.id === (''+newID)) {\r\n file = Gallery.cache;\r\n $.off(file, 'error', Gallery.cacheError);\r\n $.on(file, 'error', Gallery.error);\r\n } else {\r\n file = Gallery.load(thumb, Gallery.error);\r\n }\r\n\r\n // Replace old image with new one\r\n $.off(nodes.current, 'error', Gallery.error);\r\n ImageCommon.pause(nodes.current);\r\n $.replace(nodes.current, file);\r\n nodes.current = file;\r\n\r\n if (file.nodeName === 'VIDEO') {\r\n file.loop = true;\r\n Volume.setup(file);\r\n if (Conf['Autoplay']) { file.play(); }\r\n if (Conf['Show Controls']) { ImageCommon.addControls(file); }\r\n }\r\n\r\n doc.classList.toggle('gal-pdf', file.nodeName === 'IFRAME');\r\n Gallery.cb.setHeight();\r\n nodes.count.textContent = +thumb.dataset.id + 1;\r\n nodes.name.download = (nodes.name.textContent = thumb.title);\r\n nodes.name.href = thumb.href;\r\n nodes.frame.scrollTop = 0;\r\n nodes.next.focus();\r\n\r\n // Set sauce links\r\n $.rmAll(nodes.sauce);\r\n if (Conf['Sauce'] && Sauce.links && (post = g.posts.get(file.dataset.post))) {\r\n const sauces = [];\r\n for (var link of Sauce.links) {\r\n var node;\r\n if (node = Sauce.createSauceLink(link, post, post.files[+file.dataset.file])) {\r\n sauces.push($.tn(' '), node);\r\n }\r\n }\r\n $.add(nodes.sauce, sauces);\r\n }\r\n\r\n // Continue slideshow if moving forward, stop otherwise\r\n if (Gallery.slideshow && ((newID > oldID) || ((oldID === (Gallery.images.length-1)) && (newID === 0)))) {\r\n Gallery.setupTimer();\r\n } else {\r\n Gallery.cb.stop();\r\n }\r\n\r\n // Scroll to post\r\n if (Conf['Scroll to Post'] && (post = g.posts.get(file.dataset.post))) {\r\n Header.scrollTo(post.nodes.root);\r\n }\r\n\r\n // Preload next image\r\n if (isNaN(oldID) || (newID === ((oldID + 1) % Gallery.images.length))) {\r\n return Gallery.cache = Gallery.load(Gallery.images[(newID + 1) % Gallery.images.length], Gallery.cacheError);\r\n }\r\n },\r\n\r\n error() {\r\n if (this.error?.code === MediaError.MEDIA_ERR_DECODE) {\r\n return new Notice('error', 'Corrupt or unplayable video', 30);\r\n }\r\n if (ImageCommon.isFromArchive(this)) { return; }\r\n const post = g.posts.get(this.dataset.post);\r\n const file = post.files[+this.dataset.file];\r\n return ImageCommon.error(this, post, file, null, url => {\r\n if (!url) { return; }\r\n Gallery.images[+this.dataset.id].href = url;\r\n if (Gallery.nodes.current === this) { return this.src = url; }\r\n });\r\n },\r\n\r\n cacheError() {\r\n return delete Gallery.cache;\r\n },\r\n\r\n cleanupTimer() {\r\n clearTimeout(Gallery.timeoutID);\r\n const {current} = Gallery.nodes;\r\n $.off(current, 'canplaythrough load', Gallery.startTimer);\r\n return $.off(current, 'ended', Gallery.cb.next);\r\n },\r\n\r\n startTimer() {\r\n return Gallery.timeoutID = setTimeout(Gallery.checkTimer, Gallery.delay * SECOND);\r\n },\r\n\r\n setupTimer() {\r\n Gallery.cleanupTimer();\r\n const {current} = Gallery.nodes;\r\n const isVideo = current.nodeName === 'VIDEO';\r\n if (isVideo) { current.play(); }\r\n if ((isVideo ? current.readyState >= 4 : current.complete) || (current.nodeName === 'IFRAME')) {\r\n return Gallery.startTimer();\r\n } else {\r\n return $.on(current, (isVideo ? 'canplaythrough' : 'load'), Gallery.startTimer);\r\n }\r\n },\r\n\r\n checkTimer() {\r\n const {current} = Gallery.nodes;\r\n if ((current.nodeName === 'VIDEO') && !current.paused) {\r\n $.on(current, 'ended', Gallery.cb.next);\r\n return current.loop = false;\r\n } else {\r\n return Gallery.cb.next();\r\n }\r\n },\r\n\r\n cb: {\r\n keybinds(e) {\r\n let key;\r\n if (!(key = Keybinds.keyCode(e))) { return; }\r\n\r\n const cb = (() => { switch (key) {\r\n case Conf['Close']: case Conf['Open Gallery']:\r\n return Gallery.cb.close;\r\n case Conf['Next Gallery Image']:\r\n return Gallery.cb.next;\r\n case Conf['Advance Gallery']:\r\n return Gallery.cb.advance;\r\n case Conf['Previous Gallery Image']:\r\n return Gallery.cb.prev;\r\n case Conf['Pause']:\r\n return Gallery.cb.pause;\r\n case Conf['Slideshow']:\r\n return Gallery.cb.toggleSlideshow;\r\n case Conf['Rotate image anticlockwise']:\r\n return Gallery.cb.rotateLeft;\r\n case Conf['Rotate image clockwise']:\r\n return Gallery.cb.rotateRight;\r\n case Conf['Download Gallery Image']:\r\n return Gallery.cb.download;\r\n } })();\r\n\r\n if (!cb) { return; }\r\n e.stopPropagation();\r\n e.preventDefault();\r\n return cb();\r\n },\r\n\r\n open(e) {\r\n if (e) { e.preventDefault(); }\r\n if (this) { return Gallery.open(this); }\r\n },\r\n\r\n image(e) {\r\n e.preventDefault();\r\n e.stopPropagation();\r\n return Gallery.build(this);\r\n },\r\n\r\n prev() {\r\n return Gallery.cb.open.call(\r\n Gallery.images[+Gallery.nodes.current.dataset.id - 1] || Gallery.images[Gallery.images.length - 1]\r\n );\r\n },\r\n next() {\r\n return Gallery.cb.open.call(\r\n Gallery.images[+Gallery.nodes.current.dataset.id + 1] || Gallery.images[0]\r\n );\r\n },\r\n\r\n click(e) {\r\n if (ImageCommon.onControls(e)) { return; }\r\n e.preventDefault();\r\n return Gallery.cb.advance();\r\n },\r\n\r\n advance() { if (!Conf['Autoplay'] && Gallery.nodes.current.paused) { return Gallery.nodes.current.play(); } else { return Gallery.cb.next(); } },\r\n toggle() { return (Gallery.nodes ? Gallery.cb.close : Gallery.build)(); },\r\n blank(e) { if (e.target === this) { return Gallery.cb.close(); } },\r\n toggleSlideshow() { return Gallery.cb[Gallery.slideshow ? 'stop' : 'start'](); },\r\n\r\n download() {\r\n const name = $('.gal-name');\r\n return name.click();\r\n },\r\n\r\n pause() {\r\n Gallery.cb.stop();\r\n const {current} = Gallery.nodes;\r\n if (current.nodeName === 'VIDEO') { return current[current.paused ? 'play' : 'pause'](); }\r\n },\r\n\r\n start() {\r\n $.addClass(Gallery.nodes.buttons, 'gal-playing');\r\n Gallery.slideshow = true;\r\n return Gallery.setupTimer();\r\n },\r\n\r\n stop() {\r\n if (!Gallery.slideshow) { return; }\r\n Gallery.cleanupTimer();\r\n const {current} = Gallery.nodes;\r\n if (current.nodeName === 'VIDEO') { current.loop = true; }\r\n $.rmClass(Gallery.nodes.buttons, 'gal-playing');\r\n return Gallery.slideshow = false;\r\n },\r\n\r\n rotateLeft() { return Gallery.cb.rotate(270); },\r\n rotateRight() { return Gallery.cb.rotate(90); },\r\n\r\n rotate: debounce(100, function(delta) {\r\n const {current} = Gallery.nodes;\r\n if (current.nodeName === 'IFRAME') { return; }\r\n current.dataRotate = ((current.dataRotate || 0) + delta) % 360;\r\n current.style.transform = `rotate(${current.dataRotate}deg)`;\r\n return Gallery.cb.setHeight();\r\n }),\r\n\r\n close() {\r\n $.off(Gallery.nodes.current, 'error', Gallery.error);\r\n ImageCommon.pause(Gallery.nodes.current);\r\n $.rm(Gallery.nodes.el);\r\n $.rmClass(doc, 'gallery-open');\r\n if (Conf['Fullscreen Gallery']) {\r\n $.off(d, 'fullscreenchange mozfullscreenchange webkitfullscreenchange', Gallery.cb.close);\r\n d.mozCancelFullScreen?.();\r\n d.webkitExitFullscreen?.();\r\n }\r\n delete Gallery.nodes;\r\n delete Gallery.fileIDs;\r\n doc.style.overflow = '';\r\n\r\n $.off(d, 'keydown', Gallery.cb.keybinds);\r\n if (Conf['Keybinds']) { $.on(d, 'keydown', Keybinds.keydown); }\r\n $.off(window, 'resize', Gallery.cb.setHeight);\r\n return clearTimeout(Gallery.timeoutID);\r\n },\r\n\r\n setFitness() {\r\n return (this.checked ? $.addClass : $.rmClass)(doc, `gal-${this.name.toLowerCase().replace(/\\s+/g, '-')}`);\r\n },\r\n\r\n setHeight: debounce(100, function () {\r\n let dim, margin, minHeight;\r\n const {current, frame} = Gallery.nodes;\r\n const {style} = current;\r\n\r\n if (Conf['Stretch to Fit'] && (dim = g.posts.get(current.dataset.post)?.files[+current.dataset.file].dimensions)) {\r\n const [width, height] = dim.split('x');\r\n let containerWidth = frame.clientWidth;\r\n let containerHeight = doc.clientHeight - 25;\r\n if (((current.dataRotate || 0) % 180) === 90) {\r\n [containerWidth, containerHeight] = [containerHeight, containerWidth];\r\n }\r\n minHeight = Math.min(containerHeight, (height / width) * containerWidth);\r\n style.minHeight = minHeight + 'px';\r\n style.minWidth = ((width / height) * minHeight) + 'px';\r\n } else {\r\n style.minHeight = (style.minWidth = '');\r\n }\r\n\r\n if (((current.dataRotate || 0) % 180) === 90) {\r\n style.maxWidth = Conf['Fit Height'] ? `${doc.clientHeight - 25}px` : 'none';\r\n style.maxHeight = Conf['Fit Width'] ? `${frame.clientWidth}px` : 'none';\r\n margin = (current.clientWidth - current.clientHeight)/2;\r\n return style.margin = `${margin}px ${-margin}px`;\r\n } else {\r\n return style.maxWidth = (style.maxHeight = (style.margin = ''));\r\n }\r\n }),\r\n\r\n setDelay() { return Gallery.delay = +this.value; }\r\n },\r\n\r\n menu: {\r\n init() {\r\n if (!Gallery.enabled) { return; }\r\n\r\n const el = $.el('span', {\r\n textContent: 'Gallery',\r\n className: 'gallery-link'\r\n }\r\n );\r\n\r\n return Header.menu.addEntry({\r\n el,\r\n order: 105,\r\n subEntries: Gallery.menu.createSubEntries()\r\n });\r\n },\r\n\r\n createSubEntry(name) {\r\n const label = UI.checkbox(name, name);\r\n const input = label.firstElementChild;\r\n if (['Hide Thumbnails', 'Fit Width', 'Fit Height'].includes(name)) { $.on(input, 'change', Gallery.cb.setFitness); }\r\n $.event('change', null, input);\r\n $.on(input, 'change', $.cb.checked);\r\n if (['Hide Thumbnails', 'Fit Width', 'Fit Height', 'Stretch to Fit'].includes(name)) { $.on(input, 'change', Gallery.cb.setHeight); }\r\n return {el: label};\r\n },\r\n\r\n createSubEntries() {\r\n const subEntries = (['Hide Thumbnails', 'Fit Width', 'Fit Height', 'Stretch to Fit', 'Scroll to Post'].map((item) => Gallery.menu.createSubEntry(item)));\r\n\r\n const delayLabel = $.el('label', {innerHTML: 'Slide Delay: '});\r\n const delayInput = delayLabel.firstElementChild;\r\n delayInput.value = Gallery.delay;\r\n $.on(delayInput, 'change', Gallery.cb.setDelay);\r\n $.on(delayInput, 'change', $.cb.value);\r\n subEntries.push({el: delayLabel});\r\n\r\n return subEntries;\r\n }\r\n }\r\n};\r\nexport default Gallery;\r\n","import Get from '../General/Get';\r\nimport Header from '../General/Header';\r\nimport UI from '../General/UI';\r\nimport { g, Conf, d, doc, E } from '../globals/globals';\r\nimport ImageHost from '../Images/ImageHost';\r\nimport Main from '../main/Main';\r\nimport $ from '../platform/$';\r\nimport $$ from '../platform/$$';\r\nimport CrossOrigin from '../platform/CrossOrigin';\r\nimport { dict } from '../platform/helpers';\r\nimport EmbeddingPage from './Embedding/Embed.html';\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS205: Consider reworking code to avoid use of IIFEs\r\n * DS207: Consider shorter variations of null checks\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\n\r\nvar Embedding = {\r\n init() {\r\n if (!['index', 'thread', 'archive'].includes(g.VIEW) || !Conf['Linkify'] || (!Conf['Embedding'] && !Conf['Link Title'] && !Conf['Cover Preview'])) { return; }\r\n this.types = dict();\r\n for (var type of this.ordered_types) { this.types[type.key] = type; }\r\n\r\n if (Conf['Embedding'] && (g.VIEW !== 'archive')) {\r\n this.dialog = UI.dialog('embedding',\r\n { innerHTML: EmbeddingPage });\r\n this.media = $('#media-embed', this.dialog);\r\n $.one(d, '4chanXInitFinished', this.ready);\r\n $.on(d, 'IndexRefreshInternal', () => g.posts.forEach(function(post) {\r\n for (post of [post, ...post.clones]) {\r\n for (var embed of post.nodes.embedlinks) {\r\n Embedding.cb.catalogRemove.call(embed);\r\n }\r\n }\r\n }));\r\n }\r\n if (Conf['Link Title']) {\r\n return $.on(d, '4chanXInitFinished PostsInserted', function() {\r\n for (var key in Embedding.types) {\r\n var service = Embedding.types[key];\r\n if (service.title?.batchSize) {\r\n Embedding.flushTitles(service.title);\r\n }\r\n }\r\n });\r\n }\r\n },\r\n\r\n events(post) {\r\n let el, i, items;\r\n if (g.VIEW === 'archive') { return; }\r\n if (Conf['Embedding']) {\r\n i = 0;\r\n items = (post.nodes.embedlinks = $$('.embedder', post.nodes.comment));\r\n while ((el = items[i++])) {\r\n $.on(el, 'click', Embedding.cb.click);\r\n if ($.hasClass(el, 'embedded')) { Embedding.cb.toggle.call(el); }\r\n }\r\n }\r\n if (Conf['Cover Preview']) {\r\n i = 0;\r\n items = $$('.linkify', post.nodes.comment);\r\n while ((el = items[i++])) {\r\n var data;\r\n if (data = Embedding.services(el)) {\r\n Embedding.preview(data);\r\n }\r\n }\r\n return;\r\n }\r\n },\r\n\r\n process(link, post) {\r\n let data;\r\n if (!Conf['Embedding'] && !Conf['Link Title'] && !Conf['Cover Preview']) { return; }\r\n if ($.x('ancestor::pre', link)) { return; }\r\n if (data = Embedding.services(link)) {\r\n data.post = post;\r\n if (Conf['Embedding'] && (g.VIEW !== 'archive')) { Embedding.embed(data); }\r\n if (Conf['Link Title']) { Embedding.title(data); }\r\n if (Conf['Cover Preview'] && (g.VIEW !== 'archive')) { return Embedding.preview(data); }\r\n }\r\n },\r\n\r\n services(link) {\r\n const {href} = link;\r\n for (var type of Embedding.ordered_types) {\r\n var match;\r\n if (match = type.regExp.exec(href)) {\r\n return {key: type.key, uid: match[1], options: match[2], link};\r\n }\r\n }\r\n },\r\n\r\n embed(data) {\r\n const {key, uid, options, link, post} = data;\r\n const {href} = link;\r\n\r\n $.addClass(link, key.toLowerCase());\r\n\r\n const embed = $.el('a', {\r\n className: 'embedder',\r\n href: 'javascript:;'\r\n }\r\n ,\r\n {innerHTML: '(unembed)'});\r\n\r\n const object = {key, uid, options, href};\r\n for (var name in object) { var value = object[name]; embed.dataset[name] = value; }\r\n\r\n $.on(embed, 'click', Embedding.cb.click);\r\n $.after(link, [$.tn(' '), embed]);\r\n post.nodes.embedlinks.push(embed);\r\n\r\n if (Conf['Auto-embed'] && !Conf['Floating Embeds'] && !post.isFetchedQuote) {\r\n if ($.hasClass(doc, 'catalog-mode')) {\r\n return $.addClass(embed, 'embed-removed');\r\n } else {\r\n return Embedding.cb.toggle.call(embed);\r\n }\r\n }\r\n },\r\n\r\n ready() {\r\n if (!Main.isThisPageLegit()) { return; }\r\n $.addClass(Embedding.dialog, 'empty');\r\n $.on($('.close', Embedding.dialog), 'click', Embedding.closeFloat);\r\n $.on($('.move', Embedding.dialog), 'mousedown', Embedding.dragEmbed);\r\n $.on($('.jump', Embedding.dialog), 'click', function() {\r\n if (doc.contains(Embedding.lastEmbed)) { return Header.scrollTo(Embedding.lastEmbed); }\r\n });\r\n return $.add(d.body, Embedding.dialog);\r\n },\r\n\r\n closeFloat() {\r\n delete Embedding.lastEmbed;\r\n $.addClass(Embedding.dialog, 'empty');\r\n return $.replace(Embedding.media.firstChild, $.el('div'));\r\n },\r\n\r\n dragEmbed() {\r\n // only webkit can handle a blocking div\r\n const {style} = Embedding.media;\r\n if (Embedding.dragEmbed.mouseup) {\r\n $.off(d, 'mouseup', Embedding.dragEmbed);\r\n Embedding.dragEmbed.mouseup = false;\r\n style.pointerEvents = '';\r\n return;\r\n }\r\n $.on(d, 'mouseup', Embedding.dragEmbed);\r\n Embedding.dragEmbed.mouseup = true;\r\n return style.pointerEvents = 'none';\r\n },\r\n\r\n title(data) {\r\n let service;\r\n const {key, uid, options, link, post} = data;\r\n if (!(service = Embedding.types[key].title)) { return; }\r\n $.addClass(link, key.toLowerCase());\r\n if (service.batchSize) {\r\n (service.queue || (service.queue = [])).push(data);\r\n if (service.queue.length >= service.batchSize) {\r\n return Embedding.flushTitles(service);\r\n }\r\n } else {\r\n return CrossOrigin.cache(service.api(uid), (function() { return Embedding.cb.title(this, data); }));\r\n }\r\n },\r\n\r\n flushTitles(service) {\r\n let data;\r\n const {queue} = service;\r\n if (!queue?.length) { return; }\r\n service.queue = [];\r\n const cb = function() {\r\n for (data of queue) { Embedding.cb.title(this, data); }\r\n };\r\n return CrossOrigin.cache(service.api((() => {\r\n const result = [];\r\n for (data of queue) { result.push(data.uid);\r\n }\r\n return result;\r\n })()), cb);\r\n },\r\n\r\n preview(data) {\r\n let service;\r\n const {key, uid, link} = data;\r\n if (!(service = Embedding.types[key].preview)) { return; }\r\n return $.on(link, 'mouseover', function(e) {\r\n const src = service.url(uid);\r\n const {height} = service;\r\n const el = $.el('img', {\r\n src,\r\n id: 'ihover'\r\n }\r\n );\r\n $.add(Header.hover, el);\r\n return UI.hover({\r\n root: link,\r\n el,\r\n latestEvent: e,\r\n endEvents: 'mouseout click',\r\n height\r\n });\r\n });\r\n },\r\n\r\n cb: {\r\n click(e) {\r\n e.preventDefault();\r\n if (!$.hasClass(this, 'embedded') && (Conf['Floating Embeds'] || $.hasClass(doc, 'catalog-mode'))) {\r\n let div;\r\n if (!(div = Embedding.media.firstChild)) { return; }\r\n $.replace(div, Embedding.cb.embed(this));\r\n Embedding.lastEmbed = Get.postFromNode(this).nodes.root;\r\n return $.rmClass(Embedding.dialog, 'empty');\r\n } else {\r\n return Embedding.cb.toggle.call(this);\r\n }\r\n },\r\n\r\n toggle() {\r\n if ($.hasClass(this, \"embedded\")) {\r\n $.rm(this.nextElementSibling);\r\n } else {\r\n $.after(this, Embedding.cb.embed(this));\r\n }\r\n return $.toggleClass(this, 'embedded');\r\n },\r\n\r\n embed(a) {\r\n // We create an element to embed\r\n let el, type;\r\n const container = $.el('div', {className: 'media-embed'});\r\n $.add(container, (el = (type = Embedding.types[a.dataset.key]).el(a)));\r\n\r\n // Set style values.\r\n el.style.cssText = (type.style != null) ?\r\n type.style\r\n :\r\n 'border: none; width: 640px; height: 360px;';\r\n\r\n return container;\r\n },\r\n\r\n catalogRemove() {\r\n const isCatalog = $.hasClass(doc, 'catalog-mode');\r\n if ((isCatalog && $.hasClass(this, 'embedded')) || (!isCatalog && $.hasClass(this, 'embed-removed'))) {\r\n Embedding.cb.toggle.call(this);\r\n return $.toggleClass(this, 'embed-removed');\r\n }\r\n },\r\n\r\n title(req, data) {\r\n let text;\r\n const {key, uid, options, link, post} = data;\r\n const service = Embedding.types[key].title;\r\n\r\n let {status} = req;\r\n if ([200, 304].includes(status) && service.status) {\r\n status = service.status(req.response)[0];\r\n }\r\n\r\n if (!status) { return; }\r\n\r\n text = `[${key}] ${(() => { switch (status) {\r\n case 200: case 304:\r\n text = service.text(req.response, uid);\r\n if (typeof text === 'string') {\r\n return text;\r\n } else {\r\n return text = link.textContent;\r\n }\r\n case 404:\r\n return \"Not Found\";\r\n case 403: case 401:\r\n return \"Forbidden or Private\";\r\n default:\r\n return `${status}'d`;\r\n } })()\r\n }`;\r\n\r\n link.dataset.original = link.textContent;\r\n link.textContent = text;\r\n for (var post2 of post.clones) {\r\n for (var link2 of $$('a.linkify', post2.nodes.comment)) {\r\n if (link2.href === link.href) {\r\n if (link2.dataset.original == null) { link2.dataset.original = link2.textContent; }\r\n link2.textContent = text;\r\n }\r\n }\r\n }\r\n }\r\n },\r\n\r\n ordered_types: [{\r\n key: 'audio',\r\n regExp: /^[^?#]+\\.(?:mp3|m4a|oga|wav|flac)(?:[?#]|$)/i,\r\n style: '',\r\n el(a) {\r\n return $.el('audio', {\r\n controls: true,\r\n preload: 'auto',\r\n src: a.dataset.href\r\n }\r\n );\r\n }\r\n }\r\n , {\r\n key: 'image',\r\n regExp: /^[^?#]+\\.(?:gif|png|jpg|jpeg|bmp|webp)(?::\\w+)?(?:[?#]|$)/i,\r\n style: '',\r\n el(a) {\r\n const hrefEsc = E(a.dataset.href);\r\n return $.el('div', { innerHTML: ``});\r\n }\r\n }\r\n , {\r\n key: 'video',\r\n regExp: /^[^?#]+\\.(?:og[gv]|webm|mp4)(?:[?#]|$)/i,\r\n style: 'max-width: 80vw; max-height: 80vh;',\r\n el(a) {\r\n const el = $.el('video', {\r\n hidden: true,\r\n controls: true,\r\n preload: 'auto',\r\n src: a.dataset.href,\r\n loop: ImageHost.test(a.dataset.href.split('/')[2])\r\n });\r\n $.on(el, 'loadedmetadata', function() {\r\n if ((el.videoHeight === 0) && el.parentNode) {\r\n return $.replace(el, Embedding.types.audio.el(a));\r\n } else {\r\n return el.hidden = false;\r\n }\r\n });\r\n return el;\r\n }\r\n }\r\n , {\r\n key: 'PeerTube',\r\n regExp: /^(\\w+:\\/\\/[^\\/]+\\/videos\\/watch\\/\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12})(.*)/,\r\n el(a) {\r\n let start;\r\n const options = (start = a.dataset.options.match(/[?&](start=\\w+)/)) ? `?${start[1]}` : '';\r\n const el = $.el('iframe',\r\n {src: a.dataset.uid.replace('/videos/watch/', '/videos/embed/') + options});\r\n el.setAttribute(\"allowfullscreen\", \"true\");\r\n return el;\r\n }\r\n }\r\n , {\r\n key: 'BitChute',\r\n regExp: /^\\w+:\\/\\/(?:www\\.)?bitchute\\.com\\/video\\/([\\w\\-]+)/,\r\n el(a) {\r\n const el = $.el('iframe',\r\n {src: `https://www.bitchute.com/embed/${a.dataset.uid}/`});\r\n el.setAttribute(\"allowfullscreen\", \"true\");\r\n return el;\r\n }\r\n }\r\n , {\r\n key: 'Clyp',\r\n regExp: /^\\w+:\\/\\/(?:www\\.)?clyp\\.it\\/(\\w{8})/,\r\n style: 'border: 0; width: 640px; height: 160px;',\r\n el(a) {\r\n return $.el('iframe',\r\n {src: `https://clyp.it/${a.dataset.uid}/widget`});\r\n },\r\n title: {\r\n api(uid) { return `https://api.clyp.it/oembed?url=https://clyp.it/${uid}`; },\r\n text(_) { return _.title; }\r\n }\r\n }\r\n , {\r\n key: 'Dailymotion',\r\n regExp: /^\\w+:\\/\\/(?:(?:www\\.)?dailymotion\\.com\\/(?:embed\\/)?video|dai\\.ly)\\/([A-Za-z0-9]+)[^?]*(.*)/,\r\n el(a) {\r\n let start;\r\n const options = (start = a.dataset.options.match(/[?&](start=\\d+)/)) ? `?${start[1]}` : '';\r\n const el = $.el('iframe',\r\n {src: `//www.dailymotion.com/embed/video/${a.dataset.uid}${options}`});\r\n el.setAttribute(\"allowfullscreen\", \"true\");\r\n return el;\r\n },\r\n title: {\r\n api(uid) { return `https://api.dailymotion.com/video/${uid}`; },\r\n text(_) { return _.title; }\r\n },\r\n preview: {\r\n url(uid) { return `https://www.dailymotion.com/thumbnail/video/${uid}`; },\r\n height: 240\r\n }\r\n }\r\n , {\r\n key: 'Gfycat',\r\n regExp: /^\\w+:\\/\\/(?:www\\.)?gfycat\\.com\\/(?:iframe\\/)?(\\w+)/,\r\n el(a) {\r\n const el = $.el('iframe',\r\n {src: `//gfycat.com/ifr/${a.dataset.uid}`});\r\n el.setAttribute(\"allowfullscreen\", \"true\");\r\n return el;\r\n }\r\n }\r\n , {\r\n key: 'Gist',\r\n regExp: /^\\w+:\\/\\/gist\\.github\\.com\\/[\\w\\-]+\\/(\\w+)/,\r\n style: '',\r\n el: (function() {\r\n let counter = 0;\r\n return function(a) {\r\n const el = $.el('pre', {\r\n hidden: true,\r\n id: `gist-embed-${counter++}`\r\n }\r\n );\r\n CrossOrigin.cache(`https://api.github.com/gists/${a.dataset.uid}`, function() {\r\n el.textContent = Object.values(this.response.files)[0].content;\r\n el.className = 'prettyprint';\r\n $.global(() => window.prettyPrint?.((function() {}), document.getElementById(document.currentScript.dataset.id).parentNode)\r\n , {id: el.id});\r\n return el.hidden = false;\r\n });\r\n return el;\r\n };\r\n })(),\r\n title: {\r\n api(uid) { return `https://api.github.com/gists/${uid}`; },\r\n text({files}) {\r\n for (var file in files) { if (files.hasOwnProperty(file)) { return file; } }\r\n }\r\n }\r\n }\r\n , {\r\n key: 'InstallGentoo',\r\n regExp: /^\\w+:\\/\\/paste\\.installgentoo\\.com\\/view\\/(?:raw\\/|download\\/|embed\\/)?(\\w+)/,\r\n el(a) {\r\n return $.el('iframe',\r\n {src: `https://paste.installgentoo.com/view/embed/${a.dataset.uid}`});\r\n }\r\n }\r\n , {\r\n key: 'LiveLeak',\r\n regExp: /^\\w+:\\/\\/(?:\\w+\\.)?liveleak\\.com\\/.*\\?.*[tif]=(\\w+)/,\r\n el(a) {\r\n const el = $.el('iframe',\r\n {src: `https://www.liveleak.com/e/${a.dataset.uid}`,});\r\n el.setAttribute(\"allowfullscreen\", \"true\");\r\n return el;\r\n }\r\n }\r\n , {\r\n key: 'Loopvid',\r\n regExp: /^\\w+:\\/\\/(?:www\\.)?loopvid.appspot.com\\/#?((?:pf|kd|lv|gd|gh|db|dx|nn|cp|wu|ig|ky|mf|m2|pc|1c|pi|ni|wl|ko|mm|ic|gc)\\/[\\w\\-\\/]+(?:,[\\w\\-\\/]+)*|fc\\/\\w+\\/\\d+|https?:\\/\\/.+)/,\r\n style: 'max-width: 80vw; max-height: 80vh;',\r\n el(a) {\r\n const el = $.el('video', {\r\n controls: true,\r\n preload: 'auto',\r\n loop: true\r\n }\r\n );\r\n if (/^http/.test(a.dataset.uid)) {\r\n $.add(el, $.el('source', {src: a.dataset.uid}));\r\n return el;\r\n }\r\n const [_, host, names] = a.dataset.uid.match(/(\\w+)\\/(.*)/);\r\n const types = (() => { switch (host) {\r\n case 'gd': case 'wu': case 'fc': return [''];\r\n case 'gc': return ['giant', 'fat', 'zippy'];\r\n default: return ['.webm', '.mp4'];\r\n } })();\r\n for (var name of names.split(',')) {\r\n for (var type of types) {\r\n var base = `${name}${type}`;\r\n var urls = (() => { switch (host) {\r\n // list from src/common.py at http://loopvid.appspot.com/source.html\r\n case 'pf': return [`https://kastden.org/_loopvid_media/pf/${base}`, `https://web.archive.org/web/2/http://a.pomf.se/${base}`];\r\n case 'kd': return [`https://kastden.org/loopvid/${base}`];\r\n case 'lv': return [`https://lv.kastden.org/${base}`];\r\n case 'gd': return [`https://docs.google.com/uc?export=download&id=${base}`];\r\n case 'gh': return [`https://googledrive.com/host/${base}`];\r\n case 'db': return [`https://dl.dropboxusercontent.com/u/${base}`];\r\n case 'dx': return [`https://dl.dropboxusercontent.com/${base}`];\r\n case 'nn': return [`https://kastden.org/_loopvid_media/nn/${base}`];\r\n case 'cp': return [`https://copy.com/${base}`];\r\n case 'wu': return [`http://webmup.com/${base}/vid.webm`];\r\n case 'ig': return [`https://i.imgur.com/${base}`];\r\n case 'ky': return [`https://kastden.org/_loopvid_media/ky/${base}`];\r\n case 'mf': return [`https://kastden.org/_loopvid_media/mf/${base}`, `https://web.archive.org/web/2/https://d.maxfile.ro/${base}`];\r\n case 'm2': return [`https://kastden.org/_loopvid_media/m2/${base}`];\r\n case 'pc': return [`https://kastden.org/_loopvid_media/pc/${base}`, `https://web.archive.org/web/2/http://a.pomf.cat/${base}`];\r\n case '1c': return [`http://b.1339.cf/${base}`];\r\n case 'pi': return [`https://kastden.org/_loopvid_media/pi/${base}`, `https://web.archive.org/web/2/https://u.pomf.is/${base}`];\r\n case 'ni': return [`https://kastden.org/_loopvid_media/ni/${base}`, `https://web.archive.org/web/2/https://u.nya.is/${base}`];\r\n case 'wl': return [`http://webm.land/media/${base}`];\r\n case 'ko': return [`https://kordy.kastden.org/loopvid/${base}`];\r\n case 'mm': return [`https://kastden.org/_loopvid_media/mm/${base}`, `https://web.archive.org/web/2/https://my.mixtape.moe/${base}`];\r\n case 'ic': return [`https://media.8ch.net/file_store/${base}`];\r\n case 'fc': return [`//${ImageHost.host()}/${base}.webm`];\r\n case 'gc': return [`https://${type}.gfycat.com/${name}.webm`];\r\n } })();\r\n\r\n for (var url of urls) {\r\n $.add(el, $.el('source', {src: url}));\r\n }\r\n }\r\n }\r\n return el;\r\n }\r\n }\r\n , {\r\n key: 'Openings.moe',\r\n regExp: /^\\w+:\\/\\/openings.moe\\/\\?video=([^.&=]+)/,\r\n style: 'width: 1280px; height: 720px; max-width: 80vw; max-height: 80vh;',\r\n el(a) {\r\n const el = $.el('iframe',\r\n {src: `https://openings.moe/?video=${a.dataset.uid}`,});\r\n el.setAttribute(\"allowfullscreen\", \"true\");\r\n return el;\r\n }\r\n }\r\n , {\r\n key: 'Pastebin',\r\n regExp: /^\\w+:\\/\\/(?:\\w+\\.)?pastebin\\.com\\/(?!u\\/)(?:[\\w.]+(?:\\/|\\?i\\=))?(\\w+)/,\r\n el(a) {\r\n let div;\r\n return div = $.el('iframe',\r\n {src: `//pastebin.com/embed_iframe.php?i=${a.dataset.uid}`});\r\n }\r\n }\r\n , {\r\n key: 'SoundCloud',\r\n regExp: /^\\w+:\\/\\/(?:www\\.)?(?:soundcloud\\.com\\/|snd\\.sc\\/)([\\w\\-\\/]+)/,\r\n style: 'border: 0; width: 500px; height: 400px;',\r\n el(a) {\r\n return $.el('iframe',\r\n {src: `https://w.soundcloud.com/player/?visual=true&show_comments=false&url=https%3A%2F%2Fsoundcloud.com%2F${encodeURIComponent(a.dataset.uid)}`});\r\n },\r\n title: {\r\n api(uid) { return `${location.protocol}//soundcloud.com/oembed?format=json&url=https%3A%2F%2Fsoundcloud.com%2F${encodeURIComponent(uid)}`; },\r\n text(_) { return _.title; }\r\n }\r\n }\r\n , {\r\n key: 'StrawPoll',\r\n regExp: /^\\w+:\\/\\/(?:www\\.)?strawpoll\\.me\\/(?:embed_\\d+\\/)?(\\d+(?:\\/r)?)/,\r\n style: 'border: 0; width: 600px; height: 406px;',\r\n el(a) {\r\n return $.el('iframe',\r\n {src: `https://www.strawpoll.me/embed_1/${a.dataset.uid}`});\r\n }\r\n }\r\n , {\r\n key: 'Streamable',\r\n regExp: /^\\w+:\\/\\/(?:www\\.)?streamable\\.com\\/(\\w+)/,\r\n el(a) {\r\n const el = $.el('iframe',\r\n {src: `https://streamable.com/o/${a.dataset.uid}`});\r\n el.setAttribute(\"allowfullscreen\", \"true\");\r\n return el;\r\n },\r\n title: {\r\n api(uid) { return `https://api.streamable.com/oembed?url=https://streamable.com/${uid}`; },\r\n text(_) { return _.title; }\r\n }\r\n }\r\n , {\r\n key: 'TwitchTV',\r\n regExp: /^\\w+:\\/\\/(?:www\\.|secure\\.|clips\\.|m\\.)?twitch\\.tv\\/(\\w[^#\\&\\?]*)/,\r\n el(a) {\r\n let url;\r\n let m = a.dataset.href.match(/^\\w+:\\/\\/(?:(clips\\.)|\\w+\\.)?twitch\\.tv\\/(?:\\w+\\/)?(clip\\/)?(\\w[^#\\&\\?]*)/);\r\n if (m[1] || m[2]) {\r\n url = `//clips.twitch.tv/embed?clip=${m[3]}&parent=${location.hostname}`;\r\n } else {\r\n let time;\r\n m = a.dataset.uid.match(/(\\w+)(?:\\/(?:v\\/)?(\\d+))?/);\r\n url = `//player.twitch.tv/?${m[2] ? `video=v${m[2]}` : `channel=${m[1]}`}&autoplay=false&parent=${location.hostname}`;\r\n if (time = a.dataset.href.match(/\\bt=(\\w+)/)) {\r\n url += `&time=${time[1]}`;\r\n }\r\n }\r\n const el = $.el('iframe',\r\n {src: url});\r\n el.setAttribute(\"allowfullscreen\", \"true\");\r\n return el;\r\n }\r\n }\r\n , {\r\n key: 'Twitter',\r\n regExp: /^\\w+:\\/\\/(?:www\\.|mobile\\.)?(?:twitter|x)\\.com\\/(\\w+\\/status\\/\\d+)/,\r\n style: 'border: none; width: 550px; height: 250px; overflow: hidden; resize: both;',\r\n el(a) {\r\n const el = $.el('iframe');\r\n $.on(el, 'load', function() {\r\n return this.contentWindow.postMessage({element: 't', query: 'height'}, 'https://twitframe.com');\r\n });\r\n var onMessage = function(e) {\r\n if ((e.source === el.contentWindow) && (e.origin === 'https://twitframe.com')) {\r\n $.off(window, 'message', onMessage);\r\n return (cont || el).style.height = `${+$.minmax(e.data.height, 250, 0.8 * doc.clientHeight)}px`;\r\n }\r\n };\r\n $.on(window, 'message', onMessage);\r\n el.src = `https://twitframe.com/show?url=https://twitter.com/${a.dataset.uid}`;\r\n if ($.engine === 'gecko') {\r\n // XXX https://bugzilla.mozilla.org/show_bug.cgi?id=680823\r\n el.style.cssText = 'border: none; width: 100%; height: 100%;';\r\n var cont = $.el('div');\r\n $.add(cont, el);\r\n return cont;\r\n } else {\r\n return el;\r\n }\r\n }\r\n }\r\n , {\r\n key: 'VidLii',\r\n regExp: /^\\w+:\\/\\/(?:www\\.)?vidlii\\.com\\/watch\\?v=(\\w{11})/,\r\n style: 'border: none; width: 640px; height: 392px;',\r\n el(a) {\r\n const el = $.el('iframe',\r\n {src: `https://www.vidlii.com/embed?v=${a.dataset.uid}&a=0`});\r\n el.setAttribute(\"allowfullscreen\", \"true\");\r\n return el;\r\n }\r\n }\r\n , {\r\n key: 'Vimeo',\r\n regExp: /^\\w+:\\/\\/(?:www\\.)?vimeo\\.com\\/(\\d+)/,\r\n el(a) {\r\n const el = $.el('iframe',\r\n {src: `//player.vimeo.com/video/${a.dataset.uid}?wmode=opaque`});\r\n el.setAttribute(\"allowfullscreen\", \"true\");\r\n return el;\r\n },\r\n title: {\r\n api(uid) { return `https://vimeo.com/api/oembed.json?url=https://vimeo.com/${uid}`; },\r\n text(_) { return _.title; }\r\n }\r\n }\r\n , {\r\n key: 'Vine',\r\n regExp: /^\\w+:\\/\\/(?:www\\.)?vine\\.co\\/v\\/(\\w+)/,\r\n style: 'border: none; width: 500px; height: 500px;',\r\n el(a) {\r\n return $.el('iframe',\r\n {src: `https://vine.co/v/${a.dataset.uid}/card`});\r\n }\r\n }\r\n , {\r\n key: 'Vocaroo',\r\n regExp: /^\\w+:\\/\\/(?:(?:www\\.|old\\.)?vocaroo\\.com|voca\\.ro)\\/((?:i\\/)?\\w+)/,\r\n style: '',\r\n el(a) {\r\n const el = $.el('iframe');\r\n el.width = 300;\r\n el.height = 60;\r\n el.setAttribute('frameborder', 0);\r\n el.src = `https://vocaroo.com/embed/${a.dataset.uid.replace(/^i\\//, '')}?autoplay=0`;\r\n return el;\r\n }\r\n }\r\n , {\r\n key: 'YouTube',\r\n regExp: /^\\w+:\\/\\/(?:youtu.be\\/|[\\w.]*youtube[\\w.]*\\/.*(?:v=|\\bembed\\/|\\bv\\/|live\\/))([\\w\\-]{11})(.*)/,\r\n el(a) {\r\n let start = a.dataset.options.match(/\\b(?:star)?t\\=(\\w+)/);\r\n if (start) { start = start[1]; }\r\n if (start && !/^\\d+$/.test(start)) {\r\n start += ' 0h0m0s';\r\n start = (3600 * start.match(/(\\d+)h/)[1]) + (60 * start.match(/(\\d+)m/)[1]) + (1 * start.match(/(\\d+)s/)[1]);\r\n }\r\n const el = $.el('iframe',\r\n {src: `//www.youtube.com/embed/${a.dataset.uid}?rel=0&wmode=opaque${start ? '&start=' + start : ''}`});\r\n el.setAttribute(\"allowfullscreen\", \"true\");\r\n return el;\r\n },\r\n title: {\r\n api(uid) { return `https://www.youtube.com/oembed?url=https%3A//www.youtube.com/watch%3Fv%3D${uid}&format=json`; },\r\n text(_) { return _.title; },\r\n status(_) {\r\n if (_.error) {\r\n const m = _.error.match(/^(\\d*)\\s*(.*)/);\r\n return [+m[1], m[2]];\r\n } else {\r\n return [200, 'OK'];\r\n }\r\n }\r\n },\r\n preview: {\r\n url(uid) { return `https://img.youtube.com/vi/${uid}/0.jpg`; },\r\n height: 360\r\n }\r\n }\r\n ]\r\n};\r\nexport default Embedding;\r\n","import Notice from \"../classes/Notice\";\r\nimport Config from \"../config/Config\";\r\nimport Filter from \"../Filtering/Filter\";\r\nimport ThreadHiding from \"../Filtering/ThreadHiding\";\r\nimport BoardConfig from \"../General/BoardConfig\";\r\nimport Get from \"../General/Get\";\r\nimport Header from \"../General/Header\";\r\nimport Index from \"../General/Index\";\r\nimport Settings from \"../General/Settings\";\r\nimport { Conf, d, g } from \"../globals/globals\";\r\nimport FappeTyme from \"../Images/FappeTyme\";\r\nimport Gallery from \"../Images/Gallery\";\r\nimport ImageExpand from \"../Images/ImageExpand\";\r\nimport Embedding from \"../Linkification/Embedding\";\r\nimport ThreadUpdater from \"../Monitoring/ThreadUpdater\";\r\nimport ThreadWatcher from \"../Monitoring/ThreadWatcher\";\r\nimport UnreadIndex from \"../Monitoring/UnreadIndex\";\r\nimport $ from \"../platform/$\";\r\nimport $$ from \"../platform/$$\";\r\nimport QR from \"../Posting/QR\";\r\nimport QuoteThreading from \"../Quotelinks/QuoteThreading\";\r\nimport QuoteYou from \"../Quotelinks/QuoteYou\";\r\nimport CatalogLinks from \"./CatalogLinks\";\r\nimport ExpandThread from \"./ExpandThread\";\r\nimport Nav from \"./Nav\";\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS205: Consider reworking code to avoid use of IIFEs\r\n * DS207: Consider shorter variations of null checks\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\nvar Keybinds = {\r\n init() {\r\n if (!Conf['Keybinds']) { return; }\r\n\r\n for (var hotkey in Config.hotkeys) {\r\n $.sync(hotkey, Keybinds.sync);\r\n }\r\n\r\n var init = function() {\r\n $.off(d, '4chanXInitFinished', init);\r\n $.on(d, 'keydown', Keybinds.keydown);\r\n for (var node of $$('[accesskey]')) {\r\n node.removeAttribute('accesskey');\r\n }\r\n };\r\n return $.on(d, '4chanXInitFinished', init);\r\n },\r\n\r\n sync(key, hotkey) {\r\n return Conf[hotkey] = key;\r\n },\r\n\r\n keydown(e) {\r\n let key, thread, threadRoot;\r\n let catalog, notifications;\r\n if (!(key = Keybinds.keyCode(e))) { return; }\r\n const {target} = e;\r\n if (['INPUT', 'TEXTAREA'].includes(target.nodeName)) {\r\n if (!/(Esc|Alt|Ctrl|Meta|Shift\\+\\w{2,})/.test(key) || !!/^Alt\\+(\\d|Up|Down|Left|Right)$/.test(key)) { return; }\r\n }\r\n if (['index', 'thread'].includes(g.VIEW)) {\r\n threadRoot = Nav.getThread();\r\n thread = Get.threadFromRoot(threadRoot);\r\n }\r\n switch (key) {\r\n // QR & Options\r\n case Conf['Toggle board list']:\r\n if (!Conf['Custom Board Navigation']) { return; }\r\n Header.toggleBoardList();\r\n break;\r\n case Conf['Toggle header']:\r\n Header.toggleBarVisibility();\r\n break;\r\n case Conf['Open empty QR']:\r\n if (!QR.postingIsEnabled) { return; }\r\n Keybinds.qr();\r\n break;\r\n case Conf['Open QR']:\r\n if (!QR.postingIsEnabled || !threadRoot) { return; }\r\n Keybinds.qr(threadRoot);\r\n break;\r\n case Conf['Open settings']:\r\n Settings.open();\r\n break;\r\n case Conf['Close']:\r\n if (Settings.dialog) {\r\n Settings.close();\r\n } else if ((notifications = $$('.notification')).length) {\r\n for (var notification of notifications) {\r\n $('.close', notification).click();\r\n }\r\n } else if (QR.nodes && !(QR.nodes.el.hidden || (window.getComputedStyle(QR.nodes.form).display === 'none'))) {\r\n if (Conf['Persistent QR']) {\r\n QR.hide();\r\n } else {\r\n QR.close();\r\n }\r\n } else if (Embedding.lastEmbed) {\r\n Embedding.closeFloat();\r\n } else {\r\n return;\r\n }\r\n break;\r\n case Conf['Spoiler tags']:\r\n if (target.nodeName !== 'TEXTAREA') { return; }\r\n Keybinds.tags('spoiler', target);\r\n break;\r\n case Conf['Code tags']:\r\n if (target.nodeName !== 'TEXTAREA') { return; }\r\n Keybinds.tags('code', target);\r\n break;\r\n case Conf['Eqn tags']:\r\n if (target.nodeName !== 'TEXTAREA') { return; }\r\n Keybinds.tags('eqn', target);\r\n break;\r\n case Conf['Math tags']:\r\n if (target.nodeName !== 'TEXTAREA') { return; }\r\n Keybinds.tags('math', target);\r\n break;\r\n case Conf['SJIS tags']:\r\n if (target.nodeName !== 'TEXTAREA') { return; }\r\n Keybinds.tags('sjis', target);\r\n break;\r\n case Conf['Toggle sage']:\r\n if (!QR.nodes || !!QR.nodes.el.hidden) { return; }\r\n Keybinds.sage();\r\n break;\r\n case Conf['Toggle Cooldown']:\r\n if (!QR.nodes || !!QR.nodes.el.hidden || !$.hasClass(QR.nodes.fileSubmit, 'custom-cooldown')) { return; }\r\n QR.toggleCustomCooldown();\r\n break;\r\n case Conf['Post from URL']:\r\n if (!QR.postingIsEnabled) { return; }\r\n QR.handleUrl('');\r\n break;\r\n case Conf['Add new post']:\r\n if (!QR.postingIsEnabled) { return; }\r\n QR.addPost();\r\n break;\r\n case Conf['Submit QR']:\r\n if (!QR.nodes || !!QR.nodes.el.hidden) { return; }\r\n if (!QR.status()) { QR.submit(); }\r\n break;\r\n // Index/Thread related\r\n case Conf['Update']:\r\n switch (g.VIEW) {\r\n case 'thread':\r\n if (!ThreadUpdater.enabled) { return; }\r\n ThreadUpdater.update();\r\n break;\r\n case 'index':\r\n if (!Index.enabled) { return; }\r\n Index.update();\r\n break;\r\n default:\r\n return;\r\n }\r\n break;\r\n case Conf['Watch']:\r\n if (!ThreadWatcher.enabled || !thread) { return; }\r\n ThreadWatcher.toggle(thread);\r\n break;\r\n case Conf['Update thread watcher']:\r\n if (!ThreadWatcher.enabled) { return; }\r\n ThreadWatcher.buttonFetchAll();\r\n break;\r\n case Conf['Toggle thread watcher']:\r\n if (!ThreadWatcher.enabled) { return; }\r\n ThreadWatcher.toggleWatcher();\r\n break;\r\n case Conf['Toggle threading']:\r\n if (!QuoteThreading.ready) { return; }\r\n QuoteThreading.toggleThreading();\r\n break;\r\n case Conf['Mark thread read']:\r\n if ((g.VIEW !== 'index') || !thread || !UnreadIndex.enabled) { return; }\r\n UnreadIndex.markRead.call(threadRoot);\r\n break;\r\n // Images\r\n case Conf['Expand image']:\r\n if (!ImageExpand.enabled || !threadRoot) { return; }\r\n var post = Get.postFromNode(Keybinds.post(threadRoot));\r\n if (post.file) { ImageExpand.toggle(post); }\r\n break;\r\n case Conf['Expand images']:\r\n if (!ImageExpand.enabled) { return; }\r\n ImageExpand.cb.toggleAll();\r\n break;\r\n case Conf['Open Gallery']:\r\n if (!Gallery.enabled) { return; }\r\n Gallery.cb.toggle();\r\n break;\r\n case Conf['fappeTyme']:\r\n if (!FappeTyme.nodes?.fappe) { return; }\r\n FappeTyme.toggle('fappe');\r\n break;\r\n case Conf['werkTyme']:\r\n if (!FappeTyme.nodes?.werk) { return; }\r\n FappeTyme.toggle('werk');\r\n break;\r\n // Board Navigation\r\n case Conf['Front page']:\r\n if (Index.enabled) {\r\n Index.userPageNav(1);\r\n } else {\r\n location.href = `/${g.BOARD}/`;\r\n }\r\n break;\r\n case Conf['Open front page']:\r\n $.open(`${location.origin}/${g.BOARD}/`);\r\n break;\r\n case Conf['Next page']:\r\n if ((g.VIEW !== 'index') || !!g.SITE.isOnePage?.(g.BOARD)) { return; }\r\n if (Index.enabled) {\r\n if (!['paged', 'infinite'].includes(Conf['Index Mode'])) { return; }\r\n $('.next button', Index.pagelist).click();\r\n } else {\r\n $(g.SITE.selectors.nav.next)?.click();\r\n }\r\n break;\r\n case Conf['Previous page']:\r\n if ((g.VIEW !== 'index') || !!g.SITE.isOnePage?.(g.BOARD)) { return; }\r\n if (Index.enabled) {\r\n if (!['paged', 'infinite'].includes(Conf['Index Mode'])) { return; }\r\n $('.prev button', Index.pagelist).click();\r\n } else {\r\n $(g.SITE.selectors.nav.prev)?.click();\r\n }\r\n break;\r\n case Conf['Search form']:\r\n if (g.VIEW !== 'index') { return; }\r\n var searchInput = Index.enabled ?\r\n Index.searchInput\r\n : g.SITE.selectors.searchBox ?\r\n $(g.SITE.selectors.searchBox)\r\n :\r\n undefined;\r\n if (!searchInput) { return; }\r\n Header.scrollToIfNeeded(searchInput);\r\n searchInput.focus();\r\n break;\r\n case Conf['Paged mode']:\r\n if (!Index.enabledOn(g.BOARD)) { return; }\r\n location.href = g.VIEW === 'index' ? '#paged' : `/${g.BOARD}/#paged`;\r\n break;\r\n case Conf['Infinite scrolling mode']:\r\n if (!Index.enabledOn(g.BOARD)) { return; }\r\n location.href = g.VIEW === 'index' ? '#infinite' : `/${g.BOARD}/#infinite`;\r\n break;\r\n case Conf['All pages mode']:\r\n if (!Index.enabledOn(g.BOARD)) { return; }\r\n location.href = g.VIEW === 'index' ? '#all-pages' : `/${g.BOARD}/#all-pages`;\r\n break;\r\n case Conf['Open catalog']:\r\n if (!(catalog = CatalogLinks.catalog())) { return; }\r\n location.href = catalog;\r\n break;\r\n case Conf['Cycle sort type']:\r\n if (!Index.enabled) { return; }\r\n Index.cycleSortType();\r\n break;\r\n // Thread Navigation\r\n case Conf['Next thread']:\r\n if ((g.VIEW !== 'index') || !threadRoot) { return; }\r\n Nav.scroll(+1);\r\n break;\r\n case Conf['Previous thread']:\r\n if ((g.VIEW !== 'index') || !threadRoot) { return; }\r\n Nav.scroll(-1);\r\n break;\r\n case Conf['Expand thread']:\r\n if ((g.VIEW !== 'index') || !threadRoot) { return; }\r\n ExpandThread.toggle(thread);\r\n // Keep thread from moving off screen when contracted.\r\n Header.scrollTo(threadRoot);\r\n break;\r\n case Conf['Open thread']:\r\n if ((g.VIEW !== 'index') || !threadRoot) { return; }\r\n Keybinds.open(thread);\r\n break;\r\n case Conf['Open thread tab']:\r\n if ((g.VIEW !== 'index') || !threadRoot) { return; }\r\n Keybinds.open(thread, true);\r\n break;\r\n // Reply Navigation\r\n case Conf['Next reply']:\r\n if (!threadRoot) { return; }\r\n Keybinds.hl(+1, threadRoot);\r\n break;\r\n case Conf['Previous reply']:\r\n if (!threadRoot) { return; }\r\n Keybinds.hl(-1, threadRoot);\r\n break;\r\n case Conf['Deselect reply']:\r\n if (!threadRoot) { return; }\r\n Keybinds.hl(0, threadRoot);\r\n break;\r\n case Conf['Hide']:\r\n if (!thread || !ThreadHiding.db) { return; }\r\n Header.scrollTo(threadRoot);\r\n ThreadHiding.toggle(thread);\r\n break;\r\n case Conf['Quick Filter MD5']:\r\n if (!threadRoot) { return; }\r\n post = Keybinds.post(threadRoot);\r\n Keybinds.hl(+1, threadRoot);\r\n Filter.quickFilterMD5.call(post, e);\r\n break;\r\n case Conf['Previous Post Quoting You']:\r\n if (!threadRoot || !QuoteYou.db) { return; }\r\n QuoteYou.cb.seek('preceding');\r\n break;\r\n case Conf['Next Post Quoting You']:\r\n if (!threadRoot || !QuoteYou.db) { return; }\r\n QuoteYou.cb.seek('following');\r\n break;\r\n default:\r\n return;\r\n }\r\n e.preventDefault();\r\n return e.stopPropagation();\r\n },\r\n\r\n keyCode(e) {\r\n let key = (() => { let kc;\r\n switch ((kc = e.keyCode)) {\r\n case 8: // return\r\n return '';\r\n case 13:\r\n return 'Enter';\r\n case 27:\r\n return 'Esc';\r\n case 32:\r\n return 'Space';\r\n case 37:\r\n return 'Left';\r\n case 38:\r\n return 'Up';\r\n case 39:\r\n return 'Right';\r\n case 40:\r\n return 'Down';\r\n case 188:\r\n return 'Comma';\r\n case 190:\r\n return 'Period';\r\n case 191:\r\n return 'Slash';\r\n case 59: case 186:\r\n return 'Semicolon';\r\n default:\r\n if ((48 <= kc && kc <= 57) || (65 <= kc && kc <= 90)) { // 0-9, A-Z\r\n return String.fromCharCode(kc).toLowerCase();\r\n } else if (96 <= kc && kc <= 105) { // numpad 0-9\r\n return String.fromCharCode(kc - 48).toLowerCase();\r\n } else {\r\n return null;\r\n }\r\n } })();\r\n if (key) {\r\n if (e.altKey) { key = 'Alt+' + key; }\r\n if (e.ctrlKey) { key = 'Ctrl+' + key; }\r\n if (e.metaKey) { key = 'Meta+' + key; }\r\n if (e.shiftKey) { key = 'Shift+' + key; }\r\n }\r\n return key;\r\n },\r\n\r\n post(thread) {\r\n const s = g.SITE.selectors;\r\n return (\r\n $(`${s.postContainer}${s.highlightable.reply}.${g.SITE.classes.highlight}`, thread) ||\r\n $(`${g.SITE.isOPContainerThread ? s.thread : s.postContainer}${s.highlightable.op}`, thread)\r\n );\r\n },\r\n\r\n qr(thread) {\r\n QR.open();\r\n if (thread != null) {\r\n QR.quote.call(Keybinds.post(thread));\r\n }\r\n return QR.nodes.com.focus();\r\n },\r\n\r\n tags(tag, ta) {\r\n BoardConfig.ready(function() {\r\n const {config} = g.BOARD;\r\n const supported = (() => { switch (tag) {\r\n case 'spoiler': return !!config.spoilers;\r\n case 'code': return !!config.code_tags;\r\n case 'math': case 'eqn': return !!config.math_tags;\r\n case 'sjis': return !!config.sjis_tags;\r\n } })();\r\n if (!supported) { return new Notice('warning', `[${tag}] tags are not supported on /${g.BOARD}/.`, 20); }\r\n });\r\n\r\n const {\r\n value\r\n } = ta;\r\n const selStart = ta.selectionStart;\r\n const selEnd = ta.selectionEnd;\r\n\r\n ta.value =\r\n value.slice(0, selStart) +\r\n `[${tag}]` + value.slice(selStart, selEnd) + `[/${tag}]` +\r\n value.slice(selEnd);\r\n\r\n // Move the caret to the end of the selection.\r\n const range = (`[${tag}]`).length + selEnd;\r\n ta.setSelectionRange(range, range);\r\n\r\n // Fire the 'input' event\r\n return $.event('input', null, ta);\r\n },\r\n\r\n sage() {\r\n const isSage = /sage/i.test(QR.nodes.email.value);\r\n return QR.nodes.email.value = isSage ?\r\n \"\"\r\n : \"sage\";\r\n },\r\n\r\n open(thread, tab) {\r\n if (g.VIEW !== 'index') { return; }\r\n const url = Get.url('thread', thread);\r\n if (tab) {\r\n return $.open(url);\r\n } else {\r\n return location.href = url;\r\n }\r\n },\r\n\r\n hl(delta, thread) {\r\n const replySelector = `${g.SITE.selectors.postContainer}${g.SITE.selectors.highlightable.reply}`;\r\n const {highlight} = g.SITE.classes;\r\n\r\n const postEl = $(`${replySelector}.${highlight}`, thread);\r\n\r\n if (!delta) {\r\n if (postEl) { $.rmClass(postEl, highlight); }\r\n return;\r\n }\r\n\r\n if (postEl) {\r\n const {height} = postEl.getBoundingClientRect();\r\n if ((Header.getTopOf(postEl) >= -height) && (Header.getBottomOf(postEl) >= -height)) { // We're at least partially visible\r\n let next;\r\n const {root} = Get.postFromNode(postEl).nodes;\r\n const axis = delta === +1 ?\r\n 'following'\r\n :\r\n 'preceding';\r\n if (!(next = $.x(`${axis}-sibling::${g.SITE.xpath.replyContainer}[not(@hidden) and not(child::div[@class='stub'])][1]`, root))) { return; }\r\n if (!next.matches(replySelector)) { next = $(replySelector, next); }\r\n Header.scrollToIfNeeded(next, delta === +1);\r\n $.addClass(next, highlight);\r\n $.rmClass(postEl, highlight);\r\n return;\r\n }\r\n $.rmClass(postEl, highlight);\r\n }\r\n\r\n const replies = $$(replySelector, thread);\r\n if (delta === -1) { replies.reverse(); }\r\n for (var reply of replies) {\r\n if (((delta === +1) && (Header.getTopOf(reply) > 0)) || ((delta === -1) && (Header.getBottomOf(reply) > 0))) {\r\n $.addClass(reply, highlight);\r\n return;\r\n }\r\n }\r\n }\r\n};\r\nexport default Keybinds;\r\n","import $ from \"../platform/$\";\r\nimport CaptchaReplace from \"./Captcha.replace\";\r\nimport CaptchaT from \"./Captcha.t\";\r\nimport meta from '../../package.json';\r\nimport Main from \"../main/Main\";\r\nimport Keybinds from \"../Miscellaneous/Keybinds\";\r\nimport $$ from \"../platform/$$\";\r\nimport QR from \"./QR\";\r\nimport { Conf, d } from \"../globals/globals\";\r\nimport { MINUTE, SECOND } from \"../platform/helpers\";\r\n\r\nconst Captcha = {\r\n Cache: {\r\n init() {\r\n $.on(d, 'SaveCaptcha', e => {\r\n return this.saveAPI(e.detail);\r\n });\r\n return $.on(d, 'NoCaptcha', e => {\r\n return this.noCaptcha(e.detail);\r\n });\r\n },\r\n\r\n captchas: [],\r\n\r\n getCount() {\r\n return this.captchas.length;\r\n },\r\n\r\n neededRaw() {\r\n return !(\r\n this.haveCookie() || this.captchas.length || QR.req || this.submitCB\r\n ) && (\r\n (QR.posts.length > 1) || Conf['Auto-load captcha'] || !QR.posts[0].isOnlyQuotes() || QR.posts[0].file\r\n );\r\n },\r\n\r\n needed() {\r\n return this.neededRaw() && $.event('LoadCaptcha');\r\n },\r\n\r\n prerequest() {\r\n if (!Conf['Prerequest Captcha']) { return; }\r\n // Post count temporarily off by 1 when called from QR.post.rm, QR.close, or QR.submit\r\n return $.queueTask(() => {\r\n if (\r\n !this.prerequested &&\r\n this.neededRaw() &&\r\n !$.event('LoadCaptcha') &&\r\n !QR.captcha.occupied() &&\r\n (QR.cooldown.seconds <= 60) &&\r\n (QR.selected === QR.posts[QR.posts.length - 1]) &&\r\n !QR.selected.isOnlyQuotes()\r\n ) {\r\n const isReply = (QR.selected.thread !== 'new');\r\n if (!$.event('RequestCaptcha', { isReply })) {\r\n this.prerequested = true;\r\n this.submitCB = captcha => {\r\n if (captcha) { return this.save(captcha); }\r\n };\r\n return this.updateCount();\r\n }\r\n }\r\n });\r\n },\r\n\r\n haveCookie() {\r\n return /\\b_ct=/.test(d.cookie) && (QR.posts[0].thread !== 'new');\r\n },\r\n\r\n getOne() {\r\n let captcha;\r\n delete this.prerequested;\r\n this.clear();\r\n if (captcha = this.captchas.shift()) {\r\n this.count();\r\n return captcha;\r\n } else {\r\n return null;\r\n }\r\n },\r\n\r\n request(isReply) {\r\n if (!this.submitCB) {\r\n if ($.event('RequestCaptcha', { isReply })) { return; }\r\n }\r\n return cb => {\r\n this.submitCB = cb;\r\n return this.updateCount();\r\n };\r\n },\r\n\r\n abort() {\r\n if (this.submitCB) {\r\n delete this.submitCB;\r\n $.event('AbortCaptcha');\r\n return this.updateCount();\r\n }\r\n },\r\n\r\n saveAPI(captcha) {\r\n let cb;\r\n if (cb = this.submitCB) {\r\n delete this.submitCB;\r\n cb(captcha);\r\n return this.updateCount();\r\n } else {\r\n return this.save(captcha);\r\n }\r\n },\r\n\r\n noCaptcha(detail) {\r\n let cb;\r\n if (cb = this.submitCB) {\r\n if (!this.haveCookie() || detail?.error) {\r\n QR.error(detail?.error || 'Failed to retrieve captcha.');\r\n QR.captcha.setup(d.activeElement === QR.nodes.status);\r\n }\r\n delete this.submitCB;\r\n cb();\r\n return this.updateCount();\r\n }\r\n },\r\n\r\n save(captcha) {\r\n let cb;\r\n if (cb = this.submitCB) {\r\n this.abort();\r\n cb(captcha);\r\n return;\r\n }\r\n this.captchas.push(captcha);\r\n this.captchas.sort((a, b) => a.timeout - b.timeout);\r\n return this.count();\r\n },\r\n\r\n clear() {\r\n if (this.captchas.length) {\r\n let i;\r\n const now = Date.now();\r\n for (i = 0; i < this.captchas.length; i++) {\r\n var captcha = this.captchas[i];\r\n if (captcha.timeout > now) { break; }\r\n }\r\n if (i) {\r\n this.captchas = this.captchas.slice(i);\r\n return this.count();\r\n }\r\n }\r\n },\r\n\r\n count() {\r\n clearTimeout(this.timer);\r\n if (this.captchas.length) {\r\n this.timer = setTimeout(this.clear.bind(this), this.captchas[0].timeout - Date.now());\r\n }\r\n return this.updateCount();\r\n },\r\n\r\n updateCount() {\r\n return $.event('CaptchaCount', this.captchas.length);\r\n }\r\n }, Replace: CaptchaReplace, t: CaptchaT, v2: {\r\n lifetime: 2 * MINUTE,\r\n\r\n init() {\r\n if (d.cookie.indexOf('pass_enabled=1') >= 0) { return; }\r\n if (!(this.isEnabled = !!$('#g-recaptcha, #captcha-forced-noscript') || !$.id('postForm'))) { return; }\r\n\r\n if (this.noscript = Conf['Force Noscript Captcha'] || !Main.jsEnabled) {\r\n $.addClass(QR.nodes.el, 'noscript-captcha');\r\n }\r\n\r\n Captcha.cache.init();\r\n $.on(d, 'CaptchaCount', this.count.bind(this));\r\n\r\n const root = $.el('div', { className: 'captcha-root' });\r\n $.extend(root, {\r\n innerHTML:\r\n '
'\r\n }\r\n );\r\n const counter = $('.captcha-counter > a', root);\r\n this.nodes = { root, counter };\r\n this.count();\r\n $.addClass(QR.nodes.el, 'has-captcha', 'captcha-v2');\r\n $.after(QR.nodes.com.parentNode, root);\r\n\r\n $.on(counter, 'click', this.toggle.bind(this));\r\n $.on(counter, 'keydown', e => {\r\n if (Keybinds.keyCode(e) !== 'Space') { return; }\r\n this.toggle();\r\n e.preventDefault();\r\n return e.stopPropagation();\r\n });\r\n return $.on(window, 'captcha:success', () => {\r\n // XXX Greasemonkey 1.x workaround to gain access to GM_* functions.\r\n return $.queueTask(() => this.save(false));\r\n });\r\n },\r\n\r\n timeouts: {},\r\n prevNeeded: 0,\r\n\r\n noscriptURL() {\r\n let lang;\r\n let url = `https://www.google.com/recaptcha/api/fallback?k=${meta.recaptchaKey}`;\r\n if (lang = Conf['captchaLanguage'].trim()) {\r\n url += `&hl=${encodeURIComponent(lang)}`;\r\n }\r\n return url;\r\n },\r\n\r\n moreNeeded() {\r\n // Post count temporarily off by 1 when called from QR.post.rm, QR.close, or QR.submit\r\n return $.queueTask(() => {\r\n const needed = Captcha.cache.needed();\r\n if (needed && !this.prevNeeded) {\r\n this.setup(QR.cooldown.auto && (d.activeElement === QR.nodes.status));\r\n }\r\n return this.prevNeeded = needed;\r\n });\r\n },\r\n\r\n toggle() {\r\n if (this.nodes.container && !this.timeouts.destroy) {\r\n return this.destroy();\r\n } else {\r\n return this.setup(true, true);\r\n }\r\n },\r\n\r\n setup(focus, force) {\r\n if (!this.isEnabled || (!Captcha.cache.needed() && !force)) { return; }\r\n\r\n if (focus) {\r\n $.addClass(QR.nodes.el, 'focus');\r\n this.nodes.counter.focus();\r\n }\r\n\r\n if (this.timeouts.destroy) {\r\n clearTimeout(this.timeouts.destroy);\r\n delete this.timeouts.destroy;\r\n return this.reload();\r\n }\r\n\r\n if (this.nodes.container) {\r\n // XXX https://bugzilla.mozilla.org/show_bug.cgi?id=1226835\r\n $.queueTask(() => {\r\n let iframe;\r\n if (this.nodes.container && (d.activeElement === this.nodes.counter) && (iframe = $('iframe[src^=\"https://www.google.com/recaptcha/\"]', this.nodes.container))) {\r\n iframe.focus();\r\n return QR.focus();\r\n }\r\n }); // Event handler not fired in Firefox\r\n return;\r\n }\r\n\r\n this.nodes.container = $.el('div', { className: 'captcha-container' });\r\n $.prepend(this.nodes.root, this.nodes.container);\r\n new MutationObserver(this.afterSetup.bind(this)).observe(this.nodes.container, {\r\n childList: true,\r\n subtree: true\r\n }\r\n );\r\n\r\n if (this.noscript) {\r\n return this.setupNoscript();\r\n } else {\r\n return this.setupJS();\r\n }\r\n },\r\n\r\n setupNoscript() {\r\n const iframe = $.el('iframe', {\r\n id: 'qr-captcha-iframe',\r\n scrolling: 'no',\r\n src: this.noscriptURL()\r\n }\r\n );\r\n const div = $.el('div');\r\n const textarea = $.el('textarea');\r\n $.add(div, textarea);\r\n return $.add(this.nodes.container, [iframe, div]);\r\n },\r\n\r\n setupJS() {\r\n return $.global(function () {\r\n const render = function () {\r\n const { classList } = document.documentElement;\r\n const container = document.querySelector('#qr .captcha-container');\r\n return container.dataset.widgetID = window.grecaptcha.render(container, {\r\n sitekey: meta.recaptchaKey,\r\n theme: classList.contains('tomorrow') || classList.contains('spooky') || classList.contains('dark-captcha') ? 'dark' : 'light',\r\n callback(response) {\r\n return window.dispatchEvent(new CustomEvent('captcha:success', { detail: response }));\r\n }\r\n }\r\n );\r\n };\r\n if (window.grecaptcha) {\r\n return render();\r\n } else {\r\n const cbNative = window.onRecaptchaLoaded;\r\n window.onRecaptchaLoaded = function () {\r\n render();\r\n return cbNative();\r\n };\r\n if (!document.head.querySelector('script[src^=\"https://www.google.com/recaptcha/api.js\"]')) {\r\n const script = document.createElement('script');\r\n script.src = 'https://www.google.com/recaptcha/api.js?onload=onRecaptchaLoaded&render=explicit';\r\n return document.head.appendChild(script);\r\n }\r\n }\r\n });\r\n },\r\n\r\n afterSetup(mutations) {\r\n for (var mutation of mutations) {\r\n for (var node of mutation.addedNodes) {\r\n var iframe, textarea;\r\n if (iframe = $.x('./descendant-or-self::iframe[starts-with(@src, \"https://www.google.com/recaptcha/\")]', node)) { this.setupIFrame(iframe); }\r\n if (textarea = $.x('./descendant-or-self::textarea', node)) { this.setupTextArea(textarea); }\r\n }\r\n }\r\n },\r\n\r\n setupIFrame(iframe) {\r\n let needle;\r\n if (!doc.contains(iframe)) { return; }\r\n Captcha.replace.iframe(iframe);\r\n $.addClass(QR.nodes.el, 'captcha-open');\r\n this.fixQRPosition();\r\n $.on(iframe, 'load', this.fixQRPosition);\r\n if (d.activeElement === this.nodes.counter) { iframe.focus(); }\r\n // XXX Make sure scroll on space prevention (see src/css/style.css) doesn't cause scrolling of div\r\n if (['blink', 'edge'].includes($.engine) && (needle = iframe.parentNode, $$('#qr .captcha-container > div > div:first-of-type').includes(needle))) {\r\n return $.on(iframe.parentNode, 'scroll', function () { return this.scrollTop = 0; });\r\n }\r\n },\r\n\r\n fixQRPosition() {\r\n if (QR.nodes.el.getBoundingClientRect().bottom > doc.clientHeight) {\r\n QR.nodes.el.style.top = '';\r\n return QR.nodes.el.style.bottom = '0px';\r\n }\r\n },\r\n\r\n setupTextArea(textarea) {\r\n return $.one(textarea, 'input', () => this.save(true));\r\n },\r\n\r\n destroy() {\r\n if (!this.isEnabled) { return; }\r\n delete this.timeouts.destroy;\r\n $.rmClass(QR.nodes.el, 'captcha-open');\r\n if (this.nodes.container) {\r\n $.global(function () {\r\n const container = document.querySelector('#qr .captcha-container');\r\n return window.grecaptcha.reset(container.dataset.widgetID);\r\n });\r\n $.rm(this.nodes.container);\r\n return delete this.nodes.container;\r\n }\r\n },\r\n\r\n getOne(isReply) {\r\n return Captcha.cache.getOne(isReply);\r\n },\r\n\r\n save(pasted, token) {\r\n Captcha.cache.save({\r\n response: token || $('textarea', this.nodes.container).value,\r\n timeout: Date.now() + this.lifetime\r\n });\r\n\r\n const focus = (d.activeElement?.nodeName === 'IFRAME') && /https?:\\/\\/www\\.google\\.com\\/recaptcha\\//.test(d.activeElement.src);\r\n if (Captcha.cache.needed()) {\r\n if (focus) {\r\n if (QR.cooldown.auto || Conf['Post on Captcha Completion']) {\r\n this.nodes.counter.focus();\r\n } else {\r\n QR.nodes.status.focus();\r\n }\r\n }\r\n this.reload();\r\n } else {\r\n if (pasted) {\r\n this.destroy();\r\n } else {\r\n if (this.timeouts.destroy == null) { this.timeouts.destroy = setTimeout(this.destroy.bind(this), 3 * SECOND); }\r\n }\r\n if (focus) { QR.nodes.status.focus(); }\r\n }\r\n\r\n if (Conf['Post on Captcha Completion'] && !QR.cooldown.auto) { return QR.submit(); }\r\n },\r\n\r\n count() {\r\n const count = Captcha.cache.getCount();\r\n const loading = Captcha.cache.submitCB ? '...' : '';\r\n this.nodes.counter.textContent = `Captchas: ${count}${loading}`;\r\n return this.moreNeeded();\r\n },\r\n\r\n reload() {\r\n if ($('iframe[src^=\"https://www.google.com/recaptcha/api/fallback?\"]', this.nodes.container)) {\r\n this.destroy();\r\n return this.setup(false, true);\r\n } else {\r\n return $.global(function () {\r\n const container = document.querySelector('#qr .captcha-container');\r\n return window.grecaptcha.reset(container.dataset.widgetID);\r\n });\r\n }\r\n },\r\n\r\n occupied() {\r\n return !!this.nodes.container && !this.timeouts.destroy;\r\n }\r\n }\r\n};\r\nexport default Captcha;\r\n","import QuickReplyPage from './QR/QuickReply.html';\r\nimport $ from '../platform/$';\r\nimport Callbacks from '../classes/Callbacks';\r\nimport Notice from '../classes/Notice';\r\nimport Main from '../main/Main';\r\nimport Favicon from '../Monitoring/Favicon';\r\nimport $$ from '../platform/$$';\r\nimport CrossOrigin from '../platform/CrossOrigin';\r\nimport Captcha from './Captcha';\r\nimport meta from '../../package.json';\r\nimport Header from '../General/Header';\r\nimport { Conf, E, d, doc, g } from '../globals/globals';\r\nimport Menu from '../Menu/Menu';\r\nimport UI from '../General/UI';\r\nimport BoardConfig from '../General/BoardConfig';\r\nimport Get from '../General/Get';\r\nimport { DAY, dict, SECOND } from '../platform/helpers';\r\n\r\n/*\r\n * decaffeinate suggestions:\r\n * DS102: Remove unnecessary code created because of implicit returns\r\n * DS202: Simplify dynamic range loops\r\n * DS207: Consider shorter variations of null checks\r\n * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md\r\n */\r\n\r\nvar QR = {\r\n mimeTypes: ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/vnd.adobe.flash.movie', 'application/x-shockwave-flash', 'video/webm'],\r\n\r\n validExtension: /\\.(jpe?g|png|gif|pdf|swf|webm)$/i,\r\n\r\n typeFromExtension: {\r\n 'jpg': 'image/jpeg',\r\n 'jpeg': 'image/jpeg',\r\n 'png': 'image/png',\r\n 'gif': 'image/gif',\r\n 'pdf': 'application/pdf',\r\n 'swf': 'application/vnd.adobe.flash.movie',\r\n 'webm': 'video/webm'\r\n },\r\n\r\n extensionFromType: {\r\n 'image/jpeg': 'jpg',\r\n 'image/png': 'png',\r\n 'image/gif': 'gif',\r\n 'application/pdf': 'pdf',\r\n 'application/vnd.adobe.flash.movie': 'swf',\r\n 'application/x-shockwave-flash': 'swf',\r\n 'video/webm': 'webm'\r\n },\r\n\r\n init() {\r\n let sc;\r\n if (!Conf['Quick Reply']) { return; }\r\n\r\n this.posts = [];\r\n\r\n $.on(d, '4chanXInitFinished', () => BoardConfig.ready(QR.initReady));\r\n\r\n Callbacks.Post.push({\r\n name: 'Quick Reply',\r\n cb: this.node\r\n });\r\n\r\n this.shortcut = (sc = $.el('a', {\r\n className: 'disabled',\r\n textContent: '↩',\r\n title: 'Quick Reply',\r\n href: 'javascript:;'\r\n }\r\n ));\r\n $.on(sc, 'click', function() {\r\n if (!QR.postingIsEnabled) { return; }\r\n if (Conf['Persistent QR'] || !QR.nodes || QR.nodes.el.hidden) {\r\n QR.open();\r\n return QR.nodes.com.focus();\r\n } else {\r\n return QR.close();\r\n }\r\n });\r\n\r\n return Header.addShortcut('qr', sc, 540);\r\n },\r\n\r\n initReady() {\r\n let origToggle;\r\n const captchaVersion = $('#g-recaptcha, #captcha-forced-noscript') ? 'v2' : 't';\r\n QR.captcha = Captcha[captchaVersion];\r\n QR.postingIsEnabled = true;\r\n\r\n const {config} = g.BOARD;\r\n const prop = (key, def) => +(config[key] ?? def);\r\n\r\n QR.min_width = prop('min_image_width', 1);\r\n QR.min_height = prop('min_image_height', 1);\r\n QR.max_width = (QR.max_height = 10000);\r\n\r\n QR.max_size = prop('max_filesize', 4194304);\r\n QR.max_size_video = prop('max_webm_filesize', QR.max_size);\r\n QR.max_comment = prop('max_comment_chars', 2000);\r\n\r\n QR.max_width_video = (QR.max_height_video = 2048);\r\n QR.max_duration_video = prop('max_webm_duration', 120);\r\n\r\n QR.forcedAnon = !!config.forced_anon;\r\n QR.spoiler = !!config.spoilers;\r\n\r\n if (origToggle = $.id('togglePostFormLink')) {\r\n const link = $.el('h1',\r\n {className: \"qr-link-container\"});\r\n $.extend(link, {\r\n innerHTML:\r\n `${g.VIEW === \"thread\" ? \"Reply to Thread\" : \"Start a Thread\"}`\r\n });\r\n\r\n QR.link = link.firstElementChild;\r\n $.on(link.firstChild, 'click', function() {\r\n QR.open();\r\n return QR.nodes.com.focus();\r\n });\r\n\r\n $.before(origToggle, link);\r\n origToggle.firstElementChild.textContent = 'Original Form';\r\n }\r\n\r\n if (g.VIEW === 'thread') {\r\n let navLinksBot;\r\n const linkBot = $.el('div',\r\n {className: \"brackets-wrap qr-link-container-bottom\"});\r\n $.extend(linkBot, {innerHTML: 'Reply to Thread'});\r\n\r\n $.on(linkBot.firstElementChild, 'click', function() {\r\n QR.open();\r\n return QR.nodes.com.focus();\r\n });\r\n\r\n if (navLinksBot = $('.navLinksBot')) { $.prepend(navLinksBot, linkBot); }\r\n }\r\n\r\n $.on(d, 'QRGetFile', QR.getFile);\r\n $.on(d, 'QRDrawFile', QR.drawFile);\r\n $.on(d, 'QRSetFile', QR.setFile);\r\n\r\n $.on(d, 'paste', QR.paste);\r\n $.on(d, 'dragover', QR.dragOver);\r\n $.on(d, 'drop', QR.dropFile);\r\n $.on(d, 'dragstart dragend', QR.drag);\r\n\r\n $.on(d, 'IndexRefreshInternal', QR.generatePostableThreadsList);\r\n $.on(d, 'ThreadUpdate', QR.statusCheck);\r\n\r\n if (!Conf['Persistent QR']) { return; }\r\n QR.open();\r\n if (Conf['Auto Hide QR']) { return QR.hide(); }\r\n },\r\n\r\n statusCheck() {\r\n if (!QR.nodes) { return; }\r\n const {thread} = QR.posts[0];\r\n if ((thread !== 'new') && g.threads.get(`${g.BOARD}.${thread}`).isDead) {\r\n return QR.abort();\r\n } else {\r\n return QR.status();\r\n }\r\n },\r\n\r\n node() {\r\n $.on(this.nodes.quote, 'click', QR.quote);\r\n if (this.isFetchedQuote) { return QR.generatePostableThreadsList(); }\r\n },\r\n\r\n open() {\r\n if (QR.nodes) {\r\n if (QR.nodes.el.hidden) { QR.captcha.setup(); }\r\n QR.nodes.el.hidden = false;\r\n QR.unhide();\r\n } else {\r\n try {\r\n QR.dialog();\r\n } catch (err) {\r\n delete QR.nodes;\r\n Main.handleErrors({\r\n message: 'Quick Reply dialog creation crashed.',\r\n error: err\r\n });\r\n return;\r\n }\r\n }\r\n return $.rmClass(QR.shortcut, 'disabled');\r\n },\r\n\r\n close() {\r\n if (QR.req) {\r\n QR.abort();\r\n return;\r\n }\r\n QR.nodes.el.hidden = true;\r\n QR.cleanNotifications();\r\n QR.blur();\r\n $.rmClass(QR.nodes.el, 'dump');\r\n $.addClass(QR.shortcut, 'disabled');\r\n new QR.post(true);\r\n for (var post of QR.posts.splice(0, QR.posts.length - 1)) {\r\n post.delete();\r\n }\r\n QR.cooldown.auto = false;\r\n QR.status();\r\n return QR.captcha.destroy();\r\n },\r\n\r\n focus() {\r\n return $.queueTask(function() {\r\n if (!QR.inBubble()) {\r\n QR.hasFocus = d.activeElement && QR.nodes.el.contains(d.activeElement);\r\n return QR.nodes.el.classList.toggle('focus', QR.hasFocus);\r\n }\r\n });\r\n },\r\n\r\n inBubble() {\r\n const bubbles = $$('iframe[src^=\"https://www.google.com/recaptcha/api2/frame\"]');\r\n return bubbles.includes(d.activeElement) || bubbles.some(el => (getComputedStyle(el).visibility !== 'hidden') && (el.getBoundingClientRect().bottom > 0));\r\n },\r\n\r\n hide() {\r\n QR.blur();\r\n $.addClass(QR.nodes.el, 'autohide');\r\n return QR.nodes.autohide.checked = true;\r\n },\r\n\r\n unhide() {\r\n $.rmClass(QR.nodes.el, 'autohide');\r\n return QR.nodes.autohide.checked = false;\r\n },\r\n\r\n toggleHide() {\r\n if (this.checked) {\r\n return QR.hide();\r\n } else {\r\n return QR.unhide();\r\n }\r\n },\r\n\r\n blur() {\r\n if (QR.nodes.el.contains(d.activeElement)) { return d.activeElement.blur(); }\r\n },\r\n\r\n toggleSJIS(e) {\r\n e.preventDefault();\r\n Conf['sjisPreview'] = !Conf['sjisPreview'];\r\n $.set('sjisPreview', Conf['sjisPreview']);\r\n return QR.nodes.el.classList.toggle('sjis-preview', Conf['sjisPreview']);\r\n },\r\n\r\n texPreviewShow() {\r\n if ($.hasClass(QR.nodes.el, 'tex-preview')) { return QR.texPreviewHide(); }\r\n $.addClass(QR.nodes.el, 'tex-preview');\r\n QR.nodes.texPreview.textContent = QR.nodes.com.value;\r\n return $.event('mathjax', null, QR.nodes.texPreview);\r\n },\r\n\r\n texPreviewHide() {\r\n return $.rmClass(QR.nodes.el, 'tex-preview');\r\n },\r\n\r\n addPost() {\r\n const wasOpen = (QR.nodes && !QR.nodes.el.hidden);\r\n QR.open();\r\n if (wasOpen) {\r\n $.addClass(QR.nodes.el, 'dump');\r\n new QR.post(true);\r\n }\r\n return QR.nodes.com.focus();\r\n },\r\n\r\n setCustomCooldown(enabled) {\r\n Conf['customCooldownEnabled'] = enabled;\r\n QR.cooldown.customCooldown = enabled;\r\n return QR.nodes.customCooldown.classList.toggle('disabled', !enabled);\r\n },\r\n\r\n toggleCustomCooldown() {\r\n const enabled = $.hasClass(QR.nodes.customCooldown, 'disabled');\r\n QR.setCustomCooldown(enabled);\r\n return $.set('customCooldownEnabled', enabled);\r\n },\r\n\r\n error(err, focusOverride) {\r\n let el;\r\n QR.open();\r\n if (typeof err === 'string') {\r\n el = $.tn(err);\r\n } else {\r\n el = err;\r\n el.removeAttribute('style');\r\n }\r\n const notice = new Notice('warning', el);\r\n QR.notifications.push(notice);\r\n if (!Header.areNotificationsEnabled) {\r\n if (d.hidden && !QR.cooldown.auto) { return alert(el.textContent); }\r\n } else if (d.hidden || !(focusOverride || d.hasFocus())) {\r\n const notif = new Notification(el.textContent, {\r\n body: el.textContent,\r\n icon: Favicon.logo\r\n }\r\n );\r\n notif.onclick = () => window.focus();\r\n if ($.engine !== 'gecko') {\r\n // Firefox automatically closes notifications\r\n // so we can't control the onclose properly.\r\n notif.onclose = () => notice.close();\r\n return notif.onshow = () => setTimeout(function() {\r\n notif.onclose = null;\r\n return notif.close();\r\n }\r\n , 7 * SECOND);\r\n }\r\n }\r\n },\r\n\r\n connectionError() {\r\n return $.el('span',\r\n { innerHTML:\r\n 'Connection error while posting. ' +\r\n '[More info]'\r\n }\r\n );\r\n },\r\n\r\n notifications: [],\r\n\r\n cleanNotifications() {\r\n for (var notification of QR.notifications) {\r\n notification.close();\r\n }\r\n return QR.notifications = [];\r\n },\r\n\r\n status() {\r\n let disabled, value;\r\n if (!QR.nodes) { return; }\r\n const {thread} = QR.posts[0];\r\n if ((thread !== 'new') && g.threads.get(`${g.BOARD}.${thread}`).isDead) {\r\n value = 'Dead';\r\n disabled = true;\r\n QR.cooldown.auto = false;\r\n }\r\n\r\n value = QR.req ?\r\n QR.req.progress\r\n :\r\n QR.cooldown.seconds || value;\r\n\r\n const {status} = QR.nodes;\r\n status.value = !value ?\r\n 'Submit'\r\n : QR.cooldown.auto ?\r\n `Auto ${value}`\r\n :\r\n value;\r\n return status.disabled = disabled || false;\r\n },\r\n\r\n openPost() {\r\n QR.open();\r\n if (QR.selected.isLocked) {\r\n const index = QR.posts.indexOf(QR.selected);\r\n (QR.posts[index+1] || new QR.post()).select();\r\n $.addClass(QR.nodes.el, 'dump');\r\n return QR.cooldown.auto = true;\r\n }\r\n },\r\n\r\n quote(e) {\r\n let range;\r\n e?.preventDefault();\r\n if (!QR.postingIsEnabled) { return; }\r\n const sel = d.getSelection();\r\n const post = Get.postFromNode(this);\r\n const {root} = post.nodes;\r\n const postRange = new Range();\r\n postRange.selectNode(root);\r\n let text = post.board.ID === g.BOARD.ID ? `>>${post}\\n` : `>>>/${post.board}/${post}\\n`;\r\n for (let i = 0, end = sel.rangeCount, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i--) {\r\n try {\r\n var insideCode, node;\r\n range = sel.getRangeAt(i);\r\n // Trim range to be fully inside post\r\n if (range.compareBoundaryPoints(Range.START_TO_START, postRange) < 0) {\r\n range.setStartBefore(root);\r\n }\r\n if (range.compareBoundaryPoints(Range.END_TO_END, postRange) > 0) {\r\n range.setEndAfter(root);\r\n }\r\n\r\n if (!range.toString().trim()) { continue; }\r\n\r\n var frag = range.cloneContents();\r\n var ancestor = range.commonAncestorContainer;\r\n // Quoting the insides of a spoiler/code tag.\r\n if ($.x('ancestor-or-self::*[self::s or contains(@class,\"removed-spoiler\")]', ancestor)) {\r\n $.prepend(frag, $.tn('[spoiler]'));\r\n $.add(frag, $.tn('[/spoiler]'));\r\n }\r\n if (insideCode = $.x('ancestor-or-self::pre[contains(@class,\"prettyprint\")]', ancestor)) {\r\n $.prepend(frag, $.tn('[code]'));\r\n $.add(frag, $.tn('[/code]'));\r\n }\r\n for (node of $$((insideCode ? 'br' : '.prettyprint br'), frag)) {\r\n $.replace(node, $.tn('\\n'));\r\n }\r\n for (node of $$('br', frag)) {\r\n if (node !== frag.lastChild) { $.replace(node, $.tn('\\n>')); }\r\n }\r\n g.SITE.insertTags?.(frag);\r\n for (node of $$('.linkify[data-original]', frag)) {\r\n $.replace(node, $.tn(node.dataset.original));\r\n }\r\n for (node of $$('.embedder', frag)) {\r\n if (node.previousSibling?.nodeValue === ' ') { $.rm(node.previousSibling); }\r\n $.rm(node);\r\n }\r\n text += `>${frag.textContent.trim()}\\n`;\r\n } catch (error) { }\r\n }\r\n\r\n QR.openPost();\r\n const {com, thread} = QR.nodes;\r\n if (!com.value) { thread.value = Get.threadFromNode(this); }\r\n\r\n const wasOnlyQuotes = QR.selected.isOnlyQuotes();\r\n\r\n const caretPos = com.selectionStart;\r\n // Replace selection for text.\r\n com.value = com.value.slice(0, caretPos) + text + com.value.slice(com.selectionEnd);\r\n // Move the caret to the end of the new quote.\r\n range = caretPos + text.length;\r\n com.setSelectionRange(range, range);\r\n com.focus();\r\n\r\n // This allows us to determine if any text other than quotes has been typed.\r\n if (wasOnlyQuotes) { QR.selected.quotedText = com.value; }\r\n\r\n QR.selected.save(com);\r\n return QR.selected.save(thread);\r\n },\r\n\r\n characterCount() {\r\n const counter = QR.nodes.charCount;\r\n const count = QR.nodes.com.value.replace(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g, '_').length;\r\n counter.textContent = count;\r\n counter.hidden = count < (QR.max_comment/2);\r\n return (count > QR.max_comment ? $.addClass : $.rmClass)(counter, 'warning');\r\n },\r\n\r\n getFile() {\r\n return $.event('QRFile', QR.selected?.file);\r\n },\r\n\r\n drawFile(e) {\r\n const file = QR.selected?.file;\r\n if (!file || !/^(image|video)\\//.test(file.type)) { return; }\r\n const isVideo = /^video\\//.test(file);\r\n const el = $.el((isVideo ? 'video' : 'img'));\r\n $.on(el, 'error', () => QR.openError());\r\n $.on(el, (isVideo ? 'loadeddata' : 'load'), function() {\r\n e.target.getContext('2d').drawImage(el, 0, 0);\r\n URL.revokeObjectURL(el.src);\r\n return $.event('QRImageDrawn', null, e.target);\r\n });\r\n return el.src = URL.createObjectURL(file);\r\n },\r\n\r\n openError() {\r\n const div = $.el('div');\r\n $.extend(div, {\r\n innerHTML:\r\n 'Could not open file. [More info]'\r\n });\r\n return QR.error(div);\r\n },\r\n\r\n setFile(e) {\r\n const {file, name, source} = e.detail;\r\n if (name != null) { file.name = name; }\r\n if (source != null) { file.source = source; }\r\n QR.open();\r\n return QR.handleFiles([file]);\r\n },\r\n\r\n drag(e) {\r\n // Let it drag anything from the page.\r\n const toggle = e.type === 'dragstart' ? $.off : $.on;\r\n toggle(d, 'dragover', QR.dragOver);\r\n return toggle(d, 'drop', QR.dropFile);\r\n },\r\n\r\n dragOver(e) {\r\n e.preventDefault();\r\n return e.dataTransfer.dropEffect = 'copy';\r\n }, // cursor feedback\r\n\r\n dropFile(e) {\r\n // Let it only handle files from the desktop.\r\n if (!e.dataTransfer.files.length) { return; }\r\n e.preventDefault();\r\n QR.open();\r\n return QR.handleFiles(e.dataTransfer.files);\r\n },\r\n\r\n paste(e) {\r\n if (!e.clipboardData.items) { return; }\r\n let file = null;\r\n let score = -1;\r\n for (var item of e.clipboardData.items) {\r\n var file2;\r\n if ((item.kind === 'file') && (file2 = item.getAsFile())) {\r\n var score2 = (2*(file2.size <= QR.max_size)) + (file2.type === 'image/png');\r\n if (score2 > score) {\r\n file = file2;\r\n score = score2;\r\n }\r\n }\r\n }\r\n if (file) {\r\n const {type} = file;\r\n const blob = new Blob([file], {type});\r\n blob.name = `${Conf['pastedname']}.${$.getOwn(QR.extensionFromType, type) || 'jpg'}`;\r\n QR.open();\r\n QR.handleFiles([blob]);\r\n $.addClass(QR.nodes.el, 'dump');\r\n }\r\n },\r\n\r\n pasteFF() {\r\n const {pasteArea} = QR.nodes;\r\n if (!pasteArea.childNodes.length) { return; }\r\n const images = $$('img', pasteArea);\r\n $.rmAll(pasteArea);\r\n for (var img of images) {\r\n var m;\r\n var {src} = img;\r\n if (m = src.match(/data:(image\\/(\\w+));base64,(.+)/)) {\r\n var bstr = atob(m[3]);\r\n var arr = new Uint8Array(bstr.length);\r\n for (var i = 0, end = bstr.length, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i--) {\r\n arr[i] = bstr.charCodeAt(i);\r\n }\r\n var blob = new Blob([arr], {type: m[1]});\r\n blob.name = `${Conf['pastedname']}.${m[2]}`;\r\n QR.handleFiles([blob]);\r\n } else if (/^https?:\\/\\//.test(src)) {\r\n QR.handleUrl(src);\r\n }\r\n }\r\n },\r\n\r\n handleUrl(urlDefault) {\r\n QR.open();\r\n QR.selected.preventAutoPost();\r\n return CrossOrigin.permission(function() {\r\n const url = prompt('Enter a URL:', urlDefault);\r\n if (url === null) { return; }\r\n QR.nodes.fileButton.focus();\r\n return CrossOrigin.file(url, function(blob) {\r\n if (blob && !/^text\\//.test(blob.type)) {\r\n return QR.handleFiles([blob]);\r\n } else {\r\n return QR.error(\"Can't load file.\");\r\n }\r\n });\r\n });\r\n },\r\n\r\n handleFiles(files) {\r\n if (this !== QR) { // file input\r\n files = [...this.files];\r\n this.value = null;\r\n }\r\n if (!files.length) { return; }\r\n QR.cleanNotifications();\r\n for (var file of files) {\r\n QR.handleFile(file, files.length);\r\n }\r\n if (files.length !== 1) { $.addClass(QR.nodes.el, 'dump'); }\r\n if ((d.activeElement === QR.nodes.fileButton) && $.hasClass(QR.nodes.fileSubmit, 'has-file')) {\r\n return QR.nodes.filename.focus();\r\n }\r\n },\r\n\r\n handleFile(file, nfiles) {\r\n let post;\r\n const isText = /^text\\//.test(file.type);\r\n if (nfiles === 1) {\r\n post = QR.selected;\r\n } else {\r\n post = QR.posts[QR.posts.length - 1];\r\n if (isText ? post.com || post.pasting : post.file) {\r\n post = new QR.post();\r\n }\r\n }\r\n return post[isText ? 'pasteText' : 'setFile'](file);\r\n },\r\n\r\n openFileInput() {\r\n if (QR.nodes.fileButton.disabled) { return; }\r\n QR.nodes.fileInput.click();\r\n return QR.nodes.fileButton.focus();\r\n },\r\n\r\n generatePostableThreadsList() {\r\n if (!QR.nodes) { return; }\r\n const list = QR.nodes.thread;\r\n const options = [list.firstElementChild];\r\n for (var thread of g.BOARD.threads.keys) {\r\n options.push($.el('option', {\r\n value: thread,\r\n textContent: `Thread ${thread}`\r\n }\r\n )\r\n );\r\n }\r\n const val = list.value;\r\n $.rmAll(list);\r\n $.add(list, options);\r\n list.value = val;\r\n if (list.value === val) { return; }\r\n // Fix the value if the option disappeared.\r\n list.value = g.VIEW === 'thread' ?\r\n g.THREADID\r\n :\r\n 'new';\r\n return (g.VIEW === 'thread' ? $.addClass : $.rmClass)(QR.nodes.el, 'reply-to-thread');\r\n },\r\n\r\n dialog() {\r\n let dialog, event, nodes;\r\n let name;\r\n QR.nodes = (nodes = {\r\n el: (dialog = UI.dialog('qr',\r\n { innerHTML: QuickReplyPage }))\r\n });\r\n\r\n const setNode = (name, query) => nodes[name] = $(query, dialog);\r\n\r\n setNode('move', '.move');\r\n setNode('autohide', '#autohide');\r\n setNode('close', '.close');\r\n setNode('thread', 'select');\r\n setNode('form', 'form');\r\n setNode('sjisToggle', '#sjis-toggle');\r\n setNode('texButton', '#tex-preview-button');\r\n setNode('name', '[data-name=name]');\r\n setNode('email', '[data-name=email]');\r\n setNode('sub', '[data-name=sub]');\r\n setNode('com', '[data-name=com]');\r\n setNode('charCount', '#char-count');\r\n setNode('texPreview', '#tex-preview');\r\n setNode('dumpList', '#dump-list');\r\n setNode('addPost', '#add-post');\r\n setNode('oekaki', '.oekaki');\r\n setNode('drawButton', '#qr-draw-button');\r\n setNode('fileSubmit', '#file-n-submit');\r\n setNode('fileButton', '#qr-file-button');\r\n setNode('noFile', '#qr-no-file');\r\n setNode('filename', '#qr-filename');\r\n setNode('spoiler', '#qr-file-spoiler');\r\n setNode('oekakiButton', '#qr-oekaki-button');\r\n setNode('fileRM', '#qr-filerm');\r\n setNode('urlButton', '#url-button');\r\n setNode('pasteArea', '#paste-area');\r\n setNode('customCooldown', '#custom-cooldown-button');\r\n setNode('dumpButton', '#dump-button');\r\n setNode('status', '[type=submit]');\r\n setNode('flashTag', '[name=filetag]');\r\n setNode('fileInput', '[type=file]');\r\n\r\n const {config} = g.BOARD;\r\n const {classList} = QR.nodes.el;\r\n classList.toggle('forced-anon', QR.forcedAnon);\r\n classList.toggle('has-spoiler', QR.spoiler);\r\n classList.toggle('has-sjis', !!config.sjis_tags);\r\n classList.toggle('has-math', !!config.math_tags);\r\n classList.toggle('sjis-preview', !!config.sjis_tags && Conf['sjisPreview']);\r\n classList.toggle('show-new-thread-option', Conf['Show New Thread Option in Threads']);\r\n\r\n if (parseInt(Conf['customCooldown'], 10) > 0) {\r\n $.addClass(QR.nodes.fileSubmit, 'custom-cooldown');\r\n $.get('customCooldownEnabled', Conf['customCooldownEnabled'], function({customCooldownEnabled}) {\r\n QR.setCustomCooldown(customCooldownEnabled);\r\n return $.sync('customCooldownEnabled', QR.setCustomCooldown);\r\n });\r\n }\r\n\r\n QR.flagsInput();\r\n\r\n $.on(nodes.autohide, 'change', QR.toggleHide);\r\n $.on(nodes.close, 'click', QR.close);\r\n $.on(nodes.status, 'click', QR.submit);\r\n $.on(nodes.form, 'submit', QR.submit);\r\n $.on(nodes.sjisToggle, 'click', QR.toggleSJIS);\r\n $.on(nodes.texButton, 'mousedown', QR.texPreviewShow);\r\n $.on(nodes.texButton, 'mouseup', QR.texPreviewHide);\r\n $.on(nodes.addPost, 'click', () => new QR.post(true));\r\n $.on(nodes.drawButton, 'click', QR.oekaki.draw);\r\n $.on(nodes.fileButton, 'click', QR.openFileInput);\r\n $.on(nodes.noFile, 'click', QR.openFileInput);\r\n $.on(nodes.filename, 'focus', function() { return $.addClass(this.parentNode, 'focus'); });\r\n $.on(nodes.filename, 'blur', function() { return $.rmClass(this.parentNode, 'focus'); });\r\n $.on(nodes.spoiler, 'change', () => QR.selected.nodes.spoiler.click());\r\n $.on(nodes.oekakiButton, 'click', QR.oekaki.button);\r\n $.on(nodes.fileRM, 'click', () => QR.selected.rmFile());\r\n $.on(nodes.urlButton, 'click', () => QR.handleUrl(''));\r\n $.on(nodes.customCooldown, 'click', QR.toggleCustomCooldown);\r\n $.on(nodes.dumpButton, 'click', () => nodes.el.classList.toggle('dump'));\r\n $.on(nodes.fileInput, 'change', QR.handleFiles);\r\n\r\n window.addEventListener('focus', QR.focus, true);\r\n window.addEventListener('blur', QR.focus, true);\r\n // We don't receive blur events from captcha iframe.\r\n $.on(d, 'click', QR.focus);\r\n\r\n // XXX Workaround for image pasting in Firefox, obsolete as of v50.\r\n // https://bugzilla.mozilla.org/show_bug.cgi?id=906420\r\n if (($.engine === 'gecko') && !window.DataTransferItemList) {\r\n nodes.pasteArea.hidden = false;\r\n }\r\n new MutationObserver(QR.pasteFF).observe(nodes.pasteArea, {childList: true});\r\n\r\n // save selected post's data\r\n const items = ['thread', 'name', 'email', 'sub', 'com', 'filename', 'flag'];\r\n let i = 0;\r\n const save = function() { return QR.selected.save(this); };\r\n while ((name = items[i++])) {\r\n var node;\r\n if (!(node = nodes[name])) { continue; }\r\n event = node.nodeName === 'SELECT' ? 'change' : 'input';\r\n $.on(nodes[name], event, save);\r\n }\r\n\r\n // XXX Blink and WebKit treat width and height of