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.3
  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-ver203.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 Highlight and Seek 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 Highlight and Seek 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 == undefined){
  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. else var btnchk = "";
  233. if (hlprecode) var btnprecode = " checked=\"checked\"";
  234. else var btnprecode = "";
  235. 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>" +
  236. "<div id=\"thdtopcurrent\"><p id=\"thdtopkeywords\" title=\"Click to View, Edit, Seek, or Add Keywords\">Click here to manage keyword/highlight sets</p>" +
  237. "<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>" +
  238. "<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>" +
  239. "<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>" +
  240. "<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 +
  241. "> 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 +
  242. "> Match in pre/code</label></li></ul></div>" +
  243. "<button class=\"btnkwhiclose\" onclick=\"document.getElementById('thdtopbar').style.display='none';document.getElementById('thdtopspacer').style.display='none';return false;\" style=\"float:right\">X</button></form>" +
  244. "<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} " +
  245. "#thdtopbar,#thdtopbar *{box-sizing:content-box;} #thdtopform{display:block;position:relative;float:left;width:100%;margin:0;border:none;} " +
  246. "#thdtopbarhome,#thdtopcurrent,#thdtopfindbuttons,#thdtopoptions{float:left;top:0;left:0;margin:0;padding:5px 8px 4px;border-right:1px solid #fff;font-size:16px;} " +
  247. "#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} " +
  248. "#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;} " +
  249. "#thdtopfindbuttons button:hover{background:#ffa;} #thdseekdesc{cursor:pointer} #thdtopkeywords{margin:0;width:500px;cursor:pointer;} " +
  250. "#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}" +
  251. "#thdtopkeywords span{display:inline-block;width:100%;overflow:hidden;text-overflow:ellipsis;} #thdtable{max-height:600px;overflow-y:auto;overflow-x:hidden} " +
  252. "#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;} " +
  253. "#thdtopdrop table{width:100%;background:#fff;border-top:1px solid #000;border-left:1px solid #000;table-layout:fixed} " +
  254. "#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;} " +
  255. "#thdtopoptions{position:relative;width:160px;height:26px;padding:0 8px;} #thdtopoptions > div{padding:5px 0 4px;} " +
  256. "#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;} " +
  257. "#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;}" +
  258. ".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>";
  259. document.body.appendChild(kwhibar);
  260. // Attach event handlers
  261. document.getElementById("thdtopkeywords").addEventListener("click",thddroptoggle,false);
  262. document.getElementById("kwhitbod").addEventListener("click",kwhiformevent,false);
  263. document.getElementById("btnkwhiadd").addEventListener("click",kwhinewset,false);
  264. document.getElementById("btnkwhiexport").addEventListener("click",kwhiexport,false);
  265. document.getElementById("btnkwhiimport").addEventListener("click",kwhiimport,false);
  266. document.getElementById("thdtopfindbuttons").addEventListener("click",thdseek,false);
  267. document.getElementById("chkhbtn").addEventListener("click",kwhihbtn,false);
  268. document.getElementById("chkprecode").addEventListener("click",kwhiprecode,false);
  269. // Add spacer at top of body
  270. var divsp = document.createElement("div");
  271. divsp.id = "thdtopspacer";
  272. divsp.setAttribute("style","clear:both;display:none");
  273. divsp.style.height = parseInt(27 - parseInt(window.getComputedStyle(document.body,null).getPropertyValue("margin-top"))) + "px";
  274. document.body.insertBefore(divsp, document.body.childNodes[0]);
  275. // Switch JS text to icon
  276. var JSBTN = document.createElement("img");
  277. JSBTN.src = GM_getResourceURL("mycon");
  278. document.querySelector("#thdtopbar a").textContent = "";
  279. document.querySelector("#thdtopbar a").appendChild(JSBTN);
  280. // Add menu item
  281. GM_registerMenuCommand("Show Text Highlight and Seek Bar - View, Edit, Add Keywords and Styles", editKW);
  282. // Inject H button
  283. if (hlbtnvis == "off") var hbtndisp = ' style="display:none"';
  284. else hbtndisp = '';
  285. var dNew = document.createElement("div");
  286. dNew.innerHTML = '<button id="btnshowkwhi"' + hbtndisp + '>H</button><style type="text/css">#btnshowkwhi{position:fixed;top:4px;right:4px;opacity:0.2;' +
  287. '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}' +
  288. '#btnshowkwhi:hover{opacity:0.8}@media print{#btnshowkwhi{display:none;}}</style>';
  289. document.body.appendChild(dNew);
  290. document.getElementById("btnshowkwhi").addEventListener("click",editKW,false);
  291. function editKW(e){
  292. refreshSetList();
  293. // show form
  294. document.getElementById("thdtopbar").style.display = "block";
  295. document.getElementById("thdtopspacer").style.display = "block";
  296. }
  297. function thdDropSetList(e){
  298. refreshSetList();
  299. document.getElementById("thdtopdrop").style.display = "block";
  300. }
  301. function thddroptoggle(e){
  302. if (document.getElementById("thdtopdrop").style.display == "none") thdDropSetList();
  303. else document.getElementById("thdtopdrop").style.display = "none";
  304. }
  305. function refreshSetList(e){
  306. // clear old rows from form
  307. document.getElementById("kwhitbod").innerHTML = "";
  308. // populate data - hlobj is global
  309. for (var j = 0; j < hlkeys.length; ++j){
  310. var hlset = hlkeys[j];
  311. if (hlobj[hlset].visible == "true"){
  312. if (hlobj[hlset].enabled == "true") var strchk = ' checked=\"checked\"';
  313. else var strchk = '';
  314. var newrow = document.createElement("tr");
  315. var thdtypenote = '';
  316. newrow.setAttribute("kwhiset", hlset);
  317. if(hlobj[hlset].type != "string"){
  318. thdtypenote = '<span class="thdtype">' + hlobj[hlset].type + '</span>';
  319. }
  320. if (j == 0){
  321. newrow.innerHTML = '<td style=\"width:286px\"><div class=\"' + hlset + '\">' + hlobj[hlset].keywords + '</div>' + thdtypenote + '</td>' +
  322. '<td style=\"width:195px\"><button kwhiset=\"' + hlset + '\" title=\"Bring matches into view\">Seek</button> ' +
  323. '<button kwhiset=\"' + hlset + '\">Edit</button> <label><input type=\"checkbox\" kwhiset=\"' + hlset +
  324. '\"' + strchk + '"> Enabled </label></td>';
  325. } else {
  326. newrow.innerHTML = '<td><div class=\"' + hlset + '\">' + hlobj[hlset].keywords + '</div>' + thdtypenote + '</td>' +
  327. '<td><button kwhiset=\"' + hlset + '\" title=\"Bring matches into view\">Seek</button> ' +
  328. '<button kwhiset=\"' + hlset + '\">Edit</button> <label><input type=\"checkbox\" kwhiset=\"' + hlset +
  329. '\"' + strchk + '"> Enabled </label></td>';
  330. }
  331. document.getElementById("kwhitbod").appendChild(newrow);
  332. }
  333. }
  334. }
  335. function kwhiformevent(e){
  336. if (e.target.nodeName == "INPUT"){ // Enabled checkbox
  337. var hlsetnum = e.target.getAttribute("kwhiset");
  338. kwhienabledisable(hlsetnum, e.target.checked);
  339. }
  340. if (e.target.nodeName == "BUTTON"){ // Call up edit form or find bar
  341. var hlset = e.target.getAttribute('kwhiset');
  342. if (e.target.textContent == "Edit"){
  343. // set set number attribute
  344. document.querySelector('#kwhiedit tr').setAttribute('kwhiset', hlset);
  345. // set class for keywords
  346. document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className = hlset;
  347. // enter placeholder text & type
  348. document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent = hlobj[hlset].keywords;
  349. document.getElementById("kwhipattype").selectedIndex = 0;
  350. if (hlobj[hlset].type == "word") document.getElementById("kwhipattype").selectedIndex = 1;
  351. if (hlobj[hlset].type == "regex") document.getElementById("kwhipattype").selectedIndex = 2;
  352. // set style editing to default and override with set rules
  353. kwhieditstyle = ["rgb(0,0,255)","rgb(255,255,0)","inherit",""]; // defaults
  354. if (hlobj[hlset].textcolor.length > 0) kwhieditstyle[0] = hlobj[hlset].textcolor;
  355. if (hlobj[hlset].backcolor.length > 0) kwhieditstyle[1] = hlobj[hlset].backcolor;
  356. if (hlobj[hlset].fontweight.length > 0) kwhieditstyle[2] = hlobj[hlset].fontweight;
  357. if (hlobj[hlset].custom.length > 0) kwhieditstyle[3] = hlobj[hlset].custom;
  358. kwhiShowEditForm();
  359. }
  360. if (e.target.textContent == "Seek"){
  361. // Populate current seek set to #thdtopkeywords
  362. var divDataTD = e.target.parentNode.previousElementSibling;
  363. document.getElementById("thdtopkeywords").innerHTML = "<i>Seeking:</i> " + divDataTD.firstChild.outerHTML;
  364. // Store set to seek in #thdtopfindbuttons
  365. document.getElementById("thdtopfindbuttons").setAttribute("thdseek", hlset);
  366. // Close Keyword Sets form
  367. document.getElementById('thdtopdrop').style.display='none';
  368. // Send click event to the "seek first" button
  369. document.getElementById('thdtopfindbuttons').children[0].click();
  370. }
  371. }
  372. }
  373. function kwhienabledisable(hlsetnum,enable){
  374. if (enable == false) {
  375. // Update object and persist to GM storage
  376. hlobj[hlsetnum].enabled = "false";
  377. hljson = JSON.stringify(hlobj);
  378. GM_setValue("kwstyles",hljson);
  379. // Unhighlight
  380. unhighlight(hlsetnum);
  381. // Clear seek info from bar if this set is there
  382. var seekset = document.getElementById("thdtopfindbuttons").getAttribute("thdseek");
  383. if (seekset){
  384. if(seekset.indexOf("|") > -1) seekset = seekset.split("|")[0];
  385. if (hlsetnum == seekset){
  386. document.getElementById("thdtopfindbuttons").setAttribute("thdseek","");
  387. document.getElementById("thdseekdesc").textContent = "Seek";
  388. document.getElementById("thdtopkeywords").innerHTML = "Click here to manage keyword/highlight sets";
  389. }
  390. }
  391. } else {
  392. // Update object and persist to GM storage
  393. hlobj[hlsetnum].enabled = "true";
  394. hljson = JSON.stringify(hlobj);
  395. GM_setValue("kwstyles",hljson);
  396. // Highlight
  397. THmo_doHighlight(document.body,[hlsetnum]);
  398. }
  399. }
  400. function kwhinewset(e,kwtext){ // call up new set form
  401. // set set number attribute
  402. document.querySelector('#kwhiedit tr').setAttribute('kwhiset', 'new');
  403. // clear class for keywords
  404. document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className = "";
  405. // enter placeholder text & default type
  406. if (kwtext) document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent = kwtext;
  407. else document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent = "larry|moe|curly";
  408. document.getElementById("kwhipattype").selectedIndex = 0;
  409. // set style editing to defaults
  410. kwhieditstyle = ["rgb(0,0,255)","rgb(255,255,0)","inherit",""];
  411. kwhiShowEditForm();
  412. }
  413. function kwhiShowEditForm(){
  414. var rule = "#stylecontrols>p>span{";
  415. if (kwhieditstyle[0].length > 0) rule += "color:"+kwhieditstyle[0]+";";
  416. if (kwhieditstyle[1].length > 0) rule += "background-color:"+kwhieditstyle[1]+";";
  417. if (kwhieditstyle[2].length > 0) rule += "font-weight:"+kwhieditstyle[2]+";";
  418. if (kwhieditstyle[3].length > 0) rule += kwhieditstyle[3]+";";
  419. document.getElementById("kwhiedittemp").innerHTML = rule + "}";
  420. populateRGB("txt",kwhieditstyle[0]);
  421. populateRGB("bkg",kwhieditstyle[1]);
  422. document.getElementById("fwsel").value = kwhieditstyle[2];
  423. document.getElementById("kwhicustom").value = kwhieditstyle[3];
  424. // show form
  425. document.getElementById("kwhiedit").style.display = "block";
  426. }
  427. function kwhiexport(e){
  428. prompt("JSON data\nPress Ctrl+c or right-click to copy\n ", JSON.stringify(hlobj));
  429. }
  430. function kwhiimport(e){
  431. var txtImport = prompt("Paste in the exported data and click OK to start parsing", "");
  432. try{
  433. var objImport = JSON.parse(txtImport);
  434. } catch(err){
  435. 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!");
  436. return;
  437. }
  438. var keysImport = Object.keys(objImport);
  439. // Compare for duplicate set numbers
  440. var keysString = "|" + hlkeys.join("|") + "|";
  441. var counter = 0;
  442. for (var j = 0; j < keysImport.length; ++j){
  443. if(keysString.indexOf("|"+keysImport[j]+"|") > -1) counter++;
  444. }
  445. if (counter > 0){
  446. 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");
  447. if (!arc) return;
  448. if (arc.length == 0) return;
  449. if (arc.toLowerCase() == "c") return;
  450. if (arc.toLowerCase() == "t"){
  451. if(!confirm("Total replacement has no error checking. Click OK to confirm total replacement, or click Cancel to only Replace matching sets.")) arc = "R";
  452. }
  453. } else {
  454. var arc = "A";
  455. }
  456. if (arc.toLowerCase() == "t"){ // Total replacement
  457. hlobj = JSON.parse(txtImport);
  458. // Update the global key array
  459. hlkeys = Object.keys(hlobj);
  460. // Persist the object
  461. hljson = JSON.stringify(hlobj);
  462. GM_setValue("kwstyles",hljson);
  463. // Apply to page (see below)
  464. } else {
  465. for (var j = 0; j < keysImport.length; ++j){ // Add/replace individual sets
  466. var impset = keysImport[j];
  467. if(keysString.indexOf("|"+impset+"|") > -1 && arc.toLowerCase() == "r"){ // replace
  468. var hlset = impset;
  469. hlobj[hlset].keywords = objImport[impset].keywords || "keywords|not|found";
  470. hlobj[hlset].type = objImport[impset].type || "string";
  471. hlobj[hlset].hlpat = objImport[impset].hlpat || "";
  472. hlobj[hlset].textcolor = objImport[impset].textcolor || "rgb(0,0,255)";
  473. hlobj[hlset].backcolor = objImport[impset].backcolor || "rgb(255,255,0)";
  474. hlobj[hlset].fontweight = objImport[impset].fontweight || "inherit";
  475. hlobj[hlset].custom = objImport[impset].custom || "";
  476. hlobj[hlset].enabled = objImport[impset].enabled || "true";
  477. hlobj[hlset].visible = objImport[impset].visible || "true";
  478. hlobj[hlset].updated = (new Date()).toJSON();
  479. } else { // add
  480. if(keysString.indexOf("|"+impset+"|") > -1 && arc.toLowerCase() == "a"){
  481. // create a new set number instead
  482. var hlset = "set" + hlnextset;
  483. hlnextset += 1;
  484. GM_setValue("hlnextset",hlnextset);
  485. } else {
  486. var hlset = impset;
  487. }
  488. // add the set
  489. hlobj[hlset] = {
  490. keywords : objImport[impset].keywords || "keywords|not|found",
  491. type: objImport[impset].type || "string",
  492. hlpat : objImport[impset].hlpat || "",
  493. textcolor : objImport[impset].textcolor || "rgb(0,0,255)",
  494. backcolor : objImport[impset].backcolor || "rgb(255,255,0)",
  495. fontweight : objImport[impset].fontweight || "inherit",
  496. custom : objImport[impset].custom || "",
  497. enabled : objImport[impset].enabled || "true",
  498. visible : objImport[impset].visible || "true",
  499. updated : objImport[impset].updated || ""
  500. }
  501. }
  502. // Update the global key array
  503. hlkeys = Object.keys(hlobj);
  504. // Persist the object
  505. hljson = JSON.stringify(hlobj);
  506. GM_setValue("kwstyles",hljson);
  507. }
  508. }
  509. // TODO: Could an error prevent reaching this point, for example, if the import object is missing properties due to bad editing?
  510. // Update CSS rule and command bar list
  511. insertCSS(hlkeys);
  512. refreshSetList();
  513. // Unhighlight all, re-highlight all, close dialog
  514. unhighlight(null);
  515. THmo_doHighlight(document.body);
  516. }
  517. function kwhihbtn(e){
  518. if (e.target.checked == false){
  519. hlbtnvis = "off";
  520. GM_setValue("hlbtnvis",hlbtnvis);
  521. document.getElementById("btnshowkwhi").style.display = "none";
  522. } else {
  523. hlbtnvis = "on";
  524. GM_setValue("hlbtnvis",hlbtnvis);
  525. document.getElementById("btnshowkwhi").style.display = "";
  526. }
  527. }
  528. function kwhiprecode(e){
  529. if (e.target.checked == false){
  530. // Update var, persist the preference, unhighlight, rehighlight
  531. hlprecode = false;
  532. GM_setValue("hlprecode",hlprecode);
  533. unhighlight(null);
  534. THmo_doHighlight(document.body);
  535. } else {
  536. // Update var, persist the preference, rehighlight
  537. hlprecode = true;
  538. GM_setValue("hlprecode",hlprecode);
  539. THmo_doHighlight(document.body);
  540. }
  541. }
  542. function thdseek(e){
  543. if (e.target.nodeName == "DIV") return; // ignore background clicks
  544. var seekset = e.currentTarget.getAttribute("thdseek");
  545. if (!seekset){ // user needs to select a set to seek in
  546. thdDropSetList();
  547. } else {
  548. var seekparams = seekset.split("|");
  549. var seekmatches = document.querySelectorAll('thdfrag[txhidy15="'+seekparams[0]+'"]');
  550. // Update or add total size of set; FIGURE OUT LATER: what if this changed??
  551. seekparams[1] = seekmatches.length;
  552. if (seekmatches.length > 0){
  553. if (e.target.nodeName == "SPAN"){ // re-scroll to the current reference
  554. thdshow(seekmatches[parseInt(seekparams[2])]);
  555. } else { // BUTTON
  556. var seekaction = e.target.getAttribute("thdaction");
  557. if (!seekaction) seekaction = "f";
  558. if (seekparams.length == 3){ // User has seeked in this set
  559. switch (seekaction){
  560. case "f":
  561. seekparams[2] = 0;
  562. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  563. if (rtn == false) seekagain("n");
  564. break;
  565. case "p":
  566. if (parseInt(seekparams[2]) > 0) {
  567. seekparams[2] = parseInt(seekparams[2]) - 1;
  568. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  569. if (rtn == false){
  570. if (parseInt(seekparams[2]) > 0) seekagain("p");
  571. else seekfailnotc("No previous match visible");
  572. }
  573. } else {
  574. seekfailnotc("Already reached first match");
  575. }
  576. break;
  577. case "n":
  578. if (parseInt(seekparams[2]) < (seekmatches.length-1)) {
  579. seekparams[2] = parseInt(seekparams[2]) + 1;
  580. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  581. if (rtn == false){
  582. if (parseInt(seekparams[2]) < (seekmatches.length-1)) seekagain("n");
  583. else seekfailnotc("No later match visible");
  584. }
  585. } else {
  586. seekparams[2] = (seekmatches.length-1); // in case it's too high, fix that here
  587. seekfailnotc("Already reached last match");
  588. }
  589. break;
  590. case "l":
  591. seekparams[2] = (seekmatches.length-1);
  592. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  593. if (rtn == false) seekagain("p");
  594. break;
  595. }
  596. } else {
  597. seekparams[2] = 0;
  598. thdshow(seekmatches[parseInt(seekparams[2])]);
  599. }
  600. document.getElementById("thdtopfindbuttons").setAttribute("thdseek", seekparams.join("|"));
  601. document.getElementById("thdseekdesc").textContent = (parseInt(seekparams[2])+1) + " of " + seekparams[1];
  602. }
  603. } else {
  604. document.getElementById("thdseekdesc").textContent = "0 of 0";
  605. }
  606. }
  607. }
  608. function thdshow(elt){ // this could be much prettier with animation!
  609. elt.scrollIntoView();
  610. var rect = elt.getClientRects()[0];
  611. if (rect){ // scroll down if behind the control bar
  612. if (rect.top < 27) window.scroll(0, window.scrollY-27);
  613. return true;
  614. } else { // match is not visible
  615. return false;
  616. }
  617. }
  618. function seekagain(dir){
  619. switch (dir){
  620. case "p":
  621. seekfailnotc("Hidden, trying previous match...");
  622. window.setTimeout(function(){document.querySelector('button[thdaction="p"]').click();},250);
  623. break;
  624. case "n":
  625. seekfailnotc("Hidden, trying next match...");
  626. window.setTimeout(function(){document.querySelector('button[thdaction="n"]').click();},250);
  627. break;
  628. }
  629. }
  630. var evttimer;
  631. function seekfailnotc(txt){
  632. var sfdiv = document.getElementById("thdseekfail");
  633. sfdiv.textContent = txt;
  634. sfdiv.style.display = "block";
  635. if (evttimer) window.clearTimeout(evttimer);
  636. evttimer = window.setTimeout(function(){document.getElementById("thdseekfail").style.display="none";}, 800);
  637. }
  638. function unhighlight(setnum){
  639. if (setnum) var tgts = document.querySelectorAll('thdfrag[txhidy15="' + setnum + '"]');
  640. else var tgts = document.querySelectorAll('thdfrag[txhidy15]'); // remove ALL
  641. for (var i=0; i<tgts.length; i++){
  642. // Check for co-extant parent(s) to remove potentially stranded <span>s
  643. var parnode = tgts[i].parentNode, parpar = parnode.parentNode, tgtspan;
  644. if (parnode.hasAttribute("thdcontain") && parnode.innerHTML == tgts[i].outerHTML){
  645. parnode.outerHTML = tgts[i].textContent.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  646. tgtspan = parpar;
  647. } else {
  648. tgts[i].outerHTML = tgts[i].textContent.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  649. tgtspan = parnode;
  650. }
  651. tgtspan.normalize();
  652. if (tgtspan.hasAttribute("thdcontain")){
  653. parnode = tgtspan.parentNode;
  654. if (parnode){
  655. if (parnode.hasAttribute("thdcontain") && parnode.innerHTML == tgtspan.outerHTML && tgtspan.querySelectorAll('thdfrag[txhidy15]').length == 0){
  656. parnode.outerHTML = tgtspan.innerHTML;
  657. } else if (parnode.innerHTML == tgtspan.outerHTML && tgtspan.querySelectorAll('thdfrag[txhidy15]').length == 0) {
  658. parnode.innerHTML = tgtspan.innerHTML;
  659. }
  660. }
  661. }
  662. }
  663. }
  664. // Set up add/edit form
  665. var kwhied = document.createElement("div");
  666. kwhied.id = "kwhiedit";
  667. kwhied.innerHTML = "<form onsubmit=\"return false;\"><p style=\"margin-top:0\"><b>Edit/Add Keywords/Highlighting</b>" +
  668. "<button class=\"btnkwhiclose\" onclick=\"document.getElementById('kwhiedit').style.display='none'; return false;\">X</button>" +
  669. "</p><p>List longer forms of a word first to match both in full. Example: \"children|child\" will highlight both, but \"child|children\" " +
  670. "will only highlight child, it won't expand the selection to children.</p>" +
  671. "<table cellspacing=\"0\" style=\"table-layout:fixed\"><tbody><tr kwhiset=\"new\"><td style=\"width:45%\">" +
  672. "<p contenteditable=\"true\" style=\"border:1px dotted #000;word-wrap:break-word;display:block!important\" class=\"\">placeholder</p>" +
  673. "<p style=\"margin-top:2em\">Match type: <select id=\"kwhipattype\"><option value=\"string\" selected>Anywhere in a word</option>" +
  674. "<option value=\"word\">\"Whole\" words only</option><option value=\"regex\">Regular Expression (advanced)</option></select></p></td>" +
  675. "<td style=\"width:55%\" id=\"stylecontrols\"><p><span>Text color:</span> R:<input id=\"txtr\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" " +
  676. "style=\"width:4em\" value=\"0\"> G:<input id=\"txtg\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" " +
  677. "style=\"width:4em\" value=\"0\"> B:<input id=\"txtb\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" " +
  678. "style=\"width:4em\" value=\"0\"> <button id=\"btntxtreset\">Reset</button></p><p><span>Background:</span> R:<input id=\"bkgr\" " +
  679. "type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:4em\" value=\"255\"> G:<input id=\"bkgg\" " +
  680. "type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:4em\" value=\"255\"> B:<input id=\"bkgb\" " +
  681. "type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:4em\" value=\"128\"> <button id=\"btnbkgreset\">Reset</button>" +
  682. "</p><p><span>Font-weight:</span> <select id=\"fwsel\"><option value=\"inherit\" selected>inherit</option>" +
  683. "<option value=\"bold\"><b>bold</b></option><option value=\"normal\">not bold</option></select></p><p><span>Custom:</span> <input type=\"text\" " +
  684. "id=\"kwhicustom\" style=\"width:55%\"> <button id=\"kwhicustomapply\">Apply</button></p></td></tr></tbody></table>" +
  685. "<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\">" +
  686. "#kwhiedit{position:fixed;top:1px;left:150px;width:800px;height:400px;border:1px solid #000;border-radius:6px;padding:1em;color:#000;" +
  687. "background:#fafafa;z-index:2501;display:none} #kwhiedit table{width:100%;background:#fff;border-top:1px solid #000;" +
  688. "border-left:1px solid #000;} #kwhiedit td{padding:0 16px; vertical-align:top;border-right:1px solid #000;border-bottom:1px solid #000;}" +
  689. "#stylecontrols>p>span{display:inline-block;width:6.5em;}</style><style type=\"text/css\" id=\"kwhiedittemp\"></style></div>";
  690. document.body.appendChild(kwhied);
  691. // Attach event handlers
  692. document.getElementById("btnkwhisave").addEventListener("click",kwhisavechg,false);
  693. document.getElementById("btnkwhicancel").addEventListener("click",kwhicancel,false);
  694. document.getElementById("btnkwhiremove").addEventListener("click",kwhiremove,false);
  695. document.getElementById("stylecontrols").addEventListener("input", updatestyle, false);
  696. document.getElementById("btntxtreset").addEventListener("click",kwhicolorreset,false);
  697. document.getElementById("btnbkgreset").addEventListener("click",kwhicolorreset,false);
  698. document.getElementById("fwsel").addEventListener("change",kwhifwchg,false);
  699. document.getElementById("kwhicustomapply").addEventListener("click",kwhicustom,false);
  700.  
  701. function kwhisavechg(e){
  702. // Update object, regenerate CSS if applicable, apply to document
  703. var hlset = document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className;
  704. var kwtext = document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent;
  705. if (hlset == ""){
  706. // create a new set number
  707. var hlset = "set" + hlnextset;
  708. hlnextset += 1;
  709. GM_setValue("hlnextset",hlnextset);
  710. // add the set
  711. if (document.getElementById("kwhipattype").value == "regex"){
  712. kwtext = kwtext.replace(/\\/g, "\\");
  713. var hlpattxt = ""; //TODOLATER
  714. } else {
  715. var hlpattxt = "";
  716. }
  717. hlobj[hlset] = {
  718. keywords : kwtext,
  719. type : document.getElementById("kwhipattype").value,
  720. hlpat : hlpattxt,
  721. textcolor : kwhieditstyle[0],
  722. backcolor : kwhieditstyle[1],
  723. fontweight : kwhieditstyle[2],
  724. custom : kwhieditstyle[3],
  725. enabled : "true",
  726. visible : "true",
  727. updated : ""
  728. }
  729. // Update the global key array
  730. hlkeys = Object.keys(hlobj);
  731. } else {
  732. hlobj[hlset].type = document.getElementById("kwhipattype").value;
  733. // Save keyword changes after user confirmation
  734. if (kwtext != hlobj[hlset].keywords){
  735. if (confirm("Save updated keywords (and other changes)?")){
  736. if (hlobj[hlset].type != "regex") hlobj[hlset].keywords = kwtext;
  737. else{
  738. hlobj[hlset].keywords = kwtext.replace(/\\/g, "\\");
  739. hlobj[hlset].hlpat = ""; //TODOLATER
  740. }
  741. } else return;
  742. }
  743. // Save style changes without confirmation
  744. hlobj[hlset].textcolor = kwhieditstyle[0];
  745. hlobj[hlset].backcolor = kwhieditstyle[1];
  746. hlobj[hlset].fontweight = kwhieditstyle[2];
  747. hlobj[hlset].custom = kwhieditstyle[3];
  748. // Set updated date/time
  749. hlobj[hlset].updated = (new Date()).toJSON();
  750. }
  751. // Persist the object
  752. hljson = JSON.stringify(hlobj);
  753. GM_setValue("kwstyles",hljson);
  754. // Update CSS rule and parent form
  755. insertCSS([hlset]);
  756. refreshSetList();
  757. // Unhighlight, re-highlight, close dialog
  758. unhighlight(hlset);
  759. THmo_doHighlight(document.body,[hlset])
  760. document.getElementById('kwhiedit').style.display='none';
  761. }
  762. function kwhicancel(e){
  763. // Close dialog (fields will be refresh if it is opened again)
  764. document.getElementById('kwhiedit').style.display='none';
  765. }
  766. function kwhiremove(e){
  767. var hlset = document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className;
  768. if (hlset == ""){
  769. alert("This set has not been saved and therefore does not need to be hidden, you can just close the dialog to discard it.");
  770. } else {
  771. if (confirm("Are you sure you want to hide this set instead of editing it to your own liking?")){
  772. hlobj[hlset].visible = "false";
  773. hlobj[hlset].updated = (new Date()).toJSON();
  774. // Persist the object
  775. hljson = JSON.stringify(hlobj);
  776. GM_setValue("kwstyles",hljson);
  777. // Update set list, remove highlighting, close form
  778. refreshSetList();
  779. unhighlight(hlset);
  780. document.getElementById('kwhiedit').style.display='none';
  781. }
  782. }
  783. }
  784. function kwhicolorreset(e){
  785. // what set is this?
  786. var set = document.querySelector('#kwhiedit tr').getAttribute('kwhiset');
  787. // check which button, reset the RGB
  788. if (e.target.id == "btntxtreset"){
  789. if (set == "new"){
  790. kwhieditstyle[0] = "rgb(0,0,255)";
  791. } else {
  792. kwhieditstyle[0] = hlobj[set].textcolor;
  793. }
  794. populateRGB("txt",kwhieditstyle[0]);
  795. setdivstyle(["txt"]);
  796. }
  797. if (e.target.id == "btnbkgreset"){
  798. if (set == "new"){
  799. kwhieditstyle[1] = "rgb(255,255,0)";
  800. } else {
  801. kwhieditstyle[1] = hlobj[set].backcolor;
  802. }
  803. populateRGB("bkg",kwhieditstyle[1]);
  804. setdivstyle(["bkg"]);
  805. }
  806. e.target.blur();
  807. }
  808. function populateRGB(prop,stylestring){
  809. var rgbvals = stylestring.substr(stylestring.indexOf("(")+1);
  810. rgbvals = rgbvals.substr(0,rgbvals.length-1).split(",");
  811. document.getElementById(prop+"r").value = parseInt(rgbvals[0]);
  812. document.getElementById(prop+"g").value = parseInt(rgbvals[1]);
  813. document.getElementById(prop+"b").value = parseInt(rgbvals[2]);
  814. }
  815. function updatestyle(e){
  816. // validate value and apply change
  817. if (e.target.id.indexOf("txt") == 0 || e.target.id.indexOf("bkg") == 0){
  818. if (isNaN(e.target.value)){
  819. alert("Please only use values between 0 and 255");
  820. return;
  821. }
  822. if (parseInt(e.target.value) != e.target.value){
  823. e.target.value = parseInt(e.target.value);
  824. }
  825. if (e.target.value < 0){
  826. e.target.value = 0;
  827. }
  828. if (e.target.value > 255){
  829. e.target.value = 255;
  830. }
  831. if (e.target.id.indexOf("txt") == 0) setdivstyle(["txt"]);
  832. if (e.target.id.indexOf("bkg") == 0) setdivstyle(["bkg"]);
  833. } else {
  834. if (e.target.id == "kwhicustom") return;
  835. console.log("updatestyle on "+e.target.id);
  836. }
  837. }
  838. function setdivstyle(props){
  839. for (var i=0; i<props.length; i++){
  840. switch (props[i]){
  841. case "txt":
  842. kwhieditstyle[0] = "rgb(" + document.getElementById("txtr").value + "," +
  843. document.getElementById("txtg").value + "," + document.getElementById("txtb").value + ")";
  844. break;
  845. case "bkg":
  846. kwhieditstyle[1] = "rgb(" + document.getElementById("bkgr").value + "," +
  847. document.getElementById("bkgg").value + "," + document.getElementById("bkgb").value + ")";
  848. break;
  849. default:
  850. console.log("default?");
  851. }
  852. }
  853. var rule = "#stylecontrols>p>span{";
  854. if (kwhieditstyle[0].length > 0) rule += "color:"+kwhieditstyle[0]+";";
  855. if (kwhieditstyle[1].length > 0) rule += "background-color:"+kwhieditstyle[1]+";";
  856. if (kwhieditstyle[2].length > 0) rule += "font-weight:"+kwhieditstyle[2]+";";
  857. if (kwhieditstyle[3].length > 0) rule += kwhieditstyle[3]+";";
  858. document.getElementById("kwhiedittemp").innerHTML = rule + "}";
  859. }
  860. function kwhifwchg(e){
  861. kwhieditstyle[2] = e.target.value;
  862. setdivstyle([]);
  863. }
  864. function kwhicustom(e){
  865. kwhieditstyle[3] = document.getElementById("kwhicustom").value;
  866. setdivstyle([]);
  867. }
  868. // Context menu options -- do not replace any existing menu!
  869. if (!document.body.hasAttribute("contextmenu") && "contextMenu" in document.documentElement){
  870. var cmenu = document.createElement("menu");
  871. cmenu.id = "THDcontext";
  872. cmenu.setAttribute("type", "context");
  873. cmenu.innerHTML = '<menu label="Text Highlight and Seek">' +
  874. '<menuitem id="THDshowbar" label="Show bar"></menuitem>' +
  875. '<menuitem id="THDenableset" label="Enable matching set"></menuitem>' +
  876. '<menuitem id="THDdisableset" label="Disable this set"></menuitem>' +
  877. '<menuitem id="THDnewset" label="Add new set"></menuitem>' +
  878. '</menu>';
  879. document.body.appendChild(cmenu);
  880. document.getElementById("THDshowbar").addEventListener("click",editKW,false);
  881. document.getElementById("THDenableset").addEventListener("click",cmenuEnable,false);
  882. document.getElementById("THDdisableset").addEventListener("click",cmenuDisable,false);
  883. document.getElementById("THDnewset").addEventListener("click",cmenuNewset,false);
  884. // attach menu and create event for filtering
  885. document.body.setAttribute("contextmenu", "THDcontext");
  886. document.body.addEventListener("contextmenu",cmenuFilter,false);
  887. }
  888. function cmenuFilter(e){
  889. document.getElementById("THDenableset").setAttribute("disabled","disabled");
  890. document.getElementById("THDenableset").setAttribute("THDtext","");
  891. document.getElementById("THDdisableset").setAttribute("disabled","disabled");
  892. document.getElementById("THDdisableset").setAttribute("THDset","");
  893. var s = window.getSelection();
  894. if (s.isCollapsed) document.getElementById("THDnewset").setAttribute("THDtext","");
  895. else document.getElementById("THDnewset").setAttribute("THDtext",s.getRangeAt(0).toString().trim());
  896. if (e.target.hasAttribute('txhidy15')){
  897. document.getElementById("THDdisableset").removeAttribute("disabled");
  898. document.getElementById("THDdisableset").setAttribute("THDset",e.target.getAttribute('txhidy15'));
  899. } else {
  900. document.getElementById("THDdisableset").setAttribute("disabled","disabled");
  901. if (!s.isCollapsed){
  902. document.getElementById("THDenableset").removeAttribute("disabled");
  903. document.getElementById("THDenableset").setAttribute("THDtext",s.getRangeAt(0).toString().trim());
  904. }
  905. }
  906. }
  907. function cmenuEnable(e){
  908. var kw = e.target.getAttribute("THDtext").toLowerCase();
  909. var toggled = false;
  910. for (var j = 0; j < hlkeys.length; ++j){
  911. var hlset = hlkeys[j];
  912. var kwlist = "|" + hlobj[hlset].keywords.toLowerCase() + "|";
  913. if(kwlist.indexOf("|" + kw + "|") > -1){
  914. if (hlobj[hlset].enabled == "true") break; // already enabled
  915. kwhienabledisable(hlset,true);
  916. refreshSetList();
  917. toggled = true;
  918. break;
  919. }
  920. }
  921. if (toggled == false){
  922. if (document.getElementById("thdtopbar").style.display != "block") editKW();
  923. if (document.getElementById("thdtopdrop").style.display != "block") thdDropSetList();
  924. }
  925. }
  926. function cmenuDisable(e){
  927. kwhienabledisable(e.target.getAttribute("THDset"),false);
  928. refreshSetList();
  929. }
  930. function cmenuNewset(e){
  931. //TODO - if there's a selection, get it into the form
  932. kwhinewset(e,e.target.getAttribute("THDtext"));
  933. }
  934.  
  935. // TESTING ONLY
  936. function flushData(){
  937. GM_setValue("kwstyles", "");
  938. }
  939. GM_registerMenuCommand("TEST ONLY - flush keyword sets for Text Highlight and Seek", flushData);
  940.  
  941. })(); // end of anonymous function