Completed
Push — master ( 7c2706...6e6b11 )
by D
02:19
created

src/ts/modules/accordion.ts   A

Complexity

Total Complexity 9
Complexity/F 2.25

Size

Lines of Code 60
Function Count 4

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 46
mnd 5
bc 5
fnc 4
dl 0
loc 60
bpm 1.25
cpm 2.25
noi 0
c 0
b 0
f 0
rs 10

4 Functions

Rating   Name   Duplication   Size   Complexity  
A Accordion.onInit 0 4 5
A Accordion.addClasses 0 4 1
A Accordion.toggleState 0 13 2
A Accordion.closeAll 0 4 1
1
import {define} from "../globals/globals";
2
import {AccordionInterface} from "../interfaces/AccordionInterface";
3
import {AccordionOptions} from '../types/AccordionOptions'
4
5
(function (root, factory) {
6
    if (typeof define === 'function' && define.amd) {
7
        define([], factory);
8
    } else if (typeof module === 'object' && module.exports) {
9
        module.exports = factory();
10
    } else {
11
        root.Accordion = factory();
12
    }
13
}(typeof self !== 'undefined' ? self : this, function () {
14
15
    class Accordion implements AccordionInterface {
16
        public options: AccordionOptions;
17
18
        constructor(options: AccordionOptions = {}) {
19
            this.options = options as object;
20
            this.options.el = typeof options.el === 'string' ? document.querySelectorAll(options.el) : options.el || document.querySelectorAll('.accordion');
21
            this.onInit();
22
        }
23
24
        protected onInit(): void {
25
            this.addClasses();
26
            this.toggleState();
27
        }
28
29
        static closeAll(accordions: NodeListOf<HTMLElement>): void {
30
            accordions.forEach(function (accordion: Element) {
31
                accordion.classList.remove('active')
32
            })
33
        }
34
35
        protected addClasses(): void {
36
            (this.options.el as NodeListOf<HTMLElement>).forEach(function (element: HTMLElement) {
37
                element.classList.add('accordion')
38
            })
39
        }
40
41
        protected toggleState(): void {
42
            let that = this;
43
44
            (that.options.el as NodeListOf<HTMLElement>).forEach(function (element: HTMLElement) {
45
                element.firstElementChild!.addEventListener('click', function () {
46
                    if(that.options.openOneCloseAll) {
47
                        Accordion.closeAll(that.options.el as NodeListOf<HTMLElement>);
48
49
                        (this as HTMLElement).parentElement!.classList.toggle('active')
50
                    }
51
                    else {
52
                        element.classList.toggle('active')
53
                    }
54
                })
55
            })
56
        }
57
    }
58
59
    return Accordion;
60
}));