Passed
Push — trunk ( 54c4dd...cf5ce9 )
by Christian
15:20 queued 20s
created

responsive.directive.ts ➔ inserted   B

Complexity

Conditions 7

Size

Total Lines 24
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 20
dl 0
loc 24
rs 8
c 0
b 0
f 0
1
import type { DirectiveBinding } from 'vue/types/options';
2
3
interface ResponsiveDirectiveBinding extends DirectiveBinding {
4
    value?: {
5
        [key: string]: ((elementSizeValues: DOMRectReadOnly) => boolean) | number;
6
    }
7
}
8
9
/**
10
 * @package admin
11
 *
12
 * @deprecated tag:v6.6.0 - Will be private
13
 * Directive for responsive element classes
14
 *
15
 * Usage:
16
 * v-responsive="{ 'is--compact': el => el.width <= 1620, timeout: 200 }"
17
 * Explanation:
18
 *  - Apply class (in this case: 'is--compact') when the width of the element is smaller than 1620px.
19
 *  - timeout: Sets the duration on how much the throttle should wait.
20
 */
21
22
Shopware.Directive.register('responsive', {
23
    inserted(el: HTMLElement, binding: ResponsiveDirectiveBinding) {
24
        const timeout = typeof binding.value?.timeout === 'number' ? binding.value.timeout : 200;
25
26
        const handleResize: ResizeObserverCallback = Shopware.Utils.throttle((entries: ResizeObserverEntry[]) => {
27
            entries.forEach(entry => {
28
                const elementSizeValues = entry.contentRect;
29
30
                Object.entries(binding.value ?? {}).forEach(([breakpointClass, breakpointCallback]) => {
31
                    if (typeof breakpointCallback !== 'function') {
32
                        return;
33
                    }
34
35
                    if (breakpointCallback(elementSizeValues)) {
36
                        el.classList.add(breakpointClass);
37
                        return;
38
                    }
39
40
                    el.classList.remove(breakpointClass);
41
                });
42
            });
43
        }, timeout);
44
45
        const observer = new ResizeObserver(handleResize);
46
        observer.observe(el);
47
    },
48
});
49
50