Stack Exchange comment template context menu

Adds a context menu (right click, long press, command click, etc) to comment boxes on Stack Exchange with customizable pre-written responses.

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

  1. // ==UserScript==
  2. // @name Stack Exchange comment template context menu
  3. // @namespace http://ostermiller.org/
  4. // @version 1.10
  5. // @description Adds a context menu (right click, long press, command click, etc) to comment boxes on Stack Exchange with customizable pre-written responses.
  6. // @match https://*.stackexchange.com/questions/*
  7. // @match https://*.stackexchange.com/review/*
  8. // @match https://*.stackoverflow.com/*questions/*
  9. // @match https://*.stackoverflow.com/review/*
  10. // @match https://*.askubuntu.com/questions/*
  11. // @match https://*.askubuntu.com/review/*
  12. // @match https://*.superuser.com/questions/*
  13. // @match https://*.superuser.com/review/*
  14. // @match https://*.serverfault.com/questions/*
  15. // @match https://*.serverfault.com/review/*
  16. // @match https://*.mathoverflow.net/questions/*
  17. // @match https://*.mathoverflow.net/review/*
  18. // @match https://*.stackapps.com/questions/*
  19. // @match https://*.stackapps.com/review/*
  20. // @connect raw.githubusercontent.com
  21. // @connect *
  22. // @grant GM_addStyle
  23. // @grant GM_setValue
  24. // @grant GM_getValue
  25. // @grant GM_deleteValue
  26. // @grant GM_xmlhttpRequest
  27. // ==/UserScript==
  28. (function() {
  29. 'use strict'
  30.  
  31. // Access to JavaScript variables from the Stack Exchange site
  32. var $ = unsafeWindow.jQuery
  33.  
  34. // eg. physics.stackexchange.com -> physics
  35. function validateSite(s){
  36. var m = /^((?:meta\.)?[a-z0-9]+(?:\.meta)?)\.?[a-z0-9\.]*$/.exec(s.toLowerCase().trim().replace(/^(https?:\/\/)?(www\.)?/,""))
  37. if (!m) return null
  38. return m[1]
  39. }
  40.  
  41. function validateTag(s){
  42. return s.toLowerCase().trim().replace(/ +/,"-")
  43. }
  44.  
  45. // eg hello-world, hello-worlds, hello world, hello worlds, and hw all map to hello-world
  46. function makeFilterMap(s){
  47. var m = {}
  48. s=s.split(/,/)
  49. for (var i=0; i<s.length; i++){
  50. // original
  51. m[s[i]] = s[i]
  52. // plural
  53. m[s[i]+"s"] = s[i]
  54. // with spaces
  55. m[s[i].replace(/-/g," ")] = s[i]
  56. // plural with spaces
  57. m[s[i].replace(/-/g," ")+"s"] = s[i]
  58. // abbreviation
  59. m[s[i].replace(/([a-z])[a-z]+(-|$)/g,"$1")] = s[i]
  60. }
  61. return m
  62. }
  63.  
  64. var userMapInput = "moderator,user"
  65. var userMap = makeFilterMap(userMapInput)
  66. function validateUser(s){
  67. return userMap[s.toLowerCase().trim()]
  68. }
  69.  
  70. var typeMapInput = "question,answer,edit-question,edit-answer,close-question,flag-comment,flag-question,flag-answer,decline-flag,helpful-flag,reject-edit"
  71. var typeMap = makeFilterMap(typeMapInput)
  72. typeMap.c = 'close-question'
  73. typeMap.close = 'close-question'
  74.  
  75. function loadComments(urls){
  76. loadCommentsRecursive([], urls.split(/[\r\n ]+/))
  77. }
  78.  
  79. function loadCommentsRecursive(aComments, aUrls){
  80. if (!aUrls.length) {
  81. if (aComments.length){
  82. comments = aComments
  83. storeComments()
  84. if(GM_getValue(storageKeys.url)){
  85. GM_setValue(storageKeys.lastUpdate, Date.now())
  86. }
  87. }
  88. return
  89. }
  90. var url = aUrls.pop()
  91. if (!url){
  92. loadCommentsRecursive(aComments, aUrls)
  93. return
  94. }
  95. console.log("Loading comments from " + url)
  96. GM_xmlhttpRequest({
  97. method: "GET",
  98. url: url,
  99. onload: function(r){
  100. var lComments = parseComments(r.responseText)
  101. if (!lComments || !lComments.length){
  102. alert("No comment templates loaded from " + url)
  103. } else {
  104. aComments = aComments.concat(lComments)
  105. }
  106. loadCommentsRecursive(aComments, aUrls)
  107. },
  108. onerror: function(){
  109. alert("Could not load comment templates from " + url)
  110. loadCommentsRecursive(aComments, aUrls)
  111. }
  112. })
  113. }
  114.  
  115. function validateType(s){
  116. return typeMap[s.toLowerCase().trim()]
  117. }
  118.  
  119. // Map of functions that clean up the filter-tags on comment templates
  120. var tagValidators = {
  121. tags: validateTag,
  122. sites: validateSite,
  123. users: validateUser,
  124. types: validateType
  125. }
  126.  
  127. var attributeValidators = {
  128. socvr: trim
  129. }
  130.  
  131. function trim(s){
  132. return s.trim()
  133. }
  134.  
  135. // Given a filter tag name and an array of filter tag values,
  136. // clean up and canonicalize each of them
  137. // Put them into a hash set (map each to true) for performant lookups
  138. function validateAllTagValues(tag, arr){
  139. var ret = {}
  140. for (var i=0; i<arr.length; i++){
  141. // look up the validation function for the filter tag type and call it
  142. var v = tagValidators[tag](arr[i])
  143. // Put it in the hash set
  144. if (v) ret[v]=1
  145. }
  146. if (Object.keys(ret).length) return ret
  147. return null
  148. }
  149.  
  150. function validateValues(tag, value){
  151. if (tag in tagValidators) return validateAllTagValues(tag, value.split(/,/))
  152. if (tag in attributeValidators) return attributeValidators[tag](value)
  153. return null
  154. }
  155.  
  156. // List of keys used for storage, centralized for multiple usages
  157. var storageKeys = {
  158. comments: "ctcm-comments",
  159. url: "ctcm-url",
  160. lastUpdate: "ctcm-last-update"
  161. }
  162.  
  163. // On-load, parse comment templates from local storage
  164. var comments = parseComments(GM_getValue(storageKeys.comments))
  165. // The download comment templates from URL if configured
  166. if(GM_getValue(storageKeys.url)){
  167. loadStorageUrlComments()
  168. } else if (!comments || !comments.length){
  169. // If there are NO comments, fetch the defaults
  170. loadComments("https://raw.githubusercontent.com/stephenostermiller/stack-exchange-comment-templates/master/default-templates.txt")
  171. }
  172.  
  173. checkCommentLengths()
  174. function checkCommentLengths(){
  175. for (var i=0; i<comments.length; i++){
  176. var c = comments[i]
  177. var length = c.comment.length;
  178. if (length > 600){
  179. console.log("Comment template is too long (" + length + "/600): " + c.title)
  180. } else if (length > 500 && (!c.types || c.types['flag-question'] || c.types['flag-answer'])){
  181. console.log("Comment template is too long for flagging posts (" + length + "/500): " + c.title)
  182. } else if (length > 300 && (!c.types || c.types['edit-question'] || c.types['edit-answer'])){
  183. console.log("Comment template is too long for an edit (" + length + "/300): " + c.title)
  184. } else if (length > 200 && (!c.types || c.types['decline-flag'] || c.types['helpful-flag'])){
  185. console.log("Comment template is too long for flag handling (" + length + "/200): " + c.title)
  186. } else if (length > 200 && (!c.types || c.types['flag-comment'])){
  187. console.log("Comment template is too long for flagging comments (" + length + "/200): " + c.title)
  188. }
  189. }
  190. }
  191.  
  192. // Serialize the comment templates into local storage
  193. function storeComments(){
  194. if (!comments || !comments.length) GM_deleteValue(storageKeys.comments)
  195. else GM_setValue(storageKeys.comments, exportComments())
  196. }
  197.  
  198. function parseJsonpComments(s){
  199. var cs = []
  200. var callback = function(o){
  201. for (var i=0; i<o.length; i++){
  202. var c = {
  203. title: o[i].name,
  204. comment: o[i].description
  205. }
  206. var m = /^(?:\[([A-Z,]+)\])\s*(.*)$/.exec(c.title);
  207. if (m){
  208. c.title=m[2]
  209. c.types=validateValues("types",m[1])
  210. }
  211. if (c && c.title && c.comment) cs.push(c)
  212. }
  213. }
  214. eval(s)
  215. return cs
  216. }
  217.  
  218. function parseComments(s){
  219. if (!s) return []
  220. if (s.startsWith("callback(")) return parseJsonpComments(s)
  221. var lines = s.split(/\n|\r|\r\n/)
  222. var c, m, cs = []
  223. for (var i=0; i<lines.length; i++){
  224. var line = lines[i].trim()
  225. if (!line){
  226. // Blank line indicates end of comment
  227. if (c && c.title && c.comment) cs.push(c)
  228. c=null
  229. } else {
  230. // Comment template title
  231. // Starts with #
  232. // May contain type filter tag abbreviations (for compat with SE-AutoReviewComments)
  233. // eg # Comment title
  234. // eg ### [Q,A] Commment title
  235. m = /^#+\s*(?:\[([A-Z,]+)\])?\s*(.*)$/.exec(line);
  236. if (m){
  237. // Stash previous comment if it wasn't already ended by a new line
  238. if (c && c.title && c.comment) cs.push(c)
  239. // Start a new comment with title
  240. c={title:m[2]}
  241. // Handle type filter tags if they exist
  242. if (m[1]) c.types=validateValues("types",m[1])
  243. } else if (c) {
  244. // Already started parsing a comment, look for filter tags and comment body
  245. m = /^(sites|types|users|tags|socvr)\:\s*(.*)$/.exec(line);
  246. if (m){
  247. // Add filter tags
  248. c[m[1]]=validateValues(m[1],m[2])
  249. } else {
  250. // Comment body (join multiple lines with spaces)
  251. if (c.comment) c.comment=c.comment+" "+line
  252. else c.comment=line
  253. }
  254. } else {
  255. // No comment started, didn't find a comment title
  256. console.log("Could not parse line from comment templates: " + line)
  257. }
  258. }
  259. }
  260. // Stash the last comment if it isn't followed by a new line
  261. if (c && c.title && c.comment) cs.push(c)
  262. return cs
  263. }
  264.  
  265. function sort(arr){
  266. if (!(arr instanceof Array)) arr = Object.keys(arr)
  267. arr.sort()
  268. return arr
  269. }
  270.  
  271. function exportComments(){
  272. var s ="";
  273. for (var i=0; i<comments.length; i++){
  274. var c = comments[i]
  275. s += "# " + c.title + "\n"
  276. s += c.comment + "\n"
  277. if (c.types) s += "types: " + sort(c.types).join(", ") + "\n"
  278. if (c.sites) s += "sites: " + sort(c.sites).join(", ") + "\n"
  279. if (c.users) s += "users: " + sort(c.users).join(", ") + "\n"
  280. if (c.tags) s += "tags: " + sort(c.tags).join(", ") + "\n"
  281. if (c.socvr) s += "socvr: " + c.socvr + "\n"
  282. s += "\n"
  283. }
  284. return s;
  285. }
  286.  
  287. // inner lightbox content area
  288. var ctcmi = $('<div id=ctcm-menu>')
  289. // outer translucent lightbox background that covers the whole page
  290. var ctcmo = $('<div id=ctcm-back>').append(ctcmi)
  291. GM_addStyle("#ctcm-back{z-index:999998;display:none;position:fixed;left:0;top:0;width:100vw;height:100vh;background:rgba(0,0,0,.5)}")
  292. GM_addStyle("#ctcm-menu{z-index:999999;min-width:320px;position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);background:var(--white);border:5px solid var(--theme-header-foreground-color);padding:1em;max-width:100vw;max-height:100vh;overflow:auto}")
  293. GM_addStyle(".ctcm-body{display:none;background:var(--black-050);padding:.3em;cursor: pointer;")
  294. GM_addStyle(".ctcm-expand{float:right;cursor: pointer;}")
  295. GM_addStyle(".ctcm-title{margin-top:.3em;cursor: pointer;}")
  296. GM_addStyle("#ctcm-menu textarea{width:90vw;min-width:300px;max-width:1000px;height:60vh;resize:both;display:block}")
  297. GM_addStyle("#ctcm-menu input[type='text']{width:90vw;min-width:300px;max-width:1000px;display:block}")
  298. GM_addStyle("#ctcm-menu button{margin-top:1em;margin-right:.5em}")
  299.  
  300. // Node input: text field where content can be written.
  301. // Used for filter tags to know which comment templates to show in which contexts.
  302. // Also used for knowing which clicks should show the context menu,
  303. // if a type isn't returned by this method, no menu will show up
  304. function getType(node){
  305. var prefix = "";
  306.  
  307. // Most of these rules use properties of the node or the node's parents
  308. // to deduce their context
  309.  
  310. if (node.is('.js-rejection-reason-custom')) return "reject-edit"
  311. if (node.parents('.js-comment-flag-option').length) return "flag-comment"
  312. if (node.parents('.js-flagged-post').length){
  313. if (/decline/.exec(node.attr('placeholder'))) return "decline-flag"
  314. else return "helpful-flag"
  315. }
  316.  
  317. if (node.parents('.site-specific-pane').length) prefix = "close-"
  318. else if (node.parents('.mod-attention-subform').length) prefix = "flag-"
  319. else if (node.is('.edit-comment,#edit-comment')) prefix = "edit-"
  320. else if(node.is('.js-comment-text-input')) prefix = ""
  321. else return null
  322.  
  323. if (node.parents('#question,.question').length) return prefix + "question"
  324. if (node.parents('#answers,.answer').length) return prefix + "answer"
  325.  
  326. // Fallback for single post edit page
  327. if (node.parents('.post-form').find('h2:last').text()=='Question') return prefix + "question"
  328. if (node.parents('.post-form').find('h2:last').text()=='Answer') return prefix + "answer"
  329.  
  330. return null
  331. }
  332.  
  333. // Mostly moderator or non-moderator (user.)
  334. // Not-logged in and low rep users are not able to comment much
  335. // and are unlikely to use this tool, no need to identify them
  336. // and give them special behavior.
  337. // Maybe add a class for staff in the future?
  338. var userclass
  339. function getUserClass(){
  340. if (!userclass){
  341. if ($('.js-mod-inbox-button').length) userclass="moderator"
  342. else if ($('.s-topbar--item.s-user-card').length) userclass="user"
  343. else userclass="anonymous"
  344. }
  345. return userclass
  346. }
  347.  
  348. // The Stack Exchange site this is run on (just the subdoman, eg "stackoverflow")
  349. var site
  350. function getSite(){
  351. if(!site) site=validateSite(location.hostname)
  352. return site
  353. }
  354.  
  355. // Which tags are on the question currently being viewed
  356. var tags
  357. function getTags(){
  358. if(!tags) tags=$.map($('.post-taglist .post-tag'),function(tag){return $(tag).text()})
  359. return tags
  360. }
  361.  
  362. // The id of the question currently being viewed
  363. function getQuestionId(){
  364. if (!varCache.questionid) varCache.questionid=$('.question').attr('data-questionid')
  365. var l = $('.answer-hyperlink')
  366. if (!varCache.questionid && l.length) varCache.questionid=l.attr('href').replace(/^\/questions\/([0-9]+).*/,"$1")
  367. if (!varCache.questionid) varCache.questionid="-"
  368. return varCache.questionid
  369. }
  370.  
  371. // The human readable name of the current Stack Exchange site
  372. function getSiteName(){
  373. if (!varCache.sitename) varCache.sitename = $('meta[property="og:site_name"]').attr('content').replace(/ ?Stack Exchange/, "")
  374. return varCache.sitename
  375. }
  376.  
  377. // The Stack Exchange user id for the person using this tool
  378. function getMyUserId() {
  379. if (!varCache.myUserId) varCache.myUserId = $('a.s-topbar--item.s-user-card').attr('href').replace(/^\/users\/([0-9]+)\/.*/,"$1")
  380. return varCache.myUserId
  381. }
  382.  
  383. // The full host name of the Stack Exchange site
  384. function getSiteUrl(){
  385. if (!varCache.siteurl) varCache.siteurl = location.hostname
  386. return varCache.siteurl
  387. }
  388.  
  389. // Store the comment text field that was clicked on
  390. // so that it can be filled with the comment template
  391. var commentTextField
  392.  
  393. // Insert the comment template into the text field
  394. // called when a template is clicked in the dialog box
  395. // so "this" refers to the clicked item
  396. function insertComment(){
  397. // The comment to insert is stored in a div
  398. // near the item that was clicked
  399. var body = $(this).parent().children('.ctcm-body')
  400. var socvr = body.attr('data-socvr')
  401. if (socvr){
  402. var url = "//" + getSiteUrl() + "/questions/" + getQuestionId()
  403. var title = $('h1').first().text()
  404. title = new Option(title).innerHTML
  405. $('#content').prepend($(`<div style="border:5px solid blue;padding:.7em;margin:.5em 0"><a target=_blank href=//chat.stackoverflow.com/rooms/41570/so-close-vote-reviewers>SOCVR: </a><div>[tag:cv-pls] ${socvr} [${title}](${url})</div></div>`))
  406. }
  407. var cmt = body.text()
  408.  
  409. // Put in the comment
  410. commentTextField.val(cmt).focus()
  411.  
  412. // highlight place for additional input,
  413. // if specified in the template
  414. var typeHere="[type here]"
  415. var typeHereInd = cmt.indexOf(typeHere)
  416. if (typeHereInd >= 0) commentTextField[0].setSelectionRange(typeHereInd, typeHereInd + typeHere.length)
  417.  
  418. closeMenu()
  419. }
  420.  
  421. // User clicked on the expand icon in the dialog
  422. // to show the full text of a comment
  423. function expandFullComment(){
  424. $(this).parent().children('.ctcm-body').show()
  425. $(this).hide()
  426. }
  427.  
  428. // Apply comment tag filters
  429. // For a given comment, say whether it
  430. // should be shown given the current context
  431. function commentMatches(comment, type, user, site, tags){
  432. if (comment.types && !comment.types[type]) return false
  433. if (comment.users && !comment.users[user]) return false
  434. if (comment.sites && !comment.sites[site]) return false
  435. if (comment.tags){
  436. var hasTag = false
  437. for(var i=0; tags && i<tags.length; i++){
  438. if (comment.tags[tags[i]]) hasTag=true
  439. }
  440. if(!hasTag) return false
  441. }
  442. return true
  443. }
  444.  
  445. // User clicked "Save" when editing the list of comment templates
  446. function doneEditing(){
  447. comments = parseComments($(this).prev('textarea').val())
  448. storeComments()
  449. closeMenu()
  450. }
  451.  
  452. // Show the edit comment dialog
  453. function editComments(){
  454. // Pointless to edit comments that will just get overwritten
  455. // If there is a URL, only allow the URL to be edited
  456. if(GM_getValue(storageKeys.url)) return urlConf()
  457. ctcmi.html(
  458. "<pre># Comment title\n"+
  459. "Comment body\n"+
  460. "types: "+typeMapInput.replace(/,/g, ", ")+"\n"+
  461. "users: "+userMapInput.replace(/,/g, ", ")+"\n"+
  462. "sites: stackoverflow, physics, meta.stackoverflow, physics.meta, etc\n"+
  463. "tags: javascript, python, etc\n"+
  464. "socvr: Message for Stack Overflow close vote reviews chat</pre>"+
  465. "<p>types, users, sites, tags, and socvr are optional.</p>"
  466. )
  467. ctcmi.append($('<textarea>').val(exportComments()))
  468. ctcmi.append($('<button>Save</Button>').click(doneEditing))
  469. ctcmi.append($('<button>Cancel</Button>').click(closeMenu))
  470. ctcmi.append($('<button>From URL...</Button>').click(urlConf))
  471. return false
  472. }
  473.  
  474. function getAuthorNode(postNode){
  475. return postNode.find('.post-signature .user-details[itemprop="author"]')
  476. }
  477.  
  478. function getOpNode(){
  479. if (!varCache.opNode) varCache.opNode = getAuthorNode($('#question,.question'))
  480. return varCache.opNode
  481. }
  482.  
  483. function getUserNodeId(node){
  484. if (!node) return "-"
  485. var link = node.find('a')
  486. if (!link.length) return "-"
  487. var href = link.attr('href')
  488. if (!href) return "-"
  489. return href.replace(/[^0-9]+/g, "")
  490. }
  491.  
  492. function getOpId(){
  493. if (!varCache.opId) varCache.opId = getUserNodeId(getOpNode())
  494. return varCache.opId
  495. }
  496.  
  497. function getUserNodeName(node){
  498. if (!node) return "-"
  499. var link = node.find('a')
  500. if (!link.length) return "-"
  501. // Remove spaces from user names so that they can be used in @name references
  502. return link.text().replace(/ /,"")
  503. }
  504.  
  505. function getOpName(){
  506. if (!varCache.opName) varCache.opName = getUserNodeName(getOpNode())
  507. return varCache.opName
  508. }
  509.  
  510. function getUserNodeRep(node){
  511. if (!node) return "-"
  512. var r = node.find('.reputation-score')
  513. if (!r.length) return "-"
  514. return r.text()
  515. }
  516.  
  517. function getOpRep(){
  518. if (!varCache.opRep) varCache.opRep = getUserNodeRep(getOpNode())
  519. return varCache.opRep
  520. }
  521.  
  522. function getPostNode(){
  523. if (!varCache.postNode) varCache.postNode = commentTextField.parents('#question,.question,.answer')
  524. return varCache.postNode
  525. }
  526.  
  527. function getPostAuthorNode(){
  528. if (!varCache.postAuthorNode) varCache.postAuthorNode = getAuthorNode(getPostNode())
  529. return varCache.postAuthorNode
  530. }
  531.  
  532. function getAuthorId(){
  533. if (!varCache.authorId) varCache.authorId = getUserNodeId(getPostAuthorNode())
  534. return varCache.authorId
  535. }
  536.  
  537. function getAuthorName(){
  538. if (!varCache.authorName) varCache.authorName = getUserNodeName(getPostAuthorNode())
  539. return varCache.authorName
  540. }
  541.  
  542. function getAuthorRep(){
  543. if (!varCache.authorRep) varCache.authorRep = getUserNodeRep(getPostAuthorNode())
  544. return varCache.authorRep
  545. }
  546.  
  547. function getPostId(){
  548. var postNode = getPostNode();
  549. if (!postNode.length) return "-"
  550. if (postNode.attr('data-questionid')) return postNode.attr('data-questionid')
  551. if (postNode.attr('data-answerid')) return postNode.attr('data-answerid')
  552. return "-"
  553. }
  554.  
  555. // Map of variables to functions that return their replacements
  556. var varMap = {
  557. 'SITENAME': getSiteName,
  558. 'SITEURL': getSiteUrl,
  559. 'MYUSERID': getMyUserId,
  560. 'QUESTIONID': getQuestionId,
  561. 'OPID': getOpId,
  562. 'OPNAME': getOpName,
  563. 'OPREP': getOpRep,
  564. 'POSTID': getPostId,
  565. 'AUTHORID': getAuthorId,
  566. 'AUTHORNAME': getAuthorName,
  567. 'AUTHORREP': getAuthorRep
  568. }
  569.  
  570. function logVars(){
  571. var varnames = Object.keys(varMap)
  572. for (var i=0; i<varnames.length; i++){
  573. console.log(varnames[i] + ": " + varMap[varnames[i]]())
  574. }
  575. }
  576.  
  577. // Build regex to find variables from keys of map
  578. var varRegex = new RegExp('\\$('+Object.keys(varMap).join('|')+')\\$?', 'g')
  579. function fillVariables(s){
  580. // Perform the variable replacement
  581. return s.replace(varRegex, function (m) {
  582. // Remove $ before looking up in map
  583. return varMap[m.replace(/\$/g,"")]()
  584. });
  585. }
  586.  
  587. // Show the URL configuration dialog
  588. function urlConf(){
  589. var url = GM_getValue(storageKeys.url)
  590. ctcmi.html(
  591. "<p>Comments will be loaded from these URLs when saved and once a day afterwards. Multiple URLs can be specified, each on its own line. Github raw URLs have been whitelisted. Other URLs will ask for your permission.</p>"
  592. )
  593. if (url) ctcmi.append("<p>Remove all the URLs to be able to edit the comments in your browser.</p>")
  594. else ctcmi.append("<p>Using a URL will <b>overwrite</b> any edits to the comments you have made.</p>")
  595. ctcmi.append($('<textarea placeholder=https://raw.githubusercontent.com/user/repo/123/stack-exchange-comments.txt>').val(url))
  596. ctcmi.append($('<button>Save</Button>').click(doneUrlConf))
  597. ctcmi.append($('<button>Cancel</Button>').click(closeMenu))
  598. return false
  599. }
  600.  
  601. // User clicked "Save" in URL configuration dialog
  602. function doneUrlConf(){
  603. GM_setValue(storageKeys.url, $(this).prev('textarea').val())
  604. // Force a load by removing the timestamp of the last load
  605. GM_deleteValue(storageKeys.lastUpdate)
  606. loadStorageUrlComments()
  607. closeMenu()
  608. }
  609.  
  610. // Look up the URL from local storage, fetch the URL
  611. // and parse the comment templates from it
  612. // unless it has already been done recently
  613. function loadStorageUrlComments(){
  614. var url = GM_getValue(storageKeys.url)
  615. if (!url) return
  616. var lu = GM_getValue(storageKeys.lastUpdate);
  617. if (lu && lu > Date.now() - 8600000) return
  618. loadComments(url)
  619. }
  620.  
  621. // Hook into clicks for the entire page that should show a context menu
  622. // Only handle the clicks on comment input areas (don't prevent
  623. // the context menu from appearing in other places.)
  624. $(document).contextmenu(function(e){
  625. var target = $(e.target)
  626. if (target.is('.comments-link')){
  627. // The "Add a comment" link
  628. var parent = target.parents('.answer,#question,.question')
  629. // Show the comment text area
  630. target.trigger('click')
  631. // Bring up the context menu for it
  632. showMenu(parent.find('textarea'))
  633. e.preventDefault()
  634. return false
  635. } else if (target.closest('#review-action-Reject,label[for="review-action-Reject"]').length){
  636. // Suggested edit review queue - reject
  637. target.trigger('click')
  638. $('button.js-review-submit').trigger('click')
  639. setTimeout(function(){
  640. // Click "causes harm"
  641. $('#rejection-reason-0').trigger('click')
  642. },100)
  643. setTimeout(function(){
  644. showMenu($('#rejection-reason-0').parents('.flex--item').find('textarea'))
  645. },200)
  646. e.preventDefault()
  647. return false
  648. } else if (target.closest('#review-action-Unsalvageable,label[for="review-action-Unsalvageable"]').length){
  649. // Triage review queue - unsalvageable
  650. target.trigger('click')
  651. $('button.js-review-submit').trigger('click')
  652. showMenuInFlagDialog()
  653. e.preventDefault()
  654. return false
  655. } else if (target.is('.js-flag-post-link')){
  656. // the "Flag" link for a question or answer
  657. // Click it to show pop up
  658. target.trigger('click')
  659. showMenuInFlagDialog()
  660. e.preventDefault()
  661. return false
  662. } else if (target.closest('.js-comment-flag').length){
  663. // The flag icon next to a comment
  664. target.trigger('click')
  665. setTimeout(function(){
  666. // Click "Something else"
  667. $('#comment-flag-type-CommentOther').prop('checked',true).parents('.js-comment-flag-option').find('.js-required-comment').removeClass('d-none')
  668. },100)
  669. setTimeout(function(){
  670. showMenu($('#comment-flag-type-CommentOther').parents('.js-comment-flag-option').find('textarea'))
  671. },200)
  672. e.preventDefault()
  673. return false
  674. } else if (target.closest('#review-action-Close,label[for="review-action-Close"],#review-action-NeedsAuthorEdit,label[for="review-action-NeedsAuthorEdit"]').length){
  675. // Close votes review queue - close action
  676. // or Triage review queue - needs author edit action
  677. target.trigger('click')
  678. $('button.js-review-submit').trigger('click')
  679. showMenuInCloseDialog()
  680. e.preventDefault()
  681. return false
  682. } else if (target.is('.js-close-question-link')){
  683. // The "Close" link for a question
  684. target.trigger('click')
  685. showMenuInCloseDialog()
  686. e.preventDefault()
  687. return false
  688. } else if (target.is('textarea,input[type="text"]') && (!target.val() || target.val() == target[0].defaultValue)){
  689. // A text field that is blank or hasn't been modified
  690. var type = getType(target)
  691. //console.log("Type: " + type)
  692. if (type){
  693. // A text field for entering a comment
  694. showMenu(target)
  695. e.preventDefault()
  696. return false
  697. }
  698. }
  699. })
  700.  
  701. function showMenuInFlagDialog(){
  702. // Wait for the popup
  703. setTimeout(function(){
  704. $('input[value="PostOther"]').trigger('click')
  705. },100)
  706. setTimeout(function(){
  707. showMenu($('input[value="PostOther"]').parents('label').find('textarea'))
  708. },200)
  709. }
  710.  
  711. function showMenuInCloseDialog(){
  712. setTimeout(function(){
  713. $('#closeReasonId-SiteSpecific').trigger('click')
  714. },100)
  715. setTimeout(function(){
  716. $('#siteSpecificCloseReasonId-other').trigger('click')
  717. },200)
  718. setTimeout(function(){
  719. showMenu($('#siteSpecificCloseReasonId-other').parents('.js-popup-radio-action').find('textarea'))
  720. },300)
  721. }
  722.  
  723. var varCache={} // Cache variables so they don't have to be looked up for every single question
  724. function showMenu(target){
  725. varCache={} // Clear the variable cache
  726. commentTextField=target
  727. var type = getType(target)
  728. var user = getUserClass()
  729. var site = getSite()
  730. var tags = getTags()
  731. ctcmi.html("")
  732. //logVars()
  733. for (var i=0; i<comments.length; i++){
  734. if(commentMatches(comments[i], type, user, site, tags)){
  735. ctcmi.append(
  736. $('<div class=ctcm-comment>').append(
  737. $('<span class=ctcm-expand>\u25bc</span>').click(expandFullComment)
  738. ).append(
  739. $('<h4 class=ctcm-title>').text(comments[i].title).click(insertComment)
  740. ).append(
  741. $('<div class=ctcm-body>').text(fillVariables(comments[i].comment)).click(insertComment).attr('data-socvr',comments[i].socvr||"")
  742. )
  743. )
  744. }
  745. }
  746. ctcmi.append($('<button>Edit</Button>').click(editComments))
  747. ctcmi.append($('<button>Cancel</Button>').click(closeMenu))
  748. target.parents('.popup,#modal-base,body').first().append(ctcmo)
  749. ctcmo.show()
  750. }
  751.  
  752. function closeMenu(){
  753. ctcmo.hide()
  754. ctcmo.remove()
  755. }
  756.  
  757. // Hook into clicks anywhere in the document
  758. // and listen for ones that related to our dialog
  759. $(document).click(function(e){
  760. if(ctcmo.is(':visible')){
  761. // dialog is open
  762. if($(e.target).parents('#ctcm-back').length == 0) {
  763. // click wasn't on the dialog itself
  764. closeMenu()
  765. }
  766. // Clicks when the dialog are open belong to us,
  767. // prevent other things from happening
  768. e.preventDefault()
  769. return false
  770. }
  771. })
  772. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址