UNPKG

2.98 kBJavaScriptView Raw
1import kebabCase from 'lodash/kebabCase';
2import UAParser from 'ua-parser-js';
3import MobileDetect from 'mobile-detect';
4
5if (process.client) {
6 require('feature.js');
7}
8
9export default ({ app, store, req }, inject) => {
10 /*
11 ** User Agent
12 */
13 const ua = process.client
14 ? window.navigator.userAgent
15 : req.headers['user-agent'];
16 const userAgent = UAParser(ua);
17
18 inject('userAgent', userAgent);
19
20 if (process.client) {
21 document.documentElement.classList.add(kebabCase(userAgent.browser.name));
22 document.documentElement.classList.add(kebabCase(userAgent.os.name));
23 }
24
25 /*
26 ** Device Type
27 */
28 const md = new MobileDetect(ua);
29
30 const device = {
31 isMobile: !!md.mobile(),
32 isTablet: !!md.tablet(),
33 isDesktop: !!(!md.mobile() && !md.tablet()),
34 };
35
36 inject('device', device);
37
38 if (process.client) {
39 if (md.mobile()) {
40 document.documentElement.classList.add('mobile');
41 }
42 if (md.tablet()) {
43 document.documentElement.classList.add('tablet');
44 }
45 if (!md.mobile() && !md.tablet()) {
46 document.documentElement.classList.add('desktop');
47 }
48 }
49
50 /*
51 ** Window Loaded
52 */
53 if (process.client) {
54 window.addEventListener(
55 'load',
56 () => {
57 store.commit('DEVICE', { isLoaded: true });
58 document.documentElement.classList.add('loaded');
59 },
60 { once: true }
61 );
62 }
63
64 /*
65 ** Viewport Dimensions
66 */
67 if (process.client) {
68 const setViewportVars = (event, init = false) => {
69 setTimeout(() => {
70 const availableHeight =
71 screen.height - (screen.height - window.innerHeight);
72 const isPortrait = window.matchMedia('(orientation: portrait)').matches;
73 store.commit('DEVICE', { isPortrait, isLandscape: !isPortrait });
74 if (init) {
75 document.documentElement.style.setProperty(
76 '--ah-init',
77 `${availableHeight}px`
78 );
79 }
80 document.documentElement.style.setProperty(
81 '--ah',
82 `${availableHeight}px`
83 );
84 }, 100);
85 };
86
87 setViewportVars(null, true);
88
89 window.addEventListener('orientationchange', setViewportVars);
90 window.addEventListener('resize', setViewportVars);
91 }
92
93 /*
94 ** Tabbing
95 */
96 if (process.client) {
97 document.addEventListener('keydown', event => {
98 if (event.keyCode === 9) {
99 document.documentElement.classList.add('tabbed');
100 }
101 });
102 document.addEventListener('mousedown', () => {
103 document.documentElement.classList.remove('tabbed');
104 });
105 }
106
107 /*
108 ** Scroll
109 */
110 inject(
111 'scrollTo',
112 (
113 selector,
114 { block, behavior } = { block: 'start', behavior: 'smooth' }
115 ) => {
116 document.querySelector(selector).scrollIntoView({ block, behavior });
117 }
118 );
119
120 app.$init(() => {
121 /*
122 ** User Agent
123 */
124 store.commit('USERAGENT', userAgent);
125
126 /*
127 ** Device Type
128 */
129 store.commit('DEVICE', device);
130 });
131};