find-me-at-thbwiki

Find selection text on THBWiki

  1. // ==UserScript==
  2. // @name find-me-at-thbwiki
  3. // @namespace Gizeta.Debris.FindMeAtTHBWiki
  4. // @version 0.1.1
  5. // @description Find selection text on THBWiki
  6. // @author Gizeta
  7. // @match *://*/*
  8. // @grant none
  9. // ==/UserScript==
  10.  
  11. /* jshint esversion: 6 */
  12.  
  13. const API = 'https://thwiki.cc/api.php?action=query&format=json&uselang=zh&list=search&srlimit=5&srsearch=';
  14.  
  15. function getTooltipTarget(create = false) {
  16. const target = document.getElementById('find-me-at-thbwiki-tooltip');
  17. if (!create || target)
  18. return target;
  19. const tooltip = document.createElement('div');
  20. tooltip.id = 'find-me-at-thbwiki-tooltip';
  21. tooltip.style.position = 'absolute';
  22. tooltip.style.backgroundColor = '#ddd';
  23. tooltip.style.maxWidth = '50%';
  24. tooltip.style.padding = '5px';
  25. document.body.appendChild(tooltip);
  26. return tooltip;
  27. }
  28.  
  29. function getPosition() {
  30. const rect = document.getSelection().getRangeAt(0).getBoundingClientRect();
  31. const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  32. const top = Math.floor(scrollTop + rect.top + rect.height);
  33. const left = Math.floor(rect.left);
  34. return [top, left];
  35. }
  36.  
  37. function showTooltip(result) {
  38. const tooltip = getTooltipTarget(true);
  39. const [top, left] = getPosition();
  40. tooltip.style.display = 'block';
  41. tooltip.style.fontSize = '14px';
  42. tooltip.style.color = 'black';
  43. tooltip.style.top = `${top}px`;
  44. tooltip.style.left = `${left}px`;
  45. tooltip.innerHTML = result.map(([title, content]) => `<h3><a href="https://thwiki.cc/${title}" target="_blank" rel="noopener noreferrer">${title}</a></h3><div>${content}</div>`);
  46. }
  47.  
  48. function hideToolip() {
  49. if (getTooltipTarget())
  50. getTooltipTarget().style.display = 'none';
  51. }
  52.  
  53. document.body.addEventListener("mouseup", () => {
  54. const selection = document.getSelection();
  55. if (!selection || selection.type === "Caret") {
  56. hideToolip();
  57. return;
  58. }
  59. fetch(API + selection.toString().trim()).then(resp => resp.json()).then(data => {
  60. if (data.query && data.query.search && data.query.search.length > 0)
  61. showTooltip(data.query.search.map(x => [x.title, x.snippet]));
  62. else
  63. showTooltip('', 'not found');
  64. });
  65. });