WK Overlay

Overlays component information on reviews when show info is pressed.

  1. // ==UserScript==
  2. // @name WK Overlay
  3. // @namespace wkoverlay
  4. // @version 0.3.4
  5. // @description Overlays component information on reviews when show info is pressed.
  6. // @author Ethan
  7. // @match https://www.wanikani.com/review/session*
  8. // @grant none
  9. // ==/UserScript==
  10.  
  11. // TODO if kanji or radical follows vocab, overlay is not removed
  12. var addStyleTag = function(){
  13. /* Non-Javascript determined (to be put in style tag)*/
  14. var styleText =
  15. "@media (max-width: 767px) .wkOverlay {\r\n" +
  16. "font-size: 3.0625em;\r\n" +
  17. "font-weight: normal;\r\n" +
  18. "line-height: 2.4em;\r\n" +
  19. "}\r\n" +
  20. ".wkOverlay {\r\n" +
  21. "display: block;\r\n" +
  22. "position: absolute;\r\n" +
  23. "}\r\n" +
  24. ".infoSpan {\r\n" +
  25. "position: absolute;\r\n" +
  26. "background-color: black;\r\n" +
  27. "color: #fff;\r\n" +
  28. "text-align: center;\r\n" +
  29. "padding: 5px 10px;\r\n" +
  30. "border-radius: 6px;\r\n" +
  31. "display: inline-flex;\r\n" +
  32. "font-size: 10pt;\r\n" +
  33. "margin-right:0 2%;\r\n" +
  34. "}\r\n" +
  35. ".infoRadSpan {\r\n" +
  36. "position: absolute;\r\n" +
  37. "background-color: black;\r\n" +
  38. "color: #fff;\r\n" +
  39. "text-align: center;\r\n" +
  40. "padding: 5px 10px;\r\n" +
  41. "border-radius: 6px;\r\n" +
  42. "display: inline-flex;\r\n" +
  43. "font-size: 10pt;\r\n" +
  44. "}\r\n" +
  45. ".infoTop::after{\r\n" +
  46. "content: '';\r\n" +
  47. "position: absolute;\r\n" +
  48. "top: 100%;\r\n" +
  49. "left:20px;\r\n" +
  50. "margin-left: -10px;\r\n" +
  51. "border-width: 10px;\r\n" +
  52. "border-style: solid;\r\n" +
  53. "border-color: black transparent transparent transparent\r\n" +
  54. "}\r\n" +
  55. ".infoTop{\r\n" +
  56. "bottom: 100%;\r\n" +
  57. "}\r\n" +
  58. ".infoBottom{\r\n" +
  59. "top: 100%;\r\n" +
  60. "}\r\n" +
  61. ".infoBottom::after{\r\n" +
  62. "content: '';\r\n" +
  63. "position: absolute;\r\n" +
  64. "bottom: 100%;\r\n" +
  65. "left:20px;\r\n" +
  66. "margin-left: -10px;\r\n" +
  67. "border-width: 10px;\r\n" +
  68. "border-style: solid;\r\n" +
  69. "border-color: transparent transparent black transparent\r\n" +
  70. "} \r\n"+
  71. "span.wkOverlayRadBox\r\n{" +
  72. "background-color: #0af;" +
  73. "display: inline-block;" +
  74. "margin-right: 0.3em;" +
  75. "width: 1.8em;" +
  76. "height: 1.8em;" +
  77. "color: #fff;" +
  78. "line-height: 1.7em;" +
  79. "text-align: center;" +
  80. "text-shadow: 0 1px 0 rgba(0,0,0,0.3);" +
  81. "-webkit-box-sizing: border-box;" +
  82. "-moz-box-sizing: border-box;" +
  83. "box-sizing: border-box;" +
  84. "-webkit-border-radius: 3px;" +
  85. "-moz-border-radius: 3px;" +
  86. "border-radius: 3px;" +
  87. "-webkit-box-shadow: 0 -3px 0 rgba(0,0,0,0.2) inset, 0 0 10px rgba(255,255,255,0.5);" +
  88. "-moz-box-shadow: 0 -3px 0 rgba(0,0,0,0.2) inset,0 0 10px rgba(255,255,255,0.5);" +
  89. "box-shadow: 0 -3px 0 rgba(0,0,0,0.2) inset, 0 0 10px rgba(255,255,255,0.5);" +
  90. "}\r\n" +
  91. "";
  92. var styleElem = document.createElement('style');
  93. styleElem.appendChild(document.createTextNode(styleText));
  94. document.head.appendChild(styleElem);
  95. };
  96.  
  97. (function() {
  98. 'use strict';
  99.  
  100. // Salt this event so future scripts don't throw multiple events and confuse the script.
  101. // This should ensure these events are unique to this script and minimise the chances of catching events in error.
  102. // TODO: handle possibility of multiple events being thrown by other scripts based on context (eg. multiple 'show' events without a 'hide' => 1 'show') for greater integration between scripts.
  103. var hideEvent = "hide"+Math.trunc(Math.random()*1000000);
  104. var showEvent = "show"+Math.trunc(Math.random()*1000000);
  105. //---------------------------
  106. var oldHide = $.fn.hide;
  107. $.fn.hide = function(){this.trigger(new jQuery.Event(hideEvent)); return oldHide.apply(this, arguments);};
  108. var oldShow = $.fn.show;
  109. $.fn.show = function(){this.trigger(new jQuery.Event(showEvent)); return oldShow.apply(this, arguments);};
  110. //--------------------------
  111.  
  112. addStyleTag();
  113.  
  114. var parentElement = $("#question");
  115. var overlay = document.createElement('div');
  116. overlay.style.display = 'none';
  117. overlay.className = "wkOverlay";
  118. overlay.setAttribute('lang', "ja");
  119.  
  120. var respComps = {};
  121. var masterRads = {};
  122. var prompt = {};
  123. parentElement[0].appendChild(overlay);
  124. var newItem = false;
  125.  
  126. // just for comparing prompts
  127. var shallowCompare = function(obj1, obj2){
  128. return ((obj1.voc && obj2.voc) || (obj1.kan && obj2.kan) || (obj1.rad && obj2.rad)) && ((obj1.voc === obj2.voc) || (obj1.kan === obj2.kan) || (obj1.rad === obj2.rad));
  129. };
  130. $.jStorage.listenKeyChange('currentItem', function(){
  131. while (overlay.firstChild){
  132. overlay.removeChild(overlay.firstChild);
  133. }
  134. // Runs after span is changed, but is this guaranteed?
  135. var oldPrompt = prompt;
  136. prompt = $.jStorage.get('currentItem');
  137. newItem = !shallowCompare(prompt, oldPrompt);
  138.  
  139. var itemString = prompt.voc||prompt.kan; // The kanji, vocab (or soon, radical)
  140. if (itemString){
  141. for (var ch in itemString){ // Kanji and radical, this will only be one (radical images may need some other handling)
  142. var chSpan = document.createElement('span');
  143.  
  144. chSpan.innerText = itemString[ch];
  145.  
  146. chSpan.style.fontSize = document.defaultView.getComputedStyle($("#character")[0], "").fontSize;
  147. }
  148. }
  149. });
  150.  
  151. var showRadicalTags = function(){
  152. console.warn("showtags");
  153. overlay.style.display = 'block';
  154. //Since we are currently adding the tips every time we catch a show event, we must delete them all first, or multiple hide/show events will build up more tips for every 'show'
  155. // Clear array of nodelists
  156. while (overlay.firstChild){
  157. overlay.removeChild(overlay.firstChild);
  158. }
  159. // Get the related kanji component info for vocab from the 'show answer' page
  160. // Create an object (respComps) indexed by Kanji characters. eg {"出":" Exit","提":" Present, Submit"}
  161. $("#related-items .kanji a").each(function(i, comp){
  162.  
  163. //Needs love to be more robust when Wanikani makes cosmetic changes to their page
  164. respComps[comp.childNodes[1].textContent] = comp.childNodes[2].textContent;
  165. });
  166.  
  167. if (prompt.voc){
  168. // Create flip flop variable so tips with multiple words don't clutter the top or bottom
  169. var flipTopBottom = false; //true: top, false: bottom
  170. // Values will be the same for all char, but need to be calculated
  171. // Position absolute needs negative margins to react to number of characters
  172. var marginLeftPercentage = (-100/prompt.voc.length) + "%";
  173. var marginRightPercentage = "2%";
  174. for (var ch in prompt.voc){
  175. flipTopBottom = !flipTopBottom;
  176. var chSpan = document.createElement('span');
  177. chSpan.className = "wkOverlayChar";
  178.  
  179. var comp = document.createElement('span');
  180. comp.innerText = prompt.voc[ch];
  181. comp.style.opacity = 0;
  182. chSpan.appendChild(comp);
  183.  
  184. console.info(respComps, prompt.voc[ch], respComps[prompt.voc[ch]]);
  185. chSpan.style.fontSize = document.defaultView.getComputedStyle($("#character")[0], "").fontSize; // and lineHeight
  186.  
  187. // Javascript determined style values.
  188. overlay.style.height = $("#character span").height() + 'px';
  189. overlay.style.top = $("#character span").position().top + 'px';
  190. overlay.style.left = $("#character span").position().left + 'px';
  191. overlay.style.height = $("#character span").height() + 'px';
  192.  
  193. overlay.appendChild(chSpan);
  194. //debugger;
  195. if (respComps[prompt.voc[ch]]){ // any characters not present in the components section will fail here. There should be no Kanji in the prompt that is not here, so no Kanji should fail.
  196. var spInf = document.createElement('span');
  197. spInf.innerText = respComps[prompt.voc[ch]];
  198.  
  199. chSpan.appendChild(spInf);
  200. spInf.style.marginLeft = marginLeftPercentage;
  201. // spInf.style.marginRight = marginRightPercentage;
  202. if(flipTopBottom){
  203. spInf.className = "infoSpan infoTop";
  204. }
  205. else{
  206. spInf.className = "infoSpan infoBottom";
  207. }
  208. }
  209. }
  210. }
  211. if (prompt.kan){
  212. var respRads = {};
  213. var slug;
  214. $("#related-items .radical a").each(function(i, comp){
  215. //debugger;
  216.  
  217. // Needs improvement for when Wanikani changes its page structure
  218. if (comp.childNodes[1].textContent){
  219. slug = comp.childNodes[1].textContent;
  220. respRads[slug] = {name: comp.childNodes[2].textContent, kanji: {}};
  221. }
  222. else{
  223. slug = comp.childNodes[1].firstChild.className;// i class
  224. respRads[slug] = {box: comp.childNodes[1].firstChild, name: comp.childNodes[2].textContent, kanji: {}};
  225. }
  226.  
  227. //get position from browser storage if there
  228. if ($.jStorage.get("overlayMasterRads")){
  229. masterRads = $.jStorage.get("overlayMasterRads");
  230. }
  231.  
  232. if (!masterRads[slug]){
  233. masterRads[slug] = respRads[slug];
  234. }
  235.  
  236. if (masterRads[slug].kanji[prompt.kan]){
  237. respRads[slug].kanji[prompt.kan] = masterRads[slug].kanji[prompt.kan];
  238. }
  239. else{
  240. respRads[slug].kanji[prompt.kan] = {x: 0, y: 0};
  241. }
  242. });
  243. console.log("masterRads:", masterRads);
  244. var kan = document.createElement('span');
  245. kan.className = "wkOverlayChar";
  246.  
  247. kan.innerText = prompt.kan;
  248. kan.style.opacity = 0.5; //debug kanji
  249. //kan.appendChild(comp);
  250.  
  251. console.info("component object, kanji, compObj[kanji]", respComps, prompt.kan, respComps[prompt.kan]);// will probably only work on kanji that has itself as a radical (eg. 一)
  252. kan.style.fontSize = document.defaultView.getComputedStyle($("#character")[0], "").fontSize; // and lineHeight
  253.  
  254. var overlayLeftOffset = $("#character span").position().left;
  255. var overlayTopOffset = $("#character span").position().top;
  256. // Javascript determined style values.
  257. overlay.style.height = $("#character span").height() + 'px';
  258. overlay.style.top = $("#character span").position().top + 'px';
  259. overlay.style.left = overlayLeftOffset + 'px';
  260. //overlay.style.right = (overlayLeftOffset+$(overlay).width()) + 'px';
  261. //overlay.style.right = (-overlayRightOffset) + 'px';
  262. //alert(overlay.style.right);
  263. overlay.style.height = $("#character span").height() + 'px';
  264.  
  265. //overlay.appendChild(kan);
  266.  
  267. //respComps is radicals and their names as key->value pairs
  268. // we need to give the radicals some more info (position, svg path around relevant part of kanji) than the kanji has
  269. // add this info for each radical: object as scraped: {"疒":" Sick","正":" Correct"} => fn => {"疒":{name:" Sick", "症":{x:num, y:num, svg: svgElem },"正":{name:" Correct", "症":{x:num, y:num, svg: svgElem }}
  270. // the kanji info bit: "症":{x:num, y:num, svg: svgElem }, needs to be creatable, editable, and retrievable.
  271.  
  272. var dragMouseDownHandler = function(evt){
  273. console.info("mousedown event was heard", evt);
  274. evt.preventDefault();
  275. console.log('this == ', this);
  276. this._mouseDownOrigin = {x: evt.clientX, y: evt.clientY};
  277. //var elStyle = document.defaultView.getComputedStyle(evt.target, "");
  278. var elStyle = document.defaultView.getComputedStyle(this, "");
  279. var l = elStyle.left; var t = elStyle.top;
  280. //var l = evt.target.style.left; var t = evt.target.style.top;
  281. this._originalPosition = {x: parseFloat(l.substr(0, l.length-1)), y: parseFloat(t.substr(0, t.length-1))};
  282. this._mouseMoveHandler = dragMouseMoveHandler.bind(this);
  283. this._mouseUpHandler = dragMouseUpHandler.bind(this);
  284. document.addEventListener('mousemove', this._mouseMoveHandler);
  285. //document.addEventListener('mousemove', dragMouseMoveHandler);
  286. document.addEventListener('mouseup', this._mouseUpHandler);
  287. document.addEventListener('mouseout', this._mouseUpHandler);
  288. // this.addEventListener('mouseup', dragMouseUpHandler);
  289. // this.addEventListener('mouseout', dragMouseUpHandler);
  290. };
  291. var dragMouseMoveHandler = function(evt){
  292. //nsole.log("mousemove", evt, this);
  293. if (this._mouseDownOrigin){
  294.  
  295. var dx = evt.clientX - this._mouseDownOrigin.x;
  296. //console.log("dx", dx);
  297. var dy = evt.clientY - this._mouseDownOrigin.y;
  298. var l = this.style.left||"0px"; var t = this.style.top||"0px";
  299. if (l[l.length-1] === "%" || t[t.length-1] === "%"){
  300. console.log("positioned with % ??");
  301. }
  302. else{
  303. var newLeft = Math.max(-overlayLeftOffset, this._originalPosition.x + dx) + "px";
  304. console.log("-overlayLeftOffset", -overlayLeftOffset, "this._originalPosition.x", this._originalPosition, "dx", dx);
  305. var newTop = Math.max(-overlayTopOffset, this._originalPosition.y + dy) + "px";
  306. //want the highest negative number to keep it in the document
  307. console.log("moving div:" + newLeft + " " + newTop);
  308. this.style.left = newLeft;
  309. this.style.right = -'100px';
  310. this.style.top = newTop;
  311. }
  312. }
  313. };
  314. var dragMouseUpHandler = function(evt){
  315. if (evt.type === 'mouseup' || evt.type === 'mouseout' && (evt.toElement === null)){ // mouseout leaves entire document
  316. // Check if this radical has a payload for the kanji, give it one if not.
  317. masterRads[this.slug].kanji[prompt.kan] = {x: this.style.left, y:this.style.top};
  318. //console.log("find x and y?", evt);
  319. $.jStorage.set("overlayMasterRads", masterRads);
  320.  
  321. console.log("removing listeners", evt.type);
  322. document.removeEventListener('mousemove', this._mouseMoveHandler);
  323. document.removeEventListener('mouseup', this._mouseUpHandler);
  324. document.removeEventListener('mouseout', this._mouseUpHandler);
  325. }
  326. };
  327.  
  328. // Order is not important for radicals since they are just like, all over the kanji, so we will just iterate.
  329. for (var rad in respRads){
  330. var spRadName = document.createElement('span');
  331. var radBox = document.createElement('span');
  332. radBox.setAttribute("lang", "ja");
  333. radBox.className = "wkOverlayRadBox";
  334. if (!respRads[rad].box){
  335. radBox.appendChild(document.createTextNode(rad));
  336. }
  337. else{
  338. radBox.appendChild(respRads[rad].box.cloneNode());
  339. }
  340. spRadName.slug = rad;
  341. spRadName.appendChild(radBox);
  342. spRadName.appendChild(document.createTextNode(respRads[rad].name));
  343.  
  344. overlay.appendChild(spRadName);
  345. spRadName.style.marginLeft = (-100)*Math.random() + "%"; //more likely to see them if they are changed up a bit while we code
  346. spRadName.style.left = respRads[rad].kanji[prompt.kan].x;
  347. spRadName.style.top = respRads[rad].kanji[prompt.kan].y;
  348. spRadName.style.cursor = "move";
  349. spRadName.className = "infoRadSpan";
  350.  
  351. //-- todo keep track of these in objects, enable/disable handlers in an edit/setup mode
  352. //masterRads.currentSlug = slug;
  353. spRadName.addEventListener('mousedown', dragMouseDownHandler);
  354. }
  355. }
  356. };
  357.  
  358. var observer = new MutationObserver(showRadicalTags);
  359. //observer = new MutationObserver(function(mutation){console.log(mutation);});
  360.  
  361. var testObserve = new MutationObserver(function(mutations){
  362. console.info("%cObserver", "background-color:grey");
  363. console.info(typeof mutations);
  364. console.groupCollapsed("Mutation List");
  365. mutations.forEach(function(mutation){console.info(mutation.type);});
  366. console.groupEnd();
  367. });
  368.  
  369. // Show overlay when info is being shown.
  370. $("#item-info").on(showEvent, function(evt){
  371. console.info("showevt", evt);
  372. if (newItem){
  373. newItem = false;
  374. //watch related items for change
  375. observer.observe($("#item-info")[0], {childList: true, subtree:true});
  376. }
  377. else{
  378. showRadicalTags();
  379. }
  380. });
  381.  
  382. $("#item-info").on(hideEvent, function(evt){
  383. if (evt.target.id === "additional-content-load"){
  384. console.info("hide evt", evt);
  385. //debugger;
  386. overlay.style.display = 'none';
  387. }
  388. });
  389. })();