All files / lib/directives toggle.js

85.71% Statements 18/21
76.92% Branches 10/13
100% Functions 3/3
85.71% Lines 18/21
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 45 46 47 48 49 50 51 52 53 5418x     18x     18x     18x 18x           77x 3x 3x       77x   77x 77x     77x 728x   92x   92x 24x   68x           77x                      
const inBrowser = typeof window !== 'undefined';
 
import target from './_target';
const listen_types = {click: true};
 
// Property key for handler
const BVT = '__BV_toggle__';
 
// Event nmmes
const EVENT_TOGGLE = 'collapse::toggle';
const EVENT_STATE = 'collapse::toggle::state';
 
export default {
 
    bind(el, binding, vnode) {
 
        const targets = target(vnode, binding, listen_types, ({targets, vnode}) => {
            targets.forEach(target => {
                vnode.context.$root.$emit(EVENT_TOGGLE, target);
            });
        });
 
        Eif (inBrowser && vnode.context && targets.length > 0) {
            // Add aria attributes to element
            el.setAttribute('aria-controls', targets.join(' '));
            el.setAttribute('aria-expanded', 'false');
 
            // Toggle state hadnler, stored on element
            el[BVT] = function toggleDirectiveHandler(id, state) {
                if (targets.indexOf(id) !== -1) {
                    // Set aria-expanded state
                    el.setAttribute('aria-expanded', state ? 'true' : 'false');
                    // Set 'collapsed' class state
                    if (state) {
                        el.classList.remove('collapsed');
                    } else {
                        el.classList.add('collapsed');
                    }
                }
            };
 
            // Listen for toggle state changes
            vnode.context.$root.$on(EVENT_STATE, el[BVT]);
        }
    },
    unbind(el, binding, vnode) {
        if (el[BVT]) {
            // Remove our $root listener
            vnode.context.$root.$off(EVENT_STATE, el[BVT]);
            el[BVT] = null;
        }
    }
};