diff --git a/.eslintrc.js b/.eslintrc.js index ac30525..ca9d164 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -69,7 +69,6 @@ module.exports = { 'error', { min: 2, exceptions: ['x', 'y', 'i', 'k', 'l', 'm', 'n', '$', '_'] }, ], - 'require-atomic-updates': 'warn', 'guard-for-in': ['error'], 'no-var': ['error'], 'prefer-const': ['error'], @@ -159,6 +158,8 @@ module.exports = { '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-use-before-define': 'off', '@typescript-eslint/ban-ts-ignore': 'off', + '@typescript-eslint/ban-ts-comment': 'off', + '@typescript-eslint/ban-types': 'off', '@typescript-eslint/no-empty-function': 'off', '@typescript-eslint/no-inferrable-types': 'off', '@typescript-eslint/no-unused-vars': [ diff --git a/.prettierignore b/.prettierignore index 4c2ad32..d8be4ed 100644 --- a/.prettierignore +++ b/.prettierignore @@ -7,3 +7,5 @@ cache *.png *.gif *.svg +*.hbs +.gitlab-ci.yml diff --git a/.storybook/config.tsx b/.storybook/config.tsx index e9eea65..85daf2f 100644 --- a/.storybook/config.tsx +++ b/.storybook/config.tsx @@ -5,7 +5,7 @@ import storyDecorator from './storyDecorator'; const req = require.context('../packages/app', true, /\.story\.[tj]sx?$/); function loadStories() { - req.keys().forEach(filename => req(filename)); + req.keys().forEach((filename) => req(filename)); } addDecorator(storyDecorator); diff --git a/.storybook/storyDecorator.tsx b/.storybook/storyDecorator.tsx index 5158493..5431c6a 100644 --- a/.storybook/storyDecorator.tsx +++ b/.storybook/storyDecorator.tsx @@ -9,7 +9,7 @@ import { IntlDecorator } from './decorators'; const store = storeFactory(); -export default (story => { +export default ((story) => { const channel = addons.getChannel(); return ( diff --git a/@types/cwordin-api.d.ts b/@types/cwordin-api.d.ts new file mode 100644 index 0000000..0ebb860 --- /dev/null +++ b/@types/cwordin-api.d.ts @@ -0,0 +1,102 @@ +declare module 'crowdin-api' { + export interface ProjectInfoFile { + node_type: 'file'; + id: number; + name: string; + created: string; + last_updated: string; + last_accessed: string; + last_revision: string; + } + + export interface ProjectInfoDirectory { + node_type: 'directory'; + id: number; + name: string; + files: Array; + } + + export interface ProjectInfoResponse { + details: { + source_language: { + name: string; + code: string; + }; + name: string; + identifier: string; + created: string; + description: string; + join_policy: string; + last_build: string | null; + last_activity: string; + participants_count: string; // it's number, but string in the response + logo_url: string | null; + total_strings_count: string; // it's number, but string in the response + total_words_count: string; // it's number, but string in the response + duplicate_strings_count: number; + duplicate_words_count: number; + invite_url: { + translator: string; + proofreader: string; + }; + }; + languages: Array<{ + name: string; // English language name + code: string; + can_translate: 0 | 1; + can_approve: 0 | 1; + }>; + files: Array; + } + + export interface LanguageStatusNode { + node_type: 'directory' | 'file'; + id: number; + name: string; + phrases: number; + translated: number; + approved: number; + words: number; + words_translated: number; + words_approved: number; + files: Array; + } + + export interface LanguageStatusResponse { + files: Array; + } + + type FilesList = Record; + + export default class CrowdinApi { + constructor(params: { + apiKey: string; + projectName: string; + baseUrl?: string; + }); + projectInfo(): Promise; + languageStatus(language: string): Promise; + exportFile( + file: string, + language: string, + params?: { + branch?: string; + format?: 'xliff'; + export_translated_only?: boolean; + export_approved_only?: boolean; + }, + ): Promise; // TODO: not sure about Promise return type + updateFile( + files: FilesList, + params: { + titles?: Record; + export_patterns?: Record; + new_names?: Record; + first_line_contains_header?: string; + scheme?: string; + update_option?: 'update_as_unapproved' | 'update_without_changes'; + branch?: string; + }, + ): Promise; + } +} diff --git a/@types/formatjs.d.ts b/@types/formatjs.d.ts new file mode 100644 index 0000000..273fbd7 --- /dev/null +++ b/@types/formatjs.d.ts @@ -0,0 +1,2 @@ +declare module '@formatjs/intl-pluralrules/polyfill' {} +declare module '@formatjs/intl-relativetimeformat/polyfill' {} diff --git a/@types/multi-progress.d.ts b/@types/multi-progress.d.ts new file mode 100644 index 0000000..b3ab5e5 --- /dev/null +++ b/@types/multi-progress.d.ts @@ -0,0 +1,13 @@ +declare module 'multi-progress' { + export default class MultiProgress { + constructor(stream?: string); + newBar( + schema: string, + options: ProgressBar.ProgressBarOptions, + ): ProgressBar; + terminate(): void; + move(index: number): void; + tick(index: number, value?: number, options?: any): void; + update(index: number, value?: number, options?: any): void; + } +} diff --git a/@types/prompt.d.ts b/@types/prompt.d.ts new file mode 100644 index 0000000..83bd868 --- /dev/null +++ b/@types/prompt.d.ts @@ -0,0 +1,66 @@ +// Type definitions for Prompt.js 1.0.0 +// Project: https://github.com/flatiron/prompt + +declare module 'prompt' { + type PropertiesType = + | Array + | prompt.PromptSchema + | Array; + + namespace prompt { + interface PromptSchema { + properties: PromptProperties; + } + + interface PromptProperties { + [propName: string]: PromptPropertyOptions; + } + + interface PromptPropertyOptions { + name?: string; + pattern?: RegExp; + message?: string; + required?: boolean; + hidden?: boolean; + description?: string; + type?: string; + default?: string; + before?: (value: any) => any; + conform?: (result: any) => boolean; + } + + export function start(): void; + + export function get( + properties: T, + callback: ( + err: Error, + result: T extends Array + ? Record + : T extends PromptSchema + ? Record + : T extends Array + ? Record< + T[number]['name'] extends string ? T[number]['name'] : number, + string + > + : never, + ) => void, + ): void; + + export function addProperties( + obj: any, + properties: PropertiesType, + callback: (err: Error) => void, + ): void; + + export function history(propertyName: string): any; + + export let override: any; + export let colors: boolean; + export let message: string; + export let delimiter: string; + } + + export = prompt; +} diff --git a/@types/redux-localstorage.d.ts b/@types/redux-localstorage.d.ts new file mode 100644 index 0000000..07130b3 --- /dev/null +++ b/@types/redux-localstorage.d.ts @@ -0,0 +1,25 @@ +// https://github.com/elgerlambert/redux-localstorage/issues/78#issuecomment-323609784 + +// import * as Redux from 'redux'; + +declare module 'redux-localstorage' { + export interface ConfigRS { + key: string; + merge?: any; + slicer?: any; + serialize?: ( + value: any, + replacer?: (key: string, value: any) => any, + space?: string | number, + ) => string; + deserialize?: ( + text: string, + reviver?: (key: any, value: any) => any, + ) => any; + } + + export default function persistState( + paths: string | string[], + config: ConfigRS, + ): () => any; +} diff --git a/@types/unexpected.d.ts b/@types/unexpected.d.ts new file mode 100644 index 0000000..491d67c --- /dev/null +++ b/@types/unexpected.d.ts @@ -0,0 +1,86 @@ +declare module 'unexpected' { + namespace unexpected { + interface EnchantedPromise extends Promise { + and = []>( + assertionName: string, + subject: unknown, + ...args: A + ): EnchantedPromise; + } + + interface Expect { + /** + * @see http://unexpected.js.org/api/expect/ + */ + = []>( + subject: unknown, + assertionName: string, + ...args: A + ): EnchantedPromise; + + it = []>( + assertionName: string, + subject?: unknown, + ...args: A + ): EnchantedPromise; + + /** + * @see http://unexpected.js.org/api/clone/ + */ + clone(): this; + + /** + * @see http://unexpected.js.org/api/addAssertion/ + */ + addAssertion = []>( + pattern: string, + handler: (expect: Expect, subject: T, ...args: A) => void, + ): this; + + /** + * @see http://unexpected.js.org/api/addType/ + */ + addType(typeDefinition: unexpected.TypeDefinition): this; + + /** + * @see http://unexpected.js.org/api/fail/ + */ + fail = []>(format: string, ...args: A): void; + fail(error: E): void; + + /** + * @see http://unexpected.js.org/api/freeze/ + */ + freeze(): this; + + /** + * @see http://unexpected.js.org/api/use/ + */ + use(plugin: unexpected.PluginDefinition): this; + } + + interface PluginDefinition { + name?: string; + version?: string; + dependencies?: Array; + installInto(expect: Expect): void; + } + + interface TypeDefinition { + name: string; + identify(value: unknown): value is T; + base?: string; + equal?(a: T, b: T, equal: (a: unknown, b: unknown) => boolean): boolean; + inspect?( + value: T, + depth: number, + output: any, + inspect: (value: unknown, depth: number) => any, + ): void; + } + } + + const unexpected: unexpected.Expect; + + export = unexpected; +} diff --git a/@types/webpack-loaders.d.ts b/@types/webpack-loaders.d.ts index 2948cb9..b198f9a 100644 --- a/@types/webpack-loaders.d.ts +++ b/@types/webpack-loaders.d.ts @@ -26,9 +26,7 @@ declare module '*.jpg' { declare module '*.intl.json' { import { MessageDescriptor } from 'react-intl'; - const descriptor: { - [key: string]: MessageDescriptor; - }; + const descriptor: Record; export = descriptor; } diff --git a/jest/setupAfterEnv.js b/jest/setupAfterEnv.js index a89a3a6..a267223 100644 --- a/jest/setupAfterEnv.js +++ b/jest/setupAfterEnv.js @@ -1,8 +1,5 @@ import 'app/polyfills'; -import { configure } from 'enzyme'; -import Adapter from 'enzyme-adapter-react-16'; - -configure({ adapter: new Adapter() }); +import '@testing-library/jest-dom'; if (!window.localStorage) { window.localStorage = { diff --git a/package.json b/package.json index 10e15d9..cc1f83e 100644 --- a/package.json +++ b/package.json @@ -28,21 +28,21 @@ "e2e": "yarn --cwd ./tests-e2e test", "test": "jest", "test:watch": "yarn test --watch", - "lint": "eslint --ext js,ts,tsx --fix --quiet .", + "lint": "eslint --ext js,ts,tsx --fix .", "lint:check": "eslint --ext js,ts,tsx --quiet .", - "prettier": "prettier --write \"{packages/**/*,tests-e2e/**/*,jest/**/*,config/**/*,*}.{js,ts,tsx,json,md,scss,css}\"", - "prettier:check": "prettier --check \"{packages/**/*,tests-e2e/**/*,jest/**/*,config/**/*,*}.{js,ts,tsx,json,md,scss,css}\"", + "prettier": "prettier --write .", + "prettier:check": "prettier --check .", "ts:check": "tsc", "ci:check": "yarn lint:check && yarn ts:check && yarn test", "analyze": "yarn run clean && yarn run build:webpack --analyze", - "i18n:collect": "babel-node ./packages/scripts/i18n-collect.js", - "i18n:push": "babel-node ./packages/scripts/i18n-crowdin.js push", - "i18n:pull": "babel-node ./packages/scripts/i18n-crowdin.js pull", + "i18n:collect": "babel-node --extensions \".ts\" ./packages/scripts/i18n-collect.ts", + "i18n:push": "babel-node --extensions \".ts\" ./packages/scripts/i18n-crowdin.ts push", + "i18n:pull": "babel-node --extensions \".ts\" ./packages/scripts/i18n-crowdin.ts pull", "build": "yarn run clean && yarn run build:webpack", "build:install": "yarn install", "build:webpack": "NODE_ENV=production webpack --colors -p --bail", "build:quiet": "yarn run clean && yarn run build:webpack --quiet", - "build:dll": "node ./packages/scripts/build-dll.js", + "build:dll": "babel-node --extensions '.ts,.d.ts' ./packages/scripts/build-dll.ts", "build:serve": "http-server --proxy https://dev.account.ely.by ./build", "sb": "APP_ENV=storybook start-storybook -p 9009 --ci", "sb:build": "APP_ENV=storybook build-storybook" @@ -55,12 +55,10 @@ }, "lint-staged": { "*.{json,scss,css,md}": [ - "prettier --write", - "git add" + "prettier --write" ], "*.{js,ts,tsx}": [ - "eslint --fix --quiet", - "git add" + "eslint --fix" ] }, "jest": { @@ -71,7 +69,6 @@ "/jest/setupAfterEnv.js" ], "resetMocks": true, - "resetModules": true, "restoreMocks": true, "watchPlugins": [ "jest-watch-typeahead/filename", @@ -86,13 +83,11 @@ "^.+\\.[tj]sx?$": "babel-jest" } }, - "resolutions": { - "@types/node": "^12.0.0" - }, "dependencies": { - "react": "^16.12.0", - "react-dom": "^16.12.0", - "react-intl": "^3.11.0", + "react": "^16.13.1", + "react-dom": "^16.13.1", + "react-hot-loader": "^4.12.18", + "react-intl": "^4.5.7", "regenerator-runtime": "^0.13.3" }, "devDependencies": { @@ -118,60 +113,60 @@ "@babel/preset-react": "^7.8.3", "@babel/preset-typescript": "^7.8.3", "@babel/runtime-corejs3": "^7.8.3", - "@storybook/addon-actions": "^5.3.4", - "@storybook/addon-links": "^5.3.4", - "@storybook/addon-viewport": "^5.3.4", - "@storybook/addons": "^5.3.4", - "@storybook/react": "^5.3.4", - "@types/jest": "^24.9.0", - "@typescript-eslint/eslint-plugin": "^2.16.0", - "@typescript-eslint/parser": "^2.16.0", + "@storybook/addon-actions": "^5.3.18", + "@storybook/addon-links": "^5.3.18", + "@storybook/addon-viewport": "^5.3.18", + "@storybook/addons": "^5.3.18", + "@storybook/react": "^5.3.18", + "@types/jest": "^25.2.3", + "@types/sinon": "^9.0.3", + "@typescript-eslint/eslint-plugin": "^3.0.0", + "@typescript-eslint/parser": "^3.0.0", "babel-loader": "^8.0.0", - "babel-plugin-react-intl": "^5.1.16", - "core-js": "3.6.4", + "babel-plugin-react-intl": "^7.5.10", + "core-js": "3.6.5", "csp-webpack-plugin": "^2.0.2", - "css-loader": "^3.4.2", + "css-loader": "^3.5.3", "cssnano": "^4.1.10", "dotenv": "^8.2.0", "eager-imports-webpack-plugin": "^1.0.0", - "eslint": "^6.8.0", - "eslint-config-prettier": "^6.9.0", - "eslint-plugin-jsdoc": "^20.3.1", - "eslint-plugin-prettier": "^3.1.2", - "eslint-plugin-react": "^7.18.0", + "eslint": "^7.0.0", + "eslint-config-prettier": "^6.11.0", + "eslint-plugin-jsdoc": "^25.4.2", + "eslint-plugin-prettier": "^3.1.3", + "eslint-plugin-react": "^7.20.0", "exports-loader": "^0.7.0", - "file-loader": "^5.0.2", - "html-loader": "^0.5.5", - "html-webpack-plugin": "^3.2.0", - "husky": "^4.0.10", + "file-loader": "^6.0.0", + "html-loader": "^1.1.0", + "html-webpack-plugin": "^4.3.0", + "husky": "^4.2.5", "identity-obj-proxy": "^3.0.0", "imports-loader": "^0.8.0", - "jest": "^24.9.0", - "jest-watch-typeahead": "^0.4.2", + "jest": "^26.0.1", + "jest-watch-typeahead": "^0.6.0", "json-loader": "^0.5.4", - "lint-staged": "^9.5.0", - "loader-utils": "^1.0.0", + "lint-staged": "^10.2.4", + "loader-utils": "^2.0.0", "mini-css-extract-plugin": "^0.9.0", - "node-sass": "^4.13.0", + "node-sass": "^4.14.1", "postcss-import": "^12.0.1", "postcss-loader": "^3.0.0", - "postcss-scss": "^2.0.0", - "prettier": "^1.19.1", - "raw-loader": "^4.0.0", - "react-test-renderer": "^16.12.0", + "postcss-scss": "^2.1.1", + "prettier": "^2.0.5", + "raw-loader": "^4.0.1", "sass-loader": "^8.0.2", - "sinon": "^8.0.4", - "sitemap-webpack-plugin": "^0.6.0", - "speed-measure-webpack-plugin": "^1.3.1", + "sinon": "^9.0.2", + "sitemap-webpack-plugin": "^0.8.0", + "speed-measure-webpack-plugin": "^1.3.3", "storybook-addon-intl": "^2.4.1", - "style-loader": "~1.1.2", - "typescript": "^3.7.4", - "unexpected": "^11.12.1", + "style-loader": "~1.2.1", + "typescript": "^3.9.3", + "unexpected": "^11.14.0", "unexpected-sinon": "^10.5.1", - "url-loader": "^3.0.0", - "wait-on": "^3.3.0", + "url-loader": "^4.1.0", + "wait-on": "^5.0.0", "webpack": "^4.41.5", - "webpack-bundle-analyzer": "^3.6.0", + "webpack-bundle-analyzer": "^3.8.0", "webpack-cli": "^3.3.10", "webpack-dev-server": "^3.10.1", "webpackbar": "^4.0.0" diff --git a/packages/app/components/accounts/AccountSwitcher.tsx b/packages/app/components/accounts/AccountSwitcher.tsx index a30e056..cca5873 100644 --- a/packages/app/components/accounts/AccountSwitcher.tsx +++ b/packages/app/components/accounts/AccountSwitcher.tsx @@ -3,7 +3,7 @@ import { connect } from 'react-redux'; import clsx from 'clsx'; import { Link } from 'react-router-dom'; import { FormattedMessage as Message } from 'react-intl'; -import loader from 'app/services/loader'; +import * as loader from 'app/services/loader'; import { SKIN_DARK, COLOR_WHITE, Skin } from 'app/components/ui'; import { Button } from 'app/components/ui/form'; import { authenticate, revoke } from 'app/components/accounts/actions'; @@ -57,7 +57,9 @@ export class AccountSwitcher extends React.Component { let { available } = accounts; if (highlightActiveAccount) { - available = available.filter(account => account.id !== activeAccount.id); + available = available.filter( + (account) => account.id !== activeAccount.id, + ); } return ( @@ -152,7 +154,7 @@ export class AccountSwitcher extends React.Component { className={styles.addAccount} label={ - {message => ( + {(message) => (
{message} @@ -167,7 +169,7 @@ export class AccountSwitcher extends React.Component { ); } - onSwitch = (account: Account) => (event: React.MouseEvent) => { + onSwitch = (account: Account) => (event: React.MouseEvent) => { event.preventDefault(); loader.show(); @@ -178,11 +180,11 @@ export class AccountSwitcher extends React.Component { .then(() => this.props.onSwitch(account)) // we won't sent any logs to sentry, because an error should be already // handled by external logic - .catch(error => console.warn('Error switching account', { error })) + .catch((error) => console.warn('Error switching account', { error })) .finally(() => loader.hide()); }; - onRemove = (account: Account) => (event: React.MouseEvent) => { + onRemove = (account: Account) => (event: React.MouseEvent) => { event.preventDefault(); event.stopPropagation(); diff --git a/packages/app/components/accounts/actions.test.ts b/packages/app/components/accounts/actions.test.ts index 11a16e7..63a9891 100644 --- a/packages/app/components/accounts/actions.test.ts +++ b/packages/app/components/accounts/actions.test.ts @@ -12,13 +12,10 @@ import { } from 'app/components/accounts/actions'; import { add, - ADD, activate, - ACTIVATE, remove, reset, } from 'app/components/accounts/actions/pure-actions'; -import { SET_LOCALE } from 'app/components/i18n/actions'; import { updateUser, setUser } from 'app/components/user/actions'; import { setLogin, setAccountSwitcher } from 'app/components/auth/actions'; import { Dispatch, RootState } from 'app/reducers'; @@ -51,7 +48,7 @@ describe('components/accounts/actions', () => { beforeEach(() => { dispatch = sinon - .spy(arg => (typeof arg === 'function' ? arg(dispatch, getState) : arg)) + .spy((arg) => (typeof arg === 'function' ? arg(dispatch, getState) : arg)) .named('store.dispatch'); getState = sinon.stub().named('store.getState'); @@ -124,20 +121,20 @@ describe('components/accounts/actions', () => { ]), )); - it(`dispatches ${ADD} action`, () => + it(`dispatches accounts:add action`, () => authenticate(account)(dispatch, getState, undefined).then(() => expect(dispatch, 'to have a call satisfying', [add(account)]), )); - it(`dispatches ${ACTIVATE} action`, () => + it(`dispatches accounts:activate action`, () => authenticate(account)(dispatch, getState, undefined).then(() => expect(dispatch, 'to have a call satisfying', [activate(account)]), )); - it(`dispatches ${SET_LOCALE} action`, () => + it(`dispatches i18n:setLocale action`, () => authenticate(account)(dispatch, getState, undefined).then(() => expect(dispatch, 'to have a call satisfying', [ - { type: SET_LOCALE, payload: { locale: 'be' } }, + { type: 'i18n:setLocale', payload: { locale: 'be' } }, ]), )); @@ -149,7 +146,7 @@ describe('components/accounts/actions', () => { )); it('resolves with account', () => - authenticate(account)(dispatch, getState, undefined).then(resp => + authenticate(account)(dispatch, getState, undefined).then((resp) => expect(resp, 'to equal', account), )); @@ -479,7 +476,7 @@ describe('components/accounts/actions', () => { const key = `stranger${foreignAccount.id}`; beforeEach(() => { - sessionStorage.setItem(key, 1); + sessionStorage.setItem(key, '1'); logoutStrangers()(dispatch, getState, undefined); }); diff --git a/packages/app/components/accounts/actions.ts b/packages/app/components/accounts/actions.ts index 1c2c5d1..17d7b43 100644 --- a/packages/app/components/accounts/actions.ts +++ b/packages/app/components/accounts/actions.ts @@ -53,7 +53,7 @@ export function authenticate( } const knownAccount = getState().accounts.available.find( - item => item.id === accountId, + (item) => item.id === accountId, ); if (knownAccount) { @@ -90,7 +90,7 @@ export function authenticate( if (!newRefreshToken) { // mark user as stranger (user does not want us to remember his account) - sessionStorage.setItem(`stranger${newAccount.id}`, 1); + sessionStorage.setItem(`stranger${newAccount.id}`, '1'); } if (auth && auth.oauth && auth.oauth.clientId) { @@ -246,10 +246,10 @@ export function requestNewToken(): ThunkAction> { } return requestToken(refreshToken) - .then(token => { + .then((token) => { dispatch(updateToken(token)); }) - .catch(resp => { + .catch((resp) => { // all the logic to get the valid token was failed, // looks like we have some problems with token // lets redirect to login page @@ -313,7 +313,7 @@ export function logoutAll(): ThunkAction> { accounts: { available }, } = getState(); - available.forEach(account => + available.forEach((account) => logout(account.token).catch(() => { // we don't care }), @@ -345,10 +345,12 @@ export function logoutStrangers(): ThunkAction> { !refreshToken && !sessionStorage.getItem(`stranger${id}`); if (available.some(isStranger)) { - const accountToReplace = available.find(account => !isStranger(account)); + const accountToReplace = available.find( + (account) => !isStranger(account), + ); if (accountToReplace) { - available.filter(isStranger).forEach(account => { + available.filter(isStranger).forEach((account) => { dispatch(remove(account)); logout(account.token); }); diff --git a/packages/app/components/accounts/actions/pure-actions.ts b/packages/app/components/accounts/actions/pure-actions.ts index 3859f5c..c65d464 100644 --- a/packages/app/components/accounts/actions/pure-actions.ts +++ b/packages/app/components/accounts/actions/pure-actions.ts @@ -1,78 +1,67 @@ -import { - Account, - AddAction, - RemoveAction, - ActivateAction, - UpdateTokenAction, - ResetAction, -} from '../reducer'; +import { Action as ReduxAction } from 'redux'; +import { Account } from 'app/components/accounts/reducer'; + +interface AddAction extends ReduxAction { + type: 'accounts:add'; + payload: Account; +} -export const ADD = 'accounts:add'; -/** - * @private - * - * @param {Account} account - * - * @returns {object} - action definition - */ export function add(account: Account): AddAction { return { - type: ADD, + type: 'accounts:add', payload: account, }; } -export const REMOVE = 'accounts:remove'; -/** - * @private - * - * @param {Account} account - * - * @returns {object} - action definition - */ +interface RemoveAction extends ReduxAction { + type: 'accounts:remove'; + payload: Account; +} + export function remove(account: Account): RemoveAction { return { - type: REMOVE, + type: 'accounts:remove', payload: account, }; } -export const ACTIVATE = 'accounts:activate'; -/** - * @private - * - * @param {Account} account - * - * @returns {object} - action definition - */ +interface ActivateAction extends ReduxAction { + type: 'accounts:activate'; + payload: Account; +} + export function activate(account: Account): ActivateAction { return { - type: ACTIVATE, + type: 'accounts:activate', payload: account, }; } -export const RESET = 'accounts:reset'; -/** - * @private - * - * @returns {object} - action definition - */ +interface ResetAction extends ReduxAction { + type: 'accounts:reset'; +} + export function reset(): ResetAction { return { - type: RESET, + type: 'accounts:reset', }; } -export const UPDATE_TOKEN = 'accounts:updateToken'; -/** - * @param {string} token - * - * @returns {object} - action definition - */ +interface UpdateTokenAction extends ReduxAction { + type: 'accounts:updateToken'; + payload: string; +} + export function updateToken(token: string): UpdateTokenAction { return { - type: UPDATE_TOKEN, + type: 'accounts:updateToken', payload: token, }; } + +export type Action = + | AddAction + | RemoveAction + | ActivateAction + | ResetAction + | UpdateTokenAction; diff --git a/packages/app/components/accounts/reducer.test.ts b/packages/app/components/accounts/reducer.test.ts index c4f5fa9..4ec1c47 100644 --- a/packages/app/components/accounts/reducer.test.ts +++ b/packages/app/components/accounts/reducer.test.ts @@ -1,17 +1,8 @@ import expect from 'app/test/unexpected'; import { updateToken } from './actions'; -import { - add, - remove, - activate, - reset, - ADD, - REMOVE, - ACTIVATE, - UPDATE_TOKEN, - RESET, -} from './actions/pure-actions'; +import { add, remove, activate, reset } from './actions/pure-actions'; +import { AccountsState } from './index'; import accounts, { Account } from './reducer'; const account: Account = { @@ -22,7 +13,7 @@ const account: Account = { } as Account; describe('Accounts reducer', () => { - let initial; + let initial: AccountsState; beforeEach(() => { initial = accounts(undefined, {} as any); @@ -39,7 +30,7 @@ describe('Accounts reducer', () => { state: 'foo', })); - describe(ACTIVATE, () => { + describe('accounts:activate', () => { it('sets active account', () => { expect(accounts(initial, activate(account)), 'to satisfy', { active: account.id, @@ -47,7 +38,7 @@ describe('Accounts reducer', () => { }); }); - describe(ADD, () => { + describe('accounts:add', () => { it('adds an account', () => expect(accounts(initial, add(account)), 'to satisfy', { available: [account], @@ -106,7 +97,7 @@ describe('Accounts reducer', () => { }); }); - describe(REMOVE, () => { + describe('accounts:remove', () => { it('should remove an account', () => expect( accounts({ ...initial, available: [account] }, remove(account)), @@ -128,7 +119,7 @@ describe('Accounts reducer', () => { }); }); - describe(RESET, () => { + describe('actions:reset', () => { it('should reset accounts state', () => expect( accounts({ ...initial, available: [account] }, reset()), @@ -137,7 +128,7 @@ describe('Accounts reducer', () => { )); }); - describe(UPDATE_TOKEN, () => { + describe('accounts:updateToken', () => { it('should update token', () => { const newToken = 'newToken'; diff --git a/packages/app/components/accounts/reducer.ts b/packages/app/components/accounts/reducer.ts index c18bd16..f34799a 100644 --- a/packages/app/components/accounts/reducer.ts +++ b/packages/app/components/accounts/reducer.ts @@ -1,3 +1,5 @@ +import { Action } from './actions/pure-actions'; + export type Account = { id: number; username: string; @@ -8,30 +10,14 @@ export type Account = { export type State = { active: number | null; - available: Account[]; + available: Array; }; -export type AddAction = { type: 'accounts:add'; payload: Account }; -export type RemoveAction = { type: 'accounts:remove'; payload: Account }; -export type ActivateAction = { type: 'accounts:activate'; payload: Account }; -export type UpdateTokenAction = { - type: 'accounts:updateToken'; - payload: string; -}; -export type ResetAction = { type: 'accounts:reset' }; - -type Action = - | AddAction - | RemoveAction - | ActivateAction - | UpdateTokenAction - | ResetAction; - export function getActiveAccount(state: { accounts: State }): Account | null { const accountId = state.accounts.active; return ( - state.accounts.available.find(account => account.id === accountId) || null + state.accounts.available.find((account) => account.id === accountId) || null ); } @@ -57,7 +43,7 @@ export default function accounts( const { payload } = action; state.available = state.available - .filter(account => account.id !== payload.id) + .filter((account) => account.id !== payload.id) .concat(payload); state.available.sort((account1, account2) => { @@ -79,7 +65,7 @@ export default function accounts( const { payload } = action; return { - available: state.available.map(account => { + available: state.available.map((account) => { if (account.id === payload.id) { return { ...payload }; } @@ -105,7 +91,9 @@ export default function accounts( return { ...state, - available: state.available.filter(account => account.id !== payload.id), + available: state.available.filter( + (account) => account.id !== payload.id, + ), }; } @@ -118,7 +106,7 @@ export default function accounts( return { ...state, - available: state.available.map(account => { + available: state.available.map((account) => { if (account.id === state.active) { return { ...account, diff --git a/packages/app/components/auth/AuthTitle.tsx b/packages/app/components/auth/AuthTitle.tsx index c51028d..2557e2c 100644 --- a/packages/app/components/auth/AuthTitle.tsx +++ b/packages/app/components/auth/AuthTitle.tsx @@ -5,7 +5,7 @@ import { FormattedMessage as Message, MessageDescriptor } from 'react-intl'; export default function AuthTitle({ title }: { title: MessageDescriptor }) { return ( - {msg => ( + {(msg) => ( {msg} diff --git a/packages/app/components/auth/BaseAuthBody.tsx b/packages/app/components/auth/BaseAuthBody.tsx index 07228ee..7692663 100644 --- a/packages/app/components/auth/BaseAuthBody.tsx +++ b/packages/app/components/auth/BaseAuthBody.tsx @@ -1,7 +1,8 @@ -import React from 'react'; +import React, { ReactNode } from 'react'; +import { RouteComponentProps } from 'react-router-dom'; + import AuthError from 'app/components/auth/authError/AuthError'; import { FormModel } from 'app/components/ui/form'; -import { RouteComponentProps } from 'react-router-dom'; import Context, { AuthContext } from './Context'; @@ -11,7 +12,7 @@ import Context, { AuthContext } from './Context'; class BaseAuthBody extends React.Component< // TODO: this may be converted to generic type RouteComponentProps - RouteComponentProps<{ [key: string]: any }> + RouteComponentProps> > { static contextType = Context; /* TODO: use declare */ context: React.ContextType; @@ -32,10 +33,14 @@ class BaseAuthBody extends React.Component< this.prevErrors = this.context.auth.error; } - renderErrors() { + renderErrors(): ReactNode { const error = this.form.getFirstError(); - return error && ; + if (error === null) { + return null; + } + + return ; } onFormSubmit() { diff --git a/packages/app/components/auth/PanelTransition.tsx b/packages/app/components/auth/PanelTransition.tsx index 5e1a88e..6279498 100644 --- a/packages/app/components/auth/PanelTransition.tsx +++ b/packages/app/components/auth/PanelTransition.tsx @@ -1,8 +1,20 @@ -import React from 'react'; +import React, { + CSSProperties, + MouseEventHandler, + ReactElement, + ReactNode, +} from 'react'; import { AccountsState } from 'app/components/accounts'; import { User } from 'app/components/user'; import { connect } from 'react-redux'; -import { TransitionMotion, spring } from 'react-motion'; +import { + TransitionMotion, + spring, + PlainStyle, + Style, + TransitionStyle, + TransitionPlainStyle, +} from 'react-motion'; import { Panel, PanelBody, @@ -44,7 +56,7 @@ type PanelId = string; * - Panel index defines the direction of X transition of both panels * (e.g. the panel with lower index will slide from left side, and with greater from right side) */ -const contexts: Array = [ +const contexts: Array> = [ ['login', 'password', 'forgotPassword', 'mfa', 'recoverPassword'], ['register', 'activation', 'resendActivation'], ['acceptRules'], @@ -57,7 +69,7 @@ if (process.env.NODE_ENV !== 'production') { // TODO: it may be moved to tests in future contexts.reduce((acc, context) => { - context.forEach(panel => { + context.forEach((panel) => { if (acc[panel]) { throw new Error( `Panel ${panel} is already exists in context ${JSON.stringify( @@ -70,40 +82,41 @@ if (process.env.NODE_ENV !== 'production') { }); return acc; - }, {}); + }, {} as Record>); } type ValidationError = | string | { type: string; - payload: { [key: string]: any }; + payload: Record; }; -type AnimationProps = { +interface AnimationStyle extends PlainStyle { opacitySpring: number; transformSpring: number; -}; +} -type AnimationContext = { +interface AnimationData { + Title: ReactElement; + Body: ReactElement; + Footer: ReactElement; + Links: ReactNode; + hasBackButton: boolean | ((props: Props) => boolean); +} + +interface AnimationContext extends TransitionPlainStyle { key: PanelId; - style: AnimationProps; - data: { - Title: React.ReactElement; - Body: React.ReactElement; - Footer: React.ReactElement; - Links: React.ReactElement; - hasBackButton: boolean | ((props: Props) => boolean); - }; -}; + style: AnimationStyle; + data: AnimationData; +} -type OwnProps = { - Title: React.ReactElement; - Body: React.ReactElement; - Footer: React.ReactElement; - Links: React.ReactElement; - children?: React.ReactElement; -}; +interface OwnProps { + Title: ReactElement; + Body: ReactElement; + Footer: ReactElement; + Links: ReactNode; +} interface Props extends OwnProps { // context props @@ -114,17 +127,18 @@ interface Props extends OwnProps { resolve: () => void; reject: () => void; - setErrors: (errors: { [key: string]: ValidationError }) => void; + setErrors: (errors: Record) => void; } -type State = { +interface State { contextHeight: number; panelId: PanelId | void; prevPanelId: PanelId | void; isHeightDirty: boolean; forceHeight: 1 | 0; direction: 'X' | 'Y'; -}; + formsHeights: Record; +} class PanelTransition extends React.PureComponent { state: State = { @@ -134,16 +148,17 @@ class PanelTransition extends React.PureComponent { forceHeight: 0 as const, direction: 'X' as const, prevPanelId: undefined, + formsHeights: {}, }; isHeightMeasured: boolean = false; wasAutoFocused: boolean = false; - body: null | { + body: { autoFocus: () => void; onFormSubmit: () => void; - } = null; + } | null = null; - timerIds: NodeJS.Timeout[] = []; // this is a list of a probably running timeouts to clean on unmount + timerIds: Array = []; // this is a list of a probably running timeouts to clean on unmount componentDidUpdate(prevProps: Props) { const nextPanel: PanelId = @@ -166,7 +181,8 @@ class PanelTransition extends React.PureComponent { if (forceHeight) { this.timerIds.push( - setTimeout(() => { + // https://stackoverflow.com/a/51040768/5184751 + window.setTimeout(() => { this.setState({ forceHeight: 0 }); }, 100), ); @@ -175,7 +191,7 @@ class PanelTransition extends React.PureComponent { } componentWillUnmount() { - this.timerIds.forEach(id => clearTimeout(id)); + this.timerIds.forEach((id) => clearTimeout(id)); this.timerIds = []; } @@ -208,7 +224,7 @@ class PanelTransition extends React.PureComponent { hasGoBack: boolean; } = Body.type as any; - const formHeight = this.state[`formHeight${panelId}`] || 0; + const formHeight = this.state.formsHeights[panelId] || 0; // a hack to disable height animation on first render const { isHeightMeasured } = this; @@ -251,7 +267,7 @@ class PanelTransition extends React.PureComponent { willEnter={this.willEnter} willLeave={this.willLeave} > - {items => { + {(items) => { const panels = items.filter(({ key }) => key !== 'common'); const [common] = items.filter(({ key }) => key === 'common'); @@ -278,7 +294,7 @@ class PanelTransition extends React.PureComponent { > - {panels.map(config => this.getHeader(config))} + {panels.map((config) => this.getHeader(config))}
{ >
- {panels.map(config => this.getBody(config))} + {panels.map((config) => this.getBody(config))}
- {panels.map(config => this.getFooter(config))} + {panels.map((config) => this.getFooter(config))}
@@ -300,7 +316,7 @@ class PanelTransition extends React.PureComponent { className={helpLinksStyles} data-testid="auth-controls-secondary" > - {panels.map(config => this.getLinks(config))} + {panels.map((config) => this.getLinks(config))}
); @@ -310,7 +326,7 @@ class PanelTransition extends React.PureComponent { ); } - onFormSubmit = () => { + onFormSubmit = (): void => { this.props.clearErrors(); if (this.body) { @@ -318,35 +334,34 @@ class PanelTransition extends React.PureComponent { } }; - onFormInvalid = (errors: { [key: string]: ValidationError }) => + onFormInvalid = (errors: Record): void => this.props.setErrors(errors); - willEnter = (config: AnimationContext) => this.getTransitionStyles(config); - willLeave = (config: AnimationContext) => - this.getTransitionStyles(config, { isLeave: true }); + willEnter = (config: TransitionStyle): PlainStyle => { + const transform = this.getTransformForPanel(config.key); - /** - * @param {object} config - * @param {string} config.key - * @param {object} [options] - * @param {object} [options.isLeave=false] - true, if this is a leave transition - * - * @returns {object} - */ - getTransitionStyles( - { key }: AnimationContext, - options: { isLeave?: boolean } = {}, - ): { - transformSpring: number; - opacitySpring: number; - } { - const { isLeave = false } = options; + return { + transformSpring: transform, + opacitySpring: 1, + }; + }; + + willLeave = (config: TransitionStyle): Style => { + const transform = this.getTransformForPanel(config.key); + + return { + transformSpring: spring(transform, transformSpringConfig), + opacitySpring: spring(0, opacitySpringConfig), + }; + }; + + getTransformForPanel(key: PanelId): number { const { panelId, prevPanelId } = this.state; const fromLeft = -1; const fromRight = 1; - const currentContext = contexts.find(context => context.includes(key)); + const currentContext = contexts.find((context) => context.includes(key)); if (!currentContext) { throw new Error(`Can not find settings for ${key} panel`); @@ -363,18 +378,11 @@ class PanelTransition extends React.PureComponent { sign *= -1; } - const transform = sign * 100; - - return { - transformSpring: isLeave - ? spring(transform, transformSpringConfig) - : transform, - opacitySpring: isLeave ? spring(0, opacitySpringConfig) : 1, - }; + return sign * 100; } getDirection(next: PanelId, prev: PanelId): 'X' | 'Y' { - const context = contexts.find(item => item.includes(prev)); + const context = contexts.find((item) => item.includes(prev)); if (!context) { throw new Error(`Can not find context for transition ${prev} -> ${next}`); @@ -383,24 +391,23 @@ class PanelTransition extends React.PureComponent { return context.includes(next) ? 'X' : 'Y'; } - onUpdateHeight = (height: number, key: PanelId) => { - const heightKey = `formHeight${key}`; - - // @ts-ignore + onUpdateHeight = (height: number, key: PanelId): void => { this.setState({ - [heightKey]: height, + formsHeights: { + ...this.state.formsHeights, + [key]: height, + }, }); }; - onUpdateContextHeight = (height: number) => { + onUpdateContextHeight = (height: number): void => { this.setState({ contextHeight: height, }); }; - onGoBack = (event: React.MouseEvent) => { + onGoBack: MouseEventHandler = (event): void => { event.preventDefault(); - authFlow.goBack(); }; @@ -409,7 +416,7 @@ class PanelTransition extends React.PureComponent { * * @param {number} length number of panels transitioned */ - tryToAutoFocus(length: number) { + tryToAutoFocus(length: number): void { if (!this.body) { return; } @@ -425,20 +432,17 @@ class PanelTransition extends React.PureComponent { } } - shouldMeasureHeight() { + shouldMeasureHeight(): string { const { user, accounts, auth } = this.props; const { isHeightDirty } = this.state; - const errorString = Object.values(auth.error || {}).reduce( - (acc: string, item: ValidationError): string => { - if (typeof item === 'string') { - return acc + item; - } + const errorString = Object.values(auth.error || {}).reduce((acc, item) => { + if (typeof item === 'string') { + return acc + item; + } - return acc + item.type; - }, - '', - ) as string; + return acc + item.type; + }, '') as string; return [ errorString, @@ -448,9 +452,9 @@ class PanelTransition extends React.PureComponent { ].join(''); } - getHeader({ key, style, data }: AnimationContext) { - const { Title } = data; - const { transformSpring } = style; + getHeader({ key, style, data }: TransitionPlainStyle): ReactElement { + const { Title } = data as AnimationData; + const { transformSpring } = (style as unknown) as AnimationStyle; let { hasBackButton } = data; @@ -459,7 +463,10 @@ class PanelTransition extends React.PureComponent { } const transitionStyle = { - ...this.getDefaultTransitionStyles(key, style), + ...this.getDefaultTransitionStyles( + key, + (style as unknown) as AnimationStyle, + ), opacity: 1, // reset default }; @@ -491,15 +498,12 @@ class PanelTransition extends React.PureComponent { ); } - getBody({ key, style, data }: AnimationContext) { - const { Body } = data; - const { transformSpring } = style; + getBody({ key, style, data }: TransitionPlainStyle): ReactElement { + const { Body } = data as AnimationData; + const { transformSpring } = (style as unknown) as AnimationStyle; const { direction } = this.state; - let transform: { [key: string]: string } = this.translate( - transformSpring, - direction, - ); + let transform = this.translate(transformSpring, direction); let verticalOrigin = 'top'; if (direction === 'Y') { @@ -507,8 +511,11 @@ class PanelTransition extends React.PureComponent { transform = {}; } - const transitionStyle = { - ...this.getDefaultTransitionStyles(key, style), + const transitionStyle: CSSProperties = { + ...this.getDefaultTransitionStyles( + key, + (style as unknown) as AnimationStyle, + ), top: 'auto', // reset default [verticalOrigin]: 0, ...transform, @@ -519,10 +526,11 @@ class PanelTransition extends React.PureComponent { key={`body/${key}`} style={transitionStyle} state={this.shouldMeasureHeight()} - onMeasure={height => this.onUpdateHeight(height, key)} + onMeasure={(height) => this.onUpdateHeight(height, key)} > {React.cloneElement(Body, { - ref: body => { + // @ts-ignore + ref: (body) => { this.body = body; }, })} @@ -530,10 +538,13 @@ class PanelTransition extends React.PureComponent { ); } - getFooter({ key, style, data }: AnimationContext) { - const { Footer } = data; + getFooter({ key, style, data }: TransitionPlainStyle): ReactElement { + const { Footer } = data as AnimationData; - const transitionStyle = this.getDefaultTransitionStyles(key, style); + const transitionStyle = this.getDefaultTransitionStyles( + key, + (style as unknown) as AnimationStyle, + ); return (
@@ -542,10 +553,13 @@ class PanelTransition extends React.PureComponent { ); } - getLinks({ key, style, data }: AnimationContext) { - const { Links } = data; + getLinks({ key, style, data }: TransitionPlainStyle): ReactElement { + const { Links } = data as AnimationData; - const transitionStyle = this.getDefaultTransitionStyles(key, style); + const transitionStyle = this.getDefaultTransitionStyles( + key, + (style as unknown) as AnimationStyle, + ); return (
@@ -554,16 +568,9 @@ class PanelTransition extends React.PureComponent { ); } - /** - * @param {string} key - * @param {object} style - * @param {number} style.opacitySpring - * - * @returns {object} - */ getDefaultTransitionStyles( key: string, - { opacitySpring }: Readonly, + { opacitySpring }: Readonly, ): { position: 'absolute'; top: number; @@ -582,7 +589,11 @@ class PanelTransition extends React.PureComponent { }; } - translate(value: number, direction: 'X' | 'Y' = 'X', unit: '%' | 'px' = '%') { + translate( + value: number, + direction: 'X' | 'Y' = 'X', + unit: '%' | 'px' = '%', + ): CSSProperties { return { WebkitTransform: `translate${direction}(${value}${unit})`, transform: `translate${direction}(${value}${unit})`, @@ -590,7 +601,7 @@ class PanelTransition extends React.PureComponent { } requestRedraw = (): Promise => - new Promise(resolve => + new Promise((resolve) => this.setState({ isHeightDirty: true }, () => { this.setState({ isHeightDirty: false }); diff --git a/packages/app/components/auth/RejectionLink.tsx b/packages/app/components/auth/RejectionLink.tsx index 78f1a76..e767f9c 100644 --- a/packages/app/components/auth/RejectionLink.tsx +++ b/packages/app/components/auth/RejectionLink.tsx @@ -1,20 +1,22 @@ -import React, { useContext } from 'react'; +import React, { ComponentType, useContext } from 'react'; import { FormattedMessage as Message, MessageDescriptor } from 'react-intl'; import Context, { AuthContext } from './Context'; interface Props { isAvailable?: (context: AuthContext) => boolean; - payload?: { [key: string]: any }; + payload?: Record; label: MessageDescriptor; } -export type RejectionLinkProps = Props; - -function RejectionLink(props: Props) { +const RejectionLink: ComponentType = ({ + isAvailable, + payload, + label, +}) => { const context = useContext(Context); - if (props.isAvailable && !props.isAvailable(context)) { + if (isAvailable && !isAvailable(context)) { // TODO: if want to properly support multiple links, we should control // the dividers ' | ' rendered from factory too return null; @@ -23,15 +25,15 @@ function RejectionLink(props: Props) { return ( { + onClick={(event) => { event.preventDefault(); - context.reject(props.payload); + context.reject(payload); }} > - + ); -} +}; export default RejectionLink; diff --git a/packages/app/components/auth/acceptRules/AcceptRulesBody.js b/packages/app/components/auth/acceptRules/AcceptRulesBody.tsx similarity index 100% rename from packages/app/components/auth/acceptRules/AcceptRulesBody.js rename to packages/app/components/auth/acceptRules/AcceptRulesBody.tsx diff --git a/packages/app/components/auth/actions.test.ts b/packages/app/components/auth/actions.test.ts index 8fa5bc0..630cf4a 100644 --- a/packages/app/components/auth/actions.test.ts +++ b/packages/app/components/auth/actions.test.ts @@ -1,3 +1,4 @@ +import { Action as ReduxAction } from 'redux'; import sinon from 'sinon'; import expect from 'app/test/unexpected'; @@ -15,33 +16,36 @@ import { login, setLogin, } from 'app/components/auth/actions'; +import { OauthData, OAuthValidateResponse } from '../../services/api/oauth'; -const oauthData = { +const oauthData: OauthData = { clientId: '', redirectUrl: '', responseType: '', scope: '', state: '', + prompt: 'none', }; describe('components/auth/actions', () => { const dispatch = sinon.stub().named('store.dispatch'); const getState = sinon.stub().named('store.getState'); - function callThunk(fn, ...args) { + function callThunk, F extends (...args: A) => any>( + fn: F, + ...args: A + ): Promise { const thunk = fn(...args); return thunk(dispatch, getState); } - function expectDispatchCalls(calls) { - expect( - dispatch, - 'to have calls satisfying', - [[setLoadingState(true)]] - .concat(calls) - .concat([[setLoadingState(false)]]), - ); + function expectDispatchCalls(calls: Array>) { + expect(dispatch, 'to have calls satisfying', [ + [setLoadingState(true)], + ...calls, + [setLoadingState(false)], + ]); } beforeEach(() => { @@ -58,14 +62,20 @@ describe('components/auth/actions', () => { }); describe('#oAuthValidate()', () => { - let resp; + let resp: OAuthValidateResponse; beforeEach(() => { resp = { - client: { id: 123 }, - oAuth: { state: 123 }, + client: { + id: '123', + name: '', + description: '', + }, + oAuth: { + state: 123, + }, session: { - scopes: ['scopes'], + scopes: ['account_info'], }, }; @@ -114,7 +124,7 @@ describe('components/auth/actions', () => { return callThunk(oAuthComplete).then(() => { expect(request.post, 'to have a call satisfying', [ - '/api/oauth2/v1/complete?client_id=&redirect_uri=&response_type=&description=&scope=&prompt=&login_hint=&state=', + '/api/oauth2/v1/complete?client_id=&redirect_uri=&response_type=&description=&scope=&prompt=none&login_hint=&state=', {}, ]); }); @@ -166,7 +176,7 @@ describe('components/auth/actions', () => { (request.post as any).returns(Promise.reject(resp)); - return callThunk(oAuthComplete).catch(error => { + return callThunk(oAuthComplete).catch((error) => { expect(error.acceptRequired, 'to be true'); expectDispatchCalls([[requirePermissionsAccept()]]); }); diff --git a/packages/app/components/auth/actions.ts b/packages/app/components/auth/actions.ts index 38048ba..a18ef0b 100644 --- a/packages/app/components/auth/actions.ts +++ b/packages/app/components/auth/actions.ts @@ -1,7 +1,8 @@ +import { Action as ReduxAction } from 'redux'; import { browserHistory } from 'app/services/history'; import logger from 'app/services/logger'; import localStorage from 'app/services/localStorage'; -import loader from 'app/services/loader'; +import * as loader from 'app/services/loader'; import history from 'app/services/history'; import { updateUser, @@ -15,22 +16,27 @@ import { recoverPassword as recoverPasswordEndpoint, OAuthResponse, } from 'app/services/api/authentication'; -import oauth, { OauthData, Client, Scope } from 'app/services/api/oauth'; -import signup from 'app/services/api/signup'; +import oauth, { OauthData, Scope } from 'app/services/api/oauth'; +import { + register as registerEndpoint, + activate as activateEndpoint, + resendActivation as resendActivationEndpoint, +} from 'app/services/api/signup'; import dispatchBsod from 'app/components/ui/bsod/dispatchBsod'; import { create as createPopup } from 'app/components/ui/popup/actions'; import ContactForm from 'app/components/contact/ContactForm'; import { Account } from 'app/components/accounts/reducer'; import { ThunkAction, Dispatch } from 'app/reducers'; +import { Resp } from 'app/services/request'; -import { getCredentials } from './reducer'; +import { Credentials, Client, OAuthState, getCredentials } from './reducer'; -type ValidationError = - | string - | { - type: string; - payload: { [key: string]: any }; - }; +interface ValidationErrorLiteral { + type: string; + payload: Record; +} + +type ValidationError = string | ValidationErrorLiteral; /** * Routes user to the previous page if it is possible @@ -81,10 +87,10 @@ export function login({ totp?: string; rememberMe?: boolean; }) { - return wrapInLoader(dispatch => + return wrapInLoader((dispatch) => loginEndpoint({ login, password, totp, rememberMe }) .then(authHandler(dispatch)) - .catch(resp => { + .catch((resp) => { if (resp.errors) { if (resp.errors.password === PASSWORD_REQUIRED) { return dispatch(setLogin(login)); @@ -112,7 +118,7 @@ export function login({ } export function acceptRules() { - return wrapInLoader(dispatch => + return wrapInLoader((dispatch) => dispatch(userAcceptRules()).catch(validationErrorsHandler(dispatch)), ); } @@ -146,7 +152,7 @@ export function recoverPassword({ newPassword: string; newRePassword: string; }) { - return wrapInLoader(dispatch => + return wrapInLoader((dispatch) => recoverPasswordEndpoint(key, newPassword, newRePassword) .then(authHandler(dispatch)) .catch(validationErrorsHandler(dispatch, '/forgot-password')), @@ -169,16 +175,15 @@ export function register({ rulesAgreement: boolean; }) { return wrapInLoader((dispatch, getState) => - signup - .register({ - email, - username, - password, - rePassword, - rulesAgreement, - lang: getState().user.lang, - captcha, - }) + registerEndpoint({ + email, + username, + password, + rePassword, + rulesAgreement, + lang: getState().user.lang, + captcha, + }) .then(() => { dispatch( updateUser({ @@ -200,9 +205,8 @@ export function activate({ }: { key: string; }): ThunkAction> { - return wrapInLoader(dispatch => - signup - .activate({ key }) + return wrapInLoader((dispatch) => + activateEndpoint(key) .then(authHandler(dispatch)) .catch(validationErrorsHandler(dispatch, '/resend-activation')), ); @@ -215,10 +219,9 @@ export function resendActivation({ email: string; captcha: string; }) { - return wrapInLoader(dispatch => - signup - .resendActivation({ email, captcha }) - .then(resp => { + return wrapInLoader((dispatch) => + resendActivationEndpoint(email, captcha) + .then((resp) => { dispatch( updateUser({ email, @@ -235,25 +238,26 @@ export function contactUs() { return createPopup({ Popup: ContactForm }); } -export const SET_CREDENTIALS = 'auth:setCredentials'; +interface SetCredentialsAction extends ReduxAction { + type: 'auth:setCredentials'; + payload: Credentials | null; +} + +function setCredentials(payload: Credentials | null): SetCredentialsAction { + return { + type: 'auth:setCredentials', + payload, + }; +} + /** * Sets login in credentials state - * * Resets the state, when `null` is passed * - * @param {string|null} login - * - * @returns {object} + * @param login */ -export function setLogin(login: string | null) { - return { - type: SET_CREDENTIALS, - payload: login - ? { - login, - } - : null, - }; +export function setLogin(login: string | null): SetCredentialsAction { + return setCredentials(login ? { login } : null); } export function relogin(login: string | null): ThunkAction { @@ -262,19 +266,20 @@ export function relogin(login: string | null): ThunkAction { const returnUrl = credentials.returnUrl || location.pathname + location.search; - dispatch({ - type: SET_CREDENTIALS, - payload: { + dispatch( + setCredentials({ login, returnUrl, isRelogin: true, - }, - }); + }), + ); browserHistory.push('/login'); }; } +export type CredentialsAction = SetCredentialsAction; + function requestTotp({ login, password, @@ -288,41 +293,55 @@ function requestTotp({ // merging with current credentials to propogate returnUrl const credentials = getCredentials(getState()); - dispatch({ - type: SET_CREDENTIALS, - payload: { + dispatch( + setCredentials({ ...credentials, login, password, rememberMe, isTotpRequired: true, - }, - }); + }), + ); }; } -export const SET_SWITCHER = 'auth:setAccountSwitcher'; -export function setAccountSwitcher(isOn: boolean) { +interface SetSwitcherAction extends ReduxAction { + type: 'auth:setAccountSwitcher'; + payload: boolean; +} + +export function setAccountSwitcher(isOn: boolean): SetSwitcherAction { return { - type: SET_SWITCHER, + type: 'auth:setAccountSwitcher', payload: isOn, }; } -export const ERROR = 'auth:error'; -export function setErrors(errors: { [key: string]: ValidationError } | null) { +export type AccountSwitcherAction = SetSwitcherAction; + +interface SetErrorAction extends ReduxAction { + type: 'auth:error'; + payload: Record | null; + error: boolean; +} + +export function setErrors( + errors: Record | null, +): SetErrorAction { return { - type: ERROR, + type: 'auth:error', payload: errors, error: true, }; } -export function clearErrors() { +export function clearErrors(): SetErrorAction { return setErrors(null); } -const KNOWN_SCOPES = [ +export type ErrorAction = SetErrorAction; + +const KNOWN_SCOPES: ReadonlyArray = [ 'minecraft_server_session', 'offline_access', 'account_info', @@ -349,17 +368,17 @@ const KNOWN_SCOPES = [ export function oAuthValidate(oauthData: OauthData) { // TODO: move to oAuth actions? // test request: /oauth?client_id=ely&redirect_uri=http%3A%2F%2Fely.by&response_type=code&scope=minecraft_server_session&description=foo - return wrapInLoader(dispatch => + return wrapInLoader((dispatch) => oauth .validate(oauthData) - .then(resp => { + .then((resp) => { const { scopes } = resp.session; const invalidScopes = scopes.filter( - scope => !KNOWN_SCOPES.includes(scope), + (scope) => !KNOWN_SCOPES.includes(scope), ); let prompt = (oauthData.prompt || 'none') .split(',') - .map(item => item.trim()); + .map((item) => item.trim()); if (prompt.includes('none')) { prompt = ['none']; @@ -396,7 +415,7 @@ export function oAuthValidate(oauthData: OauthData) { /** * @param {object} params * @param {bool} params.accept=false - * + * @param params.accept * @returns {Promise} */ export function oAuthComplete(params: { accept?: boolean } = {}) { @@ -470,11 +489,76 @@ function handleOauthParamsValidation( return Promise.reject(resp); } -export const SET_CLIENT = 'set_client'; -export function setClient({ id, name, description }: Client) { +interface SetClientAction extends ReduxAction { + type: 'set_client'; + payload: Client; +} + +export function setClient(payload: Client): SetClientAction { return { - type: SET_CLIENT, - payload: { id, name, description }, + type: 'set_client', + payload, + }; +} + +export type ClientAction = SetClientAction; + +interface SetOauthAction extends ReduxAction { + type: 'set_oauth'; + payload: Pick< + OAuthState, + | 'clientId' + | 'redirectUrl' + | 'responseType' + | 'scope' + | 'prompt' + | 'loginHint' + | 'state' + >; +} + +// Input data is coming right from the query string, so the names +// are the same, as used for initializing OAuth2 request +export function setOAuthRequest(data: { + client_id?: string; + redirect_uri?: string; + response_type?: string; + scope?: string; + prompt?: string; + loginHint?: string; + state?: string; +}): SetOauthAction { + return { + type: 'set_oauth', + payload: { + // TODO: there is too much default empty string. Maybe we can somehow validate it + // on the level, where this action is called? + clientId: data.client_id || '', + redirectUrl: data.redirect_uri || '', + responseType: data.response_type || '', + scope: data.scope || '', + prompt: data.prompt || '', + loginHint: data.loginHint || '', + state: data.state || '', + }, + }; +} + +interface SetOAuthResultAction extends ReduxAction { + type: 'set_oauth_result'; + payload: Pick; +} + +export const SET_OAUTH_RESULT = 'set_oauth_result'; // TODO: remove + +export function setOAuthCode(payload: { + success: boolean; + code: string; + displayCode: boolean; +}): SetOAuthResultAction { + return { + type: 'set_oauth_result', + payload, }; } @@ -507,69 +591,43 @@ export function resetAuth(): ThunkAction { }; } -export const SET_OAUTH = 'set_oauth'; -export function setOAuthRequest(data: { - client_id?: string; - redirect_uri?: string; - response_type?: string; - scope?: string; - prompt?: string; - loginHint?: string; - state?: string; -}) { +interface RequestPermissionsAcceptAction extends ReduxAction { + type: 'require_permissions_accept'; +} + +export function requirePermissionsAccept(): RequestPermissionsAcceptAction { return { - type: SET_OAUTH, - payload: { - clientId: data.client_id, - redirectUrl: data.redirect_uri, - responseType: data.response_type, - scope: data.scope, - prompt: data.prompt, - loginHint: data.loginHint, - state: data.state, - }, + type: 'require_permissions_accept', }; } -export const SET_OAUTH_RESULT = 'set_oauth_result'; -export function setOAuthCode(data: { - success: boolean; - code: string; - displayCode: boolean; -}) { +export type OAuthAction = + | SetOauthAction + | SetOAuthResultAction + | RequestPermissionsAcceptAction; + +interface SetScopesAction extends ReduxAction { + type: 'set_scopes'; + payload: Array; +} + +export function setScopes(payload: Array): SetScopesAction { return { - type: SET_OAUTH_RESULT, - payload: { - success: data.success, - code: data.code, - displayCode: data.displayCode, - }, + type: 'set_scopes', + payload, }; } -export const REQUIRE_PERMISSIONS_ACCEPT = 'require_permissions_accept'; -export function requirePermissionsAccept() { - return { - type: REQUIRE_PERMISSIONS_ACCEPT, - }; +export type ScopesAction = SetScopesAction; + +interface SetLoadingAction extends ReduxAction { + type: 'set_loading_state'; + payload: boolean; } -export const SET_SCOPES = 'set_scopes'; -export function setScopes(scopes: Scope[]) { - if (!Array.isArray(scopes)) { - throw new Error('Scopes must be array'); - } - +export function setLoadingState(isLoading: boolean): SetLoadingAction { return { - type: SET_SCOPES, - payload: scopes, - }; -} - -export const SET_LOADING_STATE = 'set_loading_state'; -export function setLoadingState(isLoading: boolean) { - return { - type: SET_LOADING_STATE, + type: 'set_loading_state', payload: isLoading, }; } @@ -580,12 +638,12 @@ function wrapInLoader(fn: ThunkAction>): ThunkAction> { const endLoading = () => dispatch(setLoadingState(false)); return fn(dispatch, getState, undefined).then( - resp => { + (resp) => { endLoading(); return resp; }, - resp => { + (resp) => { endLoading(); return Promise.reject(resp); @@ -594,6 +652,8 @@ function wrapInLoader(fn: ThunkAction>): ThunkAction> { }; } +export type LoadingAction = SetLoadingAction; + function needActivation() { return updateUser({ isActive: false, @@ -608,19 +668,27 @@ function authHandler(dispatch: Dispatch) { token: oAuthResp.access_token, refreshToken: oAuthResp.refresh_token || null, }), - ).then(resp => { + ).then((resp) => { dispatch(setLogin(null)); return resp; }); } -function validationErrorsHandler(dispatch: Dispatch, repeatUrl?: string) { - return resp => { +function validationErrorsHandler( + dispatch: Dispatch, + repeatUrl?: string, +): ( + resp: Resp<{ + errors?: Record; + data?: Record; + }>, +) => Promise { + return (resp) => { if (resp.errors) { const [firstError] = Object.keys(resp.errors); - const error = { - type: resp.errors[firstError], + const firstErrorObj: ValidationError = { + type: resp.errors[firstError] as string, payload: { isGuest: true, repeatUrl: '', @@ -629,20 +697,24 @@ function validationErrorsHandler(dispatch: Dispatch, repeatUrl?: string) { if (resp.data) { // TODO: this should be formatted on backend - Object.assign(error.payload, resp.data); + Object.assign(firstErrorObj.payload, resp.data); } if ( - ['error.key_not_exists', 'error.key_expire'].includes(error.type) && + ['error.key_not_exists', 'error.key_expire'].includes( + firstErrorObj.type, + ) && repeatUrl ) { // TODO: this should be formatted on backend - error.payload.repeatUrl = repeatUrl; + firstErrorObj.payload.repeatUrl = repeatUrl; } - resp.errors[firstError] = error; + // TODO: can I clone the object or its necessary to catch modified errors list on corresponding catches? + const { errors } = resp; + errors[firstError] = firstErrorObj; - dispatch(setErrors(resp.errors)); + dispatch(setErrors(errors)); } return Promise.reject(resp); diff --git a/packages/app/components/auth/activation/ActivationBody.js b/packages/app/components/auth/activation/ActivationBody.tsx similarity index 89% rename from packages/app/components/auth/activation/ActivationBody.js rename to packages/app/components/auth/activation/ActivationBody.tsx index a949715..45dc4cd 100644 --- a/packages/app/components/auth/activation/ActivationBody.js +++ b/packages/app/components/auth/activation/ActivationBody.tsx @@ -1,4 +1,3 @@ -import PropTypes from 'prop-types'; import React from 'react'; import { FormattedMessage as Message } from 'react-intl'; @@ -13,14 +12,6 @@ export default class ActivationBody extends BaseAuthBody { static displayName = 'ActivationBody'; static panelId = 'activation'; - static propTypes = { - match: PropTypes.shape({ - params: PropTypes.shape({ - key: PropTypes.string, - }), - }), - }; - autoFocusField = this.props.match.params && this.props.match.params.key ? null : 'key'; diff --git a/packages/app/components/auth/authError/AuthError.js b/packages/app/components/auth/authError/AuthError.js deleted file mode 100644 index 93833ad..0000000 --- a/packages/app/components/auth/authError/AuthError.js +++ /dev/null @@ -1,45 +0,0 @@ -import PropTypes from 'prop-types'; -import React from 'react'; - -import errorsDict from 'app/services/errorsDict'; -import { PanelBodyHeader } from 'app/components/ui/Panel'; - -let autoHideTimer; -function resetTimer() { - if (autoHideTimer) { - clearTimeout(autoHideTimer); - autoHideTimer = null; - } -} -export default function AuthError({ error, onClose = function() {} }) { - resetTimer(); - - if (error.payload && error.payload.canRepeatIn) { - error.payload.msLeft = error.payload.canRepeatIn * 1000; - setTimeout(onClose, error.payload.msLeft - Date.now() + 1500); // 1500 to let the user see, that time is elapsed - } - - return ( - { - resetTimer(); - onClose(); - }} - > - {errorsDict.resolve(error)} - - ); -} - -AuthError.displayName = 'AuthError'; -AuthError.propTypes = { - error: PropTypes.oneOfType([ - PropTypes.string, - PropTypes.shape({ - type: PropTypes.string, - payload: PropTypes.object, - }), - ]).isRequired, - onClose: PropTypes.func, -}; diff --git a/packages/app/components/auth/authError/AuthError.tsx b/packages/app/components/auth/authError/AuthError.tsx new file mode 100644 index 0000000..08b29b0 --- /dev/null +++ b/packages/app/components/auth/authError/AuthError.tsx @@ -0,0 +1,45 @@ +import React, { ComponentType, useEffect } from 'react'; + +import { resolve as resolveError } from 'app/services/errorsDict'; +import { PanelBodyHeader } from 'app/components/ui/Panel'; +import { ValidationError } from 'app/components/ui/form/FormModel'; + +interface Props { + error: ValidationError; + onClose?: () => void; +} + +let autoHideTimer: number | null = null; +function resetTimeout(): void { + if (autoHideTimer) { + clearTimeout(autoHideTimer); + autoHideTimer = null; + } +} + +const AuthError: ComponentType = ({ error, onClose }) => { + useEffect(() => { + resetTimeout(); + + if ( + onClose && + typeof error !== 'string' && + error.payload && + error.payload.canRepeatIn + ) { + const msLeft = error.payload.canRepeatIn * 1000; + // 1500 to let the user see, that time is elapsed + setTimeout(onClose, msLeft - Date.now() + 1500); + } + + return resetTimeout; + }, [error, onClose]); + + return ( + + {resolveError(error)} + + ); +}; + +export default AuthError; diff --git a/packages/app/components/auth/chooseAccount/ChooseAccountBody.js b/packages/app/components/auth/chooseAccount/ChooseAccountBody.tsx similarity index 92% rename from packages/app/components/auth/chooseAccount/ChooseAccountBody.js rename to packages/app/components/auth/chooseAccount/ChooseAccountBody.tsx index 3b3d75e..7ea8286 100644 --- a/packages/app/components/auth/chooseAccount/ChooseAccountBody.js +++ b/packages/app/components/auth/chooseAccount/ChooseAccountBody.tsx @@ -4,6 +4,7 @@ import { FormattedMessage as Message } from 'react-intl'; import BaseAuthBody from 'app/components/auth/BaseAuthBody'; import { AccountSwitcher } from 'app/components/accounts'; +import { Account } from 'app/components/accounts/reducer'; import styles from './chooseAccount.scss'; import messages from './ChooseAccount.intl.json'; @@ -46,7 +47,7 @@ export default class ChooseAccountBody extends BaseAuthBody { ); } - onSwitch = account => { + onSwitch = (account: Account): void => { this.context.resolve(account); }; } diff --git a/packages/app/components/auth/factory.tsx b/packages/app/components/auth/factory.tsx index 7d10072..9cbef7f 100644 --- a/packages/app/components/auth/factory.tsx +++ b/packages/app/components/auth/factory.tsx @@ -1,36 +1,36 @@ -import React from 'react'; +import React, { ComponentProps, ComponentType } from 'react'; import { Button } from 'app/components/ui/form'; -import RejectionLink, { - RejectionLinkProps, -} from 'app/components/auth/RejectionLink'; +import RejectionLink from 'app/components/auth/RejectionLink'; import AuthTitle from 'app/components/auth/AuthTitle'; import { MessageDescriptor } from 'react-intl'; import { Color } from 'app/components/ui'; +import BaseAuthBody from './BaseAuthBody'; -/** - * @param {object} options - * @param {string|object} options.title - panel title - * @param {React.ReactElement} options.body - * @param {object} options.footer - config for footer Button - * @param {Array|object|null} options.links - link config or an array of link configs - * - * @returns {object} - structure, required for auth panel to work - */ -export default function({ - title, - body, - footer, - links, -}: { +export type Factory = () => { + Title: ComponentType; + Body: typeof BaseAuthBody; + Footer: ComponentType; + Links: ComponentType; +}; + +type RejectionLinkProps = ComponentProps; +interface FactoryParams { title: MessageDescriptor; - body: React.ElementType; + body: typeof BaseAuthBody; footer: { color?: Color; label: string | MessageDescriptor; autoFocus?: boolean; }; - links?: RejectionLinkProps | RejectionLinkProps[]; -}) { + links?: RejectionLinkProps | Array; +} + +export default function ({ + title, + body, + footer, + links, +}: FactoryParams): Factory { return () => ({ Title: () => , Body: body, @@ -38,7 +38,7 @@ export default function({ Links: () => links ? ( - {([] as RejectionLinkProps[]) + {([] as Array) .concat(links) .map((link, index) => [ index ? ' | ' : '', diff --git a/packages/app/components/auth/finish/Finish.tsx b/packages/app/components/auth/finish/Finish.tsx index b52fba7..8f68766 100644 --- a/packages/app/components/auth/finish/Finish.tsx +++ b/packages/app/components/auth/finish/Finish.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { MouseEventHandler } from 'react'; import { connect } from 'react-redux'; import { FormattedMessage as Message } from 'react-intl'; import { Helmet } from 'react-helmet-async'; @@ -13,7 +13,7 @@ interface Props { appName: string; code?: string; state: string; - displayCode?: string; + displayCode?: boolean; success?: boolean; } @@ -21,7 +21,6 @@ class Finish extends React.Component { render() { const { appName, code, state, displayCode, success } = this.props; const authData = JSON.stringify({ - // eslint-disable-next-line @typescript-eslint/camelcase auth_code: code, state, }); @@ -84,7 +83,7 @@ class Finish extends React.Component { ); } - onCopyClick = event => { + onCopyClick: MouseEventHandler = (event) => { event.preventDefault(); const { code } = this.props; diff --git a/packages/app/components/auth/forgotPassword/ForgotPasswordBody.js b/packages/app/components/auth/forgotPassword/ForgotPasswordBody.tsx similarity index 100% rename from packages/app/components/auth/forgotPassword/ForgotPasswordBody.js rename to packages/app/components/auth/forgotPassword/ForgotPasswordBody.tsx diff --git a/packages/app/components/auth/login/Login.ts b/packages/app/components/auth/login/Login.ts index 193529c..cb28913 100644 --- a/packages/app/components/auth/login/Login.ts +++ b/packages/app/components/auth/login/Login.ts @@ -10,7 +10,7 @@ export default factory({ label: messages.next, }, links: { - isAvailable: context => !context.user.isGuest, + isAvailable: (context) => !context.user.isGuest, label: messages.createNewAccount, }, }); diff --git a/packages/app/components/auth/login/LoginBody.js b/packages/app/components/auth/login/LoginBody.tsx similarity index 85% rename from packages/app/components/auth/login/LoginBody.js rename to packages/app/components/auth/login/LoginBody.tsx index f903977..a139801 100644 --- a/packages/app/components/auth/login/LoginBody.js +++ b/packages/app/components/auth/login/LoginBody.tsx @@ -1,13 +1,15 @@ import React from 'react'; + import { Input } from 'app/components/ui/form'; import BaseAuthBody from 'app/components/auth/BaseAuthBody'; +import { User } from 'app/components/user/reducer'; import messages from './Login.intl.json'; export default class LoginBody extends BaseAuthBody { static displayName = 'LoginBody'; static panelId = 'login'; - static hasGoBack = state => { + static hasGoBack = (state: { user: User }) => { return !state.user.isGuest; }; diff --git a/packages/app/components/auth/password/PasswordBody.js b/packages/app/components/auth/password/PasswordBody.tsx similarity index 100% rename from packages/app/components/auth/password/PasswordBody.js rename to packages/app/components/auth/password/PasswordBody.tsx diff --git a/packages/app/components/auth/permissions/PermissionsBody.js b/packages/app/components/auth/permissions/PermissionsBody.tsx similarity index 95% rename from packages/app/components/auth/permissions/PermissionsBody.js rename to packages/app/components/auth/permissions/PermissionsBody.tsx index be17509..7c4cd06 100644 --- a/packages/app/components/auth/permissions/PermissionsBody.js +++ b/packages/app/components/auth/permissions/PermissionsBody.tsx @@ -41,7 +41,7 @@ export default class PermissionsBody extends BaseAuthBody {
    - {scopes.map(scope => { + {scopes.map((scope) => { const key = `scope_${scope}`; const message = messages[key]; @@ -50,7 +50,7 @@ export default class PermissionsBody extends BaseAuthBody { {message ? ( ) : ( - scope.replace(/^\w|_/g, match => + scope.replace(/^\w|_/g, (match) => match.replace('_', ' ').toUpperCase(), ) )} diff --git a/packages/app/components/auth/recoverPassword/RecoverPasswordBody.js b/packages/app/components/auth/recoverPassword/RecoverPasswordBody.tsx similarity index 92% rename from packages/app/components/auth/recoverPassword/RecoverPasswordBody.js rename to packages/app/components/auth/recoverPassword/RecoverPasswordBody.tsx index 98a970f..2a252a8 100644 --- a/packages/app/components/auth/recoverPassword/RecoverPasswordBody.js +++ b/packages/app/components/auth/recoverPassword/RecoverPasswordBody.tsx @@ -1,4 +1,3 @@ -import PropTypes from 'prop-types'; import React from 'react'; import { FormattedMessage as Message } from 'react-intl'; @@ -16,14 +15,6 @@ export default class RecoverPasswordBody extends BaseAuthBody { static panelId = 'recoverPassword'; static hasGoBack = true; - static propTypes = { - match: PropTypes.shape({ - params: PropTypes.shape({ - key: PropTypes.string, - }), - }), - }; - autoFocusField = this.props.match.params && this.props.match.params.key ? 'newPassword' diff --git a/packages/app/components/auth/reducer.test.ts b/packages/app/components/auth/reducer.test.ts index 666d668..1b5ba5d 100644 --- a/packages/app/components/auth/reducer.test.ts +++ b/packages/app/components/auth/reducer.test.ts @@ -1,14 +1,9 @@ import expect from 'app/test/unexpected'; import auth from './reducer'; -import { - setLogin, - SET_CREDENTIALS, - setAccountSwitcher, - SET_SWITCHER, -} from './actions'; +import { setLogin, setAccountSwitcher } from './actions'; describe('components/auth/reducer', () => { - describe(SET_CREDENTIALS, () => { + describe('auth:setCredentials', () => { it('should set login', () => { const expectedLogin = 'foo'; @@ -22,7 +17,7 @@ describe('components/auth/reducer', () => { }); }); - describe(SET_SWITCHER, () => { + describe('auth:setAccountSwitcher', () => { it('should be enabled by default', () => expect(auth(undefined, {} as any), 'to satisfy', { isSwitcherEnabled: true, diff --git a/packages/app/components/auth/reducer.ts b/packages/app/components/auth/reducer.ts index 4b0ae6e..8be2f20 100644 --- a/packages/app/components/auth/reducer.ts +++ b/packages/app/components/auth/reducer.ts @@ -1,26 +1,34 @@ -import { combineReducers } from 'redux'; +import { combineReducers, Reducer } from 'redux'; import { RootState } from 'app/reducers'; +import { Scope } from '../../services/api/oauth'; import { - ERROR, - SET_CLIENT, - SET_OAUTH, - SET_OAUTH_RESULT, - SET_SCOPES, - SET_LOADING_STATE, - REQUIRE_PERMISSIONS_ACCEPT, - SET_CREDENTIALS, - SET_SWITCHER, + ErrorAction, + CredentialsAction, + AccountSwitcherAction, + LoadingAction, + ClientAction, + OAuthAction, + ScopesAction, } from './actions'; -type Credentials = { - login?: string; +export interface Credentials { + login?: string | null; // By some reasons there is can be null value. Need to investigate. password?: string; rememberMe?: boolean; returnUrl?: string; isRelogin?: boolean; isTotpRequired?: boolean; -}; +} + +type Error = Record< + string, + | string + | { + type: string; + payload: Record; + } +> | null; export interface Client { id: string; @@ -28,7 +36,7 @@ export interface Client { description: string; } -interface OAuthState { +export interface OAuthState { clientId: string; redirectUrl: string; responseType: string; @@ -39,27 +47,113 @@ interface OAuthState { state: string; success?: boolean; code?: string; - displayCode?: string; + displayCode?: boolean; acceptRequired?: boolean; } +type Scopes = Array; + export interface State { credentials: Credentials; - error: null | { - [key: string]: - | string - | { - type: string; - payload: { [key: string]: any }; - }; - }; + error: Error; isLoading: boolean; isSwitcherEnabled: boolean; client: Client | null; oauth: OAuthState | null; - scopes: string[]; + scopes: Scopes; } +const error: Reducer = ( + state = null, + { type, payload }, +) => { + if (type === 'auth:error') { + return payload; + } + + return state; +}; + +const credentials: Reducer = ( + state = {}, + { type, payload }, +) => { + if (type === 'auth:setCredentials') { + if (payload) { + return { + ...payload, + }; + } + + return {}; + } + + return state; +}; + +const isSwitcherEnabled: Reducer< + State['isSwitcherEnabled'], + AccountSwitcherAction +> = (state = true, { type, payload }) => { + if (type === 'auth:setAccountSwitcher') { + return payload; + } + + return state; +}; + +const isLoading: Reducer = ( + state = false, + { type, payload }, +) => { + if (type === 'set_loading_state') { + return payload; + } + + return state; +}; + +const client: Reducer = ( + state = null, + { type, payload }, +) => { + if (type === 'set_client') { + return payload; + } + + return state; +}; + +const oauth: Reducer = (state = null, action) => { + switch (action.type) { + case 'set_oauth': + return action.payload; + case 'set_oauth_result': + return { + ...(state as OAuthState), + ...action.payload, + }; + case 'require_permissions_accept': + return { + ...(state as OAuthState), + acceptRequired: true, + }; + default: + return state; + } +}; + +const scopes: Reducer = ( + state = [], + { type, payload }, +) => { + if (type === 'set_scopes') { + return payload; + } + + return state; +}; + export default combineReducers({ credentials, error, @@ -70,135 +164,6 @@ export default combineReducers({ scopes, }); -function error( - state = null, - { type, payload = null, error = false }, -): State['error'] { - switch (type) { - case ERROR: - if (!error) { - throw new Error('Expected payload with error'); - } - - return payload; - - default: - return state; - } -} - -function credentials( - state = {}, - { - type, - payload, - }: { - type: string; - payload: Credentials | null; - }, -): State['credentials'] { - if (type === SET_CREDENTIALS) { - if (payload && typeof payload === 'object') { - return { - ...payload, - }; - } - - return {}; - } - - return state; -} - -function isSwitcherEnabled( - state = true, - { type, payload = false }, -): State['isSwitcherEnabled'] { - switch (type) { - case SET_SWITCHER: - if (typeof payload !== 'boolean') { - throw new Error('Expected payload of boolean type'); - } - - return payload; - - default: - return state; - } -} - -function isLoading( - state = false, - { type, payload = null }, -): State['isLoading'] { - switch (type) { - case SET_LOADING_STATE: - return !!payload; - - default: - return state; - } -} - -function client(state = null, { type, payload }): State['client'] { - switch (type) { - case SET_CLIENT: - return { - id: payload.id, - name: payload.name, - description: payload.description, - }; - - default: - return state; - } -} - -function oauth( - state: State['oauth'] = null, - { type, payload }, -): State['oauth'] { - switch (type) { - case SET_OAUTH: - return { - clientId: payload.clientId, - redirectUrl: payload.redirectUrl, - responseType: payload.responseType, - scope: payload.scope, - prompt: payload.prompt, - loginHint: payload.loginHint, - state: payload.state, - }; - - case SET_OAUTH_RESULT: - return { - ...(state as OAuthState), - success: payload.success, - code: payload.code, - displayCode: payload.displayCode, - }; - - case REQUIRE_PERMISSIONS_ACCEPT: - return { - ...(state as OAuthState), - acceptRequired: true, - }; - - default: - return state; - } -} - -function scopes(state = [], { type, payload = [] }): State['scopes'] { - switch (type) { - case SET_SCOPES: - return payload; - - default: - return state; - } -} - export function getLogin( state: RootState | Pick, ): string | null { diff --git a/packages/app/components/auth/register/RegisterBody.js b/packages/app/components/auth/register/RegisterBody.tsx similarity index 100% rename from packages/app/components/auth/register/RegisterBody.js rename to packages/app/components/auth/register/RegisterBody.tsx diff --git a/packages/app/components/auth/resendActivation/ResendActivationBody.js b/packages/app/components/auth/resendActivation/ResendActivationBody.tsx similarity index 100% rename from packages/app/components/auth/resendActivation/ResendActivationBody.js rename to packages/app/components/auth/resendActivation/ResendActivationBody.tsx diff --git a/packages/app/components/contact/ContactForm.test.tsx b/packages/app/components/contact/ContactForm.test.tsx index 4fc7a62..99327b5 100644 --- a/packages/app/components/contact/ContactForm.test.tsx +++ b/packages/app/components/contact/ContactForm.test.tsx @@ -1,55 +1,60 @@ import React from 'react'; import expect from 'app/test/unexpected'; import sinon from 'sinon'; -import { shallow, mount } from 'enzyme'; -import { IntlProvider } from 'react-intl'; +import { render, fireEvent, waitFor, screen } from '@testing-library/react'; import feedback from 'app/services/api/feedback'; import { User } from 'app/components/user'; +import { TestContextProvider } from 'app/shell'; import { ContactForm } from './ContactForm'; -describe('ContactForm', () => { - describe('when rendered', () => { - const user = {} as User; - let component; +beforeEach(() => { + sinon.stub(feedback, 'send').returns(Promise.resolve() as any); +}); - beforeEach(() => { - component = shallow(); - }); +afterEach(() => { + (feedback.send as any).restore(); +}); + +describe('ContactForm', () => { + it('should contain Form', () => { + const user = {} as User; + + render( + + + , + ); + + expect(screen.getAllByRole('textbox').length, 'to be greater than', 1); + + expect( + screen.getByRole('button', { name: /Send/ }), + 'to have property', + 'type', + 'submit', + ); [ { - type: 'Input', + label: 'subject', name: 'subject', }, { - type: 'Input', + label: 'E‑mail', name: 'email', }, { - type: 'Dropdown', - name: 'category', - }, - { - type: 'TextArea', + label: 'message', name: 'message', }, - ].forEach(el => { - it(`should have ${el.name} field`, () => { - expect(component.find(`${el.type}[name="${el.name}"]`), 'to satisfy', { - length: 1, - }); - }); - }); - - it('should contain Form', () => { - expect(component.find('Form'), 'to satisfy', { length: 1 }); - }); - - it('should contain submit Button', () => { - expect(component.find('Button[type="submit"]'), 'to satisfy', { - length: 1, - }); + ].forEach((el) => { + expect( + screen.getByLabelText(el.label, { exact: false }), + 'to have property', + 'name', + el.name, + ); }); }); @@ -57,146 +62,109 @@ describe('ContactForm', () => { const user = { email: 'foo@bar.com', } as User; - let component; - - beforeEach(() => { - component = shallow(); - }); it('should render email field with user email', () => { + render( + + + , + ); + + expect(screen.getByDisplayValue(user.email), 'to be a', HTMLInputElement); + }); + }); + + it('should submit and then hide form and display success message', async () => { + const user = { + email: 'foo@bar.com', + } as User; + + render( + + + , + ); + + fireEvent.change(screen.getByLabelText(/subject/i), { + target: { + value: 'subject', + }, + }); + + fireEvent.change(screen.getByLabelText(/message/i), { + target: { + value: 'the message', + }, + }); + + const button = screen.getByRole('button', { name: 'Send' }); + + expect(button, 'to have property', 'disabled', false); + + fireEvent.click(button); + + expect(button, 'to have property', 'disabled', true); + expect(feedback.send, 'to have a call exhaustively satisfying', [ + { + subject: 'subject', + email: user.email, + category: '', + message: 'the message', + }, + ]); + + await waitFor(() => { expect( - component.find('Input[name="email"]').prop('defaultValue'), - 'to equal', - user.email, + screen.getByText('Your message was received', { exact: false }), + 'to be a', + HTMLElement, ); }); + + expect(screen.getByText(user.email), 'to be a', HTMLElement); + + expect(screen.queryByRole('button', { name: /Send/ }), 'to be null'); }); - describe('when email was successfully sent', () => { + it('should show validation messages', async () => { const user = { email: 'foo@bar.com', } as User; - let component; - beforeEach(() => { - component = shallow(); + (feedback.send as any).callsFake(() => + Promise.reject({ + success: false, + errors: { email: 'error.email_invalid' }, + }), + ); - component.setState({ isSuccessfullySent: true }); + render( + + + , + ); + + fireEvent.change(screen.getByLabelText(/subject/i), { + target: { + value: 'subject', + }, }); - it('should not contain Form', () => { - expect(component.find('Form'), 'to satisfy', { length: 0 }); + fireEvent.change(screen.getByLabelText(/message/i), { + target: { + value: 'the message', + }, }); - }); - xdescribe('validation', () => { - const user = { - email: 'foo@bar.com', - } as User; - let component; - let wrapper; + fireEvent.click(screen.getByRole('button', { name: 'Send' })); - beforeEach(() => { - // TODO: add polyfill for from validation for jsdom - - wrapper = mount( - - (component = el)} /> - , + await waitFor(() => { + expect( + screen.getByRole('alert'), + 'to have property', + 'innerHTML', + 'E‑mail is invalid', ); }); - - it('should require email, subject and message', () => { - // wrapper.find('[type="submit"]').simulate('click'); - wrapper.find('form').simulate('submit'); - - expect(component.form.hasErrors(), 'to be true'); - }); - }); - - describe('when user submits form', () => { - const user = { - email: 'foo@bar.com', - } as User; - let component; - let wrapper; - const requestData = { - email: user.email, - subject: 'Test subject', - message: 'Test message', - }; - - beforeEach(() => { - sinon.stub(feedback, 'send'); - - // TODO: add polyfill for from validation for jsdom - if (!(Element.prototype as any).checkValidity) { - (Element.prototype as any).checkValidity = () => true; - } - - // TODO: try to rewrite with unexpected-react - wrapper = mount( - - (component = el)} /> - , - ); - - wrapper.find('input[name="email"]').getDOMNode().value = - requestData.email; - wrapper.find('input[name="subject"]').getDOMNode().value = - requestData.subject; - wrapper.find('textarea[name="message"]').getDOMNode().value = - requestData.message; - }); - - afterEach(() => { - (feedback.send as any).restore(); - }); - - xit('should call onSubmit', () => { - sinon.stub(component, 'onSubmit'); - - wrapper.find('form').simulate('submit'); - - expect(component.onSubmit, 'was called'); - }); - - it('should call send with required data', () => { - (feedback.send as any).returns(Promise.resolve()); - - component.onSubmit(); - - expect(feedback.send, 'to have a call satisfying', [requestData]); - }); - - it('should set isSuccessfullySent', () => { - (feedback.send as any).returns(Promise.resolve()); - - return component - .onSubmit() - .then(() => - expect(component.state, 'to satisfy', { isSuccessfullySent: true }), - ); - }); - - it('should handle isLoading during request', () => { - (feedback.send as any).returns(Promise.resolve()); - - const promise = component.onSubmit(); - - expect(component.state, 'to satisfy', { isLoading: true }); - - return promise.then(() => - expect(component.state, 'to satisfy', { isLoading: false }), - ); - }); - - it('should render success message with user email', () => { - (feedback.send as any).returns(Promise.resolve()); - - return component - .onSubmit() - .then(() => expect(wrapper.text(), 'to contain', user.email)); - }); }); }); diff --git a/packages/app/components/contact/ContactForm.tsx b/packages/app/components/contact/ContactForm.tsx index f6d8e15..461f7ed 100644 --- a/packages/app/components/contact/ContactForm.tsx +++ b/packages/app/components/contact/ContactForm.tsx @@ -140,7 +140,12 @@ export class ContactForm extends React.Component<
-
); @@ -172,9 +177,9 @@ export class ContactForm extends React.Component< ); } - onSubmit = () => { + onSubmit = (): Promise => { if (this.state.isLoading) { - return; + return Promise.resolve(); } this.setState({ isLoading: true }); @@ -187,7 +192,7 @@ export class ContactForm extends React.Component< lastEmail: this.form.value('email'), }), ) - .catch(resp => { + .catch((resp) => { if (resp.errors) { this.form.setErrors(resp.errors); diff --git a/packages/app/components/contact/ContactLink.tsx b/packages/app/components/contact/ContactLink.tsx index 46c857c..651afe5 100644 --- a/packages/app/components/contact/ContactLink.tsx +++ b/packages/app/components/contact/ContactLink.tsx @@ -12,7 +12,7 @@ function ContactLink({ createContactPopup, ...props }: Props) {
{ + onClick={(event) => { event.preventDefault(); createContactPopup(); diff --git a/packages/app/components/dev/apps/actions.ts b/packages/app/components/dev/apps/actions.ts index fcf7ea4..205950c 100644 --- a/packages/app/components/dev/apps/actions.ts +++ b/packages/app/components/dev/apps/actions.ts @@ -1,17 +1,15 @@ -import { Dispatch } from 'redux'; +import { Dispatch, Action as ReduxAction } from 'redux'; import { OauthAppResponse } from 'app/services/api/oauth'; import oauth from 'app/services/api/oauth'; import { User } from 'app/components/user'; +import { ThunkAction } from 'app/reducers'; import { Apps } from './reducer'; -type SetAvailableAction = { +interface SetAvailableAction extends ReduxAction { type: 'apps:setAvailable'; payload: Array; -}; -type DeleteAppAction = { type: 'apps:deleteApp'; payload: string }; -type AddAppAction = { type: 'apps:addApp'; payload: OauthAppResponse }; -export type Action = SetAvailableAction | DeleteAppAction | AddAppAction; +} export function setAppsList(apps: Array): SetAvailableAction { return { @@ -24,17 +22,22 @@ export function getApp( state: { apps: Apps }, clientId: string, ): OauthAppResponse | null { - return state.apps.available.find(app => app.clientId === clientId) || null; + return state.apps.available.find((app) => app.clientId === clientId) || null; } -export function fetchApp(clientId: string) { - return async (dispatch: Dispatch): Promise => { +export function fetchApp(clientId: string): ThunkAction> { + return async (dispatch) => { const app = await oauth.getApp(clientId); dispatch(addApp(app)); }; } +interface AddAppAction extends ReduxAction { + type: 'apps:addApp'; + payload: OauthAppResponse; +} + function addApp(app: OauthAppResponse): AddAppAction { return { type: 'apps:addApp', @@ -69,6 +72,11 @@ export function deleteApp(clientId: string) { }; } +interface DeleteAppAction extends ReduxAction { + type: 'apps:deleteApp'; + payload: string; +} + function createDeleteAppAction(clientId: string): DeleteAppAction { return { type: 'apps:deleteApp', @@ -76,8 +84,11 @@ function createDeleteAppAction(clientId: string): DeleteAppAction { }; } -export function resetApp(clientId: string, resetSecret: boolean) { - return async (dispatch: Dispatch): Promise => { +export function resetApp( + clientId: string, + resetSecret: boolean, +): ThunkAction> { + return async (dispatch) => { const { data: app } = await oauth.reset(clientId, resetSecret); if (resetSecret) { @@ -85,3 +96,5 @@ export function resetApp(clientId: string, resetSecret: boolean) { } }; } + +export type Action = SetAvailableAction | DeleteAppAction | AddAppAction; diff --git a/packages/app/components/dev/apps/applicationForm/ApplicationForm.tsx b/packages/app/components/dev/apps/applicationForm/ApplicationForm.tsx index 863e13d..4b0938c 100644 --- a/packages/app/components/dev/apps/applicationForm/ApplicationForm.tsx +++ b/packages/app/components/dev/apps/applicationForm/ApplicationForm.tsx @@ -19,12 +19,15 @@ import ApplicationTypeSwitcher from './ApplicationTypeSwitcher'; import WebsiteType from './WebsiteType'; import MinecraftServerType from './MinecraftServerType'; -const typeToForm: { - [K in ApplicationType]: { +type TypeToForm = Record< + ApplicationType, + { label: MessageDescriptor; component: React.ComponentType; - }; -} = { + } +>; + +const typeToForm: TypeToForm = { [TYPE_APPLICATION]: { label: messages.website, component: WebsiteType, @@ -35,16 +38,15 @@ const typeToForm: { }, }; -const typeToLabel = Object.keys(typeToForm).reduce( - (result, key: ApplicationType) => { - result[key] = typeToForm[key].label; +type TypeToLabel = Record; - return result; - }, - {} as { - [K in ApplicationType]: MessageDescriptor; - }, -); +const typeToLabel: TypeToLabel = ((Object.keys(typeToForm) as unknown) as Array< + ApplicationType +>).reduce((result, key) => { + result[key] = typeToForm[key].label; + + return result; +}, {} as TypeToLabel); export default class ApplicationForm extends React.Component<{ app: OauthAppResponse; diff --git a/packages/app/components/dev/apps/applicationForm/ApplicationTypeSwitcher.tsx b/packages/app/components/dev/apps/applicationForm/ApplicationTypeSwitcher.tsx index 9fcbb58..219c54d 100644 --- a/packages/app/components/dev/apps/applicationForm/ApplicationTypeSwitcher.tsx +++ b/packages/app/components/dev/apps/applicationForm/ApplicationTypeSwitcher.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { ComponentType } from 'react'; import { ApplicationType } from 'app/components/dev/apps'; import { MessageDescriptor } from 'react-intl'; import { SKIN_LIGHT } from 'app/components/ui'; @@ -6,20 +6,20 @@ import { Radio } from 'app/components/ui/form'; import styles from './applicationTypeSwitcher.scss'; -export default function ApplicationTypeSwitcher({ - setType, - appTypes, - selectedType, -}: { - appTypes: { - [K in ApplicationType]: MessageDescriptor; - }; +interface Props { + appTypes: Record; selectedType: ApplicationType | null; setType: (type: ApplicationType) => void; -}) { - return ( -
- {Object.keys(appTypes).map((type: ApplicationType) => ( +} + +const ApplicationTypeSwitcher: ComponentType = ({ + appTypes, + selectedType, + setType, +}) => ( +
+ {((Object.keys(appTypes) as unknown) as Array).map( + (type) => (
setType(type)} @@ -29,7 +29,9 @@ export default function ApplicationTypeSwitcher({ checked={selectedType === type} />
- ))} -
- ); -} + ), + )} +
+); + +export default ApplicationTypeSwitcher; diff --git a/packages/app/components/dev/apps/applicationForm/MinecraftServerType.tsx b/packages/app/components/dev/apps/applicationForm/MinecraftServerType.tsx index 53a1c31..5993b88 100644 --- a/packages/app/components/dev/apps/applicationForm/MinecraftServerType.tsx +++ b/packages/app/components/dev/apps/applicationForm/MinecraftServerType.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { ComponentType } from 'react'; import { FormattedMessage as Message } from 'react-intl'; import { OauthAppResponse } from 'app/services/api/oauth'; import { Input, FormModel } from 'app/components/ui/form'; @@ -7,52 +7,51 @@ import styles from 'app/components/profile/profileForm.scss'; import messages from './ApplicationForm.intl.json'; -export default function MinecraftServerType({ - form, - app, -}: { +interface Props { form: FormModel; app: OauthAppResponse; -}) { - return ( -
-
- -
- -
-

- -

-
-
- -
- -
-

- -

-
-
- -
-
- ); } + +const MinecraftServerType: ComponentType = ({ form, app }) => ( +
+
+ +
+ +
+

+ +

+
+
+ +
+ +
+

+ +

+
+
+ +
+
+); + +export default MinecraftServerType; diff --git a/packages/app/components/dev/apps/applicationForm/WebsiteType.tsx b/packages/app/components/dev/apps/applicationForm/WebsiteType.tsx index 1aa54c4..b7ad785 100644 --- a/packages/app/components/dev/apps/applicationForm/WebsiteType.tsx +++ b/packages/app/components/dev/apps/applicationForm/WebsiteType.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { ComponentType } from 'react'; import { FormattedMessage as Message } from 'react-intl'; import { Input, TextArea, FormModel } from 'app/components/ui/form'; import { OauthAppResponse } from 'app/services/api/oauth'; @@ -7,68 +7,67 @@ import styles from 'app/components/profile/profileForm.scss'; import messages from './ApplicationForm.intl.json'; -export default function WebsiteType({ - form, - app, -}: { +interface Props { form: FormModel; app: OauthAppResponse; -}) { - return ( -
-
- -
- -
-

- -

-
-
-