Skip to content

Commit

Permalink
refactor: lib rewrite from typescript to native javascript
Browse files Browse the repository at this point in the history
  • Loading branch information
sibiraj-s committed Nov 24, 2019
1 parent f3c6cb8 commit a3e1bd2
Show file tree
Hide file tree
Showing 19 changed files with 376 additions and 358 deletions.
2 changes: 1 addition & 1 deletion .browserslistrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ last 5 version
> 0.5%
maintained node versions
not dead
ie > 7
ie > 9
3 changes: 3 additions & 0 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ rules:
max-len:
- error
- code: 120
quote-props:
- error
- consistent
env:
jest: true
browser: true
2 changes: 1 addition & 1 deletion docs/BrowserDtector.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';

import BrowserDtector from '../dist/lib/browser-dtector';
import BrowserDtector from '../lib/browser-dtector';

const BrowserDtectorComponent = () => {
const browser = new BrowserDtector(window.navigator.userAgent);
Expand Down
2 changes: 1 addition & 1 deletion docs/UserAgentParser.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState } from 'react';

import BrowserDtector from '../dist/lib/browser-dtector';
import BrowserDtector from '../lib/browser-dtector';

const currentUserAgent = window.navigator.userAgent;
const browser = new BrowserDtector(currentUserAgent);
Expand Down
206 changes: 191 additions & 15 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,198 @@
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html

module.exports = {
verbose: true,
// All imported modules in your tests should be mocked automatically
// automock: false,

// Stop running tests after `n` failures
// bail: 0,

// Respect "browser" field in package.json when resolving modules
// browser: false,

// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/c_/9sztbj915w16vfl38h5xqjnr0000gp/T/jest_dy",

// Automatically clear mock calls and instances between every test
clearMocks: true,

// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
collectCoverageFrom: [
'dist/lib/**/*.js',
'!dist/**/*.min.js',
'specs/**/*.js',
'!**/node_modules/**',
'!**/vendor/**',
],
testPathIgnorePatterns: [
'node_modules',
'.cache',

// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: null,

// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',

// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: [
'/node_modules/',
'/dist/',
],

// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],

// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: null,

// A path to a custom dependency extractor
// dependencyExtractor: null,

// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,

// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],

// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: null,

// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: null,

// A set of global variables that need to be available in all test environments
// globals: {},

// The maximum amount of workers used to run your tests. Can be specified as % or a number.
// E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number.
// maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",

// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],

// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],

// A map from regular expressions to module names that allow to stub out resources with a single module
moduleNameMapper: {},

// An array of regexp pattern strings, matched against all module paths
// before considered 'visible' to the module loader
modulePathIgnorePatterns: [
'<rootDir>/dist/lib/package.json',
'<rootDir>/dist/docs/',
'<rootDir>/dist/',
],
moduleNameMapper: {
'\\.(css|scss)$': 'identity-obj-proxy',

// Activates notifications for test results
// notify: false,

// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",

// A preset that is used as a base for Jest's configuration
// preset: null,

// Run tests from one or more projects
// projects: null,

// Use this configuration option to add custom reporters to Jest
// reporters: undefined,

// Automatically reset mock state between every test
// resetMocks: false,

// Reset the module registry before running each individual test
// resetModules: false,

// A path to a custom resolver
// resolver: null,

// Automatically restore mock state between every test
// restoreMocks: false,

// The root directory that Jest should scan for tests and modules within
// rootDir: null,

// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],

// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",

// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],

// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],

// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],

// The test environment that will be used for testing
// testEnvironment: "jest-environment-jsdom",

// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},

// Adds a location field to test results
// testLocationInResults: false,

// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],

// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/",
// ],

// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],

// This option allows the use of a custom results processor
// testResultsProcessor: null,

// This option allows use of a custom test runner
// testRunner: "jasmine2",

// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",

// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",

// A map from regular expressions to paths to transformers
transform: {
'^.+\\.js(x)?$': 'babel-jest',
},

// An array of regexp pattern strings that are matched against all source file paths,\
// matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/"
// ],

// An array of regexp pattern strings that are matched against
// all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,

// Indicates whether each individual test should be reported during the run
// verbose: null,

// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],

// Whether to use watchman for file crawling
// watchman: true,
};
146 changes: 146 additions & 0 deletions lib/browser-dtector.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { KnownBrowsers, KnownPlatforms } from './constants';
import { version as pkgVersion } from '../package.json';
import utils from './utils';

function BrowserDtector(userAgent) {
this.userAgent = userAgent || window.navigator.userAgent;
this.__VERSION__ = pkgVersion;

this.parseUserAgent = (userAgent) => {
const browserMatches = {};

const uaFresh = userAgent || this.userAgent;

// convert to lower case and treat tabs and multiple sapces as single space
const ua = uaFresh.toLowerCase().replace(/\s\s+/g, ' ');

const browserMatch = /(edge)\/([\w.]+)/.exec(ua)
|| /(opr)[/]([\w.]+)/.exec(ua)
|| /(jsdom)[/]([\w.]+)/.exec(ua)
|| /(samsungbrowser)[/]([\w.]+)/.exec(ua)
|| /(chrome)[/]([\w.]+)/.exec(ua)
|| /(crios)[/]([\w.]+)/.exec(ua)
|| /(opios)[/]([\w.]+)/.exec(ua)
|| /(version)(applewebkit)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(ua)
|| /(webkit)[/]([\w.]+).*(version)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(ua)
|| /(applewebkit)[/]([\w.]+).*(safari)[/]([\w.]+)/.exec(ua)
|| /(webkit)[/]([\w.]+)/.exec(ua)
|| /(opera)(?:.*version|)[/]([\w.]+)/.exec(ua)
|| /(msie) ([\w.]+)/.exec(ua)
|| /(fennec)[/]([\w.]+)/.exec(ua)
|| (ua.indexOf('trident') >= 0 && /(rv)(?::| )([\w.]+)/.exec(ua))
|| (ua.indexOf('compatible') < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua))
|| [];

const platformMatch = /(ipad)/.exec(ua)
|| /(ipod)/.exec(ua)
|| /(iphone)/.exec(ua)
|| /(jsdom)/.exec(ua)
|| /(windows phone)/.exec(ua)
|| /(xbox)/.exec(ua)
|| /(win)/.exec(ua)
|| /(tablet)/.exec(ua)
|| ((/(android)/.test(ua) && /(mobile)/.test(ua) === false) && ['androidTablet'])
|| /(android)/.exec(ua)
|| /(mac)/.exec(ua)
|| /(linux)/.exec(ua)
|| /(cros)/.exec(ua)
|| [];

const browserInfo = {
name: browserMatch[5] || browserMatch[3] || browserMatch[1] || undefined,
platform: platformMatch[0] || undefined,
userAgent: uaFresh,
version: browserMatch[4] || browserMatch[2] || undefined,
};

if (!browserInfo.name) {
Object.keys(browserInfo).forEach((key) => { browserInfo[key] = 'Unknown'; });
return browserInfo;
}

if (browserInfo.name) {
browserMatches[browserInfo.name] = true;
browserInfo.name = KnownBrowsers[browserInfo.name] || 'Unknown';
}

if (browserInfo.platform) {
browserMatches[browserInfo.platform] = true;
browserInfo.platform = KnownPlatforms[browserInfo.platform] || 'Unknown';
}

if (browserInfo.version) {
browserInfo.shortVersion = utils.toFixed(parseFloat(browserInfo.version), 2);
}

browserInfo.isAndroid = !!(
browserMatches.tablet
|| browserMatches.android
|| browserMatches.androidTablet
);

browserInfo.isTablet = !!(
browserMatches.ipad
|| browserMatches.tablet
|| browserMatches.androidTablet
);

browserInfo.isMobile = !!(
browserMatches.android
|| browserMatches.androidTablet
|| browserMatches.tablet
|| browserMatches.ipad
|| browserMatches.ipod
|| browserMatches.iphone
|| browserMatches['windows phone']
);

browserInfo.isDesktop = !!(
browserMatches.cros
|| browserMatches.mac
|| browserMatches.linux
|| browserMatches.win
);

browserInfo.isWebkit = !!(
browserMatches.chrome
|| browserMatches.crios
|| browserMatches.opr
|| browserMatches.safari
);

browserInfo.isIE = !!(
browserMatches.msie
|| browserMatches.rv
);

return browserInfo;
};

this.getBrowserInfo = () => {
const browserInfo = this.parseUserAgent();
delete browserInfo.isAndroid;
delete browserInfo.isMobile;
delete browserInfo.isTablet;
delete browserInfo.isWebkit;
delete browserInfo.isDesktop;
delete browserInfo.isIE;
return browserInfo;
};

this.getBrowserName = () => this.parseUserAgent().name;
this.getBrowserVersion = () => this.parseUserAgent().version;
this.getBrowserShortVersion = () => this.parseUserAgent().shortVersion || 'Unknown';
this.getPlatformName = () => this.parseUserAgent().platform;

this.isAndroid = () => this.parseUserAgent().isAndroid;
this.isTablet = () => this.parseUserAgent().isTablet;
this.isMobile = () => this.parseUserAgent().isMobile;
this.isWebkit = () => this.parseUserAgent().isWebkit;
this.isDesktop = () => this.parseUserAgent().isDesktop;
this.isIE = () => this.parseUserAgent().isIE;

Object.freeze(this);
}

export default BrowserDtector;
Loading

0 comments on commit a3e1bd2

Please sign in to comment.