Advertisement
Guest User

Untitled

a guest
May 23rd, 2022
393
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name        Bionic Reading
  3. // @namespace   Violentmonkey Scripts
  4. // @match       *://*/*
  5. // @grant       none
  6. // @version     1.0
  7. // @author      -
  8. // @description 23/05/2022, 10:32:48
  9. // ==/UserScript==
  10.  
  11. // https://github.com/ansh/bionic-reading/tree/master/src
  12. //
  13. // making half of the letters in a word bold
  14. function highlightText(sentenceText) {
  15.   return sentenceText
  16.     .split(' ')
  17.     .map((word) => {
  18.       // special case - hyphenated compound word, e.g. video-game
  19.       if (word.includes('-')) {
  20.         return word.split('-').map((component) => highlightText(component)).join('-')
  21.       }
  22.       const hasNumber = /\d/
  23.       if (hasNumber.test(word)) {
  24.         return word
  25.       }
  26.       const length = word.length
  27.       let midPoint = 1
  28.       if (length > 3) midPoint = Math.round(length / 2)
  29.       const firstHalf = word.slice(0, midPoint)
  30.       const secondHalf = word.slice(midPoint)
  31.       const htmlWord = `<br-bold class="br-bold">${firstHalf}</br-bold>${secondHalf}`
  32.       return htmlWord
  33.     })
  34.     .join(' ')
  35. }
  36.  
  37. function main() {
  38.     // check if we have already highlighted the text
  39.   const boldedElements = document.getElementsByTagName('br-bold')
  40.   if (boldedElements.length > 0) {
  41.     for (const element of boldedElements) {
  42.       element.classList.toggle('br-bold')
  43.     }
  44.     return
  45.   }
  46.  
  47.   // setting global styles
  48.   var style = document.createElement('style')
  49.   style.textContent = '.br-bold { font-weight: bold !important; display: inline; }'
  50.   document.head.appendChild(style)
  51.  
  52.   let tags = ['p', 'font', 'span', 'li']
  53.  
  54.   const parser = new DOMParser()
  55.   tags.forEach((tag) => {
  56.     for (let element of document.getElementsByTagName(tag)) {
  57.       const n = parser.parseFromString(element.innerHTML, 'text/html')
  58.       const textArrTransformed = Array.from(n.body.childNodes).map((node) => {
  59.         if (node.nodeType === Node.TEXT_NODE) {
  60.           return highlightText(node.nodeValue)
  61.         }
  62.         return node.outerHTML
  63.       })
  64.       element.innerHTML = textArrTransformed.join(' ')
  65.     }
  66.   })
  67. }
  68.  
  69. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement