Text Highlight and Seek

Automatically highlight user-defined text with Seek function (2019-09-22)

  1. // ==UserScript==
  2. // @name Text Highlight and Seek
  3. // @author erosman and Jefferson "jscher2000" Scher
  4. // @namespace JeffersonScher
  5. // @version 2.4.0
  6. // @description Automatically highlight user-defined text with Seek function (2019-09-22)
  7. // @include https://greasyfork.org/*
  8. // @include https://openuserjs.org/*
  9. // @include http*://www.jeffersonscher.com/*
  10. // @grant GM_registerMenuCommand
  11. // @grant GM_setValue
  12. // @grant GM.setValue
  13. // @grant GM_getValue
  14. // @grant GM.getValue
  15. // @grant GM_getResourceURL
  16. // @grant GM.getResourceUrl
  17. // @copyright Copyright 2019 Jefferson Scher. Portions created by erosman.
  18. // @license BSD-3-clause
  19. // @resource mycon http://www.jeffersonscher.com/gm/src/gfrk-THS-ver240.png
  20. // ==/UserScript==
  21. var script_about = "https://greasyfork.org/scripts/13007-text-highlight-and-seek";
  22. /* --------- Note ---------
  23. TO INCLUDE SITES (only Greasy Fork and OpenUserJS are initially included):
  24.  
  25. Go to Add-ons - User Scripts (Ctrl+Shift+a/Cmd+Shift+a on Firefox Windows/Mac)
  26. Click on the Script's Option
  27. Under User Settings Tab, Add Included/Excluded Pages that you want the script to run on
  28. Click OK
  29.  
  30. Note from erosman: If you find that another script clashes with this script, set Text Highlight and Seek to Execute first.
  31. Go to Add-ons - User Scripts ('Ctrl+ Shift + a' on Firefox)
  32. Right Click on the Script
  33. On the context menu click: Execute first
  34.  
  35. On Add-ons - User Scripts, you can also Click on the Execution Order (top Right) and
  36. change the execution order so that Text Highlight and Seek runs before those scripts that clashes with it.
  37. */
  38. var hlframe, hlobjDefault, kwhieditstyle, hljson, hlobj, hlkeys, kwold, hlold, hlbtnvis, hlprecode, hlnextset, hbtndisp;
  39. var GM4 = (typeof GM_getValue === "undefined") ? true : false;
  40.  
  41. async function THS_init(){
  42. if (!GM4){
  43. hlframe = GM_getValue("hlframe", ""); // get iframe pref
  44. } else {
  45. hlframe = await GM.getValue("hlframe", "");
  46. }
  47. if (hlframe == ""){
  48. hlframe = "none";
  49. if (!GM4){
  50. GM_setValue("hlframe", hlframe);
  51. } else {
  52. await GM.setValue("hlframe", hlframe);
  53. }
  54. }
  55. if ((window.self !== window.top) && (hlframe != "any")) { // framed page
  56. if (hlframe == "none") return;
  57. if (hlframe == "same") {
  58. console.log(window.self.location.hostname + " vs " + window.top.location.hostname);
  59. }
  60. }
  61.  
  62. // sample keyword+style object to get started
  63. hlobjDefault = {
  64. "set100" : {
  65. keywords : "scripts|script",
  66. type : "string",
  67. hlpat : "",
  68. textcolor : "rgb(0,0,0)",
  69. backcolor : "rgb(255,255,128)",
  70. fontweight : "inherit",
  71. custom : "",
  72. enabled : "true",
  73. visible : "true",
  74. updated : ""
  75. },
  76. "set099" : {
  77. keywords : "site",
  78. type : "word",
  79. hlpat : "",
  80. textcolor : "rgb(0,0,0)",
  81. backcolor : "rgb(255,192,255)",
  82. fontweight : "inherit",
  83. custom : "",
  84. enabled : "true",
  85. visible : "true",
  86. updated : ""
  87. },
  88. "set098" : {
  89. keywords : "^October \\d{1,2}",
  90. type : "regex",
  91. hlpat : "",
  92. textcolor : "rgb(0,0,0)",
  93. backcolor : "rgb(192,255,255)",
  94. fontweight : "inherit",
  95. custom : "",
  96. enabled : "true",
  97. visible : "true",
  98. updated : ""
  99. }
  100. };
  101. kwhieditstyle = ["rgb(0,0,255)","rgb(255,255,0)","inherit",""];
  102.  
  103. // read pref storage: keyword-style sets
  104. if (!GM4){
  105. hljson = GM_getValue("kwstyles");
  106. } else {
  107. hljson = await GM.getValue("kwstyles");
  108. }
  109. if (!hljson || hljson.length == 0){
  110. hlobj = hlobjDefault;
  111. // check for legacy preferences
  112. if (!GM4){
  113. kwold = GM_getValue("keywords");
  114. } else {
  115. kwold = await GM.getValue("keywords");
  116. }
  117. if (kwold) if(kwold.length > 0) {
  118. hlobj.set100.keywords = kwold.split(',').join('|');
  119. }
  120. if (!GM4){
  121. hlold = GM_getValue("highlightStyle");
  122. } else {
  123. hlold = await GM.getValue("highlightStyle");
  124. }
  125. if (hlold) if(hlold.length > 0) {
  126. // really should try to parse this, but for now...
  127. hlobj.set100.custom = hlold;
  128. }
  129. // save starting values
  130. hljson = JSON.stringify(hlobj);
  131. if (!GM4){
  132. GM_setValue("kwstyles", hljson);
  133. } else {
  134. await GM.setValue("kwstyles", hljson);
  135. }
  136. } else {
  137. hlobj = JSON.parse(hljson);
  138. }
  139. // global keys array
  140. hlkeys = Object.keys(hlobj);
  141.  
  142. // read/set other prefs
  143. if (!GM4){
  144. hlbtnvis = GM_getValue("hlbtnvis", "");
  145. } else {
  146. hlbtnvis = await GM.getValue("hlbtnvis", "");
  147. }
  148. if (hlbtnvis == ""){
  149. hlbtnvis = "on";
  150. if (!GM4){
  151. GM_setValue("hlbtnvis", hlbtnvis);
  152. } else {
  153. await GM.setValue("hlbtnvis", hlbtnvis);
  154. }
  155. }
  156.  
  157. if (!GM4){
  158. hlprecode = GM_getValue("hlprecode", "");
  159. } else {
  160. hlprecode = await GM.getValue("hlprecode", "");
  161. }
  162. if (hlprecode == ""){
  163. hlprecode = true;
  164. if (!GM4){
  165. GM_setValue("hlprecode", hlprecode);
  166. } else {
  167. await GM.setValue("hlprecode", hlprecode);
  168. }
  169. }
  170.  
  171. if (!GM4){
  172. hlnextset = GM_getValue("hlnextset", "");
  173. } else {
  174. hlnextset = await GM.getValue("hlnextset", "");
  175. }
  176. if (hlnextset == ""){
  177. hlnextset = 101;
  178. if (!GM4){
  179. GM_setValue("hlnextset", hlnextset);
  180. } else {
  181. await GM.setValue("hlnextset", hlnextset);
  182. }
  183. }
  184. // Inject CSS
  185. insertCSS(hlkeys);
  186. // first run
  187. THmo_doHighlight(document.body,null);
  188.  
  189. // Add MutationObserver to catch content added dynamically
  190. var THmo_MutOb = (window.MutationObserver) ? window.MutationObserver : window.WebKitMutationObserver;
  191. if (THmo_MutOb){
  192. var THmo_chgMon = new THmo_MutOb(function(mutationSet){
  193. mutationSet.forEach(function(mutation){
  194. for (var i=0; i<mutation.addedNodes.length; i++){
  195. if (mutation.addedNodes[i].nodeType == 1){
  196. THmo_doHighlight(mutation.addedNodes[i],null);
  197. }
  198. }
  199. });
  200. });
  201. // attach chgMon to document.body
  202. var opts = {childList: true, subtree: true};
  203. THmo_chgMon.observe(document.body, opts);
  204. }
  205.  
  206. // Set up top highlight/seek bar
  207. var kwhibar = document.createElement("div");
  208. kwhibar.id = "thdtopbar";
  209. if (hlbtnvis == "on") var btnchk = " checked=\"checked\"";
  210. else var btnchk = "";
  211. if (hlprecode) var btnprecode = " checked=\"checked\"";
  212. else var btnprecode = "";
  213. 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>" +
  214. "<div id=\"thdtopcurrent\"><p id=\"thdtopkeywords\" title=\"Click to View, Edit, Seek, or Add Keywords\">Click to manage keyword/highlight sets &bull; <em>Add New Set</em></p>" +
  215. "<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>" +
  216. "<span style=\"float:right\"><button id=\"btnkwhiexport\">Export Sets</button> <button id=\"btnkwhiimport\">Import Sets</button> <button id=\"thdtopdropclose\">X</button></span></p></div></div>" +
  217. "<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>" +
  218. "<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 +
  219. "> 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 +
  220. "> Match in pre/code</label></li><li><label style=\"padding-left:4px\">Framed pages:</label><br><select id=\"hlframeselect\" size=\"3\"><option value=\"none\">No highlighting</option><option value=\"same\">Same site only</option>" +
  221. "<option value=\"any\">Any site</option></select></li><li><button id=\"btnthsreread\" title=\"Update from and apply stored settings\" disabled>Re-Read Saved Prefs</button></li></ul></div>" +
  222. "<button class=\"btnkwhiclose\" onclick=\"document.getElementById('thdtopbar').style.display='none';document.getElementById('thdtopspacer').style.display='none';return false;\" style=\"float:right\">X</button></form>" +
  223. "<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} " +
  224. "#thdtopbar,#thdtopbar *{box-sizing:content-box;} #thdtopform{display:block;position:relative;float:left;width:100%;margin:0;border:none;} " +
  225. "#thdtopbarhome,#thdtopcurrent,#thdtopfindbuttons,#thdtopoptions{float:left;top:0;left:0;margin:0;padding:5px 8px 4px;border-right:1px solid #fff;font-size:16px;} " +
  226. "#thdtopbarhome{width:22px;text-align:center;overflow:hidden;} #thdtopbarhome a{display:block;} #thdtopbarhome a img{display:block;border:none;border-radius:3px;padding:3px;margin:-3px 0 -4px 0;background-color:#fff} " +
  227. "#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;} " +
  228. "#thdtopfindbuttons button:hover{background:#ffa;} #thdseekdesc{cursor:pointer} #thdtopkeywords{margin:0;width:500px;cursor:pointer;} #thdtopkeywords em{padding: 0 2px;} #thdtopkeywords em:hover{background:#ffa;}" +
  229. "#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}" +
  230. "#thdtopkeywords span{display:inline-block;width:100%;overflow:hidden;text-overflow:ellipsis;} #thdtable{max-height:600px;overflow-y:auto;overflow-x:hidden} " +
  231. "#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;} " +
  232. "#thdtopdrop table{width:100%;background:#fff;border-top:1px solid #000;border-left:1px solid #000;table-layout:fixed} " +
  233. "#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;} " +
  234. "#thdtopoptions{position:relative;width:160px;height:26px;padding:0 8px;} #thdtopoptions > div{padding:5px 0 4px;} " +
  235. "#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;} " +
  236. "#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;}" +
  237. ".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} #hlframeselect{margin:3px 0 3px 4px;border-radius:4px}</style>";
  238. document.body.appendChild(kwhibar);
  239. // Attach event handlers
  240. document.getElementById("thdtopkeywords").addEventListener("click",thddroptoggle,false);
  241. document.getElementById("kwhitbod").addEventListener("click",kwhiformevent,false);
  242. document.getElementById("kwhitbod").addEventListener("dblclick",kwhiformevent,false);
  243. document.getElementById("btnkwhiadd").addEventListener("click",kwhinewset,false);
  244. document.getElementById("btnkwhiexport").addEventListener("click",kwhiexport,false);
  245. document.getElementById("btnkwhiimport").addEventListener("click",kwhiimport,false);
  246. document.getElementById("thdtopfindbuttons").addEventListener("click",thdseek,false);
  247. document.getElementById("chkhbtn").addEventListener("click",kwhihbtn,false);
  248. document.getElementById("chkprecode").addEventListener("click",kwhiprecode,false);
  249. document.getElementById("btnthsreread").addEventListener("click",thsreread,false);
  250. document.getElementById("thdtopdropclose").addEventListener("click",kwhitopdropclose,false);
  251. // frame options
  252. document.getElementById("hlframeselect").addEventListener("change",thsframeselect,false);
  253. setthsframeopts();
  254. // Add spacer at top of body
  255. var divsp = document.createElement("div");
  256. divsp.id = "thdtopspacer";
  257. divsp.setAttribute("style","clear:both;display:none");
  258. divsp.style.height = parseInt(27 - parseInt(window.getComputedStyle(document.body,null).getPropertyValue("margin-top"))) + "px";
  259. document.body.insertBefore(divsp, document.body.childNodes[0]);
  260. // Switch JS text to icon
  261. var JSBTN = document.createElement("img");
  262. if (!GM4){
  263. JSBTN.src = GM_getResourceURL("mycon");
  264. } else { /* asynchronous*/
  265. JSBTN.src = await GM.getResourceUrl("mycon");
  266. }
  267. document.querySelector("#thdtopbar a").textContent = "";
  268. document.querySelector("#thdtopbar a").appendChild(JSBTN);
  269. // Add menu item
  270. if (!GM4) GM_registerMenuCommand("Show Text Highlight and Seek Bar - View, Edit, Add Keywords and Styles", editKW);
  271. // Inject H button
  272. if (hlbtnvis == "off") hbtndisp = ' style="display:none"';
  273. else hbtndisp = '';
  274. var dNew = document.createElement("div");
  275. dNew.innerHTML = '<button id="btnshowkwhi"' + hbtndisp + '>H</button><style type="text/css">#btnshowkwhi{position:fixed;top:4px;right:4px;opacity:0.2;' +
  276. '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}' +
  277. '#btnshowkwhi:hover{opacity:0.8}@media print{#btnshowkwhi{display:none;}}</style>';
  278. document.body.appendChild(dNew);
  279. document.getElementById("btnshowkwhi").addEventListener("click",editKW,false);
  280.  
  281. // Set up add/edit form
  282. var kwhied = document.createElement("div");
  283. kwhied.id = "kwhiedit";
  284. kwhied.innerHTML = "<form onsubmit=\"return false;\"><p style=\"margin-top:0\"><b>Edit/Add Keywords/Highlighting</b>" +
  285. "<span class=\"btnkwhiclose\"><button id=\"btnkwhimax\" title=\"Maximize dialog size\">^</button>&nbsp;&nbsp;" +
  286. "<button onclick=\"document.getElementById('kwhiedit').style.display='none'; return false;\" title=\"Close dialog\">X</button></span>" +
  287. "</p><p>List longer forms of a word first to match both in full. Example: \"children|child\" will highlight both, but \"child|children\" " +
  288. "will only highlight child, it won't expand the selection to children.</p>" +
  289. "<table cellspacing=\"0\" style=\"table-layout:fixed\"><tbody><tr kwhiset=\"new\"><td style=\"width:calc(100% - 464px)\">" +
  290. "<p contenteditable=\"true\" style=\"border:1px dotted #000;word-wrap:break-word;display:block!important\" class=\"\">placeholder</p>" +
  291. "<p style=\"margin-top:2em\">Match type: <select id=\"kwhipattype\"><option value=\"string\" selected>Anywhere in a word</option>" +
  292. "<option value=\"word\">\"Whole\" words only</option><option value=\"regex\">Regular Expression (advanced)</option></select></p></td>" +
  293. "<td style=\"width:416px\" id=\"stylecontrols\"><p><span>Text color:</span> <input id=\"txtcolorinput\" type=\"color\" value=\"#000000\" title=\"Pop up color picker\"> " +
  294. "R:<input id=\"txtr\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:3.25em\" value=\"0\"> " +
  295. "G:<input id=\"txtg\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:3.25em\" value=\"0\"> " +
  296. "B:<input id=\"txtb\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:3.25em\" value=\"0\"> " +
  297. "<button id=\"btntxtreset\">Reset</button></p>" +
  298. "<p><span>Background:</span> <input id=\"bkgcolorinput\" type=\"color\" value=\"#ffff80\" title=\"Pop up color picker\"> " +
  299. "R:<input id=\"bkgr\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:3.25em\" value=\"255\"> " +
  300. "G:<input id=\"bkgg\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:3.25em\" value=\"255\"> " +
  301. "B:<input id=\"bkgb\" type=\"number\" min=\"0\" max=\"255\" step=\"1\" style=\"width:3.25em\" value=\"128\"> <button id=\"btnbkgreset\">Reset</button></p>" +
  302. "<p><span>Font-weight:</span> <select id=\"fwsel\"><option value=\"inherit\" selected>inherit</option>" +
  303. "<option value=\"bold\"><b>bold</b></option><option value=\"normal\">not bold</option></select></p><p><span>Custom:</span> <input type=\"text\" " +
  304. "id=\"kwhicustom\" style=\"width:55%\"> <button id=\"kwhicustomapply\">Apply</button></p></td></tr></tbody></table>" +
  305. "<p><button id=\"btnkwhisave\">Save Changes</button> <button id=\"btnkwhicancel\">Discard Changes</button> " +
  306. "<button id=\"btnkwhiremove\">Hide Set</button> <button id=\"btnkwhirevert\" disabled>Revert Last Keyword Edit</button></p></form><style type=\"text/css\">" +
  307. "#kwhiedit{position:fixed;top:1px;left:150px;width:800px;height:400px;border:1px solid #000;border-radius:6px;padding:1em;color:#000;" +
  308. "background:#fafafa;z-index:2501;display:none} #kwhiedit table{width:100%;background:#fff;border-top:1px solid #000;" +
  309. "border-left:1px solid #000;} #kwhiedit td{padding:0 12px; vertical-align:top;border-right:1px solid #000;border-bottom:1px solid #000;}" +
  310. "#kwhiedit td p{margin-top:12px;} #stylecontrols>p>span{display:inline-block;width:6.5em;} " +
  311. "#stylecontrols input[type=\"color\"]{padding:0; width:24px; height:1.25em; border:none;}</style><style type=\"text/css\" id=\"kwhiedittemp\"></style></div>";
  312. document.body.appendChild(kwhied);
  313. // Attach event handlers
  314. document.getElementById("btnkwhisave").addEventListener("click",kwhisavechg,false);
  315. document.getElementById("btnkwhicancel").addEventListener("click",kwhicancel,false);
  316. document.getElementById("btnkwhiremove").addEventListener("click",kwhiremove,false);
  317. document.getElementById("btnkwhirevert").addEventListener("click",kwhirevert,false);
  318. document.getElementById("stylecontrols").addEventListener("input",updatestyle,false);
  319. document.getElementById("stylecontrols").addEventListener("change",updatecolor,false);
  320. document.getElementById("btntxtreset").addEventListener("click",kwhicolorreset,false);
  321. document.getElementById("btnbkgreset").addEventListener("click",kwhicolorreset,false);
  322. document.getElementById("fwsel").addEventListener("change",kwhifwchg,false);
  323. document.getElementById("kwhicustomapply").addEventListener("click",kwhicustom,false);
  324. document.getElementById("btnkwhimax").addEventListener("click",kwhimaxrestore,false);
  325.  
  326. // Context menu options -- do not replace any existing menu!
  327. if (!document.body.hasAttribute("contextmenu") && "contextMenu" in document.documentElement){
  328. var cmenu = document.createElement("menu");
  329. cmenu.id = "THDcontext";
  330. cmenu.setAttribute("type", "context");
  331. cmenu.innerHTML = '<menu label="Text Highlight and Seek">' +
  332. '<menuitem id="THDshowbar" label="Show bar"></menuitem>' +
  333. '<menuitem id="THDenableset" label="Enable matching set"></menuitem>' +
  334. '<menuitem id="THDdisableset" label="Disable this set"></menuitem>' +
  335. '<menuitem id="THDnewset" label="Add new set"></menuitem>' +
  336. '</menu>';
  337. document.body.appendChild(cmenu);
  338. document.getElementById("THDshowbar").addEventListener("click",editKW,false);
  339. document.getElementById("THDenableset").addEventListener("click",cmenuEnable,false);
  340. document.getElementById("THDdisableset").addEventListener("click",cmenuDisable,false);
  341. document.getElementById("THDnewset").addEventListener("click",cmenuNewset,false);
  342. // attach menu and create event for filtering
  343. document.body.setAttribute("contextmenu", "THDcontext");
  344. document.body.addEventListener("contextmenu",cmenuFilter,false);
  345. }
  346.  
  347. if (!GM4) GM_registerMenuCommand("TEST ONLY - flush keyword sets for Text Highlight and Seek", flushData);
  348. }
  349. THS_init();
  350.  
  351. // Main workhorse routine
  352. function THmo_doHighlight(el,subset){
  353. if (subset) var keyset = subset;
  354. else var keyset = hlkeys;
  355. for (var j = 0; j < keyset.length; ++j) {
  356. var hlset = keyset[j];
  357. if (hlobj[hlset].visible == "true" && hlobj[hlset].enabled == "true"){
  358. var hlkeywords = hlobj[hlset].keywords;
  359. if (hlkeywords.length > 0) {
  360. if (hlobj[hlset].type != "regex"){
  361. var rQuantifiers = /[-\/\\^$*+?.()[\]{}]/g;
  362. hlkeywords = hlkeywords.replace(rQuantifiers, '\\$&');
  363. if (hlobj[hlset].type == "word"){
  364. hlkeywords = "\\b" + hlkeywords.replace(/\|/g, "\\b|\\b") + "\\b";
  365. }
  366. }
  367. //console.log("hlset:"+hlset+"\nhlkeywords:"+hlkeywords);
  368. var pat = new RegExp('(' + hlkeywords + ')', 'gi');
  369. var span = document.createElement('thdfrag');
  370. span.setAttribute("thdcontain","true");
  371. // getting all text nodes with a few exceptions
  372. if (hlprecode){
  373. var snapElements = document.evaluate(
  374. './/text()[normalize-space() != "" ' +
  375. 'and not(ancestor::style) ' +
  376. 'and not(ancestor::script) ' +
  377. 'and not(ancestor::textarea) ' +
  378. 'and not(ancestor::div[@id="thdtopbar"]) ' +
  379. 'and not(ancestor::div[@id="kwhiedit"]) ' +
  380. 'and not(parent::thdfrag[@txhidy15])]',
  381. el, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  382. } else {
  383. var snapElements = document.evaluate(
  384. './/text()[normalize-space() != "" ' +
  385. 'and not(ancestor::style) ' +
  386. 'and not(ancestor::script) ' +
  387. 'and not(ancestor::textarea) ' +
  388. 'and not(ancestor::pre) ' +
  389. 'and not(ancestor::code) ' +
  390. 'and not(ancestor::div[@id="thdtopbar"]) ' +
  391. 'and not(ancestor::div[@id="kwhiedit"]) ' +
  392. 'and not(parent::thdfrag[@txhidy15])]',
  393. el, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  394. }
  395.  
  396. if (!snapElements.snapshotItem(0)) { break; }
  397.  
  398. for (var i = 0, len = snapElements.snapshotLength; i < len; i++) {
  399. var node = snapElements.snapshotItem(i);
  400. // check if it contains the keywords
  401. if (pat.test(node.nodeValue)) {
  402. // create an element, replace the text node with an element
  403. var sp = span.cloneNode(true);
  404. sp.innerHTML = node.nodeValue.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(pat, '<thdfrag class="THmo '+hlset+'" txhidy15="'+hlset+'">$1</thdfrag>');
  405. node.parentNode.replaceChild(sp, node);
  406. // try to un-nest containers
  407. if (sp.parentNode.hasAttribute("thdcontain")) sp.outerHTML = sp.innerHTML;
  408. }
  409. }
  410. }
  411. }
  412. }
  413. }
  414. function insertCSS(setkeys){
  415. for (var j = 0; j < setkeys.length; ++j){
  416. var hlset = setkeys[j];
  417. if (hlobj[hlset].visible == "true"){
  418. var rule = "."+hlset+"{display:inline!important;";
  419. if (hlobj[hlset].textcolor.length > 0) rule += "color:"+hlobj[hlset].textcolor+";";
  420. if (hlobj[hlset].backcolor.length > 0) rule += "background-color:"+hlobj[hlset].backcolor+";";
  421. if (hlobj[hlset].fontweight.length > 0) rule += "font-weight:"+hlobj[hlset].fontweight+";";
  422. if (hlobj[hlset].custom.length > 0) rule += hlobj[hlset].custom+";";
  423. rule += "}";
  424. var setrule = document.querySelector('style[hlset="' + hlset +'"]');
  425. if (!setrule){
  426. var s = document.createElement("style");
  427. s.type = "text/css";
  428. s.setAttribute("hlset", hlset);
  429. s.appendChild(document.createTextNode(rule));
  430. document.body.appendChild(s);
  431. } else {
  432. setrule.innerHTML = rule;
  433. }
  434. }
  435. }
  436. }
  437. function editKW(e){
  438. refreshSetList();
  439. // show form
  440. document.getElementById("thdtopbar").style.display = "block";
  441. document.getElementById("thdtopspacer").style.display = "block";
  442. }
  443. function thdDropSetList(e){
  444. refreshSetList();
  445. document.getElementById("thdtopdrop").style.display = "block";
  446. }
  447. function thddroptoggle(e){
  448. if (document.getElementById("thdtopdrop").style.display == "none"){
  449. thdDropSetList();
  450. if (e.target.nodeName == "EM") kwhinewset();
  451. } else if (e.target.nodeName == "EM"){
  452. kwhinewset();
  453. } else {
  454. document.getElementById("thdtopdrop").style.display = "none";
  455. }
  456. }
  457. function refreshSetList(e){
  458. // clear old rows from form
  459. document.getElementById("kwhitbod").innerHTML = "";
  460. // populate data - hlobj is global
  461. for (var j = 0; j < hlkeys.length; ++j){
  462. var hlset = hlkeys[j];
  463. if (hlobj[hlset].visible == "true"){
  464. if (hlobj[hlset].enabled == "true") var strchk = ' checked=\"checked\"';
  465. else var strchk = '';
  466. var newrow = document.createElement("tr");
  467. var thdtypenote = '';
  468. newrow.setAttribute("kwhiset", hlset);
  469. if(hlobj[hlset].type != "string"){
  470. thdtypenote = '<span class="thdtype">' + hlobj[hlset].type + '</span>';
  471. }
  472. if (j == 0){
  473. newrow.innerHTML = '<td style=\"width:286px\"><div class=\"' + hlset + '\">' + hlobj[hlset].keywords + '</div>' + thdtypenote + '</td>' +
  474. '<td style=\"width:195px\"><button kwhiset=\"' + hlset + '\" title=\"Bring matches into view\">Seek</button> ' +
  475. '<button kwhiset=\"' + hlset + '\">Edit</button> <label><input type=\"checkbox\" kwhiset=\"' + hlset +
  476. '\"' + strchk + '"> Enabled </label></td>';
  477. } else {
  478. newrow.innerHTML = '<td><div class=\"' + hlset + '\">' + hlobj[hlset].keywords + '</div>' + thdtypenote + '</td>' +
  479. '<td><button kwhiset=\"' + hlset + '\" title=\"Bring matches into view\">Seek</button> ' +
  480. '<button kwhiset=\"' + hlset + '\">Edit</button> <label><input type=\"checkbox\" kwhiset=\"' + hlset +
  481. '\"' + strchk + '"> Enabled </label></td>';
  482. }
  483. document.getElementById("kwhitbod").appendChild(newrow);
  484. }
  485. }
  486. }
  487. async function kwhiformevent(e){
  488. if (e.target.nodeName == "INPUT"){ // Enabled checkbox
  489. var hlsetnum = e.target.getAttribute("kwhiset");
  490. kwhienabledisable(hlsetnum, e.target.checked);
  491. }
  492. if (e.target.nodeName == "BUTTON"){ // Call up edit form or find bar
  493. var hlset = e.target.getAttribute('kwhiset');
  494. if (e.target.textContent == "Edit"){
  495. // need to cancel in-place editor if it's open
  496. kwhicancelipe(hlset);
  497. // set set number attribute
  498. document.querySelector('#kwhiedit tr').setAttribute('kwhiset', hlset);
  499. // set class for keywords
  500. document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className = hlset;
  501. // enter placeholder text & type
  502. document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent = hlobj[hlset].keywords;
  503. document.getElementById("kwhipattype").selectedIndex = 0;
  504. if (hlobj[hlset].type == "word") document.getElementById("kwhipattype").selectedIndex = 1;
  505. if (hlobj[hlset].type == "regex") document.getElementById("kwhipattype").selectedIndex = 2;
  506. // set style editing to default and override with set rules
  507. kwhieditstyle = ["rgb(0,0,255)","rgb(255,255,0)","inherit",""]; // defaults
  508. if (hlobj[hlset].textcolor.length > 0) kwhieditstyle[0] = hlobj[hlset].textcolor;
  509. if (hlobj[hlset].backcolor.length > 0) kwhieditstyle[1] = hlobj[hlset].backcolor;
  510. if (hlobj[hlset].fontweight.length > 0) kwhieditstyle[2] = hlobj[hlset].fontweight;
  511. if (hlobj[hlset].custom.length > 0) kwhieditstyle[3] = hlobj[hlset].custom;
  512. kwhiShowEditForm();
  513. }
  514. if (e.target.textContent == "Seek"){
  515. // need to cancel in-place editor if it's open
  516. kwhicancelipe(hlset);
  517. // Enable set if not currently enabled (2.3.5)
  518. var chkbx = e.target.parentNode.querySelector('input[type="checkbox"]');
  519. if (!chkbx.checked) chkbx.click();
  520. // Populate current seek set to #thdtopkeywords
  521. var divDataTD = e.target.parentNode.previousElementSibling;
  522. document.getElementById("thdtopkeywords").innerHTML = "<i>Seeking:</i> " + divDataTD.firstChild.outerHTML;
  523. // Store set to seek in #thdtopfindbuttons
  524. document.getElementById("thdtopfindbuttons").setAttribute("thdseek", hlset);
  525. // Close Keyword Sets form
  526. document.getElementById('thdtopdrop').style.display='none';
  527. // Send click event to the "seek first" button
  528. document.getElementById('thdtopfindbuttons').children[0].click();
  529. }
  530. if (e.target.textContent == "Save"){ // Check and save in-place keyword edit
  531. // get set number attribute
  532. var hlset = e.target.getAttribute("kwhiset");
  533. var kwtext = document.querySelector('div.'+hlset+' p.'+hlset).textContent;
  534. if (kwtext == hlobj[hlset].keywords){ // Nothing to save, cancel the edit
  535. kwhicancelipe(hlset);
  536. return;
  537. }
  538. // Save keyword changes WITHOUT user confirmation
  539. hlobj[hlset].prevkeyw = hlobj[hlset].keywords;
  540. hlobj[hlset].prevtype = hlobj[hlset].type;
  541. if (hlobj[hlset].type != "regex") hlobj[hlset].keywords = kwtext;
  542. else{
  543. hlobj[hlset].keywords = kwtext.replace(/\\/g, "\\");
  544. hlobj[hlset].hlpat = ""; //TODOLATER
  545. }
  546. // Set updated date/time
  547. hlobj[hlset].updated = (new Date()).toJSON();
  548. // Persist the object
  549. hljson = JSON.stringify(hlobj);
  550. if (!GM4){
  551. GM_setValue("kwstyles", hljson);
  552. } else {
  553. await GM.setValue("kwstyles", hljson);
  554. }
  555. // Update CSS rule and parent form
  556. insertCSS([hlset]);
  557. refreshSetList();
  558. // Unhighlight, re-highlight, close in-place editor
  559. unhighlight(hlset);
  560. THmo_doHighlight(document.body,[hlset]);
  561. kwhicancelipe(hlset);
  562. }
  563. if (e.target.textContent == "Cancel"){ // Revert in-place editor
  564. // get set number attribute
  565. var hlset = e.target.getAttribute("kwhiset");
  566. kwhicancelipe(hlset);
  567. }
  568. if (e.target.textContent == "Revert"){ // Restore previous keywords
  569. // get set number attribute
  570. var hlset = e.target.getAttribute("kwhiset");
  571. // gray the button
  572. document.getElementById('thsrevert' + hlset).setAttribute('disabled', 'disabled');
  573. // get the previous keywords (if any)
  574. if (hlobj[hlset].prevkeyw && hlobj[hlset].prevkeyw != '') var kwtext = hlobj[hlset].prevkeyw;
  575. if (!kwtext || kwtext == ''){ // uh-oh
  576. alert('Unable to undo, sorry!');
  577. document.getElementById('thsrevert' + hlset).setAttribute('disabled', 'disabled');
  578. return;
  579. }
  580. // Save keyword changes WITHOUT user confirmation
  581. hlobj[hlset].keywords = kwtext;
  582. hlobj[hlset].type = hlobj[hlset].prevtype;
  583. hlobj[hlset].prevkeyw = '';
  584. hlobj[hlset].prevtype = '';
  585. // Set updated date/time
  586. hlobj[hlset].updated = (new Date()).toJSON();
  587. // Persist the object
  588. hljson = JSON.stringify(hlobj);
  589. if (!GM4){
  590. GM_setValue("kwstyles", hljson);
  591. } else {
  592. await GM.setValue("kwstyles", hljson);
  593. }
  594. // Update CSS rule and parent form
  595. insertCSS([hlset]);
  596. refreshSetList();
  597. // Unhighlight, re-highlight
  598. unhighlight(hlset);
  599. THmo_doHighlight(document.body,[hlset]);
  600. }
  601. }
  602. if (e.type == "dblclick" && e.target.nodeName == "DIV"){ // Set up in-place quick editor
  603. if (e.target.children.length == 0) { // Ignore the double-click if the editor was already set up
  604. var hlset = e.target.className;
  605. e.target.innerHTML = '<p class="' + hlset +'" contenteditable="true" style="border:1px dotted #000">' + e.target.textContent + '</p>' +
  606. '<p style="background-color:#fff;font-size:0.8em"><button kwhiset="' + hlset + '" title="Update keywords for this set" style="font-size:0.8em">' +
  607. 'Save</button> <button kwhiset="' + hlset + '" title="Keep saved keywords" style="font-size:0.8em">Cancel</button> <button kwhiset="' +
  608. hlset + '" id="thsrevert' + hlset + '" title="Revert last edit" style="font-size:0.8em" disabled>Revert</button></p>';
  609. var rng = document.createRange();
  610. rng.selectNodeContents(e.target.children[0]);
  611. var sel = window.getSelection();
  612. sel.removeAllRanges();
  613. sel.addRange(rng);
  614. if (hlobj[hlset].prevkeyw && hlobj[hlset].prevkeyw != '') {
  615. document.getElementById('thsrevert' + hlset).removeAttribute('disabled');
  616. document.getElementById('thsrevert' + hlset).setAttribute('title','Revert to "' + hlobj[hlset].prevkeyw + '"');
  617. }
  618. }
  619. }
  620. }
  621. async function kwhienabledisable(hlsetnum,enable){
  622. if (enable == false) {
  623. // Update object and persist to GM storage
  624. hlobj[hlsetnum].enabled = "false";
  625. hljson = JSON.stringify(hlobj);
  626. if (!GM4){
  627. GM_setValue("kwstyles", hljson);
  628. } else {
  629. await GM.setValue("kwstyles", hljson);
  630. }
  631. // Unhighlight
  632. unhighlight(hlsetnum);
  633. // Clear seek info from bar if this set is there
  634. var seekset = document.getElementById("thdtopfindbuttons").getAttribute("thdseek");
  635. if (seekset){
  636. if(seekset.indexOf("|") > -1) seekset = seekset.split("|")[0];
  637. if (hlsetnum == seekset){
  638. document.getElementById("thdtopfindbuttons").setAttribute("thdseek","");
  639. document.getElementById("thdseekdesc").textContent = "Seek";
  640. document.getElementById("thdtopkeywords").innerHTML = "Click to manage keyword/highlight sets &bull; <em>Add New Set</em>";
  641. }
  642. }
  643. } else {
  644. // Update object and persist to GM storage
  645. hlobj[hlsetnum].enabled = "true";
  646. hljson = JSON.stringify(hlobj);
  647. if (!GM4){
  648. GM_setValue("kwstyles", hljson);
  649. } else {
  650. await GM.setValue("kwstyles", hljson);
  651. }
  652. // Highlight
  653. THmo_doHighlight(document.body,[hlsetnum]);
  654. }
  655. }
  656. function kwhinewset(e,kwtext){ // call up new set form
  657. // set set number attribute
  658. document.querySelector('#kwhiedit tr').setAttribute('kwhiset', 'new');
  659. // clear class for keywords
  660. document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className = "";
  661. // enter placeholder text & default type
  662. if (kwtext) document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent = kwtext;
  663. else document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent = "larry|moe|curly";
  664. document.getElementById("kwhipattype").selectedIndex = 0;
  665. // set style editing to defaults
  666. kwhieditstyle = ["rgb(0,0,255)","rgb(255,255,0)","inherit",""];
  667. kwhiShowEditForm();
  668. }
  669. function kwhiShowEditForm(){
  670. var rule = "#stylecontrols>p>span{";
  671. if (kwhieditstyle[0].length > 0) rule += "color:"+kwhieditstyle[0]+";";
  672. if (kwhieditstyle[1].length > 0) rule += "background-color:"+kwhieditstyle[1]+";";
  673. if (kwhieditstyle[2].length > 0) rule += "font-weight:"+kwhieditstyle[2]+";";
  674. if (kwhieditstyle[3].length > 0) rule += kwhieditstyle[3]+";";
  675. document.getElementById("kwhiedittemp").innerHTML = rule + "}";
  676. populateRGB("txt",kwhieditstyle[0]);
  677. populateRGB("bkg",kwhieditstyle[1]);
  678. document.getElementById("fwsel").value = kwhieditstyle[2];
  679. document.getElementById("kwhicustom").value = kwhieditstyle[3];
  680. updateColorInputs();
  681. // default the reversion button to disabled
  682. var rbtn = document.getElementById("btnkwhirevert");
  683. rbtn.setAttribute('disabled','disabled');
  684. if (rbtn.hasAttribute('kwhiset')) rbtn.removeAttribute('kwhiset');
  685. rbtn.setAttribute('title','');
  686. // show form
  687. document.getElementById("kwhiedit").style.display = "block";
  688. // check for possible reversion option
  689. var hlset = document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className;
  690. if (hlset != "" && hlobj[hlset].prevkeyw && hlobj[hlset].prevkeyw != '') {
  691. rbtn.removeAttribute('disabled');
  692. rbtn.setAttribute('kwhiset',hlset);
  693. rbtn.setAttribute('title','Revert to "' + hlobj[hlset].prevkeyw + '"');
  694. }
  695. }
  696. function kwhiexport(e){
  697. prompt("JSON data\nPress Ctrl+c or right-click to copy\n ", JSON.stringify(hlobj));
  698. }
  699. async function kwhiimport(e){
  700. var txtImport = prompt("Paste in the exported data and click OK to start parsing", "");
  701. try{
  702. var objImport = JSON.parse(txtImport);
  703. } catch(err){
  704. 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!");
  705. return;
  706. }
  707. var keysImport = Object.keys(objImport);
  708. // Compare for duplicate set numbers
  709. var keysString = "|" + hlkeys.join("|") + "|";
  710. var counter = 0;
  711. for (var j = 0; j < keysImport.length; ++j){
  712. if(keysString.indexOf("|"+keysImport[j]+"|") > -1) counter++;
  713. }
  714. if (counter > 0){
  715. 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");
  716. if (!arc) return;
  717. if (arc.length == 0) return;
  718. if (arc.toLowerCase() == "c") return;
  719. if (arc.toLowerCase() == "t"){
  720. if(!confirm("Total replacement has no error checking. Click OK to confirm total replacement, or click Cancel to only Replace matching sets.")) arc = "R";
  721. }
  722. } else {
  723. var arc = "A";
  724. }
  725. if (arc.toLowerCase() == "t"){ // Total replacement
  726. hlobj = JSON.parse(txtImport);
  727. // Update the global key array
  728. hlkeys = Object.keys(hlobj);
  729. // Persist the object
  730. hljson = JSON.stringify(hlobj);
  731. if (!GM4){
  732. GM_setValue("kwstyles", hljson);
  733. } else {
  734. await GM.setValue("kwstyles", hljson);
  735. }
  736. // Apply to page (see below)
  737. } else {
  738. for (var j = 0; j < keysImport.length; ++j){ // Add/replace individual sets
  739. var impset = keysImport[j];
  740. if(keysString.indexOf("|"+impset+"|") > -1 && arc.toLowerCase() == "r"){ // replace
  741. var hlset = impset;
  742. hlobj[hlset].keywords = objImport[impset].keywords || "keywords|not|found";
  743. hlobj[hlset].type = objImport[impset].type || "string";
  744. hlobj[hlset].hlpat = objImport[impset].hlpat || "";
  745. hlobj[hlset].textcolor = objImport[impset].textcolor || "rgb(0,0,255)";
  746. hlobj[hlset].backcolor = objImport[impset].backcolor || "rgb(255,255,0)";
  747. hlobj[hlset].fontweight = objImport[impset].fontweight || "inherit";
  748. hlobj[hlset].custom = objImport[impset].custom || "";
  749. hlobj[hlset].enabled = objImport[impset].enabled || "true";
  750. hlobj[hlset].visible = objImport[impset].visible || "true";
  751. hlobj[hlset].updated = (new Date()).toJSON();
  752. } else { // add
  753. if(keysString.indexOf("|"+impset+"|") > -1 && arc.toLowerCase() == "a"){
  754. // create a new set number instead
  755. var hlset = "set" + hlnextset;
  756. hlnextset += 1;
  757. if (!GM4){
  758. GM_setValue("hlnextset",hlnextset);
  759. } else {
  760. await GM.setValue("hlnextset",hlnextset);
  761. }
  762. } else {
  763. var hlset = impset;
  764. }
  765. // add the set
  766. hlobj[hlset] = {
  767. keywords : objImport[impset].keywords || "keywords|not|found",
  768. type: objImport[impset].type || "string",
  769. hlpat : objImport[impset].hlpat || "",
  770. textcolor : objImport[impset].textcolor || "rgb(0,0,255)",
  771. backcolor : objImport[impset].backcolor || "rgb(255,255,0)",
  772. fontweight : objImport[impset].fontweight || "inherit",
  773. custom : objImport[impset].custom || "",
  774. enabled : objImport[impset].enabled || "true",
  775. visible : objImport[impset].visible || "true",
  776. updated : objImport[impset].updated || ""
  777. }
  778. }
  779. // Update the global key array
  780. hlkeys = Object.keys(hlobj);
  781. // Persist the object
  782. hljson = JSON.stringify(hlobj);
  783. if (!GM4){
  784. GM_setValue("kwstyles", hljson);
  785. } else {
  786. await GM.setValue("kwstyles", hljson);
  787. }
  788. }
  789. }
  790. // TODO: Could an error prevent reaching this point, for example, if the import object is missing properties due to bad editing?
  791. // Update CSS rule and command bar list
  792. insertCSS(hlkeys);
  793. refreshSetList();
  794. // Unhighlight all, re-highlight all, close dialog
  795. unhighlight(null);
  796. THmo_doHighlight(document.body);
  797. }
  798. async function kwhihbtn(e){
  799. if (e.target.checked == false){
  800. hlbtnvis = "off";
  801. if (!GM4){
  802. GM_setValue("hlbtnvis",hlbtnvis);
  803. } else {
  804. await GM.setValue("hlbtnvis",hlbtnvis);
  805. }
  806. document.getElementById("btnshowkwhi").style.display = "none";
  807. } else {
  808. hlbtnvis = "on";
  809. if (!GM4){
  810. GM_setValue("hlbtnvis",hlbtnvis);
  811. } else {
  812. await GM.setValue("hlbtnvis",hlbtnvis);
  813. }
  814. document.getElementById("btnshowkwhi").style.display = "";
  815. }
  816. }
  817. async function kwhiprecode(e){
  818. if (e.target.checked == false){
  819. // Update var, persist the preference, unhighlight, rehighlight
  820. hlprecode = false;
  821. if (!GM4){
  822. GM_setValue("hlprecode",hlprecode);
  823. } else {
  824. await GM.setValue("hlprecode",hlprecode);
  825. }
  826. unhighlight(null);
  827. THmo_doHighlight(document.body);
  828. } else {
  829. // Update var, persist the preference, rehighlight
  830. hlprecode = true;
  831. if (!GM4){
  832. GM_setValue("hlprecode",hlprecode);
  833. } else {
  834. await GM.setValue("hlprecode",hlprecode);
  835. }
  836. THmo_doHighlight(document.body);
  837. }
  838. }
  839. function kwhicancelipe(setno){
  840. // clean up in-place editor(s)
  841. if (setno && setno != ''){
  842. var kwdiv = document.querySelector('#kwhitbod .'+setno);
  843. if (kwdiv){
  844. kwdiv.innerHTML = hlobj[setno].keywords;
  845. return;
  846. }
  847. } else { // Check 'em all
  848. var divs = document.querySelector('#kwhitbod div');
  849. for (var n=0; n<divs.length; n++){
  850. if (divs[n].children.length > 0 && divs[n].className != '') kwhicancelipe(divs[n].className);
  851. }
  852. }
  853. }
  854. function kwhitopdropclose(e){
  855. kwhicancelipe('');
  856. document.getElementById('thdtopdrop').style.display='none';
  857. }
  858. function thsreread(e){
  859. //TODO
  860. }
  861. async function thsframeselect(e){
  862. var selopt = e.target.options[e.target.selectedIndex].value;
  863. if (hlframe != selopt) {
  864. hlframe = selopt;
  865. if (!GM4){
  866. GM_setValue("hlframe",hlframe);
  867. } else {
  868. await GM.setValue("hlframe",hlframe);
  869. }
  870. setthsframeopts();
  871. }
  872. }
  873. function setthsframeopts(){
  874. var sel = document.getElementById("hlframeselect");
  875. if (hlframe == "none"){
  876. sel.options[0].selected = true;
  877. sel.options[0].setAttribute("selected","selected");
  878. } else {
  879. sel.options[0].selected = false;
  880. if (sel.options[0].hasAttribute("selected")) sel.options[0].removeAttribute("selected");
  881. }
  882. if (hlframe == "same"){
  883. sel.options[1].selected = true;
  884. sel.options[1].setAttribute("selected","selected");
  885. } else {
  886. sel.options[1].selected = false;
  887. if (sel.options[1].hasAttribute("selected")) sel.options[1].removeAttribute("selected");
  888. }
  889. if (hlframe == "any"){
  890. sel.options[2].selected = true;
  891. sel.options[2].setAttribute("selected","selected");
  892. } else {
  893. sel.options[2].selected = false;
  894. if (sel.options[2].hasAttribute("selected")) sel.options[2].removeAttribute("selected");
  895. }
  896. }
  897. function thdseek(e){
  898. if (e.target.nodeName == "DIV") return; // ignore background clicks
  899. var seekset = e.currentTarget.getAttribute("thdseek");
  900. if (!seekset){ // user needs to select a set to seek in
  901. thdDropSetList();
  902. } else {
  903. var seekparams = seekset.split("|");
  904. var seekmatches = document.querySelectorAll('thdfrag[txhidy15="'+seekparams[0]+'"]');
  905. // Update or add total size of set; FIGURE OUT LATER: what if this changed??
  906. seekparams[1] = seekmatches.length;
  907. if (seekmatches.length > 0){
  908. if (e.target.nodeName == "SPAN"){ // re-scroll to the current reference
  909. thdshow(seekmatches[parseInt(seekparams[2])]);
  910. } else { // BUTTON
  911. var seekaction = e.target.getAttribute("thdaction");
  912. if (!seekaction) seekaction = "f";
  913. if (seekparams.length == 3){ // User has seeked in this set
  914. switch (seekaction){
  915. case "f":
  916. seekparams[2] = 0;
  917. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  918. if (rtn == false) seekagain("n");
  919. break;
  920. case "p":
  921. if (parseInt(seekparams[2]) > 0) {
  922. seekparams[2] = parseInt(seekparams[2]) - 1;
  923. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  924. if (rtn == false){
  925. if (parseInt(seekparams[2]) > 0) seekagain("p");
  926. else seekfailnotc("No previous match visible");
  927. }
  928. } else {
  929. seekfailnotc("Already reached first match");
  930. }
  931. break;
  932. case "n":
  933. if (parseInt(seekparams[2]) < (seekmatches.length-1)) {
  934. seekparams[2] = parseInt(seekparams[2]) + 1;
  935. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  936. if (rtn == false){
  937. if (parseInt(seekparams[2]) < (seekmatches.length-1)) seekagain("n");
  938. else seekfailnotc("No later match visible");
  939. }
  940. } else {
  941. seekparams[2] = (seekmatches.length-1); // in case it's too high, fix that here
  942. seekfailnotc("Already reached last match");
  943. }
  944. break;
  945. case "l":
  946. seekparams[2] = (seekmatches.length-1);
  947. var rtn = thdshow(seekmatches[parseInt(seekparams[2])]);
  948. if (rtn == false) seekagain("p");
  949. break;
  950. }
  951. } else {
  952. seekparams[2] = 0;
  953. thdshow(seekmatches[parseInt(seekparams[2])]);
  954. }
  955. document.getElementById("thdtopfindbuttons").setAttribute("thdseek", seekparams.join("|"));
  956. document.getElementById("thdseekdesc").textContent = (parseInt(seekparams[2])+1) + " of " + seekparams[1];
  957. }
  958. } else {
  959. document.getElementById("thdseekdesc").textContent = "0 of 0";
  960. }
  961. }
  962. }
  963. function thdshow(elt){ // this could be much prettier with animation! TODO: outline/box?
  964. elt.scrollIntoView();
  965. var rect = elt.getClientRects()[0];
  966. if (rect){ // scroll down one inch to avoid many fixed headers
  967. if (rect.top < 96) window.scroll(0, window.scrollY-96);
  968. return true;
  969. } else { // match is not visible
  970. return false;
  971. }
  972. }
  973. function seekagain(dir){
  974. switch (dir){
  975. case "p":
  976. seekfailnotc("Hidden, trying previous match...");
  977. window.setTimeout(function(){document.querySelector('button[thdaction="p"]').click();},250);
  978. break;
  979. case "n":
  980. seekfailnotc("Hidden, trying next match...");
  981. window.setTimeout(function(){document.querySelector('button[thdaction="n"]').click();},250);
  982. break;
  983. }
  984. }
  985. var evttimer;
  986. function seekfailnotc(txt){
  987. var sfdiv = document.getElementById("thdseekfail");
  988. sfdiv.textContent = txt;
  989. sfdiv.style.display = "block";
  990. if (evttimer) window.clearTimeout(evttimer);
  991. evttimer = window.setTimeout(function(){document.getElementById("thdseekfail").style.display="none";}, 800);
  992. }
  993. function unhighlight(setnum){
  994. if (setnum) var tgts = document.querySelectorAll('thdfrag[txhidy15="' + setnum + '"]');
  995. else var tgts = document.querySelectorAll('thdfrag[txhidy15]'); // remove ALL
  996. for (var i=0; i<tgts.length; i++){
  997. // Check for co-extant parent(s) to remove potentially stranded <span>s
  998. var parnode = tgts[i].parentNode, parpar = parnode.parentNode, tgtspan;
  999. if (parnode.hasAttribute("thdcontain") && parnode.innerHTML == tgts[i].outerHTML){
  1000. parnode.outerHTML = tgts[i].textContent.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  1001. tgtspan = parpar;
  1002. } else {
  1003. tgts[i].outerHTML = tgts[i].textContent.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  1004. tgtspan = parnode;
  1005. }
  1006. tgtspan.normalize();
  1007. if (tgtspan.hasAttribute("thdcontain")){
  1008. parnode = tgtspan.parentNode;
  1009. if (parnode){
  1010. if (parnode.hasAttribute("thdcontain") && parnode.innerHTML == tgtspan.outerHTML && tgtspan.querySelectorAll('thdfrag[txhidy15]').length == 0){
  1011. parnode.outerHTML = tgtspan.innerHTML;
  1012. } else if (parnode.innerHTML == tgtspan.outerHTML && tgtspan.querySelectorAll('thdfrag[txhidy15]').length == 0) {
  1013. parnode.innerHTML = tgtspan.innerHTML;
  1014. }
  1015. }
  1016. }
  1017. }
  1018. }
  1019.  
  1020. async function kwhisavechg(e){
  1021. // Update object, regenerate CSS if applicable, apply to document
  1022. var hlset = document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className;
  1023. var kwtext = document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent;
  1024. if (hlset == ""){
  1025. // create a new set number
  1026. var hlset = "set" + hlnextset;
  1027. hlnextset += 1;
  1028. if (!GM4){
  1029. GM_setValue("hlnextset",hlnextset);
  1030. } else {
  1031. await GM.setValue("hlnextset",hlnextset);
  1032. }
  1033. // add the set
  1034. if (document.getElementById("kwhipattype").value == "regex"){
  1035. kwtext = kwtext.replace(/\\/g, "\\");
  1036. var hlpattxt = ""; //TODOLATER
  1037. } else {
  1038. var hlpattxt = "";
  1039. }
  1040. hlobj[hlset] = {
  1041. keywords : kwtext,
  1042. type : document.getElementById("kwhipattype").value,
  1043. hlpat : hlpattxt,
  1044. textcolor : kwhieditstyle[0],
  1045. backcolor : kwhieditstyle[1],
  1046. fontweight : kwhieditstyle[2],
  1047. custom : kwhieditstyle[3],
  1048. enabled : "true",
  1049. visible : "true",
  1050. updated : ""
  1051. }
  1052. // Update the global key array
  1053. hlkeys = Object.keys(hlobj);
  1054. } else {
  1055. var oldtype = hlobj[hlset].type;
  1056. hlobj[hlset].type = document.getElementById("kwhipattype").value;
  1057. // Save keyword changes after user confirmation
  1058. if (kwtext != hlobj[hlset].keywords){
  1059. if (confirm("Save updated keywords (and other changes)?")){
  1060. hlobj[hlset].prevkeyw = hlobj[hlset].keywords;
  1061. hlobj[hlset].prevtype = oldtype;
  1062. if (hlobj[hlset].type != "regex"){
  1063. hlobj[hlset].keywords = kwtext;
  1064. } else {
  1065. hlobj[hlset].keywords = kwtext.replace(/\\/g, "\\");
  1066. hlobj[hlset].hlpat = ""; //TODOLATER
  1067. }
  1068. } else return;
  1069. }
  1070. // Save style changes without confirmation
  1071. hlobj[hlset].textcolor = kwhieditstyle[0];
  1072. hlobj[hlset].backcolor = kwhieditstyle[1];
  1073. hlobj[hlset].fontweight = kwhieditstyle[2];
  1074. hlobj[hlset].custom = kwhieditstyle[3];
  1075. // Set updated date/time
  1076. hlobj[hlset].updated = (new Date()).toJSON();
  1077. }
  1078. // Persist the object
  1079. hljson = JSON.stringify(hlobj);
  1080. if (!GM4){
  1081. GM_setValue("kwstyles", hljson);
  1082. } else {
  1083. await GM.setValue("kwstyles", hljson);
  1084. }
  1085. // Update CSS rule and parent form
  1086. insertCSS([hlset]);
  1087. refreshSetList();
  1088. // Unhighlight, re-highlight, close dialog
  1089. unhighlight(hlset);
  1090. THmo_doHighlight(document.body,[hlset])
  1091. document.getElementById('kwhiedit').style.display='none';
  1092. }
  1093. function kwhicancel(e){
  1094. // Close dialog (fields will be refresh if it is opened again)
  1095. document.getElementById('kwhiedit').style.display='none';
  1096. }
  1097. async function kwhiremove(e){
  1098. var hlset = document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').className;
  1099. if (hlset == ""){
  1100. alert("This set has not been saved and therefore does not need to be hidden, you can just close the dialog to discard it.");
  1101. } else {
  1102. if (confirm("Are you sure you want to hide this set instead of editing it to your own liking?")){
  1103. hlobj[hlset].visible = "false";
  1104. hlobj[hlset].updated = (new Date()).toJSON();
  1105. // Persist the object
  1106. hljson = JSON.stringify(hlobj);
  1107. if (!GM4){
  1108. GM_setValue("kwstyles", hljson);
  1109. } else {
  1110. await GM.setValue("kwstyles", hljson);
  1111. }
  1112. // Update set list, remove highlighting, close form
  1113. refreshSetList();
  1114. unhighlight(hlset);
  1115. document.getElementById('kwhiedit').style.display='none';
  1116. }
  1117. }
  1118. }
  1119. async function kwhirevert(e){
  1120. // get set number attribute
  1121. var hlset = e.target.getAttribute("kwhiset");
  1122. // gray the button
  1123. e.target.setAttribute('disabled', 'disabled');
  1124. // get the previous keywords (if any)
  1125. if (hlobj[hlset].prevkeyw && hlobj[hlset].prevkeyw != '') var kwtext = hlobj[hlset].prevkeyw;
  1126. if (!kwtext || kwtext == ''){ // uh-oh
  1127. alert('Unable to undo, sorry!');
  1128. return;
  1129. }
  1130. // Save keyword changes WITHOUT user confirmation
  1131. hlobj[hlset].keywords = kwtext;
  1132. hlobj[hlset].type = hlobj[hlset].prevtype;
  1133. hlobj[hlset].prevkeyw = '';
  1134. hlobj[hlset].prevtype = '';
  1135. // Set updated date/time
  1136. hlobj[hlset].updated = (new Date()).toJSON();
  1137. // Persist the object
  1138. hljson = JSON.stringify(hlobj);
  1139. if (!GM4){
  1140. GM_setValue("kwstyles", hljson);
  1141. } else {
  1142. await GM.setValue("kwstyles", hljson);
  1143. }
  1144. // Update CSS rule and parent form
  1145. insertCSS([hlset]);
  1146. refreshSetList();
  1147. // Unhighlight, re-highlight
  1148. unhighlight(hlset);
  1149. THmo_doHighlight(document.body,[hlset]);
  1150. // Refresh the keywords and type
  1151. document.querySelector('#kwhiedit td:nth-of-type(1) p:nth-of-type(1)').textContent = hlobj[hlset].keywords;
  1152. document.getElementById("kwhipattype").selectedIndex = 0;
  1153. if (hlobj[hlset].type == "word") document.getElementById("kwhipattype").selectedIndex = 1;
  1154. if (hlobj[hlset].type == "regex") document.getElementById("kwhipattype").selectedIndex = 2;
  1155. }
  1156. function kwhicolorreset(e){
  1157. // what set is this?
  1158. var set = document.querySelector('#kwhiedit tr').getAttribute('kwhiset');
  1159. // check which button, reset the RGB
  1160. if (e.target.id == "btntxtreset"){
  1161. if (set == "new"){
  1162. kwhieditstyle[0] = "rgb(0,0,255)";
  1163. } else {
  1164. kwhieditstyle[0] = hlobj[set].textcolor;
  1165. }
  1166. populateRGB("txt",kwhieditstyle[0]);
  1167. setdivstyle(["txt"]);
  1168. }
  1169. if (e.target.id == "btnbkgreset"){
  1170. if (set == "new"){
  1171. kwhieditstyle[1] = "rgb(255,255,0)";
  1172. } else {
  1173. kwhieditstyle[1] = hlobj[set].backcolor;
  1174. }
  1175. populateRGB("bkg",kwhieditstyle[1]);
  1176. setdivstyle(["bkg"]);
  1177. }
  1178. e.target.blur();
  1179. }
  1180. function populateRGB(prop,stylestring){
  1181. var rgbvals = stylestring.substr(stylestring.indexOf("(")+1);
  1182. rgbvals = rgbvals.substr(0,rgbvals.length-1).split(",");
  1183. document.getElementById(prop+"r").value = parseInt(rgbvals[0]);
  1184. document.getElementById(prop+"g").value = parseInt(rgbvals[1]);
  1185. document.getElementById(prop+"b").value = parseInt(rgbvals[2]);
  1186. }
  1187. async function updatestyle(e){
  1188. // validate value and apply change
  1189. var tgt;
  1190. if (e.id != undefined) tgt = e;
  1191. else tgt = e.target;
  1192. if (tgt.id.indexOf("colorinput") > -1){
  1193. // let's wait for the change event to fire before updating
  1194. } else if (tgt.id.indexOf("txt") == 0 || tgt.id.indexOf("bkg") == 0){
  1195. if (isNaN(tgt.value)){
  1196. alert("Please only use values between 0 and 255");
  1197. return;
  1198. }
  1199. if (parseInt(tgt.value) != tgt.value){
  1200. tgt.value = parseInt(tgt.value);
  1201. }
  1202. if (tgt.value < 0){
  1203. tgt.value = 0;
  1204. }
  1205. if (tgt.value > 255){
  1206. tgt.value = 255;
  1207. }
  1208. if (tgt.id.indexOf("txt") == 0) setdivstyle(["txt"]);
  1209. if (tgt.id.indexOf("bkg") == 0) setdivstyle(["bkg"]);
  1210. } else {
  1211. if (tgt.id == "kwhicustom") return;
  1212. console.log("updatestyle on "+tgt.id);
  1213. }
  1214. }
  1215. function setdivstyle(props){
  1216. for (var i=0; i<props.length; i++){
  1217. switch (props[i]){
  1218. case "txt":
  1219. kwhieditstyle[0] = "rgb(" + document.getElementById("txtr").value + "," +
  1220. document.getElementById("txtg").value + "," + document.getElementById("txtb").value + ")";
  1221. break;
  1222. case "bkg":
  1223. kwhieditstyle[1] = "rgb(" + document.getElementById("bkgr").value + "," +
  1224. document.getElementById("bkgg").value + "," + document.getElementById("bkgb").value + ")";
  1225. break;
  1226. default:
  1227. console.log("default?");
  1228. }
  1229. }
  1230. var rule = "#stylecontrols>p>span{";
  1231. if (kwhieditstyle[0].length > 0) rule += "color:"+kwhieditstyle[0]+";";
  1232. if (kwhieditstyle[1].length > 0) rule += "background-color:"+kwhieditstyle[1]+";";
  1233. if (kwhieditstyle[2].length > 0) rule += "font-weight:"+kwhieditstyle[2]+";";
  1234. if (kwhieditstyle[3].length > 0) rule += kwhieditstyle[3]+";";
  1235. document.getElementById("kwhiedittemp").innerHTML = rule + "}";
  1236. updateColorInputs();
  1237. }
  1238. async function updateColorInputs(){
  1239. document.getElementById('txtcolorinput').value = '#' + ('0' + parseInt(document.getElementById("txtr").value).toString(16)).slice(-2) +
  1240. ('0' + parseInt(document.getElementById("txtg").value).toString(16)).slice(-2) +
  1241. ('0' + parseInt(document.getElementById("txtb").value).toString(16)).slice(-2);
  1242. document.getElementById('bkgcolorinput').value = '#' + ('0' + parseInt(document.getElementById("bkgr").value).toString(16)).slice(-2) +
  1243. ('0' + parseInt(document.getElementById("bkgg").value).toString(16)).slice(-2) +
  1244. ('0' + parseInt(document.getElementById("bkgb").value).toString(16)).slice(-2);
  1245. }
  1246. async function updatecolor(e){
  1247. // duplicate colors to RBG input boxes
  1248. if (e.target.id.indexOf("colorinput") > -1){
  1249. var hexcolor = e.target.value;
  1250. var prefix = e.target.id.slice(0,3);
  1251. document.getElementById(prefix + 'r').value = parseInt(hexcolor.slice(1,3), 16);
  1252. document.getElementById(prefix + 'g').value = parseInt(hexcolor.slice(3,5), 16);
  1253. document.getElementById(prefix + 'b').value = parseInt(hexcolor.slice(5,7), 16);
  1254. updatestyle(document.getElementById(prefix + 'r'));
  1255. }
  1256. }
  1257. function kwhifwchg(e){
  1258. kwhieditstyle[2] = e.target.value;
  1259. setdivstyle([]);
  1260. }
  1261. function kwhicustom(e){
  1262. kwhieditstyle[3] = document.getElementById("kwhicustom").value;
  1263. setdivstyle([]);
  1264. }
  1265. async function kwhimaxrestore(e){
  1266. var el = document.getElementById('kwhiedit');
  1267. if (e.target.textContent == '^'){
  1268. e.target.textContent = '_';
  1269. e.target.setAttribute('title', 'Restore normal dialog size');
  1270. el.style.left = '1px';
  1271. el.style.width = 'calc(100% - 3px - 2em)';
  1272. el.style.height = 'calc(100% - 4px - 2em)';
  1273. } else {
  1274. e.target.textContent = '^';
  1275. e.target.setAttribute('title', 'Maximize dialog size');
  1276. el.style.left = '';
  1277. el.style.width = '';
  1278. el.style.height = '';
  1279. }
  1280. }
  1281. function cmenuFilter(e){
  1282. document.getElementById("THDenableset").setAttribute("disabled","disabled");
  1283. document.getElementById("THDenableset").setAttribute("THDtext","");
  1284. document.getElementById("THDdisableset").setAttribute("disabled","disabled");
  1285. document.getElementById("THDdisableset").setAttribute("THDset","");
  1286. var s = window.getSelection();
  1287. if (s.isCollapsed) document.getElementById("THDnewset").setAttribute("THDtext","");
  1288. else document.getElementById("THDnewset").setAttribute("THDtext",s.getRangeAt(0).toString().trim());
  1289. if (e.target.hasAttribute('txhidy15')){
  1290. document.getElementById("THDdisableset").removeAttribute("disabled");
  1291. document.getElementById("THDdisableset").setAttribute("THDset",e.target.getAttribute('txhidy15'));
  1292. } else {
  1293. document.getElementById("THDdisableset").setAttribute("disabled","disabled");
  1294. if (!s.isCollapsed){
  1295. document.getElementById("THDenableset").removeAttribute("disabled");
  1296. document.getElementById("THDenableset").setAttribute("THDtext",s.getRangeAt(0).toString().trim());
  1297. }
  1298. }
  1299. }
  1300. function cmenuEnable(e){
  1301. var kw = e.target.getAttribute("THDtext").toLowerCase();
  1302. var toggled = false;
  1303. for (var j = 0; j < hlkeys.length; ++j){
  1304. var hlset = hlkeys[j];
  1305. var kwlist = "|" + hlobj[hlset].keywords.toLowerCase() + "|";
  1306. if(kwlist.indexOf("|" + kw + "|") > -1){
  1307. if (hlobj[hlset].enabled == "true") break; // already enabled
  1308. kwhienabledisable(hlset,true);
  1309. refreshSetList();
  1310. toggled = true;
  1311. break;
  1312. }
  1313. }
  1314. if (toggled == false){
  1315. if (document.getElementById("thdtopbar").style.display != "block") editKW();
  1316. if (document.getElementById("thdtopdrop").style.display != "block") thdDropSetList();
  1317. }
  1318. }
  1319. function cmenuDisable(e){
  1320. kwhienabledisable(e.target.getAttribute("THDset"),false);
  1321. refreshSetList();
  1322. }
  1323. function cmenuNewset(e){
  1324. //TODO - if there's a selection, get it into the form
  1325. kwhinewset(e,e.target.getAttribute("THDtext"));
  1326. }
  1327.  
  1328. // TESTING ONLY
  1329. async function flushData(){
  1330. if (!GM4){
  1331. GM_setValue("kwstyles", "");
  1332. } else {
  1333. await GM.setValue("kwstyles", "");
  1334. }
  1335. }