Skip to content

Commit

Permalink
Add TypeScript tooling
Browse files Browse the repository at this point in the history
- Migrate App component and theme to TypeScript
  • Loading branch information
OzzieOrca committed Apr 24, 2019
1 parent db1cc70 commit 27d90f7
Show file tree
Hide file tree
Showing 10 changed files with 348 additions and 57 deletions.
19 changes: 14 additions & 5 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"parser": "babel-eslint",
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
Expand Down Expand Up @@ -82,17 +82,26 @@
"react/react-in-jsx-scope": 2,
"react/no-deprecated": 2,
"react/prop-types": 0,
"react/display-name": 0
"react/display-name": 0,
"@typescript-eslint/camelcase": "off",
"@typescript-eslint/indent": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-var-requires": "off"
},
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".ios.js", ".android.js"]
"extensions": [".js", ".ts", ".tsx", ".ios.js", ".android.js"]
}
}
},
"extends": ["prettier", "plugin:react/recommended"],
"plugins": ["react", "import"],
"extends": [
"prettier",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended"
],
"plugins": ["@typescript-eslint", "react", "import"],
"overrides": [
{
"files": ["**/__tests__/**/*.js"],
Expand Down
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ matrix:
script:
- yarn run test:coverage --maxWorkers=4
- yarn run lint
- yarn run lint:ts
- yarn run prettier:check
notifications:
email: false
Expand Down
6 changes: 5 additions & 1 deletion __mock__/react-native-code-push.js
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
jest.mock('react-native-code-push', () => () => (app) => app);
jest.mock('react-native-code-push', () => {
const wrapperFn = () => app => app;
wrapperFn.CheckFrequency = { ON_APP_START: 0 };
return wrapperFn;
});
19 changes: 14 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@
"test:s": "npm run test:snapshot",
"ios": "react-native run-ios",
"ios:pod": "cd ios && pod install",
"lint": "eslint ./*.js ./src",
"lint:fix": "eslint ./*.js ./src --fix",
"prettier:check": "prettier '{{src,bin,testUtils,__{tests,mocks}__}/**/*.{js,json},./*.{js,json,yml}}' --list-different",
"prettier:write": "prettier '{{src,bin,testUtils,__{tests,mocks}__}/**/*.{js,json},./*.{js,json,yml}}' --write",
"lint": "eslint './*.{js,ts,tsx}' ./src",
"lint:fix": "eslint './*.{js,ts,tsx}' ./src --fix",
"lint:ts": "tsc",
"prettier:check": "prettier '{{src,bin,testUtils,__{tests,mocks}__}/**/*.{js,json,ts,tsx},./*.{js,json,ts,tsx,yml}}' --list-different",
"prettier:write": "prettier '{{src,bin,testUtils,__{tests,mocks}__}/**/*.{js,json,ts,tsx},./*.{js,json,ts,tsx,yml}}' --write",
"android": "react-native run-android",
"android:install:dev": "adb install android/app/build/outputs/apk/app-debug.apk",
"android:install:release": "adb install android/app/build/outputs/apk/app-release.apk",
Expand Down Expand Up @@ -82,6 +83,13 @@
"@babel/plugin-proposal-decorators": "^7.4.0",
"@babel/plugin-transform-runtime": "^7.4.3",
"@brainly/onesky-utils": "^1.3.1",
"@types/color": "^3.0.0",
"@types/jest": "^24.0.11",
"@types/react": "^16.8.14",
"@types/react-native": "^0.57.48",
"@types/react-redux": "^7.0.8",
"@typescript-eslint/eslint-plugin": "^1.7.0",
"@typescript-eslint/parser": "^1.7.0",
"appcenter-cli": "^1.1.15",
"babel-eslint": "^10.0.1",
"babel-jest": "^24.7.1",
Expand All @@ -102,7 +110,8 @@
"pretty-quick": "^1.10.0",
"react-dom": "^16.8.6",
"react-test-renderer": "^16.8.6",
"redux-mock-store": "^1.5.3"
"redux-mock-store": "^1.5.3",
"typescript": "^3.4.5"
},
"jest": {
"preset": "react-native",
Expand Down
14 changes: 14 additions & 0 deletions src/@types/react-native-default-preference/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
declare module 'react-native-default-preference' {
function get(key: String): Promise<String>;
function set(key: String, value: String): Promise<Void>;
function clear(key: String): Promise<Void>;
function getMultiple(keys: Array<String>): Promise<Array<String>>;
function setMultiple(data: Object): Promise<Void>;
function clearMultiple(keys: Array<String>): Promise<Void>;
function getAll(): Promise<Object>;
function clearAll(): Promise<Void>;

/** Gets and sets the current preferences file name (android) or user default suite name (ios) **/
function getName(): Promise<String>;
function setName(name: String): Promise<Void>;
}
7 changes: 7 additions & 0 deletions src/@types/react-native-omniture/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
declare module 'react-native-omniture' {
function trackAction(action: string, context: object);
function trackState(state: string, context: object);
function syncIdentifier(id: string | null);
function loadMarketingCloudId(callback: (id: string) => void);
function collectLifecycleData(lifecycleData: object);
}
23 changes: 15 additions & 8 deletions src/App.js → src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,15 @@ import { PersistGate } from 'redux-persist/integration/react';
deploymentKey: isAndroid
? Config.CODEPUSH_ANDROID_KEY
: Config.CODEPUSH_IOS_KEY,
checkFrequency: codePush.CheckFrequency.ON_APP_START,
})
export default class App extends Component {
showingErrorModal = false;
state = {
appState: AppState.currentState,
};

constructor(props) {
constructor(props: Readonly<{}>) {
super(props);
this.initializeErrorHandling();
}
Expand All @@ -62,7 +63,7 @@ export default class App extends Component {
const iOSKey = 'org.cru.missionhub.clientIdKey'; // key from the old iOS app
const androidKey = 'account.guest.secret'; // key from the old android app

const getKey = async key => {
const getKey = async (key: string) => {
const value = await DefaultPreference.get(key);
if (value) {
try {
Expand All @@ -88,14 +89,20 @@ export default class App extends Component {
}

initializeErrorHandling() {
window.onunhandledrejection = ({ reason }) => {
window.onunhandledrejection = ({ reason }: PromiseRejectionEvent) => {
this.handleError(reason);
};

ErrorUtils.setGlobalHandler(this.handleError);
}

handleError(e) {
handleError(e: {
apiError: any;
key?: string;
method?: string;
endpoint?: string;
query?: any;
}) {
const { apiError } = e;

if (apiError) {
Expand All @@ -115,7 +122,7 @@ export default class App extends Component {
} else {
rollbar.error(
Error(
`API Error: ${e.key} ${e.method.toUpperCase()} ${
`API Error: ${e.key} ${(e.method || '').toUpperCase()} ${
e.endpoint
}\n\nQuery Params:\n${JSON.stringify(
e.query,
Expand All @@ -131,7 +138,7 @@ export default class App extends Component {
rollbar.error(Error(`Unknown Error:\n${JSON.stringify(e, null, 2)}`));
}

LOG(e);
global.LOG(e);
}

showOfflineAlert = () => {
Expand All @@ -141,7 +148,7 @@ export default class App extends Component {
);
};

showAlert = (title, message) => {
showAlert = (title: string, message: string) => {
if (!this.showingErrorModal) {
this.showingErrorModal = true;

Expand All @@ -158,7 +165,7 @@ export default class App extends Component {
AppState.removeEventListener('change', this.handleAppStateChange);
}

handleAppStateChange = nextAppState => {
handleAppStateChange = (nextAppState: string) => {
if (
this.state.appState.match(/inactive|background/) &&
nextAppState === 'active'
Expand Down
38 changes: 23 additions & 15 deletions src/theme.js → src/theme.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Dimensions } from 'react-native';
import { Dimensions, StatusBarStyle } from 'react-native';
import Color from 'color';

import { exists, isAndroid, hasNotch } from './utils/common';
Expand All @@ -16,31 +16,38 @@ function colorConvert({
whiten,
blacken,
hex,
}: {
color: string;
alpha?: number;
lighten?: number;
darken?: number;
negate?: number;
rotate?: number;
whiten?: number;
blacken?: number;
hex?: boolean;
}) {
if (!color) {
LOG('Pass in a color!');
}
let col = Color(color);
// Lots of things you can do with color stuff
if (exists(alpha)) {
if (alpha) {
col = Color(col).alpha(alpha);
}
if (exists(lighten)) {
if (lighten) {
col = Color(col).lighten(lighten);
}
if (exists(darken)) {
if (darken) {
col = Color(col).darken(darken);
}
if (exists(negate)) {
if (negate) {
col = Color(col).negate();
}
if (exists(rotate)) {
if (rotate) {
col = Color(col).rotate(rotate);
}
if (exists(whiten)) {
if (whiten) {
col = Color(col).whiten(whiten);
}
if (exists(blacken)) {
if (blacken) {
col = Color(col).blacken(blacken);
}
if (hex === true) {
Expand Down Expand Up @@ -98,7 +105,6 @@ export default {
black: COLORS.BLACK,
backgroundColor: BACKGROUND,
textColor: COLORS.GREY,
darkText: COLORS.CHARCOAL,
iconColor: COLORS.WHITE,
transparent: COLORS.TRANSPARENT,
buttonHeight: 60,
Expand Down Expand Up @@ -137,12 +143,14 @@ export default {
statusBar: {
lightContent: {
...statusBar,
barStyle: 'light-content',
barStyle: 'light-content' as StatusBarStyle,
},
darkContent: {
...statusBar,
barStyle: isAndroid ? 'light-content' : 'dark-content',
barStyle: (isAndroid
? 'light-content'
: 'dark-content') as StatusBarStyle,
},
},
hitSlop: n => ({ top: n, right: n, left: n, bottom: n }),
hitSlop: (n: number) => ({ top: n, right: n, left: n, bottom: n }),
};
61 changes: 61 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"compilerOptions": {
/* Basic Options */
"target": "ES6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
// "lib": [" es2015" ] /* Specify library files to be included in the compilation. */,
"allowJs": true /* Allow javascript files to be compiled. */,
// "checkJs": true, /* Report errors in .js files. */
"jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */,
"skipLibCheck": true,
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "removeComments": true, /* Do not emit comments to output. */
"noEmit": true /* Do not emit outputs. */,
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
"typeRoots": [] /* List of folders to include type definitions from. */,
// "types": [], /* Type declaration files to be included in compilation. */
"allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
// "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
"experimentalDecorators": true /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}

0 comments on commit 27d90f7

Please sign in to comment.