// ==UserScript== // @name Stack Exchange CV Request Generator // @namespace https://github.com/SO-Close-Vote-Reviewers/ // @version 2.0.4 // @description This script generates formatted close-/delete-/reopen-/undelete-vote requests, spam/offensive flag requests, Smoke Detector reports, and approve-/reject-pls requests for suggested edits, then sends them to a specified chat room. // @author @TinyGiant @Makyen // @contributor @rene @Tunaki // @include /^https?://(?:[^/.]+\.)*(?:stackexchange\.com|stackoverflow\.com|serverfault\.com|superuser\.com|askubuntu\.com|stackapps\.com|mathoverflow\.net)/(?:q(?:uestions)?\/\d+|review|tools|admin|users|search|\?|$)/ // @exclude *://chat.stackoverflow.com/* // @exclude *://chat.stackexchange.com/* // @exclude *://chat.*.stackexchange.com/* // @exclude *://stackexchange.com/* // @exclude *://api.*.stackexchange.com/* // @exclude *://data.stackexchange.com/* // @require https://code.jquery.com/jquery-3.5.0.min.js // @require https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/gm4-polyfill.js // @require https://cdn.jsdelivr.net/gh/makyen/extension-and-userscript-utilities@94cbac04cb446d35dd025974a7575b25b9e134ca/executeInPage.js // @connect raw.githubusercontent.com // @connect chat.stackoverflow.com // @connect chat.stackexchange.com // @connect chat.meta.stackexchange.com // @grant GM_openInTab // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM_addValueChangeListener // @grant GM.openInTab // @grant GM.xmlHttpRequest // @grant GM.getValue // @grant GM.setValue // @grant GM.deleteValue // @grant GM.addValueChangeListener // @updateURL https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/SECloseVoteRequestGenerator.user.js // @downloadURL https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/SECloseVoteRequestGenerator.user.js // ==/UserScript== /* jshint jquery: true */ /* globals unsafeWindow, StackExchange, Markdown, toStaticHTML, tagRendererRaw, GM_getValue, GM_setValue, GM_deleteValue, GM_addValueChangeListener, GM_openInTab, GM, $, jQuery, makyenUtilities */ // eslint-disable-line no-unused-vars, no-redeclare (function() { 'use strict'; const executeInPage = makyenUtilities.executeInPage; const parser = new DOMParser(); //The RoomList is the list of chat rooms to which to send requests. It's effectively a class, but a one-off. const RoomList = {}; var CVRGUI; const isGmStorageValid = typeof GM_getValue === 'function' && typeof GM_setValue === 'function'; const socvrModeratedSites = ['stackoverflow.com']; const delayedRequestStorage = 'delayedRequests'; const rememberedRequestStorage = 'rememberedRequests'; let rememberedRequests; //Only those request states with matching times which are not automatically filled by the constructor. const requestInfoStateWithMatchingTime = ['posted', 'delayed', 'closeVoted', 'deleteVoted']; const delayableRequestTypes = ['revisit']; const delayableRequestRegex = / \(in (?:(\d+(?:\.\d+)?)|N) days?\)/; const SDRegex = / *\(?\bSD report\b\)?/ig; const NATORegex = / *\(?\bNATO\b\)?/ig; const scriptInstanceIdentifier = Math.random().toString(); //Not perfectly unique, but should be close. const canListenGMStorage = typeof GM_addValueChangeListener === 'function'; //Not available: Greasemonkey const isQuestionPage = window.location.pathname.indexOf('/questions/') === 0; const SECOND_IN_MILLISECONDS = 1000; const MINUTE_IN_MILLISECONDS = 60 * SECOND_IN_MILLISECONDS; const HOUR_IN_MILLISECONDS = 60 * MINUTE_IN_MILLISECONDS; const DAY_IN_MILLISECONDS = 24 * HOUR_IN_MILLISECONDS; const MORE_THAN_MONTH_IN_MILLISECONDS = Math.round((365.25 / 12) + 3) * DAY_IN_MILLISECONDS; const questionActivityWarningAge = (6 * MORE_THAN_MONTH_IN_MILLISECONDS) + (7 * DAY_IN_MILLISECONDS); //6 months plus a bit let openedAsDelayedRequestNoticeId = []; const requestTypesWithNoReason = ['!!/reportuser', '!!/addblu-', '!!/rmblu-', '!!/addwlu-', '!!/rmwlu-']; const requestTypesWithOptionalReason = ['!!/report', '!!/report-force', '!!/scan', '!!/scan-force', 'spam', 'offensive', 'reflag NAA', 'reflag VLQ']; const knownRooms = { SOCVR: { urlDetectionRegExp: /chat\.stackoverflow\.com\/rooms\/41570(?:$|\/)/, room: { host: 'https://chat.stackoverflow.com', url: 'https://chat.stackoverflow.com/rooms/41570/', // SOCVR id: '41570', name: 'SO Close Vote Reviewers', }, }, charcoal: { urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/11540(?:$|\/)/, room: { host: 'https://chat.stackexchange.com', url: 'https://chat.stackexchange.com/rooms/11540/', // charcoal-hq id: '11540', name: 'Charcoal HQ', }, }, tavern: { urlDetectionRegExp: /chat\.meta\.stackexchange\.com\/rooms\/89(?:$|\/)/, room: { host: 'https://chat.meta.stackexchange.com', url: 'https://chat.meta.stackexchange.com/rooms/89/', // Tavern on the Meta id: '89', name: 'Tavern on the Meta', }, }, CRCQR: { urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/85306(?:$|\/)/, room: { host: 'https://chat.stackexchange.com', url: 'https://chat.stackexchange.com/rooms/85306/', // SE Code Review Close Questions room id: '85306', name: 'SE Code Review Close Questions room', }, }, CRUDE: { urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/2165(?:$|\/)/, useMetaTag: false, //default useSiteTag: true, //default room: { host: 'https://chat.stackexchange.com', url: 'https://chat.stackexchange.com/rooms/2165/', // SE Code Review Close Questions room id: '2165', name: 'CRUDE', }, }, seNetwork: { urlDetectionRegExp: /chat\.stackexchange\.com\/rooms\/11254(?:$|\/)/, room: { host: 'https://chat.stackexchange.com', url: 'https://chat.stackexchange.com/rooms/11254/', // The Stack Exchange Network id: '11254', name: 'The Stack Exchange Network', }, }, }; //Options function CheckboxOption(_defaultValue, _text, _tooltip) { //Constructor for a checkbox option this.defaultValue = _defaultValue; this.text = _text; this.tooltip = _tooltip; } function ButtonOption(_buttonAction, _dynamicText, _text, _tooltip) { //Constructor for a button option this.buttonAction = _buttonAction; this.dynamicText = _dynamicText; this.text = _text; this.tooltip = _tooltip; } function NumberOption(_defaultValue, _min, _max, _style, _textPre, _textPost, _tooltip) { //Constructor for a number option this.defaultValue = _defaultValue; this.min = _min; this.max = _max; this.style = _style; this.textPre = _textPre; this.textPost = _textPost; this.tooltip = _tooltip; } //Object describing the options displayed in the GUI. /* beautify preserve:start */ var knownOptions = { checkboxes: { onlySocvrModeratedSites: new CheckboxOption(false, 'Don\'t show this GUI on non-SOCVR moderated sites.', 'SOCVR moderates only ' + socvrModeratedSites.join(',') + '. Checking this prevents the cv-pls/del-pls GUI from being added on sites which SOCVR does not moderate.'), onlyKnownSites: new CheckboxOption(false, 'Don\'t show this GUI on sites not pre-configured in this script.', 'Known sites are those moderated by SOCVR: ' + socvrModeratedSites.join(',') + '; Code Review; Mathematics; and Meta Stackexchange. Checking this prevents the cv-pls/del-pls GUI from being added on other sites.'), onlyCharcoalSDSpamOnUnknownSites: new CheckboxOption(true, 'On sites not specifically configured in this script, use Charcoal HQ as default & show only SD reports/spam report options.', 'On sites not specifically configured in this script, use Charcoal HQ as the default room and show only SD reports, spam and offensive as report options. This will not replace the room currently defined on any site. Basically, for any site you have visited prior to setting this option, the site will have already been defined (used to be SOCVR, then changed to "The Stack Exchange Network"). On those sites, you will need to manually change the room.'), alwaysCharcoal: new CheckboxOption(true, 'Always send SD commands to Charcoal HQ.', 'Regardless of the current room selection, always send SD commands to Charcoal HQ and show the SD command options on all sites.'), canReportSmokeDetectorSOCVR: new CheckboxOption(false, 'SOCVR: Show request types for Smoke Detector.', 'When the target Room is SOCVR, show request type options for reporting to Smoke Detector (SD) that the question is spam/offensive, or that all the user\'s posts are spam/offensive. Using SD in SOCVR requires that you are approved to do so in SOCVR. If you\'re not yet approved, sending such reports will just have SD respond saying that you\'re not approved.'), canReportSmokeDetectorOther: new CheckboxOption(true, 'non SOCVR/non Charcoal HQ rooms: Show request types for Smoke Detector.', 'For target rooms other than SOCVR, show request type options for reporting to Smoke Detector (SD) that the question is spam/offensive and other SD commands. Using SD requires that you are approved to do so in that Room. If you\'re not yet approved, sending such reports will just have SD respond saying that you\'re not approved.'), alwaysAddNato: new CheckboxOption(true, 'Add " (NATO)" to requests from NATO.', 'When submitting a request from New Answers To Old questions (NATO, part of the 10k tools), add " (NATO)" to the request reason to help people see why you\'re submitting a request about an old question.'), automaticlyPostDelayedRequests: new CheckboxOption(false, 'Automatically post delayed requests.', 'For delayed requests (e.g. "del-pls (in 2 days)"), don\'t open a page to allow you to manually post the request; just automatically post the request.\r\nNOTE: You are responsible for all requests you post. This includes things like posting duplicate requests. Thus, it\'s much better to manually verify that the request is valid (e.g. the question has not been reopened).'), }, buttons: { deleteDelayedRequests: new ButtonOption(deleteDelayedRequests, getNumberDelayedRequestsAsAddedText, 'Discard delayed requests', 'Delete all requests which you have requested be delayed (i.e. "del-pls (in 2 days)").'), }, numbers: { daysRememberRequests: new NumberOption(30, 0, 365, 'width: 5em', 'Days to remember requests (does not apply to revisits)', '', 'Number of days to remember the requests you have made. This is used to inform you if you try to make the same request again (you still can, you just have to confirm you want to post a duplicate). It\'s also used to better remember the reason you wrote (e.g. if you reload the page). Set to 0 if you don\'t want this information stored. This limit does not apply to delayed requests (i.e. revisits).'), }, }; /* beautify preserve:end */ function QuickSubstitutions(_substitutions) { this.substitutions = _substitutions; } QuickSubstitutions.prototype.get = function(r) { //Substitute space separated words in the input text which // match the properties above with the property's value. var a = r.split(' '); a.forEach(function(v, i) { a[i] = Object.prototype.hasOwnProperty.call(this.substitutions, v) && v !== 'get' ? this.substitutions[v] : v; }, this); return a.join(' '); }; function SiteConfig(_name, _siteRegExp, _offTopicCloseReasons, _quickSubstitutions, _offTopicScrapeMatch, _defaultRoomKey) { this.name = _name; this.siteRegExp = _siteRegExp; this.offTopicCloseReasons = _offTopicCloseReasons; this.quickSubstitutions = new QuickSubstitutions(_quickSubstitutions); //The offTopicScrapeMatch object defines matches which are tested against the information provided in the // question post notices in order to determine the reason that the question was closed. this.offTopicScrapeMatch = _offTopicScrapeMatch; this.defaultRoomKey = _defaultRoomKey; this.defaultRoom = JSON.parse(JSON.stringify(knownRooms[_defaultRoomKey].room)); } //The quick substitutions are changed in the text a user types for their request reason. // They are usually a single character, but can be more. As a single character, they need // to stay away from anything the user is going to type as a single character. In particular, // that means they need to not be "a". const defaultQuickSubstitutions = { 't': 'Too Broad', 'f': 'Needs More Focus', 'u': 'Unclear', 'c': 'Needs Details or Clarity', 'p': 'Primarily Opinion Based', 'o': 'Opinion Based', 'd': 'Duplicate', }; const defaultOffTopicCloseReasons = { 1: 'Blatantly off-topic', //In close-flag dialog, but not the close-vote dialog on most sites, but is in the CV dialog on some sites. 2: 'Belongs on another site', 3: 'custom', }; const defaultOffTopicCloseReasonsWithoutOtherSite = Object.assign({}, defaultOffTopicCloseReasons); delete defaultOffTopicCloseReasonsWithoutOtherSite[2]; var configsForSites = []; //The keys used for the close reasons below should match the "value" attribute in the used for // that close reason in the off-topic pane of the close-vote-/flag-dialog. //Stack Overflow configsForSites.push(new SiteConfig('Stack Overflow', /^stackoverflow.com$/, Object.assign({ 18: 'Not About Programming', 11: 'Typo or Cannot Reproduce', 13: 'No MCVE', 16: 'Request for Off-Site Resource', 19: 'Not in English', }, defaultOffTopicCloseReasons), Object.assign({ 'm': 'No MCVE', 'n': 'Not About Programming', 'r': 'Typo or Cannot Reproduce', 'g': 'General Computing', 'l': 'Request for Off-Site Resource', 'e': 'Not in English', 'F': '(FireAlarm)', 'N': '(NATO)', 'S': '(SD report)', 'D': '(not enough code to duplicate)', 'B': '(no specific expected behavior)', 'E': '(no specific problem or error)', }, defaultQuickSubstitutions), { //2022-08-03: The code which used these values is currently non-operable, due to past changes to post notices. 'reproduced': 'r', 'programming': 'n', 'recommend': 'l', 'working': 'm', }, 'SOCVR')); //Meta Stack Exchange configsForSites.push(new SiteConfig('Meta Stack Exchange', /^meta.stackexchange.com$/, Object.assign({ 5: 'Does not seek input or discussion', 6: 'Cannot be reproduced', 8: 'Not about Stack Exchange Network software', 11: 'Specific to a single site', //This site does not have a 2: 'Belongs on another site' }, defaultOffTopicCloseReasonsWithoutOtherSite), Object.assign({ 'i': 'Does not seek input or discussion', 'r': 'Cannot be reproduced', 'n': 'Not about Stack Exchange Network software', 's': 'Specific to a single site', }, defaultQuickSubstitutions), { 'reproduced': 'r', //Needs verification. 'only': 's', 'input': 'i', }, 'tavern')); //Code Review Stack Exchange configsForSites.push(new SiteConfig('Code Review Stack Exchange', /^codereview.stackexchange.com$/, Object.assign({ 20: 'Lacks concrete context', 23: 'Code not implemented or not working as intended', 25: 'Authorship of code', }, defaultOffTopicCloseReasons), Object.assign({ 'l': 'Lacks concrete context', 'i': 'Code not implemented or not working as intended', 's': 'Authorship of code', }, defaultQuickSubstitutions), { //The default method of using what's bold or italics works reasonably for this site. }, 'CRCQR')); //Mathematics Stack Exchange configsForSites.push(new SiteConfig('Mathematics Stack Exchange', /^math.stackexchange.com$/, Object.assign({ 6: 'Not about mathematics', 8: 'Seeking personal advice', 9: 'Missing context or other details', }, defaultOffTopicCloseReasons), Object.assign({ 'b': 'Blatantly off-topic', 'n': 'Not about mathematics', 'm': 'Missing context or other details', 's': 'Seeking personal advice', }, defaultQuickSubstitutions), { //All of the off-topic reasons need to be specified, because the "Not about mathematics" reason contains no bold or italic text. // As a result, we match against '', which will match anything. 'context': 'm', 'advice': 's', '': 'n', //The closed text for this reason contains no bold or italic characters. }, 'CRUDE')); //Default site configuration var currentSiteConfig = new SiteConfig('Default', /./, defaultOffTopicCloseReasons, defaultQuickSubstitutions, {}, 'seNetwork'); //If we are not trying to be compatible with IE, then could use .find here. var isKnownSite = configsForSites.some((siteConfig) => { if (siteConfig.siteRegExp.test(window.location.hostname)) { currentSiteConfig = siteConfig; return true; } // else return false; }); const reasons = currentSiteConfig.quickSubstitutions; const offTopicCloseReasons = currentSiteConfig.offTopicCloseReasons; //Set some global variables const isSocvrSite = socvrModeratedSites.indexOf(window.location.hostname) > -1; const isSocvrRoomUrlRegEx = knownRooms.SOCVR.urlDetectionRegExp; const isNato = window.location.pathname.indexOf('tools/new-answers-old-questions') > -1; const isSuggestedEditReviewPage = /^\/review\/suggested-edits(?:\/|$)/i.test(window.location.pathname); const isReviewPage = /^\/review\//i.test(window.location.pathname); //Restore the options var configOptions = getConfigOptions(); //If the options are set such that we don't show on non-SOCVR sites and this is not a SOCVR site, or we are only to run on known sites and this one isn't known, then stop processing. if ((configOptions.checkboxes.onlySocvrModeratedSites && !isSocvrSite) || (configOptions.checkboxes.onlyKnownSites && !isKnownSite)) { return; } var onlySdSpamOffensive; function setGlobalVariablesByConfigOptions() { onlySdSpamOffensive = configOptions.checkboxes.onlyCharcoalSDSpamOnUnknownSites && !isSocvrSite && !isKnownSite; RoomList.defaultRoomUrl = currentSiteConfig.defaultRoom.url; if (onlySdSpamOffensive) { RoomList.defaultRoomUrl = knownRooms.charcoal.room.url; // charcoal-hq } } setGlobalVariablesByConfigOptions(); //Get the href for the user's profile. var currentUserHref = $('.s-topbar a.s-user-card').attr('href'); //*This is not effective for some users. //MathJax corrupts the text contents of titles (from a programmatic POV: .text(), // .textContent, and .innerText). In order have requests contain the actual title text, // we save a copy of the text for each title we find in the DOM, hopefully prior to // MathJax changing them. There's a race condition here where it's assumed this is run // between when the title(s) exist in the DOM and before MathJax runs. Currently, there // isn't an effort to guarantee that. function saveCopyOfQuestionTitles() { $('#question-header h1 a, h1 a, .question-hyperlink, .answer-hyperlink').each(function() { const $this = $(this); if (!$this.attr('data-orig-text')) { $this.attr('data-orig-text', $this.text()); } }); } saveCopyOfQuestionTitles(); //NATO: Prep page so we can place del-pls normally, and detect if NATO Enhancements is being used var isNatoWithoutEnhancement = false; if (isNato) { isNatoWithoutEnhancement = true; const rows = $('body.tools-page #mainbar > table.default-view-post-table > tbody > tr'); rows.each(function() { const $this = $(this); $this.addClass('answer cvrgFakeQuestionContext'); const answerId = $('.answer-hyperlink', $this).first().attr('href').replace(/^.*#(\d+)$/, '$1'); $this.attr('data-answerid', answerId); const lastCellWithoutPostMenu = $this.children('td:last-of-type').filter(function() { return !$(this).find('.post-menu, .js-post-menu').length; }); lastCellWithoutPostMenu .append($('
')) //The .js-post-menu should be given a data-post-id attribute with the current post number. .find('.js-post-menu') .attr('data-post-id', answerId); }); /* Disabled: This is currently detecting other things than just NATO Enhancements //Observe for a change to the first TD within the first row of the page to detect the NATO Enhancements userscript. (new MutationObserver(function(mutations, observer) { if (mutations.some((mutation) => (mutation.addedNodes ? mutation.target.nodeName === 'TD' : false))) { //Found an added node that targeted a TD. It's assumed that means NATO Enhancements // is going to be reorganizing the page & we will handle it after that's done. //For now, back-out the changes we made to the DOM for NATO w/o Enhancements. isNatoWithoutEnhancement = false; observer.disconnect(); $('.cvrgFakeQuestionContext').removeClass('answer cvrgFakeQuestionContext').removeData('answerid'); $('.cvrgFakePostMenu').remove(); } })).observe(rows.first().children('td')[0], { childList: true, }); //Only need to watch the first TD. */ } function addNatoIfIsNato(text) { //If the current page is NATO, then add a notation to the text that it's NATO. if (knownOptions.checkboxes.alwaysAddNato && isNato && !/\bnato\b/i.test(text)) { text += ' (NATO)'; } return text; } function addNatoToValueIfIsNatoAndNotEmpty(element) { //Add NATO notation if it's already not there and the value isn't currently empty. var $el = (element instanceof jQuery) ? element : $(element); if ($el.val()) { //Only add if not empty $el.val(addNatoIfIsNato($el.val())); } } function addNoCodeToValueIfIsMcve(element) { //If No MCVE, and no code at all, then state that's the case. var $el = (element instanceof jQuery) ? element : $(element); var questionContext = getQuestionContext(element); var currentVal = $el.val(); if (/\bmcve\b/i.test(currentVal) && !/\bno code\b/i.test(currentVal)) { if (!$('.question code', questionContext).length) { $el.val(currentVal + ': no code'); } else if (!$('.question pre > code', questionContext).length) { $el.val(currentVal + ': no code block'); } } } function capitalizeFirstLetterOfFlexItemChildLink(element) { const $element = $(element); if ($element.is('.flex--item')) { $element.children('a').first().each(function() { const child = this.firstChild; if (child.nodeName === '#text') { const childText = child.textContent; child.textContent = childText[0].toUpperCase() + childText.slice(1); } }); } } function addSlinkClassToAllLinkChildren(el) { el.find('a').addClass('s-link'); } function getRequestTypeByQuestionStatus(inPost) { //Based on the question's current status return the text for the // type(s) of requests which are appropriate/default. var questionContext = getQuestionContext(inPost); var isSOCVR = isCurrentRoomSOCVR(); if (onlySdSpamOffensive) { return ((isSOCVR && configOptions.checkboxes.canReportSmokeDetectorSOCVR) || (!isSOCVR && (configOptions.checkboxes.canReportSmokeDetectorOther || onlySdSpamOffensive))) ? 'sd-report' : 'spam'; } //else if (isQuestionDeleted(questionContext)) { return 'undel-pls'; } //else return isQuestionClosed(questionContext) ? 'reopen/del-pls' : 'cv-pls'; } function anyElementTextStartsWithClosed($obj) { return $obj.filter(function() { return /^Closed/.test($(this).text().trim()); }).length > 0; } function isQuestionClosed(questionContext) { //True if the question is closed. const pre201910CloseBannerExists = $('.special-status .question-status H2 B', questionContext).filter(function() { return /hold|closed|marked/i.test($(this).text()); }).length > 0; const postNotices = $('.js-post-notice', questionContext); const postNoticeIsDuplicateClosure = postNotices.filter(function() { return /already has (?:an answer|answers)|close\/reopen/i.test($(this).text()); }).length > 0; const postNoticeBoldStartsWithClosed = anyElementTextStartsWithClosed($('b', postNotices)); const postNoticesRelativetimeContainers = $('.relativetime', postNotices).parent(); const postNoticesRelativetimeContainerStartsWithClosed = anyElementTextStartsWithClosed(postNoticesRelativetimeContainers); const post201910CloseBannerExists = postNoticeIsDuplicateClosure || postNoticeBoldStartsWithClosed || postNoticesRelativetimeContainerStartsWithClosed; const closeButton = $('.js-close-question-link', questionContext); const closeButtonIsClose = closeButton.attr('data-isclosed') || closeButton.text().toLowerCase().indexOf('reopen') > -1; return pre201910CloseBannerExists || post201910CloseBannerExists || closeButtonIsClose; } function isQuestionDeleted(questionContext) { //True if the question is deleted. return $('.question', questionContext).first().is('.deleted-answer'); } function isPostLocked(post) { let isLocked = false; $(post).find('.iconLightbulb, .iconLock').closest('.d-flex').each(function() { const firstBoldText = $(this).find('b').first().text(); isLocked = isLocked || /community wiki|locked/i.test(firstBoldText); }); return isLocked; } function isPostCommentLocked(post) { let isCommentLocked = false; $(post).find('.iconLightbulb, .iconLock').closest('.d-flex').each(function() { const $this = $(this); const firstBoldText = $this.find('b').first().text(); const isLocked = /community wiki|locked/i.test(firstBoldText); if (isLocked) { isCommentLocked = /Comments .{0,30}\bhave been disabled/.test($this.text()); } }); return isCommentLocked; } function getQuestionContext(element) { //If there's more than one question, the context is the closest .mainbar //This is different in // Normal pages with a single question (#mainbar) // Some review queues and the reopen queue with a question closed as duplicate (.mainbar) // Other review queues for answers: (.review-content) // In these cases (e.g. First Posts), the answer will find .mainbar, but it does not include the question, so we look for the next match further up the DOM. // MagicTag: (#mainbar-full) // Inside the Close Dialog within previewing a potential duplicate question. (.show-original) // 10k tools (NATO with NATO Enhancements): (body.tools-page #mainbar > table > tbody > tr > td) // 10k tools (NATO without NATO Enhancements): (.cvrgFakeQuestionContext is added to the DOM) const $el = (element instanceof jQuery) ? element : $(element); if (isSuggestedEditReviewPage && element.closest('.s-page-title').length) { return $('.js-review-task'); } const context = $el.closest('#mainbar, .review-content, .mainbar, #mainbar-full, .show-original, .cvrgFakeQuestionContext, body.tools-page #mainbar > table.default-view-post-table > tbody > tr > td, .js-review-task, .makyen-flag-post-preview-container'); if (!context.length) { //A containing element which we recognize as the context for the element's question wasn't found. return $(document); } if (context.is('.cvrgFakeQuestionContext') || context.find('.question').length) { return context; } //There was no .question in what was found, try higher up the DOM. return getQuestionContext(context.parent()); } //Substitution rules for request reasons. //Construct a tooltip showing the substitutions which will be made in request reasons. var reasonTooltip = 'Enter your reason for the request.\r\nIf you want to type less text, there are\r\nsome single character text shortcuts when\r\na character is surrounded by whitespace:\r\n' + Object.keys(reasons.substitutions).filter(function(key) { return key !== 'get'; }).sort().map(function(key) { return key + ' --> ' + reasons.substitutions[key]; }).join('\r\n'); var URL = 'https://github.com/SO-Close-Vote-Reviewers/UserScripts/raw/master/SECloseVoteRequestGenerator.user.js'; /* linkifyTextURLs was originally highlight text via RegExp * Copied by Makyen from Makyen's use of it in MagicTag2, which was copied from Makyen's * answer to: Highlight a word of text on the page using .replace() at: * https://stackoverflow.com/a/40712458/3773011 * and substantially rewritten for the SOCVR Archiver. This was copied from there. */ function linkifyTextURLs(element, useSpan) { //This changes bare http/https/ftp URLs into links with link-text a shortened version of the URL. // If useSpan is truthy, then a span with the new elements replaces the text node. // If useSpan is falsy, then the new nodes are added as children of the same element as the text node being replaced. // The [\u200c\u200b] characters are added by SE chat to facilitate word-wrapping & should be removed from the URL. const urlSplitRegex = /((?:\b(?:https?|ftp):\/\/)(?:[\w.~:\/?#[\]@!$&'()*+,;=\u200c\u200b-]{2,}))/g; // eslint-disable-line no-useless-escape const urlRegex = /(?:\b(?:https?|ftp):\/\/)([\w.~:\/?#[\]@!$&'()*+,;=\u200c\u200b-]{2,})/g; // eslint-disable-line no-useless-escape if (!element) { throw new Error('element is invalid'); } function handleTextNode(textNode) { const textNodeParent = textNode.parentNode; if (textNode.nodeName !== '#text' || textNodeParent.nodeName === 'SCRIPT' || textNodeParent.nodeName === 'STYLE' ) { //Don't do anything except on text nodes, which are not children // of