diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..04c01ba --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +dist/ \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..29421bc --- /dev/null +++ b/package-lock.json @@ -0,0 +1,14 @@ +{ + "name": "concise-redux", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "typescript": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.2.3.tgz", + "integrity": "sha512-qOcYwxaByStAWrBf4x0fibwZvMRG+r4cQoTjbPtUlrWjBHbmCAww1i448U0GJ+3cNNEtebDteo/cHOR3xJ4wEw==", + "dev": true + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..94e4014 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "concise-redux", + "version": "0.1.0", + "description": "A minimal, type-safe abstraction on top of Redux for better developer productivity", + "main": "dist/index.js", + "types": "dist", + "scripts": { + "build": "tsc -p ." + }, + "keywords": [ + "typescript", + "redux" + ], + "author": "João Dias", + "license": "ISC", + "devDependencies": { + "typescript": "^4.2.3" + } +} diff --git a/src/action-creator.ts b/src/action-creator.ts new file mode 100644 index 0000000..f477371 --- /dev/null +++ b/src/action-creator.ts @@ -0,0 +1,31 @@ +import { Action } from "./types/action"; +import { ActionMapConstraints } from "./types/action-constraints"; +import { StringKeysOf } from "./types/utils"; + +export function ActionCreator>() { + return function actionFactory< + ActionType extends StringKeysOf, + Payload extends ActionMap[ActionType] + >( + type: ActionType, + /** + * We use the tuple syntax to check the Payload type because, by default, conditional types distribute over unions. + * With this syntax the union type becomes atomic in the sense that the condition is + * checked against the whole type instead of its parts. + * This is necessary for the cases where Payload can be a union type, e.g., if it is a nullable type. + * More info: https://stackoverflow.com/questions/51365467/issue-with-union-types-and-conditional-types + */ + ...payload: [Payload] extends [void] ? [] : [Payload] + ): Action { + /** + * The return type of actionFactory is a conditional type. + * This works great for consuming code. + * However, the compiler is not able to match the return type from the function body. This is a design limitation. + * Because of this limitation, we need a type assertion / cast. + * More info: https://github.com/microsoft/TypeScript/issues/24929 + */ + return (payload.length === 0 + ? { type } + : { type, payload: payload[0] }) as Action; + } +} \ No newline at end of file diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..729b736 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,3 @@ +export { storeComponent } from "./store-component"; +export { ActionCreator } from "./action-creator"; +export type { ActionUnion } from "./types/action-union"; diff --git a/src/store-component.ts b/src/store-component.ts new file mode 100644 index 0000000..ef6d6b8 --- /dev/null +++ b/src/store-component.ts @@ -0,0 +1,44 @@ +import { ActionCreator } from "./action-creator"; +import { UnknownAction } from "./types/action"; +import { ActionMapConstraints } from "./types/action-constraints"; +import { ActionUnion } from "./types/action-union"; +import { UnknownCaseReducer, CaseReducers } from "./types/case-reducers"; + +export function storeComponent< + ActionMap extends ActionMapConstraints, + State +>({ + initialState, + caseReducers, +}: StoreComponentParams) { + return { + initialState: Object.freeze(initialState), + ActionCreator: ActionCreator(), + reducer: (state = initialState, action: ActionUnion) => { + const caseReducer = caseReducers[action.type]; + return caseReducer + ? apply(caseReducer, state, action) + : state; + } + }; +} + +function apply( + caseReducer: UnknownCaseReducer, + state: State, + action: UnknownAction +): State { + return { + ...state, + ...(typeof caseReducer === 'function' + ? action.payload === undefined + ? caseReducer(state) + : caseReducer(action.payload, state) + : caseReducer) + } +} + +interface StoreComponentParams, State> { + initialState: State, + caseReducers: CaseReducers +} diff --git a/src/types/action-constraints.ts b/src/types/action-constraints.ts new file mode 100644 index 0000000..eb65b5c --- /dev/null +++ b/src/types/action-constraints.ts @@ -0,0 +1,3 @@ +import { IndexableObject } from "./utils"; + +export type ActionMapConstraints = IndexableObject & Required; \ No newline at end of file diff --git a/src/types/action-union.ts b/src/types/action-union.ts new file mode 100644 index 0000000..2a274ed --- /dev/null +++ b/src/types/action-union.ts @@ -0,0 +1,7 @@ +import { Action } from "./action"; +import { ActionMapConstraints } from "./action-constraints"; +import { StringKeysOf } from "./utils"; + +export type ActionUnion> = { + [ActionType in StringKeysOf]: Action; +}[StringKeysOf]; diff --git a/src/types/action.ts b/src/types/action.ts new file mode 100644 index 0000000..5ff0106 --- /dev/null +++ b/src/types/action.ts @@ -0,0 +1,15 @@ +/** + * We use the tuple syntax to check the Payload type because, by default, conditional types distribute over unions. + * With this syntax the union type becomes atomic in the sense that the condition is + * checked against the whole type instead of its parts. + * This is necessary for the cases where Payload can be a union type, e.g., if it is a nullable type. + * More info: https://stackoverflow.com/questions/51365467/issue-with-union-types-and-conditional-types + */ +export type Action = Readonly<[Payload] extends [void] + ? { type: Type } + : { type: Type, payload: Payload }>; + +export interface UnknownAction { + type: string + payload?: unknown +} \ No newline at end of file diff --git a/src/types/case-reducers.ts b/src/types/case-reducers.ts new file mode 100644 index 0000000..b504b7e --- /dev/null +++ b/src/types/case-reducers.ts @@ -0,0 +1,18 @@ +import { ActionMapConstraints } from "./action-constraints"; +import { Immutable, StringKeysOf } from "./utils"; + +export type CaseReducers, State> = { + [ActionType in StringKeysOf]: [ActionMap[ActionType]] extends [void] + ? Partial | UnaryCaseReducer + : BinaryCaseReducer; +}; + +interface UnaryCaseReducer { + (state: Immutable): Partial +} + +interface BinaryCaseReducer { + (payload: Immutable, state: Immutable): Partial +} + +export type UnknownCaseReducer = Partial | ((...args: any[]) => Partial); \ No newline at end of file diff --git a/src/types/utils.ts b/src/types/utils.ts new file mode 100644 index 0000000..f330a7f --- /dev/null +++ b/src/types/utils.ts @@ -0,0 +1,18 @@ +export type IndexableObject = Record; + +export type StringKeysOf = string & keyof T; + +export type Primitive = + | null + | undefined + | string + | number + | boolean + | symbol + | bigint; + +export type Immutable = { + readonly [K in keyof T]: T[K] extends Primitive + ? T[K] + : Immutable +} \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..445af2b --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,67 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + /* Basic Options */ + // "incremental": true, /* Enable incremental compilation */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ + // "lib": [], /* Specify library files to be included in the compilation. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ + "declaration": true, /* Generates corresponding '.d.ts' file. */ + "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "dist", /* Redirect output structure to the directory. */ + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ + // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + /* Advanced Options */ + "skipLibCheck": true, /* Skip type checking of declaration files. */ + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + }, + "include": [ + "src" + ] +} \ No newline at end of file