UNPKG

create-dan

Version:

Dan frameworks

89 lines (77 loc) 2.29 kB
import React from 'react' export const IsContext = React.createContext() /** * Use is context */ export function useIs() { return React.useContext(IsContext) } /** * With is as a props */ export function withIs(ComposedComponent) { const Component = (props) => <ComposedComponent is={useIs()} {...props} /> if(ComposedComponent.getInitialProps) { Component.getInitialProps = ComposedComponent.getInitialProps } return Component } /** * Page with i18n as a props */ export function pageWithIs(ComposedComponent) { const Component = (props) => ( <IsContext.Provider value={props.is}> <ComposedComponent {...props} /> </IsContext.Provider> ) Component.getInitialProps = async (ctx) => { ctx.is = setupIs(ctx.req) const data = ComposedComponent.getInitialProps ?(await ComposedComponent.getInitialProps(ctx)) :{} return Object.assign( data, { is: ctx.is } ) } return Component } /** * Test a regex with the user agent * @param {RegExp|String} regex * @returns {String} */ function match(regex, userAgent) { return userAgent.search(regex) !== -1; } /** * Get is information from userAgent * @param {Object} req * @param {Object} [target] */ export function setupIs(req, target = null) { const ua = req ? req.headers['user-agent'] : navigator.userAgent; // Setup is const is = target || {} // Browsers match(/Trident\/|MSIE/, ua) && (is.ie = true); match('Edge/', ua) && (is.edge = true); match('Firefox/', ua) && (is.firefox = true); match('Chrome/', ua) && (is.chrome = true); match('Safari', ua) && !match('Chrome', ua) && (is.safari = true); match(/(iPhone|iPad|iPod)/, ua) && (is.ios = true); match('Android', ua) && (is.android = true); // Devices (match(/iPad/i, ua) || (match(/Android/i, ua) && !match(/Mobile/i, ua))) && (is.tablet = true); ((is.ios || is.android) && !is.tablet) && (is.mobile = true); (!is.mobile && !is.tablet) && (is.desktop = true); // Images is.images = [ (is.chrome || is.firefox)?'webm':null, 'png', 'jpg', ].filter(item => item !== null); return is }