redditmod2

Dark themes, inline posts/comments, endless scrolling, subreddit filters, and other improvements for reddit.com

目前为 2018-08-26 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name redditmod2
  3. // @namespace derv82
  4. // @description Dark themes, inline posts/comments, endless scrolling, subreddit filters, and other improvements for reddit.com
  5. // @include http://*.reddit.com/*
  6. // @include https://*.reddit.com/*
  7. // @version 2.2.0
  8. // @grant GM.getValue
  9. // @grant GM.setValue
  10. // @grant GM.xmlHttpRequest
  11. // @grant GM_getValue
  12. // @grant GM_setValue
  13. // @grant GM_xmlhttpRequest
  14. // @connect reddit.com
  15. // @connect www.reddit.com
  16. // @connect imgur.com
  17. // @connect mercury.postlight.com
  18. // @connect gfycat.com
  19. // @connect soundcloud.com
  20. // @connect explosm.net
  21. // @connect imgflip.com
  22. // @connect streamable.com
  23. // @connect instagram.com
  24. // @connect deviantart.com
  25. // @connect xkcd.com
  26. // @run-at document-start
  27. // @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
  28. // ==/UserScript==
  29.  
  30. /** TODO
  31. * Delete filter button.
  32. * Support domains: giphy, flickr, prnt.sc, questionablecontent
  33. * Can't collapse/expand comments provided by RedditPromise for some reason... need to hijack onclick?
  34. * Can't click links in inline-comments (should be target=_blank).
  35. * Clicking bottom of inline-comment (marked as hovered) doesn't expand/collapse.
  36. * Voting on posts expands/collapses.
  37. * Can't vote on expanded comments.
  38. * Setting toggle: Shrink images to screen height
  39. * "Options" bar @ top: Fit to window, overflow-y:scroll ?
  40. */
  41.  
  42. (() => {
  43. 'use strict';
  44.  
  45. const DEBUG = false; // TODO: Change to false for release.
  46.  
  47. /** Helper/Wrapper around console.log -- includes stack trace. */
  48. function debug() {
  49. if (!DEBUG) return;
  50. const args = ['[Redditmod@'
  51. + (new Error()).stack.replace(/.*\?id=[a-f0-9\-]*:/g, '').replace(/@.*[^\r\n]/g, '').replace(/\n\n/g, '').replace(/\n$/g, '').replace(/\n/g, ' <- ')
  52. + ']'];
  53. for (let i = 0; i < arguments.length; i++) {
  54. args.push(arguments[i]);
  55. }
  56. console.log.apply(console.log, args);
  57. }
  58.  
  59. /** Helper function for preventing event bubbling. */
  60. function stopEvent(event) {
  61. if (event && event.stopPropagation) event.stopPropagation();
  62. if (event && event.preventDefault) event.preventDefault();
  63. }
  64.  
  65.  
  66. /**
  67. * Promises accessors to a loaded configuration.
  68. */
  69. const CONFIG = (() => {
  70. const BASE_STYLE = '.thing.gilded:hover,.thing:hover{background:linear-gradient(to right,var(--bg-2),var(--bg) 50%,var(--bg-2));box-shadow:0 0 5px rgba(0,0,0,.5)}body>.content .link .rank{width:auto!important}.thing{padding:3px 10px;border-radius:10px;transition:height .2s ease-in-out}#header-img.default-header{width:30px}.redditmod-filter-subreddit-button{border:none;background-color:var(--fg-link);color:var(--bg)!important;font-weight:900;border-radius:15px;padding:0 1.9px .5px;margin-left:5px;box-shadow:0 0 5px rgba(0,0,0,.5)}.redditmod-filter-subreddit-button:hover{text-decoration:none!important;box-shadow:0 0 2px rgba(0,0,0,.5)}';
  71. const THEMED_STYLE = '#header-bottom-right,.ProfileSidebar__titleContainer,.ProfileTemplate.m-updated,.content,.link,.listing-chooser li.selected,.side,.tabmenu li.selected a,.user-subreddit-banner,body,body.with-listing-chooser .listing-chooser .grippy,html{background-color:var(--bg)}#header,#sr-drop-down,#sr-header-area,.BlueBar,.Media.m-profile.m-image,.Post,.Post__pinInfo,.Post__stickiedDivider,.ProfileBarDropdown__list,.SubscriptionBar,.author-tooltip__head,.authorized-app,.crosspost-preview,.drop-choices,.explore-comment .explore-label,.explore-discovery .explore-label,.explore-hot .explore-label,.explore-rising .explore-label,.gold-accent,.hover-bubble,.infobar,.link .usertext-body .md,.linkinfo,.listing-chooser li,.liveupdate-listing li.liveupdate time::before,.liveupdate-listing li.separator time,.message .subject .correspondent,.message.new>.entry,.modal-content,.nextprev a:hover,.raisedbox,.report-modal .modal-content,.roundfield,.searchpane,.server-seconds,.sr-interest-bar,.sr-interest-bar .bubble,.subreddit .usertext .md,.tabmenu li a,.trophy-area .content,body.with-listing-chooser .listing-chooser,div.link.self:hover,main[role=main]{background-color:var(--bg-2)}#newlink-with-image-upload #new-link-preview,#newlink-with-image-upload .image-upload-drop-target,#sr-more-link,.BlueBar__account,.goldvertisement a,.infobar.profilebetabar,.link .md :not(pre)>code,.link .md pre,.link.promotedlink.promoted,.md code,.md pre,.nextprev a,.tabmenu li a:hover,.usertable tr:hover,.usertext.border .usertext-body,.white-field,oddrow{background-color:var(--bg-odd)}.form-control,.hover-bubble.multi-selector .create-multi input[type=text],.morelink,.morelink .nub,.morelink a,button.expand-summary,button.report-button,input,input[type=password],input[type=text],select,textarea{background-color:var(--bg-input);color:var(--fg-input)}.form-control:focus,.goldvertisement a:hover,.hover-bubble.multi-selector .create-multi input[type=text]:focus,.listing-chooser li:hover,.morelink:hover,.morelink:hover .nub,.morelink:hover a,body.with-listing-chooser .listing-chooser .grippy:hover::after,body.with-listing-chooser.listing-chooser-collapsed .listing-chooser .grippy::before,button.expand-summary:hover,input:focus,input[type=password]:focus,input[type=text]:focus,select:focus,textarea:focus{background-color:var(--bg-input-hover);color:var(--fg-input-hover)}.explore-comment .comment-fade,.form-control,.infobar.onboardingbar,.listing-chooser li.selected,.morelink,.morelink .nub,.morelink:hover,.morelink:hover .nub,.navbar,.search-expando.collapsed::before,.sidebox.hohoho .morelink,body,body.with-listing-chooser .listing-chooser .grippy:hover::after,body.with-listing-chooser.listing-chooser-collapsed .listing-chooser .grippy::before,input[type=text],select,textarea{background-image:none}.hover-bubble.multi-selector label:hover,.icon-menu a,.morelink .nub,.side ul.content,.sidebox .spacer,.titlebox form.toggle,aside.sidebar #discussions li,div.link.self{background-color:transparent}.ProfileBarDropdown__listItem:hover,.drop-choices a.choice:hover,.flair,.linkflairlabel,.wiki-page .pageactions .wikiaction:hover,a.message-count{background-color:var(--fg-link);color:var(--bg)!important}.tagline .flair{background-color:var(--fg-muted);color:var(--bg)}.md hr,.tabmenu.formtab .selected a{background-color:var(--border-color)}.Post__pinInfo,.TabMenu__tab.m-active,.card a,.gold-accent,.goldvertisement,.hover-bubble,.liveupdate-listing li.separator time,.md,.message.message-parent>.entry .md,.message.recipient>.entry,.report-modal .modal-header-title,.report-modal .report-form-bottom-panel .report-form-content-policy p,.report-modal .report-form-last-step-text-custom-rules,.report-modal .report-reason-item .report-reason-display,.search-result-group footer .info,.side .titlebox .md ul li,.titlebox,.titlebox h1 a,.trophy-name,.user-subreddit-public-description,body,html,main[role=main] h1,main[role=main] h2,main[role=main] p{color:var(--fg)}.Post__score,.TrendingProfilesSidebar__header,.TrophyCaseSidebar__header,.UserModeratedSubredditsSidebar__header,.UserSpecialsListSidebar__header,.author-tooltip__credentials-list strong,.brand,.dropdown.srdrop .selected,.gold-accent th,.gold-expiration-info .karma,.goldvertisement .progress p,.hover-bubble.multi-selector strong,.link .md :not(pre)>code,.link .rank,.listing-chooser h3,.search-result :link>mark,.search-result-group-header,.server-seconds em,.sidecontentbox .title h1,.titlebox h1 a:first-child,.wiki-page .wikititle,.wiki-page-content .md h1,.wiki-page-content .md h2,.wiki-page-content .md h3,.wiki-page-content .md h4,.wiki-page-content .md h5,aside.sidebar .md h2,aside.sidebar section,dl>dt,h1,h2,h3,h4,h5{color:var(--fg-2)}#sr-header-area .selected a,#sr-more-link,.Post__authorLink,.Post__authorLink:visited,.Post__flatListItem:link,.Post__source .Post__sourceLink,.Post__tagline,.ProfileSidebar__counters,.ProfileSidebar__description,.ProfileSidebar__displayName,.SubredditListItem__subscribers,.TrophyCaseSidebar__trophyDescription,.TrophyCaseSidebar__trophyTitle,.UserSpecialsListSidebar__date,.UserSpecialsListSidebar__title,.bottommenu,.dropdown.lightdrop .selected,.entry .buttons li a,.explore-comment .comment-link,.explore-item .explore-sr-details,.flat-list li.selected a,.flat-vert.title,.footer,.gray,.gray-buttons button,.listing-chooser li a .description,.liveupdate-listing li.liveupdate time,.md blockquote,.md del,.message .search-result-meta,.message .tagline,.message.message-parent.recipient>.entry .head,.message.message-parent>.entry .head,.message.message-reply.recipient>.entry .head,.multi-details h3,.muted,.nextprev,.preftable .details,.report-modal .report-form-block-user .report-form-action-desc p,.search-expando-button,.search-result .author:link,.search-result .search-subreddit-link:link,.search-result-meta,.separator,.sidebox .subtitle,.sidecontentbox .more a,.sr-list a:link,.sr-list a:link:hover,.sr-list a:visited,.subscription-box .title:visited,.tagline,.tagline .expand,.tagline>a.author,.titlebox .bottom,.titlebox form.toggle,.trophy-description,.user,.redditmod-visited a.title,aside.sidebar #discussions li,dl>dd,label.disabled,span.domain>a{color:var(--fg-muted)}.BlueBar__logout,.ProfileBarDropdown__title,.listing-chooser .create button,.liveupdate-listing li.liveupdate a.author,.liveupdate-listing li.liveupdate:hover time,.report-modal .report-form-bottom-panel .report-form-content-policy a,.search-result :link,.subscription-box .title,.tabmenu li.selected a,.tagline a.subreddit,.thing .title,a,a:link{color:var(--fg-link)}#sr-header-area .selected a:hover,.BlueBar__logout:hover,.Post__authorLink:hover,.Post__stickied-title:hover,.Post__subredditLink:hover,.ProfileBarDropdown__title.m-opened,.author-tooltip__head a:hover,.author-tooltip__link-list a:hover,.flat-list li.selected a:hover,.liveupdate-listing li.liveupdate:hover a.author,.report-modal .report-form-bottom-panel .report-form-content-policy a:hover,.search-result :link:hover,.sidecontentbox .more a:hover,.subscription-box .title:hover,.tabmenu li a:hover,.tagline a.subreddit,.thing .title:hover,a:hover,a:visited:hover{color:var(--fg-link-hover)}.search-result :link:visited,.tabmenu li a,.tagline a.subreddit:visited,.thing .title:visited,a:visited{color:var(--fg-link-visited)}.morelink>a,.spoiler-stamp,a.TrendingProfilesSidebar__follow,a.c-btn-primary{color:#fff}.tagline .submitter{color:#4af}.Post__moderatorFlair,.green,.tagline .moderator,.tagline .pinned-tagline,.tagline .stickied-tagline,.thing.stickied.link a.title,.thing.sticky-pinned.link a.title{color:#3a3}input[style*="color:black"]{color:var(--fg-input)!important}.trophy-name{color:var(--fg-2)!important}hr{color:var(--border-color)}#header,#liveupdate-statusbar.complete,#sr-header-area,.Post.m-profile,.Post__scoreDisplay,.content,.crosspost-preview,.explore-comment .explore-label,.explore-discovery .explore-label,.explore-hot .explore-label,.explore-rising .explore-label,.flair,.footer,.infobar.profilebetabar,.link,.linkflairlabel,.linkinfo,.navbar,.organic-listing,.permission-summary,.reddit-infobar,div.link.self,noborder{border:none}button.expand-summary,button.report-button,custom-border,hr,input,select{border:var(--border)}#compose-message .roundfield select,#header,#header hr,#sr-header-area,.BlueBar,.author-tooltip__credentials-list li,.author-tooltip__head,.author-tooltip_self .author-tooltip__head,.authorized-app,.c-form-control,.drop-choices,.explore-comment .comment,.filtered-details form.add-sr .sr-name,.footer .col,.formtabs-content,.hover-bubble,.hover-bubble.multi-selector .create-multi input[type=text],.infobar,.link .md pre,.link .usertext-body .md,.listing-chooser li,.listing-chooser li.selected,.liveupdate-listing li.separator::before,.md code,.md pre,.md td,.md th,.menuarea,.message.new>.entry,.morelink,.multi-details form.add-sr .sr-name,.nextprev a,.raisedbox,.report-modal .modal-content,.roundfield input[type=text],.roundfield textarea,.search-result-group-header,.sidebox.hohoho .morelink,.sidecontentbox .content,.subreddit .usertext .md,.subscription-box .box-separator,.titlebox .bottom,.wiki-page .pageactions,.wiki-page .wiki-page-content .wiki>.toc>ul,.wiki-page .wiki-page-content .wiki>.toc>ul ul,body.with-listing-chooser .listing-chooser .grippy,body.with-listing-chooser .listing-chooser .grippy::after,body.with-listing-chooser.listing-chooser-collapsed .listing-chooser .grippy::after,hr,input,select,textarea{border-color:var(--border-color)}.tabmenu li.selected a{border-color:transparent}#header-bottom-right{border-bottom:solid 1px var(--bg)}.goldvertisement a,.listing-chooser .create button{border-color:var(--fg-link)}.nextprev .separator{border-color:var(--fg-muted)}.author-tooltip.hover-bubble.anchor-bottom-left::before,.author-tooltip.hover-bubble.anchor-bottom-right::before{border-top-color:var(--bg-2)}.ProfileBarDropdown__title.m-arrow.m-opened::after,.ProfileBarDropdown__title.m-arrow::after,.TabMenu__tab.m-active::after{border-top-color:var(--fg-muted)}.comment .child{border-left:solid 5px var(--border-color)}.hover-bubble.anchor-right::after{border-left-color:var(--bg-2)}#liveupdate-statusbar.complete,success,success a{background-color:var(--bg-success);color:var(--fg-success)}.archived-infobar.with-icon::before,.content.submit .info-notice,.reddit-infobar,.reddit-infobar .md,info,info a{background-color:var(--bg-info);color:var(--fg-info)}.app-scope,warning{background-color:var(--bg-warning);color:var(--fg-warning)}error,error a{background-color:var(--bg-error);color:var(--fg-error)}disabled{background-color:var(--bg-disabled);color:var(--fg-disabled)}pre{background-color:var(--syntax-bg);color:var(--syntax-fg)}.infobar.profilebetabar,.organic-listing,.toc>ul{box-shadow:0 0 5px rgba(0,0,0,1)}.crosspost-preview,.listing-chooser li.selected{box-shadow:30px 0 30px -15px rgba(255,255,255,.1) inset,0 2px 6px -1px rgba(0,0,0,.2)}.goldvertisement,.report-flow-form.thing:hover{box-shadow:none;background-image:none}label.disabled{cursor:not-allowed}.subreddit-subscribe:before{filter:saturate(0) brightness(150%)}.subreddit-subscribe:hover:before{filter:saturate(100%)}.add-sr button.add,.multi-details button.add,.multi-details button.remove-sr.remove-sr,img[src*="start_chat.png"]{filter:invert(200%)}';
  72.  
  73. const CSS_NO_ADS = '.goldvertisement, .thing.promoted, [id^="ad_"], #siteTable_organic {display:none!important}';
  74. const CSS_NO_CHAT = '#chat-app, #chat, #chat + span {display:none!important}';
  75. const CSS_NO_SUBLIST = '.sr-list > *:not(:first-child) {display:none!important}';
  76. const CSS_NO_FOOTER = '.footer, .footer-parent {display:none!important}';
  77. const CSS_NO_HEADER_IMAGE = '#header-img, .hohoho {display:none!important} body.with-listing-chooser #header .pagename{position:relative; bottom:0}';
  78. const CSS_COLLAPSE_SIDEBAR = '.side{position:absolute;transition:right .2s ease-in-out;box-shadow:-5px 0 3px 0 rgba(0,0,0,.1);padding-left:10px;right:-305px;width:300px;z-index:1}' +
  79. 'body{overflow-x:hidden}' +
  80. '.side:hover{right:-5px}' +
  81. '.side .nub{opacity:0}' +
  82. '.side:hover .nub{opacity:1}';
  83.  
  84. // Existing values are the *default*
  85. const config = {
  86. subreddits: [],
  87. filteredSubreddits: {},
  88. texts: [],
  89. filteredTexts: {},
  90. theme: 'obsidian',
  91. nsfwFilterState: 'show',
  92. themes: {
  93. none: '',
  94. obsidian: ':root{--fg:#E0E2E4;--bg:#293134;--bg-odd:#303a3d;--fg-2:#678CB1;--bg-2:#3F4B4E;--fg-muted:#999;--fg-input:#A7CCF1;--bg-input:#293134;--fg-input-hover:#E0E2E4;--bg-input-hover:#536364;--border:solid 0.5px #678CB1;--border-color:#678CB1;--fg-link:#EC7600;--fg-link-hover:#FC8610;--fg-link-visited:#BA4400;--fg-disabled:#ddd;--bg-disabled:#777;--fg-error:#fff;--fg-warning:#000;--fg-info:#fff;--fg-success:#fff;--bg-error:#600;--bg-warning:#fa4;--bg-info:#14a;--bg-success:#151;--syntax-fg:#F1F2F3;--syntax-fg-2:#E8E2B7;--syntax-bg:#293134;--syntax-bg-2:#3F4B4E;--syntax-comment:#66747B;--syntax-builtin:#93C763;--syntax-function:#678CB1;--syntax-keyword:#7CCADD;--syntax-number:#FFCD22;--syntax-string:#EC7600;--syntax-font-family:"Menlo","Liberation Mono","Consolas","DejaVu Sans Mono","Ubuntu Mono","Courier New","andale mono","lucida console",monospace;--selection-fg:#000}',
  95. monokai: ':root{--fg:#f8f8f2;--bg:#29281E;--bg-odd:#2f2f24;--fg-2:#66d9ef;--bg-2:#39382E;--fg-muted:#999;--fg-input:#fd971f;--bg-input:#2f2f24;--fg-input-hover:#fd971f;--bg-input-hover:#252520;--border:solid 0.5px #777;--border-color:#777;--fg-link:#f92672;--fg-link-hover:#d90652;--fg-link-visited:#fd971f;--fg-disabled:#ddd;--bg-disabled:#777;--fg-error:#fff;--fg-warning:#000;--fg-info:#fff;--fg-success:#fff;--bg-error:#600;--bg-warning:#fa4;--bg-info:#14a;--bg-success:#151;--syntax-fg:#f8f8f2;--syntax-fg-2:#f8f8f2;--syntax-bg:#272822;--syntax-bg-2:#373832;--syntax-comment:#75715e;--syntax-builtin:#f92672;--syntax-function:#a6e22e;--syntax-keyword:#76d9e6;--syntax-number:#ae81ff;--syntax-string:#e6db74;--syntax-font-family:"Menlo","Liberation Mono","Consolas","DejaVu Sans Mono","Ubuntu Mono","Courier New","andale mono","lucida console",monospace;--selection-fg:#000}',
  96. blue: ':root{--fg:#ccc;--bg:#192833;--bg-odd:#243237;--fg-2:#F39200;--bg-2:#293843;--fg-muted:#999;--fg-input:#fff;--bg-input:#334247;--fg-input-hover:#fff;--bg-input-hover:#394853;--border:solid 0.5px #495863;--border-color:#495863;--fg-link:#28c;--fg-link-hover:#6cf;--fg-link-visited:#8af;--fg-disabled:#ddd;--bg-disabled:#777;--fg-error:#fff;--fg-warning:#000;--fg-info:#fff;--fg-success:#fff;--bg-error:#600;--bg-warning:#fa4;--bg-info:#14a;--bg-success:#151;--syntax-fg:#839496;--syntax-fg-2:#eee8d5;--syntax-bg:#002b36;--syntax-bg-2:#073642;--syntax-comment:#75715e;--syntax-builtin:#268bd2;--syntax-function:#cb4b16;--syntax-keyword:#b58900;--syntax-number:#6c71c4;--syntax-string:#2aa198;--syntax-font-family:"Menlo","Liberation Mono","Consolas","DejaVu Sans Mono","Ubuntu Mono","Courier New","andale mono","lucida console",monospace;--selection-fg:#000}',
  97. black: ':root{--fg:#ccc;--bg:#101010;--bg-odd:#191919;--fg-2:#aab;--bg-2:#202020;--fg-muted:#999;--fg-input:#aaa;--bg-input:#000;--fg-input-hover:#fff;--bg-input-hover:#151515;--border:solid 0.5px #353535;--border-color:#353535;--fg-link:#369;--fg-link-hover:#47a;--fg-link-visited:#96a;--fg-disabled:#ddd;--bg-disabled:#777;--fg-error:#fff;--fg-warning:#000;--fg-info:#fff;--fg-success:#fff;--bg-error:#600;--bg-warning:#fa4;--bg-info:#14a;--bg-success:#151;--syntax-fg:#f5f5f5;--syntax-fg-2:#ffffff;--syntax-bg:#000000;--syntax-bg-2:#202020;--syntax-comment:#b0b0b0;--syntax-builtin:#fb0120;--syntax-function:#6fb3d2;--syntax-keyword:#d381c3;--syntax-number:#fc6d24;--syntax-string:#a1c659;--syntax-font-family:"Menlo","Liberation Mono","Consolas","DejaVu Sans Mono","Ubuntu Mono","Courier New","andale mono","lucida console",monospace;--selection-fg:#000}'
  98. },
  99. tweaks: {
  100. autoAlign: true,
  101. infiniteScrolling: true,
  102. loadPostsInline: true,
  103. noAds: true,
  104. noChat: true,
  105. noSublist: true,
  106. noFooter: true,
  107. noHeaderImage: true,
  108. collapseSidebar:true
  109. },
  110. visitedThings: {}
  111. };
  112.  
  113. return new Promise(resolve => {
  114. const keys = Object.keys(config);
  115. Promise.all(keys.map(key => GM.getValue('redditmod-' + key)))
  116. .then(values => {
  117. // Load config
  118. values.forEach((value, keyIndex) => {
  119. if (value !== undefined) {
  120. config[keys[keyIndex]] = JSON.parse(value);
  121. }
  122. });
  123.  
  124. // Clear visited for the past day
  125. flushVisited();
  126.  
  127. // Expose public methods
  128. resolve({
  129. getThemes, setTheme, getThemeCSS, getTheme,
  130. getTweaks, setTweak, getTweakCSS, isTweakEnabled,
  131. getSubreddits, setSubredditFilter, setAllSubredditFilters, isSubredditFiltered, removeSubreddit,
  132. getNsfwState, setNsfwState,
  133. getTexts, setTextFilter, isTextFiltered, removeText, shouldFilterTextblock,
  134. addVisitedThing, isVisited, flushVisited
  135. });
  136. });
  137. });
  138.  
  139. /* optionalKey: if given, only saves that key of the config. */
  140. function _save(optionalKey) {
  141. const keys = optionalKey !== undefined ? [optionalKey] : Object.keys(config);
  142. return new Promise(resolve => {
  143. Promise.all(keys.map(key => GM.setValue('redditmod-' + key, JSON.stringify(config[key]))))
  144. .then(resolve);
  145. });
  146. }
  147.  
  148. // ==============================================
  149. // Themes
  150. function getTheme() { return config.theme; }
  151. function getThemes() { return Object.keys(config.themes); }
  152.  
  153. function setTheme(theme) {
  154. const promises = [];
  155. theme = (theme === undefined) ? 'none' : theme;
  156. if (config.theme !== theme) {
  157. config.theme = theme;
  158. promises.push(_save('theme'));
  159. }
  160. return Promise.all(promises);
  161. }
  162.  
  163. function getThemeCSS() {
  164. if (config.theme === 'none' || config.themes[config.theme] === undefined) {
  165. return BASE_STYLE;
  166. } else {
  167. return config.themes[config.theme] + BASE_STYLE + THEMED_STYLE;
  168. }
  169. }
  170.  
  171. // =========================================
  172. // Tweaks
  173. function isTweakEnabled(tweakID) { return (config.tweaks[tweakID] === true); }
  174.  
  175. function getTweaks() {
  176. return [
  177. { name: 'Infinite Scrolling', id: 'infiniteScrolling', enabled: config.tweaks.infiniteScrolling, title: "Load next page when you reach the bottom" },
  178. { name: 'Load Pages Inline', id: 'loadPostsInline', enabled: config.tweaks.loadPostsInline, title: "Add the next page of posts to the bottom of the current page (ignored when 'Infinite Scrolling' is enabled)." },
  179. { name: 'Auto-align on expand', id: 'autoAlign', enabled: config.tweaks.autoAlign, title: "Scroll so the clicked post is at the top of the screen." },
  180. { name: 'No Ads', id: 'noAds', enabled: config.tweaks.noAds, title: "Don't display ads disguised as posts" },
  181. { name: 'No Chat', id: 'noChat', enabled: config.tweaks.noChat, title: "Don't show anything related to Reddit's Chat feature" },
  182. { name: 'No Sublist', id: 'noSublist', enabled: config.tweaks.noSublist, title: "Don't show subreddit list at top of page" },
  183. { name: 'No Footer', id: 'noFooter', enabled: config.tweaks.noFooter, title: "Don't show footer at bottom of page" },
  184. { name: 'No Header Image', id: 'noHeaderImage', enabled: config.tweaks.noHeaderImage, title: "Don't show reddit icon at top of page" },
  185. { name: 'Collapse Sidebar', id: 'collapseSidebar', enabled: config.tweaks.collapseSidebar, title: "Hide the sidebar -- visible on hover" }
  186. ];
  187. }
  188.  
  189. function getTweakCSS() {
  190. const results = [];
  191. if (config.tweaks.noAds) { results.push(CSS_NO_ADS); }
  192. if (config.tweaks.noChat) { results.push(CSS_NO_CHAT); }
  193. if (config.tweaks.noSublist) { results.push(CSS_NO_SUBLIST); }
  194. if (config.tweaks.noFooter) { results.push(CSS_NO_FOOTER); }
  195. if (config.tweaks.noHeaderImage) { results.push(CSS_NO_HEADER_IMAGE); }
  196. if (config.tweaks.collapseSidebar) { results.push(CSS_COLLAPSE_SIDEBAR); }
  197. return results.join('');
  198. }
  199.  
  200. function setTweak(tweakID, enabled) {
  201. const promises = [];
  202. config.tweaks[tweakID] = enabled;
  203. promises.push(_save('tweaks'));
  204. return Promise.all(promises);
  205. }
  206.  
  207. // ==============================================
  208. // Subreddit Filters
  209. function getSubreddits() { return config.subreddits; }
  210. function isSubredditFiltered(subreddit) { return (config.filteredSubreddits[subreddit] === true); }
  211.  
  212. function setAllSubredditFilters(enabled) {
  213. config.subreddits.forEach(subreddit => {
  214. config.filteredSubreddits[subreddit] = enabled;
  215. });
  216. return _save('filteredSubreddits');
  217. }
  218.  
  219. function setSubredditFilter(subreddit, enabled) {
  220. const promises = [];
  221. if (!config.subreddits.includes(subreddit)) {
  222. config.subreddits.push(subreddit);
  223. promises.push(_save('subreddits'));
  224. }
  225. if (config.filteredSubreddits[subreddit] !== enabled) {
  226. config.filteredSubreddits[subreddit] = enabled;
  227. promises.push(_save('filteredSubreddits'));
  228. }
  229. return Promise.all(promises);
  230. }
  231.  
  232. function removeSubreddit(subreddit) {
  233. const promises = [];
  234. if (config.subreddits.includes(subreddit)) {
  235. config.subreddits = config.subreddits.filter(sub => subreddit !== sub);
  236. promises.push(_save('subreddits'));
  237. }
  238. Promise.all(promises);
  239. }
  240.  
  241. // ==============================================
  242. // Text Filters
  243. function getTexts() { return config.texts; }
  244. function isTextFiltered(text) { return config.filteredTexts[text] === true; }
  245.  
  246. function shouldFilterTextblock(textblock) {
  247. const reasons = [];
  248. Object.keys(config.filteredTexts).forEach(filteredText => {
  249. if (isTextFiltered(filteredText) && textblock.toLowerCase().includes(filteredText.toLowerCase())) {
  250. reasons.push('TEXT("' + filteredText + '")');
  251. }
  252. });
  253. return reasons.length === 0 ? false : reasons.join(', ');
  254. }
  255.  
  256. function setTextFilter(text, enabled) {
  257. const promises = [];
  258. if (!config.texts.includes(text)) {
  259. config.texts.push(text);
  260. promises.push(_save('texts'));
  261. }
  262. if (config.filteredTexts[text] !== enabled) {
  263. config.filteredTexts[text] = enabled;
  264. promises.push(_save('filteredTexts'));
  265. }
  266. return Promise.all(promises);
  267. }
  268.  
  269. function removeText(text) {
  270. const promises = [];
  271. if (config.texts.includes(text)) {
  272. config.texts = config.texts.filter(txt => text !== txt);
  273. promises.push(_save('texts'));
  274. }
  275. Promise.all(promises);
  276. }
  277.  
  278. // ==============================================
  279. // Nsfw Filter
  280. function getNsfwState() {
  281. return config.nsfwFilterState;
  282. }
  283.  
  284. function setNsfwState(state) {
  285. config.nsfwFilterState = state;
  286. return _save('nsfwFilterState');
  287. }
  288.  
  289. // ==============================================
  290. // Visited
  291. function addVisitedThing(thingId) {
  292. config.visitedThings[thingId] = new Date().getTime();
  293. return _save('visitedThings');
  294. }
  295.  
  296. function isVisited(thingId) {
  297. return config.visitedThings[thingId] > 0;
  298. }
  299.  
  300. function flushVisited() {
  301. const yesterday = new Date().getTime() - 86400000;
  302. Object.entries(config.visitedThings)
  303. .filter(([thingId, timestamp]) => (timestamp < yesterday))
  304. .forEach(([thingId, timestamp]) => {
  305. delete config.visitedThings[thingId];
  306. });
  307. return _save('visitedThings');
  308. }
  309.  
  310. })();
  311.  
  312. /**
  313. * All things CSS & DOM (applying/removing CSS rules, waiting for DOM elements);
  314. */
  315. const CSS = (() => {
  316. const onHead = _onNode('head'); /* Wait for <head> to appear. */
  317. const onBody = _onNode('body'); /* Wait for <body> to appear. */
  318.  
  319. return {onDOM, onHead, applyStyle, removeStyle};
  320.  
  321. /** Promises a child node immediately under the root `document`. Waits if node is not found. */
  322. function _onNode(documentKey) {
  323. return new Promise(resolve => {
  324. const timer = setInterval(promiseNode, 50);
  325. function promiseNode() {
  326. if (document[documentKey]) {
  327. clearInterval(timer);
  328. resolve(document[documentKey]);
  329. }
  330. }
  331. });
  332. }
  333.  
  334. /** Promises /when/ the DOM is loaded & ready. */
  335. function onDOM() {
  336. return new Promise(resolve => {
  337. if (document.readyState === 'interactive' || document.readyState === 'complete') {
  338. resolve();
  339. } else {
  340. document.addEventListener('DOMContentLoaded', function(event) {
  341. document.removeEventListener('DOMContentLoaded', event.callee);
  342. resolve();
  343. });
  344. }
  345. });
  346. }
  347.  
  348. /**
  349. * Waits for <head> to appear, then applies CSS rules to the page.
  350. * Removes existing CSS Rules that match the given ID.
  351. * @param {String} id The identifier for this style.
  352. * @param {String} css The CSS rules in text/string format.
  353. * @return Promise for when style is applied.
  354. */
  355. function applyStyle(id, css) {
  356. return new Promise(resolve => {
  357. onHead.then(head => {
  358. let style = head.querySelector('.redditmod-style#' + id);
  359. if (style !== null && style.firstChild) {
  360. style.removeChild(style.firstChild);
  361. } else {
  362. style = document.createElement('style');
  363. Object.assign(style, { id:id, type:'text/css', className:'redditmod-style' });
  364. }
  365. style.appendChild(document.createTextNode(css));
  366. head.appendChild(style);
  367. resolve(head);
  368. });
  369. });
  370. }
  371.  
  372. /** @param {String} id The style ID, set when `applyStyle` is called. */
  373. function removeStyle(id) {
  374. const style = document.head.querySelector('style#' + id);
  375. if (style) style.parentNode.removeChild(style);
  376. }
  377. })();
  378.  
  379.  
  380. /** */
  381. const MENU = (() => {
  382. const MENU_STYLE_ID = 'redditmod-menu-style';
  383. const MENU_STYLE = '.redditmod-menu-header{margin:3px 5px 3px 5px}';
  384.  
  385. let isInitialized = false;
  386. let config;
  387. return {init};
  388.  
  389. function init(theConfig) {
  390. config = theConfig;
  391. return new Promise(resolve => {
  392. if (isInitialized) {
  393. resolve({updateMenuSection});
  394. } else {
  395. CSS.onDOM().then(() => {
  396. resetMenu();
  397. CSS.applyStyle(MENU_STYLE_ID, MENU_STYLE);
  398. isInitialized = true;
  399. resolve({updateMenuSection});
  400. });
  401. }
  402. });
  403. }
  404.  
  405. function resetMenu() {
  406. const menu = document.querySelector('.dropdown.srdrop .selected');
  407. if (menu) menu.textContent = 'OPTIONS';
  408. const dropdown = document.querySelector('.drop-choices.srdrop');
  409. if (dropdown) dropdown.innerHTML = '';
  410. }
  411.  
  412. function create(tag, props, parentToAppendTo) {
  413. const node = document.createElement(tag);
  414. if (props) Object.assign(node, props);
  415. if (parentToAppendTo) parentToAppendTo.appendChild(node);
  416. return node;
  417. }
  418.  
  419. function updateMenuSection(title, id, anchorsProps) {
  420. const dropdown = document.querySelector('.drop-choices.srdrop');
  421. if (!dropdown) return;
  422.  
  423. if (document.querySelector('.drop-choices.srdrop .redditmod-menu-header') !== null && document.querySelector('#' + id) === null) {
  424. create('hr', {className:'redditmod-menu-spacer'}, dropdown);
  425. }
  426.  
  427. const section = document.querySelector('#' + id) || create('div', {id}, dropdown);
  428. const header = section.querySelector('.redditmod-menu-header') || create('h3', {className:'redditmod-menu-header'}, section);
  429. const links = section.querySelector('.redditmod-menu-links') || create('div', {className:'redditmod-menu-links'}, section);
  430.  
  431. header.textContent = title;
  432. links.innerHTML = '';
  433. anchorsProps.forEach(props => {
  434. if (!props.href) props.href = '#';
  435. create('a', props, links).className = 'choice';
  436. });
  437. }
  438. })();
  439.  
  440. const MEDIA = (() => {
  441. const CLASS_MEDIA_EXPANDED = 'redditmod-media-expanded',
  442. CLASS_COMMENTS_EXPANDED = 'redditmod-comments-expanded',
  443. CLASS_MEDIABOX = 'redditmod-media-box',
  444. CLASS_COMMENTS = 'redditmod-comments-box',
  445. CLASS_MEDIA = 'redditmod-media',
  446. CLASS_SPINNER = 'redditmod-media-spinner',
  447. CLASS_ERROR = 'redditmod-media-error',
  448. MEDIA_STYLE_ID = 'redditmod-media-style',
  449. MEDIA_STYLE_CSS = '.redditmod-media-box, .redditmod-comments-box{max-height:0; height:0; overflow:hidden; transition: height linear 0.2s, max-height linear 0.2s}' +
  450. '.redditmod-media{}' + // ???
  451. '.redditmod-media-expanded .redditmod-media-box, .redditmod-comments-expanded .redditmod-comments-box{max-height:10000px; height:auto}' +
  452. '.redditmod-media-spinner,.redditmod-media-spinner:after{border-radius:50%;width:10em;height:10em}.redditmod-media-spinner{margin:60px auto;font-size:10px;position:relative;text-indent:-9999em;border-top:1.1em solid rgba(255,255,255,.2);border-right:1.1em solid rgba(255,255,255,.2);border-bottom:1.1em solid rgba(255,255,255,.2);border-left:1.1em solid #fff;-webkit-transform:translateZ(0);-ms-transform:translateZ(0);transform:translateZ(0);-webkit-animation:load8 1.1s infinite linear;animation:load8 1.1s infinite linear}@-webkit-keyframes load8{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes load8{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}' +
  453. '.redditmod-media-error{background-color:rgba(255,0,0,0.3); color:#fff; text-shadow:1px 1px #000}';
  454.  
  455. CSS.applyStyle(MEDIA_STYLE_ID, MEDIA_STYLE_CSS);
  456.  
  457. return {postClick};
  458.  
  459. function postClick(thing, event) {
  460. const target = event.target;
  461. const thingAnchor = thing.querySelector('a.title');
  462. const thingHref = thing.getAttribute('data-url');
  463. const thingUrl = thingHref || thingAnchor && thingAnchor.href;
  464.  
  465. if (!thing.classList.contains('redditmod-visited')) {
  466. thing.classList.add('redditmod-visited');
  467. CONFIG.then(config => config.addVisitedThing(thing.dataset.fullname));
  468. }
  469.  
  470. if (target.tagName === 'A' && target.classList.contains('comments')) {
  471. stopEvent(event);
  472. _fetchCommentsbox(thing, target.href)._toggle();
  473. return false;
  474.  
  475. } else if (_shouldUseExpando(thing, thingUrl)) {
  476. if (!target.classList.contains('expando-button')) {
  477. const expandoButton = thing.querySelector('.expando-button');
  478. if (expandoButton) {
  479. expandoButton.click(event);
  480. }
  481. }
  482. return true;
  483.  
  484. } else if ((target.tagName === 'A') ||
  485. (target.tagName === 'VIDEO' && target.controls === 'true') ||
  486. (target.classList.contains('expando-button'))) {
  487. return true; // Pass-through
  488.  
  489. } else {
  490. _fetchMediabox(thing, thingUrl).click(event); // Fetch/Contruct mediabox & click it.
  491. return false;
  492. }
  493. }
  494.  
  495. function _shouldUseExpando(thing, thingUrl) {
  496. if (!thing.querySelector('.expando-button')) {
  497. return false;
  498. } else if (thing.classList.contains('self')) {
  499. return true;
  500. } else if (/https?:\/\/(\w+\.)*(v\.redd\.it|clips\.twitch\.tv|reddituploads\.com|vimeo\.com|youtube\.com|youtu\.be)\/.*$/.test(thingUrl)) {
  501. return true;
  502. } else {
  503. return false;
  504. }
  505. }
  506.  
  507. function _fetchCommentsbox(thing, thingUrl) {
  508. const existing = thing.querySelector('.' + CLASS_COMMENTS);
  509. if (existing) {
  510. return existing;
  511. }
  512.  
  513. const commentsBox = _create('div', {className:CLASS_COMMENTS}, thing);
  514. commentsBox.onclick = stopEvent;
  515. commentsBox._toggle = () => {
  516. thing.classList.remove(CLASS_MEDIA_EXPANDED);
  517. thing.classList.toggle(CLASS_COMMENTS_EXPANDED);
  518. };
  519.  
  520. const spinner = _create('div', {className:CLASS_SPINNER}, commentsBox);
  521. RedditCommentsPromise(thingUrl)
  522. .then(container => {
  523. commentsBox.removeChild(spinner);
  524. commentsBox.appendChild(container);
  525. }).catch(reason => {
  526. debug('RedditCommentsPromise rejected, reason:', reason);
  527. });
  528.  
  529. return commentsBox;
  530. }
  531.  
  532. function _fetchMediabox(thing, thingUrl) {
  533. // Use existing mediabox
  534. const existingMediabox = thing.querySelector('.' + CLASS_MEDIABOX);
  535. if (existingMediabox) return existingMediabox;
  536.  
  537. // Create a custom mediabox
  538. const mediaBox = _create('div', {className:CLASS_MEDIABOX}, thing);
  539. mediaBox.onclick = event => {
  540. stopEvent(event);
  541. thing.classList.remove(CLASS_COMMENTS_EXPANDED);
  542. thing.classList.toggle(CLASS_MEDIA_EXPANDED);
  543. const media = thing.querySelector('.' + CLASS_MEDIA);
  544. if (thing.classList.contains(CLASS_MEDIA_EXPANDED)) {
  545. if (media && media._onshow) media._onshow();
  546. } else {
  547. if (media && media._onhide) media._onhide();
  548. }
  549. CONFIG.then(config => {
  550. if (config.isTweakEnabled('autoAlign')) {
  551. thing.scrollIntoView({block: 'start', inline: 'nearest', behavior:'smooth'});
  552. }
  553. })
  554. };
  555.  
  556. const spinner = _create('div', {className:CLASS_SPINNER}, mediaBox);
  557.  
  558. mediaBoxPromise(thingUrl)
  559. .then(media => {
  560. media.classList.add(CLASS_MEDIA);
  561. mediaBox.removeChild(spinner);
  562. mediaBox.appendChild(media);
  563. }).catch(reason => {
  564. debug('mediaboxPromise rejected, reason:', reason);
  565. mediaBox.removeChild(spinner);
  566. const errorBox = _create('div', {className:CLASS_ERROR}, mediaBox);
  567. errorBox.textContent = reason;
  568. });
  569. return mediaBox;
  570. }
  571.  
  572. function mediaBoxPromise(urlText) {
  573. return new Promise((resolve, reject) => {
  574. const url = new URL(urlText);
  575. const domain = url.hostname.replace(/^(?:.*\.)?(\w+\.\w+)$/, '$1');
  576. let promise;
  577. switch(domain) {
  578. case 'imgur.com': promise = ImgurMediaPromise(url); break;
  579. case 'gfycat.com': promise = GfycatMediaPromise(url); break;
  580. case 'soundcloud.com': promise = SoundcloudPromise(url); break;
  581. case 'explosm.net': promise = ExplosmPromise(url); break;
  582. case 'imgflip.com': promise = ImgflipPromise(url); break;
  583. case 'streamable.com': promise = StreamablePromise(url); break;
  584. case 'instagram.com': promise = InstagramPromise(url); break;
  585. case 'deviantart.com': promise = DeviantartPromise(url); break;
  586. case 'xkcd.com': promise = XkcdPromise(url); break;
  587. case 'reddit.com': promise = RedditPromise(url); break;
  588. default: promise = GenericMediaPromise(url); break;
  589. }
  590. promise.then(resolve).catch(reject);
  591. });
  592. }
  593.  
  594. function _create(tag, props, parentNode) {
  595. const node = document.createElement(tag);
  596. if (props) {
  597. Object.assign(node, props);
  598. }
  599. if (parentNode) {
  600. parentNode.appendChild(node);
  601. }
  602. return node;
  603. }
  604.  
  605. function _getJSON(url, headers) {
  606. return new Promise((resolve, reject) => {
  607. if (!headers) {
  608. headers = {'Accept': 'application/json'};
  609. } else if (!headers.Accept) {
  610. headers.Accept = 'application/json';
  611. }
  612. _getWEB(url, headers)
  613. .then(responseText => {
  614. try {
  615. resolve(JSON.parse(responseText));
  616. } catch (err) {
  617. debug('_getJSON error. url:', url.toString(), 'responseText', responseText);
  618. reject('[MEDIA._getJSON] Error parsing JSON text from ' + url.toString() + ' : ' + responseText);
  619. }
  620. })
  621. .catch(reason => {
  622. reject('[Media._getJSON] Error fetching JSON from url ' + url.toString() + ' reason: ' + reason);
  623. });
  624. });
  625. }
  626.  
  627. function _getWEB(url, headers) {
  628. return new Promise(function(resolve, reject) {
  629. if (!headers) {
  630. headers = {};
  631. }
  632. debug('MEDIA._getWEB() fetching url:', url, 'with headers', headers);
  633. const xhr = new XMLHttpRequest();
  634. xhr.onload = function(response) {
  635. debug('MEDIA._getWEB() got response (' + response.target.responseText.length.toLocaleString() + ' bytes)');
  636. resolve(response.target.responseText);
  637. };
  638. xhr.onerror = onError;
  639. xhr.onabort = onError;
  640. xhr.open('GET', url, true);
  641. Object.keys(headers).forEach(key => {
  642. xhr.setRequestHeader(key, headers[key]);
  643. });
  644. xhr.send(null);
  645. /*
  646. GM.xmlHttpRequest({
  647. method: 'GET',
  648. url: url,
  649. headers: headers,
  650. onabort: onError,
  651. onerror: onError,
  652. onload: function(response) {
  653. debug('MEDIA._getWEB() got response (' + response.responseText.length.toLocaleString() + ' bytes)');
  654. resolve(response.responseText);
  655. }
  656. });
  657. */
  658. function onError(reason) {
  659. debug('MEDIA._getWEB error. url:', url.toString(), 'reason:', reason);
  660. reject('[MEDIA._getWEB] Error fetching data from ' + url + ' Reason: ' + reason.error);
  661. }
  662. });
  663. }
  664.  
  665. function _getDocument(url, headers) {
  666. return new Promise((resolve, reject) => {
  667. _getWEB(url, headers)
  668. .then(responseText => {
  669. const html = document.createElement('html');
  670. html.innerHTML = responseText;
  671. resolve(html);
  672. })
  673. .catch(reject);
  674. });
  675. }
  676.  
  677. function GenericMediaPromise(url) {
  678. return new Promise((resolve, reject) => {
  679. const urlText = url.toString();
  680. if (/\.(jpe?g|gif|png|mp4)(\?.*)?$/i.test(urlText)) {
  681. GenericImagePromise([urlText]).then(resolve).catch(reject);
  682. } else {
  683. PostlightMediaPromise(urlText).then(resolve).catch(reject);
  684. }
  685. });
  686. }
  687.  
  688. function PostlightMediaPromise(url) {
  689. return new Promise((resolve, reject) => {
  690. const postlightUrl = 'https://mercury.postlight.com/parser?url=' + encodeURIComponent(url);
  691. const headers = {'X-api-key': 'NtFdFjTYzQXF4WUWBivfsnTj0zXZyvwCKbSQeuAB'};
  692. _getJSON(postlightUrl, headers)
  693. .then(resp => {
  694. if (resp.content === '<body></body>') {
  695. reject('[PostlightMediaProimse] Postlight returned empty content for ' + url);
  696. } else {
  697. resolve(_create('div', {innerHTML:resp.content, className:'redditmod-media-other'}));
  698. }
  699. })
  700. .catch(reject);
  701. });
  702. }
  703.  
  704. function GenericImagePromise(urls) {
  705. return new Promise((resolve, reject) => {
  706. if (urls.length === 0) {
  707. debug('GenericImagePromise error. No URLs given:', urls);
  708. reject('[GenericImagePromise] No URLs given');
  709. return;
  710. }
  711. let index = 0;
  712. const container = _create('div');
  713. const nav = _create('div', {}, container);
  714. const navPrev = _create('a', {textContent:'<',href:'#'}, nav);
  715. const navCurrent = _create('span', {textContent:'1'}, nav);
  716. const navSep = _create('span', {textContent:'/'}, nav);
  717. const navTotal = _create('span', {textContent:urls.length}, nav);
  718. const navNext = _create('a', {textContent:'>',href:'#'}, nav);
  719. const imageDiv = _create('div', {}, container);
  720. const image = _create('img', {
  721. src: urls[0],
  722. style: 'max-width:100%; max-height:100%; object-fit:scale-down'
  723. }, imageDiv);
  724. if (urls.length === 1) {
  725. nav.style.display = 'none';
  726. } else {
  727. container._click = navNext.click;
  728. }
  729. navPrev.onclick = event => {
  730. stopEvent(event);
  731. if (--index < 0) index = urls.length - 1;
  732. navCurrent.textContent = (index + 1).toString().padStart(urls.length.toString().length, '0');
  733. image.removeAttribute('src');
  734. image.src = urls[index];
  735. return false;
  736. };
  737. navNext.onclick = event => {
  738. stopEvent(event);
  739. if (++index === urls.length) index = 0;
  740. navCurrent.textContent = (index + 1).toString().padStart(urls.length.toString().length, ' ');
  741. image.removeAttribute('src');
  742. setTimeout(() => image.src = urls[index], 10);
  743. return false;
  744. };
  745. resolve(container);
  746. });
  747. }
  748.  
  749. function GenericVideoPromise(urls) {
  750. return new Promise(resolve => {
  751. const video = _create('video', {
  752. controls: false,
  753. autoplay: true,
  754. loop: true,
  755. style: 'display:block; width:' + (window.innerWidth-75) + 'px; height:' + (window.innerHeight-75) + 'px',
  756. });
  757. video._onhide = video.pause;
  758. video._onshow = video.load;
  759. urls.forEach(url => _create('source', {src:url}, video));
  760. resolve(video);
  761. });
  762. }
  763.  
  764. function ImgurMediaPromise(url) {
  765. return new Promise((resolve, reject) => {
  766. let urlText = url.toString();
  767. const albumIdMatches = urlText.match(/imgur\.com\/(?:gallery|a|r\/[^\/]+)\/(\w+)/i);
  768. debug('ImgurMediaPromise: url: ' + url + ', albumIdMatches:', albumIdMatches);
  769. if (albumIdMatches) {
  770. // Album: Extract images
  771. _getJSON('https://imgur.com/ajaxalbums/getimages/' + albumIdMatches[1] + '/hit.json')
  772. .then(resp => {
  773. if (!resp.data.images) {
  774. debug('ImgurMediaPromise: No resp.data.images, assuming single image:', albumIdMatches[1] + '.jpg');
  775. GenericImagePromise(['https://i.imgur.com/' + albumIdMatches[1] + '.jpg']).then(resolve).catch(reject);
  776. } else {
  777. debug('ImgurMediaPromise: Got ' + resp.data.images.length + ' images from album');
  778. GenericImagePromise(resp.data.images.map(image => 'https://i.imgur.com/' + image.hash + image.ext)).then(resolve).catch(reject);
  779. }
  780. });
  781. } else if (/\.(gifv?|mp4)$/.test(url)) {
  782. // Video
  783. debug('ImgurMediaPromise: gifv/mp4');
  784. urlText = urlText.replace(/\.gifv?$/, '.mp4');
  785. GenericVideoPromise([urlText]).then(resolve).catch(reject);
  786. } else {
  787. // Image?
  788. urlText = urlText.replace(/[^/]*\.imgur\.com/, 'i.imgur.com');
  789. urlText = urlText.replace(/\/\w+\//, '');
  790. urlText = urlText.replace(/_[a-z]\./, '.');
  791. urlText = urlText.replace(/\.(gif|jpg|jpeg|png)$/i, '');
  792. urlText = urlText + '.jpg';
  793. debug('ImgurMediaPromise: Unknown type, generated/mangled URL:', urlText);
  794. GenericImagePromise([urlText]).then(resolve).catch(reject);
  795. }
  796. });
  797. }
  798.  
  799. function GfycatMediaPromise(url) {
  800. return new Promise((resolve, reject) => {
  801. let gfycatUrl = url.href;
  802. const shortCode = url.href.match(/gfycat\.com\/(?:.*\/)?([a-z0-9]*)/i);
  803. if (shortCode) {
  804. gfycatUrl = 'https://gfycat.com/' + shortCode[1];
  805. }
  806. _getDocument(gfycatUrl)
  807. .then(doc => {
  808. let video = doc.querySelector('#mp4Source');
  809. if (!video) {
  810. video = doc.querySelector('.video.media source[type="video/mp4"]');
  811. }
  812. if (!video || !video.src) {
  813. reject('[GfycatMediaPromise] Could not find video at ' + gfycatUrl + ' body: ' + doc.innerHTML);
  814. } else {
  815. GenericVideoPromise([video.src]).then(resolve);
  816. }
  817. })
  818. .catch(reject);
  819. });
  820. }
  821.  
  822. function RedditPromise(url) {
  823. const urlText = url.toString();
  824. return new Promise((resolve, reject) => {
  825. if (/reddit\.com.*\/comments\/.*/.test(urlText)) {
  826. RedditCommentsPromise(urlText).then(resolve).catch(reject);
  827. } else {
  828. debug('RedditPromise error. Unable to load non-comments Reddit page', urlText);
  829. reject('[RedditPromise] Unable to load non-comments Reddit page ' + urlText);
  830. }
  831. });
  832. }
  833.  
  834. function RedditCommentsPromise(url) {
  835. return new Promise((resolve, reject) => {
  836. _getDocument(url)
  837. .then(doc => {
  838. const commentArea = doc.querySelector('.commentarea .sitetable');
  839. const container = _create('div', {className:'redditmod-media-comments-area'});
  840. commentArea.querySelectorAll('.entry').forEach(entry => {
  841. entry.onclick = event => {
  842. if (event && event.target && event.target.tagName === 'A') {
  843. return true; // Pass-through
  844. } else {
  845. // Expand/collapse comment tree
  846. stopEvent(event);
  847. entry.querySelector('a.expand').click();
  848. return false;
  849. }
  850. };
  851. });
  852. container.appendChild(commentArea);
  853. container._click = () => {};
  854. resolve(container);
  855. })
  856. .catch(reject);
  857. });
  858. }
  859.  
  860. function SoundcloudPromise(url) {
  861. return new Promise((resolve, reject) => {
  862. _getWEB(url.toString())
  863. .then(responseText => {
  864. let matches = responseText.match(/meta itemprop="embedUrl" content="([^"]*)"/);
  865. if (!matches) {
  866. matches = responseText.match(/meta property="twitter:player" content="([^"]*)"/);
  867. }
  868. if (matches && matches.length > 0) {
  869. const iframe = _create('iframe', {
  870. style: 'width:100%; height:' + (window.innerHeight / 2) + 'px',
  871. src: matches[1]
  872. });
  873. resolve(iframe);
  874. } else {
  875. reject('[SoundcloudPromise] No soundcloud data found at ' + url.toString());
  876. }
  877. })
  878. .catch(reject);
  879. });
  880. }
  881.  
  882. function ExplosmPromise(url) {
  883. return new Promise(function(resolve, reject) {
  884. _getDocument(url.toString())
  885. .then(doc => {
  886. const imageMeta = doc.querySelector('img#main-comic');
  887. if (imageMeta) {
  888. GenericImagePromise([imageMeta.src]).then(resolve, reject);
  889. } else {
  890. reject('[ExplosmPromise] No images found at ' + url.toString());
  891. }
  892. })
  893. .catch(reject);
  894. });
  895. }
  896.  
  897. function ImgflipPromise(url) {
  898. return new Promise(function(resolve, reject) {
  899. const urlText = url.toString();
  900. if (/\.(jpg|jpeg|png)$/i.test(urlText)) {
  901. GenericImagePromise([urlText]).then(resolve).catch(reject);
  902. }
  903. _getDocument(urlText)
  904. .then(doc => {
  905. const imageMeta = doc.querySelector('img#im');
  906. if (imageMeta) {
  907. GenericImagePromise([imageMeta.src]).then(resolve, reject);
  908. } else {
  909. reject('[ImgflipPromise] No images found at ' + urlText);
  910. }
  911. })
  912. .catch(reject);
  913. });
  914. }
  915.  
  916. function StreamablePromise(url) {
  917. return new Promise((resolve, reject) => {
  918. const matches = url.href.match(/streamable\.com\/([a-zA-Z0-9]*)/);
  919. if (!matches) reject('[StreamablePromise] No Streamable ID found in url ' + url.toString());
  920. const apiUrl = 'https://api.streamable.com/videos/' + matches[1];
  921. _getJSON(apiUrl)
  922. .then(json => {
  923. GenericVideoPromise([json.files.mp4.url]).then(resolve, reject);
  924. }).catch(reject);
  925. });
  926. }
  927.  
  928. function InstagramPromise(url) {
  929. const urlText = url.toString();
  930. const matches = urlText.match(/instagram\.com\/p\/([a-zA-Z0-9_\-]*)/);
  931. if (!matches) reject('[InstagramPromise] InstagramPromise error. No images found at', urlText);
  932. const apiUrl = 'https://instagram.com/p/' + matches[1] + '/';
  933. return new Promise((resolve, reject) => {
  934. _getDocument(apiUrl).then(doc => {
  935. const videoMeta = doc.querySelector('meta[property="og:video"]');
  936. const imageMeta = doc.querySelector('meta[property="og:image"]');
  937. if (videoMeta) {
  938. GenericVideoPromise([videoMeta.content]).then(resolve, reject);
  939. } else if (imageMeta) {
  940. GenericImagePromise([imageMeta.content]).then(resolve, reject);
  941. } else {
  942. reject('[InstagramPromise] Error: No images found at ' + apiUrl);
  943. }
  944. }).catch(reject);
  945. });
  946. }
  947.  
  948. function DeviantartPromise(url) {
  949. return new Promise(function(resolve, reject) {
  950. _getDocument(url.toString()).then(doc => {
  951. const fullImg = doc.querySelector('img[dev-content-full]');
  952. const smallImg = doc.querySelector('meta[property="og:image"]');
  953. if (fullImg) {
  954. GenericImagePromise([fullImg.src]).then(resolve, reject);
  955. } else if (smallImg) {
  956. GenericImagePromise([smallImg.content]).then(resolve, reject);
  957. } else {
  958. reject('[DeviantartPromise] Error: No images found at ' + url.toString());
  959. }
  960. }).catch(reject);
  961. });
  962. }
  963.  
  964. function XkcdPromise(url) {
  965. return new Promise((resolve, reject) => {
  966. const matches = url.href.match(/xkcd\.com\/([0-9]+)/);
  967. if (matches) {
  968. _getJSON("https://xkcd.com/" + matches[1] + "/info.0.json").then(json => {
  969. const xkcdDiv = document.createElement("div");
  970. const h3 = document.createElement("h3");
  971. const img = document.createElement("img");
  972. const h5 = document.createElement("h5");
  973. h3.textContent = json.title;
  974. img.src = json.img;
  975. img.title = json.alt;
  976. h5.textContent = json.alt;
  977. xkcdDiv.appendChild(h3);
  978. xkcdDiv.appendChild(img);
  979. xkcdDiv.appendChild(h5);
  980. resolve(xkcdDiv);
  981. }).catch(reject)
  982. } else if (/\.(png|gif|jpe?g)$/i.test(url.href)) {
  983. GenericImagePromise([url.toString()]).then(resolve).catch(reject);
  984. } else {
  985. reject('Failed to find XKCD metadata from ' + url.toString());
  986. }
  987. });
  988. }
  989. })();
  990.  
  991. function Filters(config, menuPromise) {
  992. const CLASS_PROCESSED = 'redditmod-thing-processed';
  993. const CLASS_FILTERED = 'redditmod-thing-filtered';
  994.  
  995. // CSS specific to filtering
  996. const CSS_FILTER = '' +
  997. '.redditmod-thing-filtered {' +
  998. 'margin:0!important;' +
  999. 'padding:0!important;' +
  1000. 'max-height:0!important;' +
  1001. 'overflow:hidden!important;' +
  1002. 'background-color:var(--bg)' +
  1003. '}' +
  1004. '.thing {' +
  1005. 'transition:background-color linear 0.2s' +
  1006. '}' +
  1007. '.redditmod-filter-subreddit-button {' +
  1008. 'border:none;' +
  1009. 'background-color:var(--fg-link);' +
  1010. 'color:var(--bg)!important;' +
  1011. 'font-weight:900;' +
  1012. 'border-radius:15px;' +
  1013. 'padding:0 1.9px .5px;' +
  1014. 'margin-left:5px' +
  1015. '}' +
  1016. '.redditmod-filter-subreddit-button:hover {' +
  1017. 'text-decoration:none!important;' +
  1018. 'box-shadow: 0 0 5px rgba(0,0,0,0.5)' +
  1019. '}';
  1020.  
  1021. // Only apply filters on URLs that match:
  1022. const URL_FILTER_REGEX = /^.*\/r\/(all|popular)\/.*$/i;
  1023. const filters = {};
  1024.  
  1025. return new Promise(resolve => {
  1026. CSS.applyStyle('redditmod-thing-style', CSS_FILTER);
  1027. menuPromise.then(menu => {
  1028. filters.nsfw = NsfwFilter(menu);
  1029. filters.text = TextFilter(menu);
  1030. filters.subreddit = SubredditFilter(menu);
  1031. processPosts();
  1032. resolve({filters, processPost, processPosts});
  1033. });
  1034. });
  1035.  
  1036. function processPosts() {
  1037. document.querySelectorAll('#siteTable .thing').forEach(thing => processPost(thing));
  1038. }
  1039.  
  1040. function processPost(thing) {
  1041. if (!thing.classList.contains(CLASS_PROCESSED)) {
  1042. thing.classList.add(CLASS_PROCESSED);
  1043. filters.subreddit.addFilterButton(thing);
  1044.  
  1045. // Hide/Show media when post is clicked
  1046. thing.addEventListener('click', event => MEDIA.postClick(thing, event));
  1047.  
  1048. // Visited
  1049. if (config.isVisited(thing.dataset.fullname)) {
  1050. thing.classList.add('redditmod-visited');
  1051. }
  1052.  
  1053. // Remove tracking from links if user did not specify in preferences.
  1054. thing.querySelectorAll('a[data-outbound-url], a[data-outbound-expiration], a[data-inbound-url]')
  1055. .forEach(anchor => {
  1056. if (anchor.dataset) {
  1057. if (anchor.dataset.outboundUrl) delete anchor.dataset.outboundUrl;
  1058. if (anchor.dataset.outboundExpiration) delete anchor.dataset.outboundExpiration;
  1059. if (anchor.dataset.inboundUrl) delete anchor.dataset.inboundUrl;
  1060. }
  1061. });
  1062. }
  1063.  
  1064. if (_shouldFilterThisPage()) {
  1065. const reasons = [];
  1066. const activeFilters = Object.entries(filters).map(
  1067. ([name, filter]) => {
  1068. const filterReason = filter.shouldFilter(thing);
  1069. if (filterReason !== false) {
  1070. reasons.push(filterReason);
  1071. }
  1072. });
  1073.  
  1074. if (reasons.length > 0 && !thing.classList.contains(CLASS_FILTERED)) {
  1075. thing.classList.add(CLASS_FILTERED);
  1076. } else if (reasons.length === 0 && thing.classList.contains(CLASS_FILTERED)) {
  1077. thing.classList.remove(CLASS_FILTERED);
  1078. }
  1079. }
  1080. }
  1081.  
  1082. function _shouldFilterThisPage() {
  1083. return URL_FILTER_REGEX.test(window.location.pathname);
  1084. }
  1085.  
  1086. ///////////////////////////////////////////
  1087. function NsfwFilter(menu) {
  1088. updateMenu();
  1089. return {shouldFilter};
  1090.  
  1091. function shouldFilter(thing) {
  1092. const state = config.getNsfwState();
  1093. const isOver18 = thing.classList.contains('over18');
  1094. let reason = false;
  1095. if (state === 'hide' && isOver18) {
  1096. reason = 'NSFW';
  1097. } else if (state === 'always' && !isOver18) {
  1098. reason = 'Not NSFW';
  1099. }
  1100. return reason;
  1101. }
  1102.  
  1103. function updateMenu() {
  1104. const submenus = [_nsfwMenu('hide'), _nsfwMenu('show'), _nsfwMenu('always')];
  1105. menu.updateMenuSection('nsfw filter', 'redditmod-menu-filter-nsfw', submenus);
  1106. }
  1107.  
  1108. // `verb` is either "hide" or "show"
  1109. function _nsfwMenu(state) {
  1110. const currentState = config.getNsfwState();
  1111. const isChecked = currentState === state;
  1112.  
  1113. let msg;
  1114. switch (state) {
  1115. case 'hide':
  1116. msg = 'hide all nsfw posts';
  1117. break;
  1118. case 'show':
  1119. msg = 'allow nsfw posts';
  1120. break;
  1121. case 'always':
  1122. msg = 'only show nsfw posts';
  1123. break;
  1124. }
  1125. return {
  1126. href:'#',
  1127. innerHTML: (isChecked ? '&#9745; ' : '&#9744; ') + msg,
  1128. onclick: _onNsfwMenuClick
  1129. };
  1130. function _onNsfwMenuClick(event) {
  1131. stopEvent(event);
  1132. config.setNsfwState(state);
  1133. updateMenu();
  1134. processPosts();
  1135. }
  1136. }
  1137. }
  1138.  
  1139. ///////////////////////////////////////////
  1140. function SubredditFilter(menu) {
  1141. updateMenu();
  1142. return {shouldFilter, addFilterButton};
  1143.  
  1144. function addFilterButton(thing) {
  1145. const subreddit = thing && thing.dataset && thing.dataset.subreddit;
  1146. const subredditLink = thing.querySelector('a.subreddit');
  1147. if (!subreddit || !subredditLink) return;
  1148. const filterButton = document.createElement('a');
  1149. Object.assign(filterButton, {
  1150. innerHTML: '&times;',
  1151. href: '#',
  1152. className: 'redditmod-filter-subreddit-button',
  1153. title: 'Filter /r/' + subreddit + ' from appearing',
  1154. onclick: event => _toggleSubreddit(subreddit, event)
  1155. });
  1156. subredditLink.parentNode.appendChild(filterButton);
  1157. }
  1158.  
  1159. function shouldFilter(thing) {
  1160. let reason = false;
  1161. if (config.isSubredditFiltered(thing.dataset.subreddit)) {
  1162. reason = 'SUBREDDIT';
  1163. }
  1164. return reason;
  1165. }
  1166.  
  1167. function updateMenu() {
  1168. const subreddits = config.getSubreddits();
  1169. const submenus = subreddits.map(subreddit => _subredditMenuProps(subreddit));
  1170. submenus.unshift({
  1171. textContent: 'select none',
  1172. onclick: event => _toggleAllSubreddits(false, event)
  1173. });
  1174. submenus.unshift({
  1175. textContent: 'select all',
  1176. onclick: event => _toggleAllSubreddits(true, event)
  1177. });
  1178. menu.updateMenuSection(
  1179. 'filtered subreddits (' + subreddits.length + ')',
  1180. 'redditmod-menu-filter-subreddits',
  1181. submenus);
  1182. }
  1183.  
  1184. function refresh() {
  1185. updateMenu();
  1186. processPosts();
  1187. }
  1188.  
  1189. function _toggleSubreddit(subreddit, event) {
  1190. stopEvent(event);
  1191. const enabled = !config.isSubredditFiltered(subreddit);
  1192. config.setSubredditFilter(subreddit, enabled).then(refresh);
  1193. }
  1194.  
  1195. function _toggleAllSubreddits(enabled, event) {
  1196. stopEvent(event);
  1197. config.setAllSubredditFilters(enabled).then(refresh);
  1198. }
  1199.  
  1200. function _subredditMenuProps(subreddit) {
  1201. return {
  1202. innerHTML: (config.isSubredditFiltered(subreddit) ? '&#9745; ' : '&#9744; ') + subreddit,
  1203. onclick: event => _toggleSubreddit(subreddit, event)
  1204. };
  1205. }
  1206. }
  1207.  
  1208. ///////////////////////////////////////////
  1209. function TextFilter(menu) {
  1210. updateMenu();
  1211. return {shouldFilter};
  1212.  
  1213. function shouldFilter(thing) {
  1214. let reason = false;
  1215. const title = thing.querySelector('a.title');
  1216. if (title) {
  1217. reason = config.shouldFilterTextblock(title.textContent);
  1218. }
  1219. return reason;
  1220. }
  1221.  
  1222. function updateMenu() {
  1223. const texts = config.getTexts();
  1224. const submenus = texts.map(text => _textMenuProps(text));
  1225. submenus.unshift({
  1226. textContent: 'add a text filter',
  1227. onclick: _addTextFilter
  1228. });
  1229. menu.updateMenuSection('filtered text (' + texts.length + ')', 'redditmod-menu-filter-texts', submenus);
  1230. }
  1231.  
  1232. function refresh() {
  1233. updateMenu();
  1234. processPosts();
  1235. }
  1236.  
  1237. function _addTextFilter(event) {
  1238. stopEvent(event);
  1239. const text = prompt(
  1240. '"Text Filter" will hide reddit posts that contain a word or phrase in the post title.' +
  1241. '\n\nYou can enter multiple words/phrases by separating them with a Comma ( , )' +
  1242. '\n\n(Text-matching is case-insensitive)' +
  1243. '\n\nEnter text to filter:', 'Example: trump, sanders, clinton');
  1244. if (text === null) return;
  1245. text.split(/\s*,\s/).forEach(word => {
  1246. config.setTextFilter(word.toLowerCase(), true);
  1247. });
  1248. refresh();
  1249. }
  1250.  
  1251. function _textMenuProps(text) {
  1252. return {
  1253. innerHTML: (config.isTextFiltered(text) ? '&#9745; ' : '&#9744; ') + text,
  1254. onclick: event => {
  1255. stopEvent(event);
  1256. _toggleText(text);
  1257. }
  1258. };
  1259. }
  1260.  
  1261. function _toggleText(text) {
  1262. const enabled = !config.isTextFiltered(text);
  1263. config.setTextFilter(text, enabled);
  1264. refresh();
  1265. }
  1266. }
  1267. }
  1268.  
  1269. function Navigation(filters) {
  1270. let loading = false;
  1271.  
  1272. CSS.onDOM().then(() => {
  1273. overrideNextButton();
  1274. scrollListener();
  1275. addScrollListener();
  1276. });
  1277.  
  1278. return {scrollListener, addScrollListener};
  1279.  
  1280. function scrollListener(event) {
  1281. const evt = event || {pageY:0};
  1282. if (document.body.clientHeight - (window.scrollY + window.innerHeight) < 200) {
  1283. CONFIG.then(config => {
  1284. if (config.isTweakEnabled('infiniteScrolling')) {
  1285. loadMorePosts();
  1286. }
  1287. });
  1288. }
  1289. }
  1290.  
  1291. function addScrollListener() { window.addEventListener('scroll', scrollListener); }
  1292. function removeScrollListener() { window.removeEventListener('scroll', scrollListener); }
  1293.  
  1294. function loadMorePosts() {
  1295. const nextButton = document.querySelector('.next-button a');
  1296. if (loading || !nextButton) {
  1297. return;
  1298. }
  1299.  
  1300. loading = true;
  1301. removeScrollListener();
  1302.  
  1303. debug('[Navigation.loadMorePosts] Fetching URL (via nextButton.href):', nextButton.href);
  1304. const xhr = new XMLHttpRequest();
  1305. xhr.onload = function(response) {
  1306. _injectPosts(response.target);
  1307. };
  1308. xhr.onerror = _onError;
  1309. xhr.onabort = _onError;
  1310. xhr.open('GET', nextButton.href, true);
  1311. xhr.send(null);
  1312. /*GM.xmlHttpRequest({
  1313. method: "GET",
  1314. url: nextButton.href,
  1315. onabort: _onError,
  1316. onerror: _onError,
  1317. onload: _injectPosts
  1318. });*/
  1319.  
  1320. const parentNode = nextButton.parentNode.parentNode;
  1321. parentNode.style.backgroundColor = '#aaa';
  1322. parentNode.opacity = '0.5';
  1323. parentNode.cursor = 'not-allowed';
  1324. parentNode.childNodes.forEach(child => {
  1325. if (child.style) {
  1326. child.style.display = 'none';
  1327. }
  1328. });
  1329.  
  1330. function _onError(response) {
  1331. debug('Navigation.loadMorePosts() error. url:', nextButton.href, 'response:', response);
  1332. const errDiv = document.createElement('div');
  1333. errDiv.className = 'redditmod-media-error';
  1334. errDiv.textContent = 'Navigation.loadMorePosts() error. URL: ' + nextButton.href + ' Reason: ' + (response.error || response.responseText);
  1335. nextButton.parentNode.parentNode.appendChild(errDiv);
  1336. }
  1337. }
  1338.  
  1339. function _injectPosts(response) {
  1340. debug('[Navigation.loadMorePosts._injectPosts] Got response (' + response.responseText.length.toLocaleString() + ' bytes)');
  1341. const previousNav = document.querySelector('.nav-buttons');
  1342. const html = document.createElement('html');
  1343. html.innerHTML = response.responseText;
  1344. html.querySelectorAll('#siteTable > *').forEach(thing => {
  1345. if (thing.classList.contains('clearleft')) return;
  1346. if (!thing.id) {
  1347. previousNav.parentNode.insertBefore(thing, previousNav);
  1348. } else if (!document.querySelector('#' + thing.id)) {
  1349. filters.processPost(thing);
  1350. previousNav.parentNode.insertBefore(thing, previousNav);
  1351. } else {
  1352. debug('[Navigation.loadMorePosts._injectPosts] Ignoring duplicate post. thing.id:', thing.id);
  1353. }
  1354. });
  1355. previousNav.parentNode.removeChild(previousNav);
  1356.  
  1357. // Re-enable features on the "new page".
  1358. overrideNextButton();
  1359. addScrollListener();
  1360. loading = false;
  1361. setTimeout(scrollListener, 250);
  1362. }
  1363.  
  1364. function overrideNextButton() {
  1365. const nextButton = document.querySelector('.next-button a');
  1366. if (!nextButton) return;
  1367. nextButton.addEventListener('click', event => {
  1368. CONFIG.then(config => {
  1369. if (config.isTweakEnabled('loadPostsInline')) {
  1370. stopEvent(event);
  1371. loadMorePosts();
  1372. }
  1373. });
  1374. });
  1375. }
  1376. }
  1377.  
  1378. function Tweaks(config, menuPromise) {
  1379. const TWEAK_STYLE_ID = 'redditmod-tweak-style';
  1380.  
  1381. return new Promise(resolve => {
  1382. // Apply tweaks CSS before MENU loads
  1383. _applyTweakCSS();
  1384.  
  1385. menuPromise.then(menu => {
  1386. updateMenu(menu);
  1387. resolve({
  1388. updateMenu: () => updateMenu(menu)
  1389. });
  1390. });
  1391. });
  1392.  
  1393. function _applyTweakCSS() {
  1394. CSS.applyStyle(TWEAK_STYLE_ID, config.getTweakCSS());
  1395. }
  1396.  
  1397. function _tweakLinkProps(tweak, menu) {
  1398. return {
  1399. innerHTML: (tweak.enabled ? '&#9745; ' : '&#9744; ') + tweak.name,
  1400. title: tweak.title,
  1401. onclick: event => {
  1402. stopEvent(event);
  1403. config.setTweak(tweak.id, !config.isTweakEnabled(tweak.id))
  1404. .then(() => {
  1405. _applyTweakCSS();
  1406. updateMenu(menu);
  1407. });
  1408. }
  1409. };
  1410. }
  1411.  
  1412. function updateMenu(menu) {
  1413. if (!menu) return;
  1414. menu.updateMenuSection(
  1415. 'tweaks', 'redditmod-menu-tweaks',
  1416. config.getTweaks().map(tweak => _tweakLinkProps(tweak, menu))
  1417. );
  1418. }
  1419. }
  1420.  
  1421. function Themes(config, menuPromise) {
  1422. const THEME_STYLE_ID = 'redditmod-theme-style';
  1423.  
  1424. return new Promise(resolve => {
  1425. // Apply theme CSS before MENU loads
  1426. applyThemeCSS();
  1427.  
  1428. menuPromise.then(menu => {
  1429. updateMenu(menu);
  1430. resolve({
  1431. applyThemeCSS,
  1432. updateMenu: () => updateMenu(menu)
  1433. });
  1434. });
  1435. });
  1436.  
  1437. function applyThemeCSS() {
  1438. CSS.applyStyle(THEME_STYLE_ID, config.getThemeCSS());
  1439. }
  1440.  
  1441. function updateMenu(menu) {
  1442. if (!menu) return;
  1443. const submenus = config.getThemes().map(themeName => ({
  1444. innerHTML: (config.getTheme() === themeName ? '&#9745; ' : '&#9744; ') + themeName,
  1445. onclick: event => {
  1446. stopEvent(event);
  1447. config.setTheme(themeName).then(() => {
  1448. applyThemeCSS();
  1449. updateMenu(menu);
  1450. });
  1451. }
  1452. }));
  1453. menu.updateMenuSection('themes', 'redditmod-menu-themes', submenus);
  1454. }
  1455. }
  1456.  
  1457. //debug('Startup: config');
  1458. CONFIG.then(config => {
  1459. //debug('Startup: menuPromise (config:', config, ')');
  1460. const menuPromise = MENU.init(config);
  1461.  
  1462. //debug('Startup: theme, tweak, & filters (menuPromise:', menuPromise, ')');
  1463. Promise.all([
  1464. Themes(config, menuPromise),
  1465. Tweaks(config, menuPromise),
  1466. Filters(config, menuPromise)
  1467. ]).then(([themes, tweaks, filters]) => {
  1468. //debug('Startup: navigation (themes:', themes, 'tweaks:', tweaks, 'filters', filters, ')');
  1469. const navigation = Navigation(filters);
  1470. //debug('Startup: COMPLETE (navigation:', navigation, ')');
  1471. });
  1472.  
  1473. });
  1474. })();