Text Highlight and Seek

Automatically highlight user-defined text with Seek function (2015-10-11)

目前为 2015-10-11 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Text Highlight and Seek
  3. // @author erosman and Jefferson "jscher2000" Scher
  4. // @namespace JeffersonScher
  5. // @version 2.0.2
  6. // @description Automatically highlight user-defined text with Seek function (2015-10-11)
  7. // @include https://greasyfork.org/*
  8. // @include https://openuserjs.org/*
  9. // @grant GM_registerMenuCommand
  10. // @grant GM_setValue
  11. // @grant GM_getValue
  12. // @grant GM_getResourceURL
  13. // @copyright Copyright 2015 Jefferson Scher. Portions created by erosman.
  14. // @license BSD 3-clause
  15. // @resource mycon http://www.jeffersonscher.com/gm/src/gfrk-THS-ver202.png
  16. // ==/UserScript==
  17. var script_about = "https://greasyfork.org/scripts/13007-text-highlight-and-seek";
  18.  
  19. /* --------- Note ---------
  20. TO INCLUDE SITES (only Greasy Fork and OpenUserJS are initially included):
  21.  
  22. Go to Add-ons - User Scripts (Ctrl+Shift+a/Cmd+Shift+a on Firefox Windows/Mac)
  23. Click on the Script's Option
  24. Under User Settings Tab, Add Included/Excluded Pages that you want the script to run on
  25. Click OK
  26.  
  27. Note from erosman: If you find that another script clashes with this script, set Text Highlighter 2015 to Execute first.
  28. Go to Add-ons - User Scripts ('Ctrl+ Shift + a' on Firefox)
  29. Right Click on the Script
  30. On the context menu click: Execute first
  31.  
  32. On Add-ons - User Scripts, you can also Click on the Execution Order (top Right) and
  33. change the execution order so that Text Highlighter runs before those scripts that clashes with it.
  34. */
  35.  
  36. (function() { // anonymous function wrapper, used for error checking & limiting scope
  37. 'use strict';
  38. if (window.self !== window.top) { return; } // end execution if in a frame ; maybe this can be relaxed someday?
  39.  
  40. // sample keyword+style object to get started
  41. var hlobjDefault = {
  42. "set100" : {
  43. keywords : "scripts|script",
  44. type : "string",
  45. hlpat : "",
  46. textcolor : "rgb(0,0,0)",
  47. backcolor : "rgb(255,255,128)",
  48. fontweight : "inherit",
  49. custom : "",
  50. enabled : "true",
  51. visible : "true",
  52. updated : ""
  53. },
  54. "set099" : {
  55. keywords : "site",
  56. type : "word",
  57. hlpat : "",
  58. textcolor : "rgb(0,0,0)",
  59. backcolor : "rgb(255,192,255)",
  60. fontweight : "inherit",
  61. custom : "",
  62. enabled : "true",
  63. visible : "true",
  64. updated : ""
  65. },
  66. "set098" : {
  67. keywords : "^October \\d{1,2}",
  68. type : "regex",
  69. hlpat : "",
  70. textcolor : "rgb(0,0,0)",
  71. backcolor : "rgb(192,255,255)",
  72. fontweight : "inherit",
  73. custom : "",
  74. enabled : "true",
  75. visible : "true",
  76. updated : ""
  77. }
  78. };
  79. var kwhieditstyle = ["rgb(0,0,255)","rgb(255,255,0)","inherit",""];
  80.  
  81. // read pref storage: keyword-style sets
  82. var hljson = GM_getValue("kwstyles");
  83. if (!hljson || hljson.length == 0){
  84. var hlobj = hlobjDefault;
  85. // check for legacy preferences
  86. var kwold = GM_getValue("keywords");
  87. if (kwold) if(kwold.length > 0) {
  88. hlobj.set100.keywords = kwold.split(',').join('|');
  89. }
  90. var hlold = GM_getValue("highlightStyle");
  91. if (hlold) if(hlold.length > 0) {
  92. // really should try to parse this, but for now...
  93. hlobj.set100.custom = hlold;
  94. }
  95. // save starting values
  96. hljson = JSON.stringify(hlobj);
  97. GM_setValue("kwstyles",hljson);
  98. } else {
  99. var hlobj = JSON.parse(hljson);
  100. }
  101. // global keys array
  102. var hlkeys = Object.keys(hlobj);
  103.  
  104. // read/set other prefs
  105. var hlbtnvis = GM_getValue("hlbtnvis");
  106. if (!hlbtnvis){
  107. hlbtnvis = "on";
  108. GM_setValue("hlbtnvis",hlbtnvis);
  109. }
  110. var hlprecode = GM_getValue("hlprecode");
  111. if (!hlprecode){
  112. hlprecode = true;
  113. GM_setValue("hlprecode",hlprecode);
  114. }
  115. var hlnextset = GM_getValue("hlnextset");
  116. if (!hlnextset){
  117. hlnextset = 101;
  118. GM_setValue("hlnextset",hlnextset);
  119. }
  120. // Inject CSS
  121. function insertCSS(setkeys){
  122. for (var j = 0; j < setkeys.length; ++j){
  123. var hlset = setkeys[j];
  124. if (hlobj[hlset].visible == "true"){
  125. var rule = "."+hlset+"{display:inline!important;";
  126. if (hlobj[hlset].textcolor.length > 0) rule += "color:"+hlobj[hlset].textcolor+";";
  127. if (hlobj[hlset].backcolor.length > 0) rule += "background-color:"+hlobj[hlset].backcolor+";";
  128. if (hlobj[hlset].fontweight.length > 0) rule += "font-weight:"+hlobj[hlset].fontweight+";";
  129. if (hlobj[hlset].custom.length > 0) rule += hlobj[hlset].custom+";";
  130. rule += "}";
  131. var setrule = document.querySelector('style[hlset="' + hlset +'"]');
  132. if (!setrule){
  133. var s = document.createElement("style");
  134. s.type = "text/css";
  135. s.setAttribute("hlset", hlset);
  136. s.appendChild(document.createTextNode(rule));
  137. document.body.appendChild(s);
  138. } else {
  139. setrule.innerHTML = rule;
  140. }
  141. }
  142. }
  143. }
  144. insertCSS(hlkeys);
  145.  
  146. // Main workhorse routine
  147. function THmo_doHighlight(el,subset){
  148. if (subset) var keyset = subset;
  149. else var keyset = hlkeys;
  150. for (var j = 0; j < keyset.length; ++j) {
  151. var hlset = keyset[j];
  152. if (hlobj[hlset].visible == "true" && hlobj[hlset].enabled == "true"){
  153. var hlkeywords = hlobj[hlset].keywords;
  154. if (hlkeywords.length > 0) {
  155. if (hlobj[hlset].type != "regex"){
  156. var rQuantifiers = /[-\/\\^$*+?.()[\]{}]/g;
  157. hlkeywords = hlkeywords.replace(rQuantifiers, '\\$&');
  158. if (hlobj[hlset].type == "word"){
  159. hlkeywords = "\\b" + hlkeywords.replace(/\|/g, "\\b|\\b") + "\\b";
  160. }
  161. }
  162. //console.log("hlset:"+hlset+"\nhlkeywords:"+hlkeywords);
  163. var pat = new RegExp('(' + hlkeywords + ')', 'gi');
  164. var span = document.createElement('thdfrag');
  165. span.setAttribute("thdcontain","true");
  166. // getting all text nodes with a few exceptions
  167. if (hlprecode){
  168. var snapElements = document.evaluate(
  169. './/text()[normalize-space() != "" ' +
  170. 'and not(ancestor::style) ' +
  171. 'and not(ancestor::script) ' +
  172. 'and not(ancestor::textarea) ' +
  173. 'and not(ancestor::div[@id="thdtopbar"]) ' +
  174. 'and not(ancestor::div[@id="kwhiedit"]) ' +
  175. 'and not(parent::thdfrag[@txhidy15])]',
  176. el, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  177. } else {
  178. var snapElements = document.evaluate(
  179. './/text()[normalize-space() != "" ' +
  180. 'and not(ancestor::style) ' +
  181. 'and not(ancestor::script) ' +
  182. 'and not(ancestor::textarea) ' +
  183. 'and not(ancestor::pre) ' +
  184. 'and not(ancestor::code) ' +
  185. 'and not(ancestor::div[@id="thdtopbar"]) ' +
  186. 'and not(ancestor::div[@id="kwhiedit"]) ' +
  187. 'and not(parent::thdfrag[@txhidy15])]',
  188. el, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  189. }
  190.  
  191. if (!snapElements.snapshotItem(0)) { break; }
  192.  
  193. for (var i = 0, len = snapElements.snapshotLength; i < len; i++) {
  194. var node = snapElements.snapshotItem(i);
  195. // check if it contains the keywords
  196. if (pat.test(node.nodeValue)) {
  197. // create an element, replace the text node with an element
  198. var sp = span.cloneNode(true);
  199. sp.innerHTML = node.nodeValue.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(pat, '<thdfrag class="THmo '+hlset+'" txhidy15="'+hlset+'">$1</thdfrag>');
  200. node.parentNode.replaceChild(sp, node);
  201. // try to un-nest containers
  202. if (sp.parentNode.hasAttribute("thdcontain")) sp.outerHTML = sp.innerHTML;
  203. }
  204. }
  205. }
  206. }
  207. }
  208. }
  209. // first run
  210. THmo_doHighlight(document.body,null);
  211. // Add MutationObserver to catch content added dynamically
  212. var THmo_MutOb = (window.MutationObserver) ? window.MutationObserver : window.WebKitMutationObserver;
  213. if (THmo_MutOb){
  214. var THmo_chgMon = new THmo_MutOb(function(mutationSet){
  215. mutationSet.forEach(function(mutation){
  216. for (var i=0; i<mutation.addedNodes.length; i++){
  217. if (mutation.addedNodes[i].nodeType == 1){
  218. THmo_doHighlight(mutation.addedNodes[i],null);
  219. }
  220. }
  221. });
  222. });
  223. // attach chgMon to document.body
  224. var opts = {childList: true, subtree: true};
  225. THmo_chgMon.observe(document.body, opts);
  226. }
  227.  
  228. // Set up top highlight/seek bar
  229. var kwhibar = document.createElement("div");
  230. kwhibar.id = "thdtopbar";
  231. if (hlbtnvis == "on") var btnchk = " checked=\"checked\"";
  232. if (hlprecode) var btnprecode = " checked=\"checked\"";
  233. else var btnchk = "";
  234. kwhibar.innerHTML = "<form id=\"thdtopform\" onsubmit=\"return false\"><p id=\"thdtopbarhome\"><a href=\"" + script_about + "\" target=\"_blank\" title=\"Go to script install page\">JS</a></p>" +
  235. "<div id=\"thdtopcurrent\"><p id=\"thdtopkeywords\" title=\"Click to View, Edit, Seek, or Add Keywords\">Click here to manage keyword/highlight sets</p>" +
  236. "<div id=\"thdtopdrop\" style=\"display:none;\"><div id=\"thdtable\"><table cellspacing=\"0\"><tbody id=\"kwhitbod\"></tbody></table></div><p><button id=\"btnkwhiadd\">Add New Set</button>" +
  237. "<span style=\"float:right\"><button id=\"btnkwhiexport\">Export Sets</button> <button id=\"btnkwhiimport\">Import Sets</button> <button onclick=\"document.getElementById('thdtopdrop').style.display='none';return false;\">X</button></span></p></div></div>" +
  238. "<div id=\"thdtopfindbuttons\"><button title=\"First match\" thdaction=\"f\"><b>l</b>&#x25c0;</button> <button title=\"Previous match\" thdaction=\"p\">&#x25c0;</button> <span id=\"thdseekdesc\">Seek</span> <button title=\"Next match\" thdaction=\"n\">&#x25b6;</button> <button title=\"Last match\" thdaction=\"l\">&#x25b6;<b>l</b></button><div id=\"thdseekfail\"></div></div>" +
  239. "<div id=\"thdtopoptions\"><div>Options</div><ul><li><label title=\"Float a button in the upper right corner of the document to quickly access this panel\"><input type=\"checkbox\" id=\"chkhbtn\"" + btnchk +
  240. "> Show H button</label></li><li><label title=\"Highlight matches in &lt;pre&gt; and &lt;code&gt; tags\"><input type=\"checkbox\" id=\"chkprecode\"" + btnprecode +
  241. "> Match in pre/code</label></li></ul></div>" +
  242. "<button class=\"btnkwhiclose\" onclick=\"document.getElementById('thdtopbar').style.display='none';document.getElementById('thdtopspacer').style.display='none';return false;\" style=\"float:right\">X</button></form>" +
  243. "<style type=\"text/css\">#thdtopbar{position:fixed;top:0;left:0;height:26px;width:100%;padding:0;color:#024;background:#ddd;font-family:sans-serif;font-size:16px;line-height:16px;border-bottom:1px solid #024;z-index:2500;display:none} " +
  244. "#thdtopbar,#thdtopbar *{box-sizing:content-box;} #thdtopform{display:block;position:relative;float:left;width:100%;margin:0;border:none;} " +
  245. "#thdtopbarhome,#thdtopcurrent,#thdtopfindbuttons,#thdtopoptions{float:left;top:0;left:0;margin:0;padding:5px 8px 4px;border-right:1px solid #fff;font-size:16px;} " +
  246. "#thdtopbarhome{width:22px;text-align:center;overflow:hidden;} #thdtopbarhome a{display:block;} #thdtopbarhome img{display:block;border:none;border-radius:3px;padding:3px;margin:-3px 0 -4px 0;background-color:#fff} " +
  247. "#thdtopfindbuttons{padding-bottom:1px;position:relative} #thdtopfindbuttons button{margin:-5px 0 -2px 0;width:28px;height:18px;color:#024;background:#f0f0f0;border:1px solid #024;border-radius:4px;padding:1px 3px;} " +
  248. "#thdtopfindbuttons button:hover{background:#ffa;} #thdseekdesc{cursor:pointer} #thdtopkeywords{margin:0;width:500px;cursor:pointer;} " +
  249. "#thdseekfail{display:none;position:absolute;top:30px;left:15px;z-index:2001;width:200px;color:#f8f8f8;background:#b00;border-radius:6px;text-align:center;font-size:12px;padding:3px}" +
  250. "#thdtopkeywords span{display:inline-block;width:100%;overflow:hidden;text-overflow:ellipsis;} #thdtable{max-height:600px;overflow-y:auto;overflow-x:hidden} " +
  251. "#thdtopdrop{position:absolute;top:26px;left:38px;width:500px;margin:0 -1px 0 -1px;padding:0 8px 8px 8px;background:#ddd;border:1px solid #024;border-top:none;border-radius:0 0 6px 6px;} " +
  252. "#thdtopdrop table{width:100%;background:#fff;border-top:1px solid #000;border-left:1px solid #000;table-layout:fixed} " +
  253. "#thdtopdrop td{padding:4px 4px; vertical-align:top;border-right:1px solid #000;border-bottom:1px solid #000;} #thdtopdrop td div{word-wrap:break-word} #thdtopdrop p{margin-top:8px;margin-bottom:0;} " +
  254. "#thdtopoptions{position:relative;width:160px;height:26px;padding:0 8px;} #thdtopoptions > div{padding:5px 0 4px;} " +
  255. "#thdtopoptions ul{position:absolute;top:26px;left:0;width:160px;margin:0 -1px 0 -1px;padding:0 8px 8px 8px;background:#ddd;border:1px solid #024;border-top:none;border-radius:0 0 6px 6px;list-style:none;} " +
  256. "#thdtopoptions li{width:100%;float:left;padding:2px 0;} #thdtopoptions ul{display:none;} #thdtopoptions:hover ul{display: block;border:1px solid #024;border-top:none;} #thdtopoptions li:hover{background:#eee;}" +
  257. ".btnkwhiclose{float:right;font-size:11px;margin-top:2px;} .thdtype{color:#ccc;float:right;font-size:12px;padding-top:8px;} #thdtopbar label{font-weight:normal;display:inline;margin:0}</style>";
  258. document.body.appendChild(kwhibar);
  259. // Attach event handlers
  260. document.getElementById("thdtopkeywords").addEventListener("click",thddroptoggle,false);
  261. document.getElementById("kwhitbod").addEventListener("click",kwhiformevent,false);
  262. document.getElementById("btnkwhiadd").addEventListener("click",kwhinewset,false);
  263. document.getElementById("btnkwhiexport").addEventListener("click",kwhiexport,false);
  264. document.getElementById("btnkwhiimport").addEventListener("click",kwhiimport,false);
  265. document.getElementById("thdtopfindbuttons").addEventListener("click",thdseek,false);
  266. document.getElementById("chkhbtn").addEventListener("click",kwhihbtn,false);
  267. document.getElementById("chkprecode").addEventListener("click",kwhiprecode,false);
  268. // Add spacer at top of body
  269. var divsp = document.createElement("div");
  270. divsp.id = "thdtopspacer";
  271. divsp.setAttribute("style","clear:both;display:none");
  272. divsp.style.height = parseInt(27 - parseInt(window.getComputedStyle(document.body,null).getPropertyValue("margin-top"))) + "px";
  273. document.body.insertBefore(divsp, document.body.childNodes[0]);
  274. // Switch JS text to icon
  275. var JSBTN = document.createElement("img");
  276. JSBTN.src = GM_getResourceURL("mycon");
  277. document.querySelector("#thdtopbar a").textContent = "";
  278. document.querySelector("#thdtopbar a").appendChild(JSBTN);
  279. // Add menu item
  280. GM_registerMenuCommand("Show Text Highlighter Bar - View, Edit, Add Keywords and Styles", editKW);
  281. // Inject H button
  282. if (hlbtnvis == "off") var hbtndisp = ' style="display:none"';
  283. else hbtndisp = '';
  284. var dNew = document.createElement("div");
  285. dNew.innerHTML = '<button id="btnshowkwhi"' + hbtndisp + '>H</button><style type="text/css">#btnshowkwhi{position:fixed;top:4px;right:4px;opacity:0.2;' +
  286. 'color:#000;background-color:#ffa;font-weight:bold;font-size:12px;border:1px solid #ccc;border-radius:4px;padding:2px 3px;z-index:1999;min-width:22px;min-height:22px}' +
  287. '#btnshowkwhi:hover{opacity:0.8}@media print{#btnshowkwhi{display:none;}}</style>';
  288. document.body.appendChild(dNew);
  289. document.getElementById("btnshowkwhi").addEventListener("click",editKW,false);
  290. function editKW(e){
  291. refreshSetList();
  292. // show form
  293. document.getElementById("thdtopbar").style.display = "block";
  294. document.getElementById("thdtopspacer").style.display = "block";
  295. }
  296. function thdDropSetList(e){
  297. refreshSetList();
  298. document.getElementById("thdtopdrop").style.display = "block";
  299. }
  300. function thddroptoggle(e){
  301. if (document.getElementById("thdtopdrop").style.display == "none") thdDropSetList();
  302. else document.getElementById("thdtopdrop").style.display = "none";
  303. }
  304. function refreshSetList(e){
  305. // clear old rows from form
  306. document.getElementById("kwhitbod").innerHTML = "";
  307. // populate data - hlobj is global
  308. for (var j = 0; j < hlkeys.length; ++j){
  309. var hlset = hlkeys[j];
  310. if (hlobj[hlset].visible == "true"){
  311. if (hlobj[hlset].enabled == "true") var strchk = ' checked=\"checked\"';
  312. else var strchk = '';
  313. var newrow = document.createElement("tr");
  314. var thdtypenote = '';
  315. newrow.setAttribute("kwhiset", hlset);
  316. if(hlobj[hlset].type != "string"){
  317. thdtypenote = '<span class="thdtype">' + hlobj[hlset].type + '</span>';
  318. }
  319. if (j == 0){
  320. newrow.innerHTML = '<td style=\"width:286px\"><div class=\"' + hlset + '\">' + hlobj[hlset].keywords + '</div>' + thdtypenote + '</td>' +
  321. '<td style=\"width:195px\"><button kwhiset=\"' + hlset + '\" title=\"Bring matches into view\">Seek</button> ' +
  322. '<button kwhiset=\"' + hlset + '\">Edit</button> <label><input type=\"checkbox\" kwhiset=\"' + hlset +
  323. '\"' + strchk + '"> Enabled </label></td>';
  324. } else {
  325. newrow.innerHTML = '<td><div class=\"' + hlset + '\">' + hlobj[hlset].keywords + '</div>' + thdtypenote + '</td>' +
  326. '<td><button kwhiset=\"' + hlset + '\" title=\"Bring matches into view\">Seek</button> ' +
  327. '<button kwhiset=\"' + hlset + '\">Edit</button> <label><input type=\"checkbox\" kwhiset=\"' + hlset +
  328. '\"' + strchk + '"> Enabled </label></td>';
  329. }
  330. document.getElementById("kwhitbod").appendChild(newrow);
  331. }
  332. }
  333. }
  334. function kwhiformevent(e){
  335. if (e.target.nodeName == "INPUT"){ // Enabled checkbox
  336. var hlsetnum = e.target.getAttribute("kwhiset");
  337. kwhienabledisable(hlsetnum, e.target.checked);
  338. }
  339. if (e.target.nodeName == "BUTTON"){ // Call up edit form or find bar
  340. var hlset = e.target.getAttribute('kwhiset');
  341. if (e.target.textContent == "Edit"){
  342. // set set number attribute
  343. document.querySelector('#kwhiedit tr').setAttribute('kwhiset', hlset);
  344. // set class for keywords
  345. document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className = hlset;
  346. // enter placeholder text & type
  347. document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent = hlobj[hlset].keywords;
  348. document.getElementById("kwhipattype").selectedIndex = 0;
  349. if (hlobj[hlset].type == "word") document.getElementById("kwhipattype").selectedIndex = 1;
  350. if (hlobj[hlset].type == "regex") document.getElementById("kwhipattype").selectedIndex = 2;
  351. // set style editing to default and override with set rules
  352. kwhieditstyle = ["rgb(0,0,255)","rgb(255,255,0)","inherit",""]; // defaults
  353. if (hlobj[hlset].textcolor.length > 0) kwhieditstyle[0] = hlobj[hlset].textcolor;
  354. if (hlobj[hlset].backcolor.length > 0) kwhieditstyle[1] = hlobj[hlset].backcolor;
  355. if (hlobj[hlset].fontweight.length > 0) kwhieditstyle[2] = hlobj[hlset].fontweight;
  356. if (hlobj[hlset].custom.length > 0) kwhieditstyle[3] = hlobj[hlset].custom;
  357. kwhiShowEditForm();
  358. }
  359. if (e.target.textContent == "Seek"){
  360. // Populate current seek set to #thdtopkeywords
  361. var divDataTD = e.target.parentNode.previousElementSibling;
  362. document.getElementById("thdtopkeywords").innerHTML = "<i>Seeking:</i> " + divDataTD.firstChild.outerHTML;
  363. // Store set to seek in #thdtopfindbuttons
  364. document.getElementById("thdtopfindbuttons").setAttribute("thdseek", hlset);
  365. // Close Keyword Sets form
  366. document.getElementById('thdtopdrop').style.display='none';
  367. // Send click event to the "seek first" button
  368. document.getElementById('thdtopfindbuttons').children[0].click();
  369. }
  370. }
  371. }
  372. function kwhienabledisable(hlsetnum,enable){
  373. if (enable == false) {
  374. // Update object and persist to GM storage
  375. hlobj[hlsetnum].enabled = "false";
  376. hljson = JSON.stringify(hlobj);
  377. GM_setValue("kwstyles",hljson);
  378. // Unhighlight
  379. unhighlight(hlsetnum);
  380. // Clear seek info from bar if this set is there
  381. var seekset = document.getElementById("thdtopfindbuttons").getAttribute("thdseek");
  382. if (seekset){
  383. if(seekset.indexOf("|") > -1) seekset = seekset.split("|")[0];
  384. if (hlsetnum == seekset){
  385. document.getElementById("thdtopfindbuttons").setAttribute("thdseek","");
  386. document.getElementById("thdseekdesc").textContent = "Seek";
  387. document.getElementById("thdtopkeywords").innerHTML = "Click here to manage keyword/highlight sets";
  388. }
  389. }
  390. } else {
  391. // Update object and persist to GM storage
  392. hlobj[hlsetnum].enabled = "true";
  393. hljson = JSON.stringify(hlobj);
  394. GM_setValue("kwstyles",hljson);
  395. // Highlight
  396. THmo_doHighlight(document.body,[hlsetnum]);
  397. }
  398. }
  399. function kwhinewset(e,kwtext){ // call up new set form
  400. // set set number attribute
  401. document.querySelector('#kwhiedit tr').setAttribute('kwhiset', 'new');
  402. // clear class for keywords
  403. document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className = "";
  404. // enter placeholder text & default type
  405. if (kwtext) document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent = kwtext;
  406. else document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent = "larry|moe|curly";
  407. document.getElementById("kwhipattype").selectedIndex = 0;
  408. // set style editing to defaults
  409. kwhieditstyle = ["rgb(0,0,255)","rgb(255,255,0)","inherit",""];
  410. kwhiShowEditForm();
  411. }
  412. function kwhiShowEditForm(){
  413. var rule = "#stylecontrols>p>span{";
  414. if (kwhieditstyle[0].length > 0) rule += "color:"+kwhieditstyle[0]+";";
  415. if (kwhieditstyle[1].length > 0) rule += "background-color:"+kwhieditstyle[1]+";";
  416. if (kwhieditstyle[2].length > 0) rule += "font-weight:"+kwhieditstyle[2]+";";
  417. if (kwhieditstyle[3].length > 0) rule += kwhieditstyle[3]+";";
  418. document.getElementById("kwhiedittemp").innerHTML = rule + "}";
  419. populateRGB("txt",kwhieditstyle[0]);
  420. populateRGB("bkg",kwhieditstyle[1]);
  421. document.getElementById("fwsel").value = kwhieditstyle[2];
  422. document.getElementById("kwhicustom").value = kwhieditstyle[3];
  423. // show form
  424. document.getElementById("kwhiedit").style.display = "block";
  425. }
  426. function kwhiexport(e){
  427. prompt("JSON data\nPress Ctrl+c or right-click to copy\n ", JSON.stringify(hlobj));
  428. }
  429. function kwhiimport(e){
  430. var txtImport = prompt("Paste in the exported data and click OK to start parsing", "");
  431. try{
  432. var objImport = JSON.parse(txtImport);
  433. } catch(err){
  434. alert("Sorry, data does not appear to be in the proper format. Here's the error according to Firefox: \n\n"+err+"\n\nHopefully you can resolve that!");
  435. return;
  436. }
  437. var keysImport = Object.keys(objImport);
  438. // Compare for duplicate set numbers
  439. var keysString = "|" + hlkeys.join("|") + "|";
  440. var counter = 0;
  441. for (var j = 0; j < keysImport.length; ++j){
  442. if(keysString.indexOf("|"+keysImport[j]+"|") > -1) counter++;
  443. }
  444. if (counter > 0){
  445. var arc = prompt("Detected "+counter+" of "+keysImport.length+" set numbers to be imported already exist. Do you want to:\nAdd these sets [A]\nReplace existing sets [R]\nTotally replace all existing sets [T]\nCancel the import [C]?","A");
  446. if (!arc) return;
  447. if (arc.length == 0) return;
  448. if (arc.toLowerCase() == "c") return;
  449. if (arc.toLowerCase() == "t"){
  450. if(!confirm("Total replacement has no error checking. Click OK to confirm total replacement, or click Cancel to only Replace matching sets.")) arc = "R";
  451. }
  452. } else {
  453. var arc = "A";
  454. }
  455. if (arc.toLowerCase() == "t"){ // Total replacement
  456. hlobj = JSON.parse(txtImport);
  457. // Update the global key array
  458. hlkeys = Object.keys(hlobj);
  459. // Persist the object
  460. hljson = JSON.stringify(hlobj);
  461. GM_setValue("kwstyles",hljson);
  462. // Apply to page (see below)
  463. } else {
  464. for (var j = 0; j < keysImport.length; ++j){ // Add/replace individual sets
  465. var impset = keysImport[j];
  466. if(keysString.indexOf("|"+impset+"|") > -1 && arc.toLowerCase() == "r"){ // replace
  467. var hlset = impset;
  468. hlobj[hlset].keywords = objImport[impset].keywords || "keywords|not|found";
  469. hlobj[hlset].type = objImport[impset].type || "string";
  470. hlobj[hlset].hlpat = objImport[impset].hlpat || "";
  471. hlobj[hlset].textcolor = objImport[impset].textcolor || "rgb(0,0,255)";
  472. hlobj[hlset].backcolor = objImport[impset].backcolor || "rgb(255,255,0)";
  473. hlobj[hlset].fontweight = objImport[impset].fontweight || "inherit";
  474. hlobj[hlset].custom = objImport[impset].custom || "";
  475. hlobj[hlset].enabled = objImport[impset].enabled || "true";
  476. hlobj[hlset].visible = objImport[impset].visible || "true";
  477. hlobj[hlset].updated = (new Date()).toJSON();
  478. } else { // add
  479. if(keysString.indexOf("|"+impset+"|") > -1 && arc.toLowerCase() == "a"){
  480. // create a new set number instead
  481. var hlset = "set" + hlnextset;
  482. hlnextset += 1;
  483. GM_setValue("hlnextset",hlnextset);
  484. } else {
  485. var hlset = impset;
  486. }
  487. // add the set
  488. hlobj[hlset] = {
  489. keywords : objImport[impset].keywords || "keywords|not|found",
  490. type: objImport[impset].type || "string",
  491. hlpat : objImport[impset].hlpat || "",
  492. textcolor : objImport[impset].textcolor || "rgb(0,0,255)",
  493. backcolor : objImport[impset].backcolor || "rgb(255,255,0)",
  494. fontweight : objImport[impset].fontweight || "inherit",
  495. custom : objImport[impset].custom || "",
  496. enabled : objImport[impset].enabled || "true",
  497. visible : objImport[impset].visible || "true",
  498. updated : objImport[impset].updated || ""
  499. }
  500. }
  501. // Update the global key array
  502. hlkeys = Object.keys(hlobj);
  503. // Persist the object
  504. hljson = JSON.stringify(hlobj);
  505. GM_setValue("kwstyles",hljson);
  506. }
  507. }
  508. // TODO: Could an error prevent reaching this point, for example, if the import object is missing properties due to bad editing?
  509. // Update CSS rule and command bar list
  510. insertCSS(hlkeys);
  511. refreshSetList();
  512. // Unhighlight all, re-highlight all, close dialog
  513. unhighlight(null);
  514. THmo_doHighlight(document.body);
  515. }
  516. function kwhihbtn(e){
  517. if (e.target.checked == false){
  518. hlbtnvis = "off";
  519. GM_setValue("hlbtnvis",hlbtnvis);
  520. document.getElementById("btnshowkwhi").style.display = "none";
  521. } else {
  522. hlbtnvis = "on";
  523. GM_setValue("hlbtnvis",hlbtnvis);
  524. document.getElementById("btnshowkwhi").style.display = "";
  525. }
  526. }
  527. function kwhiprecode(e){
  528. if (e.target.checked == false){
  529. // Update var, persist the preference, unhighlight, rehighlight
  530. hlprecode = false;
  531. GM_setValue("hlprecode",hlprecode);
  532. unhighlight(null);
  533. THmo_doHighlight(document.body);
  534. } else {
  535. // Update var, persist the preference, rehighlight
  536. hlprecode = true;
  537. GM_setValue("hlprecode",hlprecode);
  538. THmo_doHighlight(document.body);
  539. }
  540. }
  541. function thdseek(e){
  542. if (e.target.nodeName == "DIV") return; // ignore background clicks
  543. var seekset = e.currentTarget.getAttribute("thdseek");
  544. if (!seekset){ // user needs to select a set to seek in
  545. thdDropSetList();
  546. } else {
  547. var seekparams = seekset.split("|");
  548. var seekmatches = document.querySelectorAll('thdfrag[txhidy15="'+seekparams[0]+'"]');
  549. // Update or add total size of set; FIGURE OUT LATER: what if this changed??
  550. seekparams[1] = seekmatches.length;
  551. if (seekmatches.length > 0){
  552. if (e.target.nodeName == "SPAN"){ // re-scroll to the current reference
  553. thdshow(seekmatches[parseInt(seekparams[2])]);
  554. } else { // BUTTON
  555. var seekaction = e.target.getAttribute("thdaction");
  556. if (!seekaction) seekaction = "f";
  557. if (seekparams.length == 3){ // User has seeked in this set
  558. switch (seekaction){
  559. case "f":
  560. seekparams[2] = 0;
  561. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  562. if (rtn == false) seekagain("n");
  563. break;
  564. case "p":
  565. if (parseInt(seekparams[2]) > 0) {
  566. seekparams[2] = parseInt(seekparams[2]) - 1;
  567. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  568. if (rtn == false){
  569. if (parseInt(seekparams[2]) > 0) seekagain("p");
  570. else seekfailnotc("No previous match visible");
  571. }
  572. } else {
  573. seekfailnotc("Already reached first match");
  574. }
  575. break;
  576. case "n":
  577. if (parseInt(seekparams[2]) < (seekmatches.length-1)) {
  578. seekparams[2] = parseInt(seekparams[2]) + 1;
  579. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  580. if (rtn == false){
  581. if (parseInt(seekparams[2]) < (seekmatches.length-1)) seekagain("n");
  582. else seekfailnotc("No later match visible");
  583. }
  584. } else {
  585. seekparams[2] = (seekmatches.length-1); // in case it's too high, fix that here
  586. seekfailnotc("Already reached last match");
  587. }
  588. break;
  589. case "l":
  590. seekparams[2] = (seekmatches.length-1);
  591. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  592. if (rtn == false) seekagain("p");
  593. break;
  594. }
  595. } else {
  596. seekparams[2] = 0;
  597. thdshow(seekmatches[parseInt(seekparams[2])]);
  598. }
  599. document.getElementById("thdtopfindbuttons").setAttribute("thdseek", seekparams.join("|"));
  600. document.getElementById("thdseekdesc").textContent = (parseInt(seekparams[2])+1) + " of " + seekparams[1];
  601. }
  602. } else {
  603. document.getElementById("thdseekdesc").textContent = "0 of 0";
  604. }
  605. }
  606. }
  607. function thdshow(elt){ // this could be much prettier with animation!
  608. elt.scrollIntoView();
  609. var rect = elt.getClientRects()[0];
  610. if (rect){ // scroll down if behind the control bar
  611. if (rect.top < 27) window.scroll(0, window.scrollY-27);
  612. return true;
  613. } else { // match is not visible
  614. return false;
  615. }
  616. }
  617. function seekagain(dir){
  618. switch (dir){
  619. case "p":
  620. seekfailnotc("Hidden, trying previous match...");
  621. window.setTimeout(function(){document.querySelector('button[thdaction="p"]').click();},250);
  622. break;
  623. case "n":
  624. seekfailnotc("Hidden, trying next match...");
  625. window.setTimeout(function(){document.querySelector('button[thdaction="n"]').click();},250);
  626. break;
  627. }
  628. }
  629. var evttimer;
  630. function seekfailnotc(txt){
  631. var sfdiv = document.getElementById("thdseekfail");
  632. sfdiv.textContent = txt;
  633. sfdiv.style.display = "block";
  634. if (evttimer) window.clearTimeout(evttimer);
  635. evttimer = window.setTimeout(function(){document.getElementById("thdseekfail").style.display="none";}, 800);
  636. }
  637. function unhighlight(setnum){
  638. if (setnum) var tgts = document.querySelectorAll('thdfrag[txhidy15="' + setnum + '"]');
  639. else var tgts = document.querySelectorAll('thdfrag[txhidy15]'); // remove ALL
  640. for (var i=0; i<tgts.length; i++){
  641. // Check for co-extant parent(s) to remove potentially stranded <span>s
  642. var parnode = tgts[i].parentNode, parpar = parnode.parentNode, tgtspan;
  643. if (parnode.hasAttribute("thdcontain") && parnode.innerHTML == tgts[i].outerHTML){
  644. parnode.outerHTML = tgts[i].textContent.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  645. tgtspan = parpar;
  646. } else {
  647. tgts[i].outerHTML = tgts[i].textContent.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  648. tgtspan = parnode;
  649. }
  650. tgtspan.normalize();
  651. if (tgtspan.hasAttribute("thdcontain")){
  652. parnode = tgtspan.parentNode;
  653. if (parnode){
  654. if (parnode.hasAttribute("thdcontain") && parnode.innerHTML == tgtspan.outerHTML && tgtspan.querySelectorAll('thdfrag[txhidy15]').length == 0){
  655. parnode.outerHTML = tgtspan.innerHTML;
  656. } else if (parnode.innerHTML == tgtspan.outerHTML && tgtspan.querySelectorAll('thdfrag[txhidy15]').length == 0) {
  657. parnode.innerHTML = tgtspan.innerHTML;
  658. }
  659. }
  660. }
  661. }
  662. }
  663. // Set up add/edit form
  664. var kwhied = document.createElement("div");
  665. kwhied.id = "kwhiedit";
  666. kwhied.innerHTML = "<form onsubmit=\"return false;\"><p style=\"margin-top:0\"><b>Edit/Add Keywords/Highlighting</b>" +
  667. "<button class=\"btnkwhiclose\" onclick=\"document.getElementById('kwhiedit').style.display='none'; return false;\">X</button>" +
  668. "</p><p>List longer forms of a word first to match both in full. Example: \"children|child\" will highlight both, but \"child|children\" " +
  669. "will only highlight child, it won't expand the selection to children.</p>" +
  670. "<table cellspacing=\"0\" style=\"table-layout:fixed\"><tbody><tr kwhiset=\"new\"><td style=\"width:45%\">" +
  671. "<p contenteditable=\"true\" style=\"border:1px dotted #000;word-wrap:break-word;display:block!important\" class=\"\">placeholder</p>" +
  672. "<p style=\"margin-top:2em\">Match type: <select id=\"kwhipattype\"><option value=\"string\" selected>Anywhere in a word</option>" +
  673. "<option value=\"word\">\"Whole\" words only</option><option value=\"regex\">Regular Expression (advanced)</option></select></p></td>" +
  674. "<td style=\"width:55%\" id=\"stylecontrols\"><p><span>Text color:</span> R:<input id=\"txtr\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" " +
  675. "style=\"width:4em\" value=\"0\"> G:<input id=\"txtg\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" " +
  676. "style=\"width:4em\" value=\"0\"> B:<input id=\"txtb\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" " +
  677. "style=\"width:4em\" value=\"0\"> <button id=\"btntxtreset\">Reset</button></p><p><span>Background:</span> R:<input id=\"bkgr\" " +
  678. "type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:4em\" value=\"255\"> G:<input id=\"bkgg\" " +
  679. "type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:4em\" value=\"255\"> B:<input id=\"bkgb\" " +
  680. "type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:4em\" value=\"128\"> <button id=\"btnbkgreset\">Reset</button>" +
  681. "</p><p><span>Font-weight:</span> <select id=\"fwsel\"><option value=\"inherit\" selected>inherit</option>" +
  682. "<option value=\"bold\"><b>bold</b></option><option value=\"normal\">not bold</option></select></p><p><span>Custom:</span> <input type=\"text\" " +
  683. "id=\"kwhicustom\" style=\"width:55%\"> <button id=\"kwhicustomapply\">Apply</button></p></td></tr></tbody></table>" +
  684. "<p><button id=\"btnkwhisave\">Save Changes</button> <button id=\"btnkwhicancel\">Discard Changes</button> <button id=\"btnkwhiremove\">Hide Set</button></p></form><style type=\"text/css\">" +
  685. "#kwhiedit{position:fixed;top:1px;left:150px;width:800px;height:400px;border:1px solid #000;border-radius:6px;padding:1em;color:#000;" +
  686. "background:#fafafa;z-index:2501;display:none} #kwhiedit table{width:100%;background:#fff;border-top:1px solid #000;" +
  687. "border-left:1px solid #000;} #kwhiedit td{padding:0 16px; vertical-align:top;border-right:1px solid #000;border-bottom:1px solid #000;}" +
  688. "#stylecontrols>p>span{display:inline-block;width:6.5em;}</style><style type=\"text/css\" id=\"kwhiedittemp\"></style></div>";
  689. document.body.appendChild(kwhied);
  690. // Attach event handlers
  691. document.getElementById("btnkwhisave").addEventListener("click",kwhisavechg,false);
  692. document.getElementById("btnkwhicancel").addEventListener("click",kwhicancel,false);
  693. document.getElementById("btnkwhiremove").addEventListener("click",kwhiremove,false);
  694. document.getElementById("stylecontrols").addEventListener("input", updatestyle, false);
  695. document.getElementById("btntxtreset").addEventListener("click",kwhicolorreset,false);
  696. document.getElementById("btnbkgreset").addEventListener("click",kwhicolorreset,false);
  697. document.getElementById("fwsel").addEventListener("change",kwhifwchg,false);
  698. document.getElementById("kwhicustomapply").addEventListener("click",kwhicustom,false);
  699.  
  700. function kwhisavechg(e){
  701. // Update object, regenerate CSS if applicable, apply to document
  702. var hlset = document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className;
  703. var kwtext = document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent;
  704. if (hlset == ""){
  705. // create a new set number
  706. var hlset = "set" + hlnextset;
  707. hlnextset += 1;
  708. GM_setValue("hlnextset",hlnextset);
  709. // add the set
  710. if (document.getElementById("kwhipattype").value == "regex"){
  711. kwtext = kwtext.replace(/\\/g, "\\");
  712. var hlpattxt = ""; //TODOLATER
  713. } else {
  714. var hlpattxt = "";
  715. }
  716. hlobj[hlset] = {
  717. keywords : kwtext,
  718. type : document.getElementById("kwhipattype").value,
  719. hlpat : hlpattxt,
  720. textcolor : kwhieditstyle[0],
  721. backcolor : kwhieditstyle[1],
  722. fontweight : kwhieditstyle[2],
  723. custom : kwhieditstyle[3],
  724. enabled : "true",
  725. visible : "true",
  726. updated : ""
  727. }
  728. // Update the global key array
  729. hlkeys = Object.keys(hlobj);
  730. } else {
  731. hlobj[hlset].type = document.getElementById("kwhipattype").value;
  732. // Save keyword changes after user confirmation
  733. if (kwtext != hlobj[hlset].keywords){
  734. if (confirm("Save updated keywords (and other changes)?")){
  735. if (hlobj[hlset].type != "regex") hlobj[hlset].keywords = kwtext;
  736. else{
  737. hlobj[hlset].keywords = kwtext.replace(/\\/g, "\\");
  738. hlobj[hlset].hlpat = ""; //TODOLATER
  739. }
  740. } else return;
  741. }
  742. // Save style changes without confirmation
  743. hlobj[hlset].textcolor = kwhieditstyle[0];
  744. hlobj[hlset].backcolor = kwhieditstyle[1];
  745. hlobj[hlset].fontweight = kwhieditstyle[2];
  746. hlobj[hlset].custom = kwhieditstyle[3];
  747. // Set updated date/time
  748. hlobj[hlset].updated = (new Date()).toJSON();
  749. }
  750. // Persist the object
  751. hljson = JSON.stringify(hlobj);
  752. GM_setValue("kwstyles",hljson);
  753. // Update CSS rule and parent form
  754. insertCSS([hlset]);
  755. refreshSetList();
  756. // Unhighlight, re-highlight, close dialog
  757. unhighlight(hlset);
  758. THmo_doHighlight(document.body,[hlset])
  759. document.getElementById('kwhiedit').style.display='none';
  760. }
  761. function kwhicancel(e){
  762. // Close dialog (fields will be refresh if it is opened again)
  763. document.getElementById('kwhiedit').style.display='none';
  764. }
  765. function kwhiremove(e){
  766. var hlset = document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className;
  767. if (hlset == ""){
  768. alert("This set has not been saved and therefore does not need to be hidden, you can just close the dialog to discard it.");
  769. } else {
  770. if (confirm("Are you sure you want to hide this set instead of editing it to your own liking?")){
  771. hlobj[hlset].visible = "false";
  772. hlobj[hlset].updated = (new Date()).toJSON();
  773. // Persist the object
  774. hljson = JSON.stringify(hlobj);
  775. GM_setValue("kwstyles",hljson);
  776. // Update set list, remove highlighting, close form
  777. refreshSetList();
  778. unhighlight(hlset);
  779. document.getElementById('kwhiedit').style.display='none';
  780. }
  781. }
  782. }
  783. function kwhicolorreset(e){
  784. // what set is this?
  785. var set = document.querySelector('#kwhiedit tr').getAttribute('kwhiset');
  786. // check which button, reset the RGB
  787. if (e.target.id == "btntxtreset"){
  788. if (set == "new"){
  789. kwhieditstyle[0] = "rgb(0,0,255)";
  790. } else {
  791. kwhieditstyle[0] = hlobj[set].textcolor;
  792. }
  793. populateRGB("txt",kwhieditstyle[0]);
  794. setdivstyle(["txt"]);
  795. }
  796. if (e.target.id == "btnbkgreset"){
  797. if (set == "new"){
  798. kwhieditstyle[1] = "rgb(255,255,0)";
  799. } else {
  800. kwhieditstyle[1] = hlobj[set].backcolor;
  801. }
  802. populateRGB("bkg",kwhieditstyle[1]);
  803. setdivstyle(["bkg"]);
  804. }
  805. e.target.blur();
  806. }
  807. function populateRGB(prop,stylestring){
  808. var rgbvals = stylestring.substr(stylestring.indexOf("(")+1);
  809. rgbvals = rgbvals.substr(0,rgbvals.length-1).split(",");
  810. document.getElementById(prop+"r").value = parseInt(rgbvals[0]);
  811. document.getElementById(prop+"g").value = parseInt(rgbvals[1]);
  812. document.getElementById(prop+"b").value = parseInt(rgbvals[2]);
  813. }
  814. function updatestyle(e){
  815. // validate value and apply change
  816. if (e.target.id.indexOf("txt") == 0 || e.target.id.indexOf("bkg") == 0){
  817. if (isNaN(e.target.value)){
  818. alert("Please only use values between 0 and 255");
  819. return;
  820. }
  821. if (parseInt(e.target.value) != e.target.value){
  822. e.target.value = parseInt(e.target.value);
  823. }
  824. if (e.target.value < 0){
  825. e.target.value = 0;
  826. }
  827. if (e.target.value > 255){
  828. e.target.value = 255;
  829. }
  830. if (e.target.id.indexOf("txt") == 0) setdivstyle(["txt"]);
  831. if (e.target.id.indexOf("bkg") == 0) setdivstyle(["bkg"]);
  832. } else {
  833. if (e.target.id == "kwhicustom") return;
  834. console.log("updatestyle on "+e.target.id);
  835. }
  836. }
  837. function setdivstyle(props){
  838. for (var i=0; i<props.length; i++){
  839. switch (props[i]){
  840. case "txt":
  841. kwhieditstyle[0] = "rgb(" + document.getElementById("txtr").value + "," +
  842. document.getElementById("txtg").value + "," + document.getElementById("txtb").value + ")";
  843. break;
  844. case "bkg":
  845. kwhieditstyle[1] = "rgb(" + document.getElementById("bkgr").value + "," +
  846. document.getElementById("bkgg").value + "," + document.getElementById("bkgb").value + ")";
  847. break;
  848. default:
  849. console.log("default?");
  850. }
  851. }
  852. var rule = "#stylecontrols>p>span{";
  853. if (kwhieditstyle[0].length > 0) rule += "color:"+kwhieditstyle[0]+";";
  854. if (kwhieditstyle[1].length > 0) rule += "background-color:"+kwhieditstyle[1]+";";
  855. if (kwhieditstyle[2].length > 0) rule += "font-weight:"+kwhieditstyle[2]+";";
  856. if (kwhieditstyle[3].length > 0) rule += kwhieditstyle[3]+";";
  857. document.getElementById("kwhiedittemp").innerHTML = rule + "}";
  858. }
  859. function kwhifwchg(e){
  860. kwhieditstyle[2] = e.target.value;
  861. setdivstyle([]);
  862. }
  863. function kwhicustom(e){
  864. kwhieditstyle[3] = document.getElementById("kwhicustom").value;
  865. setdivstyle([]);
  866. }
  867. // Context menu options -- do not replace any existing menu!
  868. if (!document.body.hasAttribute("contextmenu") && "contextMenu" in document.documentElement){
  869. var cmenu = document.createElement("menu");
  870. cmenu.id = "THDcontext";
  871. cmenu.setAttribute("type", "context");
  872. cmenu.innerHTML = '<menu label="Text Highlighter">' +
  873. '<menuitem id="THDshowbar" label="Show bar"></menuitem>' +
  874. '<menuitem id="THDenableset" label="Enable matching set"></menuitem>' +
  875. '<menuitem id="THDdisableset" label="Disable this set"></menuitem>' +
  876. '<menuitem id="THDnewset" label="Add new set"></menuitem>' +
  877. '</menu>';
  878. document.body.appendChild(cmenu);
  879. document.getElementById("THDshowbar").addEventListener("click",editKW,false);
  880. document.getElementById("THDenableset").addEventListener("click",cmenuEnable,false);
  881. document.getElementById("THDdisableset").addEventListener("click",cmenuDisable,false);
  882. document.getElementById("THDnewset").addEventListener("click",cmenuNewset,false);
  883. // attach menu and create event for filtering
  884. document.body.setAttribute("contextmenu", "THDcontext");
  885. document.body.addEventListener("contextmenu",cmenuFilter,false);
  886. }
  887. function cmenuFilter(e){
  888. document.getElementById("THDenableset").setAttribute("disabled","disabled");
  889. document.getElementById("THDenableset").setAttribute("THDtext","");
  890. document.getElementById("THDdisableset").setAttribute("disabled","disabled");
  891. document.getElementById("THDdisableset").setAttribute("THDset","");
  892. var s = window.getSelection();
  893. if (s.isCollapsed) document.getElementById("THDnewset").setAttribute("THDtext","");
  894. else document.getElementById("THDnewset").setAttribute("THDtext",s.getRangeAt(0).toString().trim());
  895. if (e.target.hasAttribute('txhidy15')){
  896. document.getElementById("THDdisableset").removeAttribute("disabled");
  897. document.getElementById("THDdisableset").setAttribute("THDset",e.target.getAttribute('txhidy15'));
  898. } else {
  899. document.getElementById("THDdisableset").setAttribute("disabled","disabled");
  900. if (!s.isCollapsed){
  901. document.getElementById("THDenableset").removeAttribute("disabled");
  902. document.getElementById("THDenableset").setAttribute("THDtext",s.getRangeAt(0).toString().trim());
  903. }
  904. }
  905. }
  906. function cmenuEnable(e){
  907. var kw = e.target.getAttribute("THDtext").toLowerCase();
  908. var toggled = false;
  909. for (var j = 0; j < hlkeys.length; ++j){
  910. var hlset = hlkeys[j];
  911. var kwlist = "|" + hlobj[hlset].keywords.toLowerCase() + "|";
  912. if(kwlist.indexOf("|" + kw + "|") > -1){
  913. if (hlobj[hlset].enabled == "true") break; // already enabled
  914. kwhienabledisable(hlset,true);
  915. refreshSetList();
  916. toggled = true;
  917. break;
  918. }
  919. }
  920. if (toggled == false){
  921. if (document.getElementById("thdtopbar").style.display != "block") editKW();
  922. if (document.getElementById("thdtopdrop").style.display != "block") thdDropSetList();
  923. }
  924. }
  925. function cmenuDisable(e){
  926. kwhienabledisable(e.target.getAttribute("THDset"),false);
  927. refreshSetList();
  928. }
  929. function cmenuNewset(e){
  930. //TODO - if there's a selection, get it into the form
  931. kwhinewset(e,e.target.getAttribute("THDtext"));
  932. }
  933.  
  934. // TESTING ONLY
  935. function flushData(){
  936. GM_setValue("kwstyles", "");
  937. }
  938. GM_registerMenuCommand("TEST ONLY - flush keyword sets for Text Highlighter 2015", flushData);
  939.  
  940. })(); // end of anonymous function