All files linkhighlighter.ts

100% Statements 17/17
93.33% Branches 14/15
100% Functions 5/5
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44                    1x 13x       15x 15x 15x   15x 15x   15x       13x 13x   2x         13x 13x 1x 1x     14x      
/*!
 * linkhighlighter - Tiny library to highlight active link on web page.
 *
 * @author  Михаил Драгункин <contact@unsektor.com>
 * @url     https://github.com/unsektor/linkhighlighter/
 * @license ISC
 * @since   June 25, 2017
 * @ver     1.0.0
 */
 
export default class {
    constructor(private location: Location = window.location) {
    }
 
    private highlightScope(scopeElement: Element): void {
        const scopeHighlightClass = scopeElement.getAttribute('data-lh-class') || 'g-lh-active';
        const anchorElementList: NodeListOf<HTMLAnchorElement> = scopeElement.querySelectorAll('a[data-lh]');
        const self = this;
 
        anchorElementList.forEach(function (anchorElement: HTMLAnchorElement): void {
            const anchorElementOption = anchorElement.getAttribute('data-lh') || 'match-uri';
 
            if ((anchorElementOption === 'match-domain' && anchorElement.host === self.location.host) ||
                (anchorElementOption === 'match-uri' && anchorElement.href === self.location.href) ||
                (anchorElementOption === 'match-partial' && self.location.href.toLowerCase().startsWith(anchorElement.href.toLowerCase()))
            ) {
                anchorElement.classList.add(scopeHighlightClass);
                return;
            }
            anchorElement.classList.remove(scopeHighlightClass);
        })
    }
 
    public highlight(): void {
        let scopeElementList: NodeListOf<Element> = document.querySelectorAll('[data-lh-scope]');
        if (0 === scopeElementList.length) {
            this.highlightScope(document.body);
            return;
        }
 
        scopeElementList.forEach((scopeElement) => this.highlightScope(scopeElement));
    }
}