[Reddit] Modmail++

Additional tools and information to Reddit's Modmail

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

  1. // ==UserScript==
  2. // @name [Reddit] Modmail++
  3. // @namespace HKR
  4. // @match https://mod.reddit.com/mail/*
  5. // @grant none
  6. // @version 3.6
  7. // @author HKR
  8. // @description Additional tools and information to Reddit's Modmail
  9. // @icon https://www.redditstatic.com/modmail/favicon/favicon-32x32.png
  10. // @supportURL https://github.com/Hakorr/Userscripts/issues
  11. // @require https://cdn.jsdelivr.net/npm/party-js@2.1.2/bundle/party.js#sha256-J9/UDCn536lyy03NDKIUT6WX3DU9FqZZ9ydg++UVUC0=
  12. // ==/UserScript==
  13.  
  14. (() => {
  15. console.log("[Modmail++] %cScript started!", "color: green");
  16.  
  17. class __settings__ {
  18. subTag = $(".ThreadTitle__community")?.href?.slice(23) || "r/subreddit"; //Format r/subreddit
  19. userTag = "u/" + $(".InfoBar__username")?.innerText || "u/username"; //Format u/username
  20. modmail = `[modmail](https://www.reddit.com/message/compose?to=/${keepPrefix(this.subTag, true)})`;
  21. rules = `https://www.reddit.com/${keepPrefix(this.subTag, true)}/about/rules`;
  22. /* Responses - Edit to your own liking, remove whatever you don't like!
  23. - name | The name of the response that will show on the listbox. (Example value: "Hello!")
  24. - replace | Replace all messagebox text if true, otherwise just add. (Example value: true)
  25. - subreddit | Visible only while on this subreddit's modmail. (Example value: "r/subreddit")
  26. - content | This text will be added to the messagebox once selected (Example value: "Hello world!")*/
  27. responses = [
  28. {
  29. "name":"Default Approved",
  30. "replace":true,
  31. "subreddit":"",
  32. "content":`Hey, approved the post!`
  33. },
  34. {
  35. "name":"Default Rule Broken",
  36. "replace":true,
  37. "subreddit":"",
  38. "content":`Your post broke our [rules](${this.rules}).\n\nThe action will not be reverted.`
  39. },
  40. {
  41. "name":"Add Rule Description",
  42. "replace":false,
  43. "subreddit":"",
  44. "content":`<open-rulelist-dialog>`
  45. },
  46. {
  47. "name":"Add Greetings",
  48. "replace":false,
  49. "subreddit":"",
  50. "content":`${randItem(["Greetings","Hello","Hi"])} ${this.userTag},\n\n`
  51. },
  52. {
  53. "name":"Add Subreddit Mention",
  54. "replace":false,
  55. "subreddit":"",
  56. "content":`${this.subTag}`
  57. },
  58. {
  59. "name":"Add User Mention",
  60. "replace":false,
  61. "subreddit":"",
  62. "content":`${this.userTag}`
  63. },
  64. {
  65. "name":"Add Modmail Link",
  66. "replace":false,
  67. "subreddit":"",
  68. "content":`${this.modmail}`
  69. },
  70. {
  71. "name":"Add Karma Link",
  72. "replace":false,
  73. "subreddit":"",
  74. "content":`[karma](https://reddit.zendesk.com/hc/en-us/articles/204511829-What-is-karma-)`
  75. },
  76. {
  77. "name":"Add Shadowban Link",
  78. "replace":false,
  79. "subreddit":"",
  80. "content":`[shadowbanned](https://www.reddit.com/r/ShadowBan/comments/8a2gpk/an_unofficial_guide_on_how_to_avoid_being/)`
  81. },
  82. {
  83. "name":"Add Content Policy",
  84. "replace":false,
  85. "subreddit":"",
  86. "content":`[Content Policy](https://www.redditinc.com/policies/content-policy)`
  87. },
  88. {
  89. "name":"Add User Agreement",
  90. "replace":false,
  91. "subreddit":"",
  92. "content":`[User Agreement](https://www.redditinc.com/policies/user-agreement)`
  93. },
  94. {
  95. "name":"Add Reddiquette",
  96. "replace":false,
  97. "subreddit":"",
  98. "content":`[Reddiquette](https://reddit.zendesk.com/hc/en-us/articles/205926439-Reddiquette)`
  99. },
  100. {
  101. "name":"Add Admin Modmail",
  102. "replace":false,
  103. "subreddit":"",
  104. "content":`[Admins](https://www.reddit.com/message/compose?to=%2Fr%2Freddit.com)`
  105. },
  106. {
  107. "name":"Add Rickroll",
  108. "replace":false,
  109. "subreddit":"",
  110. "content":`[link](https://www.youtube.com/watch?v=dQw4w9WgXcQ)`
  111. },
  112. {
  113. "name":"Invitation (New Message)",
  114. "replace":true,
  115. "subreddit":"",
  116. "subject": `Invitation to become a moderator of ${this.subTag}`,
  117. "content":`${randItem(["Greetings","Hello","Hi"])} ${this.userTag},\n\nWould you like to moderate ${this.subTag} with us? Please let us know as soon as possible!`
  118. }
  119. ];
  120.  
  121. themeMode = $$(".theme-dark").length ? true : false;
  122. textColor = this.themeMode ? "#757575" : "#6e6e6e"; // dark hex : light hex
  123. titleColor = this.themeMode ? "#a7a7a7" : "#2c2c2c"; // dark hex : light hex
  124. listBoxColor = this.themeMode ? "#242424" : "#f1f3f5"; // dark hex : light hex
  125.  
  126. dataColor = "#0079d3"; // data (numbers etc.) color
  127.  
  128. enableCustomResponses = true; // if to append the custom response box
  129.  
  130. chatProfileIcons = true; // if to append chat profile icons
  131.  
  132. placeholderMessage = randItem([
  133. "Message...",
  134. "Look, a bird! Message...",
  135. "What have you been up to today? Message...",
  136. "Beautiful day, isn't it? Message...",
  137. "Was the weather nice? Message...",
  138. "You look good today! Message...",
  139. "What dreams did you see last night? Message...",
  140. "What did you do today? Message...",
  141. "What did you eat today? Message...",
  142. "Have you drank enough water? Message...",
  143. "Remember to stretch! Message...",
  144. "≖‿≖ I live inside of your walls. Message...",
  145. "(✿◠‿◠) Message...",
  146. ]);
  147. }
  148. /*/////////////////////////////////////////////////
  149. \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
  150. DO NOT PROCEED IF YOU DO NOT KNOW WHAT YOU'RE DOING
  151. ///////////////////////////////////////////////////
  152. \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
  153. const $ = document.querySelector.bind(document);
  154. const $$ = document.querySelectorAll.bind(document);
  155.  
  156. // returns a random item from array
  157. const randItem = itemArr => itemArr[Math.floor(Math.random() * itemArr.length)];
  158. // removes the Reddit prefix
  159. const removePrefix = username => ["r/","u/"].some(tag => username.includes(tag)) ? username.slice(2) : username;
  160. // adds the Reddit prefix if nonexistant
  161. const keepPrefix = (username, subreddit) => ["r/","u/"].some(tag => username.includes(tag)) ? username : subreddit ? `r/${username}` : `u/${username}`;
  162.  
  163. const recipientUsername = () => {
  164. const defaultUsernameElem = $(".InfoBar__username");
  165. const ModmailPlusPlusUsernameElem = $(".CustomInfoBar__username");
  166. if(defaultUsernameElem) {
  167. return removePrefix(defaultUsernameElem?.innerText);
  168. }
  169. else if (ModmailPlusPlusUsernameElem) {
  170. return removePrefix(ModmailPlusPlusUsernameElem?.innerText);
  171. }
  172. else {
  173. return undefined;
  174. }
  175. };
  176. async function Get(url) {
  177. const response = await fetch(url);
  178.  
  179. if (!response.ok) {
  180. throw new Error(`HTTP error! status: ${response.status}`);
  181. }
  182.  
  183. const text = await response.text();
  184. return text;
  185. };
  186.  
  187. async function getUserInfo() {
  188. try
  189. {
  190. const about = await Get(`https://www.reddit.com/user/${recipientUsername()}/about.json`);
  191. return JSON.parse(about);
  192. }
  193. catch
  194. {
  195. console.log("[Modmail++] %cFailed to load user information.", "color: red");
  196. return 0;
  197. }
  198. };
  199. async function getRules(Settings) {
  200. try
  201. {
  202. const rules = await Get(Settings.rules + ".json");
  203. return JSON.parse(rules);
  204. }
  205. catch
  206. {
  207. console.log("[Modmail++] %cFailed to load subreddit rules, possibly a private subreddit?", "color: red");
  208. return 0;
  209. }
  210. };
  211.  
  212. // adds a zero suffix if x < 10
  213. const fixNumber = number => number < 10 ? "0" + number : number;
  214.  
  215. // returns a date string from UNIX timestamp
  216. function unixToDate(UNIX_timestamp) {
  217. const d = new Date(UNIX_timestamp * 1000);
  218. const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  219.  
  220. const year = d.getFullYear(),
  221. monthNum = d.getMonth() + 1,
  222. month = months[d.getMonth()],
  223. date = d.getDate(),
  224. hour = fixNumber(d.getHours()),
  225. min = fixNumber(d.getMinutes()),
  226. sec = fixNumber(d.getSeconds());
  227.  
  228. return `${date}.${monthNum}.${year} ${hour}:${min}:${sec}`; // (DD/MM/YY HH/MM/SS)
  229. };
  230.  
  231. // returns a string without evil HTML elements
  232. function sanitize(evilstring) {
  233. const decoder = document.createElement('div');
  234. decoder.innerHTML = evilstring;
  235. return decoder.textContent;
  236. };
  237.  
  238. // add a link to the Modmail text and change its name to Modmail++
  239. const sidebarTitle = $(".Sidebar__titleMessage");
  240. sidebarTitle.setAttribute("onclick","window.open('https://github.com/Hakorr/Userscripts/tree/main/Reddit.com/ModmailExtraInfo')");
  241. sidebarTitle.setAttribute("style","cursor: pointer");
  242. sidebarTitle.innerText = "Modmail++";
  243.  
  244. // apply the custom css
  245. function applyCSS(Settings) {
  246. //Took advice for the listbox CSS from moderncss.dev/custom-select-styles-with-pure-css, thanks!
  247. const css = `.profileIcon:hover {
  248. -ms-transform: scale(6);
  249. -webkit-transform: scale(6);
  250. transform: scale(6);
  251. }
  252. .profileIcon {
  253. position: relative;
  254. bottom: 4px;
  255. margin-bottom: 10px;
  256. float: left; border-radius: 50%;
  257. transition: transform .1s;
  258. }
  259. .InfoBar__recentsNone {
  260. color: #6e6e6e;
  261. }
  262. .InfoBar__metadata, .InfoBar__recents {
  263. margin: 6px 0;
  264. margin-left: 10px;
  265. }
  266. .value {
  267. color: ${Settings.dataColor};
  268. }
  269. .InfoBar__banText {
  270. padding-bottom: 15px;
  271. }
  272. .InfoBar__username, .InfoBar__username:visited {
  273. padding-left: 10px;
  274. }
  275. .dataText {
  276. color: ${Settings.textColor};
  277. font-size: 13px;
  278. padding-left: 10px;
  279. }
  280. .dataTitle {
  281. color: ${Settings.titleColor};
  282. font-size: 15px;
  283. margin-bottom: 3px;
  284. margin-top: 5px;
  285. }
  286. .responseListbox {
  287. width: 50%;
  288. cursor: pointer;
  289. }
  290. :root {
  291. --select-border: #0079d3;
  292. --select-focus: blue;
  293. --select-arrow: var(--select-border);
  294. }
  295. *,
  296. *::before,
  297. *::after {
  298. box-sizing: border-box;
  299. }
  300. select {
  301. appearance: none;
  302. background-color: ${Settings.listBoxColor};
  303. color: ${Settings.textColor};
  304. border: none;
  305. padding: 0 1em 0 0;
  306. margin: 0;
  307. width: 100%;
  308. cursor: pointer;
  309. font-family: inherit;
  310. font-size: inherit;
  311. line-height: inherit;
  312. outline: none;
  313. position: relative;
  314. }
  315. .select {
  316. width: 100%;
  317. min-width: 15ch;
  318. max-width: 30ch;
  319. border: 1px solid var(--select-border);
  320. border-radius: 0.25em;
  321. padding: 0.3em 0.4em;
  322. font-size: 0.9rem;
  323. line-height: 1.1;
  324. background-color: ${Settings.listBoxColor};
  325. margin-bottom: 15px;
  326. }
  327. select::-ms-expand {
  328. display: none;
  329. }
  330. option {
  331. white-space: normal;
  332. outline-color: var(--select-focus);
  333. }
  334. select:focus + .focus {
  335. position: absolute;
  336. top: -1px;
  337. left: -1px;
  338. right: -1px;
  339. bottom: -1px;
  340. border: 2px solid var(--select-focus);
  341. border-radius: inherit;
  342. }
  343. .Author__text {
  344. padding: 6px 0;
  345. }
  346. .chatProfileIcon {
  347. margin-right: 7px;
  348. transition: transform .1s;
  349. border-radius: 50%;
  350. }
  351. .App__page {
  352. background: var(--color-tone-8);
  353. }
  354. ::-webkit-scrollbar {
  355. width: 10px;
  356. }
  357. ::-webkit-scrollbar-track {
  358. background: ${Settings.listBoxColor};
  359. }
  360. ::-webkit-scrollbar-thumb {
  361. background: #888;
  362. }
  363. ::-webkit-scrollbar-thumb:hover {
  364. background: #555;
  365. }
  366. .subredditRuleList {
  367. --newRedditTheme-bodyText: ${Settings.titleColor};
  368. --newRedditTheme-metaText: ${Settings.textColor};
  369. --newRedditTheme-navIconFaded10: rgba(215,218,220,0.1);
  370. --newRedditTheme-actionIconTinted80: #9a9b9c;
  371. --newRedditTheme-activeShaded90: #006cbd;
  372. --newRedditTheme-actionIconAlpha20: rgba(129,131,132,0.2);
  373. --newCommunityTheme-actionIcon: #818384;
  374. --newRedditTheme-bodyTextAlpha03: ${Settings.listBoxColor};
  375. --newRedditTheme-navIcon: #D7DADC;
  376. --newCommunityTheme-line: #343536;
  377. --newCommunityTheme-body: #1A1A1B;
  378. }
  379. .ruleList {
  380. padding: 0 24px 0 20px;
  381. background: var(--newRedditTheme-bodyTextAlpha03);
  382. max-height: 100%;
  383. }
  384. html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, button, cite, code, del, dfn, em, img, input, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
  385. margin: 0;
  386. padding: 0;
  387. border: 0;
  388. font-size: 100%;
  389. font: inherit;
  390. vertical-align: baseline;
  391. }
  392. .dialogWindow {
  393. pointer-events: auto;
  394. }
  395. .ruleDiv {
  396. -ms-flex-align: center;
  397. align-items: center;
  398. box-sizing: border-box;
  399. display: -ms-flexbox;
  400. display: flex;
  401. height: 100%;
  402. padding: 75px 30px 20px;
  403. pointer-events: none;
  404. position: fixed;
  405. top: 0;
  406. width: 100%;
  407. z-index: 55;
  408. }
  409. .dialogWindow {
  410. background-color: var(--newCommunityTheme-body);
  411. border: 1px solid var(--newCommunityTheme-line);
  412. border-radius: 4px;
  413. box-shadow: 0 2px 20px 0 rgb(0 0 0 / 30%);
  414. margin: auto;
  415. pointer-events: auto;
  416. z-index: 55;
  417. }
  418. .listWindow {
  419. width: 550px;
  420. position: relative;
  421. }
  422. .ruleHeader {
  423. height: 50px;
  424. border-bottom: 1px solid var(--newRedditTheme-bodyTextAlpha03);
  425. position: relative;
  426. display: -ms-flexbox;
  427. display: flex;
  428. -ms-flex-align: center;
  429. align-items: center;
  430. padding: 0 24px 0 20px;
  431. margin: 0 -24px 0 -20px;
  432. font-weight: 700;
  433. font-size: 14px;
  434. color: var(--newRedditTheme-metaText);
  435. }
  436. .infoIcon {
  437. background: #86848412;
  438. border-radius: 8px;
  439. padding: 10px 16px 10px 12px;
  440. display: -ms-flexbox;
  441. display: flex;
  442. box-sizing: border-box;
  443. margin-top: 16px;
  444. }
  445. .bottomFooter {
  446. box-shadow: 0 -1px 0 var(--newRedditTheme-bodyTextAlpha03);
  447. padding: 20px 0 16px;
  448. min-height: 80px;
  449. display: -ms-flexbox;
  450. display: flex;
  451. box-sizing: border-box;
  452. bottom: 0;
  453. left: 0;
  454. }
  455. .closeIconSVG {
  456. margin-left: auto;
  457. margin-right: -4px;
  458. cursor: pointer;
  459. height: 20px;
  460. padding: 4px;
  461. width: 20px;
  462. fill: var(--newCommunityTheme-actionIcon);
  463. }
  464. .infoIconSVG {
  465. -ms-flex: 0 0 20px;
  466. flex: 0 0 20px;
  467. width: 20px;
  468. margin-right: 12px;
  469. fill: #878a8c;
  470. }
  471. .selectButton:disabled {
  472. opacity: .5;
  473. }
  474. .selectButton {
  475. margin-top: 8px;
  476. -ms-flex: 0 0 150px;
  477. flex: 0 0 150px;
  478. background: var(--newRedditTheme-activeShaded90);
  479. height: 31px;
  480. border-radius: 100px;
  481. color: #fff;
  482. -ms-flex-item-align: end;
  483. align-self: flex-end;
  484. margin-left: auto;
  485. font-size: 12px;
  486. font-weight: 700;
  487. text-transform: uppercase;
  488. letter-spacing: .05em;
  489. outline: none!important;
  490. }
  491. .infoBox {
  492. -ms-flex: 0 1 auto;
  493. flex: 0 1 auto;
  494. font-size: 14px;
  495. line-height: 1.45;
  496. letter-spacing: -.01em;
  497. color: var(--newRedditTheme-metaText);
  498. }
  499. .infoBox a {
  500. color: #24a0ed;
  501. }
  502. button {
  503. background: transparent;
  504. border: none;
  505. color: inherit;
  506. cursor: pointer;
  507. padding: initial;
  508. }
  509. input {
  510. -webkit-writing-mode: horizontal-tb !important;
  511. text-rendering: auto;
  512. color: -internal-light-dark(black, white);
  513. letter-spacing: normal;
  514. word-spacing: normal;
  515. text-transform: none;
  516. text-indent: 0px;
  517. text-shadow: none;
  518. display: inline-block;
  519. text-align: start;
  520. appearance: auto;
  521. background-color: -internal-light-dark(rgb(255, 255, 255), rgb(59, 59, 59));
  522. -webkit-rtl-ordering: logical;
  523. cursor: text;
  524. margin: 0em;
  525. font: 400 13.3333px Arial;
  526. padding: 1px 2px;
  527. border-width: 2px;
  528. border-style: inset;
  529. border-color: -internal-light-dark(rgb(118, 118, 118), rgb(133, 133, 133));
  530. border-image: initial;
  531. }
  532. body {
  533. min-height: calc(100vh - 48px);
  534. line-height: 1;
  535. font-family: IBMPlexSans, Arial, sans-serif;
  536. -webkit-font-smoothing: antialiased;
  537. }
  538. ._3kEv5z1lDKGV8PQ5ijp4Uh {
  539. background-size: 24px 24px;
  540. background-position: 11px 6px;
  541. padding-left: 42px!important;
  542. background-repeat: no-repeat;
  543. }
  544. .title {
  545. margin-top: 16px;
  546. font-size: 16px;
  547. line-height: 1.2;
  548. font-weight: 700;
  549. color: var(--newRedditTheme-bodyText);
  550. }
  551. .fieldSet {
  552. display: -ms-flexbox;
  553. display: flex;
  554. -ms-flex-direction: column;
  555. flex-direction: column;
  556. box-sizing: border-box;
  557. }
  558. .listValue label {
  559. padding: 0 72px 0 20px;
  560. display: -ms-flexbox;
  561. display: flex;
  562. height: 100%;
  563. -ms-flex-align: center;
  564. align-items: center;
  565. cursor: pointer;
  566. font-size: 14px;
  567. font-weight: 700;
  568. color: var(--newRedditTheme-metaText);
  569. position: relative;
  570. }
  571. .listValue {
  572. box-sizing: border-box;
  573. height: 64px;
  574. border-top: 1px solid var(--newRedditTheme-navIconFaded10);
  575. }
  576. .listBox {
  577. margin: 16px -24px 0 -20px;
  578. max-height: 60vh;
  579. min-height: 100px;
  580. overflow: auto;
  581. }
  582. .listValue input {
  583. visibility: hidden;
  584. display: none;
  585. }
  586. .StyledHtml tr {
  587. color: ${Settings.titleColor};
  588. }
  589. .StyledHtml td {
  590. color: ${Settings.textColor};
  591. }
  592. #CustomMetadata {
  593. font-size: 13px;
  594. line-height: 1.5;
  595. }
  596. .CustomInfoBar__username {
  597. padding-left: 10px;
  598. font-size: 18px;
  599. line-height: 1;
  600. padding-bottom: 4px;
  601. overflow: hidden;
  602. white-space: nowrap;
  603. text-overflow: ellipsis;
  604. text-decoration: none;
  605. color: var(--color-tone-1);
  606. }
  607. .CustomSeperator {
  608. position: relative;
  609. border-top: 1px solid var(--color-tone-6);
  610. margin-top: 16px;
  611. margin-bottom: 16px;
  612. }
  613. @media (min-width: 768px)
  614. .ThreadViewer__infobarContainer {
  615. display: table;
  616. }
  617. #currentlySelected {
  618. background-color: rgba(121, 121, 121, 0.35);
  619. }
  620. .ruleDiv {
  621. background-color: rgba(26, 26, 27, 0.6);
  622. visibility: hidden;
  623. }`;
  624.  
  625. const styleSheet = document.createElement("style");
  626. styleSheet.type = "text/css";
  627. styleSheet.id = "modmailPlusSheet";
  628. styleSheet.innerText = css;
  629. if($$("#modmailPlusSheet").length == 0)
  630. document.head.appendChild(styleSheet);
  631. };
  632.  
  633. function initializeCore(Settings) {
  634. /* About the core
  635. * - it contains functions required for handling different in-page-actions, such as hiding a div
  636. * - references to variables outside the core and the document will not be recognized
  637. * */
  638. class Core {
  639. ruleListActivator = "<open-rulelist-dialog>";
  640.  
  641. listBoxChanged(responseIndex) {
  642. const message = document.ModmailPlus.responses[responseIndex].content;
  643.  
  644. if(message == this.ruleListActivator)
  645. {
  646. const ruleDiv = document.getElementsByClassName("ruleDiv")[0];
  647. ruleDiv.style.visibility = "visible";
  648. }
  649. else
  650. {
  651. const userVisitingCreatePostPage = document.querySelectorAll(".NewThread").length;
  652.  
  653. const messageBox = userVisitingCreatePostPage
  654. ? document.querySelector(".Textarea, NewThread__message")
  655. : document.getElementById("realTextarea");
  656.  
  657. const response = document.ModmailPlus.responses.find(x => x.content == message);
  658.  
  659. response.replace ? messageBox.value = message : messageBox.value += message;
  660.  
  661. if(response.subject) {
  662. document.querySelector(".NewThread__subject").value = response.subject;
  663. }
  664.  
  665. console.log("[Modmail++] Updated the message: %c" + messageBox.value,"color: orange");
  666. }
  667. }
  668.  
  669. // implement listbox select highlight
  670. selected(element) {
  671. const selectedElem = document.getElementById("currentlySelected");
  672.  
  673. // if an element already selected, reset the id and set its background color to nothing
  674. if(selectedElem)
  675. selectedElem.removeAttribute("id");
  676.  
  677. element.parentElement.id = "currentlySelected";
  678. document.getElementsByClassName("selectButton")[0].disabled = false;
  679. }
  680.  
  681. removeBreaks = text => text.replace(/(\r\n|\n|\r)/gm, "");
  682.  
  683. selectButtonClicked() {
  684. const selectedElem = document.getElementById("currentlySelected");
  685. const userVisitingCreatePostPage = document.querySelectorAll(".NewThread").length;
  686.  
  687. const messageBox = userVisitingCreatePostPage
  688. ? document.querySelector(".Textarea, NewThread__message")
  689. : document.getElementById("realTextarea");
  690.  
  691. if(selectedElem)
  692. {
  693. const selectedRule = document.ModmailPlus.rules[selectedElem.getAttribute('value')];
  694. const ruleName = selectedRule.short_name;
  695. const ruleDescription = selectedRule.description;
  696. const fixedDescription = ruleDescription.replaceAll("\n","\n> ") + '\n\n';
  697. const message = `> [**${ruleName}**]\n>\n> ${fixedDescription}`;
  698.  
  699. const response = document.ModmailPlus.responses.find(x => x.content == this.ruleListActivator);
  700. response.replace // if to replace or add text to the messagebox
  701. ? messageBox.value = message
  702. : messageBox.value += message;
  703.  
  704. console.log("[Modmail++] New messageBox value: %c" + messageBox.value,"color: orange");
  705.  
  706. this.closeIconClicked();
  707. }
  708. }
  709.  
  710. closeIconClicked() {
  711. const ruleDiv = document.querySelector(".ruleDiv");
  712. ruleDiv.style.visibility = "hidden";
  713. }
  714. divertQuoteText() {
  715. console.log("[Modmail++] %cDiverting quote text from original textbox to Modmail++'s", "color: orange");
  716. setTimeout(() => {
  717. const originalForm = document.querySelector(".Textarea, .ThreadViewerReplyForm__replyText");
  718. const originalValue = originalForm.value;
  719. let text = "";
  720.  
  721. if(originalValue.includes("\n\n"))
  722. text = originalValue.split("\n\n").filter(x => x.length > 0).pop();
  723. else
  724. text = originalValue;
  725.  
  726. if(text.indexOf("\n") == 0) text = text.slice(1);
  727.  
  728. if(text && text.includes("said:"))
  729. document.querySelector("#realTextarea").value += text + "\n\n";
  730. }, 50);
  731. }
  732. clearReplyForm() {
  733. setTimeout(() => {
  734. document.getElementById("realTextarea").value = "";
  735. console.log("[Modmail++] Cleared the textarea!");
  736. // set onclick variable again because the button refreshes itself
  737. document.querySelector(".ThreadViewerReplyForm__replyButton")
  738. .setAttribute("onclick", "document.ModmailPlus.Core.clearReplyForm()")
  739. }, 500);
  740. }
  741. };
  742. document.ModmailPlus.Core = new Core;
  743. document.ModmailPlus.responses = Settings.responses;
  744. };
  745.  
  746. async function appendChatProfileIcons() {
  747. const user = await getUserInfo();
  748.  
  749. // icon element
  750. const chatProfileIcon = document.createElement('div');
  751. chatProfileIcon.innerHTML = `<img class="chatProfileIcon" src="${user.data.icon_img}" width="25">`;
  752.  
  753. const authors = $$(".ThreadPreview__author");
  754. if(authors) {
  755. authors.forEach((author, index) => {
  756. // get username (u/xxxxxx)
  757. const name = $$(".Author__text")[index].innerText;
  758.  
  759. // check if there is an icon appended already
  760. const exists = author.childNodes.length == 1 ? false : true;
  761.  
  762. if(removePrefix(name) == recipientUsername() && !exists) // if the username is the user (non-mod)
  763. {
  764. // append the icon next to the username -> [icon] u/username
  765. author.insertBefore(chatProfileIcon.cloneNode(true), author.firstChild);
  766. }
  767. });
  768. }
  769. };
  770.  
  771. async function appendUserInfo(Settings) {
  772. const user = await getUserInfo();
  773.  
  774. if(user)
  775. {
  776. // userinfo element
  777. const userDetails = document.createElement('div');
  778. userDetails.id = "CustomMetadata";
  779. userDetails.innerHTML = `<img class="profileIcon" src="${user.data.icon_img}" width="25"/>
  780. <a class="CustomInfoBar__username" href="https://www.reddit.com/user/${user.data.name}" target="_blank">${removePrefix(user.data.subreddit.display_name_prefixed)}</a>
  781. <h1 style="color: ${Settings.textColor} ; font-size: 11px; margin-top: 17px; margin-bottom: 10px;">${sanitize(user.data.subreddit.public_description)}</h1>
  782. <h1 class="dataTitle">Main</h1>
  783. <div class="dataText">
  784. <p>Created: <span class="value">${unixToDate(user.data.created)}</span></p>
  785. <p>UserID: <span class="value">${user.data.id}</span></p>
  786. <p>Verified: <span class="value">${user.data.verified}</span></p>
  787. <p>Employee: <span class="value">${user.data.is_employee}</span></p>
  788. <p>NSFW Profile: <span class="value">${user.data.subreddit.over_18}</span></p>
  789. </div>
  790. <h1 class="dataTitle">Karma</h1>
  791. <div class="dataText">
  792. <p>Post: <span class="value">${user.data.link_karma}</span></p>
  793. <p>Comment: <span class="value">${user.data.comment_karma}</span></p>
  794. <p>Total: <span class="value">${user.data.total_karma}</span></p>
  795. <p>Awardee: <span class="value">${user.data.awardee_karma}</span></p>
  796. <p>Awarder: <span class="value">${user.data.awarder_karma}</span></p>
  797. </div>
  798. <h1 class="dataTitle">Links</h1>
  799. <div style="padding-left: 10px;">
  800. <a class="InfoBar__recent" href="https://redditmetis.com/user/${user.data.name}" target="_blank">Redditmetis</a>
  801. <a class="InfoBar__recent" href="https://www.reddit.com/search?q=${user.data.name}" target="_blank">Reddit Search</a>
  802. <a class="InfoBar__recent" href="https://www.google.com/search?q=%22${user.data.name}%22" target="_blank">Google Search</a>
  803. </div>`
  804.  
  805. // seperator element
  806. const seperator = document.createElement('div');
  807. seperator.classList.add("CustomSeperator");
  808. if(!$("#CustomMetadata")) {
  809. // append the elements
  810. $(".InfoBar").insertBefore(userDetails, $(".InfoBar__username")); // append user information on top of the sidebar
  811. $(".InfoBar").insertBefore($(".InfoBar__modActions"), $(".InfoBar__recents")); // move modActions on top of recent posts
  812.  
  813. if($(".InfoBar__banText"))
  814. $(".InfoBar").insertBefore($(".InfoBar__banText"), $("#CustomMetadata"));
  815.  
  816. $(".InfoBar__username").outerHTML = ""; // delete the original username element
  817. $(".InfoBar__metadata").outerHTML = ""; // delete the original metadata
  818. }
  819. }
  820. };
  821.  
  822. function replaceReplyForm(Settings) {
  823. // hide the original replyform textarea
  824. $(".ThreadViewerReplyForm__replyText").style.cssText += 'display: none';
  825.  
  826. // create and append a new replyform textarea
  827. const newReplyForm = document.createElement("textarea");
  828. newReplyForm.setAttribute('class', 'Textarea ThreadViewerReplyForm__replyText ');
  829. newReplyForm.setAttribute('id', 'realTextarea');
  830. newReplyForm.setAttribute('name', 'body');
  831. newReplyForm.setAttribute('placeholder', `${Settings.placeholderMessage}`);
  832. $(".ThreadViewerReplyForm").insertBefore(newReplyForm, $(".ThreadViewerReplyForm__replyFooter"));
  833.  
  834. // make the reply button clear the new replyform
  835. $(".ThreadViewerReplyForm__replyButton").setAttribute("onclick", "document.ModmailPlus.Core.clearReplyForm()");
  836. };
  837.  
  838. async function appendResponseTemplateBox(Settings) {
  839. const responseTemplateElement =
  840. `<h2 class="dataTitle">Response Templates</h2>
  841. <select id="responseListbox" onchange="document.ModmailPlus.Core.listBoxChanged(this.value);" onfocus="this.selectedIndex = -1;"/>
  842. <option selected disabled hidden>Select a template</option>
  843. <span class="focus"></span>`;
  844.  
  845. const responseTemplateParent = document.createElement('div');
  846. responseTemplateParent.classList.add("select", "customResponseBox");
  847. responseTemplateParent.innerHTML = responseTemplateElement;
  848.  
  849. const userVisitingCreatePostPage = document.querySelectorAll(".NewThread").length;
  850.  
  851. if(typeof Settings.responses == "object" && Settings.responses.length) // if the responses variable exists and has responses
  852. {
  853. if(userVisitingCreatePostPage) // user visited mod.reddit.com/mail/create
  854. {
  855. // append the template box to the site
  856. $(".NewThread__fields").prepend(responseTemplateParent);
  857. $(".NewThread__fields").insertBefore($(".customResponseBox"), $(".Textarea, .NewThread__message"));
  858. }
  859. else // user visited modmail chat
  860. {
  861. // append the template box to the site
  862. $(".ThreadViewer__replyContainer").prepend(responseTemplateParent);
  863. $(".ThreadViewer__replyContainer").insertBefore($(".ThreadViewer__typingIndicator"), $(".select")); // append typing indicator before listbox
  864. }
  865. }
  866. // populates the response template listbox
  867. function populateListbox(listBoxId) {
  868. const listBox = $(listBoxId);
  869.  
  870. if(typeof Settings.responses == "object" && Settings.responses.length) // if the responses variable exists and has responses
  871. {
  872. Settings.responses.forEach((response, i) => {
  873. const responseSubreddit = keepPrefix(response.subreddit.toLowerCase(), true);
  874. const currentSubreddit = keepPrefix(Settings.subTag.toLowerCase(), true);
  875. const sameSubreddit = currentSubreddit == responseSubreddit;
  876.  
  877. if(sameSubreddit || response.subreddit.length == 0)
  878. {
  879. if(userVisitingCreatePostPage)
  880. {
  881. listBox.options[listBox.options.length] = new Option(response.name, i);
  882. }
  883. else
  884. {
  885. if(!response.subject)
  886. {
  887. listBox.options[listBox.options.length] = new Option(response.name, i);
  888. }
  889. }
  890. }
  891. });
  892. }
  893. };
  894.  
  895. populateListbox("#responseListbox"); // add all the responses to the response template listbox
  896.  
  897. // creates and returns a list element
  898. function makeListValue(index, rule) {
  899. document.ModmailPlus.rules.push(rule);
  900. return `<div value='${index}' class="listValue">
  901. <input onclick="document.ModmailPlus.Core.selected(this)" name="subredditRule" id='${"input_" + index}' type="radio">
  902. <label for='${"input_" + index}'>${rule.short_name}</label>
  903. </div>`;
  904. };
  905.  
  906. const ruleObj = await getRules(Settings);
  907.  
  908. if(ruleObj)
  909. {
  910. $$(".subredditRuleList").forEach(elem => elem.remove()); // remove all subredditRuleList elements
  911.  
  912. let listContent = "";
  913.  
  914. ruleObj.rules.forEach((rule, index) => {
  915. listContent += makeListValue(index, rule)
  916. });
  917.  
  918. // (Append) Div ruleList element to body
  919. const ruleList = document.createElement('div');
  920. ruleList.classList.add("subredditRuleList");
  921. ruleList.innerHTML = `<div class="ruleDiv">
  922. <div aria-modal="true" class="dialogWindow" role="dialog" tabindex="-1">
  923. <div class="listWindow">
  924. <div class="ruleList">
  925. <div class="ruleHeader">Select a rule<svg onclick="document.ModmailPlus.Core.closeIconClicked()" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" class="closeIconSVG"><polygon fill="inherit" points="11.649 9.882 18.262 3.267 16.495 1.5 9.881 8.114 3.267 1.5 1.5 3.267 8.114 9.883 1.5 16.497 3.267 18.264 9.881 11.65 16.495 18.264 18.262 16.497"></polygon></svg></div>
  926. <fieldset class="fieldSet">
  927. <div class="title"><span>Which community rule did the user violate?</span></div>
  928. <div class="listBox">
  929. ${listContent}
  930. </div>
  931. <div class="infoIcon"><svg class="infoIconSVG" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><g><path d="M10,8.5 C10.553,8.5 11,8.948 11,9.5 L11,13.5 C11,14.052 10.553,14.5 10,14.5 C9.447,14.5 9,14.052 9,13.5 L9,9.5 C9,8.948 9.447,8.5 10,8.5 Z M10.7002,5.79 C10.8012,5.89 10.8702,6 10.9212,6.12 C10.9712,6.24 11.0002,6.37 11.0002,6.5 C11.0002,6.57 10.9902,6.63 10.9802,6.7 C10.9712,6.76 10.9502,6.82 10.9212,6.88 C10.9002,6.94 10.8702,7 10.8302,7.05 C10.7902,7.11 10.7502,7.16 10.7002,7.21 C10.6602,7.25 10.6102,7.29 10.5512,7.33 C10.5002,7.37 10.4402,7.4 10.3812,7.42 C10.3202,7.45 10.2612,7.47 10.1902,7.48 C10.1312,7.49 10.0602,7.5 10.0002,7.5 C9.7402,7.5 9.4802,7.39 9.2902,7.21 C9.1102,7.02 9.0002,6.77 9.0002,6.5 C9.0002,6.37 9.0302,6.24 9.0802,6.12 C9.1312,5.99 9.2002,5.89 9.2902,5.79 C9.5202,5.56 9.8702,5.46 10.1902,5.52 C10.2612,5.53 10.3202,5.55 10.3812,5.58 C10.4402,5.6 10.5002,5.63 10.5512,5.67 C10.6102,5.71 10.6602,5.75 10.7002,5.79 Z M10,16 C6.691,16 4,13.309 4,10 C4,6.691 6.691,4 10,4 C13.309,4 16,6.691 16,10 C16,13.309 13.309,16 10,16 M10,2 C5.589,2 2,5.589 2,10 C2,14.411 5.589,18 10,18 C14.411,18 18,14.411 18,10 C18,5.589 14.411,2 10,2"></path></g></svg>
  932. <div class="infoBox">
  933. <p><span>Not sure? </span><a href="https://www.reddit.com/${keepPrefix(Settings.subTag)}/about/rules" target="_blank" rel="noopener noreferrer">Read ${Settings.subTag}'s rules</a></p>
  934. </div>
  935. </div>
  936. <footer class="bottomFooter"><button type="button" disabled="" onclick="document.ModmailPlus.Core.selectButtonClicked()" class="selectButton">Select</button></footer>
  937. </fieldset>
  938. </div>
  939. </div>
  940. </div>
  941. </div>`;
  942. $("body").appendChild(ruleList);
  943. }
  944. };
  945.  
  946. function fixQuoteButtons() {
  947. /* On click, do this
  948. 1) take the text from the original form
  949. 2) split it by two new lines
  950. 3) take the last result (last quoted message)
  951. 4) paste the last result to the new form
  952. */
  953.  
  954. $$(".Message__quote").forEach(elem => {
  955. if(!elem.getAttribute("onclick"))
  956. elem.setAttribute("onclick", "document.ModmailPlus.Core.divertQuoteText()");
  957. });
  958. };
  959. function handleCreateMessagePage() {
  960. // e.g. wait for an input change, then update the template strings to have that subreddit or username
  961. function updateResponseTemplate(isPostFrom, lastValue, newValue) {
  962. const defaultValue = isPostFrom
  963. ? "r/subreddit"
  964. : "u/undefined";
  965. document.ModmailPlus.responses.forEach(response => {
  966. // update subject string
  967. if(response.subject) {
  968. response.subject = response.subject.replaceAll(
  969. lastValue || defaultValue,
  970. newValue
  971. );
  972. }
  973.  
  974. // update content string
  975. response.content = response.content.replaceAll(
  976. lastValue || defaultValue,
  977. newValue
  978. );
  979. });
  980. }
  981. (() => {
  982. let lastUsername = null;
  983.  
  984. // Handle change of "To User"
  985. const toUser = document.querySelector(".Radio__input[value=user]");
  986.  
  987. if(toUser) {
  988. toUser.onclick = () => {
  989. const waitForTextbox = setInterval(() => {
  990. const newThreadTextbox = document.querySelector(".NewThread__username");
  991.  
  992. if(newThreadTextbox) {
  993. clearInterval(waitForTextbox);
  994.  
  995. newThreadTextbox.onchange = e => {
  996. const username = "u/" + e.target.value;
  997.  
  998. updateResponseTemplate(false, lastUsername, username);
  999.  
  1000. lastUsername = username;
  1001. }
  1002. }
  1003. }, 100);
  1004. }
  1005. }
  1006.  
  1007. // Handle change of "To Subreddit"
  1008. const toSubreddit = document.querySelector(".Radio__input[value=subreddit]");
  1009.  
  1010. if(toSubreddit) {
  1011. toSubreddit.onclick = () => {
  1012. const waitForTextbox = setInterval(() => {
  1013. const newThreadTextbox = document.querySelector(".NewThread__subreddit");
  1014.  
  1015. if(newThreadTextbox) {
  1016. clearInterval(waitForTextbox);
  1017.  
  1018. newThreadTextbox.onchange = e => {
  1019. const subreddit = "r/" + e.target.value;
  1020.  
  1021. updateResponseTemplate(false, lastUsername, subreddit);
  1022.  
  1023. lastUsername = subreddit;
  1024. }
  1025. }
  1026. }, 100);
  1027. }
  1028. }
  1029. })();
  1030. (() => {
  1031. // Handle change of "Post from"
  1032. const srName = document.querySelector("[name=srName]");
  1033.  
  1034. if(srName) {
  1035. let lastSubreddit = null;
  1036.  
  1037. const postToChanges = setInterval(() => {
  1038. const subreddit = "r/" + srName.value;
  1039.  
  1040. if(subreddit != lastSubreddit && subreddit != 'r/') {
  1041. updateResponseTemplate(true, lastSubreddit, subreddit);
  1042.  
  1043. lastSubreddit = subreddit;
  1044. }
  1045. }, 500);
  1046. }
  1047. })();
  1048. };
  1049.  
  1050. const __main__ = async () => {
  1051. console.log("[Modmail++] %cMain function ran!", "color: grey");
  1052. const Settings = new __settings__();
  1053. document.ModmailPlus = {};
  1054. document.ModmailPlus.rules = [];
  1055.  
  1056. // These will be executed in any page //
  1057. if(!document.ModmailPlus.length)
  1058. initializeCore(Settings);
  1059. if(Settings.enableCustomResponses && !$("#responseListbox"))
  1060. appendResponseTemplateBox(Settings);
  1061. applyCSS(Settings);
  1062. ////////////////////////////////////////
  1063. if(!$(".NewThread")) // execute in chat page only
  1064. {
  1065. appendUserInfo(Settings); // if the element already exists will be checked before appending
  1066. if(Settings.chatProfileIcons && !$(".chatProfileIcon"))
  1067. appendChatProfileIcons();
  1068. if(!$("#realTextarea"))
  1069. replaceReplyForm(Settings);
  1070. fixQuoteButtons();
  1071. }
  1072. else // execute in create message page only
  1073. {
  1074. handleCreateMessagePage();
  1075. }
  1076.  
  1077. console.log("[Modmail++] %cLoaded!", "color: lime");
  1078. console.log("[Modmail++]", document.ModmailPlus);
  1079. };
  1080.  
  1081. let URLChangeDetectorActive = false;
  1082.  
  1083. // this is a hot mess, please help me
  1084. setInterval (() => {
  1085. if(this.lastPathStr != location.pathname)
  1086. {
  1087. this.lastPathStr = location.pathname;
  1088.  
  1089. console.log("[Modmail++] %cNew page detected!", "color: gold");
  1090.  
  1091. URLChangeDetectorActive = true;
  1092.  
  1093. const waitForElements = setInterval (() => {
  1094. if($(".NoThreadMessage__generic") && URLChangeDetectorActive) // add confetti explosion if no mail
  1095. {
  1096. clearInterval(waitForElements);
  1097. URLChangeDetectorActive = false;
  1098.  
  1099. console.log("[Modmail++] %cNo modmail!", "color: lime");
  1100.  
  1101. party.confetti($(".NoThreadMessage__generic"), {
  1102. count: 15,
  1103. spread: 50
  1104. });
  1105. }
  1106.  
  1107. if($(".InfoBar") && URLChangeDetectorActive) // user is on modmail "chat" page
  1108. {
  1109. clearInterval(waitForElements);
  1110. URLChangeDetectorActive = false;
  1111.  
  1112. if($("body") && !$("#CustomMetadata"))
  1113. __main__();
  1114. }
  1115. if($(".NewThread") && URLChangeDetectorActive) // user is on the create new message page
  1116. {
  1117. clearInterval(waitForElements);
  1118. URLChangeDetectorActive = false;
  1119. __main__();
  1120. }
  1121. }, 5);
  1122. }
  1123. }, 100);
  1124. })();