Created
October 31, 2019 08:41
-
-
Save linasmatakas/94a515f78228f023f250a1f959e073b0 to your computer and use it in GitHub Desktop.
window-service.js vue global $screen variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue from 'vue'; | |
const browser = { | |
isIe11: /rv:11.0/i.test(navigator.userAgent), | |
isEdge: /Edge\/\d./i.test(navigator.userAgent), | |
}; | |
const device = { | |
isIosMobile: /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream, | |
}; | |
const screenSizes = { | |
mobile: 480, | |
mobileBig: 600, | |
portrait: 768, | |
tabletThin: 960, | |
footerBreak: 1200, | |
}; | |
const media = { | |
isMobile: () => window.matchMedia(`(max-width: ${screenSizes.mobile}px)`).matches, | |
isMobileBig: () => window.matchMedia(`(max-width: ${screenSizes.mobileBig}px)`).matches, | |
isPortrait: () => window.matchMedia(`(max-width: ${screenSizes.portrait}px)`).matches, | |
isTabletThin: () => window.matchMedia(`(max-width: ${screenSizes.tabletThin}px)`).matches, | |
isFooterBreak: () => window.matchMedia(`(max-width: ${screenSizes.footerBreak}px)`).matches, | |
}; | |
function createScreenVar(variable, size, component, destroy = true) { | |
function mediaHandler(event) { | |
Object.assign(component, { | |
[variable]: event.matches, | |
}); | |
} | |
let mediaString; | |
if (typeof size === 'number') { | |
mediaString = `(max-width: ${size}px)`; | |
} else if (typeof size === 'object') { | |
mediaString = `(${size.direction}-width: ${size.value}px)`; | |
} else { | |
mediaString = size; | |
} | |
const mediaQuery = window.matchMedia(mediaString); | |
mediaQuery.addListener(mediaHandler); | |
if (destroy) { | |
component.$once('hook:destroyed', () => { | |
mediaQuery.removeListener(mediaHandler); | |
}); | |
} | |
return mediaQuery.matches; | |
} | |
function init() { | |
if (device.isIosMobile) { | |
document.body.classList.add('device-ios'); | |
} | |
const screen = Vue.observable({ | |
isMobile: false, | |
isMobileBig: false, | |
isPortrait: false, | |
isTabletThin: false, | |
}); | |
screen.isMobile = createScreenVar('isMobile', screenSizes.mobile, screen, false); | |
screen.isMobileBig = createScreenVar('isMobileBig', screenSizes.mobileBig, screen, false); | |
screen.isPortrait = createScreenVar('isPortrait', screenSizes.portrait, screen, false); | |
screen.isTabletThin = createScreenVar('isTabletThin', screenSizes.tabletThin, screen, false); | |
Vue.prototype.$screen = screen; | |
} | |
export default { | |
browser, | |
device, | |
screenSizes, | |
media, | |
createScreenVar, | |
init, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment