[
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 Walter Staeblein\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Text Highlighter\n\nVanilla JS class to highlight search results in a textarea while maintaining the area's functionality.\n\nSince one can't style the text in a textarea, as it is not HTML, this class comes to the rescue allowing you to highlight any text in a textarea. Such as in search results.\n\n\n![Screenshot](screen.png)\n\n\n#### [CHECK OUT THE DEMO](https://wstaeblein.github.io/texthighlighter/){:target=\"_blank\"}\n\n\n## Features\n\n- No dependencies.\n- No configuration. Just instantiate the class and call a method.\n- Can be used in as many textareas as needed, just instantiate for each one.\n- Responsive. The markings will adjust to screen size, textarea size and scroll.\n- Keeps the original background from the textarea.\n- Can be properly destroyed. Will remove all events and structure.\n- Can choose between case sensitive and insensitive search.\n- Can search freely or words only.\n- Provides a count of how many results were found.\n- Can navigate the search results, bringing them to view as needed.\n\n\n\nIts use is very straightforward, instantiate the class for the textarea you need and call the search method to highlight the text you pass in the first argument. The second argument is optional and takes a boolean that if true will make the search case sensitive. The default is case insensitive. The last argument also takes a boolean that, if true, will perform a word search. Otherwise it's a free search, where any part of words can be matched.\n\n\n\n## Usage & Code Examples\n\nAdd the following files to your project:\n- texthighlighter.js\n- texthighlighter.css\n\n\n```javascript\nlet tarea = document.getElementById('txt');\nlet hilite = new textHighlight(tarea);\n\nlet searchResult = 'Some Expression';\nlet sens = true;                        // Case sensitive. Optional, default: false\nlet word = true;                        // Perform a words only search. Optional, default: false\nhilite.search(searchResult, sens, word);\n```\n\nTo access how many occurrences were found, use:\n\n```javascript\nlet count = hilite.count();\n```\n\nYou can navigate back and forth among the highlighted results using the prev and next methods. This navigation is cyclic, this means when the end is reached the next call takes you back to the begining and vice versa. Example below:\n\n```javascript\nlet btnPrev = document.getElementById('prev');\nlet btnNext = document.getElementById('next');\n\nbtnPrev.addEventListener('click', hilite.prev);\nbtnNext.addEventListener('click', hilite.next);\n```\n\nShould you need to clear out the highlights, call the clear method.\n\n```javascript\nhilite.clear();\n```\n\nWhen it falls out of scope, just call the destroy method and all will be as it was before instantiation.\n\n```javascript\nhilite.destroy();\n```\n\n\n## About\n\nThis class was inspired by lonekorean's [highlight-within-textarea](https://github.com/lonekorean/highlight-within-textarea) JQuery plugin. Basically, I needed a similar functionality for a project but didn't want to include JQuery just for that and didn't find any other such code that was good enough. \n\nThe main aim here was to provide highlighting for search results in a textarea.\n\nThis class was tested in Chrome 117 and Firefox 118.\n\n\n\n## Licence\n\nThis project is licensed under the [MIT Licence](https://github.com/wstaeblein/texthighlighter/blob/main/LICENSE)"
  },
  {
    "path": "index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"pt\">\n    <head>\n        <title>Highlight Textarea Component</title>\n        <meta charset=\"UTF-8\">\n        <link rel=\"shortcut icon\" type=\"image/png\" href=\"favicon.png\" />\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n        <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n        <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n        <link href=\"https://fonts.googleapis.com/css2?family=Bungee&family=Open+Sans:wght@400&display=swap\" rel=\"stylesheet\">\n        <link href=\"./texthighlighter.css\" rel=\"stylesheet\">\n        <script src=\"texthighlighter.js\"></script>\n        <style>\n            body {\n                font-family: 'Open Sans', sans-serif;\n                color: #0a4ba0;\n            }\n\n            h1 {\n                font-family: 'Bungee', sans-serif;\n                text-transform: uppercase;\n                text-shadow: -1px -1px 0 #0a4ba0, 1px -1px 0 #0a4ba0, -1px 1px 0 #0a4ba0, 1px 1px 0 #0a4ba0;\n                font-size: 54px;\n                color: #fffffd;\n                margin: -45px 0 0;\n                letter-spacing: 3px;\n            }\n\n            main {\n                max-width: 1000px;\n                width: 100%;\n                margin: 20px auto;\n            }\n\n            main > div {\n                margin-top: -2.2em;\n            }\n\n            button {\n                border: 1px solid #0a4ba0;\n                background-color: #bbb7ff;\n                color: #fff;\n                text-transform: uppercase;\n                font-size: 12px;\n                font-weight: bold;\n                cursor: pointer;\n                text-shadow: 1px 1px 0 #222;\n                padding: 10px 15px 7px;\n                transition: all 0.4s ease;\n            }\n                button:hover {\n                    background-color: #0a4ba0;\n                    color: #fff;\n                }\n\n            textarea {\n                width: calc(100% - 34px);\n                height: 350px;\n                padding: 8px 16px;\n                font-size: 18px;\n                color: #444;\n                margin-top: 10px;\n                background-color: #ffffe1;\n                scroll-behavior: smooth;\n            }\n\n            hr {\n                margin: 30px 0;\n                border-style: solid;\n            }\n\n            div#txtbox {\n                padding: 2px 5px;\n                border: 1px solid #eee;\n                outline: none;\n                display: inline-block;\n                width: 244px;\n                white-space: nowrap;\n                overflow: hidden;\n            }\n\n            input[type=text] {\n                max-width: 250px;\n                padding: 5px 10px;\n                font-size: 16px;\n            }\n\n            select {\n                padding: 6px 10px;\n                font-size: 16px;\n            }\n\n            nav {\n                margin: 0;\n                display: flex;\n                flex-wrap: wrap;\n                gap: 20px;\n            }    \n            \n            nav > span {\n                display: inline-block;\n                margin-bottom: 5px;\n            }\n\n            nav > span#hoppers {\n                white-space: nowrap;\n            }\n            \n            nav > span.clear {\n                flex-grow: 1;\n                text-align: right;\n            }\n\n            .count {\n                font-size: 14px;\n            }\n\n            .hidden {\n                display: none;\n            }\n\n            .smalltitle {\n                margin-top: 0;\n            }\n        </style>\n    </head>\n    <body>\n        <main>\n            <h1>Text Highlighter</h1>\n\n            <div>\n                <p class=\"smalltitle\">Javascript class to highlight search results on a textarea without interfering with its operation</p>\n                <textarea id=\"txt\" spellcheck=\"false\">\nTHE EGG\nBy: Andy Weir\n\n\nYou were on your way home when you died.\n\nIt was a car accident. Nothing particularly remarkable, but fatal nonetheless. You left behind a wife and two children. It was a painless death. The EMTs tried their best to save you, but to no avail. Your body was so utterly shattered you were better off, trust me.\n\nAnd that’s when you met me.\n\n“What… what happened?” You asked. “Where am I?”\n\n“You died,” I said, matter-of-factly. No point in mincing words.\n\n“There was a… a truck and it was skidding…”\n\n“Yup,” I said.\n\n“I… I died?”\n\n“Yup. But don’t feel bad about it. Everyone dies,” I said.\n\nYou looked around. There was nothingness. Just you and me. “What is this place?” You asked. “Is this the afterlife?”\n\n“More or less,” I said.\n\n“Are you god?” You asked.\n\n“Yup,” I replied. “I’m God.”\n\n“My kids… my wife,” you said.\n\n“What about them?”\n\n“Will they be all right?”\n\n“That’s what I like to see,” I said. “You just died and your main concern is for your family. That’s good stuff right there.”\n\nYou looked at me with fascination. To you, I didn’t look like God. I just looked like some man. Or possibly a woman. Some vague authority figure, maybe. More of a grammar school teacher than the almighty.\n\n“Don’t worry,” I said. “They’ll be fine. Your kids will remember you as perfect in every way. They didn’t have time to grow contempt for you. Your wife will cry on the outside, but will be secretly relieved. To be fair, your marriage was falling apart. If it’s any consolation, she’ll feel very guilty for feeling relieved.”\n\n“Oh,” you said. “So what happens now? Do I go to heaven or hell or something?”\n\n“Neither,” I said. “You’ll be reincarnated.”\n\n“Ah,” you said. “So the Hindus were right,”\n\n“All religions are right in their own way,” I said. “Walk with me.”\n\nYou followed along as we strode through the void. “Where are we going?”\n\n“Nowhere in particular,” I said. “It’s just nice to walk while we talk.”\n\n“So what’s the point, then?” You asked. “When I get reborn, I’ll just be a blank slate, right? A baby. So all my experiences and everything I did in this life won’t matter.”\n\n“Not so!” I said. “You have within you all the knowledge and experiences of all your past lives. You just don’t remember them right now.”\n\nI stopped walking and took you by the shoulders. “Your soul is more magnificent, beautiful, and gigantic than you can possibly imagine. A human mind can only contain a tiny fraction of what you are. It’s like sticking your finger in a glass of water to see if it’s hot or cold. You put a tiny part of yourself into the vessel, and when you bring it back out, you’ve gained all the experiences it had.\n\n“You’ve been in a human for the last 48 years, so you haven’t stretched out yet and felt the rest of your immense consciousness. If we hung out here for long enough, you’d start remembering everything. But there’s no point to doing that between each life.”\n\n“How many times have I been reincarnated, then?”\n\n“Oh lots. Lots and lots. An in to lots of different lives.” I said. “This time around, you’ll be a Chinese peasant girl in 540 AD.”\n\n“Wait, what?” You stammered. “You’re sending me back in time?”\n\n“Well, I guess technically. Time, as you know it, only exists in your universe. Things are different where I come from.”\n\n“Where you come from?” You said.\n\n“Oh sure,” I explained “I come from somewhere. Somewhere else. And there are others like me. I know you’ll want to know what it’s like there, but honestly you wouldn’t understand.”\n\n“Oh,” you said, a little let down. “But wait. If I get reincarnated to other places in time, I could have interacted with myself at some point.”\n\n“Sure. Happens all the time. And with both lives only aware of their own lifespan you don’t even know it’s happening.”\n\n“So what’s the point of it all?”\n\n“Seriously?” I asked. “Seriously? You’re asking me for the meaning of life? Isn’t that a little stereotypical?”\n\n“Well it’s a reasonable question,” you persisted.\n\nI looked you in the eye. “The meaning of life, the reason I made this whole universe, is for you to mature.”\n\n“You mean mankind? You want us to mature?”\n\n“No, just you. I made this whole universe for you. With each new life you grow and mature and become a larger and greater intellect.”\n\n“Just me? What about everyone else?”\n\n“There is no one else,” I said. “In this universe, there’s just you and me.”\n\nYou stared blankly at me. “But all the people on earth…”\n\n“All you. Different incarnations of you.”\n\n“Wait. I’m everyone!?”\n\n“Now you’re getting it,” I said, with a congratulatory slap on the back.\n\n“I’m every human being who ever lived?”\n\n“Or who will ever live, yes.”\n\n“I’m Abraham Lincoln?”\n\n“And you’re John Wilkes Booth, too,” I added.\n\n“I’m Hitler?” You said, appalled.\n\n“And you’re the millions he killed.”\n\n“I’m Jesus?”\n\n“And you’re everyone who followed him.”\n\nYou fell silent.\n\n“Every time you victimized someone,” I said, “you were victimizing yourself. Every act of kindness you’ve done, you’ve done to yourself. Every happy and sad moment ever experienced by any human was, or will be, experienced by you.”\n\nYou thought for a long time.\n\n“Why?” You asked me. “Why do all this?”\n\n“Because someday, you will become like me. Because that’s what you are. You’re one of my kind. You’re my child.”\n\n“Whoa,” you said, incredulous. “You mean I’m a god?”\n\n“No. Not yet. You’re a fetus. You’re still growing. Once you’ve lived every human life throughout all time, you will have grown enough to be born.”\n\n“So the whole universe,” you said, “it’s just…”\n\n“An egg.” I answered. “Now it’s time for you to move on to your next life.”\n\nAnd I sent you on your way. \n                </textarea>\n                <p><b>Enter a search term below to start you search!</b>\n                    <ul>\n                        <li>Then choose the case sensitivity of the search and if it'll be free or words only. </li>\n                        <li>Next, click the SEARCH button or hit ENTER to start a search. </li>\n                        <li> If you get any results, you can use the PREV (◀) and NEXT (▶) buttons <i>(that only appear after something is highlighted)</i> to navigate them. </li>\n                        <li>You can also use the resize handler to change the box's dimensions and see the result markings adjust in real time. </li>\n                        <li>Finally, click the CLEAR button to remove any highlighted items and reset the class or just type a new search term and click SEARCH again. </li>\n                    </ul>\n                </p>\n                <hr>\n                <nav>\n                    <span>\n                        <input type=\"text\" id=\"find\" onkeypress=\"preGo(event)\" placeholder=\"Enter search term\" />\n                        <select id=\"sens\">\n                            <option value=\"\">Insensitive</option>\n                            <option value=\"1\">Sensitive</option>\n                        </select>\n                        <select id=\"word\">\n                            <option value=\"\">Free Search</option>\n                            <option value=\"1\">Words Only</option>\n                        </select>                                              \n                    </span>\n                    <span>\n                        <button onclick=\"markText()\">Search</button>\n                    </span>\n                    <span id=\"hoppers\" class=\"hidden\">\n                        <button onclick=\"move('p')\">◀</button>\n                        <button onclick=\"move('n')\">▶</button>\n                    </span>\n                    <span class=\"clear\">\n                        <button onclick=\"cls()\">Clear</button>\n                    </span>\n                </nav>\n\n                <div class=\"found\"><span id=\"count\"></span> Found</div>\n                <br><br>\n\n            </div>\n        </main>\n\n        <script>\n            let tarea, hilite, find, count, hoppers;\n\n            function preGo(evt) { \n                if (evt.key === \"Enter\") {\n                    event.preventDefault();\n                    markText();\n                }\n            }\n\n            function markText() {\n                let arg = document.getElementById('find').value; \n                let sens = document.getElementById('sens').value; \n                let word = document.getElementById('word').value; \n                \n                if (arg) { \n                    hilite.search(arg, sens, word); \n                    count.textContent = hilite.count();\n                    hopperButtons();\n                }\n            }\n\n            function cls() { \n                hilite.clear(); \n                count.textContent = '0';\n                find.value = '';\n                hopperButtons();\n                find.focus();\n            }\n\n            function move(op) {\n                if (op == 'p') { hilite.prev(); } else { hilite.next(); }\n            }\n\n            function inputHandler() {\n                count.textContent = hilite.count();\n                hopperButtons();\n            }\n\n            function hopperButtons() {\n                +count.textContent ? hoppers.classList.remove('hidden') : hoppers.classList.add('hidden');\n            }\n\n            document.addEventListener('DOMContentLoaded', function() {    \n                tarea = document.getElementById('txt');\n                find = document.getElementById('find');\n                count = document.getElementById('count'); \n                hoppers = document.getElementById('hoppers'); \n                hilite = new textHighlight(tarea);\n                \n                count.textContent = '0'; \n                tarea.addEventListener('input', inputHandler);\n                inputHandler();\n            });\n        </script>\n    </body>\n</html>"
  },
  {
    "path": "texthighlighter.css",
    "content": ".hlta-container {\n    position: relative;\n    text-size-adjust: none;\n}\n\n.hlta-backdrop {\n    position: absolute;\n    overflow: hidden;\n    border-color: transparent;\n}\n\n.hlta-highlight {\n    color: transparent !important; \n    word-wrap: break-word !important;\n}\n\n.hlta-highlight > * {\n    display: none;\n}\n\n.hlta-container > .hlta-textarea {\n    position: relative;\n    background: none transparent !important;\n}\n\n.hlta-highlight > mark {\n    background-color: #fccfc8;\n    display: inline-block;\n}\n\n\n.hlta-highlight > mark.sel {\n    background-color: #ff8572;\n}\n"
  },
  {
    "path": "texthighlighter.js",
    "content": "/*  *******************************************************\n    By Walter Staeblein - 2023\n    MIT Licence - https://choosealicense.com/licenses/mit/\n\n    https://github.com/wstaeblein/highlightTextarea\n    *******************************************************/ \nclass textHighlight {\n    constructor(ele) {\n        if (ele.tagName != 'TEXTAREA') { throw 'The element must be a textarea'; }\n\n        let styles = window.getComputedStyle(ele);\n        this.origBkgColor = styles.backgroundColor;\n        this.ele = ele;\n        this.searchArg = '';\n        this.sensitive = false;\n        this.sel = -1;\n\n        this.handlers = {\n            input: this.#inputHandler.bind(this),\n            scroll: this.#scrollHandler.bind(this)\n        }\n\n        this.ele.classList.add('hlta-textarea');\n        this.ele.addEventListener('input', this.handlers.input);\n        this.ele.addEventListener('scroll', this.handlers.scroll);\n\n        let nodeCont = document.createElement('div');\n        nodeCont.classList.add('hlta-container');\n        this.container = nodeCont;\n\n        let nodeBack = document.createElement('div');\n        nodeBack.classList.add('hlta-backdrop');    \n        this.backdrop = nodeBack; \n\n        let nodeHilite = document.createElement('div');\n        nodeHilite.classList.add('hlta-highlight');  \n        this.hilite = nodeHilite;\n\n        this.ele.parentNode.insertBefore(nodeCont, this.ele.nextSibling);\n        this.backdrop.append(this.hilite);\n        this.container.append(this.backdrop);\n        this.container.appendChild(this.ele);   \n\n        let observer = new ResizeObserver(this.#resizeObs.bind(this));\n        observer.observe(this.ele);\n        this.#inputHandler();\n    }\n    \n    search(arg, sensitive, word) {\n        this.searchArg = arg;\n        this.sensitive = !!sensitive;\n        this.word = !!word;\n        this.#inputHandler();\n        this.sel = -1;\n        this.next();\n    }\n\n    next() {\n        this.sel +=1;\n        this.#setSelection(true);\n    }\n\n    prev() {\n        this.sel -=1;\n        this.#setSelection(true);\n    }\n\n    count() {\n        let eles = this.hilite.querySelectorAll('mark');\n        return eles.length;\n    }\n\n    clear() { \n        this.searchArg  = '';\n        this.hilite.innerHTML = this.hilite.textContent;\n        this.sel = -1;\n    }\n\n    destroy() {\n        this.ele.removeEventListener('input', this.handlers.input);\n        this.ele.removeEventListener('scroll', this.handlers.scroll);\n        observer.disconnect();\n\n        this.container.parentNode.insertBefore(this.ele, this.container);\n        while (this.container.firstChild) {\n            this.container.removeChild(this.container.lastChild);\n        }\n        this.container.remove();\n    }\n\n    #resizeObs() {\n        let styles = window.getComputedStyle(this.ele);\n        let width = this.ele.scrollWidth; \n        let height = this.ele.offsetHeight;\n\n        let css = `width: ${width}px; height: ${height}px; margin: ${styles.marginTop} ${styles.marginRight} ${styles.marginBottom} ${styles.marginLeft}; \n                   background-color: ${this.origBkgColor}`; \n        this.backdrop.style.cssText = css;\n        this.#copyStyles(this.ele, this.hilite, ['width', 'paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom', 'borderTop', 'letterSpacing',\n                                                'borderLeft', 'borderRight', 'borderBottom', 'fontFamily', 'fontSize', 'fontWeight', 'lineHeight']);\n        this.hilite.style.minHeight = styles.height;\n        this.hilite.style.whiteSpace = 'pre-wrap';\n    }\n\n    #inputHandler() {\n        this.hilite.innerHTML = this.#markText();\n        this.#scrollHandler();\n        if (this.sel > -1) { this.#setSelection(); }\n    }\n\n    #copyStyles(src, dest, styles2Copy) {\n        let styles = window.getComputedStyle(src);\n        styles2Copy.forEach((stl) => dest.style[stl] = styles[stl])\n    }\n\n    #markText() { \n        let txt = this.ele.value.replace(/</g, '&lt;').replace(/>/g, '&gt;');\n        if (this.searchArg) { console.log(this.ele.value)\n            \n            let searchArg = this.searchArg.replace(/</g, '&lt;').replace(/>/g, '&gt;');\n            let boundary = this.word ? '\\\\b' : '';\n\n            let re = new RegExp(boundary + '(' + this.#escapeString(searchArg) + ')' + boundary, 'g' + (this.sensitive ? '' : 'i')); \n            return txt.replace(re, '<mark>$&</mark>');\n        } else {\n            return txt;\n        }\n    }\n\n    #escapeString(txt) {\n        let specials = ['-', '[', ']', '/', '{', '}', '(', ')', '*', '+', '?', '.', '\\\\', '^', '$', '|'];\n        return txt.replace(RegExp('[' + specials.join('\\\\') + ']', 'g'), '\\\\$&'); \n    }\n\n    #scrollHandler() { \n        this.backdrop.scrollTop = this.ele.scrollTop || 0; \n        let sclLeft = this.ele.scrollLeft;\n        this.backdrop.style.transform = (sclLeft > 0) ? 'translateX(' + -sclLeft + 'px)' : '';\n    }\n\n    #setSelection(scroll) {\n        let eles = this.hilite.querySelectorAll('mark');\n        let len = eles.length;\n\n        if (this.sel >= len) { this.sel = 0; }\n        if (this.sel < 0) { this.sel = len - 1; }\n\n        for (let i = 0; i < len; ++i) {\n            if (i == this.sel) {\n                eles[i].classList.add('sel');\n                if (scroll) { this.ele.scrollTop = eles[i].offsetTop > 10 ? eles[i].offsetTop - 10 : eles[i].offsetTop; }\n            } else {\n                eles[i].classList.remove('sel');\n            }\n        }\n    }\n}"
  }
]